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