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