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