blob: ad9ec02648b1d3364c8ef074121adb3e4f289a42 [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_) {
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800220 bool found_system_package = false;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800221 for (const ConfiguredPackage& package : package_group.packages_) {
222 if (exclude_system && package.loaded_package_->IsSystem()) {
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800223 found_system_package = true;
Adam Lesinski0c405242017-01-13 20:47:26 -0800224 continue;
225 }
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800226
227 if (exclude_system && package.loaded_package_->IsOverlay() && found_system_package) {
228 // Overlays must appear after the target package to take effect. Any overlay found in the
229 // same package as a system package is able to overlay system resources.
230 continue;
231 }
232
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800233 package.loaded_package_->CollectConfigurations(exclude_mipmap, &configurations);
Adam Lesinski0c405242017-01-13 20:47:26 -0800234 }
235 }
236 return configurations;
237}
238
239std::set<std::string> AssetManager2::GetResourceLocales(bool exclude_system,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800240 bool merge_equivalent_languages) const {
241 ATRACE_NAME("AssetManager::GetResourceLocales");
Adam Lesinski0c405242017-01-13 20:47:26 -0800242 std::set<std::string> locales;
243 for (const PackageGroup& package_group : package_groups_) {
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800244 bool found_system_package = false;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800245 for (const ConfiguredPackage& package : package_group.packages_) {
246 if (exclude_system && package.loaded_package_->IsSystem()) {
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800247 found_system_package = true;
Adam Lesinski0c405242017-01-13 20:47:26 -0800248 continue;
249 }
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800250
251 if (exclude_system && package.loaded_package_->IsOverlay() && found_system_package) {
252 // Overlays must appear after the target package to take effect. Any overlay found in the
253 // same package as a system package is able to overlay system resources.
254 continue;
255 }
256
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800257 package.loaded_package_->CollectLocales(merge_equivalent_languages, &locales);
Adam Lesinski0c405242017-01-13 20:47:26 -0800258 }
259 }
260 return locales;
261}
262
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800263std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename,
264 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700265 const std::string new_path = "assets/" + filename;
266 return OpenNonAsset(new_path, mode);
267}
268
269std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename, ApkAssetsCookie cookie,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800270 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700271 const std::string new_path = "assets/" + filename;
272 return OpenNonAsset(new_path, cookie, mode);
273}
274
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800275std::unique_ptr<AssetDir> AssetManager2::OpenDir(const std::string& dirname) const {
276 ATRACE_NAME("AssetManager::OpenDir");
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800277
278 std::string full_path = "assets/" + dirname;
279 std::unique_ptr<SortedVector<AssetDir::FileInfo>> files =
280 util::make_unique<SortedVector<AssetDir::FileInfo>>();
281
282 // Start from the back.
283 for (auto iter = apk_assets_.rbegin(); iter != apk_assets_.rend(); ++iter) {
284 const ApkAssets* apk_assets = *iter;
285
286 auto func = [&](const StringPiece& name, FileType type) {
287 AssetDir::FileInfo info;
288 info.setFileName(String8(name.data(), name.size()));
289 info.setFileType(type);
290 info.setSourceName(String8(apk_assets->GetPath().c_str()));
291 files->add(info);
292 };
293
294 if (!apk_assets->ForEachFile(full_path, func)) {
295 return {};
296 }
297 }
298
299 std::unique_ptr<AssetDir> asset_dir = util::make_unique<AssetDir>();
300 asset_dir->setFileList(files.release());
301 return asset_dir;
302}
303
Adam Lesinski7ad11102016-10-28 16:39:15 -0700304// Search in reverse because that's how we used to do it and we need to preserve behaviour.
305// This is unfortunate, because ClassLoaders delegate to the parent first, so the order
306// is inconsistent for split APKs.
307std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
308 Asset::AccessMode mode,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800309 ApkAssetsCookie* out_cookie) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700310 for (int32_t i = apk_assets_.size() - 1; i >= 0; i--) {
311 std::unique_ptr<Asset> asset = apk_assets_[i]->Open(filename, mode);
312 if (asset) {
313 if (out_cookie != nullptr) {
314 *out_cookie = i;
315 }
316 return asset;
317 }
318 }
319
320 if (out_cookie != nullptr) {
321 *out_cookie = kInvalidCookie;
322 }
323 return {};
324}
325
326std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800327 ApkAssetsCookie cookie,
328 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700329 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
330 return {};
331 }
332 return apk_assets_[cookie]->Open(filename, mode);
333}
334
335ApkAssetsCookie AssetManager2::FindEntry(uint32_t resid, uint16_t density_override,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800336 bool /*stop_at_first_match*/,
337 FindEntryResult* out_entry) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700338 // Might use this if density_override != 0.
339 ResTable_config density_override_config;
340
341 // Select our configuration or generate a density override configuration.
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800342 const ResTable_config* desired_config = &configuration_;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700343 if (density_override != 0 && density_override != configuration_.density) {
344 density_override_config = configuration_;
345 density_override_config.density = density_override;
346 desired_config = &density_override_config;
347 }
348
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800349 if (!is_valid_resid(resid)) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500350 LOG(ERROR) << base::StringPrintf("Invalid ID 0x%08x.", resid);
351 return kInvalidCookie;
352 }
353
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800354 const uint32_t package_id = get_package_id(resid);
355 const uint8_t type_idx = get_type_id(resid) - 1;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800356 const uint16_t entry_idx = get_entry_id(resid);
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800357
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800358 const uint8_t package_idx = package_ids_[package_id];
359 if (package_idx == 0xff) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500360 LOG(ERROR) << base::StringPrintf("No package ID %02x found for ID 0x%08x.", package_id, resid);
361 return kInvalidCookie;
362 }
363
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800364 const PackageGroup& package_group = package_groups_[package_idx];
Adam Lesinskib8b3a262018-02-09 11:01:45 -0800365 const size_t package_count = package_group.packages_.size();
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800366
367 ApkAssetsCookie best_cookie = kInvalidCookie;
368 const LoadedPackage* best_package = nullptr;
369 const ResTable_type* best_type = nullptr;
370 const ResTable_config* best_config = nullptr;
371 ResTable_config best_config_copy;
372 uint32_t best_offset = 0u;
373 uint32_t type_flags = 0u;
374
375 // If desired_config is the same as the set configuration, then we can use our filtered list
376 // and we don't need to match the configurations, since they already matched.
377 const bool use_fast_path = desired_config == &configuration_;
378
379 for (size_t pi = 0; pi < package_count; pi++) {
380 const ConfiguredPackage& loaded_package_impl = package_group.packages_[pi];
381 const LoadedPackage* loaded_package = loaded_package_impl.loaded_package_;
382 ApkAssetsCookie cookie = package_group.cookies_[pi];
383
384 // If the type IDs are offset in this package, we need to take that into account when searching
385 // for a type.
386 const TypeSpec* type_spec = loaded_package->GetTypeSpecByTypeIndex(type_idx);
387 if (UNLIKELY(type_spec == nullptr)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700388 continue;
389 }
390
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800391 uint16_t local_entry_idx = entry_idx;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700392
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800393 // If there is an IDMAP supplied with this package, translate the entry ID.
394 if (type_spec->idmap_entries != nullptr) {
395 if (!LoadedIdmap::Lookup(type_spec->idmap_entries, local_entry_idx, &local_entry_idx)) {
396 // There is no mapping, so the resource is not meant to be in this overlay package.
397 continue;
398 }
399 }
400
401 type_flags |= type_spec->GetFlagsForEntryIndex(local_entry_idx);
402
403 // If the package is an overlay, then even configurations that are the same MUST be chosen.
404 const bool package_is_overlay = loaded_package->IsOverlay();
405
406 const FilteredConfigGroup& filtered_group = loaded_package_impl.filtered_configs_[type_idx];
407 if (use_fast_path) {
408 const std::vector<ResTable_config>& candidate_configs = filtered_group.configurations;
409 const size_t type_count = candidate_configs.size();
410 for (uint32_t i = 0; i < type_count; i++) {
411 const ResTable_config& this_config = candidate_configs[i];
412
413 // We can skip calling ResTable_config::match() because we know that all candidate
414 // configurations that do NOT match have been filtered-out.
415 if ((best_config == nullptr || this_config.isBetterThan(*best_config, desired_config)) ||
416 (package_is_overlay && this_config.compare(*best_config) == 0)) {
417 // The configuration matches and is better than the previous selection.
418 // Find the entry value if it exists for this configuration.
419 const ResTable_type* type_chunk = filtered_group.types[i];
420 const uint32_t offset = LoadedPackage::GetEntryOffset(type_chunk, local_entry_idx);
421 if (offset == ResTable_type::NO_ENTRY) {
422 continue;
423 }
424
425 best_cookie = cookie;
426 best_package = loaded_package;
427 best_type = type_chunk;
428 best_config = &this_config;
429 best_offset = offset;
430 }
431 }
432 } else {
433 // This is the slower path, which doesn't use the filtered list of configurations.
434 // Here we must read the ResTable_config from the mmapped APK, convert it to host endianness
435 // and fill in any new fields that did not exist when the APK was compiled.
436 // Furthermore when selecting configurations we can't just record the pointer to the
437 // ResTable_config, we must copy it.
438 const auto iter_end = type_spec->types + type_spec->type_count;
439 for (auto iter = type_spec->types; iter != iter_end; ++iter) {
440 ResTable_config this_config;
441 this_config.copyFromDtoH((*iter)->config);
442
443 if (this_config.match(*desired_config)) {
444 if ((best_config == nullptr || this_config.isBetterThan(*best_config, desired_config)) ||
445 (package_is_overlay && this_config.compare(*best_config) == 0)) {
446 // The configuration matches and is better than the previous selection.
447 // Find the entry value if it exists for this configuration.
448 const uint32_t offset = LoadedPackage::GetEntryOffset(*iter, local_entry_idx);
449 if (offset == ResTable_type::NO_ENTRY) {
450 continue;
451 }
452
453 best_cookie = cookie;
454 best_package = loaded_package;
455 best_type = *iter;
456 best_config_copy = this_config;
457 best_config = &best_config_copy;
458 best_offset = offset;
459 }
460 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700461 }
462 }
463 }
464
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800465 if (UNLIKELY(best_cookie == kInvalidCookie)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700466 return kInvalidCookie;
467 }
468
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800469 const ResTable_entry* best_entry = LoadedPackage::GetEntryFromOffset(best_type, best_offset);
470 if (UNLIKELY(best_entry == nullptr)) {
471 return kInvalidCookie;
472 }
473
474 out_entry->entry = best_entry;
475 out_entry->config = *best_config;
476 out_entry->type_flags = type_flags;
477 out_entry->type_string_ref = StringPoolRef(best_package->GetTypeStringPool(), best_type->id - 1);
478 out_entry->entry_string_ref =
479 StringPoolRef(best_package->GetKeyStringPool(), best_entry->key.index);
Adam Lesinskida431a22016-12-29 16:08:16 -0500480 out_entry->dynamic_ref_table = &package_group.dynamic_ref_table;
Adam Lesinskida431a22016-12-29 16:08:16 -0500481 return best_cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700482}
483
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800484bool AssetManager2::GetResourceName(uint32_t resid, ResourceName* out_name) const {
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700485 FindEntryResult entry;
486 ApkAssetsCookie cookie =
487 FindEntry(resid, 0u /* density_override */, true /* stop_at_first_match */, &entry);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700488 if (cookie == kInvalidCookie) {
489 return false;
490 }
491
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800492 const LoadedPackage* package =
493 apk_assets_[cookie]->GetLoadedArsc()->GetPackageById(get_package_id(resid));
Adam Lesinskida431a22016-12-29 16:08:16 -0500494 if (package == nullptr) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700495 return false;
496 }
497
Adam Lesinskida431a22016-12-29 16:08:16 -0500498 out_name->package = package->GetPackageName().data();
499 out_name->package_len = package->GetPackageName().size();
Adam Lesinski7ad11102016-10-28 16:39:15 -0700500
501 out_name->type = entry.type_string_ref.string8(&out_name->type_len);
502 out_name->type16 = nullptr;
503 if (out_name->type == nullptr) {
504 out_name->type16 = entry.type_string_ref.string16(&out_name->type_len);
505 if (out_name->type16 == nullptr) {
506 return false;
507 }
508 }
509
510 out_name->entry = entry.entry_string_ref.string8(&out_name->entry_len);
511 out_name->entry16 = nullptr;
512 if (out_name->entry == nullptr) {
513 out_name->entry16 = entry.entry_string_ref.string16(&out_name->entry_len);
514 if (out_name->entry16 == nullptr) {
515 return false;
516 }
517 }
518 return true;
519}
520
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800521bool AssetManager2::GetResourceFlags(uint32_t resid, uint32_t* out_flags) const {
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700522 FindEntryResult entry;
523 ApkAssetsCookie cookie =
524 FindEntry(resid, 0u /* density_override */, false /* stop_at_first_match */, &entry);
525 if (cookie != kInvalidCookie) {
526 *out_flags = entry.type_flags;
527 return cookie;
528 }
529 return kInvalidCookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700530}
531
532ApkAssetsCookie AssetManager2::GetResource(uint32_t resid, bool may_be_bag,
533 uint16_t density_override, Res_value* out_value,
534 ResTable_config* out_selected_config,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800535 uint32_t* out_flags) const {
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700536 FindEntryResult entry;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700537 ApkAssetsCookie cookie =
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700538 FindEntry(resid, density_override, false /* stop_at_first_match */, &entry);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700539 if (cookie == kInvalidCookie) {
540 return kInvalidCookie;
541 }
542
Adam Lesinski498f6052017-11-29 13:24:29 -0800543 if (dtohs(entry.entry->flags) & ResTable_entry::FLAG_COMPLEX) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700544 if (!may_be_bag) {
545 LOG(ERROR) << base::StringPrintf("Resource %08x is a complex map type.", resid);
Adam Lesinski0c405242017-01-13 20:47:26 -0800546 return kInvalidCookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700547 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800548
549 // Create a reference since we can't represent this complex type as a Res_value.
550 out_value->dataType = Res_value::TYPE_REFERENCE;
551 out_value->data = resid;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800552 *out_selected_config = entry.config;
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700553 *out_flags = entry.type_flags;
Adam Lesinski0c405242017-01-13 20:47:26 -0800554 return cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700555 }
556
557 const Res_value* device_value = reinterpret_cast<const Res_value*>(
558 reinterpret_cast<const uint8_t*>(entry.entry) + dtohs(entry.entry->size));
559 out_value->copyFrom_dtoh(*device_value);
Adam Lesinskida431a22016-12-29 16:08:16 -0500560
561 // Convert the package ID to the runtime assigned package ID.
562 entry.dynamic_ref_table->lookupResourceValue(out_value);
563
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800564 *out_selected_config = entry.config;
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700565 *out_flags = entry.type_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700566 return cookie;
567}
568
Adam Lesinski0c405242017-01-13 20:47:26 -0800569ApkAssetsCookie AssetManager2::ResolveReference(ApkAssetsCookie cookie, Res_value* in_out_value,
570 ResTable_config* in_out_selected_config,
571 uint32_t* in_out_flags,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800572 uint32_t* out_last_reference) const {
Adam Lesinski0c405242017-01-13 20:47:26 -0800573 constexpr const int kMaxIterations = 20;
574
Adam Lesinski0c405242017-01-13 20:47:26 -0800575 for (size_t iteration = 0u; in_out_value->dataType == Res_value::TYPE_REFERENCE &&
576 in_out_value->data != 0u && iteration < kMaxIterations;
577 iteration++) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800578 *out_last_reference = in_out_value->data;
Adam Lesinski0c405242017-01-13 20:47:26 -0800579 uint32_t new_flags = 0u;
580 cookie = GetResource(in_out_value->data, true /*may_be_bag*/, 0u /*density_override*/,
581 in_out_value, in_out_selected_config, &new_flags);
582 if (cookie == kInvalidCookie) {
583 return kInvalidCookie;
584 }
585 if (in_out_flags != nullptr) {
586 *in_out_flags |= new_flags;
587 }
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800588 if (*out_last_reference == in_out_value->data) {
Adam Lesinski0c405242017-01-13 20:47:26 -0800589 // This reference can't be resolved, so exit now and let the caller deal with it.
590 return cookie;
591 }
592 }
593 return cookie;
594}
595
Adam Lesinski7ad11102016-10-28 16:39:15 -0700596const ResolvedBag* AssetManager2::GetBag(uint32_t resid) {
y57cd1952018-04-12 14:26:23 -0700597 auto found_resids = std::vector<uint32_t>();
598 return GetBag(resid, found_resids);
599}
600
601const ResolvedBag* AssetManager2::GetBag(uint32_t resid, std::vector<uint32_t>& child_resids) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800602 ATRACE_NAME("AssetManager::GetBag");
Adam Lesinski7ad11102016-10-28 16:39:15 -0700603
604 auto cached_iter = cached_bags_.find(resid);
605 if (cached_iter != cached_bags_.end()) {
606 return cached_iter->second.get();
607 }
608
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700609 FindEntryResult entry;
610 ApkAssetsCookie cookie =
611 FindEntry(resid, 0u /* density_override */, false /* stop_at_first_match */, &entry);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700612 if (cookie == kInvalidCookie) {
613 return nullptr;
614 }
615
616 // Check that the size of the entry header is at least as big as
617 // the desired ResTable_map_entry. Also verify that the entry
618 // was intended to be a map.
619 if (dtohs(entry.entry->size) < sizeof(ResTable_map_entry) ||
620 (dtohs(entry.entry->flags) & ResTable_entry::FLAG_COMPLEX) == 0) {
621 // Not a bag, nothing to do.
622 return nullptr;
623 }
624
625 const ResTable_map_entry* map = reinterpret_cast<const ResTable_map_entry*>(entry.entry);
626 const ResTable_map* map_entry =
627 reinterpret_cast<const ResTable_map*>(reinterpret_cast<const uint8_t*>(map) + map->size);
628 const ResTable_map* const map_entry_end = map_entry + dtohl(map->count);
629
y57cd1952018-04-12 14:26:23 -0700630 // Keep track of ids that have already been seen to prevent infinite loops caused by circular
631 // dependencies between bags
632 child_resids.push_back(resid);
633
Adam Lesinskida431a22016-12-29 16:08:16 -0500634 uint32_t parent_resid = dtohl(map->parent.ident);
y57cd1952018-04-12 14:26:23 -0700635 if (parent_resid == 0 || std::find(child_resids.begin(), child_resids.end(), parent_resid)
636 != child_resids.end()) {
637 // There is no parent or that a circular dependency exist, meaning there is nothing to
638 // inherit and we can do a simple copy of the entries in the map.
Adam Lesinski7ad11102016-10-28 16:39:15 -0700639 const size_t entry_count = map_entry_end - map_entry;
640 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
641 malloc(sizeof(ResolvedBag) + (entry_count * sizeof(ResolvedBag::Entry))))};
642 ResolvedBag::Entry* new_entry = new_bag->entries;
643 for (; map_entry != map_entry_end; ++map_entry) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500644 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -0800645 if (!is_internal_resid(new_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500646 // Attributes, arrays, etc don't have a resource id as the name. They specify
647 // other data, which would be wrong to change via a lookup.
648 if (entry.dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800649 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
650 resid);
Adam Lesinskida431a22016-12-29 16:08:16 -0500651 return nullptr;
652 }
653 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700654 new_entry->cookie = cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -0500655 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700656 new_entry->key_pool = nullptr;
657 new_entry->type_pool = nullptr;
Aurimas Liutikasd42a6702018-11-15 15:48:28 -0800658 new_entry->style = resid;
Adam Lesinski30080e22017-10-16 16:18:09 -0700659 new_entry->value.copyFrom_dtoh(map_entry->value);
660 status_t err = entry.dynamic_ref_table->lookupResourceValue(&new_entry->value);
661 if (err != NO_ERROR) {
662 LOG(ERROR) << base::StringPrintf(
663 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
664 new_entry->value.data, new_key);
665 return nullptr;
666 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700667 ++new_entry;
668 }
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700669 new_bag->type_spec_flags = entry.type_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700670 new_bag->entry_count = static_cast<uint32_t>(entry_count);
671 ResolvedBag* result = new_bag.get();
672 cached_bags_[resid] = std::move(new_bag);
673 return result;
674 }
675
Adam Lesinskida431a22016-12-29 16:08:16 -0500676 // In case the parent is a dynamic reference, resolve it.
677 entry.dynamic_ref_table->lookupResourceId(&parent_resid);
678
Adam Lesinski7ad11102016-10-28 16:39:15 -0700679 // Get the parent and do a merge of the keys.
y57cd1952018-04-12 14:26:23 -0700680 const ResolvedBag* parent_bag = GetBag(parent_resid, child_resids);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700681 if (parent_bag == nullptr) {
682 // Failed to get the parent that should exist.
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800683 LOG(ERROR) << base::StringPrintf("Failed to find parent 0x%08x of bag 0x%08x.", parent_resid,
684 resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700685 return nullptr;
686 }
687
Adam Lesinski7ad11102016-10-28 16:39:15 -0700688 // Create the max possible entries we can make. Once we construct the bag,
689 // we will realloc to fit to size.
690 const size_t max_count = parent_bag->entry_count + dtohl(map->count);
George Burgess IV09b119f2017-07-25 15:00:04 -0700691 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
692 malloc(sizeof(ResolvedBag) + (max_count * sizeof(ResolvedBag::Entry))))};
Adam Lesinski7ad11102016-10-28 16:39:15 -0700693 ResolvedBag::Entry* new_entry = new_bag->entries;
694
695 const ResolvedBag::Entry* parent_entry = parent_bag->entries;
696 const ResolvedBag::Entry* const parent_entry_end = parent_entry + parent_bag->entry_count;
697
698 // The keys are expected to be in sorted order. Merge the two bags.
699 while (map_entry != map_entry_end && parent_entry != parent_entry_end) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500700 uint32_t child_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -0800701 if (!is_internal_resid(child_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500702 if (entry.dynamic_ref_table->lookupResourceId(&child_key) != NO_ERROR) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800703 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", child_key,
704 resid);
Adam Lesinskida431a22016-12-29 16:08:16 -0500705 return nullptr;
706 }
707 }
708
Adam Lesinski7ad11102016-10-28 16:39:15 -0700709 if (child_key <= parent_entry->key) {
710 // Use the child key if it comes before the parent
711 // or is equal to the parent (overrides).
712 new_entry->cookie = cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700713 new_entry->key = child_key;
714 new_entry->key_pool = nullptr;
715 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -0700716 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -0800717 new_entry->style = resid;
Adam Lesinski30080e22017-10-16 16:18:09 -0700718 status_t err = entry.dynamic_ref_table->lookupResourceValue(&new_entry->value);
719 if (err != NO_ERROR) {
720 LOG(ERROR) << base::StringPrintf(
721 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
722 new_entry->value.data, child_key);
723 return nullptr;
724 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700725 ++map_entry;
726 } else {
727 // Take the parent entry as-is.
728 memcpy(new_entry, parent_entry, sizeof(*new_entry));
729 }
730
731 if (child_key >= parent_entry->key) {
732 // Move to the next parent entry if we used it or it was overridden.
733 ++parent_entry;
734 }
735 // Increment to the next entry to fill.
736 ++new_entry;
737 }
738
739 // Finish the child entries if they exist.
740 while (map_entry != map_entry_end) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500741 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -0800742 if (!is_internal_resid(new_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500743 if (entry.dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800744 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
745 resid);
Adam Lesinskida431a22016-12-29 16:08:16 -0500746 return nullptr;
747 }
748 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700749 new_entry->cookie = cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -0500750 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700751 new_entry->key_pool = nullptr;
752 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -0700753 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -0800754 new_entry->style = resid;
Adam Lesinski30080e22017-10-16 16:18:09 -0700755 status_t err = entry.dynamic_ref_table->lookupResourceValue(&new_entry->value);
756 if (err != NO_ERROR) {
757 LOG(ERROR) << base::StringPrintf("Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.",
758 new_entry->value.dataType, new_entry->value.data, new_key);
759 return nullptr;
760 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700761 ++map_entry;
762 ++new_entry;
763 }
764
765 // Finish the parent entries if they exist.
766 if (parent_entry != parent_entry_end) {
767 // Take the rest of the parent entries as-is.
768 const size_t num_entries_to_copy = parent_entry_end - parent_entry;
769 memcpy(new_entry, parent_entry, num_entries_to_copy * sizeof(*new_entry));
770 new_entry += num_entries_to_copy;
771 }
772
773 // Resize the resulting array to fit.
774 const size_t actual_count = new_entry - new_bag->entries;
775 if (actual_count != max_count) {
George Burgess IV09b119f2017-07-25 15:00:04 -0700776 new_bag.reset(reinterpret_cast<ResolvedBag*>(realloc(
777 new_bag.release(), sizeof(ResolvedBag) + (actual_count * sizeof(ResolvedBag::Entry)))));
Adam Lesinski7ad11102016-10-28 16:39:15 -0700778 }
779
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700780 // Combine flags from the parent and our own bag.
781 new_bag->type_spec_flags = entry.type_flags | parent_bag->type_spec_flags;
George Burgess IV09b119f2017-07-25 15:00:04 -0700782 new_bag->entry_count = static_cast<uint32_t>(actual_count);
783 ResolvedBag* result = new_bag.get();
784 cached_bags_[resid] = std::move(new_bag);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700785 return result;
786}
787
Adam Lesinski929d6512017-01-16 19:11:19 -0800788static bool Utf8ToUtf16(const StringPiece& str, std::u16string* out) {
789 ssize_t len =
790 utf8_to_utf16_length(reinterpret_cast<const uint8_t*>(str.data()), str.size(), false);
791 if (len < 0) {
792 return false;
793 }
794 out->resize(static_cast<size_t>(len));
795 utf8_to_utf16(reinterpret_cast<const uint8_t*>(str.data()), str.size(), &*out->begin(),
796 static_cast<size_t>(len + 1));
797 return true;
798}
799
Adam Lesinski0c405242017-01-13 20:47:26 -0800800uint32_t AssetManager2::GetResourceId(const std::string& resource_name,
801 const std::string& fallback_type,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800802 const std::string& fallback_package) const {
Adam Lesinski929d6512017-01-16 19:11:19 -0800803 StringPiece package_name, type, entry;
804 if (!ExtractResourceName(resource_name, &package_name, &type, &entry)) {
805 return 0u;
806 }
807
808 if (entry.empty()) {
809 return 0u;
810 }
811
812 if (package_name.empty()) {
813 package_name = fallback_package;
814 }
815
816 if (type.empty()) {
817 type = fallback_type;
818 }
819
820 std::u16string type16;
821 if (!Utf8ToUtf16(type, &type16)) {
822 return 0u;
823 }
824
825 std::u16string entry16;
826 if (!Utf8ToUtf16(entry, &entry16)) {
827 return 0u;
828 }
829
830 const StringPiece16 kAttr16 = u"attr";
831 const static std::u16string kAttrPrivate16 = u"^attr-private";
832
833 for (const PackageGroup& package_group : package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800834 for (const ConfiguredPackage& package_impl : package_group.packages_) {
835 const LoadedPackage* package = package_impl.loaded_package_;
Adam Lesinski929d6512017-01-16 19:11:19 -0800836 if (package_name != package->GetPackageName()) {
837 // All packages in the same group are expected to have the same package name.
838 break;
839 }
840
841 uint32_t resid = package->FindEntryByName(type16, entry16);
842 if (resid == 0u && kAttr16 == type16) {
843 // Private attributes in libraries (such as the framework) are sometimes encoded
844 // under the type '^attr-private' in order to leave the ID space of public 'attr'
845 // free for future additions. Check '^attr-private' for the same name.
846 resid = package->FindEntryByName(kAttrPrivate16, entry16);
847 }
848
849 if (resid != 0u) {
850 return fix_package_id(resid, package_group.dynamic_ref_table.mAssignedPackageId);
851 }
852 }
853 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800854 return 0u;
855}
856
Mårten Kongstad668ec5b2018-06-11 14:11:33 +0200857void AssetManager2::RebuildFilterList(bool filter_incompatible_configs) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800858 for (PackageGroup& group : package_groups_) {
859 for (ConfiguredPackage& impl : group.packages_) {
860 // Destroy it.
861 impl.filtered_configs_.~ByteBucketArray();
862
863 // Re-create it.
864 new (&impl.filtered_configs_) ByteBucketArray<FilteredConfigGroup>();
865
866 // Create the filters here.
867 impl.loaded_package_->ForEachTypeSpec([&](const TypeSpec* spec, uint8_t type_index) {
868 FilteredConfigGroup& group = impl.filtered_configs_.editItemAt(type_index);
869 const auto iter_end = spec->types + spec->type_count;
870 for (auto iter = spec->types; iter != iter_end; ++iter) {
871 ResTable_config this_config;
872 this_config.copyFromDtoH((*iter)->config);
Mårten Kongstad668ec5b2018-06-11 14:11:33 +0200873 if (!filter_incompatible_configs || this_config.match(configuration_)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800874 group.configurations.push_back(this_config);
875 group.types.push_back(*iter);
876 }
877 }
878 });
879 }
880 }
881}
882
Adam Lesinski7ad11102016-10-28 16:39:15 -0700883void AssetManager2::InvalidateCaches(uint32_t diff) {
884 if (diff == 0xffffffffu) {
885 // Everything must go.
886 cached_bags_.clear();
887 return;
888 }
889
890 // Be more conservative with what gets purged. Only if the bag has other possible
891 // variations with respect to what changed (diff) should we remove it.
892 for (auto iter = cached_bags_.cbegin(); iter != cached_bags_.cend();) {
893 if (diff & iter->second->type_spec_flags) {
894 iter = cached_bags_.erase(iter);
895 } else {
896 ++iter;
897 }
898 }
899}
900
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -0700901uint8_t AssetManager2::GetAssignedPackageId(const LoadedPackage* package) {
902 for (auto& package_group : package_groups_) {
903 for (auto& package2 : package_group.packages_) {
904 if (package2.loaded_package_ == package) {
905 return package_group.dynamic_ref_table.mAssignedPackageId;
906 }
907 }
908 }
909 return 0;
910}
911
Adam Lesinski30080e22017-10-16 16:18:09 -0700912std::unique_ptr<Theme> AssetManager2::NewTheme() {
913 return std::unique_ptr<Theme>(new Theme(this));
914}
915
916Theme::Theme(AssetManager2* asset_manager) : asset_manager_(asset_manager) {
917}
918
919Theme::~Theme() = default;
920
921namespace {
922
923struct ThemeEntry {
924 ApkAssetsCookie cookie;
925 uint32_t type_spec_flags;
926 Res_value value;
927};
928
929struct ThemeType {
930 int entry_count;
931 ThemeEntry entries[0];
932};
933
934constexpr size_t kTypeCount = std::numeric_limits<uint8_t>::max() + 1;
935
936} // namespace
937
938struct Theme::Package {
939 // Each element of Type will be a dynamically sized object
940 // allocated to have the entries stored contiguously with the Type.
941 std::array<util::unique_cptr<ThemeType>, kTypeCount> types;
942};
Adam Lesinski7ad11102016-10-28 16:39:15 -0700943
944bool Theme::ApplyStyle(uint32_t resid, bool force) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800945 ATRACE_NAME("Theme::ApplyStyle");
Adam Lesinski7ad11102016-10-28 16:39:15 -0700946
947 const ResolvedBag* bag = asset_manager_->GetBag(resid);
948 if (bag == nullptr) {
949 return false;
950 }
951
952 // Merge the flags from this style.
953 type_spec_flags_ |= bag->type_spec_flags;
954
Adam Lesinski30080e22017-10-16 16:18:09 -0700955 int last_type_idx = -1;
956 int last_package_idx = -1;
957 Package* last_package = nullptr;
958 ThemeType* last_type = nullptr;
959
960 // Iterate backwards, because each bag is sorted in ascending key ID order, meaning we will only
961 // need to perform one resize per type.
962 using reverse_bag_iterator = std::reverse_iterator<const ResolvedBag::Entry*>;
963 const auto bag_iter_end = reverse_bag_iterator(begin(bag));
964 for (auto bag_iter = reverse_bag_iterator(end(bag)); bag_iter != bag_iter_end; ++bag_iter) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700965 const uint32_t attr_resid = bag_iter->key;
966
Adam Lesinski30080e22017-10-16 16:18:09 -0700967 // If the resource ID passed in is not a style, the key can be some other identifier that is not
968 // a resource ID. We should fail fast instead of operating with strange resource IDs.
Adam Lesinski929d6512017-01-16 19:11:19 -0800969 if (!is_valid_resid(attr_resid)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700970 return false;
971 }
972
Adam Lesinski30080e22017-10-16 16:18:09 -0700973 // We don't use the 0-based index for the type so that we can avoid doing ID validation
974 // upon lookup. Instead, we keep space for the type ID 0 in our data structures. Since
975 // the construction of this type is guarded with a resource ID check, it will never be
976 // populated, and querying type ID 0 will always fail.
977 const int package_idx = get_package_id(attr_resid);
978 const int type_idx = get_type_id(attr_resid);
979 const int entry_idx = get_entry_id(attr_resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700980
Adam Lesinski30080e22017-10-16 16:18:09 -0700981 if (last_package_idx != package_idx) {
982 std::unique_ptr<Package>& package = packages_[package_idx];
983 if (package == nullptr) {
984 package.reset(new Package());
Adam Lesinski7ad11102016-10-28 16:39:15 -0700985 }
Adam Lesinski30080e22017-10-16 16:18:09 -0700986 last_package_idx = package_idx;
987 last_package = package.get();
988 last_type_idx = -1;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700989 }
Adam Lesinski30080e22017-10-16 16:18:09 -0700990
991 if (last_type_idx != type_idx) {
992 util::unique_cptr<ThemeType>& type = last_package->types[type_idx];
993 if (type == nullptr) {
994 // Allocate enough memory to contain this entry_idx. Since we're iterating in reverse over
995 // a sorted list of attributes, this shouldn't be resized again during this method call.
996 type.reset(reinterpret_cast<ThemeType*>(
997 calloc(sizeof(ThemeType) + (entry_idx + 1) * sizeof(ThemeEntry), 1)));
998 type->entry_count = entry_idx + 1;
999 } else if (entry_idx >= type->entry_count) {
1000 // Reallocate the memory to contain this entry_idx. Since we're iterating in reverse over
1001 // a sorted list of attributes, this shouldn't be resized again during this method call.
1002 const int new_count = entry_idx + 1;
1003 type.reset(reinterpret_cast<ThemeType*>(
1004 realloc(type.release(), sizeof(ThemeType) + (new_count * sizeof(ThemeEntry)))));
1005
1006 // Clear out the newly allocated space (which isn't zeroed).
1007 memset(type->entries + type->entry_count, 0,
1008 (new_count - type->entry_count) * sizeof(ThemeEntry));
1009 type->entry_count = new_count;
1010 }
1011 last_type_idx = type_idx;
1012 last_type = type.get();
1013 }
1014
1015 ThemeEntry& entry = last_type->entries[entry_idx];
1016 if (force || (entry.value.dataType == Res_value::TYPE_NULL &&
1017 entry.value.data != Res_value::DATA_NULL_EMPTY)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001018 entry.cookie = bag_iter->cookie;
1019 entry.type_spec_flags |= bag->type_spec_flags;
1020 entry.value = bag_iter->value;
1021 }
1022 }
1023 return true;
1024}
1025
1026ApkAssetsCookie Theme::GetAttribute(uint32_t resid, Res_value* out_value,
1027 uint32_t* out_flags) const {
Adam Lesinski30080e22017-10-16 16:18:09 -07001028 int cnt = 20;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001029
1030 uint32_t type_spec_flags = 0u;
1031
Adam Lesinski30080e22017-10-16 16:18:09 -07001032 do {
1033 const int package_idx = get_package_id(resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001034 const Package* package = packages_[package_idx].get();
Adam Lesinski30080e22017-10-16 16:18:09 -07001035 if (package != nullptr) {
1036 // The themes are constructed with a 1-based type ID, so no need to decrement here.
1037 const int type_idx = get_type_id(resid);
1038 const ThemeType* type = package->types[type_idx].get();
1039 if (type != nullptr) {
1040 const int entry_idx = get_entry_id(resid);
1041 if (entry_idx < type->entry_count) {
1042 const ThemeEntry& entry = type->entries[entry_idx];
1043 type_spec_flags |= entry.type_spec_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001044
Adam Lesinski30080e22017-10-16 16:18:09 -07001045 if (entry.value.dataType == Res_value::TYPE_ATTRIBUTE) {
1046 if (cnt > 0) {
1047 cnt--;
1048 resid = entry.value.data;
1049 continue;
1050 }
1051 return kInvalidCookie;
1052 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001053
Adam Lesinski30080e22017-10-16 16:18:09 -07001054 // @null is different than @empty.
1055 if (entry.value.dataType == Res_value::TYPE_NULL &&
1056 entry.value.data != Res_value::DATA_NULL_EMPTY) {
1057 return kInvalidCookie;
1058 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001059
Adam Lesinski30080e22017-10-16 16:18:09 -07001060 *out_value = entry.value;
Adam Lesinskida431a22016-12-29 16:08:16 -05001061 *out_flags = type_spec_flags;
Adam Lesinski30080e22017-10-16 16:18:09 -07001062 return entry.cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -05001063 }
Adam Lesinskida431a22016-12-29 16:08:16 -05001064 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001065 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001066 break;
1067 } while (true);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001068 return kInvalidCookie;
1069}
1070
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001071ApkAssetsCookie Theme::ResolveAttributeReference(ApkAssetsCookie cookie, Res_value* in_out_value,
1072 ResTable_config* in_out_selected_config,
1073 uint32_t* in_out_type_spec_flags,
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001074 uint32_t* out_last_ref) const {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001075 if (in_out_value->dataType == Res_value::TYPE_ATTRIBUTE) {
1076 uint32_t new_flags;
1077 cookie = GetAttribute(in_out_value->data, in_out_value, &new_flags);
1078 if (cookie == kInvalidCookie) {
1079 return kInvalidCookie;
1080 }
1081
1082 if (in_out_type_spec_flags != nullptr) {
1083 *in_out_type_spec_flags |= new_flags;
1084 }
1085 }
1086 return asset_manager_->ResolveReference(cookie, in_out_value, in_out_selected_config,
1087 in_out_type_spec_flags, out_last_ref);
1088}
1089
Adam Lesinski7ad11102016-10-28 16:39:15 -07001090void Theme::Clear() {
1091 type_spec_flags_ = 0u;
1092 for (std::unique_ptr<Package>& package : packages_) {
1093 package.reset();
1094 }
1095}
1096
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001097void Theme::SetTo(const Theme& o) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001098 if (this == &o) {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001099 return;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001100 }
1101
Adam Lesinski7ad11102016-10-28 16:39:15 -07001102 type_spec_flags_ = o.type_spec_flags_;
1103
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001104 if (asset_manager_ == o.asset_manager_) {
1105 // The theme comes from the same asset manager so all theme data can be copied exactly
1106 for (size_t p = 0; p < packages_.size(); p++) {
1107 const Package *package = o.packages_[p].get();
1108 if (package == nullptr) {
1109 // The other theme doesn't have this package, clear ours.
1110 packages_[p].reset();
Adam Lesinski7ad11102016-10-28 16:39:15 -07001111 continue;
1112 }
1113
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001114 if (packages_[p] == nullptr) {
1115 // The other theme has this package, but we don't. Make one.
1116 packages_[p].reset(new Package());
1117 }
1118
1119 for (size_t t = 0; t < package->types.size(); t++) {
1120 const ThemeType *type = package->types[t].get();
1121 if (type == nullptr) {
1122 // The other theme doesn't have this type, clear ours.
1123 packages_[p]->types[t].reset();
1124 continue;
1125 }
1126
1127 // Create a new type and update it to theirs.
1128 const size_t type_alloc_size = sizeof(ThemeType) + (type->entry_count * sizeof(ThemeEntry));
1129 void *copied_data = malloc(type_alloc_size);
1130 memcpy(copied_data, type, type_alloc_size);
1131 packages_[p]->types[t].reset(reinterpret_cast<ThemeType *>(copied_data));
1132 }
1133 }
1134 } else {
1135 std::map<ApkAssetsCookie, ApkAssetsCookie> src_to_dest_asset_cookies;
1136 typedef std::map<int, int> SourceToDestinationRuntimePackageMap;
1137 std::map<ApkAssetsCookie, SourceToDestinationRuntimePackageMap> src_asset_cookie_id_map;
1138
1139 // Determine which ApkAssets are loaded in both theme AssetManagers
1140 std::vector<const ApkAssets*> src_assets = o.asset_manager_->GetApkAssets();
1141 for (size_t i = 0; i < src_assets.size(); i++) {
1142 const ApkAssets* src_asset = src_assets[i];
1143
1144 std::vector<const ApkAssets*> dest_assets = asset_manager_->GetApkAssets();
1145 for (size_t j = 0; j < dest_assets.size(); j++) {
1146 const ApkAssets* dest_asset = dest_assets[j];
1147
1148 // Map the runtime package of the source apk asset to the destination apk asset
1149 if (src_asset->GetPath() == dest_asset->GetPath()) {
1150 const std::vector<std::unique_ptr<const LoadedPackage>>& src_packages =
1151 src_asset->GetLoadedArsc()->GetPackages();
1152 const std::vector<std::unique_ptr<const LoadedPackage>>& dest_packages =
1153 dest_asset->GetLoadedArsc()->GetPackages();
1154
1155 SourceToDestinationRuntimePackageMap package_map;
1156
1157 // The source and destination package should have the same number of packages loaded in
1158 // the same order.
1159 const size_t N = src_packages.size();
1160 CHECK(N == dest_packages.size())
1161 << " LoadedArsc " << src_asset->GetPath() << " differs number of packages.";
1162 for (size_t p = 0; p < N; p++) {
1163 auto& src_package = src_packages[p];
1164 auto& dest_package = dest_packages[p];
1165 CHECK(src_package->GetPackageName() == dest_package->GetPackageName())
1166 << " Package " << src_package->GetPackageName() << " differs in load order.";
1167
1168 int src_package_id = o.asset_manager_->GetAssignedPackageId(src_package.get());
1169 int dest_package_id = asset_manager_->GetAssignedPackageId(dest_package.get());
1170 package_map[src_package_id] = dest_package_id;
1171 }
1172
1173 src_to_dest_asset_cookies.insert(std::pair<ApkAssetsCookie, ApkAssetsCookie>(i, j));
1174 src_asset_cookie_id_map.insert(
1175 std::pair<ApkAssetsCookie, SourceToDestinationRuntimePackageMap>(i, package_map));
1176 break;
1177 }
1178 }
1179 }
1180
1181 // Reset the data in the destination theme
1182 for (size_t p = 0; p < packages_.size(); p++) {
1183 if (packages_[p] != nullptr) {
1184 packages_[p].reset();
1185 }
1186 }
1187
1188 for (size_t p = 0; p < packages_.size(); p++) {
1189 const Package *package = o.packages_[p].get();
1190 if (package == nullptr) {
1191 continue;
1192 }
1193
1194 for (size_t t = 0; t < package->types.size(); t++) {
1195 const ThemeType *type = package->types[t].get();
1196 if (type == nullptr) {
1197 continue;
1198 }
1199
1200 for (size_t e = 0; e < type->entry_count; e++) {
1201 const ThemeEntry &entry = type->entries[e];
1202 if (entry.value.dataType == Res_value::TYPE_NULL &&
1203 entry.value.data != Res_value::DATA_NULL_EMPTY) {
1204 continue;
1205 }
1206
Ryan Mitchellb85d9b22018-11-19 12:11:38 -08001207 // If the attribute value represents an attribute or reference, the package id of the
1208 // value needs to be rewritten to the package id of the value in the destination
1209 uint32_t attribue_data = entry.value.data;
1210 if ((entry.value.dataType == Res_value::TYPE_ATTRIBUTE
1211 || entry.value.dataType == Res_value::TYPE_REFERENCE
1212 || entry.value.dataType == Res_value::TYPE_DYNAMIC_ATTRIBUTE
1213 || entry.value.dataType == Res_value::TYPE_DYNAMIC_REFERENCE)
1214 && attribue_data != 0x0) {
1215
1216 // Determine the package id of the reference in the destination AssetManager
1217 auto value_package_map = src_asset_cookie_id_map.find(entry.cookie);
1218 if (value_package_map == src_asset_cookie_id_map.end()) {
1219 continue;
1220 }
1221
1222 auto value_dest_package = value_package_map->second.find(
1223 get_package_id(entry.value.data));
1224 if (value_dest_package == value_package_map->second.end()) {
1225 continue;
1226 }
1227
1228 attribue_data = fix_package_id(entry.value.data, value_dest_package->second);
1229 }
1230
1231 // The package id of the attribute needs to be rewritten to the package id of the
1232 // attribute in the destination
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001233 int attribute_dest_package_id = p;
1234 if (attribute_dest_package_id != 0x01) {
1235 // Find the cookie of the attribute resource id
1236 FindEntryResult attribute_entry_result;
1237 ApkAssetsCookie attribute_cookie =
1238 o.asset_manager_->FindEntry(make_resid(p, t, e), 0 /* density_override */ , false,
1239 &attribute_entry_result);
1240
1241 // Determine the package id of the attribute in the destination AssetManager
1242 auto attribute_package_map = src_asset_cookie_id_map.find(attribute_cookie);
1243 if (attribute_package_map == src_asset_cookie_id_map.end()) {
1244 continue;
1245 }
1246 auto attribute_dest_package = attribute_package_map->second.find(
1247 attribute_dest_package_id);
1248 if (attribute_dest_package == attribute_package_map->second.end()) {
1249 continue;
1250 }
1251 attribute_dest_package_id = attribute_dest_package->second;
1252 }
1253
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001254 // Lazily instantiate the destination package
1255 std::unique_ptr<Package>& dest_package = packages_[attribute_dest_package_id];
1256 if (dest_package == nullptr) {
1257 dest_package.reset(new Package());
1258 }
1259
1260 // Lazily instantiate and resize the destination type
1261 util::unique_cptr<ThemeType>& dest_type = dest_package->types[t];
1262 if (dest_type == nullptr || dest_type->entry_count < type->entry_count) {
1263 const size_t type_alloc_size = sizeof(ThemeType)
1264 + (type->entry_count * sizeof(ThemeEntry));
1265 void* dest_data = malloc(type_alloc_size);
1266 memset(dest_data, 0, type->entry_count * sizeof(ThemeEntry));
1267
1268 // Copy the existing destination type values if the type is resized
1269 if (dest_type != nullptr) {
1270 memcpy(dest_data, type, sizeof(ThemeType)
1271 + (dest_type->entry_count * sizeof(ThemeEntry)));
1272 }
1273
1274 dest_type.reset(reinterpret_cast<ThemeType *>(dest_data));
1275 dest_type->entry_count = type->entry_count;
1276 }
1277
1278 // Find the cookie of the value in the destination
1279 auto value_dest_cookie = src_to_dest_asset_cookies.find(entry.cookie);
1280 if (value_dest_cookie == src_to_dest_asset_cookies.end()) {
1281 continue;
1282 }
1283
1284 dest_type->entries[e].cookie = value_dest_cookie->second;
1285 dest_type->entries[e].value.dataType = entry.value.dataType;
1286 dest_type->entries[e].value.data = attribue_data;
1287 dest_type->entries[e].type_spec_flags = entry.type_spec_flags;
1288 }
1289 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001290 }
1291 }
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001292}
1293
1294void Theme::Dump() const {
1295 base::ScopedLogSeverity _log(base::INFO);
1296 LOG(INFO) << base::StringPrintf("Theme(this=%p, AssetManager2=%p)", this, asset_manager_);
1297
1298 for (int p = 0; p < packages_.size(); p++) {
1299 auto& package = packages_[p];
1300 if (package == nullptr) {
1301 continue;
1302 }
1303
1304 for (int t = 0; t < package->types.size(); t++) {
1305 auto& type = package->types[t];
1306 if (type == nullptr) {
1307 continue;
1308 }
1309
1310 for (int e = 0; e < type->entry_count; e++) {
1311 auto& entry = type->entries[e];
1312 if (entry.value.dataType == Res_value::TYPE_NULL &&
1313 entry.value.data != Res_value::DATA_NULL_EMPTY) {
1314 continue;
1315 }
1316
1317 LOG(INFO) << base::StringPrintf(" entry(0x%08x)=(0x%08x) type=(0x%02x), cookie(%d)",
1318 make_resid(p, t, e), entry.value.data,
1319 entry.value.dataType, entry.cookie);
1320 }
1321 }
1322 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001323}
1324
1325} // namespace android