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