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