blob: 508750720690f1b18c2fae23e1106d337e1a8a86 [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>
Yurii Zubrytskyi59dab3b2022-11-03 00:08:49 -070025#include <span>
Jeremy Meyere00958a2025-02-19 16:55:19 -080026#include <sstream>
Yurii Zubrytskyi1e5452a2024-06-13 19:30:36 -070027#include <utility>
Adam Lesinski0c405242017-01-13 20:47:26 -080028
Adam Lesinski7ad11102016-10-28 16:39:15 -070029#include "android-base/logging.h"
30#include "android-base/stringprintf.h"
Yurii Zubrytskyi1e5452a2024-06-13 19:30:36 -070031#include "androidfw/CombinedIterator.h"
Jackal Guo552b45d2021-09-29 10:52:19 +080032#include "androidfw/ResourceTypes.h"
Ryan Mitchell8a891d82019-07-01 09:48:23 -070033#include "androidfw/ResourceUtils.h"
Ryan Mitchell31b11052019-06-13 13:47:26 -070034#include "androidfw/Util.h"
Adam Lesinski7ad11102016-10-28 16:39:15 -070035#include "utils/ByteOrder.h"
36#include "utils/Trace.h"
37
38#ifdef _WIN32
39#ifdef ERROR
40#undef ERROR
41#endif
42#endif
43
44namespace android {
45
Ryan Mitchell80094e32020-11-16 23:08:18 +000046namespace {
47
Biswarup Palbc306b42025-02-06 23:31:30 +000048constexpr int32_t kDefaultDisplayId = 0;
49constexpr int32_t kDefaultDeviceId = 0;
50
Ryan Mitchell80094e32020-11-16 23:08:18 +000051using EntryValue = std::variant<Res_value, incfs::verified_map_ptr<ResTable_map_entry>>;
52
Eric Miao368cd192022-09-09 15:46:14 -070053/* NOTE: table_entry has been verified in LoadedPackage::GetEntryFromOffset(),
54 * and so access to ->value() and ->map_entry() are safe here
55 */
Ryan Mitchell80094e32020-11-16 23:08:18 +000056base::expected<EntryValue, IOError> GetEntryValue(
57 incfs::verified_map_ptr<ResTable_entry> table_entry) {
Eric Miao368cd192022-09-09 15:46:14 -070058 const uint16_t entry_size = table_entry->size();
Ryan Mitchell80094e32020-11-16 23:08:18 +000059
60 // Check if the entry represents a bag value.
Eric Miao368cd192022-09-09 15:46:14 -070061 if (entry_size >= sizeof(ResTable_map_entry) && table_entry->is_complex()) {
62 return table_entry.convert<ResTable_map_entry>().verified();
Ryan Mitchell80094e32020-11-16 23:08:18 +000063 }
64
Eric Miao368cd192022-09-09 15:46:14 -070065 return table_entry->value();
Ryan Mitchell80094e32020-11-16 23:08:18 +000066}
67
Jeremy Meyere00958a2025-02-19 16:55:19 -080068} // namespace
Ryan Mitchell80094e32020-11-16 23:08:18 +000069
Adam Lesinskibebfcc42018-02-12 14:27:46 -080070struct FindEntryResult {
Ryan Mitchell80094e32020-11-16 23:08:18 +000071 // The cookie representing the ApkAssets in which the value resides.
72 ApkAssetsCookie cookie;
73
74 // The value of the resource table entry. Either an android::Res_value for non-bag types or an
75 // incfs::verified_map_ptr<ResTable_map_entry> for bag types.
76 EntryValue entry;
Adam Lesinskibebfcc42018-02-12 14:27:46 -080077
78 // The configuration for which the resulting entry was defined. This is already swapped to host
79 // endianness.
80 ResTable_config config;
81
82 // The bitmask of configuration axis with which the resource value varies.
83 uint32_t type_flags;
84
Jeremy Meyerb76f7452025-03-12 10:55:53 -070085 // The bitmask of ResTable_entry flags
86 uint16_t entry_flags;
87
Adam Lesinskibebfcc42018-02-12 14:27:46 -080088 // The dynamic package ID map for the package from which this resource came from.
89 const DynamicRefTable* dynamic_ref_table;
90
Ryan Mitchell8a891d82019-07-01 09:48:23 -070091 // The package name of the resource.
92 const std::string* package_name;
93
Adam Lesinskibebfcc42018-02-12 14:27:46 -080094 // The string pool reference to the type's name. This uses a different string pool than
95 // the global string pool, but this is hidden from the caller.
96 StringPoolRef type_string_ref;
97
98 // The string pool reference to the entry's name. This uses a different string pool than
99 // the global string pool, but this is hidden from the caller.
100 StringPoolRef entry_string_ref;
101};
102
Ryan Prichard41e15a02023-08-30 22:19:30 -0700103struct Theme::Entry {
104 ApkAssetsCookie cookie;
105 uint32_t type_spec_flags;
106 Res_value value;
107};
108
Biswarup Palbc306b42025-02-06 23:31:30 +0000109AssetManager2::AssetManager2(ApkAssetsList apk_assets, const ResTable_config& configuration)
110 : display_id_(kDefaultDisplayId), device_id_(kDefaultDeviceId) {
Jeremy Meyerccf5cd72023-08-15 21:42:03 +0000111 configurations_.push_back(configuration);
112
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700113 // Don't invalidate caches here as there's nothing cached yet.
114 SetApkAssets(apk_assets, false);
Adam Lesinski970bd8d2017-09-25 13:21:55 -0700115}
Adam Lesinski7ad11102016-10-28 16:39:15 -0700116
Biswarup Palbc306b42025-02-06 23:31:30 +0000117AssetManager2::AssetManager2() : display_id_(kDefaultDisplayId), device_id_(kDefaultDeviceId) {
Yurii Zubrytskyic4dadee2024-08-15 12:08:47 -0700118 configurations_.emplace_back();
Jeremy Meyerccf5cd72023-08-15 21:42:03 +0000119}
120
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700121bool AssetManager2::SetApkAssets(ApkAssetsList apk_assets, bool invalidate_caches) {
122 BuildDynamicRefTable(apk_assets);
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800123 RebuildFilterList();
Adam Lesinski7ad11102016-10-28 16:39:15 -0700124 if (invalidate_caches) {
125 InvalidateCaches(static_cast<uint32_t>(-1));
126 }
127 return true;
128}
129
Michael Hoisie7b433332024-02-13 21:42:21 +0000130void AssetManager2::PresetApkAssets(ApkAssetsList apk_assets) {
131 BuildDynamicRefTable(apk_assets);
132}
133
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700134bool AssetManager2::SetApkAssets(std::initializer_list<ApkAssetsPtr> apk_assets,
135 bool invalidate_caches) {
136 return SetApkAssets(ApkAssetsList(apk_assets.begin(), apk_assets.size()), invalidate_caches);
137}
138
139void AssetManager2::BuildDynamicRefTable(ApkAssetsList apk_assets) {
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700140 auto op = StartOperation();
141
142 apk_assets_.resize(apk_assets.size());
143 for (size_t i = 0; i != apk_assets.size(); ++i) {
144 apk_assets_[i].first = apk_assets[i];
145 // Let's populate the locked assets right away as we're going to need them here later.
146 apk_assets_[i].second = apk_assets[i];
147 }
148
Adam Lesinskida431a22016-12-29 16:08:16 -0500149 package_groups_.clear();
150 package_ids_.fill(0xff);
151
Ryan Mitchellef538432021-03-01 14:52:14 -0800152 // A mapping from path of apk assets that could be target packages of overlays to the runtime
153 // package id of its first loaded package. Overlays currently can only override resources in the
154 // first package in the target resource table.
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800155 std::unordered_map<std::string_view, uint8_t> target_assets_package_ids;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700156
Ryan Mitchell824cc492020-02-12 10:48:14 -0800157 // Overlay resources are not directly referenced by an application so their resource ids
158 // can change throughout the application's lifetime. Assign overlay package ids last.
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700159 std::vector<const ApkAssets*> sorted_apk_assets;
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700160 sorted_apk_assets.reserve(apk_assets.size());
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700161 for (auto& asset : apk_assets) {
162 sorted_apk_assets.push_back(asset.get());
163 }
164 std::stable_partition(sorted_apk_assets.begin(), sorted_apk_assets.end(),
165 [](auto a) { return !a->IsOverlay(); });
Ryan Mitchell824cc492020-02-12 10:48:14 -0800166
167 // The assets cookie must map to the position of the apk assets in the unsorted apk assets list.
168 std::unordered_map<const ApkAssets*, ApkAssetsCookie> apk_assets_cookies;
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700169 apk_assets_cookies.reserve(apk_assets.size());
170 for (size_t i = 0, n = apk_assets.size(); i < n; i++) {
171 apk_assets_cookies[apk_assets[i].get()] = static_cast<ApkAssetsCookie>(i);
Ryan Mitchell824cc492020-02-12 10:48:14 -0800172 }
173
Ryan Mitchellb894c272020-02-12 10:31:44 -0800174 // 0x01 is reserved for the android package.
175 int next_package_id = 0x02;
Ryan Mitchell824cc492020-02-12 10:48:14 -0800176 for (const ApkAssets* apk_assets : sorted_apk_assets) {
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800177 std::shared_ptr<OverlayDynamicRefTable> overlay_ref_table;
178 if (auto loaded_idmap = apk_assets->GetLoadedIdmap(); loaded_idmap != nullptr) {
179 // The target package must precede the overlay package in the apk assets paths in order
180 // to take effect.
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800181 auto iter = target_assets_package_ids.find(loaded_idmap->TargetApkPath());
Ryan Mitchellef538432021-03-01 14:52:14 -0800182 if (iter == target_assets_package_ids.end()) {
Biswarup Palbc306b42025-02-06 23:31:30 +0000183 LOG(INFO) << "failed to find target package for overlay " << loaded_idmap->OverlayApkPath();
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800184 } else {
185 uint8_t target_package_id = iter->second;
186
187 // Create a special dynamic reference table for the overlay to rewrite references to
188 // overlay resources as references to the target resources they overlay.
189 overlay_ref_table = std::make_shared<OverlayDynamicRefTable>(
190 loaded_idmap->GetOverlayDynamicRefTable(target_package_id));
191
192 // Add the overlay resource map to the target package's set of overlays.
193 const uint8_t target_idx = package_ids_[target_package_id];
194 CHECK(target_idx != 0xff) << "overlay target '" << loaded_idmap->TargetApkPath()
195 << "'added to apk_assets_package_ids but does not have an"
196 << " assigned package group";
197
198 PackageGroup& target_package_group = package_groups_[target_idx];
Biswarup Palbc306b42025-02-06 23:31:30 +0000199 target_package_group.overlays_.push_back(ConfiguredOverlay{
200 loaded_idmap->GetTargetResourcesMap(target_package_id, overlay_ref_table.get()),
201 apk_assets_cookies[apk_assets],
202 IsAnyOverlayConstraintSatisfied(loaded_idmap->GetConstraints())
203 });
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800204 }
205 }
206
Ryan Mitchellb894c272020-02-12 10:31:44 -0800207 const LoadedArsc* loaded_arsc = apk_assets->GetLoadedArsc();
Ryan Mitchellb894c272020-02-12 10:31:44 -0800208 for (const std::unique_ptr<const LoadedPackage>& package : loaded_arsc->GetPackages()) {
209 // Get the package ID or assign one if a shared library.
210 int package_id;
211 if (package->IsDynamic()) {
212 package_id = next_package_id++;
213 } else {
214 package_id = package->GetPackageId();
Adam Lesinskida431a22016-12-29 16:08:16 -0500215 }
216
Adam Lesinskida431a22016-12-29 16:08:16 -0500217 uint8_t idx = package_ids_[package_id];
218 if (idx == 0xff) {
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800219 // Add the mapping for package ID to index if not present.
Adam Lesinskida431a22016-12-29 16:08:16 -0500220 package_ids_[package_id] = idx = static_cast<uint8_t>(package_groups_.size());
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800221 PackageGroup& new_group = package_groups_.emplace_back();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700222
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800223 if (overlay_ref_table != nullptr) {
224 // If this package is from an overlay, use a dynamic reference table that can rewrite
225 // overlay resource ids to their corresponding target resource ids.
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800226 new_group.dynamic_ref_table = std::move(overlay_ref_table);
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700227 }
228
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800229 DynamicRefTable* ref_table = new_group.dynamic_ref_table.get();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700230 ref_table->mAssignedPackageId = package_id;
231 ref_table->mAppAsLib = package->IsDynamic() && package->GetPackageId() == 0x7f;
Adam Lesinskida431a22016-12-29 16:08:16 -0500232 }
Adam Lesinskida431a22016-12-29 16:08:16 -0500233
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800234 // Add the package to the set of packages with the same ID.
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800235 PackageGroup* package_group = &package_groups_[idx];
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800236 package_group->packages_.emplace_back().loaded_package_ = package.get();
Ryan Mitchell824cc492020-02-12 10:48:14 -0800237 package_group->cookies_.push_back(apk_assets_cookies[apk_assets]);
Adam Lesinskida431a22016-12-29 16:08:16 -0500238
239 // Add the package name -> build time ID mappings.
240 for (const DynamicPackageEntry& entry : package->GetDynamicPackageMap()) {
241 String16 package_name(entry.package_name.c_str(), entry.package_name.size());
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700242 package_group->dynamic_ref_table->mEntries.replaceValueFor(
Adam Lesinskida431a22016-12-29 16:08:16 -0500243 package_name, static_cast<uint8_t>(entry.package_id));
244 }
Ryan Mitchellb894c272020-02-12 10:31:44 -0800245
Ryan Mitchellef538432021-03-01 14:52:14 -0800246 if (auto apk_assets_path = apk_assets->GetPath()) {
247 // Overlay target ApkAssets must have been created using path based load apis.
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800248 target_assets_package_ids.emplace(*apk_assets_path, package_id);
Ryan Mitchellef538432021-03-01 14:52:14 -0800249 }
Adam Lesinskida431a22016-12-29 16:08:16 -0500250 }
251 }
252
253 // Now assign the runtime IDs so that we have a build-time to runtime ID map.
Yurii Zubrytskyi59dab3b2022-11-03 00:08:49 -0700254 DynamicRefTable::AliasMap aliases;
255 for (const auto& group : package_groups_) {
256 const std::string& package_name = group.packages_[0].loaded_package_->GetPackageName();
257 const auto name_16 = String16(package_name.c_str(), package_name.size());
258 for (auto&& inner_group : package_groups_) {
259 inner_group.dynamic_ref_table->addMapping(name_16,
260 group.dynamic_ref_table->mAssignedPackageId);
Adam Lesinskida431a22016-12-29 16:08:16 -0500261 }
Yurii Zubrytskyi59dab3b2022-11-03 00:08:49 -0700262
263 for (const auto& package : group.packages_) {
264 const auto& package_aliases = package.loaded_package_->GetAliasResourceIdMap();
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800265 aliases.insert(aliases.end(), package_aliases.begin(), package_aliases.end());
Yurii Zubrytskyi59dab3b2022-11-03 00:08:49 -0700266 }
267 }
268
269 if (!aliases.empty()) {
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800270 std::sort(aliases.begin(), aliases.end(), [](auto&& l, auto&& r) { return l.first < r.first; });
271
Yurii Zubrytskyi59dab3b2022-11-03 00:08:49 -0700272 // Add the alias resources to the dynamic reference table of every package group. Since
273 // staging aliases can only be defined by the framework package (which is not a shared
274 // library), the compile-time package id of the framework is the same across all packages
275 // that compile against the framework.
276 for (auto& group : std::span(package_groups_.data(), package_groups_.size() - 1)) {
277 group.dynamic_ref_table->setAliases(aliases);
278 }
279 package_groups_.back().dynamic_ref_table->setAliases(std::move(aliases));
Adam Lesinskida431a22016-12-29 16:08:16 -0500280 }
281}
282
283void AssetManager2::DumpToLog() const {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800284 LOG(INFO) << base::StringPrintf("AssetManager2(this=%p)", this);
285
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700286 auto op = StartOperation();
Adam Lesinskida431a22016-12-29 16:08:16 -0500287 std::string list;
Yurii Zubrytskyi7d70bc52023-05-12 13:27:54 -0700288 for (size_t i = 0, s = apk_assets_.size(); i < s; ++i) {
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700289 const auto& assets = GetApkAssets(i);
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700290 base::StringAppendF(&list, "%s,", assets ? assets->GetDebugName().c_str() : "nullptr");
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800291 }
292 LOG(INFO) << "ApkAssets: " << list;
293
294 list = "";
Adam Lesinskida431a22016-12-29 16:08:16 -0500295 for (size_t i = 0; i < package_ids_.size(); i++) {
296 if (package_ids_[i] != 0xff) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800297 base::StringAppendF(&list, "%02x -> %d, ", (int)i, package_ids_[i]);
Adam Lesinskida431a22016-12-29 16:08:16 -0500298 }
299 }
300 LOG(INFO) << "Package ID map: " << list;
301
Biswarup Palbc306b42025-02-06 23:31:30 +0000302 for (const auto& package_group : package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800303 list = "";
304 for (const auto& package : package_group.packages_) {
305 const LoadedPackage* loaded_package = package.loaded_package_;
306 base::StringAppendF(&list, "%s(%02x%s), ", loaded_package->GetPackageName().c_str(),
307 loaded_package->GetPackageId(),
308 (loaded_package->IsDynamic() ? " dynamic" : ""));
309 }
310 LOG(INFO) << base::StringPrintf("PG (%02x): ",
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700311 package_group.dynamic_ref_table->mAssignedPackageId)
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800312 << list;
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800313
314 for (size_t i = 0; i < 256; i++) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700315 if (package_group.dynamic_ref_table->mLookupTable[i] != 0) {
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800316 LOG(INFO) << base::StringPrintf(" e[0x%02x] -> 0x%02x", (uint8_t) i,
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700317 package_group.dynamic_ref_table->mLookupTable[i]);
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800318 }
319 }
Adam Lesinskida431a22016-12-29 16:08:16 -0500320 }
321}
Adam Lesinski7ad11102016-10-28 16:39:15 -0700322
323const ResStringPool* AssetManager2::GetStringPoolForCookie(ApkAssetsCookie cookie) const {
324 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
325 return nullptr;
326 }
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700327 auto op = StartOperation();
328 const auto& assets = GetApkAssets(cookie);
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700329 return assets ? assets->GetLoadedArsc()->GetStringPool() : nullptr;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700330}
331
Adam Lesinskida431a22016-12-29 16:08:16 -0500332const DynamicRefTable* AssetManager2::GetDynamicRefTableForPackage(uint32_t package_id) const {
333 if (package_id >= package_ids_.size()) {
334 return nullptr;
335 }
336
337 const size_t idx = package_ids_[package_id];
338 if (idx == 0xff) {
339 return nullptr;
340 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700341 return package_groups_[idx].dynamic_ref_table.get();
Adam Lesinskida431a22016-12-29 16:08:16 -0500342}
343
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700344std::shared_ptr<const DynamicRefTable> AssetManager2::GetDynamicRefTableForCookie(
345 ApkAssetsCookie cookie) const {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800346 for (const PackageGroup& package_group : package_groups_) {
347 for (const ApkAssetsCookie& package_cookie : package_group.cookies_) {
348 if (package_cookie == cookie) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700349 return package_group.dynamic_ref_table;
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800350 }
351 }
352 }
353 return nullptr;
354}
355
MÃ¥rten Kongstadc92c4dd2019-02-05 01:29:59 +0100356const std::unordered_map<std::string, std::string>*
357 AssetManager2::GetOverlayableMapForPackage(uint32_t package_id) const {
MÃ¥rten Kongstadc92c4dd2019-02-05 01:29:59 +0100358 if (package_id >= package_ids_.size()) {
359 return nullptr;
360 }
361
362 const size_t idx = package_ids_[package_id];
363 if (idx == 0xff) {
364 return nullptr;
365 }
366
367 const PackageGroup& package_group = package_groups_[idx];
Ryan Mitchell80094e32020-11-16 23:08:18 +0000368 if (package_group.packages_.empty()) {
MÃ¥rten Kongstadc92c4dd2019-02-05 01:29:59 +0100369 return nullptr;
370 }
371
372 const auto loaded_package = package_group.packages_[0].loaded_package_;
373 return &loaded_package->GetOverlayableMap();
374}
375
Yurii Zubrytskyia5775142022-11-02 17:49:49 -0700376bool AssetManager2::GetOverlayablesToString(android::StringPiece package_name,
Ryan Mitchell2e394222019-08-28 12:10:51 -0700377 std::string* out) const {
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700378 auto op = StartOperation();
Ryan Mitchell2e394222019-08-28 12:10:51 -0700379 uint8_t package_id = 0U;
Yurii Zubrytskyi7d70bc52023-05-12 13:27:54 -0700380 for (size_t i = 0, s = apk_assets_.size(); i != s; ++i) {
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700381 const auto& assets = GetApkAssets(i);
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700382 if (!assets) {
383 continue;
384 }
385 const LoadedArsc* loaded_arsc = assets->GetLoadedArsc();
Ryan Mitchell2e394222019-08-28 12:10:51 -0700386 if (loaded_arsc == nullptr) {
387 continue;
388 }
389
390 const auto& loaded_packages = loaded_arsc->GetPackages();
391 if (loaded_packages.empty()) {
392 continue;
393 }
394
395 const auto& loaded_package = loaded_packages[0];
396 if (loaded_package->GetPackageName() == package_name) {
397 package_id = GetAssignedPackageId(loaded_package.get());
398 break;
399 }
400 }
401
402 if (package_id == 0U) {
403 ANDROID_LOG(ERROR) << base::StringPrintf("No package with name '%s", package_name.data());
404 return false;
405 }
406
407 const size_t idx = package_ids_[package_id];
408 if (idx == 0xff) {
409 return false;
410 }
411
412 std::string output;
413 for (const ConfiguredPackage& package : package_groups_[idx].packages_) {
414 const LoadedPackage* loaded_package = package.loaded_package_;
415 for (auto it = loaded_package->begin(); it != loaded_package->end(); it++) {
416 const OverlayableInfo* info = loaded_package->GetOverlayableInfo(*it);
417 if (info != nullptr) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000418 auto res_name = GetResourceName(*it);
419 if (!res_name.has_value()) {
Ryan Mitchell2e394222019-08-28 12:10:51 -0700420 ANDROID_LOG(ERROR) << base::StringPrintf(
421 "Unable to retrieve name of overlayable resource 0x%08x", *it);
422 return false;
423 }
424
Ryan Mitchell80094e32020-11-16 23:08:18 +0000425 const std::string name = ToFormattedResourceString(*res_name);
Ryan Mitchell2e394222019-08-28 12:10:51 -0700426 output.append(base::StringPrintf(
427 "resource='%s' overlayable='%s' actor='%s' policy='0x%08x'\n",
Yurii Zubrytskyi9d225372022-11-29 11:12:18 -0800428 name.c_str(), info->name.data(), info->actor.data(), info->policy_flags));
Ryan Mitchell2e394222019-08-28 12:10:51 -0700429 }
430 }
431 }
432
433 *out = std::move(output);
434 return true;
435}
436
Ryan Mitchell192400c2020-04-02 09:54:23 -0700437bool AssetManager2::ContainsAllocatedTable() const {
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700438 auto op = StartOperation();
Yurii Zubrytskyi7d70bc52023-05-12 13:27:54 -0700439 for (size_t i = 0, s = apk_assets_.size(); i != s; ++i) {
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700440 const auto& assets = GetApkAssets(i);
441 if (assets && assets->IsTableAllocated()) {
442 return true;
443 }
444 }
445 return false;
Ryan Mitchell192400c2020-04-02 09:54:23 -0700446}
447
Jeremy Meyere00958a2025-02-19 16:55:19 -0800448static std::string ConfigVecToString(std::span<const ResTable_config> configurations) {
449 std::stringstream ss;
450 ss << "[";
451 bool first = true;
452 for (const auto& config : configurations) {
453 if (!first) {
454 ss << ",";
455 }
456 char out[RESTABLE_MAX_LOCALE_LEN] = {};
457 config.getBcp47Locale(out);
458 ss << out;
459 first = false;
460 }
461 ss << "]";
462 return ss.str();
463}
464
465
Yurii Zubrytskyic4dadee2024-08-15 12:08:47 -0700466void AssetManager2::SetConfigurations(std::span<const ResTable_config> configurations,
467 bool force_refresh) {
Jeremy Meyerccf5cd72023-08-15 21:42:03 +0000468 int diff = 0;
Michael Hoisie7b433332024-02-13 21:42:21 +0000469 if (force_refresh) {
Jeremy Meyerccf5cd72023-08-15 21:42:03 +0000470 diff = -1;
471 } else {
Michael Hoisie7b433332024-02-13 21:42:21 +0000472 if (configurations_.size() != configurations.size()) {
473 diff = -1;
474 } else {
475 for (int i = 0; i < configurations_.size(); i++) {
476 diff |= configurations_[i].diff(configurations[i]);
477 }
Jeremy Meyerccf5cd72023-08-15 21:42:03 +0000478 }
479 }
Jeremy Meyere00958a2025-02-19 16:55:19 -0800480
481 // Log the locale list change to investigate b/392255526
482 if (diff & ConfigDescription::CONFIG_LOCALE) {
483 auto oldstr = ConfigVecToString(configurations_);
484 auto newstr = ConfigVecToString(configurations);
485 if (oldstr != newstr) {
486 LOG(INFO) << "AssetManager2(" << this << ") locale list changing from "
487 << oldstr << " to " << newstr;
488 }
489 }
490
Yurii Zubrytskyic4dadee2024-08-15 12:08:47 -0700491 configurations_.clear();
492 for (auto&& config : configurations) {
493 configurations_.emplace_back(config);
494 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700495 if (diff) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800496 RebuildFilterList();
Adam Lesinski7ad11102016-10-28 16:39:15 -0700497 InvalidateCaches(static_cast<uint32_t>(diff));
498 }
499}
500
Jeremy Meyere00958a2025-02-19 16:55:19 -0800501void AssetManager2::SetDefaultLocale(std::optional<ResTable_config> default_locale) {
502 int diff = 0;
503 if (default_locale_ && default_locale) {
504 diff = default_locale_->diff(default_locale.value());
505 } else if (default_locale_ || default_locale) {
506 diff = -1;
507 }
508 if (diff & ConfigDescription::CONFIG_LOCALE) {
509 char old_loc[RESTABLE_MAX_LOCALE_LEN] = {};
510 char new_loc[RESTABLE_MAX_LOCALE_LEN] = {};
511 if (default_locale_) {
512 default_locale_->getBcp47Locale(old_loc);
513 }
514 if (default_locale) {
515 default_locale->getBcp47Locale(new_loc);
516 }
517 LOG(INFO) << "AssetManager2(" << this << ") default locale changing from '"
518 << old_loc << "' to '" << new_loc << "'";
519 }
520 default_locale_ = default_locale;
521}
522
Biswarup Palbc306b42025-02-06 23:31:30 +0000523void AssetManager2::SetOverlayConstraints(int32_t display_id, int32_t device_id) {
524 bool changed = false;
525 if (display_id_ != display_id) {
526 display_id_ = display_id;
527 changed = true;
528 }
529 if (device_id_ != device_id) {
530 device_id_ = device_id;
531 changed = true;
532 }
533 if (changed) {
534 // Enable/disable overlays based on current constraints
535 for (PackageGroup& group : package_groups_) {
536 for (auto &overlay: group.overlays_) {
537 overlay.enabled = IsAnyOverlayConstraintSatisfied(
538 overlay.overlay_res_maps_.GetConstraints());
539 }
540 }
541 InvalidateCaches(static_cast<uint32_t>(-1));
542 }
543}
544
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700545std::set<AssetManager2::ApkAssetsPtr> AssetManager2::GetNonSystemOverlays() const {
546 std::set<ApkAssetsPtr> non_system_overlays;
Adam Lesinski0c405242017-01-13 20:47:26 -0800547 for (const PackageGroup& package_group : package_groups_) {
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800548 bool found_system_package = false;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800549 for (const ConfiguredPackage& package : package_group.packages_) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700550 if (package.loaded_package_->IsSystem()) {
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800551 found_system_package = true;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700552 break;
553 }
554 }
555
556 if (!found_system_package) {
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700557 auto op = StartOperation();
Biswarup Palbc306b42025-02-06 23:31:30 +0000558 // Return all overlays, including the disabled ones as this is used for static info
559 // collection only.
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700560 for (const ConfiguredOverlay& overlay : package_group.overlays_) {
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700561 if (const auto& asset = GetApkAssets(overlay.cookie)) {
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700562 non_system_overlays.insert(std::move(asset));
563 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700564 }
565 }
566 }
567
568 return non_system_overlays;
569}
570
Ryan Mitchell80094e32020-11-16 23:08:18 +0000571base::expected<std::set<ResTable_config>, IOError> AssetManager2::GetResourceConfigurations(
572 bool exclude_system, bool exclude_mipmap) const {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700573 ATRACE_NAME("AssetManager::GetResourceConfigurations");
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700574 auto op = StartOperation();
575
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700576 const auto non_system_overlays =
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700577 exclude_system ? GetNonSystemOverlays() : std::set<ApkAssetsPtr>();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700578
579 std::set<ResTable_config> configurations;
580 for (const PackageGroup& package_group : package_groups_) {
581 for (size_t i = 0; i < package_group.packages_.size(); i++) {
582 const ConfiguredPackage& package = package_group.packages_[i];
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700583 if (exclude_system) {
584 if (package.loaded_package_->IsSystem()) {
585 continue;
586 }
587 if (!non_system_overlays.empty()) {
588 // Exclude overlays that target only system resources.
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700589 const auto& apk_assets = GetApkAssets(package_group.cookies_[i]);
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700590 if (apk_assets && apk_assets->IsOverlay() &&
591 non_system_overlays.find(apk_assets) == non_system_overlays.end()) {
592 continue;
593 }
594 }
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800595 }
596
Ryan Mitchell80094e32020-11-16 23:08:18 +0000597 auto result = package.loaded_package_->CollectConfigurations(exclude_mipmap, &configurations);
598 if (UNLIKELY(!result.has_value())) {
599 return base::unexpected(result.error());
600 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800601 }
602 }
603 return configurations;
604}
605
Yurii Zubrytskyi984a84e2025-03-20 12:17:05 -0700606LoadedPackage::Locales AssetManager2::GetResourceLocales(
607 bool exclude_system, bool merge_equivalent_languages) const {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800608 ATRACE_NAME("AssetManager::GetResourceLocales");
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700609 auto op = StartOperation();
610
Yurii Zubrytskyi984a84e2025-03-20 12:17:05 -0700611 LoadedPackage::Locales locales;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700612 const auto non_system_overlays =
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700613 exclude_system ? GetNonSystemOverlays() : std::set<ApkAssetsPtr>();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700614
Adam Lesinski0c405242017-01-13 20:47:26 -0800615 for (const PackageGroup& package_group : package_groups_) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700616 for (size_t i = 0; i < package_group.packages_.size(); i++) {
617 const ConfiguredPackage& package = package_group.packages_[i];
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700618 if (exclude_system) {
619 if (package.loaded_package_->IsSystem()) {
620 continue;
621 }
622 if (!non_system_overlays.empty()) {
623 // Exclude overlays that target only system resources.
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700624 const auto& apk_assets = GetApkAssets(package_group.cookies_[i]);
Yurii Zubrytskyi984a84e2025-03-20 12:17:05 -0700625 if (apk_assets && apk_assets->IsOverlay() && !non_system_overlays.contains(apk_assets)) {
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700626 continue;
627 }
628 }
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800629 }
630
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800631 package.loaded_package_->CollectLocales(merge_equivalent_languages, &locales);
Adam Lesinski0c405242017-01-13 20:47:26 -0800632 }
633 }
634 return locales;
635}
636
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800637std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename,
638 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700639 const std::string new_path = "assets/" + filename;
640 return OpenNonAsset(new_path, mode);
641}
642
643std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename, ApkAssetsCookie cookie,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800644 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700645 const std::string new_path = "assets/" + filename;
646 return OpenNonAsset(new_path, cookie, mode);
647}
648
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800649std::unique_ptr<AssetDir> AssetManager2::OpenDir(const std::string& dirname) const {
650 ATRACE_NAME("AssetManager::OpenDir");
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700651 auto op = StartOperation();
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800652
653 std::string full_path = "assets/" + dirname;
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700654 auto files = util::make_unique<SortedVector<AssetDir::FileInfo>>();
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800655
656 // Start from the back.
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700657 for (size_t i = apk_assets_.size(); i > 0; --i) {
658 const auto& apk_assets = GetApkAssets(i - 1);
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700659 if (!apk_assets || apk_assets->IsOverlay()) {
MÃ¥rten Kongstaddbf343b2019-02-21 07:54:18 +0100660 continue;
661 }
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800662
Yurii Zubrytskyia5775142022-11-02 17:49:49 -0700663 auto func = [&](StringPiece name, FileType type) {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800664 AssetDir::FileInfo info;
665 info.setFileName(String8(name.data(), name.size()));
666 info.setFileType(type);
Ryan Mitchellef538432021-03-01 14:52:14 -0800667 info.setSourceName(String8(apk_assets->GetDebugName().c_str()));
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800668 files->add(info);
669 };
670
Ryan Mitchellc07aa702020-03-10 13:49:12 -0700671 if (!apk_assets->GetAssetsProvider()->ForEachFile(full_path, func)) {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800672 return {};
673 }
674 }
675
676 std::unique_ptr<AssetDir> asset_dir = util::make_unique<AssetDir>();
677 asset_dir->setFileList(files.release());
678 return asset_dir;
679}
680
Adam Lesinski7ad11102016-10-28 16:39:15 -0700681// Search in reverse because that's how we used to do it and we need to preserve behaviour.
682// This is unfortunate, because ClassLoaders delegate to the parent first, so the order
683// is inconsistent for split APKs.
684std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
685 Asset::AccessMode mode,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800686 ApkAssetsCookie* out_cookie) const {
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700687 auto op = StartOperation();
688 for (size_t i = apk_assets_.size(); i > 0; i--) {
689 const auto& assets = GetApkAssets(i - 1);
MÃ¥rten Kongstaddbf343b2019-02-21 07:54:18 +0100690 // Prevent RRO from modifying assets and other entries accessed by file
691 // path. Explicitly asking for a path in a given package (denoted by a
692 // cookie) is still OK.
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700693 if (!assets || assets->IsOverlay()) {
MÃ¥rten Kongstaddbf343b2019-02-21 07:54:18 +0100694 continue;
695 }
696
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700697 std::unique_ptr<Asset> asset = assets->GetAssetsProvider()->Open(filename, mode);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700698 if (asset) {
699 if (out_cookie != nullptr) {
Yurii Zubrytskyif48a56f2023-11-21 08:15:13 -0800700 *out_cookie = i - 1;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700701 }
702 return asset;
703 }
704 }
705
706 if (out_cookie != nullptr) {
707 *out_cookie = kInvalidCookie;
708 }
709 return {};
710}
711
712std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800713 ApkAssetsCookie cookie,
714 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700715 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
716 return {};
717 }
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700718 auto op = StartOperation();
719 const auto& assets = GetApkAssets(cookie);
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700720 return assets ? assets->GetAssetsProvider()->Open(filename, mode) : nullptr;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700721}
722
Ryan Mitchell80094e32020-11-16 23:08:18 +0000723base::expected<FindEntryResult, NullOrIOError> AssetManager2::FindEntry(
724 uint32_t resid, uint16_t density_override, bool stop_at_first_match,
725 bool ignore_configuration) const {
726 const bool logging_enabled = resource_resolution_logging_enabled_;
727 if (UNLIKELY(logging_enabled)) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700728 // Clear the last logged resource resolution.
729 ResetResourceResolution();
730 last_resolution_.resid = resid;
731 }
732
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700733 auto op = StartOperation();
734
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700735 // Retrieve the package group from the package id of the resource id.
Ryan Mitchell80094e32020-11-16 23:08:18 +0000736 if (UNLIKELY(!is_valid_resid(resid))) {
Mark Hansenb406b0e2022-10-14 02:18:37 +0000737 LOG(ERROR) << base::StringPrintf("Invalid resource ID 0x%08x.", resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000738 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -0500739 }
740
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800741 const uint32_t package_id = get_package_id(resid);
742 const uint8_t type_idx = get_type_id(resid) - 1;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800743 const uint16_t entry_idx = get_entry_id(resid);
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700744 uint8_t package_idx = package_ids_[package_id];
Ryan Mitchell80094e32020-11-16 23:08:18 +0000745 if (UNLIKELY(package_idx == 0xff)) {
Mark Hansenb406b0e2022-10-14 02:18:37 +0000746 ANDROID_LOG(ERROR) << base::StringPrintf("No package ID %02x found for resource ID 0x%08x.",
Ryan Mitchell2fe23472019-02-27 09:43:01 -0800747 package_id, resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000748 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -0500749 }
750
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800751 const PackageGroup& package_group = package_groups_[package_idx];
Jeremy Meyerccf5cd72023-08-15 21:42:03 +0000752 std::optional<FindEntryResult> final_result;
753 bool final_has_locale = false;
754 bool final_overlaid = false;
Biswarup Palbc306b42025-02-06 23:31:30 +0000755 for (auto& config : configurations_) {
Jeremy Meyerccf5cd72023-08-15 21:42:03 +0000756 // Might use this if density_override != 0.
757 ResTable_config density_override_config;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800758
Jeremy Meyerccf5cd72023-08-15 21:42:03 +0000759 // Select our configuration or generate a density override configuration.
760 const ResTable_config* desired_config = &config;
761 if (density_override != 0 && density_override != config.density) {
762 density_override_config = config;
763 density_override_config.density = density_override;
764 desired_config = &density_override_config;
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700765 }
Jeremy Meyerccf5cd72023-08-15 21:42:03 +0000766
767 auto result = FindEntryInternal(package_group, type_idx, entry_idx, *desired_config,
768 stop_at_first_match, ignore_configuration);
769 if (UNLIKELY(!result.has_value())) {
770 return base::unexpected(result.error());
771 }
772 bool overlaid = false;
773 if (!stop_at_first_match && !ignore_configuration) {
774 const auto& assets = GetApkAssets(result->cookie);
775 if (!assets) {
776 ALOGE("Found expired ApkAssets #%d for resource ID 0x%08x.", result->cookie, resid);
777 return base::unexpected(std::nullopt);
778 }
779 if (!assets->IsLoader()) {
780 for (const auto& id_map : package_group.overlays_) {
Biswarup Palbc306b42025-02-06 23:31:30 +0000781 auto overlay_entry = id_map.enabled ?
782 id_map.overlay_res_maps_.Lookup(resid) : IdmapResMap::Result();
Jeremy Meyerccf5cd72023-08-15 21:42:03 +0000783 if (!overlay_entry) {
784 // No id map entry exists for this target resource.
Jeremy Meyer04cf00d2023-07-20 22:17:27 +0000785 continue;
786 }
Jeremy Meyerccf5cd72023-08-15 21:42:03 +0000787 if (overlay_entry.IsInlineValue()) {
788 // The target resource is overlaid by an inline value not represented by a resource.
789 ConfigDescription best_frro_config;
790 Res_value best_frro_value;
791 bool frro_found = false;
Jeremy Meyere00958a2025-02-19 16:55:19 -0800792 for(const auto& [config, value] : overlay_entry.GetInlineValue()) {
Jeremy Meyerccf5cd72023-08-15 21:42:03 +0000793 if ((!frro_found || config.isBetterThan(best_frro_config, desired_config))
794 && config.match(*desired_config)) {
795 frro_found = true;
796 best_frro_config = config;
797 best_frro_value = value;
798 }
799 }
800 if (!frro_found) {
801 continue;
802 }
803 result->entry = best_frro_value;
804 result->dynamic_ref_table = id_map.overlay_res_maps_.GetOverlayDynamicRefTable();
805 result->cookie = id_map.cookie;
806
807 if (UNLIKELY(logging_enabled)) {
808 last_resolution_.steps.push_back(Resolution::Step{
809 Resolution::Step::Type::OVERLAID_INLINE, result->cookie, String8()});
810 if (auto path = assets->GetPath()) {
811 const std::string overlay_path = path->data();
812 if (IsFabricatedOverlay(overlay_path)) {
813 // FRRO don't have package name so we use the creating package here.
814 String8 frro_name = String8("FRRO");
815 // Get the first part of it since the expected one should be like
816 // {overlayPackageName}-{overlayName}-{4 alphanumeric chars}.frro
817 // under /data/resource-cache/.
818 const std::string name = overlay_path.substr(overlay_path.rfind('/') + 1);
819 const size_t end = name.find('-');
820 if (frro_name.size() != overlay_path.size() && end != std::string::npos) {
821 frro_name.append(base::StringPrintf(" created by %s",
822 name.substr(0 /* pos */,
823 end).c_str()).c_str());
824 }
825 last_resolution_.best_package_name = frro_name;
826 } else {
827 last_resolution_.best_package_name = result->package_name->c_str();
828 }
829 }
830 overlaid = true;
831 }
832 continue;
833 }
834
835 auto overlay_result = FindEntry(overlay_entry.GetResourceId(), density_override,
836 false /* stop_at_first_match */,
837 false /* ignore_configuration */);
838 if (UNLIKELY(IsIOError(overlay_result))) {
839 return base::unexpected(overlay_result.error());
840 }
841 if (!overlay_result.has_value()) {
842 continue;
843 }
844
845 if (!overlay_result->config.isBetterThan(result->config, desired_config)
846 && overlay_result->config.compare(result->config) != 0) {
847 // The configuration of the entry for the overlay must be equal to or better than the
848 // target configuration to be chosen as the better value.
849 continue;
850 }
851
852 result->cookie = overlay_result->cookie;
853 result->entry = overlay_result->entry;
854 result->config = overlay_result->config;
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700855 result->dynamic_ref_table = id_map.overlay_res_maps_.GetOverlayDynamicRefTable();
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700856
857 if (UNLIKELY(logging_enabled)) {
858 last_resolution_.steps.push_back(
Jeremy Meyerccf5cd72023-08-15 21:42:03 +0000859 Resolution::Step{Resolution::Step::Type::OVERLAID, overlay_result->cookie,
860 overlay_result->config.toString()});
861 last_resolution_.best_package_name =
862 overlay_result->package_name->c_str();
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700863 overlaid = true;
864 }
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800865 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700866 }
867 }
Jeremy Meyerccf5cd72023-08-15 21:42:03 +0000868
869 bool has_locale = false;
870 if (result->config.locale == 0) {
Jeremy Meyere00958a2025-02-19 16:55:19 -0800871 // The default_locale_ is the locale used for any resources with no locale in the config
872 if (default_locale_) {
873 // Since we know default_locale_ has a locale and only a locale, match will tell us if that
874 // locale matches
875 has_locale = default_locale_->match(config);
Jeremy Meyerccf5cd72023-08-15 21:42:03 +0000876 }
877 } else {
878 has_locale = true;
879 }
880
Jeremy Meyer2ae6ed592023-09-13 12:39:53 -0700881 // if we don't have a result yet
Jeremy Meyerccf5cd72023-08-15 21:42:03 +0000882 if (!final_result ||
883 // or this config is better before the locale than the existing result
Yurii Zubrytskyi2e609b12025-03-17 17:00:04 -0700884 result->config.isBetterThanBeforeLocale(final_result->config, *desired_config) ||
Jeremy Meyerccf5cd72023-08-15 21:42:03 +0000885 // or the existing config isn't better before locale and this one specifies a locale
886 // whereas the existing one doesn't
Yurii Zubrytskyi2e609b12025-03-17 17:00:04 -0700887 (!final_result->config.isBetterThanBeforeLocale(result->config, *desired_config)
Jeremy Meyerccf5cd72023-08-15 21:42:03 +0000888 && has_locale && !final_has_locale)) {
889 final_result = result.value();
890 final_overlaid = overlaid;
891 final_has_locale = has_locale;
892 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700893 }
894
Ryan Mitchell80094e32020-11-16 23:08:18 +0000895 if (UNLIKELY(logging_enabled)) {
Jeremy Meyerccf5cd72023-08-15 21:42:03 +0000896 last_resolution_.cookie = final_result->cookie;
897 last_resolution_.type_string_ref = final_result->type_string_ref;
898 last_resolution_.entry_string_ref = final_result->entry_string_ref;
899 last_resolution_.best_config_name = final_result->config.toString();
900 if (!final_overlaid) {
901 last_resolution_.best_package_name = final_result->package_name->c_str();
Jackal Guo552b45d2021-09-29 10:52:19 +0800902 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700903 }
904
Jeremy Meyerccf5cd72023-08-15 21:42:03 +0000905 return *final_result;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700906}
907
Ryan Mitchell80094e32020-11-16 23:08:18 +0000908base::expected<FindEntryResult, NullOrIOError> AssetManager2::FindEntryInternal(
909 const PackageGroup& package_group, uint8_t type_idx, uint16_t entry_idx,
910 const ResTable_config& desired_config, bool stop_at_first_match,
911 bool ignore_configuration) const {
912 const bool logging_enabled = resource_resolution_logging_enabled_;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800913 ApkAssetsCookie best_cookie = kInvalidCookie;
914 const LoadedPackage* best_package = nullptr;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000915 incfs::verified_map_ptr<ResTable_type> best_type;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800916 const ResTable_config* best_config = nullptr;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000917 uint32_t best_offset = 0U;
918 uint32_t type_flags = 0U;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800919
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800920 // If `desired_config` is not the same as the set configuration or the caller will accept a value
921 // from any configuration, then we cannot use our filtered list of types since it only it contains
922 // types matched to the set configuration.
Jeremy Meyerccf5cd72023-08-15 21:42:03 +0000923 const bool use_filtered = !ignore_configuration && std::find_if(
924 configurations_.begin(), configurations_.end(),
925 [&desired_config](auto& value) { return &desired_config == &value; })
926 != configurations_.end();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700927 const size_t package_count = package_group.packages_.size();
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800928 for (size_t pi = 0; pi < package_count; pi++) {
929 const ConfiguredPackage& loaded_package_impl = package_group.packages_[pi];
930 const LoadedPackage* loaded_package = loaded_package_impl.loaded_package_;
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800931 const ApkAssetsCookie cookie = package_group.cookies_[pi];
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800932
933 // If the type IDs are offset in this package, we need to take that into account when searching
934 // for a type.
935 const TypeSpec* type_spec = loaded_package->GetTypeSpecByTypeIndex(type_idx);
936 if (UNLIKELY(type_spec == nullptr)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700937 continue;
938 }
939
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800940 // Allow custom loader packages to overlay resource values with configurations equivalent to the
941 // current best configuration.
942 const bool package_is_loader = loaded_package->IsCustomLoader();
943
Ryan Mitchell80094e32020-11-16 23:08:18 +0000944 auto entry_flags = type_spec->GetFlagsForEntryIndex(entry_idx);
Bernie Innocenti58cf8e32020-12-19 15:31:52 +0900945 if (UNLIKELY(!entry_flags.has_value())) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000946 return base::unexpected(entry_flags.error());
947 }
948 type_flags |= entry_flags.value();
949
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800950 const FilteredConfigGroup& filtered_group = loaded_package_impl.filtered_configs_[type_idx];
951 const size_t type_entry_count = (use_filtered) ? filtered_group.type_entries.size()
952 : type_spec->type_entries.size();
953 for (size_t i = 0; i < type_entry_count; i++) {
954 const TypeSpec::TypeEntry* type_entry = (use_filtered) ? filtered_group.type_entries[i]
955 : &type_spec->type_entries[i];
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800956
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800957 // We can skip calling ResTable_config::match() if the caller does not care for the
958 // configuration to match or if we're using the list of types that have already had their
Jeremy Meyer2ae6ed592023-09-13 12:39:53 -0700959 // configuration matched. The exception to this is when the user has multiple locales set
960 // because the filtered list will then have values from multiple locales and we will need to
961 // call match() to make sure the current entry matches the config we are currently checking.
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800962 const ResTable_config& this_config = type_entry->config;
Jeremy Meyer2ae6ed592023-09-13 12:39:53 -0700963 if (!((use_filtered && (configurations_.size() == 1))
964 || ignore_configuration || this_config.match(desired_config))) {
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800965 continue;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800966 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800967
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800968 Resolution::Step::Type resolution_type;
969 if (best_config == nullptr) {
970 resolution_type = Resolution::Step::Type::INITIAL;
971 } else if (this_config.isBetterThan(*best_config, &desired_config)) {
972 resolution_type = Resolution::Step::Type::BETTER_MATCH;
973 } else if (package_is_loader && this_config.compare(*best_config) == 0) {
974 resolution_type = Resolution::Step::Type::OVERLAID;
975 } else {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000976 if (UNLIKELY(logging_enabled)) {
Jackal Guo552b45d2021-09-29 10:52:19 +0800977 last_resolution_.steps.push_back(Resolution::Step{Resolution::Step::Type::SKIPPED,
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -0700978 cookie, this_config.toString()});
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800979 }
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800980 continue;
981 }
982
983 // The configuration matches and is better than the previous selection.
984 // Find the entry value if it exists for this configuration.
985 const auto& type = type_entry->type;
986 const auto offset = LoadedPackage::GetEntryOffset(type, entry_idx);
987 if (UNLIKELY(IsIOError(offset))) {
988 return base::unexpected(offset.error());
989 }
990
991 if (!offset.has_value()) {
992 if (UNLIKELY(logging_enabled)) {
Jackal Guo552b45d2021-09-29 10:52:19 +0800993 last_resolution_.steps.push_back(Resolution::Step{Resolution::Step::Type::NO_ENTRY,
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -0700994 cookie, this_config.toString()});
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800995 }
996 continue;
997 }
998
999 best_cookie = cookie;
1000 best_package = loaded_package;
1001 best_type = type;
1002 best_config = &this_config;
1003 best_offset = offset.value();
1004
1005 if (UNLIKELY(logging_enabled)) {
1006 last_resolution_.steps.push_back(Resolution::Step{resolution_type,
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -07001007 cookie, this_config.toString()});
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001008 }
1009
1010 // Any configuration will suffice, so break.
1011 if (stop_at_first_match) {
1012 break;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001013 }
1014 }
1015 }
1016
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001017 if (UNLIKELY(best_cookie == kInvalidCookie)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001018 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001019 }
1020
Eric Miao368cd192022-09-09 15:46:14 -07001021 auto best_entry_verified = LoadedPackage::GetEntryFromOffset(best_type, best_offset);
1022 if (!best_entry_verified.has_value()) {
1023 return base::unexpected(best_entry_verified.error());
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001024 }
1025
Eric Miao368cd192022-09-09 15:46:14 -07001026 const auto entry = GetEntryValue(*best_entry_verified);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001027 if (!entry.has_value()) {
1028 return base::unexpected(entry.error());
1029 }
Winson2f3669b2019-01-11 11:28:34 -08001030
Ryan Mitchell80094e32020-11-16 23:08:18 +00001031 return FindEntryResult{
1032 .cookie = best_cookie,
1033 .entry = *entry,
1034 .config = *best_config,
1035 .type_flags = type_flags,
Jeremy Meyerb76f7452025-03-12 10:55:53 -07001036 .entry_flags = (*best_entry_verified)->flags(),
Tomasz Wasilczyk9e039b92023-06-29 12:08:24 -07001037 .dynamic_ref_table = package_group.dynamic_ref_table.get(),
Ryan Mitchell80094e32020-11-16 23:08:18 +00001038 .package_name = &best_package->GetPackageName(),
1039 .type_string_ref = StringPoolRef(best_package->GetTypeStringPool(), best_type->id - 1),
1040 .entry_string_ref = StringPoolRef(best_package->GetKeyStringPool(),
Eric Miao368cd192022-09-09 15:46:14 -07001041 (*best_entry_verified)->key()),
Ryan Mitchell80094e32020-11-16 23:08:18 +00001042 };
Adam Lesinski7ad11102016-10-28 16:39:15 -07001043}
1044
Ryan Mitchell8a891d82019-07-01 09:48:23 -07001045void AssetManager2::ResetResourceResolution() const {
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -07001046 last_resolution_ = Resolution{};
Ryan Mitchell8a891d82019-07-01 09:48:23 -07001047}
1048
Winson2f3669b2019-01-11 11:28:34 -08001049void AssetManager2::SetResourceResolutionLoggingEnabled(bool enabled) {
1050 resource_resolution_logging_enabled_ = enabled;
Winson2f3669b2019-01-11 11:28:34 -08001051 if (!enabled) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -07001052 ResetResourceResolution();
Winson2f3669b2019-01-11 11:28:34 -08001053 }
1054}
1055
1056std::string AssetManager2::GetLastResourceResolution() const {
1057 if (!resource_resolution_logging_enabled_) {
1058 LOG(ERROR) << "Must enable resource resolution logging before getting path.";
Ryan Mitchell80094e32020-11-16 23:08:18 +00001059 return {};
Winson2f3669b2019-01-11 11:28:34 -08001060 }
1061
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001062 const ApkAssetsCookie cookie = last_resolution_.cookie;
Winson2f3669b2019-01-11 11:28:34 -08001063 if (cookie == kInvalidCookie) {
1064 LOG(ERROR) << "AssetManager hasn't resolved a resource to read resolution path.";
Ryan Mitchell80094e32020-11-16 23:08:18 +00001065 return {};
Winson2f3669b2019-01-11 11:28:34 -08001066 }
1067
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -07001068 auto op = StartOperation();
1069
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001070 const uint32_t resid = last_resolution_.resid;
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -07001071 const auto& assets = GetApkAssets(cookie);
Yurii Zubrytskyib3455192023-05-01 14:35:48 -07001072 const auto package =
1073 assets ? assets->GetLoadedArsc()->GetPackageById(get_package_id(resid)) : nullptr;
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001074
Winson2f3669b2019-01-11 11:28:34 -08001075 std::string resource_name_string;
Winson2f3669b2019-01-11 11:28:34 -08001076 if (package != nullptr) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001077 auto resource_name = ToResourceName(last_resolution_.type_string_ref,
1078 last_resolution_.entry_string_ref,
1079 package->GetPackageName());
1080 resource_name_string = resource_name.has_value() ?
1081 ToFormattedResourceString(resource_name.value()) : "<unknown>";
Winson2f3669b2019-01-11 11:28:34 -08001082 }
1083
1084 std::stringstream log_stream;
Jeremy Meyerccf5cd72023-08-15 21:42:03 +00001085 if (configurations_.size() == 1) {
1086 log_stream << base::StringPrintf("Resolution for 0x%08x %s\n"
1087 "\tFor config - %s", resid, resource_name_string.c_str(),
1088 configurations_[0].toString().c_str());
1089 } else {
1090 ResTable_config conf = configurations_[0];
1091 conf.clearLocale();
1092 log_stream << base::StringPrintf("Resolution for 0x%08x %s\n\tFor config - %s and locales",
1093 resid, resource_name_string.c_str(), conf.toString().c_str());
1094 char str[40];
1095 str[0] = '\0';
Biswarup Palbc306b42025-02-06 23:31:30 +00001096 for (auto iter = configurations_.begin(); iter < configurations_.end(); iter++) {
Jeremy Meyerccf5cd72023-08-15 21:42:03 +00001097 iter->getBcp47Locale(str);
1098 log_stream << base::StringPrintf(" %s%s", str, iter < configurations_.end() ? "," : "");
1099 }
1100 }
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001101 for (const Resolution::Step& step : last_resolution_.steps) {
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -07001102 constexpr static std::array kStepStrings = {
1103 "Found initial",
1104 "Found better",
1105 "Overlaid",
1106 "Overlaid inline",
1107 "Skipped",
1108 "No entry"
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001109 };
1110
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -07001111 if (step.type < Resolution::Step::Type::INITIAL
1112 || step.type > Resolution::Step::Type::NO_ENTRY) {
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001113 continue;
Winson2f3669b2019-01-11 11:28:34 -08001114 }
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -07001115 const auto prefix = kStepStrings[int(step.type) - int(Resolution::Step::Type::INITIAL)];
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -07001116 const auto& assets = GetApkAssets(step.cookie);
Yurii Zubrytskyib3455192023-05-01 14:35:48 -07001117 log_stream << "\n\t" << prefix << ": " << (assets ? assets->GetDebugName() : "<null>")
1118 << " #" << step.cookie;
Tomasz Wasilczyk8f74b2a2023-08-24 19:02:33 +00001119 if (!step.config_name.empty()) {
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -08001120 log_stream << " - " << step.config_name;
Winson2f3669b2019-01-11 11:28:34 -08001121 }
1122 }
1123
Jackal Guo552b45d2021-09-29 10:52:19 +08001124 log_stream << "\nBest matching is from "
Tomasz Wasilczyk8f74b2a2023-08-24 19:02:33 +00001125 << (last_resolution_.best_config_name.empty() ? "default"
Tomasz Wasilczyk835dfe52023-08-17 16:27:22 +00001126 : last_resolution_.best_config_name.c_str())
Jackal Guo552b45d2021-09-29 10:52:19 +08001127 << " configuration of " << last_resolution_.best_package_name;
Winson2f3669b2019-01-11 11:28:34 -08001128 return log_stream.str();
1129}
1130
Felka Chang00964e92021-12-10 01:19:08 +08001131base::expected<uint32_t, NullOrIOError> AssetManager2::GetParentThemeResourceId(uint32_t resid)
1132const {
1133 auto entry = FindEntry(resid, 0u /* density_override */,
1134 false /* stop_at_first_match */,
1135 false /* ignore_configuration */);
1136 if (!entry.has_value()) {
1137 return base::unexpected(entry.error());
1138 }
1139
1140 auto entry_map = std::get_if<incfs::verified_map_ptr<ResTable_map_entry>>(&entry->entry);
1141 if (entry_map == nullptr) {
1142 // Not a bag, nothing to do.
1143 return base::unexpected(std::nullopt);
1144 }
1145
1146 auto map = *entry_map;
1147 const uint32_t parent_resid = dtohl(map->parent.ident);
1148
1149 return parent_resid;
1150}
1151
Ryan Mitchell80094e32020-11-16 23:08:18 +00001152base::expected<AssetManager2::ResourceName, NullOrIOError> AssetManager2::GetResourceName(
1153 uint32_t resid) const {
1154 auto result = FindEntry(resid, 0u /* density_override */, true /* stop_at_first_match */,
1155 true /* ignore_configuration */);
1156 if (!result.has_value()) {
1157 return base::unexpected(result.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001158 }
1159
Ryan Mitchell80094e32020-11-16 23:08:18 +00001160 return ToResourceName(result->type_string_ref,
1161 result->entry_string_ref,
1162 *result->package_name);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001163}
1164
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001165base::expected<uint32_t, NullOrIOError> AssetManager2::GetResourceTypeSpecFlags(
1166 uint32_t resid) const {
1167 auto result = FindEntry(resid, 0u /* density_override */, false /* stop_at_first_match */,
1168 true /* ignore_configuration */);
1169 if (!result.has_value()) {
1170 return base::unexpected(result.error());
1171 }
1172 return result->type_flags;
1173}
1174
Ryan Mitchell80094e32020-11-16 23:08:18 +00001175base::expected<AssetManager2::SelectedValue, NullOrIOError> AssetManager2::GetResource(
1176 uint32_t resid, bool may_be_bag, uint16_t density_override) const {
1177 auto result = FindEntry(resid, density_override, false /* stop_at_first_match */,
1178 false /* ignore_configuration */);
1179 if (!result.has_value()) {
1180 return base::unexpected(result.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001181 }
1182
Ryan Mitchell80094e32020-11-16 23:08:18 +00001183 auto result_map_entry = std::get_if<incfs::verified_map_ptr<ResTable_map_entry>>(&result->entry);
Ryan Mitchellbf1f45b2020-09-29 17:22:52 -07001184 if (result_map_entry != nullptr) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001185 if (!may_be_bag) {
1186 LOG(ERROR) << base::StringPrintf("Resource %08x is a complex map type.", resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001187 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001188 }
Adam Lesinski0c405242017-01-13 20:47:26 -08001189
1190 // Create a reference since we can't represent this complex type as a Res_value.
Jeremy Meyerb76f7452025-03-12 10:55:53 -07001191 return SelectedValue(Res_value::TYPE_REFERENCE, resid, result->cookie, result->entry_flags,
1192 result->type_flags, resid, result->config);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001193 }
1194
Adam Lesinskida431a22016-12-29 16:08:16 -05001195 // Convert the package ID to the runtime assigned package ID.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001196 Res_value value = std::get<Res_value>(result->entry);
1197 result->dynamic_ref_table->lookupResourceValue(&value);
Adam Lesinskida431a22016-12-29 16:08:16 -05001198
Jeremy Meyerb76f7452025-03-12 10:55:53 -07001199 return SelectedValue(value.dataType, value.data, result->cookie, result->entry_flags,
1200 result->type_flags, resid, result->config);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001201}
1202
Ryan Mitchell80094e32020-11-16 23:08:18 +00001203base::expected<std::monostate, NullOrIOError> AssetManager2::ResolveReference(
Ryan Mitchella45506e2020-11-16 23:08:18 +00001204 AssetManager2::SelectedValue& value, bool cache_value) const {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001205 if (value.type != Res_value::TYPE_REFERENCE || value.data == 0U) {
1206 // Not a reference. Nothing to do.
1207 return {};
Adam Lesinski0c405242017-01-13 20:47:26 -08001208 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001209
Ryan Mitchella45506e2020-11-16 23:08:18 +00001210 const uint32_t original_flags = value.flags;
1211 const uint32_t original_resid = value.data;
1212 if (cache_value) {
1213 auto cached_value = cached_resolved_values_.find(value.data);
1214 if (cached_value != cached_resolved_values_.end()) {
1215 value = cached_value->second;
1216 value.flags |= original_flags;
1217 return {};
1218 }
1219 }
1220
1221 uint32_t combined_flags = 0U;
1222 uint32_t resolve_resid = original_resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001223 constexpr const uint32_t kMaxIterations = 20;
1224 for (uint32_t i = 0U;; i++) {
1225 auto result = GetResource(resolve_resid, true /*may_be_bag*/);
1226 if (!result.has_value()) {
Ryan Mitchelle7ab6272020-11-13 18:06:15 -08001227 value.resid = resolve_resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001228 return base::unexpected(result.error());
1229 }
1230
Ryan Mitchelle7ab6272020-11-13 18:06:15 -08001231 // If resource resolution fails, the value should be set to the last reference that was able to
1232 // be resolved successfully.
1233 value = *result;
1234 value.flags |= combined_flags;
1235
Ryan Mitchell80094e32020-11-16 23:08:18 +00001236 if (result->type != Res_value::TYPE_REFERENCE ||
1237 result->data == Res_value::DATA_NULL_UNDEFINED ||
1238 result->data == resolve_resid || i == kMaxIterations) {
1239 // This reference can't be resolved, so exit now and let the caller deal with it.
Ryan Mitchella45506e2020-11-16 23:08:18 +00001240 if (cache_value) {
1241 cached_resolved_values_[original_resid] = value;
1242 }
1243
1244 // Above value is cached without original_flags to ensure they don't get included in future
1245 // queries that hit the cache
1246 value.flags |= original_flags;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001247 return {};
1248 }
1249
Ryan Mitchelle7ab6272020-11-13 18:06:15 -08001250 combined_flags = result->flags;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001251 resolve_resid = result->data;
1252 }
Adam Lesinski0c405242017-01-13 20:47:26 -08001253}
1254
Yurii Zubrytskyi02a555f2023-05-10 13:22:55 -07001255base::expected<const std::vector<uint32_t>*, NullOrIOError> AssetManager2::GetBagResIdStack(
1256 uint32_t resid) const {
Yurii Zubrytskyi09144882023-06-15 23:23:15 -07001257 auto it = cached_bag_resid_stacks_.find(resid);
1258 if (it != cached_bag_resid_stacks_.end()) {
1259 return &it->second;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001260 }
Yurii Zubrytskyi09144882023-06-15 23:23:15 -07001261 std::vector<uint32_t> stacks;
1262 if (auto maybe_bag = GetBag(resid, stacks); UNLIKELY(IsIOError(maybe_bag))) {
1263 return base::unexpected(maybe_bag.error());
1264 }
1265
1266 it = cached_bag_resid_stacks_.emplace(resid, std::move(stacks)).first;
Yurii Zubrytskyi02a555f2023-05-10 13:22:55 -07001267 return &it->second;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001268}
1269
Ryan Mitchell80094e32020-11-16 23:08:18 +00001270base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::ResolveBag(
1271 AssetManager2::SelectedValue& value) const {
1272 if (UNLIKELY(value.type != Res_value::TYPE_REFERENCE)) {
1273 return base::unexpected(std::nullopt);
1274 }
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001275
Ryan Mitchell80094e32020-11-16 23:08:18 +00001276 auto bag = GetBag(value.data);
1277 if (bag.has_value()) {
1278 value.flags |= (*bag)->type_spec_flags;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001279 }
1280 return bag;
y57cd1952018-04-12 14:26:23 -07001281}
1282
Ryan Mitchell80094e32020-11-16 23:08:18 +00001283base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::GetBag(uint32_t resid) const {
Yurii Zubrytskyi09144882023-06-15 23:23:15 -07001284 auto resid_stacks_it = cached_bag_resid_stacks_.find(resid);
Yurii Zubrytskyi533e8cc2023-06-16 16:38:49 -07001285 if (resid_stacks_it == cached_bag_resid_stacks_.end()) {
Yurii Zubrytskyi09144882023-06-15 23:23:15 -07001286 resid_stacks_it = cached_bag_resid_stacks_.emplace(resid, std::vector<uint32_t>{}).first;
1287 }
Yurii Zubrytskyibd1db5d2023-05-23 18:32:47 -07001288 const auto bag = GetBag(resid, resid_stacks_it->second);
1289 if (UNLIKELY(IsIOError(bag))) {
1290 cached_bag_resid_stacks_.erase(resid_stacks_it);
1291 return base::unexpected(bag.error());
1292 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001293 return bag;
Ryan Mitchell155d5392020-02-10 13:35:24 -08001294}
1295
Ryan Mitchell80094e32020-11-16 23:08:18 +00001296base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::GetBag(
1297 uint32_t resid, std::vector<uint32_t>& child_resids) const {
1298 if (auto cached_iter = cached_bags_.find(resid); cached_iter != cached_bags_.end()) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001299 return cached_iter->second.get();
1300 }
1301
Ryan Mitchell80094e32020-11-16 23:08:18 +00001302 auto entry = FindEntry(resid, 0u /* density_override */, false /* stop_at_first_match */,
1303 false /* ignore_configuration */);
1304 if (!entry.has_value()) {
1305 return base::unexpected(entry.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001306 }
1307
Ryan Mitchell80094e32020-11-16 23:08:18 +00001308 auto entry_map = std::get_if<incfs::verified_map_ptr<ResTable_map_entry>>(&entry->entry);
1309 if (entry_map == nullptr) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001310 // Not a bag, nothing to do.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001311 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001312 }
1313
Ryan Mitchell80094e32020-11-16 23:08:18 +00001314 auto map = *entry_map;
1315 auto map_entry = map.offset(dtohs(map->size)).convert<ResTable_map>();
1316 const auto map_entry_end = map_entry + dtohl(map->count);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001317
y57cd1952018-04-12 14:26:23 -07001318 // Keep track of ids that have already been seen to prevent infinite loops caused by circular
Ryan Mitchell80094e32020-11-16 23:08:18 +00001319 // dependencies between bags.
y57cd1952018-04-12 14:26:23 -07001320 child_resids.push_back(resid);
1321
Adam Lesinskida431a22016-12-29 16:08:16 -05001322 uint32_t parent_resid = dtohl(map->parent.ident);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001323 if (parent_resid == 0U ||
1324 std::find(child_resids.begin(), child_resids.end(), parent_resid) != child_resids.end()) {
1325 // There is no parent or a circular parental dependency exist, meaning there is nothing to
1326 // inherit and we can do a simple copy of the entries in the map.
Adam Lesinski7ad11102016-10-28 16:39:15 -07001327 const size_t entry_count = map_entry_end - map_entry;
1328 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
1329 malloc(sizeof(ResolvedBag) + (entry_count * sizeof(ResolvedBag::Entry))))};
Ryan Mitchell155d5392020-02-10 13:35:24 -08001330
1331 bool sort_entries = false;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001332 for (auto new_entry = new_bag->entries; map_entry != map_entry_end; ++map_entry) {
1333 if (UNLIKELY(!map_entry)) {
1334 return base::unexpected(IOError::PAGES_MISSING);
1335 }
1336
Adam Lesinskida431a22016-12-29 16:08:16 -05001337 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001338 if (!is_internal_resid(new_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -05001339 // Attributes, arrays, etc don't have a resource id as the name. They specify
1340 // other data, which would be wrong to change via a lookup.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001341 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001342 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
1343 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001344 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001345 }
1346 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001347
1348 new_entry->cookie = entry->cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -05001349 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001350 new_entry->key_pool = nullptr;
1351 new_entry->type_pool = nullptr;
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001352 new_entry->style = resid;
Adam Lesinski30080e22017-10-16 16:18:09 -07001353 new_entry->value.copyFrom_dtoh(map_entry->value);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001354 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1355 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001356 LOG(ERROR) << base::StringPrintf(
1357 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
1358 new_entry->value.data, new_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001359 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001360 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001361
Ryan Mitchell155d5392020-02-10 13:35:24 -08001362 sort_entries = sort_entries ||
1363 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001364 ++new_entry;
1365 }
Ryan Mitchell155d5392020-02-10 13:35:24 -08001366
1367 if (sort_entries) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001368 std::sort(new_bag->entries, new_bag->entries + entry_count,
1369 [](auto&& lhs, auto&& rhs) { return lhs.key < rhs.key; });
Ryan Mitchell155d5392020-02-10 13:35:24 -08001370 }
1371
Ryan Mitchell80094e32020-11-16 23:08:18 +00001372 new_bag->type_spec_flags = entry->type_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001373 new_bag->entry_count = static_cast<uint32_t>(entry_count);
1374 ResolvedBag* result = new_bag.get();
1375 cached_bags_[resid] = std::move(new_bag);
1376 return result;
1377 }
1378
Adam Lesinskida431a22016-12-29 16:08:16 -05001379 // In case the parent is a dynamic reference, resolve it.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001380 entry->dynamic_ref_table->lookupResourceId(&parent_resid);
Adam Lesinskida431a22016-12-29 16:08:16 -05001381
Adam Lesinski7ad11102016-10-28 16:39:15 -07001382 // Get the parent and do a merge of the keys.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001383 const auto parent_bag = GetBag(parent_resid, child_resids);
1384 if (UNLIKELY(!parent_bag.has_value())) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001385 // Failed to get the parent that should exist.
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001386 LOG(ERROR) << base::StringPrintf("Failed to find parent 0x%08x of bag 0x%08x.", parent_resid,
1387 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001388 return base::unexpected(parent_bag.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001389 }
1390
Adam Lesinski7ad11102016-10-28 16:39:15 -07001391 // Create the max possible entries we can make. Once we construct the bag,
1392 // we will realloc to fit to size.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001393 const size_t max_count = (*parent_bag)->entry_count + dtohl(map->count);
George Burgess IV09b119f2017-07-25 15:00:04 -07001394 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
1395 malloc(sizeof(ResolvedBag) + (max_count * sizeof(ResolvedBag::Entry))))};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001396 ResolvedBag::Entry* new_entry = new_bag->entries;
1397
Ryan Mitchell80094e32020-11-16 23:08:18 +00001398 const ResolvedBag::Entry* parent_entry = (*parent_bag)->entries;
1399 const ResolvedBag::Entry* const parent_entry_end = parent_entry + (*parent_bag)->entry_count;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001400
1401 // The keys are expected to be in sorted order. Merge the two bags.
Ryan Mitchell155d5392020-02-10 13:35:24 -08001402 bool sort_entries = false;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001403 while (map_entry != map_entry_end && parent_entry != parent_entry_end) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001404 if (UNLIKELY(!map_entry)) {
1405 return base::unexpected(IOError::PAGES_MISSING);
1406 }
1407
Adam Lesinskida431a22016-12-29 16:08:16 -05001408 uint32_t child_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001409 if (!is_internal_resid(child_key)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001410 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&child_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001411 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", child_key,
1412 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001413 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001414 }
1415 }
1416
Adam Lesinski7ad11102016-10-28 16:39:15 -07001417 if (child_key <= parent_entry->key) {
1418 // Use the child key if it comes before the parent
1419 // or is equal to the parent (overrides).
Ryan Mitchell80094e32020-11-16 23:08:18 +00001420 new_entry->cookie = entry->cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001421 new_entry->key = child_key;
1422 new_entry->key_pool = nullptr;
1423 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -07001424 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001425 new_entry->style = resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001426 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1427 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001428 LOG(ERROR) << base::StringPrintf(
1429 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
1430 new_entry->value.data, child_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001431 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001432 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001433 ++map_entry;
1434 } else {
1435 // Take the parent entry as-is.
1436 memcpy(new_entry, parent_entry, sizeof(*new_entry));
1437 }
1438
Ryan Mitchell155d5392020-02-10 13:35:24 -08001439 sort_entries = sort_entries ||
1440 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001441 if (child_key >= parent_entry->key) {
1442 // Move to the next parent entry if we used it or it was overridden.
1443 ++parent_entry;
1444 }
1445 // Increment to the next entry to fill.
1446 ++new_entry;
1447 }
1448
1449 // Finish the child entries if they exist.
1450 while (map_entry != map_entry_end) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001451 if (UNLIKELY(!map_entry)) {
1452 return base::unexpected(IOError::PAGES_MISSING);
1453 }
1454
Adam Lesinskida431a22016-12-29 16:08:16 -05001455 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001456 if (!is_internal_resid(new_key)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001457 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001458 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
1459 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001460 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001461 }
1462 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001463 new_entry->cookie = entry->cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -05001464 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001465 new_entry->key_pool = nullptr;
1466 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -07001467 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001468 new_entry->style = resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001469 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1470 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001471 LOG(ERROR) << base::StringPrintf("Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.",
1472 new_entry->value.dataType, new_entry->value.data, new_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001473 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001474 }
Ryan Mitchell155d5392020-02-10 13:35:24 -08001475 sort_entries = sort_entries ||
1476 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001477 ++map_entry;
1478 ++new_entry;
1479 }
1480
1481 // Finish the parent entries if they exist.
1482 if (parent_entry != parent_entry_end) {
1483 // Take the rest of the parent entries as-is.
1484 const size_t num_entries_to_copy = parent_entry_end - parent_entry;
1485 memcpy(new_entry, parent_entry, num_entries_to_copy * sizeof(*new_entry));
1486 new_entry += num_entries_to_copy;
1487 }
1488
1489 // Resize the resulting array to fit.
1490 const size_t actual_count = new_entry - new_bag->entries;
1491 if (actual_count != max_count) {
George Burgess IV09b119f2017-07-25 15:00:04 -07001492 new_bag.reset(reinterpret_cast<ResolvedBag*>(realloc(
1493 new_bag.release(), sizeof(ResolvedBag) + (actual_count * sizeof(ResolvedBag::Entry)))));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001494 }
1495
Ryan Mitchell155d5392020-02-10 13:35:24 -08001496 if (sort_entries) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001497 std::sort(new_bag->entries, new_bag->entries + actual_count,
1498 [](auto&& lhs, auto&& rhs) { return lhs.key < rhs.key; });
Ryan Mitchell155d5392020-02-10 13:35:24 -08001499 }
1500
Adam Lesinski1a1e9c22017-10-13 15:45:34 -07001501 // Combine flags from the parent and our own bag.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001502 new_bag->type_spec_flags = entry->type_flags | (*parent_bag)->type_spec_flags;
George Burgess IV09b119f2017-07-25 15:00:04 -07001503 new_bag->entry_count = static_cast<uint32_t>(actual_count);
1504 ResolvedBag* result = new_bag.get();
1505 cached_bags_[resid] = std::move(new_bag);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001506 return result;
1507}
1508
Yurii Zubrytskyia5775142022-11-02 17:49:49 -07001509static bool Utf8ToUtf16(StringPiece str, std::u16string* out) {
Adam Lesinski929d6512017-01-16 19:11:19 -08001510 ssize_t len =
1511 utf8_to_utf16_length(reinterpret_cast<const uint8_t*>(str.data()), str.size(), false);
1512 if (len < 0) {
1513 return false;
1514 }
1515 out->resize(static_cast<size_t>(len));
1516 utf8_to_utf16(reinterpret_cast<const uint8_t*>(str.data()), str.size(), &*out->begin(),
1517 static_cast<size_t>(len + 1));
1518 return true;
1519}
1520
Ryan Mitchell80094e32020-11-16 23:08:18 +00001521base::expected<uint32_t, NullOrIOError> AssetManager2::GetResourceId(
1522 const std::string& resource_name, const std::string& fallback_type,
1523 const std::string& fallback_package) const {
Adam Lesinski929d6512017-01-16 19:11:19 -08001524 StringPiece package_name, type, entry;
1525 if (!ExtractResourceName(resource_name, &package_name, &type, &entry)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001526 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001527 }
1528
1529 if (entry.empty()) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001530 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001531 }
1532
1533 if (package_name.empty()) {
1534 package_name = fallback_package;
1535 }
1536
1537 if (type.empty()) {
1538 type = fallback_type;
1539 }
1540
1541 std::u16string type16;
1542 if (!Utf8ToUtf16(type, &type16)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001543 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001544 }
1545
1546 std::u16string entry16;
1547 if (!Utf8ToUtf16(entry, &entry16)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001548 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001549 }
1550
1551 const StringPiece16 kAttr16 = u"attr";
Adam Lesinski929d6512017-01-16 19:11:19 -08001552 for (const PackageGroup& package_group : package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001553 for (const ConfiguredPackage& package_impl : package_group.packages_) {
1554 const LoadedPackage* package = package_impl.loaded_package_;
Adam Lesinski929d6512017-01-16 19:11:19 -08001555 if (package_name != package->GetPackageName()) {
1556 // All packages in the same group are expected to have the same package name.
1557 break;
1558 }
1559
Ryan Mitchell80094e32020-11-16 23:08:18 +00001560 base::expected<uint32_t, NullOrIOError> resid = package->FindEntryByName(type16, entry16);
1561 if (UNLIKELY(IsIOError(resid))) {
1562 return base::unexpected(resid.error());
Jeremy Meyere00958a2025-02-19 16:55:19 -08001563 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001564
1565 if (!resid.has_value() && kAttr16 == type16) {
Adam Lesinski929d6512017-01-16 19:11:19 -08001566 // Private attributes in libraries (such as the framework) are sometimes encoded
1567 // under the type '^attr-private' in order to leave the ID space of public 'attr'
1568 // free for future additions. Check '^attr-private' for the same name.
Yurii Zubrytskyie5c50e72025-02-12 19:47:09 -08001569 const static std::u16string kAttrPrivate16 = u"^attr-private";
Adam Lesinski929d6512017-01-16 19:11:19 -08001570 resid = package->FindEntryByName(kAttrPrivate16, entry16);
1571 }
1572
Ryan Mitchell80094e32020-11-16 23:08:18 +00001573 if (resid.has_value()) {
1574 return fix_package_id(*resid, package_group.dynamic_ref_table->mAssignedPackageId);
Adam Lesinski929d6512017-01-16 19:11:19 -08001575 }
1576 }
1577 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001578 return base::unexpected(std::nullopt);
Adam Lesinski0c405242017-01-13 20:47:26 -08001579}
1580
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001581void AssetManager2::RebuildFilterList() {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001582 for (PackageGroup& group : package_groups_) {
Yurii Zubrytskyidbce3562022-11-14 22:26:10 -08001583 for (ConfiguredPackage& package : group.packages_) {
1584 package.filtered_configs_.forEachItem([](auto, auto& fcg) { fcg.type_entries.clear(); });
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001585 // Create the filters here.
Yurii Zubrytskyidbce3562022-11-14 22:26:10 -08001586 package.loaded_package_->ForEachTypeSpec([&](const TypeSpec& type_spec, uint8_t type_id) {
Yurii Zubrytskyi59dab3b2022-11-03 00:08:49 -07001587 FilteredConfigGroup* group = nullptr;
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001588 for (const auto& type_entry : type_spec.type_entries) {
Biswarup Palbc306b42025-02-06 23:31:30 +00001589 for (auto& config : configurations_) {
Jeremy Meyerccf5cd72023-08-15 21:42:03 +00001590 if (type_entry.config.match(config)) {
1591 if (!group) {
1592 group = &package.filtered_configs_.editItemAt(type_id - 1);
1593 }
1594 group->type_entries.push_back(&type_entry);
1595 break;
Yurii Zubrytskyi59dab3b2022-11-03 00:08:49 -07001596 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001597 }
1598 }
1599 });
Yurii Zubrytskyidbce3562022-11-14 22:26:10 -08001600 package.filtered_configs_.trimBuckets(
1601 [](const auto& fcg) { return fcg.type_entries.empty(); });
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001602 }
1603 }
1604}
1605
Biswarup Palbc306b42025-02-06 23:31:30 +00001606bool AssetManager2::IsAnyOverlayConstraintSatisfied(const Idmap_constraints& constraints) const {
1607 if (constraints.constraint_count == 0) {
1608 // There are no constraints, return true.
1609 return true;
1610 }
1611
1612 for (uint32_t i = 0; i < constraints.constraint_count; i++) {
1613 auto constraint = constraints.constraint_entries[i];
1614 if (constraint.constraint_type == kOverlayConstraintTypeDisplayId &&
1615 constraint.constraint_value == display_id_) {
1616 return true;
1617 }
1618 if (constraint.constraint_type == kOverlayConstraintTypeDeviceId &&
1619 constraint.constraint_value == device_id_) {
1620 return true;
1621 }
1622 }
1623
1624 return false;
1625}
1626
Adam Lesinski7ad11102016-10-28 16:39:15 -07001627void AssetManager2::InvalidateCaches(uint32_t diff) {
Yurii Zubrytskyi09144882023-06-15 23:23:15 -07001628 cached_resolved_values_.clear();
Ryan Mitchell2c4d8742019-03-04 09:41:00 -08001629
Adam Lesinski7ad11102016-10-28 16:39:15 -07001630 if (diff == 0xffffffffu) {
1631 // Everything must go.
1632 cached_bags_.clear();
Yurii Zubrytskyi09144882023-06-15 23:23:15 -07001633 cached_bag_resid_stacks_.clear();
Adam Lesinski7ad11102016-10-28 16:39:15 -07001634 return;
1635 }
1636
1637 // Be more conservative with what gets purged. Only if the bag has other possible
1638 // variations with respect to what changed (diff) should we remove it.
Yurii Zubrytskyi09144882023-06-15 23:23:15 -07001639 for (auto stack_it = cached_bag_resid_stacks_.begin();
1640 stack_it != cached_bag_resid_stacks_.end();) {
1641 const auto it = cached_bags_.find(stack_it->first);
1642 if (it == cached_bags_.end()) {
1643 stack_it = cached_bag_resid_stacks_.erase(stack_it);
1644 } else if ((diff & it->second->type_spec_flags) != 0) {
1645 cached_bags_.erase(it);
1646 stack_it = cached_bag_resid_stacks_.erase(stack_it);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001647 } else {
Yurii Zubrytskyi09144882023-06-15 23:23:15 -07001648 ++stack_it; // Keep the item in both caches.
Adam Lesinski7ad11102016-10-28 16:39:15 -07001649 }
1650 }
Ryan Mitchella45506e2020-11-16 23:08:18 +00001651
Yurii Zubrytskyi09144882023-06-15 23:23:15 -07001652 // Need to ensure that both bag caches are consistent, as we populate them in the same function.
1653 // Iterate over the cached bags to erase the items without the corresponding resid_stack cache
1654 // items.
1655 for (auto it = cached_bags_.begin(); it != cached_bags_.end();) {
1656 if ((diff & it->second->type_spec_flags) != 0) {
1657 it = cached_bags_.erase(it);
1658 } else {
1659 ++it;
1660 }
1661 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001662}
1663
Ryan Mitchell2e394222019-08-28 12:10:51 -07001664uint8_t AssetManager2::GetAssignedPackageId(const LoadedPackage* package) const {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001665 for (auto& package_group : package_groups_) {
1666 for (auto& package2 : package_group.packages_) {
1667 if (package2.loaded_package_ == package) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -07001668 return package_group.dynamic_ref_table->mAssignedPackageId;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001669 }
1670 }
1671 }
1672 return 0;
1673}
1674
Adam Lesinski30080e22017-10-16 16:18:09 -07001675std::unique_ptr<Theme> AssetManager2::NewTheme() {
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001676 constexpr size_t kInitialReserveSize = 32;
1677 auto theme = std::unique_ptr<Theme>(new Theme(this));
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001678 theme->keys_.reserve(kInitialReserveSize);
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001679 theme->entries_.reserve(kInitialReserveSize);
1680 return theme;
Adam Lesinski30080e22017-10-16 16:18:09 -07001681}
1682
Yurii Zubrytskyi9eb44c92022-11-14 23:44:52 -08001683void AssetManager2::ForEachPackage(base::function_ref<bool(const std::string&, uint8_t)> func,
1684 package_property_t excluded_property_flags) const {
1685 for (const PackageGroup& package_group : package_groups_) {
1686 const auto loaded_package = package_group.packages_.front().loaded_package_;
1687 if ((loaded_package->GetPropertyFlags() & excluded_property_flags) == 0U
1688 && !func(loaded_package->GetPackageName(),
1689 package_group.dynamic_ref_table->mAssignedPackageId)) {
1690 return;
1691 }
1692 }
1693}
1694
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -07001695AssetManager2::ScopedOperation AssetManager2::StartOperation() const {
1696 ++number_of_running_scoped_operations_;
1697 return ScopedOperation(*this);
1698}
1699
1700void AssetManager2::FinishOperation() const {
1701 if (number_of_running_scoped_operations_ < 1) {
1702 ALOGW("Invalid FinishOperation() call when there's none happening");
1703 return;
1704 }
1705 if (--number_of_running_scoped_operations_ == 0) {
1706 for (auto&& [_, assets] : apk_assets_) {
1707 assets.clear();
1708 }
1709 }
1710}
1711
1712const AssetManager2::ApkAssetsPtr& AssetManager2::GetApkAssets(ApkAssetsCookie cookie) const {
1713 DCHECK(number_of_running_scoped_operations_ > 0) << "Must have an operation running";
1714
1715 if (cookie < 0 || cookie >= apk_assets_.size()) {
1716 static const ApkAssetsPtr empty{};
1717 return empty;
1718 }
1719 auto& [wptr, res] = apk_assets_[cookie];
1720 if (!res) {
1721 res = wptr.promote();
1722 }
1723 return res;
1724}
1725
Adam Lesinski30080e22017-10-16 16:18:09 -07001726Theme::Theme(AssetManager2* asset_manager) : asset_manager_(asset_manager) {
1727}
1728
1729Theme::~Theme() = default;
1730
Yurii Zubrytskyi1e5452a2024-06-13 19:30:36 -07001731static bool IsUndefined(const Res_value& value) {
1732 // DATA_NULL_EMPTY (@empty) is a valid resource value and DATA_NULL_UNDEFINED represents
1733 // an absence of a valid value.
1734 return value.dataType == Res_value::TYPE_NULL && value.data != Res_value::DATA_NULL_EMPTY;
1735}
1736
Ryan Mitchell80094e32020-11-16 23:08:18 +00001737base::expected<std::monostate, NullOrIOError> Theme::ApplyStyle(uint32_t resid, bool force) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001738 ATRACE_NAME("Theme::ApplyStyle");
Adam Lesinski7ad11102016-10-28 16:39:15 -07001739
Ryan Mitchell80094e32020-11-16 23:08:18 +00001740 auto bag = asset_manager_->GetBag(resid);
1741 if (!bag.has_value()) {
1742 return base::unexpected(bag.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001743 }
1744
1745 // Merge the flags from this style.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001746 type_spec_flags_ |= (*bag)->type_spec_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001747
Yurii Zubrytskyi1e5452a2024-06-13 19:30:36 -07001748 //
1749 // This function is the most expensive part of applying an frro to the existing app resources,
1750 // and needs to be as efficient as possible.
1751 // The data structure we're working with is two parallel sorted arrays of keys (resource IDs)
1752 // and entries (resource value + some attributes).
1753 // The styles get applied in sequence, starting with an empty set of attributes. Each style
1754 // contains its values for the theme attributes, and gets applied in either normal or forced way:
1755 // - normal way never overrides the existing attribute, so only unique style attributes are added
1756 // - forced way overrides anything for that attribute, and if it's undefined it removes the
1757 // previous value completely
1758 //
1759 // Style attributes come in a Bag data type - a sorted array of attributes with their values. This
1760 // means we don't need to re-sort the attributes ever, and instead:
1761 // - for an already existing attribute just skip it or apply the forced value
1762 // - if the forced value is undefined, mark it undefined as well to get rid of it later
1763 // - for a new attribute append it to the array, forming a new sorted section of new attributes
1764 // past the end of the original ones (ignore undefined ones here)
1765 // - inplace merge two sorted sections to form a single sorted array again.
1766 // - run the last pass to remove all undefined elements
1767 //
1768 // Using this algorithm performs better than a repeated binary search + insert in the middle,
1769 // as that keeps shifting the tail end of the arrays and wasting CPU cycles in memcpy().
1770 //
1771 const auto starting_size = keys_.size();
1772 if (starting_size == 0) {
1773 keys_.reserve((*bag)->entry_count);
1774 entries_.reserve((*bag)->entry_count);
1775 }
1776 bool wrote_undefined = false;
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001777 for (auto it = begin(*bag); it != end(*bag); ++it) {
1778 const uint32_t attr_res_id = it->key;
Adam Lesinski30080e22017-10-16 16:18:09 -07001779 // If the resource ID passed in is not a style, the key can be some other identifier that is not
1780 // a resource ID. We should fail fast instead of operating with strange resource IDs.
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001781 if (!is_valid_resid(attr_res_id)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001782 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001783 }
Yurii Zubrytskyi1e5452a2024-06-13 19:30:36 -07001784 const bool is_undefined = IsUndefined(it->value);
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001785 if (!force && is_undefined) {
1786 continue;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001787 }
Yurii Zubrytskyi1e5452a2024-06-13 19:30:36 -07001788 const auto key_it = std::lower_bound(keys_.begin(), keys_.begin() + starting_size, attr_res_id);
1789 if (key_it != keys_.begin() + starting_size && *key_it == attr_res_id) {
1790 const auto entry_it = entries_.begin() + (key_it - keys_.begin());
1791 if (force || IsUndefined(entry_it->value)) {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001792 *entry_it = Entry{it->cookie, (*bag)->type_spec_flags, it->value};
Yurii Zubrytskyi1e5452a2024-06-13 19:30:36 -07001793 wrote_undefined |= is_undefined;
Adam Lesinski30080e22017-10-16 16:18:09 -07001794 }
Yurii Zubrytskyi1e5452a2024-06-13 19:30:36 -07001795 } else if (!is_undefined) {
1796 keys_.emplace_back(attr_res_id);
1797 entries_.emplace_back(it->cookie, (*bag)->type_spec_flags, it->value);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001798 }
1799 }
Yurii Zubrytskyi1e5452a2024-06-13 19:30:36 -07001800
1801 if (starting_size && keys_.size() != starting_size) {
1802 std::inplace_merge(
1803 CombinedIterator(keys_.begin(), entries_.begin()),
1804 CombinedIterator(keys_.begin() + starting_size, entries_.begin() + starting_size),
1805 CombinedIterator(keys_.end(), entries_.end()));
1806 }
1807 if (wrote_undefined) {
1808 auto new_end = std::remove_if(CombinedIterator(keys_.begin(), entries_.begin()),
1809 CombinedIterator(keys_.end(), entries_.end()),
1810 [](const auto& pair) { return IsUndefined(pair.second.value); });
1811 keys_.erase(new_end.it1, keys_.end());
1812 entries_.erase(new_end.it2, entries_.end());
1813 }
1814 if (android::base::kEnableDChecks && !std::is_sorted(keys_.begin(), keys_.end())) {
1815 ALOGW("Bag %u was unsorted in the apk?", unsigned(resid));
1816 return base::unexpected(std::nullopt);
1817 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001818 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001819}
1820
Ryan Mitchell767e34f2021-06-07 12:29:05 -07001821void Theme::Rebase(AssetManager2* am, const uint32_t* style_ids, const uint8_t* force,
1822 size_t style_count) {
1823 ATRACE_NAME("Theme::Rebase");
1824 // Reset the entries without changing the vector capacity to prevent reallocations during
1825 // ApplyStyle.
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001826 keys_.clear();
Ryan Mitchell767e34f2021-06-07 12:29:05 -07001827 entries_.clear();
1828 asset_manager_ = am;
1829 for (size_t i = 0; i < style_count; i++) {
1830 ApplyStyle(style_ids[i], force[i]);
1831 }
1832}
1833
Ryan Mitchell80094e32020-11-16 23:08:18 +00001834std::optional<AssetManager2::SelectedValue> Theme::GetAttribute(uint32_t resid) const {
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001835 constexpr const uint32_t kMaxIterations = 20;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001836 uint32_t type_spec_flags = 0u;
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001837 for (uint32_t i = 0; i <= kMaxIterations; i++) {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001838 const auto key_it = std::lower_bound(keys_.begin(), keys_.end(), resid);
1839 if (key_it == keys_.end() || *key_it != resid) {
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001840 return std::nullopt;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001841 }
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001842 const auto entry_it = entries_.begin() + (key_it - keys_.begin());
Yurii Zubrytskyi1e5452a2024-06-13 19:30:36 -07001843 if (IsUndefined(entry_it->value)) {
1844 return std::nullopt;
1845 }
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001846 type_spec_flags |= entry_it->type_spec_flags;
1847 if (entry_it->value.dataType == Res_value::TYPE_ATTRIBUTE) {
1848 resid = entry_it->value.data;
1849 continue;
1850 }
1851
1852 return AssetManager2::SelectedValue(entry_it->value.dataType, entry_it->value.data,
Jeremy Meyerb76f7452025-03-12 10:55:53 -07001853 entry_it->cookie, 0U /* entry flags*/, type_spec_flags,
1854 0U /* resid */, {} /* config */);
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001855 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001856 return std::nullopt;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001857}
1858
Ryan Mitchell80094e32020-11-16 23:08:18 +00001859base::expected<std::monostate, NullOrIOError> Theme::ResolveAttributeReference(
1860 AssetManager2::SelectedValue& value) const {
1861 if (value.type != Res_value::TYPE_ATTRIBUTE) {
1862 return asset_manager_->ResolveReference(value);
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001863 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001864
1865 std::optional<AssetManager2::SelectedValue> result = GetAttribute(value.data);
1866 if (!result.has_value()) {
1867 return base::unexpected(std::nullopt);
1868 }
1869
Ryan Mitchella45506e2020-11-16 23:08:18 +00001870 auto resolve_result = asset_manager_->ResolveReference(*result, true /* cache_value */);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001871 if (resolve_result.has_value()) {
1872 result->flags |= value.flags;
1873 value = *result;
1874 }
1875 return resolve_result;
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001876}
1877
Adam Lesinski7ad11102016-10-28 16:39:15 -07001878void Theme::Clear() {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001879 keys_.clear();
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001880 entries_.clear();
Adam Lesinski7ad11102016-10-28 16:39:15 -07001881}
1882
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001883base::expected<std::monostate, IOError> Theme::SetTo(const Theme& source) {
1884 if (this == &source) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001885 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001886 }
1887
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001888 type_spec_flags_ = source.type_spec_flags_;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001889
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001890 if (asset_manager_ == source.asset_manager_) {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001891 keys_ = source.keys_;
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001892 entries_ = source.entries_;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001893 } else {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001894 std::unordered_map<ApkAssetsCookie, ApkAssetsCookie> src_to_dest_asset_cookies;
1895 using SourceToDestinationRuntimePackageMap = std::unordered_map<int, int>;
1896 std::unordered_map<ApkAssetsCookie, SourceToDestinationRuntimePackageMap> src_asset_cookie_id_map;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001897
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -07001898 auto op_src = source.asset_manager_->StartOperation();
1899 auto op_dst = asset_manager_->StartOperation();
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001900
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -07001901 for (size_t i = 0; i < source.asset_manager_->GetApkAssetsCount(); i++) {
1902 const auto& src_asset = source.asset_manager_->GetApkAssets(i);
1903 if (!src_asset) {
Yurii Zubrytskyib3455192023-05-01 14:35:48 -07001904 continue;
1905 }
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -07001906 for (int j = 0; j < asset_manager_->GetApkAssetsCount(); j++) {
1907 const auto& dest_asset = asset_manager_->GetApkAssets(j);
Ryan Mitchellef538432021-03-01 14:52:14 -08001908 if (src_asset != dest_asset) {
1909 // ResourcesManager caches and reuses ApkAssets when the same apk must be present in
1910 // multiple AssetManagers. Two ApkAssets point to the same version of the same resources
1911 // if they are the same instance.
1912 continue;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001913 }
Ryan Mitchellef538432021-03-01 14:52:14 -08001914
1915 // Map the package ids of the asset in the source AssetManager to the package ids of the
1916 // asset in th destination AssetManager.
1917 SourceToDestinationRuntimePackageMap package_map;
1918 for (const auto& loaded_package : src_asset->GetLoadedArsc()->GetPackages()) {
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001919 const int src_package_id = source.asset_manager_->GetAssignedPackageId(
1920 loaded_package.get());
Ryan Mitchellef538432021-03-01 14:52:14 -08001921 const int dest_package_id = asset_manager_->GetAssignedPackageId(loaded_package.get());
1922 package_map[src_package_id] = dest_package_id;
1923 }
1924
1925 src_to_dest_asset_cookies.insert(std::make_pair(i, j));
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001926 src_asset_cookie_id_map.insert(std::make_pair(i, std::move(package_map)));
Ryan Mitchellef538432021-03-01 14:52:14 -08001927 break;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001928 }
1929 }
1930
Ryan Mitchell93bca972019-03-08 17:26:28 -08001931 // Reset the data in the destination theme.
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001932 keys_.clear();
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001933 entries_.clear();
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001934
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001935 for (size_t i = 0, size = source.entries_.size(); i != size; ++i) {
1936 const auto& entry = source.entries_[i];
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001937 bool is_reference = (entry.value.dataType == Res_value::TYPE_ATTRIBUTE
1938 || entry.value.dataType == Res_value::TYPE_REFERENCE
1939 || entry.value.dataType == Res_value::TYPE_DYNAMIC_ATTRIBUTE
1940 || entry.value.dataType == Res_value::TYPE_DYNAMIC_REFERENCE)
1941 && entry.value.data != 0x0;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001942
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001943 // If the attribute value represents an attribute or reference, the package id of the
1944 // value needs to be rewritten to the package id of the value in the destination.
1945 uint32_t attribute_data = entry.value.data;
1946 if (is_reference) {
1947 // Determine the package id of the reference in the destination AssetManager.
1948 auto value_package_map = src_asset_cookie_id_map.find(entry.cookie);
1949 if (value_package_map == src_asset_cookie_id_map.end()) {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001950 continue;
1951 }
1952
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001953 auto value_dest_package = value_package_map->second.find(
1954 get_package_id(entry.value.data));
1955 if (value_dest_package == value_package_map->second.end()) {
1956 continue;
1957 }
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001958
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001959 attribute_data = fix_package_id(entry.value.data, value_dest_package->second);
1960 }
Ryan Mitchellb85d9b22018-11-19 12:11:38 -08001961
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001962 // Find the cookie of the value in the destination. If the source apk is not loaded in the
1963 // destination, only copy resources that do not reference resources in the source.
1964 ApkAssetsCookie data_dest_cookie;
1965 auto value_dest_cookie = src_to_dest_asset_cookies.find(entry.cookie);
1966 if (value_dest_cookie != src_to_dest_asset_cookies.end()) {
1967 data_dest_cookie = value_dest_cookie->second;
1968 } else {
1969 if (is_reference || entry.value.dataType == Res_value::TYPE_STRING) {
1970 continue;
1971 } else {
1972 data_dest_cookie = 0x0;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001973 }
1974 }
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001975
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001976 const auto source_res_id = source.keys_[i];
1977
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001978 // The package id of the attribute needs to be rewritten to the package id of the
1979 // attribute in the destination.
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001980 int attribute_dest_package_id = get_package_id(source_res_id);
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001981 if (attribute_dest_package_id != 0x01) {
1982 // Find the cookie of the attribute resource id in the source AssetManager
1983 base::expected<FindEntryResult, NullOrIOError> attribute_entry_result =
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001984 source.asset_manager_->FindEntry(source_res_id, 0 /* density_override */ ,
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001985 true /* stop_at_first_match */,
1986 true /* ignore_configuration */);
1987 if (UNLIKELY(IsIOError(attribute_entry_result))) {
1988 return base::unexpected(GetIOError(attribute_entry_result.error()));
1989 }
1990 if (!attribute_entry_result.has_value()) {
1991 continue;
1992 }
1993
1994 // Determine the package id of the attribute in the destination AssetManager.
1995 auto attribute_package_map = src_asset_cookie_id_map.find(
1996 attribute_entry_result->cookie);
1997 if (attribute_package_map == src_asset_cookie_id_map.end()) {
1998 continue;
1999 }
2000 auto attribute_dest_package = attribute_package_map->second.find(
2001 attribute_dest_package_id);
2002 if (attribute_dest_package == attribute_package_map->second.end()) {
2003 continue;
2004 }
2005 attribute_dest_package_id = attribute_dest_package->second;
2006 }
2007
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08002008 auto dest_attr_id = make_resid(attribute_dest_package_id, get_type_id(source_res_id),
2009 get_entry_id(source_res_id));
2010 const auto key_it = std::lower_bound(keys_.begin(), keys_.end(), dest_attr_id);
2011 const auto entry_it = entries_.begin() + (key_it - keys_.begin());
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07002012 // Since the entries were cleared, the attribute resource id has yet been mapped to any value.
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08002013 keys_.insert(key_it, dest_attr_id);
2014 entries_.insert(entry_it, Entry{data_dest_cookie, entry.type_spec_flags,
2015 Res_value{.dataType = entry.value.dataType,
2016 .data = attribute_data}});
Adam Lesinski7ad11102016-10-28 16:39:15 -07002017 }
2018 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00002019 return {};
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07002020}
2021
2022void Theme::Dump() const {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07002023 LOG(INFO) << base::StringPrintf("Theme(this=%p, AssetManager2=%p)", this, asset_manager_);
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08002024 for (size_t i = 0, size = keys_.size(); i != size; ++i) {
2025 auto res_id = keys_[i];
2026 const auto& entry = entries_[i];
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07002027 LOG(INFO) << base::StringPrintf(" entry(0x%08x)=(0x%08x) type=(0x%02x), cookie(%d)",
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08002028 res_id, entry.value.data, entry.value.dataType,
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07002029 entry.cookie);
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07002030 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07002031}
2032
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -07002033AssetManager2::ScopedOperation::ScopedOperation(const AssetManager2& am) : am_(am) {
2034}
2035
2036AssetManager2::ScopedOperation::~ScopedOperation() {
2037 am_.FinishOperation();
2038}
2039
Adam Lesinski7ad11102016-10-28 16:39:15 -07002040} // namespace android