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