blob: 94dbfb5db1d705c105eff9775d9431b9556feff1 [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) {
115 apk_assets_.assign(apk_assets.begin(), apk_assets.end());
Adam Lesinskida431a22016-12-29 16:08:16 -0500116 package_groups_.clear();
117 package_ids_.fill(0xff);
118
Ryan Mitchellef538432021-03-01 14:52:14 -0800119 // A mapping from path of apk assets that could be target packages of overlays to the runtime
120 // package id of its first loaded package. Overlays currently can only override resources in the
121 // first package in the target resource table.
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800122 std::unordered_map<std::string_view, uint8_t> target_assets_package_ids;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700123
Ryan Mitchell824cc492020-02-12 10:48:14 -0800124 // Overlay resources are not directly referenced by an application so their resource ids
125 // can change throughout the application's lifetime. Assign overlay package ids last.
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700126 std::vector<const ApkAssets*> sorted_apk_assets;
127 sorted_apk_assets.reserve(apk_assets_.size());
128 for (auto& asset : apk_assets) {
129 sorted_apk_assets.push_back(asset.get());
130 }
131 std::stable_partition(sorted_apk_assets.begin(), sorted_apk_assets.end(),
132 [](auto a) { return !a->IsOverlay(); });
Ryan Mitchell824cc492020-02-12 10:48:14 -0800133
134 // The assets cookie must map to the position of the apk assets in the unsorted apk assets list.
135 std::unordered_map<const ApkAssets*, ApkAssetsCookie> apk_assets_cookies;
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700136 apk_assets_cookies.reserve(apk_assets.size());
137 for (size_t i = 0, n = apk_assets.size(); i < n; i++) {
138 apk_assets_cookies[apk_assets[i].get()] = static_cast<ApkAssetsCookie>(i);
Ryan Mitchell824cc492020-02-12 10:48:14 -0800139 }
140
Ryan Mitchellb894c272020-02-12 10:31:44 -0800141 // 0x01 is reserved for the android package.
142 int next_package_id = 0x02;
Ryan Mitchell824cc492020-02-12 10:48:14 -0800143 for (const ApkAssets* apk_assets : sorted_apk_assets) {
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800144 std::shared_ptr<OverlayDynamicRefTable> overlay_ref_table;
145 if (auto loaded_idmap = apk_assets->GetLoadedIdmap(); loaded_idmap != nullptr) {
146 // The target package must precede the overlay package in the apk assets paths in order
147 // to take effect.
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800148 auto iter = target_assets_package_ids.find(loaded_idmap->TargetApkPath());
Ryan Mitchellef538432021-03-01 14:52:14 -0800149 if (iter == target_assets_package_ids.end()) {
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800150 LOG(INFO) << "failed to find target package for overlay "
151 << loaded_idmap->OverlayApkPath();
152 } else {
153 uint8_t target_package_id = iter->second;
154
155 // Create a special dynamic reference table for the overlay to rewrite references to
156 // overlay resources as references to the target resources they overlay.
157 overlay_ref_table = std::make_shared<OverlayDynamicRefTable>(
158 loaded_idmap->GetOverlayDynamicRefTable(target_package_id));
159
160 // Add the overlay resource map to the target package's set of overlays.
161 const uint8_t target_idx = package_ids_[target_package_id];
162 CHECK(target_idx != 0xff) << "overlay target '" << loaded_idmap->TargetApkPath()
163 << "'added to apk_assets_package_ids but does not have an"
164 << " assigned package group";
165
166 PackageGroup& target_package_group = package_groups_[target_idx];
167 target_package_group.overlays_.push_back(
168 ConfiguredOverlay{loaded_idmap->GetTargetResourcesMap(target_package_id,
169 overlay_ref_table.get()),
170 apk_assets_cookies[apk_assets]});
171 }
172 }
173
Ryan Mitchellb894c272020-02-12 10:31:44 -0800174 const LoadedArsc* loaded_arsc = apk_assets->GetLoadedArsc();
Ryan Mitchellb894c272020-02-12 10:31:44 -0800175 for (const std::unique_ptr<const LoadedPackage>& package : loaded_arsc->GetPackages()) {
176 // Get the package ID or assign one if a shared library.
177 int package_id;
178 if (package->IsDynamic()) {
179 package_id = next_package_id++;
180 } else {
181 package_id = package->GetPackageId();
Adam Lesinskida431a22016-12-29 16:08:16 -0500182 }
183
Adam Lesinskida431a22016-12-29 16:08:16 -0500184 uint8_t idx = package_ids_[package_id];
185 if (idx == 0xff) {
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800186 // Add the mapping for package ID to index if not present.
Adam Lesinskida431a22016-12-29 16:08:16 -0500187 package_ids_[package_id] = idx = static_cast<uint8_t>(package_groups_.size());
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800188 PackageGroup& new_group = package_groups_.emplace_back();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700189
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800190 if (overlay_ref_table != nullptr) {
191 // If this package is from an overlay, use a dynamic reference table that can rewrite
192 // overlay resource ids to their corresponding target resource ids.
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800193 new_group.dynamic_ref_table = std::move(overlay_ref_table);
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700194 }
195
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800196 DynamicRefTable* ref_table = new_group.dynamic_ref_table.get();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700197 ref_table->mAssignedPackageId = package_id;
198 ref_table->mAppAsLib = package->IsDynamic() && package->GetPackageId() == 0x7f;
Adam Lesinskida431a22016-12-29 16:08:16 -0500199 }
Adam Lesinskida431a22016-12-29 16:08:16 -0500200
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800201 // Add the package to the set of packages with the same ID.
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800202 PackageGroup* package_group = &package_groups_[idx];
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800203 package_group->packages_.emplace_back().loaded_package_ = package.get();
Ryan Mitchell824cc492020-02-12 10:48:14 -0800204 package_group->cookies_.push_back(apk_assets_cookies[apk_assets]);
Adam Lesinskida431a22016-12-29 16:08:16 -0500205
206 // Add the package name -> build time ID mappings.
207 for (const DynamicPackageEntry& entry : package->GetDynamicPackageMap()) {
208 String16 package_name(entry.package_name.c_str(), entry.package_name.size());
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700209 package_group->dynamic_ref_table->mEntries.replaceValueFor(
Adam Lesinskida431a22016-12-29 16:08:16 -0500210 package_name, static_cast<uint8_t>(entry.package_id));
211 }
Ryan Mitchellb894c272020-02-12 10:31:44 -0800212
Ryan Mitchellef538432021-03-01 14:52:14 -0800213 if (auto apk_assets_path = apk_assets->GetPath()) {
214 // Overlay target ApkAssets must have been created using path based load apis.
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800215 target_assets_package_ids.emplace(*apk_assets_path, package_id);
Ryan Mitchellef538432021-03-01 14:52:14 -0800216 }
Adam Lesinskida431a22016-12-29 16:08:16 -0500217 }
218 }
219
220 // Now assign the runtime IDs so that we have a build-time to runtime ID map.
Yurii Zubrytskyi59dab3b2022-11-03 00:08:49 -0700221 DynamicRefTable::AliasMap aliases;
222 for (const auto& group : package_groups_) {
223 const std::string& package_name = group.packages_[0].loaded_package_->GetPackageName();
224 const auto name_16 = String16(package_name.c_str(), package_name.size());
225 for (auto&& inner_group : package_groups_) {
226 inner_group.dynamic_ref_table->addMapping(name_16,
227 group.dynamic_ref_table->mAssignedPackageId);
Adam Lesinskida431a22016-12-29 16:08:16 -0500228 }
Yurii Zubrytskyi59dab3b2022-11-03 00:08:49 -0700229
230 for (const auto& package : group.packages_) {
231 const auto& package_aliases = package.loaded_package_->GetAliasResourceIdMap();
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800232 aliases.insert(aliases.end(), package_aliases.begin(), package_aliases.end());
Yurii Zubrytskyi59dab3b2022-11-03 00:08:49 -0700233 }
234 }
235
236 if (!aliases.empty()) {
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800237 std::sort(aliases.begin(), aliases.end(), [](auto&& l, auto&& r) { return l.first < r.first; });
238
Yurii Zubrytskyi59dab3b2022-11-03 00:08:49 -0700239 // Add the alias resources to the dynamic reference table of every package group. Since
240 // staging aliases can only be defined by the framework package (which is not a shared
241 // library), the compile-time package id of the framework is the same across all packages
242 // that compile against the framework.
243 for (auto& group : std::span(package_groups_.data(), package_groups_.size() - 1)) {
244 group.dynamic_ref_table->setAliases(aliases);
245 }
246 package_groups_.back().dynamic_ref_table->setAliases(std::move(aliases));
Adam Lesinskida431a22016-12-29 16:08:16 -0500247 }
248}
249
250void AssetManager2::DumpToLog() const {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800251 LOG(INFO) << base::StringPrintf("AssetManager2(this=%p)", this);
252
Adam Lesinskida431a22016-12-29 16:08:16 -0500253 std::string list;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800254 for (const auto& apk_assets : apk_assets_) {
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700255 auto assets = apk_assets.promote();
256 base::StringAppendF(&list, "%s,", assets ? assets->GetDebugName().c_str() : "nullptr");
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800257 }
258 LOG(INFO) << "ApkAssets: " << list;
259
260 list = "";
Adam Lesinskida431a22016-12-29 16:08:16 -0500261 for (size_t i = 0; i < package_ids_.size(); i++) {
262 if (package_ids_[i] != 0xff) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800263 base::StringAppendF(&list, "%02x -> %d, ", (int)i, package_ids_[i]);
Adam Lesinskida431a22016-12-29 16:08:16 -0500264 }
265 }
266 LOG(INFO) << "Package ID map: " << list;
267
Adam Lesinski0dd36992018-01-25 15:38:38 -0800268 for (const auto& package_group: package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800269 list = "";
270 for (const auto& package : package_group.packages_) {
271 const LoadedPackage* loaded_package = package.loaded_package_;
272 base::StringAppendF(&list, "%s(%02x%s), ", loaded_package->GetPackageName().c_str(),
273 loaded_package->GetPackageId(),
274 (loaded_package->IsDynamic() ? " dynamic" : ""));
275 }
276 LOG(INFO) << base::StringPrintf("PG (%02x): ",
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700277 package_group.dynamic_ref_table->mAssignedPackageId)
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800278 << list;
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800279
280 for (size_t i = 0; i < 256; i++) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700281 if (package_group.dynamic_ref_table->mLookupTable[i] != 0) {
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800282 LOG(INFO) << base::StringPrintf(" e[0x%02x] -> 0x%02x", (uint8_t) i,
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700283 package_group.dynamic_ref_table->mLookupTable[i]);
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800284 }
285 }
Adam Lesinskida431a22016-12-29 16:08:16 -0500286 }
287}
Adam Lesinski7ad11102016-10-28 16:39:15 -0700288
289const ResStringPool* AssetManager2::GetStringPoolForCookie(ApkAssetsCookie cookie) const {
290 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
291 return nullptr;
292 }
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700293 auto assets = apk_assets_[cookie].promote();
294 return assets ? assets->GetLoadedArsc()->GetStringPool() : nullptr;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700295}
296
Adam Lesinskida431a22016-12-29 16:08:16 -0500297const DynamicRefTable* AssetManager2::GetDynamicRefTableForPackage(uint32_t package_id) const {
298 if (package_id >= package_ids_.size()) {
299 return nullptr;
300 }
301
302 const size_t idx = package_ids_[package_id];
303 if (idx == 0xff) {
304 return nullptr;
305 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700306 return package_groups_[idx].dynamic_ref_table.get();
Adam Lesinskida431a22016-12-29 16:08:16 -0500307}
308
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700309std::shared_ptr<const DynamicRefTable> AssetManager2::GetDynamicRefTableForCookie(
310 ApkAssetsCookie cookie) const {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800311 for (const PackageGroup& package_group : package_groups_) {
312 for (const ApkAssetsCookie& package_cookie : package_group.cookies_) {
313 if (package_cookie == cookie) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700314 return package_group.dynamic_ref_table;
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800315 }
316 }
317 }
318 return nullptr;
319}
320
MÃ¥rten Kongstadc92c4dd2019-02-05 01:29:59 +0100321const std::unordered_map<std::string, std::string>*
322 AssetManager2::GetOverlayableMapForPackage(uint32_t package_id) const {
323
324 if (package_id >= package_ids_.size()) {
325 return nullptr;
326 }
327
328 const size_t idx = package_ids_[package_id];
329 if (idx == 0xff) {
330 return nullptr;
331 }
332
333 const PackageGroup& package_group = package_groups_[idx];
Ryan Mitchell80094e32020-11-16 23:08:18 +0000334 if (package_group.packages_.empty()) {
MÃ¥rten Kongstadc92c4dd2019-02-05 01:29:59 +0100335 return nullptr;
336 }
337
338 const auto loaded_package = package_group.packages_[0].loaded_package_;
339 return &loaded_package->GetOverlayableMap();
340}
341
Yurii Zubrytskyia5775142022-11-02 17:49:49 -0700342bool AssetManager2::GetOverlayablesToString(android::StringPiece package_name,
Ryan Mitchell2e394222019-08-28 12:10:51 -0700343 std::string* out) const {
344 uint8_t package_id = 0U;
345 for (const auto& apk_assets : apk_assets_) {
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700346 auto assets = apk_assets.promote();
347 if (!assets) {
348 continue;
349 }
350 const LoadedArsc* loaded_arsc = assets->GetLoadedArsc();
Ryan Mitchell2e394222019-08-28 12:10:51 -0700351 if (loaded_arsc == nullptr) {
352 continue;
353 }
354
355 const auto& loaded_packages = loaded_arsc->GetPackages();
356 if (loaded_packages.empty()) {
357 continue;
358 }
359
360 const auto& loaded_package = loaded_packages[0];
361 if (loaded_package->GetPackageName() == package_name) {
362 package_id = GetAssignedPackageId(loaded_package.get());
363 break;
364 }
365 }
366
367 if (package_id == 0U) {
368 ANDROID_LOG(ERROR) << base::StringPrintf("No package with name '%s", package_name.data());
369 return false;
370 }
371
372 const size_t idx = package_ids_[package_id];
373 if (idx == 0xff) {
374 return false;
375 }
376
377 std::string output;
378 for (const ConfiguredPackage& package : package_groups_[idx].packages_) {
379 const LoadedPackage* loaded_package = package.loaded_package_;
380 for (auto it = loaded_package->begin(); it != loaded_package->end(); it++) {
381 const OverlayableInfo* info = loaded_package->GetOverlayableInfo(*it);
382 if (info != nullptr) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000383 auto res_name = GetResourceName(*it);
384 if (!res_name.has_value()) {
Ryan Mitchell2e394222019-08-28 12:10:51 -0700385 ANDROID_LOG(ERROR) << base::StringPrintf(
386 "Unable to retrieve name of overlayable resource 0x%08x", *it);
387 return false;
388 }
389
Ryan Mitchell80094e32020-11-16 23:08:18 +0000390 const std::string name = ToFormattedResourceString(*res_name);
Ryan Mitchell2e394222019-08-28 12:10:51 -0700391 output.append(base::StringPrintf(
392 "resource='%s' overlayable='%s' actor='%s' policy='0x%08x'\n",
Yurii Zubrytskyi9d225372022-11-29 11:12:18 -0800393 name.c_str(), info->name.data(), info->actor.data(), info->policy_flags));
Ryan Mitchell2e394222019-08-28 12:10:51 -0700394 }
395 }
396 }
397
398 *out = std::move(output);
399 return true;
400}
401
Ryan Mitchell192400c2020-04-02 09:54:23 -0700402bool AssetManager2::ContainsAllocatedTable() const {
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700403 return std::find_if(apk_assets_.begin(), apk_assets_.end(), [](auto&& assets_weak) {
404 auto assets = assets_weak.promote();
405 return assets && assets->IsTableAllocated();
406 }) != apk_assets_.end();
Ryan Mitchell192400c2020-04-02 09:54:23 -0700407}
408
Adam Lesinski7ad11102016-10-28 16:39:15 -0700409void AssetManager2::SetConfiguration(const ResTable_config& configuration) {
410 const int diff = configuration_.diff(configuration);
411 configuration_ = configuration;
412
413 if (diff) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800414 RebuildFilterList();
Adam Lesinski7ad11102016-10-28 16:39:15 -0700415 InvalidateCaches(static_cast<uint32_t>(diff));
416 }
417}
418
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700419std::set<AssetManager2::ApkAssetsPtr> AssetManager2::GetNonSystemOverlays() const {
420 std::set<ApkAssetsPtr> non_system_overlays;
Adam Lesinski0c405242017-01-13 20:47:26 -0800421 for (const PackageGroup& package_group : package_groups_) {
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800422 bool found_system_package = false;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800423 for (const ConfiguredPackage& package : package_group.packages_) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700424 if (package.loaded_package_->IsSystem()) {
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800425 found_system_package = true;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700426 break;
427 }
428 }
429
430 if (!found_system_package) {
431 for (const ConfiguredOverlay& overlay : package_group.overlays_) {
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700432 if (auto asset = apk_assets_[overlay.cookie].promote()) {
433 non_system_overlays.insert(std::move(asset));
434 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700435 }
436 }
437 }
438
439 return non_system_overlays;
440}
441
Ryan Mitchell80094e32020-11-16 23:08:18 +0000442base::expected<std::set<ResTable_config>, IOError> AssetManager2::GetResourceConfigurations(
443 bool exclude_system, bool exclude_mipmap) const {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700444 ATRACE_NAME("AssetManager::GetResourceConfigurations");
445 const auto non_system_overlays =
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700446 exclude_system ? GetNonSystemOverlays() : std::set<ApkAssetsPtr>();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700447
448 std::set<ResTable_config> configurations;
449 for (const PackageGroup& package_group : package_groups_) {
450 for (size_t i = 0; i < package_group.packages_.size(); i++) {
451 const ConfiguredPackage& package = package_group.packages_[i];
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700452 if (exclude_system) {
453 if (package.loaded_package_->IsSystem()) {
454 continue;
455 }
456 if (!non_system_overlays.empty()) {
457 // Exclude overlays that target only system resources.
458 auto apk_assets = apk_assets_[package_group.cookies_[i]].promote();
459 if (apk_assets && apk_assets->IsOverlay() &&
460 non_system_overlays.find(apk_assets) == non_system_overlays.end()) {
461 continue;
462 }
463 }
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800464 }
465
Ryan Mitchell80094e32020-11-16 23:08:18 +0000466 auto result = package.loaded_package_->CollectConfigurations(exclude_mipmap, &configurations);
467 if (UNLIKELY(!result.has_value())) {
468 return base::unexpected(result.error());
469 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800470 }
471 }
472 return configurations;
473}
474
475std::set<std::string> AssetManager2::GetResourceLocales(bool exclude_system,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800476 bool merge_equivalent_languages) const {
477 ATRACE_NAME("AssetManager::GetResourceLocales");
Adam Lesinski0c405242017-01-13 20:47:26 -0800478 std::set<std::string> locales;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700479 const auto non_system_overlays =
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700480 exclude_system ? GetNonSystemOverlays() : std::set<ApkAssetsPtr>();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700481
Adam Lesinski0c405242017-01-13 20:47:26 -0800482 for (const PackageGroup& package_group : package_groups_) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700483 for (size_t i = 0; i < package_group.packages_.size(); i++) {
484 const ConfiguredPackage& package = package_group.packages_[i];
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700485 if (exclude_system) {
486 if (package.loaded_package_->IsSystem()) {
487 continue;
488 }
489 if (!non_system_overlays.empty()) {
490 // Exclude overlays that target only system resources.
491 auto apk_assets = apk_assets_[package_group.cookies_[i]].promote();
492 if (apk_assets && apk_assets->IsOverlay() &&
493 non_system_overlays.find(apk_assets) == non_system_overlays.end()) {
494 continue;
495 }
496 }
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800497 }
498
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800499 package.loaded_package_->CollectLocales(merge_equivalent_languages, &locales);
Adam Lesinski0c405242017-01-13 20:47:26 -0800500 }
501 }
502 return locales;
503}
504
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800505std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename,
506 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700507 const std::string new_path = "assets/" + filename;
508 return OpenNonAsset(new_path, mode);
509}
510
511std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename, ApkAssetsCookie cookie,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800512 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700513 const std::string new_path = "assets/" + filename;
514 return OpenNonAsset(new_path, cookie, mode);
515}
516
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800517std::unique_ptr<AssetDir> AssetManager2::OpenDir(const std::string& dirname) const {
518 ATRACE_NAME("AssetManager::OpenDir");
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800519
520 std::string full_path = "assets/" + dirname;
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700521 auto files = util::make_unique<SortedVector<AssetDir::FileInfo>>();
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800522
523 // Start from the back.
524 for (auto iter = apk_assets_.rbegin(); iter != apk_assets_.rend(); ++iter) {
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700525 auto apk_assets = iter->promote();
526 if (!apk_assets || apk_assets->IsOverlay()) {
MÃ¥rten Kongstaddbf343b2019-02-21 07:54:18 +0100527 continue;
528 }
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800529
Yurii Zubrytskyia5775142022-11-02 17:49:49 -0700530 auto func = [&](StringPiece name, FileType type) {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800531 AssetDir::FileInfo info;
532 info.setFileName(String8(name.data(), name.size()));
533 info.setFileType(type);
Ryan Mitchellef538432021-03-01 14:52:14 -0800534 info.setSourceName(String8(apk_assets->GetDebugName().c_str()));
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800535 files->add(info);
536 };
537
Ryan Mitchellc07aa702020-03-10 13:49:12 -0700538 if (!apk_assets->GetAssetsProvider()->ForEachFile(full_path, func)) {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800539 return {};
540 }
541 }
542
543 std::unique_ptr<AssetDir> asset_dir = util::make_unique<AssetDir>();
544 asset_dir->setFileList(files.release());
545 return asset_dir;
546}
547
Adam Lesinski7ad11102016-10-28 16:39:15 -0700548// Search in reverse because that's how we used to do it and we need to preserve behaviour.
549// This is unfortunate, because ClassLoaders delegate to the parent first, so the order
550// is inconsistent for split APKs.
551std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
552 Asset::AccessMode mode,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800553 ApkAssetsCookie* out_cookie) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700554 for (int32_t i = apk_assets_.size() - 1; i >= 0; i--) {
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700555 const auto assets = apk_assets_[i].promote();
MÃ¥rten Kongstaddbf343b2019-02-21 07:54:18 +0100556 // Prevent RRO from modifying assets and other entries accessed by file
557 // path. Explicitly asking for a path in a given package (denoted by a
558 // cookie) is still OK.
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700559 if (!assets || assets->IsOverlay()) {
MÃ¥rten Kongstaddbf343b2019-02-21 07:54:18 +0100560 continue;
561 }
562
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700563 std::unique_ptr<Asset> asset = assets->GetAssetsProvider()->Open(filename, mode);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700564 if (asset) {
565 if (out_cookie != nullptr) {
566 *out_cookie = i;
567 }
568 return asset;
569 }
570 }
571
572 if (out_cookie != nullptr) {
573 *out_cookie = kInvalidCookie;
574 }
575 return {};
576}
577
578std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800579 ApkAssetsCookie cookie,
580 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700581 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
582 return {};
583 }
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700584 auto assets = apk_assets_[cookie].promote();
585 return assets ? assets->GetAssetsProvider()->Open(filename, mode) : nullptr;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700586}
587
Ryan Mitchell80094e32020-11-16 23:08:18 +0000588base::expected<FindEntryResult, NullOrIOError> AssetManager2::FindEntry(
589 uint32_t resid, uint16_t density_override, bool stop_at_first_match,
590 bool ignore_configuration) const {
591 const bool logging_enabled = resource_resolution_logging_enabled_;
592 if (UNLIKELY(logging_enabled)) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700593 // Clear the last logged resource resolution.
594 ResetResourceResolution();
595 last_resolution_.resid = resid;
596 }
597
Adam Lesinski7ad11102016-10-28 16:39:15 -0700598 // Might use this if density_override != 0.
599 ResTable_config density_override_config;
600
601 // Select our configuration or generate a density override configuration.
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800602 const ResTable_config* desired_config = &configuration_;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700603 if (density_override != 0 && density_override != configuration_.density) {
604 density_override_config = configuration_;
605 density_override_config.density = density_override;
606 desired_config = &density_override_config;
607 }
608
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700609 // Retrieve the package group from the package id of the resource id.
Ryan Mitchell80094e32020-11-16 23:08:18 +0000610 if (UNLIKELY(!is_valid_resid(resid))) {
Mark Hansenb406b0e2022-10-14 02:18:37 +0000611 LOG(ERROR) << base::StringPrintf("Invalid resource ID 0x%08x.", resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000612 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -0500613 }
614
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800615 const uint32_t package_id = get_package_id(resid);
616 const uint8_t type_idx = get_type_id(resid) - 1;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800617 const uint16_t entry_idx = get_entry_id(resid);
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700618 uint8_t package_idx = package_ids_[package_id];
Ryan Mitchell80094e32020-11-16 23:08:18 +0000619 if (UNLIKELY(package_idx == 0xff)) {
Mark Hansenb406b0e2022-10-14 02:18:37 +0000620 ANDROID_LOG(ERROR) << base::StringPrintf("No package ID %02x found for resource ID 0x%08x.",
Ryan Mitchell2fe23472019-02-27 09:43:01 -0800621 package_id, resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000622 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -0500623 }
624
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800625 const PackageGroup& package_group = package_groups_[package_idx];
Ryan Mitchell80094e32020-11-16 23:08:18 +0000626 auto result = FindEntryInternal(package_group, type_idx, entry_idx, *desired_config,
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800627 stop_at_first_match, ignore_configuration);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000628 if (UNLIKELY(!result.has_value())) {
629 return base::unexpected(result.error());
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700630 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800631
Jackal Guo552b45d2021-09-29 10:52:19 +0800632 bool overlaid = false;
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700633 if (!stop_at_first_match && !ignore_configuration) {
634 auto assets = apk_assets_[result->cookie].promote();
635 if (!assets) {
636 ALOGE("Found expired ApkAssets #%d for resource ID 0x%08x.", result->cookie, resid);
637 return base::unexpected(std::nullopt);
638 }
639 if (!assets->IsLoader()) {
640 for (const auto& id_map : package_group.overlays_) {
641 auto overlay_entry = id_map.overlay_res_maps_.Lookup(resid);
642 if (!overlay_entry) {
643 // No id map entry exists for this target resource.
Jeremy Meyerbe2b7792022-08-23 17:42:50 +0000644 continue;
645 }
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700646 if (overlay_entry.IsInlineValue()) {
647 // The target resource is overlaid by an inline value not represented by a resource.
648 ConfigDescription best_frro_config;
649 Res_value best_frro_value;
650 bool frro_found = false;
651 for( const auto& [config, value] : overlay_entry.GetInlineValue()) {
652 if ((!frro_found || config.isBetterThan(best_frro_config, desired_config))
653 && config.match(*desired_config)) {
654 frro_found = true;
655 best_frro_config = config;
656 best_frro_value = value;
657 }
658 }
659 if (!frro_found) {
660 continue;
661 }
662 result->entry = best_frro_value;
663 result->dynamic_ref_table = id_map.overlay_res_maps_.GetOverlayDynamicRefTable();
664 result->cookie = id_map.cookie;
665
666 if (UNLIKELY(logging_enabled)) {
667 last_resolution_.steps.push_back(
668 Resolution::Step{Resolution::Step::Type::OVERLAID_INLINE, result->cookie, String8()});
669 if (auto path = assets->GetPath()) {
670 const std::string overlay_path = path->data();
671 if (IsFabricatedOverlay(overlay_path)) {
672 // FRRO don't have package name so we use the creating package here.
673 String8 frro_name = String8("FRRO");
674 // Get the first part of it since the expected one should be like
675 // {overlayPackageName}-{overlayName}-{4 alphanumeric chars}.frro
676 // under /data/resource-cache/.
677 const std::string name = overlay_path.substr(overlay_path.rfind('/') + 1);
678 const size_t end = name.find('-');
679 if (frro_name.size() != overlay_path.size() && end != std::string::npos) {
680 frro_name.append(base::StringPrintf(" created by %s",
681 name.substr(0 /* pos */,
682 end).c_str()).c_str());
683 }
684 last_resolution_.best_package_name = frro_name;
685 } else {
686 last_resolution_.best_package_name = result->package_name->c_str();
687 }
688 }
689 overlaid = true;
690 }
691 continue;
692 }
693
694 auto overlay_result = FindEntry(overlay_entry.GetResourceId(), density_override,
695 false /* stop_at_first_match */,
696 false /* ignore_configuration */);
697 if (UNLIKELY(IsIOError(overlay_result))) {
698 return base::unexpected(overlay_result.error());
699 }
700 if (!overlay_result.has_value()) {
701 continue;
702 }
703
704 if (!overlay_result->config.isBetterThan(result->config, desired_config)
705 && overlay_result->config.compare(result->config) != 0) {
706 // The configuration of the entry for the overlay must be equal to or better than the target
707 // configuration to be chosen as the better value.
708 continue;
709 }
710
711 result->cookie = overlay_result->cookie;
712 result->entry = overlay_result->entry;
713 result->config = overlay_result->config;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000714 result->dynamic_ref_table = id_map.overlay_res_maps_.GetOverlayDynamicRefTable();
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800715
716 if (UNLIKELY(logging_enabled)) {
717 last_resolution_.steps.push_back(
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700718 Resolution::Step{Resolution::Step::Type::OVERLAID, overlay_result->cookie,
719 overlay_result->config.toString()});
720 last_resolution_.best_package_name =
721 overlay_result->package_name->c_str();
Jackal Guo552b45d2021-09-29 10:52:19 +0800722 overlaid = true;
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800723 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700724 }
725 }
726 }
727
Ryan Mitchell80094e32020-11-16 23:08:18 +0000728 if (UNLIKELY(logging_enabled)) {
729 last_resolution_.cookie = result->cookie;
730 last_resolution_.type_string_ref = result->type_string_ref;
731 last_resolution_.entry_string_ref = result->entry_string_ref;
Jackal Guo552b45d2021-09-29 10:52:19 +0800732 last_resolution_.best_config_name = result->config.toString();
733 if (!overlaid) {
734 last_resolution_.best_package_name = result->package_name->c_str();
735 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700736 }
737
Ryan Mitchell80094e32020-11-16 23:08:18 +0000738 return result;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700739}
740
Ryan Mitchell80094e32020-11-16 23:08:18 +0000741base::expected<FindEntryResult, NullOrIOError> AssetManager2::FindEntryInternal(
742 const PackageGroup& package_group, uint8_t type_idx, uint16_t entry_idx,
743 const ResTable_config& desired_config, bool stop_at_first_match,
744 bool ignore_configuration) const {
745 const bool logging_enabled = resource_resolution_logging_enabled_;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800746 ApkAssetsCookie best_cookie = kInvalidCookie;
747 const LoadedPackage* best_package = nullptr;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000748 incfs::verified_map_ptr<ResTable_type> best_type;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800749 const ResTable_config* best_config = nullptr;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000750 uint32_t best_offset = 0U;
751 uint32_t type_flags = 0U;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800752
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800753 // If `desired_config` is not the same as the set configuration or the caller will accept a value
754 // from any configuration, then we cannot use our filtered list of types since it only it contains
755 // types matched to the set configuration.
756 const bool use_filtered = !ignore_configuration && &desired_config == &configuration_;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800757
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700758 const size_t package_count = package_group.packages_.size();
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800759 for (size_t pi = 0; pi < package_count; pi++) {
760 const ConfiguredPackage& loaded_package_impl = package_group.packages_[pi];
761 const LoadedPackage* loaded_package = loaded_package_impl.loaded_package_;
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800762 const ApkAssetsCookie cookie = package_group.cookies_[pi];
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800763
764 // If the type IDs are offset in this package, we need to take that into account when searching
765 // for a type.
766 const TypeSpec* type_spec = loaded_package->GetTypeSpecByTypeIndex(type_idx);
767 if (UNLIKELY(type_spec == nullptr)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700768 continue;
769 }
770
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800771 // Allow custom loader packages to overlay resource values with configurations equivalent to the
772 // current best configuration.
773 const bool package_is_loader = loaded_package->IsCustomLoader();
774
Ryan Mitchell80094e32020-11-16 23:08:18 +0000775 auto entry_flags = type_spec->GetFlagsForEntryIndex(entry_idx);
Bernie Innocenti58cf8e32020-12-19 15:31:52 +0900776 if (UNLIKELY(!entry_flags.has_value())) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000777 return base::unexpected(entry_flags.error());
778 }
779 type_flags |= entry_flags.value();
780
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800781 const FilteredConfigGroup& filtered_group = loaded_package_impl.filtered_configs_[type_idx];
782 const size_t type_entry_count = (use_filtered) ? filtered_group.type_entries.size()
783 : type_spec->type_entries.size();
784 for (size_t i = 0; i < type_entry_count; i++) {
785 const TypeSpec::TypeEntry* type_entry = (use_filtered) ? filtered_group.type_entries[i]
786 : &type_spec->type_entries[i];
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800787
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800788 // We can skip calling ResTable_config::match() if the caller does not care for the
789 // configuration to match or if we're using the list of types that have already had their
790 // configuration matched.
791 const ResTable_config& this_config = type_entry->config;
792 if (!(use_filtered || ignore_configuration || this_config.match(desired_config))) {
793 continue;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800794 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800795
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800796 Resolution::Step::Type resolution_type;
797 if (best_config == nullptr) {
798 resolution_type = Resolution::Step::Type::INITIAL;
799 } else if (this_config.isBetterThan(*best_config, &desired_config)) {
800 resolution_type = Resolution::Step::Type::BETTER_MATCH;
801 } else if (package_is_loader && this_config.compare(*best_config) == 0) {
802 resolution_type = Resolution::Step::Type::OVERLAID;
803 } else {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000804 if (UNLIKELY(logging_enabled)) {
Jackal Guo552b45d2021-09-29 10:52:19 +0800805 last_resolution_.steps.push_back(Resolution::Step{Resolution::Step::Type::SKIPPED,
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -0700806 cookie, this_config.toString()});
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800807 }
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800808 continue;
809 }
810
811 // The configuration matches and is better than the previous selection.
812 // Find the entry value if it exists for this configuration.
813 const auto& type = type_entry->type;
814 const auto offset = LoadedPackage::GetEntryOffset(type, entry_idx);
815 if (UNLIKELY(IsIOError(offset))) {
816 return base::unexpected(offset.error());
817 }
818
819 if (!offset.has_value()) {
820 if (UNLIKELY(logging_enabled)) {
Jackal Guo552b45d2021-09-29 10:52:19 +0800821 last_resolution_.steps.push_back(Resolution::Step{Resolution::Step::Type::NO_ENTRY,
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -0700822 cookie, this_config.toString()});
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800823 }
824 continue;
825 }
826
827 best_cookie = cookie;
828 best_package = loaded_package;
829 best_type = type;
830 best_config = &this_config;
831 best_offset = offset.value();
832
833 if (UNLIKELY(logging_enabled)) {
834 last_resolution_.steps.push_back(Resolution::Step{resolution_type,
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -0700835 cookie, this_config.toString()});
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800836 }
837
838 // Any configuration will suffice, so break.
839 if (stop_at_first_match) {
840 break;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700841 }
842 }
843 }
844
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800845 if (UNLIKELY(best_cookie == kInvalidCookie)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000846 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700847 }
848
Eric Miao368cd192022-09-09 15:46:14 -0700849 auto best_entry_verified = LoadedPackage::GetEntryFromOffset(best_type, best_offset);
850 if (!best_entry_verified.has_value()) {
851 return base::unexpected(best_entry_verified.error());
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800852 }
853
Eric Miao368cd192022-09-09 15:46:14 -0700854 const auto entry = GetEntryValue(*best_entry_verified);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000855 if (!entry.has_value()) {
856 return base::unexpected(entry.error());
857 }
Winson2f3669b2019-01-11 11:28:34 -0800858
Ryan Mitchell80094e32020-11-16 23:08:18 +0000859 return FindEntryResult{
860 .cookie = best_cookie,
861 .entry = *entry,
862 .config = *best_config,
863 .type_flags = type_flags,
864 .package_name = &best_package->GetPackageName(),
865 .type_string_ref = StringPoolRef(best_package->GetTypeStringPool(), best_type->id - 1),
866 .entry_string_ref = StringPoolRef(best_package->GetKeyStringPool(),
Eric Miao368cd192022-09-09 15:46:14 -0700867 (*best_entry_verified)->key()),
Ryan Mitchell80094e32020-11-16 23:08:18 +0000868 .dynamic_ref_table = package_group.dynamic_ref_table.get(),
869 };
Adam Lesinski7ad11102016-10-28 16:39:15 -0700870}
871
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700872void AssetManager2::ResetResourceResolution() const {
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -0700873 last_resolution_ = Resolution{};
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700874}
875
Winson2f3669b2019-01-11 11:28:34 -0800876void AssetManager2::SetResourceResolutionLoggingEnabled(bool enabled) {
877 resource_resolution_logging_enabled_ = enabled;
Winson2f3669b2019-01-11 11:28:34 -0800878 if (!enabled) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700879 ResetResourceResolution();
Winson2f3669b2019-01-11 11:28:34 -0800880 }
881}
882
883std::string AssetManager2::GetLastResourceResolution() const {
884 if (!resource_resolution_logging_enabled_) {
885 LOG(ERROR) << "Must enable resource resolution logging before getting path.";
Ryan Mitchell80094e32020-11-16 23:08:18 +0000886 return {};
Winson2f3669b2019-01-11 11:28:34 -0800887 }
888
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800889 const ApkAssetsCookie cookie = last_resolution_.cookie;
Winson2f3669b2019-01-11 11:28:34 -0800890 if (cookie == kInvalidCookie) {
891 LOG(ERROR) << "AssetManager hasn't resolved a resource to read resolution path.";
Ryan Mitchell80094e32020-11-16 23:08:18 +0000892 return {};
Winson2f3669b2019-01-11 11:28:34 -0800893 }
894
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800895 const uint32_t resid = last_resolution_.resid;
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700896 auto assets = apk_assets_[cookie].promote();
897 const auto package =
898 assets ? assets->GetLoadedArsc()->GetPackageById(get_package_id(resid)) : nullptr;
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800899
Winson2f3669b2019-01-11 11:28:34 -0800900 std::string resource_name_string;
Winson2f3669b2019-01-11 11:28:34 -0800901 if (package != nullptr) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000902 auto resource_name = ToResourceName(last_resolution_.type_string_ref,
903 last_resolution_.entry_string_ref,
904 package->GetPackageName());
905 resource_name_string = resource_name.has_value() ?
906 ToFormattedResourceString(resource_name.value()) : "<unknown>";
Winson2f3669b2019-01-11 11:28:34 -0800907 }
908
909 std::stringstream log_stream;
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800910 log_stream << base::StringPrintf("Resolution for 0x%08x %s\n"
911 "\tFor config - %s", resid, resource_name_string.c_str(),
912 configuration_.toString().c_str());
Winson2f3669b2019-01-11 11:28:34 -0800913
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800914 for (const Resolution::Step& step : last_resolution_.steps) {
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -0700915 constexpr static std::array kStepStrings = {
916 "Found initial",
917 "Found better",
918 "Overlaid",
919 "Overlaid inline",
920 "Skipped",
921 "No entry"
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800922 };
923
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -0700924 if (step.type < Resolution::Step::Type::INITIAL
925 || step.type > Resolution::Step::Type::NO_ENTRY) {
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800926 continue;
Winson2f3669b2019-01-11 11:28:34 -0800927 }
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -0700928 const auto prefix = kStepStrings[int(step.type) - int(Resolution::Step::Type::INITIAL)];
Yurii Zubrytskyib3455192023-05-01 14:35:48 -0700929 auto assets = apk_assets_[step.cookie].promote();
930 log_stream << "\n\t" << prefix << ": " << (assets ? assets->GetDebugName() : "<null>")
931 << " #" << step.cookie;
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800932 if (!step.config_name.isEmpty()) {
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800933 log_stream << " - " << step.config_name;
Winson2f3669b2019-01-11 11:28:34 -0800934 }
935 }
936
Jackal Guo552b45d2021-09-29 10:52:19 +0800937 log_stream << "\nBest matching is from "
938 << (last_resolution_.best_config_name.isEmpty() ? "default"
939 : last_resolution_.best_config_name)
940 << " configuration of " << last_resolution_.best_package_name;
Winson2f3669b2019-01-11 11:28:34 -0800941 return log_stream.str();
942}
943
Felka Chang00964e92021-12-10 01:19:08 +0800944base::expected<uint32_t, NullOrIOError> AssetManager2::GetParentThemeResourceId(uint32_t resid)
945const {
946 auto entry = FindEntry(resid, 0u /* density_override */,
947 false /* stop_at_first_match */,
948 false /* ignore_configuration */);
949 if (!entry.has_value()) {
950 return base::unexpected(entry.error());
951 }
952
953 auto entry_map = std::get_if<incfs::verified_map_ptr<ResTable_map_entry>>(&entry->entry);
954 if (entry_map == nullptr) {
955 // Not a bag, nothing to do.
956 return base::unexpected(std::nullopt);
957 }
958
959 auto map = *entry_map;
960 const uint32_t parent_resid = dtohl(map->parent.ident);
961
962 return parent_resid;
963}
964
Ryan Mitchell80094e32020-11-16 23:08:18 +0000965base::expected<AssetManager2::ResourceName, NullOrIOError> AssetManager2::GetResourceName(
966 uint32_t resid) const {
967 auto result = FindEntry(resid, 0u /* density_override */, true /* stop_at_first_match */,
968 true /* ignore_configuration */);
969 if (!result.has_value()) {
970 return base::unexpected(result.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -0700971 }
972
Ryan Mitchell80094e32020-11-16 23:08:18 +0000973 return ToResourceName(result->type_string_ref,
974 result->entry_string_ref,
975 *result->package_name);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700976}
977
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800978base::expected<uint32_t, NullOrIOError> AssetManager2::GetResourceTypeSpecFlags(
979 uint32_t resid) const {
980 auto result = FindEntry(resid, 0u /* density_override */, false /* stop_at_first_match */,
981 true /* ignore_configuration */);
982 if (!result.has_value()) {
983 return base::unexpected(result.error());
984 }
985 return result->type_flags;
986}
987
Ryan Mitchell80094e32020-11-16 23:08:18 +0000988base::expected<AssetManager2::SelectedValue, NullOrIOError> AssetManager2::GetResource(
989 uint32_t resid, bool may_be_bag, uint16_t density_override) const {
990 auto result = FindEntry(resid, density_override, false /* stop_at_first_match */,
991 false /* ignore_configuration */);
992 if (!result.has_value()) {
993 return base::unexpected(result.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -0700994 }
995
Ryan Mitchell80094e32020-11-16 23:08:18 +0000996 auto result_map_entry = std::get_if<incfs::verified_map_ptr<ResTable_map_entry>>(&result->entry);
Ryan Mitchellbf1f45b2020-09-29 17:22:52 -0700997 if (result_map_entry != nullptr) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700998 if (!may_be_bag) {
999 LOG(ERROR) << base::StringPrintf("Resource %08x is a complex map type.", resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001000 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001001 }
Adam Lesinski0c405242017-01-13 20:47:26 -08001002
1003 // Create a reference since we can't represent this complex type as a Res_value.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001004 return SelectedValue(Res_value::TYPE_REFERENCE, resid, result->cookie, result->type_flags,
1005 resid, result->config);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001006 }
1007
Adam Lesinskida431a22016-12-29 16:08:16 -05001008 // Convert the package ID to the runtime assigned package ID.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001009 Res_value value = std::get<Res_value>(result->entry);
1010 result->dynamic_ref_table->lookupResourceValue(&value);
Adam Lesinskida431a22016-12-29 16:08:16 -05001011
Ryan Mitchell80094e32020-11-16 23:08:18 +00001012 return SelectedValue(value.dataType, value.data, result->cookie, result->type_flags,
1013 resid, result->config);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001014}
1015
Ryan Mitchell80094e32020-11-16 23:08:18 +00001016base::expected<std::monostate, NullOrIOError> AssetManager2::ResolveReference(
Ryan Mitchella45506e2020-11-16 23:08:18 +00001017 AssetManager2::SelectedValue& value, bool cache_value) const {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001018 if (value.type != Res_value::TYPE_REFERENCE || value.data == 0U) {
1019 // Not a reference. Nothing to do.
1020 return {};
Adam Lesinski0c405242017-01-13 20:47:26 -08001021 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001022
Ryan Mitchella45506e2020-11-16 23:08:18 +00001023 const uint32_t original_flags = value.flags;
1024 const uint32_t original_resid = value.data;
1025 if (cache_value) {
1026 auto cached_value = cached_resolved_values_.find(value.data);
1027 if (cached_value != cached_resolved_values_.end()) {
1028 value = cached_value->second;
1029 value.flags |= original_flags;
1030 return {};
1031 }
1032 }
1033
1034 uint32_t combined_flags = 0U;
1035 uint32_t resolve_resid = original_resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001036 constexpr const uint32_t kMaxIterations = 20;
1037 for (uint32_t i = 0U;; i++) {
1038 auto result = GetResource(resolve_resid, true /*may_be_bag*/);
1039 if (!result.has_value()) {
Ryan Mitchelle7ab6272020-11-13 18:06:15 -08001040 value.resid = resolve_resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001041 return base::unexpected(result.error());
1042 }
1043
Ryan Mitchelle7ab6272020-11-13 18:06:15 -08001044 // If resource resolution fails, the value should be set to the last reference that was able to
1045 // be resolved successfully.
1046 value = *result;
1047 value.flags |= combined_flags;
1048
Ryan Mitchell80094e32020-11-16 23:08:18 +00001049 if (result->type != Res_value::TYPE_REFERENCE ||
1050 result->data == Res_value::DATA_NULL_UNDEFINED ||
1051 result->data == resolve_resid || i == kMaxIterations) {
1052 // This reference can't be resolved, so exit now and let the caller deal with it.
Ryan Mitchella45506e2020-11-16 23:08:18 +00001053 if (cache_value) {
1054 cached_resolved_values_[original_resid] = value;
1055 }
1056
1057 // Above value is cached without original_flags to ensure they don't get included in future
1058 // queries that hit the cache
1059 value.flags |= original_flags;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001060 return {};
1061 }
1062
Ryan Mitchelle7ab6272020-11-13 18:06:15 -08001063 combined_flags = result->flags;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001064 resolve_resid = result->data;
1065 }
Adam Lesinski0c405242017-01-13 20:47:26 -08001066}
1067
Ryan Mitchell80094e32020-11-16 23:08:18 +00001068const std::vector<uint32_t> AssetManager2::GetBagResIdStack(uint32_t resid) const {
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001069 auto cached_iter = cached_bag_resid_stacks_.find(resid);
1070 if (cached_iter != cached_bag_resid_stacks_.end()) {
1071 return cached_iter->second;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001072 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001073
1074 std::vector<uint32_t> found_resids;
1075 GetBag(resid, found_resids);
1076 cached_bag_resid_stacks_.emplace(resid, found_resids);
1077 return found_resids;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001078}
1079
Ryan Mitchell80094e32020-11-16 23:08:18 +00001080base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::ResolveBag(
1081 AssetManager2::SelectedValue& value) const {
1082 if (UNLIKELY(value.type != Res_value::TYPE_REFERENCE)) {
1083 return base::unexpected(std::nullopt);
1084 }
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001085
Ryan Mitchell80094e32020-11-16 23:08:18 +00001086 auto bag = GetBag(value.data);
1087 if (bag.has_value()) {
1088 value.flags |= (*bag)->type_spec_flags;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001089 }
1090 return bag;
y57cd1952018-04-12 14:26:23 -07001091}
1092
Ryan Mitchell80094e32020-11-16 23:08:18 +00001093base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::GetBag(uint32_t resid) const {
1094 std::vector<uint32_t> found_resids;
1095 const auto bag = GetBag(resid, found_resids);
Yurii Zubrytskyiab3cb302022-10-11 12:15:52 -07001096 cached_bag_resid_stacks_.emplace(resid, std::move(found_resids));
Ryan Mitchell80094e32020-11-16 23:08:18 +00001097 return bag;
Ryan Mitchell155d5392020-02-10 13:35:24 -08001098}
1099
Ryan Mitchell80094e32020-11-16 23:08:18 +00001100base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::GetBag(
1101 uint32_t resid, std::vector<uint32_t>& child_resids) const {
1102 if (auto cached_iter = cached_bags_.find(resid); cached_iter != cached_bags_.end()) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001103 return cached_iter->second.get();
1104 }
1105
Ryan Mitchell80094e32020-11-16 23:08:18 +00001106 auto entry = FindEntry(resid, 0u /* density_override */, false /* stop_at_first_match */,
1107 false /* ignore_configuration */);
1108 if (!entry.has_value()) {
1109 return base::unexpected(entry.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001110 }
1111
Ryan Mitchell80094e32020-11-16 23:08:18 +00001112 auto entry_map = std::get_if<incfs::verified_map_ptr<ResTable_map_entry>>(&entry->entry);
1113 if (entry_map == nullptr) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001114 // Not a bag, nothing to do.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001115 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001116 }
1117
Ryan Mitchell80094e32020-11-16 23:08:18 +00001118 auto map = *entry_map;
1119 auto map_entry = map.offset(dtohs(map->size)).convert<ResTable_map>();
1120 const auto map_entry_end = map_entry + dtohl(map->count);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001121
y57cd1952018-04-12 14:26:23 -07001122 // Keep track of ids that have already been seen to prevent infinite loops caused by circular
Ryan Mitchell80094e32020-11-16 23:08:18 +00001123 // dependencies between bags.
y57cd1952018-04-12 14:26:23 -07001124 child_resids.push_back(resid);
1125
Adam Lesinskida431a22016-12-29 16:08:16 -05001126 uint32_t parent_resid = dtohl(map->parent.ident);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001127 if (parent_resid == 0U ||
1128 std::find(child_resids.begin(), child_resids.end(), parent_resid) != child_resids.end()) {
1129 // There is no parent or a circular parental dependency exist, meaning there is nothing to
1130 // inherit and we can do a simple copy of the entries in the map.
Adam Lesinski7ad11102016-10-28 16:39:15 -07001131 const size_t entry_count = map_entry_end - map_entry;
1132 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
1133 malloc(sizeof(ResolvedBag) + (entry_count * sizeof(ResolvedBag::Entry))))};
Ryan Mitchell155d5392020-02-10 13:35:24 -08001134
1135 bool sort_entries = false;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001136 for (auto new_entry = new_bag->entries; map_entry != map_entry_end; ++map_entry) {
1137 if (UNLIKELY(!map_entry)) {
1138 return base::unexpected(IOError::PAGES_MISSING);
1139 }
1140
Adam Lesinskida431a22016-12-29 16:08:16 -05001141 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001142 if (!is_internal_resid(new_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -05001143 // Attributes, arrays, etc don't have a resource id as the name. They specify
1144 // other data, which would be wrong to change via a lookup.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001145 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001146 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
1147 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001148 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001149 }
1150 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001151
1152 new_entry->cookie = entry->cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -05001153 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001154 new_entry->key_pool = nullptr;
1155 new_entry->type_pool = nullptr;
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001156 new_entry->style = resid;
Adam Lesinski30080e22017-10-16 16:18:09 -07001157 new_entry->value.copyFrom_dtoh(map_entry->value);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001158 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1159 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001160 LOG(ERROR) << base::StringPrintf(
1161 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
1162 new_entry->value.data, new_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001163 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001164 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001165
Ryan Mitchell155d5392020-02-10 13:35:24 -08001166 sort_entries = sort_entries ||
1167 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001168 ++new_entry;
1169 }
Ryan Mitchell155d5392020-02-10 13:35:24 -08001170
1171 if (sort_entries) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001172 std::sort(new_bag->entries, new_bag->entries + entry_count,
1173 [](auto&& lhs, auto&& rhs) { return lhs.key < rhs.key; });
Ryan Mitchell155d5392020-02-10 13:35:24 -08001174 }
1175
Ryan Mitchell80094e32020-11-16 23:08:18 +00001176 new_bag->type_spec_flags = entry->type_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001177 new_bag->entry_count = static_cast<uint32_t>(entry_count);
1178 ResolvedBag* result = new_bag.get();
1179 cached_bags_[resid] = std::move(new_bag);
1180 return result;
1181 }
1182
Adam Lesinskida431a22016-12-29 16:08:16 -05001183 // In case the parent is a dynamic reference, resolve it.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001184 entry->dynamic_ref_table->lookupResourceId(&parent_resid);
Adam Lesinskida431a22016-12-29 16:08:16 -05001185
Adam Lesinski7ad11102016-10-28 16:39:15 -07001186 // Get the parent and do a merge of the keys.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001187 const auto parent_bag = GetBag(parent_resid, child_resids);
1188 if (UNLIKELY(!parent_bag.has_value())) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001189 // Failed to get the parent that should exist.
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001190 LOG(ERROR) << base::StringPrintf("Failed to find parent 0x%08x of bag 0x%08x.", parent_resid,
1191 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001192 return base::unexpected(parent_bag.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001193 }
1194
Adam Lesinski7ad11102016-10-28 16:39:15 -07001195 // Create the max possible entries we can make. Once we construct the bag,
1196 // we will realloc to fit to size.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001197 const size_t max_count = (*parent_bag)->entry_count + dtohl(map->count);
George Burgess IV09b119f2017-07-25 15:00:04 -07001198 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
1199 malloc(sizeof(ResolvedBag) + (max_count * sizeof(ResolvedBag::Entry))))};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001200 ResolvedBag::Entry* new_entry = new_bag->entries;
1201
Ryan Mitchell80094e32020-11-16 23:08:18 +00001202 const ResolvedBag::Entry* parent_entry = (*parent_bag)->entries;
1203 const ResolvedBag::Entry* const parent_entry_end = parent_entry + (*parent_bag)->entry_count;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001204
1205 // The keys are expected to be in sorted order. Merge the two bags.
Ryan Mitchell155d5392020-02-10 13:35:24 -08001206 bool sort_entries = false;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001207 while (map_entry != map_entry_end && parent_entry != parent_entry_end) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001208 if (UNLIKELY(!map_entry)) {
1209 return base::unexpected(IOError::PAGES_MISSING);
1210 }
1211
Adam Lesinskida431a22016-12-29 16:08:16 -05001212 uint32_t child_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001213 if (!is_internal_resid(child_key)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001214 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&child_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001215 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", child_key,
1216 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001217 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001218 }
1219 }
1220
Adam Lesinski7ad11102016-10-28 16:39:15 -07001221 if (child_key <= parent_entry->key) {
1222 // Use the child key if it comes before the parent
1223 // or is equal to the parent (overrides).
Ryan Mitchell80094e32020-11-16 23:08:18 +00001224 new_entry->cookie = entry->cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001225 new_entry->key = child_key;
1226 new_entry->key_pool = nullptr;
1227 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -07001228 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001229 new_entry->style = resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001230 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1231 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001232 LOG(ERROR) << base::StringPrintf(
1233 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
1234 new_entry->value.data, child_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001235 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001236 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001237 ++map_entry;
1238 } else {
1239 // Take the parent entry as-is.
1240 memcpy(new_entry, parent_entry, sizeof(*new_entry));
1241 }
1242
Ryan Mitchell155d5392020-02-10 13:35:24 -08001243 sort_entries = sort_entries ||
1244 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001245 if (child_key >= parent_entry->key) {
1246 // Move to the next parent entry if we used it or it was overridden.
1247 ++parent_entry;
1248 }
1249 // Increment to the next entry to fill.
1250 ++new_entry;
1251 }
1252
1253 // Finish the child entries if they exist.
1254 while (map_entry != map_entry_end) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001255 if (UNLIKELY(!map_entry)) {
1256 return base::unexpected(IOError::PAGES_MISSING);
1257 }
1258
Adam Lesinskida431a22016-12-29 16:08:16 -05001259 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001260 if (!is_internal_resid(new_key)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001261 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001262 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
1263 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001264 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001265 }
1266 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001267 new_entry->cookie = entry->cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -05001268 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001269 new_entry->key_pool = nullptr;
1270 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -07001271 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001272 new_entry->style = resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001273 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1274 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001275 LOG(ERROR) << base::StringPrintf("Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.",
1276 new_entry->value.dataType, new_entry->value.data, new_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001277 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001278 }
Ryan Mitchell155d5392020-02-10 13:35:24 -08001279 sort_entries = sort_entries ||
1280 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001281 ++map_entry;
1282 ++new_entry;
1283 }
1284
1285 // Finish the parent entries if they exist.
1286 if (parent_entry != parent_entry_end) {
1287 // Take the rest of the parent entries as-is.
1288 const size_t num_entries_to_copy = parent_entry_end - parent_entry;
1289 memcpy(new_entry, parent_entry, num_entries_to_copy * sizeof(*new_entry));
1290 new_entry += num_entries_to_copy;
1291 }
1292
1293 // Resize the resulting array to fit.
1294 const size_t actual_count = new_entry - new_bag->entries;
1295 if (actual_count != max_count) {
George Burgess IV09b119f2017-07-25 15:00:04 -07001296 new_bag.reset(reinterpret_cast<ResolvedBag*>(realloc(
1297 new_bag.release(), sizeof(ResolvedBag) + (actual_count * sizeof(ResolvedBag::Entry)))));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001298 }
1299
Ryan Mitchell155d5392020-02-10 13:35:24 -08001300 if (sort_entries) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001301 std::sort(new_bag->entries, new_bag->entries + actual_count,
1302 [](auto&& lhs, auto&& rhs) { return lhs.key < rhs.key; });
Ryan Mitchell155d5392020-02-10 13:35:24 -08001303 }
1304
Adam Lesinski1a1e9c22017-10-13 15:45:34 -07001305 // Combine flags from the parent and our own bag.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001306 new_bag->type_spec_flags = entry->type_flags | (*parent_bag)->type_spec_flags;
George Burgess IV09b119f2017-07-25 15:00:04 -07001307 new_bag->entry_count = static_cast<uint32_t>(actual_count);
1308 ResolvedBag* result = new_bag.get();
1309 cached_bags_[resid] = std::move(new_bag);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001310 return result;
1311}
1312
Yurii Zubrytskyia5775142022-11-02 17:49:49 -07001313static bool Utf8ToUtf16(StringPiece str, std::u16string* out) {
Adam Lesinski929d6512017-01-16 19:11:19 -08001314 ssize_t len =
1315 utf8_to_utf16_length(reinterpret_cast<const uint8_t*>(str.data()), str.size(), false);
1316 if (len < 0) {
1317 return false;
1318 }
1319 out->resize(static_cast<size_t>(len));
1320 utf8_to_utf16(reinterpret_cast<const uint8_t*>(str.data()), str.size(), &*out->begin(),
1321 static_cast<size_t>(len + 1));
1322 return true;
1323}
1324
Ryan Mitchell80094e32020-11-16 23:08:18 +00001325base::expected<uint32_t, NullOrIOError> AssetManager2::GetResourceId(
1326 const std::string& resource_name, const std::string& fallback_type,
1327 const std::string& fallback_package) const {
Adam Lesinski929d6512017-01-16 19:11:19 -08001328 StringPiece package_name, type, entry;
1329 if (!ExtractResourceName(resource_name, &package_name, &type, &entry)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001330 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001331 }
1332
1333 if (entry.empty()) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001334 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001335 }
1336
1337 if (package_name.empty()) {
1338 package_name = fallback_package;
1339 }
1340
1341 if (type.empty()) {
1342 type = fallback_type;
1343 }
1344
1345 std::u16string type16;
1346 if (!Utf8ToUtf16(type, &type16)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001347 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001348 }
1349
1350 std::u16string entry16;
1351 if (!Utf8ToUtf16(entry, &entry16)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001352 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001353 }
1354
1355 const StringPiece16 kAttr16 = u"attr";
1356 const static std::u16string kAttrPrivate16 = u"^attr-private";
1357
1358 for (const PackageGroup& package_group : package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001359 for (const ConfiguredPackage& package_impl : package_group.packages_) {
1360 const LoadedPackage* package = package_impl.loaded_package_;
Adam Lesinski929d6512017-01-16 19:11:19 -08001361 if (package_name != package->GetPackageName()) {
1362 // All packages in the same group are expected to have the same package name.
1363 break;
1364 }
1365
Ryan Mitchell80094e32020-11-16 23:08:18 +00001366 base::expected<uint32_t, NullOrIOError> resid = package->FindEntryByName(type16, entry16);
1367 if (UNLIKELY(IsIOError(resid))) {
1368 return base::unexpected(resid.error());
1369 }
1370
1371 if (!resid.has_value() && kAttr16 == type16) {
Adam Lesinski929d6512017-01-16 19:11:19 -08001372 // Private attributes in libraries (such as the framework) are sometimes encoded
1373 // under the type '^attr-private' in order to leave the ID space of public 'attr'
1374 // free for future additions. Check '^attr-private' for the same name.
1375 resid = package->FindEntryByName(kAttrPrivate16, entry16);
1376 }
1377
Ryan Mitchell80094e32020-11-16 23:08:18 +00001378 if (resid.has_value()) {
1379 return fix_package_id(*resid, package_group.dynamic_ref_table->mAssignedPackageId);
Adam Lesinski929d6512017-01-16 19:11:19 -08001380 }
1381 }
1382 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001383 return base::unexpected(std::nullopt);
Adam Lesinski0c405242017-01-13 20:47:26 -08001384}
1385
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001386void AssetManager2::RebuildFilterList() {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001387 for (PackageGroup& group : package_groups_) {
Yurii Zubrytskyidbce3562022-11-14 22:26:10 -08001388 for (ConfiguredPackage& package : group.packages_) {
1389 package.filtered_configs_.forEachItem([](auto, auto& fcg) { fcg.type_entries.clear(); });
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001390 // Create the filters here.
Yurii Zubrytskyidbce3562022-11-14 22:26:10 -08001391 package.loaded_package_->ForEachTypeSpec([&](const TypeSpec& type_spec, uint8_t type_id) {
Yurii Zubrytskyi59dab3b2022-11-03 00:08:49 -07001392 FilteredConfigGroup* group = nullptr;
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001393 for (const auto& type_entry : type_spec.type_entries) {
1394 if (type_entry.config.match(configuration_)) {
Yurii Zubrytskyi59dab3b2022-11-03 00:08:49 -07001395 if (!group) {
Yurii Zubrytskyidbce3562022-11-14 22:26:10 -08001396 group = &package.filtered_configs_.editItemAt(type_id - 1);
Yurii Zubrytskyi59dab3b2022-11-03 00:08:49 -07001397 }
1398 group->type_entries.push_back(&type_entry);
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001399 }
1400 }
1401 });
Yurii Zubrytskyidbce3562022-11-14 22:26:10 -08001402 package.filtered_configs_.trimBuckets(
1403 [](const auto& fcg) { return fcg.type_entries.empty(); });
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001404 }
1405 }
1406}
1407
Adam Lesinski7ad11102016-10-28 16:39:15 -07001408void AssetManager2::InvalidateCaches(uint32_t diff) {
Ryan Mitchell2c4d8742019-03-04 09:41:00 -08001409 cached_bag_resid_stacks_.clear();
1410
Adam Lesinski7ad11102016-10-28 16:39:15 -07001411 if (diff == 0xffffffffu) {
1412 // Everything must go.
1413 cached_bags_.clear();
1414 return;
1415 }
1416
1417 // Be more conservative with what gets purged. Only if the bag has other possible
1418 // variations with respect to what changed (diff) should we remove it.
1419 for (auto iter = cached_bags_.cbegin(); iter != cached_bags_.cend();) {
1420 if (diff & iter->second->type_spec_flags) {
1421 iter = cached_bags_.erase(iter);
1422 } else {
1423 ++iter;
1424 }
1425 }
Ryan Mitchella45506e2020-11-16 23:08:18 +00001426
1427 cached_resolved_values_.clear();
Adam Lesinski7ad11102016-10-28 16:39:15 -07001428}
1429
Ryan Mitchell2e394222019-08-28 12:10:51 -07001430uint8_t AssetManager2::GetAssignedPackageId(const LoadedPackage* package) const {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001431 for (auto& package_group : package_groups_) {
1432 for (auto& package2 : package_group.packages_) {
1433 if (package2.loaded_package_ == package) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -07001434 return package_group.dynamic_ref_table->mAssignedPackageId;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001435 }
1436 }
1437 }
1438 return 0;
1439}
1440
Adam Lesinski30080e22017-10-16 16:18:09 -07001441std::unique_ptr<Theme> AssetManager2::NewTheme() {
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001442 constexpr size_t kInitialReserveSize = 32;
1443 auto theme = std::unique_ptr<Theme>(new Theme(this));
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001444 theme->keys_.reserve(kInitialReserveSize);
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001445 theme->entries_.reserve(kInitialReserveSize);
1446 return theme;
Adam Lesinski30080e22017-10-16 16:18:09 -07001447}
1448
Yurii Zubrytskyi9eb44c92022-11-14 23:44:52 -08001449void AssetManager2::ForEachPackage(base::function_ref<bool(const std::string&, uint8_t)> func,
1450 package_property_t excluded_property_flags) const {
1451 for (const PackageGroup& package_group : package_groups_) {
1452 const auto loaded_package = package_group.packages_.front().loaded_package_;
1453 if ((loaded_package->GetPropertyFlags() & excluded_property_flags) == 0U
1454 && !func(loaded_package->GetPackageName(),
1455 package_group.dynamic_ref_table->mAssignedPackageId)) {
1456 return;
1457 }
1458 }
1459}
1460
Adam Lesinski30080e22017-10-16 16:18:09 -07001461Theme::Theme(AssetManager2* asset_manager) : asset_manager_(asset_manager) {
1462}
1463
1464Theme::~Theme() = default;
1465
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001466struct Theme::Entry {
Adam Lesinski30080e22017-10-16 16:18:09 -07001467 ApkAssetsCookie cookie;
1468 uint32_t type_spec_flags;
1469 Res_value value;
1470};
1471
Ryan Mitchell80094e32020-11-16 23:08:18 +00001472base::expected<std::monostate, NullOrIOError> Theme::ApplyStyle(uint32_t resid, bool force) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001473 ATRACE_NAME("Theme::ApplyStyle");
Adam Lesinski7ad11102016-10-28 16:39:15 -07001474
Ryan Mitchell80094e32020-11-16 23:08:18 +00001475 auto bag = asset_manager_->GetBag(resid);
1476 if (!bag.has_value()) {
1477 return base::unexpected(bag.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001478 }
1479
1480 // Merge the flags from this style.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001481 type_spec_flags_ |= (*bag)->type_spec_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001482
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001483 for (auto it = begin(*bag); it != end(*bag); ++it) {
1484 const uint32_t attr_res_id = it->key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001485
Adam Lesinski30080e22017-10-16 16:18:09 -07001486 // If the resource ID passed in is not a style, the key can be some other identifier that is not
1487 // a resource ID. We should fail fast instead of operating with strange resource IDs.
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001488 if (!is_valid_resid(attr_res_id)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001489 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001490 }
1491
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001492 // DATA_NULL_EMPTY (@empty) is a valid resource value and DATA_NULL_UNDEFINED represents
1493 // an absence of a valid value.
1494 bool is_undefined = it->value.dataType == Res_value::TYPE_NULL &&
1495 it->value.data != Res_value::DATA_NULL_EMPTY;
1496 if (!force && is_undefined) {
1497 continue;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001498 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001499
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001500 const auto key_it = std::lower_bound(keys_.begin(), keys_.end(), attr_res_id);
1501 const auto entry_it = entries_.begin() + (key_it - keys_.begin());
1502 if (key_it != keys_.end() && *key_it == attr_res_id) {
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001503 if (is_undefined) {
1504 // DATA_NULL_UNDEFINED clears the value of the attribute in the theme only when `force` is
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001505 // true.
1506 keys_.erase(key_it);
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001507 entries_.erase(entry_it);
1508 } else if (force) {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001509 *entry_it = Entry{it->cookie, (*bag)->type_spec_flags, it->value};
Adam Lesinski30080e22017-10-16 16:18:09 -07001510 }
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001511 } else {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001512 keys_.insert(key_it, attr_res_id);
1513 entries_.insert(entry_it, Entry{it->cookie, (*bag)->type_spec_flags, it->value});
Adam Lesinski7ad11102016-10-28 16:39:15 -07001514 }
1515 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001516 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001517}
1518
Ryan Mitchell767e34f2021-06-07 12:29:05 -07001519void Theme::Rebase(AssetManager2* am, const uint32_t* style_ids, const uint8_t* force,
1520 size_t style_count) {
1521 ATRACE_NAME("Theme::Rebase");
1522 // Reset the entries without changing the vector capacity to prevent reallocations during
1523 // ApplyStyle.
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001524 keys_.clear();
Ryan Mitchell767e34f2021-06-07 12:29:05 -07001525 entries_.clear();
1526 asset_manager_ = am;
1527 for (size_t i = 0; i < style_count; i++) {
1528 ApplyStyle(style_ids[i], force[i]);
1529 }
1530}
1531
Ryan Mitchell80094e32020-11-16 23:08:18 +00001532std::optional<AssetManager2::SelectedValue> Theme::GetAttribute(uint32_t resid) const {
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001533 constexpr const uint32_t kMaxIterations = 20;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001534 uint32_t type_spec_flags = 0u;
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001535 for (uint32_t i = 0; i <= kMaxIterations; i++) {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001536 const auto key_it = std::lower_bound(keys_.begin(), keys_.end(), resid);
1537 if (key_it == keys_.end() || *key_it != resid) {
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001538 return std::nullopt;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001539 }
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001540 const auto entry_it = entries_.begin() + (key_it - keys_.begin());
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001541 type_spec_flags |= entry_it->type_spec_flags;
1542 if (entry_it->value.dataType == Res_value::TYPE_ATTRIBUTE) {
1543 resid = entry_it->value.data;
1544 continue;
1545 }
1546
1547 return AssetManager2::SelectedValue(entry_it->value.dataType, entry_it->value.data,
1548 entry_it->cookie, type_spec_flags, 0U /* resid */,
1549 {} /* config */);
1550 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001551 return std::nullopt;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001552}
1553
Ryan Mitchell80094e32020-11-16 23:08:18 +00001554base::expected<std::monostate, NullOrIOError> Theme::ResolveAttributeReference(
1555 AssetManager2::SelectedValue& value) const {
1556 if (value.type != Res_value::TYPE_ATTRIBUTE) {
1557 return asset_manager_->ResolveReference(value);
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001558 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001559
1560 std::optional<AssetManager2::SelectedValue> result = GetAttribute(value.data);
1561 if (!result.has_value()) {
1562 return base::unexpected(std::nullopt);
1563 }
1564
Ryan Mitchella45506e2020-11-16 23:08:18 +00001565 auto resolve_result = asset_manager_->ResolveReference(*result, true /* cache_value */);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001566 if (resolve_result.has_value()) {
1567 result->flags |= value.flags;
1568 value = *result;
1569 }
1570 return resolve_result;
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001571}
1572
Adam Lesinski7ad11102016-10-28 16:39:15 -07001573void Theme::Clear() {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001574 keys_.clear();
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001575 entries_.clear();
Adam Lesinski7ad11102016-10-28 16:39:15 -07001576}
1577
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001578base::expected<std::monostate, IOError> Theme::SetTo(const Theme& source) {
1579 if (this == &source) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001580 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001581 }
1582
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001583 type_spec_flags_ = source.type_spec_flags_;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001584
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001585 if (asset_manager_ == source.asset_manager_) {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001586 keys_ = source.keys_;
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001587 entries_ = source.entries_;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001588 } else {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001589 std::unordered_map<ApkAssetsCookie, ApkAssetsCookie> src_to_dest_asset_cookies;
1590 using SourceToDestinationRuntimePackageMap = std::unordered_map<int, int>;
1591 std::unordered_map<ApkAssetsCookie, SourceToDestinationRuntimePackageMap> src_asset_cookie_id_map;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001592
Ryan Mitchell93bca972019-03-08 17:26:28 -08001593 // Determine which ApkAssets are loaded in both theme AssetManagers.
Yurii Zubrytskyia5bc9582022-11-30 23:53:59 -08001594 const auto& src_assets = source.asset_manager_->GetApkAssets();
Yurii Zubrytskyib3455192023-05-01 14:35:48 -07001595 const auto& dest_assets = asset_manager_->GetApkAssets();
1596 std::vector<AssetManager2::ApkAssetsPtr> promoted_src_assets;
1597 promoted_src_assets.reserve(src_assets.size());
1598 for (const auto& src_asset : src_assets) {
1599 promoted_src_assets.emplace_back(src_asset.promote());
1600 }
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001601
Yurii Zubrytskyib3455192023-05-01 14:35:48 -07001602 for (size_t j = 0; j < dest_assets.size(); j++) {
1603 auto dest_asset = dest_assets[j].promote();
1604 if (!dest_asset) {
1605 continue;
1606 }
1607 for (size_t i = 0; i < promoted_src_assets.size(); i++) {
1608 const auto& src_asset = promoted_src_assets[i];
Ryan Mitchellef538432021-03-01 14:52:14 -08001609 if (src_asset != dest_asset) {
1610 // ResourcesManager caches and reuses ApkAssets when the same apk must be present in
1611 // multiple AssetManagers. Two ApkAssets point to the same version of the same resources
1612 // if they are the same instance.
1613 continue;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001614 }
Ryan Mitchellef538432021-03-01 14:52:14 -08001615
1616 // Map the package ids of the asset in the source AssetManager to the package ids of the
1617 // asset in th destination AssetManager.
1618 SourceToDestinationRuntimePackageMap package_map;
1619 for (const auto& loaded_package : src_asset->GetLoadedArsc()->GetPackages()) {
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001620 const int src_package_id = source.asset_manager_->GetAssignedPackageId(
1621 loaded_package.get());
Ryan Mitchellef538432021-03-01 14:52:14 -08001622 const int dest_package_id = asset_manager_->GetAssignedPackageId(loaded_package.get());
1623 package_map[src_package_id] = dest_package_id;
1624 }
1625
1626 src_to_dest_asset_cookies.insert(std::make_pair(i, j));
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001627 src_asset_cookie_id_map.insert(std::make_pair(i, std::move(package_map)));
Ryan Mitchellef538432021-03-01 14:52:14 -08001628 break;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001629 }
1630 }
1631
Ryan Mitchell93bca972019-03-08 17:26:28 -08001632 // Reset the data in the destination theme.
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001633 keys_.clear();
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001634 entries_.clear();
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001635
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001636 for (size_t i = 0, size = source.entries_.size(); i != size; ++i) {
1637 const auto& entry = source.entries_[i];
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001638 bool is_reference = (entry.value.dataType == Res_value::TYPE_ATTRIBUTE
1639 || entry.value.dataType == Res_value::TYPE_REFERENCE
1640 || entry.value.dataType == Res_value::TYPE_DYNAMIC_ATTRIBUTE
1641 || entry.value.dataType == Res_value::TYPE_DYNAMIC_REFERENCE)
1642 && entry.value.data != 0x0;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001643
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001644 // If the attribute value represents an attribute or reference, the package id of the
1645 // value needs to be rewritten to the package id of the value in the destination.
1646 uint32_t attribute_data = entry.value.data;
1647 if (is_reference) {
1648 // Determine the package id of the reference in the destination AssetManager.
1649 auto value_package_map = src_asset_cookie_id_map.find(entry.cookie);
1650 if (value_package_map == src_asset_cookie_id_map.end()) {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001651 continue;
1652 }
1653
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001654 auto value_dest_package = value_package_map->second.find(
1655 get_package_id(entry.value.data));
1656 if (value_dest_package == value_package_map->second.end()) {
1657 continue;
1658 }
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001659
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001660 attribute_data = fix_package_id(entry.value.data, value_dest_package->second);
1661 }
Ryan Mitchellb85d9b22018-11-19 12:11:38 -08001662
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001663 // Find the cookie of the value in the destination. If the source apk is not loaded in the
1664 // destination, only copy resources that do not reference resources in the source.
1665 ApkAssetsCookie data_dest_cookie;
1666 auto value_dest_cookie = src_to_dest_asset_cookies.find(entry.cookie);
1667 if (value_dest_cookie != src_to_dest_asset_cookies.end()) {
1668 data_dest_cookie = value_dest_cookie->second;
1669 } else {
1670 if (is_reference || entry.value.dataType == Res_value::TYPE_STRING) {
1671 continue;
1672 } else {
1673 data_dest_cookie = 0x0;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001674 }
1675 }
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001676
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001677 const auto source_res_id = source.keys_[i];
1678
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001679 // The package id of the attribute needs to be rewritten to the package id of the
1680 // attribute in the destination.
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001681 int attribute_dest_package_id = get_package_id(source_res_id);
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001682 if (attribute_dest_package_id != 0x01) {
1683 // Find the cookie of the attribute resource id in the source AssetManager
1684 base::expected<FindEntryResult, NullOrIOError> attribute_entry_result =
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001685 source.asset_manager_->FindEntry(source_res_id, 0 /* density_override */ ,
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001686 true /* stop_at_first_match */,
1687 true /* ignore_configuration */);
1688 if (UNLIKELY(IsIOError(attribute_entry_result))) {
1689 return base::unexpected(GetIOError(attribute_entry_result.error()));
1690 }
1691 if (!attribute_entry_result.has_value()) {
1692 continue;
1693 }
1694
1695 // Determine the package id of the attribute in the destination AssetManager.
1696 auto attribute_package_map = src_asset_cookie_id_map.find(
1697 attribute_entry_result->cookie);
1698 if (attribute_package_map == src_asset_cookie_id_map.end()) {
1699 continue;
1700 }
1701 auto attribute_dest_package = attribute_package_map->second.find(
1702 attribute_dest_package_id);
1703 if (attribute_dest_package == attribute_package_map->second.end()) {
1704 continue;
1705 }
1706 attribute_dest_package_id = attribute_dest_package->second;
1707 }
1708
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001709 auto dest_attr_id = make_resid(attribute_dest_package_id, get_type_id(source_res_id),
1710 get_entry_id(source_res_id));
1711 const auto key_it = std::lower_bound(keys_.begin(), keys_.end(), dest_attr_id);
1712 const auto entry_it = entries_.begin() + (key_it - keys_.begin());
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001713 // Since the entries were cleared, the attribute resource id has yet been mapped to any value.
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001714 keys_.insert(key_it, dest_attr_id);
1715 entries_.insert(entry_it, Entry{data_dest_cookie, entry.type_spec_flags,
1716 Res_value{.dataType = entry.value.dataType,
1717 .data = attribute_data}});
Adam Lesinski7ad11102016-10-28 16:39:15 -07001718 }
1719 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001720 return {};
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001721}
1722
1723void Theme::Dump() const {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001724 LOG(INFO) << base::StringPrintf("Theme(this=%p, AssetManager2=%p)", this, asset_manager_);
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001725 for (size_t i = 0, size = keys_.size(); i != size; ++i) {
1726 auto res_id = keys_[i];
1727 const auto& entry = entries_[i];
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001728 LOG(INFO) << base::StringPrintf(" entry(0x%08x)=(0x%08x) type=(0x%02x), cookie(%d)",
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001729 res_id, entry.value.data, entry.value.dataType,
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001730 entry.cookie);
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001731 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001732}
1733
1734} // namespace android