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