1 //
2 // Copyright 2006 The Android Open Source Project
3 //
4 // Build resource files from raw assets.
5 //
6 
7 #include "ResourceTable.h"
8 
9 #include "AaptUtil.h"
10 #include "XMLNode.h"
11 #include "ResourceFilter.h"
12 #include "ResourceIdCache.h"
13 #include "SdkConstants.h"
14 #include "Utils.h"
15 
16 #include <algorithm>
17 #include <androidfw/PathUtils.h>
18 #include <androidfw/ResourceTypes.h>
19 #include <utils/ByteOrder.h>
20 #include <utils/TypeHelpers.h>
21 #include <stdarg.h>
22 
23 // STATUST: mingw does seem to redefine UNKNOWN_ERROR from our enum value, so a cast is necessary.
24 #if !defined(_WIN32)
25 #  define STATUST(x) x
26 #else
27 #  define STATUST(x) (status_t)x
28 #endif
29 
30 // Set to true for noisy debug output.
31 static const bool kIsDebug = false;
32 
33 #if PRINT_STRING_METRICS
34 static const bool kPrintStringMetrics = true;
35 #else
36 static const bool kPrintStringMetrics = false;
37 #endif
38 
39 static const char* kAttrPrivateType = "^attr-private";
40 
compileXmlFile(const Bundle * bundle,const sp<AaptAssets> & assets,const String16 & resourceName,const sp<AaptFile> & target,ResourceTable * table,int options)41 status_t compileXmlFile(const Bundle* bundle,
42                         const sp<AaptAssets>& assets,
43                         const String16& resourceName,
44                         const sp<AaptFile>& target,
45                         ResourceTable* table,
46                         int options)
47 {
48     sp<XMLNode> root = XMLNode::parse(target);
49     if (root == NULL) {
50         return UNKNOWN_ERROR;
51     }
52 
53     return compileXmlFile(bundle, assets, resourceName, root, target, table, options);
54 }
55 
compileXmlFile(const Bundle * bundle,const sp<AaptAssets> & assets,const String16 & resourceName,const sp<AaptFile> & target,const sp<AaptFile> & outTarget,ResourceTable * table,int options)56 status_t compileXmlFile(const Bundle* bundle,
57                         const sp<AaptAssets>& assets,
58                         const String16& resourceName,
59                         const sp<AaptFile>& target,
60                         const sp<AaptFile>& outTarget,
61                         ResourceTable* table,
62                         int options)
63 {
64     sp<XMLNode> root = XMLNode::parse(target);
65     if (root == NULL) {
66         return UNKNOWN_ERROR;
67     }
68 
69     return compileXmlFile(bundle, assets, resourceName, root, outTarget, table, options);
70 }
71 
compileXmlFile(const Bundle * bundle,const sp<AaptAssets> & assets,const String16 & resourceName,const sp<XMLNode> & root,const sp<AaptFile> & target,ResourceTable * table,int options)72 status_t compileXmlFile(const Bundle* bundle,
73                         const sp<AaptAssets>& assets,
74                         const String16& resourceName,
75                         const sp<XMLNode>& root,
76                         const sp<AaptFile>& target,
77                         ResourceTable* table,
78                         int options)
79 {
80     if (table->versionForCompat(bundle, resourceName, target, root)) {
81         // The file was versioned, so stop processing here.
82         // The resource entry has already been removed and the new one added.
83         // Remove the assets entry.
84         sp<AaptDir> resDir = assets->getDirs().valueFor(String8("res"));
85         sp<AaptDir> dir = resDir->getDirs().valueFor(target->getGroupEntry().toDirName(
86                 target->getResourceType()));
87         dir->removeFile(getPathLeaf(target->getPath()));
88         return NO_ERROR;
89     }
90 
91     if ((options&XML_COMPILE_STRIP_WHITESPACE) != 0) {
92         root->removeWhitespace(true, NULL);
93     } else  if ((options&XML_COMPILE_COMPACT_WHITESPACE) != 0) {
94         root->removeWhitespace(false, NULL);
95     }
96 
97     if ((options&XML_COMPILE_UTF8) != 0) {
98         root->setUTF8(true);
99     }
100 
101     if (table->processBundleFormat(bundle, resourceName, target, root) != NO_ERROR) {
102         return UNKNOWN_ERROR;
103     }
104 
105     bool hasErrors = false;
106     if ((options&XML_COMPILE_ASSIGN_ATTRIBUTE_IDS) != 0) {
107         status_t err = root->assignResourceIds(assets, table);
108         if (err != NO_ERROR) {
109             hasErrors = true;
110         }
111     }
112 
113     if ((options&XML_COMPILE_PARSE_VALUES) != 0) {
114         status_t err = root->parseValues(assets, table);
115         if (err != NO_ERROR) {
116             hasErrors = true;
117         }
118     }
119 
120     if (hasErrors) {
121         return UNKNOWN_ERROR;
122     }
123 
124     if (table->modifyForCompat(bundle, resourceName, target, root) != NO_ERROR) {
125         return UNKNOWN_ERROR;
126     }
127 
128     if (kIsDebug) {
129         printf("Input XML Resource:\n");
130         root->print();
131     }
132     status_t err = root->flatten(target,
133             (options&XML_COMPILE_STRIP_COMMENTS) != 0,
134             (options&XML_COMPILE_STRIP_RAW_VALUES) != 0);
135     if (err != NO_ERROR) {
136         return err;
137     }
138 
139     if (kIsDebug) {
140         printf("Output XML Resource:\n");
141         ResXMLTree tree;
142         tree.setTo(target->getData(), target->getSize());
143         printXMLBlock(&tree);
144     }
145 
146     target->setCompressionMethod(ZipEntry::kCompressDeflated);
147 
148     return err;
149 }
150 
151 struct flag_entry
152 {
153     const char16_t* name;
154     size_t nameLen;
155     uint32_t value;
156     const char* description;
157 };
158 
159 static const char16_t referenceArray[] =
160     { 'r', 'e', 'f', 'e', 'r', 'e', 'n', 'c', 'e' };
161 static const char16_t stringArray[] =
162     { 's', 't', 'r', 'i', 'n', 'g' };
163 static const char16_t integerArray[] =
164     { 'i', 'n', 't', 'e', 'g', 'e', 'r' };
165 static const char16_t booleanArray[] =
166     { 'b', 'o', 'o', 'l', 'e', 'a', 'n' };
167 static const char16_t colorArray[] =
168     { 'c', 'o', 'l', 'o', 'r' };
169 static const char16_t floatArray[] =
170     { 'f', 'l', 'o', 'a', 't' };
171 static const char16_t dimensionArray[] =
172     { 'd', 'i', 'm', 'e', 'n', 's', 'i', 'o', 'n' };
173 static const char16_t fractionArray[] =
174     { 'f', 'r', 'a', 'c', 't', 'i', 'o', 'n' };
175 static const char16_t enumArray[] =
176     { 'e', 'n', 'u', 'm' };
177 static const char16_t flagsArray[] =
178     { 'f', 'l', 'a', 'g', 's' };
179 
180 static const flag_entry gFormatFlags[] = {
181     { referenceArray, sizeof(referenceArray)/2, ResTable_map::TYPE_REFERENCE,
182       "a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\n"
183       "or to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\"."},
184     { stringArray, sizeof(stringArray)/2, ResTable_map::TYPE_STRING,
185       "a string value, using '\\\\;' to escape characters such as '\\\\n' or '\\\\uxxxx' for a unicode character." },
186     { integerArray, sizeof(integerArray)/2, ResTable_map::TYPE_INTEGER,
187       "an integer value, such as \"<code>100</code>\"." },
188     { booleanArray, sizeof(booleanArray)/2, ResTable_map::TYPE_BOOLEAN,
189       "a boolean value, either \"<code>true</code>\" or \"<code>false</code>\"." },
190     { colorArray, sizeof(colorArray)/2, ResTable_map::TYPE_COLOR,
191       "a color value, in the form of \"<code>#<i>rgb</i></code>\", \"<code>#<i>argb</i></code>\",\n"
192       "\"<code>#<i>rrggbb</i></code>\", or \"<code>#<i>aarrggbb</i></code>\"." },
193     { floatArray, sizeof(floatArray)/2, ResTable_map::TYPE_FLOAT,
194       "a floating point value, such as \"<code>1.2</code>\"."},
195     { dimensionArray, sizeof(dimensionArray)/2, ResTable_map::TYPE_DIMENSION,
196       "a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\n"
197       "Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\n"
198       "in (inches), mm (millimeters)." },
199     { fractionArray, sizeof(fractionArray)/2, ResTable_map::TYPE_FRACTION,
200       "a fractional value, which is a floating point number appended with either % or %p, such as \"<code>14.5%</code>\".\n"
201       "The % suffix always means a percentage of the base size; the optional %p suffix provides a size relative to\n"
202       "some parent container." },
203     { enumArray, sizeof(enumArray)/2, ResTable_map::TYPE_ENUM, NULL },
204     { flagsArray, sizeof(flagsArray)/2, ResTable_map::TYPE_FLAGS, NULL },
205     { NULL, 0, 0, NULL }
206 };
207 
208 static const char16_t suggestedArray[] = { 's', 'u', 'g', 'g', 'e', 's', 't', 'e', 'd' };
209 
210 static const flag_entry l10nRequiredFlags[] = {
211     { suggestedArray, sizeof(suggestedArray)/2, ResTable_map::L10N_SUGGESTED, NULL },
212     { NULL, 0, 0, NULL }
213 };
214 
215 static const char16_t nulStr[] = { 0 };
216 
parse_flags(const char16_t * str,size_t len,const flag_entry * flags,bool * outError=NULL)217 static uint32_t parse_flags(const char16_t* str, size_t len,
218                              const flag_entry* flags, bool* outError = NULL)
219 {
220     while (len > 0 && isspace(*str)) {
221         str++;
222         len--;
223     }
224     while (len > 0 && isspace(str[len-1])) {
225         len--;
226     }
227 
228     const char16_t* const end = str + len;
229     uint32_t value = 0;
230 
231     while (str < end) {
232         const char16_t* div = str;
233         while (div < end && *div != '|') {
234             div++;
235         }
236 
237         const flag_entry* cur = flags;
238         while (cur->name) {
239             if (strzcmp16(cur->name, cur->nameLen, str, div-str) == 0) {
240                 value |= cur->value;
241                 break;
242             }
243             cur++;
244         }
245 
246         if (!cur->name) {
247             if (outError) *outError = true;
248             return 0;
249         }
250 
251         str = div < end ? div+1 : div;
252     }
253 
254     if (outError) *outError = false;
255     return value;
256 }
257 
mayOrMust(int type,int flags)258 static String16 mayOrMust(int type, int flags)
259 {
260     if ((type&(~flags)) == 0) {
261         return String16("<p>Must");
262     }
263 
264     return String16("<p>May");
265 }
266 
appendTypeInfo(ResourceTable * outTable,const String16 & pkg,const String16 & typeName,const String16 & ident,int type,const flag_entry * flags)267 static void appendTypeInfo(ResourceTable* outTable, const String16& pkg,
268         const String16& typeName, const String16& ident, int type,
269         const flag_entry* flags)
270 {
271     bool hadType = false;
272     while (flags->name) {
273         if ((type&flags->value) != 0 && flags->description != NULL) {
274             String16 fullMsg(mayOrMust(type, flags->value));
275             fullMsg.append(String16(" be "));
276             fullMsg.append(String16(flags->description));
277             outTable->appendTypeComment(pkg, typeName, ident, fullMsg);
278             hadType = true;
279         }
280         flags++;
281     }
282     if (hadType && (type&ResTable_map::TYPE_REFERENCE) == 0) {
283         outTable->appendTypeComment(pkg, typeName, ident,
284                 String16("<p>This may also be a reference to a resource (in the form\n"
285                          "\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\n"
286                          "theme attribute (in the form\n"
287                          "\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\n"
288                          "containing a value of this type."));
289     }
290 }
291 
292 struct PendingAttribute
293 {
294     const String16 myPackage;
295     const SourcePos sourcePos;
296     const bool appendComment;
297     int32_t type;
298     String16 ident;
299     String16 comment;
300     bool hasErrors;
301     bool added;
302 
PendingAttributePendingAttribute303     PendingAttribute(String16 _package, const sp<AaptFile>& in,
304             ResXMLTree& block, bool _appendComment)
305         : myPackage(_package)
306         , sourcePos(in->getPrintableSource(), block.getLineNumber())
307         , appendComment(_appendComment)
308         , type(ResTable_map::TYPE_ANY)
309         , hasErrors(false)
310         , added(false)
311     {
312     }
313 
createIfNeededPendingAttribute314     status_t createIfNeeded(ResourceTable* outTable)
315     {
316         if (added || hasErrors) {
317             return NO_ERROR;
318         }
319         added = true;
320 
321         if (!outTable->makeAttribute(myPackage, ident, sourcePos, type, comment, appendComment)) {
322             hasErrors = true;
323             return UNKNOWN_ERROR;
324         }
325         return NO_ERROR;
326     }
327 };
328 
compileAttribute(const sp<AaptFile> & in,ResXMLTree & block,const String16 & myPackage,ResourceTable * outTable,String16 * outIdent=NULL,bool inStyleable=false)329 static status_t compileAttribute(const sp<AaptFile>& in,
330                                  ResXMLTree& block,
331                                  const String16& myPackage,
332                                  ResourceTable* outTable,
333                                  String16* outIdent = NULL,
334                                  bool inStyleable = false)
335 {
336     PendingAttribute attr(myPackage, in, block, inStyleable);
337 
338     const String16 attr16("attr");
339     const String16 id16("id");
340 
341     // Attribute type constants.
342     const String16 enum16("enum");
343     const String16 flag16("flag");
344 
345     ResXMLTree::event_code_t code;
346     size_t len;
347     status_t err;
348 
349     ssize_t identIdx = block.indexOfAttribute(NULL, "name");
350     if (identIdx >= 0) {
351         attr.ident = String16(block.getAttributeStringValue(identIdx, &len));
352         if (outIdent) {
353             *outIdent = attr.ident;
354         }
355     } else {
356         attr.sourcePos.error("A 'name' attribute is required for <attr>\n");
357         attr.hasErrors = true;
358     }
359 
360     attr.comment = String16(
361             block.getComment(&len) ? block.getComment(&len) : nulStr);
362 
363     ssize_t typeIdx = block.indexOfAttribute(NULL, "format");
364     if (typeIdx >= 0) {
365         String16 typeStr = String16(block.getAttributeStringValue(typeIdx, &len));
366         attr.type = parse_flags(typeStr.c_str(), typeStr.size(), gFormatFlags);
367         if (attr.type == 0) {
368             attr.sourcePos.error("Tag <attr> 'format' attribute value \"%s\" not valid\n",
369                     String8(typeStr).c_str());
370             attr.hasErrors = true;
371         }
372         attr.createIfNeeded(outTable);
373     } else if (!inStyleable) {
374         // Attribute definitions outside of styleables always define the
375         // attribute as a generic value.
376         attr.createIfNeeded(outTable);
377     }
378 
379     //printf("Attribute %s: type=0x%08x\n", String8(attr.ident).c_str(), attr.type);
380 
381     ssize_t minIdx = block.indexOfAttribute(NULL, "min");
382     if (minIdx >= 0) {
383         String16 val = String16(block.getAttributeStringValue(minIdx, &len));
384         if (!ResTable::stringToInt(val.c_str(), val.size(), NULL)) {
385             attr.sourcePos.error("Tag <attr> 'min' attribute must be a number, not \"%s\"\n",
386                     String8(val).c_str());
387             attr.hasErrors = true;
388         }
389         attr.createIfNeeded(outTable);
390         if (!attr.hasErrors) {
391             err = outTable->addBag(attr.sourcePos, myPackage, attr16, attr.ident,
392                     String16(""), String16("^min"), String16(val), NULL, NULL);
393             if (err != NO_ERROR) {
394                 attr.hasErrors = true;
395             }
396         }
397     }
398 
399     ssize_t maxIdx = block.indexOfAttribute(NULL, "max");
400     if (maxIdx >= 0) {
401         String16 val = String16(block.getAttributeStringValue(maxIdx, &len));
402         if (!ResTable::stringToInt(val.c_str(), val.size(), NULL)) {
403             attr.sourcePos.error("Tag <attr> 'max' attribute must be a number, not \"%s\"\n",
404                     String8(val).c_str());
405             attr.hasErrors = true;
406         }
407         attr.createIfNeeded(outTable);
408         if (!attr.hasErrors) {
409             err = outTable->addBag(attr.sourcePos, myPackage, attr16, attr.ident,
410                     String16(""), String16("^max"), String16(val), NULL, NULL);
411             attr.hasErrors = true;
412         }
413     }
414 
415     if ((minIdx >= 0 || maxIdx >= 0) && (attr.type&ResTable_map::TYPE_INTEGER) == 0) {
416         attr.sourcePos.error("Tag <attr> must have format=integer attribute if using max or min\n");
417         attr.hasErrors = true;
418     }
419 
420     ssize_t l10nIdx = block.indexOfAttribute(NULL, "localization");
421     if (l10nIdx >= 0) {
422         const char16_t* str = block.getAttributeStringValue(l10nIdx, &len);
423         bool error;
424         uint32_t l10n_required = parse_flags(str, len, l10nRequiredFlags, &error);
425         if (error) {
426             attr.sourcePos.error("Tag <attr> 'localization' attribute value \"%s\" not valid\n",
427                     String8(str).c_str());
428             attr.hasErrors = true;
429         }
430         attr.createIfNeeded(outTable);
431         if (!attr.hasErrors) {
432             char buf[11];
433             sprintf(buf, "%d", l10n_required);
434             err = outTable->addBag(attr.sourcePos, myPackage, attr16, attr.ident,
435                     String16(""), String16("^l10n"), String16(buf), NULL, NULL);
436             if (err != NO_ERROR) {
437                 attr.hasErrors = true;
438             }
439         }
440     }
441 
442     String16 enumOrFlagsComment;
443 
444     while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
445         if (code == ResXMLTree::START_TAG) {
446             uint32_t localType = 0;
447             if (strcmp16(block.getElementName(&len), enum16.c_str()) == 0) {
448                 localType = ResTable_map::TYPE_ENUM;
449             } else if (strcmp16(block.getElementName(&len), flag16.c_str()) == 0) {
450                 localType = ResTable_map::TYPE_FLAGS;
451             } else {
452                 SourcePos(in->getPrintableSource(), block.getLineNumber())
453                         .error("Tag <%s> can not appear inside <attr>, only <enum> or <flag>\n",
454                         String8(block.getElementName(&len)).c_str());
455                 return UNKNOWN_ERROR;
456             }
457 
458             attr.createIfNeeded(outTable);
459 
460             if (attr.type == ResTable_map::TYPE_ANY) {
461                 // No type was explicitly stated, so supplying enum tags
462                 // implicitly creates an enum or flag.
463                 attr.type = 0;
464             }
465 
466             if ((attr.type&(ResTable_map::TYPE_ENUM|ResTable_map::TYPE_FLAGS)) == 0) {
467                 // Wasn't originally specified as an enum, so update its type.
468                 attr.type |= localType;
469                 if (!attr.hasErrors) {
470                     char numberStr[16];
471                     sprintf(numberStr, "%d", attr.type);
472                     err = outTable->addBag(SourcePos(in->getPrintableSource(), block.getLineNumber()),
473                             myPackage, attr16, attr.ident, String16(""),
474                             String16("^type"), String16(numberStr), NULL, NULL, true);
475                     if (err != NO_ERROR) {
476                         attr.hasErrors = true;
477                     }
478                 }
479             } else if ((uint32_t)(attr.type&(ResTable_map::TYPE_ENUM|ResTable_map::TYPE_FLAGS)) != localType) {
480                 if (localType == ResTable_map::TYPE_ENUM) {
481                     SourcePos(in->getPrintableSource(), block.getLineNumber())
482                             .error("<enum> attribute can not be used inside a flags format\n");
483                     attr.hasErrors = true;
484                 } else {
485                     SourcePos(in->getPrintableSource(), block.getLineNumber())
486                             .error("<flag> attribute can not be used inside a enum format\n");
487                     attr.hasErrors = true;
488                 }
489             }
490 
491             String16 itemIdent;
492             ssize_t itemIdentIdx = block.indexOfAttribute(NULL, "name");
493             if (itemIdentIdx >= 0) {
494                 itemIdent = String16(block.getAttributeStringValue(itemIdentIdx, &len));
495             } else {
496                 SourcePos(in->getPrintableSource(), block.getLineNumber())
497                         .error("A 'name' attribute is required for <enum> or <flag>\n");
498                 attr.hasErrors = true;
499             }
500 
501             String16 value;
502             ssize_t valueIdx = block.indexOfAttribute(NULL, "value");
503             if (valueIdx >= 0) {
504                 value = String16(block.getAttributeStringValue(valueIdx, &len));
505             } else {
506                 SourcePos(in->getPrintableSource(), block.getLineNumber())
507                         .error("A 'value' attribute is required for <enum> or <flag>\n");
508                 attr.hasErrors = true;
509             }
510             if (!attr.hasErrors && !ResTable::stringToInt(value.c_str(), value.size(), NULL)) {
511                 SourcePos(in->getPrintableSource(), block.getLineNumber())
512                         .error("Tag <enum> or <flag> 'value' attribute must be a number,"
513                         " not \"%s\"\n",
514                         String8(value).c_str());
515                 attr.hasErrors = true;
516             }
517 
518             if (!attr.hasErrors) {
519                 if (enumOrFlagsComment.size() == 0) {
520                     enumOrFlagsComment.append(mayOrMust(attr.type,
521                             ResTable_map::TYPE_ENUM|ResTable_map::TYPE_FLAGS));
522                     enumOrFlagsComment.append((attr.type&ResTable_map::TYPE_ENUM)
523                                        ? String16(" be one of the following constant values.")
524                                        : String16(" be one or more (separated by '|') of the following constant values."));
525                     enumOrFlagsComment.append(String16("</p>\n<table>\n"
526                                                 "<colgroup align=\"left\" />\n"
527                                                 "<colgroup align=\"left\" />\n"
528                                                 "<colgroup align=\"left\" />\n"
529                                                 "<tr><th>Constant</th><th>Value</th><th>Description</th></tr>"));
530                 }
531 
532                 enumOrFlagsComment.append(String16("\n<tr><td><code>"));
533                 enumOrFlagsComment.append(itemIdent);
534                 enumOrFlagsComment.append(String16("</code></td><td>"));
535                 enumOrFlagsComment.append(value);
536                 enumOrFlagsComment.append(String16("</td><td>"));
537                 if (block.getComment(&len)) {
538                     enumOrFlagsComment.append(String16(block.getComment(&len)));
539                 }
540                 enumOrFlagsComment.append(String16("</td></tr>"));
541 
542                 err = outTable->addBag(SourcePos(in->getPrintableSource(), block.getLineNumber()),
543                                        myPackage,
544                                        attr16, attr.ident, String16(""),
545                                        itemIdent, value, NULL, NULL, false, true);
546                 if (err != NO_ERROR) {
547                     attr.hasErrors = true;
548                 }
549             }
550         } else if (code == ResXMLTree::END_TAG) {
551             if (strcmp16(block.getElementName(&len), attr16.c_str()) == 0) {
552                 break;
553             }
554             if ((attr.type&ResTable_map::TYPE_ENUM) != 0) {
555                 if (strcmp16(block.getElementName(&len), enum16.c_str()) != 0) {
556                     SourcePos(in->getPrintableSource(), block.getLineNumber())
557                             .error("Found tag </%s> where </enum> is expected\n",
558                             String8(block.getElementName(&len)).c_str());
559                     return UNKNOWN_ERROR;
560                 }
561             } else {
562                 if (strcmp16(block.getElementName(&len), flag16.c_str()) != 0) {
563                     SourcePos(in->getPrintableSource(), block.getLineNumber())
564                             .error("Found tag </%s> where </flag> is expected\n",
565                             String8(block.getElementName(&len)).c_str());
566                     return UNKNOWN_ERROR;
567                 }
568             }
569         }
570     }
571 
572     if (!attr.hasErrors && attr.added) {
573         appendTypeInfo(outTable, myPackage, attr16, attr.ident, attr.type, gFormatFlags);
574     }
575 
576     if (!attr.hasErrors && enumOrFlagsComment.size() > 0) {
577         enumOrFlagsComment.append(String16("\n</table>"));
578         outTable->appendTypeComment(myPackage, attr16, attr.ident, enumOrFlagsComment);
579     }
580 
581 
582     return NO_ERROR;
583 }
584 
localeIsDefined(const ResTable_config & config)585 bool localeIsDefined(const ResTable_config& config)
586 {
587     return config.locale == 0;
588 }
589 
parseAndAddBag(Bundle * bundle,const sp<AaptFile> & in,ResXMLTree * block,const ResTable_config & config,const String16 & myPackage,const String16 & curType,const String16 & ident,const String16 & parentIdent,const String16 & itemIdent,int32_t curFormat,bool isFormatted,const String16 &,PseudolocalizationMethod pseudolocalize,const bool overwrite,ResourceTable * outTable)590 status_t parseAndAddBag(Bundle* bundle,
591                         const sp<AaptFile>& in,
592                         ResXMLTree* block,
593                         const ResTable_config& config,
594                         const String16& myPackage,
595                         const String16& curType,
596                         const String16& ident,
597                         const String16& parentIdent,
598                         const String16& itemIdent,
599                         int32_t curFormat,
600                         bool isFormatted,
601                         const String16& /* product */,
602                         PseudolocalizationMethod pseudolocalize,
603                         const bool overwrite,
604                         ResourceTable* outTable)
605 {
606     status_t err;
607     const String16 item16("item");
608 
609     String16 str;
610     Vector<StringPool::entry_style_span> spans;
611     err = parseStyledString(bundle, in->getPrintableSource().c_str(),
612                             block, item16, &str, &spans, isFormatted,
613                             pseudolocalize);
614     if (err != NO_ERROR) {
615         return err;
616     }
617 
618     if (kIsDebug) {
619         printf("Adding resource bag entry l=%c%c c=%c%c orien=%d d=%d "
620                 " pid=%s, bag=%s, id=%s: %s\n",
621                 config.language[0], config.language[1],
622                 config.country[0], config.country[1],
623                 config.orientation, config.density,
624                 String8(parentIdent).c_str(),
625                 String8(ident).c_str(),
626                 String8(itemIdent).c_str(),
627                 String8(str).c_str());
628     }
629 
630     err = outTable->addBag(SourcePos(in->getPrintableSource(), block->getLineNumber()),
631                            myPackage, curType, ident, parentIdent, itemIdent, str,
632                            &spans, &config, overwrite, false, curFormat);
633     return err;
634 }
635 
636 /*
637  * Returns true if needle is one of the elements in the comma-separated list
638  * haystack, false otherwise.
639  */
isInProductList(const String16 & needle,const String16 & haystack)640 bool isInProductList(const String16& needle, const String16& haystack) {
641     const char16_t *needle2 = needle.c_str();
642     const char16_t *haystack2 = haystack.c_str();
643     size_t needlesize = needle.size();
644 
645     while (*haystack2 != '\0') {
646         if (strncmp16(haystack2, needle2, needlesize) == 0) {
647             if (haystack2[needlesize] == '\0' || haystack2[needlesize] == ',') {
648                 return true;
649             }
650         }
651 
652         while (*haystack2 != '\0' && *haystack2 != ',') {
653             haystack2++;
654         }
655         if (*haystack2 == ',') {
656             haystack2++;
657         }
658     }
659 
660     return false;
661 }
662 
663 /*
664  * A simple container that holds a resource type and name. It is ordered first by type then
665  * by name.
666  */
667 struct type_ident_pair_t {
668     String16 type;
669     String16 ident;
670 
type_ident_pair_ttype_ident_pair_t671     type_ident_pair_t() { };
type_ident_pair_ttype_ident_pair_t672     type_ident_pair_t(const String16& t, const String16& i) : type(t), ident(i) { }
type_ident_pair_ttype_ident_pair_t673     type_ident_pair_t(const type_ident_pair_t& o) : type(o.type), ident(o.ident) { }
operator <type_ident_pair_t674     inline bool operator < (const type_ident_pair_t& o) const {
675         int cmp = compare_type(type, o.type);
676         if (cmp < 0) {
677             return true;
678         } else if (cmp > 0) {
679             return false;
680         } else {
681             return strictly_order_type(ident, o.ident);
682         }
683     }
684 };
685 
686 
parseAndAddEntry(Bundle * bundle,const sp<AaptFile> & in,ResXMLTree * block,const ResTable_config & config,const String16 & myPackage,const String16 & curType,const String16 & ident,const String16 & curTag,bool curIsStyled,int32_t curFormat,bool isFormatted,const String16 & product,PseudolocalizationMethod pseudolocalize,const bool overwrite,KeyedVector<type_ident_pair_t,bool> * skippedResourceNames,ResourceTable * outTable)687 status_t parseAndAddEntry(Bundle* bundle,
688                         const sp<AaptFile>& in,
689                         ResXMLTree* block,
690                         const ResTable_config& config,
691                         const String16& myPackage,
692                         const String16& curType,
693                         const String16& ident,
694                         const String16& curTag,
695                         bool curIsStyled,
696                         int32_t curFormat,
697                         bool isFormatted,
698                         const String16& product,
699                         PseudolocalizationMethod pseudolocalize,
700                         const bool overwrite,
701                         KeyedVector<type_ident_pair_t, bool>* skippedResourceNames,
702                         ResourceTable* outTable)
703 {
704     status_t err;
705 
706     String16 str;
707     Vector<StringPool::entry_style_span> spans;
708     err = parseStyledString(bundle, in->getPrintableSource().c_str(), block,
709                             curTag, &str, curIsStyled ? &spans : NULL,
710                             isFormatted, pseudolocalize);
711 
712     if (err < NO_ERROR) {
713         return err;
714     }
715 
716     /*
717      * If a product type was specified on the command line
718      * and also in the string, and the two are not the same,
719      * return without adding the string.
720      */
721 
722     const char *bundleProduct = bundle->getProduct();
723     if (bundleProduct == NULL) {
724         bundleProduct = "";
725     }
726 
727     if (product.size() != 0) {
728         /*
729          * If the command-line-specified product is empty, only "default"
730          * matches.  Other variants are skipped.  This is so generation
731          * of the R.java file when the product is not known is predictable.
732          */
733 
734         if (bundleProduct[0] == '\0') {
735             if (strcmp16(String16("default").c_str(), product.c_str()) != 0) {
736                 /*
737                  * This string has a product other than 'default'. Do not add it,
738                  * but record it so that if we do not see the same string with
739                  * product 'default' or no product, then report an error.
740                  */
741                 skippedResourceNames->replaceValueFor(
742                         type_ident_pair_t(curType, ident), true);
743                 return NO_ERROR;
744             }
745         } else {
746             /*
747              * The command-line product is not empty.
748              * If the product for this string is on the command-line list,
749              * it matches.  "default" also matches, but only if nothing
750              * else has matched already.
751              */
752 
753             if (isInProductList(product, String16(bundleProduct))) {
754                 ;
755             } else if (strcmp16(String16("default").c_str(), product.c_str()) == 0 &&
756                        !outTable->hasBagOrEntry(myPackage, curType, ident, config)) {
757                 ;
758             } else {
759                 return NO_ERROR;
760             }
761         }
762     }
763 
764     if (kIsDebug) {
765         printf("Adding resource entry l=%c%c c=%c%c orien=%d d=%d id=%s: %s\n",
766                 config.language[0], config.language[1],
767                 config.country[0], config.country[1],
768                 config.orientation, config.density,
769                 String8(ident).c_str(), String8(str).c_str());
770     }
771 
772     err = outTable->addEntry(SourcePos(in->getPrintableSource(), block->getLineNumber()),
773                              myPackage, curType, ident, str, &spans, &config,
774                              false, curFormat, overwrite);
775 
776     return err;
777 }
778 
compileResourceFile(Bundle * bundle,const sp<AaptAssets> & assets,const sp<AaptFile> & in,const ResTable_config & defParams,const bool overwrite,ResourceTable * outTable)779 status_t compileResourceFile(Bundle* bundle,
780                              const sp<AaptAssets>& assets,
781                              const sp<AaptFile>& in,
782                              const ResTable_config& defParams,
783                              const bool overwrite,
784                              ResourceTable* outTable)
785 {
786     ResXMLTree block;
787     status_t err = parseXMLResource(in, &block, false, true);
788     if (err != NO_ERROR) {
789         return err;
790     }
791 
792     // Top-level tag.
793     const String16 resources16("resources");
794 
795     // Identifier declaration tags.
796     const String16 declare_styleable16("declare-styleable");
797     const String16 attr16("attr");
798 
799     // Data creation organizational tags.
800     const String16 string16("string");
801     const String16 drawable16("drawable");
802     const String16 color16("color");
803     const String16 bool16("bool");
804     const String16 integer16("integer");
805     const String16 dimen16("dimen");
806     const String16 fraction16("fraction");
807     const String16 style16("style");
808     const String16 plurals16("plurals");
809     const String16 array16("array");
810     const String16 string_array16("string-array");
811     const String16 integer_array16("integer-array");
812     const String16 public16("public");
813     const String16 public_padding16("public-padding");
814     const String16 private_symbols16("private-symbols");
815     const String16 java_symbol16("java-symbol");
816     const String16 add_resource16("add-resource");
817     const String16 skip16("skip");
818     const String16 eat_comment16("eat-comment");
819 
820     // Data creation tags.
821     const String16 bag16("bag");
822     const String16 item16("item");
823 
824     // Attribute type constants.
825     const String16 enum16("enum");
826 
827     // plural values
828     const String16 other16("other");
829     const String16 quantityOther16("^other");
830     const String16 zero16("zero");
831     const String16 quantityZero16("^zero");
832     const String16 one16("one");
833     const String16 quantityOne16("^one");
834     const String16 two16("two");
835     const String16 quantityTwo16("^two");
836     const String16 few16("few");
837     const String16 quantityFew16("^few");
838     const String16 many16("many");
839     const String16 quantityMany16("^many");
840 
841     // useful attribute names and special values
842     const String16 name16("name");
843     const String16 translatable16("translatable");
844     const String16 formatted16("formatted");
845     const String16 false16("false");
846 
847     const String16 myPackage(assets->getPackage());
848 
849     bool hasErrors = false;
850 
851     bool fileIsTranslatable = true;
852     if (strstr(in->getPrintableSource().c_str(), "donottranslate") != NULL) {
853         fileIsTranslatable = false;
854     }
855 
856     DefaultKeyedVector<String16, uint32_t> nextPublicId(0);
857 
858     // Stores the resource names that were skipped. Typically this happens when
859     // AAPT is invoked without a product specified and a resource has no
860     // 'default' product attribute.
861     KeyedVector<type_ident_pair_t, bool> skippedResourceNames;
862 
863     ResXMLTree::event_code_t code;
864     do {
865         code = block.next();
866     } while (code == ResXMLTree::START_NAMESPACE);
867 
868     size_t len;
869     if (code != ResXMLTree::START_TAG) {
870         SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
871                 "No start tag found\n");
872         return UNKNOWN_ERROR;
873     }
874     if (strcmp16(block.getElementName(&len), resources16.c_str()) != 0) {
875         SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
876                 "Invalid start tag %s\n", String8(block.getElementName(&len)).c_str());
877         return UNKNOWN_ERROR;
878     }
879 
880     ResTable_config curParams(defParams);
881 
882     ResTable_config pseudoParams(curParams);
883         pseudoParams.language[0] = 'e';
884         pseudoParams.language[1] = 'n';
885         pseudoParams.country[0] = 'X';
886         pseudoParams.country[1] = 'A';
887 
888     ResTable_config pseudoBidiParams(curParams);
889         pseudoBidiParams.language[0] = 'a';
890         pseudoBidiParams.language[1] = 'r';
891         pseudoBidiParams.country[0] = 'X';
892         pseudoBidiParams.country[1] = 'B';
893 
894     // We should skip resources for pseudolocales if they were
895     // already added automatically. This is a fix for a transition period when
896     // manually pseudolocalized resources may be expected.
897     // TODO: remove this check after next SDK version release.
898     if ((bundle->getPseudolocalize() & PSEUDO_ACCENTED &&
899          curParams.locale == pseudoParams.locale) ||
900         (bundle->getPseudolocalize() & PSEUDO_BIDI &&
901          curParams.locale == pseudoBidiParams.locale)) {
902         SourcePos(in->getPrintableSource(), 0).warning(
903                 "Resource file %s is skipped as pseudolocalization"
904                 " was done automatically.",
905                 in->getPrintableSource().c_str());
906         return NO_ERROR;
907     }
908 
909     while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
910         if (code == ResXMLTree::START_TAG) {
911             const String16* curTag = NULL;
912             String16 curType;
913             String16 curName;
914             int32_t curFormat = ResTable_map::TYPE_ANY;
915             bool curIsBag = false;
916             bool curIsBagReplaceOnOverwrite = false;
917             bool curIsStyled = false;
918             bool curIsPseudolocalizable = false;
919             bool curIsFormatted = fileIsTranslatable;
920             bool localHasErrors = false;
921 
922             if (strcmp16(block.getElementName(&len), skip16.c_str()) == 0) {
923                 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
924                         && code != ResXMLTree::BAD_DOCUMENT) {
925                     if (code == ResXMLTree::END_TAG) {
926                         if (strcmp16(block.getElementName(&len), skip16.c_str()) == 0) {
927                             break;
928                         }
929                     }
930                 }
931                 continue;
932 
933             } else if (strcmp16(block.getElementName(&len), eat_comment16.c_str()) == 0) {
934                 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
935                         && code != ResXMLTree::BAD_DOCUMENT) {
936                     if (code == ResXMLTree::END_TAG) {
937                         if (strcmp16(block.getElementName(&len), eat_comment16.c_str()) == 0) {
938                             break;
939                         }
940                     }
941                 }
942                 continue;
943 
944             } else if (strcmp16(block.getElementName(&len), public16.c_str()) == 0) {
945                 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
946 
947                 String16 type;
948                 ssize_t typeIdx = block.indexOfAttribute(NULL, "type");
949                 if (typeIdx < 0) {
950                     srcPos.error("A 'type' attribute is required for <public>\n");
951                     hasErrors = localHasErrors = true;
952                 }
953                 type = String16(block.getAttributeStringValue(typeIdx, &len));
954 
955                 String16 name;
956                 ssize_t nameIdx = block.indexOfAttribute(NULL, "name");
957                 if (nameIdx < 0) {
958                     srcPos.error("A 'name' attribute is required for <public>\n");
959                     hasErrors = localHasErrors = true;
960                 }
961                 name = String16(block.getAttributeStringValue(nameIdx, &len));
962 
963                 uint32_t ident = 0;
964                 ssize_t identIdx = block.indexOfAttribute(NULL, "id");
965                 if (identIdx >= 0) {
966                     const char16_t* identStr = block.getAttributeStringValue(identIdx, &len);
967                     Res_value identValue;
968                     if (!ResTable::stringToInt(identStr, len, &identValue)) {
969                         srcPos.error("Given 'id' attribute is not an integer: %s\n",
970                                 String8(block.getAttributeStringValue(identIdx, &len)).c_str());
971                         hasErrors = localHasErrors = true;
972                     } else {
973                         ident = identValue.data;
974                         nextPublicId.replaceValueFor(type, ident+1);
975                     }
976                 } else if (nextPublicId.indexOfKey(type) < 0) {
977                     srcPos.error("No 'id' attribute supplied <public>,"
978                             " and no previous id defined in this file.\n");
979                     hasErrors = localHasErrors = true;
980                 } else if (!localHasErrors) {
981                     ident = nextPublicId.valueFor(type);
982                     nextPublicId.replaceValueFor(type, ident+1);
983                 }
984 
985                 if (!localHasErrors) {
986                     err = outTable->addPublic(srcPos, myPackage, type, name, ident);
987                     if (err < NO_ERROR) {
988                         hasErrors = localHasErrors = true;
989                     }
990                 }
991                 if (!localHasErrors) {
992                     sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R"));
993                     if (symbols != NULL) {
994                         symbols = symbols->addNestedSymbol(String8(type), srcPos);
995                     }
996                     if (symbols != NULL) {
997                         symbols->makeSymbolPublic(String8(name), srcPos);
998                         String16 comment(
999                             block.getComment(&len) ? block.getComment(&len) : nulStr);
1000                         symbols->appendComment(String8(name), comment, srcPos);
1001                     } else {
1002                         srcPos.error("Unable to create symbols!\n");
1003                         hasErrors = localHasErrors = true;
1004                     }
1005                 }
1006 
1007                 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1008                     if (code == ResXMLTree::END_TAG) {
1009                         if (strcmp16(block.getElementName(&len), public16.c_str()) == 0) {
1010                             break;
1011                         }
1012                     }
1013                 }
1014                 continue;
1015 
1016             } else if (strcmp16(block.getElementName(&len), public_padding16.c_str()) == 0) {
1017                 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
1018 
1019                 String16 type;
1020                 ssize_t typeIdx = block.indexOfAttribute(NULL, "type");
1021                 if (typeIdx < 0) {
1022                     srcPos.error("A 'type' attribute is required for <public-padding>\n");
1023                     hasErrors = localHasErrors = true;
1024                 }
1025                 type = String16(block.getAttributeStringValue(typeIdx, &len));
1026 
1027                 String16 name;
1028                 ssize_t nameIdx = block.indexOfAttribute(NULL, "name");
1029                 if (nameIdx < 0) {
1030                     srcPos.error("A 'name' attribute is required for <public-padding>\n");
1031                     hasErrors = localHasErrors = true;
1032                 }
1033                 name = String16(block.getAttributeStringValue(nameIdx, &len));
1034 
1035                 uint32_t start = 0;
1036                 ssize_t startIdx = block.indexOfAttribute(NULL, "start");
1037                 if (startIdx >= 0) {
1038                     const char16_t* startStr = block.getAttributeStringValue(startIdx, &len);
1039                     Res_value startValue;
1040                     if (!ResTable::stringToInt(startStr, len, &startValue)) {
1041                         srcPos.error("Given 'start' attribute is not an integer: %s\n",
1042                                 String8(block.getAttributeStringValue(startIdx, &len)).c_str());
1043                         hasErrors = localHasErrors = true;
1044                     } else {
1045                         start = startValue.data;
1046                     }
1047                 } else if (nextPublicId.indexOfKey(type) < 0) {
1048                     srcPos.error("No 'start' attribute supplied <public-padding>,"
1049                             " and no previous id defined in this file.\n");
1050                     hasErrors = localHasErrors = true;
1051                 } else if (!localHasErrors) {
1052                     start = nextPublicId.valueFor(type);
1053                 }
1054 
1055                 uint32_t end = 0;
1056                 ssize_t endIdx = block.indexOfAttribute(NULL, "end");
1057                 if (endIdx >= 0) {
1058                     const char16_t* endStr = block.getAttributeStringValue(endIdx, &len);
1059                     Res_value endValue;
1060                     if (!ResTable::stringToInt(endStr, len, &endValue)) {
1061                         srcPos.error("Given 'end' attribute is not an integer: %s\n",
1062                                 String8(block.getAttributeStringValue(endIdx, &len)).c_str());
1063                         hasErrors = localHasErrors = true;
1064                     } else {
1065                         end = endValue.data;
1066                     }
1067                 } else {
1068                     srcPos.error("No 'end' attribute supplied <public-padding>\n");
1069                     hasErrors = localHasErrors = true;
1070                 }
1071 
1072                 if (end >= start) {
1073                     nextPublicId.replaceValueFor(type, end+1);
1074                 } else {
1075                     srcPos.error("Padding start '%ul' is after end '%ul'\n",
1076                             start, end);
1077                     hasErrors = localHasErrors = true;
1078                 }
1079 
1080                 String16 comment(
1081                     block.getComment(&len) ? block.getComment(&len) : nulStr);
1082                 for (uint32_t curIdent=start; curIdent<=end; curIdent++) {
1083                     if (localHasErrors) {
1084                         break;
1085                     }
1086                     String16 curName(name);
1087                     char buf[64];
1088                     sprintf(buf, "%d", (int)(end-curIdent+1));
1089                     curName.append(String16(buf));
1090 
1091                     err = outTable->addEntry(srcPos, myPackage, type, curName,
1092                                              String16("padding"), NULL, &curParams, false,
1093                                              ResTable_map::TYPE_STRING, overwrite);
1094                     if (err < NO_ERROR) {
1095                         hasErrors = localHasErrors = true;
1096                         break;
1097                     }
1098                     err = outTable->addPublic(srcPos, myPackage, type,
1099                             curName, curIdent);
1100                     if (err < NO_ERROR) {
1101                         hasErrors = localHasErrors = true;
1102                         break;
1103                     }
1104                     sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R"));
1105                     if (symbols != NULL) {
1106                         symbols = symbols->addNestedSymbol(String8(type), srcPos);
1107                     }
1108                     if (symbols != NULL) {
1109                         symbols->makeSymbolPublic(String8(curName), srcPos);
1110                         symbols->appendComment(String8(curName), comment, srcPos);
1111                     } else {
1112                         srcPos.error("Unable to create symbols!\n");
1113                         hasErrors = localHasErrors = true;
1114                     }
1115                 }
1116 
1117                 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1118                     if (code == ResXMLTree::END_TAG) {
1119                         if (strcmp16(block.getElementName(&len), public_padding16.c_str()) == 0) {
1120                             break;
1121                         }
1122                     }
1123                 }
1124                 continue;
1125 
1126             } else if (strcmp16(block.getElementName(&len), private_symbols16.c_str()) == 0) {
1127                 String16 pkg;
1128                 ssize_t pkgIdx = block.indexOfAttribute(NULL, "package");
1129                 if (pkgIdx < 0) {
1130                     SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1131                             "A 'package' attribute is required for <private-symbols>\n");
1132                     hasErrors = localHasErrors = true;
1133                 }
1134                 pkg = String16(block.getAttributeStringValue(pkgIdx, &len));
1135                 if (!localHasErrors) {
1136                     SourcePos(in->getPrintableSource(), block.getLineNumber()).warning(
1137                             "<private-symbols> is deprecated. Use the command line flag "
1138                             "--private-symbols instead.\n");
1139                     if (assets->havePrivateSymbols()) {
1140                         SourcePos(in->getPrintableSource(), block.getLineNumber()).warning(
1141                                 "private symbol package already specified. Ignoring...\n");
1142                     } else {
1143                         assets->setSymbolsPrivatePackage(String8(pkg));
1144                     }
1145                 }
1146 
1147                 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1148                     if (code == ResXMLTree::END_TAG) {
1149                         if (strcmp16(block.getElementName(&len), private_symbols16.c_str()) == 0) {
1150                             break;
1151                         }
1152                     }
1153                 }
1154                 continue;
1155 
1156             } else if (strcmp16(block.getElementName(&len), java_symbol16.c_str()) == 0) {
1157                 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
1158 
1159                 String16 type;
1160                 ssize_t typeIdx = block.indexOfAttribute(NULL, "type");
1161                 if (typeIdx < 0) {
1162                     srcPos.error("A 'type' attribute is required for <public>\n");
1163                     hasErrors = localHasErrors = true;
1164                 }
1165                 type = String16(block.getAttributeStringValue(typeIdx, &len));
1166 
1167                 String16 name;
1168                 ssize_t nameIdx = block.indexOfAttribute(NULL, "name");
1169                 if (nameIdx < 0) {
1170                     srcPos.error("A 'name' attribute is required for <public>\n");
1171                     hasErrors = localHasErrors = true;
1172                 }
1173                 name = String16(block.getAttributeStringValue(nameIdx, &len));
1174 
1175                 sp<AaptSymbols> symbols = assets->getJavaSymbolsFor(String8("R"));
1176                 if (symbols != NULL) {
1177                     symbols = symbols->addNestedSymbol(String8(type), srcPos);
1178                 }
1179                 if (symbols != NULL) {
1180                     symbols->makeSymbolJavaSymbol(String8(name), srcPos);
1181                     String16 comment(
1182                         block.getComment(&len) ? block.getComment(&len) : nulStr);
1183                     symbols->appendComment(String8(name), comment, srcPos);
1184                 } else {
1185                     srcPos.error("Unable to create symbols!\n");
1186                     hasErrors = localHasErrors = true;
1187                 }
1188 
1189                 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1190                     if (code == ResXMLTree::END_TAG) {
1191                         if (strcmp16(block.getElementName(&len), java_symbol16.c_str()) == 0) {
1192                             break;
1193                         }
1194                     }
1195                 }
1196                 continue;
1197 
1198 
1199             } else if (strcmp16(block.getElementName(&len), add_resource16.c_str()) == 0) {
1200                 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
1201 
1202                 String16 typeName;
1203                 ssize_t typeIdx = block.indexOfAttribute(NULL, "type");
1204                 if (typeIdx < 0) {
1205                     srcPos.error("A 'type' attribute is required for <add-resource>\n");
1206                     hasErrors = localHasErrors = true;
1207                 }
1208                 typeName = String16(block.getAttributeStringValue(typeIdx, &len));
1209 
1210                 String16 name;
1211                 ssize_t nameIdx = block.indexOfAttribute(NULL, "name");
1212                 if (nameIdx < 0) {
1213                     srcPos.error("A 'name' attribute is required for <add-resource>\n");
1214                     hasErrors = localHasErrors = true;
1215                 }
1216                 name = String16(block.getAttributeStringValue(nameIdx, &len));
1217 
1218                 outTable->canAddEntry(srcPos, myPackage, typeName, name);
1219 
1220                 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1221                     if (code == ResXMLTree::END_TAG) {
1222                         if (strcmp16(block.getElementName(&len), add_resource16.c_str()) == 0) {
1223                             break;
1224                         }
1225                     }
1226                 }
1227                 continue;
1228 
1229             } else if (strcmp16(block.getElementName(&len), declare_styleable16.c_str()) == 0) {
1230                 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
1231 
1232                 String16 ident;
1233                 ssize_t identIdx = block.indexOfAttribute(NULL, "name");
1234                 if (identIdx < 0) {
1235                     srcPos.error("A 'name' attribute is required for <declare-styleable>\n");
1236                     hasErrors = localHasErrors = true;
1237                 }
1238                 ident = String16(block.getAttributeStringValue(identIdx, &len));
1239 
1240                 sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R"));
1241                 if (!localHasErrors) {
1242                     if (symbols != NULL) {
1243                         symbols = symbols->addNestedSymbol(String8("styleable"), srcPos);
1244                     }
1245                     sp<AaptSymbols> styleSymbols = symbols;
1246                     if (symbols != NULL) {
1247                         symbols = symbols->addNestedSymbol(String8(ident), srcPos);
1248                     }
1249                     if (symbols == NULL) {
1250                         srcPos.error("Unable to create symbols!\n");
1251                         return UNKNOWN_ERROR;
1252                     }
1253 
1254                     String16 comment(
1255                         block.getComment(&len) ? block.getComment(&len) : nulStr);
1256                     styleSymbols->appendComment(String8(ident), comment, srcPos);
1257                 } else {
1258                     symbols = NULL;
1259                 }
1260 
1261                 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1262                     if (code == ResXMLTree::START_TAG) {
1263                         if (strcmp16(block.getElementName(&len), skip16.c_str()) == 0) {
1264                             while ((code=block.next()) != ResXMLTree::END_DOCUMENT
1265                                    && code != ResXMLTree::BAD_DOCUMENT) {
1266                                 if (code == ResXMLTree::END_TAG) {
1267                                     if (strcmp16(block.getElementName(&len), skip16.c_str()) == 0) {
1268                                         break;
1269                                     }
1270                                 }
1271                             }
1272                             continue;
1273                         } else if (strcmp16(block.getElementName(&len), eat_comment16.c_str()) == 0) {
1274                             while ((code=block.next()) != ResXMLTree::END_DOCUMENT
1275                                    && code != ResXMLTree::BAD_DOCUMENT) {
1276                                 if (code == ResXMLTree::END_TAG) {
1277                                     if (strcmp16(block.getElementName(&len), eat_comment16.c_str()) == 0) {
1278                                         break;
1279                                     }
1280                                 }
1281                             }
1282                             continue;
1283                         } else if (strcmp16(block.getElementName(&len), attr16.c_str()) != 0) {
1284                             SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1285                                     "Tag <%s> can not appear inside <declare-styleable>, only <attr>\n",
1286                                     String8(block.getElementName(&len)).c_str());
1287                             return UNKNOWN_ERROR;
1288                         }
1289 
1290                         String16 comment(
1291                             block.getComment(&len) ? block.getComment(&len) : nulStr);
1292                         String16 itemIdent;
1293                         err = compileAttribute(in, block, myPackage, outTable, &itemIdent, true);
1294                         if (err != NO_ERROR) {
1295                             hasErrors = localHasErrors = true;
1296                         }
1297 
1298                         if (symbols != NULL) {
1299                             SourcePos srcPos(String8(in->getPrintableSource()), block.getLineNumber());
1300                             symbols->addSymbol(String8(itemIdent), 0, srcPos);
1301                             symbols->appendComment(String8(itemIdent), comment, srcPos);
1302                             //printf("Attribute %s comment: %s\n", String8(itemIdent).c_str(),
1303                             //     String8(comment).c_str());
1304                         }
1305                     } else if (code == ResXMLTree::END_TAG) {
1306                         if (strcmp16(block.getElementName(&len), declare_styleable16.c_str()) == 0) {
1307                             break;
1308                         }
1309 
1310                         SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1311                                 "Found tag </%s> where </attr> is expected\n",
1312                                 String8(block.getElementName(&len)).c_str());
1313                         return UNKNOWN_ERROR;
1314                     }
1315                 }
1316                 continue;
1317 
1318             } else if (strcmp16(block.getElementName(&len), attr16.c_str()) == 0) {
1319                 err = compileAttribute(in, block, myPackage, outTable, NULL);
1320                 if (err != NO_ERROR) {
1321                     hasErrors = true;
1322                 }
1323                 continue;
1324 
1325             } else if (strcmp16(block.getElementName(&len), item16.c_str()) == 0) {
1326                 curTag = &item16;
1327                 ssize_t attri = block.indexOfAttribute(NULL, "type");
1328                 if (attri >= 0) {
1329                     curType = String16(block.getAttributeStringValue(attri, &len));
1330                     ssize_t nameIdx = block.indexOfAttribute(NULL, "name");
1331                     if (nameIdx >= 0) {
1332                         curName = String16(block.getAttributeStringValue(nameIdx, &len));
1333                     }
1334                     ssize_t formatIdx = block.indexOfAttribute(NULL, "format");
1335                     if (formatIdx >= 0) {
1336                         String16 formatStr = String16(block.getAttributeStringValue(
1337                                 formatIdx, &len));
1338                         curFormat = parse_flags(formatStr.c_str(), formatStr.size(),
1339                                                 gFormatFlags);
1340                         if (curFormat == 0) {
1341                             SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1342                                     "Tag <item> 'format' attribute value \"%s\" not valid\n",
1343                                     String8(formatStr).c_str());
1344                             hasErrors = localHasErrors = true;
1345                         }
1346                     }
1347                 } else {
1348                     SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1349                             "A 'type' attribute is required for <item>\n");
1350                     hasErrors = localHasErrors = true;
1351                 }
1352                 curIsStyled = true;
1353             } else if (strcmp16(block.getElementName(&len), string16.c_str()) == 0) {
1354                 // Note the existence and locale of every string we process
1355                 char rawLocale[RESTABLE_MAX_LOCALE_LEN];
1356                 curParams.getBcp47Locale(rawLocale);
1357                 String8 locale(rawLocale);
1358                 String16 name;
1359                 String16 translatable;
1360                 String16 formatted;
1361 
1362                 size_t n = block.getAttributeCount();
1363                 for (size_t i = 0; i < n; i++) {
1364                     size_t length;
1365                     const char16_t* attr = block.getAttributeName(i, &length);
1366                     if (strcmp16(attr, name16.c_str()) == 0) {
1367                         name = String16(block.getAttributeStringValue(i, &length));
1368                     } else if (strcmp16(attr, translatable16.c_str()) == 0) {
1369                         translatable = String16(block.getAttributeStringValue(i, &length));
1370                     } else if (strcmp16(attr, formatted16.c_str()) == 0) {
1371                         formatted = String16(block.getAttributeStringValue(i, &length));
1372                     }
1373                 }
1374 
1375                 if (name.size() > 0) {
1376                     if (locale.size() == 0) {
1377                         outTable->addDefaultLocalization(name);
1378                     }
1379                     if (translatable == false16) {
1380                         curIsFormatted = false;
1381                         // Untranslatable strings must only exist in the default [empty] locale
1382                         if (locale.size() > 0) {
1383                             SourcePos(in->getPrintableSource(), block.getLineNumber()).warning(
1384                                     "string '%s' marked untranslatable but exists in locale '%s'\n",
1385                                     String8(name).c_str(),
1386                                     locale.c_str());
1387                             // hasErrors = localHasErrors = true;
1388                         } else {
1389                             // Intentionally empty block:
1390                             //
1391                             // Don't add untranslatable strings to the localization table; that
1392                             // way if we later see localizations of them, they'll be flagged as
1393                             // having no default translation.
1394                         }
1395                     } else {
1396                         outTable->addLocalization(
1397                                 name,
1398                                 locale,
1399                                 SourcePos(in->getPrintableSource(), block.getLineNumber()));
1400                     }
1401 
1402                     if (formatted == false16) {
1403                         curIsFormatted = false;
1404                     }
1405                 }
1406 
1407                 curTag = &string16;
1408                 curType = string16;
1409                 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_STRING;
1410                 curIsStyled = true;
1411                 curIsPseudolocalizable = fileIsTranslatable && (translatable != false16);
1412             } else if (strcmp16(block.getElementName(&len), drawable16.c_str()) == 0) {
1413                 curTag = &drawable16;
1414                 curType = drawable16;
1415                 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_COLOR;
1416             } else if (strcmp16(block.getElementName(&len), color16.c_str()) == 0) {
1417                 curTag = &color16;
1418                 curType = color16;
1419                 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_COLOR;
1420             } else if (strcmp16(block.getElementName(&len), bool16.c_str()) == 0) {
1421                 curTag = &bool16;
1422                 curType = bool16;
1423                 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_BOOLEAN;
1424             } else if (strcmp16(block.getElementName(&len), integer16.c_str()) == 0) {
1425                 curTag = &integer16;
1426                 curType = integer16;
1427                 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_INTEGER;
1428             } else if (strcmp16(block.getElementName(&len), dimen16.c_str()) == 0) {
1429                 curTag = &dimen16;
1430                 curType = dimen16;
1431                 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_DIMENSION;
1432             } else if (strcmp16(block.getElementName(&len), fraction16.c_str()) == 0) {
1433                 curTag = &fraction16;
1434                 curType = fraction16;
1435                 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_FRACTION;
1436             } else if (strcmp16(block.getElementName(&len), bag16.c_str()) == 0) {
1437                 curTag = &bag16;
1438                 curIsBag = true;
1439                 ssize_t attri = block.indexOfAttribute(NULL, "type");
1440                 if (attri >= 0) {
1441                     curType = String16(block.getAttributeStringValue(attri, &len));
1442                 } else {
1443                     SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1444                             "A 'type' attribute is required for <bag>\n");
1445                     hasErrors = localHasErrors = true;
1446                 }
1447             } else if (strcmp16(block.getElementName(&len), style16.c_str()) == 0) {
1448                 curTag = &style16;
1449                 curType = style16;
1450                 curIsBag = true;
1451             } else if (strcmp16(block.getElementName(&len), plurals16.c_str()) == 0) {
1452                 curTag = &plurals16;
1453                 curType = plurals16;
1454                 curIsBag = true;
1455                 curIsPseudolocalizable = fileIsTranslatable;
1456             } else if (strcmp16(block.getElementName(&len), array16.c_str()) == 0) {
1457                 curTag = &array16;
1458                 curType = array16;
1459                 curIsBag = true;
1460                 curIsBagReplaceOnOverwrite = true;
1461                 ssize_t formatIdx = block.indexOfAttribute(NULL, "format");
1462                 if (formatIdx >= 0) {
1463                     String16 formatStr = String16(block.getAttributeStringValue(
1464                             formatIdx, &len));
1465                     curFormat = parse_flags(formatStr.c_str(), formatStr.size(),
1466                                             gFormatFlags);
1467                     if (curFormat == 0) {
1468                         SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1469                                 "Tag <array> 'format' attribute value \"%s\" not valid\n",
1470                                 String8(formatStr).c_str());
1471                         hasErrors = localHasErrors = true;
1472                     }
1473                 }
1474             } else if (strcmp16(block.getElementName(&len), string_array16.c_str()) == 0) {
1475                 // Check whether these strings need valid formats.
1476                 // (simplified form of what string16 does above)
1477                 bool isTranslatable = false;
1478                 size_t n = block.getAttributeCount();
1479 
1480                 // Pseudolocalizable by default, unless this string array isn't
1481                 // translatable.
1482                 for (size_t i = 0; i < n; i++) {
1483                     size_t length;
1484                     const char16_t* attr = block.getAttributeName(i, &length);
1485                     if (strcmp16(attr, formatted16.c_str()) == 0) {
1486                         const char16_t* value = block.getAttributeStringValue(i, &length);
1487                         if (strcmp16(value, false16.c_str()) == 0) {
1488                             curIsFormatted = false;
1489                         }
1490                     } else if (strcmp16(attr, translatable16.c_str()) == 0) {
1491                         const char16_t* value = block.getAttributeStringValue(i, &length);
1492                         if (strcmp16(value, false16.c_str()) == 0) {
1493                             isTranslatable = false;
1494                         }
1495                     }
1496                 }
1497 
1498                 curTag = &string_array16;
1499                 curType = array16;
1500                 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_STRING;
1501                 curIsBag = true;
1502                 curIsBagReplaceOnOverwrite = true;
1503                 curIsPseudolocalizable = isTranslatable && fileIsTranslatable;
1504             } else if (strcmp16(block.getElementName(&len), integer_array16.c_str()) == 0) {
1505                 curTag = &integer_array16;
1506                 curType = array16;
1507                 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_INTEGER;
1508                 curIsBag = true;
1509                 curIsBagReplaceOnOverwrite = true;
1510             } else {
1511                 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1512                         "Found tag %s where item is expected\n",
1513                         String8(block.getElementName(&len)).c_str());
1514                 return UNKNOWN_ERROR;
1515             }
1516 
1517             String16 ident;
1518             ssize_t identIdx = block.indexOfAttribute(NULL, "name");
1519             if (identIdx >= 0) {
1520                 ident = String16(block.getAttributeStringValue(identIdx, &len));
1521             } else {
1522                 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1523                         "A 'name' attribute is required for <%s>\n",
1524                         String8(*curTag).c_str());
1525                 hasErrors = localHasErrors = true;
1526             }
1527 
1528             String16 product;
1529             identIdx = block.indexOfAttribute(NULL, "product");
1530             if (identIdx >= 0) {
1531                 product = String16(block.getAttributeStringValue(identIdx, &len));
1532             }
1533 
1534             String16 comment(block.getComment(&len) ? block.getComment(&len) : nulStr);
1535 
1536             if (curIsBag) {
1537                 // Figure out the parent of this bag...
1538                 String16 parentIdent;
1539                 ssize_t parentIdentIdx = block.indexOfAttribute(NULL, "parent");
1540                 if (parentIdentIdx >= 0) {
1541                     parentIdent = String16(block.getAttributeStringValue(parentIdentIdx, &len));
1542                 } else {
1543                     ssize_t sep = ident.findLast('.');
1544                     if (sep >= 0) {
1545                         parentIdent = String16(ident, sep);
1546                     }
1547                 }
1548 
1549                 if (!localHasErrors) {
1550                     err = outTable->startBag(SourcePos(in->getPrintableSource(),
1551                             block.getLineNumber()), myPackage, curType, ident,
1552                             parentIdent, &curParams,
1553                             overwrite, curIsBagReplaceOnOverwrite);
1554                     if (err != NO_ERROR) {
1555                         hasErrors = localHasErrors = true;
1556                     }
1557                 }
1558 
1559                 ssize_t elmIndex = 0;
1560                 char elmIndexStr[14];
1561                 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
1562                         && code != ResXMLTree::BAD_DOCUMENT) {
1563 
1564                     if (code == ResXMLTree::START_TAG) {
1565                         if (strcmp16(block.getElementName(&len), item16.c_str()) != 0) {
1566                             SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1567                                     "Tag <%s> can not appear inside <%s>, only <item>\n",
1568                                     String8(block.getElementName(&len)).c_str(),
1569                                     String8(*curTag).c_str());
1570                             return UNKNOWN_ERROR;
1571                         }
1572 
1573                         String16 itemIdent;
1574                         if (curType == array16) {
1575                             sprintf(elmIndexStr, "^index_%d", (int)elmIndex++);
1576                             itemIdent = String16(elmIndexStr);
1577                         } else if (curType == plurals16) {
1578                             ssize_t itemIdentIdx = block.indexOfAttribute(NULL, "quantity");
1579                             if (itemIdentIdx >= 0) {
1580                                 String16 quantity16(block.getAttributeStringValue(itemIdentIdx, &len));
1581                                 if (quantity16 == other16) {
1582                                     itemIdent = quantityOther16;
1583                                 }
1584                                 else if (quantity16 == zero16) {
1585                                     itemIdent = quantityZero16;
1586                                 }
1587                                 else if (quantity16 == one16) {
1588                                     itemIdent = quantityOne16;
1589                                 }
1590                                 else if (quantity16 == two16) {
1591                                     itemIdent = quantityTwo16;
1592                                 }
1593                                 else if (quantity16 == few16) {
1594                                     itemIdent = quantityFew16;
1595                                 }
1596                                 else if (quantity16 == many16) {
1597                                     itemIdent = quantityMany16;
1598                                 }
1599                                 else {
1600                                     SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1601                                             "Illegal 'quantity' attribute is <item> inside <plurals>\n");
1602                                     hasErrors = localHasErrors = true;
1603                                 }
1604                             } else {
1605                                 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1606                                         "A 'quantity' attribute is required for <item> inside <plurals>\n");
1607                                 hasErrors = localHasErrors = true;
1608                             }
1609                         } else {
1610                             ssize_t itemIdentIdx = block.indexOfAttribute(NULL, "name");
1611                             if (itemIdentIdx >= 0) {
1612                                 itemIdent = String16(block.getAttributeStringValue(itemIdentIdx, &len));
1613                             } else {
1614                                 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1615                                         "A 'name' attribute is required for <item>\n");
1616                                 hasErrors = localHasErrors = true;
1617                             }
1618                         }
1619 
1620                         ResXMLParser::ResXMLPosition parserPosition;
1621                         block.getPosition(&parserPosition);
1622 
1623                         err = parseAndAddBag(bundle, in, &block, curParams, myPackage, curType,
1624                                 ident, parentIdent, itemIdent, curFormat, curIsFormatted,
1625                                 product, NO_PSEUDOLOCALIZATION, overwrite, outTable);
1626                         if (err == NO_ERROR) {
1627                             if (curIsPseudolocalizable && localeIsDefined(curParams)
1628                                     && bundle->getPseudolocalize() > 0) {
1629                                 // pseudolocalize here
1630                                 if ((PSEUDO_ACCENTED & bundle->getPseudolocalize()) ==
1631                                    PSEUDO_ACCENTED) {
1632                                     block.setPosition(parserPosition);
1633                                     err = parseAndAddBag(bundle, in, &block, pseudoParams, myPackage,
1634                                             curType, ident, parentIdent, itemIdent, curFormat,
1635                                             curIsFormatted, product, PSEUDO_ACCENTED,
1636                                             overwrite, outTable);
1637                                 }
1638                                 if ((PSEUDO_BIDI & bundle->getPseudolocalize()) ==
1639                                    PSEUDO_BIDI) {
1640                                     block.setPosition(parserPosition);
1641                                     err = parseAndAddBag(bundle, in, &block, pseudoBidiParams, myPackage,
1642                                             curType, ident, parentIdent, itemIdent, curFormat,
1643                                             curIsFormatted, product, PSEUDO_BIDI,
1644                                             overwrite, outTable);
1645                                 }
1646                             }
1647                         }
1648                         if (err != NO_ERROR) {
1649                             hasErrors = localHasErrors = true;
1650                         }
1651                     } else if (code == ResXMLTree::END_TAG) {
1652                         if (strcmp16(block.getElementName(&len), curTag->c_str()) != 0) {
1653                             SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1654                                     "Found tag </%s> where </%s> is expected\n",
1655                                     String8(block.getElementName(&len)).c_str(),
1656                                     String8(*curTag).c_str());
1657                             return UNKNOWN_ERROR;
1658                         }
1659                         break;
1660                     }
1661                 }
1662             } else {
1663                 ResXMLParser::ResXMLPosition parserPosition;
1664                 block.getPosition(&parserPosition);
1665 
1666                 err = parseAndAddEntry(bundle, in, &block, curParams, myPackage, curType, ident,
1667                         *curTag, curIsStyled, curFormat, curIsFormatted,
1668                         product, NO_PSEUDOLOCALIZATION, overwrite, &skippedResourceNames, outTable);
1669 
1670                 if (err < NO_ERROR) { // Why err < NO_ERROR instead of err != NO_ERROR?
1671                     hasErrors = localHasErrors = true;
1672                 }
1673                 else if (err == NO_ERROR) {
1674                     if (curType == string16 && !curParams.language[0] && !curParams.country[0]) {
1675                         outTable->addDefaultLocalization(curName);
1676                     }
1677                     if (curIsPseudolocalizable && localeIsDefined(curParams)
1678                             && bundle->getPseudolocalize() > 0) {
1679                         // pseudolocalize here
1680                         if ((PSEUDO_ACCENTED & bundle->getPseudolocalize()) ==
1681                            PSEUDO_ACCENTED) {
1682                             block.setPosition(parserPosition);
1683                             err = parseAndAddEntry(bundle, in, &block, pseudoParams, myPackage, curType,
1684                                     ident, *curTag, curIsStyled, curFormat,
1685                                     curIsFormatted, product,
1686                                     PSEUDO_ACCENTED, overwrite, &skippedResourceNames, outTable);
1687                         }
1688                         if ((PSEUDO_BIDI & bundle->getPseudolocalize()) ==
1689                            PSEUDO_BIDI) {
1690                             block.setPosition(parserPosition);
1691                             err = parseAndAddEntry(bundle, in, &block, pseudoBidiParams,
1692                                     myPackage, curType, ident, *curTag, curIsStyled, curFormat,
1693                                     curIsFormatted, product,
1694                                     PSEUDO_BIDI, overwrite, &skippedResourceNames, outTable);
1695                         }
1696                         if (err != NO_ERROR) {
1697                             hasErrors = localHasErrors = true;
1698                         }
1699                     }
1700                 }
1701             }
1702 
1703 #if 0
1704             if (comment.size() > 0) {
1705                 printf("Comment for @%s:%s/%s: %s\n", String8(myPackage).c_str(),
1706                        String8(curType).c_str(), String8(ident).c_str(),
1707                        String8(comment).c_str());
1708             }
1709 #endif
1710             if (!localHasErrors) {
1711                 outTable->appendComment(myPackage, curType, ident, comment, false);
1712             }
1713         }
1714         else if (code == ResXMLTree::END_TAG) {
1715             if (strcmp16(block.getElementName(&len), resources16.c_str()) != 0) {
1716                 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1717                         "Unexpected end tag %s\n", String8(block.getElementName(&len)).c_str());
1718                 return UNKNOWN_ERROR;
1719             }
1720         }
1721         else if (code == ResXMLTree::START_NAMESPACE || code == ResXMLTree::END_NAMESPACE) {
1722         }
1723         else if (code == ResXMLTree::TEXT) {
1724             if (isWhitespace(block.getText(&len))) {
1725                 continue;
1726             }
1727             SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1728                     "Found text \"%s\" where item tag is expected\n",
1729                     String8(block.getText(&len)).c_str());
1730             return UNKNOWN_ERROR;
1731         }
1732     }
1733 
1734     // For every resource defined, there must be exist one variant with a product attribute
1735     // set to 'default' (or no product attribute at all).
1736     // We check to see that for every resource that was ignored because of a mismatched
1737     // product attribute, some product variant of that resource was processed.
1738     for (size_t i = 0; i < skippedResourceNames.size(); i++) {
1739         if (skippedResourceNames[i]) {
1740             const type_ident_pair_t& p = skippedResourceNames.keyAt(i);
1741             if (!outTable->hasBagOrEntry(myPackage, p.type, p.ident)) {
1742                 const char* bundleProduct =
1743                         (bundle->getProduct() == NULL) ? "" : bundle->getProduct();
1744                 fprintf(stderr, "In resource file %s: %s\n",
1745                         in->getPrintableSource().c_str(),
1746                         curParams.toString().c_str());
1747 
1748                 fprintf(stderr, "\t%s '%s' does not match product %s.\n"
1749                         "\tYou may have forgotten to include a 'default' product variant"
1750                         " of the resource.\n",
1751                         String8(p.type).c_str(), String8(p.ident).c_str(),
1752                         bundleProduct[0] == 0 ? "default" : bundleProduct);
1753                 return UNKNOWN_ERROR;
1754             }
1755         }
1756     }
1757 
1758     return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
1759 }
1760 
ResourceTable(Bundle * bundle,const String16 & assetsPackage,ResourceTable::PackageType type)1761 ResourceTable::ResourceTable(Bundle* bundle, const String16& assetsPackage, ResourceTable::PackageType type)
1762     : mAssetsPackage(assetsPackage)
1763     , mPackageType(type)
1764     , mTypeIdOffset(0)
1765     , mNumLocal(0)
1766     , mBundle(bundle)
1767 {
1768     ssize_t packageId = -1;
1769     switch (mPackageType) {
1770         case App:
1771         case AppFeature:
1772             packageId = 0x7f;
1773             break;
1774 
1775         case System:
1776             packageId = 0x01;
1777             break;
1778 
1779         case SharedLibrary:
1780             packageId = 0x00;
1781             break;
1782 
1783         default:
1784             assert(0);
1785             break;
1786     }
1787     sp<Package> package = new Package(mAssetsPackage, packageId);
1788     mPackages.add(assetsPackage, package);
1789     mOrderedPackages.add(package);
1790 
1791     // Every resource table always has one first entry, the bag attributes.
1792     const SourcePos unknown(String8("????"), 0);
1793     getType(mAssetsPackage, String16("attr"), unknown);
1794 }
1795 
findLargestTypeIdForPackage(const ResTable & table,const String16 & packageName)1796 static uint32_t findLargestTypeIdForPackage(const ResTable& table, const String16& packageName) {
1797     const size_t basePackageCount = table.getBasePackageCount();
1798     for (size_t i = 0; i < basePackageCount; i++) {
1799         if (packageName == table.getBasePackageName(i)) {
1800             return table.getLastTypeIdForPackage(i);
1801         }
1802     }
1803     return 0;
1804 }
1805 
addIncludedResources(Bundle * bundle,const sp<AaptAssets> & assets)1806 status_t ResourceTable::addIncludedResources(Bundle* bundle, const sp<AaptAssets>& assets)
1807 {
1808     status_t err = assets->buildIncludedResources(bundle);
1809     if (err != NO_ERROR) {
1810         return err;
1811     }
1812 
1813     mAssets = assets;
1814     mTypeIdOffset = findLargestTypeIdForPackage(assets->getIncludedResources(), mAssetsPackage);
1815 
1816     const String8& featureAfter = bundle->getFeatureAfterPackage();
1817     if (!featureAfter.empty()) {
1818         AssetManager featureAssetManager;
1819         if (!featureAssetManager.addAssetPath(featureAfter, NULL)) {
1820             fprintf(stderr, "ERROR: Feature package '%s' not found.\n",
1821                     featureAfter.c_str());
1822             return UNKNOWN_ERROR;
1823         }
1824 
1825         const ResTable& featureTable = featureAssetManager.getResources(false);
1826         mTypeIdOffset = std::max(mTypeIdOffset,
1827                 findLargestTypeIdForPackage(featureTable, mAssetsPackage));
1828     }
1829 
1830     return NO_ERROR;
1831 }
1832 
addPublic(const SourcePos & sourcePos,const String16 & package,const String16 & type,const String16 & name,const uint32_t ident)1833 status_t ResourceTable::addPublic(const SourcePos& sourcePos,
1834                                   const String16& package,
1835                                   const String16& type,
1836                                   const String16& name,
1837                                   const uint32_t ident)
1838 {
1839     uint32_t rid = mAssets->getIncludedResources()
1840         .identifierForName(name.c_str(), name.size(),
1841                            type.c_str(), type.size(),
1842                            package.c_str(), package.size());
1843     if (rid != 0) {
1844         sourcePos.error("Error declaring public resource %s/%s for included package %s\n",
1845                 String8(type).c_str(), String8(name).c_str(),
1846                 String8(package).c_str());
1847         return UNKNOWN_ERROR;
1848     }
1849 
1850     sp<Type> t = getType(package, type, sourcePos);
1851     if (t == NULL) {
1852         return UNKNOWN_ERROR;
1853     }
1854     return t->addPublic(sourcePos, name, ident);
1855 }
1856 
addEntry(const SourcePos & sourcePos,const String16 & package,const String16 & type,const String16 & name,const String16 & value,const Vector<StringPool::entry_style_span> * style,const ResTable_config * params,const bool doSetIndex,const int32_t format,const bool overwrite)1857 status_t ResourceTable::addEntry(const SourcePos& sourcePos,
1858                                  const String16& package,
1859                                  const String16& type,
1860                                  const String16& name,
1861                                  const String16& value,
1862                                  const Vector<StringPool::entry_style_span>* style,
1863                                  const ResTable_config* params,
1864                                  const bool doSetIndex,
1865                                  const int32_t format,
1866                                  const bool overwrite)
1867 {
1868     uint32_t rid = mAssets->getIncludedResources()
1869         .identifierForName(name.c_str(), name.size(),
1870                            type.c_str(), type.size(),
1871                            package.c_str(), package.size());
1872     if (rid != 0) {
1873         sourcePos.error("Resource entry %s/%s is already defined in package %s.",
1874                 String8(type).c_str(), String8(name).c_str(), String8(package).c_str());
1875         return UNKNOWN_ERROR;
1876     }
1877 
1878     sp<Entry> e = getEntry(package, type, name, sourcePos, overwrite,
1879                            params, doSetIndex);
1880     if (e == NULL) {
1881         return UNKNOWN_ERROR;
1882     }
1883     status_t err = e->setItem(sourcePos, value, style, format, overwrite);
1884     if (err == NO_ERROR) {
1885         mNumLocal++;
1886     }
1887     return err;
1888 }
1889 
startBag(const SourcePos & sourcePos,const String16 & package,const String16 & type,const String16 & name,const String16 & bagParent,const ResTable_config * params,bool overlay,bool replace,bool)1890 status_t ResourceTable::startBag(const SourcePos& sourcePos,
1891                                  const String16& package,
1892                                  const String16& type,
1893                                  const String16& name,
1894                                  const String16& bagParent,
1895                                  const ResTable_config* params,
1896                                  bool overlay,
1897                                  bool replace, bool /* isId */)
1898 {
1899     status_t result = NO_ERROR;
1900 
1901     // Check for adding entries in other packages...  for now we do
1902     // nothing.  We need to do the right thing here to support skinning.
1903     uint32_t rid = mAssets->getIncludedResources()
1904     .identifierForName(name.c_str(), name.size(),
1905                        type.c_str(), type.size(),
1906                        package.c_str(), package.size());
1907     if (rid != 0) {
1908         sourcePos.error("Resource entry %s/%s is already defined in package %s.",
1909                 String8(type).c_str(), String8(name).c_str(), String8(package).c_str());
1910         return UNKNOWN_ERROR;
1911     }
1912 
1913     if (overlay && !mBundle->getAutoAddOverlay() && !hasBagOrEntry(package, type, name)) {
1914         bool canAdd = false;
1915         sp<Package> p = mPackages.valueFor(package);
1916         if (p != NULL) {
1917             sp<Type> t = p->getTypes().valueFor(type);
1918             if (t != NULL) {
1919                 if (t->getCanAddEntries().indexOf(name) >= 0) {
1920                     canAdd = true;
1921                 }
1922             }
1923         }
1924         if (!canAdd) {
1925             sourcePos.error("Resource does not already exist in overlay at '%s'; use <add-resource> to add.\n",
1926                             String8(name).c_str());
1927             return UNKNOWN_ERROR;
1928         }
1929     }
1930     sp<Entry> e = getEntry(package, type, name, sourcePos, overlay, params);
1931     if (e == NULL) {
1932         return UNKNOWN_ERROR;
1933     }
1934 
1935     // If a parent is explicitly specified, set it.
1936     if (bagParent.size() > 0) {
1937         e->setParent(bagParent);
1938     }
1939 
1940     if ((result = e->makeItABag(sourcePos)) != NO_ERROR) {
1941         return result;
1942     }
1943 
1944     if (overlay && replace) {
1945         return e->emptyBag(sourcePos);
1946     }
1947     return result;
1948 }
1949 
addBag(const SourcePos & sourcePos,const String16 & package,const String16 & type,const String16 & name,const String16 & bagParent,const String16 & bagKey,const String16 & value,const Vector<StringPool::entry_style_span> * style,const ResTable_config * params,bool replace,bool isId,const int32_t format)1950 status_t ResourceTable::addBag(const SourcePos& sourcePos,
1951                                const String16& package,
1952                                const String16& type,
1953                                const String16& name,
1954                                const String16& bagParent,
1955                                const String16& bagKey,
1956                                const String16& value,
1957                                const Vector<StringPool::entry_style_span>* style,
1958                                const ResTable_config* params,
1959                                bool replace, bool isId, const int32_t format)
1960 {
1961     // Check for adding entries in other packages...  for now we do
1962     // nothing.  We need to do the right thing here to support skinning.
1963     uint32_t rid = mAssets->getIncludedResources()
1964         .identifierForName(name.c_str(), name.size(),
1965                            type.c_str(), type.size(),
1966                            package.c_str(), package.size());
1967     if (rid != 0) {
1968         return NO_ERROR;
1969     }
1970 
1971 #if 0
1972     if (name == String16("left")) {
1973         printf("Adding bag left: file=%s, line=%d, type=%s\n",
1974                sourcePos.file.striing(), sourcePos.line, String8(type).c_str());
1975     }
1976 #endif
1977     sp<Entry> e = getEntry(package, type, name, sourcePos, replace, params);
1978     if (e == NULL) {
1979         return UNKNOWN_ERROR;
1980     }
1981 
1982     // If a parent is explicitly specified, set it.
1983     if (bagParent.size() > 0) {
1984         e->setParent(bagParent);
1985     }
1986 
1987     const bool first = e->getBag().indexOfKey(bagKey) < 0;
1988     status_t err = e->addToBag(sourcePos, bagKey, value, style, replace, isId, format);
1989     if (err == NO_ERROR && first) {
1990         mNumLocal++;
1991     }
1992     return err;
1993 }
1994 
hasBagOrEntry(const String16 & package,const String16 & type,const String16 & name) const1995 bool ResourceTable::hasBagOrEntry(const String16& package,
1996                                   const String16& type,
1997                                   const String16& name) const
1998 {
1999     // First look for this in the included resources...
2000     uint32_t rid = mAssets->getIncludedResources()
2001         .identifierForName(name.c_str(), name.size(),
2002                            type.c_str(), type.size(),
2003                            package.c_str(), package.size());
2004     if (rid != 0) {
2005         return true;
2006     }
2007 
2008     sp<Package> p = mPackages.valueFor(package);
2009     if (p != NULL) {
2010         sp<Type> t = p->getTypes().valueFor(type);
2011         if (t != NULL) {
2012             sp<ConfigList> c =  t->getConfigs().valueFor(name);
2013             if (c != NULL) return true;
2014         }
2015     }
2016 
2017     return false;
2018 }
2019 
hasBagOrEntry(const String16 & package,const String16 & type,const String16 & name,const ResTable_config & config) const2020 bool ResourceTable::hasBagOrEntry(const String16& package,
2021                                   const String16& type,
2022                                   const String16& name,
2023                                   const ResTable_config& config) const
2024 {
2025     // First look for this in the included resources...
2026     uint32_t rid = mAssets->getIncludedResources()
2027         .identifierForName(name.c_str(), name.size(),
2028                            type.c_str(), type.size(),
2029                            package.c_str(), package.size());
2030     if (rid != 0) {
2031         return true;
2032     }
2033 
2034     sp<Package> p = mPackages.valueFor(package);
2035     if (p != NULL) {
2036         sp<Type> t = p->getTypes().valueFor(type);
2037         if (t != NULL) {
2038             sp<ConfigList> c =  t->getConfigs().valueFor(name);
2039             if (c != NULL) {
2040                 sp<Entry> e = c->getEntries().valueFor(config);
2041                 if (e != NULL) {
2042                     return true;
2043                 }
2044             }
2045         }
2046     }
2047 
2048     return false;
2049 }
2050 
hasBagOrEntry(const String16 & ref,const String16 * defType,const String16 * defPackage)2051 bool ResourceTable::hasBagOrEntry(const String16& ref,
2052                                   const String16* defType,
2053                                   const String16* defPackage)
2054 {
2055     String16 package, type, name;
2056     if (!ResTable::expandResourceRef(ref.c_str(), ref.size(), &package, &type, &name,
2057                 defType, defPackage ? defPackage:&mAssetsPackage, NULL)) {
2058         return false;
2059     }
2060     return hasBagOrEntry(package, type, name);
2061 }
2062 
appendComment(const String16 & package,const String16 & type,const String16 & name,const String16 & comment,bool onlyIfEmpty)2063 bool ResourceTable::appendComment(const String16& package,
2064                                   const String16& type,
2065                                   const String16& name,
2066                                   const String16& comment,
2067                                   bool onlyIfEmpty)
2068 {
2069     if (comment.size() <= 0) {
2070         return true;
2071     }
2072 
2073     sp<Package> p = mPackages.valueFor(package);
2074     if (p != NULL) {
2075         sp<Type> t = p->getTypes().valueFor(type);
2076         if (t != NULL) {
2077             sp<ConfigList> c =  t->getConfigs().valueFor(name);
2078             if (c != NULL) {
2079                 c->appendComment(comment, onlyIfEmpty);
2080                 return true;
2081             }
2082         }
2083     }
2084     return false;
2085 }
2086 
appendTypeComment(const String16 & package,const String16 & type,const String16 & name,const String16 & comment)2087 bool ResourceTable::appendTypeComment(const String16& package,
2088                                       const String16& type,
2089                                       const String16& name,
2090                                       const String16& comment)
2091 {
2092     if (comment.size() <= 0) {
2093         return true;
2094     }
2095 
2096     sp<Package> p = mPackages.valueFor(package);
2097     if (p != NULL) {
2098         sp<Type> t = p->getTypes().valueFor(type);
2099         if (t != NULL) {
2100             sp<ConfigList> c =  t->getConfigs().valueFor(name);
2101             if (c != NULL) {
2102                 c->appendTypeComment(comment);
2103                 return true;
2104             }
2105         }
2106     }
2107     return false;
2108 }
2109 
makeAttribute(const String16 & package,const String16 & name,const SourcePos & source,int32_t format,const String16 & comment,bool shouldAppendComment)2110 bool ResourceTable::makeAttribute(const String16& package,
2111                                   const String16& name,
2112                                   const SourcePos& source,
2113                                   int32_t format,
2114                                   const String16& comment,
2115                                   bool shouldAppendComment) {
2116     const String16 attr16("attr");
2117 
2118     // First look for this in the included resources...
2119     uint32_t rid = mAssets->getIncludedResources()
2120             .identifierForName(name.c_str(), name.size(),
2121                                attr16.c_str(), attr16.size(),
2122                                package.c_str(), package.size());
2123     if (rid != 0) {
2124         source.error("Attribute \"%s\" has already been defined", String8(name).c_str());
2125         return false;
2126     }
2127 
2128     sp<ResourceTable::Entry> entry = getEntry(package, attr16, name, source, false);
2129     if (entry == NULL) {
2130         source.error("Failed to create entry attr/%s", String8(name).c_str());
2131         return false;
2132     }
2133 
2134     if (entry->makeItABag(source) != NO_ERROR) {
2135         return false;
2136     }
2137 
2138     const String16 formatKey16("^type");
2139     const String16 formatValue16(String8::format("%d", format));
2140 
2141     ssize_t idx = entry->getBag().indexOfKey(formatKey16);
2142     if (idx >= 0) {
2143         // We have already set a format for this attribute, check if they are different.
2144         // We allow duplicate attribute definitions so long as they are identical.
2145         // This is to ensure inter-operation with libraries that define the same generic attribute.
2146         const Item& formatItem = entry->getBag().valueAt(idx);
2147         if ((format & (ResTable_map::TYPE_ENUM | ResTable_map::TYPE_FLAGS)) ||
2148                 formatItem.value != formatValue16) {
2149             source.error("Attribute \"%s\" already defined with incompatible format.\n"
2150                          "%s:%d: Original attribute defined here.",
2151                          String8(name).c_str(), formatItem.sourcePos.file.c_str(),
2152                          formatItem.sourcePos.line);
2153             return false;
2154         }
2155     } else {
2156         entry->addToBag(source, formatKey16, formatValue16);
2157         // Increment the number of resources we have. This is used to determine if we should
2158         // even generate a resource table.
2159         mNumLocal++;
2160     }
2161     appendComment(package, attr16, name, comment, shouldAppendComment);
2162     return true;
2163 }
2164 
canAddEntry(const SourcePos & pos,const String16 & package,const String16 & type,const String16 & name)2165 void ResourceTable::canAddEntry(const SourcePos& pos,
2166         const String16& package, const String16& type, const String16& name)
2167 {
2168     sp<Type> t = getType(package, type, pos);
2169     if (t != NULL) {
2170         t->canAddEntry(name);
2171     }
2172 }
2173 
size() const2174 size_t ResourceTable::size() const {
2175     return mPackages.size();
2176 }
2177 
numLocalResources() const2178 size_t ResourceTable::numLocalResources() const {
2179     return mNumLocal;
2180 }
2181 
hasResources() const2182 bool ResourceTable::hasResources() const {
2183     return mNumLocal > 0;
2184 }
2185 
flatten(Bundle * bundle,const sp<const ResourceFilter> & filter,const bool isBase)2186 sp<AaptFile> ResourceTable::flatten(Bundle* bundle, const sp<const ResourceFilter>& filter,
2187         const bool isBase)
2188 {
2189     sp<AaptFile> data = new AaptFile(String8(), AaptGroupEntry(), String8());
2190     status_t err = flatten(bundle, filter, data, isBase);
2191     return err == NO_ERROR ? data : NULL;
2192 }
2193 
getResId(const sp<Package> & p,const sp<Type> & t,uint32_t nameId)2194 inline uint32_t ResourceTable::getResId(const sp<Package>& p,
2195                                         const sp<Type>& t,
2196                                         uint32_t nameId)
2197 {
2198     return makeResId(p->getAssignedId(), t->getIndex(), nameId);
2199 }
2200 
getResId(const String16 & package,const String16 & type,const String16 & name,bool onlyPublic) const2201 uint32_t ResourceTable::getResId(const String16& package,
2202                                  const String16& type,
2203                                  const String16& name,
2204                                  bool onlyPublic) const
2205 {
2206     uint32_t id = ResourceIdCache::lookup(package, type, name, onlyPublic);
2207     if (id != 0) return id;     // cache hit
2208 
2209     // First look for this in the included resources...
2210     uint32_t specFlags = 0;
2211     uint32_t rid = mAssets->getIncludedResources()
2212         .identifierForName(name.c_str(), name.size(),
2213                            type.c_str(), type.size(),
2214                            package.c_str(), package.size(),
2215                            &specFlags);
2216     if (rid != 0) {
2217         if (onlyPublic && (specFlags & ResTable_typeSpec::SPEC_PUBLIC) == 0) {
2218             // If this is a feature split and the resource has the same
2219             // package name as us, then everything is public.
2220             if (mPackageType != AppFeature || mAssetsPackage != package) {
2221                 return 0;
2222             }
2223         }
2224 
2225         return ResourceIdCache::store(package, type, name, onlyPublic, rid);
2226     }
2227 
2228     sp<Package> p = mPackages.valueFor(package);
2229     if (p == NULL) return 0;
2230     sp<Type> t = p->getTypes().valueFor(type);
2231     if (t == NULL) return 0;
2232     sp<ConfigList> c = t->getConfigs().valueFor(name);
2233     if (c == NULL) {
2234         if (type != String16("attr")) {
2235             return 0;
2236         }
2237         t = p->getTypes().valueFor(String16(kAttrPrivateType));
2238         if (t == NULL) return 0;
2239         c = t->getConfigs().valueFor(name);
2240         if (c == NULL) return 0;
2241     }
2242     int32_t ei = c->getEntryIndex();
2243     if (ei < 0) return 0;
2244 
2245     return ResourceIdCache::store(package, type, name, onlyPublic,
2246             getResId(p, t, ei));
2247 }
2248 
getResId(const String16 & ref,const String16 * defType,const String16 * defPackage,const char ** outErrorMsg,bool onlyPublic) const2249 uint32_t ResourceTable::getResId(const String16& ref,
2250                                  const String16* defType,
2251                                  const String16* defPackage,
2252                                  const char** outErrorMsg,
2253                                  bool onlyPublic) const
2254 {
2255     String16 package, type, name;
2256     bool refOnlyPublic = true;
2257     if (!ResTable::expandResourceRef(
2258         ref.c_str(), ref.size(), &package, &type, &name,
2259         defType, defPackage ? defPackage:&mAssetsPackage,
2260         outErrorMsg, &refOnlyPublic)) {
2261         if (kIsDebug) {
2262             printf("Expanding resource: ref=%s\n", String8(ref).c_str());
2263             printf("Expanding resource: defType=%s\n",
2264                     defType ? String8(*defType).c_str() : "NULL");
2265             printf("Expanding resource: defPackage=%s\n",
2266                     defPackage ? String8(*defPackage).c_str() : "NULL");
2267             printf("Expanding resource: ref=%s\n", String8(ref).c_str());
2268             printf("Expanded resource: p=%s, t=%s, n=%s, res=0\n",
2269                     String8(package).c_str(), String8(type).c_str(),
2270                     String8(name).c_str());
2271         }
2272         return 0;
2273     }
2274     uint32_t res = getResId(package, type, name, onlyPublic && refOnlyPublic);
2275     if (kIsDebug) {
2276         printf("Expanded resource: p=%s, t=%s, n=%s, res=%d\n",
2277                 String8(package).c_str(), String8(type).c_str(),
2278                 String8(name).c_str(), res);
2279     }
2280     if (res == 0) {
2281         if (outErrorMsg)
2282             *outErrorMsg = "No resource found that matches the given name";
2283     }
2284     return res;
2285 }
2286 
isValidResourceName(const String16 & s)2287 bool ResourceTable::isValidResourceName(const String16& s)
2288 {
2289     const char16_t* p = s.c_str();
2290     bool first = true;
2291     while (*p) {
2292         if ((*p >= 'a' && *p <= 'z')
2293             || (*p >= 'A' && *p <= 'Z')
2294             || *p == '_'
2295             || (!first && *p >= '0' && *p <= '9')) {
2296             first = false;
2297             p++;
2298             continue;
2299         }
2300         return false;
2301     }
2302     return true;
2303 }
2304 
stringToValue(Res_value * outValue,StringPool * pool,const String16 & str,bool preserveSpaces,bool coerceType,uint32_t attrID,const Vector<StringPool::entry_style_span> * style,String16 * outStr,void * accessorCookie,uint32_t attrType,const String8 * configTypeName,const ConfigDescription * config)2305 bool ResourceTable::stringToValue(Res_value* outValue, StringPool* pool,
2306                                   const String16& str,
2307                                   bool preserveSpaces, bool coerceType,
2308                                   uint32_t attrID,
2309                                   const Vector<StringPool::entry_style_span>* style,
2310                                   String16* outStr, void* accessorCookie,
2311                                   uint32_t attrType, const String8* configTypeName,
2312                                   const ConfigDescription* config)
2313 {
2314     String16 finalStr;
2315 
2316     bool res = true;
2317     if (style == NULL || style->size() == 0) {
2318         // Text is not styled so it can be any type...  let's figure it out.
2319         res = mAssets->getIncludedResources()
2320             .stringToValue(outValue, &finalStr, str.c_str(), str.size(), preserveSpaces,
2321                             coerceType, attrID, NULL, &mAssetsPackage, this,
2322                            accessorCookie, attrType);
2323     } else {
2324         // Styled text can only be a string, and while collecting the style
2325         // information we have already processed that string!
2326         outValue->size = sizeof(Res_value);
2327         outValue->res0 = 0;
2328         outValue->dataType = outValue->TYPE_STRING;
2329         outValue->data = 0;
2330         finalStr = str;
2331     }
2332 
2333     if (!res) {
2334         return false;
2335     }
2336 
2337     if (outValue->dataType == outValue->TYPE_STRING) {
2338         // Should do better merging styles.
2339         if (pool) {
2340             String8 configStr;
2341             if (config != NULL) {
2342                 configStr = config->toString();
2343             } else {
2344                 configStr = "(null)";
2345             }
2346             if (kIsDebug) {
2347                 printf("Adding to pool string style #%zu config %s: %s\n",
2348                         style != NULL ? style->size() : 0U,
2349                         configStr.c_str(), String8(finalStr).c_str());
2350             }
2351             if (style != NULL && style->size() > 0) {
2352                 outValue->data = pool->add(finalStr, *style, configTypeName, config);
2353             } else {
2354                 outValue->data = pool->add(finalStr, true, configTypeName, config);
2355             }
2356         } else {
2357             // Caller will fill this in later.
2358             outValue->data = 0;
2359         }
2360 
2361         if (outStr) {
2362             *outStr = finalStr;
2363         }
2364 
2365     }
2366 
2367     return true;
2368 }
2369 
getCustomResource(const String16 & package,const String16 & type,const String16 & name) const2370 uint32_t ResourceTable::getCustomResource(
2371     const String16& package, const String16& type, const String16& name) const
2372 {
2373     //printf("getCustomResource: %s %s %s\n", String8(package).c_str(),
2374     //       String8(type).c_str(), String8(name).c_str());
2375     sp<Package> p = mPackages.valueFor(package);
2376     if (p == NULL) return 0;
2377     sp<Type> t = p->getTypes().valueFor(type);
2378     if (t == NULL) return 0;
2379     sp<ConfigList> c =  t->getConfigs().valueFor(name);
2380     if (c == NULL) {
2381         if (type != String16("attr")) {
2382             return 0;
2383         }
2384         t = p->getTypes().valueFor(String16(kAttrPrivateType));
2385         if (t == NULL) return 0;
2386         c = t->getConfigs().valueFor(name);
2387         if (c == NULL) return 0;
2388     }
2389     int32_t ei = c->getEntryIndex();
2390     if (ei < 0) return 0;
2391     return getResId(p, t, ei);
2392 }
2393 
getCustomResourceWithCreation(const String16 & package,const String16 & type,const String16 & name,const bool createIfNotFound)2394 uint32_t ResourceTable::getCustomResourceWithCreation(
2395         const String16& package, const String16& type, const String16& name,
2396         const bool createIfNotFound)
2397 {
2398     uint32_t resId = getCustomResource(package, type, name);
2399     if (resId != 0 || !createIfNotFound) {
2400         return resId;
2401     }
2402 
2403     if (mAssetsPackage != package) {
2404         mCurrentXmlPos.error("creating resource for external package %s: %s/%s.",
2405                 String8(package).c_str(), String8(type).c_str(), String8(name).c_str());
2406         if (package == String16("android")) {
2407             mCurrentXmlPos.printf("did you mean to use @+id instead of @+android:id?");
2408         }
2409         return 0;
2410     }
2411 
2412     String16 value("false");
2413     status_t status = addEntry(mCurrentXmlPos, package, type, name, value, NULL, NULL, true);
2414     if (status == NO_ERROR) {
2415         resId = getResId(package, type, name);
2416         return resId;
2417     }
2418     return 0;
2419 }
2420 
getRemappedPackage(uint32_t origPackage) const2421 uint32_t ResourceTable::getRemappedPackage(uint32_t origPackage) const
2422 {
2423     return origPackage;
2424 }
2425 
getAttributeType(uint32_t attrID,uint32_t * outType)2426 bool ResourceTable::getAttributeType(uint32_t attrID, uint32_t* outType)
2427 {
2428     //printf("getAttributeType #%08x\n", attrID);
2429     Res_value value;
2430     if (getItemValue(attrID, ResTable_map::ATTR_TYPE, &value)) {
2431         //printf("getAttributeType #%08x (%s): #%08x\n", attrID,
2432         //       String8(getEntry(attrID)->getName()).c_str(), value.data);
2433         *outType = value.data;
2434         return true;
2435     }
2436     return false;
2437 }
2438 
getAttributeMin(uint32_t attrID,uint32_t * outMin)2439 bool ResourceTable::getAttributeMin(uint32_t attrID, uint32_t* outMin)
2440 {
2441     //printf("getAttributeMin #%08x\n", attrID);
2442     Res_value value;
2443     if (getItemValue(attrID, ResTable_map::ATTR_MIN, &value)) {
2444         *outMin = value.data;
2445         return true;
2446     }
2447     return false;
2448 }
2449 
getAttributeMax(uint32_t attrID,uint32_t * outMax)2450 bool ResourceTable::getAttributeMax(uint32_t attrID, uint32_t* outMax)
2451 {
2452     //printf("getAttributeMax #%08x\n", attrID);
2453     Res_value value;
2454     if (getItemValue(attrID, ResTable_map::ATTR_MAX, &value)) {
2455         *outMax = value.data;
2456         return true;
2457     }
2458     return false;
2459 }
2460 
getAttributeL10N(uint32_t attrID)2461 uint32_t ResourceTable::getAttributeL10N(uint32_t attrID)
2462 {
2463     //printf("getAttributeL10N #%08x\n", attrID);
2464     Res_value value;
2465     if (getItemValue(attrID, ResTable_map::ATTR_L10N, &value)) {
2466         return value.data;
2467     }
2468     return ResTable_map::L10N_NOT_REQUIRED;
2469 }
2470 
getLocalizationSetting()2471 bool ResourceTable::getLocalizationSetting()
2472 {
2473     return mBundle->getRequireLocalization();
2474 }
2475 
reportError(void * accessorCookie,const char * fmt,...)2476 void ResourceTable::reportError(void* accessorCookie, const char* fmt, ...)
2477 {
2478     if (accessorCookie != NULL && fmt != NULL) {
2479         AccessorCookie* ac = (AccessorCookie*)accessorCookie;
2480         char buf[1024];
2481         va_list ap;
2482         va_start(ap, fmt);
2483         vsnprintf(buf, sizeof(buf), fmt, ap);
2484         va_end(ap);
2485         ac->sourcePos.error("Error: %s (at '%s' with value '%s').\n",
2486                             buf, ac->attr.c_str(), ac->value.c_str());
2487     }
2488 }
2489 
getAttributeKeys(uint32_t attrID,Vector<String16> * outKeys)2490 bool ResourceTable::getAttributeKeys(
2491     uint32_t attrID, Vector<String16>* outKeys)
2492 {
2493     sp<const Entry> e = getEntry(attrID);
2494     if (e != NULL) {
2495         const size_t N = e->getBag().size();
2496         for (size_t i=0; i<N; i++) {
2497             const String16& key = e->getBag().keyAt(i);
2498             if (key.size() > 0 && key.c_str()[0] != '^') {
2499                 outKeys->add(key);
2500             }
2501         }
2502         return true;
2503     }
2504     return false;
2505 }
2506 
getAttributeEnum(uint32_t attrID,const char16_t * name,size_t nameLen,Res_value * outValue)2507 bool ResourceTable::getAttributeEnum(
2508     uint32_t attrID, const char16_t* name, size_t nameLen,
2509     Res_value* outValue)
2510 {
2511     //printf("getAttributeEnum #%08x %s\n", attrID, String8(name, nameLen).c_str());
2512     String16 nameStr(name, nameLen);
2513     sp<const Entry> e = getEntry(attrID);
2514     if (e != NULL) {
2515         const size_t N = e->getBag().size();
2516         for (size_t i=0; i<N; i++) {
2517             //printf("Comparing %s to %s\n", String8(name, nameLen).c_str(),
2518             //       String8(e->getBag().keyAt(i)).c_str());
2519             if (e->getBag().keyAt(i) == nameStr) {
2520                 return getItemValue(attrID, e->getBag().valueAt(i).bagKeyId, outValue);
2521             }
2522         }
2523     }
2524     return false;
2525 }
2526 
getAttributeFlags(uint32_t attrID,const char16_t * name,size_t nameLen,Res_value * outValue)2527 bool ResourceTable::getAttributeFlags(
2528     uint32_t attrID, const char16_t* name, size_t nameLen,
2529     Res_value* outValue)
2530 {
2531     outValue->dataType = Res_value::TYPE_INT_HEX;
2532     outValue->data = 0;
2533 
2534     //printf("getAttributeFlags #%08x %s\n", attrID, String8(name, nameLen).c_str());
2535     String16 nameStr(name, nameLen);
2536     sp<const Entry> e = getEntry(attrID);
2537     if (e != NULL) {
2538         const size_t N = e->getBag().size();
2539 
2540         const char16_t* end = name + nameLen;
2541         const char16_t* pos = name;
2542         while (pos < end) {
2543             const char16_t* start = pos;
2544             while (pos < end && *pos != '|') {
2545                 pos++;
2546             }
2547 
2548             String16 nameStr(start, pos-start);
2549             size_t i;
2550             for (i=0; i<N; i++) {
2551                 //printf("Comparing \"%s\" to \"%s\"\n", String8(nameStr).c_str(),
2552                 //       String8(e->getBag().keyAt(i)).c_str());
2553                 if (e->getBag().keyAt(i) == nameStr) {
2554                     Res_value val;
2555                     bool got = getItemValue(attrID, e->getBag().valueAt(i).bagKeyId, &val);
2556                     if (!got) {
2557                         return false;
2558                     }
2559                     //printf("Got value: 0x%08x\n", val.data);
2560                     outValue->data |= val.data;
2561                     break;
2562                 }
2563             }
2564 
2565             if (i >= N) {
2566                 // Didn't find this flag identifier.
2567                 return false;
2568             }
2569             pos++;
2570         }
2571 
2572         return true;
2573     }
2574     return false;
2575 }
2576 
assignResourceIds()2577 status_t ResourceTable::assignResourceIds()
2578 {
2579     const size_t N = mOrderedPackages.size();
2580     size_t pi;
2581     status_t firstError = NO_ERROR;
2582 
2583     // First generate all bag attributes and assign indices.
2584     for (pi=0; pi<N; pi++) {
2585         sp<Package> p = mOrderedPackages.itemAt(pi);
2586         if (p == NULL || p->getTypes().size() == 0) {
2587             // Empty, skip!
2588             continue;
2589         }
2590 
2591         if (mPackageType == System) {
2592             p->movePrivateAttrs();
2593         }
2594 
2595         // This has no sense for packages being built as AppFeature (aka with a non-zero offset).
2596         status_t err = p->applyPublicTypeOrder();
2597         if (err != NO_ERROR && firstError == NO_ERROR) {
2598             firstError = err;
2599         }
2600 
2601         // Generate attributes...
2602         const size_t N = p->getOrderedTypes().size();
2603         size_t ti;
2604         for (ti=0; ti<N; ti++) {
2605             sp<Type> t = p->getOrderedTypes().itemAt(ti);
2606             if (t == NULL) {
2607                 continue;
2608             }
2609             const size_t N = t->getOrderedConfigs().size();
2610             for (size_t ci=0; ci<N; ci++) {
2611                 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2612                 if (c == NULL) {
2613                     continue;
2614                 }
2615                 const size_t N = c->getEntries().size();
2616                 for (size_t ei=0; ei<N; ei++) {
2617                     sp<Entry> e = c->getEntries().valueAt(ei);
2618                     if (e == NULL) {
2619                         continue;
2620                     }
2621                     status_t err = e->generateAttributes(this, p->getName());
2622                     if (err != NO_ERROR && firstError == NO_ERROR) {
2623                         firstError = err;
2624                     }
2625                 }
2626             }
2627         }
2628 
2629         uint32_t typeIdOffset = 0;
2630         if (mPackageType == AppFeature && p->getName() == mAssetsPackage) {
2631             typeIdOffset = mTypeIdOffset;
2632         }
2633 
2634         const SourcePos unknown(String8("????"), 0);
2635         sp<Type> attr = p->getType(String16("attr"), unknown);
2636 
2637         // Force creation of ID if we are building feature splits.
2638         // Auto-generated ID resources won't apply the type ID offset correctly unless
2639         // the offset is applied here first.
2640         // b/30607637
2641         if (mPackageType == AppFeature && p->getName() == mAssetsPackage) {
2642             sp<Type> id = p->getType(String16("id"), unknown);
2643         }
2644 
2645         // Assign indices...
2646         const size_t typeCount = p->getOrderedTypes().size();
2647         for (size_t ti = 0; ti < typeCount; ti++) {
2648             sp<Type> t = p->getOrderedTypes().itemAt(ti);
2649             if (t == NULL) {
2650                 continue;
2651             }
2652 
2653             err = t->applyPublicEntryOrder();
2654             if (err != NO_ERROR && firstError == NO_ERROR) {
2655                 firstError = err;
2656             }
2657 
2658             const size_t N = t->getOrderedConfigs().size();
2659             t->setIndex(ti + 1 + typeIdOffset);
2660 
2661             LOG_ALWAYS_FATAL_IF(ti == 0 && attr != t,
2662                                 "First type is not attr!");
2663 
2664             for (size_t ei=0; ei<N; ei++) {
2665                 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ei);
2666                 if (c == NULL) {
2667                     continue;
2668                 }
2669                 c->setEntryIndex(ei);
2670             }
2671         }
2672 
2673 
2674         // Assign resource IDs to keys in bags...
2675         for (size_t ti = 0; ti < typeCount; ti++) {
2676             sp<Type> t = p->getOrderedTypes().itemAt(ti);
2677             if (t == NULL) {
2678                 continue;
2679             }
2680 
2681             const size_t N = t->getOrderedConfigs().size();
2682             for (size_t ci=0; ci<N; ci++) {
2683                 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2684                 if (c == NULL) {
2685                     continue;
2686                 }
2687                 //printf("Ordered config #%d: %p\n", ci, c.get());
2688                 const size_t N = c->getEntries().size();
2689                 for (size_t ei=0; ei<N; ei++) {
2690                     sp<Entry> e = c->getEntries().valueAt(ei);
2691                     if (e == NULL) {
2692                         continue;
2693                     }
2694                     status_t err = e->assignResourceIds(this, p->getName());
2695                     if (err != NO_ERROR && firstError == NO_ERROR) {
2696                         firstError = err;
2697                     }
2698                 }
2699             }
2700         }
2701     }
2702     return firstError;
2703 }
2704 
addSymbols(const sp<AaptSymbols> & outSymbols,bool skipSymbolsWithoutDefaultLocalization)2705 status_t ResourceTable::addSymbols(const sp<AaptSymbols>& outSymbols,
2706         bool skipSymbolsWithoutDefaultLocalization) {
2707     const size_t N = mOrderedPackages.size();
2708     const String8 defaultLocale;
2709     const String16 stringType("string");
2710     size_t pi;
2711 
2712     for (pi=0; pi<N; pi++) {
2713         sp<Package> p = mOrderedPackages.itemAt(pi);
2714         if (p->getTypes().size() == 0) {
2715             // Empty, skip!
2716             continue;
2717         }
2718 
2719         const size_t N = p->getOrderedTypes().size();
2720         size_t ti;
2721 
2722         for (ti=0; ti<N; ti++) {
2723             sp<Type> t = p->getOrderedTypes().itemAt(ti);
2724             if (t == NULL) {
2725                 continue;
2726             }
2727 
2728             const size_t N = t->getOrderedConfigs().size();
2729             sp<AaptSymbols> typeSymbols;
2730             if (t->getName() == String16(kAttrPrivateType)) {
2731                 typeSymbols = outSymbols->addNestedSymbol(String8("attr"), t->getPos());
2732             } else {
2733                 typeSymbols = outSymbols->addNestedSymbol(String8(t->getName()), t->getPos());
2734             }
2735 
2736             if (typeSymbols == NULL) {
2737                 return UNKNOWN_ERROR;
2738             }
2739 
2740             for (size_t ci=0; ci<N; ci++) {
2741                 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2742                 if (c == NULL) {
2743                     continue;
2744                 }
2745                 uint32_t rid = getResId(p, t, ci);
2746                 if (rid == 0) {
2747                     return UNKNOWN_ERROR;
2748                 }
2749                 if (Res_GETPACKAGE(rid) + 1 == p->getAssignedId()) {
2750 
2751                     if (skipSymbolsWithoutDefaultLocalization &&
2752                             t->getName() == stringType) {
2753 
2754                         // Don't generate symbols for strings without a default localization.
2755                         if (mHasDefaultLocalization.find(c->getName())
2756                                 == mHasDefaultLocalization.end()) {
2757                             // printf("Skip symbol [%08x] %s\n", rid,
2758                             //          String8(c->getName()).c_str());
2759                             continue;
2760                         }
2761                     }
2762 
2763                     typeSymbols->addSymbol(String8(c->getName()), rid, c->getPos());
2764 
2765                     String16 comment(c->getComment());
2766                     typeSymbols->appendComment(String8(c->getName()), comment, c->getPos());
2767                     //printf("Type symbol [%08x] %s comment: %s\n", rid,
2768                     //        String8(c->getName()).c_str(), String8(comment).c_str());
2769                     comment = c->getTypeComment();
2770                     typeSymbols->appendTypeComment(String8(c->getName()), comment);
2771                 }
2772             }
2773         }
2774     }
2775     return NO_ERROR;
2776 }
2777 
2778 
2779 void
addLocalization(const String16 & name,const String8 & locale,const SourcePos & src)2780 ResourceTable::addLocalization(const String16& name, const String8& locale, const SourcePos& src)
2781 {
2782     mLocalizations[name][locale] = src;
2783 }
2784 
2785 void
addDefaultLocalization(const String16 & name)2786 ResourceTable::addDefaultLocalization(const String16& name)
2787 {
2788     mHasDefaultLocalization.insert(name);
2789 }
2790 
2791 
2792 /*!
2793  * Flag various sorts of localization problems.  '+' indicates checks already implemented;
2794  * '-' indicates checks that will be implemented in the future.
2795  *
2796  * + A localized string for which no default-locale version exists => warning
2797  * + A string for which no version in an explicitly-requested locale exists => warning
2798  * + A localized translation of an translateable="false" string => warning
2799  * - A localized string not provided in every locale used by the table
2800  */
2801 status_t
validateLocalizations(void)2802 ResourceTable::validateLocalizations(void)
2803 {
2804     status_t err = NO_ERROR;
2805     const String8 defaultLocale;
2806 
2807     // For all strings...
2808     for (const auto& nameIter : mLocalizations) {
2809         const std::map<String8, SourcePos>& configSrcMap = nameIter.second;
2810 
2811         // Look for strings with no default localization
2812         if (configSrcMap.count(defaultLocale) == 0) {
2813             SourcePos().warning("string '%s' has no default translation.",
2814                     String8(nameIter.first).c_str());
2815             if (mBundle->getVerbose()) {
2816                 for (const auto& locale : configSrcMap) {
2817                     locale.second.printf("locale %s found", locale.first.c_str());
2818                 }
2819             }
2820             // !!! TODO: throw an error here in some circumstances
2821         }
2822 
2823         // Check that all requested localizations are present for this string
2824         if (mBundle->getConfigurations().size() > 0 && mBundle->getRequireLocalization()) {
2825             const char* allConfigs = mBundle->getConfigurations().c_str();
2826             const char* start = allConfigs;
2827             const char* comma;
2828 
2829             std::set<String8> missingConfigs;
2830             AaptLocaleValue locale;
2831             do {
2832                 String8 config;
2833                 comma = strchr(start, ',');
2834                 if (comma != NULL) {
2835                     config = String8(start, comma - start);
2836                     start = comma + 1;
2837                 } else {
2838                     config = start;
2839                 }
2840 
2841                 if (!locale.initFromFilterString(config)) {
2842                     continue;
2843                 }
2844 
2845                 // don't bother with the pseudolocale "en_XA" or "ar_XB"
2846                 if (config != "en_XA" && config != "ar_XB") {
2847                     if (configSrcMap.find(config) == configSrcMap.end()) {
2848                         // okay, no specific localization found.  it's possible that we are
2849                         // requiring a specific regional localization [e.g. de_DE] but there is an
2850                         // available string in the generic language localization [e.g. de];
2851                         // consider that string to have fulfilled the localization requirement.
2852                         String8 region(config.c_str(), 2);
2853                         if (configSrcMap.find(region) == configSrcMap.end() &&
2854                                 configSrcMap.count(defaultLocale) == 0) {
2855                             missingConfigs.insert(config);
2856                         }
2857                     }
2858                 }
2859             } while (comma != NULL);
2860 
2861             if (!missingConfigs.empty()) {
2862                 String8 configStr;
2863                 for (const auto& iter : missingConfigs) {
2864                     configStr.appendFormat(" %s", iter.c_str());
2865                 }
2866                 SourcePos().warning("string '%s' is missing %u required localizations:%s",
2867                         String8(nameIter.first).c_str(),
2868                         (unsigned int)missingConfigs.size(),
2869                         configStr.c_str());
2870             }
2871         }
2872     }
2873 
2874     return err;
2875 }
2876 
flatten(Bundle * bundle,const sp<const ResourceFilter> & filter,const sp<AaptFile> & dest,const bool isBase)2877 status_t ResourceTable::flatten(Bundle* bundle, const sp<const ResourceFilter>& filter,
2878         const sp<AaptFile>& dest,
2879         const bool isBase)
2880 {
2881     const ConfigDescription nullConfig;
2882 
2883     const size_t N = mOrderedPackages.size();
2884     size_t pi;
2885 
2886     const static String16 mipmap16("mipmap");
2887 
2888     bool useUTF8 = !bundle->getUTF16StringsOption();
2889 
2890     // The libraries this table references.
2891     Vector<sp<Package> > libraryPackages;
2892     const ResTable& table = mAssets->getIncludedResources();
2893     const size_t basePackageCount = table.getBasePackageCount();
2894     for (size_t i = 0; i < basePackageCount; i++) {
2895         size_t packageId = table.getBasePackageId(i);
2896         String16 packageName(table.getBasePackageName(i));
2897         if (packageId > 0x01 && packageId != 0x7f &&
2898                 packageName != String16("android")) {
2899             libraryPackages.add(sp<Package>(new Package(packageName, packageId)));
2900         }
2901     }
2902 
2903     // Iterate through all data, collecting all values (strings,
2904     // references, etc).
2905     StringPool valueStrings(useUTF8);
2906     Vector<sp<Entry> > allEntries;
2907     for (pi=0; pi<N; pi++) {
2908         sp<Package> p = mOrderedPackages.itemAt(pi);
2909         if (p->getTypes().size() == 0) {
2910             continue;
2911         }
2912 
2913         StringPool typeStrings(useUTF8);
2914         StringPool keyStrings(useUTF8);
2915 
2916         ssize_t stringsAdded = 0;
2917         const size_t N = p->getOrderedTypes().size();
2918         for (size_t ti=0; ti<N; ti++) {
2919             sp<Type> t = p->getOrderedTypes().itemAt(ti);
2920             if (t == NULL) {
2921                 typeStrings.add(String16("<empty>"), false);
2922                 stringsAdded++;
2923                 continue;
2924             }
2925 
2926             while (stringsAdded < t->getIndex() - 1) {
2927                 typeStrings.add(String16("<empty>"), false);
2928                 stringsAdded++;
2929             }
2930 
2931             const String16 typeName(t->getName());
2932             typeStrings.add(typeName, false);
2933             stringsAdded++;
2934 
2935             // This is a hack to tweak the sorting order of the final strings,
2936             // to put stuff that is generally not language-specific first.
2937             String8 configTypeName(typeName);
2938             if (configTypeName == "drawable" || configTypeName == "layout"
2939                     || configTypeName == "color" || configTypeName == "anim"
2940                     || configTypeName == "interpolator" || configTypeName == "animator"
2941                     || configTypeName == "xml" || configTypeName == "menu"
2942                     || configTypeName == "mipmap" || configTypeName == "raw") {
2943                 configTypeName = "1complex";
2944             } else {
2945                 configTypeName = "2value";
2946             }
2947 
2948             // mipmaps don't get filtered, so they will
2949             // allways end up in the base. Make sure they
2950             // don't end up in a split.
2951             if (typeName == mipmap16 && !isBase) {
2952                 continue;
2953             }
2954 
2955             const bool filterable = (typeName != mipmap16);
2956 
2957             const size_t N = t->getOrderedConfigs().size();
2958             for (size_t ci=0; ci<N; ci++) {
2959                 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2960                 if (c == NULL) {
2961                     continue;
2962                 }
2963                 const size_t N = c->getEntries().size();
2964                 for (size_t ei=0; ei<N; ei++) {
2965                     ConfigDescription config = c->getEntries().keyAt(ei);
2966                     if (filterable && !filter->match(config)) {
2967                         continue;
2968                     }
2969                     sp<Entry> e = c->getEntries().valueAt(ei);
2970                     if (e == NULL) {
2971                         continue;
2972                     }
2973                     e->setNameIndex(keyStrings.add(e->getName(), true));
2974 
2975                     status_t err = e->prepareFlatten(&valueStrings, this,
2976                             &configTypeName, &config);
2977                     if (err != NO_ERROR) {
2978                         return err;
2979                     }
2980                     allEntries.add(e);
2981                 }
2982             }
2983         }
2984 
2985         p->setTypeStrings(typeStrings.createStringBlock());
2986         p->setKeyStrings(keyStrings.createStringBlock());
2987     }
2988 
2989     if (bundle->getOutputAPKFile() != NULL) {
2990         // Now we want to sort the value strings for better locality.  This will
2991         // cause the positions of the strings to change, so we need to go back
2992         // through out resource entries and update them accordingly.  Only need
2993         // to do this if actually writing the output file.
2994         valueStrings.sortByConfig();
2995         for (pi=0; pi<allEntries.size(); pi++) {
2996             allEntries[pi]->remapStringValue(&valueStrings);
2997         }
2998     }
2999 
3000     ssize_t strAmt = 0;
3001 
3002     // Now build the array of package chunks.
3003     Vector<sp<AaptFile> > flatPackages;
3004     for (pi=0; pi<N; pi++) {
3005         sp<Package> p = mOrderedPackages.itemAt(pi);
3006         if (p->getTypes().size() == 0) {
3007             // Empty, skip!
3008             continue;
3009         }
3010 
3011         const size_t N = p->getTypeStrings().size();
3012 
3013         const size_t baseSize = sizeof(ResTable_package);
3014 
3015         // Start the package data.
3016         sp<AaptFile> data = new AaptFile(String8(), AaptGroupEntry(), String8());
3017         ResTable_package* header = (ResTable_package*)data->editData(baseSize);
3018         if (header == NULL) {
3019             fprintf(stderr, "ERROR: out of memory creating ResTable_package\n");
3020             return NO_MEMORY;
3021         }
3022         memset(header, 0, sizeof(*header));
3023         header->header.type = htods(RES_TABLE_PACKAGE_TYPE);
3024         header->header.headerSize = htods(sizeof(*header));
3025         header->id = htodl(static_cast<uint32_t>(p->getAssignedId()));
3026         strcpy16_htod(header->name, p->getName().c_str());
3027 
3028         // Write the string blocks.
3029         const size_t typeStringsStart = data->getSize();
3030         sp<AaptFile> strFile = p->getTypeStringsData();
3031         ssize_t amt = data->writeData(strFile->getData(), strFile->getSize());
3032         if (kPrintStringMetrics) {
3033             fprintf(stderr, "**** type strings: %zd\n", amt);
3034         }
3035         strAmt += amt;
3036         if (amt < 0) {
3037             return amt;
3038         }
3039         const size_t keyStringsStart = data->getSize();
3040         strFile = p->getKeyStringsData();
3041         amt = data->writeData(strFile->getData(), strFile->getSize());
3042         if (kPrintStringMetrics) {
3043             fprintf(stderr, "**** key strings: %zd\n", amt);
3044         }
3045         strAmt += amt;
3046         if (amt < 0) {
3047             return amt;
3048         }
3049 
3050         if (isBase) {
3051             status_t err = flattenLibraryTable(data, libraryPackages);
3052             if (err != NO_ERROR) {
3053                 fprintf(stderr, "ERROR: failed to write library table\n");
3054                 return err;
3055             }
3056         }
3057 
3058         // Build the type chunks inside of this package.
3059         for (size_t ti=0; ti<N; ti++) {
3060             // Retrieve them in the same order as the type string block.
3061             size_t len;
3062             String16 typeName(UnpackOptionalString(p->getTypeStrings().stringAt(ti), &len));
3063             sp<Type> t = p->getTypes().valueFor(typeName);
3064             LOG_ALWAYS_FATAL_IF(t == NULL && typeName != String16("<empty>"),
3065                                 "Type name %s not found",
3066                                 String8(typeName).c_str());
3067             if (t == NULL) {
3068                 continue;
3069             }
3070             const bool filterable = (typeName != mipmap16);
3071             const bool skipEntireType = (typeName == mipmap16 && !isBase);
3072 
3073             const size_t N = t != NULL ? t->getOrderedConfigs().size() : 0;
3074 
3075             // Until a non-NO_ENTRY value has been written for a resource,
3076             // that resource is invalid; validResources[i] represents
3077             // the item at t->getOrderedConfigs().itemAt(i).
3078             Vector<bool> validResources;
3079             validResources.insertAt(false, 0, N);
3080 
3081             // First write the typeSpec chunk, containing information about
3082             // each resource entry in this type.
3083             {
3084                 const size_t typeSpecSize = sizeof(ResTable_typeSpec) + sizeof(uint32_t)*N;
3085                 const size_t typeSpecStart = data->getSize();
3086                 ResTable_typeSpec* tsHeader = (ResTable_typeSpec*)
3087                     (((uint8_t*)data->editData(typeSpecStart+typeSpecSize)) + typeSpecStart);
3088                 if (tsHeader == NULL) {
3089                     fprintf(stderr, "ERROR: out of memory creating ResTable_typeSpec\n");
3090                     return NO_MEMORY;
3091                 }
3092                 memset(tsHeader, 0, sizeof(*tsHeader));
3093                 tsHeader->header.type = htods(RES_TABLE_TYPE_SPEC_TYPE);
3094                 tsHeader->header.headerSize = htods(sizeof(*tsHeader));
3095                 tsHeader->header.size = htodl(typeSpecSize);
3096                 tsHeader->id = ti+1;
3097                 tsHeader->entryCount = htodl(N);
3098 
3099                 uint32_t* typeSpecFlags = (uint32_t*)
3100                     (((uint8_t*)data->editData())
3101                         + typeSpecStart + sizeof(ResTable_typeSpec));
3102                 memset(typeSpecFlags, 0, sizeof(uint32_t)*N);
3103 
3104                 for (size_t ei=0; ei<N; ei++) {
3105                     sp<ConfigList> cl = t->getOrderedConfigs().itemAt(ei);
3106                     if (cl == NULL) {
3107                         continue;
3108                     }
3109 
3110                     if (cl->getPublic()) {
3111                         typeSpecFlags[ei] |= htodl(ResTable_typeSpec::SPEC_PUBLIC);
3112                     }
3113 
3114                     if (skipEntireType) {
3115                         continue;
3116                     }
3117 
3118                     const size_t CN = cl->getEntries().size();
3119                     for (size_t ci=0; ci<CN; ci++) {
3120                         if (filterable && !filter->match(cl->getEntries().keyAt(ci))) {
3121                             continue;
3122                         }
3123                         for (size_t cj=ci+1; cj<CN; cj++) {
3124                             if (filterable && !filter->match(cl->getEntries().keyAt(cj))) {
3125                                 continue;
3126                             }
3127                             typeSpecFlags[ei] |= htodl(
3128                                 cl->getEntries().keyAt(ci).diff(cl->getEntries().keyAt(cj)));
3129                         }
3130                     }
3131                 }
3132             }
3133 
3134             if (skipEntireType) {
3135                 continue;
3136             }
3137 
3138             // We need to write one type chunk for each configuration for
3139             // which we have entries in this type.
3140             SortedVector<ConfigDescription> uniqueConfigs;
3141             if (t != NULL) {
3142                 uniqueConfigs = t->getUniqueConfigs();
3143             }
3144 
3145             const size_t typeSize = sizeof(ResTable_type) + sizeof(uint32_t)*N;
3146 
3147             const size_t NC = uniqueConfigs.size();
3148             for (size_t ci=0; ci<NC; ci++) {
3149                 const ConfigDescription& config = uniqueConfigs[ci];
3150 
3151                 if (kIsDebug) {
3152                     printf("Writing config %zu config: imsi:%d/%d lang:%c%c cnt:%c%c "
3153                         "orien:%d ui:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d "
3154                         "sw%ddp w%ddp h%ddp layout:%d\n",
3155                         ti + 1,
3156                         config.mcc, config.mnc,
3157                         config.language[0] ? config.language[0] : '-',
3158                         config.language[1] ? config.language[1] : '-',
3159                         config.country[0] ? config.country[0] : '-',
3160                         config.country[1] ? config.country[1] : '-',
3161                         config.orientation,
3162                         config.uiMode,
3163                         config.touchscreen,
3164                         config.density,
3165                         config.keyboard,
3166                         config.inputFlags,
3167                         config.navigation,
3168                         config.screenWidth,
3169                         config.screenHeight,
3170                         config.smallestScreenWidthDp,
3171                         config.screenWidthDp,
3172                         config.screenHeightDp,
3173                         config.screenLayout);
3174                 }
3175 
3176                 if (filterable && !filter->match(config)) {
3177                     continue;
3178                 }
3179 
3180                 const size_t typeStart = data->getSize();
3181 
3182                 ResTable_type* tHeader = (ResTable_type*)
3183                     (((uint8_t*)data->editData(typeStart+typeSize)) + typeStart);
3184                 if (tHeader == NULL) {
3185                     fprintf(stderr, "ERROR: out of memory creating ResTable_type\n");
3186                     return NO_MEMORY;
3187                 }
3188 
3189                 memset(tHeader, 0, sizeof(*tHeader));
3190                 tHeader->header.type = htods(RES_TABLE_TYPE_TYPE);
3191                 tHeader->header.headerSize = htods(sizeof(*tHeader));
3192                 tHeader->id = ti+1;
3193                 tHeader->entryCount = htodl(N);
3194                 tHeader->entriesStart = htodl(typeSize);
3195                 tHeader->config = config;
3196                 if (kIsDebug) {
3197                     printf("Writing type %zu config: imsi:%d/%d lang:%c%c cnt:%c%c "
3198                         "orien:%d ui:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d "
3199                         "sw%ddp w%ddp h%ddp layout:%d\n",
3200                         ti + 1,
3201                         tHeader->config.mcc, tHeader->config.mnc,
3202                         tHeader->config.language[0] ? tHeader->config.language[0] : '-',
3203                         tHeader->config.language[1] ? tHeader->config.language[1] : '-',
3204                         tHeader->config.country[0] ? tHeader->config.country[0] : '-',
3205                         tHeader->config.country[1] ? tHeader->config.country[1] : '-',
3206                         tHeader->config.orientation,
3207                         tHeader->config.uiMode,
3208                         tHeader->config.touchscreen,
3209                         tHeader->config.density,
3210                         tHeader->config.keyboard,
3211                         tHeader->config.inputFlags,
3212                         tHeader->config.navigation,
3213                         tHeader->config.screenWidth,
3214                         tHeader->config.screenHeight,
3215                         tHeader->config.smallestScreenWidthDp,
3216                         tHeader->config.screenWidthDp,
3217                         tHeader->config.screenHeightDp,
3218                         tHeader->config.screenLayout);
3219                 }
3220                 tHeader->config.swapHtoD();
3221 
3222                 // Build the entries inside of this type.
3223                 for (size_t ei=0; ei<N; ei++) {
3224                     sp<ConfigList> cl = t->getOrderedConfigs().itemAt(ei);
3225                     sp<Entry> e = NULL;
3226                     if (cl != NULL) {
3227                         e = cl->getEntries().valueFor(config);
3228                     }
3229 
3230                     // Set the offset for this entry in its type.
3231                     uint32_t* index = (uint32_t*)
3232                         (((uint8_t*)data->editData())
3233                             + typeStart + sizeof(ResTable_type));
3234                     if (e != NULL) {
3235                         index[ei] = htodl(data->getSize()-typeStart-typeSize);
3236 
3237                         // Create the entry.
3238                         ssize_t amt = e->flatten(bundle, data, cl->getPublic());
3239                         if (amt < 0) {
3240                             return amt;
3241                         }
3242                         validResources.editItemAt(ei) = true;
3243                     } else {
3244                         index[ei] = htodl(ResTable_type::NO_ENTRY);
3245                     }
3246                 }
3247 
3248                 // Fill in the rest of the type information.
3249                 tHeader = (ResTable_type*)
3250                     (((uint8_t*)data->editData()) + typeStart);
3251                 tHeader->header.size = htodl(data->getSize()-typeStart);
3252             }
3253 
3254             // If we're building splits, then each invocation of the flattening
3255             // step will have 'missing' entries. Don't warn/error for this case.
3256             if (bundle->getSplitConfigurations().empty()) {
3257                 bool missing_entry = false;
3258                 const char* log_prefix = bundle->getErrorOnMissingConfigEntry() ?
3259                         "error" : "warning";
3260                 for (size_t i = 0; i < N; ++i) {
3261                     if (!validResources[i]) {
3262                         sp<ConfigList> c = t->getOrderedConfigs().itemAt(i);
3263                         if (c != NULL) {
3264                             fprintf(stderr, "%s: no entries written for %s/%s (0x%08zx)\n", log_prefix,
3265                                     String8(typeName).c_str(), String8(c->getName()).c_str(),
3266                                     Res_MAKEID(p->getAssignedId() - 1, ti, i));
3267                         }
3268                         missing_entry = true;
3269                     }
3270                 }
3271                 if (bundle->getErrorOnMissingConfigEntry() && missing_entry) {
3272                     fprintf(stderr, "Error: Missing entries, quit!\n");
3273                     return NOT_ENOUGH_DATA;
3274                 }
3275             }
3276         }
3277 
3278         // Fill in the rest of the package information.
3279         header = (ResTable_package*)data->editData();
3280         header->header.size = htodl(data->getSize());
3281         header->typeStrings = htodl(typeStringsStart);
3282         header->lastPublicType = htodl(p->getTypeStrings().size());
3283         header->keyStrings = htodl(keyStringsStart);
3284         header->lastPublicKey = htodl(p->getKeyStrings().size());
3285 
3286         flatPackages.add(data);
3287     }
3288 
3289     // And now write out the final chunks.
3290     const size_t dataStart = dest->getSize();
3291 
3292     {
3293         // blah
3294         ResTable_header header;
3295         memset(&header, 0, sizeof(header));
3296         header.header.type = htods(RES_TABLE_TYPE);
3297         header.header.headerSize = htods(sizeof(header));
3298         header.packageCount = htodl(flatPackages.size());
3299         status_t err = dest->writeData(&header, sizeof(header));
3300         if (err != NO_ERROR) {
3301             fprintf(stderr, "ERROR: out of memory creating ResTable_header\n");
3302             return err;
3303         }
3304     }
3305 
3306     ssize_t strStart = dest->getSize();
3307     status_t err = valueStrings.writeStringBlock(dest);
3308     if (err != NO_ERROR) {
3309         return err;
3310     }
3311 
3312     ssize_t amt = (dest->getSize()-strStart);
3313     strAmt += amt;
3314     if (kPrintStringMetrics) {
3315         fprintf(stderr, "**** value strings: %zd\n", amt);
3316         fprintf(stderr, "**** total strings: %zd\n", amt);
3317     }
3318 
3319     for (pi=0; pi<flatPackages.size(); pi++) {
3320         err = dest->writeData(flatPackages[pi]->getData(),
3321                               flatPackages[pi]->getSize());
3322         if (err != NO_ERROR) {
3323             fprintf(stderr, "ERROR: out of memory creating package chunk for ResTable_header\n");
3324             return err;
3325         }
3326     }
3327 
3328     ResTable_header* header = (ResTable_header*)
3329         (((uint8_t*)dest->getData()) + dataStart);
3330     header->header.size = htodl(dest->getSize() - dataStart);
3331 
3332     if (kPrintStringMetrics) {
3333         fprintf(stderr, "**** total resource table size: %zu / %zu%% strings\n",
3334                 dest->getSize(), (size_t)(strAmt*100)/dest->getSize());
3335     }
3336 
3337     return NO_ERROR;
3338 }
3339 
flattenLibraryTable(const sp<AaptFile> & dest,const Vector<sp<Package>> & libs)3340 status_t ResourceTable::flattenLibraryTable(const sp<AaptFile>& dest, const Vector<sp<Package> >& libs) {
3341     // Write out the library table if necessary
3342     if (libs.size() > 0) {
3343         if (kIsDebug) {
3344             fprintf(stderr, "Writing library reference table\n");
3345         }
3346 
3347         const size_t libStart = dest->getSize();
3348         const size_t count = libs.size();
3349         ResTable_lib_header* libHeader = (ResTable_lib_header*) dest->editDataInRange(
3350                 libStart, sizeof(ResTable_lib_header));
3351 
3352         memset(libHeader, 0, sizeof(*libHeader));
3353         libHeader->header.type = htods(RES_TABLE_LIBRARY_TYPE);
3354         libHeader->header.headerSize = htods(sizeof(*libHeader));
3355         libHeader->header.size = htodl(sizeof(*libHeader) + (sizeof(ResTable_lib_entry) * count));
3356         libHeader->count = htodl(count);
3357 
3358         // Write the library entries
3359         for (size_t i = 0; i < count; i++) {
3360             const size_t entryStart = dest->getSize();
3361             sp<Package> libPackage = libs[i];
3362             if (kIsDebug) {
3363                 fprintf(stderr, "  Entry %s -> 0x%02x\n",
3364                         String8(libPackage->getName()).c_str(),
3365                         (uint8_t)libPackage->getAssignedId());
3366             }
3367 
3368             ResTable_lib_entry* entry = (ResTable_lib_entry*) dest->editDataInRange(
3369                     entryStart, sizeof(ResTable_lib_entry));
3370             memset(entry, 0, sizeof(*entry));
3371             entry->packageId = htodl(libPackage->getAssignedId());
3372             strcpy16_htod(entry->packageName, libPackage->getName().c_str());
3373         }
3374     }
3375     return NO_ERROR;
3376 }
3377 
writePublicDefinitions(const String16 & package,FILE * fp)3378 void ResourceTable::writePublicDefinitions(const String16& package, FILE* fp)
3379 {
3380     fprintf(fp,
3381     "<!-- This file contains <public> resource definitions for all\n"
3382     "     resources that were generated from the source data. -->\n"
3383     "\n"
3384     "<resources>\n");
3385 
3386     writePublicDefinitions(package, fp, true);
3387     writePublicDefinitions(package, fp, false);
3388 
3389     fprintf(fp,
3390     "\n"
3391     "</resources>\n");
3392 }
3393 
writePublicDefinitions(const String16 & package,FILE * fp,bool pub)3394 void ResourceTable::writePublicDefinitions(const String16& package, FILE* fp, bool pub)
3395 {
3396     bool didHeader = false;
3397 
3398     sp<Package> pkg = mPackages.valueFor(package);
3399     if (pkg != NULL) {
3400         const size_t NT = pkg->getOrderedTypes().size();
3401         for (size_t i=0; i<NT; i++) {
3402             sp<Type> t = pkg->getOrderedTypes().itemAt(i);
3403             if (t == NULL) {
3404                 continue;
3405             }
3406 
3407             bool didType = false;
3408 
3409             const size_t NC = t->getOrderedConfigs().size();
3410             for (size_t j=0; j<NC; j++) {
3411                 sp<ConfigList> c = t->getOrderedConfigs().itemAt(j);
3412                 if (c == NULL) {
3413                     continue;
3414                 }
3415 
3416                 if (c->getPublic() != pub) {
3417                     continue;
3418                 }
3419 
3420                 if (!didType) {
3421                     fprintf(fp, "\n");
3422                     didType = true;
3423                 }
3424                 if (!didHeader) {
3425                     if (pub) {
3426                         fprintf(fp,"  <!-- PUBLIC SECTION.  These resources have been declared public.\n");
3427                         fprintf(fp,"       Changes to these definitions will break binary compatibility. -->\n\n");
3428                     } else {
3429                         fprintf(fp,"  <!-- PRIVATE SECTION.  These resources have not been declared public.\n");
3430                         fprintf(fp,"       You can make them public my moving these lines into a file in res/values. -->\n\n");
3431                     }
3432                     didHeader = true;
3433                 }
3434                 if (!pub) {
3435                     const size_t NE = c->getEntries().size();
3436                     for (size_t k=0; k<NE; k++) {
3437                         const SourcePos& pos = c->getEntries().valueAt(k)->getPos();
3438                         if (pos.file != "") {
3439                             fprintf(fp,"  <!-- Declared at %s:%d -->\n",
3440                                     pos.file.c_str(), pos.line);
3441                         }
3442                     }
3443                 }
3444                 fprintf(fp, "  <public type=\"%s\" name=\"%s\" id=\"0x%08x\" />\n",
3445                         String8(t->getName()).c_str(),
3446                         String8(c->getName()).c_str(),
3447                         getResId(pkg, t, c->getEntryIndex()));
3448             }
3449         }
3450     }
3451 }
3452 
Item(const SourcePos & _sourcePos,bool _isId,const String16 & _value,const Vector<StringPool::entry_style_span> * _style,int32_t _format)3453 ResourceTable::Item::Item(const SourcePos& _sourcePos,
3454                           bool _isId,
3455                           const String16& _value,
3456                           const Vector<StringPool::entry_style_span>* _style,
3457                           int32_t _format)
3458     : sourcePos(_sourcePos)
3459     , isId(_isId)
3460     , value(_value)
3461     , format(_format)
3462     , bagKeyId(0)
3463     , evaluating(false)
3464 {
3465     if (_style) {
3466         style = *_style;
3467     }
3468 }
3469 
Entry(const Entry & entry)3470 ResourceTable::Entry::Entry(const Entry& entry)
3471     : RefBase()
3472     , mName(entry.mName)
3473     , mParent(entry.mParent)
3474     , mType(entry.mType)
3475     , mItem(entry.mItem)
3476     , mItemFormat(entry.mItemFormat)
3477     , mBag(entry.mBag)
3478     , mNameIndex(entry.mNameIndex)
3479     , mParentId(entry.mParentId)
3480     , mPos(entry.mPos) {}
3481 
operator =(const Entry & entry)3482 ResourceTable::Entry& ResourceTable::Entry::operator=(const Entry& entry) {
3483     mName = entry.mName;
3484     mParent = entry.mParent;
3485     mType = entry.mType;
3486     mItem = entry.mItem;
3487     mItemFormat = entry.mItemFormat;
3488     mBag = entry.mBag;
3489     mNameIndex = entry.mNameIndex;
3490     mParentId = entry.mParentId;
3491     mPos = entry.mPos;
3492     return *this;
3493 }
3494 
makeItABag(const SourcePos & sourcePos)3495 status_t ResourceTable::Entry::makeItABag(const SourcePos& sourcePos)
3496 {
3497     if (mType == TYPE_BAG) {
3498         return NO_ERROR;
3499     }
3500     if (mType == TYPE_UNKNOWN) {
3501         mType = TYPE_BAG;
3502         return NO_ERROR;
3503     }
3504     sourcePos.error("Resource entry %s is already defined as a single item.\n"
3505                     "%s:%d: Originally defined here.\n",
3506                     String8(mName).c_str(),
3507                     mItem.sourcePos.file.c_str(), mItem.sourcePos.line);
3508     return UNKNOWN_ERROR;
3509 }
3510 
setItem(const SourcePos & sourcePos,const String16 & value,const Vector<StringPool::entry_style_span> * style,int32_t format,const bool overwrite)3511 status_t ResourceTable::Entry::setItem(const SourcePos& sourcePos,
3512                                        const String16& value,
3513                                        const Vector<StringPool::entry_style_span>* style,
3514                                        int32_t format,
3515                                        const bool overwrite)
3516 {
3517     Item item(sourcePos, false, value, style);
3518 
3519     if (mType == TYPE_BAG) {
3520         if (mBag.size() == 0) {
3521             sourcePos.error("Resource entry %s is already defined as a bag.",
3522                     String8(mName).c_str());
3523         } else {
3524             const Item& item(mBag.valueAt(0));
3525             sourcePos.error("Resource entry %s is already defined as a bag.\n"
3526                             "%s:%d: Originally defined here.\n",
3527                             String8(mName).c_str(),
3528                             item.sourcePos.file.c_str(), item.sourcePos.line);
3529         }
3530         return UNKNOWN_ERROR;
3531     }
3532     if ( (mType != TYPE_UNKNOWN) && (overwrite == false) ) {
3533         sourcePos.error("Resource entry %s is already defined.\n"
3534                         "%s:%d: Originally defined here.\n",
3535                         String8(mName).c_str(),
3536                         mItem.sourcePos.file.c_str(), mItem.sourcePos.line);
3537         return UNKNOWN_ERROR;
3538     }
3539 
3540     mType = TYPE_ITEM;
3541     mItem = item;
3542     mItemFormat = format;
3543     return NO_ERROR;
3544 }
3545 
addToBag(const SourcePos & sourcePos,const String16 & key,const String16 & value,const Vector<StringPool::entry_style_span> * style,bool replace,bool isId,int32_t format)3546 status_t ResourceTable::Entry::addToBag(const SourcePos& sourcePos,
3547                                         const String16& key, const String16& value,
3548                                         const Vector<StringPool::entry_style_span>* style,
3549                                         bool replace, bool isId, int32_t format)
3550 {
3551     status_t err = makeItABag(sourcePos);
3552     if (err != NO_ERROR) {
3553         return err;
3554     }
3555 
3556     Item item(sourcePos, isId, value, style, format);
3557 
3558     // XXX NOTE: there is an error if you try to have a bag with two keys,
3559     // one an attr and one an id, with the same name.  Not something we
3560     // currently ever have to worry about.
3561     ssize_t origKey = mBag.indexOfKey(key);
3562     if (origKey >= 0) {
3563         if (!replace) {
3564             const Item& item(mBag.valueAt(origKey));
3565             sourcePos.error("Resource entry %s already has bag item %s.\n"
3566                     "%s:%d: Originally defined here.\n",
3567                     String8(mName).c_str(), String8(key).c_str(),
3568                     item.sourcePos.file.c_str(), item.sourcePos.line);
3569             return UNKNOWN_ERROR;
3570         }
3571         //printf("Replacing %s with %s\n",
3572         //       String8(mBag.valueFor(key).value).c_str(), String8(value).c_str());
3573         mBag.replaceValueFor(key, item);
3574     }
3575 
3576     mBag.add(key, item);
3577     return NO_ERROR;
3578 }
3579 
removeFromBag(const String16 & key)3580 status_t ResourceTable::Entry::removeFromBag(const String16& key) {
3581     if (mType != Entry::TYPE_BAG) {
3582         return NO_ERROR;
3583     }
3584 
3585     if (mBag.removeItem(key) >= 0) {
3586         return NO_ERROR;
3587     }
3588     return UNKNOWN_ERROR;
3589 }
3590 
emptyBag(const SourcePos & sourcePos)3591 status_t ResourceTable::Entry::emptyBag(const SourcePos& sourcePos)
3592 {
3593     status_t err = makeItABag(sourcePos);
3594     if (err != NO_ERROR) {
3595         return err;
3596     }
3597 
3598     mBag.clear();
3599     return NO_ERROR;
3600 }
3601 
generateAttributes(ResourceTable * table,const String16 & package)3602 status_t ResourceTable::Entry::generateAttributes(ResourceTable* table,
3603                                                   const String16& package)
3604 {
3605     const String16 attr16("attr");
3606     const String16 id16("id");
3607     const size_t N = mBag.size();
3608     for (size_t i=0; i<N; i++) {
3609         const String16& key = mBag.keyAt(i);
3610         const Item& it = mBag.valueAt(i);
3611         if (it.isId) {
3612             if (!table->hasBagOrEntry(key, &id16, &package)) {
3613                 String16 value("false");
3614                 if (kIsDebug) {
3615                     fprintf(stderr, "Generating %s:id/%s\n",
3616                             String8(package).c_str(),
3617                             String8(key).c_str());
3618                 }
3619                 status_t err = table->addEntry(SourcePos(String8("<generated>"), 0), package,
3620                                                id16, key, value);
3621                 if (err != NO_ERROR) {
3622                     return err;
3623                 }
3624             }
3625         } else if (!table->hasBagOrEntry(key, &attr16, &package)) {
3626 
3627 #if 1
3628 //             fprintf(stderr, "ERROR: Bag attribute '%s' has not been defined.\n",
3629 //                     String8(key).c_str());
3630 //             const Item& item(mBag.valueAt(i));
3631 //             fprintf(stderr, "Referenced from file %s line %d\n",
3632 //                     item.sourcePos.file.c_str(), item.sourcePos.line);
3633 //             return UNKNOWN_ERROR;
3634 #else
3635             char numberStr[16];
3636             sprintf(numberStr, "%d", ResTable_map::TYPE_ANY);
3637             status_t err = table->addBag(SourcePos("<generated>", 0), package,
3638                                          attr16, key, String16(""),
3639                                          String16("^type"),
3640                                          String16(numberStr), NULL, NULL);
3641             if (err != NO_ERROR) {
3642                 return err;
3643             }
3644 #endif
3645         }
3646     }
3647     return NO_ERROR;
3648 }
3649 
assignResourceIds(ResourceTable * table,const String16 &)3650 status_t ResourceTable::Entry::assignResourceIds(ResourceTable* table,
3651                                                  const String16& /* package */)
3652 {
3653     bool hasErrors = false;
3654 
3655     if (mType == TYPE_BAG) {
3656         const char* errorMsg;
3657         const String16 style16("style");
3658         const String16 attr16("attr");
3659         const String16 id16("id");
3660         mParentId = 0;
3661         if (mParent.size() > 0) {
3662             mParentId = table->getResId(mParent, &style16, NULL, &errorMsg);
3663             if (mParentId == 0) {
3664                 mPos.error("Error retrieving parent for item: %s '%s'.\n",
3665                         errorMsg, String8(mParent).c_str());
3666                 hasErrors = true;
3667             }
3668         }
3669         const size_t N = mBag.size();
3670         for (size_t i=0; i<N; i++) {
3671             const String16& key = mBag.keyAt(i);
3672             Item& it = mBag.editValueAt(i);
3673             it.bagKeyId = table->getResId(key,
3674                     it.isId ? &id16 : &attr16, NULL, &errorMsg);
3675             //printf("Bag key of %s: #%08x\n", String8(key).c_str(), it.bagKeyId);
3676             if (it.bagKeyId == 0) {
3677                 it.sourcePos.error("Error: %s: %s '%s'.\n", errorMsg,
3678                         String8(it.isId ? id16 : attr16).c_str(),
3679                         String8(key).c_str());
3680                 hasErrors = true;
3681             }
3682         }
3683     }
3684     return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
3685 }
3686 
prepareFlatten(StringPool * strings,ResourceTable * table,const String8 * configTypeName,const ConfigDescription * config)3687 status_t ResourceTable::Entry::prepareFlatten(StringPool* strings, ResourceTable* table,
3688         const String8* configTypeName, const ConfigDescription* config)
3689 {
3690     if (mType == TYPE_ITEM) {
3691         Item& it = mItem;
3692         AccessorCookie ac(it.sourcePos, String8(mName), String8(it.value));
3693         if (!table->stringToValue(&it.parsedValue, strings,
3694                                   it.value, false, true, 0,
3695                                   &it.style, NULL, &ac, mItemFormat,
3696                                   configTypeName, config)) {
3697             return UNKNOWN_ERROR;
3698         }
3699     } else if (mType == TYPE_BAG) {
3700         const size_t N = mBag.size();
3701         for (size_t i=0; i<N; i++) {
3702             const String16& key = mBag.keyAt(i);
3703             Item& it = mBag.editValueAt(i);
3704             AccessorCookie ac(it.sourcePos, String8(key), String8(it.value));
3705             if (!table->stringToValue(&it.parsedValue, strings,
3706                                       it.value, false, true, it.bagKeyId,
3707                                       &it.style, NULL, &ac, it.format,
3708                                       configTypeName, config)) {
3709                 return UNKNOWN_ERROR;
3710             }
3711         }
3712     } else {
3713         mPos.error("Error: entry %s is not a single item or a bag.\n",
3714                    String8(mName).c_str());
3715         return UNKNOWN_ERROR;
3716     }
3717     return NO_ERROR;
3718 }
3719 
remapStringValue(StringPool * strings)3720 status_t ResourceTable::Entry::remapStringValue(StringPool* strings)
3721 {
3722     if (mType == TYPE_ITEM) {
3723         Item& it = mItem;
3724         if (it.parsedValue.dataType == Res_value::TYPE_STRING) {
3725             it.parsedValue.data = strings->mapOriginalPosToNewPos(it.parsedValue.data);
3726         }
3727     } else if (mType == TYPE_BAG) {
3728         const size_t N = mBag.size();
3729         for (size_t i=0; i<N; i++) {
3730             Item& it = mBag.editValueAt(i);
3731             if (it.parsedValue.dataType == Res_value::TYPE_STRING) {
3732                 it.parsedValue.data = strings->mapOriginalPosToNewPos(it.parsedValue.data);
3733             }
3734         }
3735     } else {
3736         mPos.error("Error: entry %s is not a single item or a bag.\n",
3737                    String8(mName).c_str());
3738         return UNKNOWN_ERROR;
3739     }
3740     return NO_ERROR;
3741 }
3742 
flatten(Bundle *,const sp<AaptFile> & data,bool isPublic)3743 ssize_t ResourceTable::Entry::flatten(Bundle* /* bundle */, const sp<AaptFile>& data, bool isPublic)
3744 {
3745     size_t amt = 0;
3746     ResTable_entry header;
3747     memset(&header, 0, sizeof(header));
3748     header.full.size = htods(sizeof(header));
3749     const type ty = mType;
3750     if (ty == TYPE_BAG) {
3751         header.full.flags |= htods(header.FLAG_COMPLEX);
3752     }
3753     if (isPublic) {
3754         header.full.flags |= htods(header.FLAG_PUBLIC);
3755     }
3756     header.full.key.index = htodl(mNameIndex);
3757     if (ty != TYPE_BAG) {
3758         status_t err = data->writeData(&header, sizeof(header));
3759         if (err != NO_ERROR) {
3760             fprintf(stderr, "ERROR: out of memory creating ResTable_entry\n");
3761             return err;
3762         }
3763 
3764         const Item& it = mItem;
3765         Res_value par;
3766         memset(&par, 0, sizeof(par));
3767         par.size = htods(it.parsedValue.size);
3768         par.dataType = it.parsedValue.dataType;
3769         par.res0 = it.parsedValue.res0;
3770         par.data = htodl(it.parsedValue.data);
3771         #if 0
3772         printf("Writing item (%s): type=%d, data=0x%x, res0=0x%x\n",
3773                String8(mName).c_str(), it.parsedValue.dataType,
3774                it.parsedValue.data, par.res0);
3775         #endif
3776         err = data->writeData(&par, it.parsedValue.size);
3777         if (err != NO_ERROR) {
3778             fprintf(stderr, "ERROR: out of memory creating Res_value\n");
3779             return err;
3780         }
3781         amt += it.parsedValue.size;
3782     } else {
3783         size_t N = mBag.size();
3784         size_t i;
3785         // Create correct ordering of items.
3786         KeyedVector<uint32_t, const Item*> items;
3787         for (i=0; i<N; i++) {
3788             const Item& it = mBag.valueAt(i);
3789             items.add(it.bagKeyId, &it);
3790         }
3791         N = items.size();
3792 
3793         ResTable_map_entry mapHeader;
3794         memcpy(&mapHeader, &header, sizeof(header));
3795         mapHeader.size = htods(sizeof(mapHeader));
3796         mapHeader.parent.ident = htodl(mParentId);
3797         mapHeader.count = htodl(N);
3798         status_t err = data->writeData(&mapHeader, sizeof(mapHeader));
3799         if (err != NO_ERROR) {
3800             fprintf(stderr, "ERROR: out of memory creating ResTable_entry\n");
3801             return err;
3802         }
3803 
3804         for (i=0; i<N; i++) {
3805             const Item& it = *items.valueAt(i);
3806             ResTable_map map;
3807             map.name.ident = htodl(it.bagKeyId);
3808             map.value.size = htods(it.parsedValue.size);
3809             map.value.dataType = it.parsedValue.dataType;
3810             map.value.res0 = it.parsedValue.res0;
3811             map.value.data = htodl(it.parsedValue.data);
3812             err = data->writeData(&map, sizeof(map));
3813             if (err != NO_ERROR) {
3814                 fprintf(stderr, "ERROR: out of memory creating Res_value\n");
3815                 return err;
3816             }
3817             amt += sizeof(map);
3818         }
3819     }
3820     return amt;
3821 }
3822 
appendComment(const String16 & comment,bool onlyIfEmpty)3823 void ResourceTable::ConfigList::appendComment(const String16& comment,
3824                                               bool onlyIfEmpty)
3825 {
3826     if (comment.size() <= 0) {
3827         return;
3828     }
3829     if (onlyIfEmpty && mComment.size() > 0) {
3830         return;
3831     }
3832     if (mComment.size() > 0) {
3833         mComment.append(String16("\n"));
3834     }
3835     mComment.append(comment);
3836 }
3837 
appendTypeComment(const String16 & comment)3838 void ResourceTable::ConfigList::appendTypeComment(const String16& comment)
3839 {
3840     if (comment.size() <= 0) {
3841         return;
3842     }
3843     if (mTypeComment.size() > 0) {
3844         mTypeComment.append(String16("\n"));
3845     }
3846     mTypeComment.append(comment);
3847 }
3848 
addPublic(const SourcePos & sourcePos,const String16 & name,const uint32_t ident)3849 status_t ResourceTable::Type::addPublic(const SourcePos& sourcePos,
3850                                         const String16& name,
3851                                         const uint32_t ident)
3852 {
3853     #if 0
3854     int32_t entryIdx = Res_GETENTRY(ident);
3855     if (entryIdx < 0) {
3856         sourcePos.error("Public resource %s/%s has an invalid 0 identifier (0x%08x).\n",
3857                 String8(mName).c_str(), String8(name).c_str(), ident);
3858         return UNKNOWN_ERROR;
3859     }
3860     #endif
3861 
3862     int32_t typeIdx = Res_GETTYPE(ident);
3863     if (typeIdx >= 0) {
3864         typeIdx++;
3865         if (mPublicIndex > 0 && mPublicIndex != typeIdx) {
3866             sourcePos.error("Public resource %s/%s has conflicting type codes for its"
3867                     " public identifiers (0x%x vs 0x%x).\n",
3868                     String8(mName).c_str(), String8(name).c_str(),
3869                     mPublicIndex, typeIdx);
3870             return UNKNOWN_ERROR;
3871         }
3872         mPublicIndex = typeIdx;
3873     }
3874 
3875     if (mFirstPublicSourcePos == NULL) {
3876         mFirstPublicSourcePos = new SourcePos(sourcePos);
3877     }
3878 
3879     if (mPublic.indexOfKey(name) < 0) {
3880         mPublic.add(name, Public(sourcePos, String16(), ident));
3881     } else {
3882         Public& p = mPublic.editValueFor(name);
3883         if (p.ident != ident) {
3884             sourcePos.error("Public resource %s/%s has conflicting public identifiers"
3885                     " (0x%08x vs 0x%08x).\n"
3886                     "%s:%d: Originally defined here.\n",
3887                     String8(mName).c_str(), String8(name).c_str(), p.ident, ident,
3888                     p.sourcePos.file.c_str(), p.sourcePos.line);
3889             return UNKNOWN_ERROR;
3890         }
3891     }
3892 
3893     return NO_ERROR;
3894 }
3895 
canAddEntry(const String16 & name)3896 void ResourceTable::Type::canAddEntry(const String16& name)
3897 {
3898     mCanAddEntries.add(name);
3899 }
3900 
getEntry(const String16 & entry,const SourcePos & sourcePos,const ResTable_config * config,bool doSetIndex,bool overlay,bool autoAddOverlay)3901 sp<ResourceTable::Entry> ResourceTable::Type::getEntry(const String16& entry,
3902                                                        const SourcePos& sourcePos,
3903                                                        const ResTable_config* config,
3904                                                        bool doSetIndex,
3905                                                        bool overlay,
3906                                                        bool autoAddOverlay)
3907 {
3908     int pos = -1;
3909     sp<ConfigList> c = mConfigs.valueFor(entry);
3910     if (c == NULL) {
3911         if (overlay && !autoAddOverlay && mCanAddEntries.indexOf(entry) < 0) {
3912             sourcePos.error("Resource at %s appears in overlay but not"
3913                             " in the base package; use <add-resource> to add.\n",
3914                             String8(entry).c_str());
3915             return NULL;
3916         }
3917         c = new ConfigList(entry, sourcePos);
3918         mConfigs.add(entry, c);
3919         pos = (int)mOrderedConfigs.size();
3920         mOrderedConfigs.add(c);
3921         if (doSetIndex) {
3922             c->setEntryIndex(pos);
3923         }
3924     }
3925 
3926     ConfigDescription cdesc;
3927     if (config) cdesc = *config;
3928 
3929     sp<Entry> e = c->getEntries().valueFor(cdesc);
3930     if (e == NULL) {
3931         if (kIsDebug) {
3932             if (config != NULL) {
3933                 printf("New entry at %s:%d: imsi:%d/%d lang:%c%c cnt:%c%c "
3934                     "orien:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d "
3935                     "sw%ddp w%ddp h%ddp layout:%d\n",
3936                       sourcePos.file.c_str(), sourcePos.line,
3937                       config->mcc, config->mnc,
3938                       config->language[0] ? config->language[0] : '-',
3939                       config->language[1] ? config->language[1] : '-',
3940                       config->country[0] ? config->country[0] : '-',
3941                       config->country[1] ? config->country[1] : '-',
3942                       config->orientation,
3943                       config->touchscreen,
3944                       config->density,
3945                       config->keyboard,
3946                       config->inputFlags,
3947                       config->navigation,
3948                       config->screenWidth,
3949                       config->screenHeight,
3950                       config->smallestScreenWidthDp,
3951                       config->screenWidthDp,
3952                       config->screenHeightDp,
3953                       config->screenLayout);
3954             } else {
3955                 printf("New entry at %s:%d: NULL config\n",
3956                         sourcePos.file.c_str(), sourcePos.line);
3957             }
3958         }
3959         e = new Entry(entry, sourcePos);
3960         c->addEntry(cdesc, e);
3961         /*
3962         if (doSetIndex) {
3963             if (pos < 0) {
3964                 for (pos=0; pos<(int)mOrderedConfigs.size(); pos++) {
3965                     if (mOrderedConfigs[pos] == c) {
3966                         break;
3967                     }
3968                 }
3969                 if (pos >= (int)mOrderedConfigs.size()) {
3970                     sourcePos.error("Internal error: config not found in mOrderedConfigs when adding entry");
3971                     return NULL;
3972                 }
3973             }
3974             e->setEntryIndex(pos);
3975         }
3976         */
3977     }
3978 
3979     return e;
3980 }
3981 
removeEntry(const String16 & entry)3982 sp<ResourceTable::ConfigList> ResourceTable::Type::removeEntry(const String16& entry) {
3983     ssize_t idx = mConfigs.indexOfKey(entry);
3984     if (idx < 0) {
3985         return NULL;
3986     }
3987 
3988     sp<ConfigList> removed = mConfigs.valueAt(idx);
3989     mConfigs.removeItemsAt(idx);
3990 
3991     Vector<sp<ConfigList> >::iterator iter = std::find(
3992             mOrderedConfigs.begin(), mOrderedConfigs.end(), removed);
3993     if (iter != mOrderedConfigs.end()) {
3994         mOrderedConfigs.erase(iter);
3995     }
3996 
3997     mPublic.removeItem(entry);
3998     return removed;
3999 }
4000 
getUniqueConfigs() const4001 SortedVector<ConfigDescription> ResourceTable::Type::getUniqueConfigs() const {
4002     SortedVector<ConfigDescription> unique;
4003     const size_t entryCount = mOrderedConfigs.size();
4004     for (size_t i = 0; i < entryCount; i++) {
4005         if (mOrderedConfigs[i] == NULL) {
4006             continue;
4007         }
4008         const DefaultKeyedVector<ConfigDescription, sp<Entry> >& configs =
4009                 mOrderedConfigs[i]->getEntries();
4010         const size_t configCount = configs.size();
4011         for (size_t j = 0; j < configCount; j++) {
4012             unique.add(configs.keyAt(j));
4013         }
4014     }
4015     return unique;
4016 }
4017 
applyPublicEntryOrder()4018 status_t ResourceTable::Type::applyPublicEntryOrder()
4019 {
4020     size_t N = mOrderedConfigs.size();
4021     Vector<sp<ConfigList> > origOrder(mOrderedConfigs);
4022     bool hasError = false;
4023 
4024     size_t i;
4025     for (i=0; i<N; i++) {
4026         mOrderedConfigs.replaceAt(NULL, i);
4027     }
4028 
4029     const size_t NP = mPublic.size();
4030     //printf("Ordering %d configs from %d public defs\n", N, NP);
4031     size_t j;
4032     for (j=0; j<NP; j++) {
4033         const String16& name = mPublic.keyAt(j);
4034         const Public& p = mPublic.valueAt(j);
4035         int32_t idx = Res_GETENTRY(p.ident);
4036         //printf("Looking for entry \"%s\"/\"%s\" (0x%08x) in %d...\n",
4037         //       String8(mName).c_str(), String8(name).c_str(), p.ident, N);
4038         bool found = false;
4039         for (i=0; i<N; i++) {
4040             sp<ConfigList> e = origOrder.itemAt(i);
4041             //printf("#%d: \"%s\"\n", i, String8(e->getName()).c_str());
4042             if (e->getName() == name) {
4043                 if (idx >= (int32_t)mOrderedConfigs.size()) {
4044                     mOrderedConfigs.resize(idx + 1);
4045                 }
4046 
4047                 if (mOrderedConfigs.itemAt(idx) == NULL) {
4048                     e->setPublic(true);
4049                     e->setPublicSourcePos(p.sourcePos);
4050                     mOrderedConfigs.replaceAt(e, idx);
4051                     origOrder.removeAt(i);
4052                     N--;
4053                     found = true;
4054                     break;
4055                 } else {
4056                     sp<ConfigList> oe = mOrderedConfigs.itemAt(idx);
4057 
4058                     p.sourcePos.error("Multiple entry names declared for public entry"
4059                             " identifier 0x%x in type %s (%s vs %s).\n"
4060                             "%s:%d: Originally defined here.",
4061                             idx+1, String8(mName).c_str(),
4062                             String8(oe->getName()).c_str(),
4063                             String8(name).c_str(),
4064                             oe->getPublicSourcePos().file.c_str(),
4065                             oe->getPublicSourcePos().line);
4066                     hasError = true;
4067                 }
4068             }
4069         }
4070 
4071         if (!found) {
4072             p.sourcePos.error("Public symbol %s/%s declared here is not defined.",
4073                     String8(mName).c_str(), String8(name).c_str());
4074             hasError = true;
4075         }
4076     }
4077 
4078     //printf("Copying back in %d non-public configs, have %d\n", N, origOrder.size());
4079 
4080     if (N != origOrder.size()) {
4081         printf("Internal error: remaining private symbol count mismatch\n");
4082         N = origOrder.size();
4083     }
4084 
4085     j = 0;
4086     for (i=0; i<N; i++) {
4087         const sp<ConfigList>& e = origOrder.itemAt(i);
4088         // There will always be enough room for the remaining entries.
4089         while (mOrderedConfigs.itemAt(j) != NULL) {
4090             j++;
4091         }
4092         mOrderedConfigs.replaceAt(e, j);
4093         j++;
4094     }
4095 
4096     return hasError ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
4097 }
4098 
Package(const String16 & name,size_t packageId)4099 ResourceTable::Package::Package(const String16& name, size_t packageId)
4100     : mName(name), mPackageId(packageId),
4101       mTypeStringsMapping(0xffffffff),
4102       mKeyStringsMapping(0xffffffff)
4103 {
4104 }
4105 
getType(const String16 & type,const SourcePos & sourcePos,bool doSetIndex)4106 sp<ResourceTable::Type> ResourceTable::Package::getType(const String16& type,
4107                                                         const SourcePos& sourcePos,
4108                                                         bool doSetIndex)
4109 {
4110     sp<Type> t = mTypes.valueFor(type);
4111     if (t == NULL) {
4112         t = new Type(type, sourcePos);
4113         mTypes.add(type, t);
4114         mOrderedTypes.add(t);
4115         if (doSetIndex) {
4116             // For some reason the type's index is set to one plus the index
4117             // in the mOrderedTypes list, rather than just the index.
4118             t->setIndex(mOrderedTypes.size());
4119         }
4120     }
4121     return t;
4122 }
4123 
setTypeStrings(const sp<AaptFile> & data)4124 status_t ResourceTable::Package::setTypeStrings(const sp<AaptFile>& data)
4125 {
4126     status_t err = setStrings(data, &mTypeStrings, &mTypeStringsMapping);
4127     if (err != NO_ERROR) {
4128         fprintf(stderr, "ERROR: Type string data is corrupt!\n");
4129         return err;
4130     }
4131 
4132     // Retain a reference to the new data after we've successfully replaced
4133     // all uses of the old reference (in setStrings() ).
4134     mTypeStringsData = data;
4135     return NO_ERROR;
4136 }
4137 
setKeyStrings(const sp<AaptFile> & data)4138 status_t ResourceTable::Package::setKeyStrings(const sp<AaptFile>& data)
4139 {
4140     status_t err = setStrings(data, &mKeyStrings, &mKeyStringsMapping);
4141     if (err != NO_ERROR) {
4142         fprintf(stderr, "ERROR: Key string data is corrupt!\n");
4143         return err;
4144     }
4145 
4146     // Retain a reference to the new data after we've successfully replaced
4147     // all uses of the old reference (in setStrings() ).
4148     mKeyStringsData = data;
4149     return NO_ERROR;
4150 }
4151 
setStrings(const sp<AaptFile> & data,ResStringPool * strings,DefaultKeyedVector<String16,uint32_t> * mappings)4152 status_t ResourceTable::Package::setStrings(const sp<AaptFile>& data,
4153                                             ResStringPool* strings,
4154                                             DefaultKeyedVector<String16, uint32_t>* mappings)
4155 {
4156     if (data->getData() == NULL) {
4157         return UNKNOWN_ERROR;
4158     }
4159 
4160     status_t err = strings->setTo(data->getData(), data->getSize());
4161     if (err == NO_ERROR) {
4162         const size_t N = strings->size();
4163         for (size_t i=0; i<N; i++) {
4164             size_t len;
4165             mappings->add(String16(UnpackOptionalString(strings->stringAt(i), &len)), i);
4166         }
4167     }
4168     return err;
4169 }
4170 
applyPublicTypeOrder()4171 status_t ResourceTable::Package::applyPublicTypeOrder()
4172 {
4173     size_t N = mOrderedTypes.size();
4174     Vector<sp<Type> > origOrder(mOrderedTypes);
4175 
4176     size_t i;
4177     for (i=0; i<N; i++) {
4178         mOrderedTypes.replaceAt(NULL, i);
4179     }
4180 
4181     for (i=0; i<N; i++) {
4182         sp<Type> t = origOrder.itemAt(i);
4183         int32_t idx = t->getPublicIndex();
4184         if (idx > 0) {
4185             idx--;
4186             while (idx >= (int32_t)mOrderedTypes.size()) {
4187                 mOrderedTypes.add();
4188             }
4189             if (mOrderedTypes.itemAt(idx) != NULL) {
4190                 sp<Type> ot = mOrderedTypes.itemAt(idx);
4191                 t->getFirstPublicSourcePos().error("Multiple type names declared for public type"
4192                         " identifier 0x%x (%s vs %s).\n"
4193                         "%s:%d: Originally defined here.",
4194                         idx, String8(ot->getName()).c_str(),
4195                         String8(t->getName()).c_str(),
4196                         ot->getFirstPublicSourcePos().file.c_str(),
4197                         ot->getFirstPublicSourcePos().line);
4198                 return UNKNOWN_ERROR;
4199             }
4200             mOrderedTypes.replaceAt(t, idx);
4201             origOrder.removeAt(i);
4202             i--;
4203             N--;
4204         }
4205     }
4206 
4207     size_t j=0;
4208     for (i=0; i<N; i++) {
4209         const sp<Type>& t = origOrder.itemAt(i);
4210         // There will always be enough room for the remaining types.
4211         while (mOrderedTypes.itemAt(j) != NULL) {
4212             j++;
4213         }
4214         mOrderedTypes.replaceAt(t, j);
4215     }
4216 
4217     return NO_ERROR;
4218 }
4219 
movePrivateAttrs()4220 void ResourceTable::Package::movePrivateAttrs() {
4221     sp<Type> attr = mTypes.valueFor(String16("attr"));
4222     if (attr == NULL) {
4223         // Nothing to do.
4224         return;
4225     }
4226 
4227     Vector<sp<ConfigList> > privateAttrs;
4228 
4229     bool hasPublic = false;
4230     const Vector<sp<ConfigList> >& configs = attr->getOrderedConfigs();
4231     const size_t configCount = configs.size();
4232     for (size_t i = 0; i < configCount; i++) {
4233         if (configs[i] == NULL) {
4234             continue;
4235         }
4236 
4237         if (attr->isPublic(configs[i]->getName())) {
4238             hasPublic = true;
4239         } else {
4240             privateAttrs.add(configs[i]);
4241         }
4242     }
4243 
4244     // Only if we have public attributes do we create a separate type for
4245     // private attributes.
4246     if (!hasPublic) {
4247         return;
4248     }
4249 
4250     // Create a new type for private attributes.
4251     sp<Type> privateAttrType = getType(String16(kAttrPrivateType), SourcePos());
4252 
4253     const size_t privateAttrCount = privateAttrs.size();
4254     for (size_t i = 0; i < privateAttrCount; i++) {
4255         const sp<ConfigList>& cl = privateAttrs[i];
4256 
4257         // Remove the private attributes from their current type.
4258         attr->removeEntry(cl->getName());
4259 
4260         // Add it to the new type.
4261         const DefaultKeyedVector<ConfigDescription, sp<Entry> >& entries = cl->getEntries();
4262         const size_t entryCount = entries.size();
4263         for (size_t j = 0; j < entryCount; j++) {
4264             const sp<Entry>& oldEntry = entries[j];
4265             sp<Entry> entry = privateAttrType->getEntry(
4266                     cl->getName(), oldEntry->getPos(), &entries.keyAt(j));
4267             *entry = *oldEntry;
4268         }
4269 
4270         // Move the symbols to the new type.
4271 
4272     }
4273 }
4274 
getPackage(const String16 & package)4275 sp<ResourceTable::Package> ResourceTable::getPackage(const String16& package)
4276 {
4277     if (package != mAssetsPackage) {
4278         return NULL;
4279     }
4280     return mPackages.valueFor(package);
4281 }
4282 
getType(const String16 & package,const String16 & type,const SourcePos & sourcePos,bool doSetIndex)4283 sp<ResourceTable::Type> ResourceTable::getType(const String16& package,
4284                                                const String16& type,
4285                                                const SourcePos& sourcePos,
4286                                                bool doSetIndex)
4287 {
4288     sp<Package> p = getPackage(package);
4289     if (p == NULL) {
4290         return NULL;
4291     }
4292     return p->getType(type, sourcePos, doSetIndex);
4293 }
4294 
getEntry(const String16 & package,const String16 & type,const String16 & name,const SourcePos & sourcePos,bool overlay,const ResTable_config * config,bool doSetIndex)4295 sp<ResourceTable::Entry> ResourceTable::getEntry(const String16& package,
4296                                                  const String16& type,
4297                                                  const String16& name,
4298                                                  const SourcePos& sourcePos,
4299                                                  bool overlay,
4300                                                  const ResTable_config* config,
4301                                                  bool doSetIndex)
4302 {
4303     sp<Type> t = getType(package, type, sourcePos, doSetIndex);
4304     if (t == NULL) {
4305         return NULL;
4306     }
4307     return t->getEntry(name, sourcePos, config, doSetIndex, overlay, mBundle->getAutoAddOverlay());
4308 }
4309 
getConfigList(const String16 & package,const String16 & type,const String16 & name) const4310 sp<ResourceTable::ConfigList> ResourceTable::getConfigList(const String16& package,
4311         const String16& type, const String16& name) const
4312 {
4313     const size_t packageCount = mOrderedPackages.size();
4314     for (size_t pi = 0; pi < packageCount; pi++) {
4315         const sp<Package>& p = mOrderedPackages[pi];
4316         if (p == NULL || p->getName() != package) {
4317             continue;
4318         }
4319 
4320         const Vector<sp<Type> >& types = p->getOrderedTypes();
4321         const size_t typeCount = types.size();
4322         for (size_t ti = 0; ti < typeCount; ti++) {
4323             const sp<Type>& t = types[ti];
4324             if (t == NULL || t->getName() != type) {
4325                 continue;
4326             }
4327 
4328             const Vector<sp<ConfigList> >& configs = t->getOrderedConfigs();
4329             const size_t configCount = configs.size();
4330             for (size_t ci = 0; ci < configCount; ci++) {
4331                 const sp<ConfigList>& cl = configs[ci];
4332                 if (cl == NULL || cl->getName() != name) {
4333                     continue;
4334                 }
4335 
4336                 return cl;
4337             }
4338         }
4339     }
4340     return NULL;
4341 }
4342 
getEntry(uint32_t resID,const ResTable_config * config) const4343 sp<const ResourceTable::Entry> ResourceTable::getEntry(uint32_t resID,
4344                                                        const ResTable_config* config) const
4345 {
4346     size_t pid = Res_GETPACKAGE(resID)+1;
4347     const size_t N = mOrderedPackages.size();
4348     sp<Package> p;
4349     for (size_t i = 0; i < N; i++) {
4350         sp<Package> check = mOrderedPackages[i];
4351         if (check->getAssignedId() == pid) {
4352             p = check;
4353             break;
4354         }
4355 
4356     }
4357     if (p == NULL) {
4358         fprintf(stderr, "warning: Package not found for resource #%08x\n", resID);
4359         return NULL;
4360     }
4361 
4362     int tid = Res_GETTYPE(resID);
4363     if (tid < 0 || tid >= (int)p->getOrderedTypes().size()) {
4364         fprintf(stderr, "warning: Type not found for resource #%08x\n", resID);
4365         return NULL;
4366     }
4367     sp<Type> t = p->getOrderedTypes()[tid];
4368 
4369     int eid = Res_GETENTRY(resID);
4370     if (eid < 0 || eid >= (int)t->getOrderedConfigs().size()) {
4371         fprintf(stderr, "warning: Entry not found for resource #%08x\n", resID);
4372         return NULL;
4373     }
4374 
4375     sp<ConfigList> c = t->getOrderedConfigs()[eid];
4376     if (c == NULL) {
4377         fprintf(stderr, "warning: Entry not found for resource #%08x\n", resID);
4378         return NULL;
4379     }
4380 
4381     ConfigDescription cdesc;
4382     if (config) cdesc = *config;
4383     sp<Entry> e = c->getEntries().valueFor(cdesc);
4384     if (c == NULL) {
4385         fprintf(stderr, "warning: Entry configuration not found for resource #%08x\n", resID);
4386         return NULL;
4387     }
4388 
4389     return e;
4390 }
4391 
getItem(uint32_t resID,uint32_t attrID) const4392 const ResourceTable::Item* ResourceTable::getItem(uint32_t resID, uint32_t attrID) const
4393 {
4394     sp<const Entry> e = getEntry(resID);
4395     if (e == NULL) {
4396         return NULL;
4397     }
4398 
4399     const size_t N = e->getBag().size();
4400     for (size_t i=0; i<N; i++) {
4401         const Item& it = e->getBag().valueAt(i);
4402         if (it.bagKeyId == 0) {
4403             fprintf(stderr, "warning: ID not yet assigned to '%s' in bag '%s'\n",
4404                     String8(e->getName()).c_str(),
4405                     String8(e->getBag().keyAt(i)).c_str());
4406         }
4407         if (it.bagKeyId == attrID) {
4408             return &it;
4409         }
4410     }
4411 
4412     return NULL;
4413 }
4414 
getItemValue(uint32_t resID,uint32_t attrID,Res_value * outValue)4415 bool ResourceTable::getItemValue(
4416     uint32_t resID, uint32_t attrID, Res_value* outValue)
4417 {
4418     const Item* item = getItem(resID, attrID);
4419 
4420     bool res = false;
4421     if (item != NULL) {
4422         if (item->evaluating) {
4423             sp<const Entry> e = getEntry(resID);
4424             const size_t N = e->getBag().size();
4425             size_t i;
4426             for (i=0; i<N; i++) {
4427                 if (&e->getBag().valueAt(i) == item) {
4428                     break;
4429                 }
4430             }
4431             fprintf(stderr, "warning: Circular reference detected in key '%s' of bag '%s'\n",
4432                     String8(e->getName()).c_str(),
4433                     String8(e->getBag().keyAt(i)).c_str());
4434             return false;
4435         }
4436         item->evaluating = true;
4437         res = stringToValue(outValue, NULL, item->value, false, false, item->bagKeyId);
4438         if (kIsDebug) {
4439             if (res) {
4440                 printf("getItemValue of #%08x[#%08x] (%s): type=#%08x, data=#%08x\n",
4441                        resID, attrID, String8(getEntry(resID)->getName()).c_str(),
4442                        outValue->dataType, outValue->data);
4443             } else {
4444                 printf("getItemValue of #%08x[#%08x]: failed\n",
4445                        resID, attrID);
4446             }
4447         }
4448         item->evaluating = false;
4449     }
4450     return res;
4451 }
4452 
4453 /**
4454  * Returns the SDK version at which the attribute was
4455  * made public, or -1 if the resource ID is not an attribute
4456  * or is not public.
4457  */
getPublicAttributeSdkLevel(uint32_t attrId) const4458 int ResourceTable::getPublicAttributeSdkLevel(uint32_t attrId) const {
4459     if (Res_GETPACKAGE(attrId) + 1 != 0x01 || Res_GETTYPE(attrId) + 1 != 0x01) {
4460         return -1;
4461     }
4462 
4463     uint32_t specFlags;
4464     if (!mAssets->getIncludedResources().getResourceFlags(attrId, &specFlags)) {
4465         return -1;
4466     }
4467 
4468     if ((specFlags & ResTable_typeSpec::SPEC_PUBLIC) == 0) {
4469         return -1;
4470     }
4471 
4472     const size_t entryId = Res_GETENTRY(attrId);
4473     if (entryId <= 0x021c) {
4474         return 1;
4475     } else if (entryId <= 0x021d) {
4476         return 2;
4477     } else if (entryId <= 0x0269) {
4478         return SDK_CUPCAKE;
4479     } else if (entryId <= 0x028d) {
4480         return SDK_DONUT;
4481     } else if (entryId <= 0x02ad) {
4482         return SDK_ECLAIR;
4483     } else if (entryId <= 0x02b3) {
4484         return SDK_ECLAIR_0_1;
4485     } else if (entryId <= 0x02b5) {
4486         return SDK_ECLAIR_MR1;
4487     } else if (entryId <= 0x02bd) {
4488         return SDK_FROYO;
4489     } else if (entryId <= 0x02cb) {
4490         return SDK_GINGERBREAD;
4491     } else if (entryId <= 0x0361) {
4492         return SDK_HONEYCOMB;
4493     } else if (entryId <= 0x0366) {
4494         return SDK_HONEYCOMB_MR1;
4495     } else if (entryId <= 0x03a6) {
4496         return SDK_HONEYCOMB_MR2;
4497     } else if (entryId <= 0x03ae) {
4498         return SDK_JELLY_BEAN;
4499     } else if (entryId <= 0x03cc) {
4500         return SDK_JELLY_BEAN_MR1;
4501     } else if (entryId <= 0x03da) {
4502         return SDK_JELLY_BEAN_MR2;
4503     } else if (entryId <= 0x03f1) {
4504         return SDK_KITKAT;
4505     } else if (entryId <= 0x03f6) {
4506         return SDK_KITKAT_WATCH;
4507     } else if (entryId <= 0x04ce) {
4508         return SDK_LOLLIPOP;
4509     } else {
4510         // Anything else is marked as defined in
4511         // SDK_LOLLIPOP_MR1 since after this
4512         // version no attribute compat work
4513         // needs to be done.
4514         return SDK_LOLLIPOP_MR1;
4515     }
4516 }
4517 
4518 /**
4519  * First check the Manifest, then check the command line flag.
4520  */
getMinSdkVersion(const Bundle * bundle)4521 static int getMinSdkVersion(const Bundle* bundle) {
4522     if (bundle->getManifestMinSdkVersion() != NULL && strlen(bundle->getManifestMinSdkVersion()) > 0) {
4523         return atoi(bundle->getManifestMinSdkVersion());
4524     } else if (bundle->getMinSdkVersion() != NULL && strlen(bundle->getMinSdkVersion()) > 0) {
4525         return atoi(bundle->getMinSdkVersion());
4526     }
4527     return 0;
4528 }
4529 
shouldGenerateVersionedResource(const sp<ResourceTable::ConfigList> & configList,const ConfigDescription & sourceConfig,const int sdkVersionToGenerate)4530 bool ResourceTable::shouldGenerateVersionedResource(
4531         const sp<ResourceTable::ConfigList>& configList,
4532         const ConfigDescription& sourceConfig,
4533         const int sdkVersionToGenerate) {
4534     assert(sdkVersionToGenerate > sourceConfig.sdkVersion);
4535     assert(configList != NULL);
4536     const DefaultKeyedVector<ConfigDescription, sp<ResourceTable::Entry>>& entries
4537             = configList->getEntries();
4538     ssize_t idx = entries.indexOfKey(sourceConfig);
4539 
4540     // The source config came from this list, so it should be here.
4541     assert(idx >= 0);
4542 
4543     // The next configuration either only varies in sdkVersion, or it is completely different
4544     // and therefore incompatible. If it is incompatible, we must generate the versioned resource.
4545 
4546     // NOTE: The ordering of configurations takes sdkVersion as higher precedence than other
4547     // qualifiers, so we need to iterate through the entire list to be sure there
4548     // are no higher sdk level versions of this resource.
4549     ConfigDescription tempConfig(sourceConfig);
4550     for (size_t i = static_cast<size_t>(idx) + 1; i < entries.size(); i++) {
4551         const ConfigDescription& nextConfig = entries.keyAt(i);
4552         tempConfig.sdkVersion = nextConfig.sdkVersion;
4553         if (tempConfig == nextConfig) {
4554             // The two configs are the same, check the sdk version.
4555             return sdkVersionToGenerate < nextConfig.sdkVersion;
4556         }
4557     }
4558 
4559     // No match was found, so we should generate the versioned resource.
4560     return true;
4561 }
4562 
4563 /**
4564  * Modifies the entries in the resource table to account for compatibility
4565  * issues with older versions of Android.
4566  *
4567  * This primarily handles the issue of private/public attribute clashes
4568  * in framework resources.
4569  *
4570  * AAPT has traditionally assigned resource IDs to public attributes,
4571  * and then followed those public definitions with private attributes.
4572  *
4573  * --- PUBLIC ---
4574  * | 0x01010234 | attr/color
4575  * | 0x01010235 | attr/background
4576  *
4577  * --- PRIVATE ---
4578  * | 0x01010236 | attr/secret
4579  * | 0x01010237 | attr/shhh
4580  *
4581  * Each release, when attributes are added, they take the place of the private
4582  * attributes and the private attributes are shifted down again.
4583  *
4584  * --- PUBLIC ---
4585  * | 0x01010234 | attr/color
4586  * | 0x01010235 | attr/background
4587  * | 0x01010236 | attr/shinyNewAttr
4588  * | 0x01010237 | attr/highlyValuedFeature
4589  *
4590  * --- PRIVATE ---
4591  * | 0x01010238 | attr/secret
4592  * | 0x01010239 | attr/shhh
4593  *
4594  * Platform code may look for private attributes set in a theme. If an app
4595  * compiled against a newer version of the platform uses a new public
4596  * attribute that happens to have the same ID as the private attribute
4597  * the older platform is expecting, then the behavior is undefined.
4598  *
4599  * We get around this by detecting any newly defined attributes (in L),
4600  * copy the resource into a -v21 qualified resource, and delete the
4601  * attribute from the original resource. This ensures that older platforms
4602  * don't see the new attribute, but when running on L+ platforms, the
4603  * attribute will be respected.
4604  */
modifyForCompat(const Bundle * bundle)4605 status_t ResourceTable::modifyForCompat(const Bundle* bundle) {
4606     const int minSdk = getMinSdkVersion(bundle);
4607     if (minSdk >= SDK_LOLLIPOP_MR1) {
4608         // Lollipop MR1 and up handles public attributes differently, no
4609         // need to do any compat modifications.
4610         return NO_ERROR;
4611     }
4612 
4613     const String16 attr16("attr");
4614 
4615     const size_t packageCount = mOrderedPackages.size();
4616     for (size_t pi = 0; pi < packageCount; pi++) {
4617         sp<Package> p = mOrderedPackages.itemAt(pi);
4618         if (p == NULL || p->getTypes().size() == 0) {
4619             // Empty, skip!
4620             continue;
4621         }
4622 
4623         const size_t typeCount = p->getOrderedTypes().size();
4624         for (size_t ti = 0; ti < typeCount; ti++) {
4625             sp<Type> t = p->getOrderedTypes().itemAt(ti);
4626             if (t == NULL) {
4627                 continue;
4628             }
4629 
4630             const size_t configCount = t->getOrderedConfigs().size();
4631             for (size_t ci = 0; ci < configCount; ci++) {
4632                 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
4633                 if (c == NULL) {
4634                     continue;
4635                 }
4636 
4637                 Vector<key_value_pair_t<ConfigDescription, sp<Entry> > > entriesToAdd;
4638                 const DefaultKeyedVector<ConfigDescription, sp<Entry> >& entries =
4639                         c->getEntries();
4640                 const size_t entryCount = entries.size();
4641                 for (size_t ei = 0; ei < entryCount; ei++) {
4642                     const sp<Entry>& e = entries.valueAt(ei);
4643                     if (e == NULL || e->getType() != Entry::TYPE_BAG) {
4644                         continue;
4645                     }
4646 
4647                     const ConfigDescription& config = entries.keyAt(ei);
4648                     if (config.sdkVersion >= SDK_LOLLIPOP_MR1) {
4649                         continue;
4650                     }
4651 
4652                     KeyedVector<int, Vector<String16> > attributesToRemove;
4653                     const KeyedVector<String16, Item>& bag = e->getBag();
4654                     const size_t bagCount = bag.size();
4655                     for (size_t bi = 0; bi < bagCount; bi++) {
4656                         const uint32_t attrId = getResId(bag.keyAt(bi), &attr16);
4657                         const int sdkLevel = getPublicAttributeSdkLevel(attrId);
4658                         if (sdkLevel > 1 && sdkLevel > config.sdkVersion && sdkLevel > minSdk) {
4659                             AaptUtil::appendValue(attributesToRemove, sdkLevel, bag.keyAt(bi));
4660                         }
4661                     }
4662 
4663                     if (attributesToRemove.isEmpty()) {
4664                         continue;
4665                     }
4666 
4667                     const size_t sdkCount = attributesToRemove.size();
4668                     for (size_t i = 0; i < sdkCount; i++) {
4669                         const int sdkLevel = attributesToRemove.keyAt(i);
4670 
4671                         if (!shouldGenerateVersionedResource(c, config, sdkLevel)) {
4672                             // There is a style that will override this generated one.
4673                             continue;
4674                         }
4675 
4676                         // Duplicate the entry under the same configuration
4677                         // but with sdkVersion == sdkLevel.
4678                         ConfigDescription newConfig(config);
4679                         newConfig.sdkVersion = sdkLevel;
4680 
4681                         sp<Entry> newEntry = new Entry(*e);
4682 
4683                         // Remove all items that have a higher SDK level than
4684                         // the one we are synthesizing.
4685                         for (size_t j = 0; j < sdkCount; j++) {
4686                             if (j == i) {
4687                                 continue;
4688                             }
4689 
4690                             if (attributesToRemove.keyAt(j) > sdkLevel) {
4691                                 const size_t attrCount = attributesToRemove[j].size();
4692                                 for (size_t k = 0; k < attrCount; k++) {
4693                                     newEntry->removeFromBag(attributesToRemove[j][k]);
4694                                 }
4695                             }
4696                         }
4697 
4698                         entriesToAdd.add(key_value_pair_t<ConfigDescription, sp<Entry> >(
4699                                 newConfig, newEntry));
4700                     }
4701 
4702                     // Remove the attribute from the original.
4703                     for (size_t i = 0; i < attributesToRemove.size(); i++) {
4704                         for (size_t j = 0; j < attributesToRemove[i].size(); j++) {
4705                             e->removeFromBag(attributesToRemove[i][j]);
4706                         }
4707                     }
4708                 }
4709 
4710                 const size_t entriesToAddCount = entriesToAdd.size();
4711                 for (size_t i = 0; i < entriesToAddCount; i++) {
4712                     assert(entries.indexOfKey(entriesToAdd[i].key) < 0);
4713 
4714                     if (bundle->getVerbose()) {
4715                         entriesToAdd[i].value->getPos()
4716                                 .printf("using v%d attributes; synthesizing resource %s:%s/%s for configuration %s.",
4717                                         entriesToAdd[i].key.sdkVersion,
4718                                         String8(p->getName()).c_str(),
4719                                         String8(t->getName()).c_str(),
4720                                         String8(entriesToAdd[i].value->getName()).c_str(),
4721                                         entriesToAdd[i].key.toString().c_str());
4722                     }
4723 
4724                     sp<Entry> newEntry = t->getEntry(c->getName(),
4725                             entriesToAdd[i].value->getPos(),
4726                             &entriesToAdd[i].key);
4727 
4728                     *newEntry = *entriesToAdd[i].value;
4729                 }
4730             }
4731         }
4732     }
4733     return NO_ERROR;
4734 }
4735 
4736 const String16 kTransitionElements[] = {
4737     String16("fade"),
4738     String16("changeBounds"),
4739     String16("slide"),
4740     String16("explode"),
4741     String16("changeImageTransform"),
4742     String16("changeTransform"),
4743     String16("changeClipBounds"),
4744     String16("autoTransition"),
4745     String16("recolor"),
4746     String16("changeScroll"),
4747     String16("transitionSet"),
4748     String16("transition"),
4749     String16("transitionManager"),
4750 };
4751 
IsTransitionElement(const String16 & name)4752 static bool IsTransitionElement(const String16& name) {
4753     for (int i = 0, size = sizeof(kTransitionElements) / sizeof(kTransitionElements[0]);
4754          i < size; ++i) {
4755         if (name == kTransitionElements[i]) {
4756             return true;
4757         }
4758     }
4759     return false;
4760 }
4761 
versionForCompat(const Bundle * bundle,const String16 & resourceName,const sp<AaptFile> & target,const sp<XMLNode> & root)4762 bool ResourceTable::versionForCompat(const Bundle* bundle, const String16& resourceName,
4763                                          const sp<AaptFile>& target, const sp<XMLNode>& root) {
4764     XMLNode* node = root.get();
4765     while (node->getType() != XMLNode::TYPE_ELEMENT) {
4766         // We're assuming the root element is what we're looking for, which can only be under a
4767         // bunch of namespace declarations.
4768         if (node->getChildren().size() != 1) {
4769           // Not sure what to do, bail.
4770           return false;
4771         }
4772         node = node->getChildren().itemAt(0).get();
4773     }
4774 
4775     if (node->getElementNamespace().size() != 0) {
4776         // Not something we care about.
4777         return false;
4778     }
4779 
4780     int versionedSdk = 0;
4781     if (node->getElementName() == String16("adaptive-icon")) {
4782         versionedSdk = SDK_O;
4783     }
4784 
4785     const int minSdkVersion = getMinSdkVersion(bundle);
4786     const ConfigDescription config(target->getGroupEntry().toParams());
4787     if (versionedSdk <= minSdkVersion || versionedSdk <= config.sdkVersion) {
4788         return false;
4789     }
4790 
4791     sp<ConfigList> cl = getConfigList(String16(mAssets->getPackage()),
4792             String16(target->getResourceType()), resourceName);
4793     if (!shouldGenerateVersionedResource(cl, config, versionedSdk)) {
4794         return false;
4795     }
4796 
4797     // Remove the original entry.
4798     cl->removeEntry(config);
4799 
4800     // We need to wholesale version this file.
4801     ConfigDescription newConfig(config);
4802     newConfig.sdkVersion = versionedSdk;
4803     sp<AaptFile> newFile = new AaptFile(target->getSourceFile(),
4804             AaptGroupEntry(newConfig), target->getResourceType());
4805     String8 resPath = String8::format("res/%s/%s.xml",
4806             newFile->getGroupEntry().toDirName(target->getResourceType()).c_str(),
4807             String8(resourceName).c_str());
4808     convertToResPath(resPath);
4809 
4810     // Add a resource table entry.
4811     addEntry(SourcePos(),
4812             String16(mAssets->getPackage()),
4813             String16(target->getResourceType()),
4814             resourceName,
4815             String16(resPath),
4816             NULL,
4817             &newConfig);
4818 
4819     // Schedule this to be compiled.
4820     CompileResourceWorkItem item;
4821     item.resourceName = resourceName;
4822     item.resPath = resPath;
4823     item.file = newFile;
4824     item.xmlRoot = root->clone();
4825     item.needsCompiling = true;
4826     mWorkQueue.push(item);
4827 
4828     // Now mark the old entry as deleted.
4829     return true;
4830 }
4831 
modifyForCompat(const Bundle * bundle,const String16 & resourceName,const sp<AaptFile> & target,const sp<XMLNode> & root)4832 status_t ResourceTable::modifyForCompat(const Bundle* bundle,
4833                                         const String16& resourceName,
4834                                         const sp<AaptFile>& target,
4835                                         const sp<XMLNode>& root) {
4836     const String16 vector16("vector");
4837     const String16 animatedVector16("animated-vector");
4838     const String16 pathInterpolator16("pathInterpolator");
4839     const String16 objectAnimator16("objectAnimator");
4840     const String16 gradient16("gradient");
4841     const String16 animatedSelector16("animated-selector");
4842 
4843     const int minSdk = getMinSdkVersion(bundle);
4844     if (minSdk >= SDK_LOLLIPOP_MR1) {
4845         // Lollipop MR1 and up handles public attributes differently, no
4846         // need to do any compat modifications.
4847         return NO_ERROR;
4848     }
4849 
4850     const ConfigDescription config(target->getGroupEntry().toParams());
4851     if (target->getResourceType() == "" || config.sdkVersion >= SDK_LOLLIPOP_MR1) {
4852         // Skip resources that have no type (AndroidManifest.xml) or are already version qualified
4853         // with v21 or higher.
4854         return NO_ERROR;
4855     }
4856 
4857     sp<XMLNode> newRoot = NULL;
4858     int sdkVersionToGenerate = SDK_LOLLIPOP_MR1;
4859 
4860     Vector<sp<XMLNode> > nodesToVisit;
4861     nodesToVisit.push(root);
4862     while (!nodesToVisit.empty()) {
4863         sp<XMLNode> node = nodesToVisit.top();
4864         nodesToVisit.pop();
4865 
4866         if (bundle->getNoVersionVectors() && (node->getElementName() == vector16 ||
4867                     node->getElementName() == animatedVector16 ||
4868                     node->getElementName() == objectAnimator16 ||
4869                     node->getElementName() == pathInterpolator16 ||
4870                     node->getElementName() == gradient16 ||
4871                     node->getElementName() == animatedSelector16)) {
4872             // We were told not to version vector tags, so skip the children here.
4873             continue;
4874         }
4875 
4876         if (bundle->getNoVersionTransitions() && (IsTransitionElement(node->getElementName()))) {
4877             // We were told not to version transition tags, so skip the children here.
4878             continue;
4879         }
4880 
4881         const Vector<XMLNode::attribute_entry>& attrs = node->getAttributes();
4882         for (size_t i = 0; i < attrs.size(); i++) {
4883             const XMLNode::attribute_entry& attr = attrs[i];
4884             const int sdkLevel = getPublicAttributeSdkLevel(attr.nameResId);
4885             if (sdkLevel > 1 && sdkLevel > config.sdkVersion && sdkLevel > minSdk) {
4886                 if (newRoot == NULL) {
4887                     newRoot = root->clone();
4888                 }
4889 
4890                 // Find the smallest sdk version that we need to synthesize for
4891                 // and do that one. Subsequent versions will be processed on
4892                 // the next pass.
4893                 sdkVersionToGenerate = std::min(sdkLevel, sdkVersionToGenerate);
4894 
4895                 if (bundle->getVerbose()) {
4896                     SourcePos(node->getFilename(), node->getStartLineNumber()).printf(
4897                             "removing attribute %s%s%s from <%s>",
4898                             String8(attr.ns).c_str(),
4899                             (attr.ns.size() == 0 ? "" : ":"),
4900                             String8(attr.name).c_str(),
4901                             String8(node->getElementName()).c_str());
4902                 }
4903                 node->removeAttribute(i);
4904                 i--;
4905             }
4906         }
4907 
4908         // Schedule a visit to the children.
4909         const Vector<sp<XMLNode> >& children = node->getChildren();
4910         const size_t childCount = children.size();
4911         for (size_t i = 0; i < childCount; i++) {
4912             nodesToVisit.push(children[i]);
4913         }
4914     }
4915 
4916     if (newRoot == NULL) {
4917         return NO_ERROR;
4918     }
4919 
4920     // Look to see if we already have an overriding v21 configuration.
4921     sp<ConfigList> cl = getConfigList(String16(mAssets->getPackage()),
4922             String16(target->getResourceType()), resourceName);
4923     if (shouldGenerateVersionedResource(cl, config, sdkVersionToGenerate)) {
4924         // We don't have an overriding entry for v21, so we must duplicate this one.
4925         ConfigDescription newConfig(config);
4926         newConfig.sdkVersion = sdkVersionToGenerate;
4927         sp<AaptFile> newFile = new AaptFile(target->getSourceFile(),
4928                 AaptGroupEntry(newConfig), target->getResourceType());
4929         String8 resPath = String8::format("res/%s/%s.xml",
4930                 newFile->getGroupEntry().toDirName(target->getResourceType()).c_str(),
4931                 String8(resourceName).c_str());
4932         convertToResPath(resPath);
4933 
4934         // Add a resource table entry.
4935         if (bundle->getVerbose()) {
4936             SourcePos(target->getSourceFile(), -1).printf(
4937                     "using v%d attributes; synthesizing resource %s:%s/%s for configuration %s.",
4938                     newConfig.sdkVersion,
4939                     mAssets->getPackage().c_str(),
4940                     newFile->getResourceType().c_str(),
4941                     String8(resourceName).c_str(),
4942                     newConfig.toString().c_str());
4943         }
4944 
4945         addEntry(SourcePos(),
4946                 String16(mAssets->getPackage()),
4947                 String16(target->getResourceType()),
4948                 resourceName,
4949                 String16(resPath),
4950                 NULL,
4951                 &newConfig);
4952 
4953         // Schedule this to be compiled.
4954         CompileResourceWorkItem item;
4955         item.resourceName = resourceName;
4956         item.resPath = resPath;
4957         item.file = newFile;
4958         item.xmlRoot = newRoot;
4959         item.needsCompiling = false;    // This step occurs after we parse/assign, so we don't need
4960                                         // to do it again.
4961         mWorkQueue.push(item);
4962     }
4963     return NO_ERROR;
4964 }
4965 
getDensityVaryingResources(KeyedVector<Symbol,Vector<SymbolDefinition>> & resources)4966 void ResourceTable::getDensityVaryingResources(
4967         KeyedVector<Symbol, Vector<SymbolDefinition> >& resources) {
4968     const ConfigDescription nullConfig;
4969 
4970     const size_t packageCount = mOrderedPackages.size();
4971     for (size_t p = 0; p < packageCount; p++) {
4972         const Vector<sp<Type> >& types = mOrderedPackages[p]->getOrderedTypes();
4973         const size_t typeCount = types.size();
4974         for (size_t t = 0; t < typeCount; t++) {
4975             const sp<Type>& type = types[t];
4976             if (type == NULL) {
4977                 continue;
4978             }
4979 
4980             const Vector<sp<ConfigList> >& configs = type->getOrderedConfigs();
4981             const size_t configCount = configs.size();
4982             for (size_t c = 0; c < configCount; c++) {
4983                 const sp<ConfigList>& configList = configs[c];
4984                 if (configList == NULL) {
4985                     continue;
4986                 }
4987 
4988                 const DefaultKeyedVector<ConfigDescription, sp<Entry> >& configEntries
4989                         = configList->getEntries();
4990                 const size_t configEntryCount = configEntries.size();
4991                 for (size_t ce = 0; ce < configEntryCount; ce++) {
4992                     const sp<Entry>& entry = configEntries.valueAt(ce);
4993                     if (entry == NULL) {
4994                         continue;
4995                     }
4996 
4997                     const ConfigDescription& config = configEntries.keyAt(ce);
4998                     if (AaptConfig::isDensityOnly(config)) {
4999                         // This configuration only varies with regards to density.
5000                         const Symbol symbol(
5001                                 mOrderedPackages[p]->getName(),
5002                                 type->getName(),
5003                                 configList->getName(),
5004                                 getResId(mOrderedPackages[p], types[t],
5005                                          configList->getEntryIndex()));
5006 
5007 
5008                         AaptUtil::appendValue(resources, symbol,
5009                                               SymbolDefinition(symbol, config, entry->getPos()));
5010                     }
5011                 }
5012             }
5013         }
5014     }
5015 }
5016 
buildNamespace(const String16 & package)5017 static String16 buildNamespace(const String16& package) {
5018     return String16("http://schemas.android.com/apk/res/") + package;
5019 }
5020 
findOnlyChildElement(const sp<XMLNode> & parent)5021 static sp<XMLNode> findOnlyChildElement(const sp<XMLNode>& parent) {
5022     const Vector<sp<XMLNode> >& children = parent->getChildren();
5023     sp<XMLNode> onlyChild;
5024     for (size_t i = 0; i < children.size(); i++) {
5025         if (children[i]->getType() != XMLNode::TYPE_CDATA) {
5026             if (onlyChild != NULL) {
5027                 return NULL;
5028             }
5029             onlyChild = children[i];
5030         }
5031     }
5032     return onlyChild;
5033 }
5034 
5035 /**
5036  * Detects use of the `bundle' format and extracts nested resources into their own top level
5037  * resources. The bundle format looks like this:
5038  *
5039  * <!-- res/drawable/bundle.xml -->
5040  * <animated-vector xmlns:aapt="http://schemas.android.com/aapt">
5041  *   <aapt:attr name="android:drawable">
5042  *     <vector android:width="60dp"
5043  *             android:height="60dp">
5044  *       <path android:name="v"
5045  *             android:fillColor="#000000"
5046  *             android:pathData="M300,70 l 0,-70 70,..." />
5047  *     </vector>
5048  *   </aapt:attr>
5049  * </animated-vector>
5050  *
5051  * When AAPT sees the <aapt:attr> tag, it will extract its single element and its children
5052  * into a new high-level resource, assigning it a name and ID. Then value of the `name`
5053  * attribute must be a resource attribute. That resource attribute is inserted into the parent
5054  * with the reference to the extracted resource as the value.
5055  *
5056  * <!-- res/drawable/bundle.xml -->
5057  * <animated-vector android:drawable="@drawable/bundle_1.xml">
5058  * </animated-vector>
5059  *
5060  * <!-- res/drawable/bundle_1.xml -->
5061  * <vector android:width="60dp"
5062  *         android:height="60dp">
5063  *   <path android:name="v"
5064  *         android:fillColor="#000000"
5065  *         android:pathData="M300,70 l 0,-70 70,..." />
5066  * </vector>
5067  */
processBundleFormat(const Bundle * bundle,const String16 & resourceName,const sp<AaptFile> & target,const sp<XMLNode> & root)5068 status_t ResourceTable::processBundleFormat(const Bundle* bundle,
5069                                             const String16& resourceName,
5070                                             const sp<AaptFile>& target,
5071                                             const sp<XMLNode>& root) {
5072     Vector<sp<XMLNode> > namespaces;
5073     if (root->getType() == XMLNode::TYPE_NAMESPACE) {
5074         namespaces.push(root);
5075     }
5076     return processBundleFormatImpl(bundle, resourceName, target, root, &namespaces);
5077 }
5078 
processBundleFormatImpl(const Bundle * bundle,const String16 & resourceName,const sp<AaptFile> & target,const sp<XMLNode> & parent,Vector<sp<XMLNode>> * namespaces)5079 status_t ResourceTable::processBundleFormatImpl(const Bundle* bundle,
5080                                                 const String16& resourceName,
5081                                                 const sp<AaptFile>& target,
5082                                                 const sp<XMLNode>& parent,
5083                                                 Vector<sp<XMLNode> >* namespaces) {
5084     const String16 kAaptNamespaceUri16("http://schemas.android.com/aapt");
5085     const String16 kName16("name");
5086     const String16 kAttr16("attr");
5087     const String16 kAssetPackage16(mAssets->getPackage());
5088 
5089     Vector<sp<XMLNode> >& children = parent->getChildren();
5090     for (size_t i = 0; i < children.size(); i++) {
5091         const sp<XMLNode>& child = children[i];
5092 
5093         if (child->getType() == XMLNode::TYPE_CDATA) {
5094             continue;
5095         } else if (child->getType() == XMLNode::TYPE_NAMESPACE) {
5096             namespaces->push(child);
5097         }
5098 
5099         if (child->getElementNamespace() != kAaptNamespaceUri16 ||
5100                 child->getElementName() != kAttr16) {
5101             status_t result = processBundleFormatImpl(bundle, resourceName, target, child,
5102                                                       namespaces);
5103             if (result != NO_ERROR) {
5104                 return result;
5105             }
5106 
5107             if (child->getType() == XMLNode::TYPE_NAMESPACE) {
5108                 namespaces->pop();
5109             }
5110             continue;
5111         }
5112 
5113         // This is the <aapt:attr> tag. Look for the 'name' attribute.
5114         SourcePos source(child->getFilename(), child->getStartLineNumber());
5115 
5116         sp<XMLNode> nestedRoot = findOnlyChildElement(child);
5117         if (nestedRoot == NULL) {
5118             source.error("<%s:%s> must have exactly one child element",
5119                          String8(child->getElementNamespace()).c_str(),
5120                          String8(child->getElementName()).c_str());
5121             return UNKNOWN_ERROR;
5122         }
5123 
5124         // Find the special attribute 'parent-attr'. This attribute's value contains
5125         // the resource attribute for which this element should be assigned in the parent.
5126         const XMLNode::attribute_entry* attr = child->getAttribute(String16(), kName16);
5127         if (attr == NULL) {
5128             source.error("inline resource definition must specify an attribute via 'name'");
5129             return UNKNOWN_ERROR;
5130         }
5131 
5132         // Parse the attribute name.
5133         const char* errorMsg = NULL;
5134         String16 attrPackage, attrType, attrName;
5135         bool result = ResTable::expandResourceRef(attr->string.c_str(),
5136                                                   attr->string.size(),
5137                                                   &attrPackage, &attrType, &attrName,
5138                                                   &kAttr16, &kAssetPackage16,
5139                                                   &errorMsg, NULL);
5140         if (!result) {
5141             source.error("invalid attribute name for 'name': %s", errorMsg);
5142             return UNKNOWN_ERROR;
5143         }
5144 
5145         if (attrType != kAttr16) {
5146             // The value of the 'name' attribute must be an attribute reference.
5147             source.error("value of 'name' must be an attribute reference.");
5148             return UNKNOWN_ERROR;
5149         }
5150 
5151         // Generate a name for this nested resource and try to add it to the table.
5152         // We do this in a loop because the name may be taken, in which case we will
5153         // increment a suffix until we succeed.
5154         String8 nestedResourceName;
5155         String8 nestedResourcePath;
5156         int suffix = 1;
5157         while (true) {
5158             // This child element will be extracted into its own resource file.
5159             // Generate a name and path for it from its parent.
5160             nestedResourceName = String8::format("%s_%d",
5161                         String8(resourceName).c_str(), suffix++);
5162             nestedResourcePath = String8::format("res/%s/%s.xml",
5163                         target->getGroupEntry().toDirName(target->getResourceType())
5164                                                .c_str(),
5165                         nestedResourceName.c_str());
5166 
5167             // Lookup or create the entry for this name.
5168             sp<Entry> entry = getEntry(kAssetPackage16,
5169                                        String16(target->getResourceType()),
5170                                        String16(nestedResourceName),
5171                                        source,
5172                                        false,
5173                                        &target->getGroupEntry().toParams(),
5174                                        true);
5175             if (entry == NULL) {
5176                 return UNKNOWN_ERROR;
5177             }
5178 
5179             if (entry->getType() == Entry::TYPE_UNKNOWN) {
5180                 // The value for this resource has never been set,
5181                 // meaning we're good!
5182                 entry->setItem(source, String16(nestedResourcePath));
5183                 break;
5184             }
5185 
5186             // We failed (name already exists), so try with a different name
5187             // (increment the suffix).
5188         }
5189 
5190         if (bundle->getVerbose()) {
5191             source.printf("generating nested resource %s:%s/%s",
5192                     mAssets->getPackage().c_str(), target->getResourceType().c_str(),
5193                     nestedResourceName.c_str());
5194         }
5195 
5196         // Build the attribute reference and assign it to the parent.
5197         String16 nestedResourceRef = String16(String8::format("@%s:%s/%s",
5198                     mAssets->getPackage().c_str(), target->getResourceType().c_str(),
5199                     nestedResourceName.c_str()));
5200 
5201         String16 attrNs = buildNamespace(attrPackage);
5202         if (parent->getAttribute(attrNs, attrName) != NULL) {
5203             SourcePos(parent->getFilename(), parent->getStartLineNumber())
5204                     .error("parent of nested resource already defines attribute '%s:%s'",
5205                            String8(attrPackage).c_str(), String8(attrName).c_str());
5206             return UNKNOWN_ERROR;
5207         }
5208 
5209         // Add the reference to the inline resource.
5210         parent->addAttribute(attrNs, attrName, nestedResourceRef);
5211 
5212         // Remove the <aapt:attr> child element from here.
5213         children.removeAt(i);
5214         i--;
5215 
5216         // Append all namespace declarations that we've seen on this branch in the XML tree
5217         // to this resource.
5218         // We do this because the order of namespace declarations and prefix usage is determined
5219         // by the developer and we do not want to override any decisions. Be conservative.
5220         for (size_t nsIndex = namespaces->size(); nsIndex > 0; nsIndex--) {
5221             const sp<XMLNode>& ns = namespaces->itemAt(nsIndex - 1);
5222             sp<XMLNode> newNs = XMLNode::newNamespace(ns->getFilename(), ns->getNamespacePrefix(),
5223                                                       ns->getNamespaceUri());
5224             newNs->addChild(nestedRoot);
5225             nestedRoot = newNs;
5226         }
5227 
5228         // Schedule compilation of the nested resource.
5229         CompileResourceWorkItem workItem;
5230         workItem.resPath = nestedResourcePath;
5231         workItem.resourceName = String16(nestedResourceName);
5232         workItem.xmlRoot = nestedRoot;
5233         workItem.file = new AaptFile(target->getSourceFile(), target->getGroupEntry(),
5234                                      target->getResourceType());
5235         mWorkQueue.push(workItem);
5236     }
5237     return NO_ERROR;
5238 }
5239