blob: d604df3565d283977f747b1474a734487ce946ec [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 Zubrytskyic357f712023-04-13 02:32:45 -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 Zubrytskyic357f712023-04-13 02:32:45 -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 Zubrytskyic357f712023-04-13 02:32:45 -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 Zubrytskyic357f712023-04-13 02:32:45 -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 Zubrytskyic357f712023-04-13 02:32:45 -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 Zubrytskyic357f712023-04-13 02:32:45 -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 Zubrytskyic357f712023-04-13 02:32:45 -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 Zubrytskyic357f712023-04-13 02:32:45 -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 Zubrytskyic357f712023-04-13 02:32:45 -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 Zubrytskyic357f712023-04-13 02:32:45 -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 Zubrytskyic357f712023-04-13 02:32:45 -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 Zubrytskyic357f712023-04-13 02:32:45 -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 Zubrytskyic357f712023-04-13 02:32:45 -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 Zubrytskyic357f712023-04-13 02:32:45 -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 Zubrytskyic357f712023-04-13 02:32:45 -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 Zubrytskyic357f712023-04-13 02:32:45 -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 Zubrytskyic357f712023-04-13 02:32:45 -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 Zubrytskyic357f712023-04-13 02:32:45 -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 Zubrytskyic357f712023-04-13 02:32:45 -0700559 if (!assets || assets->IsOverlay()) {
MÃ¥rten Kongstaddbf343b2019-02-21 07:54:18 +0100560 continue;
561 }
562
Yurii Zubrytskyic357f712023-04-13 02:32:45 -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 Zubrytskyic357f712023-04-13 02:32:45 -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 Zubrytskyic357f712023-04-13 02:32:45 -0700633 auto assets = apk_assets_[result->cookie].promote();
634 if (!assets) {
635 ALOGE("Found expired ApkAssets #%d for resource ID 0x%08x.", result->cookie, resid);
636 return base::unexpected(std::nullopt);
637 }
638 if (!stop_at_first_match && !ignore_configuration && !assets->IsLoader()) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700639 for (const auto& id_map : package_group.overlays_) {
640 auto overlay_entry = id_map.overlay_res_maps_.Lookup(resid);
641 if (!overlay_entry) {
642 // No id map entry exists for this target resource.
643 continue;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000644 }
645 if (overlay_entry.IsInlineValue()) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700646 // The target resource is overlaid by an inline value not represented by a resource.
Jeremy Meyerbe2b7792022-08-23 17:42:50 +0000647 ConfigDescription best_frro_config;
648 Res_value best_frro_value;
649 bool frro_found = false;
650 for( const auto& [config, value] : overlay_entry.GetInlineValue()) {
651 if ((!frro_found || config.isBetterThan(best_frro_config, desired_config))
652 && config.match(*desired_config)) {
653 frro_found = true;
654 best_frro_config = config;
655 best_frro_value = value;
656 }
657 }
658 if (!frro_found) {
659 continue;
660 }
661 result->entry = best_frro_value;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000662 result->dynamic_ref_table = id_map.overlay_res_maps_.GetOverlayDynamicRefTable();
663 result->cookie = id_map.cookie;
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800664
665 if (UNLIKELY(logging_enabled)) {
666 last_resolution_.steps.push_back(
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -0700667 Resolution::Step{Resolution::Step::Type::OVERLAID_INLINE, result->cookie, String8()});
Yurii Zubrytskyic357f712023-04-13 02:32:45 -0700668 if (auto path = assets->GetPath()) {
Jackal Guo552b45d2021-09-29 10:52:19 +0800669 const std::string overlay_path = path->data();
670 if (IsFabricatedOverlay(overlay_path)) {
671 // FRRO don't have package name so we use the creating package here.
672 String8 frro_name = String8("FRRO");
673 // Get the first part of it since the expected one should be like
674 // {overlayPackageName}-{overlayName}-{4 alphanumeric chars}.frro
675 // under /data/resource-cache/.
676 const std::string name = overlay_path.substr(overlay_path.rfind('/') + 1);
677 const size_t end = name.find('-');
678 if (frro_name.size() != overlay_path.size() && end != std::string::npos) {
679 frro_name.append(base::StringPrintf(" created by %s",
680 name.substr(0 /* pos */,
681 end).c_str()).c_str());
682 }
683 last_resolution_.best_package_name = frro_name;
684 } else {
685 last_resolution_.best_package_name = result->package_name->c_str();
686 }
687 }
688 overlaid = true;
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800689 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700690 continue;
691 }
692
Ryan Mitchell80094e32020-11-16 23:08:18 +0000693 auto overlay_result = FindEntry(overlay_entry.GetResourceId(), density_override,
694 false /* stop_at_first_match */,
695 false /* ignore_configuration */);
696 if (UNLIKELY(IsIOError(overlay_result))) {
697 return base::unexpected(overlay_result.error());
698 }
699 if (!overlay_result.has_value()) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700700 continue;
701 }
702
Ryan Mitchell80094e32020-11-16 23:08:18 +0000703 if (!overlay_result->config.isBetterThan(result->config, desired_config)
704 && overlay_result->config.compare(result->config) != 0) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700705 // The configuration of the entry for the overlay must be equal to or better than the target
706 // configuration to be chosen as the better value.
707 continue;
708 }
709
Ryan Mitchell80094e32020-11-16 23:08:18 +0000710 result->cookie = overlay_result->cookie;
711 result->entry = overlay_result->entry;
712 result->config = overlay_result->config;
713 result->dynamic_ref_table = id_map.overlay_res_maps_.GetOverlayDynamicRefTable();
714
715 if (UNLIKELY(logging_enabled)) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700716 last_resolution_.steps.push_back(
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -0700717 Resolution::Step{Resolution::Step::Type::OVERLAID, overlay_result->cookie,
718 overlay_result->config.toString()});
Jackal Guo552b45d2021-09-29 10:52:19 +0800719 last_resolution_.best_package_name =
720 overlay_result->package_name->c_str();
721 overlaid = true;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700722 }
723 }
724 }
725
Ryan Mitchell80094e32020-11-16 23:08:18 +0000726 if (UNLIKELY(logging_enabled)) {
727 last_resolution_.cookie = result->cookie;
728 last_resolution_.type_string_ref = result->type_string_ref;
729 last_resolution_.entry_string_ref = result->entry_string_ref;
Jackal Guo552b45d2021-09-29 10:52:19 +0800730 last_resolution_.best_config_name = result->config.toString();
731 if (!overlaid) {
732 last_resolution_.best_package_name = result->package_name->c_str();
733 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700734 }
735
Ryan Mitchell80094e32020-11-16 23:08:18 +0000736 return result;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700737}
738
Ryan Mitchell80094e32020-11-16 23:08:18 +0000739base::expected<FindEntryResult, NullOrIOError> AssetManager2::FindEntryInternal(
740 const PackageGroup& package_group, uint8_t type_idx, uint16_t entry_idx,
741 const ResTable_config& desired_config, bool stop_at_first_match,
742 bool ignore_configuration) const {
743 const bool logging_enabled = resource_resolution_logging_enabled_;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800744 ApkAssetsCookie best_cookie = kInvalidCookie;
745 const LoadedPackage* best_package = nullptr;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000746 incfs::verified_map_ptr<ResTable_type> best_type;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800747 const ResTable_config* best_config = nullptr;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000748 uint32_t best_offset = 0U;
749 uint32_t type_flags = 0U;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800750
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800751 // If `desired_config` is not the same as the set configuration or the caller will accept a value
752 // from any configuration, then we cannot use our filtered list of types since it only it contains
753 // types matched to the set configuration.
754 const bool use_filtered = !ignore_configuration && &desired_config == &configuration_;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800755
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700756 const size_t package_count = package_group.packages_.size();
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800757 for (size_t pi = 0; pi < package_count; pi++) {
758 const ConfiguredPackage& loaded_package_impl = package_group.packages_[pi];
759 const LoadedPackage* loaded_package = loaded_package_impl.loaded_package_;
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800760 const ApkAssetsCookie cookie = package_group.cookies_[pi];
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800761
762 // If the type IDs are offset in this package, we need to take that into account when searching
763 // for a type.
764 const TypeSpec* type_spec = loaded_package->GetTypeSpecByTypeIndex(type_idx);
765 if (UNLIKELY(type_spec == nullptr)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700766 continue;
767 }
768
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800769 // Allow custom loader packages to overlay resource values with configurations equivalent to the
770 // current best configuration.
771 const bool package_is_loader = loaded_package->IsCustomLoader();
772
Ryan Mitchell80094e32020-11-16 23:08:18 +0000773 auto entry_flags = type_spec->GetFlagsForEntryIndex(entry_idx);
Bernie Innocenti58cf8e32020-12-19 15:31:52 +0900774 if (UNLIKELY(!entry_flags.has_value())) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000775 return base::unexpected(entry_flags.error());
776 }
777 type_flags |= entry_flags.value();
778
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800779 const FilteredConfigGroup& filtered_group = loaded_package_impl.filtered_configs_[type_idx];
780 const size_t type_entry_count = (use_filtered) ? filtered_group.type_entries.size()
781 : type_spec->type_entries.size();
782 for (size_t i = 0; i < type_entry_count; i++) {
783 const TypeSpec::TypeEntry* type_entry = (use_filtered) ? filtered_group.type_entries[i]
784 : &type_spec->type_entries[i];
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800785
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800786 // We can skip calling ResTable_config::match() if the caller does not care for the
787 // configuration to match or if we're using the list of types that have already had their
788 // configuration matched.
789 const ResTable_config& this_config = type_entry->config;
790 if (!(use_filtered || ignore_configuration || this_config.match(desired_config))) {
791 continue;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800792 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800793
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800794 Resolution::Step::Type resolution_type;
795 if (best_config == nullptr) {
796 resolution_type = Resolution::Step::Type::INITIAL;
797 } else if (this_config.isBetterThan(*best_config, &desired_config)) {
798 resolution_type = Resolution::Step::Type::BETTER_MATCH;
799 } else if (package_is_loader && this_config.compare(*best_config) == 0) {
800 resolution_type = Resolution::Step::Type::OVERLAID;
801 } else {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000802 if (UNLIKELY(logging_enabled)) {
Jackal Guo552b45d2021-09-29 10:52:19 +0800803 last_resolution_.steps.push_back(Resolution::Step{Resolution::Step::Type::SKIPPED,
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -0700804 cookie, this_config.toString()});
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800805 }
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800806 continue;
807 }
808
809 // The configuration matches and is better than the previous selection.
810 // Find the entry value if it exists for this configuration.
811 const auto& type = type_entry->type;
812 const auto offset = LoadedPackage::GetEntryOffset(type, entry_idx);
813 if (UNLIKELY(IsIOError(offset))) {
814 return base::unexpected(offset.error());
815 }
816
817 if (!offset.has_value()) {
818 if (UNLIKELY(logging_enabled)) {
Jackal Guo552b45d2021-09-29 10:52:19 +0800819 last_resolution_.steps.push_back(Resolution::Step{Resolution::Step::Type::NO_ENTRY,
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -0700820 cookie, this_config.toString()});
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800821 }
822 continue;
823 }
824
825 best_cookie = cookie;
826 best_package = loaded_package;
827 best_type = type;
828 best_config = &this_config;
829 best_offset = offset.value();
830
831 if (UNLIKELY(logging_enabled)) {
832 last_resolution_.steps.push_back(Resolution::Step{resolution_type,
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -0700833 cookie, this_config.toString()});
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800834 }
835
836 // Any configuration will suffice, so break.
837 if (stop_at_first_match) {
838 break;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700839 }
840 }
841 }
842
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800843 if (UNLIKELY(best_cookie == kInvalidCookie)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000844 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700845 }
846
Eric Miao368cd192022-09-09 15:46:14 -0700847 auto best_entry_verified = LoadedPackage::GetEntryFromOffset(best_type, best_offset);
848 if (!best_entry_verified.has_value()) {
849 return base::unexpected(best_entry_verified.error());
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800850 }
851
Eric Miao368cd192022-09-09 15:46:14 -0700852 const auto entry = GetEntryValue(*best_entry_verified);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000853 if (!entry.has_value()) {
854 return base::unexpected(entry.error());
855 }
Winson2f3669b2019-01-11 11:28:34 -0800856
Ryan Mitchell80094e32020-11-16 23:08:18 +0000857 return FindEntryResult{
858 .cookie = best_cookie,
859 .entry = *entry,
860 .config = *best_config,
861 .type_flags = type_flags,
862 .package_name = &best_package->GetPackageName(),
863 .type_string_ref = StringPoolRef(best_package->GetTypeStringPool(), best_type->id - 1),
864 .entry_string_ref = StringPoolRef(best_package->GetKeyStringPool(),
Eric Miao368cd192022-09-09 15:46:14 -0700865 (*best_entry_verified)->key()),
Ryan Mitchell80094e32020-11-16 23:08:18 +0000866 .dynamic_ref_table = package_group.dynamic_ref_table.get(),
867 };
Adam Lesinski7ad11102016-10-28 16:39:15 -0700868}
869
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700870void AssetManager2::ResetResourceResolution() const {
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -0700871 last_resolution_ = Resolution{};
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700872}
873
Winson2f3669b2019-01-11 11:28:34 -0800874void AssetManager2::SetResourceResolutionLoggingEnabled(bool enabled) {
875 resource_resolution_logging_enabled_ = enabled;
Winson2f3669b2019-01-11 11:28:34 -0800876 if (!enabled) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700877 ResetResourceResolution();
Winson2f3669b2019-01-11 11:28:34 -0800878 }
879}
880
881std::string AssetManager2::GetLastResourceResolution() const {
882 if (!resource_resolution_logging_enabled_) {
883 LOG(ERROR) << "Must enable resource resolution logging before getting path.";
Ryan Mitchell80094e32020-11-16 23:08:18 +0000884 return {};
Winson2f3669b2019-01-11 11:28:34 -0800885 }
886
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800887 const ApkAssetsCookie cookie = last_resolution_.cookie;
Winson2f3669b2019-01-11 11:28:34 -0800888 if (cookie == kInvalidCookie) {
889 LOG(ERROR) << "AssetManager hasn't resolved a resource to read resolution path.";
Ryan Mitchell80094e32020-11-16 23:08:18 +0000890 return {};
Winson2f3669b2019-01-11 11:28:34 -0800891 }
892
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800893 const uint32_t resid = last_resolution_.resid;
Yurii Zubrytskyic357f712023-04-13 02:32:45 -0700894 auto assets = apk_assets_[cookie].promote();
895 const auto package =
896 assets ? assets->GetLoadedArsc()->GetPackageById(get_package_id(resid)) : nullptr;
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800897
Winson2f3669b2019-01-11 11:28:34 -0800898 std::string resource_name_string;
Winson2f3669b2019-01-11 11:28:34 -0800899 if (package != nullptr) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000900 auto resource_name = ToResourceName(last_resolution_.type_string_ref,
901 last_resolution_.entry_string_ref,
902 package->GetPackageName());
903 resource_name_string = resource_name.has_value() ?
904 ToFormattedResourceString(resource_name.value()) : "<unknown>";
Winson2f3669b2019-01-11 11:28:34 -0800905 }
906
907 std::stringstream log_stream;
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800908 log_stream << base::StringPrintf("Resolution for 0x%08x %s\n"
909 "\tFor config - %s", resid, resource_name_string.c_str(),
910 configuration_.toString().c_str());
Winson2f3669b2019-01-11 11:28:34 -0800911
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800912 for (const Resolution::Step& step : last_resolution_.steps) {
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -0700913 constexpr static std::array kStepStrings = {
914 "Found initial",
915 "Found better",
916 "Overlaid",
917 "Overlaid inline",
918 "Skipped",
919 "No entry"
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800920 };
921
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -0700922 if (step.type < Resolution::Step::Type::INITIAL
923 || step.type > Resolution::Step::Type::NO_ENTRY) {
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800924 continue;
Winson2f3669b2019-01-11 11:28:34 -0800925 }
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -0700926 const auto prefix = kStepStrings[int(step.type) - int(Resolution::Step::Type::INITIAL)];
Yurii Zubrytskyic357f712023-04-13 02:32:45 -0700927 auto assets = apk_assets_[step.cookie].promote();
928 log_stream << "\n\t" << prefix << ": " << (assets ? assets->GetDebugName() : "<null>")
929 << " #" << step.cookie;
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800930 if (!step.config_name.isEmpty()) {
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800931 log_stream << " - " << step.config_name;
Winson2f3669b2019-01-11 11:28:34 -0800932 }
933 }
934
Jackal Guo552b45d2021-09-29 10:52:19 +0800935 log_stream << "\nBest matching is from "
936 << (last_resolution_.best_config_name.isEmpty() ? "default"
937 : last_resolution_.best_config_name)
938 << " configuration of " << last_resolution_.best_package_name;
Winson2f3669b2019-01-11 11:28:34 -0800939 return log_stream.str();
940}
941
Felka Chang00964e92021-12-10 01:19:08 +0800942base::expected<uint32_t, NullOrIOError> AssetManager2::GetParentThemeResourceId(uint32_t resid)
943const {
944 auto entry = FindEntry(resid, 0u /* density_override */,
945 false /* stop_at_first_match */,
946 false /* ignore_configuration */);
947 if (!entry.has_value()) {
948 return base::unexpected(entry.error());
949 }
950
951 auto entry_map = std::get_if<incfs::verified_map_ptr<ResTable_map_entry>>(&entry->entry);
952 if (entry_map == nullptr) {
953 // Not a bag, nothing to do.
954 return base::unexpected(std::nullopt);
955 }
956
957 auto map = *entry_map;
958 const uint32_t parent_resid = dtohl(map->parent.ident);
959
960 return parent_resid;
961}
962
Ryan Mitchell80094e32020-11-16 23:08:18 +0000963base::expected<AssetManager2::ResourceName, NullOrIOError> AssetManager2::GetResourceName(
964 uint32_t resid) const {
965 auto result = FindEntry(resid, 0u /* density_override */, true /* stop_at_first_match */,
966 true /* ignore_configuration */);
967 if (!result.has_value()) {
968 return base::unexpected(result.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -0700969 }
970
Ryan Mitchell80094e32020-11-16 23:08:18 +0000971 return ToResourceName(result->type_string_ref,
972 result->entry_string_ref,
973 *result->package_name);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700974}
975
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800976base::expected<uint32_t, NullOrIOError> AssetManager2::GetResourceTypeSpecFlags(
977 uint32_t resid) const {
978 auto result = FindEntry(resid, 0u /* density_override */, false /* stop_at_first_match */,
979 true /* ignore_configuration */);
980 if (!result.has_value()) {
981 return base::unexpected(result.error());
982 }
983 return result->type_flags;
984}
985
Ryan Mitchell80094e32020-11-16 23:08:18 +0000986base::expected<AssetManager2::SelectedValue, NullOrIOError> AssetManager2::GetResource(
987 uint32_t resid, bool may_be_bag, uint16_t density_override) const {
988 auto result = FindEntry(resid, density_override, false /* stop_at_first_match */,
989 false /* ignore_configuration */);
990 if (!result.has_value()) {
991 return base::unexpected(result.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -0700992 }
993
Ryan Mitchell80094e32020-11-16 23:08:18 +0000994 auto result_map_entry = std::get_if<incfs::verified_map_ptr<ResTable_map_entry>>(&result->entry);
Ryan Mitchellbf1f45b2020-09-29 17:22:52 -0700995 if (result_map_entry != nullptr) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700996 if (!may_be_bag) {
997 LOG(ERROR) << base::StringPrintf("Resource %08x is a complex map type.", resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000998 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700999 }
Adam Lesinski0c405242017-01-13 20:47:26 -08001000
1001 // Create a reference since we can't represent this complex type as a Res_value.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001002 return SelectedValue(Res_value::TYPE_REFERENCE, resid, result->cookie, result->type_flags,
1003 resid, result->config);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001004 }
1005
Adam Lesinskida431a22016-12-29 16:08:16 -05001006 // Convert the package ID to the runtime assigned package ID.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001007 Res_value value = std::get<Res_value>(result->entry);
1008 result->dynamic_ref_table->lookupResourceValue(&value);
Adam Lesinskida431a22016-12-29 16:08:16 -05001009
Ryan Mitchell80094e32020-11-16 23:08:18 +00001010 return SelectedValue(value.dataType, value.data, result->cookie, result->type_flags,
1011 resid, result->config);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001012}
1013
Ryan Mitchell80094e32020-11-16 23:08:18 +00001014base::expected<std::monostate, NullOrIOError> AssetManager2::ResolveReference(
Ryan Mitchella45506e2020-11-16 23:08:18 +00001015 AssetManager2::SelectedValue& value, bool cache_value) const {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001016 if (value.type != Res_value::TYPE_REFERENCE || value.data == 0U) {
1017 // Not a reference. Nothing to do.
1018 return {};
Adam Lesinski0c405242017-01-13 20:47:26 -08001019 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001020
Ryan Mitchella45506e2020-11-16 23:08:18 +00001021 const uint32_t original_flags = value.flags;
1022 const uint32_t original_resid = value.data;
1023 if (cache_value) {
1024 auto cached_value = cached_resolved_values_.find(value.data);
1025 if (cached_value != cached_resolved_values_.end()) {
1026 value = cached_value->second;
1027 value.flags |= original_flags;
1028 return {};
1029 }
1030 }
1031
1032 uint32_t combined_flags = 0U;
1033 uint32_t resolve_resid = original_resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001034 constexpr const uint32_t kMaxIterations = 20;
1035 for (uint32_t i = 0U;; i++) {
1036 auto result = GetResource(resolve_resid, true /*may_be_bag*/);
1037 if (!result.has_value()) {
Ryan Mitchelle7ab6272020-11-13 18:06:15 -08001038 value.resid = resolve_resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001039 return base::unexpected(result.error());
1040 }
1041
Ryan Mitchelle7ab6272020-11-13 18:06:15 -08001042 // If resource resolution fails, the value should be set to the last reference that was able to
1043 // be resolved successfully.
1044 value = *result;
1045 value.flags |= combined_flags;
1046
Ryan Mitchell80094e32020-11-16 23:08:18 +00001047 if (result->type != Res_value::TYPE_REFERENCE ||
1048 result->data == Res_value::DATA_NULL_UNDEFINED ||
1049 result->data == resolve_resid || i == kMaxIterations) {
1050 // This reference can't be resolved, so exit now and let the caller deal with it.
Ryan Mitchella45506e2020-11-16 23:08:18 +00001051 if (cache_value) {
1052 cached_resolved_values_[original_resid] = value;
1053 }
1054
1055 // Above value is cached without original_flags to ensure they don't get included in future
1056 // queries that hit the cache
1057 value.flags |= original_flags;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001058 return {};
1059 }
1060
Ryan Mitchelle7ab6272020-11-13 18:06:15 -08001061 combined_flags = result->flags;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001062 resolve_resid = result->data;
1063 }
Adam Lesinski0c405242017-01-13 20:47:26 -08001064}
1065
Ryan Mitchell80094e32020-11-16 23:08:18 +00001066const std::vector<uint32_t> AssetManager2::GetBagResIdStack(uint32_t resid) const {
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001067 auto cached_iter = cached_bag_resid_stacks_.find(resid);
1068 if (cached_iter != cached_bag_resid_stacks_.end()) {
1069 return cached_iter->second;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001070 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001071
1072 std::vector<uint32_t> found_resids;
1073 GetBag(resid, found_resids);
1074 cached_bag_resid_stacks_.emplace(resid, found_resids);
1075 return found_resids;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001076}
1077
Ryan Mitchell80094e32020-11-16 23:08:18 +00001078base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::ResolveBag(
1079 AssetManager2::SelectedValue& value) const {
1080 if (UNLIKELY(value.type != Res_value::TYPE_REFERENCE)) {
1081 return base::unexpected(std::nullopt);
1082 }
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001083
Ryan Mitchell80094e32020-11-16 23:08:18 +00001084 auto bag = GetBag(value.data);
1085 if (bag.has_value()) {
1086 value.flags |= (*bag)->type_spec_flags;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001087 }
1088 return bag;
y57cd1952018-04-12 14:26:23 -07001089}
1090
Ryan Mitchell80094e32020-11-16 23:08:18 +00001091base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::GetBag(uint32_t resid) const {
1092 std::vector<uint32_t> found_resids;
1093 const auto bag = GetBag(resid, found_resids);
Yurii Zubrytskyiab3cb302022-10-11 12:15:52 -07001094 cached_bag_resid_stacks_.emplace(resid, std::move(found_resids));
Ryan Mitchell80094e32020-11-16 23:08:18 +00001095 return bag;
Ryan Mitchell155d5392020-02-10 13:35:24 -08001096}
1097
Ryan Mitchell80094e32020-11-16 23:08:18 +00001098base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::GetBag(
1099 uint32_t resid, std::vector<uint32_t>& child_resids) const {
1100 if (auto cached_iter = cached_bags_.find(resid); cached_iter != cached_bags_.end()) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001101 return cached_iter->second.get();
1102 }
1103
Ryan Mitchell80094e32020-11-16 23:08:18 +00001104 auto entry = FindEntry(resid, 0u /* density_override */, false /* stop_at_first_match */,
1105 false /* ignore_configuration */);
1106 if (!entry.has_value()) {
1107 return base::unexpected(entry.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001108 }
1109
Ryan Mitchell80094e32020-11-16 23:08:18 +00001110 auto entry_map = std::get_if<incfs::verified_map_ptr<ResTable_map_entry>>(&entry->entry);
1111 if (entry_map == nullptr) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001112 // Not a bag, nothing to do.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001113 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001114 }
1115
Ryan Mitchell80094e32020-11-16 23:08:18 +00001116 auto map = *entry_map;
1117 auto map_entry = map.offset(dtohs(map->size)).convert<ResTable_map>();
1118 const auto map_entry_end = map_entry + dtohl(map->count);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001119
y57cd1952018-04-12 14:26:23 -07001120 // Keep track of ids that have already been seen to prevent infinite loops caused by circular
Ryan Mitchell80094e32020-11-16 23:08:18 +00001121 // dependencies between bags.
y57cd1952018-04-12 14:26:23 -07001122 child_resids.push_back(resid);
1123
Adam Lesinskida431a22016-12-29 16:08:16 -05001124 uint32_t parent_resid = dtohl(map->parent.ident);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001125 if (parent_resid == 0U ||
1126 std::find(child_resids.begin(), child_resids.end(), parent_resid) != child_resids.end()) {
1127 // There is no parent or a circular parental dependency exist, meaning there is nothing to
1128 // inherit and we can do a simple copy of the entries in the map.
Adam Lesinski7ad11102016-10-28 16:39:15 -07001129 const size_t entry_count = map_entry_end - map_entry;
1130 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
1131 malloc(sizeof(ResolvedBag) + (entry_count * sizeof(ResolvedBag::Entry))))};
Ryan Mitchell155d5392020-02-10 13:35:24 -08001132
1133 bool sort_entries = false;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001134 for (auto new_entry = new_bag->entries; map_entry != map_entry_end; ++map_entry) {
1135 if (UNLIKELY(!map_entry)) {
1136 return base::unexpected(IOError::PAGES_MISSING);
1137 }
1138
Adam Lesinskida431a22016-12-29 16:08:16 -05001139 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001140 if (!is_internal_resid(new_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -05001141 // Attributes, arrays, etc don't have a resource id as the name. They specify
1142 // other data, which would be wrong to change via a lookup.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001143 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001144 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
1145 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001146 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001147 }
1148 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001149
1150 new_entry->cookie = entry->cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -05001151 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001152 new_entry->key_pool = nullptr;
1153 new_entry->type_pool = nullptr;
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001154 new_entry->style = resid;
Adam Lesinski30080e22017-10-16 16:18:09 -07001155 new_entry->value.copyFrom_dtoh(map_entry->value);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001156 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1157 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001158 LOG(ERROR) << base::StringPrintf(
1159 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
1160 new_entry->value.data, new_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001161 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001162 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001163
Ryan Mitchell155d5392020-02-10 13:35:24 -08001164 sort_entries = sort_entries ||
1165 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001166 ++new_entry;
1167 }
Ryan Mitchell155d5392020-02-10 13:35:24 -08001168
1169 if (sort_entries) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001170 std::sort(new_bag->entries, new_bag->entries + entry_count,
1171 [](auto&& lhs, auto&& rhs) { return lhs.key < rhs.key; });
Ryan Mitchell155d5392020-02-10 13:35:24 -08001172 }
1173
Ryan Mitchell80094e32020-11-16 23:08:18 +00001174 new_bag->type_spec_flags = entry->type_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001175 new_bag->entry_count = static_cast<uint32_t>(entry_count);
1176 ResolvedBag* result = new_bag.get();
1177 cached_bags_[resid] = std::move(new_bag);
1178 return result;
1179 }
1180
Adam Lesinskida431a22016-12-29 16:08:16 -05001181 // In case the parent is a dynamic reference, resolve it.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001182 entry->dynamic_ref_table->lookupResourceId(&parent_resid);
Adam Lesinskida431a22016-12-29 16:08:16 -05001183
Adam Lesinski7ad11102016-10-28 16:39:15 -07001184 // Get the parent and do a merge of the keys.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001185 const auto parent_bag = GetBag(parent_resid, child_resids);
1186 if (UNLIKELY(!parent_bag.has_value())) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001187 // Failed to get the parent that should exist.
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001188 LOG(ERROR) << base::StringPrintf("Failed to find parent 0x%08x of bag 0x%08x.", parent_resid,
1189 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001190 return base::unexpected(parent_bag.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001191 }
1192
Adam Lesinski7ad11102016-10-28 16:39:15 -07001193 // Create the max possible entries we can make. Once we construct the bag,
1194 // we will realloc to fit to size.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001195 const size_t max_count = (*parent_bag)->entry_count + dtohl(map->count);
George Burgess IV09b119f2017-07-25 15:00:04 -07001196 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
1197 malloc(sizeof(ResolvedBag) + (max_count * sizeof(ResolvedBag::Entry))))};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001198 ResolvedBag::Entry* new_entry = new_bag->entries;
1199
Ryan Mitchell80094e32020-11-16 23:08:18 +00001200 const ResolvedBag::Entry* parent_entry = (*parent_bag)->entries;
1201 const ResolvedBag::Entry* const parent_entry_end = parent_entry + (*parent_bag)->entry_count;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001202
1203 // The keys are expected to be in sorted order. Merge the two bags.
Ryan Mitchell155d5392020-02-10 13:35:24 -08001204 bool sort_entries = false;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001205 while (map_entry != map_entry_end && parent_entry != parent_entry_end) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001206 if (UNLIKELY(!map_entry)) {
1207 return base::unexpected(IOError::PAGES_MISSING);
1208 }
1209
Adam Lesinskida431a22016-12-29 16:08:16 -05001210 uint32_t child_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001211 if (!is_internal_resid(child_key)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001212 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&child_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001213 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", child_key,
1214 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001215 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001216 }
1217 }
1218
Adam Lesinski7ad11102016-10-28 16:39:15 -07001219 if (child_key <= parent_entry->key) {
1220 // Use the child key if it comes before the parent
1221 // or is equal to the parent (overrides).
Ryan Mitchell80094e32020-11-16 23:08:18 +00001222 new_entry->cookie = entry->cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001223 new_entry->key = child_key;
1224 new_entry->key_pool = nullptr;
1225 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -07001226 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001227 new_entry->style = resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001228 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1229 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001230 LOG(ERROR) << base::StringPrintf(
1231 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
1232 new_entry->value.data, child_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001233 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001234 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001235 ++map_entry;
1236 } else {
1237 // Take the parent entry as-is.
1238 memcpy(new_entry, parent_entry, sizeof(*new_entry));
1239 }
1240
Ryan Mitchell155d5392020-02-10 13:35:24 -08001241 sort_entries = sort_entries ||
1242 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001243 if (child_key >= parent_entry->key) {
1244 // Move to the next parent entry if we used it or it was overridden.
1245 ++parent_entry;
1246 }
1247 // Increment to the next entry to fill.
1248 ++new_entry;
1249 }
1250
1251 // Finish the child entries if they exist.
1252 while (map_entry != map_entry_end) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001253 if (UNLIKELY(!map_entry)) {
1254 return base::unexpected(IOError::PAGES_MISSING);
1255 }
1256
Adam Lesinskida431a22016-12-29 16:08:16 -05001257 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001258 if (!is_internal_resid(new_key)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001259 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001260 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
1261 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001262 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001263 }
1264 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001265 new_entry->cookie = entry->cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -05001266 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001267 new_entry->key_pool = nullptr;
1268 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -07001269 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001270 new_entry->style = resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001271 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1272 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001273 LOG(ERROR) << base::StringPrintf("Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.",
1274 new_entry->value.dataType, new_entry->value.data, new_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001275 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001276 }
Ryan Mitchell155d5392020-02-10 13:35:24 -08001277 sort_entries = sort_entries ||
1278 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001279 ++map_entry;
1280 ++new_entry;
1281 }
1282
1283 // Finish the parent entries if they exist.
1284 if (parent_entry != parent_entry_end) {
1285 // Take the rest of the parent entries as-is.
1286 const size_t num_entries_to_copy = parent_entry_end - parent_entry;
1287 memcpy(new_entry, parent_entry, num_entries_to_copy * sizeof(*new_entry));
1288 new_entry += num_entries_to_copy;
1289 }
1290
1291 // Resize the resulting array to fit.
1292 const size_t actual_count = new_entry - new_bag->entries;
1293 if (actual_count != max_count) {
George Burgess IV09b119f2017-07-25 15:00:04 -07001294 new_bag.reset(reinterpret_cast<ResolvedBag*>(realloc(
1295 new_bag.release(), sizeof(ResolvedBag) + (actual_count * sizeof(ResolvedBag::Entry)))));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001296 }
1297
Ryan Mitchell155d5392020-02-10 13:35:24 -08001298 if (sort_entries) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001299 std::sort(new_bag->entries, new_bag->entries + actual_count,
1300 [](auto&& lhs, auto&& rhs) { return lhs.key < rhs.key; });
Ryan Mitchell155d5392020-02-10 13:35:24 -08001301 }
1302
Adam Lesinski1a1e9c22017-10-13 15:45:34 -07001303 // Combine flags from the parent and our own bag.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001304 new_bag->type_spec_flags = entry->type_flags | (*parent_bag)->type_spec_flags;
George Burgess IV09b119f2017-07-25 15:00:04 -07001305 new_bag->entry_count = static_cast<uint32_t>(actual_count);
1306 ResolvedBag* result = new_bag.get();
1307 cached_bags_[resid] = std::move(new_bag);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001308 return result;
1309}
1310
Yurii Zubrytskyia5775142022-11-02 17:49:49 -07001311static bool Utf8ToUtf16(StringPiece str, std::u16string* out) {
Adam Lesinski929d6512017-01-16 19:11:19 -08001312 ssize_t len =
1313 utf8_to_utf16_length(reinterpret_cast<const uint8_t*>(str.data()), str.size(), false);
1314 if (len < 0) {
1315 return false;
1316 }
1317 out->resize(static_cast<size_t>(len));
1318 utf8_to_utf16(reinterpret_cast<const uint8_t*>(str.data()), str.size(), &*out->begin(),
1319 static_cast<size_t>(len + 1));
1320 return true;
1321}
1322
Ryan Mitchell80094e32020-11-16 23:08:18 +00001323base::expected<uint32_t, NullOrIOError> AssetManager2::GetResourceId(
1324 const std::string& resource_name, const std::string& fallback_type,
1325 const std::string& fallback_package) const {
Adam Lesinski929d6512017-01-16 19:11:19 -08001326 StringPiece package_name, type, entry;
1327 if (!ExtractResourceName(resource_name, &package_name, &type, &entry)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001328 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001329 }
1330
1331 if (entry.empty()) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001332 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001333 }
1334
1335 if (package_name.empty()) {
1336 package_name = fallback_package;
1337 }
1338
1339 if (type.empty()) {
1340 type = fallback_type;
1341 }
1342
1343 std::u16string type16;
1344 if (!Utf8ToUtf16(type, &type16)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001345 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001346 }
1347
1348 std::u16string entry16;
1349 if (!Utf8ToUtf16(entry, &entry16)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001350 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001351 }
1352
1353 const StringPiece16 kAttr16 = u"attr";
1354 const static std::u16string kAttrPrivate16 = u"^attr-private";
1355
1356 for (const PackageGroup& package_group : package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001357 for (const ConfiguredPackage& package_impl : package_group.packages_) {
1358 const LoadedPackage* package = package_impl.loaded_package_;
Adam Lesinski929d6512017-01-16 19:11:19 -08001359 if (package_name != package->GetPackageName()) {
1360 // All packages in the same group are expected to have the same package name.
1361 break;
1362 }
1363
Ryan Mitchell80094e32020-11-16 23:08:18 +00001364 base::expected<uint32_t, NullOrIOError> resid = package->FindEntryByName(type16, entry16);
1365 if (UNLIKELY(IsIOError(resid))) {
1366 return base::unexpected(resid.error());
1367 }
1368
1369 if (!resid.has_value() && kAttr16 == type16) {
Adam Lesinski929d6512017-01-16 19:11:19 -08001370 // Private attributes in libraries (such as the framework) are sometimes encoded
1371 // under the type '^attr-private' in order to leave the ID space of public 'attr'
1372 // free for future additions. Check '^attr-private' for the same name.
1373 resid = package->FindEntryByName(kAttrPrivate16, entry16);
1374 }
1375
Ryan Mitchell80094e32020-11-16 23:08:18 +00001376 if (resid.has_value()) {
1377 return fix_package_id(*resid, package_group.dynamic_ref_table->mAssignedPackageId);
Adam Lesinski929d6512017-01-16 19:11:19 -08001378 }
1379 }
1380 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001381 return base::unexpected(std::nullopt);
Adam Lesinski0c405242017-01-13 20:47:26 -08001382}
1383
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001384void AssetManager2::RebuildFilterList() {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001385 for (PackageGroup& group : package_groups_) {
Yurii Zubrytskyidbce3562022-11-14 22:26:10 -08001386 for (ConfiguredPackage& package : group.packages_) {
1387 package.filtered_configs_.forEachItem([](auto, auto& fcg) { fcg.type_entries.clear(); });
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001388 // Create the filters here.
Yurii Zubrytskyidbce3562022-11-14 22:26:10 -08001389 package.loaded_package_->ForEachTypeSpec([&](const TypeSpec& type_spec, uint8_t type_id) {
Yurii Zubrytskyi59dab3b2022-11-03 00:08:49 -07001390 FilteredConfigGroup* group = nullptr;
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001391 for (const auto& type_entry : type_spec.type_entries) {
1392 if (type_entry.config.match(configuration_)) {
Yurii Zubrytskyi59dab3b2022-11-03 00:08:49 -07001393 if (!group) {
Yurii Zubrytskyidbce3562022-11-14 22:26:10 -08001394 group = &package.filtered_configs_.editItemAt(type_id - 1);
Yurii Zubrytskyi59dab3b2022-11-03 00:08:49 -07001395 }
1396 group->type_entries.push_back(&type_entry);
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001397 }
1398 }
1399 });
Yurii Zubrytskyidbce3562022-11-14 22:26:10 -08001400 package.filtered_configs_.trimBuckets(
1401 [](const auto& fcg) { return fcg.type_entries.empty(); });
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001402 }
1403 }
1404}
1405
Adam Lesinski7ad11102016-10-28 16:39:15 -07001406void AssetManager2::InvalidateCaches(uint32_t diff) {
Ryan Mitchell2c4d8742019-03-04 09:41:00 -08001407 cached_bag_resid_stacks_.clear();
1408
Adam Lesinski7ad11102016-10-28 16:39:15 -07001409 if (diff == 0xffffffffu) {
1410 // Everything must go.
1411 cached_bags_.clear();
1412 return;
1413 }
1414
1415 // Be more conservative with what gets purged. Only if the bag has other possible
1416 // variations with respect to what changed (diff) should we remove it.
1417 for (auto iter = cached_bags_.cbegin(); iter != cached_bags_.cend();) {
1418 if (diff & iter->second->type_spec_flags) {
1419 iter = cached_bags_.erase(iter);
1420 } else {
1421 ++iter;
1422 }
1423 }
Ryan Mitchella45506e2020-11-16 23:08:18 +00001424
1425 cached_resolved_values_.clear();
Adam Lesinski7ad11102016-10-28 16:39:15 -07001426}
1427
Ryan Mitchell2e394222019-08-28 12:10:51 -07001428uint8_t AssetManager2::GetAssignedPackageId(const LoadedPackage* package) const {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001429 for (auto& package_group : package_groups_) {
1430 for (auto& package2 : package_group.packages_) {
1431 if (package2.loaded_package_ == package) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -07001432 return package_group.dynamic_ref_table->mAssignedPackageId;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001433 }
1434 }
1435 }
1436 return 0;
1437}
1438
Adam Lesinski30080e22017-10-16 16:18:09 -07001439std::unique_ptr<Theme> AssetManager2::NewTheme() {
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001440 constexpr size_t kInitialReserveSize = 32;
1441 auto theme = std::unique_ptr<Theme>(new Theme(this));
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001442 theme->keys_.reserve(kInitialReserveSize);
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001443 theme->entries_.reserve(kInitialReserveSize);
1444 return theme;
Adam Lesinski30080e22017-10-16 16:18:09 -07001445}
1446
Yurii Zubrytskyi9eb44c92022-11-14 23:44:52 -08001447void AssetManager2::ForEachPackage(base::function_ref<bool(const std::string&, uint8_t)> func,
1448 package_property_t excluded_property_flags) const {
1449 for (const PackageGroup& package_group : package_groups_) {
1450 const auto loaded_package = package_group.packages_.front().loaded_package_;
1451 if ((loaded_package->GetPropertyFlags() & excluded_property_flags) == 0U
1452 && !func(loaded_package->GetPackageName(),
1453 package_group.dynamic_ref_table->mAssignedPackageId)) {
1454 return;
1455 }
1456 }
1457}
1458
Adam Lesinski30080e22017-10-16 16:18:09 -07001459Theme::Theme(AssetManager2* asset_manager) : asset_manager_(asset_manager) {
1460}
1461
1462Theme::~Theme() = default;
1463
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001464struct Theme::Entry {
Adam Lesinski30080e22017-10-16 16:18:09 -07001465 ApkAssetsCookie cookie;
1466 uint32_t type_spec_flags;
1467 Res_value value;
1468};
1469
Ryan Mitchell80094e32020-11-16 23:08:18 +00001470base::expected<std::monostate, NullOrIOError> Theme::ApplyStyle(uint32_t resid, bool force) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001471 ATRACE_NAME("Theme::ApplyStyle");
Adam Lesinski7ad11102016-10-28 16:39:15 -07001472
Ryan Mitchell80094e32020-11-16 23:08:18 +00001473 auto bag = asset_manager_->GetBag(resid);
1474 if (!bag.has_value()) {
1475 return base::unexpected(bag.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001476 }
1477
1478 // Merge the flags from this style.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001479 type_spec_flags_ |= (*bag)->type_spec_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001480
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001481 for (auto it = begin(*bag); it != end(*bag); ++it) {
1482 const uint32_t attr_res_id = it->key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001483
Adam Lesinski30080e22017-10-16 16:18:09 -07001484 // If the resource ID passed in is not a style, the key can be some other identifier that is not
1485 // a resource ID. We should fail fast instead of operating with strange resource IDs.
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001486 if (!is_valid_resid(attr_res_id)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001487 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001488 }
1489
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001490 // DATA_NULL_EMPTY (@empty) is a valid resource value and DATA_NULL_UNDEFINED represents
1491 // an absence of a valid value.
1492 bool is_undefined = it->value.dataType == Res_value::TYPE_NULL &&
1493 it->value.data != Res_value::DATA_NULL_EMPTY;
1494 if (!force && is_undefined) {
1495 continue;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001496 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001497
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001498 const auto key_it = std::lower_bound(keys_.begin(), keys_.end(), attr_res_id);
1499 const auto entry_it = entries_.begin() + (key_it - keys_.begin());
1500 if (key_it != keys_.end() && *key_it == attr_res_id) {
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001501 if (is_undefined) {
1502 // DATA_NULL_UNDEFINED clears the value of the attribute in the theme only when `force` is
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001503 // true.
1504 keys_.erase(key_it);
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001505 entries_.erase(entry_it);
1506 } else if (force) {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001507 *entry_it = Entry{it->cookie, (*bag)->type_spec_flags, it->value};
Adam Lesinski30080e22017-10-16 16:18:09 -07001508 }
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001509 } else {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001510 keys_.insert(key_it, attr_res_id);
1511 entries_.insert(entry_it, Entry{it->cookie, (*bag)->type_spec_flags, it->value});
Adam Lesinski7ad11102016-10-28 16:39:15 -07001512 }
1513 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001514 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001515}
1516
Ryan Mitchell767e34f2021-06-07 12:29:05 -07001517void Theme::Rebase(AssetManager2* am, const uint32_t* style_ids, const uint8_t* force,
1518 size_t style_count) {
1519 ATRACE_NAME("Theme::Rebase");
1520 // Reset the entries without changing the vector capacity to prevent reallocations during
1521 // ApplyStyle.
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001522 keys_.clear();
Ryan Mitchell767e34f2021-06-07 12:29:05 -07001523 entries_.clear();
1524 asset_manager_ = am;
1525 for (size_t i = 0; i < style_count; i++) {
1526 ApplyStyle(style_ids[i], force[i]);
1527 }
1528}
1529
Ryan Mitchell80094e32020-11-16 23:08:18 +00001530std::optional<AssetManager2::SelectedValue> Theme::GetAttribute(uint32_t resid) const {
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001531 constexpr const uint32_t kMaxIterations = 20;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001532 uint32_t type_spec_flags = 0u;
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001533 for (uint32_t i = 0; i <= kMaxIterations; i++) {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001534 const auto key_it = std::lower_bound(keys_.begin(), keys_.end(), resid);
1535 if (key_it == keys_.end() || *key_it != resid) {
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001536 return std::nullopt;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001537 }
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001538 const auto entry_it = entries_.begin() + (key_it - keys_.begin());
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001539 type_spec_flags |= entry_it->type_spec_flags;
1540 if (entry_it->value.dataType == Res_value::TYPE_ATTRIBUTE) {
1541 resid = entry_it->value.data;
1542 continue;
1543 }
1544
1545 return AssetManager2::SelectedValue(entry_it->value.dataType, entry_it->value.data,
1546 entry_it->cookie, type_spec_flags, 0U /* resid */,
1547 {} /* config */);
1548 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001549 return std::nullopt;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001550}
1551
Ryan Mitchell80094e32020-11-16 23:08:18 +00001552base::expected<std::monostate, NullOrIOError> Theme::ResolveAttributeReference(
1553 AssetManager2::SelectedValue& value) const {
1554 if (value.type != Res_value::TYPE_ATTRIBUTE) {
1555 return asset_manager_->ResolveReference(value);
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001556 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001557
1558 std::optional<AssetManager2::SelectedValue> result = GetAttribute(value.data);
1559 if (!result.has_value()) {
1560 return base::unexpected(std::nullopt);
1561 }
1562
Ryan Mitchella45506e2020-11-16 23:08:18 +00001563 auto resolve_result = asset_manager_->ResolveReference(*result, true /* cache_value */);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001564 if (resolve_result.has_value()) {
1565 result->flags |= value.flags;
1566 value = *result;
1567 }
1568 return resolve_result;
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001569}
1570
Adam Lesinski7ad11102016-10-28 16:39:15 -07001571void Theme::Clear() {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001572 keys_.clear();
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001573 entries_.clear();
Adam Lesinski7ad11102016-10-28 16:39:15 -07001574}
1575
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001576base::expected<std::monostate, IOError> Theme::SetTo(const Theme& source) {
1577 if (this == &source) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001578 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001579 }
1580
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001581 type_spec_flags_ = source.type_spec_flags_;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001582
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001583 if (asset_manager_ == source.asset_manager_) {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001584 keys_ = source.keys_;
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001585 entries_ = source.entries_;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001586 } else {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001587 std::unordered_map<ApkAssetsCookie, ApkAssetsCookie> src_to_dest_asset_cookies;
1588 using SourceToDestinationRuntimePackageMap = std::unordered_map<int, int>;
1589 std::unordered_map<ApkAssetsCookie, SourceToDestinationRuntimePackageMap> src_asset_cookie_id_map;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001590
Ryan Mitchell93bca972019-03-08 17:26:28 -08001591 // Determine which ApkAssets are loaded in both theme AssetManagers.
Yurii Zubrytskyia5bc9582022-11-30 23:53:59 -08001592 const auto& src_assets = source.asset_manager_->GetApkAssets();
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001593 for (size_t i = 0; i < src_assets.size(); i++) {
Yurii Zubrytskyic357f712023-04-13 02:32:45 -07001594 auto src_asset = src_assets[i].promote();
1595 if (!src_asset) {
1596 continue;
1597 }
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001598
Yurii Zubrytskyia5bc9582022-11-30 23:53:59 -08001599 const auto& dest_assets = asset_manager_->GetApkAssets();
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001600 for (size_t j = 0; j < dest_assets.size(); j++) {
Yurii Zubrytskyic357f712023-04-13 02:32:45 -07001601 auto dest_asset = dest_assets[j].promote();
Ryan Mitchellef538432021-03-01 14:52:14 -08001602 if (src_asset != dest_asset) {
1603 // ResourcesManager caches and reuses ApkAssets when the same apk must be present in
1604 // multiple AssetManagers. Two ApkAssets point to the same version of the same resources
1605 // if they are the same instance.
1606 continue;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001607 }
Ryan Mitchellef538432021-03-01 14:52:14 -08001608
1609 // Map the package ids of the asset in the source AssetManager to the package ids of the
1610 // asset in th destination AssetManager.
1611 SourceToDestinationRuntimePackageMap package_map;
1612 for (const auto& loaded_package : src_asset->GetLoadedArsc()->GetPackages()) {
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001613 const int src_package_id = source.asset_manager_->GetAssignedPackageId(
1614 loaded_package.get());
Ryan Mitchellef538432021-03-01 14:52:14 -08001615 const int dest_package_id = asset_manager_->GetAssignedPackageId(loaded_package.get());
1616 package_map[src_package_id] = dest_package_id;
1617 }
1618
1619 src_to_dest_asset_cookies.insert(std::make_pair(i, j));
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001620 src_asset_cookie_id_map.insert(std::make_pair(i, std::move(package_map)));
Ryan Mitchellef538432021-03-01 14:52:14 -08001621 break;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001622 }
1623 }
1624
Ryan Mitchell93bca972019-03-08 17:26:28 -08001625 // Reset the data in the destination theme.
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001626 keys_.clear();
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001627 entries_.clear();
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001628
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001629 for (size_t i = 0, size = source.entries_.size(); i != size; ++i) {
1630 const auto& entry = source.entries_[i];
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001631 bool is_reference = (entry.value.dataType == Res_value::TYPE_ATTRIBUTE
1632 || entry.value.dataType == Res_value::TYPE_REFERENCE
1633 || entry.value.dataType == Res_value::TYPE_DYNAMIC_ATTRIBUTE
1634 || entry.value.dataType == Res_value::TYPE_DYNAMIC_REFERENCE)
1635 && entry.value.data != 0x0;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001636
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001637 // If the attribute value represents an attribute or reference, the package id of the
1638 // value needs to be rewritten to the package id of the value in the destination.
1639 uint32_t attribute_data = entry.value.data;
1640 if (is_reference) {
1641 // Determine the package id of the reference in the destination AssetManager.
1642 auto value_package_map = src_asset_cookie_id_map.find(entry.cookie);
1643 if (value_package_map == src_asset_cookie_id_map.end()) {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001644 continue;
1645 }
1646
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001647 auto value_dest_package = value_package_map->second.find(
1648 get_package_id(entry.value.data));
1649 if (value_dest_package == value_package_map->second.end()) {
1650 continue;
1651 }
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001652
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001653 attribute_data = fix_package_id(entry.value.data, value_dest_package->second);
1654 }
Ryan Mitchellb85d9b22018-11-19 12:11:38 -08001655
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001656 // Find the cookie of the value in the destination. If the source apk is not loaded in the
1657 // destination, only copy resources that do not reference resources in the source.
1658 ApkAssetsCookie data_dest_cookie;
1659 auto value_dest_cookie = src_to_dest_asset_cookies.find(entry.cookie);
1660 if (value_dest_cookie != src_to_dest_asset_cookies.end()) {
1661 data_dest_cookie = value_dest_cookie->second;
1662 } else {
1663 if (is_reference || entry.value.dataType == Res_value::TYPE_STRING) {
1664 continue;
1665 } else {
1666 data_dest_cookie = 0x0;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001667 }
1668 }
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001669
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001670 const auto source_res_id = source.keys_[i];
1671
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001672 // The package id of the attribute needs to be rewritten to the package id of the
1673 // attribute in the destination.
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001674 int attribute_dest_package_id = get_package_id(source_res_id);
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001675 if (attribute_dest_package_id != 0x01) {
1676 // Find the cookie of the attribute resource id in the source AssetManager
1677 base::expected<FindEntryResult, NullOrIOError> attribute_entry_result =
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001678 source.asset_manager_->FindEntry(source_res_id, 0 /* density_override */ ,
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001679 true /* stop_at_first_match */,
1680 true /* ignore_configuration */);
1681 if (UNLIKELY(IsIOError(attribute_entry_result))) {
1682 return base::unexpected(GetIOError(attribute_entry_result.error()));
1683 }
1684 if (!attribute_entry_result.has_value()) {
1685 continue;
1686 }
1687
1688 // Determine the package id of the attribute in the destination AssetManager.
1689 auto attribute_package_map = src_asset_cookie_id_map.find(
1690 attribute_entry_result->cookie);
1691 if (attribute_package_map == src_asset_cookie_id_map.end()) {
1692 continue;
1693 }
1694 auto attribute_dest_package = attribute_package_map->second.find(
1695 attribute_dest_package_id);
1696 if (attribute_dest_package == attribute_package_map->second.end()) {
1697 continue;
1698 }
1699 attribute_dest_package_id = attribute_dest_package->second;
1700 }
1701
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001702 auto dest_attr_id = make_resid(attribute_dest_package_id, get_type_id(source_res_id),
1703 get_entry_id(source_res_id));
1704 const auto key_it = std::lower_bound(keys_.begin(), keys_.end(), dest_attr_id);
1705 const auto entry_it = entries_.begin() + (key_it - keys_.begin());
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001706 // Since the entries were cleared, the attribute resource id has yet been mapped to any value.
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001707 keys_.insert(key_it, dest_attr_id);
1708 entries_.insert(entry_it, Entry{data_dest_cookie, entry.type_spec_flags,
1709 Res_value{.dataType = entry.value.dataType,
1710 .data = attribute_data}});
Adam Lesinski7ad11102016-10-28 16:39:15 -07001711 }
1712 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001713 return {};
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001714}
1715
1716void Theme::Dump() const {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001717 LOG(INFO) << base::StringPrintf("Theme(this=%p, AssetManager2=%p)", this, asset_manager_);
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001718 for (size_t i = 0, size = keys_.size(); i != size; ++i) {
1719 auto res_id = keys_[i];
1720 const auto& entry = entries_[i];
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001721 LOG(INFO) << base::StringPrintf(" entry(0x%08x)=(0x%08x) type=(0x%02x), cookie(%d)",
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001722 res_id, entry.value.data, entry.value.dataType,
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001723 entry.cookie);
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001724 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001725}
1726
1727} // namespace android