blob: fd5d07f22419aaa87d3b90db3307bbee11ef5fd5 [file] [log] [blame]
Adam Lesinski7ad11102016-10-28 16:39:15 -07001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define ATRACE_TAG ATRACE_TAG_RESOURCES
18
19#include "androidfw/AssetManager2.h"
20
y57cd1952018-04-12 14:26:23 -070021#include <algorithm>
Adam Lesinski30080e22017-10-16 16:18:09 -070022#include <iterator>
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -070023#include <map>
Winson2f3669b2019-01-11 11:28:34 -080024#include <set>
Yurii Zubrytskyi59dab3b2022-11-03 00:08:49 -070025#include <span>
Adam Lesinski0c405242017-01-13 20:47:26 -080026
Adam Lesinski7ad11102016-10-28 16:39:15 -070027#include "android-base/logging.h"
28#include "android-base/stringprintf.h"
Jackal Guo552b45d2021-09-29 10:52:19 +080029#include "androidfw/ResourceTypes.h"
Ryan Mitchell8a891d82019-07-01 09:48:23 -070030#include "androidfw/ResourceUtils.h"
Ryan Mitchell31b11052019-06-13 13:47:26 -070031#include "androidfw/Util.h"
Adam Lesinski7ad11102016-10-28 16:39:15 -070032#include "utils/ByteOrder.h"
33#include "utils/Trace.h"
34
35#ifdef _WIN32
36#ifdef ERROR
37#undef ERROR
38#endif
39#endif
40
41namespace android {
42
Ryan Mitchell80094e32020-11-16 23:08:18 +000043namespace {
44
45using EntryValue = std::variant<Res_value, incfs::verified_map_ptr<ResTable_map_entry>>;
46
Eric Miao368cd192022-09-09 15:46:14 -070047/* NOTE: table_entry has been verified in LoadedPackage::GetEntryFromOffset(),
48 * and so access to ->value() and ->map_entry() are safe here
49 */
Ryan Mitchell80094e32020-11-16 23:08:18 +000050base::expected<EntryValue, IOError> GetEntryValue(
51 incfs::verified_map_ptr<ResTable_entry> table_entry) {
Eric Miao368cd192022-09-09 15:46:14 -070052 const uint16_t entry_size = table_entry->size();
Ryan Mitchell80094e32020-11-16 23:08:18 +000053
54 // Check if the entry represents a bag value.
Eric Miao368cd192022-09-09 15:46:14 -070055 if (entry_size >= sizeof(ResTable_map_entry) && table_entry->is_complex()) {
56 return table_entry.convert<ResTable_map_entry>().verified();
Ryan Mitchell80094e32020-11-16 23:08:18 +000057 }
58
Eric Miao368cd192022-09-09 15:46:14 -070059 return table_entry->value();
Ryan Mitchell80094e32020-11-16 23:08:18 +000060}
61
62} // namespace
63
Adam Lesinskibebfcc42018-02-12 14:27:46 -080064struct FindEntryResult {
Ryan Mitchell80094e32020-11-16 23:08:18 +000065 // The cookie representing the ApkAssets in which the value resides.
66 ApkAssetsCookie cookie;
67
68 // The value of the resource table entry. Either an android::Res_value for non-bag types or an
69 // incfs::verified_map_ptr<ResTable_map_entry> for bag types.
70 EntryValue entry;
Adam Lesinskibebfcc42018-02-12 14:27:46 -080071
72 // The configuration for which the resulting entry was defined. This is already swapped to host
73 // endianness.
74 ResTable_config config;
75
76 // The bitmask of configuration axis with which the resource value varies.
77 uint32_t type_flags;
78
79 // The dynamic package ID map for the package from which this resource came from.
80 const DynamicRefTable* dynamic_ref_table;
81
Ryan Mitchell8a891d82019-07-01 09:48:23 -070082 // The package name of the resource.
83 const std::string* package_name;
84
Adam Lesinskibebfcc42018-02-12 14:27:46 -080085 // The string pool reference to the type's name. This uses a different string pool than
86 // the global string pool, but this is hidden from the caller.
87 StringPoolRef type_string_ref;
88
89 // The string pool reference to the entry's name. This uses a different string pool than
90 // the global string pool, but this is hidden from the caller.
91 StringPoolRef entry_string_ref;
92};
93
Yurii Zubrytskyib3455192023-05-01 14:35:48 -070094AssetManager2::AssetManager2(ApkAssetsList apk_assets, const ResTable_config& configuration)
95 : configuration_(configuration) {
96 // Don't invalidate caches here as there's nothing cached yet.
97 SetApkAssets(apk_assets, false);
Adam Lesinski970bd8d2017-09-25 13:21:55 -070098}
Adam Lesinski7ad11102016-10-28 16:39:15 -070099
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700100bool AssetManager2::SetApkAssets(ApkAssetsList apk_assets, bool invalidate_caches) {
101 BuildDynamicRefTable(apk_assets);
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800102 RebuildFilterList();
Adam Lesinski7ad11102016-10-28 16:39:15 -0700103 if (invalidate_caches) {
104 InvalidateCaches(static_cast<uint32_t>(-1));
105 }
106 return true;
107}
108
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700109bool AssetManager2::SetApkAssets(std::initializer_list<ApkAssetsPtr> apk_assets,
110 bool invalidate_caches) {
111 return SetApkAssets(ApkAssetsList(apk_assets.begin(), apk_assets.size()), invalidate_caches);
112}
113
114void AssetManager2::BuildDynamicRefTable(ApkAssetsList apk_assets) {
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700115 auto op = StartOperation();
116
117 apk_assets_.resize(apk_assets.size());
118 for (size_t i = 0; i != apk_assets.size(); ++i) {
119 apk_assets_[i].first = apk_assets[i];
120 // Let's populate the locked assets right away as we're going to need them here later.
121 apk_assets_[i].second = apk_assets[i];
122 }
123
Adam Lesinskida431a22016-12-29 16:08:16 -0500124 package_groups_.clear();
125 package_ids_.fill(0xff);
126
Ryan Mitchellef538432021-03-01 14:52:14 -0800127 // A mapping from path of apk assets that could be target packages of overlays to the runtime
128 // package id of its first loaded package. Overlays currently can only override resources in the
129 // first package in the target resource table.
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800130 std::unordered_map<std::string_view, uint8_t> target_assets_package_ids;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700131
Ryan Mitchell824cc492020-02-12 10:48:14 -0800132 // Overlay resources are not directly referenced by an application so their resource ids
133 // can change throughout the application's lifetime. Assign overlay package ids last.
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700134 std::vector<const ApkAssets*> sorted_apk_assets;
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700135 sorted_apk_assets.reserve(apk_assets.size());
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700136 for (auto& asset : apk_assets) {
137 sorted_apk_assets.push_back(asset.get());
138 }
139 std::stable_partition(sorted_apk_assets.begin(), sorted_apk_assets.end(),
140 [](auto a) { return !a->IsOverlay(); });
Ryan Mitchell824cc492020-02-12 10:48:14 -0800141
142 // The assets cookie must map to the position of the apk assets in the unsorted apk assets list.
143 std::unordered_map<const ApkAssets*, ApkAssetsCookie> apk_assets_cookies;
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700144 apk_assets_cookies.reserve(apk_assets.size());
145 for (size_t i = 0, n = apk_assets.size(); i < n; i++) {
146 apk_assets_cookies[apk_assets[i].get()] = static_cast<ApkAssetsCookie>(i);
Ryan Mitchell824cc492020-02-12 10:48:14 -0800147 }
148
Ryan Mitchellb894c272020-02-12 10:31:44 -0800149 // 0x01 is reserved for the android package.
150 int next_package_id = 0x02;
Ryan Mitchell824cc492020-02-12 10:48:14 -0800151 for (const ApkAssets* apk_assets : sorted_apk_assets) {
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800152 std::shared_ptr<OverlayDynamicRefTable> overlay_ref_table;
153 if (auto loaded_idmap = apk_assets->GetLoadedIdmap(); loaded_idmap != nullptr) {
154 // The target package must precede the overlay package in the apk assets paths in order
155 // to take effect.
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800156 auto iter = target_assets_package_ids.find(loaded_idmap->TargetApkPath());
Ryan Mitchellef538432021-03-01 14:52:14 -0800157 if (iter == target_assets_package_ids.end()) {
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800158 LOG(INFO) << "failed to find target package for overlay "
159 << loaded_idmap->OverlayApkPath();
160 } else {
161 uint8_t target_package_id = iter->second;
162
163 // Create a special dynamic reference table for the overlay to rewrite references to
164 // overlay resources as references to the target resources they overlay.
165 overlay_ref_table = std::make_shared<OverlayDynamicRefTable>(
166 loaded_idmap->GetOverlayDynamicRefTable(target_package_id));
167
168 // Add the overlay resource map to the target package's set of overlays.
169 const uint8_t target_idx = package_ids_[target_package_id];
170 CHECK(target_idx != 0xff) << "overlay target '" << loaded_idmap->TargetApkPath()
171 << "'added to apk_assets_package_ids but does not have an"
172 << " assigned package group";
173
174 PackageGroup& target_package_group = package_groups_[target_idx];
175 target_package_group.overlays_.push_back(
176 ConfiguredOverlay{loaded_idmap->GetTargetResourcesMap(target_package_id,
177 overlay_ref_table.get()),
178 apk_assets_cookies[apk_assets]});
179 }
180 }
181
Ryan Mitchellb894c272020-02-12 10:31:44 -0800182 const LoadedArsc* loaded_arsc = apk_assets->GetLoadedArsc();
Ryan Mitchellb894c272020-02-12 10:31:44 -0800183 for (const std::unique_ptr<const LoadedPackage>& package : loaded_arsc->GetPackages()) {
184 // Get the package ID or assign one if a shared library.
185 int package_id;
186 if (package->IsDynamic()) {
187 package_id = next_package_id++;
188 } else {
189 package_id = package->GetPackageId();
Adam Lesinskida431a22016-12-29 16:08:16 -0500190 }
191
Adam Lesinskida431a22016-12-29 16:08:16 -0500192 uint8_t idx = package_ids_[package_id];
193 if (idx == 0xff) {
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800194 // Add the mapping for package ID to index if not present.
Adam Lesinskida431a22016-12-29 16:08:16 -0500195 package_ids_[package_id] = idx = static_cast<uint8_t>(package_groups_.size());
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800196 PackageGroup& new_group = package_groups_.emplace_back();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700197
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800198 if (overlay_ref_table != nullptr) {
199 // If this package is from an overlay, use a dynamic reference table that can rewrite
200 // overlay resource ids to their corresponding target resource ids.
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800201 new_group.dynamic_ref_table = std::move(overlay_ref_table);
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700202 }
203
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800204 DynamicRefTable* ref_table = new_group.dynamic_ref_table.get();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700205 ref_table->mAssignedPackageId = package_id;
206 ref_table->mAppAsLib = package->IsDynamic() && package->GetPackageId() == 0x7f;
Adam Lesinskida431a22016-12-29 16:08:16 -0500207 }
Adam Lesinskida431a22016-12-29 16:08:16 -0500208
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800209 // Add the package to the set of packages with the same ID.
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800210 PackageGroup* package_group = &package_groups_[idx];
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800211 package_group->packages_.emplace_back().loaded_package_ = package.get();
Ryan Mitchell824cc492020-02-12 10:48:14 -0800212 package_group->cookies_.push_back(apk_assets_cookies[apk_assets]);
Adam Lesinskida431a22016-12-29 16:08:16 -0500213
214 // Add the package name -> build time ID mappings.
215 for (const DynamicPackageEntry& entry : package->GetDynamicPackageMap()) {
216 String16 package_name(entry.package_name.c_str(), entry.package_name.size());
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700217 package_group->dynamic_ref_table->mEntries.replaceValueFor(
Adam Lesinskida431a22016-12-29 16:08:16 -0500218 package_name, static_cast<uint8_t>(entry.package_id));
219 }
Ryan Mitchellb894c272020-02-12 10:31:44 -0800220
Ryan Mitchellef538432021-03-01 14:52:14 -0800221 if (auto apk_assets_path = apk_assets->GetPath()) {
222 // Overlay target ApkAssets must have been created using path based load apis.
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800223 target_assets_package_ids.emplace(*apk_assets_path, package_id);
Ryan Mitchellef538432021-03-01 14:52:14 -0800224 }
Adam Lesinskida431a22016-12-29 16:08:16 -0500225 }
226 }
227
228 // Now assign the runtime IDs so that we have a build-time to runtime ID map.
Yurii Zubrytskyi59dab3b2022-11-03 00:08:49 -0700229 DynamicRefTable::AliasMap aliases;
230 for (const auto& group : package_groups_) {
231 const std::string& package_name = group.packages_[0].loaded_package_->GetPackageName();
232 const auto name_16 = String16(package_name.c_str(), package_name.size());
233 for (auto&& inner_group : package_groups_) {
234 inner_group.dynamic_ref_table->addMapping(name_16,
235 group.dynamic_ref_table->mAssignedPackageId);
Adam Lesinskida431a22016-12-29 16:08:16 -0500236 }
Yurii Zubrytskyi59dab3b2022-11-03 00:08:49 -0700237
238 for (const auto& package : group.packages_) {
239 const auto& package_aliases = package.loaded_package_->GetAliasResourceIdMap();
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800240 aliases.insert(aliases.end(), package_aliases.begin(), package_aliases.end());
Yurii Zubrytskyi59dab3b2022-11-03 00:08:49 -0700241 }
242 }
243
244 if (!aliases.empty()) {
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800245 std::sort(aliases.begin(), aliases.end(), [](auto&& l, auto&& r) { return l.first < r.first; });
246
Yurii Zubrytskyi59dab3b2022-11-03 00:08:49 -0700247 // Add the alias resources to the dynamic reference table of every package group. Since
248 // staging aliases can only be defined by the framework package (which is not a shared
249 // library), the compile-time package id of the framework is the same across all packages
250 // that compile against the framework.
251 for (auto& group : std::span(package_groups_.data(), package_groups_.size() - 1)) {
252 group.dynamic_ref_table->setAliases(aliases);
253 }
254 package_groups_.back().dynamic_ref_table->setAliases(std::move(aliases));
Adam Lesinskida431a22016-12-29 16:08:16 -0500255 }
256}
257
258void AssetManager2::DumpToLog() const {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800259 LOG(INFO) << base::StringPrintf("AssetManager2(this=%p)", this);
260
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700261 auto op = StartOperation();
Adam Lesinskida431a22016-12-29 16:08:16 -0500262 std::string list;
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700263 for (size_t i = 0; i < apk_assets_.size(); ++i) {
264 const auto& assets = GetApkAssets(i);
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700265 base::StringAppendF(&list, "%s,", assets ? assets->GetDebugName().c_str() : "nullptr");
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800266 }
267 LOG(INFO) << "ApkAssets: " << list;
268
269 list = "";
Adam Lesinskida431a22016-12-29 16:08:16 -0500270 for (size_t i = 0; i < package_ids_.size(); i++) {
271 if (package_ids_[i] != 0xff) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800272 base::StringAppendF(&list, "%02x -> %d, ", (int)i, package_ids_[i]);
Adam Lesinskida431a22016-12-29 16:08:16 -0500273 }
274 }
275 LOG(INFO) << "Package ID map: " << list;
276
Adam Lesinski0dd36992018-01-25 15:38:38 -0800277 for (const auto& package_group: package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800278 list = "";
279 for (const auto& package : package_group.packages_) {
280 const LoadedPackage* loaded_package = package.loaded_package_;
281 base::StringAppendF(&list, "%s(%02x%s), ", loaded_package->GetPackageName().c_str(),
282 loaded_package->GetPackageId(),
283 (loaded_package->IsDynamic() ? " dynamic" : ""));
284 }
285 LOG(INFO) << base::StringPrintf("PG (%02x): ",
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700286 package_group.dynamic_ref_table->mAssignedPackageId)
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800287 << list;
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800288
289 for (size_t i = 0; i < 256; i++) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700290 if (package_group.dynamic_ref_table->mLookupTable[i] != 0) {
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800291 LOG(INFO) << base::StringPrintf(" e[0x%02x] -> 0x%02x", (uint8_t) i,
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700292 package_group.dynamic_ref_table->mLookupTable[i]);
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800293 }
294 }
Adam Lesinskida431a22016-12-29 16:08:16 -0500295 }
296}
Adam Lesinski7ad11102016-10-28 16:39:15 -0700297
298const ResStringPool* AssetManager2::GetStringPoolForCookie(ApkAssetsCookie cookie) const {
299 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
300 return nullptr;
301 }
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700302 auto op = StartOperation();
303 const auto& assets = GetApkAssets(cookie);
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700304 return assets ? assets->GetLoadedArsc()->GetStringPool() : nullptr;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700305}
306
Adam Lesinskida431a22016-12-29 16:08:16 -0500307const DynamicRefTable* AssetManager2::GetDynamicRefTableForPackage(uint32_t package_id) const {
308 if (package_id >= package_ids_.size()) {
309 return nullptr;
310 }
311
312 const size_t idx = package_ids_[package_id];
313 if (idx == 0xff) {
314 return nullptr;
315 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700316 return package_groups_[idx].dynamic_ref_table.get();
Adam Lesinskida431a22016-12-29 16:08:16 -0500317}
318
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700319std::shared_ptr<const DynamicRefTable> AssetManager2::GetDynamicRefTableForCookie(
320 ApkAssetsCookie cookie) const {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800321 for (const PackageGroup& package_group : package_groups_) {
322 for (const ApkAssetsCookie& package_cookie : package_group.cookies_) {
323 if (package_cookie == cookie) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700324 return package_group.dynamic_ref_table;
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800325 }
326 }
327 }
328 return nullptr;
329}
330
MÃ¥rten Kongstadc92c4dd2019-02-05 01:29:59 +0100331const std::unordered_map<std::string, std::string>*
332 AssetManager2::GetOverlayableMapForPackage(uint32_t package_id) const {
333
334 if (package_id >= package_ids_.size()) {
335 return nullptr;
336 }
337
338 const size_t idx = package_ids_[package_id];
339 if (idx == 0xff) {
340 return nullptr;
341 }
342
343 const PackageGroup& package_group = package_groups_[idx];
Ryan Mitchell80094e32020-11-16 23:08:18 +0000344 if (package_group.packages_.empty()) {
MÃ¥rten Kongstadc92c4dd2019-02-05 01:29:59 +0100345 return nullptr;
346 }
347
348 const auto loaded_package = package_group.packages_[0].loaded_package_;
349 return &loaded_package->GetOverlayableMap();
350}
351
Yurii Zubrytskyia5775142022-11-02 17:49:49 -0700352bool AssetManager2::GetOverlayablesToString(android::StringPiece package_name,
Ryan Mitchell2e394222019-08-28 12:10:51 -0700353 std::string* out) const {
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700354 auto op = StartOperation();
Ryan Mitchell2e394222019-08-28 12:10:51 -0700355 uint8_t package_id = 0U;
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700356 for (size_t i = 0; i != apk_assets_.size(); ++i) {
357 const auto& assets = GetApkAssets(i);
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700358 if (!assets) {
359 continue;
360 }
361 const LoadedArsc* loaded_arsc = assets->GetLoadedArsc();
Ryan Mitchell2e394222019-08-28 12:10:51 -0700362 if (loaded_arsc == nullptr) {
363 continue;
364 }
365
366 const auto& loaded_packages = loaded_arsc->GetPackages();
367 if (loaded_packages.empty()) {
368 continue;
369 }
370
371 const auto& loaded_package = loaded_packages[0];
372 if (loaded_package->GetPackageName() == package_name) {
373 package_id = GetAssignedPackageId(loaded_package.get());
374 break;
375 }
376 }
377
378 if (package_id == 0U) {
379 ANDROID_LOG(ERROR) << base::StringPrintf("No package with name '%s", package_name.data());
380 return false;
381 }
382
383 const size_t idx = package_ids_[package_id];
384 if (idx == 0xff) {
385 return false;
386 }
387
388 std::string output;
389 for (const ConfiguredPackage& package : package_groups_[idx].packages_) {
390 const LoadedPackage* loaded_package = package.loaded_package_;
391 for (auto it = loaded_package->begin(); it != loaded_package->end(); it++) {
392 const OverlayableInfo* info = loaded_package->GetOverlayableInfo(*it);
393 if (info != nullptr) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000394 auto res_name = GetResourceName(*it);
395 if (!res_name.has_value()) {
Ryan Mitchell2e394222019-08-28 12:10:51 -0700396 ANDROID_LOG(ERROR) << base::StringPrintf(
397 "Unable to retrieve name of overlayable resource 0x%08x", *it);
398 return false;
399 }
400
Ryan Mitchell80094e32020-11-16 23:08:18 +0000401 const std::string name = ToFormattedResourceString(*res_name);
Ryan Mitchell2e394222019-08-28 12:10:51 -0700402 output.append(base::StringPrintf(
403 "resource='%s' overlayable='%s' actor='%s' policy='0x%08x'\n",
Yurii Zubrytskyi9d225372022-11-29 11:12:18 -0800404 name.c_str(), info->name.data(), info->actor.data(), info->policy_flags));
Ryan Mitchell2e394222019-08-28 12:10:51 -0700405 }
406 }
407 }
408
409 *out = std::move(output);
410 return true;
411}
412
Ryan Mitchell192400c2020-04-02 09:54:23 -0700413bool AssetManager2::ContainsAllocatedTable() const {
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700414 auto op = StartOperation();
415 for (size_t i = 0; i != apk_assets_.size(); ++i) {
416 const auto& assets = GetApkAssets(i);
417 if (assets && assets->IsTableAllocated()) {
418 return true;
419 }
420 }
421 return false;
Ryan Mitchell192400c2020-04-02 09:54:23 -0700422}
423
Adam Lesinski7ad11102016-10-28 16:39:15 -0700424void AssetManager2::SetConfiguration(const ResTable_config& configuration) {
425 const int diff = configuration_.diff(configuration);
426 configuration_ = configuration;
427
428 if (diff) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800429 RebuildFilterList();
Adam Lesinski7ad11102016-10-28 16:39:15 -0700430 InvalidateCaches(static_cast<uint32_t>(diff));
431 }
432}
433
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700434std::set<AssetManager2::ApkAssetsPtr> AssetManager2::GetNonSystemOverlays() const {
435 std::set<ApkAssetsPtr> non_system_overlays;
Adam Lesinski0c405242017-01-13 20:47:26 -0800436 for (const PackageGroup& package_group : package_groups_) {
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800437 bool found_system_package = false;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800438 for (const ConfiguredPackage& package : package_group.packages_) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700439 if (package.loaded_package_->IsSystem()) {
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800440 found_system_package = true;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700441 break;
442 }
443 }
444
445 if (!found_system_package) {
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700446 auto op = StartOperation();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700447 for (const ConfiguredOverlay& overlay : package_group.overlays_) {
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700448 if (const auto& asset = GetApkAssets(overlay.cookie)) {
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700449 non_system_overlays.insert(std::move(asset));
450 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700451 }
452 }
453 }
454
455 return non_system_overlays;
456}
457
Ryan Mitchell80094e32020-11-16 23:08:18 +0000458base::expected<std::set<ResTable_config>, IOError> AssetManager2::GetResourceConfigurations(
459 bool exclude_system, bool exclude_mipmap) const {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700460 ATRACE_NAME("AssetManager::GetResourceConfigurations");
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700461 auto op = StartOperation();
462
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700463 const auto non_system_overlays =
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700464 exclude_system ? GetNonSystemOverlays() : std::set<ApkAssetsPtr>();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700465
466 std::set<ResTable_config> configurations;
467 for (const PackageGroup& package_group : package_groups_) {
468 for (size_t i = 0; i < package_group.packages_.size(); i++) {
469 const ConfiguredPackage& package = package_group.packages_[i];
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700470 if (exclude_system) {
471 if (package.loaded_package_->IsSystem()) {
472 continue;
473 }
474 if (!non_system_overlays.empty()) {
475 // Exclude overlays that target only system resources.
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700476 const auto& apk_assets = GetApkAssets(package_group.cookies_[i]);
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700477 if (apk_assets && apk_assets->IsOverlay() &&
478 non_system_overlays.find(apk_assets) == non_system_overlays.end()) {
479 continue;
480 }
481 }
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800482 }
483
Ryan Mitchell80094e32020-11-16 23:08:18 +0000484 auto result = package.loaded_package_->CollectConfigurations(exclude_mipmap, &configurations);
485 if (UNLIKELY(!result.has_value())) {
486 return base::unexpected(result.error());
487 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800488 }
489 }
490 return configurations;
491}
492
493std::set<std::string> AssetManager2::GetResourceLocales(bool exclude_system,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800494 bool merge_equivalent_languages) const {
495 ATRACE_NAME("AssetManager::GetResourceLocales");
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700496 auto op = StartOperation();
497
Adam Lesinski0c405242017-01-13 20:47:26 -0800498 std::set<std::string> locales;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700499 const auto non_system_overlays =
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700500 exclude_system ? GetNonSystemOverlays() : std::set<ApkAssetsPtr>();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700501
Adam Lesinski0c405242017-01-13 20:47:26 -0800502 for (const PackageGroup& package_group : package_groups_) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700503 for (size_t i = 0; i < package_group.packages_.size(); i++) {
504 const ConfiguredPackage& package = package_group.packages_[i];
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700505 if (exclude_system) {
506 if (package.loaded_package_->IsSystem()) {
507 continue;
508 }
509 if (!non_system_overlays.empty()) {
510 // Exclude overlays that target only system resources.
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700511 const auto& apk_assets = GetApkAssets(package_group.cookies_[i]);
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700512 if (apk_assets && apk_assets->IsOverlay() &&
513 non_system_overlays.find(apk_assets) == non_system_overlays.end()) {
514 continue;
515 }
516 }
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800517 }
518
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800519 package.loaded_package_->CollectLocales(merge_equivalent_languages, &locales);
Adam Lesinski0c405242017-01-13 20:47:26 -0800520 }
521 }
522 return locales;
523}
524
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800525std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename,
526 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700527 const std::string new_path = "assets/" + filename;
528 return OpenNonAsset(new_path, mode);
529}
530
531std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename, ApkAssetsCookie cookie,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800532 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700533 const std::string new_path = "assets/" + filename;
534 return OpenNonAsset(new_path, cookie, mode);
535}
536
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800537std::unique_ptr<AssetDir> AssetManager2::OpenDir(const std::string& dirname) const {
538 ATRACE_NAME("AssetManager::OpenDir");
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700539 auto op = StartOperation();
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800540
541 std::string full_path = "assets/" + dirname;
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700542 auto files = util::make_unique<SortedVector<AssetDir::FileInfo>>();
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800543
544 // Start from the back.
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700545 for (size_t i = apk_assets_.size(); i > 0; --i) {
546 const auto& apk_assets = GetApkAssets(i - 1);
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700547 if (!apk_assets || apk_assets->IsOverlay()) {
MÃ¥rten Kongstaddbf343b2019-02-21 07:54:18 +0100548 continue;
549 }
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800550
Yurii Zubrytskyia5775142022-11-02 17:49:49 -0700551 auto func = [&](StringPiece name, FileType type) {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800552 AssetDir::FileInfo info;
553 info.setFileName(String8(name.data(), name.size()));
554 info.setFileType(type);
Ryan Mitchellef538432021-03-01 14:52:14 -0800555 info.setSourceName(String8(apk_assets->GetDebugName().c_str()));
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800556 files->add(info);
557 };
558
Ryan Mitchellc07aa702020-03-10 13:49:12 -0700559 if (!apk_assets->GetAssetsProvider()->ForEachFile(full_path, func)) {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800560 return {};
561 }
562 }
563
564 std::unique_ptr<AssetDir> asset_dir = util::make_unique<AssetDir>();
565 asset_dir->setFileList(files.release());
566 return asset_dir;
567}
568
Adam Lesinski7ad11102016-10-28 16:39:15 -0700569// Search in reverse because that's how we used to do it and we need to preserve behaviour.
570// This is unfortunate, because ClassLoaders delegate to the parent first, so the order
571// is inconsistent for split APKs.
572std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
573 Asset::AccessMode mode,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800574 ApkAssetsCookie* out_cookie) const {
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700575 auto op = StartOperation();
576 for (size_t i = apk_assets_.size(); i > 0; i--) {
577 const auto& assets = GetApkAssets(i - 1);
MÃ¥rten Kongstaddbf343b2019-02-21 07:54:18 +0100578 // Prevent RRO from modifying assets and other entries accessed by file
579 // path. Explicitly asking for a path in a given package (denoted by a
580 // cookie) is still OK.
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700581 if (!assets || assets->IsOverlay()) {
MÃ¥rten Kongstaddbf343b2019-02-21 07:54:18 +0100582 continue;
583 }
584
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700585 std::unique_ptr<Asset> asset = assets->GetAssetsProvider()->Open(filename, mode);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700586 if (asset) {
587 if (out_cookie != nullptr) {
588 *out_cookie = i;
589 }
590 return asset;
591 }
592 }
593
594 if (out_cookie != nullptr) {
595 *out_cookie = kInvalidCookie;
596 }
597 return {};
598}
599
600std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800601 ApkAssetsCookie cookie,
602 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700603 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
604 return {};
605 }
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700606 auto op = StartOperation();
607 const auto& assets = GetApkAssets(cookie);
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700608 return assets ? assets->GetAssetsProvider()->Open(filename, mode) : nullptr;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700609}
610
Ryan Mitchell80094e32020-11-16 23:08:18 +0000611base::expected<FindEntryResult, NullOrIOError> AssetManager2::FindEntry(
612 uint32_t resid, uint16_t density_override, bool stop_at_first_match,
613 bool ignore_configuration) const {
614 const bool logging_enabled = resource_resolution_logging_enabled_;
615 if (UNLIKELY(logging_enabled)) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700616 // Clear the last logged resource resolution.
617 ResetResourceResolution();
618 last_resolution_.resid = resid;
619 }
620
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700621 auto op = StartOperation();
622
Adam Lesinski7ad11102016-10-28 16:39:15 -0700623 // Might use this if density_override != 0.
624 ResTable_config density_override_config;
625
626 // Select our configuration or generate a density override configuration.
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800627 const ResTable_config* desired_config = &configuration_;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700628 if (density_override != 0 && density_override != configuration_.density) {
629 density_override_config = configuration_;
630 density_override_config.density = density_override;
631 desired_config = &density_override_config;
632 }
633
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700634 // Retrieve the package group from the package id of the resource id.
Ryan Mitchell80094e32020-11-16 23:08:18 +0000635 if (UNLIKELY(!is_valid_resid(resid))) {
Mark Hansenb406b0e2022-10-14 02:18:37 +0000636 LOG(ERROR) << base::StringPrintf("Invalid resource ID 0x%08x.", resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000637 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -0500638 }
639
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800640 const uint32_t package_id = get_package_id(resid);
641 const uint8_t type_idx = get_type_id(resid) - 1;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800642 const uint16_t entry_idx = get_entry_id(resid);
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700643 uint8_t package_idx = package_ids_[package_id];
Ryan Mitchell80094e32020-11-16 23:08:18 +0000644 if (UNLIKELY(package_idx == 0xff)) {
Mark Hansenb406b0e2022-10-14 02:18:37 +0000645 ANDROID_LOG(ERROR) << base::StringPrintf("No package ID %02x found for resource ID 0x%08x.",
Ryan Mitchell2fe23472019-02-27 09:43:01 -0800646 package_id, resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000647 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -0500648 }
649
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800650 const PackageGroup& package_group = package_groups_[package_idx];
Ryan Mitchell80094e32020-11-16 23:08:18 +0000651 auto result = FindEntryInternal(package_group, type_idx, entry_idx, *desired_config,
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800652 stop_at_first_match, ignore_configuration);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000653 if (UNLIKELY(!result.has_value())) {
654 return base::unexpected(result.error());
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700655 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800656
Jackal Guo552b45d2021-09-29 10:52:19 +0800657 bool overlaid = false;
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700658 if (!stop_at_first_match && !ignore_configuration) {
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700659 const auto& assets = GetApkAssets(result->cookie);
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700660 if (!assets) {
661 ALOGE("Found expired ApkAssets #%d for resource ID 0x%08x.", result->cookie, resid);
662 return base::unexpected(std::nullopt);
663 }
664 if (!assets->IsLoader()) {
665 for (const auto& id_map : package_group.overlays_) {
666 auto overlay_entry = id_map.overlay_res_maps_.Lookup(resid);
667 if (!overlay_entry) {
668 // No id map entry exists for this target resource.
Jeremy Meyerbe2b7792022-08-23 17:42:50 +0000669 continue;
670 }
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700671 if (overlay_entry.IsInlineValue()) {
672 // The target resource is overlaid by an inline value not represented by a resource.
673 ConfigDescription best_frro_config;
674 Res_value best_frro_value;
675 bool frro_found = false;
676 for( const auto& [config, value] : overlay_entry.GetInlineValue()) {
677 if ((!frro_found || config.isBetterThan(best_frro_config, desired_config))
678 && config.match(*desired_config)) {
679 frro_found = true;
680 best_frro_config = config;
681 best_frro_value = value;
682 }
683 }
684 if (!frro_found) {
685 continue;
686 }
687 result->entry = best_frro_value;
688 result->dynamic_ref_table = id_map.overlay_res_maps_.GetOverlayDynamicRefTable();
689 result->cookie = id_map.cookie;
690
691 if (UNLIKELY(logging_enabled)) {
692 last_resolution_.steps.push_back(
693 Resolution::Step{Resolution::Step::Type::OVERLAID_INLINE, result->cookie, String8()});
694 if (auto path = assets->GetPath()) {
695 const std::string overlay_path = path->data();
696 if (IsFabricatedOverlay(overlay_path)) {
697 // FRRO don't have package name so we use the creating package here.
698 String8 frro_name = String8("FRRO");
699 // Get the first part of it since the expected one should be like
700 // {overlayPackageName}-{overlayName}-{4 alphanumeric chars}.frro
701 // under /data/resource-cache/.
702 const std::string name = overlay_path.substr(overlay_path.rfind('/') + 1);
703 const size_t end = name.find('-');
704 if (frro_name.size() != overlay_path.size() && end != std::string::npos) {
705 frro_name.append(base::StringPrintf(" created by %s",
706 name.substr(0 /* pos */,
707 end).c_str()).c_str());
708 }
709 last_resolution_.best_package_name = frro_name;
710 } else {
711 last_resolution_.best_package_name = result->package_name->c_str();
712 }
713 }
714 overlaid = true;
715 }
716 continue;
717 }
718
719 auto overlay_result = FindEntry(overlay_entry.GetResourceId(), density_override,
720 false /* stop_at_first_match */,
721 false /* ignore_configuration */);
722 if (UNLIKELY(IsIOError(overlay_result))) {
723 return base::unexpected(overlay_result.error());
724 }
725 if (!overlay_result.has_value()) {
726 continue;
727 }
728
729 if (!overlay_result->config.isBetterThan(result->config, desired_config)
730 && overlay_result->config.compare(result->config) != 0) {
731 // The configuration of the entry for the overlay must be equal to or better than the target
732 // configuration to be chosen as the better value.
733 continue;
734 }
735
736 result->cookie = overlay_result->cookie;
737 result->entry = overlay_result->entry;
738 result->config = overlay_result->config;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000739 result->dynamic_ref_table = id_map.overlay_res_maps_.GetOverlayDynamicRefTable();
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800740
741 if (UNLIKELY(logging_enabled)) {
742 last_resolution_.steps.push_back(
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700743 Resolution::Step{Resolution::Step::Type::OVERLAID, overlay_result->cookie,
744 overlay_result->config.toString()});
745 last_resolution_.best_package_name =
746 overlay_result->package_name->c_str();
Jackal Guo552b45d2021-09-29 10:52:19 +0800747 overlaid = true;
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800748 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700749 }
750 }
751 }
752
Ryan Mitchell80094e32020-11-16 23:08:18 +0000753 if (UNLIKELY(logging_enabled)) {
754 last_resolution_.cookie = result->cookie;
755 last_resolution_.type_string_ref = result->type_string_ref;
756 last_resolution_.entry_string_ref = result->entry_string_ref;
Jackal Guo552b45d2021-09-29 10:52:19 +0800757 last_resolution_.best_config_name = result->config.toString();
758 if (!overlaid) {
759 last_resolution_.best_package_name = result->package_name->c_str();
760 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700761 }
762
Ryan Mitchell80094e32020-11-16 23:08:18 +0000763 return result;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700764}
765
Ryan Mitchell80094e32020-11-16 23:08:18 +0000766base::expected<FindEntryResult, NullOrIOError> AssetManager2::FindEntryInternal(
767 const PackageGroup& package_group, uint8_t type_idx, uint16_t entry_idx,
768 const ResTable_config& desired_config, bool stop_at_first_match,
769 bool ignore_configuration) const {
770 const bool logging_enabled = resource_resolution_logging_enabled_;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800771 ApkAssetsCookie best_cookie = kInvalidCookie;
772 const LoadedPackage* best_package = nullptr;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000773 incfs::verified_map_ptr<ResTable_type> best_type;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800774 const ResTable_config* best_config = nullptr;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000775 uint32_t best_offset = 0U;
776 uint32_t type_flags = 0U;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800777
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800778 // If `desired_config` is not the same as the set configuration or the caller will accept a value
779 // from any configuration, then we cannot use our filtered list of types since it only it contains
780 // types matched to the set configuration.
781 const bool use_filtered = !ignore_configuration && &desired_config == &configuration_;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800782
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700783 const size_t package_count = package_group.packages_.size();
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800784 for (size_t pi = 0; pi < package_count; pi++) {
785 const ConfiguredPackage& loaded_package_impl = package_group.packages_[pi];
786 const LoadedPackage* loaded_package = loaded_package_impl.loaded_package_;
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800787 const ApkAssetsCookie cookie = package_group.cookies_[pi];
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800788
789 // If the type IDs are offset in this package, we need to take that into account when searching
790 // for a type.
791 const TypeSpec* type_spec = loaded_package->GetTypeSpecByTypeIndex(type_idx);
792 if (UNLIKELY(type_spec == nullptr)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700793 continue;
794 }
795
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800796 // Allow custom loader packages to overlay resource values with configurations equivalent to the
797 // current best configuration.
798 const bool package_is_loader = loaded_package->IsCustomLoader();
799
Ryan Mitchell80094e32020-11-16 23:08:18 +0000800 auto entry_flags = type_spec->GetFlagsForEntryIndex(entry_idx);
Bernie Innocenti58cf8e32020-12-19 15:31:52 +0900801 if (UNLIKELY(!entry_flags.has_value())) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000802 return base::unexpected(entry_flags.error());
803 }
804 type_flags |= entry_flags.value();
805
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800806 const FilteredConfigGroup& filtered_group = loaded_package_impl.filtered_configs_[type_idx];
807 const size_t type_entry_count = (use_filtered) ? filtered_group.type_entries.size()
808 : type_spec->type_entries.size();
809 for (size_t i = 0; i < type_entry_count; i++) {
810 const TypeSpec::TypeEntry* type_entry = (use_filtered) ? filtered_group.type_entries[i]
811 : &type_spec->type_entries[i];
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800812
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800813 // We can skip calling ResTable_config::match() if the caller does not care for the
814 // configuration to match or if we're using the list of types that have already had their
815 // configuration matched.
816 const ResTable_config& this_config = type_entry->config;
817 if (!(use_filtered || ignore_configuration || this_config.match(desired_config))) {
818 continue;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800819 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800820
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800821 Resolution::Step::Type resolution_type;
822 if (best_config == nullptr) {
823 resolution_type = Resolution::Step::Type::INITIAL;
824 } else if (this_config.isBetterThan(*best_config, &desired_config)) {
825 resolution_type = Resolution::Step::Type::BETTER_MATCH;
826 } else if (package_is_loader && this_config.compare(*best_config) == 0) {
827 resolution_type = Resolution::Step::Type::OVERLAID;
828 } else {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000829 if (UNLIKELY(logging_enabled)) {
Jackal Guo552b45d2021-09-29 10:52:19 +0800830 last_resolution_.steps.push_back(Resolution::Step{Resolution::Step::Type::SKIPPED,
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -0700831 cookie, this_config.toString()});
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800832 }
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800833 continue;
834 }
835
836 // The configuration matches and is better than the previous selection.
837 // Find the entry value if it exists for this configuration.
838 const auto& type = type_entry->type;
839 const auto offset = LoadedPackage::GetEntryOffset(type, entry_idx);
840 if (UNLIKELY(IsIOError(offset))) {
841 return base::unexpected(offset.error());
842 }
843
844 if (!offset.has_value()) {
845 if (UNLIKELY(logging_enabled)) {
Jackal Guo552b45d2021-09-29 10:52:19 +0800846 last_resolution_.steps.push_back(Resolution::Step{Resolution::Step::Type::NO_ENTRY,
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -0700847 cookie, this_config.toString()});
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800848 }
849 continue;
850 }
851
852 best_cookie = cookie;
853 best_package = loaded_package;
854 best_type = type;
855 best_config = &this_config;
856 best_offset = offset.value();
857
858 if (UNLIKELY(logging_enabled)) {
859 last_resolution_.steps.push_back(Resolution::Step{resolution_type,
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -0700860 cookie, this_config.toString()});
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800861 }
862
863 // Any configuration will suffice, so break.
864 if (stop_at_first_match) {
865 break;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700866 }
867 }
868 }
869
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800870 if (UNLIKELY(best_cookie == kInvalidCookie)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000871 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700872 }
873
Eric Miao368cd192022-09-09 15:46:14 -0700874 auto best_entry_verified = LoadedPackage::GetEntryFromOffset(best_type, best_offset);
875 if (!best_entry_verified.has_value()) {
876 return base::unexpected(best_entry_verified.error());
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800877 }
878
Eric Miao368cd192022-09-09 15:46:14 -0700879 const auto entry = GetEntryValue(*best_entry_verified);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000880 if (!entry.has_value()) {
881 return base::unexpected(entry.error());
882 }
Winson2f3669b2019-01-11 11:28:34 -0800883
Ryan Mitchell80094e32020-11-16 23:08:18 +0000884 return FindEntryResult{
885 .cookie = best_cookie,
886 .entry = *entry,
887 .config = *best_config,
888 .type_flags = type_flags,
889 .package_name = &best_package->GetPackageName(),
890 .type_string_ref = StringPoolRef(best_package->GetTypeStringPool(), best_type->id - 1),
891 .entry_string_ref = StringPoolRef(best_package->GetKeyStringPool(),
Eric Miao368cd192022-09-09 15:46:14 -0700892 (*best_entry_verified)->key()),
Ryan Mitchell80094e32020-11-16 23:08:18 +0000893 .dynamic_ref_table = package_group.dynamic_ref_table.get(),
894 };
Adam Lesinski7ad11102016-10-28 16:39:15 -0700895}
896
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700897void AssetManager2::ResetResourceResolution() const {
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -0700898 last_resolution_ = Resolution{};
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700899}
900
Winson2f3669b2019-01-11 11:28:34 -0800901void AssetManager2::SetResourceResolutionLoggingEnabled(bool enabled) {
902 resource_resolution_logging_enabled_ = enabled;
Winson2f3669b2019-01-11 11:28:34 -0800903 if (!enabled) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700904 ResetResourceResolution();
Winson2f3669b2019-01-11 11:28:34 -0800905 }
906}
907
908std::string AssetManager2::GetLastResourceResolution() const {
909 if (!resource_resolution_logging_enabled_) {
910 LOG(ERROR) << "Must enable resource resolution logging before getting path.";
Ryan Mitchell80094e32020-11-16 23:08:18 +0000911 return {};
Winson2f3669b2019-01-11 11:28:34 -0800912 }
913
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800914 const ApkAssetsCookie cookie = last_resolution_.cookie;
Winson2f3669b2019-01-11 11:28:34 -0800915 if (cookie == kInvalidCookie) {
916 LOG(ERROR) << "AssetManager hasn't resolved a resource to read resolution path.";
Ryan Mitchell80094e32020-11-16 23:08:18 +0000917 return {};
Winson2f3669b2019-01-11 11:28:34 -0800918 }
919
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700920 auto op = StartOperation();
921
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800922 const uint32_t resid = last_resolution_.resid;
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700923 const auto& assets = GetApkAssets(cookie);
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700924 const auto package =
925 assets ? assets->GetLoadedArsc()->GetPackageById(get_package_id(resid)) : nullptr;
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800926
Winson2f3669b2019-01-11 11:28:34 -0800927 std::string resource_name_string;
Winson2f3669b2019-01-11 11:28:34 -0800928 if (package != nullptr) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000929 auto resource_name = ToResourceName(last_resolution_.type_string_ref,
930 last_resolution_.entry_string_ref,
931 package->GetPackageName());
932 resource_name_string = resource_name.has_value() ?
933 ToFormattedResourceString(resource_name.value()) : "<unknown>";
Winson2f3669b2019-01-11 11:28:34 -0800934 }
935
936 std::stringstream log_stream;
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800937 log_stream << base::StringPrintf("Resolution for 0x%08x %s\n"
938 "\tFor config - %s", resid, resource_name_string.c_str(),
939 configuration_.toString().c_str());
Winson2f3669b2019-01-11 11:28:34 -0800940
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800941 for (const Resolution::Step& step : last_resolution_.steps) {
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -0700942 constexpr static std::array kStepStrings = {
943 "Found initial",
944 "Found better",
945 "Overlaid",
946 "Overlaid inline",
947 "Skipped",
948 "No entry"
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800949 };
950
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -0700951 if (step.type < Resolution::Step::Type::INITIAL
952 || step.type > Resolution::Step::Type::NO_ENTRY) {
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800953 continue;
Winson2f3669b2019-01-11 11:28:34 -0800954 }
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -0700955 const auto prefix = kStepStrings[int(step.type) - int(Resolution::Step::Type::INITIAL)];
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -0700956 const auto& assets = GetApkAssets(step.cookie);
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700957 log_stream << "\n\t" << prefix << ": " << (assets ? assets->GetDebugName() : "<null>")
958 << " #" << step.cookie;
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800959 if (!step.config_name.isEmpty()) {
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800960 log_stream << " - " << step.config_name;
Winson2f3669b2019-01-11 11:28:34 -0800961 }
962 }
963
Jackal Guo552b45d2021-09-29 10:52:19 +0800964 log_stream << "\nBest matching is from "
965 << (last_resolution_.best_config_name.isEmpty() ? "default"
966 : last_resolution_.best_config_name)
967 << " configuration of " << last_resolution_.best_package_name;
Winson2f3669b2019-01-11 11:28:34 -0800968 return log_stream.str();
969}
970
Felka Chang00964e92021-12-10 01:19:08 +0800971base::expected<uint32_t, NullOrIOError> AssetManager2::GetParentThemeResourceId(uint32_t resid)
972const {
973 auto entry = FindEntry(resid, 0u /* density_override */,
974 false /* stop_at_first_match */,
975 false /* ignore_configuration */);
976 if (!entry.has_value()) {
977 return base::unexpected(entry.error());
978 }
979
980 auto entry_map = std::get_if<incfs::verified_map_ptr<ResTable_map_entry>>(&entry->entry);
981 if (entry_map == nullptr) {
982 // Not a bag, nothing to do.
983 return base::unexpected(std::nullopt);
984 }
985
986 auto map = *entry_map;
987 const uint32_t parent_resid = dtohl(map->parent.ident);
988
989 return parent_resid;
990}
991
Ryan Mitchell80094e32020-11-16 23:08:18 +0000992base::expected<AssetManager2::ResourceName, NullOrIOError> AssetManager2::GetResourceName(
993 uint32_t resid) const {
994 auto result = FindEntry(resid, 0u /* density_override */, true /* stop_at_first_match */,
995 true /* ignore_configuration */);
996 if (!result.has_value()) {
997 return base::unexpected(result.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -0700998 }
999
Ryan Mitchell80094e32020-11-16 23:08:18 +00001000 return ToResourceName(result->type_string_ref,
1001 result->entry_string_ref,
1002 *result->package_name);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001003}
1004
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001005base::expected<uint32_t, NullOrIOError> AssetManager2::GetResourceTypeSpecFlags(
1006 uint32_t resid) const {
1007 auto result = FindEntry(resid, 0u /* density_override */, false /* stop_at_first_match */,
1008 true /* ignore_configuration */);
1009 if (!result.has_value()) {
1010 return base::unexpected(result.error());
1011 }
1012 return result->type_flags;
1013}
1014
Ryan Mitchell80094e32020-11-16 23:08:18 +00001015base::expected<AssetManager2::SelectedValue, NullOrIOError> AssetManager2::GetResource(
1016 uint32_t resid, bool may_be_bag, uint16_t density_override) const {
1017 auto result = FindEntry(resid, density_override, false /* stop_at_first_match */,
1018 false /* ignore_configuration */);
1019 if (!result.has_value()) {
1020 return base::unexpected(result.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001021 }
1022
Ryan Mitchell80094e32020-11-16 23:08:18 +00001023 auto result_map_entry = std::get_if<incfs::verified_map_ptr<ResTable_map_entry>>(&result->entry);
Ryan Mitchellbf1f45b2020-09-29 17:22:52 -07001024 if (result_map_entry != nullptr) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001025 if (!may_be_bag) {
1026 LOG(ERROR) << base::StringPrintf("Resource %08x is a complex map type.", resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001027 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001028 }
Adam Lesinski0c405242017-01-13 20:47:26 -08001029
1030 // Create a reference since we can't represent this complex type as a Res_value.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001031 return SelectedValue(Res_value::TYPE_REFERENCE, resid, result->cookie, result->type_flags,
1032 resid, result->config);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001033 }
1034
Adam Lesinskida431a22016-12-29 16:08:16 -05001035 // Convert the package ID to the runtime assigned package ID.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001036 Res_value value = std::get<Res_value>(result->entry);
1037 result->dynamic_ref_table->lookupResourceValue(&value);
Adam Lesinskida431a22016-12-29 16:08:16 -05001038
Ryan Mitchell80094e32020-11-16 23:08:18 +00001039 return SelectedValue(value.dataType, value.data, result->cookie, result->type_flags,
1040 resid, result->config);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001041}
1042
Ryan Mitchell80094e32020-11-16 23:08:18 +00001043base::expected<std::monostate, NullOrIOError> AssetManager2::ResolveReference(
Ryan Mitchella45506e2020-11-16 23:08:18 +00001044 AssetManager2::SelectedValue& value, bool cache_value) const {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001045 if (value.type != Res_value::TYPE_REFERENCE || value.data == 0U) {
1046 // Not a reference. Nothing to do.
1047 return {};
Adam Lesinski0c405242017-01-13 20:47:26 -08001048 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001049
Ryan Mitchella45506e2020-11-16 23:08:18 +00001050 const uint32_t original_flags = value.flags;
1051 const uint32_t original_resid = value.data;
1052 if (cache_value) {
1053 auto cached_value = cached_resolved_values_.find(value.data);
1054 if (cached_value != cached_resolved_values_.end()) {
1055 value = cached_value->second;
1056 value.flags |= original_flags;
1057 return {};
1058 }
1059 }
1060
1061 uint32_t combined_flags = 0U;
1062 uint32_t resolve_resid = original_resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001063 constexpr const uint32_t kMaxIterations = 20;
1064 for (uint32_t i = 0U;; i++) {
1065 auto result = GetResource(resolve_resid, true /*may_be_bag*/);
1066 if (!result.has_value()) {
Ryan Mitchelle7ab6272020-11-13 18:06:15 -08001067 value.resid = resolve_resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001068 return base::unexpected(result.error());
1069 }
1070
Ryan Mitchelle7ab6272020-11-13 18:06:15 -08001071 // If resource resolution fails, the value should be set to the last reference that was able to
1072 // be resolved successfully.
1073 value = *result;
1074 value.flags |= combined_flags;
1075
Ryan Mitchell80094e32020-11-16 23:08:18 +00001076 if (result->type != Res_value::TYPE_REFERENCE ||
1077 result->data == Res_value::DATA_NULL_UNDEFINED ||
1078 result->data == resolve_resid || i == kMaxIterations) {
1079 // This reference can't be resolved, so exit now and let the caller deal with it.
Ryan Mitchella45506e2020-11-16 23:08:18 +00001080 if (cache_value) {
1081 cached_resolved_values_[original_resid] = value;
1082 }
1083
1084 // Above value is cached without original_flags to ensure they don't get included in future
1085 // queries that hit the cache
1086 value.flags |= original_flags;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001087 return {};
1088 }
1089
Ryan Mitchelle7ab6272020-11-13 18:06:15 -08001090 combined_flags = result->flags;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001091 resolve_resid = result->data;
1092 }
Adam Lesinski0c405242017-01-13 20:47:26 -08001093}
1094
Ryan Mitchell80094e32020-11-16 23:08:18 +00001095const std::vector<uint32_t> AssetManager2::GetBagResIdStack(uint32_t resid) const {
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001096 auto cached_iter = cached_bag_resid_stacks_.find(resid);
1097 if (cached_iter != cached_bag_resid_stacks_.end()) {
1098 return cached_iter->second;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001099 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001100
1101 std::vector<uint32_t> found_resids;
1102 GetBag(resid, found_resids);
1103 cached_bag_resid_stacks_.emplace(resid, found_resids);
1104 return found_resids;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001105}
1106
Ryan Mitchell80094e32020-11-16 23:08:18 +00001107base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::ResolveBag(
1108 AssetManager2::SelectedValue& value) const {
1109 if (UNLIKELY(value.type != Res_value::TYPE_REFERENCE)) {
1110 return base::unexpected(std::nullopt);
1111 }
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001112
Ryan Mitchell80094e32020-11-16 23:08:18 +00001113 auto bag = GetBag(value.data);
1114 if (bag.has_value()) {
1115 value.flags |= (*bag)->type_spec_flags;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001116 }
1117 return bag;
y57cd1952018-04-12 14:26:23 -07001118}
1119
Ryan Mitchell80094e32020-11-16 23:08:18 +00001120base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::GetBag(uint32_t resid) const {
1121 std::vector<uint32_t> found_resids;
1122 const auto bag = GetBag(resid, found_resids);
Yurii Zubrytskyiab3cb302022-10-11 12:15:52 -07001123 cached_bag_resid_stacks_.emplace(resid, std::move(found_resids));
Ryan Mitchell80094e32020-11-16 23:08:18 +00001124 return bag;
Ryan Mitchell155d5392020-02-10 13:35:24 -08001125}
1126
Ryan Mitchell80094e32020-11-16 23:08:18 +00001127base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::GetBag(
1128 uint32_t resid, std::vector<uint32_t>& child_resids) const {
1129 if (auto cached_iter = cached_bags_.find(resid); cached_iter != cached_bags_.end()) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001130 return cached_iter->second.get();
1131 }
1132
Ryan Mitchell80094e32020-11-16 23:08:18 +00001133 auto entry = FindEntry(resid, 0u /* density_override */, false /* stop_at_first_match */,
1134 false /* ignore_configuration */);
1135 if (!entry.has_value()) {
1136 return base::unexpected(entry.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001137 }
1138
Ryan Mitchell80094e32020-11-16 23:08:18 +00001139 auto entry_map = std::get_if<incfs::verified_map_ptr<ResTable_map_entry>>(&entry->entry);
1140 if (entry_map == nullptr) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001141 // Not a bag, nothing to do.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001142 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001143 }
1144
Ryan Mitchell80094e32020-11-16 23:08:18 +00001145 auto map = *entry_map;
1146 auto map_entry = map.offset(dtohs(map->size)).convert<ResTable_map>();
1147 const auto map_entry_end = map_entry + dtohl(map->count);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001148
y57cd1952018-04-12 14:26:23 -07001149 // Keep track of ids that have already been seen to prevent infinite loops caused by circular
Ryan Mitchell80094e32020-11-16 23:08:18 +00001150 // dependencies between bags.
y57cd1952018-04-12 14:26:23 -07001151 child_resids.push_back(resid);
1152
Adam Lesinskida431a22016-12-29 16:08:16 -05001153 uint32_t parent_resid = dtohl(map->parent.ident);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001154 if (parent_resid == 0U ||
1155 std::find(child_resids.begin(), child_resids.end(), parent_resid) != child_resids.end()) {
1156 // There is no parent or a circular parental dependency exist, meaning there is nothing to
1157 // inherit and we can do a simple copy of the entries in the map.
Adam Lesinski7ad11102016-10-28 16:39:15 -07001158 const size_t entry_count = map_entry_end - map_entry;
1159 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
1160 malloc(sizeof(ResolvedBag) + (entry_count * sizeof(ResolvedBag::Entry))))};
Ryan Mitchell155d5392020-02-10 13:35:24 -08001161
1162 bool sort_entries = false;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001163 for (auto new_entry = new_bag->entries; map_entry != map_entry_end; ++map_entry) {
1164 if (UNLIKELY(!map_entry)) {
1165 return base::unexpected(IOError::PAGES_MISSING);
1166 }
1167
Adam Lesinskida431a22016-12-29 16:08:16 -05001168 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001169 if (!is_internal_resid(new_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -05001170 // Attributes, arrays, etc don't have a resource id as the name. They specify
1171 // other data, which would be wrong to change via a lookup.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001172 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001173 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
1174 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001175 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001176 }
1177 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001178
1179 new_entry->cookie = entry->cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -05001180 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001181 new_entry->key_pool = nullptr;
1182 new_entry->type_pool = nullptr;
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001183 new_entry->style = resid;
Adam Lesinski30080e22017-10-16 16:18:09 -07001184 new_entry->value.copyFrom_dtoh(map_entry->value);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001185 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1186 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001187 LOG(ERROR) << base::StringPrintf(
1188 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
1189 new_entry->value.data, new_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001190 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001191 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001192
Ryan Mitchell155d5392020-02-10 13:35:24 -08001193 sort_entries = sort_entries ||
1194 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001195 ++new_entry;
1196 }
Ryan Mitchell155d5392020-02-10 13:35:24 -08001197
1198 if (sort_entries) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001199 std::sort(new_bag->entries, new_bag->entries + entry_count,
1200 [](auto&& lhs, auto&& rhs) { return lhs.key < rhs.key; });
Ryan Mitchell155d5392020-02-10 13:35:24 -08001201 }
1202
Ryan Mitchell80094e32020-11-16 23:08:18 +00001203 new_bag->type_spec_flags = entry->type_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001204 new_bag->entry_count = static_cast<uint32_t>(entry_count);
1205 ResolvedBag* result = new_bag.get();
1206 cached_bags_[resid] = std::move(new_bag);
1207 return result;
1208 }
1209
Adam Lesinskida431a22016-12-29 16:08:16 -05001210 // In case the parent is a dynamic reference, resolve it.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001211 entry->dynamic_ref_table->lookupResourceId(&parent_resid);
Adam Lesinskida431a22016-12-29 16:08:16 -05001212
Adam Lesinski7ad11102016-10-28 16:39:15 -07001213 // Get the parent and do a merge of the keys.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001214 const auto parent_bag = GetBag(parent_resid, child_resids);
1215 if (UNLIKELY(!parent_bag.has_value())) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001216 // Failed to get the parent that should exist.
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001217 LOG(ERROR) << base::StringPrintf("Failed to find parent 0x%08x of bag 0x%08x.", parent_resid,
1218 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001219 return base::unexpected(parent_bag.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001220 }
1221
Adam Lesinski7ad11102016-10-28 16:39:15 -07001222 // Create the max possible entries we can make. Once we construct the bag,
1223 // we will realloc to fit to size.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001224 const size_t max_count = (*parent_bag)->entry_count + dtohl(map->count);
George Burgess IV09b119f2017-07-25 15:00:04 -07001225 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
1226 malloc(sizeof(ResolvedBag) + (max_count * sizeof(ResolvedBag::Entry))))};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001227 ResolvedBag::Entry* new_entry = new_bag->entries;
1228
Ryan Mitchell80094e32020-11-16 23:08:18 +00001229 const ResolvedBag::Entry* parent_entry = (*parent_bag)->entries;
1230 const ResolvedBag::Entry* const parent_entry_end = parent_entry + (*parent_bag)->entry_count;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001231
1232 // The keys are expected to be in sorted order. Merge the two bags.
Ryan Mitchell155d5392020-02-10 13:35:24 -08001233 bool sort_entries = false;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001234 while (map_entry != map_entry_end && parent_entry != parent_entry_end) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001235 if (UNLIKELY(!map_entry)) {
1236 return base::unexpected(IOError::PAGES_MISSING);
1237 }
1238
Adam Lesinskida431a22016-12-29 16:08:16 -05001239 uint32_t child_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001240 if (!is_internal_resid(child_key)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001241 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&child_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001242 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", child_key,
1243 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001244 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001245 }
1246 }
1247
Adam Lesinski7ad11102016-10-28 16:39:15 -07001248 if (child_key <= parent_entry->key) {
1249 // Use the child key if it comes before the parent
1250 // or is equal to the parent (overrides).
Ryan Mitchell80094e32020-11-16 23:08:18 +00001251 new_entry->cookie = entry->cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001252 new_entry->key = child_key;
1253 new_entry->key_pool = nullptr;
1254 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -07001255 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001256 new_entry->style = resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001257 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1258 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001259 LOG(ERROR) << base::StringPrintf(
1260 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
1261 new_entry->value.data, child_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001262 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001263 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001264 ++map_entry;
1265 } else {
1266 // Take the parent entry as-is.
1267 memcpy(new_entry, parent_entry, sizeof(*new_entry));
1268 }
1269
Ryan Mitchell155d5392020-02-10 13:35:24 -08001270 sort_entries = sort_entries ||
1271 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001272 if (child_key >= parent_entry->key) {
1273 // Move to the next parent entry if we used it or it was overridden.
1274 ++parent_entry;
1275 }
1276 // Increment to the next entry to fill.
1277 ++new_entry;
1278 }
1279
1280 // Finish the child entries if they exist.
1281 while (map_entry != map_entry_end) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001282 if (UNLIKELY(!map_entry)) {
1283 return base::unexpected(IOError::PAGES_MISSING);
1284 }
1285
Adam Lesinskida431a22016-12-29 16:08:16 -05001286 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001287 if (!is_internal_resid(new_key)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001288 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001289 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
1290 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001291 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001292 }
1293 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001294 new_entry->cookie = entry->cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -05001295 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001296 new_entry->key_pool = nullptr;
1297 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -07001298 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001299 new_entry->style = resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001300 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1301 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001302 LOG(ERROR) << base::StringPrintf("Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.",
1303 new_entry->value.dataType, new_entry->value.data, new_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001304 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001305 }
Ryan Mitchell155d5392020-02-10 13:35:24 -08001306 sort_entries = sort_entries ||
1307 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001308 ++map_entry;
1309 ++new_entry;
1310 }
1311
1312 // Finish the parent entries if they exist.
1313 if (parent_entry != parent_entry_end) {
1314 // Take the rest of the parent entries as-is.
1315 const size_t num_entries_to_copy = parent_entry_end - parent_entry;
1316 memcpy(new_entry, parent_entry, num_entries_to_copy * sizeof(*new_entry));
1317 new_entry += num_entries_to_copy;
1318 }
1319
1320 // Resize the resulting array to fit.
1321 const size_t actual_count = new_entry - new_bag->entries;
1322 if (actual_count != max_count) {
George Burgess IV09b119f2017-07-25 15:00:04 -07001323 new_bag.reset(reinterpret_cast<ResolvedBag*>(realloc(
1324 new_bag.release(), sizeof(ResolvedBag) + (actual_count * sizeof(ResolvedBag::Entry)))));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001325 }
1326
Ryan Mitchell155d5392020-02-10 13:35:24 -08001327 if (sort_entries) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001328 std::sort(new_bag->entries, new_bag->entries + actual_count,
1329 [](auto&& lhs, auto&& rhs) { return lhs.key < rhs.key; });
Ryan Mitchell155d5392020-02-10 13:35:24 -08001330 }
1331
Adam Lesinski1a1e9c22017-10-13 15:45:34 -07001332 // Combine flags from the parent and our own bag.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001333 new_bag->type_spec_flags = entry->type_flags | (*parent_bag)->type_spec_flags;
George Burgess IV09b119f2017-07-25 15:00:04 -07001334 new_bag->entry_count = static_cast<uint32_t>(actual_count);
1335 ResolvedBag* result = new_bag.get();
1336 cached_bags_[resid] = std::move(new_bag);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001337 return result;
1338}
1339
Yurii Zubrytskyia5775142022-11-02 17:49:49 -07001340static bool Utf8ToUtf16(StringPiece str, std::u16string* out) {
Adam Lesinski929d6512017-01-16 19:11:19 -08001341 ssize_t len =
1342 utf8_to_utf16_length(reinterpret_cast<const uint8_t*>(str.data()), str.size(), false);
1343 if (len < 0) {
1344 return false;
1345 }
1346 out->resize(static_cast<size_t>(len));
1347 utf8_to_utf16(reinterpret_cast<const uint8_t*>(str.data()), str.size(), &*out->begin(),
1348 static_cast<size_t>(len + 1));
1349 return true;
1350}
1351
Ryan Mitchell80094e32020-11-16 23:08:18 +00001352base::expected<uint32_t, NullOrIOError> AssetManager2::GetResourceId(
1353 const std::string& resource_name, const std::string& fallback_type,
1354 const std::string& fallback_package) const {
Adam Lesinski929d6512017-01-16 19:11:19 -08001355 StringPiece package_name, type, entry;
1356 if (!ExtractResourceName(resource_name, &package_name, &type, &entry)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001357 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001358 }
1359
1360 if (entry.empty()) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001361 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001362 }
1363
1364 if (package_name.empty()) {
1365 package_name = fallback_package;
1366 }
1367
1368 if (type.empty()) {
1369 type = fallback_type;
1370 }
1371
1372 std::u16string type16;
1373 if (!Utf8ToUtf16(type, &type16)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001374 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001375 }
1376
1377 std::u16string entry16;
1378 if (!Utf8ToUtf16(entry, &entry16)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001379 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001380 }
1381
1382 const StringPiece16 kAttr16 = u"attr";
1383 const static std::u16string kAttrPrivate16 = u"^attr-private";
1384
1385 for (const PackageGroup& package_group : package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001386 for (const ConfiguredPackage& package_impl : package_group.packages_) {
1387 const LoadedPackage* package = package_impl.loaded_package_;
Adam Lesinski929d6512017-01-16 19:11:19 -08001388 if (package_name != package->GetPackageName()) {
1389 // All packages in the same group are expected to have the same package name.
1390 break;
1391 }
1392
Ryan Mitchell80094e32020-11-16 23:08:18 +00001393 base::expected<uint32_t, NullOrIOError> resid = package->FindEntryByName(type16, entry16);
1394 if (UNLIKELY(IsIOError(resid))) {
1395 return base::unexpected(resid.error());
1396 }
1397
1398 if (!resid.has_value() && kAttr16 == type16) {
Adam Lesinski929d6512017-01-16 19:11:19 -08001399 // Private attributes in libraries (such as the framework) are sometimes encoded
1400 // under the type '^attr-private' in order to leave the ID space of public 'attr'
1401 // free for future additions. Check '^attr-private' for the same name.
1402 resid = package->FindEntryByName(kAttrPrivate16, entry16);
1403 }
1404
Ryan Mitchell80094e32020-11-16 23:08:18 +00001405 if (resid.has_value()) {
1406 return fix_package_id(*resid, package_group.dynamic_ref_table->mAssignedPackageId);
Adam Lesinski929d6512017-01-16 19:11:19 -08001407 }
1408 }
1409 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001410 return base::unexpected(std::nullopt);
Adam Lesinski0c405242017-01-13 20:47:26 -08001411}
1412
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001413void AssetManager2::RebuildFilterList() {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001414 for (PackageGroup& group : package_groups_) {
Yurii Zubrytskyidbce3562022-11-14 22:26:10 -08001415 for (ConfiguredPackage& package : group.packages_) {
1416 package.filtered_configs_.forEachItem([](auto, auto& fcg) { fcg.type_entries.clear(); });
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001417 // Create the filters here.
Yurii Zubrytskyidbce3562022-11-14 22:26:10 -08001418 package.loaded_package_->ForEachTypeSpec([&](const TypeSpec& type_spec, uint8_t type_id) {
Yurii Zubrytskyi59dab3b2022-11-03 00:08:49 -07001419 FilteredConfigGroup* group = nullptr;
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001420 for (const auto& type_entry : type_spec.type_entries) {
1421 if (type_entry.config.match(configuration_)) {
Yurii Zubrytskyi59dab3b2022-11-03 00:08:49 -07001422 if (!group) {
Yurii Zubrytskyidbce3562022-11-14 22:26:10 -08001423 group = &package.filtered_configs_.editItemAt(type_id - 1);
Yurii Zubrytskyi59dab3b2022-11-03 00:08:49 -07001424 }
1425 group->type_entries.push_back(&type_entry);
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001426 }
1427 }
1428 });
Yurii Zubrytskyidbce3562022-11-14 22:26:10 -08001429 package.filtered_configs_.trimBuckets(
1430 [](const auto& fcg) { return fcg.type_entries.empty(); });
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001431 }
1432 }
1433}
1434
Adam Lesinski7ad11102016-10-28 16:39:15 -07001435void AssetManager2::InvalidateCaches(uint32_t diff) {
Ryan Mitchell2c4d8742019-03-04 09:41:00 -08001436 cached_bag_resid_stacks_.clear();
1437
Adam Lesinski7ad11102016-10-28 16:39:15 -07001438 if (diff == 0xffffffffu) {
1439 // Everything must go.
1440 cached_bags_.clear();
1441 return;
1442 }
1443
1444 // Be more conservative with what gets purged. Only if the bag has other possible
1445 // variations with respect to what changed (diff) should we remove it.
1446 for (auto iter = cached_bags_.cbegin(); iter != cached_bags_.cend();) {
1447 if (diff & iter->second->type_spec_flags) {
1448 iter = cached_bags_.erase(iter);
1449 } else {
1450 ++iter;
1451 }
1452 }
Ryan Mitchella45506e2020-11-16 23:08:18 +00001453
1454 cached_resolved_values_.clear();
Adam Lesinski7ad11102016-10-28 16:39:15 -07001455}
1456
Ryan Mitchell2e394222019-08-28 12:10:51 -07001457uint8_t AssetManager2::GetAssignedPackageId(const LoadedPackage* package) const {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001458 for (auto& package_group : package_groups_) {
1459 for (auto& package2 : package_group.packages_) {
1460 if (package2.loaded_package_ == package) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -07001461 return package_group.dynamic_ref_table->mAssignedPackageId;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001462 }
1463 }
1464 }
1465 return 0;
1466}
1467
Adam Lesinski30080e22017-10-16 16:18:09 -07001468std::unique_ptr<Theme> AssetManager2::NewTheme() {
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001469 constexpr size_t kInitialReserveSize = 32;
1470 auto theme = std::unique_ptr<Theme>(new Theme(this));
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001471 theme->keys_.reserve(kInitialReserveSize);
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001472 theme->entries_.reserve(kInitialReserveSize);
1473 return theme;
Adam Lesinski30080e22017-10-16 16:18:09 -07001474}
1475
Yurii Zubrytskyi9eb44c92022-11-14 23:44:52 -08001476void AssetManager2::ForEachPackage(base::function_ref<bool(const std::string&, uint8_t)> func,
1477 package_property_t excluded_property_flags) const {
1478 for (const PackageGroup& package_group : package_groups_) {
1479 const auto loaded_package = package_group.packages_.front().loaded_package_;
1480 if ((loaded_package->GetPropertyFlags() & excluded_property_flags) == 0U
1481 && !func(loaded_package->GetPackageName(),
1482 package_group.dynamic_ref_table->mAssignedPackageId)) {
1483 return;
1484 }
1485 }
1486}
1487
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -07001488AssetManager2::ScopedOperation AssetManager2::StartOperation() const {
1489 ++number_of_running_scoped_operations_;
1490 return ScopedOperation(*this);
1491}
1492
1493void AssetManager2::FinishOperation() const {
1494 if (number_of_running_scoped_operations_ < 1) {
1495 ALOGW("Invalid FinishOperation() call when there's none happening");
1496 return;
1497 }
1498 if (--number_of_running_scoped_operations_ == 0) {
1499 for (auto&& [_, assets] : apk_assets_) {
1500 assets.clear();
1501 }
1502 }
1503}
1504
1505const AssetManager2::ApkAssetsPtr& AssetManager2::GetApkAssets(ApkAssetsCookie cookie) const {
1506 DCHECK(number_of_running_scoped_operations_ > 0) << "Must have an operation running";
1507
1508 if (cookie < 0 || cookie >= apk_assets_.size()) {
1509 static const ApkAssetsPtr empty{};
1510 return empty;
1511 }
1512 auto& [wptr, res] = apk_assets_[cookie];
1513 if (!res) {
1514 res = wptr.promote();
1515 }
1516 return res;
1517}
1518
Adam Lesinski30080e22017-10-16 16:18:09 -07001519Theme::Theme(AssetManager2* asset_manager) : asset_manager_(asset_manager) {
1520}
1521
1522Theme::~Theme() = default;
1523
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001524struct Theme::Entry {
Adam Lesinski30080e22017-10-16 16:18:09 -07001525 ApkAssetsCookie cookie;
1526 uint32_t type_spec_flags;
1527 Res_value value;
1528};
1529
Ryan Mitchell80094e32020-11-16 23:08:18 +00001530base::expected<std::monostate, NullOrIOError> Theme::ApplyStyle(uint32_t resid, bool force) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001531 ATRACE_NAME("Theme::ApplyStyle");
Adam Lesinski7ad11102016-10-28 16:39:15 -07001532
Ryan Mitchell80094e32020-11-16 23:08:18 +00001533 auto bag = asset_manager_->GetBag(resid);
1534 if (!bag.has_value()) {
1535 return base::unexpected(bag.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001536 }
1537
1538 // Merge the flags from this style.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001539 type_spec_flags_ |= (*bag)->type_spec_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001540
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001541 for (auto it = begin(*bag); it != end(*bag); ++it) {
1542 const uint32_t attr_res_id = it->key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001543
Adam Lesinski30080e22017-10-16 16:18:09 -07001544 // If the resource ID passed in is not a style, the key can be some other identifier that is not
1545 // a resource ID. We should fail fast instead of operating with strange resource IDs.
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001546 if (!is_valid_resid(attr_res_id)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001547 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001548 }
1549
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001550 // DATA_NULL_EMPTY (@empty) is a valid resource value and DATA_NULL_UNDEFINED represents
1551 // an absence of a valid value.
1552 bool is_undefined = it->value.dataType == Res_value::TYPE_NULL &&
1553 it->value.data != Res_value::DATA_NULL_EMPTY;
1554 if (!force && is_undefined) {
1555 continue;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001556 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001557
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001558 const auto key_it = std::lower_bound(keys_.begin(), keys_.end(), attr_res_id);
1559 const auto entry_it = entries_.begin() + (key_it - keys_.begin());
1560 if (key_it != keys_.end() && *key_it == attr_res_id) {
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001561 if (is_undefined) {
1562 // DATA_NULL_UNDEFINED clears the value of the attribute in the theme only when `force` is
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001563 // true.
1564 keys_.erase(key_it);
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001565 entries_.erase(entry_it);
1566 } else if (force) {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001567 *entry_it = Entry{it->cookie, (*bag)->type_spec_flags, it->value};
Adam Lesinski30080e22017-10-16 16:18:09 -07001568 }
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001569 } else {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001570 keys_.insert(key_it, attr_res_id);
1571 entries_.insert(entry_it, Entry{it->cookie, (*bag)->type_spec_flags, it->value});
Adam Lesinski7ad11102016-10-28 16:39:15 -07001572 }
1573 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001574 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001575}
1576
Ryan Mitchell767e34f2021-06-07 12:29:05 -07001577void Theme::Rebase(AssetManager2* am, const uint32_t* style_ids, const uint8_t* force,
1578 size_t style_count) {
1579 ATRACE_NAME("Theme::Rebase");
1580 // Reset the entries without changing the vector capacity to prevent reallocations during
1581 // ApplyStyle.
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001582 keys_.clear();
Ryan Mitchell767e34f2021-06-07 12:29:05 -07001583 entries_.clear();
1584 asset_manager_ = am;
1585 for (size_t i = 0; i < style_count; i++) {
1586 ApplyStyle(style_ids[i], force[i]);
1587 }
1588}
1589
Ryan Mitchell80094e32020-11-16 23:08:18 +00001590std::optional<AssetManager2::SelectedValue> Theme::GetAttribute(uint32_t resid) const {
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001591 constexpr const uint32_t kMaxIterations = 20;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001592 uint32_t type_spec_flags = 0u;
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001593 for (uint32_t i = 0; i <= kMaxIterations; i++) {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001594 const auto key_it = std::lower_bound(keys_.begin(), keys_.end(), resid);
1595 if (key_it == keys_.end() || *key_it != resid) {
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001596 return std::nullopt;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001597 }
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001598 const auto entry_it = entries_.begin() + (key_it - keys_.begin());
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001599 type_spec_flags |= entry_it->type_spec_flags;
1600 if (entry_it->value.dataType == Res_value::TYPE_ATTRIBUTE) {
1601 resid = entry_it->value.data;
1602 continue;
1603 }
1604
1605 return AssetManager2::SelectedValue(entry_it->value.dataType, entry_it->value.data,
1606 entry_it->cookie, type_spec_flags, 0U /* resid */,
1607 {} /* config */);
1608 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001609 return std::nullopt;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001610}
1611
Ryan Mitchell80094e32020-11-16 23:08:18 +00001612base::expected<std::monostate, NullOrIOError> Theme::ResolveAttributeReference(
1613 AssetManager2::SelectedValue& value) const {
1614 if (value.type != Res_value::TYPE_ATTRIBUTE) {
1615 return asset_manager_->ResolveReference(value);
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001616 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001617
1618 std::optional<AssetManager2::SelectedValue> result = GetAttribute(value.data);
1619 if (!result.has_value()) {
1620 return base::unexpected(std::nullopt);
1621 }
1622
Ryan Mitchella45506e2020-11-16 23:08:18 +00001623 auto resolve_result = asset_manager_->ResolveReference(*result, true /* cache_value */);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001624 if (resolve_result.has_value()) {
1625 result->flags |= value.flags;
1626 value = *result;
1627 }
1628 return resolve_result;
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001629}
1630
Adam Lesinski7ad11102016-10-28 16:39:15 -07001631void Theme::Clear() {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001632 keys_.clear();
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001633 entries_.clear();
Adam Lesinski7ad11102016-10-28 16:39:15 -07001634}
1635
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001636base::expected<std::monostate, IOError> Theme::SetTo(const Theme& source) {
1637 if (this == &source) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001638 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001639 }
1640
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001641 type_spec_flags_ = source.type_spec_flags_;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001642
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001643 if (asset_manager_ == source.asset_manager_) {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001644 keys_ = source.keys_;
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001645 entries_ = source.entries_;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001646 } else {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001647 std::unordered_map<ApkAssetsCookie, ApkAssetsCookie> src_to_dest_asset_cookies;
1648 using SourceToDestinationRuntimePackageMap = std::unordered_map<int, int>;
1649 std::unordered_map<ApkAssetsCookie, SourceToDestinationRuntimePackageMap> src_asset_cookie_id_map;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001650
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -07001651 auto op_src = source.asset_manager_->StartOperation();
1652 auto op_dst = asset_manager_->StartOperation();
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001653
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -07001654 for (size_t i = 0; i < source.asset_manager_->GetApkAssetsCount(); i++) {
1655 const auto& src_asset = source.asset_manager_->GetApkAssets(i);
1656 if (!src_asset) {
Yurii Zubrytskyib3455192023-05-01 14:35:48 -07001657 continue;
1658 }
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -07001659 for (int j = 0; j < asset_manager_->GetApkAssetsCount(); j++) {
1660 const auto& dest_asset = asset_manager_->GetApkAssets(j);
Ryan Mitchellef538432021-03-01 14:52:14 -08001661 if (src_asset != dest_asset) {
1662 // ResourcesManager caches and reuses ApkAssets when the same apk must be present in
1663 // multiple AssetManagers. Two ApkAssets point to the same version of the same resources
1664 // if they are the same instance.
1665 continue;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001666 }
Ryan Mitchellef538432021-03-01 14:52:14 -08001667
1668 // Map the package ids of the asset in the source AssetManager to the package ids of the
1669 // asset in th destination AssetManager.
1670 SourceToDestinationRuntimePackageMap package_map;
1671 for (const auto& loaded_package : src_asset->GetLoadedArsc()->GetPackages()) {
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001672 const int src_package_id = source.asset_manager_->GetAssignedPackageId(
1673 loaded_package.get());
Ryan Mitchellef538432021-03-01 14:52:14 -08001674 const int dest_package_id = asset_manager_->GetAssignedPackageId(loaded_package.get());
1675 package_map[src_package_id] = dest_package_id;
1676 }
1677
1678 src_to_dest_asset_cookies.insert(std::make_pair(i, j));
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001679 src_asset_cookie_id_map.insert(std::make_pair(i, std::move(package_map)));
Ryan Mitchellef538432021-03-01 14:52:14 -08001680 break;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001681 }
1682 }
1683
Ryan Mitchell93bca972019-03-08 17:26:28 -08001684 // Reset the data in the destination theme.
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001685 keys_.clear();
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001686 entries_.clear();
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001687
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001688 for (size_t i = 0, size = source.entries_.size(); i != size; ++i) {
1689 const auto& entry = source.entries_[i];
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001690 bool is_reference = (entry.value.dataType == Res_value::TYPE_ATTRIBUTE
1691 || entry.value.dataType == Res_value::TYPE_REFERENCE
1692 || entry.value.dataType == Res_value::TYPE_DYNAMIC_ATTRIBUTE
1693 || entry.value.dataType == Res_value::TYPE_DYNAMIC_REFERENCE)
1694 && entry.value.data != 0x0;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001695
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001696 // If the attribute value represents an attribute or reference, the package id of the
1697 // value needs to be rewritten to the package id of the value in the destination.
1698 uint32_t attribute_data = entry.value.data;
1699 if (is_reference) {
1700 // Determine the package id of the reference in the destination AssetManager.
1701 auto value_package_map = src_asset_cookie_id_map.find(entry.cookie);
1702 if (value_package_map == src_asset_cookie_id_map.end()) {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001703 continue;
1704 }
1705
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001706 auto value_dest_package = value_package_map->second.find(
1707 get_package_id(entry.value.data));
1708 if (value_dest_package == value_package_map->second.end()) {
1709 continue;
1710 }
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001711
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001712 attribute_data = fix_package_id(entry.value.data, value_dest_package->second);
1713 }
Ryan Mitchellb85d9b22018-11-19 12:11:38 -08001714
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001715 // Find the cookie of the value in the destination. If the source apk is not loaded in the
1716 // destination, only copy resources that do not reference resources in the source.
1717 ApkAssetsCookie data_dest_cookie;
1718 auto value_dest_cookie = src_to_dest_asset_cookies.find(entry.cookie);
1719 if (value_dest_cookie != src_to_dest_asset_cookies.end()) {
1720 data_dest_cookie = value_dest_cookie->second;
1721 } else {
1722 if (is_reference || entry.value.dataType == Res_value::TYPE_STRING) {
1723 continue;
1724 } else {
1725 data_dest_cookie = 0x0;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001726 }
1727 }
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001728
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001729 const auto source_res_id = source.keys_[i];
1730
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001731 // The package id of the attribute needs to be rewritten to the package id of the
1732 // attribute in the destination.
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001733 int attribute_dest_package_id = get_package_id(source_res_id);
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001734 if (attribute_dest_package_id != 0x01) {
1735 // Find the cookie of the attribute resource id in the source AssetManager
1736 base::expected<FindEntryResult, NullOrIOError> attribute_entry_result =
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001737 source.asset_manager_->FindEntry(source_res_id, 0 /* density_override */ ,
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001738 true /* stop_at_first_match */,
1739 true /* ignore_configuration */);
1740 if (UNLIKELY(IsIOError(attribute_entry_result))) {
1741 return base::unexpected(GetIOError(attribute_entry_result.error()));
1742 }
1743 if (!attribute_entry_result.has_value()) {
1744 continue;
1745 }
1746
1747 // Determine the package id of the attribute in the destination AssetManager.
1748 auto attribute_package_map = src_asset_cookie_id_map.find(
1749 attribute_entry_result->cookie);
1750 if (attribute_package_map == src_asset_cookie_id_map.end()) {
1751 continue;
1752 }
1753 auto attribute_dest_package = attribute_package_map->second.find(
1754 attribute_dest_package_id);
1755 if (attribute_dest_package == attribute_package_map->second.end()) {
1756 continue;
1757 }
1758 attribute_dest_package_id = attribute_dest_package->second;
1759 }
1760
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001761 auto dest_attr_id = make_resid(attribute_dest_package_id, get_type_id(source_res_id),
1762 get_entry_id(source_res_id));
1763 const auto key_it = std::lower_bound(keys_.begin(), keys_.end(), dest_attr_id);
1764 const auto entry_it = entries_.begin() + (key_it - keys_.begin());
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001765 // Since the entries were cleared, the attribute resource id has yet been mapped to any value.
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001766 keys_.insert(key_it, dest_attr_id);
1767 entries_.insert(entry_it, Entry{data_dest_cookie, entry.type_spec_flags,
1768 Res_value{.dataType = entry.value.dataType,
1769 .data = attribute_data}});
Adam Lesinski7ad11102016-10-28 16:39:15 -07001770 }
1771 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001772 return {};
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001773}
1774
1775void Theme::Dump() const {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001776 LOG(INFO) << base::StringPrintf("Theme(this=%p, AssetManager2=%p)", this, asset_manager_);
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001777 for (size_t i = 0, size = keys_.size(); i != size; ++i) {
1778 auto res_id = keys_[i];
1779 const auto& entry = entries_[i];
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001780 LOG(INFO) << base::StringPrintf(" entry(0x%08x)=(0x%08x) type=(0x%02x), cookie(%d)",
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001781 res_id, entry.value.data, entry.value.dataType,
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001782 entry.cookie);
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001783 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001784}
1785
Yurii Zubrytskyibdcbf552023-05-10 13:16:23 -07001786AssetManager2::ScopedOperation::ScopedOperation(const AssetManager2& am) : am_(am) {
1787}
1788
1789AssetManager2::ScopedOperation::~ScopedOperation() {
1790 am_.FinishOperation();
1791}
1792
Adam Lesinski7ad11102016-10-28 16:39:15 -07001793} // namespace android