blob: 85e72cccc703c896ec1fc2215e94970f82939a06 [file] [log] [blame]
Adam Lesinski7ad11102016-10-28 16:39:15 -07001/*
2 * Copyright (C) 2016 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#define ATRACE_TAG ATRACE_TAG_RESOURCES
18
19#include "androidfw/AssetManager2.h"
20
y57cd1952018-04-12 14:26:23 -070021#include <algorithm>
Adam Lesinski30080e22017-10-16 16:18:09 -070022#include <iterator>
Adam Lesinski0c405242017-01-13 20:47:26 -080023#include <set>
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -070024#include <map>
Adam Lesinski0c405242017-01-13 20:47:26 -080025
Adam Lesinski7ad11102016-10-28 16:39:15 -070026#include "android-base/logging.h"
27#include "android-base/stringprintf.h"
28#include "utils/ByteOrder.h"
29#include "utils/Trace.h"
30
31#ifdef _WIN32
32#ifdef ERROR
33#undef ERROR
34#endif
35#endif
36
Adam Lesinski929d6512017-01-16 19:11:19 -080037#include "androidfw/ResourceUtils.h"
38
Adam Lesinski7ad11102016-10-28 16:39:15 -070039namespace android {
40
Adam Lesinskibebfcc42018-02-12 14:27:46 -080041struct FindEntryResult {
42 // A pointer to the resource table entry for this resource.
43 // If the size of the entry is > sizeof(ResTable_entry), it can be cast to
44 // a ResTable_map_entry and processed as a bag/map.
45 const ResTable_entry* entry;
46
47 // The configuration for which the resulting entry was defined. This is already swapped to host
48 // endianness.
49 ResTable_config config;
50
51 // The bitmask of configuration axis with which the resource value varies.
52 uint32_t type_flags;
53
54 // The dynamic package ID map for the package from which this resource came from.
55 const DynamicRefTable* dynamic_ref_table;
56
57 // The string pool reference to the type's name. This uses a different string pool than
58 // the global string pool, but this is hidden from the caller.
59 StringPoolRef type_string_ref;
60
61 // The string pool reference to the entry's name. This uses a different string pool than
62 // the global string pool, but this is hidden from the caller.
63 StringPoolRef entry_string_ref;
64};
65
Adam Lesinski970bd8d2017-09-25 13:21:55 -070066AssetManager2::AssetManager2() {
67 memset(&configuration_, 0, sizeof(configuration_));
68}
Adam Lesinski7ad11102016-10-28 16:39:15 -070069
70bool AssetManager2::SetApkAssets(const std::vector<const ApkAssets*>& apk_assets,
Mårten Kongstad668ec5b2018-06-11 14:11:33 +020071 bool invalidate_caches, bool filter_incompatible_configs) {
Adam Lesinski7ad11102016-10-28 16:39:15 -070072 apk_assets_ = apk_assets;
Adam Lesinskida431a22016-12-29 16:08:16 -050073 BuildDynamicRefTable();
Mårten Kongstad668ec5b2018-06-11 14:11:33 +020074 RebuildFilterList(filter_incompatible_configs);
Adam Lesinski7ad11102016-10-28 16:39:15 -070075 if (invalidate_caches) {
76 InvalidateCaches(static_cast<uint32_t>(-1));
77 }
78 return true;
79}
80
Adam Lesinskida431a22016-12-29 16:08:16 -050081void AssetManager2::BuildDynamicRefTable() {
82 package_groups_.clear();
83 package_ids_.fill(0xff);
84
85 // 0x01 is reserved for the android package.
86 int next_package_id = 0x02;
87 const size_t apk_assets_count = apk_assets_.size();
88 for (size_t i = 0; i < apk_assets_count; i++) {
Adam Lesinski970bd8d2017-09-25 13:21:55 -070089 const LoadedArsc* loaded_arsc = apk_assets_[i]->GetLoadedArsc();
90
91 for (const std::unique_ptr<const LoadedPackage>& package : loaded_arsc->GetPackages()) {
Adam Lesinskida431a22016-12-29 16:08:16 -050092 // Get the package ID or assign one if a shared library.
93 int package_id;
94 if (package->IsDynamic()) {
95 package_id = next_package_id++;
96 } else {
97 package_id = package->GetPackageId();
98 }
99
100 // Add the mapping for package ID to index if not present.
101 uint8_t idx = package_ids_[package_id];
102 if (idx == 0xff) {
103 package_ids_[package_id] = idx = static_cast<uint8_t>(package_groups_.size());
104 package_groups_.push_back({});
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800105 DynamicRefTable& ref_table = package_groups_.back().dynamic_ref_table;
106 ref_table.mAssignedPackageId = package_id;
107 ref_table.mAppAsLib = package->IsDynamic() && package->GetPackageId() == 0x7f;
Adam Lesinskida431a22016-12-29 16:08:16 -0500108 }
109 PackageGroup* package_group = &package_groups_[idx];
110
111 // Add the package and to the set of packages with the same ID.
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800112 package_group->packages_.push_back(ConfiguredPackage{package.get(), {}});
Adam Lesinskida431a22016-12-29 16:08:16 -0500113 package_group->cookies_.push_back(static_cast<ApkAssetsCookie>(i));
114
115 // Add the package name -> build time ID mappings.
116 for (const DynamicPackageEntry& entry : package->GetDynamicPackageMap()) {
117 String16 package_name(entry.package_name.c_str(), entry.package_name.size());
118 package_group->dynamic_ref_table.mEntries.replaceValueFor(
119 package_name, static_cast<uint8_t>(entry.package_id));
120 }
121 }
122 }
123
124 // Now assign the runtime IDs so that we have a build-time to runtime ID map.
125 const auto package_groups_end = package_groups_.end();
126 for (auto iter = package_groups_.begin(); iter != package_groups_end; ++iter) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800127 const std::string& package_name = iter->packages_[0].loaded_package_->GetPackageName();
Adam Lesinskida431a22016-12-29 16:08:16 -0500128 for (auto iter2 = package_groups_.begin(); iter2 != package_groups_end; ++iter2) {
129 iter2->dynamic_ref_table.addMapping(String16(package_name.c_str(), package_name.size()),
130 iter->dynamic_ref_table.mAssignedPackageId);
131 }
132 }
133}
134
135void AssetManager2::DumpToLog() const {
136 base::ScopedLogSeverity _log(base::INFO);
137
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800138 LOG(INFO) << base::StringPrintf("AssetManager2(this=%p)", this);
139
Adam Lesinskida431a22016-12-29 16:08:16 -0500140 std::string list;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800141 for (const auto& apk_assets : apk_assets_) {
142 base::StringAppendF(&list, "%s,", apk_assets->GetPath().c_str());
143 }
144 LOG(INFO) << "ApkAssets: " << list;
145
146 list = "";
Adam Lesinskida431a22016-12-29 16:08:16 -0500147 for (size_t i = 0; i < package_ids_.size(); i++) {
148 if (package_ids_[i] != 0xff) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800149 base::StringAppendF(&list, "%02x -> %d, ", (int)i, package_ids_[i]);
Adam Lesinskida431a22016-12-29 16:08:16 -0500150 }
151 }
152 LOG(INFO) << "Package ID map: " << list;
153
Adam Lesinski0dd36992018-01-25 15:38:38 -0800154 for (const auto& package_group: package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800155 list = "";
156 for (const auto& package : package_group.packages_) {
157 const LoadedPackage* loaded_package = package.loaded_package_;
158 base::StringAppendF(&list, "%s(%02x%s), ", loaded_package->GetPackageName().c_str(),
159 loaded_package->GetPackageId(),
160 (loaded_package->IsDynamic() ? " dynamic" : ""));
161 }
162 LOG(INFO) << base::StringPrintf("PG (%02x): ",
163 package_group.dynamic_ref_table.mAssignedPackageId)
164 << list;
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800165
166 for (size_t i = 0; i < 256; i++) {
167 if (package_group.dynamic_ref_table.mLookupTable[i] != 0) {
168 LOG(INFO) << base::StringPrintf(" e[0x%02x] -> 0x%02x", (uint8_t) i,
169 package_group.dynamic_ref_table.mLookupTable[i]);
170 }
171 }
Adam Lesinskida431a22016-12-29 16:08:16 -0500172 }
173}
Adam Lesinski7ad11102016-10-28 16:39:15 -0700174
175const ResStringPool* AssetManager2::GetStringPoolForCookie(ApkAssetsCookie cookie) const {
176 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
177 return nullptr;
178 }
179 return apk_assets_[cookie]->GetLoadedArsc()->GetStringPool();
180}
181
Adam Lesinskida431a22016-12-29 16:08:16 -0500182const DynamicRefTable* AssetManager2::GetDynamicRefTableForPackage(uint32_t package_id) const {
183 if (package_id >= package_ids_.size()) {
184 return nullptr;
185 }
186
187 const size_t idx = package_ids_[package_id];
188 if (idx == 0xff) {
189 return nullptr;
190 }
191 return &package_groups_[idx].dynamic_ref_table;
192}
193
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800194const DynamicRefTable* AssetManager2::GetDynamicRefTableForCookie(ApkAssetsCookie cookie) const {
195 for (const PackageGroup& package_group : package_groups_) {
196 for (const ApkAssetsCookie& package_cookie : package_group.cookies_) {
197 if (package_cookie == cookie) {
198 return &package_group.dynamic_ref_table;
199 }
200 }
201 }
202 return nullptr;
203}
204
Adam Lesinski7ad11102016-10-28 16:39:15 -0700205void AssetManager2::SetConfiguration(const ResTable_config& configuration) {
206 const int diff = configuration_.diff(configuration);
207 configuration_ = configuration;
208
209 if (diff) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800210 RebuildFilterList();
Adam Lesinski7ad11102016-10-28 16:39:15 -0700211 InvalidateCaches(static_cast<uint32_t>(diff));
212 }
213}
214
Adam Lesinski0c405242017-01-13 20:47:26 -0800215std::set<ResTable_config> AssetManager2::GetResourceConfigurations(bool exclude_system,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800216 bool exclude_mipmap) const {
217 ATRACE_NAME("AssetManager::GetResourceConfigurations");
Adam Lesinski0c405242017-01-13 20:47:26 -0800218 std::set<ResTable_config> configurations;
219 for (const PackageGroup& package_group : package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800220 for (const ConfiguredPackage& package : package_group.packages_) {
221 if (exclude_system && package.loaded_package_->IsSystem()) {
Adam Lesinski0c405242017-01-13 20:47:26 -0800222 continue;
223 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800224 package.loaded_package_->CollectConfigurations(exclude_mipmap, &configurations);
Adam Lesinski0c405242017-01-13 20:47:26 -0800225 }
226 }
227 return configurations;
228}
229
230std::set<std::string> AssetManager2::GetResourceLocales(bool exclude_system,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800231 bool merge_equivalent_languages) const {
232 ATRACE_NAME("AssetManager::GetResourceLocales");
Adam Lesinski0c405242017-01-13 20:47:26 -0800233 std::set<std::string> locales;
234 for (const PackageGroup& package_group : package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800235 for (const ConfiguredPackage& package : package_group.packages_) {
236 if (exclude_system && package.loaded_package_->IsSystem()) {
Adam Lesinski0c405242017-01-13 20:47:26 -0800237 continue;
238 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800239 package.loaded_package_->CollectLocales(merge_equivalent_languages, &locales);
Adam Lesinski0c405242017-01-13 20:47:26 -0800240 }
241 }
242 return locales;
243}
244
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800245std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename,
246 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700247 const std::string new_path = "assets/" + filename;
248 return OpenNonAsset(new_path, mode);
249}
250
251std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename, ApkAssetsCookie cookie,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800252 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700253 const std::string new_path = "assets/" + filename;
254 return OpenNonAsset(new_path, cookie, mode);
255}
256
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800257std::unique_ptr<AssetDir> AssetManager2::OpenDir(const std::string& dirname) const {
258 ATRACE_NAME("AssetManager::OpenDir");
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800259
260 std::string full_path = "assets/" + dirname;
261 std::unique_ptr<SortedVector<AssetDir::FileInfo>> files =
262 util::make_unique<SortedVector<AssetDir::FileInfo>>();
263
264 // Start from the back.
265 for (auto iter = apk_assets_.rbegin(); iter != apk_assets_.rend(); ++iter) {
266 const ApkAssets* apk_assets = *iter;
267
268 auto func = [&](const StringPiece& name, FileType type) {
269 AssetDir::FileInfo info;
270 info.setFileName(String8(name.data(), name.size()));
271 info.setFileType(type);
272 info.setSourceName(String8(apk_assets->GetPath().c_str()));
273 files->add(info);
274 };
275
276 if (!apk_assets->ForEachFile(full_path, func)) {
277 return {};
278 }
279 }
280
281 std::unique_ptr<AssetDir> asset_dir = util::make_unique<AssetDir>();
282 asset_dir->setFileList(files.release());
283 return asset_dir;
284}
285
Adam Lesinski7ad11102016-10-28 16:39:15 -0700286// Search in reverse because that's how we used to do it and we need to preserve behaviour.
287// This is unfortunate, because ClassLoaders delegate to the parent first, so the order
288// is inconsistent for split APKs.
289std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
290 Asset::AccessMode mode,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800291 ApkAssetsCookie* out_cookie) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700292 for (int32_t i = apk_assets_.size() - 1; i >= 0; i--) {
293 std::unique_ptr<Asset> asset = apk_assets_[i]->Open(filename, mode);
294 if (asset) {
295 if (out_cookie != nullptr) {
296 *out_cookie = i;
297 }
298 return asset;
299 }
300 }
301
302 if (out_cookie != nullptr) {
303 *out_cookie = kInvalidCookie;
304 }
305 return {};
306}
307
308std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800309 ApkAssetsCookie cookie,
310 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700311 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
312 return {};
313 }
314 return apk_assets_[cookie]->Open(filename, mode);
315}
316
317ApkAssetsCookie AssetManager2::FindEntry(uint32_t resid, uint16_t density_override,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800318 bool /*stop_at_first_match*/,
319 FindEntryResult* out_entry) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700320 // Might use this if density_override != 0.
321 ResTable_config density_override_config;
322
323 // Select our configuration or generate a density override configuration.
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800324 const ResTable_config* desired_config = &configuration_;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700325 if (density_override != 0 && density_override != configuration_.density) {
326 density_override_config = configuration_;
327 density_override_config.density = density_override;
328 desired_config = &density_override_config;
329 }
330
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800331 if (!is_valid_resid(resid)) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500332 LOG(ERROR) << base::StringPrintf("Invalid ID 0x%08x.", resid);
333 return kInvalidCookie;
334 }
335
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800336 const uint32_t package_id = get_package_id(resid);
337 const uint8_t type_idx = get_type_id(resid) - 1;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800338 const uint16_t entry_idx = get_entry_id(resid);
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800339
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800340 const uint8_t package_idx = package_ids_[package_id];
341 if (package_idx == 0xff) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500342 LOG(ERROR) << base::StringPrintf("No package ID %02x found for ID 0x%08x.", package_id, resid);
343 return kInvalidCookie;
344 }
345
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800346 const PackageGroup& package_group = package_groups_[package_idx];
Adam Lesinskib8b3a262018-02-09 11:01:45 -0800347 const size_t package_count = package_group.packages_.size();
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800348
349 ApkAssetsCookie best_cookie = kInvalidCookie;
350 const LoadedPackage* best_package = nullptr;
351 const ResTable_type* best_type = nullptr;
352 const ResTable_config* best_config = nullptr;
353 ResTable_config best_config_copy;
354 uint32_t best_offset = 0u;
355 uint32_t type_flags = 0u;
356
357 // If desired_config is the same as the set configuration, then we can use our filtered list
358 // and we don't need to match the configurations, since they already matched.
359 const bool use_fast_path = desired_config == &configuration_;
360
361 for (size_t pi = 0; pi < package_count; pi++) {
362 const ConfiguredPackage& loaded_package_impl = package_group.packages_[pi];
363 const LoadedPackage* loaded_package = loaded_package_impl.loaded_package_;
364 ApkAssetsCookie cookie = package_group.cookies_[pi];
365
366 // If the type IDs are offset in this package, we need to take that into account when searching
367 // for a type.
368 const TypeSpec* type_spec = loaded_package->GetTypeSpecByTypeIndex(type_idx);
369 if (UNLIKELY(type_spec == nullptr)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700370 continue;
371 }
372
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800373 uint16_t local_entry_idx = entry_idx;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700374
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800375 // If there is an IDMAP supplied with this package, translate the entry ID.
376 if (type_spec->idmap_entries != nullptr) {
377 if (!LoadedIdmap::Lookup(type_spec->idmap_entries, local_entry_idx, &local_entry_idx)) {
378 // There is no mapping, so the resource is not meant to be in this overlay package.
379 continue;
380 }
381 }
382
383 type_flags |= type_spec->GetFlagsForEntryIndex(local_entry_idx);
384
385 // If the package is an overlay, then even configurations that are the same MUST be chosen.
386 const bool package_is_overlay = loaded_package->IsOverlay();
387
388 const FilteredConfigGroup& filtered_group = loaded_package_impl.filtered_configs_[type_idx];
389 if (use_fast_path) {
390 const std::vector<ResTable_config>& candidate_configs = filtered_group.configurations;
391 const size_t type_count = candidate_configs.size();
392 for (uint32_t i = 0; i < type_count; i++) {
393 const ResTable_config& this_config = candidate_configs[i];
394
395 // We can skip calling ResTable_config::match() because we know that all candidate
396 // configurations that do NOT match have been filtered-out.
397 if ((best_config == nullptr || this_config.isBetterThan(*best_config, desired_config)) ||
398 (package_is_overlay && this_config.compare(*best_config) == 0)) {
399 // The configuration matches and is better than the previous selection.
400 // Find the entry value if it exists for this configuration.
401 const ResTable_type* type_chunk = filtered_group.types[i];
402 const uint32_t offset = LoadedPackage::GetEntryOffset(type_chunk, local_entry_idx);
403 if (offset == ResTable_type::NO_ENTRY) {
404 continue;
405 }
406
407 best_cookie = cookie;
408 best_package = loaded_package;
409 best_type = type_chunk;
410 best_config = &this_config;
411 best_offset = offset;
412 }
413 }
414 } else {
415 // This is the slower path, which doesn't use the filtered list of configurations.
416 // Here we must read the ResTable_config from the mmapped APK, convert it to host endianness
417 // and fill in any new fields that did not exist when the APK was compiled.
418 // Furthermore when selecting configurations we can't just record the pointer to the
419 // ResTable_config, we must copy it.
420 const auto iter_end = type_spec->types + type_spec->type_count;
421 for (auto iter = type_spec->types; iter != iter_end; ++iter) {
422 ResTable_config this_config;
423 this_config.copyFromDtoH((*iter)->config);
424
425 if (this_config.match(*desired_config)) {
426 if ((best_config == nullptr || this_config.isBetterThan(*best_config, desired_config)) ||
427 (package_is_overlay && this_config.compare(*best_config) == 0)) {
428 // The configuration matches and is better than the previous selection.
429 // Find the entry value if it exists for this configuration.
430 const uint32_t offset = LoadedPackage::GetEntryOffset(*iter, local_entry_idx);
431 if (offset == ResTable_type::NO_ENTRY) {
432 continue;
433 }
434
435 best_cookie = cookie;
436 best_package = loaded_package;
437 best_type = *iter;
438 best_config_copy = this_config;
439 best_config = &best_config_copy;
440 best_offset = offset;
441 }
442 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700443 }
444 }
445 }
446
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800447 if (UNLIKELY(best_cookie == kInvalidCookie)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700448 return kInvalidCookie;
449 }
450
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800451 const ResTable_entry* best_entry = LoadedPackage::GetEntryFromOffset(best_type, best_offset);
452 if (UNLIKELY(best_entry == nullptr)) {
453 return kInvalidCookie;
454 }
455
456 out_entry->entry = best_entry;
457 out_entry->config = *best_config;
458 out_entry->type_flags = type_flags;
459 out_entry->type_string_ref = StringPoolRef(best_package->GetTypeStringPool(), best_type->id - 1);
460 out_entry->entry_string_ref =
461 StringPoolRef(best_package->GetKeyStringPool(), best_entry->key.index);
Adam Lesinskida431a22016-12-29 16:08:16 -0500462 out_entry->dynamic_ref_table = &package_group.dynamic_ref_table;
Adam Lesinskida431a22016-12-29 16:08:16 -0500463 return best_cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700464}
465
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800466bool AssetManager2::GetResourceName(uint32_t resid, ResourceName* out_name) const {
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700467 FindEntryResult entry;
468 ApkAssetsCookie cookie =
469 FindEntry(resid, 0u /* density_override */, true /* stop_at_first_match */, &entry);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700470 if (cookie == kInvalidCookie) {
471 return false;
472 }
473
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800474 const LoadedPackage* package =
475 apk_assets_[cookie]->GetLoadedArsc()->GetPackageById(get_package_id(resid));
Adam Lesinskida431a22016-12-29 16:08:16 -0500476 if (package == nullptr) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700477 return false;
478 }
479
Adam Lesinskida431a22016-12-29 16:08:16 -0500480 out_name->package = package->GetPackageName().data();
481 out_name->package_len = package->GetPackageName().size();
Adam Lesinski7ad11102016-10-28 16:39:15 -0700482
483 out_name->type = entry.type_string_ref.string8(&out_name->type_len);
484 out_name->type16 = nullptr;
485 if (out_name->type == nullptr) {
486 out_name->type16 = entry.type_string_ref.string16(&out_name->type_len);
487 if (out_name->type16 == nullptr) {
488 return false;
489 }
490 }
491
492 out_name->entry = entry.entry_string_ref.string8(&out_name->entry_len);
493 out_name->entry16 = nullptr;
494 if (out_name->entry == nullptr) {
495 out_name->entry16 = entry.entry_string_ref.string16(&out_name->entry_len);
496 if (out_name->entry16 == nullptr) {
497 return false;
498 }
499 }
500 return true;
501}
502
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800503bool AssetManager2::GetResourceFlags(uint32_t resid, uint32_t* out_flags) const {
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700504 FindEntryResult entry;
505 ApkAssetsCookie cookie =
506 FindEntry(resid, 0u /* density_override */, false /* stop_at_first_match */, &entry);
507 if (cookie != kInvalidCookie) {
508 *out_flags = entry.type_flags;
509 return cookie;
510 }
511 return kInvalidCookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700512}
513
514ApkAssetsCookie AssetManager2::GetResource(uint32_t resid, bool may_be_bag,
515 uint16_t density_override, Res_value* out_value,
516 ResTable_config* out_selected_config,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800517 uint32_t* out_flags) const {
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700518 FindEntryResult entry;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700519 ApkAssetsCookie cookie =
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700520 FindEntry(resid, density_override, false /* stop_at_first_match */, &entry);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700521 if (cookie == kInvalidCookie) {
522 return kInvalidCookie;
523 }
524
Adam Lesinski498f6052017-11-29 13:24:29 -0800525 if (dtohs(entry.entry->flags) & ResTable_entry::FLAG_COMPLEX) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700526 if (!may_be_bag) {
527 LOG(ERROR) << base::StringPrintf("Resource %08x is a complex map type.", resid);
Adam Lesinski0c405242017-01-13 20:47:26 -0800528 return kInvalidCookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700529 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800530
531 // Create a reference since we can't represent this complex type as a Res_value.
532 out_value->dataType = Res_value::TYPE_REFERENCE;
533 out_value->data = resid;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800534 *out_selected_config = entry.config;
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700535 *out_flags = entry.type_flags;
Adam Lesinski0c405242017-01-13 20:47:26 -0800536 return cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700537 }
538
539 const Res_value* device_value = reinterpret_cast<const Res_value*>(
540 reinterpret_cast<const uint8_t*>(entry.entry) + dtohs(entry.entry->size));
541 out_value->copyFrom_dtoh(*device_value);
Adam Lesinskida431a22016-12-29 16:08:16 -0500542
543 // Convert the package ID to the runtime assigned package ID.
544 entry.dynamic_ref_table->lookupResourceValue(out_value);
545
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800546 *out_selected_config = entry.config;
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700547 *out_flags = entry.type_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700548 return cookie;
549}
550
Adam Lesinski0c405242017-01-13 20:47:26 -0800551ApkAssetsCookie AssetManager2::ResolveReference(ApkAssetsCookie cookie, Res_value* in_out_value,
552 ResTable_config* in_out_selected_config,
553 uint32_t* in_out_flags,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800554 uint32_t* out_last_reference) const {
Adam Lesinski0c405242017-01-13 20:47:26 -0800555 constexpr const int kMaxIterations = 20;
556
Adam Lesinski0c405242017-01-13 20:47:26 -0800557 for (size_t iteration = 0u; in_out_value->dataType == Res_value::TYPE_REFERENCE &&
558 in_out_value->data != 0u && iteration < kMaxIterations;
559 iteration++) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800560 *out_last_reference = in_out_value->data;
Adam Lesinski0c405242017-01-13 20:47:26 -0800561 uint32_t new_flags = 0u;
562 cookie = GetResource(in_out_value->data, true /*may_be_bag*/, 0u /*density_override*/,
563 in_out_value, in_out_selected_config, &new_flags);
564 if (cookie == kInvalidCookie) {
565 return kInvalidCookie;
566 }
567 if (in_out_flags != nullptr) {
568 *in_out_flags |= new_flags;
569 }
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800570 if (*out_last_reference == in_out_value->data) {
Adam Lesinski0c405242017-01-13 20:47:26 -0800571 // This reference can't be resolved, so exit now and let the caller deal with it.
572 return cookie;
573 }
574 }
575 return cookie;
576}
577
Adam Lesinski7ad11102016-10-28 16:39:15 -0700578const ResolvedBag* AssetManager2::GetBag(uint32_t resid) {
y57cd1952018-04-12 14:26:23 -0700579 auto found_resids = std::vector<uint32_t>();
580 return GetBag(resid, found_resids);
581}
582
583const ResolvedBag* AssetManager2::GetBag(uint32_t resid, std::vector<uint32_t>& child_resids) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800584 ATRACE_NAME("AssetManager::GetBag");
Adam Lesinski7ad11102016-10-28 16:39:15 -0700585
586 auto cached_iter = cached_bags_.find(resid);
587 if (cached_iter != cached_bags_.end()) {
588 return cached_iter->second.get();
589 }
590
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700591 FindEntryResult entry;
592 ApkAssetsCookie cookie =
593 FindEntry(resid, 0u /* density_override */, false /* stop_at_first_match */, &entry);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700594 if (cookie == kInvalidCookie) {
595 return nullptr;
596 }
597
598 // Check that the size of the entry header is at least as big as
599 // the desired ResTable_map_entry. Also verify that the entry
600 // was intended to be a map.
601 if (dtohs(entry.entry->size) < sizeof(ResTable_map_entry) ||
602 (dtohs(entry.entry->flags) & ResTable_entry::FLAG_COMPLEX) == 0) {
603 // Not a bag, nothing to do.
604 return nullptr;
605 }
606
607 const ResTable_map_entry* map = reinterpret_cast<const ResTable_map_entry*>(entry.entry);
608 const ResTable_map* map_entry =
609 reinterpret_cast<const ResTable_map*>(reinterpret_cast<const uint8_t*>(map) + map->size);
610 const ResTable_map* const map_entry_end = map_entry + dtohl(map->count);
611
y57cd1952018-04-12 14:26:23 -0700612 // Keep track of ids that have already been seen to prevent infinite loops caused by circular
613 // dependencies between bags
614 child_resids.push_back(resid);
615
Adam Lesinskida431a22016-12-29 16:08:16 -0500616 uint32_t parent_resid = dtohl(map->parent.ident);
y57cd1952018-04-12 14:26:23 -0700617 if (parent_resid == 0 || std::find(child_resids.begin(), child_resids.end(), parent_resid)
618 != child_resids.end()) {
619 // There is no parent or that a circular dependency exist, meaning there is nothing to
620 // inherit and we can do a simple copy of the entries in the map.
Adam Lesinski7ad11102016-10-28 16:39:15 -0700621 const size_t entry_count = map_entry_end - map_entry;
622 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
623 malloc(sizeof(ResolvedBag) + (entry_count * sizeof(ResolvedBag::Entry))))};
624 ResolvedBag::Entry* new_entry = new_bag->entries;
625 for (; map_entry != map_entry_end; ++map_entry) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500626 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -0800627 if (!is_internal_resid(new_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500628 // Attributes, arrays, etc don't have a resource id as the name. They specify
629 // other data, which would be wrong to change via a lookup.
630 if (entry.dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800631 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
632 resid);
Adam Lesinskida431a22016-12-29 16:08:16 -0500633 return nullptr;
634 }
635 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700636 new_entry->cookie = cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -0500637 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700638 new_entry->key_pool = nullptr;
639 new_entry->type_pool = nullptr;
Aurimas Liutikasd42a6702018-11-15 15:48:28 -0800640 new_entry->style = resid;
Adam Lesinski30080e22017-10-16 16:18:09 -0700641 new_entry->value.copyFrom_dtoh(map_entry->value);
642 status_t err = entry.dynamic_ref_table->lookupResourceValue(&new_entry->value);
643 if (err != NO_ERROR) {
644 LOG(ERROR) << base::StringPrintf(
645 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
646 new_entry->value.data, new_key);
647 return nullptr;
648 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700649 ++new_entry;
650 }
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700651 new_bag->type_spec_flags = entry.type_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700652 new_bag->entry_count = static_cast<uint32_t>(entry_count);
653 ResolvedBag* result = new_bag.get();
654 cached_bags_[resid] = std::move(new_bag);
655 return result;
656 }
657
Adam Lesinskida431a22016-12-29 16:08:16 -0500658 // In case the parent is a dynamic reference, resolve it.
659 entry.dynamic_ref_table->lookupResourceId(&parent_resid);
660
Adam Lesinski7ad11102016-10-28 16:39:15 -0700661 // Get the parent and do a merge of the keys.
y57cd1952018-04-12 14:26:23 -0700662 const ResolvedBag* parent_bag = GetBag(parent_resid, child_resids);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700663 if (parent_bag == nullptr) {
664 // Failed to get the parent that should exist.
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800665 LOG(ERROR) << base::StringPrintf("Failed to find parent 0x%08x of bag 0x%08x.", parent_resid,
666 resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700667 return nullptr;
668 }
669
Adam Lesinski7ad11102016-10-28 16:39:15 -0700670 // Create the max possible entries we can make. Once we construct the bag,
671 // we will realloc to fit to size.
672 const size_t max_count = parent_bag->entry_count + dtohl(map->count);
George Burgess IV09b119f2017-07-25 15:00:04 -0700673 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
674 malloc(sizeof(ResolvedBag) + (max_count * sizeof(ResolvedBag::Entry))))};
Adam Lesinski7ad11102016-10-28 16:39:15 -0700675 ResolvedBag::Entry* new_entry = new_bag->entries;
676
677 const ResolvedBag::Entry* parent_entry = parent_bag->entries;
678 const ResolvedBag::Entry* const parent_entry_end = parent_entry + parent_bag->entry_count;
679
680 // The keys are expected to be in sorted order. Merge the two bags.
681 while (map_entry != map_entry_end && parent_entry != parent_entry_end) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500682 uint32_t child_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -0800683 if (!is_internal_resid(child_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500684 if (entry.dynamic_ref_table->lookupResourceId(&child_key) != NO_ERROR) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800685 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", child_key,
686 resid);
Adam Lesinskida431a22016-12-29 16:08:16 -0500687 return nullptr;
688 }
689 }
690
Adam Lesinski7ad11102016-10-28 16:39:15 -0700691 if (child_key <= parent_entry->key) {
692 // Use the child key if it comes before the parent
693 // or is equal to the parent (overrides).
694 new_entry->cookie = cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700695 new_entry->key = child_key;
696 new_entry->key_pool = nullptr;
697 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -0700698 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -0800699 new_entry->style = resid;
Adam Lesinski30080e22017-10-16 16:18:09 -0700700 status_t err = entry.dynamic_ref_table->lookupResourceValue(&new_entry->value);
701 if (err != NO_ERROR) {
702 LOG(ERROR) << base::StringPrintf(
703 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
704 new_entry->value.data, child_key);
705 return nullptr;
706 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700707 ++map_entry;
708 } else {
709 // Take the parent entry as-is.
710 memcpy(new_entry, parent_entry, sizeof(*new_entry));
711 }
712
713 if (child_key >= parent_entry->key) {
714 // Move to the next parent entry if we used it or it was overridden.
715 ++parent_entry;
716 }
717 // Increment to the next entry to fill.
718 ++new_entry;
719 }
720
721 // Finish the child entries if they exist.
722 while (map_entry != map_entry_end) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500723 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -0800724 if (!is_internal_resid(new_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500725 if (entry.dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800726 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
727 resid);
Adam Lesinskida431a22016-12-29 16:08:16 -0500728 return nullptr;
729 }
730 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700731 new_entry->cookie = cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -0500732 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700733 new_entry->key_pool = nullptr;
734 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -0700735 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -0800736 new_entry->style = resid;
Adam Lesinski30080e22017-10-16 16:18:09 -0700737 status_t err = entry.dynamic_ref_table->lookupResourceValue(&new_entry->value);
738 if (err != NO_ERROR) {
739 LOG(ERROR) << base::StringPrintf("Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.",
740 new_entry->value.dataType, new_entry->value.data, new_key);
741 return nullptr;
742 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700743 ++map_entry;
744 ++new_entry;
745 }
746
747 // Finish the parent entries if they exist.
748 if (parent_entry != parent_entry_end) {
749 // Take the rest of the parent entries as-is.
750 const size_t num_entries_to_copy = parent_entry_end - parent_entry;
751 memcpy(new_entry, parent_entry, num_entries_to_copy * sizeof(*new_entry));
752 new_entry += num_entries_to_copy;
753 }
754
755 // Resize the resulting array to fit.
756 const size_t actual_count = new_entry - new_bag->entries;
757 if (actual_count != max_count) {
George Burgess IV09b119f2017-07-25 15:00:04 -0700758 new_bag.reset(reinterpret_cast<ResolvedBag*>(realloc(
759 new_bag.release(), sizeof(ResolvedBag) + (actual_count * sizeof(ResolvedBag::Entry)))));
Adam Lesinski7ad11102016-10-28 16:39:15 -0700760 }
761
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700762 // Combine flags from the parent and our own bag.
763 new_bag->type_spec_flags = entry.type_flags | parent_bag->type_spec_flags;
George Burgess IV09b119f2017-07-25 15:00:04 -0700764 new_bag->entry_count = static_cast<uint32_t>(actual_count);
765 ResolvedBag* result = new_bag.get();
766 cached_bags_[resid] = std::move(new_bag);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700767 return result;
768}
769
Adam Lesinski929d6512017-01-16 19:11:19 -0800770static bool Utf8ToUtf16(const StringPiece& str, std::u16string* out) {
771 ssize_t len =
772 utf8_to_utf16_length(reinterpret_cast<const uint8_t*>(str.data()), str.size(), false);
773 if (len < 0) {
774 return false;
775 }
776 out->resize(static_cast<size_t>(len));
777 utf8_to_utf16(reinterpret_cast<const uint8_t*>(str.data()), str.size(), &*out->begin(),
778 static_cast<size_t>(len + 1));
779 return true;
780}
781
Adam Lesinski0c405242017-01-13 20:47:26 -0800782uint32_t AssetManager2::GetResourceId(const std::string& resource_name,
783 const std::string& fallback_type,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800784 const std::string& fallback_package) const {
Adam Lesinski929d6512017-01-16 19:11:19 -0800785 StringPiece package_name, type, entry;
786 if (!ExtractResourceName(resource_name, &package_name, &type, &entry)) {
787 return 0u;
788 }
789
790 if (entry.empty()) {
791 return 0u;
792 }
793
794 if (package_name.empty()) {
795 package_name = fallback_package;
796 }
797
798 if (type.empty()) {
799 type = fallback_type;
800 }
801
802 std::u16string type16;
803 if (!Utf8ToUtf16(type, &type16)) {
804 return 0u;
805 }
806
807 std::u16string entry16;
808 if (!Utf8ToUtf16(entry, &entry16)) {
809 return 0u;
810 }
811
812 const StringPiece16 kAttr16 = u"attr";
813 const static std::u16string kAttrPrivate16 = u"^attr-private";
814
815 for (const PackageGroup& package_group : package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800816 for (const ConfiguredPackage& package_impl : package_group.packages_) {
817 const LoadedPackage* package = package_impl.loaded_package_;
Adam Lesinski929d6512017-01-16 19:11:19 -0800818 if (package_name != package->GetPackageName()) {
819 // All packages in the same group are expected to have the same package name.
820 break;
821 }
822
823 uint32_t resid = package->FindEntryByName(type16, entry16);
824 if (resid == 0u && kAttr16 == type16) {
825 // Private attributes in libraries (such as the framework) are sometimes encoded
826 // under the type '^attr-private' in order to leave the ID space of public 'attr'
827 // free for future additions. Check '^attr-private' for the same name.
828 resid = package->FindEntryByName(kAttrPrivate16, entry16);
829 }
830
831 if (resid != 0u) {
832 return fix_package_id(resid, package_group.dynamic_ref_table.mAssignedPackageId);
833 }
834 }
835 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800836 return 0u;
837}
838
Mårten Kongstad668ec5b2018-06-11 14:11:33 +0200839void AssetManager2::RebuildFilterList(bool filter_incompatible_configs) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800840 for (PackageGroup& group : package_groups_) {
841 for (ConfiguredPackage& impl : group.packages_) {
842 // Destroy it.
843 impl.filtered_configs_.~ByteBucketArray();
844
845 // Re-create it.
846 new (&impl.filtered_configs_) ByteBucketArray<FilteredConfigGroup>();
847
848 // Create the filters here.
849 impl.loaded_package_->ForEachTypeSpec([&](const TypeSpec* spec, uint8_t type_index) {
850 FilteredConfigGroup& group = impl.filtered_configs_.editItemAt(type_index);
851 const auto iter_end = spec->types + spec->type_count;
852 for (auto iter = spec->types; iter != iter_end; ++iter) {
853 ResTable_config this_config;
854 this_config.copyFromDtoH((*iter)->config);
Mårten Kongstad668ec5b2018-06-11 14:11:33 +0200855 if (!filter_incompatible_configs || this_config.match(configuration_)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800856 group.configurations.push_back(this_config);
857 group.types.push_back(*iter);
858 }
859 }
860 });
861 }
862 }
863}
864
Adam Lesinski7ad11102016-10-28 16:39:15 -0700865void AssetManager2::InvalidateCaches(uint32_t diff) {
866 if (diff == 0xffffffffu) {
867 // Everything must go.
868 cached_bags_.clear();
869 return;
870 }
871
872 // Be more conservative with what gets purged. Only if the bag has other possible
873 // variations with respect to what changed (diff) should we remove it.
874 for (auto iter = cached_bags_.cbegin(); iter != cached_bags_.cend();) {
875 if (diff & iter->second->type_spec_flags) {
876 iter = cached_bags_.erase(iter);
877 } else {
878 ++iter;
879 }
880 }
881}
882
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -0700883uint8_t AssetManager2::GetAssignedPackageId(const LoadedPackage* package) {
884 for (auto& package_group : package_groups_) {
885 for (auto& package2 : package_group.packages_) {
886 if (package2.loaded_package_ == package) {
887 return package_group.dynamic_ref_table.mAssignedPackageId;
888 }
889 }
890 }
891 return 0;
892}
893
Adam Lesinski30080e22017-10-16 16:18:09 -0700894std::unique_ptr<Theme> AssetManager2::NewTheme() {
895 return std::unique_ptr<Theme>(new Theme(this));
896}
897
898Theme::Theme(AssetManager2* asset_manager) : asset_manager_(asset_manager) {
899}
900
901Theme::~Theme() = default;
902
903namespace {
904
905struct ThemeEntry {
906 ApkAssetsCookie cookie;
907 uint32_t type_spec_flags;
908 Res_value value;
909};
910
911struct ThemeType {
912 int entry_count;
913 ThemeEntry entries[0];
914};
915
916constexpr size_t kTypeCount = std::numeric_limits<uint8_t>::max() + 1;
917
918} // namespace
919
920struct Theme::Package {
921 // Each element of Type will be a dynamically sized object
922 // allocated to have the entries stored contiguously with the Type.
923 std::array<util::unique_cptr<ThemeType>, kTypeCount> types;
924};
Adam Lesinski7ad11102016-10-28 16:39:15 -0700925
926bool Theme::ApplyStyle(uint32_t resid, bool force) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800927 ATRACE_NAME("Theme::ApplyStyle");
Adam Lesinski7ad11102016-10-28 16:39:15 -0700928
929 const ResolvedBag* bag = asset_manager_->GetBag(resid);
930 if (bag == nullptr) {
931 return false;
932 }
933
934 // Merge the flags from this style.
935 type_spec_flags_ |= bag->type_spec_flags;
936
Adam Lesinski30080e22017-10-16 16:18:09 -0700937 int last_type_idx = -1;
938 int last_package_idx = -1;
939 Package* last_package = nullptr;
940 ThemeType* last_type = nullptr;
941
942 // Iterate backwards, because each bag is sorted in ascending key ID order, meaning we will only
943 // need to perform one resize per type.
944 using reverse_bag_iterator = std::reverse_iterator<const ResolvedBag::Entry*>;
945 const auto bag_iter_end = reverse_bag_iterator(begin(bag));
946 for (auto bag_iter = reverse_bag_iterator(end(bag)); bag_iter != bag_iter_end; ++bag_iter) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700947 const uint32_t attr_resid = bag_iter->key;
948
Adam Lesinski30080e22017-10-16 16:18:09 -0700949 // If the resource ID passed in is not a style, the key can be some other identifier that is not
950 // a resource ID. We should fail fast instead of operating with strange resource IDs.
Adam Lesinski929d6512017-01-16 19:11:19 -0800951 if (!is_valid_resid(attr_resid)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700952 return false;
953 }
954
Adam Lesinski30080e22017-10-16 16:18:09 -0700955 // We don't use the 0-based index for the type so that we can avoid doing ID validation
956 // upon lookup. Instead, we keep space for the type ID 0 in our data structures. Since
957 // the construction of this type is guarded with a resource ID check, it will never be
958 // populated, and querying type ID 0 will always fail.
959 const int package_idx = get_package_id(attr_resid);
960 const int type_idx = get_type_id(attr_resid);
961 const int entry_idx = get_entry_id(attr_resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700962
Adam Lesinski30080e22017-10-16 16:18:09 -0700963 if (last_package_idx != package_idx) {
964 std::unique_ptr<Package>& package = packages_[package_idx];
965 if (package == nullptr) {
966 package.reset(new Package());
Adam Lesinski7ad11102016-10-28 16:39:15 -0700967 }
Adam Lesinski30080e22017-10-16 16:18:09 -0700968 last_package_idx = package_idx;
969 last_package = package.get();
970 last_type_idx = -1;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700971 }
Adam Lesinski30080e22017-10-16 16:18:09 -0700972
973 if (last_type_idx != type_idx) {
974 util::unique_cptr<ThemeType>& type = last_package->types[type_idx];
975 if (type == nullptr) {
976 // Allocate enough memory to contain this entry_idx. Since we're iterating in reverse over
977 // a sorted list of attributes, this shouldn't be resized again during this method call.
978 type.reset(reinterpret_cast<ThemeType*>(
979 calloc(sizeof(ThemeType) + (entry_idx + 1) * sizeof(ThemeEntry), 1)));
980 type->entry_count = entry_idx + 1;
981 } else if (entry_idx >= type->entry_count) {
982 // Reallocate the memory to contain this entry_idx. Since we're iterating in reverse over
983 // a sorted list of attributes, this shouldn't be resized again during this method call.
984 const int new_count = entry_idx + 1;
985 type.reset(reinterpret_cast<ThemeType*>(
986 realloc(type.release(), sizeof(ThemeType) + (new_count * sizeof(ThemeEntry)))));
987
988 // Clear out the newly allocated space (which isn't zeroed).
989 memset(type->entries + type->entry_count, 0,
990 (new_count - type->entry_count) * sizeof(ThemeEntry));
991 type->entry_count = new_count;
992 }
993 last_type_idx = type_idx;
994 last_type = type.get();
995 }
996
997 ThemeEntry& entry = last_type->entries[entry_idx];
998 if (force || (entry.value.dataType == Res_value::TYPE_NULL &&
999 entry.value.data != Res_value::DATA_NULL_EMPTY)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001000 entry.cookie = bag_iter->cookie;
1001 entry.type_spec_flags |= bag->type_spec_flags;
1002 entry.value = bag_iter->value;
1003 }
1004 }
1005 return true;
1006}
1007
1008ApkAssetsCookie Theme::GetAttribute(uint32_t resid, Res_value* out_value,
1009 uint32_t* out_flags) const {
Adam Lesinski30080e22017-10-16 16:18:09 -07001010 int cnt = 20;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001011
1012 uint32_t type_spec_flags = 0u;
1013
Adam Lesinski30080e22017-10-16 16:18:09 -07001014 do {
1015 const int package_idx = get_package_id(resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001016 const Package* package = packages_[package_idx].get();
Adam Lesinski30080e22017-10-16 16:18:09 -07001017 if (package != nullptr) {
1018 // The themes are constructed with a 1-based type ID, so no need to decrement here.
1019 const int type_idx = get_type_id(resid);
1020 const ThemeType* type = package->types[type_idx].get();
1021 if (type != nullptr) {
1022 const int entry_idx = get_entry_id(resid);
1023 if (entry_idx < type->entry_count) {
1024 const ThemeEntry& entry = type->entries[entry_idx];
1025 type_spec_flags |= entry.type_spec_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001026
Adam Lesinski30080e22017-10-16 16:18:09 -07001027 if (entry.value.dataType == Res_value::TYPE_ATTRIBUTE) {
1028 if (cnt > 0) {
1029 cnt--;
1030 resid = entry.value.data;
1031 continue;
1032 }
1033 return kInvalidCookie;
1034 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001035
Adam Lesinski30080e22017-10-16 16:18:09 -07001036 // @null is different than @empty.
1037 if (entry.value.dataType == Res_value::TYPE_NULL &&
1038 entry.value.data != Res_value::DATA_NULL_EMPTY) {
1039 return kInvalidCookie;
1040 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001041
Adam Lesinski30080e22017-10-16 16:18:09 -07001042 *out_value = entry.value;
Adam Lesinskida431a22016-12-29 16:08:16 -05001043 *out_flags = type_spec_flags;
Adam Lesinski30080e22017-10-16 16:18:09 -07001044 return entry.cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -05001045 }
Adam Lesinskida431a22016-12-29 16:08:16 -05001046 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001047 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001048 break;
1049 } while (true);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001050 return kInvalidCookie;
1051}
1052
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001053ApkAssetsCookie Theme::ResolveAttributeReference(ApkAssetsCookie cookie, Res_value* in_out_value,
1054 ResTable_config* in_out_selected_config,
1055 uint32_t* in_out_type_spec_flags,
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001056 uint32_t* out_last_ref) const {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001057 if (in_out_value->dataType == Res_value::TYPE_ATTRIBUTE) {
1058 uint32_t new_flags;
1059 cookie = GetAttribute(in_out_value->data, in_out_value, &new_flags);
1060 if (cookie == kInvalidCookie) {
1061 return kInvalidCookie;
1062 }
1063
1064 if (in_out_type_spec_flags != nullptr) {
1065 *in_out_type_spec_flags |= new_flags;
1066 }
1067 }
1068 return asset_manager_->ResolveReference(cookie, in_out_value, in_out_selected_config,
1069 in_out_type_spec_flags, out_last_ref);
1070}
1071
Adam Lesinski7ad11102016-10-28 16:39:15 -07001072void Theme::Clear() {
1073 type_spec_flags_ = 0u;
1074 for (std::unique_ptr<Package>& package : packages_) {
1075 package.reset();
1076 }
1077}
1078
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001079void Theme::SetTo(const Theme& o) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001080 if (this == &o) {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001081 return;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001082 }
1083
Adam Lesinski7ad11102016-10-28 16:39:15 -07001084 type_spec_flags_ = o.type_spec_flags_;
1085
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001086 if (asset_manager_ == o.asset_manager_) {
1087 // The theme comes from the same asset manager so all theme data can be copied exactly
1088 for (size_t p = 0; p < packages_.size(); p++) {
1089 const Package *package = o.packages_[p].get();
1090 if (package == nullptr) {
1091 // The other theme doesn't have this package, clear ours.
1092 packages_[p].reset();
Adam Lesinski7ad11102016-10-28 16:39:15 -07001093 continue;
1094 }
1095
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001096 if (packages_[p] == nullptr) {
1097 // The other theme has this package, but we don't. Make one.
1098 packages_[p].reset(new Package());
1099 }
1100
1101 for (size_t t = 0; t < package->types.size(); t++) {
1102 const ThemeType *type = package->types[t].get();
1103 if (type == nullptr) {
1104 // The other theme doesn't have this type, clear ours.
1105 packages_[p]->types[t].reset();
1106 continue;
1107 }
1108
1109 // Create a new type and update it to theirs.
1110 const size_t type_alloc_size = sizeof(ThemeType) + (type->entry_count * sizeof(ThemeEntry));
1111 void *copied_data = malloc(type_alloc_size);
1112 memcpy(copied_data, type, type_alloc_size);
1113 packages_[p]->types[t].reset(reinterpret_cast<ThemeType *>(copied_data));
1114 }
1115 }
1116 } else {
1117 std::map<ApkAssetsCookie, ApkAssetsCookie> src_to_dest_asset_cookies;
1118 typedef std::map<int, int> SourceToDestinationRuntimePackageMap;
1119 std::map<ApkAssetsCookie, SourceToDestinationRuntimePackageMap> src_asset_cookie_id_map;
1120
1121 // Determine which ApkAssets are loaded in both theme AssetManagers
1122 std::vector<const ApkAssets*> src_assets = o.asset_manager_->GetApkAssets();
1123 for (size_t i = 0; i < src_assets.size(); i++) {
1124 const ApkAssets* src_asset = src_assets[i];
1125
1126 std::vector<const ApkAssets*> dest_assets = asset_manager_->GetApkAssets();
1127 for (size_t j = 0; j < dest_assets.size(); j++) {
1128 const ApkAssets* dest_asset = dest_assets[j];
1129
1130 // Map the runtime package of the source apk asset to the destination apk asset
1131 if (src_asset->GetPath() == dest_asset->GetPath()) {
1132 const std::vector<std::unique_ptr<const LoadedPackage>>& src_packages =
1133 src_asset->GetLoadedArsc()->GetPackages();
1134 const std::vector<std::unique_ptr<const LoadedPackage>>& dest_packages =
1135 dest_asset->GetLoadedArsc()->GetPackages();
1136
1137 SourceToDestinationRuntimePackageMap package_map;
1138
1139 // The source and destination package should have the same number of packages loaded in
1140 // the same order.
1141 const size_t N = src_packages.size();
1142 CHECK(N == dest_packages.size())
1143 << " LoadedArsc " << src_asset->GetPath() << " differs number of packages.";
1144 for (size_t p = 0; p < N; p++) {
1145 auto& src_package = src_packages[p];
1146 auto& dest_package = dest_packages[p];
1147 CHECK(src_package->GetPackageName() == dest_package->GetPackageName())
1148 << " Package " << src_package->GetPackageName() << " differs in load order.";
1149
1150 int src_package_id = o.asset_manager_->GetAssignedPackageId(src_package.get());
1151 int dest_package_id = asset_manager_->GetAssignedPackageId(dest_package.get());
1152 package_map[src_package_id] = dest_package_id;
1153 }
1154
1155 src_to_dest_asset_cookies.insert(std::pair<ApkAssetsCookie, ApkAssetsCookie>(i, j));
1156 src_asset_cookie_id_map.insert(
1157 std::pair<ApkAssetsCookie, SourceToDestinationRuntimePackageMap>(i, package_map));
1158 break;
1159 }
1160 }
1161 }
1162
1163 // Reset the data in the destination theme
1164 for (size_t p = 0; p < packages_.size(); p++) {
1165 if (packages_[p] != nullptr) {
1166 packages_[p].reset();
1167 }
1168 }
1169
1170 for (size_t p = 0; p < packages_.size(); p++) {
1171 const Package *package = o.packages_[p].get();
1172 if (package == nullptr) {
1173 continue;
1174 }
1175
1176 for (size_t t = 0; t < package->types.size(); t++) {
1177 const ThemeType *type = package->types[t].get();
1178 if (type == nullptr) {
1179 continue;
1180 }
1181
1182 for (size_t e = 0; e < type->entry_count; e++) {
1183 const ThemeEntry &entry = type->entries[e];
1184 if (entry.value.dataType == Res_value::TYPE_NULL &&
1185 entry.value.data != Res_value::DATA_NULL_EMPTY) {
1186 continue;
1187 }
1188
1189 // The package id of the attribute needs to be rewritten to the package id of the value in
1190 // the destination
1191 int attribute_dest_package_id = p;
1192 if (attribute_dest_package_id != 0x01) {
1193 // Find the cookie of the attribute resource id
1194 FindEntryResult attribute_entry_result;
1195 ApkAssetsCookie attribute_cookie =
1196 o.asset_manager_->FindEntry(make_resid(p, t, e), 0 /* density_override */ , false,
1197 &attribute_entry_result);
1198
1199 // Determine the package id of the attribute in the destination AssetManager
1200 auto attribute_package_map = src_asset_cookie_id_map.find(attribute_cookie);
1201 if (attribute_package_map == src_asset_cookie_id_map.end()) {
1202 continue;
1203 }
1204 auto attribute_dest_package = attribute_package_map->second.find(
1205 attribute_dest_package_id);
1206 if (attribute_dest_package == attribute_package_map->second.end()) {
1207 continue;
1208 }
1209 attribute_dest_package_id = attribute_dest_package->second;
1210 }
1211
1212 // If the attribute value represents an attribute or reference, the package id of the
1213 // value needs to be rewritten to the package id of the value in the destination
1214 uint32_t attribue_data = entry.value.data;
1215 if (entry.value.dataType == Res_value::TYPE_DYNAMIC_ATTRIBUTE
1216 || entry.value.dataType == Res_value::TYPE_DYNAMIC_REFERENCE
1217 || entry.value.dataType == Res_value::TYPE_ATTRIBUTE
1218 || entry.value.dataType == Res_value::TYPE_REFERENCE) {
1219
1220 // Determine the package id of the reference in the destination AssetManager
1221 auto value_package_map = src_asset_cookie_id_map.find(entry.cookie);
1222 if (value_package_map == src_asset_cookie_id_map.end()) {
1223 continue;
1224 }
1225
1226 auto value_dest_package = value_package_map->second.find(
1227 get_package_id(entry.value.data));
1228 if (value_dest_package == value_package_map->second.end()) {
1229 continue;
1230 }
1231
1232 attribue_data = fix_package_id(entry.value.data, value_dest_package->second);
1233 }
1234
1235 // Lazily instantiate the destination package
1236 std::unique_ptr<Package>& dest_package = packages_[attribute_dest_package_id];
1237 if (dest_package == nullptr) {
1238 dest_package.reset(new Package());
1239 }
1240
1241 // Lazily instantiate and resize the destination type
1242 util::unique_cptr<ThemeType>& dest_type = dest_package->types[t];
1243 if (dest_type == nullptr || dest_type->entry_count < type->entry_count) {
1244 const size_t type_alloc_size = sizeof(ThemeType)
1245 + (type->entry_count * sizeof(ThemeEntry));
1246 void* dest_data = malloc(type_alloc_size);
1247 memset(dest_data, 0, type->entry_count * sizeof(ThemeEntry));
1248
1249 // Copy the existing destination type values if the type is resized
1250 if (dest_type != nullptr) {
1251 memcpy(dest_data, type, sizeof(ThemeType)
1252 + (dest_type->entry_count * sizeof(ThemeEntry)));
1253 }
1254
1255 dest_type.reset(reinterpret_cast<ThemeType *>(dest_data));
1256 dest_type->entry_count = type->entry_count;
1257 }
1258
1259 // Find the cookie of the value in the destination
1260 auto value_dest_cookie = src_to_dest_asset_cookies.find(entry.cookie);
1261 if (value_dest_cookie == src_to_dest_asset_cookies.end()) {
1262 continue;
1263 }
1264
1265 dest_type->entries[e].cookie = value_dest_cookie->second;
1266 dest_type->entries[e].value.dataType = entry.value.dataType;
1267 dest_type->entries[e].value.data = attribue_data;
1268 dest_type->entries[e].type_spec_flags = entry.type_spec_flags;
1269 }
1270 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001271 }
1272 }
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001273}
1274
1275void Theme::Dump() const {
1276 base::ScopedLogSeverity _log(base::INFO);
1277 LOG(INFO) << base::StringPrintf("Theme(this=%p, AssetManager2=%p)", this, asset_manager_);
1278
1279 for (int p = 0; p < packages_.size(); p++) {
1280 auto& package = packages_[p];
1281 if (package == nullptr) {
1282 continue;
1283 }
1284
1285 for (int t = 0; t < package->types.size(); t++) {
1286 auto& type = package->types[t];
1287 if (type == nullptr) {
1288 continue;
1289 }
1290
1291 for (int e = 0; e < type->entry_count; e++) {
1292 auto& entry = type->entries[e];
1293 if (entry.value.dataType == Res_value::TYPE_NULL &&
1294 entry.value.data != Res_value::DATA_NULL_EMPTY) {
1295 continue;
1296 }
1297
1298 LOG(INFO) << base::StringPrintf(" entry(0x%08x)=(0x%08x) type=(0x%02x), cookie(%d)",
1299 make_resid(p, t, e), entry.value.data,
1300 entry.value.dataType, entry.cookie);
1301 }
1302 }
1303 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001304}
1305
1306} // namespace android