BinaryResourceParser.cpp revision a6fe345be955368a13aea76aefb4db821aad11df
1/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "ResourceTable.h"
18#include "ResourceUtils.h"
19#include "ResourceValues.h"
20#include "Source.h"
21#include "ValueVisitor.h"
22
23#include "flatten/ResourceTypeExtensions.h"
24#include "unflatten/BinaryResourceParser.h"
25#include "unflatten/ResChunkPullParser.h"
26#include "util/Util.h"
27
28#include <androidfw/ResourceTypes.h>
29#include <androidfw/TypeWrappers.h>
30#include <android-base/macros.h>
31
32#include <map>
33#include <string>
34
35namespace aapt {
36
37using namespace android;
38
39/*
40 * Visitor that converts a reference's resource ID to a resource name,
41 * given a mapping from resource ID to resource name.
42 */
43class ReferenceIdToNameVisitor : public ValueVisitor {
44private:
45    const std::map<ResourceId, ResourceName>* mMapping;
46
47public:
48    using ValueVisitor::visit;
49
50    ReferenceIdToNameVisitor(const std::map<ResourceId, ResourceName>* mapping) :
51            mMapping(mapping) {
52        assert(mMapping);
53    }
54
55    void visit(Reference* reference) override {
56        if (!reference->id || !reference->id.value().isValid()) {
57            return;
58        }
59
60        ResourceId id = reference->id.value();
61        auto cacheIter = mMapping->find(id);
62        if (cacheIter != mMapping->end()) {
63            reference->name = cacheIter->second;
64            reference->id = {};
65        }
66    }
67};
68
69BinaryResourceParser::BinaryResourceParser(IAaptContext* context, ResourceTable* table,
70                                           const Source& source, const void* data, size_t len) :
71        mContext(context), mTable(table), mSource(source), mData(data), mDataLen(len) {
72}
73
74bool BinaryResourceParser::parse() {
75    ResChunkPullParser parser(mData, mDataLen);
76
77    bool error = false;
78    while(ResChunkPullParser::isGoodEvent(parser.next())) {
79        if (parser.getChunk()->type != android::RES_TABLE_TYPE) {
80            mContext->getDiagnostics()->warn(DiagMessage(mSource)
81                                             << "unknown chunk of type '"
82                                             << (int) parser.getChunk()->type << "'");
83            continue;
84        }
85
86        if (!parseTable(parser.getChunk())) {
87            error = true;
88        }
89    }
90
91    if (parser.getEvent() == ResChunkPullParser::Event::BadDocument) {
92        mContext->getDiagnostics()->error(DiagMessage(mSource)
93                                          << "corrupt resource table: "
94                                          << parser.getLastError());
95        return false;
96    }
97    return !error;
98}
99
100Maybe<Reference> BinaryResourceParser::getSymbol(const void* data) {
101    if (!mSymbolEntries || mSymbolEntryCount == 0) {
102        return {};
103    }
104
105    if ((uintptr_t) data < (uintptr_t) mData) {
106        return {};
107    }
108
109    // We only support 32 bit offsets right now.
110    const uintptr_t offset = (uintptr_t) data - (uintptr_t) mData;
111    if (offset > std::numeric_limits<uint32_t>::max()) {
112        return {};
113    }
114
115    for (size_t i = 0; i < mSymbolEntryCount; i++) {
116        if (util::deviceToHost32(mSymbolEntries[i].offset) == offset) {
117            // This offset is a symbol!
118            const StringPiece16 str = util::getString(
119                    mSymbolPool, util::deviceToHost32(mSymbolEntries[i].name.index));
120
121            ResourceNameRef nameRef;
122            bool privateRef = false;
123            if (!ResourceUtils::parseResourceName(str, &nameRef, &privateRef)) {
124                return {};
125            }
126
127            // Since we scan the symbol table in order, we can start looking for the
128            // next symbol from this point.
129            mSymbolEntryCount -= i + 1;
130            mSymbolEntries += i + 1;
131
132            Reference ref(nameRef);
133            ref.privateReference = privateRef;
134            return Maybe<Reference>(std::move(ref));
135        }
136    }
137    return {};
138}
139
140/**
141 * Parses the SymbolTable_header, which is present on non-final resource tables
142 * after the compile phase.
143 *
144 * | SymbolTable_header |
145 * |--------------------|
146 * |SymbolTable_entry 0 |
147 * |SymbolTable_entry 1 |
148 * | ...                |
149 * |SymbolTable_entry n |
150 * |--------------------|
151 *
152 */
153bool BinaryResourceParser::parseSymbolTable(const ResChunk_header* chunk) {
154    const SymbolTable_header* header = convertTo<SymbolTable_header>(chunk);
155    if (!header) {
156        mContext->getDiagnostics()->error(DiagMessage(mSource)
157                                          << "corrupt SymbolTable_header");
158        return false;
159    }
160
161    const uint32_t entrySizeBytes =
162            util::deviceToHost32(header->count) * sizeof(SymbolTable_entry);
163    if (entrySizeBytes > getChunkDataLen(&header->header)) {
164        mContext->getDiagnostics()->error(DiagMessage(mSource)
165                                          << "SymbolTable_header data section too long");
166        return false;
167    }
168
169    mSymbolEntries = (const SymbolTable_entry*) getChunkData(&header->header);
170    mSymbolEntryCount = util::deviceToHost32(header->count);
171
172    // Skip over the symbol entries and parse the StringPool chunk that should be next.
173    ResChunkPullParser parser(getChunkData(&header->header) + entrySizeBytes,
174                              getChunkDataLen(&header->header) - entrySizeBytes);
175    if (!ResChunkPullParser::isGoodEvent(parser.next())) {
176        mContext->getDiagnostics()->error(DiagMessage(mSource)
177                                          << "failed to parse chunk in SymbolTable: "
178                                          << parser.getLastError());
179        return false;
180    }
181
182    const ResChunk_header* nextChunk = parser.getChunk();
183    if (util::deviceToHost16(nextChunk->type) != android::RES_STRING_POOL_TYPE) {
184        mContext->getDiagnostics()->error(DiagMessage(mSource)
185                                          << "expected string pool in SymbolTable but got "
186                                          << "chunk of type "
187                                          << (int) util::deviceToHost16(nextChunk->type));
188        return false;
189    }
190
191    if (mSymbolPool.setTo(nextChunk, util::deviceToHost32(nextChunk->size)) != NO_ERROR) {
192        mContext->getDiagnostics()->error(DiagMessage(mSource)
193                                          << "corrupt string pool in SymbolTable: "
194                                          << mSymbolPool.getError());
195        return false;
196    }
197    return true;
198}
199
200/**
201 * Parses the resource table, which contains all the packages, types, and entries.
202 */
203bool BinaryResourceParser::parseTable(const ResChunk_header* chunk) {
204    const ResTable_header* tableHeader = convertTo<ResTable_header>(chunk);
205    if (!tableHeader) {
206        mContext->getDiagnostics()->error(DiagMessage(mSource) << "corrupt ResTable_header chunk");
207        return false;
208    }
209
210    ResChunkPullParser parser(getChunkData(&tableHeader->header),
211                              getChunkDataLen(&tableHeader->header));
212    while (ResChunkPullParser::isGoodEvent(parser.next())) {
213        switch (util::deviceToHost16(parser.getChunk()->type)) {
214        case android::RES_STRING_POOL_TYPE:
215            if (mValuePool.getError() == NO_INIT) {
216                status_t err = mValuePool.setTo(parser.getChunk(),
217                                                util::deviceToHost32(parser.getChunk()->size));
218                if (err != NO_ERROR) {
219                    mContext->getDiagnostics()->error(DiagMessage(mSource)
220                                                      << "corrupt string pool in ResTable: "
221                                                      << mValuePool.getError());
222                    return false;
223                }
224
225                // Reserve some space for the strings we are going to add.
226                mTable->stringPool.hintWillAdd(mValuePool.size(), mValuePool.styleCount());
227            } else {
228                mContext->getDiagnostics()->warn(DiagMessage(mSource)
229                                                 << "unexpected string pool in ResTable");
230            }
231            break;
232
233        case RES_TABLE_SYMBOL_TABLE_TYPE:
234            if (!parseSymbolTable(parser.getChunk())) {
235                return false;
236            }
237            break;
238
239        case RES_TABLE_SOURCE_POOL_TYPE: {
240            status_t err = mSourcePool.setTo(getChunkData(parser.getChunk()),
241                                             getChunkDataLen(parser.getChunk()));
242            if (err != NO_ERROR) {
243                mContext->getDiagnostics()->error(DiagMessage(mSource)
244                                                  << "corrupt source string pool in ResTable: "
245                                                  << mSourcePool.getError());
246                return false;
247            }
248            break;
249        }
250
251        case android::RES_TABLE_PACKAGE_TYPE:
252            if (!parsePackage(parser.getChunk())) {
253                return false;
254            }
255            break;
256
257        default:
258            mContext->getDiagnostics()
259                    ->warn(DiagMessage(mSource)
260                           << "unexpected chunk type "
261                           << (int) util::deviceToHost16(parser.getChunk()->type));
262            break;
263        }
264    }
265
266    if (parser.getEvent() == ResChunkPullParser::Event::BadDocument) {
267        mContext->getDiagnostics()->error(DiagMessage(mSource)
268                                          << "corrupt resource table: " << parser.getLastError());
269        return false;
270    }
271    return true;
272}
273
274
275bool BinaryResourceParser::parsePackage(const ResChunk_header* chunk) {
276    const ResTable_package* packageHeader = convertTo<ResTable_package>(chunk);
277    if (!packageHeader) {
278        mContext->getDiagnostics()->error(DiagMessage(mSource)
279                                          << "corrupt ResTable_package chunk");
280        return false;
281    }
282
283    uint32_t packageId = util::deviceToHost32(packageHeader->id);
284    if (packageId > std::numeric_limits<uint8_t>::max()) {
285        mContext->getDiagnostics()->error(DiagMessage(mSource)
286                                          << "package ID is too big (" << packageId << ")");
287        return false;
288    }
289
290    // Extract the package name.
291    size_t len = strnlen16((const char16_t*) packageHeader->name, arraysize(packageHeader->name));
292    std::u16string packageName;
293    packageName.resize(len);
294    for (size_t i = 0; i < len; i++) {
295        packageName[i] = util::deviceToHost16(packageHeader->name[i]);
296    }
297
298    ResourceTablePackage* package = mTable->createPackage(packageName, (uint8_t) packageId);
299    if (!package) {
300        mContext->getDiagnostics()->error(DiagMessage(mSource)
301                                          << "incompatible package '" << packageName
302                                          << "' with ID " << packageId);
303        return false;
304    }
305
306    // There can be multiple packages in a table, so
307    // clear the type and key pool in case they were set from a previous package.
308    mTypePool.uninit();
309    mKeyPool.uninit();
310
311    ResChunkPullParser parser(getChunkData(&packageHeader->header),
312                              getChunkDataLen(&packageHeader->header));
313    while (ResChunkPullParser::isGoodEvent(parser.next())) {
314        switch (util::deviceToHost16(parser.getChunk()->type)) {
315        case android::RES_STRING_POOL_TYPE:
316            if (mTypePool.getError() == NO_INIT) {
317                status_t err = mTypePool.setTo(parser.getChunk(),
318                                               util::deviceToHost32(parser.getChunk()->size));
319                if (err != NO_ERROR) {
320                    mContext->getDiagnostics()->error(DiagMessage(mSource)
321                                                      << "corrupt type string pool in "
322                                                      << "ResTable_package: "
323                                                      << mTypePool.getError());
324                    return false;
325                }
326            } else if (mKeyPool.getError() == NO_INIT) {
327                status_t err = mKeyPool.setTo(parser.getChunk(),
328                                              util::deviceToHost32(parser.getChunk()->size));
329                if (err != NO_ERROR) {
330                    mContext->getDiagnostics()->error(DiagMessage(mSource)
331                                                      << "corrupt key string pool in "
332                                                      << "ResTable_package: "
333                                                      << mKeyPool.getError());
334                    return false;
335                }
336            } else {
337                mContext->getDiagnostics()->warn(DiagMessage(mSource) << "unexpected string pool");
338            }
339            break;
340
341        case android::RES_TABLE_TYPE_SPEC_TYPE:
342            if (!parseTypeSpec(parser.getChunk())) {
343                return false;
344            }
345            break;
346
347        case android::RES_TABLE_TYPE_TYPE:
348            if (!parseType(package, parser.getChunk())) {
349                return false;
350            }
351            break;
352
353        case RES_TABLE_PUBLIC_TYPE:
354            if (!parsePublic(package, parser.getChunk())) {
355                return false;
356            }
357            break;
358
359        default:
360            mContext->getDiagnostics()
361                    ->warn(DiagMessage(mSource)
362                           << "unexpected chunk type "
363                           << (int) util::deviceToHost16(parser.getChunk()->type));
364            break;
365        }
366    }
367
368    if (parser.getEvent() == ResChunkPullParser::Event::BadDocument) {
369        mContext->getDiagnostics()->error(DiagMessage(mSource)
370                                          << "corrupt ResTable_package: "
371                                          << parser.getLastError());
372        return false;
373    }
374
375    // Now go through the table and change local resource ID references to
376    // symbolic references.
377    ReferenceIdToNameVisitor visitor(&mIdIndex);
378    for (auto& package : mTable->packages) {
379        for (auto& type : package->types) {
380            for (auto& entry : type->entries) {
381                for (auto& configValue : entry->values) {
382                    configValue.value->accept(&visitor);
383                }
384            }
385        }
386    }
387    return true;
388}
389
390bool BinaryResourceParser::parsePublic(const ResourceTablePackage* package,
391                                       const ResChunk_header* chunk) {
392    const Public_header* header = convertTo<Public_header>(chunk);
393    if (!header) {
394        mContext->getDiagnostics()->error(DiagMessage(mSource)
395                                          << "corrupt Public_header chunk");
396        return false;
397    }
398
399    if (header->typeId == 0) {
400        mContext->getDiagnostics()->error(DiagMessage(mSource)
401                                          << "invalid type ID "
402                                          << (int) header->typeId);
403        return false;
404    }
405
406    StringPiece16 typeStr16 = util::getString(mTypePool, header->typeId - 1);
407    const ResourceType* parsedType = parseResourceType(typeStr16);
408    if (!parsedType) {
409        mContext->getDiagnostics()->error(DiagMessage(mSource)
410                                          << "invalid type '" << typeStr16 << "'");
411        return false;
412    }
413
414    const uintptr_t chunkEnd = (uintptr_t) chunk + util::deviceToHost32(chunk->size);
415    const Public_entry* entry = (const Public_entry*) getChunkData(&header->header);
416    for (uint32_t i = 0; i < util::deviceToHost32(header->count); i++) {
417        if ((uintptr_t) entry + sizeof(*entry) > chunkEnd) {
418            mContext->getDiagnostics()->error(DiagMessage(mSource)
419                                              << "Public_entry data section is too long");
420            return false;
421        }
422
423        const ResourceId resId(package->id.value(), header->typeId,
424                               util::deviceToHost16(entry->entryId));
425
426        const ResourceName name(package->name, *parsedType,
427                                util::getString(mKeyPool, entry->key.index).toString());
428
429        Symbol symbol;
430        if (mSourcePool.getError() == NO_ERROR) {
431            symbol.source.path = util::utf16ToUtf8(util::getString(
432                    mSourcePool, util::deviceToHost32(entry->source.path.index)));
433            symbol.source.line = util::deviceToHost32(entry->source.line);
434        }
435
436        StringPiece16 comment = util::getString(mSourcePool,
437                                                util::deviceToHost32(entry->source.comment.index));
438        if (!comment.empty()) {
439            symbol.comment = comment.toString();
440        }
441
442        switch (util::deviceToHost16(entry->state)) {
443        case Public_entry::kPrivate:
444            symbol.state = SymbolState::kPrivate;
445            break;
446
447        case Public_entry::kPublic:
448            symbol.state = SymbolState::kPublic;
449            break;
450
451        case Public_entry::kUndefined:
452            symbol.state = SymbolState::kUndefined;
453            break;
454        }
455
456        if (!mTable->setSymbolStateAllowMangled(name, resId, symbol, mContext->getDiagnostics())) {
457            return false;
458        }
459
460        // Add this resource name->id mapping to the index so
461        // that we can resolve all ID references to name references.
462        auto cacheIter = mIdIndex.find(resId);
463        if (cacheIter == mIdIndex.end()) {
464            mIdIndex.insert({ resId, name });
465        }
466
467        entry++;
468    }
469    return true;
470}
471
472bool BinaryResourceParser::parseTypeSpec(const ResChunk_header* chunk) {
473    if (mTypePool.getError() != NO_ERROR) {
474        mContext->getDiagnostics()->error(DiagMessage(mSource)
475                                          << "missing type string pool");
476        return false;
477    }
478
479    const ResTable_typeSpec* typeSpec = convertTo<ResTable_typeSpec>(chunk);
480    if (!typeSpec) {
481        mContext->getDiagnostics()->error(DiagMessage(mSource)
482                                          << "corrupt ResTable_typeSpec chunk");
483        return false;
484    }
485
486    if (typeSpec->id == 0) {
487        mContext->getDiagnostics()->error(DiagMessage(mSource)
488                                          << "ResTable_typeSpec has invalid id: " << typeSpec->id);
489        return false;
490    }
491    return true;
492}
493
494bool BinaryResourceParser::parseType(const ResourceTablePackage* package,
495                                     const ResChunk_header* chunk) {
496    if (mTypePool.getError() != NO_ERROR) {
497        mContext->getDiagnostics()->error(DiagMessage(mSource)
498                                          << "missing type string pool");
499        return false;
500    }
501
502    if (mKeyPool.getError() != NO_ERROR) {
503        mContext->getDiagnostics()->error(DiagMessage(mSource)
504                                          << "missing key string pool");
505        return false;
506    }
507
508    const ResTable_type* type = convertTo<ResTable_type>(chunk);
509    if (!type) {
510        mContext->getDiagnostics()->error(DiagMessage(mSource)
511                                          << "corrupt ResTable_type chunk");
512        return false;
513    }
514
515    if (type->id == 0) {
516        mContext->getDiagnostics()->error(DiagMessage(mSource)
517                                          << "ResTable_type has invalid id: " << (int) type->id);
518        return false;
519    }
520
521    ConfigDescription config;
522    config.copyFromDtoH(type->config);
523
524    StringPiece16 typeStr16 = util::getString(mTypePool, type->id - 1);
525
526    const ResourceType* parsedType = parseResourceType(typeStr16);
527    if (!parsedType) {
528        mContext->getDiagnostics()->error(DiagMessage(mSource)
529                                          << "invalid type name '" << typeStr16
530                                          << "' for type with ID " << (int) type->id);
531        return false;
532    }
533
534    TypeVariant tv(type);
535    for (auto it = tv.beginEntries(); it != tv.endEntries(); ++it) {
536        const ResTable_entry* entry = *it;
537        if (!entry) {
538            continue;
539        }
540
541        const ResourceName name(package->name, *parsedType,
542                                util::getString(mKeyPool,
543                                                util::deviceToHost32(entry->key.index)).toString());
544
545        const ResourceId resId(package->id.value(), type->id, static_cast<uint16_t>(it.index()));
546
547        std::unique_ptr<Value> resourceValue;
548        const ResTable_entry_source* sourceBlock = nullptr;
549
550        if (entry->flags & ResTable_entry::FLAG_COMPLEX) {
551            const ResTable_map_entry* mapEntry = static_cast<const ResTable_map_entry*>(entry);
552            if (util::deviceToHost32(mapEntry->size) - sizeof(*mapEntry) == sizeof(*sourceBlock)) {
553                const uint8_t* data = (const uint8_t*) mapEntry;
554                data += util::deviceToHost32(mapEntry->size) - sizeof(*sourceBlock);
555                sourceBlock = (const ResTable_entry_source*) data;
556            }
557
558            // TODO(adamlesinski): Check that the entry count is valid.
559            resourceValue = parseMapEntry(name, config, mapEntry);
560        } else {
561            if (util::deviceToHost32(entry->size) - sizeof(*entry) == sizeof(*sourceBlock)) {
562                const uint8_t* data = (const uint8_t*) entry;
563                data += util::deviceToHost32(entry->size) - sizeof(*sourceBlock);
564                sourceBlock = (const ResTable_entry_source*) data;
565            }
566
567            const Res_value* value = (const Res_value*)(
568                    (const uint8_t*) entry + util::deviceToHost32(entry->size));
569            resourceValue = parseValue(name, config, value, entry->flags);
570        }
571
572        if (!resourceValue) {
573            mContext->getDiagnostics()->error(DiagMessage(mSource)
574                                              << "failed to parse value for resource " << name
575                                              << " (" << resId << ") with configuration '"
576                                              << config << "'");
577            return false;
578        }
579
580        Source source = mSource;
581        if (sourceBlock) {
582            StringPiece path = util::getString8(mSourcePool,
583                                                util::deviceToHost32(sourceBlock->path.index));
584            if (!path.empty()) {
585                source.path = path.toString();
586            }
587            source.line = util::deviceToHost32(sourceBlock->line);
588        }
589
590        StringPiece16 comment = util::getString(mSourcePool,
591                                                util::deviceToHost32(sourceBlock->comment.index));
592        if (!comment.empty()) {
593            resourceValue->setComment(comment);
594        }
595
596        resourceValue->setSource(source);
597        if (!mTable->addResourceAllowMangled(name, config, std::move(resourceValue),
598                                             mContext->getDiagnostics())) {
599            return false;
600        }
601
602        if ((entry->flags & ResTable_entry::FLAG_PUBLIC) != 0) {
603            Symbol symbol;
604            symbol.state = SymbolState::kPublic;
605            symbol.source = mSource.withLine(0);
606            if (!mTable->setSymbolStateAllowMangled(name, resId, symbol,
607                                                    mContext->getDiagnostics())) {
608                return false;
609            }
610        }
611
612        // Add this resource name->id mapping to the index so
613        // that we can resolve all ID references to name references.
614        auto cacheIter = mIdIndex.find(resId);
615        if (cacheIter == mIdIndex.end()) {
616            mIdIndex.insert({ resId, name });
617        }
618    }
619    return true;
620}
621
622std::unique_ptr<Item> BinaryResourceParser::parseValue(const ResourceNameRef& name,
623                                                       const ConfigDescription& config,
624                                                       const Res_value* value,
625                                                       uint16_t flags) {
626    if (name.type == ResourceType::kId) {
627        return util::make_unique<Id>();
628    }
629
630    const uint32_t data = util::deviceToHost32(value->data);
631
632    if (value->dataType == Res_value::TYPE_STRING) {
633        StringPiece16 str = util::getString(mValuePool, data);
634
635        const ResStringPool_span* spans = mValuePool.styleAt(data);
636
637        // Check if the string has a valid style associated with it.
638        if (spans != nullptr && spans->name.index != ResStringPool_span::END) {
639            StyleString styleStr = { str.toString() };
640            while (spans->name.index != ResStringPool_span::END) {
641                styleStr.spans.push_back(Span{
642                        util::getString(mValuePool, spans->name.index).toString(),
643                        spans->firstChar,
644                        spans->lastChar
645                });
646                spans++;
647            }
648            return util::make_unique<StyledString>(mTable->stringPool.makeRef(
649                    styleStr, StringPool::Context{1, config}));
650        } else {
651            if (name.type != ResourceType::kString &&
652                    util::stringStartsWith<char16_t>(str, u"res/")) {
653                // This must be a FileReference.
654                return util::make_unique<FileReference>(mTable->stringPool.makeRef(
655                            str, StringPool::Context{ 0, config }));
656            }
657
658            // There are no styles associated with this string, so treat it as
659            // a simple string.
660            return util::make_unique<String>(mTable->stringPool.makeRef(
661                    str, StringPool::Context{1, config}));
662        }
663    }
664
665    if (value->dataType == Res_value::TYPE_REFERENCE ||
666            value->dataType == Res_value::TYPE_ATTRIBUTE) {
667        const Reference::Type type = (value->dataType == Res_value::TYPE_REFERENCE) ?
668                Reference::Type::kResource : Reference::Type::kAttribute;
669
670        if (data != 0) {
671            // This is a normal reference.
672            return util::make_unique<Reference>(data, type);
673        }
674
675        // This reference has an invalid ID. Check if it is an unresolved symbol.
676        if (Maybe<Reference> ref = getSymbol(&value->data)) {
677            ref.value().referenceType = type;
678            return util::make_unique<Reference>(std::move(ref.value()));
679        }
680
681        // This is not an unresolved symbol, so it must be the magic @null reference.
682        Res_value nullType = {};
683        nullType.dataType = Res_value::TYPE_REFERENCE;
684        return util::make_unique<BinaryPrimitive>(nullType);
685    }
686
687    if (value->dataType == ExtendedTypes::TYPE_RAW_STRING) {
688        return util::make_unique<RawString>(mTable->stringPool.makeRef(
689                util::getString(mValuePool, data), StringPool::Context{ 1, config }));
690    }
691
692    // Treat this as a raw binary primitive.
693    return util::make_unique<BinaryPrimitive>(*value);
694}
695
696std::unique_ptr<Value> BinaryResourceParser::parseMapEntry(const ResourceNameRef& name,
697                                                           const ConfigDescription& config,
698                                                           const ResTable_map_entry* map) {
699    switch (name.type) {
700        case ResourceType::kStyle:
701            return parseStyle(name, config, map);
702        case ResourceType::kAttrPrivate:
703            // fallthrough
704        case ResourceType::kAttr:
705            return parseAttr(name, config, map);
706        case ResourceType::kArray:
707            return parseArray(name, config, map);
708        case ResourceType::kStyleable:
709            return parseStyleable(name, config, map);
710        case ResourceType::kPlurals:
711            return parsePlural(name, config, map);
712        default:
713            assert(false && "unknown map type");
714            break;
715    }
716    return {};
717}
718
719std::unique_ptr<Style> BinaryResourceParser::parseStyle(const ResourceNameRef& name,
720                                                        const ConfigDescription& config,
721                                                        const ResTable_map_entry* map) {
722    std::unique_ptr<Style> style = util::make_unique<Style>();
723    if (util::deviceToHost32(map->parent.ident) == 0) {
724        // The parent is either not set or it is an unresolved symbol.
725        // Check to see if it is a symbol.
726        style->parent = getSymbol(&map->parent.ident);
727
728    } else {
729         // The parent is a regular reference to a resource.
730        style->parent = Reference(util::deviceToHost32(map->parent.ident));
731    }
732
733    for (const ResTable_map& mapEntry : map) {
734        if (Res_INTERNALID(util::deviceToHost32(mapEntry.name.ident))) {
735            if (style->entries.empty()) {
736                mContext->getDiagnostics()->error(DiagMessage(mSource)
737                                                  << "out-of-sequence meta data in style");
738                return {};
739            }
740            collectMetaData(mapEntry, &style->entries.back().key);
741            continue;
742        }
743
744        style->entries.emplace_back();
745        Style::Entry& styleEntry = style->entries.back();
746
747        if (util::deviceToHost32(mapEntry.name.ident) == 0) {
748            // The map entry's key (attribute) is not set. This must be
749            // a symbol reference, so resolve it.
750            Maybe<Reference> symbol = getSymbol(&mapEntry.name.ident);
751            if (!symbol) {
752                mContext->getDiagnostics()->error(DiagMessage(mSource)
753                                                  << "unresolved style attribute");
754                return {};
755            }
756            styleEntry.key = std::move(symbol.value());
757
758        } else {
759            // The map entry's key (attribute) is a regular reference.
760            styleEntry.key.id = ResourceId(util::deviceToHost32(mapEntry.name.ident));
761        }
762
763        // Parse the attribute's value.
764        styleEntry.value = parseValue(name, config, &mapEntry.value, 0);
765        if (!styleEntry.value) {
766            return {};
767        }
768    }
769    return style;
770}
771
772std::unique_ptr<Attribute> BinaryResourceParser::parseAttr(const ResourceNameRef& name,
773                                                           const ConfigDescription& config,
774                                                           const ResTable_map_entry* map) {
775    const bool isWeak = (util::deviceToHost16(map->flags) & ResTable_entry::FLAG_WEAK) != 0;
776    std::unique_ptr<Attribute> attr = util::make_unique<Attribute>(isWeak);
777
778    // First we must discover what type of attribute this is. Find the type mask.
779    auto typeMaskIter = std::find_if(begin(map), end(map), [](const ResTable_map& entry) -> bool {
780        return util::deviceToHost32(entry.name.ident) == ResTable_map::ATTR_TYPE;
781    });
782
783    if (typeMaskIter != end(map)) {
784        attr->typeMask = util::deviceToHost32(typeMaskIter->value.data);
785    }
786
787    for (const ResTable_map& mapEntry : map) {
788        if (Res_INTERNALID(util::deviceToHost32(mapEntry.name.ident))) {
789            switch (util::deviceToHost32(mapEntry.name.ident)) {
790            case ResTable_map::ATTR_MIN:
791                attr->minInt = static_cast<int32_t>(mapEntry.value.data);
792                break;
793            case ResTable_map::ATTR_MAX:
794                attr->maxInt = static_cast<int32_t>(mapEntry.value.data);
795                break;
796            }
797            continue;
798        }
799
800        if (attr->typeMask & (ResTable_map::TYPE_ENUM | ResTable_map::TYPE_FLAGS)) {
801            Attribute::Symbol symbol;
802            symbol.value = util::deviceToHost32(mapEntry.value.data);
803            if (util::deviceToHost32(mapEntry.name.ident) == 0) {
804                // The map entry's key (id) is not set. This must be
805                // a symbol reference, so resolve it.
806                Maybe<Reference> ref = getSymbol(&mapEntry.name.ident);
807                if (!ref) {
808                    mContext->getDiagnostics()->error(DiagMessage(mSource)
809                                                      << "unresolved attribute symbol");
810                    return {};
811                }
812                symbol.symbol = std::move(ref.value());
813
814            } else {
815                // The map entry's key (id) is a regular reference.
816                symbol.symbol.id = ResourceId(util::deviceToHost32(mapEntry.name.ident));
817            }
818
819            attr->symbols.push_back(std::move(symbol));
820        }
821    }
822
823    // TODO(adamlesinski): Find i80n, attributes.
824    return attr;
825}
826
827static bool isMetaDataEntry(const ResTable_map& mapEntry) {
828    switch (util::deviceToHost32(mapEntry.name.ident)) {
829    case ExtendedResTableMapTypes::ATTR_SOURCE_PATH:
830    case ExtendedResTableMapTypes::ATTR_SOURCE_LINE:
831    case ExtendedResTableMapTypes::ATTR_COMMENT:
832        return true;
833    }
834    return false;
835}
836
837bool BinaryResourceParser::collectMetaData(const ResTable_map& mapEntry, Value* value) {
838    switch (util::deviceToHost32(mapEntry.name.ident)) {
839    case ExtendedResTableMapTypes::ATTR_SOURCE_PATH:
840        value->setSource(Source(util::getString8(mSourcePool,
841                                                 util::deviceToHost32(mapEntry.value.data))));
842        return true;
843        break;
844
845    case ExtendedResTableMapTypes::ATTR_SOURCE_LINE:
846        value->setSource(value->getSource().withLine(util::deviceToHost32(mapEntry.value.data)));
847        return true;
848        break;
849
850    case ExtendedResTableMapTypes::ATTR_COMMENT:
851        value->setComment(util::getString(mSourcePool, util::deviceToHost32(mapEntry.value.data)));
852        return true;
853        break;
854    }
855    return false;
856}
857
858std::unique_ptr<Array> BinaryResourceParser::parseArray(const ResourceNameRef& name,
859                                                        const ConfigDescription& config,
860                                                        const ResTable_map_entry* map) {
861    std::unique_ptr<Array> array = util::make_unique<Array>();
862    Source source;
863    for (const ResTable_map& mapEntry : map) {
864        if (isMetaDataEntry(mapEntry)) {
865            if (array->items.empty()) {
866                mContext->getDiagnostics()->error(DiagMessage(mSource)
867                                                  << "out-of-sequence meta data in array");
868                return {};
869            }
870            collectMetaData(mapEntry, array->items.back().get());
871            continue;
872        }
873
874        array->items.push_back(parseValue(name, config, &mapEntry.value, 0));
875    }
876    return array;
877}
878
879std::unique_ptr<Styleable> BinaryResourceParser::parseStyleable(const ResourceNameRef& name,
880                                                                const ConfigDescription& config,
881                                                                const ResTable_map_entry* map) {
882    std::unique_ptr<Styleable> styleable = util::make_unique<Styleable>();
883    for (const ResTable_map& mapEntry : map) {
884        if (isMetaDataEntry(mapEntry)) {
885            if (styleable->entries.empty()) {
886                mContext->getDiagnostics()->error(DiagMessage(mSource)
887                                                  << "out-of-sequence meta data in styleable");
888                return {};
889            }
890            collectMetaData(mapEntry, &styleable->entries.back());
891            continue;
892        }
893
894        if (util::deviceToHost32(mapEntry.name.ident) == 0) {
895            // The map entry's key (attribute) is not set. This must be
896            // a symbol reference, so resolve it.
897            Maybe<Reference> ref = getSymbol(&mapEntry.name.ident);
898            if (!ref) {
899                mContext->getDiagnostics()->error(DiagMessage(mSource)
900                                                  << "unresolved styleable symbol");
901                return {};
902            }
903            styleable->entries.emplace_back(std::move(ref.value()));
904
905        } else {
906            // The map entry's key (attribute) is a regular reference.
907            styleable->entries.emplace_back(util::deviceToHost32(mapEntry.name.ident));
908        }
909    }
910    return styleable;
911}
912
913std::unique_ptr<Plural> BinaryResourceParser::parsePlural(const ResourceNameRef& name,
914                                                          const ConfigDescription& config,
915                                                          const ResTable_map_entry* map) {
916    std::unique_ptr<Plural> plural = util::make_unique<Plural>();
917    Item* lastEntry = nullptr;
918    for (const ResTable_map& mapEntry : map) {
919        if (isMetaDataEntry(mapEntry)) {
920            if (!lastEntry) {
921                mContext->getDiagnostics()->error(DiagMessage(mSource)
922                                                  << "out-of-sequence meta data in plural");
923                return {};
924            }
925            collectMetaData(mapEntry, lastEntry);
926            continue;
927        }
928
929        std::unique_ptr<Item> item = parseValue(name, config, &mapEntry.value, 0);
930        if (!item) {
931            return {};
932        }
933
934        lastEntry = item.get();
935
936        switch (util::deviceToHost32(mapEntry.name.ident)) {
937            case ResTable_map::ATTR_ZERO:
938                plural->values[Plural::Zero] = std::move(item);
939                break;
940            case ResTable_map::ATTR_ONE:
941                plural->values[Plural::One] = std::move(item);
942                break;
943            case ResTable_map::ATTR_TWO:
944                plural->values[Plural::Two] = std::move(item);
945                break;
946            case ResTable_map::ATTR_FEW:
947                plural->values[Plural::Few] = std::move(item);
948                break;
949            case ResTable_map::ATTR_MANY:
950                plural->values[Plural::Many] = std::move(item);
951                break;
952            case ResTable_map::ATTR_OTHER:
953                plural->values[Plural::Other] = std::move(item);
954                break;
955        }
956    }
957    return plural;
958}
959
960} // namespace aapt
961