blob: 5e04bfea2bef3cce672353d0166cdf7f07ae1581 [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 Zubrytskyi59dab3ba2022-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
Ryan Prichardacb04a02023-09-06 18:11:38 -070094struct Theme::Entry {
95 ApkAssetsCookie cookie;
96 uint32_t type_spec_flags;
97 Res_value value;
98};
99
Yurii Zubrytskyi1cf74932023-05-01 14:35:48 -0700100AssetManager2::AssetManager2(ApkAssetsList apk_assets, const ResTable_config& configuration)
101 : configuration_(configuration) {
102 // Don't invalidate caches here as there's nothing cached yet.
103 SetApkAssets(apk_assets, false);
Adam Lesinski970bd8d2017-09-25 13:21:55 -0700104}
Adam Lesinski7ad11102016-10-28 16:39:15 -0700105
Yurii Zubrytskyi1cf74932023-05-01 14:35:48 -0700106bool AssetManager2::SetApkAssets(ApkAssetsList apk_assets, bool invalidate_caches) {
107 BuildDynamicRefTable(apk_assets);
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800108 RebuildFilterList();
Adam Lesinski7ad11102016-10-28 16:39:15 -0700109 if (invalidate_caches) {
110 InvalidateCaches(static_cast<uint32_t>(-1));
111 }
112 return true;
113}
114
Yurii Zubrytskyi1cf74932023-05-01 14:35:48 -0700115bool AssetManager2::SetApkAssets(std::initializer_list<ApkAssetsPtr> apk_assets,
116 bool invalidate_caches) {
117 return SetApkAssets(ApkAssetsList(apk_assets.begin(), apk_assets.size()), invalidate_caches);
118}
119
120void AssetManager2::BuildDynamicRefTable(ApkAssetsList apk_assets) {
Yurii Zubrytskyi657f3c62023-05-10 13:16:23 -0700121 auto op = StartOperation();
122
123 apk_assets_.resize(apk_assets.size());
124 for (size_t i = 0; i != apk_assets.size(); ++i) {
125 apk_assets_[i].first = apk_assets[i];
126 // Let's populate the locked assets right away as we're going to need them here later.
127 apk_assets_[i].second = apk_assets[i];
128 }
129
Adam Lesinskida431a22016-12-29 16:08:16 -0500130 package_groups_.clear();
131 package_ids_.fill(0xff);
132
Ryan Mitchellef538432021-03-01 14:52:14 -0800133 // A mapping from path of apk assets that could be target packages of overlays to the runtime
134 // package id of its first loaded package. Overlays currently can only override resources in the
135 // first package in the target resource table.
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800136 std::unordered_map<std::string_view, uint8_t> target_assets_package_ids;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700137
Ryan Mitchell824cc492020-02-12 10:48:14 -0800138 // Overlay resources are not directly referenced by an application so their resource ids
139 // can change throughout the application's lifetime. Assign overlay package ids last.
Yurii Zubrytskyi1cf74932023-05-01 14:35:48 -0700140 std::vector<const ApkAssets*> sorted_apk_assets;
Yurii Zubrytskyi657f3c62023-05-10 13:16:23 -0700141 sorted_apk_assets.reserve(apk_assets.size());
Yurii Zubrytskyi1cf74932023-05-01 14:35:48 -0700142 for (auto& asset : apk_assets) {
143 sorted_apk_assets.push_back(asset.get());
144 }
145 std::stable_partition(sorted_apk_assets.begin(), sorted_apk_assets.end(),
146 [](auto a) { return !a->IsOverlay(); });
Ryan Mitchell824cc492020-02-12 10:48:14 -0800147
148 // The assets cookie must map to the position of the apk assets in the unsorted apk assets list.
149 std::unordered_map<const ApkAssets*, ApkAssetsCookie> apk_assets_cookies;
Yurii Zubrytskyi1cf74932023-05-01 14:35:48 -0700150 apk_assets_cookies.reserve(apk_assets.size());
151 for (size_t i = 0, n = apk_assets.size(); i < n; i++) {
152 apk_assets_cookies[apk_assets[i].get()] = static_cast<ApkAssetsCookie>(i);
Ryan Mitchell824cc492020-02-12 10:48:14 -0800153 }
154
Ryan Mitchellb894c272020-02-12 10:31:44 -0800155 // 0x01 is reserved for the android package.
156 int next_package_id = 0x02;
Ryan Mitchell824cc492020-02-12 10:48:14 -0800157 for (const ApkAssets* apk_assets : sorted_apk_assets) {
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800158 std::shared_ptr<OverlayDynamicRefTable> overlay_ref_table;
159 if (auto loaded_idmap = apk_assets->GetLoadedIdmap(); loaded_idmap != nullptr) {
160 // The target package must precede the overlay package in the apk assets paths in order
161 // to take effect.
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800162 auto iter = target_assets_package_ids.find(loaded_idmap->TargetApkPath());
Ryan Mitchellef538432021-03-01 14:52:14 -0800163 if (iter == target_assets_package_ids.end()) {
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800164 LOG(INFO) << "failed to find target package for overlay "
165 << loaded_idmap->OverlayApkPath();
166 } else {
167 uint8_t target_package_id = iter->second;
168
169 // Create a special dynamic reference table for the overlay to rewrite references to
170 // overlay resources as references to the target resources they overlay.
171 overlay_ref_table = std::make_shared<OverlayDynamicRefTable>(
172 loaded_idmap->GetOverlayDynamicRefTable(target_package_id));
173
174 // Add the overlay resource map to the target package's set of overlays.
175 const uint8_t target_idx = package_ids_[target_package_id];
176 CHECK(target_idx != 0xff) << "overlay target '" << loaded_idmap->TargetApkPath()
177 << "'added to apk_assets_package_ids but does not have an"
178 << " assigned package group";
179
180 PackageGroup& target_package_group = package_groups_[target_idx];
181 target_package_group.overlays_.push_back(
182 ConfiguredOverlay{loaded_idmap->GetTargetResourcesMap(target_package_id,
183 overlay_ref_table.get()),
184 apk_assets_cookies[apk_assets]});
185 }
186 }
187
Ryan Mitchellb894c272020-02-12 10:31:44 -0800188 const LoadedArsc* loaded_arsc = apk_assets->GetLoadedArsc();
Ryan Mitchellb894c272020-02-12 10:31:44 -0800189 for (const std::unique_ptr<const LoadedPackage>& package : loaded_arsc->GetPackages()) {
190 // Get the package ID or assign one if a shared library.
191 int package_id;
192 if (package->IsDynamic()) {
193 package_id = next_package_id++;
194 } else {
195 package_id = package->GetPackageId();
Adam Lesinskida431a22016-12-29 16:08:16 -0500196 }
197
Adam Lesinskida431a22016-12-29 16:08:16 -0500198 uint8_t idx = package_ids_[package_id];
199 if (idx == 0xff) {
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800200 // Add the mapping for package ID to index if not present.
Adam Lesinskida431a22016-12-29 16:08:16 -0500201 package_ids_[package_id] = idx = static_cast<uint8_t>(package_groups_.size());
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800202 PackageGroup& new_group = package_groups_.emplace_back();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700203
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800204 if (overlay_ref_table != nullptr) {
205 // If this package is from an overlay, use a dynamic reference table that can rewrite
206 // overlay resource ids to their corresponding target resource ids.
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800207 new_group.dynamic_ref_table = std::move(overlay_ref_table);
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700208 }
209
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800210 DynamicRefTable* ref_table = new_group.dynamic_ref_table.get();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700211 ref_table->mAssignedPackageId = package_id;
212 ref_table->mAppAsLib = package->IsDynamic() && package->GetPackageId() == 0x7f;
Adam Lesinskida431a22016-12-29 16:08:16 -0500213 }
Adam Lesinskida431a22016-12-29 16:08:16 -0500214
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800215 // Add the package to the set of packages with the same ID.
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800216 PackageGroup* package_group = &package_groups_[idx];
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800217 package_group->packages_.emplace_back().loaded_package_ = package.get();
Ryan Mitchell824cc492020-02-12 10:48:14 -0800218 package_group->cookies_.push_back(apk_assets_cookies[apk_assets]);
Adam Lesinskida431a22016-12-29 16:08:16 -0500219
220 // Add the package name -> build time ID mappings.
221 for (const DynamicPackageEntry& entry : package->GetDynamicPackageMap()) {
222 String16 package_name(entry.package_name.c_str(), entry.package_name.size());
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700223 package_group->dynamic_ref_table->mEntries.replaceValueFor(
Adam Lesinskida431a22016-12-29 16:08:16 -0500224 package_name, static_cast<uint8_t>(entry.package_id));
225 }
Ryan Mitchellb894c272020-02-12 10:31:44 -0800226
Ryan Mitchellef538432021-03-01 14:52:14 -0800227 if (auto apk_assets_path = apk_assets->GetPath()) {
228 // Overlay target ApkAssets must have been created using path based load apis.
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800229 target_assets_package_ids.emplace(*apk_assets_path, package_id);
Ryan Mitchellef538432021-03-01 14:52:14 -0800230 }
Adam Lesinskida431a22016-12-29 16:08:16 -0500231 }
232 }
233
234 // Now assign the runtime IDs so that we have a build-time to runtime ID map.
Yurii Zubrytskyi59dab3ba2022-11-03 00:08:49 -0700235 DynamicRefTable::AliasMap aliases;
236 for (const auto& group : package_groups_) {
237 const std::string& package_name = group.packages_[0].loaded_package_->GetPackageName();
238 const auto name_16 = String16(package_name.c_str(), package_name.size());
239 for (auto&& inner_group : package_groups_) {
240 inner_group.dynamic_ref_table->addMapping(name_16,
241 group.dynamic_ref_table->mAssignedPackageId);
Adam Lesinskida431a22016-12-29 16:08:16 -0500242 }
Yurii Zubrytskyi59dab3ba2022-11-03 00:08:49 -0700243
244 for (const auto& package : group.packages_) {
245 const auto& package_aliases = package.loaded_package_->GetAliasResourceIdMap();
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800246 aliases.insert(aliases.end(), package_aliases.begin(), package_aliases.end());
Yurii Zubrytskyi59dab3ba2022-11-03 00:08:49 -0700247 }
248 }
249
250 if (!aliases.empty()) {
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800251 std::sort(aliases.begin(), aliases.end(), [](auto&& l, auto&& r) { return l.first < r.first; });
252
Yurii Zubrytskyi59dab3ba2022-11-03 00:08:49 -0700253 // Add the alias resources to the dynamic reference table of every package group. Since
254 // staging aliases can only be defined by the framework package (which is not a shared
255 // library), the compile-time package id of the framework is the same across all packages
256 // that compile against the framework.
257 for (auto& group : std::span(package_groups_.data(), package_groups_.size() - 1)) {
258 group.dynamic_ref_table->setAliases(aliases);
259 }
260 package_groups_.back().dynamic_ref_table->setAliases(std::move(aliases));
Adam Lesinskida431a22016-12-29 16:08:16 -0500261 }
262}
263
264void AssetManager2::DumpToLog() const {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800265 LOG(INFO) << base::StringPrintf("AssetManager2(this=%p)", this);
266
Yurii Zubrytskyi657f3c62023-05-10 13:16:23 -0700267 auto op = StartOperation();
Adam Lesinskida431a22016-12-29 16:08:16 -0500268 std::string list;
Yurii Zubrytskyi657f3c62023-05-10 13:16:23 -0700269 for (size_t i = 0; i < apk_assets_.size(); ++i) {
270 const auto& assets = GetApkAssets(i);
Yurii Zubrytskyi1cf74932023-05-01 14:35:48 -0700271 base::StringAppendF(&list, "%s,", assets ? assets->GetDebugName().c_str() : "nullptr");
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800272 }
273 LOG(INFO) << "ApkAssets: " << list;
274
275 list = "";
Adam Lesinskida431a22016-12-29 16:08:16 -0500276 for (size_t i = 0; i < package_ids_.size(); i++) {
277 if (package_ids_[i] != 0xff) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800278 base::StringAppendF(&list, "%02x -> %d, ", (int)i, package_ids_[i]);
Adam Lesinskida431a22016-12-29 16:08:16 -0500279 }
280 }
281 LOG(INFO) << "Package ID map: " << list;
282
Adam Lesinski0dd369912018-01-25 15:38:38 -0800283 for (const auto& package_group: package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800284 list = "";
285 for (const auto& package : package_group.packages_) {
286 const LoadedPackage* loaded_package = package.loaded_package_;
287 base::StringAppendF(&list, "%s(%02x%s), ", loaded_package->GetPackageName().c_str(),
288 loaded_package->GetPackageId(),
289 (loaded_package->IsDynamic() ? " dynamic" : ""));
290 }
291 LOG(INFO) << base::StringPrintf("PG (%02x): ",
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700292 package_group.dynamic_ref_table->mAssignedPackageId)
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800293 << list;
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800294
295 for (size_t i = 0; i < 256; i++) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700296 if (package_group.dynamic_ref_table->mLookupTable[i] != 0) {
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800297 LOG(INFO) << base::StringPrintf(" e[0x%02x] -> 0x%02x", (uint8_t) i,
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700298 package_group.dynamic_ref_table->mLookupTable[i]);
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800299 }
300 }
Adam Lesinskida431a22016-12-29 16:08:16 -0500301 }
302}
Adam Lesinski7ad11102016-10-28 16:39:15 -0700303
304const ResStringPool* AssetManager2::GetStringPoolForCookie(ApkAssetsCookie cookie) const {
305 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
306 return nullptr;
307 }
Yurii Zubrytskyi657f3c62023-05-10 13:16:23 -0700308 auto op = StartOperation();
309 const auto& assets = GetApkAssets(cookie);
Yurii Zubrytskyi1cf74932023-05-01 14:35:48 -0700310 return assets ? assets->GetLoadedArsc()->GetStringPool() : nullptr;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700311}
312
Adam Lesinskida431a22016-12-29 16:08:16 -0500313const DynamicRefTable* AssetManager2::GetDynamicRefTableForPackage(uint32_t package_id) const {
314 if (package_id >= package_ids_.size()) {
315 return nullptr;
316 }
317
318 const size_t idx = package_ids_[package_id];
319 if (idx == 0xff) {
320 return nullptr;
321 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700322 return package_groups_[idx].dynamic_ref_table.get();
Adam Lesinskida431a22016-12-29 16:08:16 -0500323}
324
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700325std::shared_ptr<const DynamicRefTable> AssetManager2::GetDynamicRefTableForCookie(
326 ApkAssetsCookie cookie) const {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800327 for (const PackageGroup& package_group : package_groups_) {
328 for (const ApkAssetsCookie& package_cookie : package_group.cookies_) {
329 if (package_cookie == cookie) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700330 return package_group.dynamic_ref_table;
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800331 }
332 }
333 }
334 return nullptr;
335}
336
MÃ¥rten Kongstadc92c4dd2019-02-05 01:29:59 +0100337const std::unordered_map<std::string, std::string>*
338 AssetManager2::GetOverlayableMapForPackage(uint32_t package_id) const {
339
340 if (package_id >= package_ids_.size()) {
341 return nullptr;
342 }
343
344 const size_t idx = package_ids_[package_id];
345 if (idx == 0xff) {
346 return nullptr;
347 }
348
349 const PackageGroup& package_group = package_groups_[idx];
Ryan Mitchell80094e32020-11-16 23:08:18 +0000350 if (package_group.packages_.empty()) {
MÃ¥rten Kongstadc92c4dd2019-02-05 01:29:59 +0100351 return nullptr;
352 }
353
354 const auto loaded_package = package_group.packages_[0].loaded_package_;
355 return &loaded_package->GetOverlayableMap();
356}
357
Yurii Zubrytskyia5775142022-11-02 17:49:49 -0700358bool AssetManager2::GetOverlayablesToString(android::StringPiece package_name,
Ryan Mitchell2e394222019-08-28 12:10:51 -0700359 std::string* out) const {
Yurii Zubrytskyi657f3c62023-05-10 13:16:23 -0700360 auto op = StartOperation();
Ryan Mitchell2e394222019-08-28 12:10:51 -0700361 uint8_t package_id = 0U;
Yurii Zubrytskyi657f3c62023-05-10 13:16:23 -0700362 for (size_t i = 0; i != apk_assets_.size(); ++i) {
363 const auto& assets = GetApkAssets(i);
Yurii Zubrytskyi1cf74932023-05-01 14:35:48 -0700364 if (!assets) {
365 continue;
366 }
367 const LoadedArsc* loaded_arsc = assets->GetLoadedArsc();
Ryan Mitchell2e394222019-08-28 12:10:51 -0700368 if (loaded_arsc == nullptr) {
369 continue;
370 }
371
372 const auto& loaded_packages = loaded_arsc->GetPackages();
373 if (loaded_packages.empty()) {
374 continue;
375 }
376
377 const auto& loaded_package = loaded_packages[0];
378 if (loaded_package->GetPackageName() == package_name) {
379 package_id = GetAssignedPackageId(loaded_package.get());
380 break;
381 }
382 }
383
384 if (package_id == 0U) {
385 ANDROID_LOG(ERROR) << base::StringPrintf("No package with name '%s", package_name.data());
386 return false;
387 }
388
389 const size_t idx = package_ids_[package_id];
390 if (idx == 0xff) {
391 return false;
392 }
393
394 std::string output;
395 for (const ConfiguredPackage& package : package_groups_[idx].packages_) {
396 const LoadedPackage* loaded_package = package.loaded_package_;
397 for (auto it = loaded_package->begin(); it != loaded_package->end(); it++) {
398 const OverlayableInfo* info = loaded_package->GetOverlayableInfo(*it);
399 if (info != nullptr) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000400 auto res_name = GetResourceName(*it);
401 if (!res_name.has_value()) {
Ryan Mitchell2e394222019-08-28 12:10:51 -0700402 ANDROID_LOG(ERROR) << base::StringPrintf(
403 "Unable to retrieve name of overlayable resource 0x%08x", *it);
404 return false;
405 }
406
Ryan Mitchell80094e32020-11-16 23:08:18 +0000407 const std::string name = ToFormattedResourceString(*res_name);
Ryan Mitchell2e394222019-08-28 12:10:51 -0700408 output.append(base::StringPrintf(
409 "resource='%s' overlayable='%s' actor='%s' policy='0x%08x'\n",
Yurii Zubrytskyi9d225372022-11-29 11:12:18 -0800410 name.c_str(), info->name.data(), info->actor.data(), info->policy_flags));
Ryan Mitchell2e394222019-08-28 12:10:51 -0700411 }
412 }
413 }
414
415 *out = std::move(output);
416 return true;
417}
418
Ryan Mitchell192400c2020-04-02 09:54:23 -0700419bool AssetManager2::ContainsAllocatedTable() const {
Yurii Zubrytskyi657f3c62023-05-10 13:16:23 -0700420 auto op = StartOperation();
421 for (size_t i = 0; i != apk_assets_.size(); ++i) {
422 const auto& assets = GetApkAssets(i);
423 if (assets && assets->IsTableAllocated()) {
424 return true;
425 }
426 }
427 return false;
Ryan Mitchell192400c2020-04-02 09:54:23 -0700428}
429
Adam Lesinski7ad11102016-10-28 16:39:15 -0700430void AssetManager2::SetConfiguration(const ResTable_config& configuration) {
431 const int diff = configuration_.diff(configuration);
432 configuration_ = configuration;
433
434 if (diff) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800435 RebuildFilterList();
Adam Lesinski7ad11102016-10-28 16:39:15 -0700436 InvalidateCaches(static_cast<uint32_t>(diff));
437 }
438}
439
Yurii Zubrytskyi1cf74932023-05-01 14:35:48 -0700440std::set<AssetManager2::ApkAssetsPtr> AssetManager2::GetNonSystemOverlays() const {
441 std::set<ApkAssetsPtr> non_system_overlays;
Adam Lesinski0c405242017-01-13 20:47:26 -0800442 for (const PackageGroup& package_group : package_groups_) {
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800443 bool found_system_package = false;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800444 for (const ConfiguredPackage& package : package_group.packages_) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700445 if (package.loaded_package_->IsSystem()) {
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800446 found_system_package = true;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700447 break;
448 }
449 }
450
451 if (!found_system_package) {
Yurii Zubrytskyi657f3c62023-05-10 13:16:23 -0700452 auto op = StartOperation();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700453 for (const ConfiguredOverlay& overlay : package_group.overlays_) {
Yurii Zubrytskyi657f3c62023-05-10 13:16:23 -0700454 if (const auto& asset = GetApkAssets(overlay.cookie)) {
Yurii Zubrytskyi1cf74932023-05-01 14:35:48 -0700455 non_system_overlays.insert(std::move(asset));
456 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700457 }
458 }
459 }
460
461 return non_system_overlays;
462}
463
Ryan Mitchell80094e32020-11-16 23:08:18 +0000464base::expected<std::set<ResTable_config>, IOError> AssetManager2::GetResourceConfigurations(
465 bool exclude_system, bool exclude_mipmap) const {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700466 ATRACE_NAME("AssetManager::GetResourceConfigurations");
Yurii Zubrytskyi657f3c62023-05-10 13:16:23 -0700467 auto op = StartOperation();
468
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700469 const auto non_system_overlays =
Yurii Zubrytskyi1cf74932023-05-01 14:35:48 -0700470 exclude_system ? GetNonSystemOverlays() : std::set<ApkAssetsPtr>();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700471
472 std::set<ResTable_config> configurations;
473 for (const PackageGroup& package_group : package_groups_) {
474 for (size_t i = 0; i < package_group.packages_.size(); i++) {
475 const ConfiguredPackage& package = package_group.packages_[i];
Yurii Zubrytskyi1cf74932023-05-01 14:35:48 -0700476 if (exclude_system) {
477 if (package.loaded_package_->IsSystem()) {
478 continue;
479 }
480 if (!non_system_overlays.empty()) {
481 // Exclude overlays that target only system resources.
Yurii Zubrytskyi657f3c62023-05-10 13:16:23 -0700482 const auto& apk_assets = GetApkAssets(package_group.cookies_[i]);
Yurii Zubrytskyi1cf74932023-05-01 14:35:48 -0700483 if (apk_assets && apk_assets->IsOverlay() &&
484 non_system_overlays.find(apk_assets) == non_system_overlays.end()) {
485 continue;
486 }
487 }
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800488 }
489
Ryan Mitchell80094e32020-11-16 23:08:18 +0000490 auto result = package.loaded_package_->CollectConfigurations(exclude_mipmap, &configurations);
491 if (UNLIKELY(!result.has_value())) {
492 return base::unexpected(result.error());
493 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800494 }
495 }
496 return configurations;
497}
498
499std::set<std::string> AssetManager2::GetResourceLocales(bool exclude_system,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800500 bool merge_equivalent_languages) const {
501 ATRACE_NAME("AssetManager::GetResourceLocales");
Yurii Zubrytskyi657f3c62023-05-10 13:16:23 -0700502 auto op = StartOperation();
503
Adam Lesinski0c405242017-01-13 20:47:26 -0800504 std::set<std::string> locales;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700505 const auto non_system_overlays =
Yurii Zubrytskyi1cf74932023-05-01 14:35:48 -0700506 exclude_system ? GetNonSystemOverlays() : std::set<ApkAssetsPtr>();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700507
Adam Lesinski0c405242017-01-13 20:47:26 -0800508 for (const PackageGroup& package_group : package_groups_) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700509 for (size_t i = 0; i < package_group.packages_.size(); i++) {
510 const ConfiguredPackage& package = package_group.packages_[i];
Yurii Zubrytskyi1cf74932023-05-01 14:35:48 -0700511 if (exclude_system) {
512 if (package.loaded_package_->IsSystem()) {
513 continue;
514 }
515 if (!non_system_overlays.empty()) {
516 // Exclude overlays that target only system resources.
Yurii Zubrytskyi657f3c62023-05-10 13:16:23 -0700517 const auto& apk_assets = GetApkAssets(package_group.cookies_[i]);
Yurii Zubrytskyi1cf74932023-05-01 14:35:48 -0700518 if (apk_assets && apk_assets->IsOverlay() &&
519 non_system_overlays.find(apk_assets) == non_system_overlays.end()) {
520 continue;
521 }
522 }
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800523 }
524
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800525 package.loaded_package_->CollectLocales(merge_equivalent_languages, &locales);
Adam Lesinski0c405242017-01-13 20:47:26 -0800526 }
527 }
528 return locales;
529}
530
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800531std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename,
532 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700533 const std::string new_path = "assets/" + filename;
534 return OpenNonAsset(new_path, mode);
535}
536
537std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename, ApkAssetsCookie cookie,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800538 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700539 const std::string new_path = "assets/" + filename;
540 return OpenNonAsset(new_path, cookie, mode);
541}
542
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800543std::unique_ptr<AssetDir> AssetManager2::OpenDir(const std::string& dirname) const {
544 ATRACE_NAME("AssetManager::OpenDir");
Yurii Zubrytskyi657f3c62023-05-10 13:16:23 -0700545 auto op = StartOperation();
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800546
547 std::string full_path = "assets/" + dirname;
Yurii Zubrytskyi1cf74932023-05-01 14:35:48 -0700548 auto files = util::make_unique<SortedVector<AssetDir::FileInfo>>();
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800549
550 // Start from the back.
Yurii Zubrytskyi657f3c62023-05-10 13:16:23 -0700551 for (size_t i = apk_assets_.size(); i > 0; --i) {
552 const auto& apk_assets = GetApkAssets(i - 1);
Yurii Zubrytskyi1cf74932023-05-01 14:35:48 -0700553 if (!apk_assets || apk_assets->IsOverlay()) {
MÃ¥rten Kongstaddbf343b2019-02-21 07:54:18 +0100554 continue;
555 }
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800556
Yurii Zubrytskyia5775142022-11-02 17:49:49 -0700557 auto func = [&](StringPiece name, FileType type) {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800558 AssetDir::FileInfo info;
559 info.setFileName(String8(name.data(), name.size()));
560 info.setFileType(type);
Ryan Mitchellef538432021-03-01 14:52:14 -0800561 info.setSourceName(String8(apk_assets->GetDebugName().c_str()));
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800562 files->add(info);
563 };
564
Ryan Mitchellc07aa702020-03-10 13:49:12 -0700565 if (!apk_assets->GetAssetsProvider()->ForEachFile(full_path, func)) {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800566 return {};
567 }
568 }
569
570 std::unique_ptr<AssetDir> asset_dir = util::make_unique<AssetDir>();
571 asset_dir->setFileList(files.release());
572 return asset_dir;
573}
574
Adam Lesinski7ad11102016-10-28 16:39:15 -0700575// Search in reverse because that's how we used to do it and we need to preserve behaviour.
576// This is unfortunate, because ClassLoaders delegate to the parent first, so the order
577// is inconsistent for split APKs.
578std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
579 Asset::AccessMode mode,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800580 ApkAssetsCookie* out_cookie) const {
Yurii Zubrytskyi657f3c62023-05-10 13:16:23 -0700581 auto op = StartOperation();
582 for (size_t i = apk_assets_.size(); i > 0; i--) {
583 const auto& assets = GetApkAssets(i - 1);
MÃ¥rten Kongstaddbf343b2019-02-21 07:54:18 +0100584 // Prevent RRO from modifying assets and other entries accessed by file
585 // path. Explicitly asking for a path in a given package (denoted by a
586 // cookie) is still OK.
Yurii Zubrytskyi1cf74932023-05-01 14:35:48 -0700587 if (!assets || assets->IsOverlay()) {
MÃ¥rten Kongstaddbf343b2019-02-21 07:54:18 +0100588 continue;
589 }
590
Yurii Zubrytskyi1cf74932023-05-01 14:35:48 -0700591 std::unique_ptr<Asset> asset = assets->GetAssetsProvider()->Open(filename, mode);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700592 if (asset) {
593 if (out_cookie != nullptr) {
594 *out_cookie = i;
595 }
596 return asset;
597 }
598 }
599
600 if (out_cookie != nullptr) {
601 *out_cookie = kInvalidCookie;
602 }
603 return {};
604}
605
606std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800607 ApkAssetsCookie cookie,
608 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700609 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
610 return {};
611 }
Yurii Zubrytskyi657f3c62023-05-10 13:16:23 -0700612 auto op = StartOperation();
613 const auto& assets = GetApkAssets(cookie);
Yurii Zubrytskyi1cf74932023-05-01 14:35:48 -0700614 return assets ? assets->GetAssetsProvider()->Open(filename, mode) : nullptr;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700615}
616
Ryan Mitchell80094e32020-11-16 23:08:18 +0000617base::expected<FindEntryResult, NullOrIOError> AssetManager2::FindEntry(
618 uint32_t resid, uint16_t density_override, bool stop_at_first_match,
619 bool ignore_configuration) const {
620 const bool logging_enabled = resource_resolution_logging_enabled_;
621 if (UNLIKELY(logging_enabled)) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700622 // Clear the last logged resource resolution.
623 ResetResourceResolution();
624 last_resolution_.resid = resid;
625 }
626
Yurii Zubrytskyi657f3c62023-05-10 13:16:23 -0700627 auto op = StartOperation();
628
Adam Lesinski7ad11102016-10-28 16:39:15 -0700629 // Might use this if density_override != 0.
630 ResTable_config density_override_config;
631
632 // Select our configuration or generate a density override configuration.
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800633 const ResTable_config* desired_config = &configuration_;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700634 if (density_override != 0 && density_override != configuration_.density) {
635 density_override_config = configuration_;
636 density_override_config.density = density_override;
637 desired_config = &density_override_config;
638 }
639
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700640 // Retrieve the package group from the package id of the resource id.
Ryan Mitchell80094e32020-11-16 23:08:18 +0000641 if (UNLIKELY(!is_valid_resid(resid))) {
Mark Hansenb406b0e2022-10-14 02:18:37 +0000642 LOG(ERROR) << base::StringPrintf("Invalid resource ID 0x%08x.", resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000643 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -0500644 }
645
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800646 const uint32_t package_id = get_package_id(resid);
647 const uint8_t type_idx = get_type_id(resid) - 1;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800648 const uint16_t entry_idx = get_entry_id(resid);
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700649 uint8_t package_idx = package_ids_[package_id];
Ryan Mitchell80094e32020-11-16 23:08:18 +0000650 if (UNLIKELY(package_idx == 0xff)) {
Mark Hansenb406b0e2022-10-14 02:18:37 +0000651 ANDROID_LOG(ERROR) << base::StringPrintf("No package ID %02x found for resource ID 0x%08x.",
Ryan Mitchell2fe23472019-02-27 09:43:01 -0800652 package_id, resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000653 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -0500654 }
655
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800656 const PackageGroup& package_group = package_groups_[package_idx];
Ryan Mitchell80094e32020-11-16 23:08:18 +0000657 auto result = FindEntryInternal(package_group, type_idx, entry_idx, *desired_config,
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800658 stop_at_first_match, ignore_configuration);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000659 if (UNLIKELY(!result.has_value())) {
660 return base::unexpected(result.error());
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700661 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800662
Jackal Guo552b45d2021-09-29 10:52:19 +0800663 bool overlaid = false;
Yurii Zubrytskyi1cf74932023-05-01 14:35:48 -0700664 if (!stop_at_first_match && !ignore_configuration) {
Yurii Zubrytskyi657f3c62023-05-10 13:16:23 -0700665 const auto& assets = GetApkAssets(result->cookie);
Yurii Zubrytskyi1cf74932023-05-01 14:35:48 -0700666 if (!assets) {
667 ALOGE("Found expired ApkAssets #%d for resource ID 0x%08x.", result->cookie, resid);
668 return base::unexpected(std::nullopt);
669 }
670 if (!assets->IsLoader()) {
671 for (const auto& id_map : package_group.overlays_) {
672 auto overlay_entry = id_map.overlay_res_maps_.Lookup(resid);
673 if (!overlay_entry) {
674 // No id map entry exists for this target resource.
Jeremy Meyerbe2b7792022-08-23 17:42:50 +0000675 continue;
676 }
Yurii Zubrytskyi1cf74932023-05-01 14:35:48 -0700677 if (overlay_entry.IsInlineValue()) {
678 // The target resource is overlaid by an inline value not represented by a resource.
679 ConfigDescription best_frro_config;
680 Res_value best_frro_value;
681 bool frro_found = false;
682 for( const auto& [config, value] : overlay_entry.GetInlineValue()) {
683 if ((!frro_found || config.isBetterThan(best_frro_config, desired_config))
684 && config.match(*desired_config)) {
685 frro_found = true;
686 best_frro_config = config;
687 best_frro_value = value;
688 }
689 }
690 if (!frro_found) {
691 continue;
692 }
693 result->entry = best_frro_value;
694 result->dynamic_ref_table = id_map.overlay_res_maps_.GetOverlayDynamicRefTable();
695 result->cookie = id_map.cookie;
696
697 if (UNLIKELY(logging_enabled)) {
698 last_resolution_.steps.push_back(
699 Resolution::Step{Resolution::Step::Type::OVERLAID_INLINE, String8(), result->cookie});
700 if (auto path = assets->GetPath()) {
701 const std::string overlay_path = path->data();
702 if (IsFabricatedOverlay(overlay_path)) {
703 // FRRO don't have package name so we use the creating package here.
704 String8 frro_name = String8("FRRO");
705 // Get the first part of it since the expected one should be like
706 // {overlayPackageName}-{overlayName}-{4 alphanumeric chars}.frro
707 // under /data/resource-cache/.
708 const std::string name = overlay_path.substr(overlay_path.rfind('/') + 1);
709 const size_t end = name.find('-');
710 if (frro_name.size() != overlay_path.size() && end != std::string::npos) {
711 frro_name.append(base::StringPrintf(" created by %s",
712 name.substr(0 /* pos */,
713 end).c_str()).c_str());
714 }
715 last_resolution_.best_package_name = frro_name;
716 } else {
717 last_resolution_.best_package_name = result->package_name->c_str();
718 }
719 }
720 overlaid = true;
721 }
722 continue;
723 }
724
725 auto overlay_result = FindEntry(overlay_entry.GetResourceId(), density_override,
726 false /* stop_at_first_match */,
727 false /* ignore_configuration */);
728 if (UNLIKELY(IsIOError(overlay_result))) {
729 return base::unexpected(overlay_result.error());
730 }
731 if (!overlay_result.has_value()) {
732 continue;
733 }
734
735 if (!overlay_result->config.isBetterThan(result->config, desired_config)
736 && overlay_result->config.compare(result->config) != 0) {
737 // The configuration of the entry for the overlay must be equal to or better than the target
738 // configuration to be chosen as the better value.
739 continue;
740 }
741
742 result->cookie = overlay_result->cookie;
743 result->entry = overlay_result->entry;
744 result->config = overlay_result->config;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000745 result->dynamic_ref_table = id_map.overlay_res_maps_.GetOverlayDynamicRefTable();
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800746
747 if (UNLIKELY(logging_enabled)) {
748 last_resolution_.steps.push_back(
Yurii Zubrytskyi1cf74932023-05-01 14:35:48 -0700749 Resolution::Step{Resolution::Step::Type::OVERLAID, overlay_result->config.toString(),
750 overlay_result->cookie});
751 last_resolution_.best_package_name =
752 overlay_result->package_name->c_str();
Jackal Guo552b45d2021-09-29 10:52:19 +0800753 overlaid = true;
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800754 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700755 }
756 }
757 }
758
Ryan Mitchell80094e32020-11-16 23:08:18 +0000759 if (UNLIKELY(logging_enabled)) {
760 last_resolution_.cookie = result->cookie;
761 last_resolution_.type_string_ref = result->type_string_ref;
762 last_resolution_.entry_string_ref = result->entry_string_ref;
Jackal Guo552b45d2021-09-29 10:52:19 +0800763 last_resolution_.best_config_name = result->config.toString();
764 if (!overlaid) {
765 last_resolution_.best_package_name = result->package_name->c_str();
766 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700767 }
768
Ryan Mitchell80094e32020-11-16 23:08:18 +0000769 return result;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700770}
771
Ryan Mitchell80094e32020-11-16 23:08:18 +0000772base::expected<FindEntryResult, NullOrIOError> AssetManager2::FindEntryInternal(
773 const PackageGroup& package_group, uint8_t type_idx, uint16_t entry_idx,
774 const ResTable_config& desired_config, bool stop_at_first_match,
775 bool ignore_configuration) const {
776 const bool logging_enabled = resource_resolution_logging_enabled_;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800777 ApkAssetsCookie best_cookie = kInvalidCookie;
778 const LoadedPackage* best_package = nullptr;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000779 incfs::verified_map_ptr<ResTable_type> best_type;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800780 const ResTable_config* best_config = nullptr;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000781 uint32_t best_offset = 0U;
782 uint32_t type_flags = 0U;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800783
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800784 // If `desired_config` is not the same as the set configuration or the caller will accept a value
785 // from any configuration, then we cannot use our filtered list of types since it only it contains
786 // types matched to the set configuration.
787 const bool use_filtered = !ignore_configuration && &desired_config == &configuration_;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800788
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700789 const size_t package_count = package_group.packages_.size();
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800790 for (size_t pi = 0; pi < package_count; pi++) {
791 const ConfiguredPackage& loaded_package_impl = package_group.packages_[pi];
792 const LoadedPackage* loaded_package = loaded_package_impl.loaded_package_;
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800793 const ApkAssetsCookie cookie = package_group.cookies_[pi];
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800794
795 // If the type IDs are offset in this package, we need to take that into account when searching
796 // for a type.
797 const TypeSpec* type_spec = loaded_package->GetTypeSpecByTypeIndex(type_idx);
798 if (UNLIKELY(type_spec == nullptr)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700799 continue;
800 }
801
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800802 // Allow custom loader packages to overlay resource values with configurations equivalent to the
803 // current best configuration.
804 const bool package_is_loader = loaded_package->IsCustomLoader();
805
Ryan Mitchell80094e32020-11-16 23:08:18 +0000806 auto entry_flags = type_spec->GetFlagsForEntryIndex(entry_idx);
Bernie Innocenti58cf8e32020-12-19 15:31:52 +0900807 if (UNLIKELY(!entry_flags.has_value())) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000808 return base::unexpected(entry_flags.error());
809 }
810 type_flags |= entry_flags.value();
811
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800812 const FilteredConfigGroup& filtered_group = loaded_package_impl.filtered_configs_[type_idx];
813 const size_t type_entry_count = (use_filtered) ? filtered_group.type_entries.size()
814 : type_spec->type_entries.size();
815 for (size_t i = 0; i < type_entry_count; i++) {
816 const TypeSpec::TypeEntry* type_entry = (use_filtered) ? filtered_group.type_entries[i]
817 : &type_spec->type_entries[i];
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800818
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800819 // We can skip calling ResTable_config::match() if the caller does not care for the
820 // configuration to match or if we're using the list of types that have already had their
821 // configuration matched.
822 const ResTable_config& this_config = type_entry->config;
823 if (!(use_filtered || ignore_configuration || this_config.match(desired_config))) {
824 continue;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800825 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800826
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800827 Resolution::Step::Type resolution_type;
828 if (best_config == nullptr) {
829 resolution_type = Resolution::Step::Type::INITIAL;
830 } else if (this_config.isBetterThan(*best_config, &desired_config)) {
831 resolution_type = Resolution::Step::Type::BETTER_MATCH;
832 } else if (package_is_loader && this_config.compare(*best_config) == 0) {
833 resolution_type = Resolution::Step::Type::OVERLAID;
834 } else {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000835 if (UNLIKELY(logging_enabled)) {
Jackal Guo552b45d2021-09-29 10:52:19 +0800836 last_resolution_.steps.push_back(Resolution::Step{Resolution::Step::Type::SKIPPED,
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800837 this_config.toString(),
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800838 cookie});
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800839 }
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800840 continue;
841 }
842
843 // The configuration matches and is better than the previous selection.
844 // Find the entry value if it exists for this configuration.
845 const auto& type = type_entry->type;
846 const auto offset = LoadedPackage::GetEntryOffset(type, entry_idx);
847 if (UNLIKELY(IsIOError(offset))) {
848 return base::unexpected(offset.error());
849 }
850
851 if (!offset.has_value()) {
852 if (UNLIKELY(logging_enabled)) {
Jackal Guo552b45d2021-09-29 10:52:19 +0800853 last_resolution_.steps.push_back(Resolution::Step{Resolution::Step::Type::NO_ENTRY,
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800854 this_config.toString(),
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800855 cookie});
856 }
857 continue;
858 }
859
860 best_cookie = cookie;
861 best_package = loaded_package;
862 best_type = type;
863 best_config = &this_config;
864 best_offset = offset.value();
865
866 if (UNLIKELY(logging_enabled)) {
867 last_resolution_.steps.push_back(Resolution::Step{resolution_type,
868 this_config.toString(),
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800869 cookie});
870 }
871
872 // Any configuration will suffice, so break.
873 if (stop_at_first_match) {
874 break;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700875 }
876 }
877 }
878
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800879 if (UNLIKELY(best_cookie == kInvalidCookie)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000880 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700881 }
882
Eric Miao368cd192022-09-09 15:46:14 -0700883 auto best_entry_verified = LoadedPackage::GetEntryFromOffset(best_type, best_offset);
884 if (!best_entry_verified.has_value()) {
885 return base::unexpected(best_entry_verified.error());
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800886 }
887
Eric Miao368cd192022-09-09 15:46:14 -0700888 const auto entry = GetEntryValue(*best_entry_verified);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000889 if (!entry.has_value()) {
890 return base::unexpected(entry.error());
891 }
Winson2f3669b2019-01-11 11:28:34 -0800892
Ryan Mitchell80094e32020-11-16 23:08:18 +0000893 return FindEntryResult{
894 .cookie = best_cookie,
895 .entry = *entry,
896 .config = *best_config,
897 .type_flags = type_flags,
898 .package_name = &best_package->GetPackageName(),
899 .type_string_ref = StringPoolRef(best_package->GetTypeStringPool(), best_type->id - 1),
900 .entry_string_ref = StringPoolRef(best_package->GetKeyStringPool(),
Eric Miao368cd192022-09-09 15:46:14 -0700901 (*best_entry_verified)->key()),
Ryan Mitchell80094e32020-11-16 23:08:18 +0000902 .dynamic_ref_table = package_group.dynamic_ref_table.get(),
903 };
Adam Lesinski7ad11102016-10-28 16:39:15 -0700904}
905
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700906void AssetManager2::ResetResourceResolution() const {
Yurii Zubrytskyi657f3c62023-05-10 13:16:23 -0700907 last_resolution_ = Resolution{};
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700908}
909
Winson2f3669b2019-01-11 11:28:34 -0800910void AssetManager2::SetResourceResolutionLoggingEnabled(bool enabled) {
911 resource_resolution_logging_enabled_ = enabled;
Winson2f3669b2019-01-11 11:28:34 -0800912 if (!enabled) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700913 ResetResourceResolution();
Winson2f3669b2019-01-11 11:28:34 -0800914 }
915}
916
917std::string AssetManager2::GetLastResourceResolution() const {
918 if (!resource_resolution_logging_enabled_) {
919 LOG(ERROR) << "Must enable resource resolution logging before getting path.";
Ryan Mitchell80094e32020-11-16 23:08:18 +0000920 return {};
Winson2f3669b2019-01-11 11:28:34 -0800921 }
922
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800923 const ApkAssetsCookie cookie = last_resolution_.cookie;
Winson2f3669b2019-01-11 11:28:34 -0800924 if (cookie == kInvalidCookie) {
925 LOG(ERROR) << "AssetManager hasn't resolved a resource to read resolution path.";
Ryan Mitchell80094e32020-11-16 23:08:18 +0000926 return {};
Winson2f3669b2019-01-11 11:28:34 -0800927 }
928
Yurii Zubrytskyi657f3c62023-05-10 13:16:23 -0700929 auto op = StartOperation();
930
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800931 const uint32_t resid = last_resolution_.resid;
Yurii Zubrytskyi657f3c62023-05-10 13:16:23 -0700932 const auto& assets = GetApkAssets(cookie);
Yurii Zubrytskyi1cf74932023-05-01 14:35:48 -0700933 const auto package =
934 assets ? assets->GetLoadedArsc()->GetPackageById(get_package_id(resid)) : nullptr;
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800935
Winson2f3669b2019-01-11 11:28:34 -0800936 std::string resource_name_string;
Winson2f3669b2019-01-11 11:28:34 -0800937 if (package != nullptr) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000938 auto resource_name = ToResourceName(last_resolution_.type_string_ref,
939 last_resolution_.entry_string_ref,
940 package->GetPackageName());
941 resource_name_string = resource_name.has_value() ?
942 ToFormattedResourceString(resource_name.value()) : "<unknown>";
Winson2f3669b2019-01-11 11:28:34 -0800943 }
944
945 std::stringstream log_stream;
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800946 log_stream << base::StringPrintf("Resolution for 0x%08x %s\n"
947 "\tFor config - %s", resid, resource_name_string.c_str(),
948 configuration_.toString().c_str());
Winson2f3669b2019-01-11 11:28:34 -0800949
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800950 for (const Resolution::Step& step : last_resolution_.steps) {
951 const static std::unordered_map<Resolution::Step::Type, const char*> kStepStrings = {
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800952 {Resolution::Step::Type::INITIAL, "Found initial"},
953 {Resolution::Step::Type::BETTER_MATCH, "Found better"},
954 {Resolution::Step::Type::OVERLAID, "Overlaid"},
955 {Resolution::Step::Type::OVERLAID_INLINE, "Overlaid inline"},
956 {Resolution::Step::Type::SKIPPED, "Skipped"},
957 {Resolution::Step::Type::NO_ENTRY, "No entry"}
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800958 };
959
960 const auto prefix = kStepStrings.find(step.type);
961 if (prefix == kStepStrings.end()) {
962 continue;
Winson2f3669b2019-01-11 11:28:34 -0800963 }
Yurii Zubrytskyi657f3c62023-05-10 13:16:23 -0700964 const auto& assets = GetApkAssets(step.cookie);
Yurii Zubrytskyi1cf74932023-05-01 14:35:48 -0700965 log_stream << "\n\t" << prefix->second << ": "
966 << (assets ? assets->GetDebugName() : "<null>") << " #" << step.cookie;
Tomasz Wasilczyk7e22cab2023-08-24 19:02:33 +0000967 if (!step.config_name.empty()) {
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800968 log_stream << " - " << step.config_name;
Winson2f3669b2019-01-11 11:28:34 -0800969 }
970 }
971
Jackal Guo552b45d2021-09-29 10:52:19 +0800972 log_stream << "\nBest matching is from "
Tomasz Wasilczyk7e22cab2023-08-24 19:02:33 +0000973 << (last_resolution_.best_config_name.empty() ? "default"
Tomasz Wasilczyk835dfe52023-08-17 16:27:22 +0000974 : last_resolution_.best_config_name.c_str())
Jackal Guo552b45d2021-09-29 10:52:19 +0800975 << " configuration of " << last_resolution_.best_package_name;
Winson2f3669b2019-01-11 11:28:34 -0800976 return log_stream.str();
977}
978
Felka Chang00964e92021-12-10 01:19:08 +0800979base::expected<uint32_t, NullOrIOError> AssetManager2::GetParentThemeResourceId(uint32_t resid)
980const {
981 auto entry = FindEntry(resid, 0u /* density_override */,
982 false /* stop_at_first_match */,
983 false /* ignore_configuration */);
984 if (!entry.has_value()) {
985 return base::unexpected(entry.error());
986 }
987
988 auto entry_map = std::get_if<incfs::verified_map_ptr<ResTable_map_entry>>(&entry->entry);
989 if (entry_map == nullptr) {
990 // Not a bag, nothing to do.
991 return base::unexpected(std::nullopt);
992 }
993
994 auto map = *entry_map;
995 const uint32_t parent_resid = dtohl(map->parent.ident);
996
997 return parent_resid;
998}
999
Ryan Mitchell80094e32020-11-16 23:08:18 +00001000base::expected<AssetManager2::ResourceName, NullOrIOError> AssetManager2::GetResourceName(
1001 uint32_t resid) const {
1002 auto result = FindEntry(resid, 0u /* density_override */, true /* stop_at_first_match */,
1003 true /* ignore_configuration */);
1004 if (!result.has_value()) {
1005 return base::unexpected(result.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001006 }
1007
Ryan Mitchell80094e32020-11-16 23:08:18 +00001008 return ToResourceName(result->type_string_ref,
1009 result->entry_string_ref,
1010 *result->package_name);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001011}
1012
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001013base::expected<uint32_t, NullOrIOError> AssetManager2::GetResourceTypeSpecFlags(
1014 uint32_t resid) const {
1015 auto result = FindEntry(resid, 0u /* density_override */, false /* stop_at_first_match */,
1016 true /* ignore_configuration */);
1017 if (!result.has_value()) {
1018 return base::unexpected(result.error());
1019 }
1020 return result->type_flags;
1021}
1022
Ryan Mitchell80094e32020-11-16 23:08:18 +00001023base::expected<AssetManager2::SelectedValue, NullOrIOError> AssetManager2::GetResource(
1024 uint32_t resid, bool may_be_bag, uint16_t density_override) const {
1025 auto result = FindEntry(resid, density_override, false /* stop_at_first_match */,
1026 false /* ignore_configuration */);
1027 if (!result.has_value()) {
1028 return base::unexpected(result.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001029 }
1030
Ryan Mitchell80094e32020-11-16 23:08:18 +00001031 auto result_map_entry = std::get_if<incfs::verified_map_ptr<ResTable_map_entry>>(&result->entry);
Ryan Mitchellbf1f45b2020-09-29 17:22:52 -07001032 if (result_map_entry != nullptr) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001033 if (!may_be_bag) {
1034 LOG(ERROR) << base::StringPrintf("Resource %08x is a complex map type.", resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001035 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001036 }
Adam Lesinski0c405242017-01-13 20:47:26 -08001037
1038 // Create a reference since we can't represent this complex type as a Res_value.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001039 return SelectedValue(Res_value::TYPE_REFERENCE, resid, result->cookie, result->type_flags,
1040 resid, result->config);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001041 }
1042
Adam Lesinskida431a22016-12-29 16:08:16 -05001043 // Convert the package ID to the runtime assigned package ID.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001044 Res_value value = std::get<Res_value>(result->entry);
1045 result->dynamic_ref_table->lookupResourceValue(&value);
Adam Lesinskida431a22016-12-29 16:08:16 -05001046
Ryan Mitchell80094e32020-11-16 23:08:18 +00001047 return SelectedValue(value.dataType, value.data, result->cookie, result->type_flags,
1048 resid, result->config);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001049}
1050
Ryan Mitchell80094e32020-11-16 23:08:18 +00001051base::expected<std::monostate, NullOrIOError> AssetManager2::ResolveReference(
Ryan Mitchella45506e2020-11-16 23:08:18 +00001052 AssetManager2::SelectedValue& value, bool cache_value) const {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001053 if (value.type != Res_value::TYPE_REFERENCE || value.data == 0U) {
1054 // Not a reference. Nothing to do.
1055 return {};
Adam Lesinski0c405242017-01-13 20:47:26 -08001056 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001057
Ryan Mitchella45506e2020-11-16 23:08:18 +00001058 const uint32_t original_flags = value.flags;
1059 const uint32_t original_resid = value.data;
1060 if (cache_value) {
1061 auto cached_value = cached_resolved_values_.find(value.data);
1062 if (cached_value != cached_resolved_values_.end()) {
1063 value = cached_value->second;
1064 value.flags |= original_flags;
1065 return {};
1066 }
1067 }
1068
1069 uint32_t combined_flags = 0U;
1070 uint32_t resolve_resid = original_resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001071 constexpr const uint32_t kMaxIterations = 20;
1072 for (uint32_t i = 0U;; i++) {
1073 auto result = GetResource(resolve_resid, true /*may_be_bag*/);
1074 if (!result.has_value()) {
Ryan Mitchelle7ab6272020-11-13 18:06:15 -08001075 value.resid = resolve_resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001076 return base::unexpected(result.error());
1077 }
1078
Ryan Mitchelle7ab6272020-11-13 18:06:15 -08001079 // If resource resolution fails, the value should be set to the last reference that was able to
1080 // be resolved successfully.
1081 value = *result;
1082 value.flags |= combined_flags;
1083
Ryan Mitchell80094e32020-11-16 23:08:18 +00001084 if (result->type != Res_value::TYPE_REFERENCE ||
1085 result->data == Res_value::DATA_NULL_UNDEFINED ||
1086 result->data == resolve_resid || i == kMaxIterations) {
1087 // This reference can't be resolved, so exit now and let the caller deal with it.
Ryan Mitchella45506e2020-11-16 23:08:18 +00001088 if (cache_value) {
1089 cached_resolved_values_[original_resid] = value;
1090 }
1091
1092 // Above value is cached without original_flags to ensure they don't get included in future
1093 // queries that hit the cache
1094 value.flags |= original_flags;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001095 return {};
1096 }
1097
Ryan Mitchelle7ab6272020-11-13 18:06:15 -08001098 combined_flags = result->flags;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001099 resolve_resid = result->data;
1100 }
Adam Lesinski0c405242017-01-13 20:47:26 -08001101}
1102
Ryan Mitchell80094e32020-11-16 23:08:18 +00001103const std::vector<uint32_t> AssetManager2::GetBagResIdStack(uint32_t resid) const {
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001104 auto cached_iter = cached_bag_resid_stacks_.find(resid);
1105 if (cached_iter != cached_bag_resid_stacks_.end()) {
1106 return cached_iter->second;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001107 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001108
1109 std::vector<uint32_t> found_resids;
1110 GetBag(resid, found_resids);
1111 cached_bag_resid_stacks_.emplace(resid, found_resids);
1112 return found_resids;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001113}
1114
Ryan Mitchell80094e32020-11-16 23:08:18 +00001115base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::ResolveBag(
1116 AssetManager2::SelectedValue& value) const {
1117 if (UNLIKELY(value.type != Res_value::TYPE_REFERENCE)) {
1118 return base::unexpected(std::nullopt);
1119 }
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001120
Ryan Mitchell80094e32020-11-16 23:08:18 +00001121 auto bag = GetBag(value.data);
1122 if (bag.has_value()) {
1123 value.flags |= (*bag)->type_spec_flags;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001124 }
1125 return bag;
y57cd1952018-04-12 14:26:23 -07001126}
1127
Ryan Mitchell80094e32020-11-16 23:08:18 +00001128base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::GetBag(uint32_t resid) const {
1129 std::vector<uint32_t> found_resids;
1130 const auto bag = GetBag(resid, found_resids);
Yurii Zubrytskyiab3cb302022-10-11 12:15:52 -07001131 cached_bag_resid_stacks_.emplace(resid, std::move(found_resids));
Ryan Mitchell80094e32020-11-16 23:08:18 +00001132 return bag;
Ryan Mitchell155d5392020-02-10 13:35:24 -08001133}
1134
Ryan Mitchell80094e32020-11-16 23:08:18 +00001135base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::GetBag(
1136 uint32_t resid, std::vector<uint32_t>& child_resids) const {
1137 if (auto cached_iter = cached_bags_.find(resid); cached_iter != cached_bags_.end()) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001138 return cached_iter->second.get();
1139 }
1140
Ryan Mitchell80094e32020-11-16 23:08:18 +00001141 auto entry = FindEntry(resid, 0u /* density_override */, false /* stop_at_first_match */,
1142 false /* ignore_configuration */);
1143 if (!entry.has_value()) {
1144 return base::unexpected(entry.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001145 }
1146
Ryan Mitchell80094e32020-11-16 23:08:18 +00001147 auto entry_map = std::get_if<incfs::verified_map_ptr<ResTable_map_entry>>(&entry->entry);
1148 if (entry_map == nullptr) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001149 // Not a bag, nothing to do.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001150 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001151 }
1152
Ryan Mitchell80094e32020-11-16 23:08:18 +00001153 auto map = *entry_map;
1154 auto map_entry = map.offset(dtohs(map->size)).convert<ResTable_map>();
1155 const auto map_entry_end = map_entry + dtohl(map->count);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001156
y57cd1952018-04-12 14:26:23 -07001157 // Keep track of ids that have already been seen to prevent infinite loops caused by circular
Ryan Mitchell80094e32020-11-16 23:08:18 +00001158 // dependencies between bags.
y57cd1952018-04-12 14:26:23 -07001159 child_resids.push_back(resid);
1160
Adam Lesinskida431a22016-12-29 16:08:16 -05001161 uint32_t parent_resid = dtohl(map->parent.ident);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001162 if (parent_resid == 0U ||
1163 std::find(child_resids.begin(), child_resids.end(), parent_resid) != child_resids.end()) {
1164 // There is no parent or a circular parental dependency exist, meaning there is nothing to
1165 // inherit and we can do a simple copy of the entries in the map.
Adam Lesinski7ad11102016-10-28 16:39:15 -07001166 const size_t entry_count = map_entry_end - map_entry;
1167 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
1168 malloc(sizeof(ResolvedBag) + (entry_count * sizeof(ResolvedBag::Entry))))};
Ryan Mitchell155d5392020-02-10 13:35:24 -08001169
1170 bool sort_entries = false;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001171 for (auto new_entry = new_bag->entries; map_entry != map_entry_end; ++map_entry) {
1172 if (UNLIKELY(!map_entry)) {
1173 return base::unexpected(IOError::PAGES_MISSING);
1174 }
1175
Adam Lesinskida431a22016-12-29 16:08:16 -05001176 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001177 if (!is_internal_resid(new_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -05001178 // Attributes, arrays, etc don't have a resource id as the name. They specify
1179 // other data, which would be wrong to change via a lookup.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001180 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001181 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
1182 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001183 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001184 }
1185 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001186
1187 new_entry->cookie = entry->cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -05001188 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001189 new_entry->key_pool = nullptr;
1190 new_entry->type_pool = nullptr;
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001191 new_entry->style = resid;
Adam Lesinski30080e22017-10-16 16:18:09 -07001192 new_entry->value.copyFrom_dtoh(map_entry->value);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001193 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1194 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001195 LOG(ERROR) << base::StringPrintf(
1196 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
1197 new_entry->value.data, new_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001198 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001199 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001200
Ryan Mitchell155d5392020-02-10 13:35:24 -08001201 sort_entries = sort_entries ||
1202 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001203 ++new_entry;
1204 }
Ryan Mitchell155d5392020-02-10 13:35:24 -08001205
1206 if (sort_entries) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001207 std::sort(new_bag->entries, new_bag->entries + entry_count,
1208 [](auto&& lhs, auto&& rhs) { return lhs.key < rhs.key; });
Ryan Mitchell155d5392020-02-10 13:35:24 -08001209 }
1210
Ryan Mitchell80094e32020-11-16 23:08:18 +00001211 new_bag->type_spec_flags = entry->type_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001212 new_bag->entry_count = static_cast<uint32_t>(entry_count);
1213 ResolvedBag* result = new_bag.get();
1214 cached_bags_[resid] = std::move(new_bag);
1215 return result;
1216 }
1217
Adam Lesinskida431a22016-12-29 16:08:16 -05001218 // In case the parent is a dynamic reference, resolve it.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001219 entry->dynamic_ref_table->lookupResourceId(&parent_resid);
Adam Lesinskida431a22016-12-29 16:08:16 -05001220
Adam Lesinski7ad11102016-10-28 16:39:15 -07001221 // Get the parent and do a merge of the keys.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001222 const auto parent_bag = GetBag(parent_resid, child_resids);
1223 if (UNLIKELY(!parent_bag.has_value())) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001224 // Failed to get the parent that should exist.
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001225 LOG(ERROR) << base::StringPrintf("Failed to find parent 0x%08x of bag 0x%08x.", parent_resid,
1226 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001227 return base::unexpected(parent_bag.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001228 }
1229
Adam Lesinski7ad11102016-10-28 16:39:15 -07001230 // Create the max possible entries we can make. Once we construct the bag,
1231 // we will realloc to fit to size.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001232 const size_t max_count = (*parent_bag)->entry_count + dtohl(map->count);
George Burgess IV09b119f2017-07-25 15:00:04 -07001233 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
1234 malloc(sizeof(ResolvedBag) + (max_count * sizeof(ResolvedBag::Entry))))};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001235 ResolvedBag::Entry* new_entry = new_bag->entries;
1236
Ryan Mitchell80094e32020-11-16 23:08:18 +00001237 const ResolvedBag::Entry* parent_entry = (*parent_bag)->entries;
1238 const ResolvedBag::Entry* const parent_entry_end = parent_entry + (*parent_bag)->entry_count;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001239
1240 // The keys are expected to be in sorted order. Merge the two bags.
Ryan Mitchell155d5392020-02-10 13:35:24 -08001241 bool sort_entries = false;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001242 while (map_entry != map_entry_end && parent_entry != parent_entry_end) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001243 if (UNLIKELY(!map_entry)) {
1244 return base::unexpected(IOError::PAGES_MISSING);
1245 }
1246
Adam Lesinskida431a22016-12-29 16:08:16 -05001247 uint32_t child_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001248 if (!is_internal_resid(child_key)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001249 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&child_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001250 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", child_key,
1251 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001252 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001253 }
1254 }
1255
Adam Lesinski7ad11102016-10-28 16:39:15 -07001256 if (child_key <= parent_entry->key) {
1257 // Use the child key if it comes before the parent
1258 // or is equal to the parent (overrides).
Ryan Mitchell80094e32020-11-16 23:08:18 +00001259 new_entry->cookie = entry->cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001260 new_entry->key = child_key;
1261 new_entry->key_pool = nullptr;
1262 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -07001263 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001264 new_entry->style = resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001265 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1266 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001267 LOG(ERROR) << base::StringPrintf(
1268 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
1269 new_entry->value.data, child_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001270 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001271 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001272 ++map_entry;
1273 } else {
1274 // Take the parent entry as-is.
1275 memcpy(new_entry, parent_entry, sizeof(*new_entry));
1276 }
1277
Ryan Mitchell155d5392020-02-10 13:35:24 -08001278 sort_entries = sort_entries ||
1279 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001280 if (child_key >= parent_entry->key) {
1281 // Move to the next parent entry if we used it or it was overridden.
1282 ++parent_entry;
1283 }
1284 // Increment to the next entry to fill.
1285 ++new_entry;
1286 }
1287
1288 // Finish the child entries if they exist.
1289 while (map_entry != map_entry_end) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001290 if (UNLIKELY(!map_entry)) {
1291 return base::unexpected(IOError::PAGES_MISSING);
1292 }
1293
Adam Lesinskida431a22016-12-29 16:08:16 -05001294 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001295 if (!is_internal_resid(new_key)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001296 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001297 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
1298 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001299 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001300 }
1301 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001302 new_entry->cookie = entry->cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -05001303 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001304 new_entry->key_pool = nullptr;
1305 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -07001306 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001307 new_entry->style = resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001308 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1309 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001310 LOG(ERROR) << base::StringPrintf("Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.",
1311 new_entry->value.dataType, new_entry->value.data, new_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001312 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001313 }
Ryan Mitchell155d5392020-02-10 13:35:24 -08001314 sort_entries = sort_entries ||
1315 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001316 ++map_entry;
1317 ++new_entry;
1318 }
1319
1320 // Finish the parent entries if they exist.
1321 if (parent_entry != parent_entry_end) {
1322 // Take the rest of the parent entries as-is.
1323 const size_t num_entries_to_copy = parent_entry_end - parent_entry;
1324 memcpy(new_entry, parent_entry, num_entries_to_copy * sizeof(*new_entry));
1325 new_entry += num_entries_to_copy;
1326 }
1327
1328 // Resize the resulting array to fit.
1329 const size_t actual_count = new_entry - new_bag->entries;
1330 if (actual_count != max_count) {
George Burgess IV09b119f2017-07-25 15:00:04 -07001331 new_bag.reset(reinterpret_cast<ResolvedBag*>(realloc(
1332 new_bag.release(), sizeof(ResolvedBag) + (actual_count * sizeof(ResolvedBag::Entry)))));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001333 }
1334
Ryan Mitchell155d5392020-02-10 13:35:24 -08001335 if (sort_entries) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001336 std::sort(new_bag->entries, new_bag->entries + actual_count,
1337 [](auto&& lhs, auto&& rhs) { return lhs.key < rhs.key; });
Ryan Mitchell155d5392020-02-10 13:35:24 -08001338 }
1339
Adam Lesinski1a1e9c22017-10-13 15:45:34 -07001340 // Combine flags from the parent and our own bag.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001341 new_bag->type_spec_flags = entry->type_flags | (*parent_bag)->type_spec_flags;
George Burgess IV09b119f2017-07-25 15:00:04 -07001342 new_bag->entry_count = static_cast<uint32_t>(actual_count);
1343 ResolvedBag* result = new_bag.get();
1344 cached_bags_[resid] = std::move(new_bag);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001345 return result;
1346}
1347
Yurii Zubrytskyia5775142022-11-02 17:49:49 -07001348static bool Utf8ToUtf16(StringPiece str, std::u16string* out) {
Adam Lesinski929d6512017-01-16 19:11:19 -08001349 ssize_t len =
1350 utf8_to_utf16_length(reinterpret_cast<const uint8_t*>(str.data()), str.size(), false);
1351 if (len < 0) {
1352 return false;
1353 }
1354 out->resize(static_cast<size_t>(len));
1355 utf8_to_utf16(reinterpret_cast<const uint8_t*>(str.data()), str.size(), &*out->begin(),
1356 static_cast<size_t>(len + 1));
1357 return true;
1358}
1359
Ryan Mitchell80094e32020-11-16 23:08:18 +00001360base::expected<uint32_t, NullOrIOError> AssetManager2::GetResourceId(
1361 const std::string& resource_name, const std::string& fallback_type,
1362 const std::string& fallback_package) const {
Adam Lesinski929d6512017-01-16 19:11:19 -08001363 StringPiece package_name, type, entry;
1364 if (!ExtractResourceName(resource_name, &package_name, &type, &entry)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001365 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001366 }
1367
1368 if (entry.empty()) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001369 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001370 }
1371
1372 if (package_name.empty()) {
1373 package_name = fallback_package;
1374 }
1375
1376 if (type.empty()) {
1377 type = fallback_type;
1378 }
1379
1380 std::u16string type16;
1381 if (!Utf8ToUtf16(type, &type16)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001382 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001383 }
1384
1385 std::u16string entry16;
1386 if (!Utf8ToUtf16(entry, &entry16)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001387 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001388 }
1389
1390 const StringPiece16 kAttr16 = u"attr";
1391 const static std::u16string kAttrPrivate16 = u"^attr-private";
1392
1393 for (const PackageGroup& package_group : package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001394 for (const ConfiguredPackage& package_impl : package_group.packages_) {
1395 const LoadedPackage* package = package_impl.loaded_package_;
Adam Lesinski929d6512017-01-16 19:11:19 -08001396 if (package_name != package->GetPackageName()) {
1397 // All packages in the same group are expected to have the same package name.
1398 break;
1399 }
1400
Ryan Mitchell80094e32020-11-16 23:08:18 +00001401 base::expected<uint32_t, NullOrIOError> resid = package->FindEntryByName(type16, entry16);
1402 if (UNLIKELY(IsIOError(resid))) {
1403 return base::unexpected(resid.error());
1404 }
1405
1406 if (!resid.has_value() && kAttr16 == type16) {
Adam Lesinski929d6512017-01-16 19:11:19 -08001407 // Private attributes in libraries (such as the framework) are sometimes encoded
1408 // under the type '^attr-private' in order to leave the ID space of public 'attr'
1409 // free for future additions. Check '^attr-private' for the same name.
1410 resid = package->FindEntryByName(kAttrPrivate16, entry16);
1411 }
1412
Ryan Mitchell80094e32020-11-16 23:08:18 +00001413 if (resid.has_value()) {
1414 return fix_package_id(*resid, package_group.dynamic_ref_table->mAssignedPackageId);
Adam Lesinski929d6512017-01-16 19:11:19 -08001415 }
1416 }
1417 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001418 return base::unexpected(std::nullopt);
Adam Lesinski0c405242017-01-13 20:47:26 -08001419}
1420
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001421void AssetManager2::RebuildFilterList() {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001422 for (PackageGroup& group : package_groups_) {
Yurii Zubrytskyidbce3562022-11-14 22:26:10 -08001423 for (ConfiguredPackage& package : group.packages_) {
1424 package.filtered_configs_.forEachItem([](auto, auto& fcg) { fcg.type_entries.clear(); });
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001425 // Create the filters here.
Yurii Zubrytskyidbce3562022-11-14 22:26:10 -08001426 package.loaded_package_->ForEachTypeSpec([&](const TypeSpec& type_spec, uint8_t type_id) {
Yurii Zubrytskyi59dab3ba2022-11-03 00:08:49 -07001427 FilteredConfigGroup* group = nullptr;
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001428 for (const auto& type_entry : type_spec.type_entries) {
1429 if (type_entry.config.match(configuration_)) {
Yurii Zubrytskyi59dab3ba2022-11-03 00:08:49 -07001430 if (!group) {
Yurii Zubrytskyidbce3562022-11-14 22:26:10 -08001431 group = &package.filtered_configs_.editItemAt(type_id - 1);
Yurii Zubrytskyi59dab3ba2022-11-03 00:08:49 -07001432 }
1433 group->type_entries.push_back(&type_entry);
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001434 }
1435 }
1436 });
Yurii Zubrytskyidbce3562022-11-14 22:26:10 -08001437 package.filtered_configs_.trimBuckets(
1438 [](const auto& fcg) { return fcg.type_entries.empty(); });
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001439 }
1440 }
1441}
1442
Adam Lesinski7ad11102016-10-28 16:39:15 -07001443void AssetManager2::InvalidateCaches(uint32_t diff) {
Ryan Mitchell2c4d8742019-03-04 09:41:00 -08001444 cached_bag_resid_stacks_.clear();
1445
Adam Lesinski7ad11102016-10-28 16:39:15 -07001446 if (diff == 0xffffffffu) {
1447 // Everything must go.
1448 cached_bags_.clear();
1449 return;
1450 }
1451
1452 // Be more conservative with what gets purged. Only if the bag has other possible
1453 // variations with respect to what changed (diff) should we remove it.
1454 for (auto iter = cached_bags_.cbegin(); iter != cached_bags_.cend();) {
1455 if (diff & iter->second->type_spec_flags) {
1456 iter = cached_bags_.erase(iter);
1457 } else {
1458 ++iter;
1459 }
1460 }
Ryan Mitchella45506e2020-11-16 23:08:18 +00001461
1462 cached_resolved_values_.clear();
Adam Lesinski7ad11102016-10-28 16:39:15 -07001463}
1464
Ryan Mitchell2e394222019-08-28 12:10:51 -07001465uint8_t AssetManager2::GetAssignedPackageId(const LoadedPackage* package) const {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001466 for (auto& package_group : package_groups_) {
1467 for (auto& package2 : package_group.packages_) {
1468 if (package2.loaded_package_ == package) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -07001469 return package_group.dynamic_ref_table->mAssignedPackageId;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001470 }
1471 }
1472 }
1473 return 0;
1474}
1475
Adam Lesinski30080e22017-10-16 16:18:09 -07001476std::unique_ptr<Theme> AssetManager2::NewTheme() {
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001477 constexpr size_t kInitialReserveSize = 32;
1478 auto theme = std::unique_ptr<Theme>(new Theme(this));
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001479 theme->keys_.reserve(kInitialReserveSize);
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001480 theme->entries_.reserve(kInitialReserveSize);
1481 return theme;
Adam Lesinski30080e22017-10-16 16:18:09 -07001482}
1483
Yurii Zubrytskyi9eb44c92022-11-14 23:44:52 -08001484void AssetManager2::ForEachPackage(base::function_ref<bool(const std::string&, uint8_t)> func,
1485 package_property_t excluded_property_flags) const {
1486 for (const PackageGroup& package_group : package_groups_) {
1487 const auto loaded_package = package_group.packages_.front().loaded_package_;
1488 if ((loaded_package->GetPropertyFlags() & excluded_property_flags) == 0U
1489 && !func(loaded_package->GetPackageName(),
1490 package_group.dynamic_ref_table->mAssignedPackageId)) {
1491 return;
1492 }
1493 }
1494}
1495
Yurii Zubrytskyi657f3c62023-05-10 13:16:23 -07001496AssetManager2::ScopedOperation AssetManager2::StartOperation() const {
1497 ++number_of_running_scoped_operations_;
1498 return ScopedOperation(*this);
1499}
1500
1501void AssetManager2::FinishOperation() const {
1502 if (number_of_running_scoped_operations_ < 1) {
1503 ALOGW("Invalid FinishOperation() call when there's none happening");
1504 return;
1505 }
1506 if (--number_of_running_scoped_operations_ == 0) {
1507 for (auto&& [_, assets] : apk_assets_) {
1508 assets.clear();
1509 }
1510 }
1511}
1512
1513const AssetManager2::ApkAssetsPtr& AssetManager2::GetApkAssets(ApkAssetsCookie cookie) const {
1514 DCHECK(number_of_running_scoped_operations_ > 0) << "Must have an operation running";
1515
1516 if (cookie < 0 || cookie >= apk_assets_.size()) {
1517 static const ApkAssetsPtr empty{};
1518 return empty;
1519 }
1520 auto& [wptr, res] = apk_assets_[cookie];
1521 if (!res) {
1522 res = wptr.promote();
1523 }
1524 return res;
1525}
1526
Adam Lesinski30080e22017-10-16 16:18:09 -07001527Theme::Theme(AssetManager2* asset_manager) : asset_manager_(asset_manager) {
1528}
1529
1530Theme::~Theme() = default;
1531
Ryan Mitchell80094e32020-11-16 23:08:18 +00001532base::expected<std::monostate, NullOrIOError> Theme::ApplyStyle(uint32_t resid, bool force) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001533 ATRACE_NAME("Theme::ApplyStyle");
Adam Lesinski7ad11102016-10-28 16:39:15 -07001534
Ryan Mitchell80094e32020-11-16 23:08:18 +00001535 auto bag = asset_manager_->GetBag(resid);
1536 if (!bag.has_value()) {
1537 return base::unexpected(bag.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001538 }
1539
1540 // Merge the flags from this style.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001541 type_spec_flags_ |= (*bag)->type_spec_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001542
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001543 for (auto it = begin(*bag); it != end(*bag); ++it) {
1544 const uint32_t attr_res_id = it->key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001545
Adam Lesinski30080e22017-10-16 16:18:09 -07001546 // If the resource ID passed in is not a style, the key can be some other identifier that is not
1547 // a resource ID. We should fail fast instead of operating with strange resource IDs.
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001548 if (!is_valid_resid(attr_res_id)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001549 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001550 }
1551
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001552 // DATA_NULL_EMPTY (@empty) is a valid resource value and DATA_NULL_UNDEFINED represents
1553 // an absence of a valid value.
1554 bool is_undefined = it->value.dataType == Res_value::TYPE_NULL &&
1555 it->value.data != Res_value::DATA_NULL_EMPTY;
1556 if (!force && is_undefined) {
1557 continue;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001558 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001559
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001560 const auto key_it = std::lower_bound(keys_.begin(), keys_.end(), attr_res_id);
1561 const auto entry_it = entries_.begin() + (key_it - keys_.begin());
1562 if (key_it != keys_.end() && *key_it == attr_res_id) {
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001563 if (is_undefined) {
1564 // DATA_NULL_UNDEFINED clears the value of the attribute in the theme only when `force` is
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001565 // true.
1566 keys_.erase(key_it);
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001567 entries_.erase(entry_it);
1568 } else if (force) {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001569 *entry_it = Entry{it->cookie, (*bag)->type_spec_flags, it->value};
Adam Lesinski30080e22017-10-16 16:18:09 -07001570 }
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001571 } else {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001572 keys_.insert(key_it, attr_res_id);
1573 entries_.insert(entry_it, Entry{it->cookie, (*bag)->type_spec_flags, it->value});
Adam Lesinski7ad11102016-10-28 16:39:15 -07001574 }
1575 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001576 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001577}
1578
Ryan Mitchell767e34f2021-06-07 12:29:05 -07001579void Theme::Rebase(AssetManager2* am, const uint32_t* style_ids, const uint8_t* force,
1580 size_t style_count) {
1581 ATRACE_NAME("Theme::Rebase");
1582 // Reset the entries without changing the vector capacity to prevent reallocations during
1583 // ApplyStyle.
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001584 keys_.clear();
Ryan Mitchell767e34f2021-06-07 12:29:05 -07001585 entries_.clear();
1586 asset_manager_ = am;
1587 for (size_t i = 0; i < style_count; i++) {
1588 ApplyStyle(style_ids[i], force[i]);
1589 }
1590}
1591
Ryan Mitchell80094e32020-11-16 23:08:18 +00001592std::optional<AssetManager2::SelectedValue> Theme::GetAttribute(uint32_t resid) const {
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001593 constexpr const uint32_t kMaxIterations = 20;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001594 uint32_t type_spec_flags = 0u;
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001595 for (uint32_t i = 0; i <= kMaxIterations; i++) {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001596 const auto key_it = std::lower_bound(keys_.begin(), keys_.end(), resid);
1597 if (key_it == keys_.end() || *key_it != resid) {
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001598 return std::nullopt;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001599 }
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001600 const auto entry_it = entries_.begin() + (key_it - keys_.begin());
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001601 type_spec_flags |= entry_it->type_spec_flags;
1602 if (entry_it->value.dataType == Res_value::TYPE_ATTRIBUTE) {
1603 resid = entry_it->value.data;
1604 continue;
1605 }
1606
1607 return AssetManager2::SelectedValue(entry_it->value.dataType, entry_it->value.data,
1608 entry_it->cookie, type_spec_flags, 0U /* resid */,
1609 {} /* config */);
1610 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001611 return std::nullopt;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001612}
1613
Ryan Mitchell80094e32020-11-16 23:08:18 +00001614base::expected<std::monostate, NullOrIOError> Theme::ResolveAttributeReference(
1615 AssetManager2::SelectedValue& value) const {
1616 if (value.type != Res_value::TYPE_ATTRIBUTE) {
1617 return asset_manager_->ResolveReference(value);
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001618 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001619
1620 std::optional<AssetManager2::SelectedValue> result = GetAttribute(value.data);
1621 if (!result.has_value()) {
1622 return base::unexpected(std::nullopt);
1623 }
1624
Ryan Mitchella45506e2020-11-16 23:08:18 +00001625 auto resolve_result = asset_manager_->ResolveReference(*result, true /* cache_value */);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001626 if (resolve_result.has_value()) {
1627 result->flags |= value.flags;
1628 value = *result;
1629 }
1630 return resolve_result;
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001631}
1632
Adam Lesinski7ad11102016-10-28 16:39:15 -07001633void Theme::Clear() {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001634 keys_.clear();
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001635 entries_.clear();
Adam Lesinski7ad11102016-10-28 16:39:15 -07001636}
1637
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001638base::expected<std::monostate, IOError> Theme::SetTo(const Theme& source) {
1639 if (this == &source) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001640 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001641 }
1642
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001643 type_spec_flags_ = source.type_spec_flags_;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001644
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001645 if (asset_manager_ == source.asset_manager_) {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001646 keys_ = source.keys_;
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001647 entries_ = source.entries_;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001648 } else {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001649 std::unordered_map<ApkAssetsCookie, ApkAssetsCookie> src_to_dest_asset_cookies;
1650 using SourceToDestinationRuntimePackageMap = std::unordered_map<int, int>;
1651 std::unordered_map<ApkAssetsCookie, SourceToDestinationRuntimePackageMap> src_asset_cookie_id_map;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001652
Yurii Zubrytskyi657f3c62023-05-10 13:16:23 -07001653 auto op_src = source.asset_manager_->StartOperation();
1654 auto op_dst = asset_manager_->StartOperation();
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001655
Yurii Zubrytskyi657f3c62023-05-10 13:16:23 -07001656 for (size_t i = 0; i < source.asset_manager_->GetApkAssetsCount(); i++) {
1657 const auto& src_asset = source.asset_manager_->GetApkAssets(i);
1658 if (!src_asset) {
Yurii Zubrytskyi1cf74932023-05-01 14:35:48 -07001659 continue;
1660 }
Yurii Zubrytskyi657f3c62023-05-10 13:16:23 -07001661 for (int j = 0; j < asset_manager_->GetApkAssetsCount(); j++) {
1662 const auto& dest_asset = asset_manager_->GetApkAssets(j);
Ryan Mitchellef538432021-03-01 14:52:14 -08001663 if (src_asset != dest_asset) {
1664 // ResourcesManager caches and reuses ApkAssets when the same apk must be present in
1665 // multiple AssetManagers. Two ApkAssets point to the same version of the same resources
1666 // if they are the same instance.
1667 continue;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001668 }
Ryan Mitchellef538432021-03-01 14:52:14 -08001669
1670 // Map the package ids of the asset in the source AssetManager to the package ids of the
1671 // asset in th destination AssetManager.
1672 SourceToDestinationRuntimePackageMap package_map;
1673 for (const auto& loaded_package : src_asset->GetLoadedArsc()->GetPackages()) {
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001674 const int src_package_id = source.asset_manager_->GetAssignedPackageId(
1675 loaded_package.get());
Ryan Mitchellef538432021-03-01 14:52:14 -08001676 const int dest_package_id = asset_manager_->GetAssignedPackageId(loaded_package.get());
1677 package_map[src_package_id] = dest_package_id;
1678 }
1679
1680 src_to_dest_asset_cookies.insert(std::make_pair(i, j));
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001681 src_asset_cookie_id_map.insert(std::make_pair(i, std::move(package_map)));
Ryan Mitchellef538432021-03-01 14:52:14 -08001682 break;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001683 }
1684 }
1685
Ryan Mitchell93bca972019-03-08 17:26:28 -08001686 // Reset the data in the destination theme.
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001687 keys_.clear();
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001688 entries_.clear();
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001689
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001690 for (size_t i = 0, size = source.entries_.size(); i != size; ++i) {
1691 const auto& entry = source.entries_[i];
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001692 bool is_reference = (entry.value.dataType == Res_value::TYPE_ATTRIBUTE
1693 || entry.value.dataType == Res_value::TYPE_REFERENCE
1694 || entry.value.dataType == Res_value::TYPE_DYNAMIC_ATTRIBUTE
1695 || entry.value.dataType == Res_value::TYPE_DYNAMIC_REFERENCE)
1696 && entry.value.data != 0x0;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001697
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001698 // If the attribute value represents an attribute or reference, the package id of the
1699 // value needs to be rewritten to the package id of the value in the destination.
1700 uint32_t attribute_data = entry.value.data;
1701 if (is_reference) {
1702 // Determine the package id of the reference in the destination AssetManager.
1703 auto value_package_map = src_asset_cookie_id_map.find(entry.cookie);
1704 if (value_package_map == src_asset_cookie_id_map.end()) {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001705 continue;
1706 }
1707
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001708 auto value_dest_package = value_package_map->second.find(
1709 get_package_id(entry.value.data));
1710 if (value_dest_package == value_package_map->second.end()) {
1711 continue;
1712 }
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001713
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001714 attribute_data = fix_package_id(entry.value.data, value_dest_package->second);
1715 }
Ryan Mitchellb85d9b22018-11-19 12:11:38 -08001716
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001717 // Find the cookie of the value in the destination. If the source apk is not loaded in the
1718 // destination, only copy resources that do not reference resources in the source.
1719 ApkAssetsCookie data_dest_cookie;
1720 auto value_dest_cookie = src_to_dest_asset_cookies.find(entry.cookie);
1721 if (value_dest_cookie != src_to_dest_asset_cookies.end()) {
1722 data_dest_cookie = value_dest_cookie->second;
1723 } else {
1724 if (is_reference || entry.value.dataType == Res_value::TYPE_STRING) {
1725 continue;
1726 } else {
1727 data_dest_cookie = 0x0;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001728 }
1729 }
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001730
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001731 const auto source_res_id = source.keys_[i];
1732
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001733 // The package id of the attribute needs to be rewritten to the package id of the
1734 // attribute in the destination.
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001735 int attribute_dest_package_id = get_package_id(source_res_id);
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001736 if (attribute_dest_package_id != 0x01) {
1737 // Find the cookie of the attribute resource id in the source AssetManager
1738 base::expected<FindEntryResult, NullOrIOError> attribute_entry_result =
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001739 source.asset_manager_->FindEntry(source_res_id, 0 /* density_override */ ,
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001740 true /* stop_at_first_match */,
1741 true /* ignore_configuration */);
1742 if (UNLIKELY(IsIOError(attribute_entry_result))) {
1743 return base::unexpected(GetIOError(attribute_entry_result.error()));
1744 }
1745 if (!attribute_entry_result.has_value()) {
1746 continue;
1747 }
1748
1749 // Determine the package id of the attribute in the destination AssetManager.
1750 auto attribute_package_map = src_asset_cookie_id_map.find(
1751 attribute_entry_result->cookie);
1752 if (attribute_package_map == src_asset_cookie_id_map.end()) {
1753 continue;
1754 }
1755 auto attribute_dest_package = attribute_package_map->second.find(
1756 attribute_dest_package_id);
1757 if (attribute_dest_package == attribute_package_map->second.end()) {
1758 continue;
1759 }
1760 attribute_dest_package_id = attribute_dest_package->second;
1761 }
1762
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001763 auto dest_attr_id = make_resid(attribute_dest_package_id, get_type_id(source_res_id),
1764 get_entry_id(source_res_id));
1765 const auto key_it = std::lower_bound(keys_.begin(), keys_.end(), dest_attr_id);
1766 const auto entry_it = entries_.begin() + (key_it - keys_.begin());
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001767 // Since the entries were cleared, the attribute resource id has yet been mapped to any value.
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001768 keys_.insert(key_it, dest_attr_id);
1769 entries_.insert(entry_it, Entry{data_dest_cookie, entry.type_spec_flags,
1770 Res_value{.dataType = entry.value.dataType,
1771 .data = attribute_data}});
Adam Lesinski7ad11102016-10-28 16:39:15 -07001772 }
1773 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001774 return {};
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001775}
1776
1777void Theme::Dump() const {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001778 LOG(INFO) << base::StringPrintf("Theme(this=%p, AssetManager2=%p)", this, asset_manager_);
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001779 for (size_t i = 0, size = keys_.size(); i != size; ++i) {
1780 auto res_id = keys_[i];
1781 const auto& entry = entries_[i];
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001782 LOG(INFO) << base::StringPrintf(" entry(0x%08x)=(0x%08x) type=(0x%02x), cookie(%d)",
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001783 res_id, entry.value.data, entry.value.dataType,
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001784 entry.cookie);
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001785 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001786}
1787
Yurii Zubrytskyi657f3c62023-05-10 13:16:23 -07001788AssetManager2::ScopedOperation::ScopedOperation(const AssetManager2& am) : am_(am) {
1789}
1790
1791AssetManager2::ScopedOperation::~ScopedOperation() {
1792 am_.FinishOperation();
1793}
1794
Adam Lesinski7ad11102016-10-28 16:39:15 -07001795} // namespace android