blob: 822a387351e375372e99b7dec1abfb05467b13ad [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>
Yurii Zubrytskyi1e5452a2024-06-13 19:30:36 -070026#include <utility>
Adam Lesinski0c405242017-01-13 20:47:26 -080027
Adam Lesinski7ad11102016-10-28 16:39:15 -070028#include "android-base/logging.h"
29#include "android-base/stringprintf.h"
Yurii Zubrytskyi1e5452a2024-06-13 19:30:36 -070030#include "androidfw/CombinedIterator.h"
Jackal Guo552b45d2021-09-29 10:52:19 +080031#include "androidfw/ResourceTypes.h"
Ryan Mitchell8a891d82019-07-01 09:48:23 -070032#include "androidfw/ResourceUtils.h"
Ryan Mitchell31b11052019-06-13 13:47:26 -070033#include "androidfw/Util.h"
Adam Lesinski7ad11102016-10-28 16:39:15 -070034#include "utils/ByteOrder.h"
35#include "utils/Trace.h"
36
37#ifdef _WIN32
38#ifdef ERROR
39#undef ERROR
40#endif
41#endif
42
43namespace android {
44
Ryan Mitchell80094e32020-11-16 23:08:18 +000045namespace {
46
47using EntryValue = std::variant<Res_value, incfs::verified_map_ptr<ResTable_map_entry>>;
48
Eric Miao368cd192022-09-09 15:46:14 -070049/* NOTE: table_entry has been verified in LoadedPackage::GetEntryFromOffset(),
50 * and so access to ->value() and ->map_entry() are safe here
51 */
Ryan Mitchell80094e32020-11-16 23:08:18 +000052base::expected<EntryValue, IOError> GetEntryValue(
53 incfs::verified_map_ptr<ResTable_entry> table_entry) {
Eric Miao368cd192022-09-09 15:46:14 -070054 const uint16_t entry_size = table_entry->size();
Ryan Mitchell80094e32020-11-16 23:08:18 +000055
56 // Check if the entry represents a bag value.
Eric Miao368cd192022-09-09 15:46:14 -070057 if (entry_size >= sizeof(ResTable_map_entry) && table_entry->is_complex()) {
58 return table_entry.convert<ResTable_map_entry>().verified();
Ryan Mitchell80094e32020-11-16 23:08:18 +000059 }
60
Eric Miao368cd192022-09-09 15:46:14 -070061 return table_entry->value();
Ryan Mitchell80094e32020-11-16 23:08:18 +000062}
63
64} // namespace
65
Adam Lesinskibebfcc42018-02-12 14:27:46 -080066struct FindEntryResult {
Ryan Mitchell80094e32020-11-16 23:08:18 +000067 // The cookie representing the ApkAssets in which the value resides.
68 ApkAssetsCookie cookie;
69
70 // The value of the resource table entry. Either an android::Res_value for non-bag types or an
71 // incfs::verified_map_ptr<ResTable_map_entry> for bag types.
72 EntryValue entry;
Adam Lesinskibebfcc42018-02-12 14:27:46 -080073
74 // The configuration for which the resulting entry was defined. This is already swapped to host
75 // endianness.
76 ResTable_config config;
77
78 // The bitmask of configuration axis with which the resource value varies.
79 uint32_t type_flags;
80
81 // The dynamic package ID map for the package from which this resource came from.
82 const DynamicRefTable* dynamic_ref_table;
83
Ryan Mitchell8a891d82019-07-01 09:48:23 -070084 // The package name of the resource.
85 const std::string* package_name;
86
Adam Lesinskibebfcc42018-02-12 14:27:46 -080087 // The string pool reference to the type's name. This uses a different string pool than
88 // the global string pool, but this is hidden from the caller.
89 StringPoolRef type_string_ref;
90
91 // The string pool reference to the entry's name. This uses a different string pool than
92 // the global string pool, but this is hidden from the caller.
93 StringPoolRef entry_string_ref;
94};
95
Ryan Prichard41e15a02023-08-30 22:19:30 -070096struct Theme::Entry {
97 ApkAssetsCookie cookie;
98 uint32_t type_spec_flags;
99 Res_value value;
100};
101
Jeremy Meyerccf5cd72023-08-15 21:42:03 +0000102AssetManager2::AssetManager2(ApkAssetsList apk_assets, const ResTable_config& configuration) {
103 configurations_.push_back(configuration);
104
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700105 // Don't invalidate caches here as there's nothing cached yet.
106 SetApkAssets(apk_assets, false);
Adam Lesinski970bd8d2017-09-25 13:21:55 -0700107}
Adam Lesinski7ad11102016-10-28 16:39:15 -0700108
Jeremy Meyerccf5cd72023-08-15 21:42:03 +0000109AssetManager2::AssetManager2() {
110 configurations_.resize(1);
111}
112
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700113bool AssetManager2::SetApkAssets(ApkAssetsList apk_assets, bool invalidate_caches) {
114 BuildDynamicRefTable(apk_assets);
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800115 RebuildFilterList();
Adam Lesinski7ad11102016-10-28 16:39:15 -0700116 if (invalidate_caches) {
117 InvalidateCaches(static_cast<uint32_t>(-1));
118 }
119 return true;
120}
121
Michael Hoisie7b433332024-02-13 21:42:21 +0000122void AssetManager2::PresetApkAssets(ApkAssetsList apk_assets) {
123 BuildDynamicRefTable(apk_assets);
124}
125
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700126bool AssetManager2::SetApkAssets(std::initializer_list<ApkAssetsPtr> apk_assets,
127 bool invalidate_caches) {
128 return SetApkAssets(ApkAssetsList(apk_assets.begin(), apk_assets.size()), invalidate_caches);
129}
130
131void AssetManager2::BuildDynamicRefTable(ApkAssetsList apk_assets) {
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700132 auto op = StartOperation();
133
134 apk_assets_.resize(apk_assets.size());
135 for (size_t i = 0; i != apk_assets.size(); ++i) {
136 apk_assets_[i].first = apk_assets[i];
137 // Let's populate the locked assets right away as we're going to need them here later.
138 apk_assets_[i].second = apk_assets[i];
139 }
140
Adam Lesinskida431a22016-12-29 16:08:16 -0500141 package_groups_.clear();
142 package_ids_.fill(0xff);
143
Ryan Mitchellef538432021-03-01 14:52:14 -0800144 // A mapping from path of apk assets that could be target packages of overlays to the runtime
145 // package id of its first loaded package. Overlays currently can only override resources in the
146 // first package in the target resource table.
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800147 std::unordered_map<std::string_view, uint8_t> target_assets_package_ids;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700148
Ryan Mitchell824cc492020-02-12 10:48:14 -0800149 // Overlay resources are not directly referenced by an application so their resource ids
150 // can change throughout the application's lifetime. Assign overlay package ids last.
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700151 std::vector<const ApkAssets*> sorted_apk_assets;
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700152 sorted_apk_assets.reserve(apk_assets.size());
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700153 for (auto& asset : apk_assets) {
154 sorted_apk_assets.push_back(asset.get());
155 }
156 std::stable_partition(sorted_apk_assets.begin(), sorted_apk_assets.end(),
157 [](auto a) { return !a->IsOverlay(); });
Ryan Mitchell824cc492020-02-12 10:48:14 -0800158
159 // The assets cookie must map to the position of the apk assets in the unsorted apk assets list.
160 std::unordered_map<const ApkAssets*, ApkAssetsCookie> apk_assets_cookies;
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700161 apk_assets_cookies.reserve(apk_assets.size());
162 for (size_t i = 0, n = apk_assets.size(); i < n; i++) {
163 apk_assets_cookies[apk_assets[i].get()] = static_cast<ApkAssetsCookie>(i);
Ryan Mitchell824cc492020-02-12 10:48:14 -0800164 }
165
Ryan Mitchellb894c272020-02-12 10:31:44 -0800166 // 0x01 is reserved for the android package.
167 int next_package_id = 0x02;
Ryan Mitchell824cc492020-02-12 10:48:14 -0800168 for (const ApkAssets* apk_assets : sorted_apk_assets) {
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800169 std::shared_ptr<OverlayDynamicRefTable> overlay_ref_table;
170 if (auto loaded_idmap = apk_assets->GetLoadedIdmap(); loaded_idmap != nullptr) {
171 // The target package must precede the overlay package in the apk assets paths in order
172 // to take effect.
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800173 auto iter = target_assets_package_ids.find(loaded_idmap->TargetApkPath());
Ryan Mitchellef538432021-03-01 14:52:14 -0800174 if (iter == target_assets_package_ids.end()) {
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800175 LOG(INFO) << "failed to find target package for overlay "
176 << loaded_idmap->OverlayApkPath();
177 } else {
178 uint8_t target_package_id = iter->second;
179
180 // Create a special dynamic reference table for the overlay to rewrite references to
181 // overlay resources as references to the target resources they overlay.
182 overlay_ref_table = std::make_shared<OverlayDynamicRefTable>(
183 loaded_idmap->GetOverlayDynamicRefTable(target_package_id));
184
185 // Add the overlay resource map to the target package's set of overlays.
186 const uint8_t target_idx = package_ids_[target_package_id];
187 CHECK(target_idx != 0xff) << "overlay target '" << loaded_idmap->TargetApkPath()
188 << "'added to apk_assets_package_ids but does not have an"
189 << " assigned package group";
190
191 PackageGroup& target_package_group = package_groups_[target_idx];
192 target_package_group.overlays_.push_back(
193 ConfiguredOverlay{loaded_idmap->GetTargetResourcesMap(target_package_id,
194 overlay_ref_table.get()),
195 apk_assets_cookies[apk_assets]});
196 }
197 }
198
Ryan Mitchellb894c272020-02-12 10:31:44 -0800199 const LoadedArsc* loaded_arsc = apk_assets->GetLoadedArsc();
Ryan Mitchellb894c272020-02-12 10:31:44 -0800200 for (const std::unique_ptr<const LoadedPackage>& package : loaded_arsc->GetPackages()) {
201 // Get the package ID or assign one if a shared library.
202 int package_id;
203 if (package->IsDynamic()) {
204 package_id = next_package_id++;
205 } else {
206 package_id = package->GetPackageId();
Adam Lesinskida431a22016-12-29 16:08:16 -0500207 }
208
Adam Lesinskida431a22016-12-29 16:08:16 -0500209 uint8_t idx = package_ids_[package_id];
210 if (idx == 0xff) {
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800211 // Add the mapping for package ID to index if not present.
Adam Lesinskida431a22016-12-29 16:08:16 -0500212 package_ids_[package_id] = idx = static_cast<uint8_t>(package_groups_.size());
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800213 PackageGroup& new_group = package_groups_.emplace_back();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700214
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800215 if (overlay_ref_table != nullptr) {
216 // If this package is from an overlay, use a dynamic reference table that can rewrite
217 // overlay resource ids to their corresponding target resource ids.
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800218 new_group.dynamic_ref_table = std::move(overlay_ref_table);
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700219 }
220
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800221 DynamicRefTable* ref_table = new_group.dynamic_ref_table.get();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700222 ref_table->mAssignedPackageId = package_id;
223 ref_table->mAppAsLib = package->IsDynamic() && package->GetPackageId() == 0x7f;
Adam Lesinskida431a22016-12-29 16:08:16 -0500224 }
Adam Lesinskida431a22016-12-29 16:08:16 -0500225
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800226 // Add the package to the set of packages with the same ID.
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800227 PackageGroup* package_group = &package_groups_[idx];
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800228 package_group->packages_.emplace_back().loaded_package_ = package.get();
Ryan Mitchell824cc492020-02-12 10:48:14 -0800229 package_group->cookies_.push_back(apk_assets_cookies[apk_assets]);
Adam Lesinskida431a22016-12-29 16:08:16 -0500230
231 // Add the package name -> build time ID mappings.
232 for (const DynamicPackageEntry& entry : package->GetDynamicPackageMap()) {
233 String16 package_name(entry.package_name.c_str(), entry.package_name.size());
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700234 package_group->dynamic_ref_table->mEntries.replaceValueFor(
Adam Lesinskida431a22016-12-29 16:08:16 -0500235 package_name, static_cast<uint8_t>(entry.package_id));
236 }
Ryan Mitchellb894c272020-02-12 10:31:44 -0800237
Ryan Mitchellef538432021-03-01 14:52:14 -0800238 if (auto apk_assets_path = apk_assets->GetPath()) {
239 // Overlay target ApkAssets must have been created using path based load apis.
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800240 target_assets_package_ids.emplace(*apk_assets_path, package_id);
Ryan Mitchellef538432021-03-01 14:52:14 -0800241 }
Adam Lesinskida431a22016-12-29 16:08:16 -0500242 }
243 }
244
245 // Now assign the runtime IDs so that we have a build-time to runtime ID map.
Yurii Zubrytskyi59dab3b2022-11-03 00:08:49 -0700246 DynamicRefTable::AliasMap aliases;
247 for (const auto& group : package_groups_) {
248 const std::string& package_name = group.packages_[0].loaded_package_->GetPackageName();
249 const auto name_16 = String16(package_name.c_str(), package_name.size());
250 for (auto&& inner_group : package_groups_) {
251 inner_group.dynamic_ref_table->addMapping(name_16,
252 group.dynamic_ref_table->mAssignedPackageId);
Adam Lesinskida431a22016-12-29 16:08:16 -0500253 }
Yurii Zubrytskyi59dab3b2022-11-03 00:08:49 -0700254
255 for (const auto& package : group.packages_) {
256 const auto& package_aliases = package.loaded_package_->GetAliasResourceIdMap();
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800257 aliases.insert(aliases.end(), package_aliases.begin(), package_aliases.end());
Yurii Zubrytskyi59dab3b2022-11-03 00:08:49 -0700258 }
259 }
260
261 if (!aliases.empty()) {
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800262 std::sort(aliases.begin(), aliases.end(), [](auto&& l, auto&& r) { return l.first < r.first; });
263
Yurii Zubrytskyi59dab3b2022-11-03 00:08:49 -0700264 // Add the alias resources to the dynamic reference table of every package group. Since
265 // staging aliases can only be defined by the framework package (which is not a shared
266 // library), the compile-time package id of the framework is the same across all packages
267 // that compile against the framework.
268 for (auto& group : std::span(package_groups_.data(), package_groups_.size() - 1)) {
269 group.dynamic_ref_table->setAliases(aliases);
270 }
271 package_groups_.back().dynamic_ref_table->setAliases(std::move(aliases));
Adam Lesinskida431a22016-12-29 16:08:16 -0500272 }
273}
274
275void AssetManager2::DumpToLog() const {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800276 LOG(INFO) << base::StringPrintf("AssetManager2(this=%p)", this);
277
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700278 auto op = StartOperation();
Adam Lesinskida431a22016-12-29 16:08:16 -0500279 std::string list;
Yurii Zubrytskyi7d70bc52023-05-12 13:27:54 -0700280 for (size_t i = 0, s = apk_assets_.size(); i < s; ++i) {
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700281 const auto& assets = GetApkAssets(i);
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700282 base::StringAppendF(&list, "%s,", assets ? assets->GetDebugName().c_str() : "nullptr");
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800283 }
284 LOG(INFO) << "ApkAssets: " << list;
285
286 list = "";
Adam Lesinskida431a22016-12-29 16:08:16 -0500287 for (size_t i = 0; i < package_ids_.size(); i++) {
288 if (package_ids_[i] != 0xff) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800289 base::StringAppendF(&list, "%02x -> %d, ", (int)i, package_ids_[i]);
Adam Lesinskida431a22016-12-29 16:08:16 -0500290 }
291 }
292 LOG(INFO) << "Package ID map: " << list;
293
Adam Lesinski0dd36992018-01-25 15:38:38 -0800294 for (const auto& package_group: package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800295 list = "";
296 for (const auto& package : package_group.packages_) {
297 const LoadedPackage* loaded_package = package.loaded_package_;
298 base::StringAppendF(&list, "%s(%02x%s), ", loaded_package->GetPackageName().c_str(),
299 loaded_package->GetPackageId(),
300 (loaded_package->IsDynamic() ? " dynamic" : ""));
301 }
302 LOG(INFO) << base::StringPrintf("PG (%02x): ",
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700303 package_group.dynamic_ref_table->mAssignedPackageId)
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800304 << list;
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800305
306 for (size_t i = 0; i < 256; i++) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700307 if (package_group.dynamic_ref_table->mLookupTable[i] != 0) {
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800308 LOG(INFO) << base::StringPrintf(" e[0x%02x] -> 0x%02x", (uint8_t) i,
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700309 package_group.dynamic_ref_table->mLookupTable[i]);
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800310 }
311 }
Adam Lesinskida431a22016-12-29 16:08:16 -0500312 }
313}
Adam Lesinski7ad11102016-10-28 16:39:15 -0700314
315const ResStringPool* AssetManager2::GetStringPoolForCookie(ApkAssetsCookie cookie) const {
316 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
317 return nullptr;
318 }
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700319 auto op = StartOperation();
320 const auto& assets = GetApkAssets(cookie);
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700321 return assets ? assets->GetLoadedArsc()->GetStringPool() : nullptr;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700322}
323
Adam Lesinskida431a22016-12-29 16:08:16 -0500324const DynamicRefTable* AssetManager2::GetDynamicRefTableForPackage(uint32_t package_id) const {
325 if (package_id >= package_ids_.size()) {
326 return nullptr;
327 }
328
329 const size_t idx = package_ids_[package_id];
330 if (idx == 0xff) {
331 return nullptr;
332 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700333 return package_groups_[idx].dynamic_ref_table.get();
Adam Lesinskida431a22016-12-29 16:08:16 -0500334}
335
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700336std::shared_ptr<const DynamicRefTable> AssetManager2::GetDynamicRefTableForCookie(
337 ApkAssetsCookie cookie) const {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800338 for (const PackageGroup& package_group : package_groups_) {
339 for (const ApkAssetsCookie& package_cookie : package_group.cookies_) {
340 if (package_cookie == cookie) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700341 return package_group.dynamic_ref_table;
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800342 }
343 }
344 }
345 return nullptr;
346}
347
MÃ¥rten Kongstadc92c4dd2019-02-05 01:29:59 +0100348const std::unordered_map<std::string, std::string>*
349 AssetManager2::GetOverlayableMapForPackage(uint32_t package_id) const {
350
351 if (package_id >= package_ids_.size()) {
352 return nullptr;
353 }
354
355 const size_t idx = package_ids_[package_id];
356 if (idx == 0xff) {
357 return nullptr;
358 }
359
360 const PackageGroup& package_group = package_groups_[idx];
Ryan Mitchell80094e32020-11-16 23:08:18 +0000361 if (package_group.packages_.empty()) {
MÃ¥rten Kongstadc92c4dd2019-02-05 01:29:59 +0100362 return nullptr;
363 }
364
365 const auto loaded_package = package_group.packages_[0].loaded_package_;
366 return &loaded_package->GetOverlayableMap();
367}
368
Yurii Zubrytskyia5775142022-11-02 17:49:49 -0700369bool AssetManager2::GetOverlayablesToString(android::StringPiece package_name,
Ryan Mitchell2e394222019-08-28 12:10:51 -0700370 std::string* out) const {
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700371 auto op = StartOperation();
Ryan Mitchell2e394222019-08-28 12:10:51 -0700372 uint8_t package_id = 0U;
Yurii Zubrytskyi7d70bc52023-05-12 13:27:54 -0700373 for (size_t i = 0, s = apk_assets_.size(); i != s; ++i) {
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700374 const auto& assets = GetApkAssets(i);
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700375 if (!assets) {
376 continue;
377 }
378 const LoadedArsc* loaded_arsc = assets->GetLoadedArsc();
Ryan Mitchell2e394222019-08-28 12:10:51 -0700379 if (loaded_arsc == nullptr) {
380 continue;
381 }
382
383 const auto& loaded_packages = loaded_arsc->GetPackages();
384 if (loaded_packages.empty()) {
385 continue;
386 }
387
388 const auto& loaded_package = loaded_packages[0];
389 if (loaded_package->GetPackageName() == package_name) {
390 package_id = GetAssignedPackageId(loaded_package.get());
391 break;
392 }
393 }
394
395 if (package_id == 0U) {
396 ANDROID_LOG(ERROR) << base::StringPrintf("No package with name '%s", package_name.data());
397 return false;
398 }
399
400 const size_t idx = package_ids_[package_id];
401 if (idx == 0xff) {
402 return false;
403 }
404
405 std::string output;
406 for (const ConfiguredPackage& package : package_groups_[idx].packages_) {
407 const LoadedPackage* loaded_package = package.loaded_package_;
408 for (auto it = loaded_package->begin(); it != loaded_package->end(); it++) {
409 const OverlayableInfo* info = loaded_package->GetOverlayableInfo(*it);
410 if (info != nullptr) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000411 auto res_name = GetResourceName(*it);
412 if (!res_name.has_value()) {
Ryan Mitchell2e394222019-08-28 12:10:51 -0700413 ANDROID_LOG(ERROR) << base::StringPrintf(
414 "Unable to retrieve name of overlayable resource 0x%08x", *it);
415 return false;
416 }
417
Ryan Mitchell80094e32020-11-16 23:08:18 +0000418 const std::string name = ToFormattedResourceString(*res_name);
Ryan Mitchell2e394222019-08-28 12:10:51 -0700419 output.append(base::StringPrintf(
420 "resource='%s' overlayable='%s' actor='%s' policy='0x%08x'\n",
Yurii Zubrytskyi9d225372022-11-29 11:12:18 -0800421 name.c_str(), info->name.data(), info->actor.data(), info->policy_flags));
Ryan Mitchell2e394222019-08-28 12:10:51 -0700422 }
423 }
424 }
425
426 *out = std::move(output);
427 return true;
428}
429
Ryan Mitchell192400c2020-04-02 09:54:23 -0700430bool AssetManager2::ContainsAllocatedTable() const {
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700431 auto op = StartOperation();
Yurii Zubrytskyi7d70bc52023-05-12 13:27:54 -0700432 for (size_t i = 0, s = apk_assets_.size(); i != s; ++i) {
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700433 const auto& assets = GetApkAssets(i);
434 if (assets && assets->IsTableAllocated()) {
435 return true;
436 }
437 }
438 return false;
Ryan Mitchell192400c2020-04-02 09:54:23 -0700439}
440
Michael Hoisie7b433332024-02-13 21:42:21 +0000441void AssetManager2::SetConfigurations(std::vector<ResTable_config> configurations,
442 bool force_refresh) {
Jeremy Meyerccf5cd72023-08-15 21:42:03 +0000443 int diff = 0;
Michael Hoisie7b433332024-02-13 21:42:21 +0000444 if (force_refresh) {
Jeremy Meyerccf5cd72023-08-15 21:42:03 +0000445 diff = -1;
446 } else {
Michael Hoisie7b433332024-02-13 21:42:21 +0000447 if (configurations_.size() != configurations.size()) {
448 diff = -1;
449 } else {
450 for (int i = 0; i < configurations_.size(); i++) {
451 diff |= configurations_[i].diff(configurations[i]);
452 }
Jeremy Meyerccf5cd72023-08-15 21:42:03 +0000453 }
454 }
455 configurations_ = std::move(configurations);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700456
457 if (diff) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800458 RebuildFilterList();
Adam Lesinski7ad11102016-10-28 16:39:15 -0700459 InvalidateCaches(static_cast<uint32_t>(diff));
460 }
461}
462
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700463std::set<AssetManager2::ApkAssetsPtr> AssetManager2::GetNonSystemOverlays() const {
464 std::set<ApkAssetsPtr> non_system_overlays;
Adam Lesinski0c405242017-01-13 20:47:26 -0800465 for (const PackageGroup& package_group : package_groups_) {
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800466 bool found_system_package = false;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800467 for (const ConfiguredPackage& package : package_group.packages_) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700468 if (package.loaded_package_->IsSystem()) {
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800469 found_system_package = true;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700470 break;
471 }
472 }
473
474 if (!found_system_package) {
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700475 auto op = StartOperation();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700476 for (const ConfiguredOverlay& overlay : package_group.overlays_) {
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700477 if (const auto& asset = GetApkAssets(overlay.cookie)) {
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700478 non_system_overlays.insert(std::move(asset));
479 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700480 }
481 }
482 }
483
484 return non_system_overlays;
485}
486
Ryan Mitchell80094e32020-11-16 23:08:18 +0000487base::expected<std::set<ResTable_config>, IOError> AssetManager2::GetResourceConfigurations(
488 bool exclude_system, bool exclude_mipmap) const {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700489 ATRACE_NAME("AssetManager::GetResourceConfigurations");
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700490 auto op = StartOperation();
491
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700492 const auto non_system_overlays =
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700493 exclude_system ? GetNonSystemOverlays() : std::set<ApkAssetsPtr>();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700494
495 std::set<ResTable_config> configurations;
496 for (const PackageGroup& package_group : package_groups_) {
497 for (size_t i = 0; i < package_group.packages_.size(); i++) {
498 const ConfiguredPackage& package = package_group.packages_[i];
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700499 if (exclude_system) {
500 if (package.loaded_package_->IsSystem()) {
501 continue;
502 }
503 if (!non_system_overlays.empty()) {
504 // Exclude overlays that target only system resources.
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700505 const auto& apk_assets = GetApkAssets(package_group.cookies_[i]);
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700506 if (apk_assets && apk_assets->IsOverlay() &&
507 non_system_overlays.find(apk_assets) == non_system_overlays.end()) {
508 continue;
509 }
510 }
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800511 }
512
Ryan Mitchell80094e32020-11-16 23:08:18 +0000513 auto result = package.loaded_package_->CollectConfigurations(exclude_mipmap, &configurations);
514 if (UNLIKELY(!result.has_value())) {
515 return base::unexpected(result.error());
516 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800517 }
518 }
519 return configurations;
520}
521
522std::set<std::string> AssetManager2::GetResourceLocales(bool exclude_system,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800523 bool merge_equivalent_languages) const {
524 ATRACE_NAME("AssetManager::GetResourceLocales");
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700525 auto op = StartOperation();
526
Adam Lesinski0c405242017-01-13 20:47:26 -0800527 std::set<std::string> locales;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700528 const auto non_system_overlays =
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700529 exclude_system ? GetNonSystemOverlays() : std::set<ApkAssetsPtr>();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700530
Adam Lesinski0c405242017-01-13 20:47:26 -0800531 for (const PackageGroup& package_group : package_groups_) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700532 for (size_t i = 0; i < package_group.packages_.size(); i++) {
533 const ConfiguredPackage& package = package_group.packages_[i];
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700534 if (exclude_system) {
535 if (package.loaded_package_->IsSystem()) {
536 continue;
537 }
538 if (!non_system_overlays.empty()) {
539 // Exclude overlays that target only system resources.
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700540 const auto& apk_assets = GetApkAssets(package_group.cookies_[i]);
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700541 if (apk_assets && apk_assets->IsOverlay() &&
542 non_system_overlays.find(apk_assets) == non_system_overlays.end()) {
543 continue;
544 }
545 }
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800546 }
547
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800548 package.loaded_package_->CollectLocales(merge_equivalent_languages, &locales);
Adam Lesinski0c405242017-01-13 20:47:26 -0800549 }
550 }
551 return locales;
552}
553
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800554std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename,
555 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700556 const std::string new_path = "assets/" + filename;
557 return OpenNonAsset(new_path, mode);
558}
559
560std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename, ApkAssetsCookie cookie,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800561 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700562 const std::string new_path = "assets/" + filename;
563 return OpenNonAsset(new_path, cookie, mode);
564}
565
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800566std::unique_ptr<AssetDir> AssetManager2::OpenDir(const std::string& dirname) const {
567 ATRACE_NAME("AssetManager::OpenDir");
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700568 auto op = StartOperation();
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800569
570 std::string full_path = "assets/" + dirname;
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700571 auto files = util::make_unique<SortedVector<AssetDir::FileInfo>>();
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800572
573 // Start from the back.
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700574 for (size_t i = apk_assets_.size(); i > 0; --i) {
575 const auto& apk_assets = GetApkAssets(i - 1);
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700576 if (!apk_assets || apk_assets->IsOverlay()) {
MÃ¥rten Kongstaddbf343b2019-02-21 07:54:18 +0100577 continue;
578 }
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800579
Yurii Zubrytskyia5775142022-11-02 17:49:49 -0700580 auto func = [&](StringPiece name, FileType type) {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800581 AssetDir::FileInfo info;
582 info.setFileName(String8(name.data(), name.size()));
583 info.setFileType(type);
Ryan Mitchellef538432021-03-01 14:52:14 -0800584 info.setSourceName(String8(apk_assets->GetDebugName().c_str()));
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800585 files->add(info);
586 };
587
Ryan Mitchellc07aa702020-03-10 13:49:12 -0700588 if (!apk_assets->GetAssetsProvider()->ForEachFile(full_path, func)) {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800589 return {};
590 }
591 }
592
593 std::unique_ptr<AssetDir> asset_dir = util::make_unique<AssetDir>();
594 asset_dir->setFileList(files.release());
595 return asset_dir;
596}
597
Adam Lesinski7ad11102016-10-28 16:39:15 -0700598// Search in reverse because that's how we used to do it and we need to preserve behaviour.
599// This is unfortunate, because ClassLoaders delegate to the parent first, so the order
600// is inconsistent for split APKs.
601std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
602 Asset::AccessMode mode,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800603 ApkAssetsCookie* out_cookie) const {
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700604 auto op = StartOperation();
605 for (size_t i = apk_assets_.size(); i > 0; i--) {
606 const auto& assets = GetApkAssets(i - 1);
MÃ¥rten Kongstaddbf343b2019-02-21 07:54:18 +0100607 // Prevent RRO from modifying assets and other entries accessed by file
608 // path. Explicitly asking for a path in a given package (denoted by a
609 // cookie) is still OK.
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700610 if (!assets || assets->IsOverlay()) {
MÃ¥rten Kongstaddbf343b2019-02-21 07:54:18 +0100611 continue;
612 }
613
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700614 std::unique_ptr<Asset> asset = assets->GetAssetsProvider()->Open(filename, mode);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700615 if (asset) {
616 if (out_cookie != nullptr) {
Yurii Zubrytskyif48a56f2023-11-21 08:15:13 -0800617 *out_cookie = i - 1;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700618 }
619 return asset;
620 }
621 }
622
623 if (out_cookie != nullptr) {
624 *out_cookie = kInvalidCookie;
625 }
626 return {};
627}
628
629std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800630 ApkAssetsCookie cookie,
631 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700632 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
633 return {};
634 }
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700635 auto op = StartOperation();
636 const auto& assets = GetApkAssets(cookie);
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700637 return assets ? assets->GetAssetsProvider()->Open(filename, mode) : nullptr;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700638}
639
Ryan Mitchell80094e32020-11-16 23:08:18 +0000640base::expected<FindEntryResult, NullOrIOError> AssetManager2::FindEntry(
641 uint32_t resid, uint16_t density_override, bool stop_at_first_match,
642 bool ignore_configuration) const {
643 const bool logging_enabled = resource_resolution_logging_enabled_;
644 if (UNLIKELY(logging_enabled)) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700645 // Clear the last logged resource resolution.
646 ResetResourceResolution();
647 last_resolution_.resid = resid;
648 }
649
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700650 auto op = StartOperation();
651
Adam Lesinski7ad11102016-10-28 16:39:15 -0700652
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700653 // Retrieve the package group from the package id of the resource id.
Ryan Mitchell80094e32020-11-16 23:08:18 +0000654 if (UNLIKELY(!is_valid_resid(resid))) {
Mark Hansenb406b0e2022-10-14 02:18:37 +0000655 LOG(ERROR) << base::StringPrintf("Invalid resource ID 0x%08x.", resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000656 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -0500657 }
658
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800659 const uint32_t package_id = get_package_id(resid);
660 const uint8_t type_idx = get_type_id(resid) - 1;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800661 const uint16_t entry_idx = get_entry_id(resid);
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700662 uint8_t package_idx = package_ids_[package_id];
Ryan Mitchell80094e32020-11-16 23:08:18 +0000663 if (UNLIKELY(package_idx == 0xff)) {
Mark Hansenb406b0e2022-10-14 02:18:37 +0000664 ANDROID_LOG(ERROR) << base::StringPrintf("No package ID %02x found for resource ID 0x%08x.",
Ryan Mitchell2fe23472019-02-27 09:43:01 -0800665 package_id, resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000666 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -0500667 }
668
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800669 const PackageGroup& package_group = package_groups_[package_idx];
Jeremy Meyerccf5cd72023-08-15 21:42:03 +0000670 std::optional<FindEntryResult> final_result;
671 bool final_has_locale = false;
672 bool final_overlaid = false;
673 for (auto & config : configurations_) {
674 // Might use this if density_override != 0.
675 ResTable_config density_override_config;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800676
Jeremy Meyerccf5cd72023-08-15 21:42:03 +0000677 // Select our configuration or generate a density override configuration.
678 const ResTable_config* desired_config = &config;
679 if (density_override != 0 && density_override != config.density) {
680 density_override_config = config;
681 density_override_config.density = density_override;
682 desired_config = &density_override_config;
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700683 }
Jeremy Meyerccf5cd72023-08-15 21:42:03 +0000684
685 auto result = FindEntryInternal(package_group, type_idx, entry_idx, *desired_config,
686 stop_at_first_match, ignore_configuration);
687 if (UNLIKELY(!result.has_value())) {
688 return base::unexpected(result.error());
689 }
690 bool overlaid = false;
691 if (!stop_at_first_match && !ignore_configuration) {
692 const auto& assets = GetApkAssets(result->cookie);
693 if (!assets) {
694 ALOGE("Found expired ApkAssets #%d for resource ID 0x%08x.", result->cookie, resid);
695 return base::unexpected(std::nullopt);
696 }
697 if (!assets->IsLoader()) {
698 for (const auto& id_map : package_group.overlays_) {
699 auto overlay_entry = id_map.overlay_res_maps_.Lookup(resid);
700 if (!overlay_entry) {
701 // No id map entry exists for this target resource.
Jeremy Meyer04cf00d2023-07-20 22:17:27 +0000702 continue;
703 }
Jeremy Meyerccf5cd72023-08-15 21:42:03 +0000704 if (overlay_entry.IsInlineValue()) {
705 // The target resource is overlaid by an inline value not represented by a resource.
706 ConfigDescription best_frro_config;
707 Res_value best_frro_value;
708 bool frro_found = false;
709 for( const auto& [config, value] : overlay_entry.GetInlineValue()) {
710 if ((!frro_found || config.isBetterThan(best_frro_config, desired_config))
711 && config.match(*desired_config)) {
712 frro_found = true;
713 best_frro_config = config;
714 best_frro_value = value;
715 }
716 }
717 if (!frro_found) {
718 continue;
719 }
720 result->entry = best_frro_value;
721 result->dynamic_ref_table = id_map.overlay_res_maps_.GetOverlayDynamicRefTable();
722 result->cookie = id_map.cookie;
723
724 if (UNLIKELY(logging_enabled)) {
725 last_resolution_.steps.push_back(Resolution::Step{
726 Resolution::Step::Type::OVERLAID_INLINE, result->cookie, String8()});
727 if (auto path = assets->GetPath()) {
728 const std::string overlay_path = path->data();
729 if (IsFabricatedOverlay(overlay_path)) {
730 // FRRO don't have package name so we use the creating package here.
731 String8 frro_name = String8("FRRO");
732 // Get the first part of it since the expected one should be like
733 // {overlayPackageName}-{overlayName}-{4 alphanumeric chars}.frro
734 // under /data/resource-cache/.
735 const std::string name = overlay_path.substr(overlay_path.rfind('/') + 1);
736 const size_t end = name.find('-');
737 if (frro_name.size() != overlay_path.size() && end != std::string::npos) {
738 frro_name.append(base::StringPrintf(" created by %s",
739 name.substr(0 /* pos */,
740 end).c_str()).c_str());
741 }
742 last_resolution_.best_package_name = frro_name;
743 } else {
744 last_resolution_.best_package_name = result->package_name->c_str();
745 }
746 }
747 overlaid = true;
748 }
749 continue;
750 }
751
752 auto overlay_result = FindEntry(overlay_entry.GetResourceId(), density_override,
753 false /* stop_at_first_match */,
754 false /* ignore_configuration */);
755 if (UNLIKELY(IsIOError(overlay_result))) {
756 return base::unexpected(overlay_result.error());
757 }
758 if (!overlay_result.has_value()) {
759 continue;
760 }
761
762 if (!overlay_result->config.isBetterThan(result->config, desired_config)
763 && overlay_result->config.compare(result->config) != 0) {
764 // The configuration of the entry for the overlay must be equal to or better than the
765 // target configuration to be chosen as the better value.
766 continue;
767 }
768
769 result->cookie = overlay_result->cookie;
770 result->entry = overlay_result->entry;
771 result->config = overlay_result->config;
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700772 result->dynamic_ref_table = id_map.overlay_res_maps_.GetOverlayDynamicRefTable();
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700773
774 if (UNLIKELY(logging_enabled)) {
775 last_resolution_.steps.push_back(
Jeremy Meyerccf5cd72023-08-15 21:42:03 +0000776 Resolution::Step{Resolution::Step::Type::OVERLAID, overlay_result->cookie,
777 overlay_result->config.toString()});
778 last_resolution_.best_package_name =
779 overlay_result->package_name->c_str();
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700780 overlaid = true;
781 }
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800782 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700783 }
784 }
Jeremy Meyerccf5cd72023-08-15 21:42:03 +0000785
786 bool has_locale = false;
787 if (result->config.locale == 0) {
788 if (default_locale_ != 0) {
Michael Hoisie7b433332024-02-13 21:42:21 +0000789 ResTable_config conf = {.locale = default_locale_};
Jeremy Meyerccf5cd72023-08-15 21:42:03 +0000790 // Since we know conf has a locale and only a locale, match will tell us if that locale
791 // matches
792 has_locale = conf.match(config);
793 }
794 } else {
795 has_locale = true;
796 }
797
Jeremy Meyer2ae6ed592023-09-13 12:39:53 -0700798 // if we don't have a result yet
Jeremy Meyerccf5cd72023-08-15 21:42:03 +0000799 if (!final_result ||
800 // or this config is better before the locale than the existing result
801 result->config.isBetterThanBeforeLocale(final_result->config, desired_config) ||
802 // or the existing config isn't better before locale and this one specifies a locale
803 // whereas the existing one doesn't
804 (!final_result->config.isBetterThanBeforeLocale(result->config, desired_config)
805 && has_locale && !final_has_locale)) {
806 final_result = result.value();
807 final_overlaid = overlaid;
808 final_has_locale = has_locale;
809 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700810 }
811
Ryan Mitchell80094e32020-11-16 23:08:18 +0000812 if (UNLIKELY(logging_enabled)) {
Jeremy Meyerccf5cd72023-08-15 21:42:03 +0000813 last_resolution_.cookie = final_result->cookie;
814 last_resolution_.type_string_ref = final_result->type_string_ref;
815 last_resolution_.entry_string_ref = final_result->entry_string_ref;
816 last_resolution_.best_config_name = final_result->config.toString();
817 if (!final_overlaid) {
818 last_resolution_.best_package_name = final_result->package_name->c_str();
Jackal Guo552b45d2021-09-29 10:52:19 +0800819 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700820 }
821
Jeremy Meyerccf5cd72023-08-15 21:42:03 +0000822 return *final_result;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700823}
824
Ryan Mitchell80094e32020-11-16 23:08:18 +0000825base::expected<FindEntryResult, NullOrIOError> AssetManager2::FindEntryInternal(
826 const PackageGroup& package_group, uint8_t type_idx, uint16_t entry_idx,
827 const ResTable_config& desired_config, bool stop_at_first_match,
828 bool ignore_configuration) const {
829 const bool logging_enabled = resource_resolution_logging_enabled_;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800830 ApkAssetsCookie best_cookie = kInvalidCookie;
831 const LoadedPackage* best_package = nullptr;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000832 incfs::verified_map_ptr<ResTable_type> best_type;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800833 const ResTable_config* best_config = nullptr;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000834 uint32_t best_offset = 0U;
835 uint32_t type_flags = 0U;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800836
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800837 // If `desired_config` is not the same as the set configuration or the caller will accept a value
838 // from any configuration, then we cannot use our filtered list of types since it only it contains
839 // types matched to the set configuration.
Jeremy Meyerccf5cd72023-08-15 21:42:03 +0000840 const bool use_filtered = !ignore_configuration && std::find_if(
841 configurations_.begin(), configurations_.end(),
842 [&desired_config](auto& value) { return &desired_config == &value; })
843 != configurations_.end();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700844 const size_t package_count = package_group.packages_.size();
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800845 for (size_t pi = 0; pi < package_count; pi++) {
846 const ConfiguredPackage& loaded_package_impl = package_group.packages_[pi];
847 const LoadedPackage* loaded_package = loaded_package_impl.loaded_package_;
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800848 const ApkAssetsCookie cookie = package_group.cookies_[pi];
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800849
850 // If the type IDs are offset in this package, we need to take that into account when searching
851 // for a type.
852 const TypeSpec* type_spec = loaded_package->GetTypeSpecByTypeIndex(type_idx);
853 if (UNLIKELY(type_spec == nullptr)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700854 continue;
855 }
856
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800857 // Allow custom loader packages to overlay resource values with configurations equivalent to the
858 // current best configuration.
859 const bool package_is_loader = loaded_package->IsCustomLoader();
860
Ryan Mitchell80094e32020-11-16 23:08:18 +0000861 auto entry_flags = type_spec->GetFlagsForEntryIndex(entry_idx);
Bernie Innocenti58cf8e32020-12-19 15:31:52 +0900862 if (UNLIKELY(!entry_flags.has_value())) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000863 return base::unexpected(entry_flags.error());
864 }
865 type_flags |= entry_flags.value();
866
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800867 const FilteredConfigGroup& filtered_group = loaded_package_impl.filtered_configs_[type_idx];
868 const size_t type_entry_count = (use_filtered) ? filtered_group.type_entries.size()
869 : type_spec->type_entries.size();
870 for (size_t i = 0; i < type_entry_count; i++) {
871 const TypeSpec::TypeEntry* type_entry = (use_filtered) ? filtered_group.type_entries[i]
872 : &type_spec->type_entries[i];
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800873
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800874 // We can skip calling ResTable_config::match() if the caller does not care for the
875 // configuration to match or if we're using the list of types that have already had their
Jeremy Meyer2ae6ed592023-09-13 12:39:53 -0700876 // configuration matched. The exception to this is when the user has multiple locales set
877 // because the filtered list will then have values from multiple locales and we will need to
878 // call match() to make sure the current entry matches the config we are currently checking.
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800879 const ResTable_config& this_config = type_entry->config;
Jeremy Meyer2ae6ed592023-09-13 12:39:53 -0700880 if (!((use_filtered && (configurations_.size() == 1))
881 || ignore_configuration || this_config.match(desired_config))) {
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800882 continue;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800883 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800884
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800885 Resolution::Step::Type resolution_type;
886 if (best_config == nullptr) {
887 resolution_type = Resolution::Step::Type::INITIAL;
888 } else if (this_config.isBetterThan(*best_config, &desired_config)) {
889 resolution_type = Resolution::Step::Type::BETTER_MATCH;
890 } else if (package_is_loader && this_config.compare(*best_config) == 0) {
891 resolution_type = Resolution::Step::Type::OVERLAID;
892 } else {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000893 if (UNLIKELY(logging_enabled)) {
Jackal Guo552b45d2021-09-29 10:52:19 +0800894 last_resolution_.steps.push_back(Resolution::Step{Resolution::Step::Type::SKIPPED,
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -0700895 cookie, this_config.toString()});
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800896 }
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800897 continue;
898 }
899
900 // The configuration matches and is better than the previous selection.
901 // Find the entry value if it exists for this configuration.
902 const auto& type = type_entry->type;
903 const auto offset = LoadedPackage::GetEntryOffset(type, entry_idx);
904 if (UNLIKELY(IsIOError(offset))) {
905 return base::unexpected(offset.error());
906 }
907
908 if (!offset.has_value()) {
909 if (UNLIKELY(logging_enabled)) {
Jackal Guo552b45d2021-09-29 10:52:19 +0800910 last_resolution_.steps.push_back(Resolution::Step{Resolution::Step::Type::NO_ENTRY,
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -0700911 cookie, this_config.toString()});
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800912 }
913 continue;
914 }
915
916 best_cookie = cookie;
917 best_package = loaded_package;
918 best_type = type;
919 best_config = &this_config;
920 best_offset = offset.value();
921
922 if (UNLIKELY(logging_enabled)) {
923 last_resolution_.steps.push_back(Resolution::Step{resolution_type,
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -0700924 cookie, this_config.toString()});
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800925 }
926
927 // Any configuration will suffice, so break.
928 if (stop_at_first_match) {
929 break;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700930 }
931 }
932 }
933
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800934 if (UNLIKELY(best_cookie == kInvalidCookie)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000935 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700936 }
937
Eric Miao368cd192022-09-09 15:46:14 -0700938 auto best_entry_verified = LoadedPackage::GetEntryFromOffset(best_type, best_offset);
939 if (!best_entry_verified.has_value()) {
940 return base::unexpected(best_entry_verified.error());
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800941 }
942
Eric Miao368cd192022-09-09 15:46:14 -0700943 const auto entry = GetEntryValue(*best_entry_verified);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000944 if (!entry.has_value()) {
945 return base::unexpected(entry.error());
946 }
Winson2f3669b2019-01-11 11:28:34 -0800947
Ryan Mitchell80094e32020-11-16 23:08:18 +0000948 return FindEntryResult{
949 .cookie = best_cookie,
950 .entry = *entry,
951 .config = *best_config,
952 .type_flags = type_flags,
Tomasz Wasilczyk9e039b92023-06-29 12:08:24 -0700953 .dynamic_ref_table = package_group.dynamic_ref_table.get(),
Ryan Mitchell80094e32020-11-16 23:08:18 +0000954 .package_name = &best_package->GetPackageName(),
955 .type_string_ref = StringPoolRef(best_package->GetTypeStringPool(), best_type->id - 1),
956 .entry_string_ref = StringPoolRef(best_package->GetKeyStringPool(),
Eric Miao368cd192022-09-09 15:46:14 -0700957 (*best_entry_verified)->key()),
Ryan Mitchell80094e32020-11-16 23:08:18 +0000958 };
Adam Lesinski7ad11102016-10-28 16:39:15 -0700959}
960
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700961void AssetManager2::ResetResourceResolution() const {
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -0700962 last_resolution_ = Resolution{};
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700963}
964
Winson2f3669b2019-01-11 11:28:34 -0800965void AssetManager2::SetResourceResolutionLoggingEnabled(bool enabled) {
966 resource_resolution_logging_enabled_ = enabled;
Winson2f3669b2019-01-11 11:28:34 -0800967 if (!enabled) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700968 ResetResourceResolution();
Winson2f3669b2019-01-11 11:28:34 -0800969 }
970}
971
972std::string AssetManager2::GetLastResourceResolution() const {
973 if (!resource_resolution_logging_enabled_) {
974 LOG(ERROR) << "Must enable resource resolution logging before getting path.";
Ryan Mitchell80094e32020-11-16 23:08:18 +0000975 return {};
Winson2f3669b2019-01-11 11:28:34 -0800976 }
977
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800978 const ApkAssetsCookie cookie = last_resolution_.cookie;
Winson2f3669b2019-01-11 11:28:34 -0800979 if (cookie == kInvalidCookie) {
980 LOG(ERROR) << "AssetManager hasn't resolved a resource to read resolution path.";
Ryan Mitchell80094e32020-11-16 23:08:18 +0000981 return {};
Winson2f3669b2019-01-11 11:28:34 -0800982 }
983
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700984 auto op = StartOperation();
985
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800986 const uint32_t resid = last_resolution_.resid;
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700987 const auto& assets = GetApkAssets(cookie);
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700988 const auto package =
989 assets ? assets->GetLoadedArsc()->GetPackageById(get_package_id(resid)) : nullptr;
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800990
Winson2f3669b2019-01-11 11:28:34 -0800991 std::string resource_name_string;
Winson2f3669b2019-01-11 11:28:34 -0800992 if (package != nullptr) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000993 auto resource_name = ToResourceName(last_resolution_.type_string_ref,
994 last_resolution_.entry_string_ref,
995 package->GetPackageName());
996 resource_name_string = resource_name.has_value() ?
997 ToFormattedResourceString(resource_name.value()) : "<unknown>";
Winson2f3669b2019-01-11 11:28:34 -0800998 }
999
1000 std::stringstream log_stream;
Jeremy Meyerccf5cd72023-08-15 21:42:03 +00001001 if (configurations_.size() == 1) {
1002 log_stream << base::StringPrintf("Resolution for 0x%08x %s\n"
1003 "\tFor config - %s", resid, resource_name_string.c_str(),
1004 configurations_[0].toString().c_str());
1005 } else {
1006 ResTable_config conf = configurations_[0];
1007 conf.clearLocale();
1008 log_stream << base::StringPrintf("Resolution for 0x%08x %s\n\tFor config - %s and locales",
1009 resid, resource_name_string.c_str(), conf.toString().c_str());
1010 char str[40];
1011 str[0] = '\0';
1012 for(auto iter = configurations_.begin(); iter < configurations_.end(); iter++) {
1013 iter->getBcp47Locale(str);
1014 log_stream << base::StringPrintf(" %s%s", str, iter < configurations_.end() ? "," : "");
1015 }
1016 }
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001017 for (const Resolution::Step& step : last_resolution_.steps) {
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -07001018 constexpr static std::array kStepStrings = {
1019 "Found initial",
1020 "Found better",
1021 "Overlaid",
1022 "Overlaid inline",
1023 "Skipped",
1024 "No entry"
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001025 };
1026
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -07001027 if (step.type < Resolution::Step::Type::INITIAL
1028 || step.type > Resolution::Step::Type::NO_ENTRY) {
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001029 continue;
Winson2f3669b2019-01-11 11:28:34 -08001030 }
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -07001031 const auto prefix = kStepStrings[int(step.type) - int(Resolution::Step::Type::INITIAL)];
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -07001032 const auto& assets = GetApkAssets(step.cookie);
Yurii Zubrytskyib3455192023-05-01 14:35:48 -07001033 log_stream << "\n\t" << prefix << ": " << (assets ? assets->GetDebugName() : "<null>")
1034 << " #" << step.cookie;
Tomasz Wasilczyk8f74b2a2023-08-24 19:02:33 +00001035 if (!step.config_name.empty()) {
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -08001036 log_stream << " - " << step.config_name;
Winson2f3669b2019-01-11 11:28:34 -08001037 }
1038 }
1039
Jackal Guo552b45d2021-09-29 10:52:19 +08001040 log_stream << "\nBest matching is from "
Tomasz Wasilczyk8f74b2a2023-08-24 19:02:33 +00001041 << (last_resolution_.best_config_name.empty() ? "default"
Tomasz Wasilczyk835dfe52023-08-17 16:27:22 +00001042 : last_resolution_.best_config_name.c_str())
Jackal Guo552b45d2021-09-29 10:52:19 +08001043 << " configuration of " << last_resolution_.best_package_name;
Winson2f3669b2019-01-11 11:28:34 -08001044 return log_stream.str();
1045}
1046
Felka Chang00964e92021-12-10 01:19:08 +08001047base::expected<uint32_t, NullOrIOError> AssetManager2::GetParentThemeResourceId(uint32_t resid)
1048const {
1049 auto entry = FindEntry(resid, 0u /* density_override */,
1050 false /* stop_at_first_match */,
1051 false /* ignore_configuration */);
1052 if (!entry.has_value()) {
1053 return base::unexpected(entry.error());
1054 }
1055
1056 auto entry_map = std::get_if<incfs::verified_map_ptr<ResTable_map_entry>>(&entry->entry);
1057 if (entry_map == nullptr) {
1058 // Not a bag, nothing to do.
1059 return base::unexpected(std::nullopt);
1060 }
1061
1062 auto map = *entry_map;
1063 const uint32_t parent_resid = dtohl(map->parent.ident);
1064
1065 return parent_resid;
1066}
1067
Ryan Mitchell80094e32020-11-16 23:08:18 +00001068base::expected<AssetManager2::ResourceName, NullOrIOError> AssetManager2::GetResourceName(
1069 uint32_t resid) const {
1070 auto result = FindEntry(resid, 0u /* density_override */, true /* stop_at_first_match */,
1071 true /* ignore_configuration */);
1072 if (!result.has_value()) {
1073 return base::unexpected(result.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001074 }
1075
Ryan Mitchell80094e32020-11-16 23:08:18 +00001076 return ToResourceName(result->type_string_ref,
1077 result->entry_string_ref,
1078 *result->package_name);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001079}
1080
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001081base::expected<uint32_t, NullOrIOError> AssetManager2::GetResourceTypeSpecFlags(
1082 uint32_t resid) const {
1083 auto result = FindEntry(resid, 0u /* density_override */, false /* stop_at_first_match */,
1084 true /* ignore_configuration */);
1085 if (!result.has_value()) {
1086 return base::unexpected(result.error());
1087 }
1088 return result->type_flags;
1089}
1090
Ryan Mitchell80094e32020-11-16 23:08:18 +00001091base::expected<AssetManager2::SelectedValue, NullOrIOError> AssetManager2::GetResource(
1092 uint32_t resid, bool may_be_bag, uint16_t density_override) const {
1093 auto result = FindEntry(resid, density_override, false /* stop_at_first_match */,
1094 false /* ignore_configuration */);
1095 if (!result.has_value()) {
1096 return base::unexpected(result.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001097 }
1098
Ryan Mitchell80094e32020-11-16 23:08:18 +00001099 auto result_map_entry = std::get_if<incfs::verified_map_ptr<ResTable_map_entry>>(&result->entry);
Ryan Mitchellbf1f45b2020-09-29 17:22:52 -07001100 if (result_map_entry != nullptr) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001101 if (!may_be_bag) {
1102 LOG(ERROR) << base::StringPrintf("Resource %08x is a complex map type.", resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001103 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001104 }
Adam Lesinski0c405242017-01-13 20:47:26 -08001105
1106 // Create a reference since we can't represent this complex type as a Res_value.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001107 return SelectedValue(Res_value::TYPE_REFERENCE, resid, result->cookie, result->type_flags,
1108 resid, result->config);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001109 }
1110
Adam Lesinskida431a22016-12-29 16:08:16 -05001111 // Convert the package ID to the runtime assigned package ID.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001112 Res_value value = std::get<Res_value>(result->entry);
1113 result->dynamic_ref_table->lookupResourceValue(&value);
Adam Lesinskida431a22016-12-29 16:08:16 -05001114
Ryan Mitchell80094e32020-11-16 23:08:18 +00001115 return SelectedValue(value.dataType, value.data, result->cookie, result->type_flags,
1116 resid, result->config);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001117}
1118
Ryan Mitchell80094e32020-11-16 23:08:18 +00001119base::expected<std::monostate, NullOrIOError> AssetManager2::ResolveReference(
Ryan Mitchella45506e2020-11-16 23:08:18 +00001120 AssetManager2::SelectedValue& value, bool cache_value) const {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001121 if (value.type != Res_value::TYPE_REFERENCE || value.data == 0U) {
1122 // Not a reference. Nothing to do.
1123 return {};
Adam Lesinski0c405242017-01-13 20:47:26 -08001124 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001125
Ryan Mitchella45506e2020-11-16 23:08:18 +00001126 const uint32_t original_flags = value.flags;
1127 const uint32_t original_resid = value.data;
1128 if (cache_value) {
1129 auto cached_value = cached_resolved_values_.find(value.data);
1130 if (cached_value != cached_resolved_values_.end()) {
1131 value = cached_value->second;
1132 value.flags |= original_flags;
1133 return {};
1134 }
1135 }
1136
1137 uint32_t combined_flags = 0U;
1138 uint32_t resolve_resid = original_resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001139 constexpr const uint32_t kMaxIterations = 20;
1140 for (uint32_t i = 0U;; i++) {
1141 auto result = GetResource(resolve_resid, true /*may_be_bag*/);
1142 if (!result.has_value()) {
Ryan Mitchelle7ab6272020-11-13 18:06:15 -08001143 value.resid = resolve_resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001144 return base::unexpected(result.error());
1145 }
1146
Ryan Mitchelle7ab6272020-11-13 18:06:15 -08001147 // If resource resolution fails, the value should be set to the last reference that was able to
1148 // be resolved successfully.
1149 value = *result;
1150 value.flags |= combined_flags;
1151
Ryan Mitchell80094e32020-11-16 23:08:18 +00001152 if (result->type != Res_value::TYPE_REFERENCE ||
1153 result->data == Res_value::DATA_NULL_UNDEFINED ||
1154 result->data == resolve_resid || i == kMaxIterations) {
1155 // This reference can't be resolved, so exit now and let the caller deal with it.
Ryan Mitchella45506e2020-11-16 23:08:18 +00001156 if (cache_value) {
1157 cached_resolved_values_[original_resid] = value;
1158 }
1159
1160 // Above value is cached without original_flags to ensure they don't get included in future
1161 // queries that hit the cache
1162 value.flags |= original_flags;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001163 return {};
1164 }
1165
Ryan Mitchelle7ab6272020-11-13 18:06:15 -08001166 combined_flags = result->flags;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001167 resolve_resid = result->data;
1168 }
Adam Lesinski0c405242017-01-13 20:47:26 -08001169}
1170
Yurii Zubrytskyi02a555f2023-05-10 13:22:55 -07001171base::expected<const std::vector<uint32_t>*, NullOrIOError> AssetManager2::GetBagResIdStack(
1172 uint32_t resid) const {
Yurii Zubrytskyi09144882023-06-15 23:23:15 -07001173 auto it = cached_bag_resid_stacks_.find(resid);
1174 if (it != cached_bag_resid_stacks_.end()) {
1175 return &it->second;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001176 }
Yurii Zubrytskyi09144882023-06-15 23:23:15 -07001177 std::vector<uint32_t> stacks;
1178 if (auto maybe_bag = GetBag(resid, stacks); UNLIKELY(IsIOError(maybe_bag))) {
1179 return base::unexpected(maybe_bag.error());
1180 }
1181
1182 it = cached_bag_resid_stacks_.emplace(resid, std::move(stacks)).first;
Yurii Zubrytskyi02a555f2023-05-10 13:22:55 -07001183 return &it->second;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001184}
1185
Ryan Mitchell80094e32020-11-16 23:08:18 +00001186base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::ResolveBag(
1187 AssetManager2::SelectedValue& value) const {
1188 if (UNLIKELY(value.type != Res_value::TYPE_REFERENCE)) {
1189 return base::unexpected(std::nullopt);
1190 }
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001191
Ryan Mitchell80094e32020-11-16 23:08:18 +00001192 auto bag = GetBag(value.data);
1193 if (bag.has_value()) {
1194 value.flags |= (*bag)->type_spec_flags;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001195 }
1196 return bag;
y57cd1952018-04-12 14:26:23 -07001197}
1198
Ryan Mitchell80094e32020-11-16 23:08:18 +00001199base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::GetBag(uint32_t resid) const {
Yurii Zubrytskyi09144882023-06-15 23:23:15 -07001200 auto resid_stacks_it = cached_bag_resid_stacks_.find(resid);
Yurii Zubrytskyi533e8cc2023-06-16 16:38:49 -07001201 if (resid_stacks_it == cached_bag_resid_stacks_.end()) {
Yurii Zubrytskyi09144882023-06-15 23:23:15 -07001202 resid_stacks_it = cached_bag_resid_stacks_.emplace(resid, std::vector<uint32_t>{}).first;
1203 }
Yurii Zubrytskyibd1db5d2023-05-23 18:32:47 -07001204 const auto bag = GetBag(resid, resid_stacks_it->second);
1205 if (UNLIKELY(IsIOError(bag))) {
1206 cached_bag_resid_stacks_.erase(resid_stacks_it);
1207 return base::unexpected(bag.error());
1208 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001209 return bag;
Ryan Mitchell155d5392020-02-10 13:35:24 -08001210}
1211
Ryan Mitchell80094e32020-11-16 23:08:18 +00001212base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::GetBag(
1213 uint32_t resid, std::vector<uint32_t>& child_resids) const {
1214 if (auto cached_iter = cached_bags_.find(resid); cached_iter != cached_bags_.end()) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001215 return cached_iter->second.get();
1216 }
1217
Ryan Mitchell80094e32020-11-16 23:08:18 +00001218 auto entry = FindEntry(resid, 0u /* density_override */, false /* stop_at_first_match */,
1219 false /* ignore_configuration */);
1220 if (!entry.has_value()) {
1221 return base::unexpected(entry.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001222 }
1223
Ryan Mitchell80094e32020-11-16 23:08:18 +00001224 auto entry_map = std::get_if<incfs::verified_map_ptr<ResTable_map_entry>>(&entry->entry);
1225 if (entry_map == nullptr) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001226 // Not a bag, nothing to do.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001227 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001228 }
1229
Ryan Mitchell80094e32020-11-16 23:08:18 +00001230 auto map = *entry_map;
1231 auto map_entry = map.offset(dtohs(map->size)).convert<ResTable_map>();
1232 const auto map_entry_end = map_entry + dtohl(map->count);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001233
y57cd1952018-04-12 14:26:23 -07001234 // Keep track of ids that have already been seen to prevent infinite loops caused by circular
Ryan Mitchell80094e32020-11-16 23:08:18 +00001235 // dependencies between bags.
y57cd1952018-04-12 14:26:23 -07001236 child_resids.push_back(resid);
1237
Adam Lesinskida431a22016-12-29 16:08:16 -05001238 uint32_t parent_resid = dtohl(map->parent.ident);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001239 if (parent_resid == 0U ||
1240 std::find(child_resids.begin(), child_resids.end(), parent_resid) != child_resids.end()) {
1241 // There is no parent or a circular parental dependency exist, meaning there is nothing to
1242 // inherit and we can do a simple copy of the entries in the map.
Adam Lesinski7ad11102016-10-28 16:39:15 -07001243 const size_t entry_count = map_entry_end - map_entry;
1244 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
1245 malloc(sizeof(ResolvedBag) + (entry_count * sizeof(ResolvedBag::Entry))))};
Ryan Mitchell155d5392020-02-10 13:35:24 -08001246
1247 bool sort_entries = false;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001248 for (auto new_entry = new_bag->entries; map_entry != map_entry_end; ++map_entry) {
1249 if (UNLIKELY(!map_entry)) {
1250 return base::unexpected(IOError::PAGES_MISSING);
1251 }
1252
Adam Lesinskida431a22016-12-29 16:08:16 -05001253 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001254 if (!is_internal_resid(new_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -05001255 // Attributes, arrays, etc don't have a resource id as the name. They specify
1256 // other data, which would be wrong to change via a lookup.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001257 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001258 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
1259 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001260 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001261 }
1262 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001263
1264 new_entry->cookie = entry->cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -05001265 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001266 new_entry->key_pool = nullptr;
1267 new_entry->type_pool = nullptr;
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001268 new_entry->style = resid;
Adam Lesinski30080e22017-10-16 16:18:09 -07001269 new_entry->value.copyFrom_dtoh(map_entry->value);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001270 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1271 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001272 LOG(ERROR) << base::StringPrintf(
1273 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
1274 new_entry->value.data, new_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001275 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001276 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001277
Ryan Mitchell155d5392020-02-10 13:35:24 -08001278 sort_entries = sort_entries ||
1279 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001280 ++new_entry;
1281 }
Ryan Mitchell155d5392020-02-10 13:35:24 -08001282
1283 if (sort_entries) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001284 std::sort(new_bag->entries, new_bag->entries + entry_count,
1285 [](auto&& lhs, auto&& rhs) { return lhs.key < rhs.key; });
Ryan Mitchell155d5392020-02-10 13:35:24 -08001286 }
1287
Ryan Mitchell80094e32020-11-16 23:08:18 +00001288 new_bag->type_spec_flags = entry->type_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001289 new_bag->entry_count = static_cast<uint32_t>(entry_count);
1290 ResolvedBag* result = new_bag.get();
1291 cached_bags_[resid] = std::move(new_bag);
1292 return result;
1293 }
1294
Adam Lesinskida431a22016-12-29 16:08:16 -05001295 // In case the parent is a dynamic reference, resolve it.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001296 entry->dynamic_ref_table->lookupResourceId(&parent_resid);
Adam Lesinskida431a22016-12-29 16:08:16 -05001297
Adam Lesinski7ad11102016-10-28 16:39:15 -07001298 // Get the parent and do a merge of the keys.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001299 const auto parent_bag = GetBag(parent_resid, child_resids);
1300 if (UNLIKELY(!parent_bag.has_value())) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001301 // Failed to get the parent that should exist.
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001302 LOG(ERROR) << base::StringPrintf("Failed to find parent 0x%08x of bag 0x%08x.", parent_resid,
1303 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001304 return base::unexpected(parent_bag.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001305 }
1306
Adam Lesinski7ad11102016-10-28 16:39:15 -07001307 // Create the max possible entries we can make. Once we construct the bag,
1308 // we will realloc to fit to size.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001309 const size_t max_count = (*parent_bag)->entry_count + dtohl(map->count);
George Burgess IV09b119f2017-07-25 15:00:04 -07001310 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
1311 malloc(sizeof(ResolvedBag) + (max_count * sizeof(ResolvedBag::Entry))))};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001312 ResolvedBag::Entry* new_entry = new_bag->entries;
1313
Ryan Mitchell80094e32020-11-16 23:08:18 +00001314 const ResolvedBag::Entry* parent_entry = (*parent_bag)->entries;
1315 const ResolvedBag::Entry* const parent_entry_end = parent_entry + (*parent_bag)->entry_count;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001316
1317 // The keys are expected to be in sorted order. Merge the two bags.
Ryan Mitchell155d5392020-02-10 13:35:24 -08001318 bool sort_entries = false;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001319 while (map_entry != map_entry_end && parent_entry != parent_entry_end) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001320 if (UNLIKELY(!map_entry)) {
1321 return base::unexpected(IOError::PAGES_MISSING);
1322 }
1323
Adam Lesinskida431a22016-12-29 16:08:16 -05001324 uint32_t child_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001325 if (!is_internal_resid(child_key)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001326 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&child_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001327 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", child_key,
1328 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001329 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001330 }
1331 }
1332
Adam Lesinski7ad11102016-10-28 16:39:15 -07001333 if (child_key <= parent_entry->key) {
1334 // Use the child key if it comes before the parent
1335 // or is equal to the parent (overrides).
Ryan Mitchell80094e32020-11-16 23:08:18 +00001336 new_entry->cookie = entry->cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001337 new_entry->key = child_key;
1338 new_entry->key_pool = nullptr;
1339 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -07001340 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001341 new_entry->style = resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001342 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1343 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001344 LOG(ERROR) << base::StringPrintf(
1345 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
1346 new_entry->value.data, child_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001347 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001348 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001349 ++map_entry;
1350 } else {
1351 // Take the parent entry as-is.
1352 memcpy(new_entry, parent_entry, sizeof(*new_entry));
1353 }
1354
Ryan Mitchell155d5392020-02-10 13:35:24 -08001355 sort_entries = sort_entries ||
1356 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001357 if (child_key >= parent_entry->key) {
1358 // Move to the next parent entry if we used it or it was overridden.
1359 ++parent_entry;
1360 }
1361 // Increment to the next entry to fill.
1362 ++new_entry;
1363 }
1364
1365 // Finish the child entries if they exist.
1366 while (map_entry != map_entry_end) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001367 if (UNLIKELY(!map_entry)) {
1368 return base::unexpected(IOError::PAGES_MISSING);
1369 }
1370
Adam Lesinskida431a22016-12-29 16:08:16 -05001371 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001372 if (!is_internal_resid(new_key)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001373 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001374 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
1375 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001376 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001377 }
1378 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001379 new_entry->cookie = entry->cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -05001380 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001381 new_entry->key_pool = nullptr;
1382 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -07001383 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001384 new_entry->style = resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001385 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1386 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001387 LOG(ERROR) << base::StringPrintf("Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.",
1388 new_entry->value.dataType, new_entry->value.data, new_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001389 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001390 }
Ryan Mitchell155d5392020-02-10 13:35:24 -08001391 sort_entries = sort_entries ||
1392 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001393 ++map_entry;
1394 ++new_entry;
1395 }
1396
1397 // Finish the parent entries if they exist.
1398 if (parent_entry != parent_entry_end) {
1399 // Take the rest of the parent entries as-is.
1400 const size_t num_entries_to_copy = parent_entry_end - parent_entry;
1401 memcpy(new_entry, parent_entry, num_entries_to_copy * sizeof(*new_entry));
1402 new_entry += num_entries_to_copy;
1403 }
1404
1405 // Resize the resulting array to fit.
1406 const size_t actual_count = new_entry - new_bag->entries;
1407 if (actual_count != max_count) {
George Burgess IV09b119f2017-07-25 15:00:04 -07001408 new_bag.reset(reinterpret_cast<ResolvedBag*>(realloc(
1409 new_bag.release(), sizeof(ResolvedBag) + (actual_count * sizeof(ResolvedBag::Entry)))));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001410 }
1411
Ryan Mitchell155d5392020-02-10 13:35:24 -08001412 if (sort_entries) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001413 std::sort(new_bag->entries, new_bag->entries + actual_count,
1414 [](auto&& lhs, auto&& rhs) { return lhs.key < rhs.key; });
Ryan Mitchell155d5392020-02-10 13:35:24 -08001415 }
1416
Adam Lesinski1a1e9c22017-10-13 15:45:34 -07001417 // Combine flags from the parent and our own bag.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001418 new_bag->type_spec_flags = entry->type_flags | (*parent_bag)->type_spec_flags;
George Burgess IV09b119f2017-07-25 15:00:04 -07001419 new_bag->entry_count = static_cast<uint32_t>(actual_count);
1420 ResolvedBag* result = new_bag.get();
1421 cached_bags_[resid] = std::move(new_bag);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001422 return result;
1423}
1424
Yurii Zubrytskyia5775142022-11-02 17:49:49 -07001425static bool Utf8ToUtf16(StringPiece str, std::u16string* out) {
Adam Lesinski929d6512017-01-16 19:11:19 -08001426 ssize_t len =
1427 utf8_to_utf16_length(reinterpret_cast<const uint8_t*>(str.data()), str.size(), false);
1428 if (len < 0) {
1429 return false;
1430 }
1431 out->resize(static_cast<size_t>(len));
1432 utf8_to_utf16(reinterpret_cast<const uint8_t*>(str.data()), str.size(), &*out->begin(),
1433 static_cast<size_t>(len + 1));
1434 return true;
1435}
1436
Ryan Mitchell80094e32020-11-16 23:08:18 +00001437base::expected<uint32_t, NullOrIOError> AssetManager2::GetResourceId(
1438 const std::string& resource_name, const std::string& fallback_type,
1439 const std::string& fallback_package) const {
Adam Lesinski929d6512017-01-16 19:11:19 -08001440 StringPiece package_name, type, entry;
1441 if (!ExtractResourceName(resource_name, &package_name, &type, &entry)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001442 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001443 }
1444
1445 if (entry.empty()) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001446 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001447 }
1448
1449 if (package_name.empty()) {
1450 package_name = fallback_package;
1451 }
1452
1453 if (type.empty()) {
1454 type = fallback_type;
1455 }
1456
1457 std::u16string type16;
1458 if (!Utf8ToUtf16(type, &type16)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001459 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001460 }
1461
1462 std::u16string entry16;
1463 if (!Utf8ToUtf16(entry, &entry16)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001464 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001465 }
1466
1467 const StringPiece16 kAttr16 = u"attr";
1468 const static std::u16string kAttrPrivate16 = u"^attr-private";
1469
1470 for (const PackageGroup& package_group : package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001471 for (const ConfiguredPackage& package_impl : package_group.packages_) {
1472 const LoadedPackage* package = package_impl.loaded_package_;
Adam Lesinski929d6512017-01-16 19:11:19 -08001473 if (package_name != package->GetPackageName()) {
1474 // All packages in the same group are expected to have the same package name.
1475 break;
1476 }
1477
Ryan Mitchell80094e32020-11-16 23:08:18 +00001478 base::expected<uint32_t, NullOrIOError> resid = package->FindEntryByName(type16, entry16);
1479 if (UNLIKELY(IsIOError(resid))) {
1480 return base::unexpected(resid.error());
1481 }
1482
1483 if (!resid.has_value() && kAttr16 == type16) {
Adam Lesinski929d6512017-01-16 19:11:19 -08001484 // Private attributes in libraries (such as the framework) are sometimes encoded
1485 // under the type '^attr-private' in order to leave the ID space of public 'attr'
1486 // free for future additions. Check '^attr-private' for the same name.
1487 resid = package->FindEntryByName(kAttrPrivate16, entry16);
1488 }
1489
Ryan Mitchell80094e32020-11-16 23:08:18 +00001490 if (resid.has_value()) {
1491 return fix_package_id(*resid, package_group.dynamic_ref_table->mAssignedPackageId);
Adam Lesinski929d6512017-01-16 19:11:19 -08001492 }
1493 }
1494 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001495 return base::unexpected(std::nullopt);
Adam Lesinski0c405242017-01-13 20:47:26 -08001496}
1497
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001498void AssetManager2::RebuildFilterList() {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001499 for (PackageGroup& group : package_groups_) {
Yurii Zubrytskyidbce3562022-11-14 22:26:10 -08001500 for (ConfiguredPackage& package : group.packages_) {
1501 package.filtered_configs_.forEachItem([](auto, auto& fcg) { fcg.type_entries.clear(); });
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001502 // Create the filters here.
Yurii Zubrytskyidbce3562022-11-14 22:26:10 -08001503 package.loaded_package_->ForEachTypeSpec([&](const TypeSpec& type_spec, uint8_t type_id) {
Yurii Zubrytskyi59dab3b2022-11-03 00:08:49 -07001504 FilteredConfigGroup* group = nullptr;
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001505 for (const auto& type_entry : type_spec.type_entries) {
Jeremy Meyerccf5cd72023-08-15 21:42:03 +00001506 for (auto & config : configurations_) {
1507 if (type_entry.config.match(config)) {
1508 if (!group) {
1509 group = &package.filtered_configs_.editItemAt(type_id - 1);
1510 }
1511 group->type_entries.push_back(&type_entry);
1512 break;
Yurii Zubrytskyi59dab3b2022-11-03 00:08:49 -07001513 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001514 }
1515 }
1516 });
Yurii Zubrytskyidbce3562022-11-14 22:26:10 -08001517 package.filtered_configs_.trimBuckets(
1518 [](const auto& fcg) { return fcg.type_entries.empty(); });
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001519 }
1520 }
1521}
1522
Adam Lesinski7ad11102016-10-28 16:39:15 -07001523void AssetManager2::InvalidateCaches(uint32_t diff) {
Yurii Zubrytskyi09144882023-06-15 23:23:15 -07001524 cached_resolved_values_.clear();
Ryan Mitchell2c4d8742019-03-04 09:41:00 -08001525
Adam Lesinski7ad11102016-10-28 16:39:15 -07001526 if (diff == 0xffffffffu) {
1527 // Everything must go.
1528 cached_bags_.clear();
Yurii Zubrytskyi09144882023-06-15 23:23:15 -07001529 cached_bag_resid_stacks_.clear();
Adam Lesinski7ad11102016-10-28 16:39:15 -07001530 return;
1531 }
1532
1533 // Be more conservative with what gets purged. Only if the bag has other possible
1534 // variations with respect to what changed (diff) should we remove it.
Yurii Zubrytskyi09144882023-06-15 23:23:15 -07001535 for (auto stack_it = cached_bag_resid_stacks_.begin();
1536 stack_it != cached_bag_resid_stacks_.end();) {
1537 const auto it = cached_bags_.find(stack_it->first);
1538 if (it == cached_bags_.end()) {
1539 stack_it = cached_bag_resid_stacks_.erase(stack_it);
1540 } else if ((diff & it->second->type_spec_flags) != 0) {
1541 cached_bags_.erase(it);
1542 stack_it = cached_bag_resid_stacks_.erase(stack_it);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001543 } else {
Yurii Zubrytskyi09144882023-06-15 23:23:15 -07001544 ++stack_it; // Keep the item in both caches.
Adam Lesinski7ad11102016-10-28 16:39:15 -07001545 }
1546 }
Ryan Mitchella45506e2020-11-16 23:08:18 +00001547
Yurii Zubrytskyi09144882023-06-15 23:23:15 -07001548 // Need to ensure that both bag caches are consistent, as we populate them in the same function.
1549 // Iterate over the cached bags to erase the items without the corresponding resid_stack cache
1550 // items.
1551 for (auto it = cached_bags_.begin(); it != cached_bags_.end();) {
1552 if ((diff & it->second->type_spec_flags) != 0) {
1553 it = cached_bags_.erase(it);
1554 } else {
1555 ++it;
1556 }
1557 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001558}
1559
Ryan Mitchell2e394222019-08-28 12:10:51 -07001560uint8_t AssetManager2::GetAssignedPackageId(const LoadedPackage* package) const {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001561 for (auto& package_group : package_groups_) {
1562 for (auto& package2 : package_group.packages_) {
1563 if (package2.loaded_package_ == package) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -07001564 return package_group.dynamic_ref_table->mAssignedPackageId;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001565 }
1566 }
1567 }
1568 return 0;
1569}
1570
Adam Lesinski30080e22017-10-16 16:18:09 -07001571std::unique_ptr<Theme> AssetManager2::NewTheme() {
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001572 constexpr size_t kInitialReserveSize = 32;
1573 auto theme = std::unique_ptr<Theme>(new Theme(this));
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001574 theme->keys_.reserve(kInitialReserveSize);
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001575 theme->entries_.reserve(kInitialReserveSize);
1576 return theme;
Adam Lesinski30080e22017-10-16 16:18:09 -07001577}
1578
Yurii Zubrytskyi9eb44c92022-11-14 23:44:52 -08001579void AssetManager2::ForEachPackage(base::function_ref<bool(const std::string&, uint8_t)> func,
1580 package_property_t excluded_property_flags) const {
1581 for (const PackageGroup& package_group : package_groups_) {
1582 const auto loaded_package = package_group.packages_.front().loaded_package_;
1583 if ((loaded_package->GetPropertyFlags() & excluded_property_flags) == 0U
1584 && !func(loaded_package->GetPackageName(),
1585 package_group.dynamic_ref_table->mAssignedPackageId)) {
1586 return;
1587 }
1588 }
1589}
1590
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -07001591AssetManager2::ScopedOperation AssetManager2::StartOperation() const {
1592 ++number_of_running_scoped_operations_;
1593 return ScopedOperation(*this);
1594}
1595
1596void AssetManager2::FinishOperation() const {
1597 if (number_of_running_scoped_operations_ < 1) {
1598 ALOGW("Invalid FinishOperation() call when there's none happening");
1599 return;
1600 }
1601 if (--number_of_running_scoped_operations_ == 0) {
1602 for (auto&& [_, assets] : apk_assets_) {
1603 assets.clear();
1604 }
1605 }
1606}
1607
1608const AssetManager2::ApkAssetsPtr& AssetManager2::GetApkAssets(ApkAssetsCookie cookie) const {
1609 DCHECK(number_of_running_scoped_operations_ > 0) << "Must have an operation running";
1610
1611 if (cookie < 0 || cookie >= apk_assets_.size()) {
1612 static const ApkAssetsPtr empty{};
1613 return empty;
1614 }
1615 auto& [wptr, res] = apk_assets_[cookie];
1616 if (!res) {
1617 res = wptr.promote();
1618 }
1619 return res;
1620}
1621
Adam Lesinski30080e22017-10-16 16:18:09 -07001622Theme::Theme(AssetManager2* asset_manager) : asset_manager_(asset_manager) {
1623}
1624
1625Theme::~Theme() = default;
1626
Yurii Zubrytskyi1e5452a2024-06-13 19:30:36 -07001627static bool IsUndefined(const Res_value& value) {
1628 // DATA_NULL_EMPTY (@empty) is a valid resource value and DATA_NULL_UNDEFINED represents
1629 // an absence of a valid value.
1630 return value.dataType == Res_value::TYPE_NULL && value.data != Res_value::DATA_NULL_EMPTY;
1631}
1632
Ryan Mitchell80094e32020-11-16 23:08:18 +00001633base::expected<std::monostate, NullOrIOError> Theme::ApplyStyle(uint32_t resid, bool force) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001634 ATRACE_NAME("Theme::ApplyStyle");
Adam Lesinski7ad11102016-10-28 16:39:15 -07001635
Ryan Mitchell80094e32020-11-16 23:08:18 +00001636 auto bag = asset_manager_->GetBag(resid);
1637 if (!bag.has_value()) {
1638 return base::unexpected(bag.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001639 }
1640
1641 // Merge the flags from this style.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001642 type_spec_flags_ |= (*bag)->type_spec_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001643
Yurii Zubrytskyi1e5452a2024-06-13 19:30:36 -07001644 //
1645 // This function is the most expensive part of applying an frro to the existing app resources,
1646 // and needs to be as efficient as possible.
1647 // The data structure we're working with is two parallel sorted arrays of keys (resource IDs)
1648 // and entries (resource value + some attributes).
1649 // The styles get applied in sequence, starting with an empty set of attributes. Each style
1650 // contains its values for the theme attributes, and gets applied in either normal or forced way:
1651 // - normal way never overrides the existing attribute, so only unique style attributes are added
1652 // - forced way overrides anything for that attribute, and if it's undefined it removes the
1653 // previous value completely
1654 //
1655 // Style attributes come in a Bag data type - a sorted array of attributes with their values. This
1656 // means we don't need to re-sort the attributes ever, and instead:
1657 // - for an already existing attribute just skip it or apply the forced value
1658 // - if the forced value is undefined, mark it undefined as well to get rid of it later
1659 // - for a new attribute append it to the array, forming a new sorted section of new attributes
1660 // past the end of the original ones (ignore undefined ones here)
1661 // - inplace merge two sorted sections to form a single sorted array again.
1662 // - run the last pass to remove all undefined elements
1663 //
1664 // Using this algorithm performs better than a repeated binary search + insert in the middle,
1665 // as that keeps shifting the tail end of the arrays and wasting CPU cycles in memcpy().
1666 //
1667 const auto starting_size = keys_.size();
1668 if (starting_size == 0) {
1669 keys_.reserve((*bag)->entry_count);
1670 entries_.reserve((*bag)->entry_count);
1671 }
1672 bool wrote_undefined = false;
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001673 for (auto it = begin(*bag); it != end(*bag); ++it) {
1674 const uint32_t attr_res_id = it->key;
Adam Lesinski30080e22017-10-16 16:18:09 -07001675 // If the resource ID passed in is not a style, the key can be some other identifier that is not
1676 // a resource ID. We should fail fast instead of operating with strange resource IDs.
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001677 if (!is_valid_resid(attr_res_id)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001678 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001679 }
Yurii Zubrytskyi1e5452a2024-06-13 19:30:36 -07001680 const bool is_undefined = IsUndefined(it->value);
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001681 if (!force && is_undefined) {
1682 continue;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001683 }
Yurii Zubrytskyi1e5452a2024-06-13 19:30:36 -07001684 const auto key_it = std::lower_bound(keys_.begin(), keys_.begin() + starting_size, attr_res_id);
1685 if (key_it != keys_.begin() + starting_size && *key_it == attr_res_id) {
1686 const auto entry_it = entries_.begin() + (key_it - keys_.begin());
1687 if (force || IsUndefined(entry_it->value)) {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001688 *entry_it = Entry{it->cookie, (*bag)->type_spec_flags, it->value};
Yurii Zubrytskyi1e5452a2024-06-13 19:30:36 -07001689 wrote_undefined |= is_undefined;
Adam Lesinski30080e22017-10-16 16:18:09 -07001690 }
Yurii Zubrytskyi1e5452a2024-06-13 19:30:36 -07001691 } else if (!is_undefined) {
1692 keys_.emplace_back(attr_res_id);
1693 entries_.emplace_back(it->cookie, (*bag)->type_spec_flags, it->value);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001694 }
1695 }
Yurii Zubrytskyi1e5452a2024-06-13 19:30:36 -07001696
1697 if (starting_size && keys_.size() != starting_size) {
1698 std::inplace_merge(
1699 CombinedIterator(keys_.begin(), entries_.begin()),
1700 CombinedIterator(keys_.begin() + starting_size, entries_.begin() + starting_size),
1701 CombinedIterator(keys_.end(), entries_.end()));
1702 }
1703 if (wrote_undefined) {
1704 auto new_end = std::remove_if(CombinedIterator(keys_.begin(), entries_.begin()),
1705 CombinedIterator(keys_.end(), entries_.end()),
1706 [](const auto& pair) { return IsUndefined(pair.second.value); });
1707 keys_.erase(new_end.it1, keys_.end());
1708 entries_.erase(new_end.it2, entries_.end());
1709 }
1710 if (android::base::kEnableDChecks && !std::is_sorted(keys_.begin(), keys_.end())) {
1711 ALOGW("Bag %u was unsorted in the apk?", unsigned(resid));
1712 return base::unexpected(std::nullopt);
1713 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001714 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001715}
1716
Ryan Mitchell767e34f2021-06-07 12:29:05 -07001717void Theme::Rebase(AssetManager2* am, const uint32_t* style_ids, const uint8_t* force,
1718 size_t style_count) {
1719 ATRACE_NAME("Theme::Rebase");
1720 // Reset the entries without changing the vector capacity to prevent reallocations during
1721 // ApplyStyle.
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001722 keys_.clear();
Ryan Mitchell767e34f2021-06-07 12:29:05 -07001723 entries_.clear();
1724 asset_manager_ = am;
1725 for (size_t i = 0; i < style_count; i++) {
1726 ApplyStyle(style_ids[i], force[i]);
1727 }
1728}
1729
Ryan Mitchell80094e32020-11-16 23:08:18 +00001730std::optional<AssetManager2::SelectedValue> Theme::GetAttribute(uint32_t resid) const {
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001731 constexpr const uint32_t kMaxIterations = 20;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001732 uint32_t type_spec_flags = 0u;
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001733 for (uint32_t i = 0; i <= kMaxIterations; i++) {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001734 const auto key_it = std::lower_bound(keys_.begin(), keys_.end(), resid);
1735 if (key_it == keys_.end() || *key_it != resid) {
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001736 return std::nullopt;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001737 }
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001738 const auto entry_it = entries_.begin() + (key_it - keys_.begin());
Yurii Zubrytskyi1e5452a2024-06-13 19:30:36 -07001739 if (IsUndefined(entry_it->value)) {
1740 return std::nullopt;
1741 }
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001742 type_spec_flags |= entry_it->type_spec_flags;
1743 if (entry_it->value.dataType == Res_value::TYPE_ATTRIBUTE) {
1744 resid = entry_it->value.data;
1745 continue;
1746 }
1747
1748 return AssetManager2::SelectedValue(entry_it->value.dataType, entry_it->value.data,
1749 entry_it->cookie, type_spec_flags, 0U /* resid */,
1750 {} /* config */);
1751 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001752 return std::nullopt;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001753}
1754
Ryan Mitchell80094e32020-11-16 23:08:18 +00001755base::expected<std::monostate, NullOrIOError> Theme::ResolveAttributeReference(
1756 AssetManager2::SelectedValue& value) const {
1757 if (value.type != Res_value::TYPE_ATTRIBUTE) {
1758 return asset_manager_->ResolveReference(value);
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001759 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001760
1761 std::optional<AssetManager2::SelectedValue> result = GetAttribute(value.data);
1762 if (!result.has_value()) {
1763 return base::unexpected(std::nullopt);
1764 }
1765
Ryan Mitchella45506e2020-11-16 23:08:18 +00001766 auto resolve_result = asset_manager_->ResolveReference(*result, true /* cache_value */);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001767 if (resolve_result.has_value()) {
1768 result->flags |= value.flags;
1769 value = *result;
1770 }
1771 return resolve_result;
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001772}
1773
Adam Lesinski7ad11102016-10-28 16:39:15 -07001774void Theme::Clear() {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001775 keys_.clear();
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001776 entries_.clear();
Adam Lesinski7ad11102016-10-28 16:39:15 -07001777}
1778
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001779base::expected<std::monostate, IOError> Theme::SetTo(const Theme& source) {
1780 if (this == &source) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001781 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001782 }
1783
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001784 type_spec_flags_ = source.type_spec_flags_;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001785
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001786 if (asset_manager_ == source.asset_manager_) {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001787 keys_ = source.keys_;
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001788 entries_ = source.entries_;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001789 } else {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001790 std::unordered_map<ApkAssetsCookie, ApkAssetsCookie> src_to_dest_asset_cookies;
1791 using SourceToDestinationRuntimePackageMap = std::unordered_map<int, int>;
1792 std::unordered_map<ApkAssetsCookie, SourceToDestinationRuntimePackageMap> src_asset_cookie_id_map;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001793
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -07001794 auto op_src = source.asset_manager_->StartOperation();
1795 auto op_dst = asset_manager_->StartOperation();
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001796
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -07001797 for (size_t i = 0; i < source.asset_manager_->GetApkAssetsCount(); i++) {
1798 const auto& src_asset = source.asset_manager_->GetApkAssets(i);
1799 if (!src_asset) {
Yurii Zubrytskyib3455192023-05-01 14:35:48 -07001800 continue;
1801 }
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -07001802 for (int j = 0; j < asset_manager_->GetApkAssetsCount(); j++) {
1803 const auto& dest_asset = asset_manager_->GetApkAssets(j);
Ryan Mitchellef538432021-03-01 14:52:14 -08001804 if (src_asset != dest_asset) {
1805 // ResourcesManager caches and reuses ApkAssets when the same apk must be present in
1806 // multiple AssetManagers. Two ApkAssets point to the same version of the same resources
1807 // if they are the same instance.
1808 continue;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001809 }
Ryan Mitchellef538432021-03-01 14:52:14 -08001810
1811 // Map the package ids of the asset in the source AssetManager to the package ids of the
1812 // asset in th destination AssetManager.
1813 SourceToDestinationRuntimePackageMap package_map;
1814 for (const auto& loaded_package : src_asset->GetLoadedArsc()->GetPackages()) {
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001815 const int src_package_id = source.asset_manager_->GetAssignedPackageId(
1816 loaded_package.get());
Ryan Mitchellef538432021-03-01 14:52:14 -08001817 const int dest_package_id = asset_manager_->GetAssignedPackageId(loaded_package.get());
1818 package_map[src_package_id] = dest_package_id;
1819 }
1820
1821 src_to_dest_asset_cookies.insert(std::make_pair(i, j));
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001822 src_asset_cookie_id_map.insert(std::make_pair(i, std::move(package_map)));
Ryan Mitchellef538432021-03-01 14:52:14 -08001823 break;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001824 }
1825 }
1826
Ryan Mitchell93bca972019-03-08 17:26:28 -08001827 // Reset the data in the destination theme.
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001828 keys_.clear();
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001829 entries_.clear();
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001830
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001831 for (size_t i = 0, size = source.entries_.size(); i != size; ++i) {
1832 const auto& entry = source.entries_[i];
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001833 bool is_reference = (entry.value.dataType == Res_value::TYPE_ATTRIBUTE
1834 || entry.value.dataType == Res_value::TYPE_REFERENCE
1835 || entry.value.dataType == Res_value::TYPE_DYNAMIC_ATTRIBUTE
1836 || entry.value.dataType == Res_value::TYPE_DYNAMIC_REFERENCE)
1837 && entry.value.data != 0x0;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001838
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001839 // If the attribute value represents an attribute or reference, the package id of the
1840 // value needs to be rewritten to the package id of the value in the destination.
1841 uint32_t attribute_data = entry.value.data;
1842 if (is_reference) {
1843 // Determine the package id of the reference in the destination AssetManager.
1844 auto value_package_map = src_asset_cookie_id_map.find(entry.cookie);
1845 if (value_package_map == src_asset_cookie_id_map.end()) {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001846 continue;
1847 }
1848
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001849 auto value_dest_package = value_package_map->second.find(
1850 get_package_id(entry.value.data));
1851 if (value_dest_package == value_package_map->second.end()) {
1852 continue;
1853 }
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001854
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001855 attribute_data = fix_package_id(entry.value.data, value_dest_package->second);
1856 }
Ryan Mitchellb85d9b22018-11-19 12:11:38 -08001857
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001858 // Find the cookie of the value in the destination. If the source apk is not loaded in the
1859 // destination, only copy resources that do not reference resources in the source.
1860 ApkAssetsCookie data_dest_cookie;
1861 auto value_dest_cookie = src_to_dest_asset_cookies.find(entry.cookie);
1862 if (value_dest_cookie != src_to_dest_asset_cookies.end()) {
1863 data_dest_cookie = value_dest_cookie->second;
1864 } else {
1865 if (is_reference || entry.value.dataType == Res_value::TYPE_STRING) {
1866 continue;
1867 } else {
1868 data_dest_cookie = 0x0;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001869 }
1870 }
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001871
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001872 const auto source_res_id = source.keys_[i];
1873
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001874 // The package id of the attribute needs to be rewritten to the package id of the
1875 // attribute in the destination.
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001876 int attribute_dest_package_id = get_package_id(source_res_id);
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001877 if (attribute_dest_package_id != 0x01) {
1878 // Find the cookie of the attribute resource id in the source AssetManager
1879 base::expected<FindEntryResult, NullOrIOError> attribute_entry_result =
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001880 source.asset_manager_->FindEntry(source_res_id, 0 /* density_override */ ,
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001881 true /* stop_at_first_match */,
1882 true /* ignore_configuration */);
1883 if (UNLIKELY(IsIOError(attribute_entry_result))) {
1884 return base::unexpected(GetIOError(attribute_entry_result.error()));
1885 }
1886 if (!attribute_entry_result.has_value()) {
1887 continue;
1888 }
1889
1890 // Determine the package id of the attribute in the destination AssetManager.
1891 auto attribute_package_map = src_asset_cookie_id_map.find(
1892 attribute_entry_result->cookie);
1893 if (attribute_package_map == src_asset_cookie_id_map.end()) {
1894 continue;
1895 }
1896 auto attribute_dest_package = attribute_package_map->second.find(
1897 attribute_dest_package_id);
1898 if (attribute_dest_package == attribute_package_map->second.end()) {
1899 continue;
1900 }
1901 attribute_dest_package_id = attribute_dest_package->second;
1902 }
1903
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001904 auto dest_attr_id = make_resid(attribute_dest_package_id, get_type_id(source_res_id),
1905 get_entry_id(source_res_id));
1906 const auto key_it = std::lower_bound(keys_.begin(), keys_.end(), dest_attr_id);
1907 const auto entry_it = entries_.begin() + (key_it - keys_.begin());
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001908 // Since the entries were cleared, the attribute resource id has yet been mapped to any value.
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001909 keys_.insert(key_it, dest_attr_id);
1910 entries_.insert(entry_it, Entry{data_dest_cookie, entry.type_spec_flags,
1911 Res_value{.dataType = entry.value.dataType,
1912 .data = attribute_data}});
Adam Lesinski7ad11102016-10-28 16:39:15 -07001913 }
1914 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001915 return {};
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001916}
1917
1918void Theme::Dump() const {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001919 LOG(INFO) << base::StringPrintf("Theme(this=%p, AssetManager2=%p)", this, asset_manager_);
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001920 for (size_t i = 0, size = keys_.size(); i != size; ++i) {
1921 auto res_id = keys_[i];
1922 const auto& entry = entries_[i];
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001923 LOG(INFO) << base::StringPrintf(" entry(0x%08x)=(0x%08x) type=(0x%02x), cookie(%d)",
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001924 res_id, entry.value.data, entry.value.dataType,
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001925 entry.cookie);
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001926 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001927}
1928
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -07001929AssetManager2::ScopedOperation::ScopedOperation(const AssetManager2& am) : am_(am) {
1930}
1931
1932AssetManager2::ScopedOperation::~ScopedOperation() {
1933 am_.FinishOperation();
1934}
1935
Adam Lesinski7ad11102016-10-28 16:39:15 -07001936} // namespace android