blob: 1381bdd6a50d91218b586690e6ba323dc8115802 [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>
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -070023#include <map>
Winson2f3669b2019-01-11 11:28:34 -080024#include <set>
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"
Jackal Guo552b45d2021-09-29 10:52:19 +080028#include "androidfw/ResourceTypes.h"
Ryan Mitchell8a891d82019-07-01 09:48:23 -070029#include "androidfw/ResourceUtils.h"
Ryan Mitchell31b11052019-06-13 13:47:26 -070030#include "androidfw/Util.h"
Adam Lesinski7ad11102016-10-28 16:39:15 -070031#include "utils/ByteOrder.h"
32#include "utils/Trace.h"
33
34#ifdef _WIN32
35#ifdef ERROR
36#undef ERROR
37#endif
38#endif
39
40namespace android {
41
Ryan Mitchell80094e32020-11-16 23:08:18 +000042namespace {
43
44using EntryValue = std::variant<Res_value, incfs::verified_map_ptr<ResTable_map_entry>>;
45
46base::expected<EntryValue, IOError> GetEntryValue(
47 incfs::verified_map_ptr<ResTable_entry> table_entry) {
48 const uint16_t entry_size = dtohs(table_entry->size);
49
50 // Check if the entry represents a bag value.
51 if (entry_size >= sizeof(ResTable_map_entry) &&
52 (dtohs(table_entry->flags) & ResTable_entry::FLAG_COMPLEX)) {
53 const auto map_entry = table_entry.convert<ResTable_map_entry>();
54 if (!map_entry) {
55 return base::unexpected(IOError::PAGES_MISSING);
56 }
57 return map_entry.verified();
58 }
59
60 // The entry represents a non-bag value.
61 const auto entry_value = table_entry.offset(entry_size).convert<Res_value>();
62 if (!entry_value) {
63 return base::unexpected(IOError::PAGES_MISSING);
64 }
65 Res_value value;
66 value.copyFrom_dtoh(entry_value.value());
67 return value;
68}
69
70} // namespace
71
Adam Lesinskibebfcc42018-02-12 14:27:46 -080072struct FindEntryResult {
Ryan Mitchell80094e32020-11-16 23:08:18 +000073 // The cookie representing the ApkAssets in which the value resides.
74 ApkAssetsCookie cookie;
75
76 // The value of the resource table entry. Either an android::Res_value for non-bag types or an
77 // incfs::verified_map_ptr<ResTable_map_entry> for bag types.
78 EntryValue entry;
Adam Lesinskibebfcc42018-02-12 14:27:46 -080079
80 // The configuration for which the resulting entry was defined. This is already swapped to host
81 // endianness.
82 ResTable_config config;
83
84 // The bitmask of configuration axis with which the resource value varies.
85 uint32_t type_flags;
86
87 // The dynamic package ID map for the package from which this resource came from.
88 const DynamicRefTable* dynamic_ref_table;
89
Ryan Mitchell8a891d82019-07-01 09:48:23 -070090 // The package name of the resource.
91 const std::string* package_name;
92
Adam Lesinskibebfcc42018-02-12 14:27:46 -080093 // The string pool reference to the type's name. This uses a different string pool than
94 // the global string pool, but this is hidden from the caller.
95 StringPoolRef type_string_ref;
96
97 // The string pool reference to the entry's name. This uses a different string pool than
98 // the global string pool, but this is hidden from the caller.
99 StringPoolRef entry_string_ref;
100};
101
Ryan Mitchellb894c272020-02-12 10:31:44 -0800102AssetManager2::AssetManager2() {
Adam Lesinski970bd8d2017-09-25 13:21:55 -0700103 memset(&configuration_, 0, sizeof(configuration_));
104}
Adam Lesinski7ad11102016-10-28 16:39:15 -0700105
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800106bool AssetManager2::SetApkAssets(std::vector<const ApkAssets*> apk_assets, bool invalidate_caches) {
107 apk_assets_ = std::move(apk_assets);
Adam Lesinskida431a22016-12-29 16:08:16 -0500108 BuildDynamicRefTable();
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800109 RebuildFilterList();
Adam Lesinski7ad11102016-10-28 16:39:15 -0700110 if (invalidate_caches) {
111 InvalidateCaches(static_cast<uint32_t>(-1));
112 }
113 return true;
114}
115
Adam Lesinskida431a22016-12-29 16:08:16 -0500116void AssetManager2::BuildDynamicRefTable() {
117 package_groups_.clear();
118 package_ids_.fill(0xff);
119
Ryan Mitchellef538432021-03-01 14:52:14 -0800120 // A mapping from path of apk assets that could be target packages of overlays to the runtime
121 // package id of its first loaded package. Overlays currently can only override resources in the
122 // first package in the target resource table.
123 std::unordered_map<std::string, uint8_t> target_assets_package_ids;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700124
Ryan Mitchell824cc492020-02-12 10:48:14 -0800125 // Overlay resources are not directly referenced by an application so their resource ids
126 // can change throughout the application's lifetime. Assign overlay package ids last.
127 std::vector<const ApkAssets*> sorted_apk_assets(apk_assets_);
128 std::stable_partition(sorted_apk_assets.begin(), sorted_apk_assets.end(), [](const ApkAssets* a) {
129 return !a->IsOverlay();
130 });
131
132 // The assets cookie must map to the position of the apk assets in the unsorted apk assets list.
133 std::unordered_map<const ApkAssets*, ApkAssetsCookie> apk_assets_cookies;
134 apk_assets_cookies.reserve(apk_assets_.size());
135 for (size_t i = 0, n = apk_assets_.size(); i < n; i++) {
136 apk_assets_cookies[apk_assets_[i]] = static_cast<ApkAssetsCookie>(i);
137 }
138
Ryan Mitchellb894c272020-02-12 10:31:44 -0800139 // 0x01 is reserved for the android package.
140 int next_package_id = 0x02;
Ryan Mitchell824cc492020-02-12 10:48:14 -0800141 for (const ApkAssets* apk_assets : sorted_apk_assets) {
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800142 std::shared_ptr<OverlayDynamicRefTable> overlay_ref_table;
143 if (auto loaded_idmap = apk_assets->GetLoadedIdmap(); loaded_idmap != nullptr) {
144 // The target package must precede the overlay package in the apk assets paths in order
145 // to take effect.
Ryan Mitchellef538432021-03-01 14:52:14 -0800146 auto iter = target_assets_package_ids.find(std::string(loaded_idmap->TargetApkPath()));
147 if (iter == target_assets_package_ids.end()) {
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800148 LOG(INFO) << "failed to find target package for overlay "
149 << loaded_idmap->OverlayApkPath();
150 } else {
151 uint8_t target_package_id = iter->second;
152
153 // Create a special dynamic reference table for the overlay to rewrite references to
154 // overlay resources as references to the target resources they overlay.
155 overlay_ref_table = std::make_shared<OverlayDynamicRefTable>(
156 loaded_idmap->GetOverlayDynamicRefTable(target_package_id));
157
158 // Add the overlay resource map to the target package's set of overlays.
159 const uint8_t target_idx = package_ids_[target_package_id];
160 CHECK(target_idx != 0xff) << "overlay target '" << loaded_idmap->TargetApkPath()
161 << "'added to apk_assets_package_ids but does not have an"
162 << " assigned package group";
163
164 PackageGroup& target_package_group = package_groups_[target_idx];
165 target_package_group.overlays_.push_back(
166 ConfiguredOverlay{loaded_idmap->GetTargetResourcesMap(target_package_id,
167 overlay_ref_table.get()),
168 apk_assets_cookies[apk_assets]});
169 }
170 }
171
Ryan Mitchellb894c272020-02-12 10:31:44 -0800172 const LoadedArsc* loaded_arsc = apk_assets->GetLoadedArsc();
Ryan Mitchellb894c272020-02-12 10:31:44 -0800173 for (const std::unique_ptr<const LoadedPackage>& package : loaded_arsc->GetPackages()) {
174 // Get the package ID or assign one if a shared library.
175 int package_id;
176 if (package->IsDynamic()) {
177 package_id = next_package_id++;
178 } else {
179 package_id = package->GetPackageId();
Adam Lesinskida431a22016-12-29 16:08:16 -0500180 }
181
Adam Lesinskida431a22016-12-29 16:08:16 -0500182 uint8_t idx = package_ids_[package_id];
183 if (idx == 0xff) {
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800184 // Add the mapping for package ID to index if not present.
Adam Lesinskida431a22016-12-29 16:08:16 -0500185 package_ids_[package_id] = idx = static_cast<uint8_t>(package_groups_.size());
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800186 PackageGroup& new_group = package_groups_.emplace_back();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700187
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800188 if (overlay_ref_table != nullptr) {
189 // If this package is from an overlay, use a dynamic reference table that can rewrite
190 // overlay resource ids to their corresponding target resource ids.
191 new_group.dynamic_ref_table = overlay_ref_table;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700192 }
193
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800194 DynamicRefTable* ref_table = new_group.dynamic_ref_table.get();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700195 ref_table->mAssignedPackageId = package_id;
196 ref_table->mAppAsLib = package->IsDynamic() && package->GetPackageId() == 0x7f;
Adam Lesinskida431a22016-12-29 16:08:16 -0500197 }
Adam Lesinskida431a22016-12-29 16:08:16 -0500198
199 // Add the package and to the set of packages with the same ID.
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800200 PackageGroup* package_group = &package_groups_[idx];
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800201 package_group->packages_.push_back(ConfiguredPackage{package.get(), {}});
Ryan Mitchell824cc492020-02-12 10:48:14 -0800202 package_group->cookies_.push_back(apk_assets_cookies[apk_assets]);
Adam Lesinskida431a22016-12-29 16:08:16 -0500203
204 // Add the package name -> build time ID mappings.
205 for (const DynamicPackageEntry& entry : package->GetDynamicPackageMap()) {
206 String16 package_name(entry.package_name.c_str(), entry.package_name.size());
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700207 package_group->dynamic_ref_table->mEntries.replaceValueFor(
Adam Lesinskida431a22016-12-29 16:08:16 -0500208 package_name, static_cast<uint8_t>(entry.package_id));
209 }
Ryan Mitchellb894c272020-02-12 10:31:44 -0800210
Ryan Mitchellef538432021-03-01 14:52:14 -0800211 if (auto apk_assets_path = apk_assets->GetPath()) {
212 // Overlay target ApkAssets must have been created using path based load apis.
213 target_assets_package_ids.insert(std::make_pair(std::string(*apk_assets_path), package_id));
214 }
Adam Lesinskida431a22016-12-29 16:08:16 -0500215 }
216 }
217
218 // Now assign the runtime IDs so that we have a build-time to runtime ID map.
219 const auto package_groups_end = package_groups_.end();
220 for (auto iter = package_groups_.begin(); iter != package_groups_end; ++iter) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800221 const std::string& package_name = iter->packages_[0].loaded_package_->GetPackageName();
Adam Lesinskida431a22016-12-29 16:08:16 -0500222 for (auto iter2 = package_groups_.begin(); iter2 != package_groups_end; ++iter2) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700223 iter2->dynamic_ref_table->addMapping(String16(package_name.c_str(), package_name.size()),
224 iter->dynamic_ref_table->mAssignedPackageId);
Ryan Mitchell2fedba92021-04-23 07:47:38 -0700225
226 // Add the alias resources to the dynamic reference table of every package group. Since
227 // staging aliases can only be defined by the framework package (which is not a shared
228 // library), the compile-time package id of the framework is the same across all packages
229 // that compile against the framework.
Ryan Mitchell2ec8e1b2021-05-11 08:28:00 -0700230 for (const auto& package : iter->packages_) {
Ryan Mitchell2fedba92021-04-23 07:47:38 -0700231 for (const auto& entry : package.loaded_package_->GetAliasResourceIdMap()) {
Ryan Mitchell2ec8e1b2021-05-11 08:28:00 -0700232 iter2->dynamic_ref_table->addAlias(entry.first, entry.second);
Ryan Mitchell2fedba92021-04-23 07:47:38 -0700233 }
234 }
Adam Lesinskida431a22016-12-29 16:08:16 -0500235 }
236 }
237}
238
239void AssetManager2::DumpToLog() const {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800240 LOG(INFO) << base::StringPrintf("AssetManager2(this=%p)", this);
241
Adam Lesinskida431a22016-12-29 16:08:16 -0500242 std::string list;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800243 for (const auto& apk_assets : apk_assets_) {
Ryan Mitchellef538432021-03-01 14:52:14 -0800244 base::StringAppendF(&list, "%s,", apk_assets->GetDebugName().c_str());
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800245 }
246 LOG(INFO) << "ApkAssets: " << list;
247
248 list = "";
Adam Lesinskida431a22016-12-29 16:08:16 -0500249 for (size_t i = 0; i < package_ids_.size(); i++) {
250 if (package_ids_[i] != 0xff) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800251 base::StringAppendF(&list, "%02x -> %d, ", (int)i, package_ids_[i]);
Adam Lesinskida431a22016-12-29 16:08:16 -0500252 }
253 }
254 LOG(INFO) << "Package ID map: " << list;
255
Adam Lesinski0dd36992018-01-25 15:38:38 -0800256 for (const auto& package_group: package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800257 list = "";
258 for (const auto& package : package_group.packages_) {
259 const LoadedPackage* loaded_package = package.loaded_package_;
260 base::StringAppendF(&list, "%s(%02x%s), ", loaded_package->GetPackageName().c_str(),
261 loaded_package->GetPackageId(),
262 (loaded_package->IsDynamic() ? " dynamic" : ""));
263 }
264 LOG(INFO) << base::StringPrintf("PG (%02x): ",
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700265 package_group.dynamic_ref_table->mAssignedPackageId)
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800266 << list;
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800267
268 for (size_t i = 0; i < 256; i++) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700269 if (package_group.dynamic_ref_table->mLookupTable[i] != 0) {
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800270 LOG(INFO) << base::StringPrintf(" e[0x%02x] -> 0x%02x", (uint8_t) i,
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700271 package_group.dynamic_ref_table->mLookupTable[i]);
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800272 }
273 }
Adam Lesinskida431a22016-12-29 16:08:16 -0500274 }
275}
Adam Lesinski7ad11102016-10-28 16:39:15 -0700276
277const ResStringPool* AssetManager2::GetStringPoolForCookie(ApkAssetsCookie cookie) const {
278 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
279 return nullptr;
280 }
281 return apk_assets_[cookie]->GetLoadedArsc()->GetStringPool();
282}
283
Adam Lesinskida431a22016-12-29 16:08:16 -0500284const DynamicRefTable* AssetManager2::GetDynamicRefTableForPackage(uint32_t package_id) const {
285 if (package_id >= package_ids_.size()) {
286 return nullptr;
287 }
288
289 const size_t idx = package_ids_[package_id];
290 if (idx == 0xff) {
291 return nullptr;
292 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700293 return package_groups_[idx].dynamic_ref_table.get();
Adam Lesinskida431a22016-12-29 16:08:16 -0500294}
295
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700296std::shared_ptr<const DynamicRefTable> AssetManager2::GetDynamicRefTableForCookie(
297 ApkAssetsCookie cookie) const {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800298 for (const PackageGroup& package_group : package_groups_) {
299 for (const ApkAssetsCookie& package_cookie : package_group.cookies_) {
300 if (package_cookie == cookie) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700301 return package_group.dynamic_ref_table;
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800302 }
303 }
304 }
305 return nullptr;
306}
307
MÃ¥rten Kongstadc92c4dd2019-02-05 01:29:59 +0100308const std::unordered_map<std::string, std::string>*
309 AssetManager2::GetOverlayableMapForPackage(uint32_t package_id) const {
310
311 if (package_id >= package_ids_.size()) {
312 return nullptr;
313 }
314
315 const size_t idx = package_ids_[package_id];
316 if (idx == 0xff) {
317 return nullptr;
318 }
319
320 const PackageGroup& package_group = package_groups_[idx];
Ryan Mitchell80094e32020-11-16 23:08:18 +0000321 if (package_group.packages_.empty()) {
MÃ¥rten Kongstadc92c4dd2019-02-05 01:29:59 +0100322 return nullptr;
323 }
324
325 const auto loaded_package = package_group.packages_[0].loaded_package_;
326 return &loaded_package->GetOverlayableMap();
327}
328
Ryan Mitchell2e394222019-08-28 12:10:51 -0700329bool AssetManager2::GetOverlayablesToString(const android::StringPiece& package_name,
330 std::string* out) const {
331 uint8_t package_id = 0U;
332 for (const auto& apk_assets : apk_assets_) {
333 const LoadedArsc* loaded_arsc = apk_assets->GetLoadedArsc();
334 if (loaded_arsc == nullptr) {
335 continue;
336 }
337
338 const auto& loaded_packages = loaded_arsc->GetPackages();
339 if (loaded_packages.empty()) {
340 continue;
341 }
342
343 const auto& loaded_package = loaded_packages[0];
344 if (loaded_package->GetPackageName() == package_name) {
345 package_id = GetAssignedPackageId(loaded_package.get());
346 break;
347 }
348 }
349
350 if (package_id == 0U) {
351 ANDROID_LOG(ERROR) << base::StringPrintf("No package with name '%s", package_name.data());
352 return false;
353 }
354
355 const size_t idx = package_ids_[package_id];
356 if (idx == 0xff) {
357 return false;
358 }
359
360 std::string output;
361 for (const ConfiguredPackage& package : package_groups_[idx].packages_) {
362 const LoadedPackage* loaded_package = package.loaded_package_;
363 for (auto it = loaded_package->begin(); it != loaded_package->end(); it++) {
364 const OverlayableInfo* info = loaded_package->GetOverlayableInfo(*it);
365 if (info != nullptr) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000366 auto res_name = GetResourceName(*it);
367 if (!res_name.has_value()) {
Ryan Mitchell2e394222019-08-28 12:10:51 -0700368 ANDROID_LOG(ERROR) << base::StringPrintf(
369 "Unable to retrieve name of overlayable resource 0x%08x", *it);
370 return false;
371 }
372
Ryan Mitchell80094e32020-11-16 23:08:18 +0000373 const std::string name = ToFormattedResourceString(*res_name);
Ryan Mitchell2e394222019-08-28 12:10:51 -0700374 output.append(base::StringPrintf(
375 "resource='%s' overlayable='%s' actor='%s' policy='0x%08x'\n",
376 name.c_str(), info->name.c_str(), info->actor.c_str(), info->policy_flags));
377 }
378 }
379 }
380
381 *out = std::move(output);
382 return true;
383}
384
Ryan Mitchell192400c2020-04-02 09:54:23 -0700385bool AssetManager2::ContainsAllocatedTable() const {
386 return std::find_if(apk_assets_.begin(), apk_assets_.end(),
387 std::mem_fn(&ApkAssets::IsTableAllocated)) != apk_assets_.end();
388}
389
Adam Lesinski7ad11102016-10-28 16:39:15 -0700390void AssetManager2::SetConfiguration(const ResTable_config& configuration) {
391 const int diff = configuration_.diff(configuration);
392 configuration_ = configuration;
393
394 if (diff) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800395 RebuildFilterList();
Adam Lesinski7ad11102016-10-28 16:39:15 -0700396 InvalidateCaches(static_cast<uint32_t>(diff));
397 }
398}
399
Ryan Mitchellef538432021-03-01 14:52:14 -0800400std::set<const ApkAssets*> AssetManager2::GetNonSystemOverlays() const {
401 std::set<const ApkAssets*> non_system_overlays;
Adam Lesinski0c405242017-01-13 20:47:26 -0800402 for (const PackageGroup& package_group : package_groups_) {
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800403 bool found_system_package = false;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800404 for (const ConfiguredPackage& package : package_group.packages_) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700405 if (package.loaded_package_->IsSystem()) {
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800406 found_system_package = true;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700407 break;
408 }
409 }
410
411 if (!found_system_package) {
412 for (const ConfiguredOverlay& overlay : package_group.overlays_) {
Ryan Mitchellef538432021-03-01 14:52:14 -0800413 non_system_overlays.insert(apk_assets_[overlay.cookie]);
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700414 }
415 }
416 }
417
418 return non_system_overlays;
419}
420
Ryan Mitchell80094e32020-11-16 23:08:18 +0000421base::expected<std::set<ResTable_config>, IOError> AssetManager2::GetResourceConfigurations(
422 bool exclude_system, bool exclude_mipmap) const {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700423 ATRACE_NAME("AssetManager::GetResourceConfigurations");
424 const auto non_system_overlays =
Ryan Mitchellef538432021-03-01 14:52:14 -0800425 (exclude_system) ? GetNonSystemOverlays() : std::set<const ApkAssets*>();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700426
427 std::set<ResTable_config> configurations;
428 for (const PackageGroup& package_group : package_groups_) {
429 for (size_t i = 0; i < package_group.packages_.size(); i++) {
430 const ConfiguredPackage& package = package_group.packages_[i];
431 if (exclude_system && package.loaded_package_->IsSystem()) {
Adam Lesinski0c405242017-01-13 20:47:26 -0800432 continue;
433 }
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800434
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700435 auto apk_assets = apk_assets_[package_group.cookies_[i]];
Ryan Mitchellef538432021-03-01 14:52:14 -0800436 if (exclude_system && apk_assets->IsOverlay() &&
437 non_system_overlays.find(apk_assets) == non_system_overlays.end()) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700438 // Exclude overlays that target system resources.
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800439 continue;
440 }
441
Ryan Mitchell80094e32020-11-16 23:08:18 +0000442 auto result = package.loaded_package_->CollectConfigurations(exclude_mipmap, &configurations);
443 if (UNLIKELY(!result.has_value())) {
444 return base::unexpected(result.error());
445 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800446 }
447 }
448 return configurations;
449}
450
451std::set<std::string> AssetManager2::GetResourceLocales(bool exclude_system,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800452 bool merge_equivalent_languages) const {
453 ATRACE_NAME("AssetManager::GetResourceLocales");
Adam Lesinski0c405242017-01-13 20:47:26 -0800454 std::set<std::string> locales;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700455 const auto non_system_overlays =
Ryan Mitchellef538432021-03-01 14:52:14 -0800456 (exclude_system) ? GetNonSystemOverlays() : std::set<const ApkAssets*>();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700457
Adam Lesinski0c405242017-01-13 20:47:26 -0800458 for (const PackageGroup& package_group : package_groups_) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700459 for (size_t i = 0; i < package_group.packages_.size(); i++) {
460 const ConfiguredPackage& package = package_group.packages_[i];
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800461 if (exclude_system && package.loaded_package_->IsSystem()) {
Adam Lesinski0c405242017-01-13 20:47:26 -0800462 continue;
463 }
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800464
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700465 auto apk_assets = apk_assets_[package_group.cookies_[i]];
Ryan Mitchellef538432021-03-01 14:52:14 -0800466 if (exclude_system && apk_assets->IsOverlay() &&
467 non_system_overlays.find(apk_assets) == non_system_overlays.end()) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700468 // Exclude overlays that target system resources.
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800469 continue;
470 }
471
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800472 package.loaded_package_->CollectLocales(merge_equivalent_languages, &locales);
Adam Lesinski0c405242017-01-13 20:47:26 -0800473 }
474 }
475 return locales;
476}
477
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800478std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename,
479 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700480 const std::string new_path = "assets/" + filename;
481 return OpenNonAsset(new_path, mode);
482}
483
484std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename, ApkAssetsCookie cookie,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800485 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700486 const std::string new_path = "assets/" + filename;
487 return OpenNonAsset(new_path, cookie, mode);
488}
489
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800490std::unique_ptr<AssetDir> AssetManager2::OpenDir(const std::string& dirname) const {
491 ATRACE_NAME("AssetManager::OpenDir");
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800492
493 std::string full_path = "assets/" + dirname;
494 std::unique_ptr<SortedVector<AssetDir::FileInfo>> files =
495 util::make_unique<SortedVector<AssetDir::FileInfo>>();
496
497 // Start from the back.
498 for (auto iter = apk_assets_.rbegin(); iter != apk_assets_.rend(); ++iter) {
499 const ApkAssets* apk_assets = *iter;
MÃ¥rten Kongstaddbf343b2019-02-21 07:54:18 +0100500 if (apk_assets->IsOverlay()) {
501 continue;
502 }
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800503
504 auto func = [&](const StringPiece& name, FileType type) {
505 AssetDir::FileInfo info;
506 info.setFileName(String8(name.data(), name.size()));
507 info.setFileType(type);
Ryan Mitchellef538432021-03-01 14:52:14 -0800508 info.setSourceName(String8(apk_assets->GetDebugName().c_str()));
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800509 files->add(info);
510 };
511
Ryan Mitchellc07aa702020-03-10 13:49:12 -0700512 if (!apk_assets->GetAssetsProvider()->ForEachFile(full_path, func)) {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800513 return {};
514 }
515 }
516
517 std::unique_ptr<AssetDir> asset_dir = util::make_unique<AssetDir>();
518 asset_dir->setFileList(files.release());
519 return asset_dir;
520}
521
Adam Lesinski7ad11102016-10-28 16:39:15 -0700522// Search in reverse because that's how we used to do it and we need to preserve behaviour.
523// This is unfortunate, because ClassLoaders delegate to the parent first, so the order
524// is inconsistent for split APKs.
525std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
526 Asset::AccessMode mode,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800527 ApkAssetsCookie* out_cookie) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700528 for (int32_t i = apk_assets_.size() - 1; i >= 0; i--) {
MÃ¥rten Kongstaddbf343b2019-02-21 07:54:18 +0100529 // Prevent RRO from modifying assets and other entries accessed by file
530 // path. Explicitly asking for a path in a given package (denoted by a
531 // cookie) is still OK.
532 if (apk_assets_[i]->IsOverlay()) {
533 continue;
534 }
535
Ryan Mitchellc07aa702020-03-10 13:49:12 -0700536 std::unique_ptr<Asset> asset = apk_assets_[i]->GetAssetsProvider()->Open(filename, mode);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700537 if (asset) {
538 if (out_cookie != nullptr) {
539 *out_cookie = i;
540 }
541 return asset;
542 }
543 }
544
545 if (out_cookie != nullptr) {
546 *out_cookie = kInvalidCookie;
547 }
548 return {};
549}
550
551std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800552 ApkAssetsCookie cookie,
553 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700554 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
555 return {};
556 }
Ryan Mitchellc07aa702020-03-10 13:49:12 -0700557 return apk_assets_[cookie]->GetAssetsProvider()->Open(filename, mode);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700558}
559
Ryan Mitchell80094e32020-11-16 23:08:18 +0000560base::expected<FindEntryResult, NullOrIOError> AssetManager2::FindEntry(
561 uint32_t resid, uint16_t density_override, bool stop_at_first_match,
562 bool ignore_configuration) const {
563 const bool logging_enabled = resource_resolution_logging_enabled_;
564 if (UNLIKELY(logging_enabled)) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700565 // Clear the last logged resource resolution.
566 ResetResourceResolution();
567 last_resolution_.resid = resid;
568 }
569
Adam Lesinski7ad11102016-10-28 16:39:15 -0700570 // Might use this if density_override != 0.
571 ResTable_config density_override_config;
572
573 // Select our configuration or generate a density override configuration.
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800574 const ResTable_config* desired_config = &configuration_;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700575 if (density_override != 0 && density_override != configuration_.density) {
576 density_override_config = configuration_;
577 density_override_config.density = density_override;
578 desired_config = &density_override_config;
579 }
580
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700581 // Retrieve the package group from the package id of the resource id.
Ryan Mitchell80094e32020-11-16 23:08:18 +0000582 if (UNLIKELY(!is_valid_resid(resid))) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500583 LOG(ERROR) << base::StringPrintf("Invalid ID 0x%08x.", resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000584 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -0500585 }
586
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800587 const uint32_t package_id = get_package_id(resid);
588 const uint8_t type_idx = get_type_id(resid) - 1;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800589 const uint16_t entry_idx = get_entry_id(resid);
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700590 uint8_t package_idx = package_ids_[package_id];
Ryan Mitchell80094e32020-11-16 23:08:18 +0000591 if (UNLIKELY(package_idx == 0xff)) {
Ryan Mitchell2fe23472019-02-27 09:43:01 -0800592 ANDROID_LOG(ERROR) << base::StringPrintf("No package ID %02x found for ID 0x%08x.",
593 package_id, resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000594 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -0500595 }
596
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800597 const PackageGroup& package_group = package_groups_[package_idx];
Ryan Mitchell80094e32020-11-16 23:08:18 +0000598 auto result = FindEntryInternal(package_group, type_idx, entry_idx, *desired_config,
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800599 stop_at_first_match, ignore_configuration);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000600 if (UNLIKELY(!result.has_value())) {
601 return base::unexpected(result.error());
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700602 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800603
Jackal Guo552b45d2021-09-29 10:52:19 +0800604 bool overlaid = false;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000605 if (!stop_at_first_match && !ignore_configuration && !apk_assets_[result->cookie]->IsLoader()) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700606 for (const auto& id_map : package_group.overlays_) {
607 auto overlay_entry = id_map.overlay_res_maps_.Lookup(resid);
608 if (!overlay_entry) {
609 // No id map entry exists for this target resource.
610 continue;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000611 }
612 if (overlay_entry.IsInlineValue()) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700613 // The target resource is overlaid by an inline value not represented by a resource.
Jeremy Meyerbe2b7792022-08-23 17:42:50 +0000614 ConfigDescription best_frro_config;
615 Res_value best_frro_value;
616 bool frro_found = false;
617 for( const auto& [config, value] : overlay_entry.GetInlineValue()) {
618 if ((!frro_found || config.isBetterThan(best_frro_config, desired_config))
619 && config.match(*desired_config)) {
620 frro_found = true;
621 best_frro_config = config;
622 best_frro_value = value;
623 }
624 }
625 if (!frro_found) {
626 continue;
627 }
628 result->entry = best_frro_value;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000629 result->dynamic_ref_table = id_map.overlay_res_maps_.GetOverlayDynamicRefTable();
630 result->cookie = id_map.cookie;
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800631
632 if (UNLIKELY(logging_enabled)) {
633 last_resolution_.steps.push_back(
634 Resolution::Step{Resolution::Step::Type::OVERLAID_INLINE, String8(), result->cookie});
Jackal Guo552b45d2021-09-29 10:52:19 +0800635 if (auto path = apk_assets_[result->cookie]->GetPath()) {
636 const std::string overlay_path = path->data();
637 if (IsFabricatedOverlay(overlay_path)) {
638 // FRRO don't have package name so we use the creating package here.
639 String8 frro_name = String8("FRRO");
640 // Get the first part of it since the expected one should be like
641 // {overlayPackageName}-{overlayName}-{4 alphanumeric chars}.frro
642 // under /data/resource-cache/.
643 const std::string name = overlay_path.substr(overlay_path.rfind('/') + 1);
644 const size_t end = name.find('-');
645 if (frro_name.size() != overlay_path.size() && end != std::string::npos) {
646 frro_name.append(base::StringPrintf(" created by %s",
647 name.substr(0 /* pos */,
648 end).c_str()).c_str());
649 }
650 last_resolution_.best_package_name = frro_name;
651 } else {
652 last_resolution_.best_package_name = result->package_name->c_str();
653 }
654 }
655 overlaid = true;
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800656 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700657 continue;
658 }
659
Ryan Mitchell80094e32020-11-16 23:08:18 +0000660 auto overlay_result = FindEntry(overlay_entry.GetResourceId(), density_override,
661 false /* stop_at_first_match */,
662 false /* ignore_configuration */);
663 if (UNLIKELY(IsIOError(overlay_result))) {
664 return base::unexpected(overlay_result.error());
665 }
666 if (!overlay_result.has_value()) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700667 continue;
668 }
669
Ryan Mitchell80094e32020-11-16 23:08:18 +0000670 if (!overlay_result->config.isBetterThan(result->config, desired_config)
671 && overlay_result->config.compare(result->config) != 0) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700672 // The configuration of the entry for the overlay must be equal to or better than the target
673 // configuration to be chosen as the better value.
674 continue;
675 }
676
Ryan Mitchell80094e32020-11-16 23:08:18 +0000677 result->cookie = overlay_result->cookie;
678 result->entry = overlay_result->entry;
679 result->config = overlay_result->config;
680 result->dynamic_ref_table = id_map.overlay_res_maps_.GetOverlayDynamicRefTable();
681
682 if (UNLIKELY(logging_enabled)) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700683 last_resolution_.steps.push_back(
Ryan Mitchell80094e32020-11-16 23:08:18 +0000684 Resolution::Step{Resolution::Step::Type::OVERLAID, overlay_result->config.toString(),
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800685 overlay_result->cookie});
Jackal Guo552b45d2021-09-29 10:52:19 +0800686 last_resolution_.best_package_name =
687 overlay_result->package_name->c_str();
688 overlaid = true;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700689 }
690 }
691 }
692
Ryan Mitchell80094e32020-11-16 23:08:18 +0000693 if (UNLIKELY(logging_enabled)) {
694 last_resolution_.cookie = result->cookie;
695 last_resolution_.type_string_ref = result->type_string_ref;
696 last_resolution_.entry_string_ref = result->entry_string_ref;
Jackal Guo552b45d2021-09-29 10:52:19 +0800697 last_resolution_.best_config_name = result->config.toString();
698 if (!overlaid) {
699 last_resolution_.best_package_name = result->package_name->c_str();
700 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700701 }
702
Ryan Mitchell80094e32020-11-16 23:08:18 +0000703 return result;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700704}
705
Ryan Mitchell80094e32020-11-16 23:08:18 +0000706base::expected<FindEntryResult, NullOrIOError> AssetManager2::FindEntryInternal(
707 const PackageGroup& package_group, uint8_t type_idx, uint16_t entry_idx,
708 const ResTable_config& desired_config, bool stop_at_first_match,
709 bool ignore_configuration) const {
710 const bool logging_enabled = resource_resolution_logging_enabled_;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800711 ApkAssetsCookie best_cookie = kInvalidCookie;
712 const LoadedPackage* best_package = nullptr;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000713 incfs::verified_map_ptr<ResTable_type> best_type;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800714 const ResTable_config* best_config = nullptr;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000715 uint32_t best_offset = 0U;
716 uint32_t type_flags = 0U;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800717
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800718 // If `desired_config` is not the same as the set configuration or the caller will accept a value
719 // from any configuration, then we cannot use our filtered list of types since it only it contains
720 // types matched to the set configuration.
721 const bool use_filtered = !ignore_configuration && &desired_config == &configuration_;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800722
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700723 const size_t package_count = package_group.packages_.size();
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800724 for (size_t pi = 0; pi < package_count; pi++) {
725 const ConfiguredPackage& loaded_package_impl = package_group.packages_[pi];
726 const LoadedPackage* loaded_package = loaded_package_impl.loaded_package_;
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800727 const ApkAssetsCookie cookie = package_group.cookies_[pi];
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800728
729 // If the type IDs are offset in this package, we need to take that into account when searching
730 // for a type.
731 const TypeSpec* type_spec = loaded_package->GetTypeSpecByTypeIndex(type_idx);
732 if (UNLIKELY(type_spec == nullptr)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700733 continue;
734 }
735
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800736 // Allow custom loader packages to overlay resource values with configurations equivalent to the
737 // current best configuration.
738 const bool package_is_loader = loaded_package->IsCustomLoader();
739
Ryan Mitchell80094e32020-11-16 23:08:18 +0000740 auto entry_flags = type_spec->GetFlagsForEntryIndex(entry_idx);
Bernie Innocenti58cf8e32020-12-19 15:31:52 +0900741 if (UNLIKELY(!entry_flags.has_value())) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000742 return base::unexpected(entry_flags.error());
743 }
744 type_flags |= entry_flags.value();
745
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800746 const FilteredConfigGroup& filtered_group = loaded_package_impl.filtered_configs_[type_idx];
747 const size_t type_entry_count = (use_filtered) ? filtered_group.type_entries.size()
748 : type_spec->type_entries.size();
749 for (size_t i = 0; i < type_entry_count; i++) {
750 const TypeSpec::TypeEntry* type_entry = (use_filtered) ? filtered_group.type_entries[i]
751 : &type_spec->type_entries[i];
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800752
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800753 // We can skip calling ResTable_config::match() if the caller does not care for the
754 // configuration to match or if we're using the list of types that have already had their
755 // configuration matched.
756 const ResTable_config& this_config = type_entry->config;
757 if (!(use_filtered || ignore_configuration || this_config.match(desired_config))) {
758 continue;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800759 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800760
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800761 Resolution::Step::Type resolution_type;
762 if (best_config == nullptr) {
763 resolution_type = Resolution::Step::Type::INITIAL;
764 } else if (this_config.isBetterThan(*best_config, &desired_config)) {
765 resolution_type = Resolution::Step::Type::BETTER_MATCH;
766 } else if (package_is_loader && this_config.compare(*best_config) == 0) {
767 resolution_type = Resolution::Step::Type::OVERLAID;
768 } else {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000769 if (UNLIKELY(logging_enabled)) {
Jackal Guo552b45d2021-09-29 10:52:19 +0800770 last_resolution_.steps.push_back(Resolution::Step{Resolution::Step::Type::SKIPPED,
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800771 this_config.toString(),
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800772 cookie});
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800773 }
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800774 continue;
775 }
776
777 // The configuration matches and is better than the previous selection.
778 // Find the entry value if it exists for this configuration.
779 const auto& type = type_entry->type;
780 const auto offset = LoadedPackage::GetEntryOffset(type, entry_idx);
781 if (UNLIKELY(IsIOError(offset))) {
782 return base::unexpected(offset.error());
783 }
784
785 if (!offset.has_value()) {
786 if (UNLIKELY(logging_enabled)) {
Jackal Guo552b45d2021-09-29 10:52:19 +0800787 last_resolution_.steps.push_back(Resolution::Step{Resolution::Step::Type::NO_ENTRY,
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800788 this_config.toString(),
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800789 cookie});
790 }
791 continue;
792 }
793
794 best_cookie = cookie;
795 best_package = loaded_package;
796 best_type = type;
797 best_config = &this_config;
798 best_offset = offset.value();
799
800 if (UNLIKELY(logging_enabled)) {
801 last_resolution_.steps.push_back(Resolution::Step{resolution_type,
802 this_config.toString(),
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800803 cookie});
804 }
805
806 // Any configuration will suffice, so break.
807 if (stop_at_first_match) {
808 break;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700809 }
810 }
811 }
812
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800813 if (UNLIKELY(best_cookie == kInvalidCookie)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000814 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700815 }
816
Ryan Mitchell80094e32020-11-16 23:08:18 +0000817 auto best_entry_result = LoadedPackage::GetEntryFromOffset(best_type, best_offset);
818 if (!best_entry_result.has_value()) {
819 return base::unexpected(best_entry_result.error());
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800820 }
821
Ryan Mitchell80094e32020-11-16 23:08:18 +0000822 const incfs::map_ptr<ResTable_entry> best_entry = *best_entry_result;
823 if (!best_entry) {
824 return base::unexpected(IOError::PAGES_MISSING);
Ryan Mitchellbf1f45b2020-09-29 17:22:52 -0700825 }
826
Ryan Mitchell80094e32020-11-16 23:08:18 +0000827 const auto entry = GetEntryValue(best_entry.verified());
828 if (!entry.has_value()) {
829 return base::unexpected(entry.error());
830 }
Winson2f3669b2019-01-11 11:28:34 -0800831
Ryan Mitchell80094e32020-11-16 23:08:18 +0000832 return FindEntryResult{
833 .cookie = best_cookie,
834 .entry = *entry,
835 .config = *best_config,
836 .type_flags = type_flags,
837 .package_name = &best_package->GetPackageName(),
838 .type_string_ref = StringPoolRef(best_package->GetTypeStringPool(), best_type->id - 1),
839 .entry_string_ref = StringPoolRef(best_package->GetKeyStringPool(),
840 best_entry->key.index),
841 .dynamic_ref_table = package_group.dynamic_ref_table.get(),
842 };
Adam Lesinski7ad11102016-10-28 16:39:15 -0700843}
844
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700845void AssetManager2::ResetResourceResolution() const {
846 last_resolution_.cookie = kInvalidCookie;
847 last_resolution_.resid = 0;
848 last_resolution_.steps.clear();
849 last_resolution_.type_string_ref = StringPoolRef();
850 last_resolution_.entry_string_ref = StringPoolRef();
Jackal Guo552b45d2021-09-29 10:52:19 +0800851 last_resolution_.best_config_name.clear();
852 last_resolution_.best_package_name.clear();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700853}
854
Winson2f3669b2019-01-11 11:28:34 -0800855void AssetManager2::SetResourceResolutionLoggingEnabled(bool enabled) {
856 resource_resolution_logging_enabled_ = enabled;
Winson2f3669b2019-01-11 11:28:34 -0800857 if (!enabled) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700858 ResetResourceResolution();
Winson2f3669b2019-01-11 11:28:34 -0800859 }
860}
861
862std::string AssetManager2::GetLastResourceResolution() const {
863 if (!resource_resolution_logging_enabled_) {
864 LOG(ERROR) << "Must enable resource resolution logging before getting path.";
Ryan Mitchell80094e32020-11-16 23:08:18 +0000865 return {};
Winson2f3669b2019-01-11 11:28:34 -0800866 }
867
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800868 const ApkAssetsCookie cookie = last_resolution_.cookie;
Winson2f3669b2019-01-11 11:28:34 -0800869 if (cookie == kInvalidCookie) {
870 LOG(ERROR) << "AssetManager hasn't resolved a resource to read resolution path.";
Ryan Mitchell80094e32020-11-16 23:08:18 +0000871 return {};
Winson2f3669b2019-01-11 11:28:34 -0800872 }
873
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800874 const uint32_t resid = last_resolution_.resid;
875 const auto package = apk_assets_[cookie]->GetLoadedArsc()->GetPackageById(get_package_id(resid));
876
Winson2f3669b2019-01-11 11:28:34 -0800877 std::string resource_name_string;
Winson2f3669b2019-01-11 11:28:34 -0800878 if (package != nullptr) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000879 auto resource_name = ToResourceName(last_resolution_.type_string_ref,
880 last_resolution_.entry_string_ref,
881 package->GetPackageName());
882 resource_name_string = resource_name.has_value() ?
883 ToFormattedResourceString(resource_name.value()) : "<unknown>";
Winson2f3669b2019-01-11 11:28:34 -0800884 }
885
886 std::stringstream log_stream;
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800887 log_stream << base::StringPrintf("Resolution for 0x%08x %s\n"
888 "\tFor config - %s", resid, resource_name_string.c_str(),
889 configuration_.toString().c_str());
Winson2f3669b2019-01-11 11:28:34 -0800890
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800891 for (const Resolution::Step& step : last_resolution_.steps) {
892 const static std::unordered_map<Resolution::Step::Type, const char*> kStepStrings = {
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800893 {Resolution::Step::Type::INITIAL, "Found initial"},
894 {Resolution::Step::Type::BETTER_MATCH, "Found better"},
895 {Resolution::Step::Type::OVERLAID, "Overlaid"},
896 {Resolution::Step::Type::OVERLAID_INLINE, "Overlaid inline"},
897 {Resolution::Step::Type::SKIPPED, "Skipped"},
898 {Resolution::Step::Type::NO_ENTRY, "No entry"}
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800899 };
900
901 const auto prefix = kStepStrings.find(step.type);
902 if (prefix == kStepStrings.end()) {
903 continue;
Winson2f3669b2019-01-11 11:28:34 -0800904 }
905
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800906 log_stream << "\n\t" << prefix->second << ": " << apk_assets_[step.cookie]->GetDebugName();
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800907 if (!step.config_name.isEmpty()) {
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800908 log_stream << " - " << step.config_name;
Winson2f3669b2019-01-11 11:28:34 -0800909 }
910 }
911
Jackal Guo552b45d2021-09-29 10:52:19 +0800912 log_stream << "\nBest matching is from "
913 << (last_resolution_.best_config_name.isEmpty() ? "default"
914 : last_resolution_.best_config_name)
915 << " configuration of " << last_resolution_.best_package_name;
Winson2f3669b2019-01-11 11:28:34 -0800916 return log_stream.str();
917}
918
Felka Chang00964e92021-12-10 01:19:08 +0800919base::expected<uint32_t, NullOrIOError> AssetManager2::GetParentThemeResourceId(uint32_t resid)
920const {
921 auto entry = FindEntry(resid, 0u /* density_override */,
922 false /* stop_at_first_match */,
923 false /* ignore_configuration */);
924 if (!entry.has_value()) {
925 return base::unexpected(entry.error());
926 }
927
928 auto entry_map = std::get_if<incfs::verified_map_ptr<ResTable_map_entry>>(&entry->entry);
929 if (entry_map == nullptr) {
930 // Not a bag, nothing to do.
931 return base::unexpected(std::nullopt);
932 }
933
934 auto map = *entry_map;
935 const uint32_t parent_resid = dtohl(map->parent.ident);
936
937 return parent_resid;
938}
939
Ryan Mitchell80094e32020-11-16 23:08:18 +0000940base::expected<AssetManager2::ResourceName, NullOrIOError> AssetManager2::GetResourceName(
941 uint32_t resid) const {
942 auto result = FindEntry(resid, 0u /* density_override */, true /* stop_at_first_match */,
943 true /* ignore_configuration */);
944 if (!result.has_value()) {
945 return base::unexpected(result.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -0700946 }
947
Ryan Mitchell80094e32020-11-16 23:08:18 +0000948 return ToResourceName(result->type_string_ref,
949 result->entry_string_ref,
950 *result->package_name);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700951}
952
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800953base::expected<uint32_t, NullOrIOError> AssetManager2::GetResourceTypeSpecFlags(
954 uint32_t resid) const {
955 auto result = FindEntry(resid, 0u /* density_override */, false /* stop_at_first_match */,
956 true /* ignore_configuration */);
957 if (!result.has_value()) {
958 return base::unexpected(result.error());
959 }
960 return result->type_flags;
961}
962
Ryan Mitchell80094e32020-11-16 23:08:18 +0000963base::expected<AssetManager2::SelectedValue, NullOrIOError> AssetManager2::GetResource(
964 uint32_t resid, bool may_be_bag, uint16_t density_override) const {
965 auto result = FindEntry(resid, density_override, false /* stop_at_first_match */,
966 false /* ignore_configuration */);
967 if (!result.has_value()) {
968 return base::unexpected(result.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -0700969 }
970
Ryan Mitchell80094e32020-11-16 23:08:18 +0000971 auto result_map_entry = std::get_if<incfs::verified_map_ptr<ResTable_map_entry>>(&result->entry);
Ryan Mitchellbf1f45b2020-09-29 17:22:52 -0700972 if (result_map_entry != nullptr) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700973 if (!may_be_bag) {
974 LOG(ERROR) << base::StringPrintf("Resource %08x is a complex map type.", resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000975 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700976 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800977
978 // Create a reference since we can't represent this complex type as a Res_value.
Ryan Mitchell80094e32020-11-16 23:08:18 +0000979 return SelectedValue(Res_value::TYPE_REFERENCE, resid, result->cookie, result->type_flags,
980 resid, result->config);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700981 }
982
Adam Lesinskida431a22016-12-29 16:08:16 -0500983 // Convert the package ID to the runtime assigned package ID.
Ryan Mitchell80094e32020-11-16 23:08:18 +0000984 Res_value value = std::get<Res_value>(result->entry);
985 result->dynamic_ref_table->lookupResourceValue(&value);
Adam Lesinskida431a22016-12-29 16:08:16 -0500986
Ryan Mitchell80094e32020-11-16 23:08:18 +0000987 return SelectedValue(value.dataType, value.data, result->cookie, result->type_flags,
988 resid, result->config);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700989}
990
Ryan Mitchell80094e32020-11-16 23:08:18 +0000991base::expected<std::monostate, NullOrIOError> AssetManager2::ResolveReference(
Ryan Mitchella45506e2020-11-16 23:08:18 +0000992 AssetManager2::SelectedValue& value, bool cache_value) const {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000993 if (value.type != Res_value::TYPE_REFERENCE || value.data == 0U) {
994 // Not a reference. Nothing to do.
995 return {};
Adam Lesinski0c405242017-01-13 20:47:26 -0800996 }
Ryan Mitchell80094e32020-11-16 23:08:18 +0000997
Ryan Mitchella45506e2020-11-16 23:08:18 +0000998 const uint32_t original_flags = value.flags;
999 const uint32_t original_resid = value.data;
1000 if (cache_value) {
1001 auto cached_value = cached_resolved_values_.find(value.data);
1002 if (cached_value != cached_resolved_values_.end()) {
1003 value = cached_value->second;
1004 value.flags |= original_flags;
1005 return {};
1006 }
1007 }
1008
1009 uint32_t combined_flags = 0U;
1010 uint32_t resolve_resid = original_resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001011 constexpr const uint32_t kMaxIterations = 20;
1012 for (uint32_t i = 0U;; i++) {
1013 auto result = GetResource(resolve_resid, true /*may_be_bag*/);
1014 if (!result.has_value()) {
Ryan Mitchelle7ab6272020-11-13 18:06:15 -08001015 value.resid = resolve_resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001016 return base::unexpected(result.error());
1017 }
1018
Ryan Mitchelle7ab6272020-11-13 18:06:15 -08001019 // If resource resolution fails, the value should be set to the last reference that was able to
1020 // be resolved successfully.
1021 value = *result;
1022 value.flags |= combined_flags;
1023
Ryan Mitchell80094e32020-11-16 23:08:18 +00001024 if (result->type != Res_value::TYPE_REFERENCE ||
1025 result->data == Res_value::DATA_NULL_UNDEFINED ||
1026 result->data == resolve_resid || i == kMaxIterations) {
1027 // This reference can't be resolved, so exit now and let the caller deal with it.
Ryan Mitchella45506e2020-11-16 23:08:18 +00001028 if (cache_value) {
1029 cached_resolved_values_[original_resid] = value;
1030 }
1031
1032 // Above value is cached without original_flags to ensure they don't get included in future
1033 // queries that hit the cache
1034 value.flags |= original_flags;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001035 return {};
1036 }
1037
Ryan Mitchelle7ab6272020-11-13 18:06:15 -08001038 combined_flags = result->flags;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001039 resolve_resid = result->data;
1040 }
Adam Lesinski0c405242017-01-13 20:47:26 -08001041}
1042
Ryan Mitchell80094e32020-11-16 23:08:18 +00001043const std::vector<uint32_t> AssetManager2::GetBagResIdStack(uint32_t resid) const {
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001044 auto cached_iter = cached_bag_resid_stacks_.find(resid);
1045 if (cached_iter != cached_bag_resid_stacks_.end()) {
1046 return cached_iter->second;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001047 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001048
1049 std::vector<uint32_t> found_resids;
1050 GetBag(resid, found_resids);
1051 cached_bag_resid_stacks_.emplace(resid, found_resids);
1052 return found_resids;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001053}
1054
Ryan Mitchell80094e32020-11-16 23:08:18 +00001055base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::ResolveBag(
1056 AssetManager2::SelectedValue& value) const {
1057 if (UNLIKELY(value.type != Res_value::TYPE_REFERENCE)) {
1058 return base::unexpected(std::nullopt);
1059 }
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001060
Ryan Mitchell80094e32020-11-16 23:08:18 +00001061 auto bag = GetBag(value.data);
1062 if (bag.has_value()) {
1063 value.flags |= (*bag)->type_spec_flags;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001064 }
1065 return bag;
y57cd1952018-04-12 14:26:23 -07001066}
1067
Ryan Mitchell80094e32020-11-16 23:08:18 +00001068base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::GetBag(uint32_t resid) const {
1069 std::vector<uint32_t> found_resids;
1070 const auto bag = GetBag(resid, found_resids);
Yurii Zubrytskyiab3cb302022-10-11 12:15:52 -07001071 cached_bag_resid_stacks_.emplace(resid, std::move(found_resids));
Ryan Mitchell80094e32020-11-16 23:08:18 +00001072 return bag;
Ryan Mitchell155d5392020-02-10 13:35:24 -08001073}
1074
Ryan Mitchell80094e32020-11-16 23:08:18 +00001075base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::GetBag(
1076 uint32_t resid, std::vector<uint32_t>& child_resids) const {
1077 if (auto cached_iter = cached_bags_.find(resid); cached_iter != cached_bags_.end()) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001078 return cached_iter->second.get();
1079 }
1080
Ryan Mitchell80094e32020-11-16 23:08:18 +00001081 auto entry = FindEntry(resid, 0u /* density_override */, false /* stop_at_first_match */,
1082 false /* ignore_configuration */);
1083 if (!entry.has_value()) {
1084 return base::unexpected(entry.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001085 }
1086
Ryan Mitchell80094e32020-11-16 23:08:18 +00001087 auto entry_map = std::get_if<incfs::verified_map_ptr<ResTable_map_entry>>(&entry->entry);
1088 if (entry_map == nullptr) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001089 // Not a bag, nothing to do.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001090 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001091 }
1092
Ryan Mitchell80094e32020-11-16 23:08:18 +00001093 auto map = *entry_map;
1094 auto map_entry = map.offset(dtohs(map->size)).convert<ResTable_map>();
1095 const auto map_entry_end = map_entry + dtohl(map->count);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001096
y57cd1952018-04-12 14:26:23 -07001097 // Keep track of ids that have already been seen to prevent infinite loops caused by circular
Ryan Mitchell80094e32020-11-16 23:08:18 +00001098 // dependencies between bags.
y57cd1952018-04-12 14:26:23 -07001099 child_resids.push_back(resid);
1100
Adam Lesinskida431a22016-12-29 16:08:16 -05001101 uint32_t parent_resid = dtohl(map->parent.ident);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001102 if (parent_resid == 0U ||
1103 std::find(child_resids.begin(), child_resids.end(), parent_resid) != child_resids.end()) {
1104 // There is no parent or a circular parental dependency exist, meaning there is nothing to
1105 // inherit and we can do a simple copy of the entries in the map.
Adam Lesinski7ad11102016-10-28 16:39:15 -07001106 const size_t entry_count = map_entry_end - map_entry;
1107 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
1108 malloc(sizeof(ResolvedBag) + (entry_count * sizeof(ResolvedBag::Entry))))};
Ryan Mitchell155d5392020-02-10 13:35:24 -08001109
1110 bool sort_entries = false;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001111 for (auto new_entry = new_bag->entries; map_entry != map_entry_end; ++map_entry) {
1112 if (UNLIKELY(!map_entry)) {
1113 return base::unexpected(IOError::PAGES_MISSING);
1114 }
1115
Adam Lesinskida431a22016-12-29 16:08:16 -05001116 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001117 if (!is_internal_resid(new_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -05001118 // Attributes, arrays, etc don't have a resource id as the name. They specify
1119 // other data, which would be wrong to change via a lookup.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001120 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001121 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
1122 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001123 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001124 }
1125 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001126
1127 new_entry->cookie = entry->cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -05001128 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001129 new_entry->key_pool = nullptr;
1130 new_entry->type_pool = nullptr;
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001131 new_entry->style = resid;
Adam Lesinski30080e22017-10-16 16:18:09 -07001132 new_entry->value.copyFrom_dtoh(map_entry->value);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001133 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1134 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001135 LOG(ERROR) << base::StringPrintf(
1136 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
1137 new_entry->value.data, new_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001138 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001139 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001140
Ryan Mitchell155d5392020-02-10 13:35:24 -08001141 sort_entries = sort_entries ||
1142 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001143 ++new_entry;
1144 }
Ryan Mitchell155d5392020-02-10 13:35:24 -08001145
1146 if (sort_entries) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001147 std::sort(new_bag->entries, new_bag->entries + entry_count,
1148 [](auto&& lhs, auto&& rhs) { return lhs.key < rhs.key; });
Ryan Mitchell155d5392020-02-10 13:35:24 -08001149 }
1150
Ryan Mitchell80094e32020-11-16 23:08:18 +00001151 new_bag->type_spec_flags = entry->type_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001152 new_bag->entry_count = static_cast<uint32_t>(entry_count);
1153 ResolvedBag* result = new_bag.get();
1154 cached_bags_[resid] = std::move(new_bag);
1155 return result;
1156 }
1157
Adam Lesinskida431a22016-12-29 16:08:16 -05001158 // In case the parent is a dynamic reference, resolve it.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001159 entry->dynamic_ref_table->lookupResourceId(&parent_resid);
Adam Lesinskida431a22016-12-29 16:08:16 -05001160
Adam Lesinski7ad11102016-10-28 16:39:15 -07001161 // Get the parent and do a merge of the keys.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001162 const auto parent_bag = GetBag(parent_resid, child_resids);
1163 if (UNLIKELY(!parent_bag.has_value())) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001164 // Failed to get the parent that should exist.
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001165 LOG(ERROR) << base::StringPrintf("Failed to find parent 0x%08x of bag 0x%08x.", parent_resid,
1166 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001167 return base::unexpected(parent_bag.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001168 }
1169
Adam Lesinski7ad11102016-10-28 16:39:15 -07001170 // Create the max possible entries we can make. Once we construct the bag,
1171 // we will realloc to fit to size.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001172 const size_t max_count = (*parent_bag)->entry_count + dtohl(map->count);
George Burgess IV09b119f2017-07-25 15:00:04 -07001173 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
1174 malloc(sizeof(ResolvedBag) + (max_count * sizeof(ResolvedBag::Entry))))};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001175 ResolvedBag::Entry* new_entry = new_bag->entries;
1176
Ryan Mitchell80094e32020-11-16 23:08:18 +00001177 const ResolvedBag::Entry* parent_entry = (*parent_bag)->entries;
1178 const ResolvedBag::Entry* const parent_entry_end = parent_entry + (*parent_bag)->entry_count;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001179
1180 // The keys are expected to be in sorted order. Merge the two bags.
Ryan Mitchell155d5392020-02-10 13:35:24 -08001181 bool sort_entries = false;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001182 while (map_entry != map_entry_end && parent_entry != parent_entry_end) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001183 if (UNLIKELY(!map_entry)) {
1184 return base::unexpected(IOError::PAGES_MISSING);
1185 }
1186
Adam Lesinskida431a22016-12-29 16:08:16 -05001187 uint32_t child_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001188 if (!is_internal_resid(child_key)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001189 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&child_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001190 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", child_key,
1191 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001192 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001193 }
1194 }
1195
Adam Lesinski7ad11102016-10-28 16:39:15 -07001196 if (child_key <= parent_entry->key) {
1197 // Use the child key if it comes before the parent
1198 // or is equal to the parent (overrides).
Ryan Mitchell80094e32020-11-16 23:08:18 +00001199 new_entry->cookie = entry->cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001200 new_entry->key = child_key;
1201 new_entry->key_pool = nullptr;
1202 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -07001203 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001204 new_entry->style = resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001205 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1206 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001207 LOG(ERROR) << base::StringPrintf(
1208 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
1209 new_entry->value.data, child_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001210 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001211 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001212 ++map_entry;
1213 } else {
1214 // Take the parent entry as-is.
1215 memcpy(new_entry, parent_entry, sizeof(*new_entry));
1216 }
1217
Ryan Mitchell155d5392020-02-10 13:35:24 -08001218 sort_entries = sort_entries ||
1219 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001220 if (child_key >= parent_entry->key) {
1221 // Move to the next parent entry if we used it or it was overridden.
1222 ++parent_entry;
1223 }
1224 // Increment to the next entry to fill.
1225 ++new_entry;
1226 }
1227
1228 // Finish the child entries if they exist.
1229 while (map_entry != map_entry_end) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001230 if (UNLIKELY(!map_entry)) {
1231 return base::unexpected(IOError::PAGES_MISSING);
1232 }
1233
Adam Lesinskida431a22016-12-29 16:08:16 -05001234 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001235 if (!is_internal_resid(new_key)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001236 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001237 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
1238 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001239 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001240 }
1241 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001242 new_entry->cookie = entry->cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -05001243 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001244 new_entry->key_pool = nullptr;
1245 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -07001246 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001247 new_entry->style = resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001248 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1249 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001250 LOG(ERROR) << base::StringPrintf("Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.",
1251 new_entry->value.dataType, new_entry->value.data, new_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001252 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001253 }
Ryan Mitchell155d5392020-02-10 13:35:24 -08001254 sort_entries = sort_entries ||
1255 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001256 ++map_entry;
1257 ++new_entry;
1258 }
1259
1260 // Finish the parent entries if they exist.
1261 if (parent_entry != parent_entry_end) {
1262 // Take the rest of the parent entries as-is.
1263 const size_t num_entries_to_copy = parent_entry_end - parent_entry;
1264 memcpy(new_entry, parent_entry, num_entries_to_copy * sizeof(*new_entry));
1265 new_entry += num_entries_to_copy;
1266 }
1267
1268 // Resize the resulting array to fit.
1269 const size_t actual_count = new_entry - new_bag->entries;
1270 if (actual_count != max_count) {
George Burgess IV09b119f2017-07-25 15:00:04 -07001271 new_bag.reset(reinterpret_cast<ResolvedBag*>(realloc(
1272 new_bag.release(), sizeof(ResolvedBag) + (actual_count * sizeof(ResolvedBag::Entry)))));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001273 }
1274
Ryan Mitchell155d5392020-02-10 13:35:24 -08001275 if (sort_entries) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001276 std::sort(new_bag->entries, new_bag->entries + actual_count,
1277 [](auto&& lhs, auto&& rhs) { return lhs.key < rhs.key; });
Ryan Mitchell155d5392020-02-10 13:35:24 -08001278 }
1279
Adam Lesinski1a1e9c22017-10-13 15:45:34 -07001280 // Combine flags from the parent and our own bag.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001281 new_bag->type_spec_flags = entry->type_flags | (*parent_bag)->type_spec_flags;
George Burgess IV09b119f2017-07-25 15:00:04 -07001282 new_bag->entry_count = static_cast<uint32_t>(actual_count);
1283 ResolvedBag* result = new_bag.get();
1284 cached_bags_[resid] = std::move(new_bag);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001285 return result;
1286}
1287
Adam Lesinski929d6512017-01-16 19:11:19 -08001288static bool Utf8ToUtf16(const StringPiece& str, std::u16string* out) {
1289 ssize_t len =
1290 utf8_to_utf16_length(reinterpret_cast<const uint8_t*>(str.data()), str.size(), false);
1291 if (len < 0) {
1292 return false;
1293 }
1294 out->resize(static_cast<size_t>(len));
1295 utf8_to_utf16(reinterpret_cast<const uint8_t*>(str.data()), str.size(), &*out->begin(),
1296 static_cast<size_t>(len + 1));
1297 return true;
1298}
1299
Ryan Mitchell80094e32020-11-16 23:08:18 +00001300base::expected<uint32_t, NullOrIOError> AssetManager2::GetResourceId(
1301 const std::string& resource_name, const std::string& fallback_type,
1302 const std::string& fallback_package) const {
Adam Lesinski929d6512017-01-16 19:11:19 -08001303 StringPiece package_name, type, entry;
1304 if (!ExtractResourceName(resource_name, &package_name, &type, &entry)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001305 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001306 }
1307
1308 if (entry.empty()) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001309 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001310 }
1311
1312 if (package_name.empty()) {
1313 package_name = fallback_package;
1314 }
1315
1316 if (type.empty()) {
1317 type = fallback_type;
1318 }
1319
1320 std::u16string type16;
1321 if (!Utf8ToUtf16(type, &type16)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001322 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001323 }
1324
1325 std::u16string entry16;
1326 if (!Utf8ToUtf16(entry, &entry16)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001327 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001328 }
1329
1330 const StringPiece16 kAttr16 = u"attr";
1331 const static std::u16string kAttrPrivate16 = u"^attr-private";
1332
1333 for (const PackageGroup& package_group : package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001334 for (const ConfiguredPackage& package_impl : package_group.packages_) {
1335 const LoadedPackage* package = package_impl.loaded_package_;
Adam Lesinski929d6512017-01-16 19:11:19 -08001336 if (package_name != package->GetPackageName()) {
1337 // All packages in the same group are expected to have the same package name.
1338 break;
1339 }
1340
Ryan Mitchell80094e32020-11-16 23:08:18 +00001341 base::expected<uint32_t, NullOrIOError> resid = package->FindEntryByName(type16, entry16);
1342 if (UNLIKELY(IsIOError(resid))) {
1343 return base::unexpected(resid.error());
1344 }
1345
1346 if (!resid.has_value() && kAttr16 == type16) {
Adam Lesinski929d6512017-01-16 19:11:19 -08001347 // Private attributes in libraries (such as the framework) are sometimes encoded
1348 // under the type '^attr-private' in order to leave the ID space of public 'attr'
1349 // free for future additions. Check '^attr-private' for the same name.
1350 resid = package->FindEntryByName(kAttrPrivate16, entry16);
1351 }
1352
Ryan Mitchell80094e32020-11-16 23:08:18 +00001353 if (resid.has_value()) {
1354 return fix_package_id(*resid, package_group.dynamic_ref_table->mAssignedPackageId);
Adam Lesinski929d6512017-01-16 19:11:19 -08001355 }
1356 }
1357 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001358 return base::unexpected(std::nullopt);
Adam Lesinski0c405242017-01-13 20:47:26 -08001359}
1360
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001361void AssetManager2::RebuildFilterList() {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001362 for (PackageGroup& group : package_groups_) {
1363 for (ConfiguredPackage& impl : group.packages_) {
1364 // Destroy it.
1365 impl.filtered_configs_.~ByteBucketArray();
1366
1367 // Re-create it.
1368 new (&impl.filtered_configs_) ByteBucketArray<FilteredConfigGroup>();
1369
1370 // Create the filters here.
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001371 impl.loaded_package_->ForEachTypeSpec([&](const TypeSpec& type_spec, uint8_t type_id) {
1372 FilteredConfigGroup& group = impl.filtered_configs_.editItemAt(type_id - 1);
1373 for (const auto& type_entry : type_spec.type_entries) {
1374 if (type_entry.config.match(configuration_)) {
1375 group.type_entries.push_back(&type_entry);
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001376 }
1377 }
1378 });
1379 }
1380 }
1381}
1382
Adam Lesinski7ad11102016-10-28 16:39:15 -07001383void AssetManager2::InvalidateCaches(uint32_t diff) {
Ryan Mitchell2c4d8742019-03-04 09:41:00 -08001384 cached_bag_resid_stacks_.clear();
1385
Adam Lesinski7ad11102016-10-28 16:39:15 -07001386 if (diff == 0xffffffffu) {
1387 // Everything must go.
1388 cached_bags_.clear();
1389 return;
1390 }
1391
1392 // Be more conservative with what gets purged. Only if the bag has other possible
1393 // variations with respect to what changed (diff) should we remove it.
1394 for (auto iter = cached_bags_.cbegin(); iter != cached_bags_.cend();) {
1395 if (diff & iter->second->type_spec_flags) {
1396 iter = cached_bags_.erase(iter);
1397 } else {
1398 ++iter;
1399 }
1400 }
Ryan Mitchella45506e2020-11-16 23:08:18 +00001401
1402 cached_resolved_values_.clear();
Adam Lesinski7ad11102016-10-28 16:39:15 -07001403}
1404
Ryan Mitchell2e394222019-08-28 12:10:51 -07001405uint8_t AssetManager2::GetAssignedPackageId(const LoadedPackage* package) const {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001406 for (auto& package_group : package_groups_) {
1407 for (auto& package2 : package_group.packages_) {
1408 if (package2.loaded_package_ == package) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -07001409 return package_group.dynamic_ref_table->mAssignedPackageId;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001410 }
1411 }
1412 }
1413 return 0;
1414}
1415
Adam Lesinski30080e22017-10-16 16:18:09 -07001416std::unique_ptr<Theme> AssetManager2::NewTheme() {
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001417 constexpr size_t kInitialReserveSize = 32;
1418 auto theme = std::unique_ptr<Theme>(new Theme(this));
1419 theme->entries_.reserve(kInitialReserveSize);
1420 return theme;
Adam Lesinski30080e22017-10-16 16:18:09 -07001421}
1422
1423Theme::Theme(AssetManager2* asset_manager) : asset_manager_(asset_manager) {
1424}
1425
1426Theme::~Theme() = default;
1427
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001428struct Theme::Entry {
1429 uint32_t attr_res_id;
Adam Lesinski30080e22017-10-16 16:18:09 -07001430 ApkAssetsCookie cookie;
1431 uint32_t type_spec_flags;
1432 Res_value value;
1433};
1434
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001435namespace {
1436struct ThemeEntryKeyComparer {
1437 bool operator() (const Theme::Entry& entry, uint32_t attr_res_id) const noexcept {
1438 return entry.attr_res_id < attr_res_id;
1439 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001440};
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001441} // namespace
Adam Lesinski7ad11102016-10-28 16:39:15 -07001442
Ryan Mitchell80094e32020-11-16 23:08:18 +00001443base::expected<std::monostate, NullOrIOError> Theme::ApplyStyle(uint32_t resid, bool force) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001444 ATRACE_NAME("Theme::ApplyStyle");
Adam Lesinski7ad11102016-10-28 16:39:15 -07001445
Ryan Mitchell80094e32020-11-16 23:08:18 +00001446 auto bag = asset_manager_->GetBag(resid);
1447 if (!bag.has_value()) {
1448 return base::unexpected(bag.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001449 }
1450
1451 // Merge the flags from this style.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001452 type_spec_flags_ |= (*bag)->type_spec_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001453
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001454 for (auto it = begin(*bag); it != end(*bag); ++it) {
1455 const uint32_t attr_res_id = it->key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001456
Adam Lesinski30080e22017-10-16 16:18:09 -07001457 // If the resource ID passed in is not a style, the key can be some other identifier that is not
1458 // a resource ID. We should fail fast instead of operating with strange resource IDs.
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001459 if (!is_valid_resid(attr_res_id)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001460 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001461 }
1462
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001463 // DATA_NULL_EMPTY (@empty) is a valid resource value and DATA_NULL_UNDEFINED represents
1464 // an absence of a valid value.
1465 bool is_undefined = it->value.dataType == Res_value::TYPE_NULL &&
1466 it->value.data != Res_value::DATA_NULL_EMPTY;
1467 if (!force && is_undefined) {
1468 continue;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001469 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001470
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001471 auto entry_it = std::lower_bound(entries_.begin(), entries_.end(), attr_res_id,
1472 ThemeEntryKeyComparer{});
1473 if (entry_it != entries_.end() && entry_it->attr_res_id == attr_res_id) {
1474 if (is_undefined) {
1475 // DATA_NULL_UNDEFINED clears the value of the attribute in the theme only when `force` is
1476 /// true.
1477 entries_.erase(entry_it);
1478 } else if (force) {
Yurii Zubrytskyiab3cb302022-10-11 12:15:52 -07001479 *entry_it = Entry{attr_res_id, it->cookie, (*bag)->type_spec_flags, it->value};
Adam Lesinski30080e22017-10-16 16:18:09 -07001480 }
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001481 } else {
Yurii Zubrytskyiab3cb302022-10-11 12:15:52 -07001482 entries_.insert(entry_it, Entry{attr_res_id, it->cookie, (*bag)->type_spec_flags, it->value});
Adam Lesinski7ad11102016-10-28 16:39:15 -07001483 }
1484 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001485 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001486}
1487
Ryan Mitchell767e34f2021-06-07 12:29:05 -07001488void Theme::Rebase(AssetManager2* am, const uint32_t* style_ids, const uint8_t* force,
1489 size_t style_count) {
1490 ATRACE_NAME("Theme::Rebase");
1491 // Reset the entries without changing the vector capacity to prevent reallocations during
1492 // ApplyStyle.
1493 entries_.clear();
1494 asset_manager_ = am;
1495 for (size_t i = 0; i < style_count; i++) {
1496 ApplyStyle(style_ids[i], force[i]);
1497 }
1498}
1499
Ryan Mitchell80094e32020-11-16 23:08:18 +00001500std::optional<AssetManager2::SelectedValue> Theme::GetAttribute(uint32_t resid) const {
1501
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001502 constexpr const uint32_t kMaxIterations = 20;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001503 uint32_t type_spec_flags = 0u;
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001504 for (uint32_t i = 0; i <= kMaxIterations; i++) {
1505 auto entry_it = std::lower_bound(entries_.begin(), entries_.end(), resid,
1506 ThemeEntryKeyComparer{});
1507 if (entry_it == entries_.end() || entry_it->attr_res_id != resid) {
1508 return std::nullopt;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001509 }
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001510
1511 type_spec_flags |= entry_it->type_spec_flags;
1512 if (entry_it->value.dataType == Res_value::TYPE_ATTRIBUTE) {
1513 resid = entry_it->value.data;
1514 continue;
1515 }
1516
1517 return AssetManager2::SelectedValue(entry_it->value.dataType, entry_it->value.data,
1518 entry_it->cookie, type_spec_flags, 0U /* resid */,
1519 {} /* config */);
1520 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001521 return std::nullopt;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001522}
1523
Ryan Mitchell80094e32020-11-16 23:08:18 +00001524base::expected<std::monostate, NullOrIOError> Theme::ResolveAttributeReference(
1525 AssetManager2::SelectedValue& value) const {
1526 if (value.type != Res_value::TYPE_ATTRIBUTE) {
1527 return asset_manager_->ResolveReference(value);
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001528 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001529
1530 std::optional<AssetManager2::SelectedValue> result = GetAttribute(value.data);
1531 if (!result.has_value()) {
1532 return base::unexpected(std::nullopt);
1533 }
1534
Ryan Mitchella45506e2020-11-16 23:08:18 +00001535 auto resolve_result = asset_manager_->ResolveReference(*result, true /* cache_value */);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001536 if (resolve_result.has_value()) {
1537 result->flags |= value.flags;
1538 value = *result;
1539 }
1540 return resolve_result;
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001541}
1542
Adam Lesinski7ad11102016-10-28 16:39:15 -07001543void Theme::Clear() {
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001544 entries_.clear();
Adam Lesinski7ad11102016-10-28 16:39:15 -07001545}
1546
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001547base::expected<std::monostate, IOError> Theme::SetTo(const Theme& source) {
1548 if (this == &source) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001549 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001550 }
1551
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001552 type_spec_flags_ = source.type_spec_flags_;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001553
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001554 if (asset_manager_ == source.asset_manager_) {
1555 entries_ = source.entries_;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001556 } else {
1557 std::map<ApkAssetsCookie, ApkAssetsCookie> src_to_dest_asset_cookies;
1558 typedef std::map<int, int> SourceToDestinationRuntimePackageMap;
1559 std::map<ApkAssetsCookie, SourceToDestinationRuntimePackageMap> src_asset_cookie_id_map;
1560
Ryan Mitchell93bca972019-03-08 17:26:28 -08001561 // Determine which ApkAssets are loaded in both theme AssetManagers.
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001562 const auto src_assets = source.asset_manager_->GetApkAssets();
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001563 for (size_t i = 0; i < src_assets.size(); i++) {
1564 const ApkAssets* src_asset = src_assets[i];
1565
Ryan Mitchellef538432021-03-01 14:52:14 -08001566 const auto dest_assets = asset_manager_->GetApkAssets();
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001567 for (size_t j = 0; j < dest_assets.size(); j++) {
1568 const ApkAssets* dest_asset = dest_assets[j];
Ryan Mitchellef538432021-03-01 14:52:14 -08001569 if (src_asset != dest_asset) {
1570 // ResourcesManager caches and reuses ApkAssets when the same apk must be present in
1571 // multiple AssetManagers. Two ApkAssets point to the same version of the same resources
1572 // if they are the same instance.
1573 continue;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001574 }
Ryan Mitchellef538432021-03-01 14:52:14 -08001575
1576 // Map the package ids of the asset in the source AssetManager to the package ids of the
1577 // asset in th destination AssetManager.
1578 SourceToDestinationRuntimePackageMap package_map;
1579 for (const auto& loaded_package : src_asset->GetLoadedArsc()->GetPackages()) {
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001580 const int src_package_id = source.asset_manager_->GetAssignedPackageId(
1581 loaded_package.get());
Ryan Mitchellef538432021-03-01 14:52:14 -08001582 const int dest_package_id = asset_manager_->GetAssignedPackageId(loaded_package.get());
1583 package_map[src_package_id] = dest_package_id;
1584 }
1585
1586 src_to_dest_asset_cookies.insert(std::make_pair(i, j));
1587 src_asset_cookie_id_map.insert(std::make_pair(i, package_map));
1588 break;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001589 }
1590 }
1591
Ryan Mitchell93bca972019-03-08 17:26:28 -08001592 // Reset the data in the destination theme.
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001593 entries_.clear();
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001594
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001595 for (const auto& entry : source.entries_) {
1596 bool is_reference = (entry.value.dataType == Res_value::TYPE_ATTRIBUTE
1597 || entry.value.dataType == Res_value::TYPE_REFERENCE
1598 || entry.value.dataType == Res_value::TYPE_DYNAMIC_ATTRIBUTE
1599 || entry.value.dataType == Res_value::TYPE_DYNAMIC_REFERENCE)
1600 && entry.value.data != 0x0;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001601
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001602 // If the attribute value represents an attribute or reference, the package id of the
1603 // value needs to be rewritten to the package id of the value in the destination.
1604 uint32_t attribute_data = entry.value.data;
1605 if (is_reference) {
1606 // Determine the package id of the reference in the destination AssetManager.
1607 auto value_package_map = src_asset_cookie_id_map.find(entry.cookie);
1608 if (value_package_map == src_asset_cookie_id_map.end()) {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001609 continue;
1610 }
1611
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001612 auto value_dest_package = value_package_map->second.find(
1613 get_package_id(entry.value.data));
1614 if (value_dest_package == value_package_map->second.end()) {
1615 continue;
1616 }
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001617
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001618 attribute_data = fix_package_id(entry.value.data, value_dest_package->second);
1619 }
Ryan Mitchellb85d9b22018-11-19 12:11:38 -08001620
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001621 // Find the cookie of the value in the destination. If the source apk is not loaded in the
1622 // destination, only copy resources that do not reference resources in the source.
1623 ApkAssetsCookie data_dest_cookie;
1624 auto value_dest_cookie = src_to_dest_asset_cookies.find(entry.cookie);
1625 if (value_dest_cookie != src_to_dest_asset_cookies.end()) {
1626 data_dest_cookie = value_dest_cookie->second;
1627 } else {
1628 if (is_reference || entry.value.dataType == Res_value::TYPE_STRING) {
1629 continue;
1630 } else {
1631 data_dest_cookie = 0x0;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001632 }
1633 }
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001634
1635 // The package id of the attribute needs to be rewritten to the package id of the
1636 // attribute in the destination.
1637 int attribute_dest_package_id = get_package_id(entry.attr_res_id);
1638 if (attribute_dest_package_id != 0x01) {
1639 // Find the cookie of the attribute resource id in the source AssetManager
1640 base::expected<FindEntryResult, NullOrIOError> attribute_entry_result =
1641 source.asset_manager_->FindEntry(entry.attr_res_id, 0 /* density_override */ ,
1642 true /* stop_at_first_match */,
1643 true /* ignore_configuration */);
1644 if (UNLIKELY(IsIOError(attribute_entry_result))) {
1645 return base::unexpected(GetIOError(attribute_entry_result.error()));
1646 }
1647 if (!attribute_entry_result.has_value()) {
1648 continue;
1649 }
1650
1651 // Determine the package id of the attribute in the destination AssetManager.
1652 auto attribute_package_map = src_asset_cookie_id_map.find(
1653 attribute_entry_result->cookie);
1654 if (attribute_package_map == src_asset_cookie_id_map.end()) {
1655 continue;
1656 }
1657 auto attribute_dest_package = attribute_package_map->second.find(
1658 attribute_dest_package_id);
1659 if (attribute_dest_package == attribute_package_map->second.end()) {
1660 continue;
1661 }
1662 attribute_dest_package_id = attribute_dest_package->second;
1663 }
1664
1665 auto dest_attr_id = make_resid(attribute_dest_package_id, get_type_id(entry.attr_res_id),
1666 get_entry_id(entry.attr_res_id));
1667 Theme::Entry new_entry{dest_attr_id, data_dest_cookie, entry.type_spec_flags,
1668 Res_value{.dataType = entry.value.dataType,
1669 .data = attribute_data}};
1670
1671 // Since the entries were cleared, the attribute resource id has yet been mapped to any value.
1672 auto entry_it = std::lower_bound(entries_.begin(), entries_.end(), dest_attr_id,
1673 ThemeEntryKeyComparer{});
1674 entries_.insert(entry_it, new_entry);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001675 }
1676 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001677 return {};
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001678}
1679
1680void Theme::Dump() const {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001681 LOG(INFO) << base::StringPrintf("Theme(this=%p, AssetManager2=%p)", this, asset_manager_);
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001682 for (auto& entry : entries_) {
1683 LOG(INFO) << base::StringPrintf(" entry(0x%08x)=(0x%08x) type=(0x%02x), cookie(%d)",
1684 entry.attr_res_id, entry.value.data, entry.value.dataType,
1685 entry.cookie);
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001686 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001687}
1688
1689} // namespace android