ResourceTable.cpp revision 8daabceb2efddebe2e7c0b2425ad9f8ef62c0a5c
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 = 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 (map<String16, map<String8, SourcePos> >::iterator nameIter = mLocalizations.begin();
2671         nameIter != mLocalizations.end();
2672         nameIter++) {
2673        const map<String8, SourcePos>& configSrcMap = nameIter->second;
2674
2675        // Look for strings with no default localization
2676        if (configSrcMap.count(defaultLocale) == 0) {
2677            SourcePos().warning("string '%s' has no default translation.",
2678                    String8(nameIter->first).string());
2679            if (mBundle->getVerbose()) {
2680                for (map<String8, SourcePos>::const_iterator locales = configSrcMap.begin();
2681                    locales != configSrcMap.end();
2682                    locales++) {
2683                    locales->second.printf("locale %s found", locales->first.string());
2684                }
2685            }
2686            // !!! TODO: throw an error here in some circumstances
2687        }
2688
2689        // Check that all requested localizations are present for this string
2690        if (mBundle->getConfigurations().size() > 0 && mBundle->getRequireLocalization()) {
2691            const char* allConfigs = mBundle->getConfigurations().string();
2692            const char* start = allConfigs;
2693            const char* comma;
2694
2695            set<String8> missingConfigs;
2696            AaptLocaleValue locale;
2697            do {
2698                String8 config;
2699                comma = strchr(start, ',');
2700                if (comma != NULL) {
2701                    config.setTo(start, comma - start);
2702                    start = comma + 1;
2703                } else {
2704                    config.setTo(start);
2705                }
2706
2707                if (!locale.initFromFilterString(config)) {
2708                    continue;
2709                }
2710
2711                // don't bother with the pseudolocale "en_XA" or "ar_XB"
2712                if (config != "en_XA" && config != "ar_XB") {
2713                    if (configSrcMap.find(config) == configSrcMap.end()) {
2714                        // okay, no specific localization found.  it's possible that we are
2715                        // requiring a specific regional localization [e.g. de_DE] but there is an
2716                        // available string in the generic language localization [e.g. de];
2717                        // consider that string to have fulfilled the localization requirement.
2718                        String8 region(config.string(), 2);
2719                        if (configSrcMap.find(region) == configSrcMap.end() &&
2720                                configSrcMap.count(defaultLocale) == 0) {
2721                            missingConfigs.insert(config);
2722                        }
2723                    }
2724                }
2725            } while (comma != NULL);
2726
2727            if (!missingConfigs.empty()) {
2728                String8 configStr;
2729                for (set<String8>::iterator iter = missingConfigs.begin();
2730                     iter != missingConfigs.end();
2731                     iter++) {
2732                    configStr.appendFormat(" %s", iter->string());
2733                }
2734                SourcePos().warning("string '%s' is missing %u required localizations:%s",
2735                        String8(nameIter->first).string(),
2736                        (unsigned int)missingConfigs.size(),
2737                        configStr.string());
2738            }
2739        }
2740    }
2741
2742    return err;
2743}
2744
2745status_t ResourceTable::flatten(Bundle* bundle, const sp<const ResourceFilter>& filter,
2746        const sp<AaptFile>& dest,
2747        const bool isBase)
2748{
2749    const ConfigDescription nullConfig;
2750
2751    const size_t N = mOrderedPackages.size();
2752    size_t pi;
2753
2754    const static String16 mipmap16("mipmap");
2755
2756    bool useUTF8 = !bundle->getUTF16StringsOption();
2757
2758    // The libraries this table references.
2759    Vector<sp<Package> > libraryPackages;
2760    const ResTable& table = mAssets->getIncludedResources();
2761    const size_t basePackageCount = table.getBasePackageCount();
2762    for (size_t i = 0; i < basePackageCount; i++) {
2763        size_t packageId = table.getBasePackageId(i);
2764        String16 packageName(table.getBasePackageName(i));
2765        if (packageId > 0x01 && packageId != 0x7f &&
2766                packageName != String16("android")) {
2767            libraryPackages.add(sp<Package>(new Package(packageName, packageId)));
2768        }
2769    }
2770
2771    // Iterate through all data, collecting all values (strings,
2772    // references, etc).
2773    StringPool valueStrings(useUTF8);
2774    Vector<sp<Entry> > allEntries;
2775    for (pi=0; pi<N; pi++) {
2776        sp<Package> p = mOrderedPackages.itemAt(pi);
2777        if (p->getTypes().size() == 0) {
2778            continue;
2779        }
2780
2781        StringPool typeStrings(useUTF8);
2782        StringPool keyStrings(useUTF8);
2783
2784        ssize_t stringsAdded = 0;
2785        const size_t N = p->getOrderedTypes().size();
2786        for (size_t ti=0; ti<N; ti++) {
2787            sp<Type> t = p->getOrderedTypes().itemAt(ti);
2788            if (t == NULL) {
2789                typeStrings.add(String16("<empty>"), false);
2790                stringsAdded++;
2791                continue;
2792            }
2793
2794            while (stringsAdded < t->getIndex() - 1) {
2795                typeStrings.add(String16("<empty>"), false);
2796                stringsAdded++;
2797            }
2798
2799            const String16 typeName(t->getName());
2800            typeStrings.add(typeName, false);
2801            stringsAdded++;
2802
2803            // This is a hack to tweak the sorting order of the final strings,
2804            // to put stuff that is generally not language-specific first.
2805            String8 configTypeName(typeName);
2806            if (configTypeName == "drawable" || configTypeName == "layout"
2807                    || configTypeName == "color" || configTypeName == "anim"
2808                    || configTypeName == "interpolator" || configTypeName == "animator"
2809                    || configTypeName == "xml" || configTypeName == "menu"
2810                    || configTypeName == "mipmap" || configTypeName == "raw") {
2811                configTypeName = "1complex";
2812            } else {
2813                configTypeName = "2value";
2814            }
2815
2816            // mipmaps don't get filtered, so they will
2817            // allways end up in the base. Make sure they
2818            // don't end up in a split.
2819            if (typeName == mipmap16 && !isBase) {
2820                continue;
2821            }
2822
2823            const bool filterable = (typeName != mipmap16);
2824
2825            const size_t N = t->getOrderedConfigs().size();
2826            for (size_t ci=0; ci<N; ci++) {
2827                sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2828                if (c == NULL) {
2829                    continue;
2830                }
2831                const size_t N = c->getEntries().size();
2832                for (size_t ei=0; ei<N; ei++) {
2833                    ConfigDescription config = c->getEntries().keyAt(ei);
2834                    if (filterable && !filter->match(config)) {
2835                        continue;
2836                    }
2837                    sp<Entry> e = c->getEntries().valueAt(ei);
2838                    if (e == NULL) {
2839                        continue;
2840                    }
2841                    e->setNameIndex(keyStrings.add(e->getName(), true));
2842
2843                    // If this entry has no values for other configs,
2844                    // and is the default config, then it is special.  Otherwise
2845                    // we want to add it with the config info.
2846                    ConfigDescription* valueConfig = NULL;
2847                    if (N != 1 || config == nullConfig) {
2848                        valueConfig = &config;
2849                    }
2850
2851                    status_t err = e->prepareFlatten(&valueStrings, this,
2852                            &configTypeName, &config);
2853                    if (err != NO_ERROR) {
2854                        return err;
2855                    }
2856                    allEntries.add(e);
2857                }
2858            }
2859        }
2860
2861        p->setTypeStrings(typeStrings.createStringBlock());
2862        p->setKeyStrings(keyStrings.createStringBlock());
2863    }
2864
2865    if (bundle->getOutputAPKFile() != NULL) {
2866        // Now we want to sort the value strings for better locality.  This will
2867        // cause the positions of the strings to change, so we need to go back
2868        // through out resource entries and update them accordingly.  Only need
2869        // to do this if actually writing the output file.
2870        valueStrings.sortByConfig();
2871        for (pi=0; pi<allEntries.size(); pi++) {
2872            allEntries[pi]->remapStringValue(&valueStrings);
2873        }
2874    }
2875
2876    ssize_t strAmt = 0;
2877
2878    // Now build the array of package chunks.
2879    Vector<sp<AaptFile> > flatPackages;
2880    for (pi=0; pi<N; pi++) {
2881        sp<Package> p = mOrderedPackages.itemAt(pi);
2882        if (p->getTypes().size() == 0) {
2883            // Empty, skip!
2884            continue;
2885        }
2886
2887        const size_t N = p->getTypeStrings().size();
2888
2889        const size_t baseSize = sizeof(ResTable_package);
2890
2891        // Start the package data.
2892        sp<AaptFile> data = new AaptFile(String8(), AaptGroupEntry(), String8());
2893        ResTable_package* header = (ResTable_package*)data->editData(baseSize);
2894        if (header == NULL) {
2895            fprintf(stderr, "ERROR: out of memory creating ResTable_package\n");
2896            return NO_MEMORY;
2897        }
2898        memset(header, 0, sizeof(*header));
2899        header->header.type = htods(RES_TABLE_PACKAGE_TYPE);
2900        header->header.headerSize = htods(sizeof(*header));
2901        header->id = htodl(static_cast<uint32_t>(p->getAssignedId()));
2902        strcpy16_htod(header->name, p->getName().string());
2903
2904        // Write the string blocks.
2905        const size_t typeStringsStart = data->getSize();
2906        sp<AaptFile> strFile = p->getTypeStringsData();
2907        ssize_t amt = data->writeData(strFile->getData(), strFile->getSize());
2908        if (kPrintStringMetrics) {
2909            fprintf(stderr, "**** type strings: %zd\n", SSIZE(amt));
2910        }
2911        strAmt += amt;
2912        if (amt < 0) {
2913            return amt;
2914        }
2915        const size_t keyStringsStart = data->getSize();
2916        strFile = p->getKeyStringsData();
2917        amt = data->writeData(strFile->getData(), strFile->getSize());
2918        if (kPrintStringMetrics) {
2919            fprintf(stderr, "**** key strings: %zd\n", SSIZE(amt));
2920        }
2921        strAmt += amt;
2922        if (amt < 0) {
2923            return amt;
2924        }
2925
2926        if (isBase) {
2927            status_t err = flattenLibraryTable(data, libraryPackages);
2928            if (err != NO_ERROR) {
2929                fprintf(stderr, "ERROR: failed to write library table\n");
2930                return err;
2931            }
2932        }
2933
2934        // Build the type chunks inside of this package.
2935        for (size_t ti=0; ti<N; ti++) {
2936            // Retrieve them in the same order as the type string block.
2937            size_t len;
2938            String16 typeName(p->getTypeStrings().stringAt(ti, &len));
2939            sp<Type> t = p->getTypes().valueFor(typeName);
2940            LOG_ALWAYS_FATAL_IF(t == NULL && typeName != String16("<empty>"),
2941                                "Type name %s not found",
2942                                String8(typeName).string());
2943            if (t == NULL) {
2944                continue;
2945            }
2946            const bool filterable = (typeName != mipmap16);
2947            const bool skipEntireType = (typeName == mipmap16 && !isBase);
2948
2949            const size_t N = t != NULL ? t->getOrderedConfigs().size() : 0;
2950
2951            // Until a non-NO_ENTRY value has been written for a resource,
2952            // that resource is invalid; validResources[i] represents
2953            // the item at t->getOrderedConfigs().itemAt(i).
2954            Vector<bool> validResources;
2955            validResources.insertAt(false, 0, N);
2956
2957            // First write the typeSpec chunk, containing information about
2958            // each resource entry in this type.
2959            {
2960                const size_t typeSpecSize = sizeof(ResTable_typeSpec) + sizeof(uint32_t)*N;
2961                const size_t typeSpecStart = data->getSize();
2962                ResTable_typeSpec* tsHeader = (ResTable_typeSpec*)
2963                    (((uint8_t*)data->editData(typeSpecStart+typeSpecSize)) + typeSpecStart);
2964                if (tsHeader == NULL) {
2965                    fprintf(stderr, "ERROR: out of memory creating ResTable_typeSpec\n");
2966                    return NO_MEMORY;
2967                }
2968                memset(tsHeader, 0, sizeof(*tsHeader));
2969                tsHeader->header.type = htods(RES_TABLE_TYPE_SPEC_TYPE);
2970                tsHeader->header.headerSize = htods(sizeof(*tsHeader));
2971                tsHeader->header.size = htodl(typeSpecSize);
2972                tsHeader->id = ti+1;
2973                tsHeader->entryCount = htodl(N);
2974
2975                uint32_t* typeSpecFlags = (uint32_t*)
2976                    (((uint8_t*)data->editData())
2977                        + typeSpecStart + sizeof(ResTable_typeSpec));
2978                memset(typeSpecFlags, 0, sizeof(uint32_t)*N);
2979
2980                for (size_t ei=0; ei<N; ei++) {
2981                    sp<ConfigList> cl = t->getOrderedConfigs().itemAt(ei);
2982                    if (cl->getPublic()) {
2983                        typeSpecFlags[ei] |= htodl(ResTable_typeSpec::SPEC_PUBLIC);
2984                    }
2985
2986                    if (skipEntireType) {
2987                        continue;
2988                    }
2989
2990                    const size_t CN = cl->getEntries().size();
2991                    for (size_t ci=0; ci<CN; ci++) {
2992                        if (filterable && !filter->match(cl->getEntries().keyAt(ci))) {
2993                            continue;
2994                        }
2995                        for (size_t cj=ci+1; cj<CN; cj++) {
2996                            if (filterable && !filter->match(cl->getEntries().keyAt(cj))) {
2997                                continue;
2998                            }
2999                            typeSpecFlags[ei] |= htodl(
3000                                cl->getEntries().keyAt(ci).diff(cl->getEntries().keyAt(cj)));
3001                        }
3002                    }
3003                }
3004            }
3005
3006            if (skipEntireType) {
3007                continue;
3008            }
3009
3010            // We need to write one type chunk for each configuration for
3011            // which we have entries in this type.
3012            const size_t NC = t->getUniqueConfigs().size();
3013
3014            const size_t typeSize = sizeof(ResTable_type) + sizeof(uint32_t)*N;
3015
3016            for (size_t ci=0; ci<NC; ci++) {
3017                ConfigDescription config = t->getUniqueConfigs().itemAt(ci);
3018
3019                if (kIsDebug) {
3020                    printf("Writing config %zu config: imsi:%d/%d lang:%c%c cnt:%c%c "
3021                        "orien:%d ui:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d "
3022                        "sw%ddp w%ddp h%ddp layout:%d\n",
3023                        ti + 1,
3024                        config.mcc, config.mnc,
3025                        config.language[0] ? config.language[0] : '-',
3026                        config.language[1] ? config.language[1] : '-',
3027                        config.country[0] ? config.country[0] : '-',
3028                        config.country[1] ? config.country[1] : '-',
3029                        config.orientation,
3030                        config.uiMode,
3031                        config.touchscreen,
3032                        config.density,
3033                        config.keyboard,
3034                        config.inputFlags,
3035                        config.navigation,
3036                        config.screenWidth,
3037                        config.screenHeight,
3038                        config.smallestScreenWidthDp,
3039                        config.screenWidthDp,
3040                        config.screenHeightDp,
3041                        config.screenLayout);
3042                }
3043
3044                if (filterable && !filter->match(config)) {
3045                    continue;
3046                }
3047
3048                const size_t typeStart = data->getSize();
3049
3050                ResTable_type* tHeader = (ResTable_type*)
3051                    (((uint8_t*)data->editData(typeStart+typeSize)) + typeStart);
3052                if (tHeader == NULL) {
3053                    fprintf(stderr, "ERROR: out of memory creating ResTable_type\n");
3054                    return NO_MEMORY;
3055                }
3056
3057                memset(tHeader, 0, sizeof(*tHeader));
3058                tHeader->header.type = htods(RES_TABLE_TYPE_TYPE);
3059                tHeader->header.headerSize = htods(sizeof(*tHeader));
3060                tHeader->id = ti+1;
3061                tHeader->entryCount = htodl(N);
3062                tHeader->entriesStart = htodl(typeSize);
3063                tHeader->config = config;
3064                if (kIsDebug) {
3065                    printf("Writing type %zu config: imsi:%d/%d lang:%c%c cnt:%c%c "
3066                        "orien:%d ui:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d "
3067                        "sw%ddp w%ddp h%ddp layout:%d\n",
3068                        ti + 1,
3069                        tHeader->config.mcc, tHeader->config.mnc,
3070                        tHeader->config.language[0] ? tHeader->config.language[0] : '-',
3071                        tHeader->config.language[1] ? tHeader->config.language[1] : '-',
3072                        tHeader->config.country[0] ? tHeader->config.country[0] : '-',
3073                        tHeader->config.country[1] ? tHeader->config.country[1] : '-',
3074                        tHeader->config.orientation,
3075                        tHeader->config.uiMode,
3076                        tHeader->config.touchscreen,
3077                        tHeader->config.density,
3078                        tHeader->config.keyboard,
3079                        tHeader->config.inputFlags,
3080                        tHeader->config.navigation,
3081                        tHeader->config.screenWidth,
3082                        tHeader->config.screenHeight,
3083                        tHeader->config.smallestScreenWidthDp,
3084                        tHeader->config.screenWidthDp,
3085                        tHeader->config.screenHeightDp,
3086                        tHeader->config.screenLayout);
3087                }
3088                tHeader->config.swapHtoD();
3089
3090                // Build the entries inside of this type.
3091                for (size_t ei=0; ei<N; ei++) {
3092                    sp<ConfigList> cl = t->getOrderedConfigs().itemAt(ei);
3093                    sp<Entry> e = cl->getEntries().valueFor(config);
3094
3095                    // Set the offset for this entry in its type.
3096                    uint32_t* index = (uint32_t*)
3097                        (((uint8_t*)data->editData())
3098                            + typeStart + sizeof(ResTable_type));
3099                    if (e != NULL) {
3100                        index[ei] = htodl(data->getSize()-typeStart-typeSize);
3101
3102                        // Create the entry.
3103                        ssize_t amt = e->flatten(bundle, data, cl->getPublic());
3104                        if (amt < 0) {
3105                            return amt;
3106                        }
3107                        validResources.editItemAt(ei) = true;
3108                    } else {
3109                        index[ei] = htodl(ResTable_type::NO_ENTRY);
3110                    }
3111                }
3112
3113                // Fill in the rest of the type information.
3114                tHeader = (ResTable_type*)
3115                    (((uint8_t*)data->editData()) + typeStart);
3116                tHeader->header.size = htodl(data->getSize()-typeStart);
3117            }
3118
3119            // If we're building splits, then each invocation of the flattening
3120            // step will have 'missing' entries. Don't warn/error for this case.
3121            if (bundle->getSplitConfigurations().isEmpty()) {
3122                bool missing_entry = false;
3123                const char* log_prefix = bundle->getErrorOnMissingConfigEntry() ?
3124                        "error" : "warning";
3125                for (size_t i = 0; i < N; ++i) {
3126                    if (!validResources[i]) {
3127                        sp<ConfigList> c = t->getOrderedConfigs().itemAt(i);
3128                        fprintf(stderr, "%s: no entries written for %s/%s (0x%08x)\n", log_prefix,
3129                                String8(typeName).string(), String8(c->getName()).string(),
3130                                Res_MAKEID(p->getAssignedId() - 1, ti, i));
3131                        missing_entry = true;
3132                    }
3133                }
3134                if (bundle->getErrorOnMissingConfigEntry() && missing_entry) {
3135                    fprintf(stderr, "Error: Missing entries, quit!\n");
3136                    return NOT_ENOUGH_DATA;
3137                }
3138            }
3139        }
3140
3141        // Fill in the rest of the package information.
3142        header = (ResTable_package*)data->editData();
3143        header->header.size = htodl(data->getSize());
3144        header->typeStrings = htodl(typeStringsStart);
3145        header->lastPublicType = htodl(p->getTypeStrings().size());
3146        header->keyStrings = htodl(keyStringsStart);
3147        header->lastPublicKey = htodl(p->getKeyStrings().size());
3148
3149        flatPackages.add(data);
3150    }
3151
3152    // And now write out the final chunks.
3153    const size_t dataStart = dest->getSize();
3154
3155    {
3156        // blah
3157        ResTable_header header;
3158        memset(&header, 0, sizeof(header));
3159        header.header.type = htods(RES_TABLE_TYPE);
3160        header.header.headerSize = htods(sizeof(header));
3161        header.packageCount = htodl(flatPackages.size());
3162        status_t err = dest->writeData(&header, sizeof(header));
3163        if (err != NO_ERROR) {
3164            fprintf(stderr, "ERROR: out of memory creating ResTable_header\n");
3165            return err;
3166        }
3167    }
3168
3169    ssize_t strStart = dest->getSize();
3170    status_t err = valueStrings.writeStringBlock(dest);
3171    if (err != NO_ERROR) {
3172        return err;
3173    }
3174
3175    ssize_t amt = (dest->getSize()-strStart);
3176    strAmt += amt;
3177    if (kPrintStringMetrics) {
3178        fprintf(stderr, "**** value strings: %zd\n", SSIZE(amt));
3179        fprintf(stderr, "**** total strings: %zd\n", SSIZE(strAmt));
3180    }
3181
3182    for (pi=0; pi<flatPackages.size(); pi++) {
3183        err = dest->writeData(flatPackages[pi]->getData(),
3184                              flatPackages[pi]->getSize());
3185        if (err != NO_ERROR) {
3186            fprintf(stderr, "ERROR: out of memory creating package chunk for ResTable_header\n");
3187            return err;
3188        }
3189    }
3190
3191    ResTable_header* header = (ResTable_header*)
3192        (((uint8_t*)dest->getData()) + dataStart);
3193    header->header.size = htodl(dest->getSize() - dataStart);
3194
3195    if (kPrintStringMetrics) {
3196        fprintf(stderr, "**** total resource table size: %zu / %zu%% strings\n",
3197                dest->getSize(), (size_t)(strAmt*100)/dest->getSize());
3198    }
3199
3200    return NO_ERROR;
3201}
3202
3203status_t ResourceTable::flattenLibraryTable(const sp<AaptFile>& dest, const Vector<sp<Package> >& libs) {
3204    // Write out the library table if necessary
3205    if (libs.size() > 0) {
3206        if (kIsDebug) {
3207            fprintf(stderr, "Writing library reference table\n");
3208        }
3209
3210        const size_t libStart = dest->getSize();
3211        const size_t count = libs.size();
3212        ResTable_lib_header* libHeader = (ResTable_lib_header*) dest->editDataInRange(
3213                libStart, sizeof(ResTable_lib_header));
3214
3215        memset(libHeader, 0, sizeof(*libHeader));
3216        libHeader->header.type = htods(RES_TABLE_LIBRARY_TYPE);
3217        libHeader->header.headerSize = htods(sizeof(*libHeader));
3218        libHeader->header.size = htodl(sizeof(*libHeader) + (sizeof(ResTable_lib_entry) * count));
3219        libHeader->count = htodl(count);
3220
3221        // Write the library entries
3222        for (size_t i = 0; i < count; i++) {
3223            const size_t entryStart = dest->getSize();
3224            sp<Package> libPackage = libs[i];
3225            if (kIsDebug) {
3226                fprintf(stderr, "  Entry %s -> 0x%02x\n",
3227                        String8(libPackage->getName()).string(),
3228                        (uint8_t)libPackage->getAssignedId());
3229            }
3230
3231            ResTable_lib_entry* entry = (ResTable_lib_entry*) dest->editDataInRange(
3232                    entryStart, sizeof(ResTable_lib_entry));
3233            memset(entry, 0, sizeof(*entry));
3234            entry->packageId = htodl(libPackage->getAssignedId());
3235            strcpy16_htod(entry->packageName, libPackage->getName().string());
3236        }
3237    }
3238    return NO_ERROR;
3239}
3240
3241void ResourceTable::writePublicDefinitions(const String16& package, FILE* fp)
3242{
3243    fprintf(fp,
3244    "<!-- This file contains <public> resource definitions for all\n"
3245    "     resources that were generated from the source data. -->\n"
3246    "\n"
3247    "<resources>\n");
3248
3249    writePublicDefinitions(package, fp, true);
3250    writePublicDefinitions(package, fp, false);
3251
3252    fprintf(fp,
3253    "\n"
3254    "</resources>\n");
3255}
3256
3257void ResourceTable::writePublicDefinitions(const String16& package, FILE* fp, bool pub)
3258{
3259    bool didHeader = false;
3260
3261    sp<Package> pkg = mPackages.valueFor(package);
3262    if (pkg != NULL) {
3263        const size_t NT = pkg->getOrderedTypes().size();
3264        for (size_t i=0; i<NT; i++) {
3265            sp<Type> t = pkg->getOrderedTypes().itemAt(i);
3266            if (t == NULL) {
3267                continue;
3268            }
3269
3270            bool didType = false;
3271
3272            const size_t NC = t->getOrderedConfigs().size();
3273            for (size_t j=0; j<NC; j++) {
3274                sp<ConfigList> c = t->getOrderedConfigs().itemAt(j);
3275                if (c == NULL) {
3276                    continue;
3277                }
3278
3279                if (c->getPublic() != pub) {
3280                    continue;
3281                }
3282
3283                if (!didType) {
3284                    fprintf(fp, "\n");
3285                    didType = true;
3286                }
3287                if (!didHeader) {
3288                    if (pub) {
3289                        fprintf(fp,"  <!-- PUBLIC SECTION.  These resources have been declared public.\n");
3290                        fprintf(fp,"       Changes to these definitions will break binary compatibility. -->\n\n");
3291                    } else {
3292                        fprintf(fp,"  <!-- PRIVATE SECTION.  These resources have not been declared public.\n");
3293                        fprintf(fp,"       You can make them public my moving these lines into a file in res/values. -->\n\n");
3294                    }
3295                    didHeader = true;
3296                }
3297                if (!pub) {
3298                    const size_t NE = c->getEntries().size();
3299                    for (size_t k=0; k<NE; k++) {
3300                        const SourcePos& pos = c->getEntries().valueAt(k)->getPos();
3301                        if (pos.file != "") {
3302                            fprintf(fp,"  <!-- Declared at %s:%d -->\n",
3303                                    pos.file.string(), pos.line);
3304                        }
3305                    }
3306                }
3307                fprintf(fp, "  <public type=\"%s\" name=\"%s\" id=\"0x%08x\" />\n",
3308                        String8(t->getName()).string(),
3309                        String8(c->getName()).string(),
3310                        getResId(pkg, t, c->getEntryIndex()));
3311            }
3312        }
3313    }
3314}
3315
3316ResourceTable::Item::Item(const SourcePos& _sourcePos,
3317                          bool _isId,
3318                          const String16& _value,
3319                          const Vector<StringPool::entry_style_span>* _style,
3320                          int32_t _format)
3321    : sourcePos(_sourcePos)
3322    , isId(_isId)
3323    , value(_value)
3324    , format(_format)
3325    , bagKeyId(0)
3326    , evaluating(false)
3327{
3328    if (_style) {
3329        style = *_style;
3330    }
3331}
3332
3333ResourceTable::Entry::Entry(const Entry& entry)
3334    : RefBase()
3335    , mName(entry.mName)
3336    , mParent(entry.mParent)
3337    , mType(entry.mType)
3338    , mItem(entry.mItem)
3339    , mItemFormat(entry.mItemFormat)
3340    , mBag(entry.mBag)
3341    , mNameIndex(entry.mNameIndex)
3342    , mParentId(entry.mParentId)
3343    , mPos(entry.mPos) {}
3344
3345ResourceTable::Entry& ResourceTable::Entry::operator=(const Entry& entry) {
3346    mName = entry.mName;
3347    mParent = entry.mParent;
3348    mType = entry.mType;
3349    mItem = entry.mItem;
3350    mItemFormat = entry.mItemFormat;
3351    mBag = entry.mBag;
3352    mNameIndex = entry.mNameIndex;
3353    mParentId = entry.mParentId;
3354    mPos = entry.mPos;
3355    return *this;
3356}
3357
3358status_t ResourceTable::Entry::makeItABag(const SourcePos& sourcePos)
3359{
3360    if (mType == TYPE_BAG) {
3361        return NO_ERROR;
3362    }
3363    if (mType == TYPE_UNKNOWN) {
3364        mType = TYPE_BAG;
3365        return NO_ERROR;
3366    }
3367    sourcePos.error("Resource entry %s is already defined as a single item.\n"
3368                    "%s:%d: Originally defined here.\n",
3369                    String8(mName).string(),
3370                    mItem.sourcePos.file.string(), mItem.sourcePos.line);
3371    return UNKNOWN_ERROR;
3372}
3373
3374status_t ResourceTable::Entry::setItem(const SourcePos& sourcePos,
3375                                       const String16& value,
3376                                       const Vector<StringPool::entry_style_span>* style,
3377                                       int32_t format,
3378                                       const bool overwrite)
3379{
3380    Item item(sourcePos, false, value, style);
3381
3382    if (mType == TYPE_BAG) {
3383        if (mBag.size() == 0) {
3384            sourcePos.error("Resource entry %s is already defined as a bag.",
3385                    String8(mName).string());
3386        } else {
3387            const Item& item(mBag.valueAt(0));
3388            sourcePos.error("Resource entry %s is already defined as a bag.\n"
3389                            "%s:%d: Originally defined here.\n",
3390                            String8(mName).string(),
3391                            item.sourcePos.file.string(), item.sourcePos.line);
3392        }
3393        return UNKNOWN_ERROR;
3394    }
3395    if ( (mType != TYPE_UNKNOWN) && (overwrite == false) ) {
3396        sourcePos.error("Resource entry %s is already defined.\n"
3397                        "%s:%d: Originally defined here.\n",
3398                        String8(mName).string(),
3399                        mItem.sourcePos.file.string(), mItem.sourcePos.line);
3400        return UNKNOWN_ERROR;
3401    }
3402
3403    mType = TYPE_ITEM;
3404    mItem = item;
3405    mItemFormat = format;
3406    return NO_ERROR;
3407}
3408
3409status_t ResourceTable::Entry::addToBag(const SourcePos& sourcePos,
3410                                        const String16& key, const String16& value,
3411                                        const Vector<StringPool::entry_style_span>* style,
3412                                        bool replace, bool isId, int32_t format)
3413{
3414    status_t err = makeItABag(sourcePos);
3415    if (err != NO_ERROR) {
3416        return err;
3417    }
3418
3419    Item item(sourcePos, isId, value, style, format);
3420
3421    // XXX NOTE: there is an error if you try to have a bag with two keys,
3422    // one an attr and one an id, with the same name.  Not something we
3423    // currently ever have to worry about.
3424    ssize_t origKey = mBag.indexOfKey(key);
3425    if (origKey >= 0) {
3426        if (!replace) {
3427            const Item& item(mBag.valueAt(origKey));
3428            sourcePos.error("Resource entry %s already has bag item %s.\n"
3429                    "%s:%d: Originally defined here.\n",
3430                    String8(mName).string(), String8(key).string(),
3431                    item.sourcePos.file.string(), item.sourcePos.line);
3432            return UNKNOWN_ERROR;
3433        }
3434        //printf("Replacing %s with %s\n",
3435        //       String8(mBag.valueFor(key).value).string(), String8(value).string());
3436        mBag.replaceValueFor(key, item);
3437    }
3438
3439    mBag.add(key, item);
3440    return NO_ERROR;
3441}
3442
3443status_t ResourceTable::Entry::removeFromBag(const String16& key) {
3444    if (mType != Entry::TYPE_BAG) {
3445        return NO_ERROR;
3446    }
3447
3448    if (mBag.removeItem(key) >= 0) {
3449        return NO_ERROR;
3450    }
3451    return UNKNOWN_ERROR;
3452}
3453
3454status_t ResourceTable::Entry::emptyBag(const SourcePos& sourcePos)
3455{
3456    status_t err = makeItABag(sourcePos);
3457    if (err != NO_ERROR) {
3458        return err;
3459    }
3460
3461    mBag.clear();
3462    return NO_ERROR;
3463}
3464
3465status_t ResourceTable::Entry::generateAttributes(ResourceTable* table,
3466                                                  const String16& package)
3467{
3468    const String16 attr16("attr");
3469    const String16 id16("id");
3470    const size_t N = mBag.size();
3471    for (size_t i=0; i<N; i++) {
3472        const String16& key = mBag.keyAt(i);
3473        const Item& it = mBag.valueAt(i);
3474        if (it.isId) {
3475            if (!table->hasBagOrEntry(key, &id16, &package)) {
3476                String16 value("false");
3477                if (kIsDebug) {
3478                    fprintf(stderr, "Generating %s:id/%s\n",
3479                            String8(package).string(),
3480                            String8(key).string());
3481                }
3482                status_t err = table->addEntry(SourcePos(String8("<generated>"), 0), package,
3483                                               id16, key, value);
3484                if (err != NO_ERROR) {
3485                    return err;
3486                }
3487            }
3488        } else if (!table->hasBagOrEntry(key, &attr16, &package)) {
3489
3490#if 1
3491//             fprintf(stderr, "ERROR: Bag attribute '%s' has not been defined.\n",
3492//                     String8(key).string());
3493//             const Item& item(mBag.valueAt(i));
3494//             fprintf(stderr, "Referenced from file %s line %d\n",
3495//                     item.sourcePos.file.string(), item.sourcePos.line);
3496//             return UNKNOWN_ERROR;
3497#else
3498            char numberStr[16];
3499            sprintf(numberStr, "%d", ResTable_map::TYPE_ANY);
3500            status_t err = table->addBag(SourcePos("<generated>", 0), package,
3501                                         attr16, key, String16(""),
3502                                         String16("^type"),
3503                                         String16(numberStr), NULL, NULL);
3504            if (err != NO_ERROR) {
3505                return err;
3506            }
3507#endif
3508        }
3509    }
3510    return NO_ERROR;
3511}
3512
3513status_t ResourceTable::Entry::assignResourceIds(ResourceTable* table,
3514                                                 const String16& /* package */)
3515{
3516    bool hasErrors = false;
3517
3518    if (mType == TYPE_BAG) {
3519        const char* errorMsg;
3520        const String16 style16("style");
3521        const String16 attr16("attr");
3522        const String16 id16("id");
3523        mParentId = 0;
3524        if (mParent.size() > 0) {
3525            mParentId = table->getResId(mParent, &style16, NULL, &errorMsg);
3526            if (mParentId == 0) {
3527                mPos.error("Error retrieving parent for item: %s '%s'.\n",
3528                        errorMsg, String8(mParent).string());
3529                hasErrors = true;
3530            }
3531        }
3532        const size_t N = mBag.size();
3533        for (size_t i=0; i<N; i++) {
3534            const String16& key = mBag.keyAt(i);
3535            Item& it = mBag.editValueAt(i);
3536            it.bagKeyId = table->getResId(key,
3537                    it.isId ? &id16 : &attr16, NULL, &errorMsg);
3538            //printf("Bag key of %s: #%08x\n", String8(key).string(), it.bagKeyId);
3539            if (it.bagKeyId == 0) {
3540                it.sourcePos.error("Error: %s: %s '%s'.\n", errorMsg,
3541                        String8(it.isId ? id16 : attr16).string(),
3542                        String8(key).string());
3543                hasErrors = true;
3544            }
3545        }
3546    }
3547    return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
3548}
3549
3550status_t ResourceTable::Entry::prepareFlatten(StringPool* strings, ResourceTable* table,
3551        const String8* configTypeName, const ConfigDescription* config)
3552{
3553    if (mType == TYPE_ITEM) {
3554        Item& it = mItem;
3555        AccessorCookie ac(it.sourcePos, String8(mName), String8(it.value));
3556        if (!table->stringToValue(&it.parsedValue, strings,
3557                                  it.value, false, true, 0,
3558                                  &it.style, NULL, &ac, mItemFormat,
3559                                  configTypeName, config)) {
3560            return UNKNOWN_ERROR;
3561        }
3562    } else if (mType == TYPE_BAG) {
3563        const size_t N = mBag.size();
3564        for (size_t i=0; i<N; i++) {
3565            const String16& key = mBag.keyAt(i);
3566            Item& it = mBag.editValueAt(i);
3567            AccessorCookie ac(it.sourcePos, String8(key), String8(it.value));
3568            if (!table->stringToValue(&it.parsedValue, strings,
3569                                      it.value, false, true, it.bagKeyId,
3570                                      &it.style, NULL, &ac, it.format,
3571                                      configTypeName, config)) {
3572                return UNKNOWN_ERROR;
3573            }
3574        }
3575    } else {
3576        mPos.error("Error: entry %s is not a single item or a bag.\n",
3577                   String8(mName).string());
3578        return UNKNOWN_ERROR;
3579    }
3580    return NO_ERROR;
3581}
3582
3583status_t ResourceTable::Entry::remapStringValue(StringPool* strings)
3584{
3585    if (mType == TYPE_ITEM) {
3586        Item& it = mItem;
3587        if (it.parsedValue.dataType == Res_value::TYPE_STRING) {
3588            it.parsedValue.data = strings->mapOriginalPosToNewPos(it.parsedValue.data);
3589        }
3590    } else if (mType == TYPE_BAG) {
3591        const size_t N = mBag.size();
3592        for (size_t i=0; i<N; i++) {
3593            Item& it = mBag.editValueAt(i);
3594            if (it.parsedValue.dataType == Res_value::TYPE_STRING) {
3595                it.parsedValue.data = strings->mapOriginalPosToNewPos(it.parsedValue.data);
3596            }
3597        }
3598    } else {
3599        mPos.error("Error: entry %s is not a single item or a bag.\n",
3600                   String8(mName).string());
3601        return UNKNOWN_ERROR;
3602    }
3603    return NO_ERROR;
3604}
3605
3606ssize_t ResourceTable::Entry::flatten(Bundle* /* bundle */, const sp<AaptFile>& data, bool isPublic)
3607{
3608    size_t amt = 0;
3609    ResTable_entry header;
3610    memset(&header, 0, sizeof(header));
3611    header.size = htods(sizeof(header));
3612    const type ty = mType;
3613    if (ty == TYPE_BAG) {
3614        header.flags |= htods(header.FLAG_COMPLEX);
3615    }
3616    if (isPublic) {
3617        header.flags |= htods(header.FLAG_PUBLIC);
3618    }
3619    header.key.index = htodl(mNameIndex);
3620    if (ty != TYPE_BAG) {
3621        status_t err = data->writeData(&header, sizeof(header));
3622        if (err != NO_ERROR) {
3623            fprintf(stderr, "ERROR: out of memory creating ResTable_entry\n");
3624            return err;
3625        }
3626
3627        const Item& it = mItem;
3628        Res_value par;
3629        memset(&par, 0, sizeof(par));
3630        par.size = htods(it.parsedValue.size);
3631        par.dataType = it.parsedValue.dataType;
3632        par.res0 = it.parsedValue.res0;
3633        par.data = htodl(it.parsedValue.data);
3634        #if 0
3635        printf("Writing item (%s): type=%d, data=0x%x, res0=0x%x\n",
3636               String8(mName).string(), it.parsedValue.dataType,
3637               it.parsedValue.data, par.res0);
3638        #endif
3639        err = data->writeData(&par, it.parsedValue.size);
3640        if (err != NO_ERROR) {
3641            fprintf(stderr, "ERROR: out of memory creating Res_value\n");
3642            return err;
3643        }
3644        amt += it.parsedValue.size;
3645    } else {
3646        size_t N = mBag.size();
3647        size_t i;
3648        // Create correct ordering of items.
3649        KeyedVector<uint32_t, const Item*> items;
3650        for (i=0; i<N; i++) {
3651            const Item& it = mBag.valueAt(i);
3652            items.add(it.bagKeyId, &it);
3653        }
3654        N = items.size();
3655
3656        ResTable_map_entry mapHeader;
3657        memcpy(&mapHeader, &header, sizeof(header));
3658        mapHeader.size = htods(sizeof(mapHeader));
3659        mapHeader.parent.ident = htodl(mParentId);
3660        mapHeader.count = htodl(N);
3661        status_t err = data->writeData(&mapHeader, sizeof(mapHeader));
3662        if (err != NO_ERROR) {
3663            fprintf(stderr, "ERROR: out of memory creating ResTable_entry\n");
3664            return err;
3665        }
3666
3667        for (i=0; i<N; i++) {
3668            const Item& it = *items.valueAt(i);
3669            ResTable_map map;
3670            map.name.ident = htodl(it.bagKeyId);
3671            map.value.size = htods(it.parsedValue.size);
3672            map.value.dataType = it.parsedValue.dataType;
3673            map.value.res0 = it.parsedValue.res0;
3674            map.value.data = htodl(it.parsedValue.data);
3675            err = data->writeData(&map, sizeof(map));
3676            if (err != NO_ERROR) {
3677                fprintf(stderr, "ERROR: out of memory creating Res_value\n");
3678                return err;
3679            }
3680            amt += sizeof(map);
3681        }
3682    }
3683    return amt;
3684}
3685
3686void ResourceTable::ConfigList::appendComment(const String16& comment,
3687                                              bool onlyIfEmpty)
3688{
3689    if (comment.size() <= 0) {
3690        return;
3691    }
3692    if (onlyIfEmpty && mComment.size() > 0) {
3693        return;
3694    }
3695    if (mComment.size() > 0) {
3696        mComment.append(String16("\n"));
3697    }
3698    mComment.append(comment);
3699}
3700
3701void ResourceTable::ConfigList::appendTypeComment(const String16& comment)
3702{
3703    if (comment.size() <= 0) {
3704        return;
3705    }
3706    if (mTypeComment.size() > 0) {
3707        mTypeComment.append(String16("\n"));
3708    }
3709    mTypeComment.append(comment);
3710}
3711
3712status_t ResourceTable::Type::addPublic(const SourcePos& sourcePos,
3713                                        const String16& name,
3714                                        const uint32_t ident)
3715{
3716    #if 0
3717    int32_t entryIdx = Res_GETENTRY(ident);
3718    if (entryIdx < 0) {
3719        sourcePos.error("Public resource %s/%s has an invalid 0 identifier (0x%08x).\n",
3720                String8(mName).string(), String8(name).string(), ident);
3721        return UNKNOWN_ERROR;
3722    }
3723    #endif
3724
3725    int32_t typeIdx = Res_GETTYPE(ident);
3726    if (typeIdx >= 0) {
3727        typeIdx++;
3728        if (mPublicIndex > 0 && mPublicIndex != typeIdx) {
3729            sourcePos.error("Public resource %s/%s has conflicting type codes for its"
3730                    " public identifiers (0x%x vs 0x%x).\n",
3731                    String8(mName).string(), String8(name).string(),
3732                    mPublicIndex, typeIdx);
3733            return UNKNOWN_ERROR;
3734        }
3735        mPublicIndex = typeIdx;
3736    }
3737
3738    if (mFirstPublicSourcePos == NULL) {
3739        mFirstPublicSourcePos = new SourcePos(sourcePos);
3740    }
3741
3742    if (mPublic.indexOfKey(name) < 0) {
3743        mPublic.add(name, Public(sourcePos, String16(), ident));
3744    } else {
3745        Public& p = mPublic.editValueFor(name);
3746        if (p.ident != ident) {
3747            sourcePos.error("Public resource %s/%s has conflicting public identifiers"
3748                    " (0x%08x vs 0x%08x).\n"
3749                    "%s:%d: Originally defined here.\n",
3750                    String8(mName).string(), String8(name).string(), p.ident, ident,
3751                    p.sourcePos.file.string(), p.sourcePos.line);
3752            return UNKNOWN_ERROR;
3753        }
3754    }
3755
3756    return NO_ERROR;
3757}
3758
3759void ResourceTable::Type::canAddEntry(const String16& name)
3760{
3761    mCanAddEntries.add(name);
3762}
3763
3764sp<ResourceTable::Entry> ResourceTable::Type::getEntry(const String16& entry,
3765                                                       const SourcePos& sourcePos,
3766                                                       const ResTable_config* config,
3767                                                       bool doSetIndex,
3768                                                       bool overlay,
3769                                                       bool autoAddOverlay)
3770{
3771    int pos = -1;
3772    sp<ConfigList> c = mConfigs.valueFor(entry);
3773    if (c == NULL) {
3774        if (overlay && !autoAddOverlay && mCanAddEntries.indexOf(entry) < 0) {
3775            sourcePos.error("Resource at %s appears in overlay but not"
3776                            " in the base package; use <add-resource> to add.\n",
3777                            String8(entry).string());
3778            return NULL;
3779        }
3780        c = new ConfigList(entry, sourcePos);
3781        mConfigs.add(entry, c);
3782        pos = (int)mOrderedConfigs.size();
3783        mOrderedConfigs.add(c);
3784        if (doSetIndex) {
3785            c->setEntryIndex(pos);
3786        }
3787    }
3788
3789    ConfigDescription cdesc;
3790    if (config) cdesc = *config;
3791
3792    sp<Entry> e = c->getEntries().valueFor(cdesc);
3793    if (e == NULL) {
3794        if (kIsDebug) {
3795            if (config != NULL) {
3796                printf("New entry at %s:%d: imsi:%d/%d lang:%c%c cnt:%c%c "
3797                    "orien:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d "
3798                    "sw%ddp w%ddp h%ddp layout:%d\n",
3799                      sourcePos.file.string(), sourcePos.line,
3800                      config->mcc, config->mnc,
3801                      config->language[0] ? config->language[0] : '-',
3802                      config->language[1] ? config->language[1] : '-',
3803                      config->country[0] ? config->country[0] : '-',
3804                      config->country[1] ? config->country[1] : '-',
3805                      config->orientation,
3806                      config->touchscreen,
3807                      config->density,
3808                      config->keyboard,
3809                      config->inputFlags,
3810                      config->navigation,
3811                      config->screenWidth,
3812                      config->screenHeight,
3813                      config->smallestScreenWidthDp,
3814                      config->screenWidthDp,
3815                      config->screenHeightDp,
3816                      config->screenLayout);
3817            } else {
3818                printf("New entry at %s:%d: NULL config\n",
3819                        sourcePos.file.string(), sourcePos.line);
3820            }
3821        }
3822        e = new Entry(entry, sourcePos);
3823        c->addEntry(cdesc, e);
3824        /*
3825        if (doSetIndex) {
3826            if (pos < 0) {
3827                for (pos=0; pos<(int)mOrderedConfigs.size(); pos++) {
3828                    if (mOrderedConfigs[pos] == c) {
3829                        break;
3830                    }
3831                }
3832                if (pos >= (int)mOrderedConfigs.size()) {
3833                    sourcePos.error("Internal error: config not found in mOrderedConfigs when adding entry");
3834                    return NULL;
3835                }
3836            }
3837            e->setEntryIndex(pos);
3838        }
3839        */
3840    }
3841
3842    mUniqueConfigs.add(cdesc);
3843
3844    return e;
3845}
3846
3847status_t ResourceTable::Type::applyPublicEntryOrder()
3848{
3849    size_t N = mOrderedConfigs.size();
3850    Vector<sp<ConfigList> > origOrder(mOrderedConfigs);
3851    bool hasError = false;
3852
3853    size_t i;
3854    for (i=0; i<N; i++) {
3855        mOrderedConfigs.replaceAt(NULL, i);
3856    }
3857
3858    const size_t NP = mPublic.size();
3859    //printf("Ordering %d configs from %d public defs\n", N, NP);
3860    size_t j;
3861    for (j=0; j<NP; j++) {
3862        const String16& name = mPublic.keyAt(j);
3863        const Public& p = mPublic.valueAt(j);
3864        int32_t idx = Res_GETENTRY(p.ident);
3865        //printf("Looking for entry \"%s\"/\"%s\" (0x%08x) in %d...\n",
3866        //       String8(mName).string(), String8(name).string(), p.ident, N);
3867        bool found = false;
3868        for (i=0; i<N; i++) {
3869            sp<ConfigList> e = origOrder.itemAt(i);
3870            //printf("#%d: \"%s\"\n", i, String8(e->getName()).string());
3871            if (e->getName() == name) {
3872                if (idx >= (int32_t)mOrderedConfigs.size()) {
3873                    p.sourcePos.error("Public entry identifier 0x%x entry index "
3874                            "is larger than available symbols (index %d, total symbols %d).\n",
3875                            p.ident, idx, mOrderedConfigs.size());
3876                    hasError = true;
3877                } else if (mOrderedConfigs.itemAt(idx) == NULL) {
3878                    e->setPublic(true);
3879                    e->setPublicSourcePos(p.sourcePos);
3880                    mOrderedConfigs.replaceAt(e, idx);
3881                    origOrder.removeAt(i);
3882                    N--;
3883                    found = true;
3884                    break;
3885                } else {
3886                    sp<ConfigList> oe = mOrderedConfigs.itemAt(idx);
3887
3888                    p.sourcePos.error("Multiple entry names declared for public entry"
3889                            " identifier 0x%x in type %s (%s vs %s).\n"
3890                            "%s:%d: Originally defined here.",
3891                            idx+1, String8(mName).string(),
3892                            String8(oe->getName()).string(),
3893                            String8(name).string(),
3894                            oe->getPublicSourcePos().file.string(),
3895                            oe->getPublicSourcePos().line);
3896                    hasError = true;
3897                }
3898            }
3899        }
3900
3901        if (!found) {
3902            p.sourcePos.error("Public symbol %s/%s declared here is not defined.",
3903                    String8(mName).string(), String8(name).string());
3904            hasError = true;
3905        }
3906    }
3907
3908    //printf("Copying back in %d non-public configs, have %d\n", N, origOrder.size());
3909
3910    if (N != origOrder.size()) {
3911        printf("Internal error: remaining private symbol count mismatch\n");
3912        N = origOrder.size();
3913    }
3914
3915    j = 0;
3916    for (i=0; i<N; i++) {
3917        sp<ConfigList> e = origOrder.itemAt(i);
3918        // There will always be enough room for the remaining entries.
3919        while (mOrderedConfigs.itemAt(j) != NULL) {
3920            j++;
3921        }
3922        mOrderedConfigs.replaceAt(e, j);
3923        j++;
3924    }
3925
3926    return hasError ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
3927}
3928
3929ResourceTable::Package::Package(const String16& name, size_t packageId)
3930    : mName(name), mPackageId(packageId),
3931      mTypeStringsMapping(0xffffffff),
3932      mKeyStringsMapping(0xffffffff)
3933{
3934}
3935
3936sp<ResourceTable::Type> ResourceTable::Package::getType(const String16& type,
3937                                                        const SourcePos& sourcePos,
3938                                                        bool doSetIndex)
3939{
3940    sp<Type> t = mTypes.valueFor(type);
3941    if (t == NULL) {
3942        t = new Type(type, sourcePos);
3943        mTypes.add(type, t);
3944        mOrderedTypes.add(t);
3945        if (doSetIndex) {
3946            // For some reason the type's index is set to one plus the index
3947            // in the mOrderedTypes list, rather than just the index.
3948            t->setIndex(mOrderedTypes.size());
3949        }
3950    }
3951    return t;
3952}
3953
3954status_t ResourceTable::Package::setTypeStrings(const sp<AaptFile>& data)
3955{
3956    status_t err = setStrings(data, &mTypeStrings, &mTypeStringsMapping);
3957    if (err != NO_ERROR) {
3958        fprintf(stderr, "ERROR: Type string data is corrupt!\n");
3959        return err;
3960    }
3961
3962    // Retain a reference to the new data after we've successfully replaced
3963    // all uses of the old reference (in setStrings() ).
3964    mTypeStringsData = data;
3965    return NO_ERROR;
3966}
3967
3968status_t ResourceTable::Package::setKeyStrings(const sp<AaptFile>& data)
3969{
3970    status_t err = setStrings(data, &mKeyStrings, &mKeyStringsMapping);
3971    if (err != NO_ERROR) {
3972        fprintf(stderr, "ERROR: Key string data is corrupt!\n");
3973        return err;
3974    }
3975
3976    // Retain a reference to the new data after we've successfully replaced
3977    // all uses of the old reference (in setStrings() ).
3978    mKeyStringsData = data;
3979    return NO_ERROR;
3980}
3981
3982status_t ResourceTable::Package::setStrings(const sp<AaptFile>& data,
3983                                            ResStringPool* strings,
3984                                            DefaultKeyedVector<String16, uint32_t>* mappings)
3985{
3986    if (data->getData() == NULL) {
3987        return UNKNOWN_ERROR;
3988    }
3989
3990    status_t err = strings->setTo(data->getData(), data->getSize());
3991    if (err == NO_ERROR) {
3992        const size_t N = strings->size();
3993        for (size_t i=0; i<N; i++) {
3994            size_t len;
3995            mappings->add(String16(strings->stringAt(i, &len)), i);
3996        }
3997    }
3998    return err;
3999}
4000
4001status_t ResourceTable::Package::applyPublicTypeOrder()
4002{
4003    size_t N = mOrderedTypes.size();
4004    Vector<sp<Type> > origOrder(mOrderedTypes);
4005
4006    size_t i;
4007    for (i=0; i<N; i++) {
4008        mOrderedTypes.replaceAt(NULL, i);
4009    }
4010
4011    for (i=0; i<N; i++) {
4012        sp<Type> t = origOrder.itemAt(i);
4013        int32_t idx = t->getPublicIndex();
4014        if (idx > 0) {
4015            idx--;
4016            while (idx >= (int32_t)mOrderedTypes.size()) {
4017                mOrderedTypes.add();
4018            }
4019            if (mOrderedTypes.itemAt(idx) != NULL) {
4020                sp<Type> ot = mOrderedTypes.itemAt(idx);
4021                t->getFirstPublicSourcePos().error("Multiple type names declared for public type"
4022                        " identifier 0x%x (%s vs %s).\n"
4023                        "%s:%d: Originally defined here.",
4024                        idx, String8(ot->getName()).string(),
4025                        String8(t->getName()).string(),
4026                        ot->getFirstPublicSourcePos().file.string(),
4027                        ot->getFirstPublicSourcePos().line);
4028                return UNKNOWN_ERROR;
4029            }
4030            mOrderedTypes.replaceAt(t, idx);
4031            origOrder.removeAt(i);
4032            i--;
4033            N--;
4034        }
4035    }
4036
4037    size_t j=0;
4038    for (i=0; i<N; i++) {
4039        sp<Type> t = origOrder.itemAt(i);
4040        // There will always be enough room for the remaining types.
4041        while (mOrderedTypes.itemAt(j) != NULL) {
4042            j++;
4043        }
4044        mOrderedTypes.replaceAt(t, j);
4045    }
4046
4047    return NO_ERROR;
4048}
4049
4050sp<ResourceTable::Package> ResourceTable::getPackage(const String16& package)
4051{
4052    if (package != mAssetsPackage) {
4053        return NULL;
4054    }
4055    return mPackages.valueFor(package);
4056}
4057
4058sp<ResourceTable::Type> ResourceTable::getType(const String16& package,
4059                                               const String16& type,
4060                                               const SourcePos& sourcePos,
4061                                               bool doSetIndex)
4062{
4063    sp<Package> p = getPackage(package);
4064    if (p == NULL) {
4065        return NULL;
4066    }
4067    return p->getType(type, sourcePos, doSetIndex);
4068}
4069
4070sp<ResourceTable::Entry> ResourceTable::getEntry(const String16& package,
4071                                                 const String16& type,
4072                                                 const String16& name,
4073                                                 const SourcePos& sourcePos,
4074                                                 bool overlay,
4075                                                 const ResTable_config* config,
4076                                                 bool doSetIndex)
4077{
4078    sp<Type> t = getType(package, type, sourcePos, doSetIndex);
4079    if (t == NULL) {
4080        return NULL;
4081    }
4082    return t->getEntry(name, sourcePos, config, doSetIndex, overlay, mBundle->getAutoAddOverlay());
4083}
4084
4085sp<ResourceTable::ConfigList> ResourceTable::getConfigList(const String16& package,
4086        const String16& type, const String16& name) const
4087{
4088    const size_t packageCount = mOrderedPackages.size();
4089    for (size_t pi = 0; pi < packageCount; pi++) {
4090        const sp<Package>& p = mOrderedPackages[pi];
4091        if (p == NULL || p->getName() != package) {
4092            continue;
4093        }
4094
4095        const Vector<sp<Type> >& types = p->getOrderedTypes();
4096        const size_t typeCount = types.size();
4097        for (size_t ti = 0; ti < typeCount; ti++) {
4098            const sp<Type>& t = types[ti];
4099            if (t == NULL || t->getName() != type) {
4100                continue;
4101            }
4102
4103            const Vector<sp<ConfigList> >& configs = t->getOrderedConfigs();
4104            const size_t configCount = configs.size();
4105            for (size_t ci = 0; ci < configCount; ci++) {
4106                const sp<ConfigList>& cl = configs[ci];
4107                if (cl == NULL || cl->getName() != name) {
4108                    continue;
4109                }
4110
4111                return cl;
4112            }
4113        }
4114    }
4115    return NULL;
4116}
4117
4118sp<const ResourceTable::Entry> ResourceTable::getEntry(uint32_t resID,
4119                                                       const ResTable_config* config) const
4120{
4121    size_t pid = Res_GETPACKAGE(resID)+1;
4122    const size_t N = mOrderedPackages.size();
4123    sp<Package> p;
4124    for (size_t i = 0; i < N; i++) {
4125        sp<Package> check = mOrderedPackages[i];
4126        if (check->getAssignedId() == pid) {
4127            p = check;
4128            break;
4129        }
4130
4131    }
4132    if (p == NULL) {
4133        fprintf(stderr, "warning: Package not found for resource #%08x\n", resID);
4134        return NULL;
4135    }
4136
4137    int tid = Res_GETTYPE(resID);
4138    if (tid < 0 || tid >= (int)p->getOrderedTypes().size()) {
4139        fprintf(stderr, "warning: Type not found for resource #%08x\n", resID);
4140        return NULL;
4141    }
4142    sp<Type> t = p->getOrderedTypes()[tid];
4143
4144    int eid = Res_GETENTRY(resID);
4145    if (eid < 0 || eid >= (int)t->getOrderedConfigs().size()) {
4146        fprintf(stderr, "warning: Entry not found for resource #%08x\n", resID);
4147        return NULL;
4148    }
4149
4150    sp<ConfigList> c = t->getOrderedConfigs()[eid];
4151    if (c == NULL) {
4152        fprintf(stderr, "warning: Entry not found for resource #%08x\n", resID);
4153        return NULL;
4154    }
4155
4156    ConfigDescription cdesc;
4157    if (config) cdesc = *config;
4158    sp<Entry> e = c->getEntries().valueFor(cdesc);
4159    if (c == NULL) {
4160        fprintf(stderr, "warning: Entry configuration not found for resource #%08x\n", resID);
4161        return NULL;
4162    }
4163
4164    return e;
4165}
4166
4167const ResourceTable::Item* ResourceTable::getItem(uint32_t resID, uint32_t attrID) const
4168{
4169    sp<const Entry> e = getEntry(resID);
4170    if (e == NULL) {
4171        return NULL;
4172    }
4173
4174    const size_t N = e->getBag().size();
4175    for (size_t i=0; i<N; i++) {
4176        const Item& it = e->getBag().valueAt(i);
4177        if (it.bagKeyId == 0) {
4178            fprintf(stderr, "warning: ID not yet assigned to '%s' in bag '%s'\n",
4179                    String8(e->getName()).string(),
4180                    String8(e->getBag().keyAt(i)).string());
4181        }
4182        if (it.bagKeyId == attrID) {
4183            return &it;
4184        }
4185    }
4186
4187    return NULL;
4188}
4189
4190bool ResourceTable::getItemValue(
4191    uint32_t resID, uint32_t attrID, Res_value* outValue)
4192{
4193    const Item* item = getItem(resID, attrID);
4194
4195    bool res = false;
4196    if (item != NULL) {
4197        if (item->evaluating) {
4198            sp<const Entry> e = getEntry(resID);
4199            const size_t N = e->getBag().size();
4200            size_t i;
4201            for (i=0; i<N; i++) {
4202                if (&e->getBag().valueAt(i) == item) {
4203                    break;
4204                }
4205            }
4206            fprintf(stderr, "warning: Circular reference detected in key '%s' of bag '%s'\n",
4207                    String8(e->getName()).string(),
4208                    String8(e->getBag().keyAt(i)).string());
4209            return false;
4210        }
4211        item->evaluating = true;
4212        res = stringToValue(outValue, NULL, item->value, false, false, item->bagKeyId);
4213        if (kIsDebug) {
4214            if (res) {
4215                printf("getItemValue of #%08x[#%08x] (%s): type=#%08x, data=#%08x\n",
4216                       resID, attrID, String8(getEntry(resID)->getName()).string(),
4217                       outValue->dataType, outValue->data);
4218            } else {
4219                printf("getItemValue of #%08x[#%08x]: failed\n",
4220                       resID, attrID);
4221            }
4222        }
4223        item->evaluating = false;
4224    }
4225    return res;
4226}
4227
4228/**
4229 * Returns true if the given attribute ID comes from
4230 * a platform version from or after L.
4231 */
4232bool ResourceTable::isAttributeFromL(uint32_t attrId) {
4233    const uint32_t baseAttrId = 0x010103f7;
4234    if ((attrId & 0xffff0000) != (baseAttrId & 0xffff0000)) {
4235        return false;
4236    }
4237
4238    uint32_t specFlags;
4239    if (!mAssets->getIncludedResources().getResourceFlags(attrId, &specFlags)) {
4240        return false;
4241    }
4242
4243    return (specFlags & ResTable_typeSpec::SPEC_PUBLIC) != 0 &&
4244        (attrId & 0x0000ffff) >= (baseAttrId & 0x0000ffff);
4245}
4246
4247static bool isMinSdkVersionLOrAbove(const Bundle* bundle) {
4248    if (bundle->getMinSdkVersion() != NULL && strlen(bundle->getMinSdkVersion()) > 0) {
4249        const char firstChar = bundle->getMinSdkVersion()[0];
4250        if (firstChar >= 'L' && firstChar <= 'Z') {
4251            // L is the code-name for the v21 release.
4252            return true;
4253        }
4254
4255        const int minSdk = atoi(bundle->getMinSdkVersion());
4256        if (minSdk >= SDK_L) {
4257            return true;
4258        }
4259    }
4260    return false;
4261}
4262
4263/**
4264 * Modifies the entries in the resource table to account for compatibility
4265 * issues with older versions of Android.
4266 *
4267 * This primarily handles the issue of private/public attribute clashes
4268 * in framework resources.
4269 *
4270 * AAPT has traditionally assigned resource IDs to public attributes,
4271 * and then followed those public definitions with private attributes.
4272 *
4273 * --- PUBLIC ---
4274 * | 0x01010234 | attr/color
4275 * | 0x01010235 | attr/background
4276 *
4277 * --- PRIVATE ---
4278 * | 0x01010236 | attr/secret
4279 * | 0x01010237 | attr/shhh
4280 *
4281 * Each release, when attributes are added, they take the place of the private
4282 * attributes and the private attributes are shifted down again.
4283 *
4284 * --- PUBLIC ---
4285 * | 0x01010234 | attr/color
4286 * | 0x01010235 | attr/background
4287 * | 0x01010236 | attr/shinyNewAttr
4288 * | 0x01010237 | attr/highlyValuedFeature
4289 *
4290 * --- PRIVATE ---
4291 * | 0x01010238 | attr/secret
4292 * | 0x01010239 | attr/shhh
4293 *
4294 * Platform code may look for private attributes set in a theme. If an app
4295 * compiled against a newer version of the platform uses a new public
4296 * attribute that happens to have the same ID as the private attribute
4297 * the older platform is expecting, then the behavior is undefined.
4298 *
4299 * We get around this by detecting any newly defined attributes (in L),
4300 * copy the resource into a -v21 qualified resource, and delete the
4301 * attribute from the original resource. This ensures that older platforms
4302 * don't see the new attribute, but when running on L+ platforms, the
4303 * attribute will be respected.
4304 */
4305status_t ResourceTable::modifyForCompat(const Bundle* bundle) {
4306    if (isMinSdkVersionLOrAbove(bundle)) {
4307        // If this app will only ever run on L+ devices,
4308        // we don't need to do any compatibility work.
4309        return NO_ERROR;
4310    }
4311
4312    const String16 attr16("attr");
4313
4314    const size_t packageCount = mOrderedPackages.size();
4315    for (size_t pi = 0; pi < packageCount; pi++) {
4316        sp<Package> p = mOrderedPackages.itemAt(pi);
4317        if (p == NULL || p->getTypes().size() == 0) {
4318            // Empty, skip!
4319            continue;
4320        }
4321
4322        const size_t typeCount = p->getOrderedTypes().size();
4323        for (size_t ti = 0; ti < typeCount; ti++) {
4324            sp<Type> t = p->getOrderedTypes().itemAt(ti);
4325            if (t == NULL) {
4326                continue;
4327            }
4328
4329            const size_t configCount = t->getOrderedConfigs().size();
4330            for (size_t ci = 0; ci < configCount; ci++) {
4331                sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
4332                if (c == NULL) {
4333                    continue;
4334                }
4335
4336                Vector<key_value_pair_t<ConfigDescription, sp<Entry> > > entriesToAdd;
4337                const DefaultKeyedVector<ConfigDescription, sp<Entry> >& entries =
4338                        c->getEntries();
4339                const size_t entryCount = entries.size();
4340                for (size_t ei = 0; ei < entryCount; ei++) {
4341                    sp<Entry> e = entries.valueAt(ei);
4342                    if (e == NULL || e->getType() != Entry::TYPE_BAG) {
4343                        continue;
4344                    }
4345
4346                    const ConfigDescription& config = entries.keyAt(ei);
4347                    if (config.sdkVersion >= SDK_L) {
4348                        // We don't need to do anything if the resource is
4349                        // already qualified for version 21 or higher.
4350                        continue;
4351                    }
4352
4353                    Vector<String16> attributesToRemove;
4354                    const KeyedVector<String16, Item>& bag = e->getBag();
4355                    const size_t bagCount = bag.size();
4356                    for (size_t bi = 0; bi < bagCount; bi++) {
4357                        const Item& item = bag.valueAt(bi);
4358                        const uint32_t attrId = getResId(bag.keyAt(bi), &attr16);
4359                        if (isAttributeFromL(attrId)) {
4360                            attributesToRemove.add(bag.keyAt(bi));
4361                        }
4362                    }
4363
4364                    if (attributesToRemove.isEmpty()) {
4365                        continue;
4366                    }
4367
4368                    // Duplicate the entry under the same configuration
4369                    // but with sdkVersion == SDK_L.
4370                    ConfigDescription newConfig(config);
4371                    newConfig.sdkVersion = SDK_L;
4372                    entriesToAdd.add(key_value_pair_t<ConfigDescription, sp<Entry> >(
4373                            newConfig, new Entry(*e)));
4374
4375                    // Remove the attribute from the original.
4376                    for (size_t i = 0; i < attributesToRemove.size(); i++) {
4377                        e->removeFromBag(attributesToRemove[i]);
4378                    }
4379                }
4380
4381                const size_t entriesToAddCount = entriesToAdd.size();
4382                for (size_t i = 0; i < entriesToAddCount; i++) {
4383                    if (entries.indexOfKey(entriesToAdd[i].key) >= 0) {
4384                        // An entry already exists for this config.
4385                        // That means that any attributes that were
4386                        // defined in L in the original bag will be overriden
4387                        // anyways on L devices, so we do nothing.
4388                        continue;
4389                    }
4390
4391                    entriesToAdd[i].value->getPos()
4392                            .printf("using v%d attributes; synthesizing resource %s:%s/%s for configuration %s.",
4393                                    SDK_L,
4394                                    String8(p->getName()).string(),
4395                                    String8(t->getName()).string(),
4396                                    String8(entriesToAdd[i].value->getName()).string(),
4397                                    entriesToAdd[i].key.toString().string());
4398
4399                    sp<Entry> newEntry = t->getEntry(c->getName(),
4400                            entriesToAdd[i].value->getPos(),
4401                            &entriesToAdd[i].key);
4402
4403                    *newEntry = *entriesToAdd[i].value;
4404                }
4405            }
4406        }
4407    }
4408    return NO_ERROR;
4409}
4410
4411status_t ResourceTable::modifyForCompat(const Bundle* bundle,
4412                                        const String16& resourceName,
4413                                        const sp<AaptFile>& target,
4414                                        const sp<XMLNode>& root) {
4415    if (isMinSdkVersionLOrAbove(bundle)) {
4416        return NO_ERROR;
4417    }
4418
4419    if (target->getResourceType() == "" || target->getGroupEntry().toParams().sdkVersion >= SDK_L) {
4420        // Skip resources that have no type (AndroidManifest.xml) or are already version qualified with v21
4421        // or higher.
4422        return NO_ERROR;
4423    }
4424
4425    Vector<key_value_pair_t<sp<XMLNode>, size_t> > attrsToRemove;
4426
4427    Vector<sp<XMLNode> > nodesToVisit;
4428    nodesToVisit.push(root);
4429    while (!nodesToVisit.isEmpty()) {
4430        sp<XMLNode> node = nodesToVisit.top();
4431        nodesToVisit.pop();
4432
4433        const Vector<XMLNode::attribute_entry>& attrs = node->getAttributes();
4434        const size_t attrCount = attrs.size();
4435        for (size_t i = 0; i < attrCount; i++) {
4436            const XMLNode::attribute_entry& attr = attrs[i];
4437            if (isAttributeFromL(attr.nameResId)) {
4438                attrsToRemove.add(key_value_pair_t<sp<XMLNode>, size_t>(node, i));
4439            }
4440        }
4441
4442        // Schedule a visit to the children.
4443        const Vector<sp<XMLNode> >& children = node->getChildren();
4444        const size_t childCount = children.size();
4445        for (size_t i = 0; i < childCount; i++) {
4446            nodesToVisit.push(children[i]);
4447        }
4448    }
4449
4450    if (attrsToRemove.isEmpty()) {
4451        return NO_ERROR;
4452    }
4453
4454    ConfigDescription newConfig(target->getGroupEntry().toParams());
4455    newConfig.sdkVersion = SDK_L;
4456
4457    // Look to see if we already have an overriding v21 configuration.
4458    sp<ConfigList> cl = getConfigList(String16(mAssets->getPackage()),
4459            String16(target->getResourceType()), resourceName);
4460    if (cl->getEntries().indexOfKey(newConfig) < 0) {
4461        // We don't have an overriding entry for v21, so we must duplicate this one.
4462        sp<XMLNode> newRoot = root->clone();
4463        sp<AaptFile> newFile = new AaptFile(target->getSourceFile(),
4464                AaptGroupEntry(newConfig), target->getResourceType());
4465        String8 resPath = String8::format("res/%s/%s",
4466                newFile->getGroupEntry().toDirName(target->getResourceType()).string(),
4467                target->getPath().getPathLeaf().string());
4468        resPath.convertToResPath();
4469
4470        // Add a resource table entry.
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        addEntry(SourcePos(),
4480                String16(mAssets->getPackage()),
4481                String16(target->getResourceType()),
4482                resourceName,
4483                String16(resPath),
4484                NULL,
4485                &newConfig);
4486
4487        // Schedule this to be compiled.
4488        CompileResourceWorkItem item;
4489        item.resourceName = resourceName;
4490        item.resPath = resPath;
4491        item.file = newFile;
4492        mWorkQueue.push(item);
4493    }
4494
4495    const size_t removeCount = attrsToRemove.size();
4496    for (size_t i = 0; i < removeCount; i++) {
4497        sp<XMLNode> node = attrsToRemove[i].key;
4498        size_t attrIndex = attrsToRemove[i].value;
4499        const XMLNode::attribute_entry& ae = node->getAttributes()[attrIndex];
4500        SourcePos(node->getFilename(), node->getStartLineNumber()).printf(
4501                "removing attribute %s%s%s from <%s>",
4502                String8(ae.ns).string(),
4503                (ae.ns.size() == 0 ? "" : ":"),
4504                String8(ae.name).string(),
4505                String8(node->getElementName()).string());
4506        node->removeAttribute(attrIndex);
4507    }
4508
4509    return NO_ERROR;
4510}
4511