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 "ConfigDescription.h"
18#include "Resource.h"
19#include "ValueVisitor.h"
20#include "process/SymbolTable.h"
21#include "util/Util.h"
22
23#include <androidfw/AssetManager.h>
24#include <androidfw/ResourceTypes.h>
25
26namespace aapt {
27
28void SymbolTable::appendSource(std::unique_ptr<ISymbolSource> source) {
29    mSources.push_back(std::move(source));
30
31    // We do not clear the cache, because sources earlier in the list take precedent.
32}
33
34void SymbolTable::prependSource(std::unique_ptr<ISymbolSource> source) {
35    mSources.insert(mSources.begin(), std::move(source));
36
37    // We must clear the cache in case we did a lookup before adding this resource.
38    mCache.clear();
39}
40
41const SymbolTable::Symbol* SymbolTable::findByName(const ResourceName& name) {
42    if (const std::shared_ptr<Symbol>& s = mCache.get(name)) {
43        return s.get();
44    }
45
46    // We did not find it in the cache, so look through the sources.
47    for (auto& symbolSource : mSources) {
48        std::unique_ptr<Symbol> symbol = symbolSource->findByName(name);
49        if (symbol) {
50            // Take ownership of the symbol into a shared_ptr. We do this because LruCache
51            // doesn't support unique_ptr.
52            std::shared_ptr<Symbol> sharedSymbol = std::shared_ptr<Symbol>(symbol.release());
53            mCache.put(name, sharedSymbol);
54
55            if (sharedSymbol->id) {
56                // The symbol has an ID, so we can also cache this!
57                mIdCache.put(sharedSymbol->id.value(), sharedSymbol);
58            }
59            return sharedSymbol.get();
60        }
61    }
62    return nullptr;
63}
64
65const SymbolTable::Symbol* SymbolTable::findById(ResourceId id) {
66    if (const std::shared_ptr<Symbol>& s = mIdCache.get(id)) {
67        return s.get();
68    }
69
70    // We did not find it in the cache, so look through the sources.
71    for (auto& symbolSource : mSources) {
72        std::unique_ptr<Symbol> symbol = symbolSource->findById(id);
73        if (symbol) {
74            // Take ownership of the symbol into a shared_ptr. We do this because LruCache
75            // doesn't support unique_ptr.
76            std::shared_ptr<Symbol> sharedSymbol = std::shared_ptr<Symbol>(symbol.release());
77            mIdCache.put(id, sharedSymbol);
78            return sharedSymbol.get();
79        }
80    }
81    return nullptr;
82}
83
84const SymbolTable::Symbol* SymbolTable::findByReference(const Reference& ref) {
85    // First try the ID. This is because when we lookup by ID, we only fill in the ID cache.
86    // Looking up by name fills in the name and ID cache. So a cache miss will cause a failed
87    // ID lookup, then a successfull name lookup. Subsequent look ups will hit immediately
88    // because the ID is cached too.
89    //
90    // If we looked up by name first, a cache miss would mean we failed to lookup by name, then
91    // succeeded to lookup by ID. Subsequent lookups will miss then hit.
92    const SymbolTable::Symbol* symbol = nullptr;
93    if (ref.id) {
94        symbol = findById(ref.id.value());
95    }
96
97    if (ref.name && !symbol) {
98        symbol = findByName(ref.name.value());
99    }
100    return symbol;
101}
102
103std::unique_ptr<SymbolTable::Symbol> ResourceTableSymbolSource::findByName(
104        const ResourceName& name) {
105    Maybe<ResourceTable::SearchResult> result = mTable->findResource(name);
106    if (!result) {
107        if (name.type == ResourceType::kAttr) {
108            // Recurse and try looking up a private attribute.
109            return findByName(ResourceName(name.package, ResourceType::kAttrPrivate, name.entry));
110        }
111        return {};
112    }
113
114    ResourceTable::SearchResult sr = result.value();
115
116    std::unique_ptr<SymbolTable::Symbol> symbol = util::make_unique<SymbolTable::Symbol>();
117    symbol->isPublic = (sr.entry->symbolStatus.state == SymbolState::kPublic);
118
119    if (sr.package->id && sr.type->id && sr.entry->id) {
120        symbol->id = ResourceId(sr.package->id.value(), sr.type->id.value(), sr.entry->id.value());
121    }
122
123    if (name.type == ResourceType::kAttr || name.type == ResourceType::kAttrPrivate) {
124        const ConfigDescription kDefaultConfig;
125        ResourceConfigValue* configValue = sr.entry->findValue(kDefaultConfig);
126        if (configValue) {
127            // This resource has an Attribute.
128            if (Attribute* attr = valueCast<Attribute>(configValue->value.get())) {
129                symbol->attribute = std::make_shared<Attribute>(*attr);
130            } else {
131                return {};
132            }
133        }
134    }
135    return symbol;
136}
137
138bool AssetManagerSymbolSource::addAssetPath(const StringPiece& path) {
139    int32_t cookie = 0;
140    return mAssets.addAssetPath(android::String8(path.data(), path.size()), &cookie);
141}
142
143static std::unique_ptr<SymbolTable::Symbol> lookupAttributeInTable(const android::ResTable& table,
144                                                                   ResourceId id) {
145    // Try as a bag.
146    const android::ResTable::bag_entry* entry;
147    ssize_t count = table.lockBag(id.id, &entry);
148    if (count < 0) {
149        table.unlockBag(entry);
150        return nullptr;
151    }
152
153    // We found a resource.
154    std::unique_ptr<SymbolTable::Symbol> s = util::make_unique<SymbolTable::Symbol>();
155    s->id = id;
156
157    // Check to see if it is an attribute.
158    for (size_t i = 0; i < (size_t) count; i++) {
159        if (entry[i].map.name.ident == android::ResTable_map::ATTR_TYPE) {
160            s->attribute = std::make_shared<Attribute>(false);
161            s->attribute->typeMask = entry[i].map.value.data;
162            break;
163        }
164    }
165
166    if (s->attribute) {
167        for (size_t i = 0; i < (size_t) count; i++) {
168            const android::ResTable_map& mapEntry = entry[i].map;
169            if (Res_INTERNALID(mapEntry.name.ident)) {
170                switch (mapEntry.name.ident) {
171                case android::ResTable_map::ATTR_MIN:
172                    s->attribute->minInt = static_cast<int32_t>(mapEntry.value.data);
173                    break;
174                case android::ResTable_map::ATTR_MAX:
175                    s->attribute->maxInt = static_cast<int32_t>(mapEntry.value.data);
176                    break;
177                }
178                continue;
179            }
180
181            android::ResTable::resource_name entryName;
182            if (!table.getResourceName(mapEntry.name.ident, false, &entryName)) {
183                table.unlockBag(entry);
184                return nullptr;
185            }
186
187            const ResourceType* parsedType = parseResourceType(
188                    StringPiece16(entryName.type, entryName.typeLen));
189            if (!parsedType) {
190                table.unlockBag(entry);
191                return nullptr;
192            }
193
194            Attribute::Symbol symbol;
195            symbol.symbol.name = ResourceName(
196                    StringPiece16(entryName.package, entryName.packageLen),
197                    *parsedType,
198                    StringPiece16(entryName.name, entryName.nameLen));
199            symbol.symbol.id = ResourceId(mapEntry.name.ident);
200            symbol.value = mapEntry.value.data;
201            s->attribute->symbols.push_back(std::move(symbol));
202        }
203    }
204    table.unlockBag(entry);
205    return s;
206}
207
208std::unique_ptr<SymbolTable::Symbol> AssetManagerSymbolSource::findByName(
209        const ResourceName& name) {
210    const android::ResTable& table = mAssets.getResources(false);
211    StringPiece16 typeStr = toString(name.type);
212    uint32_t typeSpecFlags = 0;
213    ResourceId resId = table.identifierForName(name.entry.data(), name.entry.size(),
214                                               typeStr.data(), typeStr.size(),
215                                               name.package.data(), name.package.size(),
216                                               &typeSpecFlags);
217    if (!resId.isValid()) {
218        return {};
219    }
220
221    std::unique_ptr<SymbolTable::Symbol> s;
222    if (name.type == ResourceType::kAttr) {
223        s = lookupAttributeInTable(table, resId);
224    } else {
225        s = util::make_unique<SymbolTable::Symbol>();
226        s->id = resId;
227    }
228
229    if (s) {
230        s->isPublic = (typeSpecFlags & android::ResTable_typeSpec::SPEC_PUBLIC) != 0;
231        return s;
232    }
233    return {};
234}
235
236static Maybe<ResourceName> getResourceName(const android::ResTable& table, ResourceId id) {
237    android::ResTable::resource_name resName = {};
238    if (!table.getResourceName(id.id, true, &resName)) {
239        return {};
240    }
241
242    ResourceName name;
243    if (resName.package) {
244        name.package = StringPiece16(resName.package, resName.packageLen).toString();
245    }
246
247    const ResourceType* type;
248    if (resName.type) {
249        type = parseResourceType(StringPiece16(resName.type, resName.typeLen));
250
251    } else if (resName.type8) {
252        type = parseResourceType(util::utf8ToUtf16(StringPiece(resName.type8, resName.typeLen)));
253    } else {
254        return {};
255    }
256
257    if (!type) {
258        return {};
259    }
260
261    name.type = *type;
262
263    if (resName.name) {
264        name.entry = StringPiece16(resName.name, resName.nameLen).toString();
265    } else if (resName.name8) {
266        name.entry = util::utf8ToUtf16(StringPiece(resName.name8, resName.nameLen));
267    } else {
268        return {};
269    }
270
271    return name;
272}
273
274std::unique_ptr<SymbolTable::Symbol> AssetManagerSymbolSource::findById(ResourceId id) {
275    const android::ResTable& table = mAssets.getResources(false);
276    Maybe<ResourceName> maybeName = getResourceName(table, id);
277    if (!maybeName) {
278        return {};
279    }
280
281    uint32_t typeSpecFlags = 0;
282    table.getResourceFlags(id.id, &typeSpecFlags);
283
284    std::unique_ptr<SymbolTable::Symbol> s;
285    if (maybeName.value().type == ResourceType::kAttr) {
286        s = lookupAttributeInTable(table, id);
287    } else {
288        s = util::make_unique<SymbolTable::Symbol>();
289        s->id = id;
290    }
291
292    if (s) {
293        s->isPublic = (typeSpecFlags & android::ResTable_typeSpec::SPEC_PUBLIC) != 0;
294        return s;
295    }
296    return {};
297}
298
299std::unique_ptr<SymbolTable::Symbol> AssetManagerSymbolSource::findByReference(
300        const Reference& ref) {
301    // AssetManager always prefers IDs.
302    if (ref.id) {
303        return findById(ref.id.value());
304    } else if (ref.name) {
305        return findByName(ref.name.value());
306    }
307    return {};
308}
309
310} // namespace aapt
311