blob: 4d83c9dc6903309078a482d6947fdef93d30af02 [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 Meyer72e79042025-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
48using EntryValue = std::variant<Res_value, incfs::verified_map_ptr<ResTable_map_entry>>;
49
Eric Miao368cd192022-09-09 15:46:14 -070050/* NOTE: table_entry has been verified in LoadedPackage::GetEntryFromOffset(),
51 * and so access to ->value() and ->map_entry() are safe here
52 */
Ryan Mitchell80094e32020-11-16 23:08:18 +000053base::expected<EntryValue, IOError> GetEntryValue(
54 incfs::verified_map_ptr<ResTable_entry> table_entry) {
Eric Miao368cd192022-09-09 15:46:14 -070055 const uint16_t entry_size = table_entry->size();
Ryan Mitchell80094e32020-11-16 23:08:18 +000056
57 // Check if the entry represents a bag value.
Eric Miao368cd192022-09-09 15:46:14 -070058 if (entry_size >= sizeof(ResTable_map_entry) && table_entry->is_complex()) {
59 return table_entry.convert<ResTable_map_entry>().verified();
Ryan Mitchell80094e32020-11-16 23:08:18 +000060 }
61
Eric Miao368cd192022-09-09 15:46:14 -070062 return table_entry->value();
Ryan Mitchell80094e32020-11-16 23:08:18 +000063}
64
65} // namespace
66
Adam Lesinskibebfcc42018-02-12 14:27:46 -080067struct FindEntryResult {
Ryan Mitchell80094e32020-11-16 23:08:18 +000068 // The cookie representing the ApkAssets in which the value resides.
69 ApkAssetsCookie cookie;
70
71 // The value of the resource table entry. Either an android::Res_value for non-bag types or an
72 // incfs::verified_map_ptr<ResTable_map_entry> for bag types.
73 EntryValue entry;
Adam Lesinskibebfcc42018-02-12 14:27:46 -080074
75 // The configuration for which the resulting entry was defined. This is already swapped to host
76 // endianness.
77 ResTable_config config;
78
79 // The bitmask of configuration axis with which the resource value varies.
80 uint32_t type_flags;
81
82 // The dynamic package ID map for the package from which this resource came from.
83 const DynamicRefTable* dynamic_ref_table;
84
Ryan Mitchell8a891d82019-07-01 09:48:23 -070085 // The package name of the resource.
86 const std::string* package_name;
87
Adam Lesinskibebfcc42018-02-12 14:27:46 -080088 // The string pool reference to the type's name. This uses a different string pool than
89 // the global string pool, but this is hidden from the caller.
90 StringPoolRef type_string_ref;
91
92 // The string pool reference to the entry's name. This uses a different string pool than
93 // the global string pool, but this is hidden from the caller.
94 StringPoolRef entry_string_ref;
95};
96
Ryan Prichard41e15a02023-08-30 22:19:30 -070097struct Theme::Entry {
98 ApkAssetsCookie cookie;
99 uint32_t type_spec_flags;
100 Res_value value;
101};
102
Jeremy Meyerccf5cd72023-08-15 21:42:03 +0000103AssetManager2::AssetManager2(ApkAssetsList apk_assets, const ResTable_config& configuration) {
104 configurations_.push_back(configuration);
105
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700106 // Don't invalidate caches here as there's nothing cached yet.
107 SetApkAssets(apk_assets, false);
Adam Lesinski970bd8d2017-09-25 13:21:55 -0700108}
Adam Lesinski7ad11102016-10-28 16:39:15 -0700109
Jeremy Meyerccf5cd72023-08-15 21:42:03 +0000110AssetManager2::AssetManager2() {
Yurii Zubrytskyic4dadee2024-08-15 12:08:47 -0700111 configurations_.emplace_back();
Jeremy Meyerccf5cd72023-08-15 21:42:03 +0000112}
113
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700114bool AssetManager2::SetApkAssets(ApkAssetsList apk_assets, bool invalidate_caches) {
115 BuildDynamicRefTable(apk_assets);
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800116 RebuildFilterList();
Adam Lesinski7ad11102016-10-28 16:39:15 -0700117 if (invalidate_caches) {
118 InvalidateCaches(static_cast<uint32_t>(-1));
119 }
120 return true;
121}
122
Michael Hoisie7b433332024-02-13 21:42:21 +0000123void AssetManager2::PresetApkAssets(ApkAssetsList apk_assets) {
124 BuildDynamicRefTable(apk_assets);
125}
126
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700127bool AssetManager2::SetApkAssets(std::initializer_list<ApkAssetsPtr> apk_assets,
128 bool invalidate_caches) {
129 return SetApkAssets(ApkAssetsList(apk_assets.begin(), apk_assets.size()), invalidate_caches);
130}
131
132void AssetManager2::BuildDynamicRefTable(ApkAssetsList apk_assets) {
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700133 auto op = StartOperation();
134
135 apk_assets_.resize(apk_assets.size());
136 for (size_t i = 0; i != apk_assets.size(); ++i) {
137 apk_assets_[i].first = apk_assets[i];
138 // Let's populate the locked assets right away as we're going to need them here later.
139 apk_assets_[i].second = apk_assets[i];
140 }
141
Adam Lesinskida431a22016-12-29 16:08:16 -0500142 package_groups_.clear();
143 package_ids_.fill(0xff);
144
Ryan Mitchellef538432021-03-01 14:52:14 -0800145 // A mapping from path of apk assets that could be target packages of overlays to the runtime
146 // package id of its first loaded package. Overlays currently can only override resources in the
147 // first package in the target resource table.
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800148 std::unordered_map<std::string_view, uint8_t> target_assets_package_ids;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700149
Ryan Mitchell824cc492020-02-12 10:48:14 -0800150 // Overlay resources are not directly referenced by an application so their resource ids
151 // can change throughout the application's lifetime. Assign overlay package ids last.
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700152 std::vector<const ApkAssets*> sorted_apk_assets;
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700153 sorted_apk_assets.reserve(apk_assets.size());
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700154 for (auto& asset : apk_assets) {
155 sorted_apk_assets.push_back(asset.get());
156 }
157 std::stable_partition(sorted_apk_assets.begin(), sorted_apk_assets.end(),
158 [](auto a) { return !a->IsOverlay(); });
Ryan Mitchell824cc492020-02-12 10:48:14 -0800159
160 // The assets cookie must map to the position of the apk assets in the unsorted apk assets list.
161 std::unordered_map<const ApkAssets*, ApkAssetsCookie> apk_assets_cookies;
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700162 apk_assets_cookies.reserve(apk_assets.size());
163 for (size_t i = 0, n = apk_assets.size(); i < n; i++) {
164 apk_assets_cookies[apk_assets[i].get()] = static_cast<ApkAssetsCookie>(i);
Ryan Mitchell824cc492020-02-12 10:48:14 -0800165 }
166
Ryan Mitchellb894c272020-02-12 10:31:44 -0800167 // 0x01 is reserved for the android package.
168 int next_package_id = 0x02;
Ryan Mitchell824cc492020-02-12 10:48:14 -0800169 for (const ApkAssets* apk_assets : sorted_apk_assets) {
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800170 std::shared_ptr<OverlayDynamicRefTable> overlay_ref_table;
171 if (auto loaded_idmap = apk_assets->GetLoadedIdmap(); loaded_idmap != nullptr) {
172 // The target package must precede the overlay package in the apk assets paths in order
173 // to take effect.
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800174 auto iter = target_assets_package_ids.find(loaded_idmap->TargetApkPath());
Ryan Mitchellef538432021-03-01 14:52:14 -0800175 if (iter == target_assets_package_ids.end()) {
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800176 LOG(INFO) << "failed to find target package for overlay "
177 << loaded_idmap->OverlayApkPath();
178 } else {
179 uint8_t target_package_id = iter->second;
180
181 // Create a special dynamic reference table for the overlay to rewrite references to
182 // overlay resources as references to the target resources they overlay.
183 overlay_ref_table = std::make_shared<OverlayDynamicRefTable>(
184 loaded_idmap->GetOverlayDynamicRefTable(target_package_id));
185
186 // Add the overlay resource map to the target package's set of overlays.
187 const uint8_t target_idx = package_ids_[target_package_id];
188 CHECK(target_idx != 0xff) << "overlay target '" << loaded_idmap->TargetApkPath()
189 << "'added to apk_assets_package_ids but does not have an"
190 << " assigned package group";
191
192 PackageGroup& target_package_group = package_groups_[target_idx];
193 target_package_group.overlays_.push_back(
194 ConfiguredOverlay{loaded_idmap->GetTargetResourcesMap(target_package_id,
195 overlay_ref_table.get()),
196 apk_assets_cookies[apk_assets]});
197 }
198 }
199
Ryan Mitchellb894c272020-02-12 10:31:44 -0800200 const LoadedArsc* loaded_arsc = apk_assets->GetLoadedArsc();
Ryan Mitchellb894c272020-02-12 10:31:44 -0800201 for (const std::unique_ptr<const LoadedPackage>& package : loaded_arsc->GetPackages()) {
202 // Get the package ID or assign one if a shared library.
203 int package_id;
204 if (package->IsDynamic()) {
205 package_id = next_package_id++;
206 } else {
207 package_id = package->GetPackageId();
Adam Lesinskida431a22016-12-29 16:08:16 -0500208 }
209
Adam Lesinskida431a22016-12-29 16:08:16 -0500210 uint8_t idx = package_ids_[package_id];
211 if (idx == 0xff) {
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800212 // Add the mapping for package ID to index if not present.
Adam Lesinskida431a22016-12-29 16:08:16 -0500213 package_ids_[package_id] = idx = static_cast<uint8_t>(package_groups_.size());
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800214 PackageGroup& new_group = package_groups_.emplace_back();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700215
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800216 if (overlay_ref_table != nullptr) {
217 // If this package is from an overlay, use a dynamic reference table that can rewrite
218 // overlay resource ids to their corresponding target resource ids.
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800219 new_group.dynamic_ref_table = std::move(overlay_ref_table);
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700220 }
221
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800222 DynamicRefTable* ref_table = new_group.dynamic_ref_table.get();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700223 ref_table->mAssignedPackageId = package_id;
224 ref_table->mAppAsLib = package->IsDynamic() && package->GetPackageId() == 0x7f;
Adam Lesinskida431a22016-12-29 16:08:16 -0500225 }
Adam Lesinskida431a22016-12-29 16:08:16 -0500226
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800227 // Add the package to the set of packages with the same ID.
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800228 PackageGroup* package_group = &package_groups_[idx];
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800229 package_group->packages_.emplace_back().loaded_package_ = package.get();
Ryan Mitchell824cc492020-02-12 10:48:14 -0800230 package_group->cookies_.push_back(apk_assets_cookies[apk_assets]);
Adam Lesinskida431a22016-12-29 16:08:16 -0500231
232 // Add the package name -> build time ID mappings.
233 for (const DynamicPackageEntry& entry : package->GetDynamicPackageMap()) {
234 String16 package_name(entry.package_name.c_str(), entry.package_name.size());
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700235 package_group->dynamic_ref_table->mEntries.replaceValueFor(
Adam Lesinskida431a22016-12-29 16:08:16 -0500236 package_name, static_cast<uint8_t>(entry.package_id));
237 }
Ryan Mitchellb894c272020-02-12 10:31:44 -0800238
Ryan Mitchellef538432021-03-01 14:52:14 -0800239 if (auto apk_assets_path = apk_assets->GetPath()) {
240 // Overlay target ApkAssets must have been created using path based load apis.
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800241 target_assets_package_ids.emplace(*apk_assets_path, package_id);
Ryan Mitchellef538432021-03-01 14:52:14 -0800242 }
Adam Lesinskida431a22016-12-29 16:08:16 -0500243 }
244 }
245
246 // Now assign the runtime IDs so that we have a build-time to runtime ID map.
Yurii Zubrytskyi59dab3b2022-11-03 00:08:49 -0700247 DynamicRefTable::AliasMap aliases;
248 for (const auto& group : package_groups_) {
249 const std::string& package_name = group.packages_[0].loaded_package_->GetPackageName();
250 const auto name_16 = String16(package_name.c_str(), package_name.size());
251 for (auto&& inner_group : package_groups_) {
252 inner_group.dynamic_ref_table->addMapping(name_16,
253 group.dynamic_ref_table->mAssignedPackageId);
Adam Lesinskida431a22016-12-29 16:08:16 -0500254 }
Yurii Zubrytskyi59dab3b2022-11-03 00:08:49 -0700255
256 for (const auto& package : group.packages_) {
257 const auto& package_aliases = package.loaded_package_->GetAliasResourceIdMap();
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800258 aliases.insert(aliases.end(), package_aliases.begin(), package_aliases.end());
Yurii Zubrytskyi59dab3b2022-11-03 00:08:49 -0700259 }
260 }
261
262 if (!aliases.empty()) {
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800263 std::sort(aliases.begin(), aliases.end(), [](auto&& l, auto&& r) { return l.first < r.first; });
264
Yurii Zubrytskyi59dab3b2022-11-03 00:08:49 -0700265 // Add the alias resources to the dynamic reference table of every package group. Since
266 // staging aliases can only be defined by the framework package (which is not a shared
267 // library), the compile-time package id of the framework is the same across all packages
268 // that compile against the framework.
269 for (auto& group : std::span(package_groups_.data(), package_groups_.size() - 1)) {
270 group.dynamic_ref_table->setAliases(aliases);
271 }
272 package_groups_.back().dynamic_ref_table->setAliases(std::move(aliases));
Adam Lesinskida431a22016-12-29 16:08:16 -0500273 }
274}
275
276void AssetManager2::DumpToLog() const {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800277 LOG(INFO) << base::StringPrintf("AssetManager2(this=%p)", this);
278
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700279 auto op = StartOperation();
Adam Lesinskida431a22016-12-29 16:08:16 -0500280 std::string list;
Yurii Zubrytskyi7d70bc52023-05-12 13:27:54 -0700281 for (size_t i = 0, s = apk_assets_.size(); i < s; ++i) {
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700282 const auto& assets = GetApkAssets(i);
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700283 base::StringAppendF(&list, "%s,", assets ? assets->GetDebugName().c_str() : "nullptr");
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800284 }
285 LOG(INFO) << "ApkAssets: " << list;
286
287 list = "";
Adam Lesinskida431a22016-12-29 16:08:16 -0500288 for (size_t i = 0; i < package_ids_.size(); i++) {
289 if (package_ids_[i] != 0xff) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800290 base::StringAppendF(&list, "%02x -> %d, ", (int)i, package_ids_[i]);
Adam Lesinskida431a22016-12-29 16:08:16 -0500291 }
292 }
293 LOG(INFO) << "Package ID map: " << list;
294
Adam Lesinski0dd36992018-01-25 15:38:38 -0800295 for (const auto& package_group: package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800296 list = "";
297 for (const auto& package : package_group.packages_) {
298 const LoadedPackage* loaded_package = package.loaded_package_;
299 base::StringAppendF(&list, "%s(%02x%s), ", loaded_package->GetPackageName().c_str(),
300 loaded_package->GetPackageId(),
301 (loaded_package->IsDynamic() ? " dynamic" : ""));
302 }
303 LOG(INFO) << base::StringPrintf("PG (%02x): ",
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700304 package_group.dynamic_ref_table->mAssignedPackageId)
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800305 << list;
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800306
307 for (size_t i = 0; i < 256; i++) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700308 if (package_group.dynamic_ref_table->mLookupTable[i] != 0) {
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800309 LOG(INFO) << base::StringPrintf(" e[0x%02x] -> 0x%02x", (uint8_t) i,
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700310 package_group.dynamic_ref_table->mLookupTable[i]);
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800311 }
312 }
Adam Lesinskida431a22016-12-29 16:08:16 -0500313 }
314}
Adam Lesinski7ad11102016-10-28 16:39:15 -0700315
316const ResStringPool* AssetManager2::GetStringPoolForCookie(ApkAssetsCookie cookie) const {
317 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
318 return nullptr;
319 }
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700320 auto op = StartOperation();
321 const auto& assets = GetApkAssets(cookie);
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700322 return assets ? assets->GetLoadedArsc()->GetStringPool() : nullptr;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700323}
324
Adam Lesinskida431a22016-12-29 16:08:16 -0500325const DynamicRefTable* AssetManager2::GetDynamicRefTableForPackage(uint32_t package_id) const {
326 if (package_id >= package_ids_.size()) {
327 return nullptr;
328 }
329
330 const size_t idx = package_ids_[package_id];
331 if (idx == 0xff) {
332 return nullptr;
333 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700334 return package_groups_[idx].dynamic_ref_table.get();
Adam Lesinskida431a22016-12-29 16:08:16 -0500335}
336
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700337std::shared_ptr<const DynamicRefTable> AssetManager2::GetDynamicRefTableForCookie(
338 ApkAssetsCookie cookie) const {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800339 for (const PackageGroup& package_group : package_groups_) {
340 for (const ApkAssetsCookie& package_cookie : package_group.cookies_) {
341 if (package_cookie == cookie) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700342 return package_group.dynamic_ref_table;
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800343 }
344 }
345 }
346 return nullptr;
347}
348
MÃ¥rten Kongstadc92c4dd2019-02-05 01:29:59 +0100349const std::unordered_map<std::string, std::string>*
350 AssetManager2::GetOverlayableMapForPackage(uint32_t package_id) const {
351
352 if (package_id >= package_ids_.size()) {
353 return nullptr;
354 }
355
356 const size_t idx = package_ids_[package_id];
357 if (idx == 0xff) {
358 return nullptr;
359 }
360
361 const PackageGroup& package_group = package_groups_[idx];
Ryan Mitchell80094e32020-11-16 23:08:18 +0000362 if (package_group.packages_.empty()) {
MÃ¥rten Kongstadc92c4dd2019-02-05 01:29:59 +0100363 return nullptr;
364 }
365
366 const auto loaded_package = package_group.packages_[0].loaded_package_;
367 return &loaded_package->GetOverlayableMap();
368}
369
Yurii Zubrytskyia5775142022-11-02 17:49:49 -0700370bool AssetManager2::GetOverlayablesToString(android::StringPiece package_name,
Ryan Mitchell2e394222019-08-28 12:10:51 -0700371 std::string* out) const {
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700372 auto op = StartOperation();
Ryan Mitchell2e394222019-08-28 12:10:51 -0700373 uint8_t package_id = 0U;
Yurii Zubrytskyi7d70bc52023-05-12 13:27:54 -0700374 for (size_t i = 0, s = apk_assets_.size(); i != s; ++i) {
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700375 const auto& assets = GetApkAssets(i);
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700376 if (!assets) {
377 continue;
378 }
379 const LoadedArsc* loaded_arsc = assets->GetLoadedArsc();
Ryan Mitchell2e394222019-08-28 12:10:51 -0700380 if (loaded_arsc == nullptr) {
381 continue;
382 }
383
384 const auto& loaded_packages = loaded_arsc->GetPackages();
385 if (loaded_packages.empty()) {
386 continue;
387 }
388
389 const auto& loaded_package = loaded_packages[0];
390 if (loaded_package->GetPackageName() == package_name) {
391 package_id = GetAssignedPackageId(loaded_package.get());
392 break;
393 }
394 }
395
396 if (package_id == 0U) {
397 ANDROID_LOG(ERROR) << base::StringPrintf("No package with name '%s", package_name.data());
398 return false;
399 }
400
401 const size_t idx = package_ids_[package_id];
402 if (idx == 0xff) {
403 return false;
404 }
405
406 std::string output;
407 for (const ConfiguredPackage& package : package_groups_[idx].packages_) {
408 const LoadedPackage* loaded_package = package.loaded_package_;
409 for (auto it = loaded_package->begin(); it != loaded_package->end(); it++) {
410 const OverlayableInfo* info = loaded_package->GetOverlayableInfo(*it);
411 if (info != nullptr) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000412 auto res_name = GetResourceName(*it);
413 if (!res_name.has_value()) {
Ryan Mitchell2e394222019-08-28 12:10:51 -0700414 ANDROID_LOG(ERROR) << base::StringPrintf(
415 "Unable to retrieve name of overlayable resource 0x%08x", *it);
416 return false;
417 }
418
Ryan Mitchell80094e32020-11-16 23:08:18 +0000419 const std::string name = ToFormattedResourceString(*res_name);
Ryan Mitchell2e394222019-08-28 12:10:51 -0700420 output.append(base::StringPrintf(
421 "resource='%s' overlayable='%s' actor='%s' policy='0x%08x'\n",
Yurii Zubrytskyi9d225372022-11-29 11:12:18 -0800422 name.c_str(), info->name.data(), info->actor.data(), info->policy_flags));
Ryan Mitchell2e394222019-08-28 12:10:51 -0700423 }
424 }
425 }
426
427 *out = std::move(output);
428 return true;
429}
430
Ryan Mitchell192400c2020-04-02 09:54:23 -0700431bool AssetManager2::ContainsAllocatedTable() const {
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700432 auto op = StartOperation();
Yurii Zubrytskyi7d70bc52023-05-12 13:27:54 -0700433 for (size_t i = 0, s = apk_assets_.size(); i != s; ++i) {
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700434 const auto& assets = GetApkAssets(i);
435 if (assets && assets->IsTableAllocated()) {
436 return true;
437 }
438 }
439 return false;
Ryan Mitchell192400c2020-04-02 09:54:23 -0700440}
441
Jeremy Meyer72e79042025-02-19 16:55:19 -0800442static std::string ConfigVecToString(std::span<const ResTable_config> configurations) {
443 std::stringstream ss;
444 ss << "[";
445 bool first = true;
446 for (const auto& config : configurations) {
447 if (!first) {
448 ss << ",";
449 }
450 char out[RESTABLE_MAX_LOCALE_LEN] = {};
451 config.getBcp47Locale(out);
452 ss << out;
453 first = false;
454 }
455 ss << "]";
456 return ss.str();
457}
458
459
Yurii Zubrytskyic4dadee2024-08-15 12:08:47 -0700460void AssetManager2::SetConfigurations(std::span<const ResTable_config> configurations,
461 bool force_refresh) {
Jeremy Meyerccf5cd72023-08-15 21:42:03 +0000462 int diff = 0;
Michael Hoisie7b433332024-02-13 21:42:21 +0000463 if (force_refresh) {
Jeremy Meyerccf5cd72023-08-15 21:42:03 +0000464 diff = -1;
465 } else {
Michael Hoisie7b433332024-02-13 21:42:21 +0000466 if (configurations_.size() != configurations.size()) {
467 diff = -1;
468 } else {
469 for (int i = 0; i < configurations_.size(); i++) {
470 diff |= configurations_[i].diff(configurations[i]);
471 }
Jeremy Meyerccf5cd72023-08-15 21:42:03 +0000472 }
473 }
Jeremy Meyer72e79042025-02-19 16:55:19 -0800474
475 // Log the locale list change to investigate b/392255526
476 if (diff & ConfigDescription::CONFIG_LOCALE) {
477 auto oldstr = ConfigVecToString(configurations_);
478 auto newstr = ConfigVecToString(configurations);
479 if (oldstr != newstr) {
480 LOG(INFO) << "AssetManager2(" << this << ") locale list changing from "
481 << oldstr << " to " << newstr;
482 }
483 }
484
Yurii Zubrytskyic4dadee2024-08-15 12:08:47 -0700485 configurations_.clear();
486 for (auto&& config : configurations) {
487 configurations_.emplace_back(config);
488 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700489 if (diff) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800490 RebuildFilterList();
Adam Lesinski7ad11102016-10-28 16:39:15 -0700491 InvalidateCaches(static_cast<uint32_t>(diff));
492 }
493}
494
Jeremy Meyer72e79042025-02-19 16:55:19 -0800495void AssetManager2::SetDefaultLocale(std::optional<ResTable_config> default_locale) {
496 int diff = 0;
497 if (default_locale_ && default_locale) {
498 diff = default_locale_->diff(default_locale.value());
499 } else if (default_locale_ || default_locale) {
500 diff = -1;
501 }
502 if (diff & ConfigDescription::CONFIG_LOCALE) {
503 char old_loc[RESTABLE_MAX_LOCALE_LEN] = {};
504 char new_loc[RESTABLE_MAX_LOCALE_LEN] = {};
505 if (default_locale_) {
506 default_locale_->getBcp47Locale(old_loc);
507 }
508 if (default_locale) {
509 default_locale->getBcp47Locale(new_loc);
510 }
511 LOG(INFO) << "AssetManager2(" << this << ") default locale changing from '"
512 << old_loc << "' to '" << new_loc << "'";
513 }
514 default_locale_ = default_locale;
515}
516
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700517std::set<AssetManager2::ApkAssetsPtr> AssetManager2::GetNonSystemOverlays() const {
518 std::set<ApkAssetsPtr> non_system_overlays;
Adam Lesinski0c405242017-01-13 20:47:26 -0800519 for (const PackageGroup& package_group : package_groups_) {
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800520 bool found_system_package = false;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800521 for (const ConfiguredPackage& package : package_group.packages_) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700522 if (package.loaded_package_->IsSystem()) {
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800523 found_system_package = true;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700524 break;
525 }
526 }
527
528 if (!found_system_package) {
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700529 auto op = StartOperation();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700530 for (const ConfiguredOverlay& overlay : package_group.overlays_) {
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700531 if (const auto& asset = GetApkAssets(overlay.cookie)) {
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700532 non_system_overlays.insert(std::move(asset));
533 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700534 }
535 }
536 }
537
538 return non_system_overlays;
539}
540
Ryan Mitchell80094e32020-11-16 23:08:18 +0000541base::expected<std::set<ResTable_config>, IOError> AssetManager2::GetResourceConfigurations(
542 bool exclude_system, bool exclude_mipmap) const {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700543 ATRACE_NAME("AssetManager::GetResourceConfigurations");
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700544 auto op = StartOperation();
545
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700546 const auto non_system_overlays =
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700547 exclude_system ? GetNonSystemOverlays() : std::set<ApkAssetsPtr>();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700548
549 std::set<ResTable_config> configurations;
550 for (const PackageGroup& package_group : package_groups_) {
551 for (size_t i = 0; i < package_group.packages_.size(); i++) {
552 const ConfiguredPackage& package = package_group.packages_[i];
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700553 if (exclude_system) {
554 if (package.loaded_package_->IsSystem()) {
555 continue;
556 }
557 if (!non_system_overlays.empty()) {
558 // Exclude overlays that target only system resources.
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700559 const auto& apk_assets = GetApkAssets(package_group.cookies_[i]);
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700560 if (apk_assets && apk_assets->IsOverlay() &&
561 non_system_overlays.find(apk_assets) == non_system_overlays.end()) {
562 continue;
563 }
564 }
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800565 }
566
Ryan Mitchell80094e32020-11-16 23:08:18 +0000567 auto result = package.loaded_package_->CollectConfigurations(exclude_mipmap, &configurations);
568 if (UNLIKELY(!result.has_value())) {
569 return base::unexpected(result.error());
570 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800571 }
572 }
573 return configurations;
574}
575
576std::set<std::string> AssetManager2::GetResourceLocales(bool exclude_system,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800577 bool merge_equivalent_languages) const {
578 ATRACE_NAME("AssetManager::GetResourceLocales");
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700579 auto op = StartOperation();
580
Adam Lesinski0c405242017-01-13 20:47:26 -0800581 std::set<std::string> locales;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700582 const auto non_system_overlays =
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700583 exclude_system ? GetNonSystemOverlays() : std::set<ApkAssetsPtr>();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700584
Adam Lesinski0c405242017-01-13 20:47:26 -0800585 for (const PackageGroup& package_group : package_groups_) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700586 for (size_t i = 0; i < package_group.packages_.size(); i++) {
587 const ConfiguredPackage& package = package_group.packages_[i];
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700588 if (exclude_system) {
589 if (package.loaded_package_->IsSystem()) {
590 continue;
591 }
592 if (!non_system_overlays.empty()) {
593 // Exclude overlays that target only system resources.
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700594 const auto& apk_assets = GetApkAssets(package_group.cookies_[i]);
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700595 if (apk_assets && apk_assets->IsOverlay() &&
596 non_system_overlays.find(apk_assets) == non_system_overlays.end()) {
597 continue;
598 }
599 }
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800600 }
601
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800602 package.loaded_package_->CollectLocales(merge_equivalent_languages, &locales);
Adam Lesinski0c405242017-01-13 20:47:26 -0800603 }
604 }
605 return locales;
606}
607
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800608std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename,
609 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700610 const std::string new_path = "assets/" + filename;
611 return OpenNonAsset(new_path, mode);
612}
613
614std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename, ApkAssetsCookie cookie,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800615 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700616 const std::string new_path = "assets/" + filename;
617 return OpenNonAsset(new_path, cookie, mode);
618}
619
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800620std::unique_ptr<AssetDir> AssetManager2::OpenDir(const std::string& dirname) const {
621 ATRACE_NAME("AssetManager::OpenDir");
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700622 auto op = StartOperation();
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800623
624 std::string full_path = "assets/" + dirname;
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700625 auto files = util::make_unique<SortedVector<AssetDir::FileInfo>>();
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800626
627 // Start from the back.
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700628 for (size_t i = apk_assets_.size(); i > 0; --i) {
629 const auto& apk_assets = GetApkAssets(i - 1);
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700630 if (!apk_assets || apk_assets->IsOverlay()) {
MÃ¥rten Kongstaddbf343b2019-02-21 07:54:18 +0100631 continue;
632 }
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800633
Yurii Zubrytskyia5775142022-11-02 17:49:49 -0700634 auto func = [&](StringPiece name, FileType type) {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800635 AssetDir::FileInfo info;
636 info.setFileName(String8(name.data(), name.size()));
637 info.setFileType(type);
Ryan Mitchellef538432021-03-01 14:52:14 -0800638 info.setSourceName(String8(apk_assets->GetDebugName().c_str()));
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800639 files->add(info);
640 };
641
Ryan Mitchellc07aa702020-03-10 13:49:12 -0700642 if (!apk_assets->GetAssetsProvider()->ForEachFile(full_path, func)) {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800643 return {};
644 }
645 }
646
647 std::unique_ptr<AssetDir> asset_dir = util::make_unique<AssetDir>();
648 asset_dir->setFileList(files.release());
649 return asset_dir;
650}
651
Adam Lesinski7ad11102016-10-28 16:39:15 -0700652// Search in reverse because that's how we used to do it and we need to preserve behaviour.
653// This is unfortunate, because ClassLoaders delegate to the parent first, so the order
654// is inconsistent for split APKs.
655std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
656 Asset::AccessMode mode,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800657 ApkAssetsCookie* out_cookie) const {
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700658 auto op = StartOperation();
659 for (size_t i = apk_assets_.size(); i > 0; i--) {
660 const auto& assets = GetApkAssets(i - 1);
MÃ¥rten Kongstaddbf343b2019-02-21 07:54:18 +0100661 // Prevent RRO from modifying assets and other entries accessed by file
662 // path. Explicitly asking for a path in a given package (denoted by a
663 // cookie) is still OK.
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700664 if (!assets || assets->IsOverlay()) {
MÃ¥rten Kongstaddbf343b2019-02-21 07:54:18 +0100665 continue;
666 }
667
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700668 std::unique_ptr<Asset> asset = assets->GetAssetsProvider()->Open(filename, mode);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700669 if (asset) {
670 if (out_cookie != nullptr) {
Yurii Zubrytskyif48a56f2023-11-21 08:15:13 -0800671 *out_cookie = i - 1;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700672 }
673 return asset;
674 }
675 }
676
677 if (out_cookie != nullptr) {
678 *out_cookie = kInvalidCookie;
679 }
680 return {};
681}
682
683std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800684 ApkAssetsCookie cookie,
685 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700686 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
687 return {};
688 }
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700689 auto op = StartOperation();
690 const auto& assets = GetApkAssets(cookie);
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700691 return assets ? assets->GetAssetsProvider()->Open(filename, mode) : nullptr;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700692}
693
Ryan Mitchell80094e32020-11-16 23:08:18 +0000694base::expected<FindEntryResult, NullOrIOError> AssetManager2::FindEntry(
695 uint32_t resid, uint16_t density_override, bool stop_at_first_match,
696 bool ignore_configuration) const {
697 const bool logging_enabled = resource_resolution_logging_enabled_;
698 if (UNLIKELY(logging_enabled)) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700699 // Clear the last logged resource resolution.
700 ResetResourceResolution();
701 last_resolution_.resid = resid;
702 }
703
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700704 auto op = StartOperation();
705
Adam Lesinski7ad11102016-10-28 16:39:15 -0700706
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700707 // Retrieve the package group from the package id of the resource id.
Ryan Mitchell80094e32020-11-16 23:08:18 +0000708 if (UNLIKELY(!is_valid_resid(resid))) {
Mark Hansenb406b0e2022-10-14 02:18:37 +0000709 LOG(ERROR) << base::StringPrintf("Invalid resource ID 0x%08x.", resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000710 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -0500711 }
712
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800713 const uint32_t package_id = get_package_id(resid);
714 const uint8_t type_idx = get_type_id(resid) - 1;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800715 const uint16_t entry_idx = get_entry_id(resid);
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700716 uint8_t package_idx = package_ids_[package_id];
Ryan Mitchell80094e32020-11-16 23:08:18 +0000717 if (UNLIKELY(package_idx == 0xff)) {
Mark Hansenb406b0e2022-10-14 02:18:37 +0000718 ANDROID_LOG(ERROR) << base::StringPrintf("No package ID %02x found for resource ID 0x%08x.",
Ryan Mitchell2fe23472019-02-27 09:43:01 -0800719 package_id, resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000720 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -0500721 }
722
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800723 const PackageGroup& package_group = package_groups_[package_idx];
Jeremy Meyerccf5cd72023-08-15 21:42:03 +0000724 std::optional<FindEntryResult> final_result;
725 bool final_has_locale = false;
726 bool final_overlaid = false;
727 for (auto & config : configurations_) {
728 // Might use this if density_override != 0.
729 ResTable_config density_override_config;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800730
Jeremy Meyerccf5cd72023-08-15 21:42:03 +0000731 // Select our configuration or generate a density override configuration.
732 const ResTable_config* desired_config = &config;
733 if (density_override != 0 && density_override != config.density) {
734 density_override_config = config;
735 density_override_config.density = density_override;
736 desired_config = &density_override_config;
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700737 }
Jeremy Meyerccf5cd72023-08-15 21:42:03 +0000738
739 auto result = FindEntryInternal(package_group, type_idx, entry_idx, *desired_config,
740 stop_at_first_match, ignore_configuration);
741 if (UNLIKELY(!result.has_value())) {
742 return base::unexpected(result.error());
743 }
744 bool overlaid = false;
745 if (!stop_at_first_match && !ignore_configuration) {
746 const auto& assets = GetApkAssets(result->cookie);
747 if (!assets) {
748 ALOGE("Found expired ApkAssets #%d for resource ID 0x%08x.", result->cookie, resid);
749 return base::unexpected(std::nullopt);
750 }
751 if (!assets->IsLoader()) {
752 for (const auto& id_map : package_group.overlays_) {
753 auto overlay_entry = id_map.overlay_res_maps_.Lookup(resid);
754 if (!overlay_entry) {
755 // No id map entry exists for this target resource.
Jeremy Meyer04cf00d2023-07-20 22:17:27 +0000756 continue;
757 }
Jeremy Meyerccf5cd72023-08-15 21:42:03 +0000758 if (overlay_entry.IsInlineValue()) {
759 // The target resource is overlaid by an inline value not represented by a resource.
760 ConfigDescription best_frro_config;
761 Res_value best_frro_value;
762 bool frro_found = false;
Jeremy Meyer72e79042025-02-19 16:55:19 -0800763 for (const auto& [config, value] : overlay_entry.GetInlineValue()) {
Jeremy Meyerccf5cd72023-08-15 21:42:03 +0000764 if ((!frro_found || config.isBetterThan(best_frro_config, desired_config))
765 && config.match(*desired_config)) {
766 frro_found = true;
767 best_frro_config = config;
768 best_frro_value = value;
769 }
770 }
771 if (!frro_found) {
772 continue;
773 }
774 result->entry = best_frro_value;
775 result->dynamic_ref_table = id_map.overlay_res_maps_.GetOverlayDynamicRefTable();
776 result->cookie = id_map.cookie;
777
778 if (UNLIKELY(logging_enabled)) {
779 last_resolution_.steps.push_back(Resolution::Step{
780 Resolution::Step::Type::OVERLAID_INLINE, result->cookie, String8()});
781 if (auto path = assets->GetPath()) {
782 const std::string overlay_path = path->data();
783 if (IsFabricatedOverlay(overlay_path)) {
784 // FRRO don't have package name so we use the creating package here.
785 String8 frro_name = String8("FRRO");
786 // Get the first part of it since the expected one should be like
787 // {overlayPackageName}-{overlayName}-{4 alphanumeric chars}.frro
788 // under /data/resource-cache/.
789 const std::string name = overlay_path.substr(overlay_path.rfind('/') + 1);
790 const size_t end = name.find('-');
791 if (frro_name.size() != overlay_path.size() && end != std::string::npos) {
792 frro_name.append(base::StringPrintf(" created by %s",
793 name.substr(0 /* pos */,
794 end).c_str()).c_str());
795 }
796 last_resolution_.best_package_name = frro_name;
797 } else {
798 last_resolution_.best_package_name = result->package_name->c_str();
799 }
800 }
801 overlaid = true;
802 }
803 continue;
804 }
805
806 auto overlay_result = FindEntry(overlay_entry.GetResourceId(), density_override,
807 false /* stop_at_first_match */,
808 false /* ignore_configuration */);
809 if (UNLIKELY(IsIOError(overlay_result))) {
810 return base::unexpected(overlay_result.error());
811 }
812 if (!overlay_result.has_value()) {
813 continue;
814 }
815
816 if (!overlay_result->config.isBetterThan(result->config, desired_config)
817 && overlay_result->config.compare(result->config) != 0) {
818 // The configuration of the entry for the overlay must be equal to or better than the
819 // target configuration to be chosen as the better value.
820 continue;
821 }
822
823 result->cookie = overlay_result->cookie;
824 result->entry = overlay_result->entry;
825 result->config = overlay_result->config;
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700826 result->dynamic_ref_table = id_map.overlay_res_maps_.GetOverlayDynamicRefTable();
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700827
828 if (UNLIKELY(logging_enabled)) {
829 last_resolution_.steps.push_back(
Jeremy Meyerccf5cd72023-08-15 21:42:03 +0000830 Resolution::Step{Resolution::Step::Type::OVERLAID, overlay_result->cookie,
831 overlay_result->config.toString()});
832 last_resolution_.best_package_name =
833 overlay_result->package_name->c_str();
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700834 overlaid = true;
835 }
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800836 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700837 }
838 }
Jeremy Meyerccf5cd72023-08-15 21:42:03 +0000839
840 bool has_locale = false;
841 if (result->config.locale == 0) {
Jeremy Meyer72e79042025-02-19 16:55:19 -0800842 // The default_locale_ is the locale used for any resources with no locale in the config
843 if (default_locale_) {
844 // Since we know default_locale_ has a locale and only a locale, match will tell us if that
845 // locale matches
846 has_locale = default_locale_->match(config);
Jeremy Meyerccf5cd72023-08-15 21:42:03 +0000847 }
848 } else {
849 has_locale = true;
850 }
851
Jeremy Meyer2ae6ed592023-09-13 12:39:53 -0700852 // if we don't have a result yet
Jeremy Meyerccf5cd72023-08-15 21:42:03 +0000853 if (!final_result ||
854 // or this config is better before the locale than the existing result
855 result->config.isBetterThanBeforeLocale(final_result->config, desired_config) ||
856 // or the existing config isn't better before locale and this one specifies a locale
857 // whereas the existing one doesn't
858 (!final_result->config.isBetterThanBeforeLocale(result->config, desired_config)
859 && has_locale && !final_has_locale)) {
860 final_result = result.value();
861 final_overlaid = overlaid;
862 final_has_locale = has_locale;
863 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700864 }
865
Ryan Mitchell80094e32020-11-16 23:08:18 +0000866 if (UNLIKELY(logging_enabled)) {
Jeremy Meyerccf5cd72023-08-15 21:42:03 +0000867 last_resolution_.cookie = final_result->cookie;
868 last_resolution_.type_string_ref = final_result->type_string_ref;
869 last_resolution_.entry_string_ref = final_result->entry_string_ref;
870 last_resolution_.best_config_name = final_result->config.toString();
871 if (!final_overlaid) {
872 last_resolution_.best_package_name = final_result->package_name->c_str();
Jackal Guo552b45d2021-09-29 10:52:19 +0800873 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700874 }
875
Jeremy Meyerccf5cd72023-08-15 21:42:03 +0000876 return *final_result;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700877}
878
Ryan Mitchell80094e32020-11-16 23:08:18 +0000879base::expected<FindEntryResult, NullOrIOError> AssetManager2::FindEntryInternal(
880 const PackageGroup& package_group, uint8_t type_idx, uint16_t entry_idx,
881 const ResTable_config& desired_config, bool stop_at_first_match,
882 bool ignore_configuration) const {
883 const bool logging_enabled = resource_resolution_logging_enabled_;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800884 ApkAssetsCookie best_cookie = kInvalidCookie;
885 const LoadedPackage* best_package = nullptr;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000886 incfs::verified_map_ptr<ResTable_type> best_type;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800887 const ResTable_config* best_config = nullptr;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000888 uint32_t best_offset = 0U;
889 uint32_t type_flags = 0U;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800890
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800891 // If `desired_config` is not the same as the set configuration or the caller will accept a value
892 // from any configuration, then we cannot use our filtered list of types since it only it contains
893 // types matched to the set configuration.
Jeremy Meyerccf5cd72023-08-15 21:42:03 +0000894 const bool use_filtered = !ignore_configuration && std::find_if(
895 configurations_.begin(), configurations_.end(),
896 [&desired_config](auto& value) { return &desired_config == &value; })
897 != configurations_.end();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700898 const size_t package_count = package_group.packages_.size();
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800899 for (size_t pi = 0; pi < package_count; pi++) {
900 const ConfiguredPackage& loaded_package_impl = package_group.packages_[pi];
901 const LoadedPackage* loaded_package = loaded_package_impl.loaded_package_;
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800902 const ApkAssetsCookie cookie = package_group.cookies_[pi];
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800903
904 // If the type IDs are offset in this package, we need to take that into account when searching
905 // for a type.
906 const TypeSpec* type_spec = loaded_package->GetTypeSpecByTypeIndex(type_idx);
907 if (UNLIKELY(type_spec == nullptr)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700908 continue;
909 }
910
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800911 // Allow custom loader packages to overlay resource values with configurations equivalent to the
912 // current best configuration.
913 const bool package_is_loader = loaded_package->IsCustomLoader();
914
Ryan Mitchell80094e32020-11-16 23:08:18 +0000915 auto entry_flags = type_spec->GetFlagsForEntryIndex(entry_idx);
Bernie Innocenti58cf8e32020-12-19 15:31:52 +0900916 if (UNLIKELY(!entry_flags.has_value())) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000917 return base::unexpected(entry_flags.error());
918 }
919 type_flags |= entry_flags.value();
920
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800921 const FilteredConfigGroup& filtered_group = loaded_package_impl.filtered_configs_[type_idx];
922 const size_t type_entry_count = (use_filtered) ? filtered_group.type_entries.size()
923 : type_spec->type_entries.size();
924 for (size_t i = 0; i < type_entry_count; i++) {
925 const TypeSpec::TypeEntry* type_entry = (use_filtered) ? filtered_group.type_entries[i]
926 : &type_spec->type_entries[i];
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800927
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800928 // We can skip calling ResTable_config::match() if the caller does not care for the
929 // configuration to match or if we're using the list of types that have already had their
Jeremy Meyer2ae6ed592023-09-13 12:39:53 -0700930 // configuration matched. The exception to this is when the user has multiple locales set
931 // because the filtered list will then have values from multiple locales and we will need to
932 // call match() to make sure the current entry matches the config we are currently checking.
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800933 const ResTable_config& this_config = type_entry->config;
Jeremy Meyer2ae6ed592023-09-13 12:39:53 -0700934 if (!((use_filtered && (configurations_.size() == 1))
935 || ignore_configuration || this_config.match(desired_config))) {
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800936 continue;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800937 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800938
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800939 Resolution::Step::Type resolution_type;
940 if (best_config == nullptr) {
941 resolution_type = Resolution::Step::Type::INITIAL;
942 } else if (this_config.isBetterThan(*best_config, &desired_config)) {
943 resolution_type = Resolution::Step::Type::BETTER_MATCH;
944 } else if (package_is_loader && this_config.compare(*best_config) == 0) {
945 resolution_type = Resolution::Step::Type::OVERLAID;
946 } else {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000947 if (UNLIKELY(logging_enabled)) {
Jackal Guo552b45d2021-09-29 10:52:19 +0800948 last_resolution_.steps.push_back(Resolution::Step{Resolution::Step::Type::SKIPPED,
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -0700949 cookie, this_config.toString()});
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800950 }
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800951 continue;
952 }
953
954 // The configuration matches and is better than the previous selection.
955 // Find the entry value if it exists for this configuration.
956 const auto& type = type_entry->type;
957 const auto offset = LoadedPackage::GetEntryOffset(type, entry_idx);
958 if (UNLIKELY(IsIOError(offset))) {
959 return base::unexpected(offset.error());
960 }
961
962 if (!offset.has_value()) {
963 if (UNLIKELY(logging_enabled)) {
Jackal Guo552b45d2021-09-29 10:52:19 +0800964 last_resolution_.steps.push_back(Resolution::Step{Resolution::Step::Type::NO_ENTRY,
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -0700965 cookie, this_config.toString()});
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800966 }
967 continue;
968 }
969
970 best_cookie = cookie;
971 best_package = loaded_package;
972 best_type = type;
973 best_config = &this_config;
974 best_offset = offset.value();
975
976 if (UNLIKELY(logging_enabled)) {
977 last_resolution_.steps.push_back(Resolution::Step{resolution_type,
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -0700978 cookie, this_config.toString()});
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800979 }
980
981 // Any configuration will suffice, so break.
982 if (stop_at_first_match) {
983 break;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700984 }
985 }
986 }
987
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800988 if (UNLIKELY(best_cookie == kInvalidCookie)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000989 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700990 }
991
Eric Miao368cd192022-09-09 15:46:14 -0700992 auto best_entry_verified = LoadedPackage::GetEntryFromOffset(best_type, best_offset);
993 if (!best_entry_verified.has_value()) {
994 return base::unexpected(best_entry_verified.error());
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800995 }
996
Eric Miao368cd192022-09-09 15:46:14 -0700997 const auto entry = GetEntryValue(*best_entry_verified);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000998 if (!entry.has_value()) {
999 return base::unexpected(entry.error());
1000 }
Winson2f3669b2019-01-11 11:28:34 -08001001
Ryan Mitchell80094e32020-11-16 23:08:18 +00001002 return FindEntryResult{
1003 .cookie = best_cookie,
1004 .entry = *entry,
1005 .config = *best_config,
1006 .type_flags = type_flags,
Tomasz Wasilczyk9e039b92023-06-29 12:08:24 -07001007 .dynamic_ref_table = package_group.dynamic_ref_table.get(),
Ryan Mitchell80094e32020-11-16 23:08:18 +00001008 .package_name = &best_package->GetPackageName(),
1009 .type_string_ref = StringPoolRef(best_package->GetTypeStringPool(), best_type->id - 1),
1010 .entry_string_ref = StringPoolRef(best_package->GetKeyStringPool(),
Eric Miao368cd192022-09-09 15:46:14 -07001011 (*best_entry_verified)->key()),
Ryan Mitchell80094e32020-11-16 23:08:18 +00001012 };
Adam Lesinski7ad11102016-10-28 16:39:15 -07001013}
1014
Ryan Mitchell8a891d82019-07-01 09:48:23 -07001015void AssetManager2::ResetResourceResolution() const {
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -07001016 last_resolution_ = Resolution{};
Ryan Mitchell8a891d82019-07-01 09:48:23 -07001017}
1018
Winson2f3669b2019-01-11 11:28:34 -08001019void AssetManager2::SetResourceResolutionLoggingEnabled(bool enabled) {
1020 resource_resolution_logging_enabled_ = enabled;
Winson2f3669b2019-01-11 11:28:34 -08001021 if (!enabled) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -07001022 ResetResourceResolution();
Winson2f3669b2019-01-11 11:28:34 -08001023 }
1024}
1025
1026std::string AssetManager2::GetLastResourceResolution() const {
1027 if (!resource_resolution_logging_enabled_) {
1028 LOG(ERROR) << "Must enable resource resolution logging before getting path.";
Ryan Mitchell80094e32020-11-16 23:08:18 +00001029 return {};
Winson2f3669b2019-01-11 11:28:34 -08001030 }
1031
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001032 const ApkAssetsCookie cookie = last_resolution_.cookie;
Winson2f3669b2019-01-11 11:28:34 -08001033 if (cookie == kInvalidCookie) {
1034 LOG(ERROR) << "AssetManager hasn't resolved a resource to read resolution path.";
Ryan Mitchell80094e32020-11-16 23:08:18 +00001035 return {};
Winson2f3669b2019-01-11 11:28:34 -08001036 }
1037
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -07001038 auto op = StartOperation();
1039
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001040 const uint32_t resid = last_resolution_.resid;
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -07001041 const auto& assets = GetApkAssets(cookie);
Yurii Zubrytskyib3455192023-05-01 14:35:48 -07001042 const auto package =
1043 assets ? assets->GetLoadedArsc()->GetPackageById(get_package_id(resid)) : nullptr;
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001044
Winson2f3669b2019-01-11 11:28:34 -08001045 std::string resource_name_string;
Winson2f3669b2019-01-11 11:28:34 -08001046 if (package != nullptr) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001047 auto resource_name = ToResourceName(last_resolution_.type_string_ref,
1048 last_resolution_.entry_string_ref,
1049 package->GetPackageName());
1050 resource_name_string = resource_name.has_value() ?
1051 ToFormattedResourceString(resource_name.value()) : "<unknown>";
Winson2f3669b2019-01-11 11:28:34 -08001052 }
1053
1054 std::stringstream log_stream;
Jeremy Meyerccf5cd72023-08-15 21:42:03 +00001055 if (configurations_.size() == 1) {
1056 log_stream << base::StringPrintf("Resolution for 0x%08x %s\n"
1057 "\tFor config - %s", resid, resource_name_string.c_str(),
1058 configurations_[0].toString().c_str());
1059 } else {
1060 ResTable_config conf = configurations_[0];
1061 conf.clearLocale();
1062 log_stream << base::StringPrintf("Resolution for 0x%08x %s\n\tFor config - %s and locales",
1063 resid, resource_name_string.c_str(), conf.toString().c_str());
1064 char str[40];
1065 str[0] = '\0';
1066 for(auto iter = configurations_.begin(); iter < configurations_.end(); iter++) {
1067 iter->getBcp47Locale(str);
1068 log_stream << base::StringPrintf(" %s%s", str, iter < configurations_.end() ? "," : "");
1069 }
1070 }
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001071 for (const Resolution::Step& step : last_resolution_.steps) {
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -07001072 constexpr static std::array kStepStrings = {
1073 "Found initial",
1074 "Found better",
1075 "Overlaid",
1076 "Overlaid inline",
1077 "Skipped",
1078 "No entry"
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001079 };
1080
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -07001081 if (step.type < Resolution::Step::Type::INITIAL
1082 || step.type > Resolution::Step::Type::NO_ENTRY) {
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001083 continue;
Winson2f3669b2019-01-11 11:28:34 -08001084 }
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -07001085 const auto prefix = kStepStrings[int(step.type) - int(Resolution::Step::Type::INITIAL)];
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -07001086 const auto& assets = GetApkAssets(step.cookie);
Yurii Zubrytskyib3455192023-05-01 14:35:48 -07001087 log_stream << "\n\t" << prefix << ": " << (assets ? assets->GetDebugName() : "<null>")
1088 << " #" << step.cookie;
Tomasz Wasilczyk8f74b2a2023-08-24 19:02:33 +00001089 if (!step.config_name.empty()) {
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -08001090 log_stream << " - " << step.config_name;
Winson2f3669b2019-01-11 11:28:34 -08001091 }
1092 }
1093
Jackal Guo552b45d2021-09-29 10:52:19 +08001094 log_stream << "\nBest matching is from "
Tomasz Wasilczyk8f74b2a2023-08-24 19:02:33 +00001095 << (last_resolution_.best_config_name.empty() ? "default"
Tomasz Wasilczyk835dfe52023-08-17 16:27:22 +00001096 : last_resolution_.best_config_name.c_str())
Jackal Guo552b45d2021-09-29 10:52:19 +08001097 << " configuration of " << last_resolution_.best_package_name;
Winson2f3669b2019-01-11 11:28:34 -08001098 return log_stream.str();
1099}
1100
Felka Chang00964e92021-12-10 01:19:08 +08001101base::expected<uint32_t, NullOrIOError> AssetManager2::GetParentThemeResourceId(uint32_t resid)
1102const {
1103 auto entry = FindEntry(resid, 0u /* density_override */,
1104 false /* stop_at_first_match */,
1105 false /* ignore_configuration */);
1106 if (!entry.has_value()) {
1107 return base::unexpected(entry.error());
1108 }
1109
1110 auto entry_map = std::get_if<incfs::verified_map_ptr<ResTable_map_entry>>(&entry->entry);
1111 if (entry_map == nullptr) {
1112 // Not a bag, nothing to do.
1113 return base::unexpected(std::nullopt);
1114 }
1115
1116 auto map = *entry_map;
1117 const uint32_t parent_resid = dtohl(map->parent.ident);
1118
1119 return parent_resid;
1120}
1121
Ryan Mitchell80094e32020-11-16 23:08:18 +00001122base::expected<AssetManager2::ResourceName, NullOrIOError> AssetManager2::GetResourceName(
1123 uint32_t resid) const {
1124 auto result = FindEntry(resid, 0u /* density_override */, true /* stop_at_first_match */,
1125 true /* ignore_configuration */);
1126 if (!result.has_value()) {
1127 return base::unexpected(result.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001128 }
1129
Ryan Mitchell80094e32020-11-16 23:08:18 +00001130 return ToResourceName(result->type_string_ref,
1131 result->entry_string_ref,
1132 *result->package_name);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001133}
1134
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001135base::expected<uint32_t, NullOrIOError> AssetManager2::GetResourceTypeSpecFlags(
1136 uint32_t resid) const {
1137 auto result = FindEntry(resid, 0u /* density_override */, false /* stop_at_first_match */,
1138 true /* ignore_configuration */);
1139 if (!result.has_value()) {
1140 return base::unexpected(result.error());
1141 }
1142 return result->type_flags;
1143}
1144
Ryan Mitchell80094e32020-11-16 23:08:18 +00001145base::expected<AssetManager2::SelectedValue, NullOrIOError> AssetManager2::GetResource(
1146 uint32_t resid, bool may_be_bag, uint16_t density_override) const {
1147 auto result = FindEntry(resid, density_override, false /* stop_at_first_match */,
1148 false /* ignore_configuration */);
1149 if (!result.has_value()) {
1150 return base::unexpected(result.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001151 }
1152
Ryan Mitchell80094e32020-11-16 23:08:18 +00001153 auto result_map_entry = std::get_if<incfs::verified_map_ptr<ResTable_map_entry>>(&result->entry);
Ryan Mitchellbf1f45b2020-09-29 17:22:52 -07001154 if (result_map_entry != nullptr) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001155 if (!may_be_bag) {
1156 LOG(ERROR) << base::StringPrintf("Resource %08x is a complex map type.", resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001157 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001158 }
Adam Lesinski0c405242017-01-13 20:47:26 -08001159
1160 // Create a reference since we can't represent this complex type as a Res_value.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001161 return SelectedValue(Res_value::TYPE_REFERENCE, resid, result->cookie, result->type_flags,
1162 resid, result->config);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001163 }
1164
Adam Lesinskida431a22016-12-29 16:08:16 -05001165 // Convert the package ID to the runtime assigned package ID.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001166 Res_value value = std::get<Res_value>(result->entry);
1167 result->dynamic_ref_table->lookupResourceValue(&value);
Adam Lesinskida431a22016-12-29 16:08:16 -05001168
Ryan Mitchell80094e32020-11-16 23:08:18 +00001169 return SelectedValue(value.dataType, value.data, result->cookie, result->type_flags,
1170 resid, result->config);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001171}
1172
Ryan Mitchell80094e32020-11-16 23:08:18 +00001173base::expected<std::monostate, NullOrIOError> AssetManager2::ResolveReference(
Ryan Mitchella45506e2020-11-16 23:08:18 +00001174 AssetManager2::SelectedValue& value, bool cache_value) const {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001175 if (value.type != Res_value::TYPE_REFERENCE || value.data == 0U) {
1176 // Not a reference. Nothing to do.
1177 return {};
Adam Lesinski0c405242017-01-13 20:47:26 -08001178 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001179
Ryan Mitchella45506e2020-11-16 23:08:18 +00001180 const uint32_t original_flags = value.flags;
1181 const uint32_t original_resid = value.data;
1182 if (cache_value) {
1183 auto cached_value = cached_resolved_values_.find(value.data);
1184 if (cached_value != cached_resolved_values_.end()) {
1185 value = cached_value->second;
1186 value.flags |= original_flags;
1187 return {};
1188 }
1189 }
1190
1191 uint32_t combined_flags = 0U;
1192 uint32_t resolve_resid = original_resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001193 constexpr const uint32_t kMaxIterations = 20;
1194 for (uint32_t i = 0U;; i++) {
1195 auto result = GetResource(resolve_resid, true /*may_be_bag*/);
1196 if (!result.has_value()) {
Ryan Mitchelle7ab6272020-11-13 18:06:15 -08001197 value.resid = resolve_resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001198 return base::unexpected(result.error());
1199 }
1200
Ryan Mitchelle7ab6272020-11-13 18:06:15 -08001201 // If resource resolution fails, the value should be set to the last reference that was able to
1202 // be resolved successfully.
1203 value = *result;
1204 value.flags |= combined_flags;
1205
Ryan Mitchell80094e32020-11-16 23:08:18 +00001206 if (result->type != Res_value::TYPE_REFERENCE ||
1207 result->data == Res_value::DATA_NULL_UNDEFINED ||
1208 result->data == resolve_resid || i == kMaxIterations) {
1209 // This reference can't be resolved, so exit now and let the caller deal with it.
Ryan Mitchella45506e2020-11-16 23:08:18 +00001210 if (cache_value) {
1211 cached_resolved_values_[original_resid] = value;
1212 }
1213
1214 // Above value is cached without original_flags to ensure they don't get included in future
1215 // queries that hit the cache
1216 value.flags |= original_flags;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001217 return {};
1218 }
1219
Ryan Mitchelle7ab6272020-11-13 18:06:15 -08001220 combined_flags = result->flags;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001221 resolve_resid = result->data;
1222 }
Adam Lesinski0c405242017-01-13 20:47:26 -08001223}
1224
Yurii Zubrytskyi02a555f2023-05-10 13:22:55 -07001225base::expected<const std::vector<uint32_t>*, NullOrIOError> AssetManager2::GetBagResIdStack(
1226 uint32_t resid) const {
Yurii Zubrytskyi09144882023-06-15 23:23:15 -07001227 auto it = cached_bag_resid_stacks_.find(resid);
1228 if (it != cached_bag_resid_stacks_.end()) {
1229 return &it->second;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001230 }
Yurii Zubrytskyi09144882023-06-15 23:23:15 -07001231 std::vector<uint32_t> stacks;
1232 if (auto maybe_bag = GetBag(resid, stacks); UNLIKELY(IsIOError(maybe_bag))) {
1233 return base::unexpected(maybe_bag.error());
1234 }
1235
1236 it = cached_bag_resid_stacks_.emplace(resid, std::move(stacks)).first;
Yurii Zubrytskyi02a555f2023-05-10 13:22:55 -07001237 return &it->second;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001238}
1239
Ryan Mitchell80094e32020-11-16 23:08:18 +00001240base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::ResolveBag(
1241 AssetManager2::SelectedValue& value) const {
1242 if (UNLIKELY(value.type != Res_value::TYPE_REFERENCE)) {
1243 return base::unexpected(std::nullopt);
1244 }
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001245
Ryan Mitchell80094e32020-11-16 23:08:18 +00001246 auto bag = GetBag(value.data);
1247 if (bag.has_value()) {
1248 value.flags |= (*bag)->type_spec_flags;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001249 }
1250 return bag;
y57cd1952018-04-12 14:26:23 -07001251}
1252
Ryan Mitchell80094e32020-11-16 23:08:18 +00001253base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::GetBag(uint32_t resid) const {
Yurii Zubrytskyi09144882023-06-15 23:23:15 -07001254 auto resid_stacks_it = cached_bag_resid_stacks_.find(resid);
Yurii Zubrytskyi533e8cc2023-06-16 16:38:49 -07001255 if (resid_stacks_it == cached_bag_resid_stacks_.end()) {
Yurii Zubrytskyi09144882023-06-15 23:23:15 -07001256 resid_stacks_it = cached_bag_resid_stacks_.emplace(resid, std::vector<uint32_t>{}).first;
1257 }
Yurii Zubrytskyibd1db5d2023-05-23 18:32:47 -07001258 const auto bag = GetBag(resid, resid_stacks_it->second);
1259 if (UNLIKELY(IsIOError(bag))) {
1260 cached_bag_resid_stacks_.erase(resid_stacks_it);
1261 return base::unexpected(bag.error());
1262 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001263 return bag;
Ryan Mitchell155d5392020-02-10 13:35:24 -08001264}
1265
Ryan Mitchell80094e32020-11-16 23:08:18 +00001266base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::GetBag(
1267 uint32_t resid, std::vector<uint32_t>& child_resids) const {
1268 if (auto cached_iter = cached_bags_.find(resid); cached_iter != cached_bags_.end()) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001269 return cached_iter->second.get();
1270 }
1271
Ryan Mitchell80094e32020-11-16 23:08:18 +00001272 auto entry = FindEntry(resid, 0u /* density_override */, false /* stop_at_first_match */,
1273 false /* ignore_configuration */);
1274 if (!entry.has_value()) {
1275 return base::unexpected(entry.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001276 }
1277
Ryan Mitchell80094e32020-11-16 23:08:18 +00001278 auto entry_map = std::get_if<incfs::verified_map_ptr<ResTable_map_entry>>(&entry->entry);
1279 if (entry_map == nullptr) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001280 // Not a bag, nothing to do.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001281 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001282 }
1283
Ryan Mitchell80094e32020-11-16 23:08:18 +00001284 auto map = *entry_map;
1285 auto map_entry = map.offset(dtohs(map->size)).convert<ResTable_map>();
1286 const auto map_entry_end = map_entry + dtohl(map->count);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001287
y57cd1952018-04-12 14:26:23 -07001288 // Keep track of ids that have already been seen to prevent infinite loops caused by circular
Ryan Mitchell80094e32020-11-16 23:08:18 +00001289 // dependencies between bags.
y57cd1952018-04-12 14:26:23 -07001290 child_resids.push_back(resid);
1291
Adam Lesinskida431a22016-12-29 16:08:16 -05001292 uint32_t parent_resid = dtohl(map->parent.ident);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001293 if (parent_resid == 0U ||
1294 std::find(child_resids.begin(), child_resids.end(), parent_resid) != child_resids.end()) {
1295 // There is no parent or a circular parental dependency exist, meaning there is nothing to
1296 // inherit and we can do a simple copy of the entries in the map.
Adam Lesinski7ad11102016-10-28 16:39:15 -07001297 const size_t entry_count = map_entry_end - map_entry;
1298 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
1299 malloc(sizeof(ResolvedBag) + (entry_count * sizeof(ResolvedBag::Entry))))};
Ryan Mitchell155d5392020-02-10 13:35:24 -08001300
1301 bool sort_entries = false;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001302 for (auto new_entry = new_bag->entries; map_entry != map_entry_end; ++map_entry) {
1303 if (UNLIKELY(!map_entry)) {
1304 return base::unexpected(IOError::PAGES_MISSING);
1305 }
1306
Adam Lesinskida431a22016-12-29 16:08:16 -05001307 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001308 if (!is_internal_resid(new_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -05001309 // Attributes, arrays, etc don't have a resource id as the name. They specify
1310 // other data, which would be wrong to change via a lookup.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001311 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001312 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
1313 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001314 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001315 }
1316 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001317
1318 new_entry->cookie = entry->cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -05001319 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001320 new_entry->key_pool = nullptr;
1321 new_entry->type_pool = nullptr;
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001322 new_entry->style = resid;
Adam Lesinski30080e22017-10-16 16:18:09 -07001323 new_entry->value.copyFrom_dtoh(map_entry->value);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001324 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1325 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001326 LOG(ERROR) << base::StringPrintf(
1327 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
1328 new_entry->value.data, new_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001329 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001330 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001331
Ryan Mitchell155d5392020-02-10 13:35:24 -08001332 sort_entries = sort_entries ||
1333 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001334 ++new_entry;
1335 }
Ryan Mitchell155d5392020-02-10 13:35:24 -08001336
1337 if (sort_entries) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001338 std::sort(new_bag->entries, new_bag->entries + entry_count,
1339 [](auto&& lhs, auto&& rhs) { return lhs.key < rhs.key; });
Ryan Mitchell155d5392020-02-10 13:35:24 -08001340 }
1341
Ryan Mitchell80094e32020-11-16 23:08:18 +00001342 new_bag->type_spec_flags = entry->type_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001343 new_bag->entry_count = static_cast<uint32_t>(entry_count);
1344 ResolvedBag* result = new_bag.get();
1345 cached_bags_[resid] = std::move(new_bag);
1346 return result;
1347 }
1348
Adam Lesinskida431a22016-12-29 16:08:16 -05001349 // In case the parent is a dynamic reference, resolve it.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001350 entry->dynamic_ref_table->lookupResourceId(&parent_resid);
Adam Lesinskida431a22016-12-29 16:08:16 -05001351
Adam Lesinski7ad11102016-10-28 16:39:15 -07001352 // Get the parent and do a merge of the keys.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001353 const auto parent_bag = GetBag(parent_resid, child_resids);
1354 if (UNLIKELY(!parent_bag.has_value())) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001355 // Failed to get the parent that should exist.
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001356 LOG(ERROR) << base::StringPrintf("Failed to find parent 0x%08x of bag 0x%08x.", parent_resid,
1357 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001358 return base::unexpected(parent_bag.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001359 }
1360
Adam Lesinski7ad11102016-10-28 16:39:15 -07001361 // Create the max possible entries we can make. Once we construct the bag,
1362 // we will realloc to fit to size.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001363 const size_t max_count = (*parent_bag)->entry_count + dtohl(map->count);
George Burgess IV09b119f2017-07-25 15:00:04 -07001364 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
1365 malloc(sizeof(ResolvedBag) + (max_count * sizeof(ResolvedBag::Entry))))};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001366 ResolvedBag::Entry* new_entry = new_bag->entries;
1367
Ryan Mitchell80094e32020-11-16 23:08:18 +00001368 const ResolvedBag::Entry* parent_entry = (*parent_bag)->entries;
1369 const ResolvedBag::Entry* const parent_entry_end = parent_entry + (*parent_bag)->entry_count;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001370
1371 // The keys are expected to be in sorted order. Merge the two bags.
Ryan Mitchell155d5392020-02-10 13:35:24 -08001372 bool sort_entries = false;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001373 while (map_entry != map_entry_end && parent_entry != parent_entry_end) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001374 if (UNLIKELY(!map_entry)) {
1375 return base::unexpected(IOError::PAGES_MISSING);
1376 }
1377
Adam Lesinskida431a22016-12-29 16:08:16 -05001378 uint32_t child_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001379 if (!is_internal_resid(child_key)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001380 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&child_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001381 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", child_key,
1382 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001383 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001384 }
1385 }
1386
Adam Lesinski7ad11102016-10-28 16:39:15 -07001387 if (child_key <= parent_entry->key) {
1388 // Use the child key if it comes before the parent
1389 // or is equal to the parent (overrides).
Ryan Mitchell80094e32020-11-16 23:08:18 +00001390 new_entry->cookie = entry->cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001391 new_entry->key = child_key;
1392 new_entry->key_pool = nullptr;
1393 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -07001394 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001395 new_entry->style = resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001396 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1397 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001398 LOG(ERROR) << base::StringPrintf(
1399 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
1400 new_entry->value.data, child_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001401 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001402 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001403 ++map_entry;
1404 } else {
1405 // Take the parent entry as-is.
1406 memcpy(new_entry, parent_entry, sizeof(*new_entry));
1407 }
1408
Ryan Mitchell155d5392020-02-10 13:35:24 -08001409 sort_entries = sort_entries ||
1410 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001411 if (child_key >= parent_entry->key) {
1412 // Move to the next parent entry if we used it or it was overridden.
1413 ++parent_entry;
1414 }
1415 // Increment to the next entry to fill.
1416 ++new_entry;
1417 }
1418
1419 // Finish the child entries if they exist.
1420 while (map_entry != map_entry_end) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001421 if (UNLIKELY(!map_entry)) {
1422 return base::unexpected(IOError::PAGES_MISSING);
1423 }
1424
Adam Lesinskida431a22016-12-29 16:08:16 -05001425 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001426 if (!is_internal_resid(new_key)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001427 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001428 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
1429 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001430 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001431 }
1432 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001433 new_entry->cookie = entry->cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -05001434 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001435 new_entry->key_pool = nullptr;
1436 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -07001437 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001438 new_entry->style = resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001439 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1440 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001441 LOG(ERROR) << base::StringPrintf("Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.",
1442 new_entry->value.dataType, new_entry->value.data, new_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001443 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001444 }
Ryan Mitchell155d5392020-02-10 13:35:24 -08001445 sort_entries = sort_entries ||
1446 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001447 ++map_entry;
1448 ++new_entry;
1449 }
1450
1451 // Finish the parent entries if they exist.
1452 if (parent_entry != parent_entry_end) {
1453 // Take the rest of the parent entries as-is.
1454 const size_t num_entries_to_copy = parent_entry_end - parent_entry;
1455 memcpy(new_entry, parent_entry, num_entries_to_copy * sizeof(*new_entry));
1456 new_entry += num_entries_to_copy;
1457 }
1458
1459 // Resize the resulting array to fit.
1460 const size_t actual_count = new_entry - new_bag->entries;
1461 if (actual_count != max_count) {
George Burgess IV09b119f2017-07-25 15:00:04 -07001462 new_bag.reset(reinterpret_cast<ResolvedBag*>(realloc(
1463 new_bag.release(), sizeof(ResolvedBag) + (actual_count * sizeof(ResolvedBag::Entry)))));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001464 }
1465
Ryan Mitchell155d5392020-02-10 13:35:24 -08001466 if (sort_entries) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001467 std::sort(new_bag->entries, new_bag->entries + actual_count,
1468 [](auto&& lhs, auto&& rhs) { return lhs.key < rhs.key; });
Ryan Mitchell155d5392020-02-10 13:35:24 -08001469 }
1470
Adam Lesinski1a1e9c22017-10-13 15:45:34 -07001471 // Combine flags from the parent and our own bag.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001472 new_bag->type_spec_flags = entry->type_flags | (*parent_bag)->type_spec_flags;
George Burgess IV09b119f2017-07-25 15:00:04 -07001473 new_bag->entry_count = static_cast<uint32_t>(actual_count);
1474 ResolvedBag* result = new_bag.get();
1475 cached_bags_[resid] = std::move(new_bag);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001476 return result;
1477}
1478
Yurii Zubrytskyia5775142022-11-02 17:49:49 -07001479static bool Utf8ToUtf16(StringPiece str, std::u16string* out) {
Adam Lesinski929d6512017-01-16 19:11:19 -08001480 ssize_t len =
1481 utf8_to_utf16_length(reinterpret_cast<const uint8_t*>(str.data()), str.size(), false);
1482 if (len < 0) {
1483 return false;
1484 }
1485 out->resize(static_cast<size_t>(len));
1486 utf8_to_utf16(reinterpret_cast<const uint8_t*>(str.data()), str.size(), &*out->begin(),
1487 static_cast<size_t>(len + 1));
1488 return true;
1489}
1490
Ryan Mitchell80094e32020-11-16 23:08:18 +00001491base::expected<uint32_t, NullOrIOError> AssetManager2::GetResourceId(
1492 const std::string& resource_name, const std::string& fallback_type,
1493 const std::string& fallback_package) const {
Adam Lesinski929d6512017-01-16 19:11:19 -08001494 StringPiece package_name, type, entry;
1495 if (!ExtractResourceName(resource_name, &package_name, &type, &entry)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001496 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001497 }
1498
1499 if (entry.empty()) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001500 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001501 }
1502
1503 if (package_name.empty()) {
1504 package_name = fallback_package;
1505 }
1506
1507 if (type.empty()) {
1508 type = fallback_type;
1509 }
1510
1511 std::u16string type16;
1512 if (!Utf8ToUtf16(type, &type16)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001513 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001514 }
1515
1516 std::u16string entry16;
1517 if (!Utf8ToUtf16(entry, &entry16)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001518 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001519 }
1520
1521 const StringPiece16 kAttr16 = u"attr";
1522 const static std::u16string kAttrPrivate16 = u"^attr-private";
1523
1524 for (const PackageGroup& package_group : package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001525 for (const ConfiguredPackage& package_impl : package_group.packages_) {
1526 const LoadedPackage* package = package_impl.loaded_package_;
Adam Lesinski929d6512017-01-16 19:11:19 -08001527 if (package_name != package->GetPackageName()) {
1528 // All packages in the same group are expected to have the same package name.
1529 break;
1530 }
1531
Ryan Mitchell80094e32020-11-16 23:08:18 +00001532 base::expected<uint32_t, NullOrIOError> resid = package->FindEntryByName(type16, entry16);
1533 if (UNLIKELY(IsIOError(resid))) {
1534 return base::unexpected(resid.error());
1535 }
1536
1537 if (!resid.has_value() && kAttr16 == type16) {
Adam Lesinski929d6512017-01-16 19:11:19 -08001538 // Private attributes in libraries (such as the framework) are sometimes encoded
1539 // under the type '^attr-private' in order to leave the ID space of public 'attr'
1540 // free for future additions. Check '^attr-private' for the same name.
1541 resid = package->FindEntryByName(kAttrPrivate16, entry16);
1542 }
1543
Ryan Mitchell80094e32020-11-16 23:08:18 +00001544 if (resid.has_value()) {
1545 return fix_package_id(*resid, package_group.dynamic_ref_table->mAssignedPackageId);
Adam Lesinski929d6512017-01-16 19:11:19 -08001546 }
1547 }
1548 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001549 return base::unexpected(std::nullopt);
Adam Lesinski0c405242017-01-13 20:47:26 -08001550}
1551
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001552void AssetManager2::RebuildFilterList() {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001553 for (PackageGroup& group : package_groups_) {
Yurii Zubrytskyidbce3562022-11-14 22:26:10 -08001554 for (ConfiguredPackage& package : group.packages_) {
1555 package.filtered_configs_.forEachItem([](auto, auto& fcg) { fcg.type_entries.clear(); });
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001556 // Create the filters here.
Yurii Zubrytskyidbce3562022-11-14 22:26:10 -08001557 package.loaded_package_->ForEachTypeSpec([&](const TypeSpec& type_spec, uint8_t type_id) {
Yurii Zubrytskyi59dab3b2022-11-03 00:08:49 -07001558 FilteredConfigGroup* group = nullptr;
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001559 for (const auto& type_entry : type_spec.type_entries) {
Jeremy Meyerccf5cd72023-08-15 21:42:03 +00001560 for (auto & config : configurations_) {
1561 if (type_entry.config.match(config)) {
1562 if (!group) {
1563 group = &package.filtered_configs_.editItemAt(type_id - 1);
1564 }
1565 group->type_entries.push_back(&type_entry);
1566 break;
Yurii Zubrytskyi59dab3b2022-11-03 00:08:49 -07001567 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001568 }
1569 }
1570 });
Yurii Zubrytskyidbce3562022-11-14 22:26:10 -08001571 package.filtered_configs_.trimBuckets(
1572 [](const auto& fcg) { return fcg.type_entries.empty(); });
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001573 }
1574 }
1575}
1576
Adam Lesinski7ad11102016-10-28 16:39:15 -07001577void AssetManager2::InvalidateCaches(uint32_t diff) {
Yurii Zubrytskyi09144882023-06-15 23:23:15 -07001578 cached_resolved_values_.clear();
Ryan Mitchell2c4d8742019-03-04 09:41:00 -08001579
Adam Lesinski7ad11102016-10-28 16:39:15 -07001580 if (diff == 0xffffffffu) {
1581 // Everything must go.
1582 cached_bags_.clear();
Yurii Zubrytskyi09144882023-06-15 23:23:15 -07001583 cached_bag_resid_stacks_.clear();
Adam Lesinski7ad11102016-10-28 16:39:15 -07001584 return;
1585 }
1586
1587 // Be more conservative with what gets purged. Only if the bag has other possible
1588 // variations with respect to what changed (diff) should we remove it.
Yurii Zubrytskyi09144882023-06-15 23:23:15 -07001589 for (auto stack_it = cached_bag_resid_stacks_.begin();
1590 stack_it != cached_bag_resid_stacks_.end();) {
1591 const auto it = cached_bags_.find(stack_it->first);
1592 if (it == cached_bags_.end()) {
1593 stack_it = cached_bag_resid_stacks_.erase(stack_it);
1594 } else if ((diff & it->second->type_spec_flags) != 0) {
1595 cached_bags_.erase(it);
1596 stack_it = cached_bag_resid_stacks_.erase(stack_it);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001597 } else {
Yurii Zubrytskyi09144882023-06-15 23:23:15 -07001598 ++stack_it; // Keep the item in both caches.
Adam Lesinski7ad11102016-10-28 16:39:15 -07001599 }
1600 }
Ryan Mitchella45506e2020-11-16 23:08:18 +00001601
Yurii Zubrytskyi09144882023-06-15 23:23:15 -07001602 // Need to ensure that both bag caches are consistent, as we populate them in the same function.
1603 // Iterate over the cached bags to erase the items without the corresponding resid_stack cache
1604 // items.
1605 for (auto it = cached_bags_.begin(); it != cached_bags_.end();) {
1606 if ((diff & it->second->type_spec_flags) != 0) {
1607 it = cached_bags_.erase(it);
1608 } else {
1609 ++it;
1610 }
1611 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001612}
1613
Ryan Mitchell2e394222019-08-28 12:10:51 -07001614uint8_t AssetManager2::GetAssignedPackageId(const LoadedPackage* package) const {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001615 for (auto& package_group : package_groups_) {
1616 for (auto& package2 : package_group.packages_) {
1617 if (package2.loaded_package_ == package) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -07001618 return package_group.dynamic_ref_table->mAssignedPackageId;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001619 }
1620 }
1621 }
1622 return 0;
1623}
1624
Adam Lesinski30080e22017-10-16 16:18:09 -07001625std::unique_ptr<Theme> AssetManager2::NewTheme() {
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001626 constexpr size_t kInitialReserveSize = 32;
1627 auto theme = std::unique_ptr<Theme>(new Theme(this));
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001628 theme->keys_.reserve(kInitialReserveSize);
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001629 theme->entries_.reserve(kInitialReserveSize);
1630 return theme;
Adam Lesinski30080e22017-10-16 16:18:09 -07001631}
1632
Yurii Zubrytskyi9eb44c92022-11-14 23:44:52 -08001633void AssetManager2::ForEachPackage(base::function_ref<bool(const std::string&, uint8_t)> func,
1634 package_property_t excluded_property_flags) const {
1635 for (const PackageGroup& package_group : package_groups_) {
1636 const auto loaded_package = package_group.packages_.front().loaded_package_;
1637 if ((loaded_package->GetPropertyFlags() & excluded_property_flags) == 0U
1638 && !func(loaded_package->GetPackageName(),
1639 package_group.dynamic_ref_table->mAssignedPackageId)) {
1640 return;
1641 }
1642 }
1643}
1644
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -07001645AssetManager2::ScopedOperation AssetManager2::StartOperation() const {
1646 ++number_of_running_scoped_operations_;
1647 return ScopedOperation(*this);
1648}
1649
1650void AssetManager2::FinishOperation() const {
1651 if (number_of_running_scoped_operations_ < 1) {
1652 ALOGW("Invalid FinishOperation() call when there's none happening");
1653 return;
1654 }
1655 if (--number_of_running_scoped_operations_ == 0) {
1656 for (auto&& [_, assets] : apk_assets_) {
1657 assets.clear();
1658 }
1659 }
1660}
1661
1662const AssetManager2::ApkAssetsPtr& AssetManager2::GetApkAssets(ApkAssetsCookie cookie) const {
1663 DCHECK(number_of_running_scoped_operations_ > 0) << "Must have an operation running";
1664
1665 if (cookie < 0 || cookie >= apk_assets_.size()) {
1666 static const ApkAssetsPtr empty{};
1667 return empty;
1668 }
1669 auto& [wptr, res] = apk_assets_[cookie];
1670 if (!res) {
1671 res = wptr.promote();
1672 }
1673 return res;
1674}
1675
Adam Lesinski30080e22017-10-16 16:18:09 -07001676Theme::Theme(AssetManager2* asset_manager) : asset_manager_(asset_manager) {
1677}
1678
1679Theme::~Theme() = default;
1680
Yurii Zubrytskyi1e5452a2024-06-13 19:30:36 -07001681static bool IsUndefined(const Res_value& value) {
1682 // DATA_NULL_EMPTY (@empty) is a valid resource value and DATA_NULL_UNDEFINED represents
1683 // an absence of a valid value.
1684 return value.dataType == Res_value::TYPE_NULL && value.data != Res_value::DATA_NULL_EMPTY;
1685}
1686
Ryan Mitchell80094e32020-11-16 23:08:18 +00001687base::expected<std::monostate, NullOrIOError> Theme::ApplyStyle(uint32_t resid, bool force) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001688 ATRACE_NAME("Theme::ApplyStyle");
Adam Lesinski7ad11102016-10-28 16:39:15 -07001689
Ryan Mitchell80094e32020-11-16 23:08:18 +00001690 auto bag = asset_manager_->GetBag(resid);
1691 if (!bag.has_value()) {
1692 return base::unexpected(bag.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001693 }
1694
1695 // Merge the flags from this style.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001696 type_spec_flags_ |= (*bag)->type_spec_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001697
Yurii Zubrytskyi1e5452a2024-06-13 19:30:36 -07001698 //
1699 // This function is the most expensive part of applying an frro to the existing app resources,
1700 // and needs to be as efficient as possible.
1701 // The data structure we're working with is two parallel sorted arrays of keys (resource IDs)
1702 // and entries (resource value + some attributes).
1703 // The styles get applied in sequence, starting with an empty set of attributes. Each style
1704 // contains its values for the theme attributes, and gets applied in either normal or forced way:
1705 // - normal way never overrides the existing attribute, so only unique style attributes are added
1706 // - forced way overrides anything for that attribute, and if it's undefined it removes the
1707 // previous value completely
1708 //
1709 // Style attributes come in a Bag data type - a sorted array of attributes with their values. This
1710 // means we don't need to re-sort the attributes ever, and instead:
1711 // - for an already existing attribute just skip it or apply the forced value
1712 // - if the forced value is undefined, mark it undefined as well to get rid of it later
1713 // - for a new attribute append it to the array, forming a new sorted section of new attributes
1714 // past the end of the original ones (ignore undefined ones here)
1715 // - inplace merge two sorted sections to form a single sorted array again.
1716 // - run the last pass to remove all undefined elements
1717 //
1718 // Using this algorithm performs better than a repeated binary search + insert in the middle,
1719 // as that keeps shifting the tail end of the arrays and wasting CPU cycles in memcpy().
1720 //
1721 const auto starting_size = keys_.size();
1722 if (starting_size == 0) {
1723 keys_.reserve((*bag)->entry_count);
1724 entries_.reserve((*bag)->entry_count);
1725 }
1726 bool wrote_undefined = false;
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001727 for (auto it = begin(*bag); it != end(*bag); ++it) {
1728 const uint32_t attr_res_id = it->key;
Adam Lesinski30080e22017-10-16 16:18:09 -07001729 // If the resource ID passed in is not a style, the key can be some other identifier that is not
1730 // a resource ID. We should fail fast instead of operating with strange resource IDs.
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001731 if (!is_valid_resid(attr_res_id)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001732 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001733 }
Yurii Zubrytskyi1e5452a2024-06-13 19:30:36 -07001734 const bool is_undefined = IsUndefined(it->value);
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001735 if (!force && is_undefined) {
1736 continue;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001737 }
Yurii Zubrytskyi1e5452a2024-06-13 19:30:36 -07001738 const auto key_it = std::lower_bound(keys_.begin(), keys_.begin() + starting_size, attr_res_id);
1739 if (key_it != keys_.begin() + starting_size && *key_it == attr_res_id) {
1740 const auto entry_it = entries_.begin() + (key_it - keys_.begin());
1741 if (force || IsUndefined(entry_it->value)) {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001742 *entry_it = Entry{it->cookie, (*bag)->type_spec_flags, it->value};
Yurii Zubrytskyi1e5452a2024-06-13 19:30:36 -07001743 wrote_undefined |= is_undefined;
Adam Lesinski30080e22017-10-16 16:18:09 -07001744 }
Yurii Zubrytskyi1e5452a2024-06-13 19:30:36 -07001745 } else if (!is_undefined) {
1746 keys_.emplace_back(attr_res_id);
1747 entries_.emplace_back(it->cookie, (*bag)->type_spec_flags, it->value);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001748 }
1749 }
Yurii Zubrytskyi1e5452a2024-06-13 19:30:36 -07001750
1751 if (starting_size && keys_.size() != starting_size) {
1752 std::inplace_merge(
1753 CombinedIterator(keys_.begin(), entries_.begin()),
1754 CombinedIterator(keys_.begin() + starting_size, entries_.begin() + starting_size),
1755 CombinedIterator(keys_.end(), entries_.end()));
1756 }
1757 if (wrote_undefined) {
1758 auto new_end = std::remove_if(CombinedIterator(keys_.begin(), entries_.begin()),
1759 CombinedIterator(keys_.end(), entries_.end()),
1760 [](const auto& pair) { return IsUndefined(pair.second.value); });
1761 keys_.erase(new_end.it1, keys_.end());
1762 entries_.erase(new_end.it2, entries_.end());
1763 }
1764 if (android::base::kEnableDChecks && !std::is_sorted(keys_.begin(), keys_.end())) {
1765 ALOGW("Bag %u was unsorted in the apk?", unsigned(resid));
1766 return base::unexpected(std::nullopt);
1767 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001768 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001769}
1770
Ryan Mitchell767e34f2021-06-07 12:29:05 -07001771void Theme::Rebase(AssetManager2* am, const uint32_t* style_ids, const uint8_t* force,
1772 size_t style_count) {
1773 ATRACE_NAME("Theme::Rebase");
1774 // Reset the entries without changing the vector capacity to prevent reallocations during
1775 // ApplyStyle.
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001776 keys_.clear();
Ryan Mitchell767e34f2021-06-07 12:29:05 -07001777 entries_.clear();
1778 asset_manager_ = am;
1779 for (size_t i = 0; i < style_count; i++) {
1780 ApplyStyle(style_ids[i], force[i]);
1781 }
1782}
1783
Ryan Mitchell80094e32020-11-16 23:08:18 +00001784std::optional<AssetManager2::SelectedValue> Theme::GetAttribute(uint32_t resid) const {
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001785 constexpr const uint32_t kMaxIterations = 20;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001786 uint32_t type_spec_flags = 0u;
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001787 for (uint32_t i = 0; i <= kMaxIterations; i++) {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001788 const auto key_it = std::lower_bound(keys_.begin(), keys_.end(), resid);
1789 if (key_it == keys_.end() || *key_it != resid) {
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001790 return std::nullopt;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001791 }
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001792 const auto entry_it = entries_.begin() + (key_it - keys_.begin());
Yurii Zubrytskyi1e5452a2024-06-13 19:30:36 -07001793 if (IsUndefined(entry_it->value)) {
1794 return std::nullopt;
1795 }
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001796 type_spec_flags |= entry_it->type_spec_flags;
1797 if (entry_it->value.dataType == Res_value::TYPE_ATTRIBUTE) {
1798 resid = entry_it->value.data;
1799 continue;
1800 }
1801
1802 return AssetManager2::SelectedValue(entry_it->value.dataType, entry_it->value.data,
1803 entry_it->cookie, type_spec_flags, 0U /* resid */,
1804 {} /* config */);
1805 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001806 return std::nullopt;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001807}
1808
Ryan Mitchell80094e32020-11-16 23:08:18 +00001809base::expected<std::monostate, NullOrIOError> Theme::ResolveAttributeReference(
1810 AssetManager2::SelectedValue& value) const {
1811 if (value.type != Res_value::TYPE_ATTRIBUTE) {
1812 return asset_manager_->ResolveReference(value);
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001813 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001814
1815 std::optional<AssetManager2::SelectedValue> result = GetAttribute(value.data);
1816 if (!result.has_value()) {
1817 return base::unexpected(std::nullopt);
1818 }
1819
Ryan Mitchella45506e2020-11-16 23:08:18 +00001820 auto resolve_result = asset_manager_->ResolveReference(*result, true /* cache_value */);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001821 if (resolve_result.has_value()) {
1822 result->flags |= value.flags;
1823 value = *result;
1824 }
1825 return resolve_result;
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001826}
1827
Adam Lesinski7ad11102016-10-28 16:39:15 -07001828void Theme::Clear() {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001829 keys_.clear();
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001830 entries_.clear();
Adam Lesinski7ad11102016-10-28 16:39:15 -07001831}
1832
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001833base::expected<std::monostate, IOError> Theme::SetTo(const Theme& source) {
1834 if (this == &source) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001835 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001836 }
1837
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001838 type_spec_flags_ = source.type_spec_flags_;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001839
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001840 if (asset_manager_ == source.asset_manager_) {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001841 keys_ = source.keys_;
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001842 entries_ = source.entries_;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001843 } else {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001844 std::unordered_map<ApkAssetsCookie, ApkAssetsCookie> src_to_dest_asset_cookies;
1845 using SourceToDestinationRuntimePackageMap = std::unordered_map<int, int>;
1846 std::unordered_map<ApkAssetsCookie, SourceToDestinationRuntimePackageMap> src_asset_cookie_id_map;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001847
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -07001848 auto op_src = source.asset_manager_->StartOperation();
1849 auto op_dst = asset_manager_->StartOperation();
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001850
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -07001851 for (size_t i = 0; i < source.asset_manager_->GetApkAssetsCount(); i++) {
1852 const auto& src_asset = source.asset_manager_->GetApkAssets(i);
1853 if (!src_asset) {
Yurii Zubrytskyib3455192023-05-01 14:35:48 -07001854 continue;
1855 }
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -07001856 for (int j = 0; j < asset_manager_->GetApkAssetsCount(); j++) {
1857 const auto& dest_asset = asset_manager_->GetApkAssets(j);
Ryan Mitchellef538432021-03-01 14:52:14 -08001858 if (src_asset != dest_asset) {
1859 // ResourcesManager caches and reuses ApkAssets when the same apk must be present in
1860 // multiple AssetManagers. Two ApkAssets point to the same version of the same resources
1861 // if they are the same instance.
1862 continue;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001863 }
Ryan Mitchellef538432021-03-01 14:52:14 -08001864
1865 // Map the package ids of the asset in the source AssetManager to the package ids of the
1866 // asset in th destination AssetManager.
1867 SourceToDestinationRuntimePackageMap package_map;
1868 for (const auto& loaded_package : src_asset->GetLoadedArsc()->GetPackages()) {
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001869 const int src_package_id = source.asset_manager_->GetAssignedPackageId(
1870 loaded_package.get());
Ryan Mitchellef538432021-03-01 14:52:14 -08001871 const int dest_package_id = asset_manager_->GetAssignedPackageId(loaded_package.get());
1872 package_map[src_package_id] = dest_package_id;
1873 }
1874
1875 src_to_dest_asset_cookies.insert(std::make_pair(i, j));
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001876 src_asset_cookie_id_map.insert(std::make_pair(i, std::move(package_map)));
Ryan Mitchellef538432021-03-01 14:52:14 -08001877 break;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001878 }
1879 }
1880
Ryan Mitchell93bca972019-03-08 17:26:28 -08001881 // Reset the data in the destination theme.
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001882 keys_.clear();
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001883 entries_.clear();
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001884
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001885 for (size_t i = 0, size = source.entries_.size(); i != size; ++i) {
1886 const auto& entry = source.entries_[i];
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001887 bool is_reference = (entry.value.dataType == Res_value::TYPE_ATTRIBUTE
1888 || entry.value.dataType == Res_value::TYPE_REFERENCE
1889 || entry.value.dataType == Res_value::TYPE_DYNAMIC_ATTRIBUTE
1890 || entry.value.dataType == Res_value::TYPE_DYNAMIC_REFERENCE)
1891 && entry.value.data != 0x0;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001892
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001893 // If the attribute value represents an attribute or reference, the package id of the
1894 // value needs to be rewritten to the package id of the value in the destination.
1895 uint32_t attribute_data = entry.value.data;
1896 if (is_reference) {
1897 // Determine the package id of the reference in the destination AssetManager.
1898 auto value_package_map = src_asset_cookie_id_map.find(entry.cookie);
1899 if (value_package_map == src_asset_cookie_id_map.end()) {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001900 continue;
1901 }
1902
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001903 auto value_dest_package = value_package_map->second.find(
1904 get_package_id(entry.value.data));
1905 if (value_dest_package == value_package_map->second.end()) {
1906 continue;
1907 }
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001908
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001909 attribute_data = fix_package_id(entry.value.data, value_dest_package->second);
1910 }
Ryan Mitchellb85d9b22018-11-19 12:11:38 -08001911
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001912 // Find the cookie of the value in the destination. If the source apk is not loaded in the
1913 // destination, only copy resources that do not reference resources in the source.
1914 ApkAssetsCookie data_dest_cookie;
1915 auto value_dest_cookie = src_to_dest_asset_cookies.find(entry.cookie);
1916 if (value_dest_cookie != src_to_dest_asset_cookies.end()) {
1917 data_dest_cookie = value_dest_cookie->second;
1918 } else {
1919 if (is_reference || entry.value.dataType == Res_value::TYPE_STRING) {
1920 continue;
1921 } else {
1922 data_dest_cookie = 0x0;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001923 }
1924 }
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001925
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001926 const auto source_res_id = source.keys_[i];
1927
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001928 // The package id of the attribute needs to be rewritten to the package id of the
1929 // attribute in the destination.
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001930 int attribute_dest_package_id = get_package_id(source_res_id);
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001931 if (attribute_dest_package_id != 0x01) {
1932 // Find the cookie of the attribute resource id in the source AssetManager
1933 base::expected<FindEntryResult, NullOrIOError> attribute_entry_result =
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001934 source.asset_manager_->FindEntry(source_res_id, 0 /* density_override */ ,
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001935 true /* stop_at_first_match */,
1936 true /* ignore_configuration */);
1937 if (UNLIKELY(IsIOError(attribute_entry_result))) {
1938 return base::unexpected(GetIOError(attribute_entry_result.error()));
1939 }
1940 if (!attribute_entry_result.has_value()) {
1941 continue;
1942 }
1943
1944 // Determine the package id of the attribute in the destination AssetManager.
1945 auto attribute_package_map = src_asset_cookie_id_map.find(
1946 attribute_entry_result->cookie);
1947 if (attribute_package_map == src_asset_cookie_id_map.end()) {
1948 continue;
1949 }
1950 auto attribute_dest_package = attribute_package_map->second.find(
1951 attribute_dest_package_id);
1952 if (attribute_dest_package == attribute_package_map->second.end()) {
1953 continue;
1954 }
1955 attribute_dest_package_id = attribute_dest_package->second;
1956 }
1957
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001958 auto dest_attr_id = make_resid(attribute_dest_package_id, get_type_id(source_res_id),
1959 get_entry_id(source_res_id));
1960 const auto key_it = std::lower_bound(keys_.begin(), keys_.end(), dest_attr_id);
1961 const auto entry_it = entries_.begin() + (key_it - keys_.begin());
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001962 // Since the entries were cleared, the attribute resource id has yet been mapped to any value.
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001963 keys_.insert(key_it, dest_attr_id);
1964 entries_.insert(entry_it, Entry{data_dest_cookie, entry.type_spec_flags,
1965 Res_value{.dataType = entry.value.dataType,
1966 .data = attribute_data}});
Adam Lesinski7ad11102016-10-28 16:39:15 -07001967 }
1968 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001969 return {};
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001970}
1971
1972void Theme::Dump() const {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001973 LOG(INFO) << base::StringPrintf("Theme(this=%p, AssetManager2=%p)", this, asset_manager_);
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001974 for (size_t i = 0, size = keys_.size(); i != size; ++i) {
1975 auto res_id = keys_[i];
1976 const auto& entry = entries_[i];
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001977 LOG(INFO) << base::StringPrintf(" entry(0x%08x)=(0x%08x) type=(0x%02x), cookie(%d)",
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001978 res_id, entry.value.data, entry.value.dataType,
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001979 entry.cookie);
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001980 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001981}
1982
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -07001983AssetManager2::ScopedOperation::ScopedOperation(const AssetManager2& am) : am_(am) {
1984}
1985
1986AssetManager2::ScopedOperation::~ScopedOperation() {
1987 am_.FinishOperation();
1988}
1989
Adam Lesinski7ad11102016-10-28 16:39:15 -07001990} // namespace android