blob: 6a955bc3f7e352c7771b642c8ff276f336b3dbe6 [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>
Adam Lesinski0c405242017-01-13 20:47:26 -080026
Adam Lesinski7ad11102016-10-28 16:39:15 -070027#include "android-base/logging.h"
28#include "android-base/stringprintf.h"
Jackal Guo552b45d2021-09-29 10:52:19 +080029#include "androidfw/ResourceTypes.h"
Ryan Mitchell8a891d82019-07-01 09:48:23 -070030#include "androidfw/ResourceUtils.h"
Ryan Mitchell31b11052019-06-13 13:47:26 -070031#include "androidfw/Util.h"
Adam Lesinski7ad11102016-10-28 16:39:15 -070032#include "utils/ByteOrder.h"
33#include "utils/Trace.h"
34
35#ifdef _WIN32
36#ifdef ERROR
37#undef ERROR
38#endif
39#endif
40
41namespace android {
42
Ryan Mitchell80094e32020-11-16 23:08:18 +000043namespace {
44
45using EntryValue = std::variant<Res_value, incfs::verified_map_ptr<ResTable_map_entry>>;
46
Eric Miao368cd192022-09-09 15:46:14 -070047/* NOTE: table_entry has been verified in LoadedPackage::GetEntryFromOffset(),
48 * and so access to ->value() and ->map_entry() are safe here
49 */
Ryan Mitchell80094e32020-11-16 23:08:18 +000050base::expected<EntryValue, IOError> GetEntryValue(
51 incfs::verified_map_ptr<ResTable_entry> table_entry) {
Eric Miao368cd192022-09-09 15:46:14 -070052 const uint16_t entry_size = table_entry->size();
Ryan Mitchell80094e32020-11-16 23:08:18 +000053
54 // Check if the entry represents a bag value.
Eric Miao368cd192022-09-09 15:46:14 -070055 if (entry_size >= sizeof(ResTable_map_entry) && table_entry->is_complex()) {
56 return table_entry.convert<ResTable_map_entry>().verified();
Ryan Mitchell80094e32020-11-16 23:08:18 +000057 }
58
Eric Miao368cd192022-09-09 15:46:14 -070059 return table_entry->value();
Ryan Mitchell80094e32020-11-16 23:08:18 +000060}
61
62} // namespace
63
Adam Lesinskibebfcc42018-02-12 14:27:46 -080064struct FindEntryResult {
Ryan Mitchell80094e32020-11-16 23:08:18 +000065 // The cookie representing the ApkAssets in which the value resides.
66 ApkAssetsCookie cookie;
67
68 // The value of the resource table entry. Either an android::Res_value for non-bag types or an
69 // incfs::verified_map_ptr<ResTable_map_entry> for bag types.
70 EntryValue entry;
Adam Lesinskibebfcc42018-02-12 14:27:46 -080071
72 // The configuration for which the resulting entry was defined. This is already swapped to host
73 // endianness.
74 ResTable_config config;
75
76 // The bitmask of configuration axis with which the resource value varies.
77 uint32_t type_flags;
78
79 // The dynamic package ID map for the package from which this resource came from.
80 const DynamicRefTable* dynamic_ref_table;
81
Ryan Mitchell8a891d82019-07-01 09:48:23 -070082 // The package name of the resource.
83 const std::string* package_name;
84
Adam Lesinskibebfcc42018-02-12 14:27:46 -080085 // The string pool reference to the type's name. This uses a different string pool than
86 // the global string pool, but this is hidden from the caller.
87 StringPoolRef type_string_ref;
88
89 // The string pool reference to the entry's name. This uses a different string pool than
90 // the global string pool, but this is hidden from the caller.
91 StringPoolRef entry_string_ref;
92};
93
Jeremy Meyer04cf00d2023-07-20 22:17:27 +000094AssetManager2::AssetManager2(ApkAssetsList apk_assets, const ResTable_config& configuration) {
95 configurations_.push_back(configuration);
96
Yurii Zubrytskyib3455192023-05-01 14:35:48 -070097 // Don't invalidate caches here as there's nothing cached yet.
98 SetApkAssets(apk_assets, false);
Adam Lesinski970bd8d2017-09-25 13:21:55 -070099}
Adam Lesinski7ad11102016-10-28 16:39:15 -0700100
Jeremy Meyer04cf00d2023-07-20 22:17:27 +0000101AssetManager2::AssetManager2() {
102 configurations_.resize(1);
103}
104
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700105bool AssetManager2::SetApkAssets(ApkAssetsList apk_assets, bool invalidate_caches) {
106 BuildDynamicRefTable(apk_assets);
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800107 RebuildFilterList();
Adam Lesinski7ad11102016-10-28 16:39:15 -0700108 if (invalidate_caches) {
109 InvalidateCaches(static_cast<uint32_t>(-1));
110 }
111 return true;
112}
113
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700114bool AssetManager2::SetApkAssets(std::initializer_list<ApkAssetsPtr> apk_assets,
115 bool invalidate_caches) {
116 return SetApkAssets(ApkAssetsList(apk_assets.begin(), apk_assets.size()), invalidate_caches);
117}
118
119void AssetManager2::BuildDynamicRefTable(ApkAssetsList apk_assets) {
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700120 auto op = StartOperation();
121
122 apk_assets_.resize(apk_assets.size());
123 for (size_t i = 0; i != apk_assets.size(); ++i) {
124 apk_assets_[i].first = apk_assets[i];
125 // Let's populate the locked assets right away as we're going to need them here later.
126 apk_assets_[i].second = apk_assets[i];
127 }
128
Adam Lesinskida431a22016-12-29 16:08:16 -0500129 package_groups_.clear();
130 package_ids_.fill(0xff);
131
Ryan Mitchellef538432021-03-01 14:52:14 -0800132 // A mapping from path of apk assets that could be target packages of overlays to the runtime
133 // package id of its first loaded package. Overlays currently can only override resources in the
134 // first package in the target resource table.
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800135 std::unordered_map<std::string_view, uint8_t> target_assets_package_ids;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700136
Ryan Mitchell824cc492020-02-12 10:48:14 -0800137 // Overlay resources are not directly referenced by an application so their resource ids
138 // can change throughout the application's lifetime. Assign overlay package ids last.
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700139 std::vector<const ApkAssets*> sorted_apk_assets;
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700140 sorted_apk_assets.reserve(apk_assets.size());
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700141 for (auto& asset : apk_assets) {
142 sorted_apk_assets.push_back(asset.get());
143 }
144 std::stable_partition(sorted_apk_assets.begin(), sorted_apk_assets.end(),
145 [](auto a) { return !a->IsOverlay(); });
Ryan Mitchell824cc492020-02-12 10:48:14 -0800146
147 // The assets cookie must map to the position of the apk assets in the unsorted apk assets list.
148 std::unordered_map<const ApkAssets*, ApkAssetsCookie> apk_assets_cookies;
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700149 apk_assets_cookies.reserve(apk_assets.size());
150 for (size_t i = 0, n = apk_assets.size(); i < n; i++) {
151 apk_assets_cookies[apk_assets[i].get()] = static_cast<ApkAssetsCookie>(i);
Ryan Mitchell824cc492020-02-12 10:48:14 -0800152 }
153
Ryan Mitchellb894c272020-02-12 10:31:44 -0800154 // 0x01 is reserved for the android package.
155 int next_package_id = 0x02;
Ryan Mitchell824cc492020-02-12 10:48:14 -0800156 for (const ApkAssets* apk_assets : sorted_apk_assets) {
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800157 std::shared_ptr<OverlayDynamicRefTable> overlay_ref_table;
158 if (auto loaded_idmap = apk_assets->GetLoadedIdmap(); loaded_idmap != nullptr) {
159 // The target package must precede the overlay package in the apk assets paths in order
160 // to take effect.
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800161 auto iter = target_assets_package_ids.find(loaded_idmap->TargetApkPath());
Ryan Mitchellef538432021-03-01 14:52:14 -0800162 if (iter == target_assets_package_ids.end()) {
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800163 LOG(INFO) << "failed to find target package for overlay "
164 << loaded_idmap->OverlayApkPath();
165 } else {
166 uint8_t target_package_id = iter->second;
167
168 // Create a special dynamic reference table for the overlay to rewrite references to
169 // overlay resources as references to the target resources they overlay.
170 overlay_ref_table = std::make_shared<OverlayDynamicRefTable>(
171 loaded_idmap->GetOverlayDynamicRefTable(target_package_id));
172
173 // Add the overlay resource map to the target package's set of overlays.
174 const uint8_t target_idx = package_ids_[target_package_id];
175 CHECK(target_idx != 0xff) << "overlay target '" << loaded_idmap->TargetApkPath()
176 << "'added to apk_assets_package_ids but does not have an"
177 << " assigned package group";
178
179 PackageGroup& target_package_group = package_groups_[target_idx];
180 target_package_group.overlays_.push_back(
181 ConfiguredOverlay{loaded_idmap->GetTargetResourcesMap(target_package_id,
182 overlay_ref_table.get()),
183 apk_assets_cookies[apk_assets]});
184 }
185 }
186
Ryan Mitchellb894c272020-02-12 10:31:44 -0800187 const LoadedArsc* loaded_arsc = apk_assets->GetLoadedArsc();
Ryan Mitchellb894c272020-02-12 10:31:44 -0800188 for (const std::unique_ptr<const LoadedPackage>& package : loaded_arsc->GetPackages()) {
189 // Get the package ID or assign one if a shared library.
190 int package_id;
191 if (package->IsDynamic()) {
192 package_id = next_package_id++;
193 } else {
194 package_id = package->GetPackageId();
Adam Lesinskida431a22016-12-29 16:08:16 -0500195 }
196
Adam Lesinskida431a22016-12-29 16:08:16 -0500197 uint8_t idx = package_ids_[package_id];
198 if (idx == 0xff) {
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800199 // Add the mapping for package ID to index if not present.
Adam Lesinskida431a22016-12-29 16:08:16 -0500200 package_ids_[package_id] = idx = static_cast<uint8_t>(package_groups_.size());
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800201 PackageGroup& new_group = package_groups_.emplace_back();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700202
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800203 if (overlay_ref_table != nullptr) {
204 // If this package is from an overlay, use a dynamic reference table that can rewrite
205 // overlay resource ids to their corresponding target resource ids.
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800206 new_group.dynamic_ref_table = std::move(overlay_ref_table);
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700207 }
208
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800209 DynamicRefTable* ref_table = new_group.dynamic_ref_table.get();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700210 ref_table->mAssignedPackageId = package_id;
211 ref_table->mAppAsLib = package->IsDynamic() && package->GetPackageId() == 0x7f;
Adam Lesinskida431a22016-12-29 16:08:16 -0500212 }
Adam Lesinskida431a22016-12-29 16:08:16 -0500213
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800214 // Add the package to the set of packages with the same ID.
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800215 PackageGroup* package_group = &package_groups_[idx];
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800216 package_group->packages_.emplace_back().loaded_package_ = package.get();
Ryan Mitchell824cc492020-02-12 10:48:14 -0800217 package_group->cookies_.push_back(apk_assets_cookies[apk_assets]);
Adam Lesinskida431a22016-12-29 16:08:16 -0500218
219 // Add the package name -> build time ID mappings.
220 for (const DynamicPackageEntry& entry : package->GetDynamicPackageMap()) {
221 String16 package_name(entry.package_name.c_str(), entry.package_name.size());
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700222 package_group->dynamic_ref_table->mEntries.replaceValueFor(
Adam Lesinskida431a22016-12-29 16:08:16 -0500223 package_name, static_cast<uint8_t>(entry.package_id));
224 }
Ryan Mitchellb894c272020-02-12 10:31:44 -0800225
Ryan Mitchellef538432021-03-01 14:52:14 -0800226 if (auto apk_assets_path = apk_assets->GetPath()) {
227 // Overlay target ApkAssets must have been created using path based load apis.
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800228 target_assets_package_ids.emplace(*apk_assets_path, package_id);
Ryan Mitchellef538432021-03-01 14:52:14 -0800229 }
Adam Lesinskida431a22016-12-29 16:08:16 -0500230 }
231 }
232
233 // Now assign the runtime IDs so that we have a build-time to runtime ID map.
Yurii Zubrytskyi59dab3b2022-11-03 00:08:49 -0700234 DynamicRefTable::AliasMap aliases;
235 for (const auto& group : package_groups_) {
236 const std::string& package_name = group.packages_[0].loaded_package_->GetPackageName();
237 const auto name_16 = String16(package_name.c_str(), package_name.size());
238 for (auto&& inner_group : package_groups_) {
239 inner_group.dynamic_ref_table->addMapping(name_16,
240 group.dynamic_ref_table->mAssignedPackageId);
Adam Lesinskida431a22016-12-29 16:08:16 -0500241 }
Yurii Zubrytskyi59dab3b2022-11-03 00:08:49 -0700242
243 for (const auto& package : group.packages_) {
244 const auto& package_aliases = package.loaded_package_->GetAliasResourceIdMap();
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800245 aliases.insert(aliases.end(), package_aliases.begin(), package_aliases.end());
Yurii Zubrytskyi59dab3b2022-11-03 00:08:49 -0700246 }
247 }
248
249 if (!aliases.empty()) {
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800250 std::sort(aliases.begin(), aliases.end(), [](auto&& l, auto&& r) { return l.first < r.first; });
251
Yurii Zubrytskyi59dab3b2022-11-03 00:08:49 -0700252 // Add the alias resources to the dynamic reference table of every package group. Since
253 // staging aliases can only be defined by the framework package (which is not a shared
254 // library), the compile-time package id of the framework is the same across all packages
255 // that compile against the framework.
256 for (auto& group : std::span(package_groups_.data(), package_groups_.size() - 1)) {
257 group.dynamic_ref_table->setAliases(aliases);
258 }
259 package_groups_.back().dynamic_ref_table->setAliases(std::move(aliases));
Adam Lesinskida431a22016-12-29 16:08:16 -0500260 }
261}
262
263void AssetManager2::DumpToLog() const {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800264 LOG(INFO) << base::StringPrintf("AssetManager2(this=%p)", this);
265
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700266 auto op = StartOperation();
Adam Lesinskida431a22016-12-29 16:08:16 -0500267 std::string list;
Yurii Zubrytskyi7d70bc52023-05-12 13:27:54 -0700268 for (size_t i = 0, s = apk_assets_.size(); i < s; ++i) {
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700269 const auto& assets = GetApkAssets(i);
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700270 base::StringAppendF(&list, "%s,", assets ? assets->GetDebugName().c_str() : "nullptr");
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800271 }
272 LOG(INFO) << "ApkAssets: " << list;
273
274 list = "";
Adam Lesinskida431a22016-12-29 16:08:16 -0500275 for (size_t i = 0; i < package_ids_.size(); i++) {
276 if (package_ids_[i] != 0xff) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800277 base::StringAppendF(&list, "%02x -> %d, ", (int)i, package_ids_[i]);
Adam Lesinskida431a22016-12-29 16:08:16 -0500278 }
279 }
280 LOG(INFO) << "Package ID map: " << list;
281
Adam Lesinski0dd36992018-01-25 15:38:38 -0800282 for (const auto& package_group: package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800283 list = "";
284 for (const auto& package : package_group.packages_) {
285 const LoadedPackage* loaded_package = package.loaded_package_;
286 base::StringAppendF(&list, "%s(%02x%s), ", loaded_package->GetPackageName().c_str(),
287 loaded_package->GetPackageId(),
288 (loaded_package->IsDynamic() ? " dynamic" : ""));
289 }
290 LOG(INFO) << base::StringPrintf("PG (%02x): ",
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700291 package_group.dynamic_ref_table->mAssignedPackageId)
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800292 << list;
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800293
294 for (size_t i = 0; i < 256; i++) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700295 if (package_group.dynamic_ref_table->mLookupTable[i] != 0) {
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800296 LOG(INFO) << base::StringPrintf(" e[0x%02x] -> 0x%02x", (uint8_t) i,
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700297 package_group.dynamic_ref_table->mLookupTable[i]);
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800298 }
299 }
Adam Lesinskida431a22016-12-29 16:08:16 -0500300 }
301}
Adam Lesinski7ad11102016-10-28 16:39:15 -0700302
303const ResStringPool* AssetManager2::GetStringPoolForCookie(ApkAssetsCookie cookie) const {
304 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
305 return nullptr;
306 }
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700307 auto op = StartOperation();
308 const auto& assets = GetApkAssets(cookie);
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700309 return assets ? assets->GetLoadedArsc()->GetStringPool() : nullptr;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700310}
311
Adam Lesinskida431a22016-12-29 16:08:16 -0500312const DynamicRefTable* AssetManager2::GetDynamicRefTableForPackage(uint32_t package_id) const {
313 if (package_id >= package_ids_.size()) {
314 return nullptr;
315 }
316
317 const size_t idx = package_ids_[package_id];
318 if (idx == 0xff) {
319 return nullptr;
320 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700321 return package_groups_[idx].dynamic_ref_table.get();
Adam Lesinskida431a22016-12-29 16:08:16 -0500322}
323
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700324std::shared_ptr<const DynamicRefTable> AssetManager2::GetDynamicRefTableForCookie(
325 ApkAssetsCookie cookie) const {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800326 for (const PackageGroup& package_group : package_groups_) {
327 for (const ApkAssetsCookie& package_cookie : package_group.cookies_) {
328 if (package_cookie == cookie) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700329 return package_group.dynamic_ref_table;
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800330 }
331 }
332 }
333 return nullptr;
334}
335
MÃ¥rten Kongstadc92c4dd2019-02-05 01:29:59 +0100336const std::unordered_map<std::string, std::string>*
337 AssetManager2::GetOverlayableMapForPackage(uint32_t package_id) const {
338
339 if (package_id >= package_ids_.size()) {
340 return nullptr;
341 }
342
343 const size_t idx = package_ids_[package_id];
344 if (idx == 0xff) {
345 return nullptr;
346 }
347
348 const PackageGroup& package_group = package_groups_[idx];
Ryan Mitchell80094e32020-11-16 23:08:18 +0000349 if (package_group.packages_.empty()) {
MÃ¥rten Kongstadc92c4dd2019-02-05 01:29:59 +0100350 return nullptr;
351 }
352
353 const auto loaded_package = package_group.packages_[0].loaded_package_;
354 return &loaded_package->GetOverlayableMap();
355}
356
Yurii Zubrytskyia5775142022-11-02 17:49:49 -0700357bool AssetManager2::GetOverlayablesToString(android::StringPiece package_name,
Ryan Mitchell2e394222019-08-28 12:10:51 -0700358 std::string* out) const {
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700359 auto op = StartOperation();
Ryan Mitchell2e394222019-08-28 12:10:51 -0700360 uint8_t package_id = 0U;
Yurii Zubrytskyi7d70bc52023-05-12 13:27:54 -0700361 for (size_t i = 0, s = apk_assets_.size(); i != s; ++i) {
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700362 const auto& assets = GetApkAssets(i);
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700363 if (!assets) {
364 continue;
365 }
366 const LoadedArsc* loaded_arsc = assets->GetLoadedArsc();
Ryan Mitchell2e394222019-08-28 12:10:51 -0700367 if (loaded_arsc == nullptr) {
368 continue;
369 }
370
371 const auto& loaded_packages = loaded_arsc->GetPackages();
372 if (loaded_packages.empty()) {
373 continue;
374 }
375
376 const auto& loaded_package = loaded_packages[0];
377 if (loaded_package->GetPackageName() == package_name) {
378 package_id = GetAssignedPackageId(loaded_package.get());
379 break;
380 }
381 }
382
383 if (package_id == 0U) {
384 ANDROID_LOG(ERROR) << base::StringPrintf("No package with name '%s", package_name.data());
385 return false;
386 }
387
388 const size_t idx = package_ids_[package_id];
389 if (idx == 0xff) {
390 return false;
391 }
392
393 std::string output;
394 for (const ConfiguredPackage& package : package_groups_[idx].packages_) {
395 const LoadedPackage* loaded_package = package.loaded_package_;
396 for (auto it = loaded_package->begin(); it != loaded_package->end(); it++) {
397 const OverlayableInfo* info = loaded_package->GetOverlayableInfo(*it);
398 if (info != nullptr) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000399 auto res_name = GetResourceName(*it);
400 if (!res_name.has_value()) {
Ryan Mitchell2e394222019-08-28 12:10:51 -0700401 ANDROID_LOG(ERROR) << base::StringPrintf(
402 "Unable to retrieve name of overlayable resource 0x%08x", *it);
403 return false;
404 }
405
Ryan Mitchell80094e32020-11-16 23:08:18 +0000406 const std::string name = ToFormattedResourceString(*res_name);
Ryan Mitchell2e394222019-08-28 12:10:51 -0700407 output.append(base::StringPrintf(
408 "resource='%s' overlayable='%s' actor='%s' policy='0x%08x'\n",
Yurii Zubrytskyi9d225372022-11-29 11:12:18 -0800409 name.c_str(), info->name.data(), info->actor.data(), info->policy_flags));
Ryan Mitchell2e394222019-08-28 12:10:51 -0700410 }
411 }
412 }
413
414 *out = std::move(output);
415 return true;
416}
417
Ryan Mitchell192400c2020-04-02 09:54:23 -0700418bool AssetManager2::ContainsAllocatedTable() const {
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700419 auto op = StartOperation();
Yurii Zubrytskyi7d70bc52023-05-12 13:27:54 -0700420 for (size_t i = 0, s = apk_assets_.size(); i != s; ++i) {
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700421 const auto& assets = GetApkAssets(i);
422 if (assets && assets->IsTableAllocated()) {
423 return true;
424 }
425 }
426 return false;
Ryan Mitchell192400c2020-04-02 09:54:23 -0700427}
428
Jeremy Meyer04cf00d2023-07-20 22:17:27 +0000429void AssetManager2::SetConfigurations(std::vector<ResTable_config> configurations) {
430 int diff = 0;
431 if (configurations_.size() != configurations.size()) {
432 diff = -1;
433 } else {
434 for (int i = 0; i < configurations_.size(); i++) {
435 diff |= configurations_[i].diff(configurations[i]);
436 }
437 }
438 configurations_ = std::move(configurations);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700439
440 if (diff) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800441 RebuildFilterList();
Adam Lesinski7ad11102016-10-28 16:39:15 -0700442 InvalidateCaches(static_cast<uint32_t>(diff));
443 }
444}
445
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700446std::set<AssetManager2::ApkAssetsPtr> AssetManager2::GetNonSystemOverlays() const {
447 std::set<ApkAssetsPtr> non_system_overlays;
Adam Lesinski0c405242017-01-13 20:47:26 -0800448 for (const PackageGroup& package_group : package_groups_) {
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800449 bool found_system_package = false;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800450 for (const ConfiguredPackage& package : package_group.packages_) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700451 if (package.loaded_package_->IsSystem()) {
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800452 found_system_package = true;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700453 break;
454 }
455 }
456
457 if (!found_system_package) {
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700458 auto op = StartOperation();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700459 for (const ConfiguredOverlay& overlay : package_group.overlays_) {
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700460 if (const auto& asset = GetApkAssets(overlay.cookie)) {
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700461 non_system_overlays.insert(std::move(asset));
462 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700463 }
464 }
465 }
466
467 return non_system_overlays;
468}
469
Ryan Mitchell80094e32020-11-16 23:08:18 +0000470base::expected<std::set<ResTable_config>, IOError> AssetManager2::GetResourceConfigurations(
471 bool exclude_system, bool exclude_mipmap) const {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700472 ATRACE_NAME("AssetManager::GetResourceConfigurations");
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700473 auto op = StartOperation();
474
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700475 const auto non_system_overlays =
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700476 exclude_system ? GetNonSystemOverlays() : std::set<ApkAssetsPtr>();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700477
478 std::set<ResTable_config> configurations;
479 for (const PackageGroup& package_group : package_groups_) {
480 for (size_t i = 0; i < package_group.packages_.size(); i++) {
481 const ConfiguredPackage& package = package_group.packages_[i];
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700482 if (exclude_system) {
483 if (package.loaded_package_->IsSystem()) {
484 continue;
485 }
486 if (!non_system_overlays.empty()) {
487 // Exclude overlays that target only system resources.
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700488 const auto& apk_assets = GetApkAssets(package_group.cookies_[i]);
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700489 if (apk_assets && apk_assets->IsOverlay() &&
490 non_system_overlays.find(apk_assets) == non_system_overlays.end()) {
491 continue;
492 }
493 }
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800494 }
495
Ryan Mitchell80094e32020-11-16 23:08:18 +0000496 auto result = package.loaded_package_->CollectConfigurations(exclude_mipmap, &configurations);
497 if (UNLIKELY(!result.has_value())) {
498 return base::unexpected(result.error());
499 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800500 }
501 }
502 return configurations;
503}
504
505std::set<std::string> AssetManager2::GetResourceLocales(bool exclude_system,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800506 bool merge_equivalent_languages) const {
507 ATRACE_NAME("AssetManager::GetResourceLocales");
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700508 auto op = StartOperation();
509
Adam Lesinski0c405242017-01-13 20:47:26 -0800510 std::set<std::string> locales;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700511 const auto non_system_overlays =
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700512 exclude_system ? GetNonSystemOverlays() : std::set<ApkAssetsPtr>();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700513
Adam Lesinski0c405242017-01-13 20:47:26 -0800514 for (const PackageGroup& package_group : package_groups_) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700515 for (size_t i = 0; i < package_group.packages_.size(); i++) {
516 const ConfiguredPackage& package = package_group.packages_[i];
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700517 if (exclude_system) {
518 if (package.loaded_package_->IsSystem()) {
519 continue;
520 }
521 if (!non_system_overlays.empty()) {
522 // Exclude overlays that target only system resources.
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700523 const auto& apk_assets = GetApkAssets(package_group.cookies_[i]);
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700524 if (apk_assets && apk_assets->IsOverlay() &&
525 non_system_overlays.find(apk_assets) == non_system_overlays.end()) {
526 continue;
527 }
528 }
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800529 }
530
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800531 package.loaded_package_->CollectLocales(merge_equivalent_languages, &locales);
Adam Lesinski0c405242017-01-13 20:47:26 -0800532 }
533 }
534 return locales;
535}
536
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800537std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename,
538 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700539 const std::string new_path = "assets/" + filename;
540 return OpenNonAsset(new_path, mode);
541}
542
543std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename, ApkAssetsCookie cookie,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800544 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700545 const std::string new_path = "assets/" + filename;
546 return OpenNonAsset(new_path, cookie, mode);
547}
548
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800549std::unique_ptr<AssetDir> AssetManager2::OpenDir(const std::string& dirname) const {
550 ATRACE_NAME("AssetManager::OpenDir");
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700551 auto op = StartOperation();
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800552
553 std::string full_path = "assets/" + dirname;
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700554 auto files = util::make_unique<SortedVector<AssetDir::FileInfo>>();
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800555
556 // Start from the back.
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700557 for (size_t i = apk_assets_.size(); i > 0; --i) {
558 const auto& apk_assets = GetApkAssets(i - 1);
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700559 if (!apk_assets || apk_assets->IsOverlay()) {
MÃ¥rten Kongstaddbf343b2019-02-21 07:54:18 +0100560 continue;
561 }
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800562
Yurii Zubrytskyia5775142022-11-02 17:49:49 -0700563 auto func = [&](StringPiece name, FileType type) {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800564 AssetDir::FileInfo info;
565 info.setFileName(String8(name.data(), name.size()));
566 info.setFileType(type);
Ryan Mitchellef538432021-03-01 14:52:14 -0800567 info.setSourceName(String8(apk_assets->GetDebugName().c_str()));
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800568 files->add(info);
569 };
570
Ryan Mitchellc07aa702020-03-10 13:49:12 -0700571 if (!apk_assets->GetAssetsProvider()->ForEachFile(full_path, func)) {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800572 return {};
573 }
574 }
575
576 std::unique_ptr<AssetDir> asset_dir = util::make_unique<AssetDir>();
577 asset_dir->setFileList(files.release());
578 return asset_dir;
579}
580
Adam Lesinski7ad11102016-10-28 16:39:15 -0700581// Search in reverse because that's how we used to do it and we need to preserve behaviour.
582// This is unfortunate, because ClassLoaders delegate to the parent first, so the order
583// is inconsistent for split APKs.
584std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
585 Asset::AccessMode mode,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800586 ApkAssetsCookie* out_cookie) const {
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700587 auto op = StartOperation();
588 for (size_t i = apk_assets_.size(); i > 0; i--) {
589 const auto& assets = GetApkAssets(i - 1);
MÃ¥rten Kongstaddbf343b2019-02-21 07:54:18 +0100590 // Prevent RRO from modifying assets and other entries accessed by file
591 // path. Explicitly asking for a path in a given package (denoted by a
592 // cookie) is still OK.
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700593 if (!assets || assets->IsOverlay()) {
MÃ¥rten Kongstaddbf343b2019-02-21 07:54:18 +0100594 continue;
595 }
596
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700597 std::unique_ptr<Asset> asset = assets->GetAssetsProvider()->Open(filename, mode);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700598 if (asset) {
599 if (out_cookie != nullptr) {
600 *out_cookie = i;
601 }
602 return asset;
603 }
604 }
605
606 if (out_cookie != nullptr) {
607 *out_cookie = kInvalidCookie;
608 }
609 return {};
610}
611
612std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800613 ApkAssetsCookie cookie,
614 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700615 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
616 return {};
617 }
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700618 auto op = StartOperation();
619 const auto& assets = GetApkAssets(cookie);
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700620 return assets ? assets->GetAssetsProvider()->Open(filename, mode) : nullptr;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700621}
622
Ryan Mitchell80094e32020-11-16 23:08:18 +0000623base::expected<FindEntryResult, NullOrIOError> AssetManager2::FindEntry(
624 uint32_t resid, uint16_t density_override, bool stop_at_first_match,
625 bool ignore_configuration) const {
626 const bool logging_enabled = resource_resolution_logging_enabled_;
627 if (UNLIKELY(logging_enabled)) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700628 // Clear the last logged resource resolution.
629 ResetResourceResolution();
630 last_resolution_.resid = resid;
631 }
632
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700633 auto op = StartOperation();
634
Adam Lesinski7ad11102016-10-28 16:39:15 -0700635
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700636 // Retrieve the package group from the package id of the resource id.
Ryan Mitchell80094e32020-11-16 23:08:18 +0000637 if (UNLIKELY(!is_valid_resid(resid))) {
Mark Hansenb406b0e2022-10-14 02:18:37 +0000638 LOG(ERROR) << base::StringPrintf("Invalid resource ID 0x%08x.", resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000639 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -0500640 }
641
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800642 const uint32_t package_id = get_package_id(resid);
643 const uint8_t type_idx = get_type_id(resid) - 1;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800644 const uint16_t entry_idx = get_entry_id(resid);
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700645 uint8_t package_idx = package_ids_[package_id];
Ryan Mitchell80094e32020-11-16 23:08:18 +0000646 if (UNLIKELY(package_idx == 0xff)) {
Mark Hansenb406b0e2022-10-14 02:18:37 +0000647 ANDROID_LOG(ERROR) << base::StringPrintf("No package ID %02x found for resource ID 0x%08x.",
Ryan Mitchell2fe23472019-02-27 09:43:01 -0800648 package_id, resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000649 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -0500650 }
651
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800652 const PackageGroup& package_group = package_groups_[package_idx];
Jeremy Meyer04cf00d2023-07-20 22:17:27 +0000653 std::optional<FindEntryResult> final_result;
654 bool final_has_locale = false;
655 bool final_overlaid = false;
656 for (auto & config : configurations_) {
657 // Might use this if density_override != 0.
658 ResTable_config density_override_config;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800659
Jeremy Meyer04cf00d2023-07-20 22:17:27 +0000660 // Select our configuration or generate a density override configuration.
661 const ResTable_config* desired_config = &config;
662 if (density_override != 0 && density_override != config.density) {
663 density_override_config = config;
664 density_override_config.density = density_override;
665 desired_config = &density_override_config;
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700666 }
Jeremy Meyer04cf00d2023-07-20 22:17:27 +0000667
668 auto result = FindEntryInternal(package_group, type_idx, entry_idx, *desired_config,
669 stop_at_first_match, ignore_configuration);
670 if (UNLIKELY(!result.has_value())) {
671 return base::unexpected(result.error());
672 }
673 bool overlaid = false;
674 if (!stop_at_first_match && !ignore_configuration) {
675 const auto& assets = GetApkAssets(result->cookie);
676 if (!assets) {
677 ALOGE("Found expired ApkAssets #%d for resource ID 0x%08x.", result->cookie, resid);
678 return base::unexpected(std::nullopt);
679 }
680 if (!assets->IsLoader()) {
681 for (const auto& id_map : package_group.overlays_) {
682 auto overlay_entry = id_map.overlay_res_maps_.Lookup(resid);
683 if (!overlay_entry) {
684 // No id map entry exists for this target resource.
Jeremy Meyer09158c62023-03-23 17:17:15 +0000685 continue;
686 }
Jeremy Meyer04cf00d2023-07-20 22:17:27 +0000687 if (overlay_entry.IsInlineValue()) {
688 // The target resource is overlaid by an inline value not represented by a resource.
689 ConfigDescription best_frro_config;
690 Res_value best_frro_value;
691 bool frro_found = false;
692 for( const auto& [config, value] : overlay_entry.GetInlineValue()) {
693 if ((!frro_found || config.isBetterThan(best_frro_config, desired_config))
694 && config.match(*desired_config)) {
695 frro_found = true;
696 best_frro_config = config;
697 best_frro_value = value;
698 }
699 }
700 if (!frro_found) {
701 continue;
702 }
703 result->entry = best_frro_value;
704 result->dynamic_ref_table = id_map.overlay_res_maps_.GetOverlayDynamicRefTable();
705 result->cookie = id_map.cookie;
706
707 if (UNLIKELY(logging_enabled)) {
708 last_resolution_.steps.push_back(Resolution::Step{
709 Resolution::Step::Type::OVERLAID_INLINE, result->cookie, String8()});
710 if (auto path = assets->GetPath()) {
711 const std::string overlay_path = path->data();
712 if (IsFabricatedOverlay(overlay_path)) {
713 // FRRO don't have package name so we use the creating package here.
714 String8 frro_name = String8("FRRO");
715 // Get the first part of it since the expected one should be like
716 // {overlayPackageName}-{overlayName}-{4 alphanumeric chars}.frro
717 // under /data/resource-cache/.
718 const std::string name = overlay_path.substr(overlay_path.rfind('/') + 1);
719 const size_t end = name.find('-');
720 if (frro_name.size() != overlay_path.size() && end != std::string::npos) {
721 frro_name.append(base::StringPrintf(" created by %s",
722 name.substr(0 /* pos */,
723 end).c_str()).c_str());
724 }
725 last_resolution_.best_package_name = frro_name;
726 } else {
727 last_resolution_.best_package_name = result->package_name->c_str();
728 }
729 }
730 overlaid = true;
731 }
732 continue;
733 }
734
735 auto overlay_result = FindEntry(overlay_entry.GetResourceId(), density_override,
736 false /* stop_at_first_match */,
737 false /* ignore_configuration */);
738 if (UNLIKELY(IsIOError(overlay_result))) {
739 return base::unexpected(overlay_result.error());
740 }
741 if (!overlay_result.has_value()) {
742 continue;
743 }
744
745 if (!overlay_result->config.isBetterThan(result->config, desired_config)
746 && overlay_result->config.compare(result->config) != 0) {
747 // The configuration of the entry for the overlay must be equal to or better than the
748 // target configuration to be chosen as the better value.
749 continue;
750 }
751
752 result->cookie = overlay_result->cookie;
753 result->entry = overlay_result->entry;
754 result->config = overlay_result->config;
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700755 result->dynamic_ref_table = id_map.overlay_res_maps_.GetOverlayDynamicRefTable();
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700756
757 if (UNLIKELY(logging_enabled)) {
758 last_resolution_.steps.push_back(
Jeremy Meyer04cf00d2023-07-20 22:17:27 +0000759 Resolution::Step{Resolution::Step::Type::OVERLAID, overlay_result->cookie,
760 overlay_result->config.toString()});
761 last_resolution_.best_package_name =
762 overlay_result->package_name->c_str();
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700763 overlaid = true;
764 }
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800765 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700766 }
767 }
Jeremy Meyer04cf00d2023-07-20 22:17:27 +0000768
769 bool has_locale = false;
770 if (result->config.locale == 0) {
771 if (default_locale_ != 0) {
772 ResTable_config conf;
773 conf.locale = default_locale_;
774 // Since we know conf has a locale and only a locale, match will tell us if that locale
775 // matches
776 has_locale = conf.match(config);
777 }
778 } else {
779 has_locale = true;
780 }
781
782 // if we don't have a result yet
783 if (!final_result ||
784 // or this config is better before the locale than the existing result
785 result->config.isBetterThanBeforeLocale(final_result->config, desired_config) ||
786 // or the existing config isn't better before locale and this one specifies a locale
787 // whereas the existing one doesn't
788 (!final_result->config.isBetterThanBeforeLocale(result->config, desired_config)
789 && has_locale && !final_has_locale)) {
790 final_result = result.value();
791 final_overlaid = overlaid;
792 final_has_locale = has_locale;
793 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700794 }
795
Ryan Mitchell80094e32020-11-16 23:08:18 +0000796 if (UNLIKELY(logging_enabled)) {
Jeremy Meyer04cf00d2023-07-20 22:17:27 +0000797 last_resolution_.cookie = final_result->cookie;
798 last_resolution_.type_string_ref = final_result->type_string_ref;
799 last_resolution_.entry_string_ref = final_result->entry_string_ref;
800 last_resolution_.best_config_name = final_result->config.toString();
801 if (!final_overlaid) {
802 last_resolution_.best_package_name = final_result->package_name->c_str();
Jackal Guo552b45d2021-09-29 10:52:19 +0800803 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700804 }
805
Jeremy Meyer04cf00d2023-07-20 22:17:27 +0000806 return *final_result;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700807}
808
Ryan Mitchell80094e32020-11-16 23:08:18 +0000809base::expected<FindEntryResult, NullOrIOError> AssetManager2::FindEntryInternal(
810 const PackageGroup& package_group, uint8_t type_idx, uint16_t entry_idx,
811 const ResTable_config& desired_config, bool stop_at_first_match,
812 bool ignore_configuration) const {
813 const bool logging_enabled = resource_resolution_logging_enabled_;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800814 ApkAssetsCookie best_cookie = kInvalidCookie;
815 const LoadedPackage* best_package = nullptr;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000816 incfs::verified_map_ptr<ResTable_type> best_type;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800817 const ResTable_config* best_config = nullptr;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000818 uint32_t best_offset = 0U;
819 uint32_t type_flags = 0U;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800820
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800821 // If `desired_config` is not the same as the set configuration or the caller will accept a value
822 // from any configuration, then we cannot use our filtered list of types since it only it contains
823 // types matched to the set configuration.
Jeremy Meyer04cf00d2023-07-20 22:17:27 +0000824 const bool use_filtered = !ignore_configuration && std::find_if(
825 configurations_.begin(), configurations_.end(),
826 [&desired_config](auto& value) { return &desired_config == &value; })
827 != configurations_.end();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700828 const size_t package_count = package_group.packages_.size();
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800829 for (size_t pi = 0; pi < package_count; pi++) {
830 const ConfiguredPackage& loaded_package_impl = package_group.packages_[pi];
831 const LoadedPackage* loaded_package = loaded_package_impl.loaded_package_;
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800832 const ApkAssetsCookie cookie = package_group.cookies_[pi];
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800833
834 // If the type IDs are offset in this package, we need to take that into account when searching
835 // for a type.
836 const TypeSpec* type_spec = loaded_package->GetTypeSpecByTypeIndex(type_idx);
837 if (UNLIKELY(type_spec == nullptr)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700838 continue;
839 }
840
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800841 // Allow custom loader packages to overlay resource values with configurations equivalent to the
842 // current best configuration.
843 const bool package_is_loader = loaded_package->IsCustomLoader();
844
Ryan Mitchell80094e32020-11-16 23:08:18 +0000845 auto entry_flags = type_spec->GetFlagsForEntryIndex(entry_idx);
Bernie Innocenti58cf8e32020-12-19 15:31:52 +0900846 if (UNLIKELY(!entry_flags.has_value())) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000847 return base::unexpected(entry_flags.error());
848 }
849 type_flags |= entry_flags.value();
850
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800851 const FilteredConfigGroup& filtered_group = loaded_package_impl.filtered_configs_[type_idx];
852 const size_t type_entry_count = (use_filtered) ? filtered_group.type_entries.size()
853 : type_spec->type_entries.size();
854 for (size_t i = 0; i < type_entry_count; i++) {
855 const TypeSpec::TypeEntry* type_entry = (use_filtered) ? filtered_group.type_entries[i]
856 : &type_spec->type_entries[i];
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800857
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800858 // We can skip calling ResTable_config::match() if the caller does not care for the
859 // configuration to match or if we're using the list of types that have already had their
860 // configuration matched.
861 const ResTable_config& this_config = type_entry->config;
862 if (!(use_filtered || ignore_configuration || this_config.match(desired_config))) {
863 continue;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800864 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800865
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800866 Resolution::Step::Type resolution_type;
867 if (best_config == nullptr) {
868 resolution_type = Resolution::Step::Type::INITIAL;
869 } else if (this_config.isBetterThan(*best_config, &desired_config)) {
870 resolution_type = Resolution::Step::Type::BETTER_MATCH;
871 } else if (package_is_loader && this_config.compare(*best_config) == 0) {
872 resolution_type = Resolution::Step::Type::OVERLAID;
873 } else {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000874 if (UNLIKELY(logging_enabled)) {
Jackal Guo552b45d2021-09-29 10:52:19 +0800875 last_resolution_.steps.push_back(Resolution::Step{Resolution::Step::Type::SKIPPED,
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -0700876 cookie, this_config.toString()});
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800877 }
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800878 continue;
879 }
880
881 // The configuration matches and is better than the previous selection.
882 // Find the entry value if it exists for this configuration.
883 const auto& type = type_entry->type;
884 const auto offset = LoadedPackage::GetEntryOffset(type, entry_idx);
885 if (UNLIKELY(IsIOError(offset))) {
886 return base::unexpected(offset.error());
887 }
888
889 if (!offset.has_value()) {
890 if (UNLIKELY(logging_enabled)) {
Jackal Guo552b45d2021-09-29 10:52:19 +0800891 last_resolution_.steps.push_back(Resolution::Step{Resolution::Step::Type::NO_ENTRY,
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -0700892 cookie, this_config.toString()});
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800893 }
894 continue;
895 }
896
897 best_cookie = cookie;
898 best_package = loaded_package;
899 best_type = type;
900 best_config = &this_config;
901 best_offset = offset.value();
902
903 if (UNLIKELY(logging_enabled)) {
904 last_resolution_.steps.push_back(Resolution::Step{resolution_type,
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -0700905 cookie, this_config.toString()});
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800906 }
907
908 // Any configuration will suffice, so break.
909 if (stop_at_first_match) {
910 break;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700911 }
912 }
913 }
914
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800915 if (UNLIKELY(best_cookie == kInvalidCookie)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000916 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700917 }
918
Eric Miao368cd192022-09-09 15:46:14 -0700919 auto best_entry_verified = LoadedPackage::GetEntryFromOffset(best_type, best_offset);
920 if (!best_entry_verified.has_value()) {
921 return base::unexpected(best_entry_verified.error());
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800922 }
923
Eric Miao368cd192022-09-09 15:46:14 -0700924 const auto entry = GetEntryValue(*best_entry_verified);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000925 if (!entry.has_value()) {
926 return base::unexpected(entry.error());
927 }
Winson2f3669b2019-01-11 11:28:34 -0800928
Ryan Mitchell80094e32020-11-16 23:08:18 +0000929 return FindEntryResult{
930 .cookie = best_cookie,
931 .entry = *entry,
932 .config = *best_config,
933 .type_flags = type_flags,
934 .package_name = &best_package->GetPackageName(),
935 .type_string_ref = StringPoolRef(best_package->GetTypeStringPool(), best_type->id - 1),
936 .entry_string_ref = StringPoolRef(best_package->GetKeyStringPool(),
Eric Miao368cd192022-09-09 15:46:14 -0700937 (*best_entry_verified)->key()),
Ryan Mitchell80094e32020-11-16 23:08:18 +0000938 .dynamic_ref_table = package_group.dynamic_ref_table.get(),
939 };
Adam Lesinski7ad11102016-10-28 16:39:15 -0700940}
941
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700942void AssetManager2::ResetResourceResolution() const {
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -0700943 last_resolution_ = Resolution{};
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700944}
945
Winson2f3669b2019-01-11 11:28:34 -0800946void AssetManager2::SetResourceResolutionLoggingEnabled(bool enabled) {
947 resource_resolution_logging_enabled_ = enabled;
Winson2f3669b2019-01-11 11:28:34 -0800948 if (!enabled) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700949 ResetResourceResolution();
Winson2f3669b2019-01-11 11:28:34 -0800950 }
951}
952
953std::string AssetManager2::GetLastResourceResolution() const {
954 if (!resource_resolution_logging_enabled_) {
955 LOG(ERROR) << "Must enable resource resolution logging before getting path.";
Ryan Mitchell80094e32020-11-16 23:08:18 +0000956 return {};
Winson2f3669b2019-01-11 11:28:34 -0800957 }
958
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800959 const ApkAssetsCookie cookie = last_resolution_.cookie;
Winson2f3669b2019-01-11 11:28:34 -0800960 if (cookie == kInvalidCookie) {
961 LOG(ERROR) << "AssetManager hasn't resolved a resource to read resolution path.";
Ryan Mitchell80094e32020-11-16 23:08:18 +0000962 return {};
Winson2f3669b2019-01-11 11:28:34 -0800963 }
964
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700965 auto op = StartOperation();
966
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800967 const uint32_t resid = last_resolution_.resid;
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700968 const auto& assets = GetApkAssets(cookie);
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700969 const auto package =
970 assets ? assets->GetLoadedArsc()->GetPackageById(get_package_id(resid)) : nullptr;
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800971
Winson2f3669b2019-01-11 11:28:34 -0800972 std::string resource_name_string;
Winson2f3669b2019-01-11 11:28:34 -0800973 if (package != nullptr) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000974 auto resource_name = ToResourceName(last_resolution_.type_string_ref,
975 last_resolution_.entry_string_ref,
976 package->GetPackageName());
977 resource_name_string = resource_name.has_value() ?
978 ToFormattedResourceString(resource_name.value()) : "<unknown>";
Winson2f3669b2019-01-11 11:28:34 -0800979 }
980
981 std::stringstream log_stream;
Jeremy Meyer04cf00d2023-07-20 22:17:27 +0000982 if (configurations_.size() == 1) {
983 log_stream << base::StringPrintf("Resolution for 0x%08x %s\n"
984 "\tFor config - %s", resid, resource_name_string.c_str(),
985 configurations_[0].toString().c_str());
986 } else {
987 ResTable_config conf = configurations_[0];
988 conf.clearLocale();
989 log_stream << base::StringPrintf("Resolution for 0x%08x %s\n\tFor config - %s and locales",
990 resid, resource_name_string.c_str(), conf.toString().c_str());
991 char str[40];
992 str[0] = '\0';
993 for(auto iter = configurations_.begin(); iter < configurations_.end(); iter++) {
994 iter->getBcp47Locale(str);
995 log_stream << base::StringPrintf(" %s%s", str, iter < configurations_.end() ? "," : "");
996 }
997 }
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800998 for (const Resolution::Step& step : last_resolution_.steps) {
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -0700999 constexpr static std::array kStepStrings = {
1000 "Found initial",
1001 "Found better",
1002 "Overlaid",
1003 "Overlaid inline",
1004 "Skipped",
1005 "No entry"
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001006 };
1007
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -07001008 if (step.type < Resolution::Step::Type::INITIAL
1009 || step.type > Resolution::Step::Type::NO_ENTRY) {
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001010 continue;
Winson2f3669b2019-01-11 11:28:34 -08001011 }
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -07001012 const auto prefix = kStepStrings[int(step.type) - int(Resolution::Step::Type::INITIAL)];
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -07001013 const auto& assets = GetApkAssets(step.cookie);
Yurii Zubrytskyib3455192023-05-01 14:35:48 -07001014 log_stream << "\n\t" << prefix << ": " << (assets ? assets->GetDebugName() : "<null>")
1015 << " #" << step.cookie;
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001016 if (!step.config_name.isEmpty()) {
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -08001017 log_stream << " - " << step.config_name;
Winson2f3669b2019-01-11 11:28:34 -08001018 }
1019 }
1020
Jackal Guo552b45d2021-09-29 10:52:19 +08001021 log_stream << "\nBest matching is from "
1022 << (last_resolution_.best_config_name.isEmpty() ? "default"
1023 : last_resolution_.best_config_name)
1024 << " configuration of " << last_resolution_.best_package_name;
Winson2f3669b2019-01-11 11:28:34 -08001025 return log_stream.str();
1026}
1027
Felka Chang00964e92021-12-10 01:19:08 +08001028base::expected<uint32_t, NullOrIOError> AssetManager2::GetParentThemeResourceId(uint32_t resid)
1029const {
1030 auto entry = FindEntry(resid, 0u /* density_override */,
1031 false /* stop_at_first_match */,
1032 false /* ignore_configuration */);
1033 if (!entry.has_value()) {
1034 return base::unexpected(entry.error());
1035 }
1036
1037 auto entry_map = std::get_if<incfs::verified_map_ptr<ResTable_map_entry>>(&entry->entry);
1038 if (entry_map == nullptr) {
1039 // Not a bag, nothing to do.
1040 return base::unexpected(std::nullopt);
1041 }
1042
1043 auto map = *entry_map;
1044 const uint32_t parent_resid = dtohl(map->parent.ident);
1045
1046 return parent_resid;
1047}
1048
Ryan Mitchell80094e32020-11-16 23:08:18 +00001049base::expected<AssetManager2::ResourceName, NullOrIOError> AssetManager2::GetResourceName(
1050 uint32_t resid) const {
1051 auto result = FindEntry(resid, 0u /* density_override */, true /* stop_at_first_match */,
1052 true /* ignore_configuration */);
1053 if (!result.has_value()) {
1054 return base::unexpected(result.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001055 }
1056
Ryan Mitchell80094e32020-11-16 23:08:18 +00001057 return ToResourceName(result->type_string_ref,
1058 result->entry_string_ref,
1059 *result->package_name);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001060}
1061
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001062base::expected<uint32_t, NullOrIOError> AssetManager2::GetResourceTypeSpecFlags(
1063 uint32_t resid) const {
1064 auto result = FindEntry(resid, 0u /* density_override */, false /* stop_at_first_match */,
1065 true /* ignore_configuration */);
1066 if (!result.has_value()) {
1067 return base::unexpected(result.error());
1068 }
1069 return result->type_flags;
1070}
1071
Ryan Mitchell80094e32020-11-16 23:08:18 +00001072base::expected<AssetManager2::SelectedValue, NullOrIOError> AssetManager2::GetResource(
1073 uint32_t resid, bool may_be_bag, uint16_t density_override) const {
1074 auto result = FindEntry(resid, density_override, false /* stop_at_first_match */,
1075 false /* ignore_configuration */);
1076 if (!result.has_value()) {
1077 return base::unexpected(result.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001078 }
1079
Ryan Mitchell80094e32020-11-16 23:08:18 +00001080 auto result_map_entry = std::get_if<incfs::verified_map_ptr<ResTable_map_entry>>(&result->entry);
Ryan Mitchellbf1f45b2020-09-29 17:22:52 -07001081 if (result_map_entry != nullptr) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001082 if (!may_be_bag) {
1083 LOG(ERROR) << base::StringPrintf("Resource %08x is a complex map type.", resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001084 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001085 }
Adam Lesinski0c405242017-01-13 20:47:26 -08001086
1087 // Create a reference since we can't represent this complex type as a Res_value.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001088 return SelectedValue(Res_value::TYPE_REFERENCE, resid, result->cookie, result->type_flags,
1089 resid, result->config);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001090 }
1091
Adam Lesinskida431a22016-12-29 16:08:16 -05001092 // Convert the package ID to the runtime assigned package ID.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001093 Res_value value = std::get<Res_value>(result->entry);
1094 result->dynamic_ref_table->lookupResourceValue(&value);
Adam Lesinskida431a22016-12-29 16:08:16 -05001095
Ryan Mitchell80094e32020-11-16 23:08:18 +00001096 return SelectedValue(value.dataType, value.data, result->cookie, result->type_flags,
1097 resid, result->config);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001098}
1099
Ryan Mitchell80094e32020-11-16 23:08:18 +00001100base::expected<std::monostate, NullOrIOError> AssetManager2::ResolveReference(
Ryan Mitchella45506e2020-11-16 23:08:18 +00001101 AssetManager2::SelectedValue& value, bool cache_value) const {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001102 if (value.type != Res_value::TYPE_REFERENCE || value.data == 0U) {
1103 // Not a reference. Nothing to do.
1104 return {};
Adam Lesinski0c405242017-01-13 20:47:26 -08001105 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001106
Ryan Mitchella45506e2020-11-16 23:08:18 +00001107 const uint32_t original_flags = value.flags;
1108 const uint32_t original_resid = value.data;
1109 if (cache_value) {
1110 auto cached_value = cached_resolved_values_.find(value.data);
1111 if (cached_value != cached_resolved_values_.end()) {
1112 value = cached_value->second;
1113 value.flags |= original_flags;
1114 return {};
1115 }
1116 }
1117
1118 uint32_t combined_flags = 0U;
1119 uint32_t resolve_resid = original_resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001120 constexpr const uint32_t kMaxIterations = 20;
1121 for (uint32_t i = 0U;; i++) {
1122 auto result = GetResource(resolve_resid, true /*may_be_bag*/);
1123 if (!result.has_value()) {
Ryan Mitchelle7ab6272020-11-13 18:06:15 -08001124 value.resid = resolve_resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001125 return base::unexpected(result.error());
1126 }
1127
Ryan Mitchelle7ab6272020-11-13 18:06:15 -08001128 // If resource resolution fails, the value should be set to the last reference that was able to
1129 // be resolved successfully.
1130 value = *result;
1131 value.flags |= combined_flags;
1132
Ryan Mitchell80094e32020-11-16 23:08:18 +00001133 if (result->type != Res_value::TYPE_REFERENCE ||
1134 result->data == Res_value::DATA_NULL_UNDEFINED ||
1135 result->data == resolve_resid || i == kMaxIterations) {
1136 // This reference can't be resolved, so exit now and let the caller deal with it.
Ryan Mitchella45506e2020-11-16 23:08:18 +00001137 if (cache_value) {
1138 cached_resolved_values_[original_resid] = value;
1139 }
1140
1141 // Above value is cached without original_flags to ensure they don't get included in future
1142 // queries that hit the cache
1143 value.flags |= original_flags;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001144 return {};
1145 }
1146
Ryan Mitchelle7ab6272020-11-13 18:06:15 -08001147 combined_flags = result->flags;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001148 resolve_resid = result->data;
1149 }
Adam Lesinski0c405242017-01-13 20:47:26 -08001150}
1151
Yurii Zubrytskyi02a555f2023-05-10 13:22:55 -07001152base::expected<const std::vector<uint32_t>*, NullOrIOError> AssetManager2::GetBagResIdStack(
1153 uint32_t resid) const {
1154 auto [it, inserted] = cached_bag_resid_stacks_.try_emplace(resid);
1155 if (inserted) {
1156 // This is a new entry in the cache, need to populate it.
Yurii Zubrytskyibd1db5d2023-05-23 18:32:47 -07001157 if (auto maybe_bag = GetBag(resid, it->second); UNLIKELY(IsIOError(maybe_bag))) {
Yurii Zubrytskyi02a555f2023-05-10 13:22:55 -07001158 cached_bag_resid_stacks_.erase(it);
1159 return base::unexpected(maybe_bag.error());
1160 }
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001161 }
Yurii Zubrytskyi02a555f2023-05-10 13:22:55 -07001162 return &it->second;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001163}
1164
Ryan Mitchell80094e32020-11-16 23:08:18 +00001165base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::ResolveBag(
1166 AssetManager2::SelectedValue& value) const {
1167 if (UNLIKELY(value.type != Res_value::TYPE_REFERENCE)) {
1168 return base::unexpected(std::nullopt);
1169 }
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001170
Ryan Mitchell80094e32020-11-16 23:08:18 +00001171 auto bag = GetBag(value.data);
1172 if (bag.has_value()) {
1173 value.flags |= (*bag)->type_spec_flags;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001174 }
1175 return bag;
y57cd1952018-04-12 14:26:23 -07001176}
1177
Ryan Mitchell80094e32020-11-16 23:08:18 +00001178base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::GetBag(uint32_t resid) const {
Yurii Zubrytskyibd1db5d2023-05-23 18:32:47 -07001179 auto [resid_stacks_it, _] = cached_bag_resid_stacks_.try_emplace(resid);
1180 resid_stacks_it->second.clear();
1181 const auto bag = GetBag(resid, resid_stacks_it->second);
1182 if (UNLIKELY(IsIOError(bag))) {
1183 cached_bag_resid_stacks_.erase(resid_stacks_it);
1184 return base::unexpected(bag.error());
1185 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001186 return bag;
Ryan Mitchell155d5392020-02-10 13:35:24 -08001187}
1188
Ryan Mitchell80094e32020-11-16 23:08:18 +00001189base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::GetBag(
1190 uint32_t resid, std::vector<uint32_t>& child_resids) const {
1191 if (auto cached_iter = cached_bags_.find(resid); cached_iter != cached_bags_.end()) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001192 return cached_iter->second.get();
1193 }
1194
Ryan Mitchell80094e32020-11-16 23:08:18 +00001195 auto entry = FindEntry(resid, 0u /* density_override */, false /* stop_at_first_match */,
1196 false /* ignore_configuration */);
1197 if (!entry.has_value()) {
1198 return base::unexpected(entry.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001199 }
1200
Ryan Mitchell80094e32020-11-16 23:08:18 +00001201 auto entry_map = std::get_if<incfs::verified_map_ptr<ResTable_map_entry>>(&entry->entry);
1202 if (entry_map == nullptr) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001203 // Not a bag, nothing to do.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001204 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001205 }
1206
Ryan Mitchell80094e32020-11-16 23:08:18 +00001207 auto map = *entry_map;
1208 auto map_entry = map.offset(dtohs(map->size)).convert<ResTable_map>();
1209 const auto map_entry_end = map_entry + dtohl(map->count);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001210
y57cd1952018-04-12 14:26:23 -07001211 // Keep track of ids that have already been seen to prevent infinite loops caused by circular
Ryan Mitchell80094e32020-11-16 23:08:18 +00001212 // dependencies between bags.
y57cd1952018-04-12 14:26:23 -07001213 child_resids.push_back(resid);
1214
Adam Lesinskida431a22016-12-29 16:08:16 -05001215 uint32_t parent_resid = dtohl(map->parent.ident);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001216 if (parent_resid == 0U ||
1217 std::find(child_resids.begin(), child_resids.end(), parent_resid) != child_resids.end()) {
1218 // There is no parent or a circular parental dependency exist, meaning there is nothing to
1219 // inherit and we can do a simple copy of the entries in the map.
Adam Lesinski7ad11102016-10-28 16:39:15 -07001220 const size_t entry_count = map_entry_end - map_entry;
1221 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
1222 malloc(sizeof(ResolvedBag) + (entry_count * sizeof(ResolvedBag::Entry))))};
Ryan Mitchell155d5392020-02-10 13:35:24 -08001223
1224 bool sort_entries = false;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001225 for (auto new_entry = new_bag->entries; map_entry != map_entry_end; ++map_entry) {
1226 if (UNLIKELY(!map_entry)) {
1227 return base::unexpected(IOError::PAGES_MISSING);
1228 }
1229
Adam Lesinskida431a22016-12-29 16:08:16 -05001230 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001231 if (!is_internal_resid(new_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -05001232 // Attributes, arrays, etc don't have a resource id as the name. They specify
1233 // other data, which would be wrong to change via a lookup.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001234 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001235 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
1236 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001237 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001238 }
1239 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001240
1241 new_entry->cookie = entry->cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -05001242 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001243 new_entry->key_pool = nullptr;
1244 new_entry->type_pool = nullptr;
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001245 new_entry->style = resid;
Adam Lesinski30080e22017-10-16 16:18:09 -07001246 new_entry->value.copyFrom_dtoh(map_entry->value);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001247 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1248 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001249 LOG(ERROR) << base::StringPrintf(
1250 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
1251 new_entry->value.data, new_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001252 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001253 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001254
Ryan Mitchell155d5392020-02-10 13:35:24 -08001255 sort_entries = sort_entries ||
1256 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001257 ++new_entry;
1258 }
Ryan Mitchell155d5392020-02-10 13:35:24 -08001259
1260 if (sort_entries) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001261 std::sort(new_bag->entries, new_bag->entries + entry_count,
1262 [](auto&& lhs, auto&& rhs) { return lhs.key < rhs.key; });
Ryan Mitchell155d5392020-02-10 13:35:24 -08001263 }
1264
Ryan Mitchell80094e32020-11-16 23:08:18 +00001265 new_bag->type_spec_flags = entry->type_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001266 new_bag->entry_count = static_cast<uint32_t>(entry_count);
1267 ResolvedBag* result = new_bag.get();
1268 cached_bags_[resid] = std::move(new_bag);
1269 return result;
1270 }
1271
Adam Lesinskida431a22016-12-29 16:08:16 -05001272 // In case the parent is a dynamic reference, resolve it.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001273 entry->dynamic_ref_table->lookupResourceId(&parent_resid);
Adam Lesinskida431a22016-12-29 16:08:16 -05001274
Adam Lesinski7ad11102016-10-28 16:39:15 -07001275 // Get the parent and do a merge of the keys.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001276 const auto parent_bag = GetBag(parent_resid, child_resids);
1277 if (UNLIKELY(!parent_bag.has_value())) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001278 // Failed to get the parent that should exist.
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001279 LOG(ERROR) << base::StringPrintf("Failed to find parent 0x%08x of bag 0x%08x.", parent_resid,
1280 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001281 return base::unexpected(parent_bag.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001282 }
1283
Adam Lesinski7ad11102016-10-28 16:39:15 -07001284 // Create the max possible entries we can make. Once we construct the bag,
1285 // we will realloc to fit to size.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001286 const size_t max_count = (*parent_bag)->entry_count + dtohl(map->count);
George Burgess IV09b119f2017-07-25 15:00:04 -07001287 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
1288 malloc(sizeof(ResolvedBag) + (max_count * sizeof(ResolvedBag::Entry))))};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001289 ResolvedBag::Entry* new_entry = new_bag->entries;
1290
Ryan Mitchell80094e32020-11-16 23:08:18 +00001291 const ResolvedBag::Entry* parent_entry = (*parent_bag)->entries;
1292 const ResolvedBag::Entry* const parent_entry_end = parent_entry + (*parent_bag)->entry_count;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001293
1294 // The keys are expected to be in sorted order. Merge the two bags.
Ryan Mitchell155d5392020-02-10 13:35:24 -08001295 bool sort_entries = false;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001296 while (map_entry != map_entry_end && parent_entry != parent_entry_end) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001297 if (UNLIKELY(!map_entry)) {
1298 return base::unexpected(IOError::PAGES_MISSING);
1299 }
1300
Adam Lesinskida431a22016-12-29 16:08:16 -05001301 uint32_t child_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001302 if (!is_internal_resid(child_key)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001303 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&child_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001304 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", child_key,
1305 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001306 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001307 }
1308 }
1309
Adam Lesinski7ad11102016-10-28 16:39:15 -07001310 if (child_key <= parent_entry->key) {
1311 // Use the child key if it comes before the parent
1312 // or is equal to the parent (overrides).
Ryan Mitchell80094e32020-11-16 23:08:18 +00001313 new_entry->cookie = entry->cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001314 new_entry->key = child_key;
1315 new_entry->key_pool = nullptr;
1316 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -07001317 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001318 new_entry->style = resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001319 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1320 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001321 LOG(ERROR) << base::StringPrintf(
1322 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
1323 new_entry->value.data, child_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001324 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001325 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001326 ++map_entry;
1327 } else {
1328 // Take the parent entry as-is.
1329 memcpy(new_entry, parent_entry, sizeof(*new_entry));
1330 }
1331
Ryan Mitchell155d5392020-02-10 13:35:24 -08001332 sort_entries = sort_entries ||
1333 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001334 if (child_key >= parent_entry->key) {
1335 // Move to the next parent entry if we used it or it was overridden.
1336 ++parent_entry;
1337 }
1338 // Increment to the next entry to fill.
1339 ++new_entry;
1340 }
1341
1342 // Finish the child entries if they exist.
1343 while (map_entry != map_entry_end) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001344 if (UNLIKELY(!map_entry)) {
1345 return base::unexpected(IOError::PAGES_MISSING);
1346 }
1347
Adam Lesinskida431a22016-12-29 16:08:16 -05001348 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001349 if (!is_internal_resid(new_key)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001350 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001351 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
1352 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001353 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001354 }
1355 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001356 new_entry->cookie = entry->cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -05001357 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001358 new_entry->key_pool = nullptr;
1359 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -07001360 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001361 new_entry->style = resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001362 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1363 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001364 LOG(ERROR) << base::StringPrintf("Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.",
1365 new_entry->value.dataType, new_entry->value.data, new_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001366 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001367 }
Ryan Mitchell155d5392020-02-10 13:35:24 -08001368 sort_entries = sort_entries ||
1369 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001370 ++map_entry;
1371 ++new_entry;
1372 }
1373
1374 // Finish the parent entries if they exist.
1375 if (parent_entry != parent_entry_end) {
1376 // Take the rest of the parent entries as-is.
1377 const size_t num_entries_to_copy = parent_entry_end - parent_entry;
1378 memcpy(new_entry, parent_entry, num_entries_to_copy * sizeof(*new_entry));
1379 new_entry += num_entries_to_copy;
1380 }
1381
1382 // Resize the resulting array to fit.
1383 const size_t actual_count = new_entry - new_bag->entries;
1384 if (actual_count != max_count) {
George Burgess IV09b119f2017-07-25 15:00:04 -07001385 new_bag.reset(reinterpret_cast<ResolvedBag*>(realloc(
1386 new_bag.release(), sizeof(ResolvedBag) + (actual_count * sizeof(ResolvedBag::Entry)))));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001387 }
1388
Ryan Mitchell155d5392020-02-10 13:35:24 -08001389 if (sort_entries) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001390 std::sort(new_bag->entries, new_bag->entries + actual_count,
1391 [](auto&& lhs, auto&& rhs) { return lhs.key < rhs.key; });
Ryan Mitchell155d5392020-02-10 13:35:24 -08001392 }
1393
Adam Lesinski1a1e9c22017-10-13 15:45:34 -07001394 // Combine flags from the parent and our own bag.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001395 new_bag->type_spec_flags = entry->type_flags | (*parent_bag)->type_spec_flags;
George Burgess IV09b119f2017-07-25 15:00:04 -07001396 new_bag->entry_count = static_cast<uint32_t>(actual_count);
1397 ResolvedBag* result = new_bag.get();
1398 cached_bags_[resid] = std::move(new_bag);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001399 return result;
1400}
1401
Yurii Zubrytskyia5775142022-11-02 17:49:49 -07001402static bool Utf8ToUtf16(StringPiece str, std::u16string* out) {
Adam Lesinski929d6512017-01-16 19:11:19 -08001403 ssize_t len =
1404 utf8_to_utf16_length(reinterpret_cast<const uint8_t*>(str.data()), str.size(), false);
1405 if (len < 0) {
1406 return false;
1407 }
1408 out->resize(static_cast<size_t>(len));
1409 utf8_to_utf16(reinterpret_cast<const uint8_t*>(str.data()), str.size(), &*out->begin(),
1410 static_cast<size_t>(len + 1));
1411 return true;
1412}
1413
Ryan Mitchell80094e32020-11-16 23:08:18 +00001414base::expected<uint32_t, NullOrIOError> AssetManager2::GetResourceId(
1415 const std::string& resource_name, const std::string& fallback_type,
1416 const std::string& fallback_package) const {
Adam Lesinski929d6512017-01-16 19:11:19 -08001417 StringPiece package_name, type, entry;
1418 if (!ExtractResourceName(resource_name, &package_name, &type, &entry)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001419 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001420 }
1421
1422 if (entry.empty()) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001423 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001424 }
1425
1426 if (package_name.empty()) {
1427 package_name = fallback_package;
1428 }
1429
1430 if (type.empty()) {
1431 type = fallback_type;
1432 }
1433
1434 std::u16string type16;
1435 if (!Utf8ToUtf16(type, &type16)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001436 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001437 }
1438
1439 std::u16string entry16;
1440 if (!Utf8ToUtf16(entry, &entry16)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001441 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001442 }
1443
1444 const StringPiece16 kAttr16 = u"attr";
1445 const static std::u16string kAttrPrivate16 = u"^attr-private";
1446
1447 for (const PackageGroup& package_group : package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001448 for (const ConfiguredPackage& package_impl : package_group.packages_) {
1449 const LoadedPackage* package = package_impl.loaded_package_;
Adam Lesinski929d6512017-01-16 19:11:19 -08001450 if (package_name != package->GetPackageName()) {
1451 // All packages in the same group are expected to have the same package name.
1452 break;
1453 }
1454
Ryan Mitchell80094e32020-11-16 23:08:18 +00001455 base::expected<uint32_t, NullOrIOError> resid = package->FindEntryByName(type16, entry16);
1456 if (UNLIKELY(IsIOError(resid))) {
1457 return base::unexpected(resid.error());
1458 }
1459
1460 if (!resid.has_value() && kAttr16 == type16) {
Adam Lesinski929d6512017-01-16 19:11:19 -08001461 // Private attributes in libraries (such as the framework) are sometimes encoded
1462 // under the type '^attr-private' in order to leave the ID space of public 'attr'
1463 // free for future additions. Check '^attr-private' for the same name.
1464 resid = package->FindEntryByName(kAttrPrivate16, entry16);
1465 }
1466
Ryan Mitchell80094e32020-11-16 23:08:18 +00001467 if (resid.has_value()) {
1468 return fix_package_id(*resid, package_group.dynamic_ref_table->mAssignedPackageId);
Adam Lesinski929d6512017-01-16 19:11:19 -08001469 }
1470 }
1471 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001472 return base::unexpected(std::nullopt);
Adam Lesinski0c405242017-01-13 20:47:26 -08001473}
1474
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001475void AssetManager2::RebuildFilterList() {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001476 for (PackageGroup& group : package_groups_) {
Yurii Zubrytskyidbce3562022-11-14 22:26:10 -08001477 for (ConfiguredPackage& package : group.packages_) {
1478 package.filtered_configs_.forEachItem([](auto, auto& fcg) { fcg.type_entries.clear(); });
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001479 // Create the filters here.
Yurii Zubrytskyidbce3562022-11-14 22:26:10 -08001480 package.loaded_package_->ForEachTypeSpec([&](const TypeSpec& type_spec, uint8_t type_id) {
Yurii Zubrytskyi59dab3b2022-11-03 00:08:49 -07001481 FilteredConfigGroup* group = nullptr;
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001482 for (const auto& type_entry : type_spec.type_entries) {
Jeremy Meyer04cf00d2023-07-20 22:17:27 +00001483 for (auto & config : configurations_) {
1484 if (type_entry.config.match(config)) {
1485 if (!group) {
1486 group = &package.filtered_configs_.editItemAt(type_id - 1);
1487 }
1488 group->type_entries.push_back(&type_entry);
1489 break;
Yurii Zubrytskyi59dab3b2022-11-03 00:08:49 -07001490 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001491 }
1492 }
1493 });
Yurii Zubrytskyidbce3562022-11-14 22:26:10 -08001494 package.filtered_configs_.trimBuckets(
1495 [](const auto& fcg) { return fcg.type_entries.empty(); });
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001496 }
1497 }
1498}
1499
Adam Lesinski7ad11102016-10-28 16:39:15 -07001500void AssetManager2::InvalidateCaches(uint32_t diff) {
Ryan Mitchell2c4d8742019-03-04 09:41:00 -08001501 cached_bag_resid_stacks_.clear();
1502
Adam Lesinski7ad11102016-10-28 16:39:15 -07001503 if (diff == 0xffffffffu) {
1504 // Everything must go.
1505 cached_bags_.clear();
1506 return;
1507 }
1508
1509 // Be more conservative with what gets purged. Only if the bag has other possible
1510 // variations with respect to what changed (diff) should we remove it.
1511 for (auto iter = cached_bags_.cbegin(); iter != cached_bags_.cend();) {
1512 if (diff & iter->second->type_spec_flags) {
1513 iter = cached_bags_.erase(iter);
1514 } else {
1515 ++iter;
1516 }
1517 }
Ryan Mitchella45506e2020-11-16 23:08:18 +00001518
1519 cached_resolved_values_.clear();
Adam Lesinski7ad11102016-10-28 16:39:15 -07001520}
1521
Ryan Mitchell2e394222019-08-28 12:10:51 -07001522uint8_t AssetManager2::GetAssignedPackageId(const LoadedPackage* package) const {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001523 for (auto& package_group : package_groups_) {
1524 for (auto& package2 : package_group.packages_) {
1525 if (package2.loaded_package_ == package) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -07001526 return package_group.dynamic_ref_table->mAssignedPackageId;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001527 }
1528 }
1529 }
1530 return 0;
1531}
1532
Adam Lesinski30080e22017-10-16 16:18:09 -07001533std::unique_ptr<Theme> AssetManager2::NewTheme() {
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001534 constexpr size_t kInitialReserveSize = 32;
1535 auto theme = std::unique_ptr<Theme>(new Theme(this));
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001536 theme->keys_.reserve(kInitialReserveSize);
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001537 theme->entries_.reserve(kInitialReserveSize);
1538 return theme;
Adam Lesinski30080e22017-10-16 16:18:09 -07001539}
1540
Yurii Zubrytskyi9eb44c92022-11-14 23:44:52 -08001541void AssetManager2::ForEachPackage(base::function_ref<bool(const std::string&, uint8_t)> func,
1542 package_property_t excluded_property_flags) const {
1543 for (const PackageGroup& package_group : package_groups_) {
1544 const auto loaded_package = package_group.packages_.front().loaded_package_;
1545 if ((loaded_package->GetPropertyFlags() & excluded_property_flags) == 0U
1546 && !func(loaded_package->GetPackageName(),
1547 package_group.dynamic_ref_table->mAssignedPackageId)) {
1548 return;
1549 }
1550 }
1551}
1552
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -07001553AssetManager2::ScopedOperation AssetManager2::StartOperation() const {
1554 ++number_of_running_scoped_operations_;
1555 return ScopedOperation(*this);
1556}
1557
1558void AssetManager2::FinishOperation() const {
1559 if (number_of_running_scoped_operations_ < 1) {
1560 ALOGW("Invalid FinishOperation() call when there's none happening");
1561 return;
1562 }
1563 if (--number_of_running_scoped_operations_ == 0) {
1564 for (auto&& [_, assets] : apk_assets_) {
1565 assets.clear();
1566 }
1567 }
1568}
1569
1570const AssetManager2::ApkAssetsPtr& AssetManager2::GetApkAssets(ApkAssetsCookie cookie) const {
1571 DCHECK(number_of_running_scoped_operations_ > 0) << "Must have an operation running";
1572
1573 if (cookie < 0 || cookie >= apk_assets_.size()) {
1574 static const ApkAssetsPtr empty{};
1575 return empty;
1576 }
1577 auto& [wptr, res] = apk_assets_[cookie];
1578 if (!res) {
1579 res = wptr.promote();
1580 }
1581 return res;
1582}
1583
Adam Lesinski30080e22017-10-16 16:18:09 -07001584Theme::Theme(AssetManager2* asset_manager) : asset_manager_(asset_manager) {
1585}
1586
1587Theme::~Theme() = default;
1588
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001589struct Theme::Entry {
Adam Lesinski30080e22017-10-16 16:18:09 -07001590 ApkAssetsCookie cookie;
1591 uint32_t type_spec_flags;
1592 Res_value value;
1593};
1594
Ryan Mitchell80094e32020-11-16 23:08:18 +00001595base::expected<std::monostate, NullOrIOError> Theme::ApplyStyle(uint32_t resid, bool force) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001596 ATRACE_NAME("Theme::ApplyStyle");
Adam Lesinski7ad11102016-10-28 16:39:15 -07001597
Ryan Mitchell80094e32020-11-16 23:08:18 +00001598 auto bag = asset_manager_->GetBag(resid);
1599 if (!bag.has_value()) {
1600 return base::unexpected(bag.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001601 }
1602
1603 // Merge the flags from this style.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001604 type_spec_flags_ |= (*bag)->type_spec_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001605
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001606 for (auto it = begin(*bag); it != end(*bag); ++it) {
1607 const uint32_t attr_res_id = it->key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001608
Adam Lesinski30080e22017-10-16 16:18:09 -07001609 // If the resource ID passed in is not a style, the key can be some other identifier that is not
1610 // a resource ID. We should fail fast instead of operating with strange resource IDs.
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001611 if (!is_valid_resid(attr_res_id)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001612 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001613 }
1614
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001615 // DATA_NULL_EMPTY (@empty) is a valid resource value and DATA_NULL_UNDEFINED represents
1616 // an absence of a valid value.
1617 bool is_undefined = it->value.dataType == Res_value::TYPE_NULL &&
1618 it->value.data != Res_value::DATA_NULL_EMPTY;
1619 if (!force && is_undefined) {
1620 continue;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001621 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001622
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001623 const auto key_it = std::lower_bound(keys_.begin(), keys_.end(), attr_res_id);
1624 const auto entry_it = entries_.begin() + (key_it - keys_.begin());
1625 if (key_it != keys_.end() && *key_it == attr_res_id) {
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001626 if (is_undefined) {
1627 // DATA_NULL_UNDEFINED clears the value of the attribute in the theme only when `force` is
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001628 // true.
1629 keys_.erase(key_it);
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001630 entries_.erase(entry_it);
1631 } else if (force) {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001632 *entry_it = Entry{it->cookie, (*bag)->type_spec_flags, it->value};
Adam Lesinski30080e22017-10-16 16:18:09 -07001633 }
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001634 } else {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001635 keys_.insert(key_it, attr_res_id);
1636 entries_.insert(entry_it, Entry{it->cookie, (*bag)->type_spec_flags, it->value});
Adam Lesinski7ad11102016-10-28 16:39:15 -07001637 }
1638 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001639 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001640}
1641
Ryan Mitchell767e34f2021-06-07 12:29:05 -07001642void Theme::Rebase(AssetManager2* am, const uint32_t* style_ids, const uint8_t* force,
1643 size_t style_count) {
1644 ATRACE_NAME("Theme::Rebase");
1645 // Reset the entries without changing the vector capacity to prevent reallocations during
1646 // ApplyStyle.
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001647 keys_.clear();
Ryan Mitchell767e34f2021-06-07 12:29:05 -07001648 entries_.clear();
1649 asset_manager_ = am;
1650 for (size_t i = 0; i < style_count; i++) {
1651 ApplyStyle(style_ids[i], force[i]);
1652 }
1653}
1654
Ryan Mitchell80094e32020-11-16 23:08:18 +00001655std::optional<AssetManager2::SelectedValue> Theme::GetAttribute(uint32_t resid) const {
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001656 constexpr const uint32_t kMaxIterations = 20;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001657 uint32_t type_spec_flags = 0u;
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001658 for (uint32_t i = 0; i <= kMaxIterations; i++) {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001659 const auto key_it = std::lower_bound(keys_.begin(), keys_.end(), resid);
1660 if (key_it == keys_.end() || *key_it != resid) {
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001661 return std::nullopt;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001662 }
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001663 const auto entry_it = entries_.begin() + (key_it - keys_.begin());
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001664 type_spec_flags |= entry_it->type_spec_flags;
1665 if (entry_it->value.dataType == Res_value::TYPE_ATTRIBUTE) {
1666 resid = entry_it->value.data;
1667 continue;
1668 }
1669
1670 return AssetManager2::SelectedValue(entry_it->value.dataType, entry_it->value.data,
1671 entry_it->cookie, type_spec_flags, 0U /* resid */,
1672 {} /* config */);
1673 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001674 return std::nullopt;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001675}
1676
Ryan Mitchell80094e32020-11-16 23:08:18 +00001677base::expected<std::monostate, NullOrIOError> Theme::ResolveAttributeReference(
1678 AssetManager2::SelectedValue& value) const {
1679 if (value.type != Res_value::TYPE_ATTRIBUTE) {
1680 return asset_manager_->ResolveReference(value);
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001681 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001682
1683 std::optional<AssetManager2::SelectedValue> result = GetAttribute(value.data);
1684 if (!result.has_value()) {
1685 return base::unexpected(std::nullopt);
1686 }
1687
Ryan Mitchella45506e2020-11-16 23:08:18 +00001688 auto resolve_result = asset_manager_->ResolveReference(*result, true /* cache_value */);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001689 if (resolve_result.has_value()) {
1690 result->flags |= value.flags;
1691 value = *result;
1692 }
1693 return resolve_result;
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001694}
1695
Adam Lesinski7ad11102016-10-28 16:39:15 -07001696void Theme::Clear() {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001697 keys_.clear();
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001698 entries_.clear();
Adam Lesinski7ad11102016-10-28 16:39:15 -07001699}
1700
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001701base::expected<std::monostate, IOError> Theme::SetTo(const Theme& source) {
1702 if (this == &source) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001703 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001704 }
1705
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001706 type_spec_flags_ = source.type_spec_flags_;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001707
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001708 if (asset_manager_ == source.asset_manager_) {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001709 keys_ = source.keys_;
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001710 entries_ = source.entries_;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001711 } else {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001712 std::unordered_map<ApkAssetsCookie, ApkAssetsCookie> src_to_dest_asset_cookies;
1713 using SourceToDestinationRuntimePackageMap = std::unordered_map<int, int>;
1714 std::unordered_map<ApkAssetsCookie, SourceToDestinationRuntimePackageMap> src_asset_cookie_id_map;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001715
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -07001716 auto op_src = source.asset_manager_->StartOperation();
1717 auto op_dst = asset_manager_->StartOperation();
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001718
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -07001719 for (size_t i = 0; i < source.asset_manager_->GetApkAssetsCount(); i++) {
1720 const auto& src_asset = source.asset_manager_->GetApkAssets(i);
1721 if (!src_asset) {
Yurii Zubrytskyib3455192023-05-01 14:35:48 -07001722 continue;
1723 }
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -07001724 for (int j = 0; j < asset_manager_->GetApkAssetsCount(); j++) {
1725 const auto& dest_asset = asset_manager_->GetApkAssets(j);
Ryan Mitchellef538432021-03-01 14:52:14 -08001726 if (src_asset != dest_asset) {
1727 // ResourcesManager caches and reuses ApkAssets when the same apk must be present in
1728 // multiple AssetManagers. Two ApkAssets point to the same version of the same resources
1729 // if they are the same instance.
1730 continue;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001731 }
Ryan Mitchellef538432021-03-01 14:52:14 -08001732
1733 // Map the package ids of the asset in the source AssetManager to the package ids of the
1734 // asset in th destination AssetManager.
1735 SourceToDestinationRuntimePackageMap package_map;
1736 for (const auto& loaded_package : src_asset->GetLoadedArsc()->GetPackages()) {
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001737 const int src_package_id = source.asset_manager_->GetAssignedPackageId(
1738 loaded_package.get());
Ryan Mitchellef538432021-03-01 14:52:14 -08001739 const int dest_package_id = asset_manager_->GetAssignedPackageId(loaded_package.get());
1740 package_map[src_package_id] = dest_package_id;
1741 }
1742
1743 src_to_dest_asset_cookies.insert(std::make_pair(i, j));
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001744 src_asset_cookie_id_map.insert(std::make_pair(i, std::move(package_map)));
Ryan Mitchellef538432021-03-01 14:52:14 -08001745 break;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001746 }
1747 }
1748
Ryan Mitchell93bca972019-03-08 17:26:28 -08001749 // Reset the data in the destination theme.
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001750 keys_.clear();
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001751 entries_.clear();
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001752
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001753 for (size_t i = 0, size = source.entries_.size(); i != size; ++i) {
1754 const auto& entry = source.entries_[i];
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001755 bool is_reference = (entry.value.dataType == Res_value::TYPE_ATTRIBUTE
1756 || entry.value.dataType == Res_value::TYPE_REFERENCE
1757 || entry.value.dataType == Res_value::TYPE_DYNAMIC_ATTRIBUTE
1758 || entry.value.dataType == Res_value::TYPE_DYNAMIC_REFERENCE)
1759 && entry.value.data != 0x0;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001760
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001761 // If the attribute value represents an attribute or reference, the package id of the
1762 // value needs to be rewritten to the package id of the value in the destination.
1763 uint32_t attribute_data = entry.value.data;
1764 if (is_reference) {
1765 // Determine the package id of the reference in the destination AssetManager.
1766 auto value_package_map = src_asset_cookie_id_map.find(entry.cookie);
1767 if (value_package_map == src_asset_cookie_id_map.end()) {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001768 continue;
1769 }
1770
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001771 auto value_dest_package = value_package_map->second.find(
1772 get_package_id(entry.value.data));
1773 if (value_dest_package == value_package_map->second.end()) {
1774 continue;
1775 }
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001776
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001777 attribute_data = fix_package_id(entry.value.data, value_dest_package->second);
1778 }
Ryan Mitchellb85d9b22018-11-19 12:11:38 -08001779
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001780 // Find the cookie of the value in the destination. If the source apk is not loaded in the
1781 // destination, only copy resources that do not reference resources in the source.
1782 ApkAssetsCookie data_dest_cookie;
1783 auto value_dest_cookie = src_to_dest_asset_cookies.find(entry.cookie);
1784 if (value_dest_cookie != src_to_dest_asset_cookies.end()) {
1785 data_dest_cookie = value_dest_cookie->second;
1786 } else {
1787 if (is_reference || entry.value.dataType == Res_value::TYPE_STRING) {
1788 continue;
1789 } else {
1790 data_dest_cookie = 0x0;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001791 }
1792 }
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001793
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001794 const auto source_res_id = source.keys_[i];
1795
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001796 // The package id of the attribute needs to be rewritten to the package id of the
1797 // attribute in the destination.
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001798 int attribute_dest_package_id = get_package_id(source_res_id);
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001799 if (attribute_dest_package_id != 0x01) {
1800 // Find the cookie of the attribute resource id in the source AssetManager
1801 base::expected<FindEntryResult, NullOrIOError> attribute_entry_result =
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001802 source.asset_manager_->FindEntry(source_res_id, 0 /* density_override */ ,
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001803 true /* stop_at_first_match */,
1804 true /* ignore_configuration */);
1805 if (UNLIKELY(IsIOError(attribute_entry_result))) {
1806 return base::unexpected(GetIOError(attribute_entry_result.error()));
1807 }
1808 if (!attribute_entry_result.has_value()) {
1809 continue;
1810 }
1811
1812 // Determine the package id of the attribute in the destination AssetManager.
1813 auto attribute_package_map = src_asset_cookie_id_map.find(
1814 attribute_entry_result->cookie);
1815 if (attribute_package_map == src_asset_cookie_id_map.end()) {
1816 continue;
1817 }
1818 auto attribute_dest_package = attribute_package_map->second.find(
1819 attribute_dest_package_id);
1820 if (attribute_dest_package == attribute_package_map->second.end()) {
1821 continue;
1822 }
1823 attribute_dest_package_id = attribute_dest_package->second;
1824 }
1825
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001826 auto dest_attr_id = make_resid(attribute_dest_package_id, get_type_id(source_res_id),
1827 get_entry_id(source_res_id));
1828 const auto key_it = std::lower_bound(keys_.begin(), keys_.end(), dest_attr_id);
1829 const auto entry_it = entries_.begin() + (key_it - keys_.begin());
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001830 // Since the entries were cleared, the attribute resource id has yet been mapped to any value.
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001831 keys_.insert(key_it, dest_attr_id);
1832 entries_.insert(entry_it, Entry{data_dest_cookie, entry.type_spec_flags,
1833 Res_value{.dataType = entry.value.dataType,
1834 .data = attribute_data}});
Adam Lesinski7ad11102016-10-28 16:39:15 -07001835 }
1836 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001837 return {};
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001838}
1839
1840void Theme::Dump() const {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001841 LOG(INFO) << base::StringPrintf("Theme(this=%p, AssetManager2=%p)", this, asset_manager_);
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001842 for (size_t i = 0, size = keys_.size(); i != size; ++i) {
1843 auto res_id = keys_[i];
1844 const auto& entry = entries_[i];
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001845 LOG(INFO) << base::StringPrintf(" entry(0x%08x)=(0x%08x) type=(0x%02x), cookie(%d)",
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001846 res_id, entry.value.data, entry.value.dataType,
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001847 entry.cookie);
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001848 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001849}
1850
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -07001851AssetManager2::ScopedOperation::ScopedOperation(const AssetManager2& am) : am_(am) {
1852}
1853
1854AssetManager2::ScopedOperation::~ScopedOperation() {
1855 am_.FinishOperation();
1856}
1857
Adam Lesinski7ad11102016-10-28 16:39:15 -07001858} // namespace android