ResourceTable.cpp revision 84410b054c7db0b6685a0f15cb2d1ffcb264f6c9
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                        PseudolocalizationMethod 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                        PseudolocalizationMethod 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] = 'e';
858        pseudoParams.language[1] = 'n';
859        pseudoParams.country[0] = 'X';
860        pseudoParams.country[1] = 'A';
861
862    ResTable_config pseudoBidiParams(curParams);
863        pseudoBidiParams.language[0] = 'a';
864        pseudoBidiParams.language[1] = 'r';
865        pseudoBidiParams.country[0] = 'X';
866        pseudoBidiParams.country[1] = 'B';
867
868    while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
869        if (code == ResXMLTree::START_TAG) {
870            const String16* curTag = NULL;
871            String16 curType;
872            int32_t curFormat = ResTable_map::TYPE_ANY;
873            bool curIsBag = false;
874            bool curIsBagReplaceOnOverwrite = false;
875            bool curIsStyled = false;
876            bool curIsPseudolocalizable = false;
877            bool curIsFormatted = fileIsTranslatable;
878            bool localHasErrors = false;
879
880            if (strcmp16(block.getElementName(&len), skip16.string()) == 0) {
881                while ((code=block.next()) != ResXMLTree::END_DOCUMENT
882                        && code != ResXMLTree::BAD_DOCUMENT) {
883                    if (code == ResXMLTree::END_TAG) {
884                        if (strcmp16(block.getElementName(&len), skip16.string()) == 0) {
885                            break;
886                        }
887                    }
888                }
889                continue;
890
891            } else if (strcmp16(block.getElementName(&len), eat_comment16.string()) == 0) {
892                while ((code=block.next()) != ResXMLTree::END_DOCUMENT
893                        && code != ResXMLTree::BAD_DOCUMENT) {
894                    if (code == ResXMLTree::END_TAG) {
895                        if (strcmp16(block.getElementName(&len), eat_comment16.string()) == 0) {
896                            break;
897                        }
898                    }
899                }
900                continue;
901
902            } else if (strcmp16(block.getElementName(&len), public16.string()) == 0) {
903                SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
904
905                String16 type;
906                ssize_t typeIdx = block.indexOfAttribute(NULL, "type");
907                if (typeIdx < 0) {
908                    srcPos.error("A 'type' attribute is required for <public>\n");
909                    hasErrors = localHasErrors = true;
910                }
911                type = String16(block.getAttributeStringValue(typeIdx, &len));
912
913                String16 name;
914                ssize_t nameIdx = block.indexOfAttribute(NULL, "name");
915                if (nameIdx < 0) {
916                    srcPos.error("A 'name' attribute is required for <public>\n");
917                    hasErrors = localHasErrors = true;
918                }
919                name = String16(block.getAttributeStringValue(nameIdx, &len));
920
921                uint32_t ident = 0;
922                ssize_t identIdx = block.indexOfAttribute(NULL, "id");
923                if (identIdx >= 0) {
924                    const char16_t* identStr = block.getAttributeStringValue(identIdx, &len);
925                    Res_value identValue;
926                    if (!ResTable::stringToInt(identStr, len, &identValue)) {
927                        srcPos.error("Given 'id' attribute is not an integer: %s\n",
928                                String8(block.getAttributeStringValue(identIdx, &len)).string());
929                        hasErrors = localHasErrors = true;
930                    } else {
931                        ident = identValue.data;
932                        nextPublicId.replaceValueFor(type, ident+1);
933                    }
934                } else if (nextPublicId.indexOfKey(type) < 0) {
935                    srcPos.error("No 'id' attribute supplied <public>,"
936                            " and no previous id defined in this file.\n");
937                    hasErrors = localHasErrors = true;
938                } else if (!localHasErrors) {
939                    ident = nextPublicId.valueFor(type);
940                    nextPublicId.replaceValueFor(type, ident+1);
941                }
942
943                if (!localHasErrors) {
944                    err = outTable->addPublic(srcPos, myPackage, type, name, ident);
945                    if (err < NO_ERROR) {
946                        hasErrors = localHasErrors = true;
947                    }
948                }
949                if (!localHasErrors) {
950                    sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R"));
951                    if (symbols != NULL) {
952                        symbols = symbols->addNestedSymbol(String8(type), srcPos);
953                    }
954                    if (symbols != NULL) {
955                        symbols->makeSymbolPublic(String8(name), srcPos);
956                        String16 comment(
957                            block.getComment(&len) ? block.getComment(&len) : nulStr);
958                        symbols->appendComment(String8(name), comment, srcPos);
959                    } else {
960                        srcPos.error("Unable to create symbols!\n");
961                        hasErrors = localHasErrors = true;
962                    }
963                }
964
965                while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
966                    if (code == ResXMLTree::END_TAG) {
967                        if (strcmp16(block.getElementName(&len), public16.string()) == 0) {
968                            break;
969                        }
970                    }
971                }
972                continue;
973
974            } else if (strcmp16(block.getElementName(&len), public_padding16.string()) == 0) {
975                SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
976
977                String16 type;
978                ssize_t typeIdx = block.indexOfAttribute(NULL, "type");
979                if (typeIdx < 0) {
980                    srcPos.error("A 'type' attribute is required for <public-padding>\n");
981                    hasErrors = localHasErrors = true;
982                }
983                type = String16(block.getAttributeStringValue(typeIdx, &len));
984
985                String16 name;
986                ssize_t nameIdx = block.indexOfAttribute(NULL, "name");
987                if (nameIdx < 0) {
988                    srcPos.error("A 'name' attribute is required for <public-padding>\n");
989                    hasErrors = localHasErrors = true;
990                }
991                name = String16(block.getAttributeStringValue(nameIdx, &len));
992
993                uint32_t start = 0;
994                ssize_t startIdx = block.indexOfAttribute(NULL, "start");
995                if (startIdx >= 0) {
996                    const char16_t* startStr = block.getAttributeStringValue(startIdx, &len);
997                    Res_value startValue;
998                    if (!ResTable::stringToInt(startStr, len, &startValue)) {
999                        srcPos.error("Given 'start' attribute is not an integer: %s\n",
1000                                String8(block.getAttributeStringValue(startIdx, &len)).string());
1001                        hasErrors = localHasErrors = true;
1002                    } else {
1003                        start = startValue.data;
1004                    }
1005                } else if (nextPublicId.indexOfKey(type) < 0) {
1006                    srcPos.error("No 'start' attribute supplied <public-padding>,"
1007                            " and no previous id defined in this file.\n");
1008                    hasErrors = localHasErrors = true;
1009                } else if (!localHasErrors) {
1010                    start = nextPublicId.valueFor(type);
1011                }
1012
1013                uint32_t end = 0;
1014                ssize_t endIdx = block.indexOfAttribute(NULL, "end");
1015                if (endIdx >= 0) {
1016                    const char16_t* endStr = block.getAttributeStringValue(endIdx, &len);
1017                    Res_value endValue;
1018                    if (!ResTable::stringToInt(endStr, len, &endValue)) {
1019                        srcPos.error("Given 'end' attribute is not an integer: %s\n",
1020                                String8(block.getAttributeStringValue(endIdx, &len)).string());
1021                        hasErrors = localHasErrors = true;
1022                    } else {
1023                        end = endValue.data;
1024                    }
1025                } else {
1026                    srcPos.error("No 'end' attribute supplied <public-padding>\n");
1027                    hasErrors = localHasErrors = true;
1028                }
1029
1030                if (end >= start) {
1031                    nextPublicId.replaceValueFor(type, end+1);
1032                } else {
1033                    srcPos.error("Padding start '%ul' is after end '%ul'\n",
1034                            start, end);
1035                    hasErrors = localHasErrors = true;
1036                }
1037
1038                String16 comment(
1039                    block.getComment(&len) ? block.getComment(&len) : nulStr);
1040                for (uint32_t curIdent=start; curIdent<=end; curIdent++) {
1041                    if (localHasErrors) {
1042                        break;
1043                    }
1044                    String16 curName(name);
1045                    char buf[64];
1046                    sprintf(buf, "%d", (int)(end-curIdent+1));
1047                    curName.append(String16(buf));
1048
1049                    err = outTable->addEntry(srcPos, myPackage, type, curName,
1050                                             String16("padding"), NULL, &curParams, false,
1051                                             ResTable_map::TYPE_STRING, overwrite);
1052                    if (err < NO_ERROR) {
1053                        hasErrors = localHasErrors = true;
1054                        break;
1055                    }
1056                    err = outTable->addPublic(srcPos, myPackage, type,
1057                            curName, curIdent);
1058                    if (err < NO_ERROR) {
1059                        hasErrors = localHasErrors = true;
1060                        break;
1061                    }
1062                    sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R"));
1063                    if (symbols != NULL) {
1064                        symbols = symbols->addNestedSymbol(String8(type), srcPos);
1065                    }
1066                    if (symbols != NULL) {
1067                        symbols->makeSymbolPublic(String8(curName), srcPos);
1068                        symbols->appendComment(String8(curName), comment, srcPos);
1069                    } else {
1070                        srcPos.error("Unable to create symbols!\n");
1071                        hasErrors = localHasErrors = true;
1072                    }
1073                }
1074
1075                while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1076                    if (code == ResXMLTree::END_TAG) {
1077                        if (strcmp16(block.getElementName(&len), public_padding16.string()) == 0) {
1078                            break;
1079                        }
1080                    }
1081                }
1082                continue;
1083
1084            } else if (strcmp16(block.getElementName(&len), private_symbols16.string()) == 0) {
1085                String16 pkg;
1086                ssize_t pkgIdx = block.indexOfAttribute(NULL, "package");
1087                if (pkgIdx < 0) {
1088                    SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1089                            "A 'package' attribute is required for <private-symbols>\n");
1090                    hasErrors = localHasErrors = true;
1091                }
1092                pkg = String16(block.getAttributeStringValue(pkgIdx, &len));
1093                if (!localHasErrors) {
1094                    assets->setSymbolsPrivatePackage(String8(pkg));
1095                }
1096
1097                while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1098                    if (code == ResXMLTree::END_TAG) {
1099                        if (strcmp16(block.getElementName(&len), private_symbols16.string()) == 0) {
1100                            break;
1101                        }
1102                    }
1103                }
1104                continue;
1105
1106            } else if (strcmp16(block.getElementName(&len), java_symbol16.string()) == 0) {
1107                SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
1108
1109                String16 type;
1110                ssize_t typeIdx = block.indexOfAttribute(NULL, "type");
1111                if (typeIdx < 0) {
1112                    srcPos.error("A 'type' attribute is required for <public>\n");
1113                    hasErrors = localHasErrors = true;
1114                }
1115                type = String16(block.getAttributeStringValue(typeIdx, &len));
1116
1117                String16 name;
1118                ssize_t nameIdx = block.indexOfAttribute(NULL, "name");
1119                if (nameIdx < 0) {
1120                    srcPos.error("A 'name' attribute is required for <public>\n");
1121                    hasErrors = localHasErrors = true;
1122                }
1123                name = String16(block.getAttributeStringValue(nameIdx, &len));
1124
1125                sp<AaptSymbols> symbols = assets->getJavaSymbolsFor(String8("R"));
1126                if (symbols != NULL) {
1127                    symbols = symbols->addNestedSymbol(String8(type), srcPos);
1128                }
1129                if (symbols != NULL) {
1130                    symbols->makeSymbolJavaSymbol(String8(name), srcPos);
1131                    String16 comment(
1132                        block.getComment(&len) ? block.getComment(&len) : nulStr);
1133                    symbols->appendComment(String8(name), comment, srcPos);
1134                } else {
1135                    srcPos.error("Unable to create symbols!\n");
1136                    hasErrors = localHasErrors = true;
1137                }
1138
1139                while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1140                    if (code == ResXMLTree::END_TAG) {
1141                        if (strcmp16(block.getElementName(&len), java_symbol16.string()) == 0) {
1142                            break;
1143                        }
1144                    }
1145                }
1146                continue;
1147
1148
1149            } else if (strcmp16(block.getElementName(&len), add_resource16.string()) == 0) {
1150                SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
1151
1152                String16 typeName;
1153                ssize_t typeIdx = block.indexOfAttribute(NULL, "type");
1154                if (typeIdx < 0) {
1155                    srcPos.error("A 'type' attribute is required for <add-resource>\n");
1156                    hasErrors = localHasErrors = true;
1157                }
1158                typeName = String16(block.getAttributeStringValue(typeIdx, &len));
1159
1160                String16 name;
1161                ssize_t nameIdx = block.indexOfAttribute(NULL, "name");
1162                if (nameIdx < 0) {
1163                    srcPos.error("A 'name' attribute is required for <add-resource>\n");
1164                    hasErrors = localHasErrors = true;
1165                }
1166                name = String16(block.getAttributeStringValue(nameIdx, &len));
1167
1168                outTable->canAddEntry(srcPos, myPackage, typeName, name);
1169
1170                while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1171                    if (code == ResXMLTree::END_TAG) {
1172                        if (strcmp16(block.getElementName(&len), add_resource16.string()) == 0) {
1173                            break;
1174                        }
1175                    }
1176                }
1177                continue;
1178
1179            } else if (strcmp16(block.getElementName(&len), declare_styleable16.string()) == 0) {
1180                SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
1181
1182                String16 ident;
1183                ssize_t identIdx = block.indexOfAttribute(NULL, "name");
1184                if (identIdx < 0) {
1185                    srcPos.error("A 'name' attribute is required for <declare-styleable>\n");
1186                    hasErrors = localHasErrors = true;
1187                }
1188                ident = String16(block.getAttributeStringValue(identIdx, &len));
1189
1190                sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R"));
1191                if (!localHasErrors) {
1192                    if (symbols != NULL) {
1193                        symbols = symbols->addNestedSymbol(String8("styleable"), srcPos);
1194                    }
1195                    sp<AaptSymbols> styleSymbols = symbols;
1196                    if (symbols != NULL) {
1197                        symbols = symbols->addNestedSymbol(String8(ident), srcPos);
1198                    }
1199                    if (symbols == NULL) {
1200                        srcPos.error("Unable to create symbols!\n");
1201                        return UNKNOWN_ERROR;
1202                    }
1203
1204                    String16 comment(
1205                        block.getComment(&len) ? block.getComment(&len) : nulStr);
1206                    styleSymbols->appendComment(String8(ident), comment, srcPos);
1207                } else {
1208                    symbols = NULL;
1209                }
1210
1211                while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1212                    if (code == ResXMLTree::START_TAG) {
1213                        if (strcmp16(block.getElementName(&len), skip16.string()) == 0) {
1214                            while ((code=block.next()) != ResXMLTree::END_DOCUMENT
1215                                   && code != ResXMLTree::BAD_DOCUMENT) {
1216                                if (code == ResXMLTree::END_TAG) {
1217                                    if (strcmp16(block.getElementName(&len), skip16.string()) == 0) {
1218                                        break;
1219                                    }
1220                                }
1221                            }
1222                            continue;
1223                        } else if (strcmp16(block.getElementName(&len), eat_comment16.string()) == 0) {
1224                            while ((code=block.next()) != ResXMLTree::END_DOCUMENT
1225                                   && code != ResXMLTree::BAD_DOCUMENT) {
1226                                if (code == ResXMLTree::END_TAG) {
1227                                    if (strcmp16(block.getElementName(&len), eat_comment16.string()) == 0) {
1228                                        break;
1229                                    }
1230                                }
1231                            }
1232                            continue;
1233                        } else if (strcmp16(block.getElementName(&len), attr16.string()) != 0) {
1234                            SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1235                                    "Tag <%s> can not appear inside <declare-styleable>, only <attr>\n",
1236                                    String8(block.getElementName(&len)).string());
1237                            return UNKNOWN_ERROR;
1238                        }
1239
1240                        String16 comment(
1241                            block.getComment(&len) ? block.getComment(&len) : nulStr);
1242                        String16 itemIdent;
1243                        err = compileAttribute(in, block, myPackage, outTable, &itemIdent, true);
1244                        if (err != NO_ERROR) {
1245                            hasErrors = localHasErrors = true;
1246                        }
1247
1248                        if (symbols != NULL) {
1249                            SourcePos srcPos(String8(in->getPrintableSource()), block.getLineNumber());
1250                            symbols->addSymbol(String8(itemIdent), 0, srcPos);
1251                            symbols->appendComment(String8(itemIdent), comment, srcPos);
1252                            //printf("Attribute %s comment: %s\n", String8(itemIdent).string(),
1253                            //     String8(comment).string());
1254                        }
1255                    } else if (code == ResXMLTree::END_TAG) {
1256                        if (strcmp16(block.getElementName(&len), declare_styleable16.string()) == 0) {
1257                            break;
1258                        }
1259
1260                        SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1261                                "Found tag </%s> where </attr> is expected\n",
1262                                String8(block.getElementName(&len)).string());
1263                        return UNKNOWN_ERROR;
1264                    }
1265                }
1266                continue;
1267
1268            } else if (strcmp16(block.getElementName(&len), attr16.string()) == 0) {
1269                err = compileAttribute(in, block, myPackage, outTable, NULL);
1270                if (err != NO_ERROR) {
1271                    hasErrors = true;
1272                }
1273                continue;
1274
1275            } else if (strcmp16(block.getElementName(&len), item16.string()) == 0) {
1276                curTag = &item16;
1277                ssize_t attri = block.indexOfAttribute(NULL, "type");
1278                if (attri >= 0) {
1279                    curType = String16(block.getAttributeStringValue(attri, &len));
1280                    ssize_t formatIdx = block.indexOfAttribute(NULL, "format");
1281                    if (formatIdx >= 0) {
1282                        String16 formatStr = String16(block.getAttributeStringValue(
1283                                formatIdx, &len));
1284                        curFormat = parse_flags(formatStr.string(), formatStr.size(),
1285                                                gFormatFlags);
1286                        if (curFormat == 0) {
1287                            SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1288                                    "Tag <item> 'format' attribute value \"%s\" not valid\n",
1289                                    String8(formatStr).string());
1290                            hasErrors = localHasErrors = true;
1291                        }
1292                    }
1293                } else {
1294                    SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1295                            "A 'type' attribute is required for <item>\n");
1296                    hasErrors = localHasErrors = true;
1297                }
1298                curIsStyled = true;
1299            } else if (strcmp16(block.getElementName(&len), string16.string()) == 0) {
1300                // Note the existence and locale of every string we process
1301                char rawLocale[RESTABLE_MAX_LOCALE_LEN];
1302                curParams.getBcp47Locale(rawLocale);
1303                String8 locale(rawLocale);
1304                String16 name;
1305                String16 translatable;
1306                String16 formatted;
1307
1308                size_t n = block.getAttributeCount();
1309                for (size_t i = 0; i < n; i++) {
1310                    size_t length;
1311                    const uint16_t* attr = block.getAttributeName(i, &length);
1312                    if (strcmp16(attr, name16.string()) == 0) {
1313                        name.setTo(block.getAttributeStringValue(i, &length));
1314                    } else if (strcmp16(attr, translatable16.string()) == 0) {
1315                        translatable.setTo(block.getAttributeStringValue(i, &length));
1316                    } else if (strcmp16(attr, formatted16.string()) == 0) {
1317                        formatted.setTo(block.getAttributeStringValue(i, &length));
1318                    }
1319                }
1320
1321                if (name.size() > 0) {
1322                    if (translatable == false16) {
1323                        curIsFormatted = false;
1324                        // Untranslatable strings must only exist in the default [empty] locale
1325                        if (locale.size() > 0) {
1326                            SourcePos(in->getPrintableSource(), block.getLineNumber()).warning(
1327                                    "string '%s' marked untranslatable but exists in locale '%s'\n",
1328                                    String8(name).string(),
1329                                    locale.string());
1330                            // hasErrors = localHasErrors = true;
1331                        } else {
1332                            // Intentionally empty block:
1333                            //
1334                            // Don't add untranslatable strings to the localization table; that
1335                            // way if we later see localizations of them, they'll be flagged as
1336                            // having no default translation.
1337                        }
1338                    } else {
1339                        outTable->addLocalization(
1340                                name,
1341                                locale,
1342                                SourcePos(in->getPrintableSource(), block.getLineNumber()));
1343                    }
1344
1345                    if (formatted == false16) {
1346                        curIsFormatted = false;
1347                    }
1348                }
1349
1350                curTag = &string16;
1351                curType = string16;
1352                curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_STRING;
1353                curIsStyled = true;
1354                curIsPseudolocalizable = fileIsTranslatable && (translatable != false16);
1355            } else if (strcmp16(block.getElementName(&len), drawable16.string()) == 0) {
1356                curTag = &drawable16;
1357                curType = drawable16;
1358                curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_COLOR;
1359            } else if (strcmp16(block.getElementName(&len), color16.string()) == 0) {
1360                curTag = &color16;
1361                curType = color16;
1362                curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_COLOR;
1363            } else if (strcmp16(block.getElementName(&len), bool16.string()) == 0) {
1364                curTag = &bool16;
1365                curType = bool16;
1366                curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_BOOLEAN;
1367            } else if (strcmp16(block.getElementName(&len), integer16.string()) == 0) {
1368                curTag = &integer16;
1369                curType = integer16;
1370                curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_INTEGER;
1371            } else if (strcmp16(block.getElementName(&len), dimen16.string()) == 0) {
1372                curTag = &dimen16;
1373                curType = dimen16;
1374                curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_DIMENSION;
1375            } else if (strcmp16(block.getElementName(&len), fraction16.string()) == 0) {
1376                curTag = &fraction16;
1377                curType = fraction16;
1378                curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_FRACTION;
1379            } else if (strcmp16(block.getElementName(&len), bag16.string()) == 0) {
1380                curTag = &bag16;
1381                curIsBag = true;
1382                ssize_t attri = block.indexOfAttribute(NULL, "type");
1383                if (attri >= 0) {
1384                    curType = String16(block.getAttributeStringValue(attri, &len));
1385                } else {
1386                    SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1387                            "A 'type' attribute is required for <bag>\n");
1388                    hasErrors = localHasErrors = true;
1389                }
1390            } else if (strcmp16(block.getElementName(&len), style16.string()) == 0) {
1391                curTag = &style16;
1392                curType = style16;
1393                curIsBag = true;
1394            } else if (strcmp16(block.getElementName(&len), plurals16.string()) == 0) {
1395                curTag = &plurals16;
1396                curType = plurals16;
1397                curIsBag = true;
1398                curIsPseudolocalizable = fileIsTranslatable;
1399            } else if (strcmp16(block.getElementName(&len), array16.string()) == 0) {
1400                curTag = &array16;
1401                curType = array16;
1402                curIsBag = true;
1403                curIsBagReplaceOnOverwrite = true;
1404                ssize_t formatIdx = block.indexOfAttribute(NULL, "format");
1405                if (formatIdx >= 0) {
1406                    String16 formatStr = String16(block.getAttributeStringValue(
1407                            formatIdx, &len));
1408                    curFormat = parse_flags(formatStr.string(), formatStr.size(),
1409                                            gFormatFlags);
1410                    if (curFormat == 0) {
1411                        SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1412                                "Tag <array> 'format' attribute value \"%s\" not valid\n",
1413                                String8(formatStr).string());
1414                        hasErrors = localHasErrors = true;
1415                    }
1416                }
1417            } else if (strcmp16(block.getElementName(&len), string_array16.string()) == 0) {
1418                // Check whether these strings need valid formats.
1419                // (simplified form of what string16 does above)
1420                bool isTranslatable = false;
1421                size_t n = block.getAttributeCount();
1422
1423                // Pseudolocalizable by default, unless this string array isn't
1424                // translatable.
1425                for (size_t i = 0; i < n; i++) {
1426                    size_t length;
1427                    const uint16_t* attr = block.getAttributeName(i, &length);
1428                    if (strcmp16(attr, formatted16.string()) == 0) {
1429                        const uint16_t* value = block.getAttributeStringValue(i, &length);
1430                        if (strcmp16(value, false16.string()) == 0) {
1431                            curIsFormatted = false;
1432                        }
1433                    } else if (strcmp16(attr, translatable16.string()) == 0) {
1434                        const uint16_t* value = block.getAttributeStringValue(i, &length);
1435                        if (strcmp16(value, false16.string()) == 0) {
1436                            isTranslatable = false;
1437                        }
1438                    }
1439                }
1440
1441                curTag = &string_array16;
1442                curType = array16;
1443                curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_STRING;
1444                curIsBag = true;
1445                curIsBagReplaceOnOverwrite = true;
1446                curIsPseudolocalizable = isTranslatable && fileIsTranslatable;
1447            } else if (strcmp16(block.getElementName(&len), integer_array16.string()) == 0) {
1448                curTag = &integer_array16;
1449                curType = array16;
1450                curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_INTEGER;
1451                curIsBag = true;
1452                curIsBagReplaceOnOverwrite = true;
1453            } else {
1454                SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1455                        "Found tag %s where item is expected\n",
1456                        String8(block.getElementName(&len)).string());
1457                return UNKNOWN_ERROR;
1458            }
1459
1460            String16 ident;
1461            ssize_t identIdx = block.indexOfAttribute(NULL, "name");
1462            if (identIdx >= 0) {
1463                ident = String16(block.getAttributeStringValue(identIdx, &len));
1464            } else {
1465                SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1466                        "A 'name' attribute is required for <%s>\n",
1467                        String8(*curTag).string());
1468                hasErrors = localHasErrors = true;
1469            }
1470
1471            String16 product;
1472            identIdx = block.indexOfAttribute(NULL, "product");
1473            if (identIdx >= 0) {
1474                product = String16(block.getAttributeStringValue(identIdx, &len));
1475            }
1476
1477            String16 comment(block.getComment(&len) ? block.getComment(&len) : nulStr);
1478
1479            if (curIsBag) {
1480                // Figure out the parent of this bag...
1481                String16 parentIdent;
1482                ssize_t parentIdentIdx = block.indexOfAttribute(NULL, "parent");
1483                if (parentIdentIdx >= 0) {
1484                    parentIdent = String16(block.getAttributeStringValue(parentIdentIdx, &len));
1485                } else {
1486                    ssize_t sep = ident.findLast('.');
1487                    if (sep >= 0) {
1488                        parentIdent.setTo(ident, sep);
1489                    }
1490                }
1491
1492                if (!localHasErrors) {
1493                    err = outTable->startBag(SourcePos(in->getPrintableSource(),
1494                            block.getLineNumber()), myPackage, curType, ident,
1495                            parentIdent, &curParams,
1496                            overwrite, curIsBagReplaceOnOverwrite);
1497                    if (err != NO_ERROR) {
1498                        hasErrors = localHasErrors = true;
1499                    }
1500                }
1501
1502                ssize_t elmIndex = 0;
1503                char elmIndexStr[14];
1504                while ((code=block.next()) != ResXMLTree::END_DOCUMENT
1505                        && code != ResXMLTree::BAD_DOCUMENT) {
1506
1507                    if (code == ResXMLTree::START_TAG) {
1508                        if (strcmp16(block.getElementName(&len), item16.string()) != 0) {
1509                            SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1510                                    "Tag <%s> can not appear inside <%s>, only <item>\n",
1511                                    String8(block.getElementName(&len)).string(),
1512                                    String8(*curTag).string());
1513                            return UNKNOWN_ERROR;
1514                        }
1515
1516                        String16 itemIdent;
1517                        if (curType == array16) {
1518                            sprintf(elmIndexStr, "^index_%d", (int)elmIndex++);
1519                            itemIdent = String16(elmIndexStr);
1520                        } else if (curType == plurals16) {
1521                            ssize_t itemIdentIdx = block.indexOfAttribute(NULL, "quantity");
1522                            if (itemIdentIdx >= 0) {
1523                                String16 quantity16(block.getAttributeStringValue(itemIdentIdx, &len));
1524                                if (quantity16 == other16) {
1525                                    itemIdent = quantityOther16;
1526                                }
1527                                else if (quantity16 == zero16) {
1528                                    itemIdent = quantityZero16;
1529                                }
1530                                else if (quantity16 == one16) {
1531                                    itemIdent = quantityOne16;
1532                                }
1533                                else if (quantity16 == two16) {
1534                                    itemIdent = quantityTwo16;
1535                                }
1536                                else if (quantity16 == few16) {
1537                                    itemIdent = quantityFew16;
1538                                }
1539                                else if (quantity16 == many16) {
1540                                    itemIdent = quantityMany16;
1541                                }
1542                                else {
1543                                    SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1544                                            "Illegal 'quantity' attribute is <item> inside <plurals>\n");
1545                                    hasErrors = localHasErrors = true;
1546                                }
1547                            } else {
1548                                SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1549                                        "A 'quantity' attribute is required for <item> inside <plurals>\n");
1550                                hasErrors = localHasErrors = true;
1551                            }
1552                        } else {
1553                            ssize_t itemIdentIdx = block.indexOfAttribute(NULL, "name");
1554                            if (itemIdentIdx >= 0) {
1555                                itemIdent = String16(block.getAttributeStringValue(itemIdentIdx, &len));
1556                            } else {
1557                                SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1558                                        "A 'name' attribute is required for <item>\n");
1559                                hasErrors = localHasErrors = true;
1560                            }
1561                        }
1562
1563                        ResXMLParser::ResXMLPosition parserPosition;
1564                        block.getPosition(&parserPosition);
1565
1566                        err = parseAndAddBag(bundle, in, &block, curParams, myPackage, curType,
1567                                ident, parentIdent, itemIdent, curFormat, curIsFormatted,
1568                                product, NO_PSEUDOLOCALIZATION, overwrite, outTable);
1569                        if (err == NO_ERROR) {
1570                            if (curIsPseudolocalizable && localeIsDefined(curParams)
1571                                    && bundle->getPseudolocalize() > 0) {
1572                                // pseudolocalize here
1573                                if ((PSEUDO_ACCENTED & bundle->getPseudolocalize()) ==
1574                                   PSEUDO_ACCENTED) {
1575                                    block.setPosition(parserPosition);
1576                                    err = parseAndAddBag(bundle, in, &block, pseudoParams, myPackage,
1577                                            curType, ident, parentIdent, itemIdent, curFormat,
1578                                            curIsFormatted, product, PSEUDO_ACCENTED,
1579                                            overwrite, outTable);
1580                                }
1581                                if ((PSEUDO_BIDI & bundle->getPseudolocalize()) ==
1582                                   PSEUDO_BIDI) {
1583                                    block.setPosition(parserPosition);
1584                                    err = parseAndAddBag(bundle, in, &block, pseudoBidiParams, myPackage,
1585                                            curType, ident, parentIdent, itemIdent, curFormat,
1586                                            curIsFormatted, product, PSEUDO_BIDI,
1587                                            overwrite, outTable);
1588                                }
1589                            }
1590                        }
1591                        if (err != NO_ERROR) {
1592                            hasErrors = localHasErrors = true;
1593                        }
1594                    } else if (code == ResXMLTree::END_TAG) {
1595                        if (strcmp16(block.getElementName(&len), curTag->string()) != 0) {
1596                            SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1597                                    "Found tag </%s> where </%s> is expected\n",
1598                                    String8(block.getElementName(&len)).string(),
1599                                    String8(*curTag).string());
1600                            return UNKNOWN_ERROR;
1601                        }
1602                        break;
1603                    }
1604                }
1605            } else {
1606                ResXMLParser::ResXMLPosition parserPosition;
1607                block.getPosition(&parserPosition);
1608
1609                err = parseAndAddEntry(bundle, in, &block, curParams, myPackage, curType, ident,
1610                        *curTag, curIsStyled, curFormat, curIsFormatted,
1611                        product, NO_PSEUDOLOCALIZATION, overwrite, &skippedResourceNames, outTable);
1612
1613                if (err < NO_ERROR) { // Why err < NO_ERROR instead of err != NO_ERROR?
1614                    hasErrors = localHasErrors = true;
1615                }
1616                else if (err == NO_ERROR) {
1617                    if (curIsPseudolocalizable && localeIsDefined(curParams)
1618                            && bundle->getPseudolocalize() > 0) {
1619                        // pseudolocalize here
1620                        if ((PSEUDO_ACCENTED & bundle->getPseudolocalize()) ==
1621                           PSEUDO_ACCENTED) {
1622                            block.setPosition(parserPosition);
1623                            err = parseAndAddEntry(bundle, in, &block, pseudoParams, myPackage, curType,
1624                                    ident, *curTag, curIsStyled, curFormat,
1625                                    curIsFormatted, product,
1626                                    PSEUDO_ACCENTED, overwrite, &skippedResourceNames, outTable);
1627                        }
1628                        if ((PSEUDO_BIDI & bundle->getPseudolocalize()) ==
1629                           PSEUDO_BIDI) {
1630                            block.setPosition(parserPosition);
1631                            err = parseAndAddEntry(bundle, in, &block, pseudoBidiParams,
1632                                    myPackage, curType, ident, *curTag, curIsStyled, curFormat,
1633                                    curIsFormatted, product,
1634                                    PSEUDO_BIDI, overwrite, &skippedResourceNames, outTable);
1635                        }
1636                        if (err != NO_ERROR) {
1637                            hasErrors = localHasErrors = true;
1638                        }
1639                    }
1640                }
1641            }
1642
1643#if 0
1644            if (comment.size() > 0) {
1645                printf("Comment for @%s:%s/%s: %s\n", String8(myPackage).string(),
1646                       String8(curType).string(), String8(ident).string(),
1647                       String8(comment).string());
1648            }
1649#endif
1650            if (!localHasErrors) {
1651                outTable->appendComment(myPackage, curType, ident, comment, false);
1652            }
1653        }
1654        else if (code == ResXMLTree::END_TAG) {
1655            if (strcmp16(block.getElementName(&len), resources16.string()) != 0) {
1656                SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1657                        "Unexpected end tag %s\n", String8(block.getElementName(&len)).string());
1658                return UNKNOWN_ERROR;
1659            }
1660        }
1661        else if (code == ResXMLTree::START_NAMESPACE || code == ResXMLTree::END_NAMESPACE) {
1662        }
1663        else if (code == ResXMLTree::TEXT) {
1664            if (isWhitespace(block.getText(&len))) {
1665                continue;
1666            }
1667            SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1668                    "Found text \"%s\" where item tag is expected\n",
1669                    String8(block.getText(&len)).string());
1670            return UNKNOWN_ERROR;
1671        }
1672    }
1673
1674    // For every resource defined, there must be exist one variant with a product attribute
1675    // set to 'default' (or no product attribute at all).
1676    // We check to see that for every resource that was ignored because of a mismatched
1677    // product attribute, some product variant of that resource was processed.
1678    for (size_t i = 0; i < skippedResourceNames.size(); i++) {
1679        if (skippedResourceNames[i]) {
1680            const type_ident_pair_t& p = skippedResourceNames.keyAt(i);
1681            if (!outTable->hasBagOrEntry(myPackage, p.type, p.ident)) {
1682                const char* bundleProduct =
1683                        (bundle->getProduct() == NULL) ? "" : bundle->getProduct();
1684                fprintf(stderr, "In resource file %s: %s\n",
1685                        in->getPrintableSource().string(),
1686                        curParams.toString().string());
1687
1688                fprintf(stderr, "\t%s '%s' does not match product %s.\n"
1689                        "\tYou may have forgotten to include a 'default' product variant"
1690                        " of the resource.\n",
1691                        String8(p.type).string(), String8(p.ident).string(),
1692                        bundleProduct[0] == 0 ? "default" : bundleProduct);
1693                return UNKNOWN_ERROR;
1694            }
1695        }
1696    }
1697
1698    return hasErrors ? UNKNOWN_ERROR : NO_ERROR;
1699}
1700
1701ResourceTable::ResourceTable(Bundle* bundle, const String16& assetsPackage)
1702    : mAssetsPackage(assetsPackage), mNextPackageId(1), mHaveAppPackage(false),
1703      mIsAppPackage(!bundle->getExtending()),
1704      mNumLocal(0),
1705      mBundle(bundle)
1706{
1707}
1708
1709status_t ResourceTable::addIncludedResources(Bundle* bundle, const sp<AaptAssets>& assets)
1710{
1711    status_t err = assets->buildIncludedResources(bundle);
1712    if (err != NO_ERROR) {
1713        return err;
1714    }
1715
1716    // For future reference to included resources.
1717    mAssets = assets;
1718
1719    const ResTable& incl = assets->getIncludedResources();
1720
1721    // Retrieve all the packages.
1722    const size_t N = incl.getBasePackageCount();
1723    for (size_t phase=0; phase<2; phase++) {
1724        for (size_t i=0; i<N; i++) {
1725            String16 name(incl.getBasePackageName(i));
1726            uint32_t id = incl.getBasePackageId(i);
1727            // First time through: only add base packages (id
1728            // is not 0); second time through add the other
1729            // packages.
1730            if (phase != 0) {
1731                if (id != 0) {
1732                    // Skip base packages -- already one.
1733                    id = 0;
1734                } else {
1735                    // Assign a dynamic id.
1736                    id = mNextPackageId;
1737                }
1738            } else if (id != 0) {
1739                if (id == 127) {
1740                    if (mHaveAppPackage) {
1741                        fprintf(stderr, "Included resources have two application packages!\n");
1742                        return UNKNOWN_ERROR;
1743                    }
1744                    mHaveAppPackage = true;
1745                }
1746                if (mNextPackageId > id) {
1747                    fprintf(stderr, "Included base package ID %d already in use!\n", id);
1748                    return UNKNOWN_ERROR;
1749                }
1750            }
1751            if (id != 0) {
1752                NOISY(printf("Including package %s with ID=%d\n",
1753                             String8(name).string(), id));
1754                sp<Package> p = new Package(name, id);
1755                mPackages.add(name, p);
1756                mOrderedPackages.add(p);
1757
1758                if (id >= mNextPackageId) {
1759                    mNextPackageId = id+1;
1760                }
1761            }
1762        }
1763    }
1764
1765    // Every resource table always has one first entry, the bag attributes.
1766    const SourcePos unknown(String8("????"), 0);
1767    sp<Type> attr = getType(mAssetsPackage, String16("attr"), unknown);
1768
1769    return NO_ERROR;
1770}
1771
1772status_t ResourceTable::addPublic(const SourcePos& sourcePos,
1773                                  const String16& package,
1774                                  const String16& type,
1775                                  const String16& name,
1776                                  const uint32_t ident)
1777{
1778    uint32_t rid = mAssets->getIncludedResources()
1779        .identifierForName(name.string(), name.size(),
1780                           type.string(), type.size(),
1781                           package.string(), package.size());
1782    if (rid != 0) {
1783        sourcePos.error("Error declaring public resource %s/%s for included package %s\n",
1784                String8(type).string(), String8(name).string(),
1785                String8(package).string());
1786        return UNKNOWN_ERROR;
1787    }
1788
1789    sp<Type> t = getType(package, type, sourcePos);
1790    if (t == NULL) {
1791        return UNKNOWN_ERROR;
1792    }
1793    return t->addPublic(sourcePos, name, ident);
1794}
1795
1796status_t ResourceTable::addEntry(const SourcePos& sourcePos,
1797                                 const String16& package,
1798                                 const String16& type,
1799                                 const String16& name,
1800                                 const String16& value,
1801                                 const Vector<StringPool::entry_style_span>* style,
1802                                 const ResTable_config* params,
1803                                 const bool doSetIndex,
1804                                 const int32_t format,
1805                                 const bool overwrite)
1806{
1807    // Check for adding entries in other packages...  for now we do
1808    // nothing.  We need to do the right thing here to support skinning.
1809    uint32_t rid = mAssets->getIncludedResources()
1810        .identifierForName(name.string(), name.size(),
1811                           type.string(), type.size(),
1812                           package.string(), package.size());
1813    if (rid != 0) {
1814        return NO_ERROR;
1815    }
1816
1817#if 0
1818    if (name == String16("left")) {
1819        printf("Adding entry left: file=%s, line=%d, type=%s, value=%s\n",
1820               sourcePos.file.string(), sourcePos.line, String8(type).string(),
1821               String8(value).string());
1822    }
1823#endif
1824
1825    sp<Entry> e = getEntry(package, type, name, sourcePos, overwrite,
1826                           params, doSetIndex);
1827    if (e == NULL) {
1828        return UNKNOWN_ERROR;
1829    }
1830    status_t err = e->setItem(sourcePos, value, style, format, overwrite);
1831    if (err == NO_ERROR) {
1832        mNumLocal++;
1833    }
1834    return err;
1835}
1836
1837status_t ResourceTable::startBag(const SourcePos& sourcePos,
1838                                 const String16& package,
1839                                 const String16& type,
1840                                 const String16& name,
1841                                 const String16& bagParent,
1842                                 const ResTable_config* params,
1843                                 bool overlay,
1844                                 bool replace, bool isId)
1845{
1846    status_t result = NO_ERROR;
1847
1848    // Check for adding entries in other packages...  for now we do
1849    // nothing.  We need to do the right thing here to support skinning.
1850    uint32_t rid = mAssets->getIncludedResources()
1851    .identifierForName(name.string(), name.size(),
1852                       type.string(), type.size(),
1853                       package.string(), package.size());
1854    if (rid != 0) {
1855        return NO_ERROR;
1856    }
1857
1858#if 0
1859    if (name == String16("left")) {
1860        printf("Adding bag left: file=%s, line=%d, type=%s\n",
1861               sourcePos.file.striing(), sourcePos.line, String8(type).string());
1862    }
1863#endif
1864    if (overlay && !mBundle->getAutoAddOverlay() && !hasBagOrEntry(package, type, name)) {
1865        bool canAdd = false;
1866        sp<Package> p = mPackages.valueFor(package);
1867        if (p != NULL) {
1868            sp<Type> t = p->getTypes().valueFor(type);
1869            if (t != NULL) {
1870                if (t->getCanAddEntries().indexOf(name) >= 0) {
1871                    canAdd = true;
1872                }
1873            }
1874        }
1875        if (!canAdd) {
1876            sourcePos.error("Resource does not already exist in overlay at '%s'; use <add-resource> to add.\n",
1877                            String8(name).string());
1878            return UNKNOWN_ERROR;
1879        }
1880    }
1881    sp<Entry> e = getEntry(package, type, name, sourcePos, overlay, params);
1882    if (e == NULL) {
1883        return UNKNOWN_ERROR;
1884    }
1885
1886    // If a parent is explicitly specified, set it.
1887    if (bagParent.size() > 0) {
1888        e->setParent(bagParent);
1889    }
1890
1891    if ((result = e->makeItABag(sourcePos)) != NO_ERROR) {
1892        return result;
1893    }
1894
1895    if (overlay && replace) {
1896        return e->emptyBag(sourcePos);
1897    }
1898    return result;
1899}
1900
1901status_t ResourceTable::addBag(const SourcePos& sourcePos,
1902                               const String16& package,
1903                               const String16& type,
1904                               const String16& name,
1905                               const String16& bagParent,
1906                               const String16& bagKey,
1907                               const String16& value,
1908                               const Vector<StringPool::entry_style_span>* style,
1909                               const ResTable_config* params,
1910                               bool replace, bool isId, const int32_t format)
1911{
1912    // Check for adding entries in other packages...  for now we do
1913    // nothing.  We need to do the right thing here to support skinning.
1914    uint32_t rid = mAssets->getIncludedResources()
1915        .identifierForName(name.string(), name.size(),
1916                           type.string(), type.size(),
1917                           package.string(), package.size());
1918    if (rid != 0) {
1919        return NO_ERROR;
1920    }
1921
1922#if 0
1923    if (name == String16("left")) {
1924        printf("Adding bag left: file=%s, line=%d, type=%s\n",
1925               sourcePos.file.striing(), sourcePos.line, String8(type).string());
1926    }
1927#endif
1928    sp<Entry> e = getEntry(package, type, name, sourcePos, replace, params);
1929    if (e == NULL) {
1930        return UNKNOWN_ERROR;
1931    }
1932
1933    // If a parent is explicitly specified, set it.
1934    if (bagParent.size() > 0) {
1935        e->setParent(bagParent);
1936    }
1937
1938    const bool first = e->getBag().indexOfKey(bagKey) < 0;
1939    status_t err = e->addToBag(sourcePos, bagKey, value, style, replace, isId, format);
1940    if (err == NO_ERROR && first) {
1941        mNumLocal++;
1942    }
1943    return err;
1944}
1945
1946bool ResourceTable::hasBagOrEntry(const String16& package,
1947                                  const String16& type,
1948                                  const String16& name) const
1949{
1950    // First look for this in the included resources...
1951    uint32_t rid = mAssets->getIncludedResources()
1952        .identifierForName(name.string(), name.size(),
1953                           type.string(), type.size(),
1954                           package.string(), package.size());
1955    if (rid != 0) {
1956        return true;
1957    }
1958
1959    sp<Package> p = mPackages.valueFor(package);
1960    if (p != NULL) {
1961        sp<Type> t = p->getTypes().valueFor(type);
1962        if (t != NULL) {
1963            sp<ConfigList> c =  t->getConfigs().valueFor(name);
1964            if (c != NULL) return true;
1965        }
1966    }
1967
1968    return false;
1969}
1970
1971bool ResourceTable::hasBagOrEntry(const String16& package,
1972                                  const String16& type,
1973                                  const String16& name,
1974                                  const ResTable_config& config) const
1975{
1976    // First look for this in the included resources...
1977    uint32_t rid = mAssets->getIncludedResources()
1978        .identifierForName(name.string(), name.size(),
1979                           type.string(), type.size(),
1980                           package.string(), package.size());
1981    if (rid != 0) {
1982        return true;
1983    }
1984
1985    sp<Package> p = mPackages.valueFor(package);
1986    if (p != NULL) {
1987        sp<Type> t = p->getTypes().valueFor(type);
1988        if (t != NULL) {
1989            sp<ConfigList> c =  t->getConfigs().valueFor(name);
1990            if (c != NULL) {
1991                sp<Entry> e = c->getEntries().valueFor(config);
1992                if (e != NULL) {
1993                    return true;
1994                }
1995            }
1996        }
1997    }
1998
1999    return false;
2000}
2001
2002bool ResourceTable::hasBagOrEntry(const String16& ref,
2003                                  const String16* defType,
2004                                  const String16* defPackage)
2005{
2006    String16 package, type, name;
2007    if (!ResTable::expandResourceRef(ref.string(), ref.size(), &package, &type, &name,
2008                defType, defPackage ? defPackage:&mAssetsPackage, NULL)) {
2009        return false;
2010    }
2011    return hasBagOrEntry(package, type, name);
2012}
2013
2014bool ResourceTable::appendComment(const String16& package,
2015                                  const String16& type,
2016                                  const String16& name,
2017                                  const String16& comment,
2018                                  bool onlyIfEmpty)
2019{
2020    if (comment.size() <= 0) {
2021        return true;
2022    }
2023
2024    sp<Package> p = mPackages.valueFor(package);
2025    if (p != NULL) {
2026        sp<Type> t = p->getTypes().valueFor(type);
2027        if (t != NULL) {
2028            sp<ConfigList> c =  t->getConfigs().valueFor(name);
2029            if (c != NULL) {
2030                c->appendComment(comment, onlyIfEmpty);
2031                return true;
2032            }
2033        }
2034    }
2035    return false;
2036}
2037
2038bool ResourceTable::appendTypeComment(const String16& package,
2039                                      const String16& type,
2040                                      const String16& name,
2041                                      const String16& comment)
2042{
2043    if (comment.size() <= 0) {
2044        return true;
2045    }
2046
2047    sp<Package> p = mPackages.valueFor(package);
2048    if (p != NULL) {
2049        sp<Type> t = p->getTypes().valueFor(type);
2050        if (t != NULL) {
2051            sp<ConfigList> c =  t->getConfigs().valueFor(name);
2052            if (c != NULL) {
2053                c->appendTypeComment(comment);
2054                return true;
2055            }
2056        }
2057    }
2058    return false;
2059}
2060
2061void ResourceTable::canAddEntry(const SourcePos& pos,
2062        const String16& package, const String16& type, const String16& name)
2063{
2064    sp<Type> t = getType(package, type, pos);
2065    if (t != NULL) {
2066        t->canAddEntry(name);
2067    }
2068}
2069
2070size_t ResourceTable::size() const {
2071    return mPackages.size();
2072}
2073
2074size_t ResourceTable::numLocalResources() const {
2075    return mNumLocal;
2076}
2077
2078bool ResourceTable::hasResources() const {
2079    return mNumLocal > 0;
2080}
2081
2082sp<AaptFile> ResourceTable::flatten(Bundle* bundle)
2083{
2084    sp<AaptFile> data = new AaptFile(String8(), AaptGroupEntry(), String8());
2085    status_t err = flatten(bundle, data);
2086    return err == NO_ERROR ? data : NULL;
2087}
2088
2089inline uint32_t ResourceTable::getResId(const sp<Package>& p,
2090                                        const sp<Type>& t,
2091                                        uint32_t nameId)
2092{
2093    return makeResId(p->getAssignedId(), t->getIndex(), nameId);
2094}
2095
2096uint32_t ResourceTable::getResId(const String16& package,
2097                                 const String16& type,
2098                                 const String16& name,
2099                                 bool onlyPublic) const
2100{
2101    uint32_t id = ResourceIdCache::lookup(package, type, name, onlyPublic);
2102    if (id != 0) return id;     // cache hit
2103
2104    sp<Package> p = mPackages.valueFor(package);
2105    if (p == NULL) return 0;
2106
2107    // First look for this in the included resources...
2108    uint32_t specFlags = 0;
2109    uint32_t rid = mAssets->getIncludedResources()
2110        .identifierForName(name.string(), name.size(),
2111                           type.string(), type.size(),
2112                           package.string(), package.size(),
2113                           &specFlags);
2114    if (rid != 0) {
2115        if (onlyPublic) {
2116            if ((specFlags & ResTable_typeSpec::SPEC_PUBLIC) == 0) {
2117                return 0;
2118            }
2119        }
2120
2121        if (Res_INTERNALID(rid)) {
2122            return ResourceIdCache::store(package, type, name, onlyPublic, rid);
2123        }
2124        return ResourceIdCache::store(package, type, name, onlyPublic,
2125                Res_MAKEID(p->getAssignedId()-1, Res_GETTYPE(rid), Res_GETENTRY(rid)));
2126    }
2127
2128    sp<Type> t = p->getTypes().valueFor(type);
2129    if (t == NULL) return 0;
2130    sp<ConfigList> c =  t->getConfigs().valueFor(name);
2131    if (c == NULL) return 0;
2132    int32_t ei = c->getEntryIndex();
2133    if (ei < 0) return 0;
2134
2135    return ResourceIdCache::store(package, type, name, onlyPublic,
2136            getResId(p, t, ei));
2137}
2138
2139uint32_t ResourceTable::getResId(const String16& ref,
2140                                 const String16* defType,
2141                                 const String16* defPackage,
2142                                 const char** outErrorMsg,
2143                                 bool onlyPublic) const
2144{
2145    String16 package, type, name;
2146    bool refOnlyPublic = true;
2147    if (!ResTable::expandResourceRef(
2148        ref.string(), ref.size(), &package, &type, &name,
2149        defType, defPackage ? defPackage:&mAssetsPackage,
2150        outErrorMsg, &refOnlyPublic)) {
2151        NOISY(printf("Expanding resource: ref=%s\n",
2152                     String8(ref).string()));
2153        NOISY(printf("Expanding resource: defType=%s\n",
2154                     defType ? String8(*defType).string() : "NULL"));
2155        NOISY(printf("Expanding resource: defPackage=%s\n",
2156                     defPackage ? String8(*defPackage).string() : "NULL"));
2157        NOISY(printf("Expanding resource: ref=%s\n", String8(ref).string()));
2158        NOISY(printf("Expanded resource: p=%s, t=%s, n=%s, res=0\n",
2159                     String8(package).string(), String8(type).string(),
2160                     String8(name).string()));
2161        return 0;
2162    }
2163    uint32_t res = getResId(package, type, name, onlyPublic && refOnlyPublic);
2164    NOISY(printf("Expanded resource: p=%s, t=%s, n=%s, res=%d\n",
2165                 String8(package).string(), String8(type).string(),
2166                 String8(name).string(), res));
2167    if (res == 0) {
2168        if (outErrorMsg)
2169            *outErrorMsg = "No resource found that matches the given name";
2170    }
2171    return res;
2172}
2173
2174bool ResourceTable::isValidResourceName(const String16& s)
2175{
2176    const char16_t* p = s.string();
2177    bool first = true;
2178    while (*p) {
2179        if ((*p >= 'a' && *p <= 'z')
2180            || (*p >= 'A' && *p <= 'Z')
2181            || *p == '_'
2182            || (!first && *p >= '0' && *p <= '9')) {
2183            first = false;
2184            p++;
2185            continue;
2186        }
2187        return false;
2188    }
2189    return true;
2190}
2191
2192bool ResourceTable::stringToValue(Res_value* outValue, StringPool* pool,
2193                                  const String16& str,
2194                                  bool preserveSpaces, bool coerceType,
2195                                  uint32_t attrID,
2196                                  const Vector<StringPool::entry_style_span>* style,
2197                                  String16* outStr, void* accessorCookie,
2198                                  uint32_t attrType, const String8* configTypeName,
2199                                  const ConfigDescription* config)
2200{
2201    String16 finalStr;
2202
2203    bool res = true;
2204    if (style == NULL || style->size() == 0) {
2205        // Text is not styled so it can be any type...  let's figure it out.
2206        res = mAssets->getIncludedResources()
2207            .stringToValue(outValue, &finalStr, str.string(), str.size(), preserveSpaces,
2208                            coerceType, attrID, NULL, &mAssetsPackage, this,
2209                           accessorCookie, attrType);
2210    } else {
2211        // Styled text can only be a string, and while collecting the style
2212        // information we have already processed that string!
2213        outValue->size = sizeof(Res_value);
2214        outValue->res0 = 0;
2215        outValue->dataType = outValue->TYPE_STRING;
2216        outValue->data = 0;
2217        finalStr = str;
2218    }
2219
2220    if (!res) {
2221        return false;
2222    }
2223
2224    if (outValue->dataType == outValue->TYPE_STRING) {
2225        // Should do better merging styles.
2226        if (pool) {
2227            String8 configStr;
2228            if (config != NULL) {
2229                configStr = config->toString();
2230            } else {
2231                configStr = "(null)";
2232            }
2233            NOISY(printf("Adding to pool string style #%d config %s: %s\n",
2234                    style != NULL ? style->size() : 0,
2235                    configStr.string(), String8(finalStr).string()));
2236            if (style != NULL && style->size() > 0) {
2237                outValue->data = pool->add(finalStr, *style, configTypeName, config);
2238            } else {
2239                outValue->data = pool->add(finalStr, true, configTypeName, config);
2240            }
2241        } else {
2242            // Caller will fill this in later.
2243            outValue->data = 0;
2244        }
2245
2246        if (outStr) {
2247            *outStr = finalStr;
2248        }
2249
2250    }
2251
2252    return true;
2253}
2254
2255uint32_t ResourceTable::getCustomResource(
2256    const String16& package, const String16& type, const String16& name) const
2257{
2258    //printf("getCustomResource: %s %s %s\n", String8(package).string(),
2259    //       String8(type).string(), String8(name).string());
2260    sp<Package> p = mPackages.valueFor(package);
2261    if (p == NULL) return 0;
2262    sp<Type> t = p->getTypes().valueFor(type);
2263    if (t == NULL) return 0;
2264    sp<ConfigList> c =  t->getConfigs().valueFor(name);
2265    if (c == NULL) return 0;
2266    int32_t ei = c->getEntryIndex();
2267    if (ei < 0) return 0;
2268    return getResId(p, t, ei);
2269}
2270
2271uint32_t ResourceTable::getCustomResourceWithCreation(
2272        const String16& package, const String16& type, const String16& name,
2273        const bool createIfNotFound)
2274{
2275    uint32_t resId = getCustomResource(package, type, name);
2276    if (resId != 0 || !createIfNotFound) {
2277        return resId;
2278    }
2279    String16 value("false");
2280
2281    status_t status = addEntry(mCurrentXmlPos, package, type, name, value, NULL, NULL, true);
2282    if (status == NO_ERROR) {
2283        resId = getResId(package, type, name);
2284        return resId;
2285    }
2286    return 0;
2287}
2288
2289uint32_t ResourceTable::getRemappedPackage(uint32_t origPackage) const
2290{
2291    return origPackage;
2292}
2293
2294bool ResourceTable::getAttributeType(uint32_t attrID, uint32_t* outType)
2295{
2296    //printf("getAttributeType #%08x\n", attrID);
2297    Res_value value;
2298    if (getItemValue(attrID, ResTable_map::ATTR_TYPE, &value)) {
2299        //printf("getAttributeType #%08x (%s): #%08x\n", attrID,
2300        //       String8(getEntry(attrID)->getName()).string(), value.data);
2301        *outType = value.data;
2302        return true;
2303    }
2304    return false;
2305}
2306
2307bool ResourceTable::getAttributeMin(uint32_t attrID, uint32_t* outMin)
2308{
2309    //printf("getAttributeMin #%08x\n", attrID);
2310    Res_value value;
2311    if (getItemValue(attrID, ResTable_map::ATTR_MIN, &value)) {
2312        *outMin = value.data;
2313        return true;
2314    }
2315    return false;
2316}
2317
2318bool ResourceTable::getAttributeMax(uint32_t attrID, uint32_t* outMax)
2319{
2320    //printf("getAttributeMax #%08x\n", attrID);
2321    Res_value value;
2322    if (getItemValue(attrID, ResTable_map::ATTR_MAX, &value)) {
2323        *outMax = value.data;
2324        return true;
2325    }
2326    return false;
2327}
2328
2329uint32_t ResourceTable::getAttributeL10N(uint32_t attrID)
2330{
2331    //printf("getAttributeL10N #%08x\n", attrID);
2332    Res_value value;
2333    if (getItemValue(attrID, ResTable_map::ATTR_L10N, &value)) {
2334        return value.data;
2335    }
2336    return ResTable_map::L10N_NOT_REQUIRED;
2337}
2338
2339bool ResourceTable::getLocalizationSetting()
2340{
2341    return mBundle->getRequireLocalization();
2342}
2343
2344void ResourceTable::reportError(void* accessorCookie, const char* fmt, ...)
2345{
2346    if (accessorCookie != NULL && fmt != NULL) {
2347        AccessorCookie* ac = (AccessorCookie*)accessorCookie;
2348        int retval=0;
2349        char buf[1024];
2350        va_list ap;
2351        va_start(ap, fmt);
2352        retval = vsnprintf(buf, sizeof(buf), fmt, ap);
2353        va_end(ap);
2354        ac->sourcePos.error("Error: %s (at '%s' with value '%s').\n",
2355                            buf, ac->attr.string(), ac->value.string());
2356    }
2357}
2358
2359bool ResourceTable::getAttributeKeys(
2360    uint32_t attrID, Vector<String16>* outKeys)
2361{
2362    sp<const Entry> e = getEntry(attrID);
2363    if (e != NULL) {
2364        const size_t N = e->getBag().size();
2365        for (size_t i=0; i<N; i++) {
2366            const String16& key = e->getBag().keyAt(i);
2367            if (key.size() > 0 && key.string()[0] != '^') {
2368                outKeys->add(key);
2369            }
2370        }
2371        return true;
2372    }
2373    return false;
2374}
2375
2376bool ResourceTable::getAttributeEnum(
2377    uint32_t attrID, const char16_t* name, size_t nameLen,
2378    Res_value* outValue)
2379{
2380    //printf("getAttributeEnum #%08x %s\n", attrID, String8(name, nameLen).string());
2381    String16 nameStr(name, nameLen);
2382    sp<const Entry> e = getEntry(attrID);
2383    if (e != NULL) {
2384        const size_t N = e->getBag().size();
2385        for (size_t i=0; i<N; i++) {
2386            //printf("Comparing %s to %s\n", String8(name, nameLen).string(),
2387            //       String8(e->getBag().keyAt(i)).string());
2388            if (e->getBag().keyAt(i) == nameStr) {
2389                return getItemValue(attrID, e->getBag().valueAt(i).bagKeyId, outValue);
2390            }
2391        }
2392    }
2393    return false;
2394}
2395
2396bool ResourceTable::getAttributeFlags(
2397    uint32_t attrID, const char16_t* name, size_t nameLen,
2398    Res_value* outValue)
2399{
2400    outValue->dataType = Res_value::TYPE_INT_HEX;
2401    outValue->data = 0;
2402
2403    //printf("getAttributeFlags #%08x %s\n", attrID, String8(name, nameLen).string());
2404    String16 nameStr(name, nameLen);
2405    sp<const Entry> e = getEntry(attrID);
2406    if (e != NULL) {
2407        const size_t N = e->getBag().size();
2408
2409        const char16_t* end = name + nameLen;
2410        const char16_t* pos = name;
2411        while (pos < end) {
2412            const char16_t* start = pos;
2413            while (pos < end && *pos != '|') {
2414                pos++;
2415            }
2416
2417            String16 nameStr(start, pos-start);
2418            size_t i;
2419            for (i=0; i<N; i++) {
2420                //printf("Comparing \"%s\" to \"%s\"\n", String8(nameStr).string(),
2421                //       String8(e->getBag().keyAt(i)).string());
2422                if (e->getBag().keyAt(i) == nameStr) {
2423                    Res_value val;
2424                    bool got = getItemValue(attrID, e->getBag().valueAt(i).bagKeyId, &val);
2425                    if (!got) {
2426                        return false;
2427                    }
2428                    //printf("Got value: 0x%08x\n", val.data);
2429                    outValue->data |= val.data;
2430                    break;
2431                }
2432            }
2433
2434            if (i >= N) {
2435                // Didn't find this flag identifier.
2436                return false;
2437            }
2438            pos++;
2439        }
2440
2441        return true;
2442    }
2443    return false;
2444}
2445
2446status_t ResourceTable::assignResourceIds()
2447{
2448    const size_t N = mOrderedPackages.size();
2449    size_t pi;
2450    status_t firstError = NO_ERROR;
2451
2452    // First generate all bag attributes and assign indices.
2453    for (pi=0; pi<N; pi++) {
2454        sp<Package> p = mOrderedPackages.itemAt(pi);
2455        if (p == NULL || p->getTypes().size() == 0) {
2456            // Empty, skip!
2457            continue;
2458        }
2459
2460        status_t err = p->applyPublicTypeOrder();
2461        if (err != NO_ERROR && firstError == NO_ERROR) {
2462            firstError = err;
2463        }
2464
2465        // Generate attributes...
2466        const size_t N = p->getOrderedTypes().size();
2467        size_t ti;
2468        for (ti=0; ti<N; ti++) {
2469            sp<Type> t = p->getOrderedTypes().itemAt(ti);
2470            if (t == NULL) {
2471                continue;
2472            }
2473            const size_t N = t->getOrderedConfigs().size();
2474            for (size_t ci=0; ci<N; ci++) {
2475                sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2476                if (c == NULL) {
2477                    continue;
2478                }
2479                const size_t N = c->getEntries().size();
2480                for (size_t ei=0; ei<N; ei++) {
2481                    sp<Entry> e = c->getEntries().valueAt(ei);
2482                    if (e == NULL) {
2483                        continue;
2484                    }
2485                    status_t err = e->generateAttributes(this, p->getName());
2486                    if (err != NO_ERROR && firstError == NO_ERROR) {
2487                        firstError = err;
2488                    }
2489                }
2490            }
2491        }
2492
2493        const SourcePos unknown(String8("????"), 0);
2494        sp<Type> attr = p->getType(String16("attr"), unknown);
2495
2496        // Assign indices...
2497        for (ti=0; ti<N; ti++) {
2498            sp<Type> t = p->getOrderedTypes().itemAt(ti);
2499            if (t == NULL) {
2500                continue;
2501            }
2502            err = t->applyPublicEntryOrder();
2503            if (err != NO_ERROR && firstError == NO_ERROR) {
2504                firstError = err;
2505            }
2506
2507            const size_t N = t->getOrderedConfigs().size();
2508            t->setIndex(ti+1);
2509
2510            LOG_ALWAYS_FATAL_IF(ti == 0 && attr != t,
2511                                "First type is not attr!");
2512
2513            for (size_t ei=0; ei<N; ei++) {
2514                sp<ConfigList> c = t->getOrderedConfigs().itemAt(ei);
2515                if (c == NULL) {
2516                    continue;
2517                }
2518                c->setEntryIndex(ei);
2519            }
2520        }
2521
2522        // Assign resource IDs to keys in bags...
2523        for (ti=0; ti<N; ti++) {
2524            sp<Type> t = p->getOrderedTypes().itemAt(ti);
2525            if (t == NULL) {
2526                continue;
2527            }
2528            const size_t N = t->getOrderedConfigs().size();
2529            for (size_t ci=0; ci<N; ci++) {
2530                sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2531                //printf("Ordered config #%d: %p\n", ci, c.get());
2532                const size_t N = c->getEntries().size();
2533                for (size_t ei=0; ei<N; ei++) {
2534                    sp<Entry> e = c->getEntries().valueAt(ei);
2535                    if (e == NULL) {
2536                        continue;
2537                    }
2538                    status_t err = e->assignResourceIds(this, p->getName());
2539                    if (err != NO_ERROR && firstError == NO_ERROR) {
2540                        firstError = err;
2541                    }
2542                }
2543            }
2544        }
2545    }
2546    return firstError;
2547}
2548
2549status_t ResourceTable::addSymbols(const sp<AaptSymbols>& outSymbols) {
2550    const size_t N = mOrderedPackages.size();
2551    size_t pi;
2552
2553    for (pi=0; pi<N; pi++) {
2554        sp<Package> p = mOrderedPackages.itemAt(pi);
2555        if (p->getTypes().size() == 0) {
2556            // Empty, skip!
2557            continue;
2558        }
2559
2560        const size_t N = p->getOrderedTypes().size();
2561        size_t ti;
2562
2563        for (ti=0; ti<N; ti++) {
2564            sp<Type> t = p->getOrderedTypes().itemAt(ti);
2565            if (t == NULL) {
2566                continue;
2567            }
2568            const size_t N = t->getOrderedConfigs().size();
2569            sp<AaptSymbols> typeSymbols;
2570            typeSymbols = outSymbols->addNestedSymbol(String8(t->getName()), t->getPos());
2571            for (size_t ci=0; ci<N; ci++) {
2572                sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2573                if (c == NULL) {
2574                    continue;
2575                }
2576                uint32_t rid = getResId(p, t, ci);
2577                if (rid == 0) {
2578                    return UNKNOWN_ERROR;
2579                }
2580                if (Res_GETPACKAGE(rid) == (size_t)(p->getAssignedId()-1)) {
2581                    typeSymbols->addSymbol(String8(c->getName()), rid, c->getPos());
2582
2583                    String16 comment(c->getComment());
2584                    typeSymbols->appendComment(String8(c->getName()), comment, c->getPos());
2585                    //printf("Type symbol [%08x] %s comment: %s\n", rid,
2586                    //        String8(c->getName()).string(), String8(comment).string());
2587                    comment = c->getTypeComment();
2588                    typeSymbols->appendTypeComment(String8(c->getName()), comment);
2589                } else {
2590#if 0
2591                    printf("**** NO MATCH: 0x%08x vs 0x%08x\n",
2592                           Res_GETPACKAGE(rid), p->getAssignedId());
2593#endif
2594                }
2595            }
2596        }
2597    }
2598    return NO_ERROR;
2599}
2600
2601
2602void
2603ResourceTable::addLocalization(const String16& name, const String8& locale, const SourcePos& src)
2604{
2605    mLocalizations[name][locale] = src;
2606}
2607
2608
2609/*!
2610 * Flag various sorts of localization problems.  '+' indicates checks already implemented;
2611 * '-' indicates checks that will be implemented in the future.
2612 *
2613 * + A localized string for which no default-locale version exists => warning
2614 * + A string for which no version in an explicitly-requested locale exists => warning
2615 * + A localized translation of an translateable="false" string => warning
2616 * - A localized string not provided in every locale used by the table
2617 */
2618status_t
2619ResourceTable::validateLocalizations(void)
2620{
2621    status_t err = NO_ERROR;
2622    const String8 defaultLocale;
2623
2624    // For all strings...
2625    for (map<String16, map<String8, SourcePos> >::iterator nameIter = mLocalizations.begin();
2626         nameIter != mLocalizations.end();
2627         nameIter++) {
2628        const map<String8, SourcePos>& configSrcMap = nameIter->second;
2629
2630        // Look for strings with no default localization
2631        if (configSrcMap.count(defaultLocale) == 0) {
2632            SourcePos().warning("string '%s' has no default translation.",
2633                    String8(nameIter->first).string());
2634            if (mBundle->getVerbose()) {
2635                for (map<String8, SourcePos>::const_iterator locales = configSrcMap.begin();
2636                    locales != configSrcMap.end();
2637                    locales++) {
2638                    locales->second.printf("locale %s found", locales->first.string());
2639                }
2640            }
2641            // !!! TODO: throw an error here in some circumstances
2642        }
2643
2644        // Check that all requested localizations are present for this string
2645        if (mBundle->getConfigurations() != NULL && mBundle->getRequireLocalization()) {
2646            const char* allConfigs = mBundle->getConfigurations();
2647            const char* start = allConfigs;
2648            const char* comma;
2649
2650            set<String8> missingConfigs;
2651            AaptLocaleValue locale;
2652            do {
2653                String8 config;
2654                comma = strchr(start, ',');
2655                if (comma != NULL) {
2656                    config.setTo(start, comma - start);
2657                    start = comma + 1;
2658                } else {
2659                    config.setTo(start);
2660                }
2661
2662                if (!locale.initFromFilterString(config)) {
2663                    continue;
2664                }
2665
2666                // don't bother with the pseudolocale "en_XA" or "ar_XB"
2667                if (config != "en_XA" && config != "ar_XB") {
2668                    if (configSrcMap.find(config) == configSrcMap.end()) {
2669                        // okay, no specific localization found.  it's possible that we are
2670                        // requiring a specific regional localization [e.g. de_DE] but there is an
2671                        // available string in the generic language localization [e.g. de];
2672                        // consider that string to have fulfilled the localization requirement.
2673                        String8 region(config.string(), 2);
2674                        if (configSrcMap.find(region) == configSrcMap.end() &&
2675                                configSrcMap.count(defaultLocale) == 0) {
2676                            missingConfigs.insert(config);
2677                        }
2678                    }
2679                }
2680            } while (comma != NULL);
2681
2682            if (!missingConfigs.empty()) {
2683                String8 configStr;
2684                for (set<String8>::iterator iter = missingConfigs.begin();
2685                     iter != missingConfigs.end();
2686                     iter++) {
2687                    configStr.appendFormat(" %s", iter->string());
2688                }
2689                SourcePos().warning("string '%s' is missing %u required localizations:%s",
2690                        String8(nameIter->first).string(),
2691                        (unsigned int)missingConfigs.size(),
2692                        configStr.string());
2693            }
2694        }
2695    }
2696
2697    return err;
2698}
2699
2700status_t ResourceTable::flatten(Bundle* bundle, const sp<AaptFile>& dest)
2701{
2702    ResourceFilter filter;
2703    status_t err = filter.parse(bundle->getConfigurations());
2704    if (err != NO_ERROR) {
2705        return err;
2706    }
2707
2708    const ConfigDescription nullConfig;
2709
2710    const size_t N = mOrderedPackages.size();
2711    size_t pi;
2712
2713    const static String16 mipmap16("mipmap");
2714
2715    bool useUTF8 = !bundle->getUTF16StringsOption();
2716
2717    // Iterate through all data, collecting all values (strings,
2718    // references, etc).
2719    StringPool valueStrings(useUTF8);
2720    Vector<sp<Entry> > allEntries;
2721    for (pi=0; pi<N; pi++) {
2722        sp<Package> p = mOrderedPackages.itemAt(pi);
2723        if (p->getTypes().size() == 0) {
2724            // Empty, skip!
2725            continue;
2726        }
2727
2728        StringPool typeStrings(useUTF8);
2729        StringPool keyStrings(useUTF8);
2730
2731        const size_t N = p->getOrderedTypes().size();
2732        for (size_t ti=0; ti<N; ti++) {
2733            sp<Type> t = p->getOrderedTypes().itemAt(ti);
2734            if (t == NULL) {
2735                typeStrings.add(String16("<empty>"), false);
2736                continue;
2737            }
2738            const String16 typeName(t->getName());
2739            typeStrings.add(typeName, false);
2740
2741            // This is a hack to tweak the sorting order of the final strings,
2742            // to put stuff that is generally not language-specific first.
2743            String8 configTypeName(typeName);
2744            if (configTypeName == "drawable" || configTypeName == "layout"
2745                    || configTypeName == "color" || configTypeName == "anim"
2746                    || configTypeName == "interpolator" || configTypeName == "animator"
2747                    || configTypeName == "xml" || configTypeName == "menu"
2748                    || configTypeName == "mipmap" || configTypeName == "raw") {
2749                configTypeName = "1complex";
2750            } else {
2751                configTypeName = "2value";
2752            }
2753
2754            const bool filterable = (typeName != mipmap16);
2755
2756            const size_t N = t->getOrderedConfigs().size();
2757            for (size_t ci=0; ci<N; ci++) {
2758                sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2759                if (c == NULL) {
2760                    continue;
2761                }
2762                const size_t N = c->getEntries().size();
2763                for (size_t ei=0; ei<N; ei++) {
2764                    ConfigDescription config = c->getEntries().keyAt(ei);
2765                    if (filterable && !filter.match(config)) {
2766                        continue;
2767                    }
2768                    sp<Entry> e = c->getEntries().valueAt(ei);
2769                    if (e == NULL) {
2770                        continue;
2771                    }
2772                    e->setNameIndex(keyStrings.add(e->getName(), true));
2773
2774                    // If this entry has no values for other configs,
2775                    // and is the default config, then it is special.  Otherwise
2776                    // we want to add it with the config info.
2777                    ConfigDescription* valueConfig = NULL;
2778                    if (N != 1 || config == nullConfig) {
2779                        valueConfig = &config;
2780                    }
2781
2782                    status_t err = e->prepareFlatten(&valueStrings, this,
2783                            &configTypeName, &config);
2784                    if (err != NO_ERROR) {
2785                        return err;
2786                    }
2787                    allEntries.add(e);
2788                }
2789            }
2790        }
2791
2792        p->setTypeStrings(typeStrings.createStringBlock());
2793        p->setKeyStrings(keyStrings.createStringBlock());
2794    }
2795
2796    if (bundle->getOutputAPKFile() != NULL) {
2797        // Now we want to sort the value strings for better locality.  This will
2798        // cause the positions of the strings to change, so we need to go back
2799        // through out resource entries and update them accordingly.  Only need
2800        // to do this if actually writing the output file.
2801        valueStrings.sortByConfig();
2802        for (pi=0; pi<allEntries.size(); pi++) {
2803            allEntries[pi]->remapStringValue(&valueStrings);
2804        }
2805    }
2806
2807    ssize_t strAmt = 0;
2808
2809    // Now build the array of package chunks.
2810    Vector<sp<AaptFile> > flatPackages;
2811    for (pi=0; pi<N; pi++) {
2812        sp<Package> p = mOrderedPackages.itemAt(pi);
2813        if (p->getTypes().size() == 0) {
2814            // Empty, skip!
2815            continue;
2816        }
2817
2818        const size_t N = p->getTypeStrings().size();
2819
2820        const size_t baseSize = sizeof(ResTable_package);
2821
2822        // Start the package data.
2823        sp<AaptFile> data = new AaptFile(String8(), AaptGroupEntry(), String8());
2824        ResTable_package* header = (ResTable_package*)data->editData(baseSize);
2825        if (header == NULL) {
2826            fprintf(stderr, "ERROR: out of memory creating ResTable_package\n");
2827            return NO_MEMORY;
2828        }
2829        memset(header, 0, sizeof(*header));
2830        header->header.type = htods(RES_TABLE_PACKAGE_TYPE);
2831        header->header.headerSize = htods(sizeof(*header));
2832        header->id = htodl(p->getAssignedId());
2833        strcpy16_htod(header->name, p->getName().string());
2834
2835        // Write the string blocks.
2836        const size_t typeStringsStart = data->getSize();
2837        sp<AaptFile> strFile = p->getTypeStringsData();
2838        ssize_t amt = data->writeData(strFile->getData(), strFile->getSize());
2839        #if PRINT_STRING_METRICS
2840        fprintf(stderr, "**** type strings: %d\n", amt);
2841        #endif
2842        strAmt += amt;
2843        if (amt < 0) {
2844            return amt;
2845        }
2846        const size_t keyStringsStart = data->getSize();
2847        strFile = p->getKeyStringsData();
2848        amt = data->writeData(strFile->getData(), strFile->getSize());
2849        #if PRINT_STRING_METRICS
2850        fprintf(stderr, "**** key strings: %d\n", amt);
2851        #endif
2852        strAmt += amt;
2853        if (amt < 0) {
2854            return amt;
2855        }
2856
2857        // Build the type chunks inside of this package.
2858        for (size_t ti=0; ti<N; ti++) {
2859            // Retrieve them in the same order as the type string block.
2860            size_t len;
2861            String16 typeName(p->getTypeStrings().stringAt(ti, &len));
2862            sp<Type> t = p->getTypes().valueFor(typeName);
2863            LOG_ALWAYS_FATAL_IF(t == NULL && typeName != String16("<empty>"),
2864                                "Type name %s not found",
2865                                String8(typeName).string());
2866
2867            const bool filterable = (typeName != mipmap16);
2868
2869            const size_t N = t != NULL ? t->getOrderedConfigs().size() : 0;
2870
2871            // Until a non-NO_ENTRY value has been written for a resource,
2872            // that resource is invalid; validResources[i] represents
2873            // the item at t->getOrderedConfigs().itemAt(i).
2874            Vector<bool> validResources;
2875            validResources.insertAt(false, 0, N);
2876
2877            // First write the typeSpec chunk, containing information about
2878            // each resource entry in this type.
2879            {
2880                const size_t typeSpecSize = sizeof(ResTable_typeSpec) + sizeof(uint32_t)*N;
2881                const size_t typeSpecStart = data->getSize();
2882                ResTable_typeSpec* tsHeader = (ResTable_typeSpec*)
2883                    (((uint8_t*)data->editData(typeSpecStart+typeSpecSize)) + typeSpecStart);
2884                if (tsHeader == NULL) {
2885                    fprintf(stderr, "ERROR: out of memory creating ResTable_typeSpec\n");
2886                    return NO_MEMORY;
2887                }
2888                memset(tsHeader, 0, sizeof(*tsHeader));
2889                tsHeader->header.type = htods(RES_TABLE_TYPE_SPEC_TYPE);
2890                tsHeader->header.headerSize = htods(sizeof(*tsHeader));
2891                tsHeader->header.size = htodl(typeSpecSize);
2892                tsHeader->id = ti+1;
2893                tsHeader->entryCount = htodl(N);
2894
2895                uint32_t* typeSpecFlags = (uint32_t*)
2896                    (((uint8_t*)data->editData())
2897                        + typeSpecStart + sizeof(ResTable_typeSpec));
2898                memset(typeSpecFlags, 0, sizeof(uint32_t)*N);
2899
2900                for (size_t ei=0; ei<N; ei++) {
2901                    sp<ConfigList> cl = t->getOrderedConfigs().itemAt(ei);
2902                    if (cl->getPublic()) {
2903                        typeSpecFlags[ei] |= htodl(ResTable_typeSpec::SPEC_PUBLIC);
2904                    }
2905                    const size_t CN = cl->getEntries().size();
2906                    for (size_t ci=0; ci<CN; ci++) {
2907                        if (filterable && !filter.match(cl->getEntries().keyAt(ci))) {
2908                            continue;
2909                        }
2910                        for (size_t cj=ci+1; cj<CN; cj++) {
2911                            if (filterable && !filter.match(cl->getEntries().keyAt(cj))) {
2912                                continue;
2913                            }
2914                            typeSpecFlags[ei] |= htodl(
2915                                cl->getEntries().keyAt(ci).diff(cl->getEntries().keyAt(cj)));
2916                        }
2917                    }
2918                }
2919            }
2920
2921            // We need to write one type chunk for each configuration for
2922            // which we have entries in this type.
2923            const size_t NC = t->getUniqueConfigs().size();
2924
2925            const size_t typeSize = sizeof(ResTable_type) + sizeof(uint32_t)*N;
2926
2927            for (size_t ci=0; ci<NC; ci++) {
2928                ConfigDescription config = t->getUniqueConfigs().itemAt(ci);
2929
2930                NOISY(printf("Writing config %d config: imsi:%d/%d lang:%c%c cnt:%c%c "
2931                     "orien:%d ui:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d "
2932                     "sw%ddp w%ddp h%ddp dir:%d\n",
2933                      ti+1,
2934                      config.mcc, config.mnc,
2935                      config.language[0] ? config.language[0] : '-',
2936                      config.language[1] ? config.language[1] : '-',
2937                      config.country[0] ? config.country[0] : '-',
2938                      config.country[1] ? config.country[1] : '-',
2939                      config.orientation,
2940                      config.uiMode,
2941                      config.touchscreen,
2942                      config.density,
2943                      config.keyboard,
2944                      config.inputFlags,
2945                      config.navigation,
2946                      config.screenWidth,
2947                      config.screenHeight,
2948                      config.smallestScreenWidthDp,
2949                      config.screenWidthDp,
2950                      config.screenHeightDp,
2951                      config.layoutDirection));
2952
2953                if (filterable && !filter.match(config)) {
2954                    continue;
2955                }
2956
2957                const size_t typeStart = data->getSize();
2958
2959                ResTable_type* tHeader = (ResTable_type*)
2960                    (((uint8_t*)data->editData(typeStart+typeSize)) + typeStart);
2961                if (tHeader == NULL) {
2962                    fprintf(stderr, "ERROR: out of memory creating ResTable_type\n");
2963                    return NO_MEMORY;
2964                }
2965
2966                memset(tHeader, 0, sizeof(*tHeader));
2967                tHeader->header.type = htods(RES_TABLE_TYPE_TYPE);
2968                tHeader->header.headerSize = htods(sizeof(*tHeader));
2969                tHeader->id = ti+1;
2970                tHeader->entryCount = htodl(N);
2971                tHeader->entriesStart = htodl(typeSize);
2972                tHeader->config = config;
2973                NOISY(printf("Writing type %d config: imsi:%d/%d lang:%c%c cnt:%c%c "
2974                     "orien:%d ui:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d "
2975                     "sw%ddp w%ddp h%ddp dir:%d\n",
2976                      ti+1,
2977                      tHeader->config.mcc, tHeader->config.mnc,
2978                      tHeader->config.language[0] ? tHeader->config.language[0] : '-',
2979                      tHeader->config.language[1] ? tHeader->config.language[1] : '-',
2980                      tHeader->config.country[0] ? tHeader->config.country[0] : '-',
2981                      tHeader->config.country[1] ? tHeader->config.country[1] : '-',
2982                      tHeader->config.orientation,
2983                      tHeader->config.uiMode,
2984                      tHeader->config.touchscreen,
2985                      tHeader->config.density,
2986                      tHeader->config.keyboard,
2987                      tHeader->config.inputFlags,
2988                      tHeader->config.navigation,
2989                      tHeader->config.screenWidth,
2990                      tHeader->config.screenHeight,
2991                      tHeader->config.smallestScreenWidthDp,
2992                      tHeader->config.screenWidthDp,
2993                      tHeader->config.screenHeightDp,
2994                      tHeader->config.layoutDirection));
2995                tHeader->config.swapHtoD();
2996
2997                // Build the entries inside of this type.
2998                for (size_t ei=0; ei<N; ei++) {
2999                    sp<ConfigList> cl = t->getOrderedConfigs().itemAt(ei);
3000                    sp<Entry> e = cl->getEntries().valueFor(config);
3001
3002                    // Set the offset for this entry in its type.
3003                    uint32_t* index = (uint32_t*)
3004                        (((uint8_t*)data->editData())
3005                            + typeStart + sizeof(ResTable_type));
3006                    if (e != NULL) {
3007                        index[ei] = htodl(data->getSize()-typeStart-typeSize);
3008
3009                        // Create the entry.
3010                        ssize_t amt = e->flatten(bundle, data, cl->getPublic());
3011                        if (amt < 0) {
3012                            return amt;
3013                        }
3014                        validResources.editItemAt(ei) = true;
3015                    } else {
3016                        index[ei] = htodl(ResTable_type::NO_ENTRY);
3017                    }
3018                }
3019
3020                // Fill in the rest of the type information.
3021                tHeader = (ResTable_type*)
3022                    (((uint8_t*)data->editData()) + typeStart);
3023                tHeader->header.size = htodl(data->getSize()-typeStart);
3024            }
3025
3026            for (size_t i = 0; i < N; ++i) {
3027                if (!validResources[i]) {
3028                    sp<ConfigList> c = t->getOrderedConfigs().itemAt(i);
3029                    fprintf(stderr, "warning: no entries written for %s/%s\n",
3030                            String8(typeName).string(), String8(c->getName()).string());
3031                }
3032            }
3033        }
3034
3035        // Fill in the rest of the package information.
3036        header = (ResTable_package*)data->editData();
3037        header->header.size = htodl(data->getSize());
3038        header->typeStrings = htodl(typeStringsStart);
3039        header->lastPublicType = htodl(p->getTypeStrings().size());
3040        header->keyStrings = htodl(keyStringsStart);
3041        header->lastPublicKey = htodl(p->getKeyStrings().size());
3042
3043        flatPackages.add(data);
3044    }
3045
3046    // And now write out the final chunks.
3047    const size_t dataStart = dest->getSize();
3048
3049    {
3050        // blah
3051        ResTable_header header;
3052        memset(&header, 0, sizeof(header));
3053        header.header.type = htods(RES_TABLE_TYPE);
3054        header.header.headerSize = htods(sizeof(header));
3055        header.packageCount = htodl(flatPackages.size());
3056        status_t err = dest->writeData(&header, sizeof(header));
3057        if (err != NO_ERROR) {
3058            fprintf(stderr, "ERROR: out of memory creating ResTable_header\n");
3059            return err;
3060        }
3061    }
3062
3063    ssize_t strStart = dest->getSize();
3064    err = valueStrings.writeStringBlock(dest);
3065    if (err != NO_ERROR) {
3066        return err;
3067    }
3068
3069    ssize_t amt = (dest->getSize()-strStart);
3070    strAmt += amt;
3071    #if PRINT_STRING_METRICS
3072    fprintf(stderr, "**** value strings: %d\n", amt);
3073    fprintf(stderr, "**** total strings: %d\n", strAmt);
3074    #endif
3075
3076    for (pi=0; pi<flatPackages.size(); pi++) {
3077        err = dest->writeData(flatPackages[pi]->getData(),
3078                              flatPackages[pi]->getSize());
3079        if (err != NO_ERROR) {
3080            fprintf(stderr, "ERROR: out of memory creating package chunk for ResTable_header\n");
3081            return err;
3082        }
3083    }
3084
3085    ResTable_header* header = (ResTable_header*)
3086        (((uint8_t*)dest->getData()) + dataStart);
3087    header->header.size = htodl(dest->getSize() - dataStart);
3088
3089    NOISY(aout << "Resource table:"
3090          << HexDump(dest->getData(), dest->getSize()) << endl);
3091
3092    #if PRINT_STRING_METRICS
3093    fprintf(stderr, "**** total resource table size: %d / %d%% strings\n",
3094        dest->getSize(), (strAmt*100)/dest->getSize());
3095    #endif
3096
3097    return NO_ERROR;
3098}
3099
3100void ResourceTable::writePublicDefinitions(const String16& package, FILE* fp)
3101{
3102    fprintf(fp,
3103    "<!-- This file contains <public> resource definitions for all\n"
3104    "     resources that were generated from the source data. -->\n"
3105    "\n"
3106    "<resources>\n");
3107
3108    writePublicDefinitions(package, fp, true);
3109    writePublicDefinitions(package, fp, false);
3110
3111    fprintf(fp,
3112    "\n"
3113    "</resources>\n");
3114}
3115
3116void ResourceTable::writePublicDefinitions(const String16& package, FILE* fp, bool pub)
3117{
3118    bool didHeader = false;
3119
3120    sp<Package> pkg = mPackages.valueFor(package);
3121    if (pkg != NULL) {
3122        const size_t NT = pkg->getOrderedTypes().size();
3123        for (size_t i=0; i<NT; i++) {
3124            sp<Type> t = pkg->getOrderedTypes().itemAt(i);
3125            if (t == NULL) {
3126                continue;
3127            }
3128
3129            bool didType = false;
3130
3131            const size_t NC = t->getOrderedConfigs().size();
3132            for (size_t j=0; j<NC; j++) {
3133                sp<ConfigList> c = t->getOrderedConfigs().itemAt(j);
3134                if (c == NULL) {
3135                    continue;
3136                }
3137
3138                if (c->getPublic() != pub) {
3139                    continue;
3140                }
3141
3142                if (!didType) {
3143                    fprintf(fp, "\n");
3144                    didType = true;
3145                }
3146                if (!didHeader) {
3147                    if (pub) {
3148                        fprintf(fp,"  <!-- PUBLIC SECTION.  These resources have been declared public.\n");
3149                        fprintf(fp,"       Changes to these definitions will break binary compatibility. -->\n\n");
3150                    } else {
3151                        fprintf(fp,"  <!-- PRIVATE SECTION.  These resources have not been declared public.\n");
3152                        fprintf(fp,"       You can make them public my moving these lines into a file in res/values. -->\n\n");
3153                    }
3154                    didHeader = true;
3155                }
3156                if (!pub) {
3157                    const size_t NE = c->getEntries().size();
3158                    for (size_t k=0; k<NE; k++) {
3159                        const SourcePos& pos = c->getEntries().valueAt(k)->getPos();
3160                        if (pos.file != "") {
3161                            fprintf(fp,"  <!-- Declared at %s:%d -->\n",
3162                                    pos.file.string(), pos.line);
3163                        }
3164                    }
3165                }
3166                fprintf(fp, "  <public type=\"%s\" name=\"%s\" id=\"0x%08x\" />\n",
3167                        String8(t->getName()).string(),
3168                        String8(c->getName()).string(),
3169                        getResId(pkg, t, c->getEntryIndex()));
3170            }
3171        }
3172    }
3173}
3174
3175ResourceTable::Item::Item(const SourcePos& _sourcePos,
3176                          bool _isId,
3177                          const String16& _value,
3178                          const Vector<StringPool::entry_style_span>* _style,
3179                          int32_t _format)
3180    : sourcePos(_sourcePos)
3181    , isId(_isId)
3182    , value(_value)
3183    , format(_format)
3184    , bagKeyId(0)
3185    , evaluating(false)
3186{
3187    if (_style) {
3188        style = *_style;
3189    }
3190}
3191
3192status_t ResourceTable::Entry::makeItABag(const SourcePos& sourcePos)
3193{
3194    if (mType == TYPE_BAG) {
3195        return NO_ERROR;
3196    }
3197    if (mType == TYPE_UNKNOWN) {
3198        mType = TYPE_BAG;
3199        return NO_ERROR;
3200    }
3201    sourcePos.error("Resource entry %s is already defined as a single item.\n"
3202                    "%s:%d: Originally defined here.\n",
3203                    String8(mName).string(),
3204                    mItem.sourcePos.file.string(), mItem.sourcePos.line);
3205    return UNKNOWN_ERROR;
3206}
3207
3208status_t ResourceTable::Entry::setItem(const SourcePos& sourcePos,
3209                                       const String16& value,
3210                                       const Vector<StringPool::entry_style_span>* style,
3211                                       int32_t format,
3212                                       const bool overwrite)
3213{
3214    Item item(sourcePos, false, value, style);
3215
3216    if (mType == TYPE_BAG) {
3217        const Item& item(mBag.valueAt(0));
3218        sourcePos.error("Resource entry %s is already defined as a bag.\n"
3219                        "%s:%d: Originally defined here.\n",
3220                        String8(mName).string(),
3221                        item.sourcePos.file.string(), item.sourcePos.line);
3222        return UNKNOWN_ERROR;
3223    }
3224    if ( (mType != TYPE_UNKNOWN) && (overwrite == false) ) {
3225        sourcePos.error("Resource entry %s is already defined.\n"
3226                        "%s:%d: Originally defined here.\n",
3227                        String8(mName).string(),
3228                        mItem.sourcePos.file.string(), mItem.sourcePos.line);
3229        return UNKNOWN_ERROR;
3230    }
3231
3232    mType = TYPE_ITEM;
3233    mItem = item;
3234    mItemFormat = format;
3235    return NO_ERROR;
3236}
3237
3238status_t ResourceTable::Entry::addToBag(const SourcePos& sourcePos,
3239                                        const String16& key, const String16& value,
3240                                        const Vector<StringPool::entry_style_span>* style,
3241                                        bool replace, bool isId, int32_t format)
3242{
3243    status_t err = makeItABag(sourcePos);
3244    if (err != NO_ERROR) {
3245        return err;
3246    }
3247
3248    Item item(sourcePos, isId, value, style, format);
3249
3250    // XXX NOTE: there is an error if you try to have a bag with two keys,
3251    // one an attr and one an id, with the same name.  Not something we
3252    // currently ever have to worry about.
3253    ssize_t origKey = mBag.indexOfKey(key);
3254    if (origKey >= 0) {
3255        if (!replace) {
3256            const Item& item(mBag.valueAt(origKey));
3257            sourcePos.error("Resource entry %s already has bag item %s.\n"
3258                    "%s:%d: Originally defined here.\n",
3259                    String8(mName).string(), String8(key).string(),
3260                    item.sourcePos.file.string(), item.sourcePos.line);
3261            return UNKNOWN_ERROR;
3262        }
3263        //printf("Replacing %s with %s\n",
3264        //       String8(mBag.valueFor(key).value).string(), String8(value).string());
3265        mBag.replaceValueFor(key, item);
3266    }
3267
3268    mBag.add(key, item);
3269    return NO_ERROR;
3270}
3271
3272status_t ResourceTable::Entry::emptyBag(const SourcePos& sourcePos)
3273{
3274    status_t err = makeItABag(sourcePos);
3275    if (err != NO_ERROR) {
3276        return err;
3277    }
3278
3279    mBag.clear();
3280    return NO_ERROR;
3281}
3282
3283status_t ResourceTable::Entry::generateAttributes(ResourceTable* table,
3284                                                  const String16& package)
3285{
3286    const String16 attr16("attr");
3287    const String16 id16("id");
3288    const size_t N = mBag.size();
3289    for (size_t i=0; i<N; i++) {
3290        const String16& key = mBag.keyAt(i);
3291        const Item& it = mBag.valueAt(i);
3292        if (it.isId) {
3293            if (!table->hasBagOrEntry(key, &id16, &package)) {
3294                String16 value("false");
3295                status_t err = table->addEntry(SourcePos(String8("<generated>"), 0), package,
3296                                               id16, key, value);
3297                if (err != NO_ERROR) {
3298                    return err;
3299                }
3300            }
3301        } else if (!table->hasBagOrEntry(key, &attr16, &package)) {
3302
3303#if 1
3304//             fprintf(stderr, "ERROR: Bag attribute '%s' has not been defined.\n",
3305//                     String8(key).string());
3306//             const Item& item(mBag.valueAt(i));
3307//             fprintf(stderr, "Referenced from file %s line %d\n",
3308//                     item.sourcePos.file.string(), item.sourcePos.line);
3309//             return UNKNOWN_ERROR;
3310#else
3311            char numberStr[16];
3312            sprintf(numberStr, "%d", ResTable_map::TYPE_ANY);
3313            status_t err = table->addBag(SourcePos("<generated>", 0), package,
3314                                         attr16, key, String16(""),
3315                                         String16("^type"),
3316                                         String16(numberStr), NULL, NULL);
3317            if (err != NO_ERROR) {
3318                return err;
3319            }
3320#endif
3321        }
3322    }
3323    return NO_ERROR;
3324}
3325
3326status_t ResourceTable::Entry::assignResourceIds(ResourceTable* table,
3327                                                 const String16& package)
3328{
3329    bool hasErrors = false;
3330
3331    if (mType == TYPE_BAG) {
3332        const char* errorMsg;
3333        const String16 style16("style");
3334        const String16 attr16("attr");
3335        const String16 id16("id");
3336        mParentId = 0;
3337        if (mParent.size() > 0) {
3338            mParentId = table->getResId(mParent, &style16, NULL, &errorMsg);
3339            if (mParentId == 0) {
3340                mPos.error("Error retrieving parent for item: %s '%s'.\n",
3341                        errorMsg, String8(mParent).string());
3342                hasErrors = true;
3343            }
3344        }
3345        const size_t N = mBag.size();
3346        for (size_t i=0; i<N; i++) {
3347            const String16& key = mBag.keyAt(i);
3348            Item& it = mBag.editValueAt(i);
3349            it.bagKeyId = table->getResId(key,
3350                    it.isId ? &id16 : &attr16, NULL, &errorMsg);
3351            //printf("Bag key of %s: #%08x\n", String8(key).string(), it.bagKeyId);
3352            if (it.bagKeyId == 0) {
3353                it.sourcePos.error("Error: %s: %s '%s'.\n", errorMsg,
3354                        String8(it.isId ? id16 : attr16).string(),
3355                        String8(key).string());
3356                hasErrors = true;
3357            }
3358        }
3359    }
3360    return hasErrors ? UNKNOWN_ERROR : NO_ERROR;
3361}
3362
3363status_t ResourceTable::Entry::prepareFlatten(StringPool* strings, ResourceTable* table,
3364        const String8* configTypeName, const ConfigDescription* config)
3365{
3366    if (mType == TYPE_ITEM) {
3367        Item& it = mItem;
3368        AccessorCookie ac(it.sourcePos, String8(mName), String8(it.value));
3369        if (!table->stringToValue(&it.parsedValue, strings,
3370                                  it.value, false, true, 0,
3371                                  &it.style, NULL, &ac, mItemFormat,
3372                                  configTypeName, config)) {
3373            return UNKNOWN_ERROR;
3374        }
3375    } else if (mType == TYPE_BAG) {
3376        const size_t N = mBag.size();
3377        for (size_t i=0; i<N; i++) {
3378            const String16& key = mBag.keyAt(i);
3379            Item& it = mBag.editValueAt(i);
3380            AccessorCookie ac(it.sourcePos, String8(key), String8(it.value));
3381            if (!table->stringToValue(&it.parsedValue, strings,
3382                                      it.value, false, true, it.bagKeyId,
3383                                      &it.style, NULL, &ac, it.format,
3384                                      configTypeName, config)) {
3385                return UNKNOWN_ERROR;
3386            }
3387        }
3388    } else {
3389        mPos.error("Error: entry %s is not a single item or a bag.\n",
3390                   String8(mName).string());
3391        return UNKNOWN_ERROR;
3392    }
3393    return NO_ERROR;
3394}
3395
3396status_t ResourceTable::Entry::remapStringValue(StringPool* strings)
3397{
3398    if (mType == TYPE_ITEM) {
3399        Item& it = mItem;
3400        if (it.parsedValue.dataType == Res_value::TYPE_STRING) {
3401            it.parsedValue.data = strings->mapOriginalPosToNewPos(it.parsedValue.data);
3402        }
3403    } else if (mType == TYPE_BAG) {
3404        const size_t N = mBag.size();
3405        for (size_t i=0; i<N; i++) {
3406            Item& it = mBag.editValueAt(i);
3407            if (it.parsedValue.dataType == Res_value::TYPE_STRING) {
3408                it.parsedValue.data = strings->mapOriginalPosToNewPos(it.parsedValue.data);
3409            }
3410        }
3411    } else {
3412        mPos.error("Error: entry %s is not a single item or a bag.\n",
3413                   String8(mName).string());
3414        return UNKNOWN_ERROR;
3415    }
3416    return NO_ERROR;
3417}
3418
3419ssize_t ResourceTable::Entry::flatten(Bundle* bundle, const sp<AaptFile>& data, bool isPublic)
3420{
3421    size_t amt = 0;
3422    ResTable_entry header;
3423    memset(&header, 0, sizeof(header));
3424    header.size = htods(sizeof(header));
3425    const type ty = this != NULL ? mType : TYPE_ITEM;
3426    if (this != NULL) {
3427        if (ty == TYPE_BAG) {
3428            header.flags |= htods(header.FLAG_COMPLEX);
3429        }
3430        if (isPublic) {
3431            header.flags |= htods(header.FLAG_PUBLIC);
3432        }
3433        header.key.index = htodl(mNameIndex);
3434    }
3435    if (ty != TYPE_BAG) {
3436        status_t err = data->writeData(&header, sizeof(header));
3437        if (err != NO_ERROR) {
3438            fprintf(stderr, "ERROR: out of memory creating ResTable_entry\n");
3439            return err;
3440        }
3441
3442        const Item& it = mItem;
3443        Res_value par;
3444        memset(&par, 0, sizeof(par));
3445        par.size = htods(it.parsedValue.size);
3446        par.dataType = it.parsedValue.dataType;
3447        par.res0 = it.parsedValue.res0;
3448        par.data = htodl(it.parsedValue.data);
3449        #if 0
3450        printf("Writing item (%s): type=%d, data=0x%x, res0=0x%x\n",
3451               String8(mName).string(), it.parsedValue.dataType,
3452               it.parsedValue.data, par.res0);
3453        #endif
3454        err = data->writeData(&par, it.parsedValue.size);
3455        if (err != NO_ERROR) {
3456            fprintf(stderr, "ERROR: out of memory creating Res_value\n");
3457            return err;
3458        }
3459        amt += it.parsedValue.size;
3460    } else {
3461        size_t N = mBag.size();
3462        size_t i;
3463        // Create correct ordering of items.
3464        KeyedVector<uint32_t, const Item*> items;
3465        for (i=0; i<N; i++) {
3466            const Item& it = mBag.valueAt(i);
3467            items.add(it.bagKeyId, &it);
3468        }
3469        N = items.size();
3470
3471        ResTable_map_entry mapHeader;
3472        memcpy(&mapHeader, &header, sizeof(header));
3473        mapHeader.size = htods(sizeof(mapHeader));
3474        mapHeader.parent.ident = htodl(mParentId);
3475        mapHeader.count = htodl(N);
3476        status_t err = data->writeData(&mapHeader, sizeof(mapHeader));
3477        if (err != NO_ERROR) {
3478            fprintf(stderr, "ERROR: out of memory creating ResTable_entry\n");
3479            return err;
3480        }
3481
3482        for (i=0; i<N; i++) {
3483            const Item& it = *items.valueAt(i);
3484            ResTable_map map;
3485            map.name.ident = htodl(it.bagKeyId);
3486            map.value.size = htods(it.parsedValue.size);
3487            map.value.dataType = it.parsedValue.dataType;
3488            map.value.res0 = it.parsedValue.res0;
3489            map.value.data = htodl(it.parsedValue.data);
3490            err = data->writeData(&map, sizeof(map));
3491            if (err != NO_ERROR) {
3492                fprintf(stderr, "ERROR: out of memory creating Res_value\n");
3493                return err;
3494            }
3495            amt += sizeof(map);
3496        }
3497    }
3498    return amt;
3499}
3500
3501void ResourceTable::ConfigList::appendComment(const String16& comment,
3502                                              bool onlyIfEmpty)
3503{
3504    if (comment.size() <= 0) {
3505        return;
3506    }
3507    if (onlyIfEmpty && mComment.size() > 0) {
3508        return;
3509    }
3510    if (mComment.size() > 0) {
3511        mComment.append(String16("\n"));
3512    }
3513    mComment.append(comment);
3514}
3515
3516void ResourceTable::ConfigList::appendTypeComment(const String16& comment)
3517{
3518    if (comment.size() <= 0) {
3519        return;
3520    }
3521    if (mTypeComment.size() > 0) {
3522        mTypeComment.append(String16("\n"));
3523    }
3524    mTypeComment.append(comment);
3525}
3526
3527status_t ResourceTable::Type::addPublic(const SourcePos& sourcePos,
3528                                        const String16& name,
3529                                        const uint32_t ident)
3530{
3531    #if 0
3532    int32_t entryIdx = Res_GETENTRY(ident);
3533    if (entryIdx < 0) {
3534        sourcePos.error("Public resource %s/%s has an invalid 0 identifier (0x%08x).\n",
3535                String8(mName).string(), String8(name).string(), ident);
3536        return UNKNOWN_ERROR;
3537    }
3538    #endif
3539
3540    int32_t typeIdx = Res_GETTYPE(ident);
3541    if (typeIdx >= 0) {
3542        typeIdx++;
3543        if (mPublicIndex > 0 && mPublicIndex != typeIdx) {
3544            sourcePos.error("Public resource %s/%s has conflicting type codes for its"
3545                    " public identifiers (0x%x vs 0x%x).\n",
3546                    String8(mName).string(), String8(name).string(),
3547                    mPublicIndex, typeIdx);
3548            return UNKNOWN_ERROR;
3549        }
3550        mPublicIndex = typeIdx;
3551    }
3552
3553    if (mFirstPublicSourcePos == NULL) {
3554        mFirstPublicSourcePos = new SourcePos(sourcePos);
3555    }
3556
3557    if (mPublic.indexOfKey(name) < 0) {
3558        mPublic.add(name, Public(sourcePos, String16(), ident));
3559    } else {
3560        Public& p = mPublic.editValueFor(name);
3561        if (p.ident != ident) {
3562            sourcePos.error("Public resource %s/%s has conflicting public identifiers"
3563                    " (0x%08x vs 0x%08x).\n"
3564                    "%s:%d: Originally defined here.\n",
3565                    String8(mName).string(), String8(name).string(), p.ident, ident,
3566                    p.sourcePos.file.string(), p.sourcePos.line);
3567            return UNKNOWN_ERROR;
3568        }
3569    }
3570
3571    return NO_ERROR;
3572}
3573
3574void ResourceTable::Type::canAddEntry(const String16& name)
3575{
3576    mCanAddEntries.add(name);
3577}
3578
3579sp<ResourceTable::Entry> ResourceTable::Type::getEntry(const String16& entry,
3580                                                       const SourcePos& sourcePos,
3581                                                       const ResTable_config* config,
3582                                                       bool doSetIndex,
3583                                                       bool overlay,
3584                                                       bool autoAddOverlay)
3585{
3586    int pos = -1;
3587    sp<ConfigList> c = mConfigs.valueFor(entry);
3588    if (c == NULL) {
3589        if (overlay && !autoAddOverlay && mCanAddEntries.indexOf(entry) < 0) {
3590            sourcePos.error("Resource at %s appears in overlay but not"
3591                            " in the base package; use <add-resource> to add.\n",
3592                            String8(entry).string());
3593            return NULL;
3594        }
3595        c = new ConfigList(entry, sourcePos);
3596        mConfigs.add(entry, c);
3597        pos = (int)mOrderedConfigs.size();
3598        mOrderedConfigs.add(c);
3599        if (doSetIndex) {
3600            c->setEntryIndex(pos);
3601        }
3602    }
3603
3604    ConfigDescription cdesc;
3605    if (config) cdesc = *config;
3606
3607    sp<Entry> e = c->getEntries().valueFor(cdesc);
3608    if (e == NULL) {
3609        if (config != NULL) {
3610            NOISY(printf("New entry at %s:%d: imsi:%d/%d lang:%c%c cnt:%c%c "
3611                    "orien:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d "
3612                    "sw%ddp w%ddp h%ddp dir:%d\n",
3613                      sourcePos.file.string(), sourcePos.line,
3614                      config->mcc, config->mnc,
3615                      config->language[0] ? config->language[0] : '-',
3616                      config->language[1] ? config->language[1] : '-',
3617                      config->country[0] ? config->country[0] : '-',
3618                      config->country[1] ? config->country[1] : '-',
3619                      config->orientation,
3620                      config->touchscreen,
3621                      config->density,
3622                      config->keyboard,
3623                      config->inputFlags,
3624                      config->navigation,
3625                      config->screenWidth,
3626                      config->screenHeight,
3627                      config->smallestScreenWidthDp,
3628                      config->screenWidthDp,
3629                      config->screenHeightDp,
3630                      config->layoutDirection));
3631        } else {
3632            NOISY(printf("New entry at %s:%d: NULL config\n",
3633                      sourcePos.file.string(), sourcePos.line));
3634        }
3635        e = new Entry(entry, sourcePos);
3636        c->addEntry(cdesc, e);
3637        /*
3638        if (doSetIndex) {
3639            if (pos < 0) {
3640                for (pos=0; pos<(int)mOrderedConfigs.size(); pos++) {
3641                    if (mOrderedConfigs[pos] == c) {
3642                        break;
3643                    }
3644                }
3645                if (pos >= (int)mOrderedConfigs.size()) {
3646                    sourcePos.error("Internal error: config not found in mOrderedConfigs when adding entry");
3647                    return NULL;
3648                }
3649            }
3650            e->setEntryIndex(pos);
3651        }
3652        */
3653    }
3654
3655    mUniqueConfigs.add(cdesc);
3656
3657    return e;
3658}
3659
3660status_t ResourceTable::Type::applyPublicEntryOrder()
3661{
3662    size_t N = mOrderedConfigs.size();
3663    Vector<sp<ConfigList> > origOrder(mOrderedConfigs);
3664    bool hasError = false;
3665
3666    size_t i;
3667    for (i=0; i<N; i++) {
3668        mOrderedConfigs.replaceAt(NULL, i);
3669    }
3670
3671    const size_t NP = mPublic.size();
3672    //printf("Ordering %d configs from %d public defs\n", N, NP);
3673    size_t j;
3674    for (j=0; j<NP; j++) {
3675        const String16& name = mPublic.keyAt(j);
3676        const Public& p = mPublic.valueAt(j);
3677        int32_t idx = Res_GETENTRY(p.ident);
3678        //printf("Looking for entry \"%s\"/\"%s\" (0x%08x) in %d...\n",
3679        //       String8(mName).string(), String8(name).string(), p.ident, N);
3680        bool found = false;
3681        for (i=0; i<N; i++) {
3682            sp<ConfigList> e = origOrder.itemAt(i);
3683            //printf("#%d: \"%s\"\n", i, String8(e->getName()).string());
3684            if (e->getName() == name) {
3685                if (idx >= (int32_t)mOrderedConfigs.size()) {
3686                    p.sourcePos.error("Public entry identifier 0x%x entry index "
3687                            "is larger than available symbols (index %d, total symbols %d).\n",
3688                            p.ident, idx, mOrderedConfigs.size());
3689                    hasError = true;
3690                } else if (mOrderedConfigs.itemAt(idx) == NULL) {
3691                    e->setPublic(true);
3692                    e->setPublicSourcePos(p.sourcePos);
3693                    mOrderedConfigs.replaceAt(e, idx);
3694                    origOrder.removeAt(i);
3695                    N--;
3696                    found = true;
3697                    break;
3698                } else {
3699                    sp<ConfigList> oe = mOrderedConfigs.itemAt(idx);
3700
3701                    p.sourcePos.error("Multiple entry names declared for public entry"
3702                            " identifier 0x%x in type %s (%s vs %s).\n"
3703                            "%s:%d: Originally defined here.",
3704                            idx+1, String8(mName).string(),
3705                            String8(oe->getName()).string(),
3706                            String8(name).string(),
3707                            oe->getPublicSourcePos().file.string(),
3708                            oe->getPublicSourcePos().line);
3709                    hasError = true;
3710                }
3711            }
3712        }
3713
3714        if (!found) {
3715            p.sourcePos.error("Public symbol %s/%s declared here is not defined.",
3716                    String8(mName).string(), String8(name).string());
3717            hasError = true;
3718        }
3719    }
3720
3721    //printf("Copying back in %d non-public configs, have %d\n", N, origOrder.size());
3722
3723    if (N != origOrder.size()) {
3724        printf("Internal error: remaining private symbol count mismatch\n");
3725        N = origOrder.size();
3726    }
3727
3728    j = 0;
3729    for (i=0; i<N; i++) {
3730        sp<ConfigList> e = origOrder.itemAt(i);
3731        // There will always be enough room for the remaining entries.
3732        while (mOrderedConfigs.itemAt(j) != NULL) {
3733            j++;
3734        }
3735        mOrderedConfigs.replaceAt(e, j);
3736        j++;
3737    }
3738
3739    return hasError ? UNKNOWN_ERROR : NO_ERROR;
3740}
3741
3742ResourceTable::Package::Package(const String16& name, ssize_t includedId)
3743    : mName(name), mIncludedId(includedId),
3744      mTypeStringsMapping(0xffffffff),
3745      mKeyStringsMapping(0xffffffff)
3746{
3747}
3748
3749sp<ResourceTable::Type> ResourceTable::Package::getType(const String16& type,
3750                                                        const SourcePos& sourcePos,
3751                                                        bool doSetIndex)
3752{
3753    sp<Type> t = mTypes.valueFor(type);
3754    if (t == NULL) {
3755        t = new Type(type, sourcePos);
3756        mTypes.add(type, t);
3757        mOrderedTypes.add(t);
3758        if (doSetIndex) {
3759            // For some reason the type's index is set to one plus the index
3760            // in the mOrderedTypes list, rather than just the index.
3761            t->setIndex(mOrderedTypes.size());
3762        }
3763    }
3764    return t;
3765}
3766
3767status_t ResourceTable::Package::setTypeStrings(const sp<AaptFile>& data)
3768{
3769    mTypeStringsData = data;
3770    status_t err = setStrings(data, &mTypeStrings, &mTypeStringsMapping);
3771    if (err != NO_ERROR) {
3772        fprintf(stderr, "ERROR: Type string data is corrupt!\n");
3773    }
3774    return err;
3775}
3776
3777status_t ResourceTable::Package::setKeyStrings(const sp<AaptFile>& data)
3778{
3779    mKeyStringsData = data;
3780    status_t err = setStrings(data, &mKeyStrings, &mKeyStringsMapping);
3781    if (err != NO_ERROR) {
3782        fprintf(stderr, "ERROR: Key string data is corrupt!\n");
3783    }
3784    return err;
3785}
3786
3787status_t ResourceTable::Package::setStrings(const sp<AaptFile>& data,
3788                                            ResStringPool* strings,
3789                                            DefaultKeyedVector<String16, uint32_t>* mappings)
3790{
3791    if (data->getData() == NULL) {
3792        return UNKNOWN_ERROR;
3793    }
3794
3795    NOISY(aout << "Setting restable string pool: "
3796          << HexDump(data->getData(), data->getSize()) << endl);
3797
3798    status_t err = strings->setTo(data->getData(), data->getSize());
3799    if (err == NO_ERROR) {
3800        const size_t N = strings->size();
3801        for (size_t i=0; i<N; i++) {
3802            size_t len;
3803            mappings->add(String16(strings->stringAt(i, &len)), i);
3804        }
3805    }
3806    return err;
3807}
3808
3809status_t ResourceTable::Package::applyPublicTypeOrder()
3810{
3811    size_t N = mOrderedTypes.size();
3812    Vector<sp<Type> > origOrder(mOrderedTypes);
3813
3814    size_t i;
3815    for (i=0; i<N; i++) {
3816        mOrderedTypes.replaceAt(NULL, i);
3817    }
3818
3819    for (i=0; i<N; i++) {
3820        sp<Type> t = origOrder.itemAt(i);
3821        int32_t idx = t->getPublicIndex();
3822        if (idx > 0) {
3823            idx--;
3824            while (idx >= (int32_t)mOrderedTypes.size()) {
3825                mOrderedTypes.add();
3826            }
3827            if (mOrderedTypes.itemAt(idx) != NULL) {
3828                sp<Type> ot = mOrderedTypes.itemAt(idx);
3829                t->getFirstPublicSourcePos().error("Multiple type names declared for public type"
3830                        " identifier 0x%x (%s vs %s).\n"
3831                        "%s:%d: Originally defined here.",
3832                        idx, String8(ot->getName()).string(),
3833                        String8(t->getName()).string(),
3834                        ot->getFirstPublicSourcePos().file.string(),
3835                        ot->getFirstPublicSourcePos().line);
3836                return UNKNOWN_ERROR;
3837            }
3838            mOrderedTypes.replaceAt(t, idx);
3839            origOrder.removeAt(i);
3840            i--;
3841            N--;
3842        }
3843    }
3844
3845    size_t j=0;
3846    for (i=0; i<N; i++) {
3847        sp<Type> t = origOrder.itemAt(i);
3848        // There will always be enough room for the remaining types.
3849        while (mOrderedTypes.itemAt(j) != NULL) {
3850            j++;
3851        }
3852        mOrderedTypes.replaceAt(t, j);
3853    }
3854
3855    return NO_ERROR;
3856}
3857
3858sp<ResourceTable::Package> ResourceTable::getPackage(const String16& package)
3859{
3860    sp<Package> p = mPackages.valueFor(package);
3861    if (p == NULL) {
3862        if (mIsAppPackage) {
3863            if (mHaveAppPackage) {
3864                fprintf(stderr, "Adding multiple application package resources; only one is allowed.\n"
3865                                "Use -x to create extended resources.\n");
3866                return NULL;
3867            }
3868            mHaveAppPackage = true;
3869            p = new Package(package, 127);
3870        } else {
3871            p = new Package(package, mNextPackageId);
3872        }
3873        //printf("*** NEW PACKAGE: \"%s\" id=%d\n",
3874        //       String8(package).string(), p->getAssignedId());
3875        mPackages.add(package, p);
3876        mOrderedPackages.add(p);
3877        mNextPackageId++;
3878    }
3879    return p;
3880}
3881
3882sp<ResourceTable::Type> ResourceTable::getType(const String16& package,
3883                                               const String16& type,
3884                                               const SourcePos& sourcePos,
3885                                               bool doSetIndex)
3886{
3887    sp<Package> p = getPackage(package);
3888    if (p == NULL) {
3889        return NULL;
3890    }
3891    return p->getType(type, sourcePos, doSetIndex);
3892}
3893
3894sp<ResourceTable::Entry> ResourceTable::getEntry(const String16& package,
3895                                                 const String16& type,
3896                                                 const String16& name,
3897                                                 const SourcePos& sourcePos,
3898                                                 bool overlay,
3899                                                 const ResTable_config* config,
3900                                                 bool doSetIndex)
3901{
3902    sp<Type> t = getType(package, type, sourcePos, doSetIndex);
3903    if (t == NULL) {
3904        return NULL;
3905    }
3906    return t->getEntry(name, sourcePos, config, doSetIndex, overlay, mBundle->getAutoAddOverlay());
3907}
3908
3909sp<const ResourceTable::Entry> ResourceTable::getEntry(uint32_t resID,
3910                                                       const ResTable_config* config) const
3911{
3912    int pid = Res_GETPACKAGE(resID)+1;
3913    const size_t N = mOrderedPackages.size();
3914    size_t i;
3915    sp<Package> p;
3916    for (i=0; i<N; i++) {
3917        sp<Package> check = mOrderedPackages[i];
3918        if (check->getAssignedId() == pid) {
3919            p = check;
3920            break;
3921        }
3922
3923    }
3924    if (p == NULL) {
3925        fprintf(stderr, "warning: Package not found for resource #%08x\n", resID);
3926        return NULL;
3927    }
3928
3929    int tid = Res_GETTYPE(resID);
3930    if (tid < 0 || tid >= (int)p->getOrderedTypes().size()) {
3931        fprintf(stderr, "warning: Type not found for resource #%08x\n", resID);
3932        return NULL;
3933    }
3934    sp<Type> t = p->getOrderedTypes()[tid];
3935
3936    int eid = Res_GETENTRY(resID);
3937    if (eid < 0 || eid >= (int)t->getOrderedConfigs().size()) {
3938        fprintf(stderr, "warning: Entry not found for resource #%08x\n", resID);
3939        return NULL;
3940    }
3941
3942    sp<ConfigList> c = t->getOrderedConfigs()[eid];
3943    if (c == NULL) {
3944        fprintf(stderr, "warning: Entry not found for resource #%08x\n", resID);
3945        return NULL;
3946    }
3947
3948    ConfigDescription cdesc;
3949    if (config) cdesc = *config;
3950    sp<Entry> e = c->getEntries().valueFor(cdesc);
3951    if (c == NULL) {
3952        fprintf(stderr, "warning: Entry configuration not found for resource #%08x\n", resID);
3953        return NULL;
3954    }
3955
3956    return e;
3957}
3958
3959const ResourceTable::Item* ResourceTable::getItem(uint32_t resID, uint32_t attrID) const
3960{
3961    sp<const Entry> e = getEntry(resID);
3962    if (e == NULL) {
3963        return NULL;
3964    }
3965
3966    const size_t N = e->getBag().size();
3967    for (size_t i=0; i<N; i++) {
3968        const Item& it = e->getBag().valueAt(i);
3969        if (it.bagKeyId == 0) {
3970            fprintf(stderr, "warning: ID not yet assigned to '%s' in bag '%s'\n",
3971                    String8(e->getName()).string(),
3972                    String8(e->getBag().keyAt(i)).string());
3973        }
3974        if (it.bagKeyId == attrID) {
3975            return &it;
3976        }
3977    }
3978
3979    return NULL;
3980}
3981
3982bool ResourceTable::getItemValue(
3983    uint32_t resID, uint32_t attrID, Res_value* outValue)
3984{
3985    const Item* item = getItem(resID, attrID);
3986
3987    bool res = false;
3988    if (item != NULL) {
3989        if (item->evaluating) {
3990            sp<const Entry> e = getEntry(resID);
3991            const size_t N = e->getBag().size();
3992            size_t i;
3993            for (i=0; i<N; i++) {
3994                if (&e->getBag().valueAt(i) == item) {
3995                    break;
3996                }
3997            }
3998            fprintf(stderr, "warning: Circular reference detected in key '%s' of bag '%s'\n",
3999                    String8(e->getName()).string(),
4000                    String8(e->getBag().keyAt(i)).string());
4001            return false;
4002        }
4003        item->evaluating = true;
4004        res = stringToValue(outValue, NULL, item->value, false, false, item->bagKeyId);
4005        NOISY(
4006            if (res) {
4007                printf("getItemValue of #%08x[#%08x] (%s): type=#%08x, data=#%08x\n",
4008                       resID, attrID, String8(getEntry(resID)->getName()).string(),
4009                       outValue->dataType, outValue->data);
4010            } else {
4011                printf("getItemValue of #%08x[#%08x]: failed\n",
4012                       resID, attrID);
4013            }
4014        );
4015        item->evaluating = false;
4016    }
4017    return res;
4018}
4019