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