ResourceTable.cpp revision f013e1afd1e68af5e3b868c26a653bbfb39538f8
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
11#include <utils/ByteOrder.h>
12#include <utils/ResourceTypes.h>
13#include <stdarg.h>
14
15#define NOISY(x) //x
16
17status_t compileXmlFile(const sp<AaptAssets>& assets,
18                        const sp<AaptFile>& target,
19                        ResourceTable* table,
20                        int options)
21{
22    sp<XMLNode> root = XMLNode::parse(target);
23    if (root == NULL) {
24        return UNKNOWN_ERROR;
25    }
26    if ((options&XML_COMPILE_STRIP_WHITESPACE) != 0) {
27        root->removeWhitespace(true, NULL);
28    } else  if ((options&XML_COMPILE_COMPACT_WHITESPACE) != 0) {
29        root->removeWhitespace(false, NULL);
30    }
31
32    bool hasErrors = false;
33
34    if ((options&XML_COMPILE_ASSIGN_ATTRIBUTE_IDS) != 0) {
35        status_t err = root->assignResourceIds(assets, table);
36        if (err != NO_ERROR) {
37            hasErrors = true;
38        }
39    }
40
41    status_t err = root->parseValues(assets, table);
42    if (err != NO_ERROR) {
43        hasErrors = true;
44    }
45
46    if (hasErrors) {
47        return UNKNOWN_ERROR;
48    }
49
50    NOISY(printf("Input XML Resource:\n"));
51    NOISY(root->print());
52    err = root->flatten(target,
53            (options&XML_COMPILE_STRIP_COMMENTS) != 0,
54            (options&XML_COMPILE_STRIP_RAW_VALUES) != 0);
55    if (err != NO_ERROR) {
56        return err;
57    }
58
59    NOISY(printf("Output XML Resource:\n"));
60    NOISY(ResXMLTree tree;
61        tree.setTo(target->getData(), target->getSize());
62        printXMLBlock(&tree));
63
64    target->setCompressionMethod(ZipEntry::kCompressDeflated);
65
66    return err;
67}
68
69#undef NOISY
70#define NOISY(x) //x
71
72struct flag_entry
73{
74    const char16_t* name;
75    size_t nameLen;
76    uint32_t value;
77    const char* description;
78};
79
80static const char16_t referenceArray[] =
81    { 'r', 'e', 'f', 'e', 'r', 'e', 'n', 'c', 'e' };
82static const char16_t stringArray[] =
83    { 's', 't', 'r', 'i', 'n', 'g' };
84static const char16_t integerArray[] =
85    { 'i', 'n', 't', 'e', 'g', 'e', 'r' };
86static const char16_t booleanArray[] =
87    { 'b', 'o', 'o', 'l', 'e', 'a', 'n' };
88static const char16_t colorArray[] =
89    { 'c', 'o', 'l', 'o', 'r' };
90static const char16_t floatArray[] =
91    { 'f', 'l', 'o', 'a', 't' };
92static const char16_t dimensionArray[] =
93    { 'd', 'i', 'm', 'e', 'n', 's', 'i', 'o', 'n' };
94static const char16_t fractionArray[] =
95    { 'f', 'r', 'a', 'c', 't', 'i', 'o', 'n' };
96static const char16_t enumArray[] =
97    { 'e', 'n', 'u', 'm' };
98static const char16_t flagsArray[] =
99    { 'f', 'l', 'a', 'g', 's' };
100
101static const flag_entry gFormatFlags[] = {
102    { referenceArray, sizeof(referenceArray)/2, ResTable_map::TYPE_REFERENCE,
103      "a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\n"
104      "or to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\"."},
105    { stringArray, sizeof(stringArray)/2, ResTable_map::TYPE_STRING,
106      "a string value, using '\\\\;' to escape characters such as '\\\\n' or '\\\\uxxxx' for a unicode character." },
107    { integerArray, sizeof(integerArray)/2, ResTable_map::TYPE_INTEGER,
108      "an integer value, such as \"<code>100</code>\"." },
109    { booleanArray, sizeof(booleanArray)/2, ResTable_map::TYPE_BOOLEAN,
110      "a boolean value, either \"<code>true</code>\" or \"<code>false</code>\"." },
111    { colorArray, sizeof(colorArray)/2, ResTable_map::TYPE_COLOR,
112      "a color value, in the form of \"<code>#<i>rgb</i></code>\", \"<code>#<i>argb</i></code>\",\n"
113      "\"<code>#<i>rrggbb</i></code>\", or \"<code>#<i>aarrggbb</i></code>\"." },
114    { floatArray, sizeof(floatArray)/2, ResTable_map::TYPE_FLOAT,
115      "a floating point value, such as \"<code>1.2</code>\"."},
116    { dimensionArray, sizeof(dimensionArray)/2, ResTable_map::TYPE_DIMENSION,
117      "a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\n"
118      "Available units are: px (pixels), db (density-independent pixels), sp (scaled pixels based on preferred font size),\n"
119      "in (inches), mm (millimeters)." },
120    { fractionArray, sizeof(fractionArray)/2, ResTable_map::TYPE_FRACTION,
121      "a fractional value, which is a floating point number appended with either % or %p, such as \"<code>14.5%</code>\".\n"
122      "The % suffix always means a percentage of the base size; the optional %p suffix provides a size relative to\n"
123      "some parent container." },
124    { enumArray, sizeof(enumArray)/2, ResTable_map::TYPE_ENUM, NULL },
125    { flagsArray, sizeof(flagsArray)/2, ResTable_map::TYPE_FLAGS, NULL },
126    { NULL, 0, 0, NULL }
127};
128
129static const char16_t suggestedArray[] = { 's', 'u', 'g', 'g', 'e', 's', 't', 'e', 'd' };
130
131static const flag_entry l10nRequiredFlags[] = {
132    { suggestedArray, sizeof(suggestedArray)/2, ResTable_map::L10N_SUGGESTED, NULL },
133    { NULL, 0, 0, NULL }
134};
135
136static const char16_t nulStr[] = { 0 };
137
138static uint32_t parse_flags(const char16_t* str, size_t len,
139                             const flag_entry* flags, bool* outError = NULL)
140{
141    while (len > 0 && isspace(*str)) {
142        str++;
143        len--;
144    }
145    while (len > 0 && isspace(str[len-1])) {
146        len--;
147    }
148
149    const char16_t* const end = str + len;
150    uint32_t value = 0;
151
152    while (str < end) {
153        const char16_t* div = str;
154        while (div < end && *div != '|') {
155            div++;
156        }
157
158        const flag_entry* cur = flags;
159        while (cur->name) {
160            if (strzcmp16(cur->name, cur->nameLen, str, div-str) == 0) {
161                value |= cur->value;
162                break;
163            }
164            cur++;
165        }
166
167        if (!cur->name) {
168            if (outError) *outError = true;
169            return 0;
170        }
171
172        str = div < end ? div+1 : div;
173    }
174
175    if (outError) *outError = false;
176    return value;
177}
178
179static String16 mayOrMust(int type, int flags)
180{
181    if ((type&(~flags)) == 0) {
182        return String16("<p>Must");
183    }
184
185    return String16("<p>May");
186}
187
188static void appendTypeInfo(ResourceTable* outTable, const String16& pkg,
189        const String16& typeName, const String16& ident, int type,
190        const flag_entry* flags)
191{
192    bool hadType = false;
193    while (flags->name) {
194        if ((type&flags->value) != 0 && flags->description != NULL) {
195            String16 fullMsg(mayOrMust(type, flags->value));
196            fullMsg.append(String16(" be "));
197            fullMsg.append(String16(flags->description));
198            outTable->appendTypeComment(pkg, typeName, ident, fullMsg);
199            hadType = true;
200        }
201        flags++;
202    }
203    if (hadType && (type&ResTable_map::TYPE_REFERENCE) == 0) {
204        outTable->appendTypeComment(pkg, typeName, ident,
205                String16("<p>This may also be a reference to a resource (in the form\n"
206                         "\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\n"
207                         "theme attribute (in the form\n"
208                         "\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\n"
209                         "containing a value of this type."));
210    }
211}
212
213struct PendingAttribute
214{
215    const String16 myPackage;
216    const SourcePos sourcePos;
217    const bool appendComment;
218    int32_t type;
219    String16 ident;
220    String16 comment;
221    bool hasErrors;
222    bool added;
223
224    PendingAttribute(String16 _package, const sp<AaptFile>& in,
225            ResXMLTree& block, bool _appendComment)
226        : myPackage(_package)
227        , sourcePos(in->getPrintableSource(), block.getLineNumber())
228        , appendComment(_appendComment)
229        , type(ResTable_map::TYPE_ANY)
230        , hasErrors(false)
231        , added(false)
232    {
233    }
234
235    status_t createIfNeeded(ResourceTable* outTable)
236    {
237        if (added || hasErrors) {
238            return NO_ERROR;
239        }
240        added = true;
241
242        String16 attr16("attr");
243
244        if (outTable->hasBagOrEntry(myPackage, attr16, ident)) {
245            sourcePos.error("Attribute \"%s\" has already been defined\n",
246                    String8(ident).string());
247            hasErrors = true;
248            return UNKNOWN_ERROR;
249        }
250
251        char numberStr[16];
252        sprintf(numberStr, "%d", type);
253        status_t err = outTable->addBag(sourcePos, myPackage,
254                attr16, ident, String16(""),
255                String16("^type"),
256                String16(numberStr), NULL, NULL);
257        if (err != NO_ERROR) {
258            hasErrors = true;
259            return err;
260        }
261        outTable->appendComment(myPackage, attr16, ident, comment, appendComment);
262        //printf("Attribute %s comment: %s\n", String8(ident).string(),
263        //     String8(comment).string());
264        return err;
265    }
266};
267
268static status_t compileAttribute(const sp<AaptFile>& in,
269                                 ResXMLTree& block,
270                                 const String16& myPackage,
271                                 ResourceTable* outTable,
272                                 String16* outIdent = NULL,
273                                 bool inStyleable = false)
274{
275    PendingAttribute attr(myPackage, in, block, inStyleable);
276
277    const String16 attr16("attr");
278    const String16 id16("id");
279
280    // Attribute type constants.
281    const String16 enum16("enum");
282    const String16 flag16("flag");
283
284    ResXMLTree::event_code_t code;
285    size_t len;
286    status_t err;
287
288    ssize_t identIdx = block.indexOfAttribute(NULL, "name");
289    if (identIdx >= 0) {
290        attr.ident = String16(block.getAttributeStringValue(identIdx, &len));
291        if (outIdent) {
292            *outIdent = attr.ident;
293        }
294    } else {
295        attr.sourcePos.error("A 'name' attribute is required for <attr>\n");
296        attr.hasErrors = true;
297    }
298
299    attr.comment = String16(
300            block.getComment(&len) ? block.getComment(&len) : nulStr);
301
302    ssize_t typeIdx = block.indexOfAttribute(NULL, "format");
303    if (typeIdx >= 0) {
304        String16 typeStr = String16(block.getAttributeStringValue(typeIdx, &len));
305        attr.type = parse_flags(typeStr.string(), typeStr.size(), gFormatFlags);
306        if (attr.type == 0) {
307            attr.sourcePos.error("Tag <attr> 'format' attribute value \"%s\" not valid\n",
308                    String8(typeStr).string());
309            attr.hasErrors = true;
310        }
311        attr.createIfNeeded(outTable);
312    } else if (!inStyleable) {
313        // Attribute definitions outside of styleables always define the
314        // attribute as a generic value.
315        attr.createIfNeeded(outTable);
316    }
317
318    //printf("Attribute %s: type=0x%08x\n", String8(attr.ident).string(), attr.type);
319
320    ssize_t minIdx = block.indexOfAttribute(NULL, "min");
321    if (minIdx >= 0) {
322        String16 val = String16(block.getAttributeStringValue(minIdx, &len));
323        if (!ResTable::stringToInt(val.string(), val.size(), NULL)) {
324            attr.sourcePos.error("Tag <attr> 'min' attribute must be a number, not \"%s\"\n",
325                    String8(val).string());
326            attr.hasErrors = true;
327        }
328        attr.createIfNeeded(outTable);
329        if (!attr.hasErrors) {
330            err = outTable->addBag(attr.sourcePos, myPackage, attr16, attr.ident,
331                    String16(""), String16("^min"), String16(val), NULL, NULL);
332            if (err != NO_ERROR) {
333                attr.hasErrors = true;
334            }
335        }
336    }
337
338    ssize_t maxIdx = block.indexOfAttribute(NULL, "max");
339    if (maxIdx >= 0) {
340        String16 val = String16(block.getAttributeStringValue(maxIdx, &len));
341        if (!ResTable::stringToInt(val.string(), val.size(), NULL)) {
342            attr.sourcePos.error("Tag <attr> 'max' attribute must be a number, not \"%s\"\n",
343                    String8(val).string());
344            attr.hasErrors = true;
345        }
346        attr.createIfNeeded(outTable);
347        if (!attr.hasErrors) {
348            err = outTable->addBag(attr.sourcePos, myPackage, attr16, attr.ident,
349                    String16(""), String16("^max"), String16(val), NULL, NULL);
350            attr.hasErrors = true;
351        }
352    }
353
354    if ((minIdx >= 0 || maxIdx >= 0) && (attr.type&ResTable_map::TYPE_INTEGER) == 0) {
355        attr.sourcePos.error("Tag <attr> must have format=integer attribute if using max or min\n");
356        attr.hasErrors = true;
357    }
358
359    ssize_t l10nIdx = block.indexOfAttribute(NULL, "localization");
360    if (l10nIdx >= 0) {
361        const uint16_t* str = block.getAttributeStringValue(l10nIdx, &len);
362        bool error;
363        uint32_t l10n_required = parse_flags(str, len, l10nRequiredFlags, &error);
364        if (error) {
365            attr.sourcePos.error("Tag <attr> 'localization' attribute value \"%s\" not valid\n",
366                    String8(str).string());
367            attr.hasErrors = true;
368        }
369        attr.createIfNeeded(outTable);
370        if (!attr.hasErrors) {
371            char buf[10];
372            sprintf(buf, "%d", l10n_required);
373            err = outTable->addBag(attr.sourcePos, myPackage, attr16, attr.ident,
374                    String16(""), String16("^l10n"), String16(buf), NULL, NULL);
375            if (err != NO_ERROR) {
376                attr.hasErrors = true;
377            }
378        }
379    }
380
381    String16 enumOrFlagsComment;
382
383    while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
384        if (code == ResXMLTree::START_TAG) {
385            uint32_t localType = 0;
386            if (strcmp16(block.getElementName(&len), enum16.string()) == 0) {
387                localType = ResTable_map::TYPE_ENUM;
388            } else if (strcmp16(block.getElementName(&len), flag16.string()) == 0) {
389                localType = ResTable_map::TYPE_FLAGS;
390            } else {
391                SourcePos(in->getPrintableSource(), block.getLineNumber())
392                        .error("Tag <%s> can not appear inside <attr>, only <enum> or <flag>\n",
393                        String8(block.getElementName(&len)).string());
394                return UNKNOWN_ERROR;
395            }
396
397            attr.createIfNeeded(outTable);
398
399            if (attr.type == ResTable_map::TYPE_ANY) {
400                // No type was explicitly stated, so supplying enum tags
401                // implicitly creates an enum or flag.
402                attr.type = 0;
403            }
404
405            if ((attr.type&(ResTable_map::TYPE_ENUM|ResTable_map::TYPE_FLAGS)) == 0) {
406                // Wasn't originally specified as an enum, so update its type.
407                attr.type |= localType;
408                if (!attr.hasErrors) {
409                    char numberStr[16];
410                    sprintf(numberStr, "%d", attr.type);
411                    err = outTable->addBag(SourcePos(in->getPrintableSource(), block.getLineNumber()),
412                            myPackage, attr16, attr.ident, String16(""),
413                            String16("^type"), String16(numberStr), NULL, NULL, true);
414                    if (err != NO_ERROR) {
415                        attr.hasErrors = true;
416                    }
417                }
418            } else if ((uint32_t)(attr.type&(ResTable_map::TYPE_ENUM|ResTable_map::TYPE_FLAGS)) != localType) {
419                if (localType == ResTable_map::TYPE_ENUM) {
420                    SourcePos(in->getPrintableSource(), block.getLineNumber())
421                            .error("<enum> attribute can not be used inside a flags format\n");
422                    attr.hasErrors = true;
423                } else {
424                    SourcePos(in->getPrintableSource(), block.getLineNumber())
425                            .error("<flag> attribute can not be used inside a enum format\n");
426                    attr.hasErrors = true;
427                }
428            }
429
430            String16 itemIdent;
431            ssize_t itemIdentIdx = block.indexOfAttribute(NULL, "name");
432            if (itemIdentIdx >= 0) {
433                itemIdent = String16(block.getAttributeStringValue(itemIdentIdx, &len));
434            } else {
435                SourcePos(in->getPrintableSource(), block.getLineNumber())
436                        .error("A 'name' attribute is required for <enum> or <flag>\n");
437                attr.hasErrors = true;
438            }
439
440            String16 value;
441            ssize_t valueIdx = block.indexOfAttribute(NULL, "value");
442            if (valueIdx >= 0) {
443                value = String16(block.getAttributeStringValue(valueIdx, &len));
444            } else {
445                SourcePos(in->getPrintableSource(), block.getLineNumber())
446                        .error("A 'value' attribute is required for <enum> or <flag>\n");
447                attr.hasErrors = true;
448            }
449            if (!attr.hasErrors && !ResTable::stringToInt(value.string(), value.size(), NULL)) {
450                SourcePos(in->getPrintableSource(), block.getLineNumber())
451                        .error("Tag <enum> or <flag> 'value' attribute must be a number,"
452                        " not \"%s\"\n",
453                        String8(value).string());
454                attr.hasErrors = true;
455            }
456
457            // Make sure an id is defined for this enum/flag identifier...
458            if (!attr.hasErrors && !outTable->hasBagOrEntry(itemIdent, &id16, &myPackage)) {
459                err = outTable->startBag(SourcePos(in->getPrintableSource(), block.getLineNumber()),
460                                         myPackage, id16, itemIdent, String16(), NULL);
461                if (err != NO_ERROR) {
462                    attr.hasErrors = true;
463                }
464            }
465
466            if (!attr.hasErrors) {
467                if (enumOrFlagsComment.size() == 0) {
468                    enumOrFlagsComment.append(mayOrMust(attr.type,
469                            ResTable_map::TYPE_ENUM|ResTable_map::TYPE_FLAGS));
470                    enumOrFlagsComment.append((attr.type&ResTable_map::TYPE_ENUM)
471                                       ? String16(" be one of the following constant values.")
472                                       : String16(" be one or more (separated by '|') of the following constant values."));
473                    enumOrFlagsComment.append(String16("</p>\n<table border=\"2\" width=\"85%\" align=\"center\" frame=\"hsides\" rules=\"all\" cellpadding=\"5\">\n"
474                                                "<colgroup align=\"left\" />\n"
475                                                "<colgroup align=\"left\" />\n"
476                                                "<colgroup align=\"left\" />\n"
477                                                "<tr><th>Constant<th>Value<th>Description</tr>"));
478                }
479
480                enumOrFlagsComment.append(String16("\n<tr><th><code>"));
481                enumOrFlagsComment.append(itemIdent);
482                enumOrFlagsComment.append(String16("</code><td>"));
483                enumOrFlagsComment.append(value);
484                enumOrFlagsComment.append(String16("<td>"));
485                if (block.getComment(&len)) {
486                    enumOrFlagsComment.append(String16(block.getComment(&len)));
487                }
488                enumOrFlagsComment.append(String16("</tr>"));
489
490                err = outTable->addBag(SourcePos(in->getPrintableSource(), block.getLineNumber()),
491                                       myPackage,
492                                       attr16, attr.ident, String16(""),
493                                       itemIdent, value, NULL, NULL, false, true);
494                if (err != NO_ERROR) {
495                    attr.hasErrors = true;
496                }
497            }
498        } else if (code == ResXMLTree::END_TAG) {
499            if (strcmp16(block.getElementName(&len), attr16.string()) == 0) {
500                break;
501            }
502            if ((attr.type&ResTable_map::TYPE_ENUM) != 0) {
503                if (strcmp16(block.getElementName(&len), enum16.string()) != 0) {
504                    SourcePos(in->getPrintableSource(), block.getLineNumber())
505                            .error("Found tag </%s> where </enum> is expected\n",
506                            String8(block.getElementName(&len)).string());
507                    return UNKNOWN_ERROR;
508                }
509            } else {
510                if (strcmp16(block.getElementName(&len), flag16.string()) != 0) {
511                    SourcePos(in->getPrintableSource(), block.getLineNumber())
512                            .error("Found tag </%s> where </flag> is expected\n",
513                            String8(block.getElementName(&len)).string());
514                    return UNKNOWN_ERROR;
515                }
516            }
517        }
518    }
519
520    if (!attr.hasErrors && attr.added) {
521        appendTypeInfo(outTable, myPackage, attr16, attr.ident, attr.type, gFormatFlags);
522    }
523
524    if (!attr.hasErrors && enumOrFlagsComment.size() > 0) {
525        enumOrFlagsComment.append(String16("\n</table>"));
526        outTable->appendTypeComment(myPackage, attr16, attr.ident, enumOrFlagsComment);
527    }
528
529
530    return NO_ERROR;
531}
532
533bool localeIsDefined(const ResTable_config& config)
534{
535    return config.locale == 0;
536}
537
538status_t parseAndAddBag(Bundle* bundle,
539                        const sp<AaptFile>& in,
540                        ResXMLTree* block,
541                        const ResTable_config& config,
542                        const String16& myPackage,
543                        const String16& curType,
544                        const String16& ident,
545                        const String16& parentIdent,
546                        const String16& itemIdent,
547                        int32_t curFormat,
548                        bool pseudolocalize,
549                        ResourceTable* outTable)
550{
551    status_t err;
552    const String16 item16("item");
553
554    String16 str;
555    Vector<StringPool::entry_style_span> spans;
556    err = parseStyledString(bundle, in->getPrintableSource().string(),
557                            block, item16, &str, &spans,
558                            pseudolocalize);
559    if (err != NO_ERROR) {
560        return err;
561    }
562
563    NOISY(printf("Adding resource bag entry l=%c%c c=%c%c orien=%d d=%d "
564                 " pid=%s, bag=%s, id=%s: %s\n",
565                 config.language[0], config.language[1],
566                 config.country[0], config.country[1],
567                 config.orientation, config.density,
568                 String8(parentIdent).string(),
569                 String8(ident).string(),
570                 String8(itemIdent).string(),
571                 String8(str).string()));
572
573    err = outTable->addBag(SourcePos(in->getPrintableSource(), block->getLineNumber()),
574                           myPackage, curType, ident, parentIdent, itemIdent, str,
575                           &spans, &config, false, false, curFormat);
576    return err;
577}
578
579
580status_t parseAndAddEntry(Bundle* bundle,
581                        const sp<AaptFile>& in,
582                        ResXMLTree* block,
583                        const ResTable_config& config,
584                        const String16& myPackage,
585                        const String16& curType,
586                        const String16& ident,
587                        const String16& curTag,
588                        bool curIsStyled,
589                        int32_t curFormat,
590                        bool pseudolocalize,
591                        ResourceTable* outTable)
592{
593    status_t err;
594
595    String16 str;
596    Vector<StringPool::entry_style_span> spans;
597    err = parseStyledString(bundle, in->getPrintableSource().string(), block,
598                            curTag, &str, curIsStyled ? &spans : NULL,
599                            pseudolocalize);
600
601    if (err < NO_ERROR) {
602        return err;
603    }
604
605    NOISY(printf("Adding resource entry l=%c%c c=%c%c orien=%d d=%d id=%s: %s\n",
606                 config.language[0], config.language[1],
607                 config.country[0], config.country[1],
608                 config.orientation, config.density,
609                 String8(ident).string(), String8(str).string()));
610
611    err = outTable->addEntry(SourcePos(in->getPrintableSource(), block->getLineNumber()),
612                             myPackage, curType, ident, str, &spans, &config,
613                             false, curFormat);
614
615    return err;
616}
617
618status_t compileResourceFile(Bundle* bundle,
619                             const sp<AaptAssets>& assets,
620                             const sp<AaptFile>& in,
621                             const ResTable_config& defParams,
622                             ResourceTable* outTable)
623{
624    ResXMLTree block;
625    status_t err = parseXMLResource(in, &block, false, true);
626    if (err != NO_ERROR) {
627        return err;
628    }
629
630    // Top-level tag.
631    const String16 resources16("resources");
632
633    // Identifier declaration tags.
634    const String16 declare_styleable16("declare-styleable");
635    const String16 attr16("attr");
636
637    // Data creation organizational tags.
638    const String16 string16("string");
639    const String16 drawable16("drawable");
640    const String16 color16("color");
641    const String16 bool16("bool");
642    const String16 integer16("integer");
643    const String16 dimen16("dimen");
644    const String16 style16("style");
645    const String16 plurals16("plurals");
646    const String16 array16("array");
647    const String16 string_array16("string-array");
648    const String16 integer_array16("integer-array");
649    const String16 public16("public");
650    const String16 private_symbols16("private-symbols");
651    const String16 skip16("skip");
652    const String16 eat_comment16("eat-comment");
653
654    // Data creation tags.
655    const String16 bag16("bag");
656    const String16 item16("item");
657
658    // Attribute type constants.
659    const String16 enum16("enum");
660
661    // plural values
662    const String16 other16("other");
663    const String16 quantityOther16("^other");
664    const String16 zero16("zero");
665    const String16 quantityZero16("^zero");
666    const String16 one16("one");
667    const String16 quantityOne16("^one");
668    const String16 two16("two");
669    const String16 quantityTwo16("^two");
670    const String16 few16("few");
671    const String16 quantityFew16("^few");
672    const String16 many16("many");
673    const String16 quantityMany16("^many");
674
675    // useful attribute names and special values
676    const String16 name16("name");
677    const String16 translatable16("translatable");
678    const String16 false16("false");
679
680    const String16 myPackage(assets->getPackage());
681
682    bool hasErrors = false;
683
684    uint32_t nextPublicId = 0;
685
686    ResXMLTree::event_code_t code;
687    do {
688        code = block.next();
689    } while (code == ResXMLTree::START_NAMESPACE);
690
691    size_t len;
692    if (code != ResXMLTree::START_TAG) {
693        SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
694                "No start tag found\n");
695        return UNKNOWN_ERROR;
696    }
697    if (strcmp16(block.getElementName(&len), resources16.string()) != 0) {
698        SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
699                "Invalid start tag %s\n", String8(block.getElementName(&len)).string());
700        return UNKNOWN_ERROR;
701    }
702
703    ResTable_config curParams(defParams);
704
705    ResTable_config pseudoParams(curParams);
706        pseudoParams.language[0] = 'z';
707        pseudoParams.language[1] = 'z';
708        pseudoParams.country[0] = 'Z';
709        pseudoParams.country[1] = 'Z';
710
711    while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
712        if (code == ResXMLTree::START_TAG) {
713            const String16* curTag = NULL;
714            String16 curType;
715            int32_t curFormat = ResTable_map::TYPE_ANY;
716            bool curIsBag = false;
717            bool curIsStyled = false;
718            bool curIsPseudolocalizable = false;
719            bool localHasErrors = false;
720
721            if (strcmp16(block.getElementName(&len), skip16.string()) == 0) {
722                while ((code=block.next()) != ResXMLTree::END_DOCUMENT
723                        && code != ResXMLTree::BAD_DOCUMENT) {
724                    if (code == ResXMLTree::END_TAG) {
725                        if (strcmp16(block.getElementName(&len), skip16.string()) == 0) {
726                            break;
727                        }
728                    }
729                }
730                continue;
731
732            } else if (strcmp16(block.getElementName(&len), eat_comment16.string()) == 0) {
733                while ((code=block.next()) != ResXMLTree::END_DOCUMENT
734                        && code != ResXMLTree::BAD_DOCUMENT) {
735                    if (code == ResXMLTree::END_TAG) {
736                        if (strcmp16(block.getElementName(&len), eat_comment16.string()) == 0) {
737                            break;
738                        }
739                    }
740                }
741                continue;
742
743            } else if (strcmp16(block.getElementName(&len), public16.string()) == 0) {
744                SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
745
746                String16 type;
747                ssize_t typeIdx = block.indexOfAttribute(NULL, "type");
748                if (typeIdx < 0) {
749                    srcPos.error("A 'type' attribute is required for <public>\n");
750                    hasErrors = localHasErrors = true;
751                }
752                type = String16(block.getAttributeStringValue(typeIdx, &len));
753
754                String16 name;
755                ssize_t nameIdx = block.indexOfAttribute(NULL, "name");
756                if (nameIdx < 0) {
757                    srcPos.error("A 'name' attribute is required for <public>\n");
758                    hasErrors = localHasErrors = true;
759                }
760                name = String16(block.getAttributeStringValue(nameIdx, &len));
761
762                uint32_t ident = 0;
763                ssize_t identIdx = block.indexOfAttribute(NULL, "id");
764                if (identIdx >= 0) {
765                    const char16_t* identStr = block.getAttributeStringValue(identIdx, &len);
766                    Res_value identValue;
767                    if (!ResTable::stringToInt(identStr, len, &identValue)) {
768                        srcPos.error("Given 'id' attribute is not an integer: %s\n",
769                                String8(block.getAttributeStringValue(identIdx, &len)).string());
770                        hasErrors = localHasErrors = true;
771                    } else {
772                        ident = identValue.data;
773                        nextPublicId = ident+1;
774                    }
775                } else if (nextPublicId == 0) {
776                    srcPos.error("No 'id' attribute supplied <public>,"
777                            " and no previous id defined in this file.\n");
778                    hasErrors = localHasErrors = true;
779                } else if (!localHasErrors) {
780                    ident = nextPublicId;
781                    nextPublicId++;
782                }
783
784                if (!localHasErrors) {
785                    err = outTable->addPublic(srcPos, myPackage, type, name, ident);
786                    if (err < NO_ERROR) {
787                        hasErrors = localHasErrors = true;
788                    }
789                }
790                if (!localHasErrors) {
791                    sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R"));
792                    if (symbols != NULL) {
793                        symbols = symbols->addNestedSymbol(String8(type), srcPos);
794                    }
795                    if (symbols != NULL) {
796                        symbols->makeSymbolPublic(String8(name), srcPos);
797                        String16 comment(
798                            block.getComment(&len) ? block.getComment(&len) : nulStr);
799                        symbols->appendComment(String8(name), comment, srcPos);
800                    } else {
801                        srcPos.error("Unable to create symbols!\n");
802                        hasErrors = localHasErrors = true;
803                    }
804                }
805
806                while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
807                    if (code == ResXMLTree::END_TAG) {
808                        if (strcmp16(block.getElementName(&len), public16.string()) == 0) {
809                            break;
810                        }
811                    }
812                }
813                continue;
814
815            } else if (strcmp16(block.getElementName(&len), private_symbols16.string()) == 0) {
816                String16 pkg;
817                ssize_t pkgIdx = block.indexOfAttribute(NULL, "package");
818                if (pkgIdx < 0) {
819                    SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
820                            "A 'package' attribute is required for <private-symbols>\n");
821                    hasErrors = localHasErrors = true;
822                }
823                pkg = String16(block.getAttributeStringValue(pkgIdx, &len));
824                if (!localHasErrors) {
825                    assets->setSymbolsPrivatePackage(String8(pkg));
826                }
827
828                while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
829                    if (code == ResXMLTree::END_TAG) {
830                        if (strcmp16(block.getElementName(&len), private_symbols16.string()) == 0) {
831                            break;
832                        }
833                    }
834                }
835                continue;
836
837            } else if (strcmp16(block.getElementName(&len), declare_styleable16.string()) == 0) {
838                SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
839
840                String16 ident;
841                ssize_t identIdx = block.indexOfAttribute(NULL, "name");
842                if (identIdx < 0) {
843                    srcPos.error("A 'name' attribute is required for <declare-styleable>\n");
844                    hasErrors = localHasErrors = true;
845                }
846                ident = String16(block.getAttributeStringValue(identIdx, &len));
847
848                sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R"));
849                if (!localHasErrors) {
850                    if (symbols != NULL) {
851                        symbols = symbols->addNestedSymbol(String8("styleable"), srcPos);
852                    }
853                    sp<AaptSymbols> styleSymbols = symbols;
854                    if (symbols != NULL) {
855                        symbols = symbols->addNestedSymbol(String8(ident), srcPos);
856                    }
857                    if (symbols == NULL) {
858                        srcPos.error("Unable to create symbols!\n");
859                        return UNKNOWN_ERROR;
860                    }
861
862                    String16 comment(
863                        block.getComment(&len) ? block.getComment(&len) : nulStr);
864                    styleSymbols->appendComment(String8(ident), comment, srcPos);
865                } else {
866                    symbols = NULL;
867                }
868
869                while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
870                    if (code == ResXMLTree::START_TAG) {
871                        if (strcmp16(block.getElementName(&len), skip16.string()) == 0) {
872                            while ((code=block.next()) != ResXMLTree::END_DOCUMENT
873                                   && code != ResXMLTree::BAD_DOCUMENT) {
874                                if (code == ResXMLTree::END_TAG) {
875                                    if (strcmp16(block.getElementName(&len), skip16.string()) == 0) {
876                                        break;
877                                    }
878                                }
879                            }
880                            continue;
881                        } else if (strcmp16(block.getElementName(&len), eat_comment16.string()) == 0) {
882                            while ((code=block.next()) != ResXMLTree::END_DOCUMENT
883                                   && code != ResXMLTree::BAD_DOCUMENT) {
884                                if (code == ResXMLTree::END_TAG) {
885                                    if (strcmp16(block.getElementName(&len), eat_comment16.string()) == 0) {
886                                        break;
887                                    }
888                                }
889                            }
890                            continue;
891                        } else if (strcmp16(block.getElementName(&len), attr16.string()) != 0) {
892                            SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
893                                    "Tag <%s> can not appear inside <declare-styleable>, only <attr>\n",
894                                    String8(block.getElementName(&len)).string());
895                            return UNKNOWN_ERROR;
896                        }
897
898                        String16 comment(
899                            block.getComment(&len) ? block.getComment(&len) : nulStr);
900                        String16 itemIdent;
901                        err = compileAttribute(in, block, myPackage, outTable, &itemIdent, true);
902                        if (err != NO_ERROR) {
903                            hasErrors = localHasErrors = true;
904                        }
905
906                        if (symbols != NULL) {
907                            SourcePos srcPos(String8(in->getPrintableSource()), block.getLineNumber());
908                            symbols->addSymbol(String8(itemIdent), 0, srcPos);
909                            symbols->appendComment(String8(itemIdent), comment, srcPos);
910                            //printf("Attribute %s comment: %s\n", String8(itemIdent).string(),
911                            //     String8(comment).string());
912                        }
913                    } else if (code == ResXMLTree::END_TAG) {
914                        if (strcmp16(block.getElementName(&len), declare_styleable16.string()) == 0) {
915                            break;
916                        }
917
918                        SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
919                                "Found tag </%s> where </attr> is expected\n",
920                                String8(block.getElementName(&len)).string());
921                        return UNKNOWN_ERROR;
922                    }
923                }
924                continue;
925
926            } else if (strcmp16(block.getElementName(&len), attr16.string()) == 0) {
927                err = compileAttribute(in, block, myPackage, outTable, NULL);
928                if (err != NO_ERROR) {
929                    hasErrors = true;
930                }
931                continue;
932
933            } else if (strcmp16(block.getElementName(&len), item16.string()) == 0) {
934                curTag = &item16;
935                ssize_t attri = block.indexOfAttribute(NULL, "type");
936                if (attri >= 0) {
937                    curType = String16(block.getAttributeStringValue(attri, &len));
938                    ssize_t formatIdx = block.indexOfAttribute(NULL, "format");
939                    if (formatIdx >= 0) {
940                        String16 formatStr = String16(block.getAttributeStringValue(
941                                formatIdx, &len));
942                        curFormat = parse_flags(formatStr.string(), formatStr.size(),
943                                                gFormatFlags);
944                        if (curFormat == 0) {
945                            SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
946                                    "Tag <item> 'format' attribute value \"%s\" not valid\n",
947                                    String8(formatStr).string());
948                            hasErrors = localHasErrors = true;
949                        }
950                    }
951                } else {
952                    SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
953                            "A 'type' attribute is required for <item>\n");
954                    hasErrors = localHasErrors = true;
955                }
956                curIsStyled = true;
957            } else if (strcmp16(block.getElementName(&len), string16.string()) == 0) {
958                // Note the existence and locale of every string we process
959                char rawLocale[16];
960                curParams.getLocale(rawLocale);
961                String8 locale(rawLocale);
962                String16 name;
963                String16 translatable;
964
965                size_t n = block.getAttributeCount();
966                for (size_t i = 0; i < n; i++) {
967                    size_t length;
968                    const uint16_t* attr = block.getAttributeName(i, &length);
969                    if (strcmp16(attr, name16.string()) == 0) {
970                        name.setTo(block.getAttributeStringValue(i, &length));
971                    } else if (strcmp16(attr, translatable16.string()) == 0) {
972                        translatable.setTo(block.getAttributeStringValue(i, &length));
973                    }
974                }
975
976                if (name.size() > 0) {
977                    if (translatable == false16) {
978                        // Untranslatable strings must only exist in the default [empty] locale
979                        if (locale.size() > 0) {
980                            fprintf(stderr, "aapt: warning: string '%s' in %s marked untranslatable but exists"
981                                    " in locale '%s'\n", String8(name).string(),
982                                    bundle->getResourceSourceDir(),
983                                    locale.string());
984                            // hasErrors = localHasErrors = true;
985                        } else {
986                            // Intentionally empty block:
987                            //
988                            // Don't add untranslatable strings to the localization table; that
989                            // way if we later see localizations of them, they'll be flagged as
990                            // having no default translation.
991                        }
992                    } else {
993                        outTable->addLocalization(name, locale);
994                    }
995                }
996
997                curTag = &string16;
998                curType = string16;
999                curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_STRING;
1000                curIsStyled = true;
1001                curIsPseudolocalizable = true;
1002            } else if (strcmp16(block.getElementName(&len), drawable16.string()) == 0) {
1003                curTag = &drawable16;
1004                curType = drawable16;
1005                curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_COLOR;
1006            } else if (strcmp16(block.getElementName(&len), color16.string()) == 0) {
1007                curTag = &color16;
1008                curType = color16;
1009                curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_COLOR;
1010            } else if (strcmp16(block.getElementName(&len), bool16.string()) == 0) {
1011                curTag = &bool16;
1012                curType = bool16;
1013                curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_BOOLEAN;
1014            } else if (strcmp16(block.getElementName(&len), integer16.string()) == 0) {
1015                curTag = &integer16;
1016                curType = integer16;
1017                curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_INTEGER;
1018            } else if (strcmp16(block.getElementName(&len), dimen16.string()) == 0) {
1019                curTag = &dimen16;
1020                curType = dimen16;
1021                curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_DIMENSION;
1022            } else if (strcmp16(block.getElementName(&len), bag16.string()) == 0) {
1023                curTag = &bag16;
1024                curIsBag = true;
1025                ssize_t attri = block.indexOfAttribute(NULL, "type");
1026                if (attri >= 0) {
1027                    curType = String16(block.getAttributeStringValue(attri, &len));
1028                } else {
1029                    SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1030                            "A 'type' attribute is required for <bag>\n");
1031                    hasErrors = localHasErrors = true;
1032                }
1033            } else if (strcmp16(block.getElementName(&len), style16.string()) == 0) {
1034                curTag = &style16;
1035                curType = style16;
1036                curIsBag = true;
1037            } else if (strcmp16(block.getElementName(&len), plurals16.string()) == 0) {
1038                curTag = &plurals16;
1039                curType = plurals16;
1040                curIsBag = true;
1041            } else if (strcmp16(block.getElementName(&len), array16.string()) == 0) {
1042                curTag = &array16;
1043                curType = array16;
1044                curIsBag = true;
1045                ssize_t formatIdx = block.indexOfAttribute(NULL, "format");
1046                if (formatIdx >= 0) {
1047                    String16 formatStr = String16(block.getAttributeStringValue(
1048                            formatIdx, &len));
1049                    curFormat = parse_flags(formatStr.string(), formatStr.size(),
1050                                            gFormatFlags);
1051                    if (curFormat == 0) {
1052                        SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1053                                "Tag <array> 'format' attribute value \"%s\" not valid\n",
1054                                String8(formatStr).string());
1055                        hasErrors = localHasErrors = true;
1056                    }
1057                }
1058            } else if (strcmp16(block.getElementName(&len), string_array16.string()) == 0) {
1059                curTag = &string_array16;
1060                curType = array16;
1061                curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_STRING;
1062                curIsBag = true;
1063                curIsPseudolocalizable = true;
1064            } else if (strcmp16(block.getElementName(&len), integer_array16.string()) == 0) {
1065                curTag = &integer_array16;
1066                curType = array16;
1067                curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_INTEGER;
1068                curIsBag = true;
1069            } else {
1070                SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1071                        "Found tag %s where item is expected\n",
1072                        String8(block.getElementName(&len)).string());
1073                return UNKNOWN_ERROR;
1074            }
1075
1076            String16 ident;
1077            ssize_t identIdx = block.indexOfAttribute(NULL, "name");
1078            if (identIdx >= 0) {
1079                ident = String16(block.getAttributeStringValue(identIdx, &len));
1080            } else {
1081                SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1082                        "A 'name' attribute is required for <%s>\n",
1083                        String8(*curTag).string());
1084                hasErrors = localHasErrors = true;
1085            }
1086
1087            String16 comment(block.getComment(&len) ? block.getComment(&len) : nulStr);
1088
1089            if (curIsBag) {
1090                // Figure out the parent of this bag...
1091                String16 parentIdent;
1092                ssize_t parentIdentIdx = block.indexOfAttribute(NULL, "parent");
1093                if (parentIdentIdx >= 0) {
1094                    parentIdent = String16(block.getAttributeStringValue(parentIdentIdx, &len));
1095                } else {
1096                    ssize_t sep = ident.findLast('.');
1097                    if (sep >= 0) {
1098                        parentIdent.setTo(ident, sep);
1099                    }
1100                }
1101
1102                if (!localHasErrors) {
1103                    err = outTable->startBag(SourcePos(in->getPrintableSource(), block.getLineNumber()),
1104                                             myPackage, curType, ident, parentIdent, &curParams);
1105                    if (err != NO_ERROR) {
1106                        hasErrors = localHasErrors = true;
1107                    }
1108                }
1109
1110                ssize_t elmIndex = 0;
1111                char elmIndexStr[14];
1112                while ((code=block.next()) != ResXMLTree::END_DOCUMENT
1113                        && code != ResXMLTree::BAD_DOCUMENT) {
1114
1115                    if (code == ResXMLTree::START_TAG) {
1116                        if (strcmp16(block.getElementName(&len), item16.string()) != 0) {
1117                            SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1118                                    "Tag <%s> can not appear inside <%s>, only <item>\n",
1119                                    String8(block.getElementName(&len)).string(),
1120                                    String8(*curTag).string());
1121                            return UNKNOWN_ERROR;
1122                        }
1123
1124                        String16 itemIdent;
1125                        if (curType == array16) {
1126                            sprintf(elmIndexStr, "^index_%d", (int)elmIndex++);
1127                            itemIdent = String16(elmIndexStr);
1128                        } else if (curType == plurals16) {
1129                            ssize_t itemIdentIdx = block.indexOfAttribute(NULL, "quantity");
1130                            if (itemIdentIdx >= 0) {
1131                                String16 quantity16(block.getAttributeStringValue(itemIdentIdx, &len));
1132                                if (quantity16 == other16) {
1133                                    itemIdent = quantityOther16;
1134                                }
1135                                else if (quantity16 == zero16) {
1136                                    itemIdent = quantityZero16;
1137                                }
1138                                else if (quantity16 == one16) {
1139                                    itemIdent = quantityOne16;
1140                                }
1141                                else if (quantity16 == two16) {
1142                                    itemIdent = quantityTwo16;
1143                                }
1144                                else if (quantity16 == few16) {
1145                                    itemIdent = quantityFew16;
1146                                }
1147                                else if (quantity16 == many16) {
1148                                    itemIdent = quantityMany16;
1149                                }
1150                                else {
1151                                    SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1152                                            "Illegal 'quantity' attribute is <item> inside <plurals>\n");
1153                                    hasErrors = localHasErrors = true;
1154                                }
1155                            } else {
1156                                SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1157                                        "A 'quantity' attribute is required for <item> inside <plurals>\n");
1158                                hasErrors = localHasErrors = true;
1159                            }
1160                        } else {
1161                            ssize_t itemIdentIdx = block.indexOfAttribute(NULL, "name");
1162                            if (itemIdentIdx >= 0) {
1163                                itemIdent = String16(block.getAttributeStringValue(itemIdentIdx, &len));
1164                            } else {
1165                                SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1166                                        "A 'name' attribute is required for <item>\n");
1167                                hasErrors = localHasErrors = true;
1168                            }
1169                        }
1170
1171                        ResXMLParser::ResXMLPosition parserPosition;
1172                        block.getPosition(&parserPosition);
1173
1174                        err = parseAndAddBag(bundle, in, &block, curParams, myPackage, curType,
1175                                ident, parentIdent, itemIdent, curFormat, false, outTable);
1176                        if (err == NO_ERROR) {
1177                            if (curIsPseudolocalizable && localeIsDefined(curParams)
1178                                    && bundle->getPseudolocalize()) {
1179                                // pseudolocalize here
1180#if 1
1181                                block.setPosition(parserPosition);
1182                                err = parseAndAddBag(bundle, in, &block, pseudoParams, myPackage,
1183                                        curType, ident, parentIdent, itemIdent, curFormat, true,
1184                                        outTable);
1185#endif
1186                            }
1187                        }
1188                        if (err != NO_ERROR) {
1189                            hasErrors = localHasErrors = true;
1190                        }
1191                    } else if (code == ResXMLTree::END_TAG) {
1192                        if (strcmp16(block.getElementName(&len), curTag->string()) != 0) {
1193                            SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1194                                    "Found tag </%s> where </%s> is expected\n",
1195                                    String8(block.getElementName(&len)).string(),
1196                                    String8(*curTag).string());
1197                            return UNKNOWN_ERROR;
1198                        }
1199                        break;
1200                    }
1201                }
1202            } else {
1203                ResXMLParser::ResXMLPosition parserPosition;
1204                block.getPosition(&parserPosition);
1205
1206                err = parseAndAddEntry(bundle, in, &block, curParams, myPackage, curType, ident,
1207                        *curTag, curIsStyled, curFormat, false, outTable);
1208
1209                if (err < NO_ERROR) { // Why err < NO_ERROR instead of err != NO_ERROR?
1210                    hasErrors = localHasErrors = true;
1211                }
1212                else if (err == NO_ERROR) {
1213                    if (curIsPseudolocalizable && localeIsDefined(curParams)
1214                            && bundle->getPseudolocalize()) {
1215                        // pseudolocalize here
1216                        block.setPosition(parserPosition);
1217                        err = parseAndAddEntry(bundle, in, &block, pseudoParams, myPackage, curType,
1218                                ident, *curTag, curIsStyled, curFormat, true, outTable);
1219                        if (err != NO_ERROR) {
1220                            hasErrors = localHasErrors = true;
1221                        }
1222                    }
1223                }
1224            }
1225
1226#if 0
1227            if (comment.size() > 0) {
1228                printf("Comment for @%s:%s/%s: %s\n", String8(myPackage).string(),
1229                       String8(curType).string(), String8(ident).string(),
1230                       String8(comment).string());
1231            }
1232#endif
1233            if (!localHasErrors) {
1234                outTable->appendComment(myPackage, curType, ident, comment, false);
1235            }
1236        }
1237        else if (code == ResXMLTree::END_TAG) {
1238            if (strcmp16(block.getElementName(&len), resources16.string()) != 0) {
1239                SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1240                        "Unexpected end tag %s\n", String8(block.getElementName(&len)).string());
1241                return UNKNOWN_ERROR;
1242            }
1243        }
1244        else if (code == ResXMLTree::START_NAMESPACE || code == ResXMLTree::END_NAMESPACE) {
1245        }
1246        else if (code == ResXMLTree::TEXT) {
1247            if (isWhitespace(block.getText(&len))) {
1248                continue;
1249            }
1250            SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1251                    "Found text \"%s\" where item tag is expected\n",
1252                    String8(block.getText(&len)).string());
1253            return UNKNOWN_ERROR;
1254        }
1255    }
1256
1257    return hasErrors ? UNKNOWN_ERROR : NO_ERROR;
1258}
1259
1260ResourceTable::ResourceTable(Bundle* bundle, const String16& assetsPackage)
1261    : mAssetsPackage(assetsPackage), mNextPackageId(1), mHaveAppPackage(false),
1262      mIsAppPackage(!bundle->getExtending()),
1263      mNumLocal(0),
1264      mBundle(bundle)
1265{
1266}
1267
1268status_t ResourceTable::addIncludedResources(Bundle* bundle, const sp<AaptAssets>& assets)
1269{
1270    status_t err = assets->buildIncludedResources(bundle);
1271    if (err != NO_ERROR) {
1272        return err;
1273    }
1274
1275    // For future reference to included resources.
1276    mAssets = assets;
1277
1278    const ResTable& incl = assets->getIncludedResources();
1279
1280    // Retrieve all the packages.
1281    const size_t N = incl.getBasePackageCount();
1282    for (size_t phase=0; phase<2; phase++) {
1283        for (size_t i=0; i<N; i++) {
1284            String16 name(incl.getBasePackageName(i));
1285            uint32_t id = incl.getBasePackageId(i);
1286            // First time through: only add base packages (id
1287            // is not 0); second time through add the other
1288            // packages.
1289            if (phase != 0) {
1290                if (id != 0) {
1291                    // Skip base packages -- already one.
1292                    id = 0;
1293                } else {
1294                    // Assign a dynamic id.
1295                    id = mNextPackageId;
1296                }
1297            } else if (id != 0) {
1298                if (id == 127) {
1299                    if (mHaveAppPackage) {
1300                        fprintf(stderr, "Included resource have two application packages!\n");
1301                        return UNKNOWN_ERROR;
1302                    }
1303                    mHaveAppPackage = true;
1304                }
1305                if (mNextPackageId > id) {
1306                    fprintf(stderr, "Included base package ID %d already in use!\n", id);
1307                    return UNKNOWN_ERROR;
1308                }
1309            }
1310            if (id != 0) {
1311                NOISY(printf("Including package %s with ID=%d\n",
1312                             String8(name).string(), id));
1313                sp<Package> p = new Package(name, id);
1314                mPackages.add(name, p);
1315                mOrderedPackages.add(p);
1316
1317                if (id >= mNextPackageId) {
1318                    mNextPackageId = id+1;
1319                }
1320            }
1321        }
1322    }
1323
1324    // Every resource table always has one first entry, the bag attributes.
1325    const SourcePos unknown(String8("????"), 0);
1326    sp<Type> attr = getType(mAssetsPackage, String16("attr"), unknown);
1327
1328    return NO_ERROR;
1329}
1330
1331status_t ResourceTable::addPublic(const SourcePos& sourcePos,
1332                                  const String16& package,
1333                                  const String16& type,
1334                                  const String16& name,
1335                                  const uint32_t ident)
1336{
1337    uint32_t rid = mAssets->getIncludedResources()
1338        .identifierForName(name.string(), name.size(),
1339                           type.string(), type.size(),
1340                           package.string(), package.size());
1341    if (rid != 0) {
1342        sourcePos.error("Error declaring public resource %s/%s for included package %s\n",
1343                String8(type).string(), String8(name).string(),
1344                String8(package).string());
1345        return UNKNOWN_ERROR;
1346    }
1347
1348    sp<Type> t = getType(package, type, sourcePos);
1349    if (t == NULL) {
1350        return UNKNOWN_ERROR;
1351    }
1352    return t->addPublic(sourcePos, name, ident);
1353}
1354
1355status_t ResourceTable::addEntry(const SourcePos& sourcePos,
1356                                 const String16& package,
1357                                 const String16& type,
1358                                 const String16& name,
1359                                 const String16& value,
1360                                 const Vector<StringPool::entry_style_span>* style,
1361                                 const ResTable_config* params,
1362                                 const bool doSetIndex,
1363                                 const int32_t format)
1364{
1365    // Check for adding entries in other packages...  for now we do
1366    // nothing.  We need to do the right thing here to support skinning.
1367    uint32_t rid = mAssets->getIncludedResources()
1368        .identifierForName(name.string(), name.size(),
1369                           type.string(), type.size(),
1370                           package.string(), package.size());
1371    if (rid != 0) {
1372        return NO_ERROR;
1373    }
1374
1375#if 0
1376    if (name == String16("left")) {
1377        printf("Adding entry left: file=%s, line=%d, type=%s, value=%s\n",
1378               sourcePos.file.string(), sourcePos.line, String8(type).string(),
1379               String8(value).string());
1380    }
1381#endif
1382
1383    sp<Entry> e = getEntry(package, type, name, sourcePos, params, doSetIndex);
1384    if (e == NULL) {
1385        return UNKNOWN_ERROR;
1386    }
1387    status_t err = e->setItem(sourcePos, value, style, format);
1388    if (err == NO_ERROR) {
1389        mNumLocal++;
1390    }
1391    return err;
1392}
1393
1394status_t ResourceTable::startBag(const SourcePos& sourcePos,
1395                                 const String16& package,
1396                                 const String16& type,
1397                                 const String16& name,
1398                                 const String16& bagParent,
1399                                 const ResTable_config* params,
1400                                 bool replace, bool isId)
1401{
1402    // Check for adding entries in other packages...  for now we do
1403    // nothing.  We need to do the right thing here to support skinning.
1404    uint32_t rid = mAssets->getIncludedResources()
1405    .identifierForName(name.string(), name.size(),
1406                       type.string(), type.size(),
1407                       package.string(), package.size());
1408    if (rid != 0) {
1409        return NO_ERROR;
1410    }
1411
1412#if 0
1413    if (name == String16("left")) {
1414        printf("Adding bag left: file=%s, line=%d, type=%s\n",
1415               sourcePos.file.striing(), sourcePos.line, String8(type).string());
1416    }
1417#endif
1418
1419    sp<Entry> e = getEntry(package, type, name, sourcePos, params);
1420    if (e == NULL) {
1421        return UNKNOWN_ERROR;
1422    }
1423
1424    // If a parent is explicitly specified, set it.
1425    if (bagParent.size() > 0) {
1426        String16 curPar = e->getParent();
1427        if (curPar.size() > 0 && curPar != bagParent) {
1428            sourcePos.error("Conflicting parents specified, was '%s', now '%s'\n",
1429                            String8(e->getParent()).string(),
1430                            String8(bagParent).string());
1431            return UNKNOWN_ERROR;
1432        }
1433        e->setParent(bagParent);
1434    }
1435
1436    return e->makeItABag(sourcePos);
1437}
1438
1439status_t ResourceTable::addBag(const SourcePos& sourcePos,
1440                               const String16& package,
1441                               const String16& type,
1442                               const String16& name,
1443                               const String16& bagParent,
1444                               const String16& bagKey,
1445                               const String16& value,
1446                               const Vector<StringPool::entry_style_span>* style,
1447                               const ResTable_config* params,
1448                               bool replace, bool isId, const int32_t format)
1449{
1450    // Check for adding entries in other packages...  for now we do
1451    // nothing.  We need to do the right thing here to support skinning.
1452    uint32_t rid = mAssets->getIncludedResources()
1453        .identifierForName(name.string(), name.size(),
1454                           type.string(), type.size(),
1455                           package.string(), package.size());
1456    if (rid != 0) {
1457        return NO_ERROR;
1458    }
1459
1460#if 0
1461    if (name == String16("left")) {
1462        printf("Adding bag left: file=%s, line=%d, type=%s\n",
1463               sourcePos.file.striing(), sourcePos.line, String8(type).string());
1464    }
1465#endif
1466
1467    sp<Entry> e = getEntry(package, type, name, sourcePos, params);
1468    if (e == NULL) {
1469        return UNKNOWN_ERROR;
1470    }
1471
1472    // If a parent is explicitly specified, set it.
1473    if (bagParent.size() > 0) {
1474        String16 curPar = e->getParent();
1475        if (curPar.size() > 0 && curPar != bagParent) {
1476            sourcePos.error("Conflicting parents specified, was '%s', now '%s'\n",
1477                    String8(e->getParent()).string(),
1478                    String8(bagParent).string());
1479            return UNKNOWN_ERROR;
1480        }
1481        e->setParent(bagParent);
1482    }
1483
1484    const bool first = e->getBag().indexOfKey(bagKey) < 0;
1485    status_t err = e->addToBag(sourcePos, bagKey, value, style, replace, isId, format);
1486    if (err == NO_ERROR && first) {
1487        mNumLocal++;
1488    }
1489    return err;
1490}
1491
1492bool ResourceTable::hasBagOrEntry(const String16& package,
1493                                  const String16& type,
1494                                  const String16& name) const
1495{
1496    // First look for this in the included resources...
1497    uint32_t rid = mAssets->getIncludedResources()
1498        .identifierForName(name.string(), name.size(),
1499                           type.string(), type.size(),
1500                           package.string(), package.size());
1501    if (rid != 0) {
1502        return true;
1503    }
1504
1505    sp<Package> p = mPackages.valueFor(package);
1506    if (p != NULL) {
1507        sp<Type> t = p->getTypes().valueFor(type);
1508        if (t != NULL) {
1509            sp<ConfigList> c =  t->getConfigs().valueFor(name);
1510            if (c != NULL) return true;
1511        }
1512    }
1513
1514    return false;
1515}
1516
1517bool ResourceTable::hasBagOrEntry(const String16& ref,
1518                                  const String16* defType,
1519                                  const String16* defPackage)
1520{
1521    String16 package, type, name;
1522    if (!ResTable::expandResourceRef(ref.string(), ref.size(), &package, &type, &name,
1523                defType, defPackage ? defPackage:&mAssetsPackage, NULL)) {
1524        return false;
1525    }
1526    return hasBagOrEntry(package, type, name);
1527}
1528
1529bool ResourceTable::appendComment(const String16& package,
1530                                  const String16& type,
1531                                  const String16& name,
1532                                  const String16& comment,
1533                                  bool onlyIfEmpty)
1534{
1535    if (comment.size() <= 0) {
1536        return true;
1537    }
1538
1539    sp<Package> p = mPackages.valueFor(package);
1540    if (p != NULL) {
1541        sp<Type> t = p->getTypes().valueFor(type);
1542        if (t != NULL) {
1543            sp<ConfigList> c =  t->getConfigs().valueFor(name);
1544            if (c != NULL) {
1545                c->appendComment(comment, onlyIfEmpty);
1546                return true;
1547            }
1548        }
1549    }
1550    return false;
1551}
1552
1553bool ResourceTable::appendTypeComment(const String16& package,
1554                                      const String16& type,
1555                                      const String16& name,
1556                                      const String16& comment)
1557{
1558    if (comment.size() <= 0) {
1559        return true;
1560    }
1561
1562    sp<Package> p = mPackages.valueFor(package);
1563    if (p != NULL) {
1564        sp<Type> t = p->getTypes().valueFor(type);
1565        if (t != NULL) {
1566            sp<ConfigList> c =  t->getConfigs().valueFor(name);
1567            if (c != NULL) {
1568                c->appendTypeComment(comment);
1569                return true;
1570            }
1571        }
1572    }
1573    return false;
1574}
1575
1576size_t ResourceTable::size() const {
1577    return mPackages.size();
1578}
1579
1580size_t ResourceTable::numLocalResources() const {
1581    return mNumLocal;
1582}
1583
1584bool ResourceTable::hasResources() const {
1585    return mNumLocal > 0;
1586}
1587
1588sp<AaptFile> ResourceTable::flatten(Bundle* bundle)
1589{
1590    sp<AaptFile> data = new AaptFile(String8(), AaptGroupEntry(), String8());
1591    status_t err = flatten(bundle, data);
1592    return err == NO_ERROR ? data : NULL;
1593}
1594
1595inline uint32_t ResourceTable::getResId(const sp<Package>& p,
1596                                        const sp<Type>& t,
1597                                        uint32_t nameId)
1598{
1599    return makeResId(p->getAssignedId(), t->getIndex(), nameId);
1600}
1601
1602uint32_t ResourceTable::getResId(const String16& package,
1603                                 const String16& type,
1604                                 const String16& name,
1605                                 bool onlyPublic) const
1606{
1607    sp<Package> p = mPackages.valueFor(package);
1608    if (p == NULL) return 0;
1609
1610    // First look for this in the included resources...
1611    uint32_t specFlags = 0;
1612    uint32_t rid = mAssets->getIncludedResources()
1613        .identifierForName(name.string(), name.size(),
1614                           type.string(), type.size(),
1615                           package.string(), package.size(),
1616                           &specFlags);
1617    if (rid != 0) {
1618        if (onlyPublic) {
1619            if ((specFlags & ResTable_typeSpec::SPEC_PUBLIC) == 0) {
1620                return 0;
1621            }
1622        }
1623
1624        if (Res_INTERNALID(rid)) {
1625            return rid;
1626        }
1627        return Res_MAKEID(p->getAssignedId()-1,
1628                          Res_GETTYPE(rid),
1629                          Res_GETENTRY(rid));
1630    }
1631
1632    sp<Type> t = p->getTypes().valueFor(type);
1633    if (t == NULL) return 0;
1634    sp<ConfigList> c =  t->getConfigs().valueFor(name);
1635    if (c == NULL) return 0;
1636    int32_t ei = c->getEntryIndex();
1637    if (ei < 0) return 0;
1638    return getResId(p, t, ei);
1639}
1640
1641uint32_t ResourceTable::getResId(const String16& ref,
1642                                 const String16* defType,
1643                                 const String16* defPackage,
1644                                 const char** outErrorMsg,
1645                                 bool onlyPublic) const
1646{
1647    String16 package, type, name;
1648    if (!ResTable::expandResourceRef(
1649        ref.string(), ref.size(), &package, &type, &name,
1650        defType, defPackage ? defPackage:&mAssetsPackage,
1651        outErrorMsg)) {
1652        NOISY(printf("Expanding resource: ref=%s\n",
1653                     String8(ref).string()));
1654        NOISY(printf("Expanding resource: defType=%s\n",
1655                     defType ? String8(*defType).string() : "NULL"));
1656        NOISY(printf("Expanding resource: defPackage=%s\n",
1657                     defPackage ? String8(*defPackage).string() : "NULL"));
1658        NOISY(printf("Expanding resource: ref=%s\n", String8(ref).string()));
1659        NOISY(printf("Expanded resource: p=%s, t=%s, n=%s, res=0\n",
1660                     String8(package).string(), String8(type).string(),
1661                     String8(name).string()));
1662        return 0;
1663    }
1664    uint32_t res = getResId(package, type, name, onlyPublic);
1665    NOISY(printf("Expanded resource: p=%s, t=%s, n=%s, res=%d\n",
1666                 String8(package).string(), String8(type).string(),
1667                 String8(name).string(), res));
1668    if (res == 0) {
1669        if (outErrorMsg)
1670            *outErrorMsg = "No resource found that matches the given name";
1671    }
1672    return res;
1673}
1674
1675bool ResourceTable::isValidResourceName(const String16& s)
1676{
1677    const char16_t* p = s.string();
1678    bool first = true;
1679    while (*p) {
1680        if ((*p >= 'a' && *p <= 'z')
1681            || (*p >= 'A' && *p <= 'Z')
1682            || *p == '_'
1683            || (!first && *p >= '0' && *p <= '9')) {
1684            first = false;
1685            p++;
1686            continue;
1687        }
1688        return false;
1689    }
1690    return true;
1691}
1692
1693bool ResourceTable::stringToValue(Res_value* outValue, StringPool* pool,
1694                                  const String16& str,
1695                                  bool preserveSpaces, bool coerceType,
1696                                  uint32_t attrID,
1697                                  const Vector<StringPool::entry_style_span>* style,
1698                                  String16* outStr, void* accessorCookie,
1699                                  uint32_t attrType)
1700{
1701    String16 finalStr;
1702
1703    bool res = true;
1704    if (style == NULL || style->size() == 0) {
1705        // Text is not styled so it can be any type...  let's figure it out.
1706        res = mAssets->getIncludedResources()
1707            .stringToValue(outValue, &finalStr, str.string(), str.size(), preserveSpaces,
1708                            coerceType, attrID, NULL, &mAssetsPackage, this,
1709                           accessorCookie, attrType);
1710    } else {
1711        // Styled text can only be a string, and while collecting the style
1712        // information we have already processed that string!
1713        outValue->size = sizeof(Res_value);
1714        outValue->res0 = 0;
1715        outValue->dataType = outValue->TYPE_STRING;
1716        outValue->data = 0;
1717        finalStr = str;
1718    }
1719
1720    if (!res) {
1721        return false;
1722    }
1723
1724    if (outValue->dataType == outValue->TYPE_STRING) {
1725        // Should do better merging styles.
1726        if (pool) {
1727            if (style != NULL && style->size() > 0) {
1728                outValue->data = pool->add(finalStr, *style);
1729            } else {
1730                outValue->data = pool->add(finalStr, true);
1731            }
1732        } else {
1733            // Caller will fill this in later.
1734            outValue->data = 0;
1735        }
1736
1737        if (outStr) {
1738            *outStr = finalStr;
1739        }
1740
1741    }
1742
1743    return true;
1744}
1745
1746uint32_t ResourceTable::getCustomResource(
1747    const String16& package, const String16& type, const String16& name) const
1748{
1749    //printf("getCustomResource: %s %s %s\n", String8(package).string(),
1750    //       String8(type).string(), String8(name).string());
1751    sp<Package> p = mPackages.valueFor(package);
1752    if (p == NULL) return 0;
1753    sp<Type> t = p->getTypes().valueFor(type);
1754    if (t == NULL) return 0;
1755    sp<ConfigList> c =  t->getConfigs().valueFor(name);
1756    if (c == NULL) return 0;
1757    int32_t ei = c->getEntryIndex();
1758    if (ei < 0) return 0;
1759    return getResId(p, t, ei);
1760}
1761
1762uint32_t ResourceTable::getCustomResourceWithCreation(
1763        const String16& package, const String16& type, const String16& name,
1764        const bool createIfNotFound)
1765{
1766    uint32_t resId = getCustomResource(package, type, name);
1767    if (resId != 0 || !createIfNotFound) {
1768        return resId;
1769    }
1770    String16 value("false");
1771
1772    status_t status = addEntry(mCurrentXmlPos, package, type, name, value, NULL, NULL, true);
1773    if (status == NO_ERROR) {
1774        resId = getResId(package, type, name);
1775        return resId;
1776    }
1777    return 0;
1778}
1779
1780uint32_t ResourceTable::getRemappedPackage(uint32_t origPackage) const
1781{
1782    return origPackage;
1783}
1784
1785bool ResourceTable::getAttributeType(uint32_t attrID, uint32_t* outType)
1786{
1787    //printf("getAttributeType #%08x\n", attrID);
1788    Res_value value;
1789    if (getItemValue(attrID, ResTable_map::ATTR_TYPE, &value)) {
1790        //printf("getAttributeType #%08x (%s): #%08x\n", attrID,
1791        //       String8(getEntry(attrID)->getName()).string(), value.data);
1792        *outType = value.data;
1793        return true;
1794    }
1795    return false;
1796}
1797
1798bool ResourceTable::getAttributeMin(uint32_t attrID, uint32_t* outMin)
1799{
1800    //printf("getAttributeMin #%08x\n", attrID);
1801    Res_value value;
1802    if (getItemValue(attrID, ResTable_map::ATTR_MIN, &value)) {
1803        *outMin = value.data;
1804        return true;
1805    }
1806    return false;
1807}
1808
1809bool ResourceTable::getAttributeMax(uint32_t attrID, uint32_t* outMax)
1810{
1811    //printf("getAttributeMax #%08x\n", attrID);
1812    Res_value value;
1813    if (getItemValue(attrID, ResTable_map::ATTR_MAX, &value)) {
1814        *outMax = value.data;
1815        return true;
1816    }
1817    return false;
1818}
1819
1820uint32_t ResourceTable::getAttributeL10N(uint32_t attrID)
1821{
1822    //printf("getAttributeL10N #%08x\n", attrID);
1823    Res_value value;
1824    if (getItemValue(attrID, ResTable_map::ATTR_L10N, &value)) {
1825        return value.data;
1826    }
1827    return ResTable_map::L10N_NOT_REQUIRED;
1828}
1829
1830bool ResourceTable::getLocalizationSetting()
1831{
1832    return mBundle->getRequireLocalization();
1833}
1834
1835void ResourceTable::reportError(void* accessorCookie, const char* fmt, ...)
1836{
1837    if (accessorCookie != NULL && fmt != NULL) {
1838        AccessorCookie* ac = (AccessorCookie*)accessorCookie;
1839        int retval=0;
1840        char buf[1024];
1841        va_list ap;
1842        va_start(ap, fmt);
1843        retval = vsnprintf(buf, sizeof(buf), fmt, ap);
1844        va_end(ap);
1845        ac->sourcePos.error("Error: %s (at '%s' with value '%s').\n",
1846                            buf, ac->attr.string(), ac->value.string());
1847    }
1848}
1849
1850bool ResourceTable::getAttributeKeys(
1851    uint32_t attrID, Vector<String16>* outKeys)
1852{
1853    sp<const Entry> e = getEntry(attrID);
1854    if (e != NULL) {
1855        const size_t N = e->getBag().size();
1856        for (size_t i=0; i<N; i++) {
1857            const String16& key = e->getBag().keyAt(i);
1858            if (key.size() > 0 && key.string()[0] != '^') {
1859                outKeys->add(key);
1860            }
1861        }
1862        return true;
1863    }
1864    return false;
1865}
1866
1867bool ResourceTable::getAttributeEnum(
1868    uint32_t attrID, const char16_t* name, size_t nameLen,
1869    Res_value* outValue)
1870{
1871    //printf("getAttributeEnum #%08x %s\n", attrID, String8(name, nameLen).string());
1872    String16 nameStr(name, nameLen);
1873    sp<const Entry> e = getEntry(attrID);
1874    if (e != NULL) {
1875        const size_t N = e->getBag().size();
1876        for (size_t i=0; i<N; i++) {
1877            //printf("Comparing %s to %s\n", String8(name, nameLen).string(),
1878            //       String8(e->getBag().keyAt(i)).string());
1879            if (e->getBag().keyAt(i) == nameStr) {
1880                return getItemValue(attrID, e->getBag().valueAt(i).bagKeyId, outValue);
1881            }
1882        }
1883    }
1884    return false;
1885}
1886
1887bool ResourceTable::getAttributeFlags(
1888    uint32_t attrID, const char16_t* name, size_t nameLen,
1889    Res_value* outValue)
1890{
1891    outValue->dataType = Res_value::TYPE_INT_HEX;
1892    outValue->data = 0;
1893
1894    //printf("getAttributeFlags #%08x %s\n", attrID, String8(name, nameLen).string());
1895    String16 nameStr(name, nameLen);
1896    sp<const Entry> e = getEntry(attrID);
1897    if (e != NULL) {
1898        const size_t N = e->getBag().size();
1899
1900        const char16_t* end = name + nameLen;
1901        const char16_t* pos = name;
1902        bool failed = false;
1903        while (pos < end && !failed) {
1904            const char16_t* start = pos;
1905            end++;
1906            while (pos < end && *pos != '|') {
1907                pos++;
1908            }
1909
1910            String16 nameStr(start, pos-start);
1911            size_t i;
1912            for (i=0; i<N; i++) {
1913                //printf("Comparing \"%s\" to \"%s\"\n", String8(nameStr).string(),
1914                //       String8(e->getBag().keyAt(i)).string());
1915                if (e->getBag().keyAt(i) == nameStr) {
1916                    Res_value val;
1917                    bool got = getItemValue(attrID, e->getBag().valueAt(i).bagKeyId, &val);
1918                    if (!got) {
1919                        return false;
1920                    }
1921                    //printf("Got value: 0x%08x\n", val.data);
1922                    outValue->data |= val.data;
1923                    break;
1924                }
1925            }
1926
1927            if (i >= N) {
1928                // Didn't find this flag identifier.
1929                return false;
1930            }
1931            if (pos < end) {
1932                pos++;
1933            }
1934        }
1935
1936        return true;
1937    }
1938    return false;
1939}
1940
1941status_t ResourceTable::assignResourceIds()
1942{
1943    const size_t N = mOrderedPackages.size();
1944    size_t pi;
1945    status_t firstError = NO_ERROR;
1946
1947    // First generate all bag attributes and assign indices.
1948    for (pi=0; pi<N; pi++) {
1949        sp<Package> p = mOrderedPackages.itemAt(pi);
1950        if (p == NULL || p->getTypes().size() == 0) {
1951            // Empty, skip!
1952            continue;
1953        }
1954
1955        status_t err = p->applyPublicTypeOrder();
1956        if (err != NO_ERROR && firstError == NO_ERROR) {
1957            firstError = err;
1958        }
1959
1960        // Generate attributes...
1961        const size_t N = p->getOrderedTypes().size();
1962        size_t ti;
1963        for (ti=0; ti<N; ti++) {
1964            sp<Type> t = p->getOrderedTypes().itemAt(ti);
1965            if (t == NULL) {
1966                continue;
1967            }
1968            const size_t N = t->getOrderedConfigs().size();
1969            for (size_t ci=0; ci<N; ci++) {
1970                sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
1971                if (c == NULL) {
1972                    continue;
1973                }
1974                const size_t N = c->getEntries().size();
1975                for (size_t ei=0; ei<N; ei++) {
1976                    sp<Entry> e = c->getEntries().valueAt(ei);
1977                    if (e == NULL) {
1978                        continue;
1979                    }
1980                    status_t err = e->generateAttributes(this, p->getName());
1981                    if (err != NO_ERROR && firstError == NO_ERROR) {
1982                        firstError = err;
1983                    }
1984                }
1985            }
1986        }
1987
1988        const SourcePos unknown(String8("????"), 0);
1989        sp<Type> attr = p->getType(String16("attr"), unknown);
1990
1991        // Assign indices...
1992        for (ti=0; ti<N; ti++) {
1993            sp<Type> t = p->getOrderedTypes().itemAt(ti);
1994            if (t == NULL) {
1995                continue;
1996            }
1997            err = t->applyPublicEntryOrder();
1998            if (err != NO_ERROR && firstError == NO_ERROR) {
1999                firstError = err;
2000            }
2001
2002            const size_t N = t->getOrderedConfigs().size();
2003            t->setIndex(ti+1);
2004
2005            LOG_ALWAYS_FATAL_IF(ti == 0 && attr != t,
2006                                "First type is not attr!");
2007
2008            for (size_t ei=0; ei<N; ei++) {
2009                sp<ConfigList> c = t->getOrderedConfigs().itemAt(ei);
2010                if (c == NULL) {
2011                    continue;
2012                }
2013                c->setEntryIndex(ei);
2014            }
2015        }
2016
2017        // Assign resource IDs to keys in bags...
2018        for (ti=0; ti<N; ti++) {
2019            sp<Type> t = p->getOrderedTypes().itemAt(ti);
2020            if (t == NULL) {
2021                continue;
2022            }
2023            const size_t N = t->getOrderedConfigs().size();
2024            for (size_t ci=0; ci<N; ci++) {
2025                sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2026                //printf("Ordered config #%d: %p\n", ci, c.get());
2027                const size_t N = c->getEntries().size();
2028                for (size_t ei=0; ei<N; ei++) {
2029                    sp<Entry> e = c->getEntries().valueAt(ei);
2030                    if (e == NULL) {
2031                        continue;
2032                    }
2033                    status_t err = e->assignResourceIds(this, p->getName());
2034                    if (err != NO_ERROR && firstError == NO_ERROR) {
2035                        firstError = err;
2036                    }
2037                }
2038            }
2039        }
2040    }
2041    return firstError;
2042}
2043
2044status_t ResourceTable::addSymbols(const sp<AaptSymbols>& outSymbols) {
2045    const size_t N = mOrderedPackages.size();
2046    size_t pi;
2047
2048    for (pi=0; pi<N; pi++) {
2049        sp<Package> p = mOrderedPackages.itemAt(pi);
2050        if (p->getTypes().size() == 0) {
2051            // Empty, skip!
2052            continue;
2053        }
2054
2055        const size_t N = p->getOrderedTypes().size();
2056        size_t ti;
2057
2058        for (ti=0; ti<N; ti++) {
2059            sp<Type> t = p->getOrderedTypes().itemAt(ti);
2060            if (t == NULL) {
2061                continue;
2062            }
2063            const size_t N = t->getOrderedConfigs().size();
2064            sp<AaptSymbols> typeSymbols;
2065            typeSymbols = outSymbols->addNestedSymbol(String8(t->getName()), t->getPos());
2066            for (size_t ci=0; ci<N; ci++) {
2067                sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2068                if (c == NULL) {
2069                    continue;
2070                }
2071                uint32_t rid = getResId(p, t, ci);
2072                if (rid == 0) {
2073                    return UNKNOWN_ERROR;
2074                }
2075                if (Res_GETPACKAGE(rid) == (size_t)(p->getAssignedId()-1)) {
2076                    typeSymbols->addSymbol(String8(c->getName()), rid, c->getPos());
2077
2078                    String16 comment(c->getComment());
2079                    typeSymbols->appendComment(String8(c->getName()), comment, c->getPos());
2080                    //printf("Type symbol %s comment: %s\n", String8(e->getName()).string(),
2081                    //     String8(comment).string());
2082                    comment = c->getTypeComment();
2083                    typeSymbols->appendTypeComment(String8(c->getName()), comment);
2084                } else {
2085#if 0
2086                    printf("**** NO MATCH: 0x%08x vs 0x%08x\n",
2087                           Res_GETPACKAGE(rid), p->getAssignedId());
2088#endif
2089                }
2090            }
2091        }
2092    }
2093    return NO_ERROR;
2094}
2095
2096
2097void
2098ResourceTable::addLocalization(const String16& name, const String8& locale)
2099{
2100    mLocalizations[name].insert(locale);
2101}
2102
2103
2104/*!
2105 * Flag various sorts of localization problems.  '+' indicates checks already implemented;
2106 * '-' indicates checks that will be implemented in the future.
2107 *
2108 * + A localized string for which no default-locale version exists => warning
2109 * + A string for which no version in an explicitly-requested locale exists => warning
2110 * + A localized translation of an translateable="false" string => warning
2111 * - A localized string not provided in every locale used by the table
2112 */
2113status_t
2114ResourceTable::validateLocalizations(void)
2115{
2116    status_t err = NO_ERROR;
2117    const String8 defaultLocale;
2118
2119    // For all strings...
2120    for (map<String16, set<String8> >::iterator nameIter = mLocalizations.begin();
2121         nameIter != mLocalizations.end();
2122         nameIter++) {
2123        const set<String8>& configSet = nameIter->second;   // naming convenience
2124
2125        // Look for strings with no default localization
2126        if (configSet.count(defaultLocale) == 0) {
2127            fprintf(stdout, "aapt: warning: string '%s' has no default translation in %s; found:",
2128                    String8(nameIter->first).string(), mBundle->getResourceSourceDir());
2129            for (set<String8>::iterator locales = configSet.begin();
2130                 locales != configSet.end();
2131                 locales++) {
2132                fprintf(stdout, " %s", (*locales).string());
2133            }
2134            fprintf(stdout, "\n");
2135            // !!! TODO: throw an error here in some circumstances
2136        }
2137
2138        // Check that all requested localizations are present for this string
2139        if (mBundle->getConfigurations() != NULL && mBundle->getRequireLocalization()) {
2140            const char* allConfigs = mBundle->getConfigurations();
2141            const char* start = allConfigs;
2142            const char* comma;
2143
2144            do {
2145                String8 config;
2146                comma = strchr(start, ',');
2147                if (comma != NULL) {
2148                    config.setTo(start, comma - start);
2149                    start = comma + 1;
2150                } else {
2151                    config.setTo(start);
2152                }
2153
2154                // don't bother with the pseudolocale "zz_ZZ"
2155                if (config != "zz_ZZ") {
2156                    if (configSet.find(config) == configSet.end()) {
2157                        // okay, no specific localization found.  it's possible that we are
2158                        // requiring a specific regional localization [e.g. de_DE] but there is an
2159                        // available string in the generic language localization [e.g. de];
2160                        // consider that string to have fulfilled the localization requirement.
2161                        String8 region(config.string(), 2);
2162                        if (configSet.find(region) == configSet.end()) {
2163                            // TODO: force an error if there is no default to fall back to
2164                            if (configSet.count(defaultLocale) == 0) {
2165                                fprintf(stdout, "aapt: warning: "
2166                                        "*** string '%s' has no default or required localization "
2167                                        "for '%s' in %s\n",
2168                                        String8(nameIter->first).string(),
2169                                        config.string(),
2170                                        mBundle->getResourceSourceDir());
2171                                //err = UNKNOWN_ERROR;
2172                            }
2173                        }
2174                    }
2175                }
2176           } while (comma != NULL);
2177        }
2178    }
2179
2180    return err;
2181}
2182
2183
2184status_t
2185ResourceFilter::parse(const char* arg)
2186{
2187    if (arg == NULL) {
2188        return 0;
2189    }
2190
2191    const char* p = arg;
2192    const char* q;
2193
2194    while (true) {
2195        q = strchr(p, ',');
2196        if (q == NULL) {
2197            q = p + strlen(p);
2198        }
2199
2200        String8 part(p, q-p);
2201
2202        if (part == "zz_ZZ") {
2203            mContainsPseudo = true;
2204        }
2205        int axis;
2206        uint32_t value;
2207        if (AaptGroupEntry::parseNamePart(part, &axis, &value)) {
2208            fprintf(stderr, "Invalid configuration: %s\n", arg);
2209            fprintf(stderr, "                       ");
2210            for (int i=0; i<p-arg; i++) {
2211                fprintf(stderr, " ");
2212            }
2213            for (int i=0; i<q-p; i++) {
2214                fprintf(stderr, "^");
2215            }
2216            fprintf(stderr, "\n");
2217            return 1;
2218        }
2219
2220        ssize_t index = mData.indexOfKey(axis);
2221        if (index < 0) {
2222            mData.add(axis, SortedVector<uint32_t>());
2223        }
2224        SortedVector<uint32_t>& sv = mData.editValueFor(axis);
2225        sv.add(value);
2226        // if it's a locale with a region, also match an unmodified locale of the
2227        // same language
2228        if (axis == AXIS_LANGUAGE) {
2229            if (value & 0xffff0000) {
2230                sv.add(value & 0x0000ffff);
2231            }
2232        }
2233        p = q;
2234        if (!*p) break;
2235        p++;
2236    }
2237
2238    return NO_ERROR;
2239}
2240
2241bool
2242ResourceFilter::match(int axis, uint32_t value)
2243{
2244    if (value == 0) {
2245        // they didn't specify anything so take everything
2246        return true;
2247    }
2248    ssize_t index = mData.indexOfKey(axis);
2249    if (index < 0) {
2250        // we didn't request anything on this axis so take everything
2251        return true;
2252    }
2253    const SortedVector<uint32_t>& sv = mData.valueAt(index);
2254    return sv.indexOf(value) >= 0;
2255}
2256
2257bool
2258ResourceFilter::match(const ResTable_config& config)
2259{
2260    if (config.locale) {
2261        uint32_t locale = (config.country[1] << 24) | (config.country[0] << 16)
2262                | (config.language[1] << 8) | (config.language[0]);
2263        if (!match(AXIS_LANGUAGE, locale)) {
2264            return false;
2265        }
2266    }
2267    if (!match(AXIS_ORIENTATION, config.orientation)) {
2268        return false;
2269    }
2270    if (!match(AXIS_DENSITY, config.density)) {
2271        return false;
2272    }
2273    if (!match(AXIS_TOUCHSCREEN, config.touchscreen)) {
2274        return false;
2275    }
2276    if (!match(AXIS_KEYSHIDDEN, config.inputFlags)) {
2277        return false;
2278    }
2279    if (!match(AXIS_KEYBOARD, config.keyboard)) {
2280        return false;
2281    }
2282    if (!match(AXIS_NAVIGATION, config.navigation)) {
2283        return false;
2284    }
2285    if (!match(AXIS_SCREENSIZE, config.screenSize)) {
2286        return false;
2287    }
2288    if (!match(AXIS_VERSION, config.version)) {
2289        return false;
2290    }
2291    return true;
2292}
2293
2294status_t ResourceTable::flatten(Bundle* bundle, const sp<AaptFile>& dest)
2295{
2296    ResourceFilter filter;
2297    status_t err = filter.parse(bundle->getConfigurations());
2298    if (err != NO_ERROR) {
2299        return err;
2300    }
2301
2302    const size_t N = mOrderedPackages.size();
2303    size_t pi;
2304
2305    // Iterate through all data, collecting all values (strings,
2306    // references, etc).
2307    StringPool valueStrings;
2308    for (pi=0; pi<N; pi++) {
2309        sp<Package> p = mOrderedPackages.itemAt(pi);
2310        if (p->getTypes().size() == 0) {
2311            // Empty, skip!
2312            continue;
2313        }
2314
2315        StringPool typeStrings;
2316        StringPool keyStrings;
2317
2318        const size_t N = p->getOrderedTypes().size();
2319        for (size_t ti=0; ti<N; ti++) {
2320            sp<Type> t = p->getOrderedTypes().itemAt(ti);
2321            if (t == NULL) {
2322                typeStrings.add(String16("<empty>"), false);
2323                continue;
2324            }
2325            typeStrings.add(t->getName(), false);
2326
2327            const size_t N = t->getOrderedConfigs().size();
2328            for (size_t ci=0; ci<N; ci++) {
2329                sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2330                if (c == NULL) {
2331                    continue;
2332                }
2333                const size_t N = c->getEntries().size();
2334                for (size_t ei=0; ei<N; ei++) {
2335                    ConfigDescription config = c->getEntries().keyAt(ei);
2336                    if (!filter.match(config)) {
2337                        continue;
2338                    }
2339                    sp<Entry> e = c->getEntries().valueAt(ei);
2340                    if (e == NULL) {
2341                        continue;
2342                    }
2343                    e->setNameIndex(keyStrings.add(e->getName(), true));
2344                    status_t err = e->prepareFlatten(&valueStrings, this);
2345                    if (err != NO_ERROR) {
2346                        return err;
2347                    }
2348                }
2349            }
2350        }
2351
2352        p->setTypeStrings(typeStrings.createStringBlock());
2353        p->setKeyStrings(keyStrings.createStringBlock());
2354    }
2355
2356    ssize_t strAmt = 0;
2357
2358    // Now build the array of package chunks.
2359    Vector<sp<AaptFile> > flatPackages;
2360    for (pi=0; pi<N; pi++) {
2361        sp<Package> p = mOrderedPackages.itemAt(pi);
2362        if (p->getTypes().size() == 0) {
2363            // Empty, skip!
2364            continue;
2365        }
2366
2367        const size_t N = p->getTypeStrings().size();
2368
2369        const size_t baseSize = sizeof(ResTable_package);
2370
2371        // Start the package data.
2372        sp<AaptFile> data = new AaptFile(String8(), AaptGroupEntry(), String8());
2373        ResTable_package* header = (ResTable_package*)data->editData(baseSize);
2374        if (header == NULL) {
2375            fprintf(stderr, "ERROR: out of memory creating ResTable_package\n");
2376            return NO_MEMORY;
2377        }
2378        memset(header, 0, sizeof(*header));
2379        header->header.type = htods(RES_TABLE_PACKAGE_TYPE);
2380        header->header.headerSize = htods(sizeof(*header));
2381        header->id = htodl(p->getAssignedId());
2382        strcpy16_htod(header->name, p->getName().string());
2383
2384        // Write the string blocks.
2385        const size_t typeStringsStart = data->getSize();
2386        sp<AaptFile> strFile = p->getTypeStringsData();
2387        ssize_t amt = data->writeData(strFile->getData(), strFile->getSize());
2388        #if PRINT_STRING_METRICS
2389        fprintf(stderr, "**** type strings: %d\n", amt);
2390        #endif
2391        strAmt += amt;
2392        if (amt < 0) {
2393            return amt;
2394        }
2395        const size_t keyStringsStart = data->getSize();
2396        strFile = p->getKeyStringsData();
2397        amt = data->writeData(strFile->getData(), strFile->getSize());
2398        #if PRINT_STRING_METRICS
2399        fprintf(stderr, "**** key strings: %d\n", amt);
2400        #endif
2401        strAmt += amt;
2402        if (amt < 0) {
2403            return amt;
2404        }
2405
2406        // Build the type chunks inside of this package.
2407        for (size_t ti=0; ti<N; ti++) {
2408            // Retrieve them in the same order as the type string block.
2409            size_t len;
2410            String16 typeName(p->getTypeStrings().stringAt(ti, &len));
2411            sp<Type> t = p->getTypes().valueFor(typeName);
2412            LOG_ALWAYS_FATAL_IF(t == NULL && typeName != String16("<empty>"),
2413                                "Type name %s not found",
2414                                String8(typeName).string());
2415
2416            const size_t N = t != NULL ? t->getOrderedConfigs().size() : 0;
2417
2418            // First write the typeSpec chunk, containing information about
2419            // each resource entry in this type.
2420            {
2421                const size_t typeSpecSize = sizeof(ResTable_typeSpec) + sizeof(uint32_t)*N;
2422                const size_t typeSpecStart = data->getSize();
2423                ResTable_typeSpec* tsHeader = (ResTable_typeSpec*)
2424                    (((uint8_t*)data->editData(typeSpecStart+typeSpecSize)) + typeSpecStart);
2425                if (tsHeader == NULL) {
2426                    fprintf(stderr, "ERROR: out of memory creating ResTable_typeSpec\n");
2427                    return NO_MEMORY;
2428                }
2429                memset(tsHeader, 0, sizeof(*tsHeader));
2430                tsHeader->header.type = htods(RES_TABLE_TYPE_SPEC_TYPE);
2431                tsHeader->header.headerSize = htods(sizeof(*tsHeader));
2432                tsHeader->header.size = htodl(typeSpecSize);
2433                tsHeader->id = ti+1;
2434                tsHeader->entryCount = htodl(N);
2435
2436                uint32_t* typeSpecFlags = (uint32_t*)
2437                    (((uint8_t*)data->editData())
2438                        + typeSpecStart + sizeof(ResTable_typeSpec));
2439                memset(typeSpecFlags, 0, sizeof(uint32_t)*N);
2440
2441                for (size_t ei=0; ei<N; ei++) {
2442                    sp<ConfigList> cl = t->getOrderedConfigs().itemAt(ei);
2443                    if (cl->getPublic()) {
2444                        typeSpecFlags[ei] |= htodl(ResTable_typeSpec::SPEC_PUBLIC);
2445                    }
2446                    const size_t CN = cl->getEntries().size();
2447                    for (size_t ci=0; ci<CN; ci++) {
2448                        if (!filter.match(cl->getEntries().keyAt(ci))) {
2449                            continue;
2450                        }
2451                        for (size_t cj=ci+1; cj<CN; cj++) {
2452                            if (!filter.match(cl->getEntries().keyAt(cj))) {
2453                                continue;
2454                            }
2455                            typeSpecFlags[ei] |= htodl(
2456                                cl->getEntries().keyAt(ci).diff(cl->getEntries().keyAt(cj)));
2457                        }
2458                    }
2459                }
2460            }
2461
2462            // We need to write one type chunk for each configuration for
2463            // which we have entries in this type.
2464            const size_t NC = t->getUniqueConfigs().size();
2465
2466            const size_t typeSize = sizeof(ResTable_type) + sizeof(uint32_t)*N;
2467
2468            for (size_t ci=0; ci<NC; ci++) {
2469                ConfigDescription config = t->getUniqueConfigs().itemAt(ci);
2470
2471                NOISY(printf("Writing config %d config: imsi:%d/%d lang:%c%c cnt:%c%c "
2472                     "orien:%d touch:%d density:%d key:%d inp:%d nav:%d w:%d h:%d\n",
2473                      ti+1,
2474                      config.mcc, config.mnc,
2475                      config.language[0] ? config.language[0] : '-',
2476                      config.language[1] ? config.language[1] : '-',
2477                      config.country[0] ? config.country[0] : '-',
2478                      config.country[1] ? config.country[1] : '-',
2479                      config.orientation,
2480                      config.touchscreen,
2481                      config.density,
2482                      config.keyboard,
2483                      config.inputFlags,
2484                      config.navigation,
2485                      config.screenWidth,
2486                      config.screenHeight));
2487
2488                if (!filter.match(config)) {
2489                    continue;
2490                }
2491
2492                const size_t typeStart = data->getSize();
2493
2494                ResTable_type* tHeader = (ResTable_type*)
2495                    (((uint8_t*)data->editData(typeStart+typeSize)) + typeStart);
2496                if (tHeader == NULL) {
2497                    fprintf(stderr, "ERROR: out of memory creating ResTable_type\n");
2498                    return NO_MEMORY;
2499                }
2500
2501                memset(tHeader, 0, sizeof(*tHeader));
2502                tHeader->header.type = htods(RES_TABLE_TYPE_TYPE);
2503                tHeader->header.headerSize = htods(sizeof(*tHeader));
2504                tHeader->id = ti+1;
2505                tHeader->entryCount = htodl(N);
2506                tHeader->entriesStart = htodl(typeSize);
2507                tHeader->config = config;
2508                NOISY(printf("Writing type %d config: imsi:%d/%d lang:%c%c cnt:%c%c "
2509                     "orien:%d touch:%d density:%d key:%d inp:%d nav:%d w:%d h:%d\n",
2510                      ti+1,
2511                      tHeader->config.mcc, tHeader->config.mnc,
2512                      tHeader->config.language[0] ? tHeader->config.language[0] : '-',
2513                      tHeader->config.language[1] ? tHeader->config.language[1] : '-',
2514                      tHeader->config.country[0] ? tHeader->config.country[0] : '-',
2515                      tHeader->config.country[1] ? tHeader->config.country[1] : '-',
2516                      tHeader->config.orientation,
2517                      tHeader->config.touchscreen,
2518                      tHeader->config.density,
2519                      tHeader->config.keyboard,
2520                      tHeader->config.inputFlags,
2521                      tHeader->config.navigation,
2522                      tHeader->config.screenWidth,
2523                      tHeader->config.screenHeight));
2524                tHeader->config.swapHtoD();
2525
2526                // Build the entries inside of this type.
2527                for (size_t ei=0; ei<N; ei++) {
2528                    sp<ConfigList> cl = t->getOrderedConfigs().itemAt(ei);
2529                    sp<Entry> e = cl->getEntries().valueFor(config);
2530
2531                    // Set the offset for this entry in its type.
2532                    uint32_t* index = (uint32_t*)
2533                        (((uint8_t*)data->editData())
2534                            + typeStart + sizeof(ResTable_type));
2535                    if (e != NULL) {
2536                        index[ei] = htodl(data->getSize()-typeStart-typeSize);
2537
2538                        // Create the entry.
2539                        ssize_t amt = e->flatten(bundle, data, cl->getPublic());
2540                        if (amt < 0) {
2541                            return amt;
2542                        }
2543                    } else {
2544                        index[ei] = htodl(ResTable_type::NO_ENTRY);
2545                    }
2546                }
2547
2548                // Fill in the rest of the type information.
2549                tHeader = (ResTable_type*)
2550                    (((uint8_t*)data->editData()) + typeStart);
2551                tHeader->header.size = htodl(data->getSize()-typeStart);
2552            }
2553        }
2554
2555        // Fill in the rest of the package information.
2556        header = (ResTable_package*)data->editData();
2557        header->header.size = htodl(data->getSize());
2558        header->typeStrings = htodl(typeStringsStart);
2559        header->lastPublicType = htodl(p->getTypeStrings().size());
2560        header->keyStrings = htodl(keyStringsStart);
2561        header->lastPublicKey = htodl(p->getKeyStrings().size());
2562
2563        flatPackages.add(data);
2564    }
2565
2566    // And now write out the final chunks.
2567    const size_t dataStart = dest->getSize();
2568
2569    {
2570        // blah
2571        ResTable_header header;
2572        memset(&header, 0, sizeof(header));
2573        header.header.type = htods(RES_TABLE_TYPE);
2574        header.header.headerSize = htods(sizeof(header));
2575        header.packageCount = htodl(flatPackages.size());
2576        status_t err = dest->writeData(&header, sizeof(header));
2577        if (err != NO_ERROR) {
2578            fprintf(stderr, "ERROR: out of memory creating ResTable_header\n");
2579            return err;
2580        }
2581    }
2582
2583    ssize_t strStart = dest->getSize();
2584    err = valueStrings.writeStringBlock(dest);
2585    if (err != NO_ERROR) {
2586        return err;
2587    }
2588
2589    ssize_t amt = (dest->getSize()-strStart);
2590    strAmt += amt;
2591    #if PRINT_STRING_METRICS
2592    fprintf(stderr, "**** value strings: %d\n", amt);
2593    fprintf(stderr, "**** total strings: %d\n", strAmt);
2594    #endif
2595
2596    for (pi=0; pi<flatPackages.size(); pi++) {
2597        err = dest->writeData(flatPackages[pi]->getData(),
2598                              flatPackages[pi]->getSize());
2599        if (err != NO_ERROR) {
2600            fprintf(stderr, "ERROR: out of memory creating package chunk for ResTable_header\n");
2601            return err;
2602        }
2603    }
2604
2605    ResTable_header* header = (ResTable_header*)
2606        (((uint8_t*)dest->getData()) + dataStart);
2607    header->header.size = htodl(dest->getSize() - dataStart);
2608
2609    NOISY(aout << "Resource table:"
2610          << HexDump(dest->getData(), dest->getSize()) << endl);
2611
2612    #if PRINT_STRING_METRICS
2613    fprintf(stderr, "**** total resource table size: %d / %d%% strings\n",
2614        dest->getSize(), (strAmt*100)/dest->getSize());
2615    #endif
2616
2617    return NO_ERROR;
2618}
2619
2620void ResourceTable::writePublicDefinitions(const String16& package, FILE* fp)
2621{
2622    fprintf(fp,
2623    "<!-- This file contains <public> resource definitions for all\n"
2624    "     resources that were generated from the source data. -->\n"
2625    "\n"
2626    "<resources>\n");
2627
2628    writePublicDefinitions(package, fp, true);
2629    writePublicDefinitions(package, fp, false);
2630
2631    fprintf(fp,
2632    "\n"
2633    "</resources>\n");
2634}
2635
2636void ResourceTable::writePublicDefinitions(const String16& package, FILE* fp, bool pub)
2637{
2638    bool didHeader = false;
2639
2640    sp<Package> pkg = mPackages.valueFor(package);
2641    if (pkg != NULL) {
2642        const size_t NT = pkg->getOrderedTypes().size();
2643        for (size_t i=0; i<NT; i++) {
2644            sp<Type> t = pkg->getOrderedTypes().itemAt(i);
2645            if (t == NULL) {
2646                continue;
2647            }
2648
2649            bool didType = false;
2650
2651            const size_t NC = t->getOrderedConfigs().size();
2652            for (size_t j=0; j<NC; j++) {
2653                sp<ConfigList> c = t->getOrderedConfigs().itemAt(j);
2654                if (c == NULL) {
2655                    continue;
2656                }
2657
2658                if (c->getPublic() != pub) {
2659                    continue;
2660                }
2661
2662                if (!didType) {
2663                    fprintf(fp, "\n");
2664                    didType = true;
2665                }
2666                if (!didHeader) {
2667                    if (pub) {
2668                        fprintf(fp,"  <!-- PUBLIC SECTION.  These resources have been declared public.\n");
2669                        fprintf(fp,"       Changes to these definitions will break binary compatibility. -->\n\n");
2670                    } else {
2671                        fprintf(fp,"  <!-- PRIVATE SECTION.  These resources have not been declared public.\n");
2672                        fprintf(fp,"       You can make them public my moving these lines into a file in res/values. -->\n\n");
2673                    }
2674                    didHeader = true;
2675                }
2676                if (!pub) {
2677                    const size_t NE = c->getEntries().size();
2678                    for (size_t k=0; k<NE; k++) {
2679                        const SourcePos& pos = c->getEntries().valueAt(k)->getPos();
2680                        if (pos.file != "") {
2681                            fprintf(fp,"  <!-- Declared at %s:%d -->\n",
2682                                    pos.file.string(), pos.line);
2683                        }
2684                    }
2685                }
2686                fprintf(fp, "  <public type=\"%s\" name=\"%s\" id=\"0x%08x\" />\n",
2687                        String8(t->getName()).string(),
2688                        String8(c->getName()).string(),
2689                        getResId(pkg, t, c->getEntryIndex()));
2690            }
2691        }
2692    }
2693}
2694
2695ResourceTable::Item::Item(const SourcePos& _sourcePos,
2696                          bool _isId,
2697                          const String16& _value,
2698                          const Vector<StringPool::entry_style_span>* _style,
2699                          int32_t _format)
2700    : sourcePos(_sourcePos)
2701    , isId(_isId)
2702    , value(_value)
2703    , format(_format)
2704    , bagKeyId(0)
2705    , evaluating(false)
2706{
2707    if (_style) {
2708        style = *_style;
2709    }
2710}
2711
2712status_t ResourceTable::Entry::makeItABag(const SourcePos& sourcePos)
2713{
2714    if (mType == TYPE_BAG) {
2715        return NO_ERROR;
2716    }
2717    if (mType == TYPE_UNKNOWN) {
2718        mType = TYPE_BAG;
2719        return NO_ERROR;
2720    }
2721    sourcePos.error("Resource entry %s is already defined as a single item.\n"
2722                    "%s:%d: Originally defined here.\n",
2723                    String8(mName).string(),
2724                    mItem.sourcePos.file.string(), mItem.sourcePos.line);
2725    return UNKNOWN_ERROR;
2726}
2727
2728status_t ResourceTable::Entry::setItem(const SourcePos& sourcePos,
2729                                       const String16& value,
2730                                       const Vector<StringPool::entry_style_span>* style,
2731                                       int32_t format)
2732{
2733    Item item(sourcePos, false, value, style);
2734
2735    if (mType == TYPE_BAG) {
2736        const Item& item(mBag.valueAt(0));
2737        sourcePos.error("Resource entry %s is already defined as a bag.\n"
2738                        "%s:%d: Originally defined here.\n",
2739                        String8(mName).string(),
2740                        item.sourcePos.file.string(), item.sourcePos.line);
2741        return UNKNOWN_ERROR;
2742    }
2743    if (mType != TYPE_UNKNOWN) {
2744        sourcePos.error("Resource entry %s is already defined.\n"
2745                        "%s:%d: Originally defined here.\n",
2746                        String8(mName).string(),
2747                        mItem.sourcePos.file.string(), mItem.sourcePos.line);
2748        return UNKNOWN_ERROR;
2749    }
2750
2751    mType = TYPE_ITEM;
2752    mItem = item;
2753    mItemFormat = format;
2754    return NO_ERROR;
2755}
2756
2757status_t ResourceTable::Entry::addToBag(const SourcePos& sourcePos,
2758                                        const String16& key, const String16& value,
2759                                        const Vector<StringPool::entry_style_span>* style,
2760                                        bool replace, bool isId, int32_t format)
2761{
2762    status_t err = makeItABag(sourcePos);
2763    if (err != NO_ERROR) {
2764        return err;
2765    }
2766
2767    Item item(sourcePos, isId, value, style, format);
2768
2769    // XXX NOTE: there is an error if you try to have a bag with two keys,
2770    // one an attr and one an id, with the same name.  Not something we
2771    // currently ever have to worry about.
2772    ssize_t origKey = mBag.indexOfKey(key);
2773    if (origKey >= 0) {
2774        if (!replace) {
2775            const Item& item(mBag.valueAt(origKey));
2776            sourcePos.error("Resource entry %s already has bag item %s.\n"
2777                    "%s:%d: Originally defined here.\n",
2778                    String8(mName).string(), String8(key).string(),
2779                    item.sourcePos.file.string(), item.sourcePos.line);
2780            return UNKNOWN_ERROR;
2781        }
2782        //printf("Replacing %s with %s\n",
2783        //       String8(mBag.valueFor(key).value).string(), String8(value).string());
2784        mBag.replaceValueFor(key, item);
2785    }
2786
2787    mBag.add(key, item);
2788    return NO_ERROR;
2789}
2790
2791status_t ResourceTable::Entry::generateAttributes(ResourceTable* table,
2792                                                  const String16& package)
2793{
2794    const String16 attr16("attr");
2795    const String16 id16("id");
2796    const size_t N = mBag.size();
2797    for (size_t i=0; i<N; i++) {
2798        const String16& key = mBag.keyAt(i);
2799        const Item& it = mBag.valueAt(i);
2800        if (it.isId) {
2801            if (!table->hasBagOrEntry(key, &id16, &package)) {
2802                String16 value("false");
2803                status_t err = table->addEntry(SourcePos(String8("<generated>"), 0), package,
2804                                               id16, key, value);
2805                if (err != NO_ERROR) {
2806                    return err;
2807                }
2808            }
2809        } else if (!table->hasBagOrEntry(key, &attr16, &package)) {
2810
2811#if 1
2812//             fprintf(stderr, "ERROR: Bag attribute '%s' has not been defined.\n",
2813//                     String8(key).string());
2814//             const Item& item(mBag.valueAt(i));
2815//             fprintf(stderr, "Referenced from file %s line %d\n",
2816//                     item.sourcePos.file.string(), item.sourcePos.line);
2817//             return UNKNOWN_ERROR;
2818#else
2819            char numberStr[16];
2820            sprintf(numberStr, "%d", ResTable_map::TYPE_ANY);
2821            status_t err = table->addBag(SourcePos("<generated>", 0), package,
2822                                         attr16, key, String16(""),
2823                                         String16("^type"),
2824                                         String16(numberStr), NULL, NULL);
2825            if (err != NO_ERROR) {
2826                return err;
2827            }
2828#endif
2829        }
2830    }
2831    return NO_ERROR;
2832}
2833
2834status_t ResourceTable::Entry::assignResourceIds(ResourceTable* table,
2835                                                 const String16& package)
2836{
2837    bool hasErrors = false;
2838
2839    if (mType == TYPE_BAG) {
2840        const char* errorMsg;
2841        const String16 style16("style");
2842        const String16 attr16("attr");
2843        const String16 id16("id");
2844        mParentId = 0;
2845        if (mParent.size() > 0) {
2846            mParentId = table->getResId(mParent, &style16, NULL, &errorMsg);
2847            if (mParentId == 0) {
2848                mPos.error("Error retrieving parent for item: %s '%s'.\n",
2849                        errorMsg, String8(mParent).string());
2850                hasErrors = true;
2851            }
2852        }
2853        const size_t N = mBag.size();
2854        for (size_t i=0; i<N; i++) {
2855            const String16& key = mBag.keyAt(i);
2856            Item& it = mBag.editValueAt(i);
2857            it.bagKeyId = table->getResId(key,
2858                    it.isId ? &id16 : &attr16, NULL, &errorMsg);
2859            //printf("Bag key of %s: #%08x\n", String8(key).string(), it.bagKeyId);
2860            if (it.bagKeyId == 0) {
2861                it.sourcePos.error("Error: %s: %s '%s'.\n", errorMsg,
2862                        String8(it.isId ? id16 : attr16).string(),
2863                        String8(key).string());
2864                hasErrors = true;
2865            }
2866        }
2867    }
2868    return hasErrors ? UNKNOWN_ERROR : NO_ERROR;
2869}
2870
2871status_t ResourceTable::Entry::prepareFlatten(StringPool* strings, ResourceTable* table)
2872{
2873    if (mType == TYPE_ITEM) {
2874        Item& it = mItem;
2875        AccessorCookie ac(it.sourcePos, String8(mName), String8(it.value));
2876        if (!table->stringToValue(&it.parsedValue, strings,
2877                                  it.value, false, true, 0,
2878                                  &it.style, NULL, &ac, mItemFormat)) {
2879            return UNKNOWN_ERROR;
2880        }
2881    } else if (mType == TYPE_BAG) {
2882        const size_t N = mBag.size();
2883        for (size_t i=0; i<N; i++) {
2884            const String16& key = mBag.keyAt(i);
2885            Item& it = mBag.editValueAt(i);
2886            AccessorCookie ac(it.sourcePos, String8(key), String8(it.value));
2887            if (!table->stringToValue(&it.parsedValue, strings,
2888                                      it.value, false, true, it.bagKeyId,
2889                                      &it.style, NULL, &ac, it.format)) {
2890                return UNKNOWN_ERROR;
2891            }
2892        }
2893    } else {
2894        mPos.error("Error: entry %s is not a single item or a bag.\n",
2895                   String8(mName).string());
2896        return UNKNOWN_ERROR;
2897    }
2898    return NO_ERROR;
2899}
2900
2901ssize_t ResourceTable::Entry::flatten(Bundle* bundle, const sp<AaptFile>& data, bool isPublic)
2902{
2903    size_t amt = 0;
2904    ResTable_entry header;
2905    memset(&header, 0, sizeof(header));
2906    header.size = htods(sizeof(header));
2907    const type ty = this != NULL ? mType : TYPE_ITEM;
2908    if (this != NULL) {
2909        if (ty == TYPE_BAG) {
2910            header.flags |= htods(header.FLAG_COMPLEX);
2911        }
2912        if (isPublic) {
2913            header.flags |= htods(header.FLAG_PUBLIC);
2914        }
2915        header.key.index = htodl(mNameIndex);
2916    }
2917    if (ty != TYPE_BAG) {
2918        status_t err = data->writeData(&header, sizeof(header));
2919        if (err != NO_ERROR) {
2920            fprintf(stderr, "ERROR: out of memory creating ResTable_entry\n");
2921            return err;
2922        }
2923
2924        const Item& it = mItem;
2925        Res_value par;
2926        memset(&par, 0, sizeof(par));
2927        par.size = htods(it.parsedValue.size);
2928        par.dataType = it.parsedValue.dataType;
2929        par.res0 = it.parsedValue.res0;
2930        par.data = htodl(it.parsedValue.data);
2931        #if 0
2932        printf("Writing item (%s): type=%d, data=0x%x, res0=0x%x\n",
2933               String8(mName).string(), it.parsedValue.dataType,
2934               it.parsedValue.data, par.res0);
2935        #endif
2936        err = data->writeData(&par, it.parsedValue.size);
2937        if (err != NO_ERROR) {
2938            fprintf(stderr, "ERROR: out of memory creating Res_value\n");
2939            return err;
2940        }
2941        amt += it.parsedValue.size;
2942    } else {
2943        size_t N = mBag.size();
2944        size_t i;
2945        // Create correct ordering of items.
2946        KeyedVector<uint32_t, const Item*> items;
2947        for (i=0; i<N; i++) {
2948            const Item& it = mBag.valueAt(i);
2949            items.add(it.bagKeyId, &it);
2950        }
2951        N = items.size();
2952
2953        ResTable_map_entry mapHeader;
2954        memcpy(&mapHeader, &header, sizeof(header));
2955        mapHeader.size = htods(sizeof(mapHeader));
2956        mapHeader.parent.ident = htodl(mParentId);
2957        mapHeader.count = htodl(N);
2958        status_t err = data->writeData(&mapHeader, sizeof(mapHeader));
2959        if (err != NO_ERROR) {
2960            fprintf(stderr, "ERROR: out of memory creating ResTable_entry\n");
2961            return err;
2962        }
2963
2964        for (i=0; i<N; i++) {
2965            const Item& it = *items.valueAt(i);
2966            ResTable_map map;
2967            map.name.ident = htodl(it.bagKeyId);
2968            map.value.size = htods(it.parsedValue.size);
2969            map.value.dataType = it.parsedValue.dataType;
2970            map.value.res0 = it.parsedValue.res0;
2971            map.value.data = htodl(it.parsedValue.data);
2972            err = data->writeData(&map, sizeof(map));
2973            if (err != NO_ERROR) {
2974                fprintf(stderr, "ERROR: out of memory creating Res_value\n");
2975                return err;
2976            }
2977            amt += sizeof(map);
2978        }
2979    }
2980    return amt;
2981}
2982
2983void ResourceTable::ConfigList::appendComment(const String16& comment,
2984                                              bool onlyIfEmpty)
2985{
2986    if (comment.size() <= 0) {
2987        return;
2988    }
2989    if (onlyIfEmpty && mComment.size() > 0) {
2990        return;
2991    }
2992    if (mComment.size() > 0) {
2993        mComment.append(String16("\n"));
2994    }
2995    mComment.append(comment);
2996}
2997
2998void ResourceTable::ConfigList::appendTypeComment(const String16& comment)
2999{
3000    if (comment.size() <= 0) {
3001        return;
3002    }
3003    if (mTypeComment.size() > 0) {
3004        mTypeComment.append(String16("\n"));
3005    }
3006    mTypeComment.append(comment);
3007}
3008
3009status_t ResourceTable::Type::addPublic(const SourcePos& sourcePos,
3010                                        const String16& name,
3011                                        const uint32_t ident)
3012{
3013    #if 0
3014    int32_t entryIdx = Res_GETENTRY(ident);
3015    if (entryIdx < 0) {
3016        sourcePos.error("Public resource %s/%s has an invalid 0 identifier (0x%08x).\n",
3017                String8(mName).string(), String8(name).string(), ident);
3018        return UNKNOWN_ERROR;
3019    }
3020    #endif
3021
3022    int32_t typeIdx = Res_GETTYPE(ident);
3023    if (typeIdx >= 0) {
3024        typeIdx++;
3025        if (mPublicIndex > 0 && mPublicIndex != typeIdx) {
3026            sourcePos.error("Public resource %s/%s has conflicting type codes for its"
3027                    " public identifiers (0x%x vs 0x%x).\n",
3028                    String8(mName).string(), String8(name).string(),
3029                    mPublicIndex, typeIdx);
3030            return UNKNOWN_ERROR;
3031        }
3032        mPublicIndex = typeIdx;
3033    }
3034
3035    if (mFirstPublicSourcePos == NULL) {
3036        mFirstPublicSourcePos = new SourcePos(sourcePos);
3037    }
3038
3039    if (mPublic.indexOfKey(name) < 0) {
3040        mPublic.add(name, Public(sourcePos, String16(), ident));
3041    } else {
3042        Public& p = mPublic.editValueFor(name);
3043        if (p.ident != ident) {
3044            sourcePos.error("Public resource %s/%s has conflicting public identifiers"
3045                    " (0x%08x vs 0x%08x).\n"
3046                    "%s:%d: Originally defined here.\n",
3047                    String8(mName).string(), String8(name).string(), p.ident, ident,
3048                    p.sourcePos.file.string(), p.sourcePos.line);
3049            return UNKNOWN_ERROR;
3050        }
3051    }
3052
3053    return NO_ERROR;
3054}
3055
3056sp<ResourceTable::Entry> ResourceTable::Type::getEntry(const String16& entry,
3057                                                       const SourcePos& sourcePos,
3058                                                       const ResTable_config* config,
3059                                                       bool doSetIndex)
3060{
3061    int pos = -1;
3062    sp<ConfigList> c = mConfigs.valueFor(entry);
3063    if (c == NULL) {
3064        c = new ConfigList(entry, sourcePos);
3065        mConfigs.add(entry, c);
3066        pos = (int)mOrderedConfigs.size();
3067        mOrderedConfigs.add(c);
3068        if (doSetIndex) {
3069            c->setEntryIndex(pos);
3070        }
3071    }
3072
3073    ConfigDescription cdesc;
3074    if (config) cdesc = *config;
3075
3076    sp<Entry> e = c->getEntries().valueFor(cdesc);
3077    if (e == NULL) {
3078        if (config != NULL) {
3079            NOISY(printf("New entry at %s:%d: imsi:%d/%d lang:%c%c cnt:%c%c "
3080                    "orien:%d touch:%d density:%d key:%d inp:%d nav:%d w:%d h:%d\n",
3081                      sourcePos.file.string(), sourcePos.line,
3082                      config->mcc, config->mnc,
3083                      config->language[0] ? config->language[0] : '-',
3084                      config->language[1] ? config->language[1] : '-',
3085                      config->country[0] ? config->country[0] : '-',
3086                      config->country[1] ? config->country[1] : '-',
3087                      config->orientation,
3088                      config->touchscreen,
3089                      config->density,
3090                      config->keyboard,
3091                      config->inputFlags,
3092                      config->navigation,
3093                      config->screenWidth,
3094                      config->screenHeight));
3095        } else {
3096            NOISY(printf("New entry at %s:%d: NULL config\n",
3097                      sourcePos.file.string(), sourcePos.line));
3098        }
3099        e = new Entry(entry, sourcePos);
3100        c->addEntry(cdesc, e);
3101        /*
3102        if (doSetIndex) {
3103            if (pos < 0) {
3104                for (pos=0; pos<(int)mOrderedConfigs.size(); pos++) {
3105                    if (mOrderedConfigs[pos] == c) {
3106                        break;
3107                    }
3108                }
3109                if (pos >= (int)mOrderedConfigs.size()) {
3110                    sourcePos.error("Internal error: config not found in mOrderedConfigs when adding entry");
3111                    return NULL;
3112                }
3113            }
3114            e->setEntryIndex(pos);
3115        }
3116        */
3117    }
3118
3119    mUniqueConfigs.add(cdesc);
3120
3121    return e;
3122}
3123
3124status_t ResourceTable::Type::applyPublicEntryOrder()
3125{
3126    size_t N = mOrderedConfigs.size();
3127    Vector<sp<ConfigList> > origOrder(mOrderedConfigs);
3128    bool hasError = false;
3129
3130    size_t i;
3131    for (i=0; i<N; i++) {
3132        mOrderedConfigs.replaceAt(NULL, i);
3133    }
3134
3135    const size_t NP = mPublic.size();
3136    //printf("Ordering %d configs from %d public defs\n", N, NP);
3137    size_t j;
3138    for (j=0; j<NP; j++) {
3139        const String16& name = mPublic.keyAt(j);
3140        const Public& p = mPublic.valueAt(j);
3141        int32_t idx = Res_GETENTRY(p.ident);
3142        //printf("Looking for entry \"%s\"/\"%s\" (0x%08x) in %d...\n",
3143        //       String8(mName).string(), String8(name).string(), p.ident, N);
3144        bool found = false;
3145        for (i=0; i<N; i++) {
3146            sp<ConfigList> e = origOrder.itemAt(i);
3147            //printf("#%d: \"%s\"\n", i, String8(e->getName()).string());
3148            if (e->getName() == name) {
3149                if (idx >= (int32_t)mOrderedConfigs.size()) {
3150                    p.sourcePos.error("Public entry identifier 0x%x entry index "
3151                            "is larger than available symbols (index %d, total symbols %d).\n",
3152                            p.ident, idx, mOrderedConfigs.size());
3153                    hasError = true;
3154                } else if (mOrderedConfigs.itemAt(idx) == NULL) {
3155                    e->setPublic(true);
3156                    e->setPublicSourcePos(p.sourcePos);
3157                    mOrderedConfigs.replaceAt(e, idx);
3158                    origOrder.removeAt(i);
3159                    N--;
3160                    found = true;
3161                    break;
3162                } else {
3163                    sp<ConfigList> oe = mOrderedConfigs.itemAt(idx);
3164
3165                    p.sourcePos.error("Multiple entry names declared for public entry"
3166                            " identifier 0x%x in type %s (%s vs %s).\n"
3167                            "%s:%d: Originally defined here.",
3168                            idx+1, String8(mName).string(),
3169                            String8(oe->getName()).string(),
3170                            String8(name).string(),
3171                            oe->getPublicSourcePos().file.string(),
3172                            oe->getPublicSourcePos().line);
3173                    hasError = true;
3174                }
3175            }
3176        }
3177
3178        if (!found) {
3179            p.sourcePos.error("Public symbol %s/%s declared here is not defined.",
3180                    String8(mName).string(), String8(name).string());
3181            hasError = true;
3182        }
3183    }
3184
3185    //printf("Copying back in %d non-public configs, have %d\n", N, origOrder.size());
3186
3187    if (N != origOrder.size()) {
3188        printf("Internal error: remaining private symbol count mismatch\n");
3189        N = origOrder.size();
3190    }
3191
3192    j = 0;
3193    for (i=0; i<N; i++) {
3194        sp<ConfigList> e = origOrder.itemAt(i);
3195        // There will always be enough room for the remaining entries.
3196        while (mOrderedConfigs.itemAt(j) != NULL) {
3197            j++;
3198        }
3199        mOrderedConfigs.replaceAt(e, j);
3200        j++;
3201    }
3202
3203    return hasError ? UNKNOWN_ERROR : NO_ERROR;
3204}
3205
3206ResourceTable::Package::Package(const String16& name, ssize_t includedId)
3207    : mName(name), mIncludedId(includedId),
3208      mTypeStringsMapping(0xffffffff),
3209      mKeyStringsMapping(0xffffffff)
3210{
3211}
3212
3213sp<ResourceTable::Type> ResourceTable::Package::getType(const String16& type,
3214                                                        const SourcePos& sourcePos,
3215                                                        bool doSetIndex)
3216{
3217    sp<Type> t = mTypes.valueFor(type);
3218    if (t == NULL) {
3219        t = new Type(type, sourcePos);
3220        mTypes.add(type, t);
3221        mOrderedTypes.add(t);
3222        if (doSetIndex) {
3223            // For some reason the type's index is set to one plus the index
3224            // in the mOrderedTypes list, rather than just the index.
3225            t->setIndex(mOrderedTypes.size());
3226        }
3227    }
3228    return t;
3229}
3230
3231status_t ResourceTable::Package::setTypeStrings(const sp<AaptFile>& data)
3232{
3233    mTypeStringsData = data;
3234    status_t err = setStrings(data, &mTypeStrings, &mTypeStringsMapping);
3235    if (err != NO_ERROR) {
3236        fprintf(stderr, "ERROR: Type string data is corrupt!\n");
3237    }
3238    return err;
3239}
3240
3241status_t ResourceTable::Package::setKeyStrings(const sp<AaptFile>& data)
3242{
3243    mKeyStringsData = data;
3244    status_t err = setStrings(data, &mKeyStrings, &mKeyStringsMapping);
3245    if (err != NO_ERROR) {
3246        fprintf(stderr, "ERROR: Key string data is corrupt!\n");
3247    }
3248    return err;
3249}
3250
3251status_t ResourceTable::Package::setStrings(const sp<AaptFile>& data,
3252                                            ResStringPool* strings,
3253                                            DefaultKeyedVector<String16, uint32_t>* mappings)
3254{
3255    if (data->getData() == NULL) {
3256        return UNKNOWN_ERROR;
3257    }
3258
3259    NOISY(aout << "Setting restable string pool: "
3260          << HexDump(data->getData(), data->getSize()) << endl);
3261
3262    status_t err = strings->setTo(data->getData(), data->getSize());
3263    if (err == NO_ERROR) {
3264        const size_t N = strings->size();
3265        for (size_t i=0; i<N; i++) {
3266            size_t len;
3267            mappings->add(String16(strings->stringAt(i, &len)), i);
3268        }
3269    }
3270    return err;
3271}
3272
3273status_t ResourceTable::Package::applyPublicTypeOrder()
3274{
3275    size_t N = mOrderedTypes.size();
3276    Vector<sp<Type> > origOrder(mOrderedTypes);
3277
3278    size_t i;
3279    for (i=0; i<N; i++) {
3280        mOrderedTypes.replaceAt(NULL, i);
3281    }
3282
3283    for (i=0; i<N; i++) {
3284        sp<Type> t = origOrder.itemAt(i);
3285        int32_t idx = t->getPublicIndex();
3286        if (idx > 0) {
3287            idx--;
3288            while (idx >= (int32_t)mOrderedTypes.size()) {
3289                mOrderedTypes.add();
3290            }
3291            if (mOrderedTypes.itemAt(idx) != NULL) {
3292                sp<Type> ot = mOrderedTypes.itemAt(idx);
3293                t->getFirstPublicSourcePos().error("Multiple type names declared for public type"
3294                        " identifier 0x%x (%s vs %s).\n"
3295                        "%s:%d: Originally defined here.",
3296                        idx, String8(ot->getName()).string(),
3297                        String8(t->getName()).string(),
3298                        ot->getFirstPublicSourcePos().file.string(),
3299                        ot->getFirstPublicSourcePos().line);
3300                return UNKNOWN_ERROR;
3301            }
3302            mOrderedTypes.replaceAt(t, idx);
3303            origOrder.removeAt(i);
3304            i--;
3305            N--;
3306        }
3307    }
3308
3309    size_t j=0;
3310    for (i=0; i<N; i++) {
3311        sp<Type> t = origOrder.itemAt(i);
3312        // There will always be enough room for the remaining types.
3313        while (mOrderedTypes.itemAt(j) != NULL) {
3314            j++;
3315        }
3316        mOrderedTypes.replaceAt(t, j);
3317    }
3318
3319    return NO_ERROR;
3320}
3321
3322sp<ResourceTable::Package> ResourceTable::getPackage(const String16& package)
3323{
3324    sp<Package> p = mPackages.valueFor(package);
3325    if (p == NULL) {
3326        if (mIsAppPackage) {
3327            if (mHaveAppPackage) {
3328                fprintf(stderr, "Adding multiple application package resources; only one is allowed.\n"
3329                                "Use -x to create extended resources.\n");
3330                return NULL;
3331            }
3332            mHaveAppPackage = true;
3333            p = new Package(package, 127);
3334        } else {
3335            p = new Package(package, mNextPackageId);
3336        }
3337        //printf("*** NEW PACKAGE: \"%s\" id=%d\n",
3338        //       String8(package).string(), p->getAssignedId());
3339        mPackages.add(package, p);
3340        mOrderedPackages.add(p);
3341        mNextPackageId++;
3342    }
3343    return p;
3344}
3345
3346sp<ResourceTable::Type> ResourceTable::getType(const String16& package,
3347                                               const String16& type,
3348                                               const SourcePos& sourcePos,
3349                                               bool doSetIndex)
3350{
3351    sp<Package> p = getPackage(package);
3352    if (p == NULL) {
3353        return NULL;
3354    }
3355    return p->getType(type, sourcePos, doSetIndex);
3356}
3357
3358sp<ResourceTable::Entry> ResourceTable::getEntry(const String16& package,
3359                                                 const String16& type,
3360                                                 const String16& name,
3361                                                 const SourcePos& sourcePos,
3362                                                 const ResTable_config* config,
3363                                                 bool doSetIndex)
3364{
3365    sp<Type> t = getType(package, type, sourcePos, doSetIndex);
3366    if (t == NULL) {
3367        return NULL;
3368    }
3369    return t->getEntry(name, sourcePos, config, doSetIndex);
3370}
3371
3372sp<const ResourceTable::Entry> ResourceTable::getEntry(uint32_t resID,
3373                                                       const ResTable_config* config) const
3374{
3375    int pid = Res_GETPACKAGE(resID)+1;
3376    const size_t N = mOrderedPackages.size();
3377    size_t i;
3378    sp<Package> p;
3379    for (i=0; i<N; i++) {
3380        sp<Package> check = mOrderedPackages[i];
3381        if (check->getAssignedId() == pid) {
3382            p = check;
3383            break;
3384        }
3385
3386    }
3387    if (p == NULL) {
3388        fprintf(stderr, "WARNING: Package not found for resource #%08x\n", resID);
3389        return NULL;
3390    }
3391
3392    int tid = Res_GETTYPE(resID);
3393    if (tid < 0 || tid >= (int)p->getOrderedTypes().size()) {
3394        fprintf(stderr, "WARNING: Type not found for resource #%08x\n", resID);
3395        return NULL;
3396    }
3397    sp<Type> t = p->getOrderedTypes()[tid];
3398
3399    int eid = Res_GETENTRY(resID);
3400    if (eid < 0 || eid >= (int)t->getOrderedConfigs().size()) {
3401        fprintf(stderr, "WARNING: Entry not found for resource #%08x\n", resID);
3402        return NULL;
3403    }
3404
3405    sp<ConfigList> c = t->getOrderedConfigs()[eid];
3406    if (c == NULL) {
3407        fprintf(stderr, "WARNING: Entry not found for resource #%08x\n", resID);
3408        return NULL;
3409    }
3410
3411    ConfigDescription cdesc;
3412    if (config) cdesc = *config;
3413    sp<Entry> e = c->getEntries().valueFor(cdesc);
3414    if (c == NULL) {
3415        fprintf(stderr, "WARNING: Entry configuration not found for resource #%08x\n", resID);
3416        return NULL;
3417    }
3418
3419    return e;
3420}
3421
3422const ResourceTable::Item* ResourceTable::getItem(uint32_t resID, uint32_t attrID) const
3423{
3424    sp<const Entry> e = getEntry(resID);
3425    if (e == NULL) {
3426        return NULL;
3427    }
3428
3429    const size_t N = e->getBag().size();
3430    for (size_t i=0; i<N; i++) {
3431        const Item& it = e->getBag().valueAt(i);
3432        if (it.bagKeyId == 0) {
3433            fprintf(stderr, "WARNING: ID not yet assigned to '%s' in bag '%s'\n",
3434                    String8(e->getName()).string(),
3435                    String8(e->getBag().keyAt(i)).string());
3436        }
3437        if (it.bagKeyId == attrID) {
3438            return &it;
3439        }
3440    }
3441
3442    return NULL;
3443}
3444
3445bool ResourceTable::getItemValue(
3446    uint32_t resID, uint32_t attrID, Res_value* outValue)
3447{
3448    const Item* item = getItem(resID, attrID);
3449
3450    bool res = false;
3451    if (item != NULL) {
3452        if (item->evaluating) {
3453            sp<const Entry> e = getEntry(resID);
3454            const size_t N = e->getBag().size();
3455            size_t i;
3456            for (i=0; i<N; i++) {
3457                if (&e->getBag().valueAt(i) == item) {
3458                    break;
3459                }
3460            }
3461            fprintf(stderr, "WARNING: Circular reference detected in key '%s' of bag '%s'\n",
3462                    String8(e->getName()).string(),
3463                    String8(e->getBag().keyAt(i)).string());
3464            return false;
3465        }
3466        item->evaluating = true;
3467        res = stringToValue(outValue, NULL, item->value, false, false, item->bagKeyId);
3468        NOISY(
3469            if (res) {
3470                printf("getItemValue of #%08x[#%08x] (%s): type=#%08x, data=#%08x\n",
3471                       resID, attrID, String8(getEntry(resID)->getName()).string(),
3472                       outValue->dataType, outValue->data);
3473            } else {
3474                printf("getItemValue of #%08x[#%08x]: failed\n",
3475                       resID, attrID);
3476            }
3477        );
3478        item->evaluating = false;
3479    }
3480    return res;
3481}
3482
3483