blob: bc46cf5a98ce8acfbef1e5c11043ed33882d9e3f [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
Ryan Mitchellb894c272020-02-12 10:31:44 -080094AssetManager2::AssetManager2() {
Adam Lesinski970bd8d2017-09-25 13:21:55 -070095 memset(&configuration_, 0, sizeof(configuration_));
96}
Adam Lesinski7ad11102016-10-28 16:39:15 -070097
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -080098bool AssetManager2::SetApkAssets(std::vector<const ApkAssets*> apk_assets, bool invalidate_caches) {
99 apk_assets_ = std::move(apk_assets);
Adam Lesinskida431a22016-12-29 16:08:16 -0500100 BuildDynamicRefTable();
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800101 RebuildFilterList();
Adam Lesinski7ad11102016-10-28 16:39:15 -0700102 if (invalidate_caches) {
103 InvalidateCaches(static_cast<uint32_t>(-1));
104 }
105 return true;
106}
107
Adam Lesinskida431a22016-12-29 16:08:16 -0500108void AssetManager2::BuildDynamicRefTable() {
109 package_groups_.clear();
110 package_ids_.fill(0xff);
111
Ryan Mitchellef538432021-03-01 14:52:14 -0800112 // A mapping from path of apk assets that could be target packages of overlays to the runtime
113 // package id of its first loaded package. Overlays currently can only override resources in the
114 // first package in the target resource table.
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800115 std::unordered_map<std::string_view, uint8_t> target_assets_package_ids;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700116
Ryan Mitchell824cc492020-02-12 10:48:14 -0800117 // Overlay resources are not directly referenced by an application so their resource ids
118 // can change throughout the application's lifetime. Assign overlay package ids last.
119 std::vector<const ApkAssets*> sorted_apk_assets(apk_assets_);
120 std::stable_partition(sorted_apk_assets.begin(), sorted_apk_assets.end(), [](const ApkAssets* a) {
121 return !a->IsOverlay();
122 });
123
124 // The assets cookie must map to the position of the apk assets in the unsorted apk assets list.
125 std::unordered_map<const ApkAssets*, ApkAssetsCookie> apk_assets_cookies;
126 apk_assets_cookies.reserve(apk_assets_.size());
127 for (size_t i = 0, n = apk_assets_.size(); i < n; i++) {
128 apk_assets_cookies[apk_assets_[i]] = static_cast<ApkAssetsCookie>(i);
129 }
130
Ryan Mitchellb894c272020-02-12 10:31:44 -0800131 // 0x01 is reserved for the android package.
132 int next_package_id = 0x02;
Ryan Mitchell824cc492020-02-12 10:48:14 -0800133 for (const ApkAssets* apk_assets : sorted_apk_assets) {
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800134 std::shared_ptr<OverlayDynamicRefTable> overlay_ref_table;
135 if (auto loaded_idmap = apk_assets->GetLoadedIdmap(); loaded_idmap != nullptr) {
136 // The target package must precede the overlay package in the apk assets paths in order
137 // to take effect.
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800138 auto iter = target_assets_package_ids.find(loaded_idmap->TargetApkPath());
Ryan Mitchellef538432021-03-01 14:52:14 -0800139 if (iter == target_assets_package_ids.end()) {
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800140 LOG(INFO) << "failed to find target package for overlay "
141 << loaded_idmap->OverlayApkPath();
142 } else {
143 uint8_t target_package_id = iter->second;
144
145 // Create a special dynamic reference table for the overlay to rewrite references to
146 // overlay resources as references to the target resources they overlay.
147 overlay_ref_table = std::make_shared<OverlayDynamicRefTable>(
148 loaded_idmap->GetOverlayDynamicRefTable(target_package_id));
149
150 // Add the overlay resource map to the target package's set of overlays.
151 const uint8_t target_idx = package_ids_[target_package_id];
152 CHECK(target_idx != 0xff) << "overlay target '" << loaded_idmap->TargetApkPath()
153 << "'added to apk_assets_package_ids but does not have an"
154 << " assigned package group";
155
156 PackageGroup& target_package_group = package_groups_[target_idx];
157 target_package_group.overlays_.push_back(
158 ConfiguredOverlay{loaded_idmap->GetTargetResourcesMap(target_package_id,
159 overlay_ref_table.get()),
160 apk_assets_cookies[apk_assets]});
161 }
162 }
163
Ryan Mitchellb894c272020-02-12 10:31:44 -0800164 const LoadedArsc* loaded_arsc = apk_assets->GetLoadedArsc();
Ryan Mitchellb894c272020-02-12 10:31:44 -0800165 for (const std::unique_ptr<const LoadedPackage>& package : loaded_arsc->GetPackages()) {
166 // Get the package ID or assign one if a shared library.
167 int package_id;
168 if (package->IsDynamic()) {
169 package_id = next_package_id++;
170 } else {
171 package_id = package->GetPackageId();
Adam Lesinskida431a22016-12-29 16:08:16 -0500172 }
173
Adam Lesinskida431a22016-12-29 16:08:16 -0500174 uint8_t idx = package_ids_[package_id];
175 if (idx == 0xff) {
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800176 // Add the mapping for package ID to index if not present.
Adam Lesinskida431a22016-12-29 16:08:16 -0500177 package_ids_[package_id] = idx = static_cast<uint8_t>(package_groups_.size());
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800178 PackageGroup& new_group = package_groups_.emplace_back();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700179
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800180 if (overlay_ref_table != nullptr) {
181 // If this package is from an overlay, use a dynamic reference table that can rewrite
182 // overlay resource ids to their corresponding target resource ids.
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800183 new_group.dynamic_ref_table = std::move(overlay_ref_table);
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700184 }
185
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800186 DynamicRefTable* ref_table = new_group.dynamic_ref_table.get();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700187 ref_table->mAssignedPackageId = package_id;
188 ref_table->mAppAsLib = package->IsDynamic() && package->GetPackageId() == 0x7f;
Adam Lesinskida431a22016-12-29 16:08:16 -0500189 }
Adam Lesinskida431a22016-12-29 16:08:16 -0500190
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800191 // Add the package to the set of packages with the same ID.
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800192 PackageGroup* package_group = &package_groups_[idx];
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800193 package_group->packages_.emplace_back().loaded_package_ = package.get();
Ryan Mitchell824cc492020-02-12 10:48:14 -0800194 package_group->cookies_.push_back(apk_assets_cookies[apk_assets]);
Adam Lesinskida431a22016-12-29 16:08:16 -0500195
196 // Add the package name -> build time ID mappings.
197 for (const DynamicPackageEntry& entry : package->GetDynamicPackageMap()) {
198 String16 package_name(entry.package_name.c_str(), entry.package_name.size());
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700199 package_group->dynamic_ref_table->mEntries.replaceValueFor(
Adam Lesinskida431a22016-12-29 16:08:16 -0500200 package_name, static_cast<uint8_t>(entry.package_id));
201 }
Ryan Mitchellb894c272020-02-12 10:31:44 -0800202
Ryan Mitchellef538432021-03-01 14:52:14 -0800203 if (auto apk_assets_path = apk_assets->GetPath()) {
204 // Overlay target ApkAssets must have been created using path based load apis.
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800205 target_assets_package_ids.emplace(*apk_assets_path, package_id);
Ryan Mitchellef538432021-03-01 14:52:14 -0800206 }
Adam Lesinskida431a22016-12-29 16:08:16 -0500207 }
208 }
209
210 // Now assign the runtime IDs so that we have a build-time to runtime ID map.
Yurii Zubrytskyi59dab3b2022-11-03 00:08:49 -0700211 DynamicRefTable::AliasMap aliases;
212 for (const auto& group : package_groups_) {
213 const std::string& package_name = group.packages_[0].loaded_package_->GetPackageName();
214 const auto name_16 = String16(package_name.c_str(), package_name.size());
215 for (auto&& inner_group : package_groups_) {
216 inner_group.dynamic_ref_table->addMapping(name_16,
217 group.dynamic_ref_table->mAssignedPackageId);
Adam Lesinskida431a22016-12-29 16:08:16 -0500218 }
Yurii Zubrytskyi59dab3b2022-11-03 00:08:49 -0700219
220 for (const auto& package : group.packages_) {
221 const auto& package_aliases = package.loaded_package_->GetAliasResourceIdMap();
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800222 aliases.insert(aliases.end(), package_aliases.begin(), package_aliases.end());
Yurii Zubrytskyi59dab3b2022-11-03 00:08:49 -0700223 }
224 }
225
226 if (!aliases.empty()) {
Yurii Zubrytskyie3f9be62022-11-14 18:30:10 -0800227 std::sort(aliases.begin(), aliases.end(), [](auto&& l, auto&& r) { return l.first < r.first; });
228
Yurii Zubrytskyi59dab3b2022-11-03 00:08:49 -0700229 // Add the alias resources to the dynamic reference table of every package group. Since
230 // staging aliases can only be defined by the framework package (which is not a shared
231 // library), the compile-time package id of the framework is the same across all packages
232 // that compile against the framework.
233 for (auto& group : std::span(package_groups_.data(), package_groups_.size() - 1)) {
234 group.dynamic_ref_table->setAliases(aliases);
235 }
236 package_groups_.back().dynamic_ref_table->setAliases(std::move(aliases));
Adam Lesinskida431a22016-12-29 16:08:16 -0500237 }
238}
239
240void AssetManager2::DumpToLog() const {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800241 LOG(INFO) << base::StringPrintf("AssetManager2(this=%p)", this);
242
Adam Lesinskida431a22016-12-29 16:08:16 -0500243 std::string list;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800244 for (const auto& apk_assets : apk_assets_) {
Ryan Mitchellef538432021-03-01 14:52:14 -0800245 base::StringAppendF(&list, "%s,", apk_assets->GetDebugName().c_str());
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800246 }
247 LOG(INFO) << "ApkAssets: " << list;
248
249 list = "";
Adam Lesinskida431a22016-12-29 16:08:16 -0500250 for (size_t i = 0; i < package_ids_.size(); i++) {
251 if (package_ids_[i] != 0xff) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800252 base::StringAppendF(&list, "%02x -> %d, ", (int)i, package_ids_[i]);
Adam Lesinskida431a22016-12-29 16:08:16 -0500253 }
254 }
255 LOG(INFO) << "Package ID map: " << list;
256
Adam Lesinski0dd36992018-01-25 15:38:38 -0800257 for (const auto& package_group: package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800258 list = "";
259 for (const auto& package : package_group.packages_) {
260 const LoadedPackage* loaded_package = package.loaded_package_;
261 base::StringAppendF(&list, "%s(%02x%s), ", loaded_package->GetPackageName().c_str(),
262 loaded_package->GetPackageId(),
263 (loaded_package->IsDynamic() ? " dynamic" : ""));
264 }
265 LOG(INFO) << base::StringPrintf("PG (%02x): ",
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700266 package_group.dynamic_ref_table->mAssignedPackageId)
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800267 << list;
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800268
269 for (size_t i = 0; i < 256; i++) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700270 if (package_group.dynamic_ref_table->mLookupTable[i] != 0) {
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800271 LOG(INFO) << base::StringPrintf(" e[0x%02x] -> 0x%02x", (uint8_t) i,
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700272 package_group.dynamic_ref_table->mLookupTable[i]);
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800273 }
274 }
Adam Lesinskida431a22016-12-29 16:08:16 -0500275 }
276}
Adam Lesinski7ad11102016-10-28 16:39:15 -0700277
278const ResStringPool* AssetManager2::GetStringPoolForCookie(ApkAssetsCookie cookie) const {
279 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
280 return nullptr;
281 }
282 return apk_assets_[cookie]->GetLoadedArsc()->GetStringPool();
283}
284
Adam Lesinskida431a22016-12-29 16:08:16 -0500285const DynamicRefTable* AssetManager2::GetDynamicRefTableForPackage(uint32_t package_id) const {
286 if (package_id >= package_ids_.size()) {
287 return nullptr;
288 }
289
290 const size_t idx = package_ids_[package_id];
291 if (idx == 0xff) {
292 return nullptr;
293 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700294 return package_groups_[idx].dynamic_ref_table.get();
Adam Lesinskida431a22016-12-29 16:08:16 -0500295}
296
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700297std::shared_ptr<const DynamicRefTable> AssetManager2::GetDynamicRefTableForCookie(
298 ApkAssetsCookie cookie) const {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800299 for (const PackageGroup& package_group : package_groups_) {
300 for (const ApkAssetsCookie& package_cookie : package_group.cookies_) {
301 if (package_cookie == cookie) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700302 return package_group.dynamic_ref_table;
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800303 }
304 }
305 }
306 return nullptr;
307}
308
MÃ¥rten Kongstadc92c4dd2019-02-05 01:29:59 +0100309const std::unordered_map<std::string, std::string>*
310 AssetManager2::GetOverlayableMapForPackage(uint32_t package_id) const {
311
312 if (package_id >= package_ids_.size()) {
313 return nullptr;
314 }
315
316 const size_t idx = package_ids_[package_id];
317 if (idx == 0xff) {
318 return nullptr;
319 }
320
321 const PackageGroup& package_group = package_groups_[idx];
Ryan Mitchell80094e32020-11-16 23:08:18 +0000322 if (package_group.packages_.empty()) {
MÃ¥rten Kongstadc92c4dd2019-02-05 01:29:59 +0100323 return nullptr;
324 }
325
326 const auto loaded_package = package_group.packages_[0].loaded_package_;
327 return &loaded_package->GetOverlayableMap();
328}
329
Yurii Zubrytskyia5775142022-11-02 17:49:49 -0700330bool AssetManager2::GetOverlayablesToString(android::StringPiece package_name,
Ryan Mitchell2e394222019-08-28 12:10:51 -0700331 std::string* out) const {
332 uint8_t package_id = 0U;
333 for (const auto& apk_assets : apk_assets_) {
334 const LoadedArsc* loaded_arsc = apk_assets->GetLoadedArsc();
335 if (loaded_arsc == nullptr) {
336 continue;
337 }
338
339 const auto& loaded_packages = loaded_arsc->GetPackages();
340 if (loaded_packages.empty()) {
341 continue;
342 }
343
344 const auto& loaded_package = loaded_packages[0];
345 if (loaded_package->GetPackageName() == package_name) {
346 package_id = GetAssignedPackageId(loaded_package.get());
347 break;
348 }
349 }
350
351 if (package_id == 0U) {
352 ANDROID_LOG(ERROR) << base::StringPrintf("No package with name '%s", package_name.data());
353 return false;
354 }
355
356 const size_t idx = package_ids_[package_id];
357 if (idx == 0xff) {
358 return false;
359 }
360
361 std::string output;
362 for (const ConfiguredPackage& package : package_groups_[idx].packages_) {
363 const LoadedPackage* loaded_package = package.loaded_package_;
364 for (auto it = loaded_package->begin(); it != loaded_package->end(); it++) {
365 const OverlayableInfo* info = loaded_package->GetOverlayableInfo(*it);
366 if (info != nullptr) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000367 auto res_name = GetResourceName(*it);
368 if (!res_name.has_value()) {
Ryan Mitchell2e394222019-08-28 12:10:51 -0700369 ANDROID_LOG(ERROR) << base::StringPrintf(
370 "Unable to retrieve name of overlayable resource 0x%08x", *it);
371 return false;
372 }
373
Ryan Mitchell80094e32020-11-16 23:08:18 +0000374 const std::string name = ToFormattedResourceString(*res_name);
Ryan Mitchell2e394222019-08-28 12:10:51 -0700375 output.append(base::StringPrintf(
376 "resource='%s' overlayable='%s' actor='%s' policy='0x%08x'\n",
Yurii Zubrytskyi9d225372022-11-29 11:12:18 -0800377 name.c_str(), info->name.data(), info->actor.data(), info->policy_flags));
Ryan Mitchell2e394222019-08-28 12:10:51 -0700378 }
379 }
380 }
381
382 *out = std::move(output);
383 return true;
384}
385
Ryan Mitchell192400c2020-04-02 09:54:23 -0700386bool AssetManager2::ContainsAllocatedTable() const {
387 return std::find_if(apk_assets_.begin(), apk_assets_.end(),
388 std::mem_fn(&ApkAssets::IsTableAllocated)) != apk_assets_.end();
389}
390
Adam Lesinski7ad11102016-10-28 16:39:15 -0700391void AssetManager2::SetConfiguration(const ResTable_config& configuration) {
392 const int diff = configuration_.diff(configuration);
393 configuration_ = configuration;
394
395 if (diff) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800396 RebuildFilterList();
Adam Lesinski7ad11102016-10-28 16:39:15 -0700397 InvalidateCaches(static_cast<uint32_t>(diff));
398 }
399}
400
Ryan Mitchellef538432021-03-01 14:52:14 -0800401std::set<const ApkAssets*> AssetManager2::GetNonSystemOverlays() const {
402 std::set<const ApkAssets*> non_system_overlays;
Adam Lesinski0c405242017-01-13 20:47:26 -0800403 for (const PackageGroup& package_group : package_groups_) {
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800404 bool found_system_package = false;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800405 for (const ConfiguredPackage& package : package_group.packages_) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700406 if (package.loaded_package_->IsSystem()) {
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800407 found_system_package = true;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700408 break;
409 }
410 }
411
412 if (!found_system_package) {
413 for (const ConfiguredOverlay& overlay : package_group.overlays_) {
Ryan Mitchellef538432021-03-01 14:52:14 -0800414 non_system_overlays.insert(apk_assets_[overlay.cookie]);
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700415 }
416 }
417 }
418
419 return non_system_overlays;
420}
421
Ryan Mitchell80094e32020-11-16 23:08:18 +0000422base::expected<std::set<ResTable_config>, IOError> AssetManager2::GetResourceConfigurations(
423 bool exclude_system, bool exclude_mipmap) const {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700424 ATRACE_NAME("AssetManager::GetResourceConfigurations");
425 const auto non_system_overlays =
Ryan Mitchellef538432021-03-01 14:52:14 -0800426 (exclude_system) ? GetNonSystemOverlays() : std::set<const ApkAssets*>();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700427
428 std::set<ResTable_config> configurations;
429 for (const PackageGroup& package_group : package_groups_) {
430 for (size_t i = 0; i < package_group.packages_.size(); i++) {
431 const ConfiguredPackage& package = package_group.packages_[i];
432 if (exclude_system && package.loaded_package_->IsSystem()) {
Adam Lesinski0c405242017-01-13 20:47:26 -0800433 continue;
434 }
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800435
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700436 auto apk_assets = apk_assets_[package_group.cookies_[i]];
Ryan Mitchellef538432021-03-01 14:52:14 -0800437 if (exclude_system && apk_assets->IsOverlay() &&
438 non_system_overlays.find(apk_assets) == non_system_overlays.end()) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700439 // Exclude overlays that target system resources.
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800440 continue;
441 }
442
Ryan Mitchell80094e32020-11-16 23:08:18 +0000443 auto result = package.loaded_package_->CollectConfigurations(exclude_mipmap, &configurations);
444 if (UNLIKELY(!result.has_value())) {
445 return base::unexpected(result.error());
446 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800447 }
448 }
449 return configurations;
450}
451
452std::set<std::string> AssetManager2::GetResourceLocales(bool exclude_system,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800453 bool merge_equivalent_languages) const {
454 ATRACE_NAME("AssetManager::GetResourceLocales");
Adam Lesinski0c405242017-01-13 20:47:26 -0800455 std::set<std::string> locales;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700456 const auto non_system_overlays =
Ryan Mitchellef538432021-03-01 14:52:14 -0800457 (exclude_system) ? GetNonSystemOverlays() : std::set<const ApkAssets*>();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700458
Adam Lesinski0c405242017-01-13 20:47:26 -0800459 for (const PackageGroup& package_group : package_groups_) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700460 for (size_t i = 0; i < package_group.packages_.size(); i++) {
461 const ConfiguredPackage& package = package_group.packages_[i];
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800462 if (exclude_system && package.loaded_package_->IsSystem()) {
Adam Lesinski0c405242017-01-13 20:47:26 -0800463 continue;
464 }
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800465
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700466 auto apk_assets = apk_assets_[package_group.cookies_[i]];
Ryan Mitchellef538432021-03-01 14:52:14 -0800467 if (exclude_system && apk_assets->IsOverlay() &&
468 non_system_overlays.find(apk_assets) == non_system_overlays.end()) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700469 // Exclude overlays that target system resources.
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800470 continue;
471 }
472
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800473 package.loaded_package_->CollectLocales(merge_equivalent_languages, &locales);
Adam Lesinski0c405242017-01-13 20:47:26 -0800474 }
475 }
476 return locales;
477}
478
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800479std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename,
480 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700481 const std::string new_path = "assets/" + filename;
482 return OpenNonAsset(new_path, mode);
483}
484
485std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename, ApkAssetsCookie cookie,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800486 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700487 const std::string new_path = "assets/" + filename;
488 return OpenNonAsset(new_path, cookie, mode);
489}
490
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800491std::unique_ptr<AssetDir> AssetManager2::OpenDir(const std::string& dirname) const {
492 ATRACE_NAME("AssetManager::OpenDir");
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800493
494 std::string full_path = "assets/" + dirname;
495 std::unique_ptr<SortedVector<AssetDir::FileInfo>> files =
496 util::make_unique<SortedVector<AssetDir::FileInfo>>();
497
498 // Start from the back.
499 for (auto iter = apk_assets_.rbegin(); iter != apk_assets_.rend(); ++iter) {
500 const ApkAssets* apk_assets = *iter;
MÃ¥rten Kongstaddbf343b2019-02-21 07:54:18 +0100501 if (apk_assets->IsOverlay()) {
502 continue;
503 }
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800504
Yurii Zubrytskyia5775142022-11-02 17:49:49 -0700505 auto func = [&](StringPiece name, FileType type) {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800506 AssetDir::FileInfo info;
507 info.setFileName(String8(name.data(), name.size()));
508 info.setFileType(type);
Ryan Mitchellef538432021-03-01 14:52:14 -0800509 info.setSourceName(String8(apk_assets->GetDebugName().c_str()));
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800510 files->add(info);
511 };
512
Ryan Mitchellc07aa702020-03-10 13:49:12 -0700513 if (!apk_assets->GetAssetsProvider()->ForEachFile(full_path, func)) {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800514 return {};
515 }
516 }
517
518 std::unique_ptr<AssetDir> asset_dir = util::make_unique<AssetDir>();
519 asset_dir->setFileList(files.release());
520 return asset_dir;
521}
522
Adam Lesinski7ad11102016-10-28 16:39:15 -0700523// Search in reverse because that's how we used to do it and we need to preserve behaviour.
524// This is unfortunate, because ClassLoaders delegate to the parent first, so the order
525// is inconsistent for split APKs.
526std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
527 Asset::AccessMode mode,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800528 ApkAssetsCookie* out_cookie) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700529 for (int32_t i = apk_assets_.size() - 1; i >= 0; i--) {
MÃ¥rten Kongstaddbf343b2019-02-21 07:54:18 +0100530 // Prevent RRO from modifying assets and other entries accessed by file
531 // path. Explicitly asking for a path in a given package (denoted by a
532 // cookie) is still OK.
533 if (apk_assets_[i]->IsOverlay()) {
534 continue;
535 }
536
Ryan Mitchellc07aa702020-03-10 13:49:12 -0700537 std::unique_ptr<Asset> asset = apk_assets_[i]->GetAssetsProvider()->Open(filename, mode);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700538 if (asset) {
539 if (out_cookie != nullptr) {
540 *out_cookie = i;
541 }
542 return asset;
543 }
544 }
545
546 if (out_cookie != nullptr) {
547 *out_cookie = kInvalidCookie;
548 }
549 return {};
550}
551
552std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800553 ApkAssetsCookie cookie,
554 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700555 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
556 return {};
557 }
Ryan Mitchellc07aa702020-03-10 13:49:12 -0700558 return apk_assets_[cookie]->GetAssetsProvider()->Open(filename, mode);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700559}
560
Ryan Mitchell80094e32020-11-16 23:08:18 +0000561base::expected<FindEntryResult, NullOrIOError> AssetManager2::FindEntry(
562 uint32_t resid, uint16_t density_override, bool stop_at_first_match,
563 bool ignore_configuration) const {
564 const bool logging_enabled = resource_resolution_logging_enabled_;
565 if (UNLIKELY(logging_enabled)) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700566 // Clear the last logged resource resolution.
567 ResetResourceResolution();
568 last_resolution_.resid = resid;
569 }
570
Adam Lesinski7ad11102016-10-28 16:39:15 -0700571 // Might use this if density_override != 0.
572 ResTable_config density_override_config;
573
574 // Select our configuration or generate a density override configuration.
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800575 const ResTable_config* desired_config = &configuration_;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700576 if (density_override != 0 && density_override != configuration_.density) {
577 density_override_config = configuration_;
578 density_override_config.density = density_override;
579 desired_config = &density_override_config;
580 }
581
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700582 // Retrieve the package group from the package id of the resource id.
Ryan Mitchell80094e32020-11-16 23:08:18 +0000583 if (UNLIKELY(!is_valid_resid(resid))) {
Mark Hansenb406b0e2022-10-14 02:18:37 +0000584 LOG(ERROR) << base::StringPrintf("Invalid resource ID 0x%08x.", resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000585 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -0500586 }
587
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800588 const uint32_t package_id = get_package_id(resid);
589 const uint8_t type_idx = get_type_id(resid) - 1;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800590 const uint16_t entry_idx = get_entry_id(resid);
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700591 uint8_t package_idx = package_ids_[package_id];
Ryan Mitchell80094e32020-11-16 23:08:18 +0000592 if (UNLIKELY(package_idx == 0xff)) {
Mark Hansenb406b0e2022-10-14 02:18:37 +0000593 ANDROID_LOG(ERROR) << base::StringPrintf("No package ID %02x found for resource ID 0x%08x.",
Ryan Mitchell2fe23472019-02-27 09:43:01 -0800594 package_id, resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000595 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -0500596 }
597
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800598 const PackageGroup& package_group = package_groups_[package_idx];
Ryan Mitchell80094e32020-11-16 23:08:18 +0000599 auto result = FindEntryInternal(package_group, type_idx, entry_idx, *desired_config,
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800600 stop_at_first_match, ignore_configuration);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000601 if (UNLIKELY(!result.has_value())) {
602 return base::unexpected(result.error());
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700603 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800604
Jackal Guo552b45d2021-09-29 10:52:19 +0800605 bool overlaid = false;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000606 if (!stop_at_first_match && !ignore_configuration && !apk_assets_[result->cookie]->IsLoader()) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700607 for (const auto& id_map : package_group.overlays_) {
608 auto overlay_entry = id_map.overlay_res_maps_.Lookup(resid);
609 if (!overlay_entry) {
610 // No id map entry exists for this target resource.
611 continue;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000612 }
613 if (overlay_entry.IsInlineValue()) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700614 // The target resource is overlaid by an inline value not represented by a resource.
Jeremy Meyerbe2b7792022-08-23 17:42:50 +0000615 ConfigDescription best_frro_config;
616 Res_value best_frro_value;
617 bool frro_found = false;
618 for( const auto& [config, value] : overlay_entry.GetInlineValue()) {
619 if ((!frro_found || config.isBetterThan(best_frro_config, desired_config))
620 && config.match(*desired_config)) {
621 frro_found = true;
622 best_frro_config = config;
623 best_frro_value = value;
624 }
625 }
626 if (!frro_found) {
627 continue;
628 }
629 result->entry = best_frro_value;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000630 result->dynamic_ref_table = id_map.overlay_res_maps_.GetOverlayDynamicRefTable();
631 result->cookie = id_map.cookie;
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800632
633 if (UNLIKELY(logging_enabled)) {
634 last_resolution_.steps.push_back(
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -0700635 Resolution::Step{Resolution::Step::Type::OVERLAID_INLINE, result->cookie, String8()});
Jackal Guo552b45d2021-09-29 10:52:19 +0800636 if (auto path = apk_assets_[result->cookie]->GetPath()) {
637 const std::string overlay_path = path->data();
638 if (IsFabricatedOverlay(overlay_path)) {
639 // FRRO don't have package name so we use the creating package here.
640 String8 frro_name = String8("FRRO");
641 // Get the first part of it since the expected one should be like
642 // {overlayPackageName}-{overlayName}-{4 alphanumeric chars}.frro
643 // under /data/resource-cache/.
644 const std::string name = overlay_path.substr(overlay_path.rfind('/') + 1);
645 const size_t end = name.find('-');
646 if (frro_name.size() != overlay_path.size() && end != std::string::npos) {
647 frro_name.append(base::StringPrintf(" created by %s",
648 name.substr(0 /* pos */,
649 end).c_str()).c_str());
650 }
651 last_resolution_.best_package_name = frro_name;
652 } else {
653 last_resolution_.best_package_name = result->package_name->c_str();
654 }
655 }
656 overlaid = true;
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800657 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700658 continue;
659 }
660
Ryan Mitchell80094e32020-11-16 23:08:18 +0000661 auto overlay_result = FindEntry(overlay_entry.GetResourceId(), density_override,
662 false /* stop_at_first_match */,
663 false /* ignore_configuration */);
664 if (UNLIKELY(IsIOError(overlay_result))) {
665 return base::unexpected(overlay_result.error());
666 }
667 if (!overlay_result.has_value()) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700668 continue;
669 }
670
Ryan Mitchell80094e32020-11-16 23:08:18 +0000671 if (!overlay_result->config.isBetterThan(result->config, desired_config)
672 && overlay_result->config.compare(result->config) != 0) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700673 // The configuration of the entry for the overlay must be equal to or better than the target
674 // configuration to be chosen as the better value.
675 continue;
676 }
677
Ryan Mitchell80094e32020-11-16 23:08:18 +0000678 result->cookie = overlay_result->cookie;
679 result->entry = overlay_result->entry;
680 result->config = overlay_result->config;
681 result->dynamic_ref_table = id_map.overlay_res_maps_.GetOverlayDynamicRefTable();
682
683 if (UNLIKELY(logging_enabled)) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700684 last_resolution_.steps.push_back(
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -0700685 Resolution::Step{Resolution::Step::Type::OVERLAID, overlay_result->cookie,
686 overlay_result->config.toString()});
Jackal Guo552b45d2021-09-29 10:52:19 +0800687 last_resolution_.best_package_name =
688 overlay_result->package_name->c_str();
689 overlaid = true;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700690 }
691 }
692 }
693
Ryan Mitchell80094e32020-11-16 23:08:18 +0000694 if (UNLIKELY(logging_enabled)) {
695 last_resolution_.cookie = result->cookie;
696 last_resolution_.type_string_ref = result->type_string_ref;
697 last_resolution_.entry_string_ref = result->entry_string_ref;
Jackal Guo552b45d2021-09-29 10:52:19 +0800698 last_resolution_.best_config_name = result->config.toString();
699 if (!overlaid) {
700 last_resolution_.best_package_name = result->package_name->c_str();
701 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700702 }
703
Ryan Mitchell80094e32020-11-16 23:08:18 +0000704 return result;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700705}
706
Ryan Mitchell80094e32020-11-16 23:08:18 +0000707base::expected<FindEntryResult, NullOrIOError> AssetManager2::FindEntryInternal(
708 const PackageGroup& package_group, uint8_t type_idx, uint16_t entry_idx,
709 const ResTable_config& desired_config, bool stop_at_first_match,
710 bool ignore_configuration) const {
711 const bool logging_enabled = resource_resolution_logging_enabled_;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800712 ApkAssetsCookie best_cookie = kInvalidCookie;
713 const LoadedPackage* best_package = nullptr;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000714 incfs::verified_map_ptr<ResTable_type> best_type;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800715 const ResTable_config* best_config = nullptr;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000716 uint32_t best_offset = 0U;
717 uint32_t type_flags = 0U;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800718
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800719 // If `desired_config` is not the same as the set configuration or the caller will accept a value
720 // from any configuration, then we cannot use our filtered list of types since it only it contains
721 // types matched to the set configuration.
722 const bool use_filtered = !ignore_configuration && &desired_config == &configuration_;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800723
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700724 const size_t package_count = package_group.packages_.size();
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800725 for (size_t pi = 0; pi < package_count; pi++) {
726 const ConfiguredPackage& loaded_package_impl = package_group.packages_[pi];
727 const LoadedPackage* loaded_package = loaded_package_impl.loaded_package_;
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800728 const ApkAssetsCookie cookie = package_group.cookies_[pi];
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800729
730 // If the type IDs are offset in this package, we need to take that into account when searching
731 // for a type.
732 const TypeSpec* type_spec = loaded_package->GetTypeSpecByTypeIndex(type_idx);
733 if (UNLIKELY(type_spec == nullptr)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700734 continue;
735 }
736
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800737 // Allow custom loader packages to overlay resource values with configurations equivalent to the
738 // current best configuration.
739 const bool package_is_loader = loaded_package->IsCustomLoader();
740
Ryan Mitchell80094e32020-11-16 23:08:18 +0000741 auto entry_flags = type_spec->GetFlagsForEntryIndex(entry_idx);
Bernie Innocenti58cf8e32020-12-19 15:31:52 +0900742 if (UNLIKELY(!entry_flags.has_value())) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000743 return base::unexpected(entry_flags.error());
744 }
745 type_flags |= entry_flags.value();
746
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800747 const FilteredConfigGroup& filtered_group = loaded_package_impl.filtered_configs_[type_idx];
748 const size_t type_entry_count = (use_filtered) ? filtered_group.type_entries.size()
749 : type_spec->type_entries.size();
750 for (size_t i = 0; i < type_entry_count; i++) {
751 const TypeSpec::TypeEntry* type_entry = (use_filtered) ? filtered_group.type_entries[i]
752 : &type_spec->type_entries[i];
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800753
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800754 // We can skip calling ResTable_config::match() if the caller does not care for the
755 // configuration to match or if we're using the list of types that have already had their
756 // configuration matched.
757 const ResTable_config& this_config = type_entry->config;
758 if (!(use_filtered || ignore_configuration || this_config.match(desired_config))) {
759 continue;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800760 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800761
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800762 Resolution::Step::Type resolution_type;
763 if (best_config == nullptr) {
764 resolution_type = Resolution::Step::Type::INITIAL;
765 } else if (this_config.isBetterThan(*best_config, &desired_config)) {
766 resolution_type = Resolution::Step::Type::BETTER_MATCH;
767 } else if (package_is_loader && this_config.compare(*best_config) == 0) {
768 resolution_type = Resolution::Step::Type::OVERLAID;
769 } else {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000770 if (UNLIKELY(logging_enabled)) {
Jackal Guo552b45d2021-09-29 10:52:19 +0800771 last_resolution_.steps.push_back(Resolution::Step{Resolution::Step::Type::SKIPPED,
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -0700772 cookie, this_config.toString()});
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800773 }
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800774 continue;
775 }
776
777 // The configuration matches and is better than the previous selection.
778 // Find the entry value if it exists for this configuration.
779 const auto& type = type_entry->type;
780 const auto offset = LoadedPackage::GetEntryOffset(type, entry_idx);
781 if (UNLIKELY(IsIOError(offset))) {
782 return base::unexpected(offset.error());
783 }
784
785 if (!offset.has_value()) {
786 if (UNLIKELY(logging_enabled)) {
Jackal Guo552b45d2021-09-29 10:52:19 +0800787 last_resolution_.steps.push_back(Resolution::Step{Resolution::Step::Type::NO_ENTRY,
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -0700788 cookie, this_config.toString()});
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800789 }
790 continue;
791 }
792
793 best_cookie = cookie;
794 best_package = loaded_package;
795 best_type = type;
796 best_config = &this_config;
797 best_offset = offset.value();
798
799 if (UNLIKELY(logging_enabled)) {
800 last_resolution_.steps.push_back(Resolution::Step{resolution_type,
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -0700801 cookie, this_config.toString()});
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800802 }
803
804 // Any configuration will suffice, so break.
805 if (stop_at_first_match) {
806 break;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700807 }
808 }
809 }
810
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800811 if (UNLIKELY(best_cookie == kInvalidCookie)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000812 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700813 }
814
Eric Miao368cd192022-09-09 15:46:14 -0700815 auto best_entry_verified = LoadedPackage::GetEntryFromOffset(best_type, best_offset);
816 if (!best_entry_verified.has_value()) {
817 return base::unexpected(best_entry_verified.error());
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800818 }
819
Eric Miao368cd192022-09-09 15:46:14 -0700820 const auto entry = GetEntryValue(*best_entry_verified);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000821 if (!entry.has_value()) {
822 return base::unexpected(entry.error());
823 }
Winson2f3669b2019-01-11 11:28:34 -0800824
Ryan Mitchell80094e32020-11-16 23:08:18 +0000825 return FindEntryResult{
826 .cookie = best_cookie,
827 .entry = *entry,
828 .config = *best_config,
829 .type_flags = type_flags,
830 .package_name = &best_package->GetPackageName(),
831 .type_string_ref = StringPoolRef(best_package->GetTypeStringPool(), best_type->id - 1),
832 .entry_string_ref = StringPoolRef(best_package->GetKeyStringPool(),
Eric Miao368cd192022-09-09 15:46:14 -0700833 (*best_entry_verified)->key()),
Ryan Mitchell80094e32020-11-16 23:08:18 +0000834 .dynamic_ref_table = package_group.dynamic_ref_table.get(),
835 };
Adam Lesinski7ad11102016-10-28 16:39:15 -0700836}
837
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700838void AssetManager2::ResetResourceResolution() const {
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -0700839 last_resolution_ = Resolution{};
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700840}
841
Winson2f3669b2019-01-11 11:28:34 -0800842void AssetManager2::SetResourceResolutionLoggingEnabled(bool enabled) {
843 resource_resolution_logging_enabled_ = enabled;
Winson2f3669b2019-01-11 11:28:34 -0800844 if (!enabled) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700845 ResetResourceResolution();
Winson2f3669b2019-01-11 11:28:34 -0800846 }
847}
848
849std::string AssetManager2::GetLastResourceResolution() const {
850 if (!resource_resolution_logging_enabled_) {
851 LOG(ERROR) << "Must enable resource resolution logging before getting path.";
Ryan Mitchell80094e32020-11-16 23:08:18 +0000852 return {};
Winson2f3669b2019-01-11 11:28:34 -0800853 }
854
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800855 const ApkAssetsCookie cookie = last_resolution_.cookie;
Winson2f3669b2019-01-11 11:28:34 -0800856 if (cookie == kInvalidCookie) {
857 LOG(ERROR) << "AssetManager hasn't resolved a resource to read resolution path.";
Ryan Mitchell80094e32020-11-16 23:08:18 +0000858 return {};
Winson2f3669b2019-01-11 11:28:34 -0800859 }
860
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800861 const uint32_t resid = last_resolution_.resid;
862 const auto package = apk_assets_[cookie]->GetLoadedArsc()->GetPackageById(get_package_id(resid));
863
Winson2f3669b2019-01-11 11:28:34 -0800864 std::string resource_name_string;
Winson2f3669b2019-01-11 11:28:34 -0800865 if (package != nullptr) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000866 auto resource_name = ToResourceName(last_resolution_.type_string_ref,
867 last_resolution_.entry_string_ref,
868 package->GetPackageName());
869 resource_name_string = resource_name.has_value() ?
870 ToFormattedResourceString(resource_name.value()) : "<unknown>";
Winson2f3669b2019-01-11 11:28:34 -0800871 }
872
873 std::stringstream log_stream;
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800874 log_stream << base::StringPrintf("Resolution for 0x%08x %s\n"
875 "\tFor config - %s", resid, resource_name_string.c_str(),
876 configuration_.toString().c_str());
Winson2f3669b2019-01-11 11:28:34 -0800877
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800878 for (const Resolution::Step& step : last_resolution_.steps) {
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -0700879 constexpr static std::array kStepStrings = {
880 "Found initial",
881 "Found better",
882 "Overlaid",
883 "Overlaid inline",
884 "Skipped",
885 "No entry"
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800886 };
887
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -0700888 if (step.type < Resolution::Step::Type::INITIAL
889 || step.type > Resolution::Step::Type::NO_ENTRY) {
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800890 continue;
Winson2f3669b2019-01-11 11:28:34 -0800891 }
Yurii Zubrytskyiff9cba72023-03-29 12:53:51 -0700892 const auto prefix = kStepStrings[int(step.type) - int(Resolution::Step::Type::INITIAL)];
893 log_stream << "\n\t" << prefix << ": " << apk_assets_[step.cookie]->GetDebugName();
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800894 if (!step.config_name.isEmpty()) {
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800895 log_stream << " - " << step.config_name;
Winson2f3669b2019-01-11 11:28:34 -0800896 }
897 }
898
Jackal Guo552b45d2021-09-29 10:52:19 +0800899 log_stream << "\nBest matching is from "
900 << (last_resolution_.best_config_name.isEmpty() ? "default"
901 : last_resolution_.best_config_name)
902 << " configuration of " << last_resolution_.best_package_name;
Winson2f3669b2019-01-11 11:28:34 -0800903 return log_stream.str();
904}
905
Felka Chang00964e92021-12-10 01:19:08 +0800906base::expected<uint32_t, NullOrIOError> AssetManager2::GetParentThemeResourceId(uint32_t resid)
907const {
908 auto entry = FindEntry(resid, 0u /* density_override */,
909 false /* stop_at_first_match */,
910 false /* ignore_configuration */);
911 if (!entry.has_value()) {
912 return base::unexpected(entry.error());
913 }
914
915 auto entry_map = std::get_if<incfs::verified_map_ptr<ResTable_map_entry>>(&entry->entry);
916 if (entry_map == nullptr) {
917 // Not a bag, nothing to do.
918 return base::unexpected(std::nullopt);
919 }
920
921 auto map = *entry_map;
922 const uint32_t parent_resid = dtohl(map->parent.ident);
923
924 return parent_resid;
925}
926
Ryan Mitchell80094e32020-11-16 23:08:18 +0000927base::expected<AssetManager2::ResourceName, NullOrIOError> AssetManager2::GetResourceName(
928 uint32_t resid) const {
929 auto result = FindEntry(resid, 0u /* density_override */, true /* stop_at_first_match */,
930 true /* ignore_configuration */);
931 if (!result.has_value()) {
932 return base::unexpected(result.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -0700933 }
934
Ryan Mitchell80094e32020-11-16 23:08:18 +0000935 return ToResourceName(result->type_string_ref,
936 result->entry_string_ref,
937 *result->package_name);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700938}
939
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800940base::expected<uint32_t, NullOrIOError> AssetManager2::GetResourceTypeSpecFlags(
941 uint32_t resid) const {
942 auto result = FindEntry(resid, 0u /* density_override */, false /* stop_at_first_match */,
943 true /* ignore_configuration */);
944 if (!result.has_value()) {
945 return base::unexpected(result.error());
946 }
947 return result->type_flags;
948}
949
Ryan Mitchell80094e32020-11-16 23:08:18 +0000950base::expected<AssetManager2::SelectedValue, NullOrIOError> AssetManager2::GetResource(
951 uint32_t resid, bool may_be_bag, uint16_t density_override) const {
952 auto result = FindEntry(resid, density_override, false /* stop_at_first_match */,
953 false /* ignore_configuration */);
954 if (!result.has_value()) {
955 return base::unexpected(result.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -0700956 }
957
Ryan Mitchell80094e32020-11-16 23:08:18 +0000958 auto result_map_entry = std::get_if<incfs::verified_map_ptr<ResTable_map_entry>>(&result->entry);
Ryan Mitchellbf1f45b2020-09-29 17:22:52 -0700959 if (result_map_entry != nullptr) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700960 if (!may_be_bag) {
961 LOG(ERROR) << base::StringPrintf("Resource %08x is a complex map type.", resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000962 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700963 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800964
965 // Create a reference since we can't represent this complex type as a Res_value.
Ryan Mitchell80094e32020-11-16 23:08:18 +0000966 return SelectedValue(Res_value::TYPE_REFERENCE, resid, result->cookie, result->type_flags,
967 resid, result->config);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700968 }
969
Adam Lesinskida431a22016-12-29 16:08:16 -0500970 // Convert the package ID to the runtime assigned package ID.
Ryan Mitchell80094e32020-11-16 23:08:18 +0000971 Res_value value = std::get<Res_value>(result->entry);
972 result->dynamic_ref_table->lookupResourceValue(&value);
Adam Lesinskida431a22016-12-29 16:08:16 -0500973
Ryan Mitchell80094e32020-11-16 23:08:18 +0000974 return SelectedValue(value.dataType, value.data, result->cookie, result->type_flags,
975 resid, result->config);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700976}
977
Ryan Mitchell80094e32020-11-16 23:08:18 +0000978base::expected<std::monostate, NullOrIOError> AssetManager2::ResolveReference(
Ryan Mitchella45506e2020-11-16 23:08:18 +0000979 AssetManager2::SelectedValue& value, bool cache_value) const {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000980 if (value.type != Res_value::TYPE_REFERENCE || value.data == 0U) {
981 // Not a reference. Nothing to do.
982 return {};
Adam Lesinski0c405242017-01-13 20:47:26 -0800983 }
Ryan Mitchell80094e32020-11-16 23:08:18 +0000984
Ryan Mitchella45506e2020-11-16 23:08:18 +0000985 const uint32_t original_flags = value.flags;
986 const uint32_t original_resid = value.data;
987 if (cache_value) {
988 auto cached_value = cached_resolved_values_.find(value.data);
989 if (cached_value != cached_resolved_values_.end()) {
990 value = cached_value->second;
991 value.flags |= original_flags;
992 return {};
993 }
994 }
995
996 uint32_t combined_flags = 0U;
997 uint32_t resolve_resid = original_resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000998 constexpr const uint32_t kMaxIterations = 20;
999 for (uint32_t i = 0U;; i++) {
1000 auto result = GetResource(resolve_resid, true /*may_be_bag*/);
1001 if (!result.has_value()) {
Ryan Mitchelle7ab6272020-11-13 18:06:15 -08001002 value.resid = resolve_resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001003 return base::unexpected(result.error());
1004 }
1005
Ryan Mitchelle7ab6272020-11-13 18:06:15 -08001006 // If resource resolution fails, the value should be set to the last reference that was able to
1007 // be resolved successfully.
1008 value = *result;
1009 value.flags |= combined_flags;
1010
Ryan Mitchell80094e32020-11-16 23:08:18 +00001011 if (result->type != Res_value::TYPE_REFERENCE ||
1012 result->data == Res_value::DATA_NULL_UNDEFINED ||
1013 result->data == resolve_resid || i == kMaxIterations) {
1014 // This reference can't be resolved, so exit now and let the caller deal with it.
Ryan Mitchella45506e2020-11-16 23:08:18 +00001015 if (cache_value) {
1016 cached_resolved_values_[original_resid] = value;
1017 }
1018
1019 // Above value is cached without original_flags to ensure they don't get included in future
1020 // queries that hit the cache
1021 value.flags |= original_flags;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001022 return {};
1023 }
1024
Ryan Mitchelle7ab6272020-11-13 18:06:15 -08001025 combined_flags = result->flags;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001026 resolve_resid = result->data;
1027 }
Adam Lesinski0c405242017-01-13 20:47:26 -08001028}
1029
Ryan Mitchell80094e32020-11-16 23:08:18 +00001030const std::vector<uint32_t> AssetManager2::GetBagResIdStack(uint32_t resid) const {
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001031 auto cached_iter = cached_bag_resid_stacks_.find(resid);
1032 if (cached_iter != cached_bag_resid_stacks_.end()) {
1033 return cached_iter->second;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001034 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001035
1036 std::vector<uint32_t> found_resids;
1037 GetBag(resid, found_resids);
1038 cached_bag_resid_stacks_.emplace(resid, found_resids);
1039 return found_resids;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001040}
1041
Ryan Mitchell80094e32020-11-16 23:08:18 +00001042base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::ResolveBag(
1043 AssetManager2::SelectedValue& value) const {
1044 if (UNLIKELY(value.type != Res_value::TYPE_REFERENCE)) {
1045 return base::unexpected(std::nullopt);
1046 }
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001047
Ryan Mitchell80094e32020-11-16 23:08:18 +00001048 auto bag = GetBag(value.data);
1049 if (bag.has_value()) {
1050 value.flags |= (*bag)->type_spec_flags;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001051 }
1052 return bag;
y57cd1952018-04-12 14:26:23 -07001053}
1054
Ryan Mitchell80094e32020-11-16 23:08:18 +00001055base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::GetBag(uint32_t resid) const {
1056 std::vector<uint32_t> found_resids;
1057 const auto bag = GetBag(resid, found_resids);
Yurii Zubrytskyiab3cb302022-10-11 12:15:52 -07001058 cached_bag_resid_stacks_.emplace(resid, std::move(found_resids));
Ryan Mitchell80094e32020-11-16 23:08:18 +00001059 return bag;
Ryan Mitchell155d5392020-02-10 13:35:24 -08001060}
1061
Ryan Mitchell80094e32020-11-16 23:08:18 +00001062base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::GetBag(
1063 uint32_t resid, std::vector<uint32_t>& child_resids) const {
1064 if (auto cached_iter = cached_bags_.find(resid); cached_iter != cached_bags_.end()) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001065 return cached_iter->second.get();
1066 }
1067
Ryan Mitchell80094e32020-11-16 23:08:18 +00001068 auto entry = FindEntry(resid, 0u /* density_override */, false /* stop_at_first_match */,
1069 false /* ignore_configuration */);
1070 if (!entry.has_value()) {
1071 return base::unexpected(entry.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001072 }
1073
Ryan Mitchell80094e32020-11-16 23:08:18 +00001074 auto entry_map = std::get_if<incfs::verified_map_ptr<ResTable_map_entry>>(&entry->entry);
1075 if (entry_map == nullptr) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001076 // Not a bag, nothing to do.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001077 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001078 }
1079
Ryan Mitchell80094e32020-11-16 23:08:18 +00001080 auto map = *entry_map;
1081 auto map_entry = map.offset(dtohs(map->size)).convert<ResTable_map>();
1082 const auto map_entry_end = map_entry + dtohl(map->count);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001083
y57cd1952018-04-12 14:26:23 -07001084 // Keep track of ids that have already been seen to prevent infinite loops caused by circular
Ryan Mitchell80094e32020-11-16 23:08:18 +00001085 // dependencies between bags.
y57cd1952018-04-12 14:26:23 -07001086 child_resids.push_back(resid);
1087
Adam Lesinskida431a22016-12-29 16:08:16 -05001088 uint32_t parent_resid = dtohl(map->parent.ident);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001089 if (parent_resid == 0U ||
1090 std::find(child_resids.begin(), child_resids.end(), parent_resid) != child_resids.end()) {
1091 // There is no parent or a circular parental dependency exist, meaning there is nothing to
1092 // inherit and we can do a simple copy of the entries in the map.
Adam Lesinski7ad11102016-10-28 16:39:15 -07001093 const size_t entry_count = map_entry_end - map_entry;
1094 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
1095 malloc(sizeof(ResolvedBag) + (entry_count * sizeof(ResolvedBag::Entry))))};
Ryan Mitchell155d5392020-02-10 13:35:24 -08001096
1097 bool sort_entries = false;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001098 for (auto new_entry = new_bag->entries; map_entry != map_entry_end; ++map_entry) {
1099 if (UNLIKELY(!map_entry)) {
1100 return base::unexpected(IOError::PAGES_MISSING);
1101 }
1102
Adam Lesinskida431a22016-12-29 16:08:16 -05001103 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001104 if (!is_internal_resid(new_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -05001105 // Attributes, arrays, etc don't have a resource id as the name. They specify
1106 // other data, which would be wrong to change via a lookup.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001107 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001108 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
1109 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001110 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001111 }
1112 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001113
1114 new_entry->cookie = entry->cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -05001115 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001116 new_entry->key_pool = nullptr;
1117 new_entry->type_pool = nullptr;
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001118 new_entry->style = resid;
Adam Lesinski30080e22017-10-16 16:18:09 -07001119 new_entry->value.copyFrom_dtoh(map_entry->value);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001120 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1121 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001122 LOG(ERROR) << base::StringPrintf(
1123 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
1124 new_entry->value.data, new_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001125 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001126 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001127
Ryan Mitchell155d5392020-02-10 13:35:24 -08001128 sort_entries = sort_entries ||
1129 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001130 ++new_entry;
1131 }
Ryan Mitchell155d5392020-02-10 13:35:24 -08001132
1133 if (sort_entries) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001134 std::sort(new_bag->entries, new_bag->entries + entry_count,
1135 [](auto&& lhs, auto&& rhs) { return lhs.key < rhs.key; });
Ryan Mitchell155d5392020-02-10 13:35:24 -08001136 }
1137
Ryan Mitchell80094e32020-11-16 23:08:18 +00001138 new_bag->type_spec_flags = entry->type_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001139 new_bag->entry_count = static_cast<uint32_t>(entry_count);
1140 ResolvedBag* result = new_bag.get();
1141 cached_bags_[resid] = std::move(new_bag);
1142 return result;
1143 }
1144
Adam Lesinskida431a22016-12-29 16:08:16 -05001145 // In case the parent is a dynamic reference, resolve it.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001146 entry->dynamic_ref_table->lookupResourceId(&parent_resid);
Adam Lesinskida431a22016-12-29 16:08:16 -05001147
Adam Lesinski7ad11102016-10-28 16:39:15 -07001148 // Get the parent and do a merge of the keys.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001149 const auto parent_bag = GetBag(parent_resid, child_resids);
1150 if (UNLIKELY(!parent_bag.has_value())) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001151 // Failed to get the parent that should exist.
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001152 LOG(ERROR) << base::StringPrintf("Failed to find parent 0x%08x of bag 0x%08x.", parent_resid,
1153 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001154 return base::unexpected(parent_bag.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001155 }
1156
Adam Lesinski7ad11102016-10-28 16:39:15 -07001157 // Create the max possible entries we can make. Once we construct the bag,
1158 // we will realloc to fit to size.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001159 const size_t max_count = (*parent_bag)->entry_count + dtohl(map->count);
George Burgess IV09b119f2017-07-25 15:00:04 -07001160 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
1161 malloc(sizeof(ResolvedBag) + (max_count * sizeof(ResolvedBag::Entry))))};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001162 ResolvedBag::Entry* new_entry = new_bag->entries;
1163
Ryan Mitchell80094e32020-11-16 23:08:18 +00001164 const ResolvedBag::Entry* parent_entry = (*parent_bag)->entries;
1165 const ResolvedBag::Entry* const parent_entry_end = parent_entry + (*parent_bag)->entry_count;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001166
1167 // The keys are expected to be in sorted order. Merge the two bags.
Ryan Mitchell155d5392020-02-10 13:35:24 -08001168 bool sort_entries = false;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001169 while (map_entry != map_entry_end && parent_entry != parent_entry_end) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001170 if (UNLIKELY(!map_entry)) {
1171 return base::unexpected(IOError::PAGES_MISSING);
1172 }
1173
Adam Lesinskida431a22016-12-29 16:08:16 -05001174 uint32_t child_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001175 if (!is_internal_resid(child_key)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001176 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&child_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001177 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", child_key,
1178 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001179 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001180 }
1181 }
1182
Adam Lesinski7ad11102016-10-28 16:39:15 -07001183 if (child_key <= parent_entry->key) {
1184 // Use the child key if it comes before the parent
1185 // or is equal to the parent (overrides).
Ryan Mitchell80094e32020-11-16 23:08:18 +00001186 new_entry->cookie = entry->cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001187 new_entry->key = child_key;
1188 new_entry->key_pool = nullptr;
1189 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -07001190 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001191 new_entry->style = resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001192 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1193 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001194 LOG(ERROR) << base::StringPrintf(
1195 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
1196 new_entry->value.data, child_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001197 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001198 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001199 ++map_entry;
1200 } else {
1201 // Take the parent entry as-is.
1202 memcpy(new_entry, parent_entry, sizeof(*new_entry));
1203 }
1204
Ryan Mitchell155d5392020-02-10 13:35:24 -08001205 sort_entries = sort_entries ||
1206 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001207 if (child_key >= parent_entry->key) {
1208 // Move to the next parent entry if we used it or it was overridden.
1209 ++parent_entry;
1210 }
1211 // Increment to the next entry to fill.
1212 ++new_entry;
1213 }
1214
1215 // Finish the child entries if they exist.
1216 while (map_entry != map_entry_end) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001217 if (UNLIKELY(!map_entry)) {
1218 return base::unexpected(IOError::PAGES_MISSING);
1219 }
1220
Adam Lesinskida431a22016-12-29 16:08:16 -05001221 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001222 if (!is_internal_resid(new_key)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001223 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001224 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
1225 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001226 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001227 }
1228 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001229 new_entry->cookie = entry->cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -05001230 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001231 new_entry->key_pool = nullptr;
1232 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -07001233 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001234 new_entry->style = resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001235 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1236 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001237 LOG(ERROR) << base::StringPrintf("Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.",
1238 new_entry->value.dataType, new_entry->value.data, new_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001239 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001240 }
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 ++map_entry;
1244 ++new_entry;
1245 }
1246
1247 // Finish the parent entries if they exist.
1248 if (parent_entry != parent_entry_end) {
1249 // Take the rest of the parent entries as-is.
1250 const size_t num_entries_to_copy = parent_entry_end - parent_entry;
1251 memcpy(new_entry, parent_entry, num_entries_to_copy * sizeof(*new_entry));
1252 new_entry += num_entries_to_copy;
1253 }
1254
1255 // Resize the resulting array to fit.
1256 const size_t actual_count = new_entry - new_bag->entries;
1257 if (actual_count != max_count) {
George Burgess IV09b119f2017-07-25 15:00:04 -07001258 new_bag.reset(reinterpret_cast<ResolvedBag*>(realloc(
1259 new_bag.release(), sizeof(ResolvedBag) + (actual_count * sizeof(ResolvedBag::Entry)))));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001260 }
1261
Ryan Mitchell155d5392020-02-10 13:35:24 -08001262 if (sort_entries) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001263 std::sort(new_bag->entries, new_bag->entries + actual_count,
1264 [](auto&& lhs, auto&& rhs) { return lhs.key < rhs.key; });
Ryan Mitchell155d5392020-02-10 13:35:24 -08001265 }
1266
Adam Lesinski1a1e9c22017-10-13 15:45:34 -07001267 // Combine flags from the parent and our own bag.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001268 new_bag->type_spec_flags = entry->type_flags | (*parent_bag)->type_spec_flags;
George Burgess IV09b119f2017-07-25 15:00:04 -07001269 new_bag->entry_count = static_cast<uint32_t>(actual_count);
1270 ResolvedBag* result = new_bag.get();
1271 cached_bags_[resid] = std::move(new_bag);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001272 return result;
1273}
1274
Yurii Zubrytskyia5775142022-11-02 17:49:49 -07001275static bool Utf8ToUtf16(StringPiece str, std::u16string* out) {
Adam Lesinski929d6512017-01-16 19:11:19 -08001276 ssize_t len =
1277 utf8_to_utf16_length(reinterpret_cast<const uint8_t*>(str.data()), str.size(), false);
1278 if (len < 0) {
1279 return false;
1280 }
1281 out->resize(static_cast<size_t>(len));
1282 utf8_to_utf16(reinterpret_cast<const uint8_t*>(str.data()), str.size(), &*out->begin(),
1283 static_cast<size_t>(len + 1));
1284 return true;
1285}
1286
Ryan Mitchell80094e32020-11-16 23:08:18 +00001287base::expected<uint32_t, NullOrIOError> AssetManager2::GetResourceId(
1288 const std::string& resource_name, const std::string& fallback_type,
1289 const std::string& fallback_package) const {
Adam Lesinski929d6512017-01-16 19:11:19 -08001290 StringPiece package_name, type, entry;
1291 if (!ExtractResourceName(resource_name, &package_name, &type, &entry)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001292 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001293 }
1294
1295 if (entry.empty()) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001296 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001297 }
1298
1299 if (package_name.empty()) {
1300 package_name = fallback_package;
1301 }
1302
1303 if (type.empty()) {
1304 type = fallback_type;
1305 }
1306
1307 std::u16string type16;
1308 if (!Utf8ToUtf16(type, &type16)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001309 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001310 }
1311
1312 std::u16string entry16;
1313 if (!Utf8ToUtf16(entry, &entry16)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001314 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001315 }
1316
1317 const StringPiece16 kAttr16 = u"attr";
1318 const static std::u16string kAttrPrivate16 = u"^attr-private";
1319
1320 for (const PackageGroup& package_group : package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001321 for (const ConfiguredPackage& package_impl : package_group.packages_) {
1322 const LoadedPackage* package = package_impl.loaded_package_;
Adam Lesinski929d6512017-01-16 19:11:19 -08001323 if (package_name != package->GetPackageName()) {
1324 // All packages in the same group are expected to have the same package name.
1325 break;
1326 }
1327
Ryan Mitchell80094e32020-11-16 23:08:18 +00001328 base::expected<uint32_t, NullOrIOError> resid = package->FindEntryByName(type16, entry16);
1329 if (UNLIKELY(IsIOError(resid))) {
1330 return base::unexpected(resid.error());
1331 }
1332
1333 if (!resid.has_value() && kAttr16 == type16) {
Adam Lesinski929d6512017-01-16 19:11:19 -08001334 // Private attributes in libraries (such as the framework) are sometimes encoded
1335 // under the type '^attr-private' in order to leave the ID space of public 'attr'
1336 // free for future additions. Check '^attr-private' for the same name.
1337 resid = package->FindEntryByName(kAttrPrivate16, entry16);
1338 }
1339
Ryan Mitchell80094e32020-11-16 23:08:18 +00001340 if (resid.has_value()) {
1341 return fix_package_id(*resid, package_group.dynamic_ref_table->mAssignedPackageId);
Adam Lesinski929d6512017-01-16 19:11:19 -08001342 }
1343 }
1344 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001345 return base::unexpected(std::nullopt);
Adam Lesinski0c405242017-01-13 20:47:26 -08001346}
1347
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001348void AssetManager2::RebuildFilterList() {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001349 for (PackageGroup& group : package_groups_) {
Yurii Zubrytskyidbce3562022-11-14 22:26:10 -08001350 for (ConfiguredPackage& package : group.packages_) {
1351 package.filtered_configs_.forEachItem([](auto, auto& fcg) { fcg.type_entries.clear(); });
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001352 // Create the filters here.
Yurii Zubrytskyidbce3562022-11-14 22:26:10 -08001353 package.loaded_package_->ForEachTypeSpec([&](const TypeSpec& type_spec, uint8_t type_id) {
Yurii Zubrytskyi59dab3b2022-11-03 00:08:49 -07001354 FilteredConfigGroup* group = nullptr;
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001355 for (const auto& type_entry : type_spec.type_entries) {
1356 if (type_entry.config.match(configuration_)) {
Yurii Zubrytskyi59dab3b2022-11-03 00:08:49 -07001357 if (!group) {
Yurii Zubrytskyidbce3562022-11-14 22:26:10 -08001358 group = &package.filtered_configs_.editItemAt(type_id - 1);
Yurii Zubrytskyi59dab3b2022-11-03 00:08:49 -07001359 }
1360 group->type_entries.push_back(&type_entry);
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001361 }
1362 }
1363 });
Yurii Zubrytskyidbce3562022-11-14 22:26:10 -08001364 package.filtered_configs_.trimBuckets(
1365 [](const auto& fcg) { return fcg.type_entries.empty(); });
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001366 }
1367 }
1368}
1369
Adam Lesinski7ad11102016-10-28 16:39:15 -07001370void AssetManager2::InvalidateCaches(uint32_t diff) {
Ryan Mitchell2c4d8742019-03-04 09:41:00 -08001371 cached_bag_resid_stacks_.clear();
1372
Adam Lesinski7ad11102016-10-28 16:39:15 -07001373 if (diff == 0xffffffffu) {
1374 // Everything must go.
1375 cached_bags_.clear();
1376 return;
1377 }
1378
1379 // Be more conservative with what gets purged. Only if the bag has other possible
1380 // variations with respect to what changed (diff) should we remove it.
1381 for (auto iter = cached_bags_.cbegin(); iter != cached_bags_.cend();) {
1382 if (diff & iter->second->type_spec_flags) {
1383 iter = cached_bags_.erase(iter);
1384 } else {
1385 ++iter;
1386 }
1387 }
Ryan Mitchella45506e2020-11-16 23:08:18 +00001388
1389 cached_resolved_values_.clear();
Adam Lesinski7ad11102016-10-28 16:39:15 -07001390}
1391
Ryan Mitchell2e394222019-08-28 12:10:51 -07001392uint8_t AssetManager2::GetAssignedPackageId(const LoadedPackage* package) const {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001393 for (auto& package_group : package_groups_) {
1394 for (auto& package2 : package_group.packages_) {
1395 if (package2.loaded_package_ == package) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -07001396 return package_group.dynamic_ref_table->mAssignedPackageId;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001397 }
1398 }
1399 }
1400 return 0;
1401}
1402
Adam Lesinski30080e22017-10-16 16:18:09 -07001403std::unique_ptr<Theme> AssetManager2::NewTheme() {
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001404 constexpr size_t kInitialReserveSize = 32;
1405 auto theme = std::unique_ptr<Theme>(new Theme(this));
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001406 theme->keys_.reserve(kInitialReserveSize);
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001407 theme->entries_.reserve(kInitialReserveSize);
1408 return theme;
Adam Lesinski30080e22017-10-16 16:18:09 -07001409}
1410
Yurii Zubrytskyi9eb44c92022-11-14 23:44:52 -08001411void AssetManager2::ForEachPackage(base::function_ref<bool(const std::string&, uint8_t)> func,
1412 package_property_t excluded_property_flags) const {
1413 for (const PackageGroup& package_group : package_groups_) {
1414 const auto loaded_package = package_group.packages_.front().loaded_package_;
1415 if ((loaded_package->GetPropertyFlags() & excluded_property_flags) == 0U
1416 && !func(loaded_package->GetPackageName(),
1417 package_group.dynamic_ref_table->mAssignedPackageId)) {
1418 return;
1419 }
1420 }
1421}
1422
Adam Lesinski30080e22017-10-16 16:18:09 -07001423Theme::Theme(AssetManager2* asset_manager) : asset_manager_(asset_manager) {
1424}
1425
1426Theme::~Theme() = default;
1427
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001428struct Theme::Entry {
Adam Lesinski30080e22017-10-16 16:18:09 -07001429 ApkAssetsCookie cookie;
1430 uint32_t type_spec_flags;
1431 Res_value value;
1432};
1433
Ryan Mitchell80094e32020-11-16 23:08:18 +00001434base::expected<std::monostate, NullOrIOError> Theme::ApplyStyle(uint32_t resid, bool force) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001435 ATRACE_NAME("Theme::ApplyStyle");
Adam Lesinski7ad11102016-10-28 16:39:15 -07001436
Ryan Mitchell80094e32020-11-16 23:08:18 +00001437 auto bag = asset_manager_->GetBag(resid);
1438 if (!bag.has_value()) {
1439 return base::unexpected(bag.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001440 }
1441
1442 // Merge the flags from this style.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001443 type_spec_flags_ |= (*bag)->type_spec_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001444
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001445 for (auto it = begin(*bag); it != end(*bag); ++it) {
1446 const uint32_t attr_res_id = it->key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001447
Adam Lesinski30080e22017-10-16 16:18:09 -07001448 // If the resource ID passed in is not a style, the key can be some other identifier that is not
1449 // a resource ID. We should fail fast instead of operating with strange resource IDs.
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001450 if (!is_valid_resid(attr_res_id)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001451 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001452 }
1453
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001454 // DATA_NULL_EMPTY (@empty) is a valid resource value and DATA_NULL_UNDEFINED represents
1455 // an absence of a valid value.
1456 bool is_undefined = it->value.dataType == Res_value::TYPE_NULL &&
1457 it->value.data != Res_value::DATA_NULL_EMPTY;
1458 if (!force && is_undefined) {
1459 continue;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001460 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001461
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001462 const auto key_it = std::lower_bound(keys_.begin(), keys_.end(), attr_res_id);
1463 const auto entry_it = entries_.begin() + (key_it - keys_.begin());
1464 if (key_it != keys_.end() && *key_it == attr_res_id) {
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001465 if (is_undefined) {
1466 // DATA_NULL_UNDEFINED clears the value of the attribute in the theme only when `force` is
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001467 // true.
1468 keys_.erase(key_it);
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001469 entries_.erase(entry_it);
1470 } else if (force) {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001471 *entry_it = Entry{it->cookie, (*bag)->type_spec_flags, it->value};
Adam Lesinski30080e22017-10-16 16:18:09 -07001472 }
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001473 } else {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001474 keys_.insert(key_it, attr_res_id);
1475 entries_.insert(entry_it, Entry{it->cookie, (*bag)->type_spec_flags, it->value});
Adam Lesinski7ad11102016-10-28 16:39:15 -07001476 }
1477 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001478 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001479}
1480
Ryan Mitchell767e34f2021-06-07 12:29:05 -07001481void Theme::Rebase(AssetManager2* am, const uint32_t* style_ids, const uint8_t* force,
1482 size_t style_count) {
1483 ATRACE_NAME("Theme::Rebase");
1484 // Reset the entries without changing the vector capacity to prevent reallocations during
1485 // ApplyStyle.
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001486 keys_.clear();
Ryan Mitchell767e34f2021-06-07 12:29:05 -07001487 entries_.clear();
1488 asset_manager_ = am;
1489 for (size_t i = 0; i < style_count; i++) {
1490 ApplyStyle(style_ids[i], force[i]);
1491 }
1492}
1493
Ryan Mitchell80094e32020-11-16 23:08:18 +00001494std::optional<AssetManager2::SelectedValue> Theme::GetAttribute(uint32_t resid) const {
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001495 constexpr const uint32_t kMaxIterations = 20;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001496 uint32_t type_spec_flags = 0u;
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001497 for (uint32_t i = 0; i <= kMaxIterations; i++) {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001498 const auto key_it = std::lower_bound(keys_.begin(), keys_.end(), resid);
1499 if (key_it == keys_.end() || *key_it != resid) {
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001500 return std::nullopt;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001501 }
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001502 const auto entry_it = entries_.begin() + (key_it - keys_.begin());
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001503 type_spec_flags |= entry_it->type_spec_flags;
1504 if (entry_it->value.dataType == Res_value::TYPE_ATTRIBUTE) {
1505 resid = entry_it->value.data;
1506 continue;
1507 }
1508
1509 return AssetManager2::SelectedValue(entry_it->value.dataType, entry_it->value.data,
1510 entry_it->cookie, type_spec_flags, 0U /* resid */,
1511 {} /* config */);
1512 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001513 return std::nullopt;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001514}
1515
Ryan Mitchell80094e32020-11-16 23:08:18 +00001516base::expected<std::monostate, NullOrIOError> Theme::ResolveAttributeReference(
1517 AssetManager2::SelectedValue& value) const {
1518 if (value.type != Res_value::TYPE_ATTRIBUTE) {
1519 return asset_manager_->ResolveReference(value);
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001520 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001521
1522 std::optional<AssetManager2::SelectedValue> result = GetAttribute(value.data);
1523 if (!result.has_value()) {
1524 return base::unexpected(std::nullopt);
1525 }
1526
Ryan Mitchella45506e2020-11-16 23:08:18 +00001527 auto resolve_result = asset_manager_->ResolveReference(*result, true /* cache_value */);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001528 if (resolve_result.has_value()) {
1529 result->flags |= value.flags;
1530 value = *result;
1531 }
1532 return resolve_result;
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001533}
1534
Adam Lesinski7ad11102016-10-28 16:39:15 -07001535void Theme::Clear() {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001536 keys_.clear();
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001537 entries_.clear();
Adam Lesinski7ad11102016-10-28 16:39:15 -07001538}
1539
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001540base::expected<std::monostate, IOError> Theme::SetTo(const Theme& source) {
1541 if (this == &source) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001542 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001543 }
1544
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001545 type_spec_flags_ = source.type_spec_flags_;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001546
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001547 if (asset_manager_ == source.asset_manager_) {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001548 keys_ = source.keys_;
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001549 entries_ = source.entries_;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001550 } else {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001551 std::unordered_map<ApkAssetsCookie, ApkAssetsCookie> src_to_dest_asset_cookies;
1552 using SourceToDestinationRuntimePackageMap = std::unordered_map<int, int>;
1553 std::unordered_map<ApkAssetsCookie, SourceToDestinationRuntimePackageMap> src_asset_cookie_id_map;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001554
Ryan Mitchell93bca972019-03-08 17:26:28 -08001555 // Determine which ApkAssets are loaded in both theme AssetManagers.
Yurii Zubrytskyia5bc9582022-11-30 23:53:59 -08001556 const auto& src_assets = source.asset_manager_->GetApkAssets();
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001557 for (size_t i = 0; i < src_assets.size(); i++) {
1558 const ApkAssets* src_asset = src_assets[i];
1559
Yurii Zubrytskyia5bc9582022-11-30 23:53:59 -08001560 const auto& dest_assets = asset_manager_->GetApkAssets();
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001561 for (size_t j = 0; j < dest_assets.size(); j++) {
1562 const ApkAssets* dest_asset = dest_assets[j];
Ryan Mitchellef538432021-03-01 14:52:14 -08001563 if (src_asset != dest_asset) {
1564 // ResourcesManager caches and reuses ApkAssets when the same apk must be present in
1565 // multiple AssetManagers. Two ApkAssets point to the same version of the same resources
1566 // if they are the same instance.
1567 continue;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001568 }
Ryan Mitchellef538432021-03-01 14:52:14 -08001569
1570 // Map the package ids of the asset in the source AssetManager to the package ids of the
1571 // asset in th destination AssetManager.
1572 SourceToDestinationRuntimePackageMap package_map;
1573 for (const auto& loaded_package : src_asset->GetLoadedArsc()->GetPackages()) {
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001574 const int src_package_id = source.asset_manager_->GetAssignedPackageId(
1575 loaded_package.get());
Ryan Mitchellef538432021-03-01 14:52:14 -08001576 const int dest_package_id = asset_manager_->GetAssignedPackageId(loaded_package.get());
1577 package_map[src_package_id] = dest_package_id;
1578 }
1579
1580 src_to_dest_asset_cookies.insert(std::make_pair(i, j));
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001581 src_asset_cookie_id_map.insert(std::make_pair(i, std::move(package_map)));
Ryan Mitchellef538432021-03-01 14:52:14 -08001582 break;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001583 }
1584 }
1585
Ryan Mitchell93bca972019-03-08 17:26:28 -08001586 // Reset the data in the destination theme.
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001587 keys_.clear();
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001588 entries_.clear();
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001589
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001590 for (size_t i = 0, size = source.entries_.size(); i != size; ++i) {
1591 const auto& entry = source.entries_[i];
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001592 bool is_reference = (entry.value.dataType == Res_value::TYPE_ATTRIBUTE
1593 || entry.value.dataType == Res_value::TYPE_REFERENCE
1594 || entry.value.dataType == Res_value::TYPE_DYNAMIC_ATTRIBUTE
1595 || entry.value.dataType == Res_value::TYPE_DYNAMIC_REFERENCE)
1596 && entry.value.data != 0x0;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001597
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001598 // If the attribute value represents an attribute or reference, the package id of the
1599 // value needs to be rewritten to the package id of the value in the destination.
1600 uint32_t attribute_data = entry.value.data;
1601 if (is_reference) {
1602 // Determine the package id of the reference in the destination AssetManager.
1603 auto value_package_map = src_asset_cookie_id_map.find(entry.cookie);
1604 if (value_package_map == src_asset_cookie_id_map.end()) {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001605 continue;
1606 }
1607
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001608 auto value_dest_package = value_package_map->second.find(
1609 get_package_id(entry.value.data));
1610 if (value_dest_package == value_package_map->second.end()) {
1611 continue;
1612 }
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001613
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001614 attribute_data = fix_package_id(entry.value.data, value_dest_package->second);
1615 }
Ryan Mitchellb85d9b22018-11-19 12:11:38 -08001616
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001617 // Find the cookie of the value in the destination. If the source apk is not loaded in the
1618 // destination, only copy resources that do not reference resources in the source.
1619 ApkAssetsCookie data_dest_cookie;
1620 auto value_dest_cookie = src_to_dest_asset_cookies.find(entry.cookie);
1621 if (value_dest_cookie != src_to_dest_asset_cookies.end()) {
1622 data_dest_cookie = value_dest_cookie->second;
1623 } else {
1624 if (is_reference || entry.value.dataType == Res_value::TYPE_STRING) {
1625 continue;
1626 } else {
1627 data_dest_cookie = 0x0;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001628 }
1629 }
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001630
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001631 const auto source_res_id = source.keys_[i];
1632
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001633 // The package id of the attribute needs to be rewritten to the package id of the
1634 // attribute in the destination.
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001635 int attribute_dest_package_id = get_package_id(source_res_id);
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001636 if (attribute_dest_package_id != 0x01) {
1637 // Find the cookie of the attribute resource id in the source AssetManager
1638 base::expected<FindEntryResult, NullOrIOError> attribute_entry_result =
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001639 source.asset_manager_->FindEntry(source_res_id, 0 /* density_override */ ,
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001640 true /* stop_at_first_match */,
1641 true /* ignore_configuration */);
1642 if (UNLIKELY(IsIOError(attribute_entry_result))) {
1643 return base::unexpected(GetIOError(attribute_entry_result.error()));
1644 }
1645 if (!attribute_entry_result.has_value()) {
1646 continue;
1647 }
1648
1649 // Determine the package id of the attribute in the destination AssetManager.
1650 auto attribute_package_map = src_asset_cookie_id_map.find(
1651 attribute_entry_result->cookie);
1652 if (attribute_package_map == src_asset_cookie_id_map.end()) {
1653 continue;
1654 }
1655 auto attribute_dest_package = attribute_package_map->second.find(
1656 attribute_dest_package_id);
1657 if (attribute_dest_package == attribute_package_map->second.end()) {
1658 continue;
1659 }
1660 attribute_dest_package_id = attribute_dest_package->second;
1661 }
1662
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001663 auto dest_attr_id = make_resid(attribute_dest_package_id, get_type_id(source_res_id),
1664 get_entry_id(source_res_id));
1665 const auto key_it = std::lower_bound(keys_.begin(), keys_.end(), dest_attr_id);
1666 const auto entry_it = entries_.begin() + (key_it - keys_.begin());
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001667 // Since the entries were cleared, the attribute resource id has yet been mapped to any value.
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001668 keys_.insert(key_it, dest_attr_id);
1669 entries_.insert(entry_it, Entry{data_dest_cookie, entry.type_spec_flags,
1670 Res_value{.dataType = entry.value.dataType,
1671 .data = attribute_data}});
Adam Lesinski7ad11102016-10-28 16:39:15 -07001672 }
1673 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001674 return {};
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001675}
1676
1677void Theme::Dump() const {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001678 LOG(INFO) << base::StringPrintf("Theme(this=%p, AssetManager2=%p)", this, asset_manager_);
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001679 for (size_t i = 0, size = keys_.size(); i != size; ++i) {
1680 auto res_id = keys_[i];
1681 const auto& entry = entries_[i];
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001682 LOG(INFO) << base::StringPrintf(" entry(0x%08x)=(0x%08x) type=(0x%02x), cookie(%d)",
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001683 res_id, entry.value.data, entry.value.dataType,
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001684 entry.cookie);
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001685 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001686}
1687
1688} // namespace android