ResourceTable.cpp revision 27f69f4e06961fdecd1078b2292d764a157e5e1c
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        const bool isBase)
2079{
2080    sp<AaptFile> data = new AaptFile(String8(), AaptGroupEntry(), String8());
2081    status_t err = flatten(bundle, filter, data, isBase);
2082    return err == NO_ERROR ? data : NULL;
2083}
2084
2085inline uint32_t ResourceTable::getResId(const sp<Package>& p,
2086                                        const sp<Type>& t,
2087                                        uint32_t nameId)
2088{
2089    return makeResId(p->getAssignedId(), t->getIndex(), nameId);
2090}
2091
2092uint32_t ResourceTable::getResId(const String16& package,
2093                                 const String16& type,
2094                                 const String16& name,
2095                                 bool onlyPublic) const
2096{
2097    uint32_t id = ResourceIdCache::lookup(package, type, name, onlyPublic);
2098    if (id != 0) return id;     // cache hit
2099
2100    // First look for this in the included resources...
2101    uint32_t specFlags = 0;
2102    uint32_t rid = mAssets->getIncludedResources()
2103        .identifierForName(name.string(), name.size(),
2104                           type.string(), type.size(),
2105                           package.string(), package.size(),
2106                           &specFlags);
2107    if (rid != 0) {
2108        if (onlyPublic) {
2109            if ((specFlags & ResTable_typeSpec::SPEC_PUBLIC) == 0) {
2110                return 0;
2111            }
2112        }
2113
2114        return ResourceIdCache::store(package, type, name, onlyPublic, rid);
2115    }
2116
2117    sp<Package> p = mPackages.valueFor(package);
2118    if (p == NULL) return 0;
2119    sp<Type> t = p->getTypes().valueFor(type);
2120    if (t == NULL) return 0;
2121    sp<ConfigList> c =  t->getConfigs().valueFor(name);
2122    if (c == NULL) return 0;
2123    int32_t ei = c->getEntryIndex();
2124    if (ei < 0) return 0;
2125
2126    return ResourceIdCache::store(package, type, name, onlyPublic,
2127            getResId(p, t, ei));
2128}
2129
2130uint32_t ResourceTable::getResId(const String16& ref,
2131                                 const String16* defType,
2132                                 const String16* defPackage,
2133                                 const char** outErrorMsg,
2134                                 bool onlyPublic) const
2135{
2136    String16 package, type, name;
2137    bool refOnlyPublic = true;
2138    if (!ResTable::expandResourceRef(
2139        ref.string(), ref.size(), &package, &type, &name,
2140        defType, defPackage ? defPackage:&mAssetsPackage,
2141        outErrorMsg, &refOnlyPublic)) {
2142        NOISY(printf("Expanding resource: ref=%s\n",
2143                     String8(ref).string()));
2144        NOISY(printf("Expanding resource: defType=%s\n",
2145                     defType ? String8(*defType).string() : "NULL"));
2146        NOISY(printf("Expanding resource: defPackage=%s\n",
2147                     defPackage ? String8(*defPackage).string() : "NULL"));
2148        NOISY(printf("Expanding resource: ref=%s\n", String8(ref).string()));
2149        NOISY(printf("Expanded resource: p=%s, t=%s, n=%s, res=0\n",
2150                     String8(package).string(), String8(type).string(),
2151                     String8(name).string()));
2152        return 0;
2153    }
2154    uint32_t res = getResId(package, type, name, onlyPublic && refOnlyPublic);
2155    NOISY(printf("Expanded resource: p=%s, t=%s, n=%s, res=%d\n",
2156                 String8(package).string(), String8(type).string(),
2157                 String8(name).string(), res));
2158    if (res == 0) {
2159        if (outErrorMsg)
2160            *outErrorMsg = "No resource found that matches the given name";
2161    }
2162    return res;
2163}
2164
2165bool ResourceTable::isValidResourceName(const String16& s)
2166{
2167    const char16_t* p = s.string();
2168    bool first = true;
2169    while (*p) {
2170        if ((*p >= 'a' && *p <= 'z')
2171            || (*p >= 'A' && *p <= 'Z')
2172            || *p == '_'
2173            || (!first && *p >= '0' && *p <= '9')) {
2174            first = false;
2175            p++;
2176            continue;
2177        }
2178        return false;
2179    }
2180    return true;
2181}
2182
2183bool ResourceTable::stringToValue(Res_value* outValue, StringPool* pool,
2184                                  const String16& str,
2185                                  bool preserveSpaces, bool coerceType,
2186                                  uint32_t attrID,
2187                                  const Vector<StringPool::entry_style_span>* style,
2188                                  String16* outStr, void* accessorCookie,
2189                                  uint32_t attrType, const String8* configTypeName,
2190                                  const ConfigDescription* config)
2191{
2192    String16 finalStr;
2193
2194    bool res = true;
2195    if (style == NULL || style->size() == 0) {
2196        // Text is not styled so it can be any type...  let's figure it out.
2197        res = mAssets->getIncludedResources()
2198            .stringToValue(outValue, &finalStr, str.string(), str.size(), preserveSpaces,
2199                            coerceType, attrID, NULL, &mAssetsPackage, this,
2200                           accessorCookie, attrType);
2201    } else {
2202        // Styled text can only be a string, and while collecting the style
2203        // information we have already processed that string!
2204        outValue->size = sizeof(Res_value);
2205        outValue->res0 = 0;
2206        outValue->dataType = outValue->TYPE_STRING;
2207        outValue->data = 0;
2208        finalStr = str;
2209    }
2210
2211    if (!res) {
2212        return false;
2213    }
2214
2215    if (outValue->dataType == outValue->TYPE_STRING) {
2216        // Should do better merging styles.
2217        if (pool) {
2218            String8 configStr;
2219            if (config != NULL) {
2220                configStr = config->toString();
2221            } else {
2222                configStr = "(null)";
2223            }
2224            NOISY(printf("Adding to pool string style #%d config %s: %s\n",
2225                    style != NULL ? style->size() : 0,
2226                    configStr.string(), String8(finalStr).string()));
2227            if (style != NULL && style->size() > 0) {
2228                outValue->data = pool->add(finalStr, *style, configTypeName, config);
2229            } else {
2230                outValue->data = pool->add(finalStr, true, configTypeName, config);
2231            }
2232        } else {
2233            // Caller will fill this in later.
2234            outValue->data = 0;
2235        }
2236
2237        if (outStr) {
2238            *outStr = finalStr;
2239        }
2240
2241    }
2242
2243    return true;
2244}
2245
2246uint32_t ResourceTable::getCustomResource(
2247    const String16& package, const String16& type, const String16& name) const
2248{
2249    //printf("getCustomResource: %s %s %s\n", String8(package).string(),
2250    //       String8(type).string(), String8(name).string());
2251    sp<Package> p = mPackages.valueFor(package);
2252    if (p == NULL) return 0;
2253    sp<Type> t = p->getTypes().valueFor(type);
2254    if (t == NULL) return 0;
2255    sp<ConfigList> c =  t->getConfigs().valueFor(name);
2256    if (c == NULL) return 0;
2257    int32_t ei = c->getEntryIndex();
2258    if (ei < 0) return 0;
2259    return getResId(p, t, ei);
2260}
2261
2262uint32_t ResourceTable::getCustomResourceWithCreation(
2263        const String16& package, const String16& type, const String16& name,
2264        const bool createIfNotFound)
2265{
2266    uint32_t resId = getCustomResource(package, type, name);
2267    if (resId != 0 || !createIfNotFound) {
2268        return resId;
2269    }
2270
2271    if (mAssetsPackage != package) {
2272        mCurrentXmlPos.error("creating resource for external package %s: %s/%s.",
2273                String8(package).string(), String8(type).string(), String8(name).string());
2274        if (package == String16("android")) {
2275            mCurrentXmlPos.printf("did you mean to use @+id instead of @+android:id?");
2276        }
2277        return 0;
2278    }
2279
2280    String16 value("false");
2281    status_t status = addEntry(mCurrentXmlPos, package, type, name, value, NULL, NULL, true);
2282    if (status == NO_ERROR) {
2283        resId = getResId(package, type, name);
2284        return resId;
2285    }
2286    return 0;
2287}
2288
2289uint32_t ResourceTable::getRemappedPackage(uint32_t origPackage) const
2290{
2291    return origPackage;
2292}
2293
2294bool ResourceTable::getAttributeType(uint32_t attrID, uint32_t* outType)
2295{
2296    //printf("getAttributeType #%08x\n", attrID);
2297    Res_value value;
2298    if (getItemValue(attrID, ResTable_map::ATTR_TYPE, &value)) {
2299        //printf("getAttributeType #%08x (%s): #%08x\n", attrID,
2300        //       String8(getEntry(attrID)->getName()).string(), value.data);
2301        *outType = value.data;
2302        return true;
2303    }
2304    return false;
2305}
2306
2307bool ResourceTable::getAttributeMin(uint32_t attrID, uint32_t* outMin)
2308{
2309    //printf("getAttributeMin #%08x\n", attrID);
2310    Res_value value;
2311    if (getItemValue(attrID, ResTable_map::ATTR_MIN, &value)) {
2312        *outMin = value.data;
2313        return true;
2314    }
2315    return false;
2316}
2317
2318bool ResourceTable::getAttributeMax(uint32_t attrID, uint32_t* outMax)
2319{
2320    //printf("getAttributeMax #%08x\n", attrID);
2321    Res_value value;
2322    if (getItemValue(attrID, ResTable_map::ATTR_MAX, &value)) {
2323        *outMax = value.data;
2324        return true;
2325    }
2326    return false;
2327}
2328
2329uint32_t ResourceTable::getAttributeL10N(uint32_t attrID)
2330{
2331    //printf("getAttributeL10N #%08x\n", attrID);
2332    Res_value value;
2333    if (getItemValue(attrID, ResTable_map::ATTR_L10N, &value)) {
2334        return value.data;
2335    }
2336    return ResTable_map::L10N_NOT_REQUIRED;
2337}
2338
2339bool ResourceTable::getLocalizationSetting()
2340{
2341    return mBundle->getRequireLocalization();
2342}
2343
2344void ResourceTable::reportError(void* accessorCookie, const char* fmt, ...)
2345{
2346    if (accessorCookie != NULL && fmt != NULL) {
2347        AccessorCookie* ac = (AccessorCookie*)accessorCookie;
2348        int retval=0;
2349        char buf[1024];
2350        va_list ap;
2351        va_start(ap, fmt);
2352        retval = vsnprintf(buf, sizeof(buf), fmt, ap);
2353        va_end(ap);
2354        ac->sourcePos.error("Error: %s (at '%s' with value '%s').\n",
2355                            buf, ac->attr.string(), ac->value.string());
2356    }
2357}
2358
2359bool ResourceTable::getAttributeKeys(
2360    uint32_t attrID, Vector<String16>* outKeys)
2361{
2362    sp<const Entry> e = getEntry(attrID);
2363    if (e != NULL) {
2364        const size_t N = e->getBag().size();
2365        for (size_t i=0; i<N; i++) {
2366            const String16& key = e->getBag().keyAt(i);
2367            if (key.size() > 0 && key.string()[0] != '^') {
2368                outKeys->add(key);
2369            }
2370        }
2371        return true;
2372    }
2373    return false;
2374}
2375
2376bool ResourceTable::getAttributeEnum(
2377    uint32_t attrID, const char16_t* name, size_t nameLen,
2378    Res_value* outValue)
2379{
2380    //printf("getAttributeEnum #%08x %s\n", attrID, String8(name, nameLen).string());
2381    String16 nameStr(name, nameLen);
2382    sp<const Entry> e = getEntry(attrID);
2383    if (e != NULL) {
2384        const size_t N = e->getBag().size();
2385        for (size_t i=0; i<N; i++) {
2386            //printf("Comparing %s to %s\n", String8(name, nameLen).string(),
2387            //       String8(e->getBag().keyAt(i)).string());
2388            if (e->getBag().keyAt(i) == nameStr) {
2389                return getItemValue(attrID, e->getBag().valueAt(i).bagKeyId, outValue);
2390            }
2391        }
2392    }
2393    return false;
2394}
2395
2396bool ResourceTable::getAttributeFlags(
2397    uint32_t attrID, const char16_t* name, size_t nameLen,
2398    Res_value* outValue)
2399{
2400    outValue->dataType = Res_value::TYPE_INT_HEX;
2401    outValue->data = 0;
2402
2403    //printf("getAttributeFlags #%08x %s\n", attrID, String8(name, nameLen).string());
2404    String16 nameStr(name, nameLen);
2405    sp<const Entry> e = getEntry(attrID);
2406    if (e != NULL) {
2407        const size_t N = e->getBag().size();
2408
2409        const char16_t* end = name + nameLen;
2410        const char16_t* pos = name;
2411        while (pos < end) {
2412            const char16_t* start = pos;
2413            while (pos < end && *pos != '|') {
2414                pos++;
2415            }
2416
2417            String16 nameStr(start, pos-start);
2418            size_t i;
2419            for (i=0; i<N; i++) {
2420                //printf("Comparing \"%s\" to \"%s\"\n", String8(nameStr).string(),
2421                //       String8(e->getBag().keyAt(i)).string());
2422                if (e->getBag().keyAt(i) == nameStr) {
2423                    Res_value val;
2424                    bool got = getItemValue(attrID, e->getBag().valueAt(i).bagKeyId, &val);
2425                    if (!got) {
2426                        return false;
2427                    }
2428                    //printf("Got value: 0x%08x\n", val.data);
2429                    outValue->data |= val.data;
2430                    break;
2431                }
2432            }
2433
2434            if (i >= N) {
2435                // Didn't find this flag identifier.
2436                return false;
2437            }
2438            pos++;
2439        }
2440
2441        return true;
2442    }
2443    return false;
2444}
2445
2446status_t ResourceTable::assignResourceIds()
2447{
2448    const size_t N = mOrderedPackages.size();
2449    size_t pi;
2450    status_t firstError = NO_ERROR;
2451
2452    // First generate all bag attributes and assign indices.
2453    for (pi=0; pi<N; pi++) {
2454        sp<Package> p = mOrderedPackages.itemAt(pi);
2455        if (p == NULL || p->getTypes().size() == 0) {
2456            // Empty, skip!
2457            continue;
2458        }
2459
2460        // This has no sense for packages being built as AppFeature (aka with a non-zero offset).
2461        status_t err = p->applyPublicTypeOrder();
2462        if (err != NO_ERROR && firstError == NO_ERROR) {
2463            firstError = err;
2464        }
2465
2466        // Generate attributes...
2467        const size_t N = p->getOrderedTypes().size();
2468        size_t ti;
2469        for (ti=0; ti<N; ti++) {
2470            sp<Type> t = p->getOrderedTypes().itemAt(ti);
2471            if (t == NULL) {
2472                continue;
2473            }
2474            const size_t N = t->getOrderedConfigs().size();
2475            for (size_t ci=0; ci<N; ci++) {
2476                sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2477                if (c == NULL) {
2478                    continue;
2479                }
2480                const size_t N = c->getEntries().size();
2481                for (size_t ei=0; ei<N; ei++) {
2482                    sp<Entry> e = c->getEntries().valueAt(ei);
2483                    if (e == NULL) {
2484                        continue;
2485                    }
2486                    status_t err = e->generateAttributes(this, p->getName());
2487                    if (err != NO_ERROR && firstError == NO_ERROR) {
2488                        firstError = err;
2489                    }
2490                }
2491            }
2492        }
2493
2494        uint32_t typeIdOffset = 0;
2495        if (mPackageType == AppFeature && p->getName() == mAssetsPackage) {
2496            typeIdOffset = mTypeIdOffset;
2497        }
2498
2499        const SourcePos unknown(String8("????"), 0);
2500        sp<Type> attr = p->getType(String16("attr"), unknown);
2501
2502        // Assign indices...
2503        const size_t typeCount = p->getOrderedTypes().size();
2504        for (size_t ti = 0; ti < typeCount; ti++) {
2505            sp<Type> t = p->getOrderedTypes().itemAt(ti);
2506            if (t == NULL) {
2507                continue;
2508            }
2509
2510            err = t->applyPublicEntryOrder();
2511            if (err != NO_ERROR && firstError == NO_ERROR) {
2512                firstError = err;
2513            }
2514
2515            const size_t N = t->getOrderedConfigs().size();
2516            t->setIndex(ti + 1 + typeIdOffset);
2517
2518            LOG_ALWAYS_FATAL_IF(ti == 0 && attr != t,
2519                                "First type is not attr!");
2520
2521            for (size_t ei=0; ei<N; ei++) {
2522                sp<ConfigList> c = t->getOrderedConfigs().itemAt(ei);
2523                if (c == NULL) {
2524                    continue;
2525                }
2526                c->setEntryIndex(ei);
2527            }
2528        }
2529
2530        // Assign resource IDs to keys in bags...
2531        for (size_t ti = 0; ti < typeCount; ti++) {
2532            sp<Type> t = p->getOrderedTypes().itemAt(ti);
2533            if (t == NULL) {
2534                continue;
2535            }
2536            const size_t N = t->getOrderedConfigs().size();
2537            for (size_t ci=0; ci<N; ci++) {
2538                sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2539                //printf("Ordered config #%d: %p\n", ci, c.get());
2540                const size_t N = c->getEntries().size();
2541                for (size_t ei=0; ei<N; ei++) {
2542                    sp<Entry> e = c->getEntries().valueAt(ei);
2543                    if (e == NULL) {
2544                        continue;
2545                    }
2546                    status_t err = e->assignResourceIds(this, p->getName());
2547                    if (err != NO_ERROR && firstError == NO_ERROR) {
2548                        firstError = err;
2549                    }
2550                }
2551            }
2552        }
2553    }
2554    return firstError;
2555}
2556
2557status_t ResourceTable::addSymbols(const sp<AaptSymbols>& outSymbols) {
2558    const size_t N = mOrderedPackages.size();
2559    size_t pi;
2560
2561    for (pi=0; pi<N; pi++) {
2562        sp<Package> p = mOrderedPackages.itemAt(pi);
2563        if (p->getTypes().size() == 0) {
2564            // Empty, skip!
2565            continue;
2566        }
2567
2568        const size_t N = p->getOrderedTypes().size();
2569        size_t ti;
2570
2571        for (ti=0; ti<N; ti++) {
2572            sp<Type> t = p->getOrderedTypes().itemAt(ti);
2573            if (t == NULL) {
2574                continue;
2575            }
2576            const size_t N = t->getOrderedConfigs().size();
2577            sp<AaptSymbols> typeSymbols;
2578            typeSymbols = outSymbols->addNestedSymbol(String8(t->getName()), t->getPos());
2579            for (size_t ci=0; ci<N; ci++) {
2580                sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2581                if (c == NULL) {
2582                    continue;
2583                }
2584                uint32_t rid = getResId(p, t, ci);
2585                if (rid == 0) {
2586                    return UNKNOWN_ERROR;
2587                }
2588                if (Res_GETPACKAGE(rid) + 1 == p->getAssignedId()) {
2589                    typeSymbols->addSymbol(String8(c->getName()), rid, c->getPos());
2590
2591                    String16 comment(c->getComment());
2592                    typeSymbols->appendComment(String8(c->getName()), comment, c->getPos());
2593                    //printf("Type symbol [%08x] %s comment: %s\n", rid,
2594                    //        String8(c->getName()).string(), String8(comment).string());
2595                    comment = c->getTypeComment();
2596                    typeSymbols->appendTypeComment(String8(c->getName()), comment);
2597                }
2598            }
2599        }
2600    }
2601    return NO_ERROR;
2602}
2603
2604
2605void
2606ResourceTable::addLocalization(const String16& name, const String8& locale, const SourcePos& src)
2607{
2608    mLocalizations[name][locale] = src;
2609}
2610
2611
2612/*!
2613 * Flag various sorts of localization problems.  '+' indicates checks already implemented;
2614 * '-' indicates checks that will be implemented in the future.
2615 *
2616 * + A localized string for which no default-locale version exists => warning
2617 * + A string for which no version in an explicitly-requested locale exists => warning
2618 * + A localized translation of an translateable="false" string => warning
2619 * - A localized string not provided in every locale used by the table
2620 */
2621status_t
2622ResourceTable::validateLocalizations(void)
2623{
2624    status_t err = NO_ERROR;
2625    const String8 defaultLocale;
2626
2627    // For all strings...
2628    for (map<String16, map<String8, SourcePos> >::iterator nameIter = mLocalizations.begin();
2629         nameIter != mLocalizations.end();
2630         nameIter++) {
2631        const map<String8, SourcePos>& configSrcMap = nameIter->second;
2632
2633        // Look for strings with no default localization
2634        if (configSrcMap.count(defaultLocale) == 0) {
2635            SourcePos().warning("string '%s' has no default translation.",
2636                    String8(nameIter->first).string());
2637            if (mBundle->getVerbose()) {
2638                for (map<String8, SourcePos>::const_iterator locales = configSrcMap.begin();
2639                    locales != configSrcMap.end();
2640                    locales++) {
2641                    locales->second.printf("locale %s found", locales->first.string());
2642                }
2643            }
2644            // !!! TODO: throw an error here in some circumstances
2645        }
2646
2647        // Check that all requested localizations are present for this string
2648        if (mBundle->getConfigurations().size() > 0 && mBundle->getRequireLocalization()) {
2649            const char* allConfigs = mBundle->getConfigurations().string();
2650            const char* start = allConfigs;
2651            const char* comma;
2652
2653            set<String8> missingConfigs;
2654            AaptLocaleValue locale;
2655            do {
2656                String8 config;
2657                comma = strchr(start, ',');
2658                if (comma != NULL) {
2659                    config.setTo(start, comma - start);
2660                    start = comma + 1;
2661                } else {
2662                    config.setTo(start);
2663                }
2664
2665                if (!locale.initFromFilterString(config)) {
2666                    continue;
2667                }
2668
2669                // don't bother with the pseudolocale "en_XA" or "ar_XB"
2670                if (config != "en_XA" && config != "ar_XB") {
2671                    if (configSrcMap.find(config) == configSrcMap.end()) {
2672                        // okay, no specific localization found.  it's possible that we are
2673                        // requiring a specific regional localization [e.g. de_DE] but there is an
2674                        // available string in the generic language localization [e.g. de];
2675                        // consider that string to have fulfilled the localization requirement.
2676                        String8 region(config.string(), 2);
2677                        if (configSrcMap.find(region) == configSrcMap.end() &&
2678                                configSrcMap.count(defaultLocale) == 0) {
2679                            missingConfigs.insert(config);
2680                        }
2681                    }
2682                }
2683            } while (comma != NULL);
2684
2685            if (!missingConfigs.empty()) {
2686                String8 configStr;
2687                for (set<String8>::iterator iter = missingConfigs.begin();
2688                     iter != missingConfigs.end();
2689                     iter++) {
2690                    configStr.appendFormat(" %s", iter->string());
2691                }
2692                SourcePos().warning("string '%s' is missing %u required localizations:%s",
2693                        String8(nameIter->first).string(),
2694                        (unsigned int)missingConfigs.size(),
2695                        configStr.string());
2696            }
2697        }
2698    }
2699
2700    return err;
2701}
2702
2703status_t ResourceTable::flatten(Bundle* bundle, const sp<const ResourceFilter>& filter,
2704        const sp<AaptFile>& dest,
2705        const bool isBase)
2706{
2707    const ConfigDescription nullConfig;
2708
2709    const size_t N = mOrderedPackages.size();
2710    size_t pi;
2711
2712    const static String16 mipmap16("mipmap");
2713
2714    bool useUTF8 = !bundle->getUTF16StringsOption();
2715
2716    // The libraries this table references.
2717    Vector<sp<Package> > libraryPackages;
2718    const ResTable& table = mAssets->getIncludedResources();
2719    const size_t basePackageCount = table.getBasePackageCount();
2720    for (size_t i = 0; i < basePackageCount; i++) {
2721        size_t packageId = table.getBasePackageId(i);
2722        String16 packageName(table.getBasePackageName(i));
2723        if (packageId > 0x01 && packageId != 0x7f &&
2724                packageName != String16("android")) {
2725            libraryPackages.add(sp<Package>(new Package(packageName, packageId)));
2726        }
2727    }
2728
2729    // Iterate through all data, collecting all values (strings,
2730    // references, etc).
2731    StringPool valueStrings(useUTF8);
2732    Vector<sp<Entry> > allEntries;
2733    for (pi=0; pi<N; pi++) {
2734        sp<Package> p = mOrderedPackages.itemAt(pi);
2735        if (p->getTypes().size() == 0) {
2736            continue;
2737        }
2738
2739        StringPool typeStrings(useUTF8);
2740        StringPool keyStrings(useUTF8);
2741
2742        ssize_t stringsAdded = 0;
2743        const size_t N = p->getOrderedTypes().size();
2744        for (size_t ti=0; ti<N; ti++) {
2745            sp<Type> t = p->getOrderedTypes().itemAt(ti);
2746            if (t == NULL) {
2747                typeStrings.add(String16("<empty>"), false);
2748                stringsAdded++;
2749                continue;
2750            }
2751
2752            while (stringsAdded < t->getIndex() - 1) {
2753                typeStrings.add(String16("<empty>"), false);
2754                stringsAdded++;
2755            }
2756
2757            const String16 typeName(t->getName());
2758            typeStrings.add(typeName, false);
2759            stringsAdded++;
2760
2761            // This is a hack to tweak the sorting order of the final strings,
2762            // to put stuff that is generally not language-specific first.
2763            String8 configTypeName(typeName);
2764            if (configTypeName == "drawable" || configTypeName == "layout"
2765                    || configTypeName == "color" || configTypeName == "anim"
2766                    || configTypeName == "interpolator" || configTypeName == "animator"
2767                    || configTypeName == "xml" || configTypeName == "menu"
2768                    || configTypeName == "mipmap" || configTypeName == "raw") {
2769                configTypeName = "1complex";
2770            } else {
2771                configTypeName = "2value";
2772            }
2773
2774            // mipmaps don't get filtered, so they will
2775            // allways end up in the base. Make sure they
2776            // don't end up in a split.
2777            if (typeName == mipmap16 && !isBase) {
2778                continue;
2779            }
2780
2781            const bool filterable = (typeName != mipmap16);
2782
2783            const size_t N = t->getOrderedConfigs().size();
2784            for (size_t ci=0; ci<N; ci++) {
2785                sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2786                if (c == NULL) {
2787                    continue;
2788                }
2789                const size_t N = c->getEntries().size();
2790                for (size_t ei=0; ei<N; ei++) {
2791                    ConfigDescription config = c->getEntries().keyAt(ei);
2792                    if (filterable && !filter->match(config)) {
2793                        continue;
2794                    }
2795                    sp<Entry> e = c->getEntries().valueAt(ei);
2796                    if (e == NULL) {
2797                        continue;
2798                    }
2799                    e->setNameIndex(keyStrings.add(e->getName(), true));
2800
2801                    // If this entry has no values for other configs,
2802                    // and is the default config, then it is special.  Otherwise
2803                    // we want to add it with the config info.
2804                    ConfigDescription* valueConfig = NULL;
2805                    if (N != 1 || config == nullConfig) {
2806                        valueConfig = &config;
2807                    }
2808
2809                    status_t err = e->prepareFlatten(&valueStrings, this,
2810                            &configTypeName, &config);
2811                    if (err != NO_ERROR) {
2812                        return err;
2813                    }
2814                    allEntries.add(e);
2815                }
2816            }
2817        }
2818
2819        p->setTypeStrings(typeStrings.createStringBlock());
2820        p->setKeyStrings(keyStrings.createStringBlock());
2821    }
2822
2823    if (bundle->getOutputAPKFile() != NULL) {
2824        // Now we want to sort the value strings for better locality.  This will
2825        // cause the positions of the strings to change, so we need to go back
2826        // through out resource entries and update them accordingly.  Only need
2827        // to do this if actually writing the output file.
2828        valueStrings.sortByConfig();
2829        for (pi=0; pi<allEntries.size(); pi++) {
2830            allEntries[pi]->remapStringValue(&valueStrings);
2831        }
2832    }
2833
2834    ssize_t strAmt = 0;
2835
2836    // Now build the array of package chunks.
2837    Vector<sp<AaptFile> > flatPackages;
2838    for (pi=0; pi<N; pi++) {
2839        sp<Package> p = mOrderedPackages.itemAt(pi);
2840        if (p->getTypes().size() == 0) {
2841            // Empty, skip!
2842            continue;
2843        }
2844
2845        const size_t N = p->getTypeStrings().size();
2846
2847        const size_t baseSize = sizeof(ResTable_package);
2848
2849        // Start the package data.
2850        sp<AaptFile> data = new AaptFile(String8(), AaptGroupEntry(), String8());
2851        ResTable_package* header = (ResTable_package*)data->editData(baseSize);
2852        if (header == NULL) {
2853            fprintf(stderr, "ERROR: out of memory creating ResTable_package\n");
2854            return NO_MEMORY;
2855        }
2856        memset(header, 0, sizeof(*header));
2857        header->header.type = htods(RES_TABLE_PACKAGE_TYPE);
2858        header->header.headerSize = htods(sizeof(*header));
2859        header->id = htodl(static_cast<uint32_t>(p->getAssignedId()));
2860        strcpy16_htod(header->name, p->getName().string());
2861
2862        // Write the string blocks.
2863        const size_t typeStringsStart = data->getSize();
2864        sp<AaptFile> strFile = p->getTypeStringsData();
2865        ssize_t amt = data->writeData(strFile->getData(), strFile->getSize());
2866        #if PRINT_STRING_METRICS
2867        fprintf(stderr, "**** type strings: %d\n", amt);
2868        #endif
2869        strAmt += amt;
2870        if (amt < 0) {
2871            return amt;
2872        }
2873        const size_t keyStringsStart = data->getSize();
2874        strFile = p->getKeyStringsData();
2875        amt = data->writeData(strFile->getData(), strFile->getSize());
2876        #if PRINT_STRING_METRICS
2877        fprintf(stderr, "**** key strings: %d\n", amt);
2878        #endif
2879        strAmt += amt;
2880        if (amt < 0) {
2881            return amt;
2882        }
2883
2884        if (isBase) {
2885            status_t err = flattenLibraryTable(data, libraryPackages);
2886            if (err != NO_ERROR) {
2887                fprintf(stderr, "ERROR: failed to write library table\n");
2888                return err;
2889            }
2890        }
2891
2892        // Build the type chunks inside of this package.
2893        for (size_t ti=0; ti<N; ti++) {
2894            // Retrieve them in the same order as the type string block.
2895            size_t len;
2896            String16 typeName(p->getTypeStrings().stringAt(ti, &len));
2897            sp<Type> t = p->getTypes().valueFor(typeName);
2898            LOG_ALWAYS_FATAL_IF(t == NULL && typeName != String16("<empty>"),
2899                                "Type name %s not found",
2900                                String8(typeName).string());
2901            if (t == NULL) {
2902                continue;
2903            }
2904            const bool filterable = (typeName != mipmap16);
2905            const bool skipEntireType = (typeName == mipmap16 && !isBase);
2906
2907            const size_t N = t != NULL ? t->getOrderedConfigs().size() : 0;
2908
2909            // Until a non-NO_ENTRY value has been written for a resource,
2910            // that resource is invalid; validResources[i] represents
2911            // the item at t->getOrderedConfigs().itemAt(i).
2912            Vector<bool> validResources;
2913            validResources.insertAt(false, 0, N);
2914
2915            // First write the typeSpec chunk, containing information about
2916            // each resource entry in this type.
2917            {
2918                const size_t typeSpecSize = sizeof(ResTable_typeSpec) + sizeof(uint32_t)*N;
2919                const size_t typeSpecStart = data->getSize();
2920                ResTable_typeSpec* tsHeader = (ResTable_typeSpec*)
2921                    (((uint8_t*)data->editData(typeSpecStart+typeSpecSize)) + typeSpecStart);
2922                if (tsHeader == NULL) {
2923                    fprintf(stderr, "ERROR: out of memory creating ResTable_typeSpec\n");
2924                    return NO_MEMORY;
2925                }
2926                memset(tsHeader, 0, sizeof(*tsHeader));
2927                tsHeader->header.type = htods(RES_TABLE_TYPE_SPEC_TYPE);
2928                tsHeader->header.headerSize = htods(sizeof(*tsHeader));
2929                tsHeader->header.size = htodl(typeSpecSize);
2930                tsHeader->id = ti+1;
2931                tsHeader->entryCount = htodl(N);
2932
2933                uint32_t* typeSpecFlags = (uint32_t*)
2934                    (((uint8_t*)data->editData())
2935                        + typeSpecStart + sizeof(ResTable_typeSpec));
2936                memset(typeSpecFlags, 0, sizeof(uint32_t)*N);
2937
2938                for (size_t ei=0; ei<N; ei++) {
2939                    sp<ConfigList> cl = t->getOrderedConfigs().itemAt(ei);
2940                    if (cl->getPublic()) {
2941                        typeSpecFlags[ei] |= htodl(ResTable_typeSpec::SPEC_PUBLIC);
2942                    }
2943
2944                    if (skipEntireType) {
2945                        continue;
2946                    }
2947
2948                    const size_t CN = cl->getEntries().size();
2949                    for (size_t ci=0; ci<CN; ci++) {
2950                        if (filterable && !filter->match(cl->getEntries().keyAt(ci))) {
2951                            continue;
2952                        }
2953                        for (size_t cj=ci+1; cj<CN; cj++) {
2954                            if (filterable && !filter->match(cl->getEntries().keyAt(cj))) {
2955                                continue;
2956                            }
2957                            typeSpecFlags[ei] |= htodl(
2958                                cl->getEntries().keyAt(ci).diff(cl->getEntries().keyAt(cj)));
2959                        }
2960                    }
2961                }
2962            }
2963
2964            if (skipEntireType) {
2965                continue;
2966            }
2967
2968            // We need to write one type chunk for each configuration for
2969            // which we have entries in this type.
2970            const size_t NC = t->getUniqueConfigs().size();
2971
2972            const size_t typeSize = sizeof(ResTable_type) + sizeof(uint32_t)*N;
2973
2974            for (size_t ci=0; ci<NC; ci++) {
2975                ConfigDescription config = t->getUniqueConfigs().itemAt(ci);
2976
2977                NOISY(printf("Writing config %d config: imsi:%d/%d lang:%c%c cnt:%c%c "
2978                     "orien:%d ui:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d "
2979                     "sw%ddp w%ddp h%ddp dir:%d\n",
2980                      ti+1,
2981                      config.mcc, config.mnc,
2982                      config.language[0] ? config.language[0] : '-',
2983                      config.language[1] ? config.language[1] : '-',
2984                      config.country[0] ? config.country[0] : '-',
2985                      config.country[1] ? config.country[1] : '-',
2986                      config.orientation,
2987                      config.uiMode,
2988                      config.touchscreen,
2989                      config.density,
2990                      config.keyboard,
2991                      config.inputFlags,
2992                      config.navigation,
2993                      config.screenWidth,
2994                      config.screenHeight,
2995                      config.smallestScreenWidthDp,
2996                      config.screenWidthDp,
2997                      config.screenHeightDp,
2998                      config.layoutDirection));
2999
3000                if (filterable && !filter->match(config)) {
3001                    continue;
3002                }
3003
3004                const size_t typeStart = data->getSize();
3005
3006                ResTable_type* tHeader = (ResTable_type*)
3007                    (((uint8_t*)data->editData(typeStart+typeSize)) + typeStart);
3008                if (tHeader == NULL) {
3009                    fprintf(stderr, "ERROR: out of memory creating ResTable_type\n");
3010                    return NO_MEMORY;
3011                }
3012
3013                memset(tHeader, 0, sizeof(*tHeader));
3014                tHeader->header.type = htods(RES_TABLE_TYPE_TYPE);
3015                tHeader->header.headerSize = htods(sizeof(*tHeader));
3016                tHeader->id = ti+1;
3017                tHeader->entryCount = htodl(N);
3018                tHeader->entriesStart = htodl(typeSize);
3019                tHeader->config = config;
3020                NOISY(printf("Writing type %d config: imsi:%d/%d lang:%c%c cnt:%c%c "
3021                     "orien:%d ui:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d "
3022                     "sw%ddp w%ddp h%ddp dir:%d\n",
3023                      ti+1,
3024                      tHeader->config.mcc, tHeader->config.mnc,
3025                      tHeader->config.language[0] ? tHeader->config.language[0] : '-',
3026                      tHeader->config.language[1] ? tHeader->config.language[1] : '-',
3027                      tHeader->config.country[0] ? tHeader->config.country[0] : '-',
3028                      tHeader->config.country[1] ? tHeader->config.country[1] : '-',
3029                      tHeader->config.orientation,
3030                      tHeader->config.uiMode,
3031                      tHeader->config.touchscreen,
3032                      tHeader->config.density,
3033                      tHeader->config.keyboard,
3034                      tHeader->config.inputFlags,
3035                      tHeader->config.navigation,
3036                      tHeader->config.screenWidth,
3037                      tHeader->config.screenHeight,
3038                      tHeader->config.smallestScreenWidthDp,
3039                      tHeader->config.screenWidthDp,
3040                      tHeader->config.screenHeightDp,
3041                      tHeader->config.layoutDirection));
3042                tHeader->config.swapHtoD();
3043
3044                // Build the entries inside of this type.
3045                for (size_t ei=0; ei<N; ei++) {
3046                    sp<ConfigList> cl = t->getOrderedConfigs().itemAt(ei);
3047                    sp<Entry> e = cl->getEntries().valueFor(config);
3048
3049                    // Set the offset for this entry in its type.
3050                    uint32_t* index = (uint32_t*)
3051                        (((uint8_t*)data->editData())
3052                            + typeStart + sizeof(ResTable_type));
3053                    if (e != NULL) {
3054                        index[ei] = htodl(data->getSize()-typeStart-typeSize);
3055
3056                        // Create the entry.
3057                        ssize_t amt = e->flatten(bundle, data, cl->getPublic());
3058                        if (amt < 0) {
3059                            return amt;
3060                        }
3061                        validResources.editItemAt(ei) = true;
3062                    } else {
3063                        index[ei] = htodl(ResTable_type::NO_ENTRY);
3064                    }
3065                }
3066
3067                // Fill in the rest of the type information.
3068                tHeader = (ResTable_type*)
3069                    (((uint8_t*)data->editData()) + typeStart);
3070                tHeader->header.size = htodl(data->getSize()-typeStart);
3071            }
3072
3073            // If we're building splits, then each invocation of the flattening
3074            // step will have 'missing' entries. Don't warn/error for this case.
3075            if (bundle->getSplitConfigurations().isEmpty()) {
3076                bool missing_entry = false;
3077                const char* log_prefix = bundle->getErrorOnMissingConfigEntry() ?
3078                        "error" : "warning";
3079                for (size_t i = 0; i < N; ++i) {
3080                    if (!validResources[i]) {
3081                        sp<ConfigList> c = t->getOrderedConfigs().itemAt(i);
3082                        fprintf(stderr, "%s: no entries written for %s/%s (0x%08x)\n", log_prefix,
3083                                String8(typeName).string(), String8(c->getName()).string(),
3084                                Res_MAKEID(p->getAssignedId() - 1, ti, i));
3085                        missing_entry = true;
3086                    }
3087                }
3088                if (bundle->getErrorOnMissingConfigEntry() && missing_entry) {
3089                    fprintf(stderr, "Error: Missing entries, quit!\n");
3090                    return NOT_ENOUGH_DATA;
3091                }
3092            }
3093        }
3094
3095        // Fill in the rest of the package information.
3096        header = (ResTable_package*)data->editData();
3097        header->header.size = htodl(data->getSize());
3098        header->typeStrings = htodl(typeStringsStart);
3099        header->lastPublicType = htodl(p->getTypeStrings().size());
3100        header->keyStrings = htodl(keyStringsStart);
3101        header->lastPublicKey = htodl(p->getKeyStrings().size());
3102
3103        flatPackages.add(data);
3104    }
3105
3106    // And now write out the final chunks.
3107    const size_t dataStart = dest->getSize();
3108
3109    {
3110        // blah
3111        ResTable_header header;
3112        memset(&header, 0, sizeof(header));
3113        header.header.type = htods(RES_TABLE_TYPE);
3114        header.header.headerSize = htods(sizeof(header));
3115        header.packageCount = htodl(flatPackages.size());
3116        status_t err = dest->writeData(&header, sizeof(header));
3117        if (err != NO_ERROR) {
3118            fprintf(stderr, "ERROR: out of memory creating ResTable_header\n");
3119            return err;
3120        }
3121    }
3122
3123    ssize_t strStart = dest->getSize();
3124    status_t err = valueStrings.writeStringBlock(dest);
3125    if (err != NO_ERROR) {
3126        return err;
3127    }
3128
3129    ssize_t amt = (dest->getSize()-strStart);
3130    strAmt += amt;
3131    #if PRINT_STRING_METRICS
3132    fprintf(stderr, "**** value strings: %d\n", amt);
3133    fprintf(stderr, "**** total strings: %d\n", strAmt);
3134    #endif
3135
3136    for (pi=0; pi<flatPackages.size(); pi++) {
3137        err = dest->writeData(flatPackages[pi]->getData(),
3138                              flatPackages[pi]->getSize());
3139        if (err != NO_ERROR) {
3140            fprintf(stderr, "ERROR: out of memory creating package chunk for ResTable_header\n");
3141            return err;
3142        }
3143    }
3144
3145    ResTable_header* header = (ResTable_header*)
3146        (((uint8_t*)dest->getData()) + dataStart);
3147    header->header.size = htodl(dest->getSize() - dataStart);
3148
3149    NOISY(aout << "Resource table:"
3150          << HexDump(dest->getData(), dest->getSize()) << endl);
3151
3152    #if PRINT_STRING_METRICS
3153    fprintf(stderr, "**** total resource table size: %d / %d%% strings\n",
3154        dest->getSize(), (strAmt*100)/dest->getSize());
3155    #endif
3156
3157    return NO_ERROR;
3158}
3159
3160status_t ResourceTable::flattenLibraryTable(const sp<AaptFile>& dest, const Vector<sp<Package> >& libs) {
3161    // Write out the library table if necessary
3162    if (libs.size() > 0) {
3163        NOISY(fprintf(stderr, "Writing library reference table\n"));
3164
3165        const size_t libStart = dest->getSize();
3166        const size_t count = libs.size();
3167        ResTable_lib_header* libHeader = (ResTable_lib_header*) dest->editDataInRange(
3168                libStart, sizeof(ResTable_lib_header));
3169
3170        memset(libHeader, 0, sizeof(*libHeader));
3171        libHeader->header.type = htods(RES_TABLE_LIBRARY_TYPE);
3172        libHeader->header.headerSize = htods(sizeof(*libHeader));
3173        libHeader->header.size = htodl(sizeof(*libHeader) + (sizeof(ResTable_lib_entry) * count));
3174        libHeader->count = htodl(count);
3175
3176        // Write the library entries
3177        for (size_t i = 0; i < count; i++) {
3178            const size_t entryStart = dest->getSize();
3179            sp<Package> libPackage = libs[i];
3180            NOISY(fprintf(stderr, "  Entry %s -> 0x%02x\n",
3181                        String8(libPackage->getName()).string(),
3182                        (uint8_t)libPackage->getAssignedId()));
3183
3184            ResTable_lib_entry* entry = (ResTable_lib_entry*) dest->editDataInRange(
3185                    entryStart, sizeof(ResTable_lib_entry));
3186            memset(entry, 0, sizeof(*entry));
3187            entry->packageId = htodl(libPackage->getAssignedId());
3188            strcpy16_htod(entry->packageName, libPackage->getName().string());
3189        }
3190    }
3191    return NO_ERROR;
3192}
3193
3194void ResourceTable::writePublicDefinitions(const String16& package, FILE* fp)
3195{
3196    fprintf(fp,
3197    "<!-- This file contains <public> resource definitions for all\n"
3198    "     resources that were generated from the source data. -->\n"
3199    "\n"
3200    "<resources>\n");
3201
3202    writePublicDefinitions(package, fp, true);
3203    writePublicDefinitions(package, fp, false);
3204
3205    fprintf(fp,
3206    "\n"
3207    "</resources>\n");
3208}
3209
3210void ResourceTable::writePublicDefinitions(const String16& package, FILE* fp, bool pub)
3211{
3212    bool didHeader = false;
3213
3214    sp<Package> pkg = mPackages.valueFor(package);
3215    if (pkg != NULL) {
3216        const size_t NT = pkg->getOrderedTypes().size();
3217        for (size_t i=0; i<NT; i++) {
3218            sp<Type> t = pkg->getOrderedTypes().itemAt(i);
3219            if (t == NULL) {
3220                continue;
3221            }
3222
3223            bool didType = false;
3224
3225            const size_t NC = t->getOrderedConfigs().size();
3226            for (size_t j=0; j<NC; j++) {
3227                sp<ConfigList> c = t->getOrderedConfigs().itemAt(j);
3228                if (c == NULL) {
3229                    continue;
3230                }
3231
3232                if (c->getPublic() != pub) {
3233                    continue;
3234                }
3235
3236                if (!didType) {
3237                    fprintf(fp, "\n");
3238                    didType = true;
3239                }
3240                if (!didHeader) {
3241                    if (pub) {
3242                        fprintf(fp,"  <!-- PUBLIC SECTION.  These resources have been declared public.\n");
3243                        fprintf(fp,"       Changes to these definitions will break binary compatibility. -->\n\n");
3244                    } else {
3245                        fprintf(fp,"  <!-- PRIVATE SECTION.  These resources have not been declared public.\n");
3246                        fprintf(fp,"       You can make them public my moving these lines into a file in res/values. -->\n\n");
3247                    }
3248                    didHeader = true;
3249                }
3250                if (!pub) {
3251                    const size_t NE = c->getEntries().size();
3252                    for (size_t k=0; k<NE; k++) {
3253                        const SourcePos& pos = c->getEntries().valueAt(k)->getPos();
3254                        if (pos.file != "") {
3255                            fprintf(fp,"  <!-- Declared at %s:%d -->\n",
3256                                    pos.file.string(), pos.line);
3257                        }
3258                    }
3259                }
3260                fprintf(fp, "  <public type=\"%s\" name=\"%s\" id=\"0x%08x\" />\n",
3261                        String8(t->getName()).string(),
3262                        String8(c->getName()).string(),
3263                        getResId(pkg, t, c->getEntryIndex()));
3264            }
3265        }
3266    }
3267}
3268
3269ResourceTable::Item::Item(const SourcePos& _sourcePos,
3270                          bool _isId,
3271                          const String16& _value,
3272                          const Vector<StringPool::entry_style_span>* _style,
3273                          int32_t _format)
3274    : sourcePos(_sourcePos)
3275    , isId(_isId)
3276    , value(_value)
3277    , format(_format)
3278    , bagKeyId(0)
3279    , evaluating(false)
3280{
3281    if (_style) {
3282        style = *_style;
3283    }
3284}
3285
3286status_t ResourceTable::Entry::makeItABag(const SourcePos& sourcePos)
3287{
3288    if (mType == TYPE_BAG) {
3289        return NO_ERROR;
3290    }
3291    if (mType == TYPE_UNKNOWN) {
3292        mType = TYPE_BAG;
3293        return NO_ERROR;
3294    }
3295    sourcePos.error("Resource entry %s is already defined as a single item.\n"
3296                    "%s:%d: Originally defined here.\n",
3297                    String8(mName).string(),
3298                    mItem.sourcePos.file.string(), mItem.sourcePos.line);
3299    return UNKNOWN_ERROR;
3300}
3301
3302status_t ResourceTable::Entry::setItem(const SourcePos& sourcePos,
3303                                       const String16& value,
3304                                       const Vector<StringPool::entry_style_span>* style,
3305                                       int32_t format,
3306                                       const bool overwrite)
3307{
3308    Item item(sourcePos, false, value, style);
3309
3310    if (mType == TYPE_BAG) {
3311        if (mBag.size() == 0) {
3312            sourcePos.error("Resource entry %s is already defined as a bag.",
3313                    String8(mName).string());
3314        } else {
3315            const Item& item(mBag.valueAt(0));
3316            sourcePos.error("Resource entry %s is already defined as a bag.\n"
3317                            "%s:%d: Originally defined here.\n",
3318                            String8(mName).string(),
3319                            item.sourcePos.file.string(), item.sourcePos.line);
3320        }
3321        return UNKNOWN_ERROR;
3322    }
3323    if ( (mType != TYPE_UNKNOWN) && (overwrite == false) ) {
3324        sourcePos.error("Resource entry %s is already defined.\n"
3325                        "%s:%d: Originally defined here.\n",
3326                        String8(mName).string(),
3327                        mItem.sourcePos.file.string(), mItem.sourcePos.line);
3328        return UNKNOWN_ERROR;
3329    }
3330
3331    mType = TYPE_ITEM;
3332    mItem = item;
3333    mItemFormat = format;
3334    return NO_ERROR;
3335}
3336
3337status_t ResourceTable::Entry::addToBag(const SourcePos& sourcePos,
3338                                        const String16& key, const String16& value,
3339                                        const Vector<StringPool::entry_style_span>* style,
3340                                        bool replace, bool isId, int32_t format)
3341{
3342    status_t err = makeItABag(sourcePos);
3343    if (err != NO_ERROR) {
3344        return err;
3345    }
3346
3347    Item item(sourcePos, isId, value, style, format);
3348
3349    // XXX NOTE: there is an error if you try to have a bag with two keys,
3350    // one an attr and one an id, with the same name.  Not something we
3351    // currently ever have to worry about.
3352    ssize_t origKey = mBag.indexOfKey(key);
3353    if (origKey >= 0) {
3354        if (!replace) {
3355            const Item& item(mBag.valueAt(origKey));
3356            sourcePos.error("Resource entry %s already has bag item %s.\n"
3357                    "%s:%d: Originally defined here.\n",
3358                    String8(mName).string(), String8(key).string(),
3359                    item.sourcePos.file.string(), item.sourcePos.line);
3360            return UNKNOWN_ERROR;
3361        }
3362        //printf("Replacing %s with %s\n",
3363        //       String8(mBag.valueFor(key).value).string(), String8(value).string());
3364        mBag.replaceValueFor(key, item);
3365    }
3366
3367    mBag.add(key, item);
3368    return NO_ERROR;
3369}
3370
3371status_t ResourceTable::Entry::emptyBag(const SourcePos& sourcePos)
3372{
3373    status_t err = makeItABag(sourcePos);
3374    if (err != NO_ERROR) {
3375        return err;
3376    }
3377
3378    mBag.clear();
3379    return NO_ERROR;
3380}
3381
3382status_t ResourceTable::Entry::generateAttributes(ResourceTable* table,
3383                                                  const String16& package)
3384{
3385    const String16 attr16("attr");
3386    const String16 id16("id");
3387    const size_t N = mBag.size();
3388    for (size_t i=0; i<N; i++) {
3389        const String16& key = mBag.keyAt(i);
3390        const Item& it = mBag.valueAt(i);
3391        if (it.isId) {
3392            if (!table->hasBagOrEntry(key, &id16, &package)) {
3393                String16 value("false");
3394                NOISY(fprintf(stderr, "Generating %s:id/%s\n",
3395                        String8(package).string(),
3396                        String8(key).string()));
3397                status_t err = table->addEntry(SourcePos(String8("<generated>"), 0), package,
3398                                               id16, key, value);
3399                if (err != NO_ERROR) {
3400                    return err;
3401                }
3402            }
3403        } else if (!table->hasBagOrEntry(key, &attr16, &package)) {
3404
3405#if 1
3406//             fprintf(stderr, "ERROR: Bag attribute '%s' has not been defined.\n",
3407//                     String8(key).string());
3408//             const Item& item(mBag.valueAt(i));
3409//             fprintf(stderr, "Referenced from file %s line %d\n",
3410//                     item.sourcePos.file.string(), item.sourcePos.line);
3411//             return UNKNOWN_ERROR;
3412#else
3413            char numberStr[16];
3414            sprintf(numberStr, "%d", ResTable_map::TYPE_ANY);
3415            status_t err = table->addBag(SourcePos("<generated>", 0), package,
3416                                         attr16, key, String16(""),
3417                                         String16("^type"),
3418                                         String16(numberStr), NULL, NULL);
3419            if (err != NO_ERROR) {
3420                return err;
3421            }
3422#endif
3423        }
3424    }
3425    return NO_ERROR;
3426}
3427
3428status_t ResourceTable::Entry::assignResourceIds(ResourceTable* table,
3429                                                 const String16& package)
3430{
3431    bool hasErrors = false;
3432
3433    if (mType == TYPE_BAG) {
3434        const char* errorMsg;
3435        const String16 style16("style");
3436        const String16 attr16("attr");
3437        const String16 id16("id");
3438        mParentId = 0;
3439        if (mParent.size() > 0) {
3440            mParentId = table->getResId(mParent, &style16, NULL, &errorMsg);
3441            if (mParentId == 0) {
3442                mPos.error("Error retrieving parent for item: %s '%s'.\n",
3443                        errorMsg, String8(mParent).string());
3444                hasErrors = true;
3445            }
3446        }
3447        const size_t N = mBag.size();
3448        for (size_t i=0; i<N; i++) {
3449            const String16& key = mBag.keyAt(i);
3450            Item& it = mBag.editValueAt(i);
3451            it.bagKeyId = table->getResId(key,
3452                    it.isId ? &id16 : &attr16, NULL, &errorMsg);
3453            //printf("Bag key of %s: #%08x\n", String8(key).string(), it.bagKeyId);
3454            if (it.bagKeyId == 0) {
3455                it.sourcePos.error("Error: %s: %s '%s'.\n", errorMsg,
3456                        String8(it.isId ? id16 : attr16).string(),
3457                        String8(key).string());
3458                hasErrors = true;
3459            }
3460        }
3461    }
3462    return hasErrors ? UNKNOWN_ERROR : NO_ERROR;
3463}
3464
3465status_t ResourceTable::Entry::prepareFlatten(StringPool* strings, ResourceTable* table,
3466        const String8* configTypeName, const ConfigDescription* config)
3467{
3468    if (mType == TYPE_ITEM) {
3469        Item& it = mItem;
3470        AccessorCookie ac(it.sourcePos, String8(mName), String8(it.value));
3471        if (!table->stringToValue(&it.parsedValue, strings,
3472                                  it.value, false, true, 0,
3473                                  &it.style, NULL, &ac, mItemFormat,
3474                                  configTypeName, config)) {
3475            return UNKNOWN_ERROR;
3476        }
3477    } else if (mType == TYPE_BAG) {
3478        const size_t N = mBag.size();
3479        for (size_t i=0; i<N; i++) {
3480            const String16& key = mBag.keyAt(i);
3481            Item& it = mBag.editValueAt(i);
3482            AccessorCookie ac(it.sourcePos, String8(key), String8(it.value));
3483            if (!table->stringToValue(&it.parsedValue, strings,
3484                                      it.value, false, true, it.bagKeyId,
3485                                      &it.style, NULL, &ac, it.format,
3486                                      configTypeName, config)) {
3487                return UNKNOWN_ERROR;
3488            }
3489        }
3490    } else {
3491        mPos.error("Error: entry %s is not a single item or a bag.\n",
3492                   String8(mName).string());
3493        return UNKNOWN_ERROR;
3494    }
3495    return NO_ERROR;
3496}
3497
3498status_t ResourceTable::Entry::remapStringValue(StringPool* strings)
3499{
3500    if (mType == TYPE_ITEM) {
3501        Item& it = mItem;
3502        if (it.parsedValue.dataType == Res_value::TYPE_STRING) {
3503            it.parsedValue.data = strings->mapOriginalPosToNewPos(it.parsedValue.data);
3504        }
3505    } else if (mType == TYPE_BAG) {
3506        const size_t N = mBag.size();
3507        for (size_t i=0; i<N; i++) {
3508            Item& it = mBag.editValueAt(i);
3509            if (it.parsedValue.dataType == Res_value::TYPE_STRING) {
3510                it.parsedValue.data = strings->mapOriginalPosToNewPos(it.parsedValue.data);
3511            }
3512        }
3513    } else {
3514        mPos.error("Error: entry %s is not a single item or a bag.\n",
3515                   String8(mName).string());
3516        return UNKNOWN_ERROR;
3517    }
3518    return NO_ERROR;
3519}
3520
3521ssize_t ResourceTable::Entry::flatten(Bundle* bundle, const sp<AaptFile>& data, bool isPublic)
3522{
3523    size_t amt = 0;
3524    ResTable_entry header;
3525    memset(&header, 0, sizeof(header));
3526    header.size = htods(sizeof(header));
3527    const type ty = this != NULL ? mType : TYPE_ITEM;
3528    if (this != NULL) {
3529        if (ty == TYPE_BAG) {
3530            header.flags |= htods(header.FLAG_COMPLEX);
3531        }
3532        if (isPublic) {
3533            header.flags |= htods(header.FLAG_PUBLIC);
3534        }
3535        header.key.index = htodl(mNameIndex);
3536    }
3537    if (ty != TYPE_BAG) {
3538        status_t err = data->writeData(&header, sizeof(header));
3539        if (err != NO_ERROR) {
3540            fprintf(stderr, "ERROR: out of memory creating ResTable_entry\n");
3541            return err;
3542        }
3543
3544        const Item& it = mItem;
3545        Res_value par;
3546        memset(&par, 0, sizeof(par));
3547        par.size = htods(it.parsedValue.size);
3548        par.dataType = it.parsedValue.dataType;
3549        par.res0 = it.parsedValue.res0;
3550        par.data = htodl(it.parsedValue.data);
3551        #if 0
3552        printf("Writing item (%s): type=%d, data=0x%x, res0=0x%x\n",
3553               String8(mName).string(), it.parsedValue.dataType,
3554               it.parsedValue.data, par.res0);
3555        #endif
3556        err = data->writeData(&par, it.parsedValue.size);
3557        if (err != NO_ERROR) {
3558            fprintf(stderr, "ERROR: out of memory creating Res_value\n");
3559            return err;
3560        }
3561        amt += it.parsedValue.size;
3562    } else {
3563        size_t N = mBag.size();
3564        size_t i;
3565        // Create correct ordering of items.
3566        KeyedVector<uint32_t, const Item*> items;
3567        for (i=0; i<N; i++) {
3568            const Item& it = mBag.valueAt(i);
3569            items.add(it.bagKeyId, &it);
3570        }
3571        N = items.size();
3572
3573        ResTable_map_entry mapHeader;
3574        memcpy(&mapHeader, &header, sizeof(header));
3575        mapHeader.size = htods(sizeof(mapHeader));
3576        mapHeader.parent.ident = htodl(mParentId);
3577        mapHeader.count = htodl(N);
3578        status_t err = data->writeData(&mapHeader, sizeof(mapHeader));
3579        if (err != NO_ERROR) {
3580            fprintf(stderr, "ERROR: out of memory creating ResTable_entry\n");
3581            return err;
3582        }
3583
3584        for (i=0; i<N; i++) {
3585            const Item& it = *items.valueAt(i);
3586            ResTable_map map;
3587            map.name.ident = htodl(it.bagKeyId);
3588            map.value.size = htods(it.parsedValue.size);
3589            map.value.dataType = it.parsedValue.dataType;
3590            map.value.res0 = it.parsedValue.res0;
3591            map.value.data = htodl(it.parsedValue.data);
3592            err = data->writeData(&map, sizeof(map));
3593            if (err != NO_ERROR) {
3594                fprintf(stderr, "ERROR: out of memory creating Res_value\n");
3595                return err;
3596            }
3597            amt += sizeof(map);
3598        }
3599    }
3600    return amt;
3601}
3602
3603void ResourceTable::ConfigList::appendComment(const String16& comment,
3604                                              bool onlyIfEmpty)
3605{
3606    if (comment.size() <= 0) {
3607        return;
3608    }
3609    if (onlyIfEmpty && mComment.size() > 0) {
3610        return;
3611    }
3612    if (mComment.size() > 0) {
3613        mComment.append(String16("\n"));
3614    }
3615    mComment.append(comment);
3616}
3617
3618void ResourceTable::ConfigList::appendTypeComment(const String16& comment)
3619{
3620    if (comment.size() <= 0) {
3621        return;
3622    }
3623    if (mTypeComment.size() > 0) {
3624        mTypeComment.append(String16("\n"));
3625    }
3626    mTypeComment.append(comment);
3627}
3628
3629status_t ResourceTable::Type::addPublic(const SourcePos& sourcePos,
3630                                        const String16& name,
3631                                        const uint32_t ident)
3632{
3633    #if 0
3634    int32_t entryIdx = Res_GETENTRY(ident);
3635    if (entryIdx < 0) {
3636        sourcePos.error("Public resource %s/%s has an invalid 0 identifier (0x%08x).\n",
3637                String8(mName).string(), String8(name).string(), ident);
3638        return UNKNOWN_ERROR;
3639    }
3640    #endif
3641
3642    int32_t typeIdx = Res_GETTYPE(ident);
3643    if (typeIdx >= 0) {
3644        typeIdx++;
3645        if (mPublicIndex > 0 && mPublicIndex != typeIdx) {
3646            sourcePos.error("Public resource %s/%s has conflicting type codes for its"
3647                    " public identifiers (0x%x vs 0x%x).\n",
3648                    String8(mName).string(), String8(name).string(),
3649                    mPublicIndex, typeIdx);
3650            return UNKNOWN_ERROR;
3651        }
3652        mPublicIndex = typeIdx;
3653    }
3654
3655    if (mFirstPublicSourcePos == NULL) {
3656        mFirstPublicSourcePos = new SourcePos(sourcePos);
3657    }
3658
3659    if (mPublic.indexOfKey(name) < 0) {
3660        mPublic.add(name, Public(sourcePos, String16(), ident));
3661    } else {
3662        Public& p = mPublic.editValueFor(name);
3663        if (p.ident != ident) {
3664            sourcePos.error("Public resource %s/%s has conflicting public identifiers"
3665                    " (0x%08x vs 0x%08x).\n"
3666                    "%s:%d: Originally defined here.\n",
3667                    String8(mName).string(), String8(name).string(), p.ident, ident,
3668                    p.sourcePos.file.string(), p.sourcePos.line);
3669            return UNKNOWN_ERROR;
3670        }
3671    }
3672
3673    return NO_ERROR;
3674}
3675
3676void ResourceTable::Type::canAddEntry(const String16& name)
3677{
3678    mCanAddEntries.add(name);
3679}
3680
3681sp<ResourceTable::Entry> ResourceTable::Type::getEntry(const String16& entry,
3682                                                       const SourcePos& sourcePos,
3683                                                       const ResTable_config* config,
3684                                                       bool doSetIndex,
3685                                                       bool overlay,
3686                                                       bool autoAddOverlay)
3687{
3688    int pos = -1;
3689    sp<ConfigList> c = mConfigs.valueFor(entry);
3690    if (c == NULL) {
3691        if (overlay && !autoAddOverlay && mCanAddEntries.indexOf(entry) < 0) {
3692            sourcePos.error("Resource at %s appears in overlay but not"
3693                            " in the base package; use <add-resource> to add.\n",
3694                            String8(entry).string());
3695            return NULL;
3696        }
3697        c = new ConfigList(entry, sourcePos);
3698        mConfigs.add(entry, c);
3699        pos = (int)mOrderedConfigs.size();
3700        mOrderedConfigs.add(c);
3701        if (doSetIndex) {
3702            c->setEntryIndex(pos);
3703        }
3704    }
3705
3706    ConfigDescription cdesc;
3707    if (config) cdesc = *config;
3708
3709    sp<Entry> e = c->getEntries().valueFor(cdesc);
3710    if (e == NULL) {
3711        if (config != NULL) {
3712            NOISY(printf("New entry at %s:%d: imsi:%d/%d lang:%c%c cnt:%c%c "
3713                    "orien:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d "
3714                    "sw%ddp w%ddp h%ddp dir:%d\n",
3715                      sourcePos.file.string(), sourcePos.line,
3716                      config->mcc, config->mnc,
3717                      config->language[0] ? config->language[0] : '-',
3718                      config->language[1] ? config->language[1] : '-',
3719                      config->country[0] ? config->country[0] : '-',
3720                      config->country[1] ? config->country[1] : '-',
3721                      config->orientation,
3722                      config->touchscreen,
3723                      config->density,
3724                      config->keyboard,
3725                      config->inputFlags,
3726                      config->navigation,
3727                      config->screenWidth,
3728                      config->screenHeight,
3729                      config->smallestScreenWidthDp,
3730                      config->screenWidthDp,
3731                      config->screenHeightDp,
3732                      config->layoutDirection));
3733        } else {
3734            NOISY(printf("New entry at %s:%d: NULL config\n",
3735                      sourcePos.file.string(), sourcePos.line));
3736        }
3737        e = new Entry(entry, sourcePos);
3738        c->addEntry(cdesc, e);
3739        /*
3740        if (doSetIndex) {
3741            if (pos < 0) {
3742                for (pos=0; pos<(int)mOrderedConfigs.size(); pos++) {
3743                    if (mOrderedConfigs[pos] == c) {
3744                        break;
3745                    }
3746                }
3747                if (pos >= (int)mOrderedConfigs.size()) {
3748                    sourcePos.error("Internal error: config not found in mOrderedConfigs when adding entry");
3749                    return NULL;
3750                }
3751            }
3752            e->setEntryIndex(pos);
3753        }
3754        */
3755    }
3756
3757    mUniqueConfigs.add(cdesc);
3758
3759    return e;
3760}
3761
3762status_t ResourceTable::Type::applyPublicEntryOrder()
3763{
3764    size_t N = mOrderedConfigs.size();
3765    Vector<sp<ConfigList> > origOrder(mOrderedConfigs);
3766    bool hasError = false;
3767
3768    size_t i;
3769    for (i=0; i<N; i++) {
3770        mOrderedConfigs.replaceAt(NULL, i);
3771    }
3772
3773    const size_t NP = mPublic.size();
3774    //printf("Ordering %d configs from %d public defs\n", N, NP);
3775    size_t j;
3776    for (j=0; j<NP; j++) {
3777        const String16& name = mPublic.keyAt(j);
3778        const Public& p = mPublic.valueAt(j);
3779        int32_t idx = Res_GETENTRY(p.ident);
3780        //printf("Looking for entry \"%s\"/\"%s\" (0x%08x) in %d...\n",
3781        //       String8(mName).string(), String8(name).string(), p.ident, N);
3782        bool found = false;
3783        for (i=0; i<N; i++) {
3784            sp<ConfigList> e = origOrder.itemAt(i);
3785            //printf("#%d: \"%s\"\n", i, String8(e->getName()).string());
3786            if (e->getName() == name) {
3787                if (idx >= (int32_t)mOrderedConfigs.size()) {
3788                    p.sourcePos.error("Public entry identifier 0x%x entry index "
3789                            "is larger than available symbols (index %d, total symbols %d).\n",
3790                            p.ident, idx, mOrderedConfigs.size());
3791                    hasError = true;
3792                } else if (mOrderedConfigs.itemAt(idx) == NULL) {
3793                    e->setPublic(true);
3794                    e->setPublicSourcePos(p.sourcePos);
3795                    mOrderedConfigs.replaceAt(e, idx);
3796                    origOrder.removeAt(i);
3797                    N--;
3798                    found = true;
3799                    break;
3800                } else {
3801                    sp<ConfigList> oe = mOrderedConfigs.itemAt(idx);
3802
3803                    p.sourcePos.error("Multiple entry names declared for public entry"
3804                            " identifier 0x%x in type %s (%s vs %s).\n"
3805                            "%s:%d: Originally defined here.",
3806                            idx+1, String8(mName).string(),
3807                            String8(oe->getName()).string(),
3808                            String8(name).string(),
3809                            oe->getPublicSourcePos().file.string(),
3810                            oe->getPublicSourcePos().line);
3811                    hasError = true;
3812                }
3813            }
3814        }
3815
3816        if (!found) {
3817            p.sourcePos.error("Public symbol %s/%s declared here is not defined.",
3818                    String8(mName).string(), String8(name).string());
3819            hasError = true;
3820        }
3821    }
3822
3823    //printf("Copying back in %d non-public configs, have %d\n", N, origOrder.size());
3824
3825    if (N != origOrder.size()) {
3826        printf("Internal error: remaining private symbol count mismatch\n");
3827        N = origOrder.size();
3828    }
3829
3830    j = 0;
3831    for (i=0; i<N; i++) {
3832        sp<ConfigList> e = origOrder.itemAt(i);
3833        // There will always be enough room for the remaining entries.
3834        while (mOrderedConfigs.itemAt(j) != NULL) {
3835            j++;
3836        }
3837        mOrderedConfigs.replaceAt(e, j);
3838        j++;
3839    }
3840
3841    return hasError ? UNKNOWN_ERROR : NO_ERROR;
3842}
3843
3844ResourceTable::Package::Package(const String16& name, size_t packageId)
3845    : mName(name), mPackageId(packageId),
3846      mTypeStringsMapping(0xffffffff),
3847      mKeyStringsMapping(0xffffffff)
3848{
3849}
3850
3851sp<ResourceTable::Type> ResourceTable::Package::getType(const String16& type,
3852                                                        const SourcePos& sourcePos,
3853                                                        bool doSetIndex)
3854{
3855    sp<Type> t = mTypes.valueFor(type);
3856    if (t == NULL) {
3857        t = new Type(type, sourcePos);
3858        mTypes.add(type, t);
3859        mOrderedTypes.add(t);
3860        if (doSetIndex) {
3861            // For some reason the type's index is set to one plus the index
3862            // in the mOrderedTypes list, rather than just the index.
3863            t->setIndex(mOrderedTypes.size());
3864        }
3865    }
3866    return t;
3867}
3868
3869status_t ResourceTable::Package::setTypeStrings(const sp<AaptFile>& data)
3870{
3871    status_t err = setStrings(data, &mTypeStrings, &mTypeStringsMapping);
3872    if (err != NO_ERROR) {
3873        fprintf(stderr, "ERROR: Type string data is corrupt!\n");
3874        return err;
3875    }
3876
3877    // Retain a reference to the new data after we've successfully replaced
3878    // all uses of the old reference (in setStrings() ).
3879    mTypeStringsData = data;
3880    return NO_ERROR;
3881}
3882
3883status_t ResourceTable::Package::setKeyStrings(const sp<AaptFile>& data)
3884{
3885    status_t err = setStrings(data, &mKeyStrings, &mKeyStringsMapping);
3886    if (err != NO_ERROR) {
3887        fprintf(stderr, "ERROR: Key string data is corrupt!\n");
3888        return err;
3889    }
3890
3891    // Retain a reference to the new data after we've successfully replaced
3892    // all uses of the old reference (in setStrings() ).
3893    mKeyStringsData = data;
3894    return NO_ERROR;
3895}
3896
3897status_t ResourceTable::Package::setStrings(const sp<AaptFile>& data,
3898                                            ResStringPool* strings,
3899                                            DefaultKeyedVector<String16, uint32_t>* mappings)
3900{
3901    if (data->getData() == NULL) {
3902        return UNKNOWN_ERROR;
3903    }
3904
3905    NOISY(aout << "Setting restable string pool: "
3906          << HexDump(data->getData(), data->getSize()) << endl);
3907
3908    status_t err = strings->setTo(data->getData(), data->getSize());
3909    if (err == NO_ERROR) {
3910        const size_t N = strings->size();
3911        for (size_t i=0; i<N; i++) {
3912            size_t len;
3913            mappings->add(String16(strings->stringAt(i, &len)), i);
3914        }
3915    }
3916    return err;
3917}
3918
3919status_t ResourceTable::Package::applyPublicTypeOrder()
3920{
3921    size_t N = mOrderedTypes.size();
3922    Vector<sp<Type> > origOrder(mOrderedTypes);
3923
3924    size_t i;
3925    for (i=0; i<N; i++) {
3926        mOrderedTypes.replaceAt(NULL, i);
3927    }
3928
3929    for (i=0; i<N; i++) {
3930        sp<Type> t = origOrder.itemAt(i);
3931        int32_t idx = t->getPublicIndex();
3932        if (idx > 0) {
3933            idx--;
3934            while (idx >= (int32_t)mOrderedTypes.size()) {
3935                mOrderedTypes.add();
3936            }
3937            if (mOrderedTypes.itemAt(idx) != NULL) {
3938                sp<Type> ot = mOrderedTypes.itemAt(idx);
3939                t->getFirstPublicSourcePos().error("Multiple type names declared for public type"
3940                        " identifier 0x%x (%s vs %s).\n"
3941                        "%s:%d: Originally defined here.",
3942                        idx, String8(ot->getName()).string(),
3943                        String8(t->getName()).string(),
3944                        ot->getFirstPublicSourcePos().file.string(),
3945                        ot->getFirstPublicSourcePos().line);
3946                return UNKNOWN_ERROR;
3947            }
3948            mOrderedTypes.replaceAt(t, idx);
3949            origOrder.removeAt(i);
3950            i--;
3951            N--;
3952        }
3953    }
3954
3955    size_t j=0;
3956    for (i=0; i<N; i++) {
3957        sp<Type> t = origOrder.itemAt(i);
3958        // There will always be enough room for the remaining types.
3959        while (mOrderedTypes.itemAt(j) != NULL) {
3960            j++;
3961        }
3962        mOrderedTypes.replaceAt(t, j);
3963    }
3964
3965    return NO_ERROR;
3966}
3967
3968sp<ResourceTable::Package> ResourceTable::getPackage(const String16& package)
3969{
3970    if (package != mAssetsPackage) {
3971        return NULL;
3972    }
3973    return mPackages.valueFor(package);
3974}
3975
3976sp<ResourceTable::Type> ResourceTable::getType(const String16& package,
3977                                               const String16& type,
3978                                               const SourcePos& sourcePos,
3979                                               bool doSetIndex)
3980{
3981    sp<Package> p = getPackage(package);
3982    if (p == NULL) {
3983        return NULL;
3984    }
3985    return p->getType(type, sourcePos, doSetIndex);
3986}
3987
3988sp<ResourceTable::Entry> ResourceTable::getEntry(const String16& package,
3989                                                 const String16& type,
3990                                                 const String16& name,
3991                                                 const SourcePos& sourcePos,
3992                                                 bool overlay,
3993                                                 const ResTable_config* config,
3994                                                 bool doSetIndex)
3995{
3996    sp<Type> t = getType(package, type, sourcePos, doSetIndex);
3997    if (t == NULL) {
3998        return NULL;
3999    }
4000    return t->getEntry(name, sourcePos, config, doSetIndex, overlay, mBundle->getAutoAddOverlay());
4001}
4002
4003sp<const ResourceTable::Entry> ResourceTable::getEntry(uint32_t resID,
4004                                                       const ResTable_config* config) const
4005{
4006    size_t pid = Res_GETPACKAGE(resID)+1;
4007    const size_t N = mOrderedPackages.size();
4008    sp<Package> p;
4009    for (size_t i = 0; i < N; i++) {
4010        sp<Package> check = mOrderedPackages[i];
4011        if (check->getAssignedId() == pid) {
4012            p = check;
4013            break;
4014        }
4015
4016    }
4017    if (p == NULL) {
4018        fprintf(stderr, "warning: Package not found for resource #%08x\n", resID);
4019        return NULL;
4020    }
4021
4022    int tid = Res_GETTYPE(resID);
4023    if (tid < 0 || tid >= (int)p->getOrderedTypes().size()) {
4024        fprintf(stderr, "warning: Type not found for resource #%08x\n", resID);
4025        return NULL;
4026    }
4027    sp<Type> t = p->getOrderedTypes()[tid];
4028
4029    int eid = Res_GETENTRY(resID);
4030    if (eid < 0 || eid >= (int)t->getOrderedConfigs().size()) {
4031        fprintf(stderr, "warning: Entry not found for resource #%08x\n", resID);
4032        return NULL;
4033    }
4034
4035    sp<ConfigList> c = t->getOrderedConfigs()[eid];
4036    if (c == NULL) {
4037        fprintf(stderr, "warning: Entry not found for resource #%08x\n", resID);
4038        return NULL;
4039    }
4040
4041    ConfigDescription cdesc;
4042    if (config) cdesc = *config;
4043    sp<Entry> e = c->getEntries().valueFor(cdesc);
4044    if (c == NULL) {
4045        fprintf(stderr, "warning: Entry configuration not found for resource #%08x\n", resID);
4046        return NULL;
4047    }
4048
4049    return e;
4050}
4051
4052const ResourceTable::Item* ResourceTable::getItem(uint32_t resID, uint32_t attrID) const
4053{
4054    sp<const Entry> e = getEntry(resID);
4055    if (e == NULL) {
4056        return NULL;
4057    }
4058
4059    const size_t N = e->getBag().size();
4060    for (size_t i=0; i<N; i++) {
4061        const Item& it = e->getBag().valueAt(i);
4062        if (it.bagKeyId == 0) {
4063            fprintf(stderr, "warning: ID not yet assigned to '%s' in bag '%s'\n",
4064                    String8(e->getName()).string(),
4065                    String8(e->getBag().keyAt(i)).string());
4066        }
4067        if (it.bagKeyId == attrID) {
4068            return &it;
4069        }
4070    }
4071
4072    return NULL;
4073}
4074
4075bool ResourceTable::getItemValue(
4076    uint32_t resID, uint32_t attrID, Res_value* outValue)
4077{
4078    const Item* item = getItem(resID, attrID);
4079
4080    bool res = false;
4081    if (item != NULL) {
4082        if (item->evaluating) {
4083            sp<const Entry> e = getEntry(resID);
4084            const size_t N = e->getBag().size();
4085            size_t i;
4086            for (i=0; i<N; i++) {
4087                if (&e->getBag().valueAt(i) == item) {
4088                    break;
4089                }
4090            }
4091            fprintf(stderr, "warning: Circular reference detected in key '%s' of bag '%s'\n",
4092                    String8(e->getName()).string(),
4093                    String8(e->getBag().keyAt(i)).string());
4094            return false;
4095        }
4096        item->evaluating = true;
4097        res = stringToValue(outValue, NULL, item->value, false, false, item->bagKeyId);
4098        NOISY(
4099            if (res) {
4100                printf("getItemValue of #%08x[#%08x] (%s): type=#%08x, data=#%08x\n",
4101                       resID, attrID, String8(getEntry(resID)->getName()).string(),
4102                       outValue->dataType, outValue->data);
4103            } else {
4104                printf("getItemValue of #%08x[#%08x]: failed\n",
4105                       resID, attrID);
4106            }
4107        );
4108        item->evaluating = false;
4109    }
4110    return res;
4111}
4112