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