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