blob: 68f5e4a88c7ef39331d9f6cf928314137fd8ead7 [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(
635 Resolution::Step{Resolution::Step::Type::OVERLAID_INLINE, String8(), result->cookie});
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(
Ryan Mitchell80094e32020-11-16 23:08:18 +0000685 Resolution::Step{Resolution::Step::Type::OVERLAID, overlay_result->config.toString(),
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800686 overlay_result->cookie});
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,
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800772 this_config.toString(),
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800773 cookie});
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800774 }
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800775 continue;
776 }
777
778 // The configuration matches and is better than the previous selection.
779 // Find the entry value if it exists for this configuration.
780 const auto& type = type_entry->type;
781 const auto offset = LoadedPackage::GetEntryOffset(type, entry_idx);
782 if (UNLIKELY(IsIOError(offset))) {
783 return base::unexpected(offset.error());
784 }
785
786 if (!offset.has_value()) {
787 if (UNLIKELY(logging_enabled)) {
Jackal Guo552b45d2021-09-29 10:52:19 +0800788 last_resolution_.steps.push_back(Resolution::Step{Resolution::Step::Type::NO_ENTRY,
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800789 this_config.toString(),
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800790 cookie});
791 }
792 continue;
793 }
794
795 best_cookie = cookie;
796 best_package = loaded_package;
797 best_type = type;
798 best_config = &this_config;
799 best_offset = offset.value();
800
801 if (UNLIKELY(logging_enabled)) {
802 last_resolution_.steps.push_back(Resolution::Step{resolution_type,
803 this_config.toString(),
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800804 cookie});
805 }
806
807 // Any configuration will suffice, so break.
808 if (stop_at_first_match) {
809 break;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700810 }
811 }
812 }
813
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800814 if (UNLIKELY(best_cookie == kInvalidCookie)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000815 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700816 }
817
Eric Miao368cd192022-09-09 15:46:14 -0700818 auto best_entry_verified = LoadedPackage::GetEntryFromOffset(best_type, best_offset);
819 if (!best_entry_verified.has_value()) {
820 return base::unexpected(best_entry_verified.error());
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800821 }
822
Eric Miao368cd192022-09-09 15:46:14 -0700823 const auto entry = GetEntryValue(*best_entry_verified);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000824 if (!entry.has_value()) {
825 return base::unexpected(entry.error());
826 }
Winson2f3669b2019-01-11 11:28:34 -0800827
Ryan Mitchell80094e32020-11-16 23:08:18 +0000828 return FindEntryResult{
829 .cookie = best_cookie,
830 .entry = *entry,
831 .config = *best_config,
832 .type_flags = type_flags,
833 .package_name = &best_package->GetPackageName(),
834 .type_string_ref = StringPoolRef(best_package->GetTypeStringPool(), best_type->id - 1),
835 .entry_string_ref = StringPoolRef(best_package->GetKeyStringPool(),
Eric Miao368cd192022-09-09 15:46:14 -0700836 (*best_entry_verified)->key()),
Ryan Mitchell80094e32020-11-16 23:08:18 +0000837 .dynamic_ref_table = package_group.dynamic_ref_table.get(),
838 };
Adam Lesinski7ad11102016-10-28 16:39:15 -0700839}
840
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700841void AssetManager2::ResetResourceResolution() const {
842 last_resolution_.cookie = kInvalidCookie;
843 last_resolution_.resid = 0;
844 last_resolution_.steps.clear();
845 last_resolution_.type_string_ref = StringPoolRef();
846 last_resolution_.entry_string_ref = StringPoolRef();
Jackal Guo552b45d2021-09-29 10:52:19 +0800847 last_resolution_.best_config_name.clear();
848 last_resolution_.best_package_name.clear();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700849}
850
Winson2f3669b2019-01-11 11:28:34 -0800851void AssetManager2::SetResourceResolutionLoggingEnabled(bool enabled) {
852 resource_resolution_logging_enabled_ = enabled;
Winson2f3669b2019-01-11 11:28:34 -0800853 if (!enabled) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700854 ResetResourceResolution();
Winson2f3669b2019-01-11 11:28:34 -0800855 }
856}
857
858std::string AssetManager2::GetLastResourceResolution() const {
859 if (!resource_resolution_logging_enabled_) {
860 LOG(ERROR) << "Must enable resource resolution logging before getting path.";
Ryan Mitchell80094e32020-11-16 23:08:18 +0000861 return {};
Winson2f3669b2019-01-11 11:28:34 -0800862 }
863
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800864 const ApkAssetsCookie cookie = last_resolution_.cookie;
Winson2f3669b2019-01-11 11:28:34 -0800865 if (cookie == kInvalidCookie) {
866 LOG(ERROR) << "AssetManager hasn't resolved a resource to read resolution path.";
Ryan Mitchell80094e32020-11-16 23:08:18 +0000867 return {};
Winson2f3669b2019-01-11 11:28:34 -0800868 }
869
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800870 const uint32_t resid = last_resolution_.resid;
871 const auto package = apk_assets_[cookie]->GetLoadedArsc()->GetPackageById(get_package_id(resid));
872
Winson2f3669b2019-01-11 11:28:34 -0800873 std::string resource_name_string;
Winson2f3669b2019-01-11 11:28:34 -0800874 if (package != nullptr) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000875 auto resource_name = ToResourceName(last_resolution_.type_string_ref,
876 last_resolution_.entry_string_ref,
877 package->GetPackageName());
878 resource_name_string = resource_name.has_value() ?
879 ToFormattedResourceString(resource_name.value()) : "<unknown>";
Winson2f3669b2019-01-11 11:28:34 -0800880 }
881
882 std::stringstream log_stream;
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800883 log_stream << base::StringPrintf("Resolution for 0x%08x %s\n"
884 "\tFor config - %s", resid, resource_name_string.c_str(),
885 configuration_.toString().c_str());
Winson2f3669b2019-01-11 11:28:34 -0800886
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800887 for (const Resolution::Step& step : last_resolution_.steps) {
888 const static std::unordered_map<Resolution::Step::Type, const char*> kStepStrings = {
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800889 {Resolution::Step::Type::INITIAL, "Found initial"},
890 {Resolution::Step::Type::BETTER_MATCH, "Found better"},
891 {Resolution::Step::Type::OVERLAID, "Overlaid"},
892 {Resolution::Step::Type::OVERLAID_INLINE, "Overlaid inline"},
893 {Resolution::Step::Type::SKIPPED, "Skipped"},
894 {Resolution::Step::Type::NO_ENTRY, "No entry"}
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800895 };
896
897 const auto prefix = kStepStrings.find(step.type);
898 if (prefix == kStepStrings.end()) {
899 continue;
Winson2f3669b2019-01-11 11:28:34 -0800900 }
901
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800902 log_stream << "\n\t" << prefix->second << ": " << apk_assets_[step.cookie]->GetDebugName();
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800903 if (!step.config_name.isEmpty()) {
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800904 log_stream << " - " << step.config_name;
Winson2f3669b2019-01-11 11:28:34 -0800905 }
906 }
907
Jackal Guo552b45d2021-09-29 10:52:19 +0800908 log_stream << "\nBest matching is from "
909 << (last_resolution_.best_config_name.isEmpty() ? "default"
910 : last_resolution_.best_config_name)
911 << " configuration of " << last_resolution_.best_package_name;
Winson2f3669b2019-01-11 11:28:34 -0800912 return log_stream.str();
913}
914
Felka Chang00964e92021-12-10 01:19:08 +0800915base::expected<uint32_t, NullOrIOError> AssetManager2::GetParentThemeResourceId(uint32_t resid)
916const {
917 auto entry = FindEntry(resid, 0u /* density_override */,
918 false /* stop_at_first_match */,
919 false /* ignore_configuration */);
920 if (!entry.has_value()) {
921 return base::unexpected(entry.error());
922 }
923
924 auto entry_map = std::get_if<incfs::verified_map_ptr<ResTable_map_entry>>(&entry->entry);
925 if (entry_map == nullptr) {
926 // Not a bag, nothing to do.
927 return base::unexpected(std::nullopt);
928 }
929
930 auto map = *entry_map;
931 const uint32_t parent_resid = dtohl(map->parent.ident);
932
933 return parent_resid;
934}
935
Ryan Mitchell80094e32020-11-16 23:08:18 +0000936base::expected<AssetManager2::ResourceName, NullOrIOError> AssetManager2::GetResourceName(
937 uint32_t resid) const {
938 auto result = FindEntry(resid, 0u /* density_override */, true /* stop_at_first_match */,
939 true /* ignore_configuration */);
940 if (!result.has_value()) {
941 return base::unexpected(result.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -0700942 }
943
Ryan Mitchell80094e32020-11-16 23:08:18 +0000944 return ToResourceName(result->type_string_ref,
945 result->entry_string_ref,
946 *result->package_name);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700947}
948
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800949base::expected<uint32_t, NullOrIOError> AssetManager2::GetResourceTypeSpecFlags(
950 uint32_t resid) const {
951 auto result = FindEntry(resid, 0u /* density_override */, false /* stop_at_first_match */,
952 true /* ignore_configuration */);
953 if (!result.has_value()) {
954 return base::unexpected(result.error());
955 }
956 return result->type_flags;
957}
958
Ryan Mitchell80094e32020-11-16 23:08:18 +0000959base::expected<AssetManager2::SelectedValue, NullOrIOError> AssetManager2::GetResource(
960 uint32_t resid, bool may_be_bag, uint16_t density_override) const {
961 auto result = FindEntry(resid, density_override, false /* stop_at_first_match */,
962 false /* ignore_configuration */);
963 if (!result.has_value()) {
964 return base::unexpected(result.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -0700965 }
966
Ryan Mitchell80094e32020-11-16 23:08:18 +0000967 auto result_map_entry = std::get_if<incfs::verified_map_ptr<ResTable_map_entry>>(&result->entry);
Ryan Mitchellbf1f45b2020-09-29 17:22:52 -0700968 if (result_map_entry != nullptr) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700969 if (!may_be_bag) {
970 LOG(ERROR) << base::StringPrintf("Resource %08x is a complex map type.", resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000971 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700972 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800973
974 // Create a reference since we can't represent this complex type as a Res_value.
Ryan Mitchell80094e32020-11-16 23:08:18 +0000975 return SelectedValue(Res_value::TYPE_REFERENCE, resid, result->cookie, result->type_flags,
976 resid, result->config);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700977 }
978
Adam Lesinskida431a22016-12-29 16:08:16 -0500979 // Convert the package ID to the runtime assigned package ID.
Ryan Mitchell80094e32020-11-16 23:08:18 +0000980 Res_value value = std::get<Res_value>(result->entry);
981 result->dynamic_ref_table->lookupResourceValue(&value);
Adam Lesinskida431a22016-12-29 16:08:16 -0500982
Ryan Mitchell80094e32020-11-16 23:08:18 +0000983 return SelectedValue(value.dataType, value.data, result->cookie, result->type_flags,
984 resid, result->config);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700985}
986
Ryan Mitchell80094e32020-11-16 23:08:18 +0000987base::expected<std::monostate, NullOrIOError> AssetManager2::ResolveReference(
Ryan Mitchella45506e2020-11-16 23:08:18 +0000988 AssetManager2::SelectedValue& value, bool cache_value) const {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000989 if (value.type != Res_value::TYPE_REFERENCE || value.data == 0U) {
990 // Not a reference. Nothing to do.
991 return {};
Adam Lesinski0c405242017-01-13 20:47:26 -0800992 }
Ryan Mitchell80094e32020-11-16 23:08:18 +0000993
Ryan Mitchella45506e2020-11-16 23:08:18 +0000994 const uint32_t original_flags = value.flags;
995 const uint32_t original_resid = value.data;
996 if (cache_value) {
997 auto cached_value = cached_resolved_values_.find(value.data);
998 if (cached_value != cached_resolved_values_.end()) {
999 value = cached_value->second;
1000 value.flags |= original_flags;
1001 return {};
1002 }
1003 }
1004
1005 uint32_t combined_flags = 0U;
1006 uint32_t resolve_resid = original_resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001007 constexpr const uint32_t kMaxIterations = 20;
1008 for (uint32_t i = 0U;; i++) {
1009 auto result = GetResource(resolve_resid, true /*may_be_bag*/);
1010 if (!result.has_value()) {
Ryan Mitchelle7ab6272020-11-13 18:06:15 -08001011 value.resid = resolve_resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001012 return base::unexpected(result.error());
1013 }
1014
Ryan Mitchelle7ab6272020-11-13 18:06:15 -08001015 // If resource resolution fails, the value should be set to the last reference that was able to
1016 // be resolved successfully.
1017 value = *result;
1018 value.flags |= combined_flags;
1019
Ryan Mitchell80094e32020-11-16 23:08:18 +00001020 if (result->type != Res_value::TYPE_REFERENCE ||
1021 result->data == Res_value::DATA_NULL_UNDEFINED ||
1022 result->data == resolve_resid || i == kMaxIterations) {
1023 // This reference can't be resolved, so exit now and let the caller deal with it.
Ryan Mitchella45506e2020-11-16 23:08:18 +00001024 if (cache_value) {
1025 cached_resolved_values_[original_resid] = value;
1026 }
1027
1028 // Above value is cached without original_flags to ensure they don't get included in future
1029 // queries that hit the cache
1030 value.flags |= original_flags;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001031 return {};
1032 }
1033
Ryan Mitchelle7ab6272020-11-13 18:06:15 -08001034 combined_flags = result->flags;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001035 resolve_resid = result->data;
1036 }
Adam Lesinski0c405242017-01-13 20:47:26 -08001037}
1038
Ryan Mitchell80094e32020-11-16 23:08:18 +00001039const std::vector<uint32_t> AssetManager2::GetBagResIdStack(uint32_t resid) const {
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001040 auto cached_iter = cached_bag_resid_stacks_.find(resid);
1041 if (cached_iter != cached_bag_resid_stacks_.end()) {
1042 return cached_iter->second;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001043 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001044
1045 std::vector<uint32_t> found_resids;
1046 GetBag(resid, found_resids);
1047 cached_bag_resid_stacks_.emplace(resid, found_resids);
1048 return found_resids;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001049}
1050
Ryan Mitchell80094e32020-11-16 23:08:18 +00001051base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::ResolveBag(
1052 AssetManager2::SelectedValue& value) const {
1053 if (UNLIKELY(value.type != Res_value::TYPE_REFERENCE)) {
1054 return base::unexpected(std::nullopt);
1055 }
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001056
Ryan Mitchell80094e32020-11-16 23:08:18 +00001057 auto bag = GetBag(value.data);
1058 if (bag.has_value()) {
1059 value.flags |= (*bag)->type_spec_flags;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001060 }
1061 return bag;
y57cd1952018-04-12 14:26:23 -07001062}
1063
Ryan Mitchell80094e32020-11-16 23:08:18 +00001064base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::GetBag(uint32_t resid) const {
1065 std::vector<uint32_t> found_resids;
1066 const auto bag = GetBag(resid, found_resids);
Yurii Zubrytskyiab3cb302022-10-11 12:15:52 -07001067 cached_bag_resid_stacks_.emplace(resid, std::move(found_resids));
Ryan Mitchell80094e32020-11-16 23:08:18 +00001068 return bag;
Ryan Mitchell155d5392020-02-10 13:35:24 -08001069}
1070
Ryan Mitchell80094e32020-11-16 23:08:18 +00001071base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::GetBag(
1072 uint32_t resid, std::vector<uint32_t>& child_resids) const {
1073 if (auto cached_iter = cached_bags_.find(resid); cached_iter != cached_bags_.end()) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001074 return cached_iter->second.get();
1075 }
1076
Ryan Mitchell80094e32020-11-16 23:08:18 +00001077 auto entry = FindEntry(resid, 0u /* density_override */, false /* stop_at_first_match */,
1078 false /* ignore_configuration */);
1079 if (!entry.has_value()) {
1080 return base::unexpected(entry.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001081 }
1082
Ryan Mitchell80094e32020-11-16 23:08:18 +00001083 auto entry_map = std::get_if<incfs::verified_map_ptr<ResTable_map_entry>>(&entry->entry);
1084 if (entry_map == nullptr) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001085 // Not a bag, nothing to do.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001086 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001087 }
1088
Ryan Mitchell80094e32020-11-16 23:08:18 +00001089 auto map = *entry_map;
1090 auto map_entry = map.offset(dtohs(map->size)).convert<ResTable_map>();
1091 const auto map_entry_end = map_entry + dtohl(map->count);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001092
y57cd1952018-04-12 14:26:23 -07001093 // Keep track of ids that have already been seen to prevent infinite loops caused by circular
Ryan Mitchell80094e32020-11-16 23:08:18 +00001094 // dependencies between bags.
y57cd1952018-04-12 14:26:23 -07001095 child_resids.push_back(resid);
1096
Adam Lesinskida431a22016-12-29 16:08:16 -05001097 uint32_t parent_resid = dtohl(map->parent.ident);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001098 if (parent_resid == 0U ||
1099 std::find(child_resids.begin(), child_resids.end(), parent_resid) != child_resids.end()) {
1100 // There is no parent or a circular parental dependency exist, meaning there is nothing to
1101 // inherit and we can do a simple copy of the entries in the map.
Adam Lesinski7ad11102016-10-28 16:39:15 -07001102 const size_t entry_count = map_entry_end - map_entry;
1103 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
1104 malloc(sizeof(ResolvedBag) + (entry_count * sizeof(ResolvedBag::Entry))))};
Ryan Mitchell155d5392020-02-10 13:35:24 -08001105
1106 bool sort_entries = false;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001107 for (auto new_entry = new_bag->entries; map_entry != map_entry_end; ++map_entry) {
1108 if (UNLIKELY(!map_entry)) {
1109 return base::unexpected(IOError::PAGES_MISSING);
1110 }
1111
Adam Lesinskida431a22016-12-29 16:08:16 -05001112 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001113 if (!is_internal_resid(new_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -05001114 // Attributes, arrays, etc don't have a resource id as the name. They specify
1115 // other data, which would be wrong to change via a lookup.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001116 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001117 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
1118 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001119 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001120 }
1121 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001122
1123 new_entry->cookie = entry->cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -05001124 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001125 new_entry->key_pool = nullptr;
1126 new_entry->type_pool = nullptr;
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001127 new_entry->style = resid;
Adam Lesinski30080e22017-10-16 16:18:09 -07001128 new_entry->value.copyFrom_dtoh(map_entry->value);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001129 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1130 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001131 LOG(ERROR) << base::StringPrintf(
1132 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
1133 new_entry->value.data, new_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001134 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001135 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001136
Ryan Mitchell155d5392020-02-10 13:35:24 -08001137 sort_entries = sort_entries ||
1138 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001139 ++new_entry;
1140 }
Ryan Mitchell155d5392020-02-10 13:35:24 -08001141
1142 if (sort_entries) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001143 std::sort(new_bag->entries, new_bag->entries + entry_count,
1144 [](auto&& lhs, auto&& rhs) { return lhs.key < rhs.key; });
Ryan Mitchell155d5392020-02-10 13:35:24 -08001145 }
1146
Ryan Mitchell80094e32020-11-16 23:08:18 +00001147 new_bag->type_spec_flags = entry->type_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001148 new_bag->entry_count = static_cast<uint32_t>(entry_count);
1149 ResolvedBag* result = new_bag.get();
1150 cached_bags_[resid] = std::move(new_bag);
1151 return result;
1152 }
1153
Adam Lesinskida431a22016-12-29 16:08:16 -05001154 // In case the parent is a dynamic reference, resolve it.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001155 entry->dynamic_ref_table->lookupResourceId(&parent_resid);
Adam Lesinskida431a22016-12-29 16:08:16 -05001156
Adam Lesinski7ad11102016-10-28 16:39:15 -07001157 // Get the parent and do a merge of the keys.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001158 const auto parent_bag = GetBag(parent_resid, child_resids);
1159 if (UNLIKELY(!parent_bag.has_value())) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001160 // Failed to get the parent that should exist.
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001161 LOG(ERROR) << base::StringPrintf("Failed to find parent 0x%08x of bag 0x%08x.", parent_resid,
1162 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001163 return base::unexpected(parent_bag.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001164 }
1165
Adam Lesinski7ad11102016-10-28 16:39:15 -07001166 // Create the max possible entries we can make. Once we construct the bag,
1167 // we will realloc to fit to size.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001168 const size_t max_count = (*parent_bag)->entry_count + dtohl(map->count);
George Burgess IV09b119f2017-07-25 15:00:04 -07001169 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
1170 malloc(sizeof(ResolvedBag) + (max_count * sizeof(ResolvedBag::Entry))))};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001171 ResolvedBag::Entry* new_entry = new_bag->entries;
1172
Ryan Mitchell80094e32020-11-16 23:08:18 +00001173 const ResolvedBag::Entry* parent_entry = (*parent_bag)->entries;
1174 const ResolvedBag::Entry* const parent_entry_end = parent_entry + (*parent_bag)->entry_count;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001175
1176 // The keys are expected to be in sorted order. Merge the two bags.
Ryan Mitchell155d5392020-02-10 13:35:24 -08001177 bool sort_entries = false;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001178 while (map_entry != map_entry_end && parent_entry != parent_entry_end) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001179 if (UNLIKELY(!map_entry)) {
1180 return base::unexpected(IOError::PAGES_MISSING);
1181 }
1182
Adam Lesinskida431a22016-12-29 16:08:16 -05001183 uint32_t child_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001184 if (!is_internal_resid(child_key)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001185 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&child_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001186 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", child_key,
1187 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001188 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001189 }
1190 }
1191
Adam Lesinski7ad11102016-10-28 16:39:15 -07001192 if (child_key <= parent_entry->key) {
1193 // Use the child key if it comes before the parent
1194 // or is equal to the parent (overrides).
Ryan Mitchell80094e32020-11-16 23:08:18 +00001195 new_entry->cookie = entry->cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001196 new_entry->key = child_key;
1197 new_entry->key_pool = nullptr;
1198 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -07001199 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001200 new_entry->style = resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001201 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1202 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001203 LOG(ERROR) << base::StringPrintf(
1204 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
1205 new_entry->value.data, child_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001206 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001207 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001208 ++map_entry;
1209 } else {
1210 // Take the parent entry as-is.
1211 memcpy(new_entry, parent_entry, sizeof(*new_entry));
1212 }
1213
Ryan Mitchell155d5392020-02-10 13:35:24 -08001214 sort_entries = sort_entries ||
1215 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001216 if (child_key >= parent_entry->key) {
1217 // Move to the next parent entry if we used it or it was overridden.
1218 ++parent_entry;
1219 }
1220 // Increment to the next entry to fill.
1221 ++new_entry;
1222 }
1223
1224 // Finish the child entries if they exist.
1225 while (map_entry != map_entry_end) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001226 if (UNLIKELY(!map_entry)) {
1227 return base::unexpected(IOError::PAGES_MISSING);
1228 }
1229
Adam Lesinskida431a22016-12-29 16:08:16 -05001230 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001231 if (!is_internal_resid(new_key)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001232 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001233 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
1234 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001235 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001236 }
1237 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001238 new_entry->cookie = entry->cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -05001239 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001240 new_entry->key_pool = nullptr;
1241 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -07001242 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001243 new_entry->style = resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001244 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1245 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001246 LOG(ERROR) << base::StringPrintf("Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.",
1247 new_entry->value.dataType, new_entry->value.data, new_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001248 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001249 }
Ryan Mitchell155d5392020-02-10 13:35:24 -08001250 sort_entries = sort_entries ||
1251 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001252 ++map_entry;
1253 ++new_entry;
1254 }
1255
1256 // Finish the parent entries if they exist.
1257 if (parent_entry != parent_entry_end) {
1258 // Take the rest of the parent entries as-is.
1259 const size_t num_entries_to_copy = parent_entry_end - parent_entry;
1260 memcpy(new_entry, parent_entry, num_entries_to_copy * sizeof(*new_entry));
1261 new_entry += num_entries_to_copy;
1262 }
1263
1264 // Resize the resulting array to fit.
1265 const size_t actual_count = new_entry - new_bag->entries;
1266 if (actual_count != max_count) {
George Burgess IV09b119f2017-07-25 15:00:04 -07001267 new_bag.reset(reinterpret_cast<ResolvedBag*>(realloc(
1268 new_bag.release(), sizeof(ResolvedBag) + (actual_count * sizeof(ResolvedBag::Entry)))));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001269 }
1270
Ryan Mitchell155d5392020-02-10 13:35:24 -08001271 if (sort_entries) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001272 std::sort(new_bag->entries, new_bag->entries + actual_count,
1273 [](auto&& lhs, auto&& rhs) { return lhs.key < rhs.key; });
Ryan Mitchell155d5392020-02-10 13:35:24 -08001274 }
1275
Adam Lesinski1a1e9c22017-10-13 15:45:34 -07001276 // Combine flags from the parent and our own bag.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001277 new_bag->type_spec_flags = entry->type_flags | (*parent_bag)->type_spec_flags;
George Burgess IV09b119f2017-07-25 15:00:04 -07001278 new_bag->entry_count = static_cast<uint32_t>(actual_count);
1279 ResolvedBag* result = new_bag.get();
1280 cached_bags_[resid] = std::move(new_bag);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001281 return result;
1282}
1283
Yurii Zubrytskyia5775142022-11-02 17:49:49 -07001284static bool Utf8ToUtf16(StringPiece str, std::u16string* out) {
Adam Lesinski929d6512017-01-16 19:11:19 -08001285 ssize_t len =
1286 utf8_to_utf16_length(reinterpret_cast<const uint8_t*>(str.data()), str.size(), false);
1287 if (len < 0) {
1288 return false;
1289 }
1290 out->resize(static_cast<size_t>(len));
1291 utf8_to_utf16(reinterpret_cast<const uint8_t*>(str.data()), str.size(), &*out->begin(),
1292 static_cast<size_t>(len + 1));
1293 return true;
1294}
1295
Ryan Mitchell80094e32020-11-16 23:08:18 +00001296base::expected<uint32_t, NullOrIOError> AssetManager2::GetResourceId(
1297 const std::string& resource_name, const std::string& fallback_type,
1298 const std::string& fallback_package) const {
Adam Lesinski929d6512017-01-16 19:11:19 -08001299 StringPiece package_name, type, entry;
1300 if (!ExtractResourceName(resource_name, &package_name, &type, &entry)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001301 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001302 }
1303
1304 if (entry.empty()) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001305 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001306 }
1307
1308 if (package_name.empty()) {
1309 package_name = fallback_package;
1310 }
1311
1312 if (type.empty()) {
1313 type = fallback_type;
1314 }
1315
1316 std::u16string type16;
1317 if (!Utf8ToUtf16(type, &type16)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001318 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001319 }
1320
1321 std::u16string entry16;
1322 if (!Utf8ToUtf16(entry, &entry16)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001323 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001324 }
1325
1326 const StringPiece16 kAttr16 = u"attr";
1327 const static std::u16string kAttrPrivate16 = u"^attr-private";
1328
1329 for (const PackageGroup& package_group : package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001330 for (const ConfiguredPackage& package_impl : package_group.packages_) {
1331 const LoadedPackage* package = package_impl.loaded_package_;
Adam Lesinski929d6512017-01-16 19:11:19 -08001332 if (package_name != package->GetPackageName()) {
1333 // All packages in the same group are expected to have the same package name.
1334 break;
1335 }
1336
Ryan Mitchell80094e32020-11-16 23:08:18 +00001337 base::expected<uint32_t, NullOrIOError> resid = package->FindEntryByName(type16, entry16);
1338 if (UNLIKELY(IsIOError(resid))) {
1339 return base::unexpected(resid.error());
1340 }
1341
1342 if (!resid.has_value() && kAttr16 == type16) {
Adam Lesinski929d6512017-01-16 19:11:19 -08001343 // Private attributes in libraries (such as the framework) are sometimes encoded
1344 // under the type '^attr-private' in order to leave the ID space of public 'attr'
1345 // free for future additions. Check '^attr-private' for the same name.
1346 resid = package->FindEntryByName(kAttrPrivate16, entry16);
1347 }
1348
Ryan Mitchell80094e32020-11-16 23:08:18 +00001349 if (resid.has_value()) {
1350 return fix_package_id(*resid, package_group.dynamic_ref_table->mAssignedPackageId);
Adam Lesinski929d6512017-01-16 19:11:19 -08001351 }
1352 }
1353 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001354 return base::unexpected(std::nullopt);
Adam Lesinski0c405242017-01-13 20:47:26 -08001355}
1356
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001357void AssetManager2::RebuildFilterList() {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001358 for (PackageGroup& group : package_groups_) {
Yurii Zubrytskyidbce3562022-11-14 22:26:10 -08001359 for (ConfiguredPackage& package : group.packages_) {
1360 package.filtered_configs_.forEachItem([](auto, auto& fcg) { fcg.type_entries.clear(); });
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001361 // Create the filters here.
Yurii Zubrytskyidbce3562022-11-14 22:26:10 -08001362 package.loaded_package_->ForEachTypeSpec([&](const TypeSpec& type_spec, uint8_t type_id) {
Yurii Zubrytskyi59dab3b2022-11-03 00:08:49 -07001363 FilteredConfigGroup* group = nullptr;
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001364 for (const auto& type_entry : type_spec.type_entries) {
1365 if (type_entry.config.match(configuration_)) {
Yurii Zubrytskyi59dab3b2022-11-03 00:08:49 -07001366 if (!group) {
Yurii Zubrytskyidbce3562022-11-14 22:26:10 -08001367 group = &package.filtered_configs_.editItemAt(type_id - 1);
Yurii Zubrytskyi59dab3b2022-11-03 00:08:49 -07001368 }
1369 group->type_entries.push_back(&type_entry);
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001370 }
1371 }
1372 });
Yurii Zubrytskyidbce3562022-11-14 22:26:10 -08001373 package.filtered_configs_.trimBuckets(
1374 [](const auto& fcg) { return fcg.type_entries.empty(); });
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001375 }
1376 }
1377}
1378
Adam Lesinski7ad11102016-10-28 16:39:15 -07001379void AssetManager2::InvalidateCaches(uint32_t diff) {
Ryan Mitchell2c4d8742019-03-04 09:41:00 -08001380 cached_bag_resid_stacks_.clear();
1381
Adam Lesinski7ad11102016-10-28 16:39:15 -07001382 if (diff == 0xffffffffu) {
1383 // Everything must go.
1384 cached_bags_.clear();
1385 return;
1386 }
1387
1388 // Be more conservative with what gets purged. Only if the bag has other possible
1389 // variations with respect to what changed (diff) should we remove it.
1390 for (auto iter = cached_bags_.cbegin(); iter != cached_bags_.cend();) {
1391 if (diff & iter->second->type_spec_flags) {
1392 iter = cached_bags_.erase(iter);
1393 } else {
1394 ++iter;
1395 }
1396 }
Ryan Mitchella45506e2020-11-16 23:08:18 +00001397
1398 cached_resolved_values_.clear();
Adam Lesinski7ad11102016-10-28 16:39:15 -07001399}
1400
Ryan Mitchell2e394222019-08-28 12:10:51 -07001401uint8_t AssetManager2::GetAssignedPackageId(const LoadedPackage* package) const {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001402 for (auto& package_group : package_groups_) {
1403 for (auto& package2 : package_group.packages_) {
1404 if (package2.loaded_package_ == package) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -07001405 return package_group.dynamic_ref_table->mAssignedPackageId;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001406 }
1407 }
1408 }
1409 return 0;
1410}
1411
Adam Lesinski30080e22017-10-16 16:18:09 -07001412std::unique_ptr<Theme> AssetManager2::NewTheme() {
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001413 constexpr size_t kInitialReserveSize = 32;
1414 auto theme = std::unique_ptr<Theme>(new Theme(this));
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001415 theme->keys_.reserve(kInitialReserveSize);
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001416 theme->entries_.reserve(kInitialReserveSize);
1417 return theme;
Adam Lesinski30080e22017-10-16 16:18:09 -07001418}
1419
Yurii Zubrytskyi9eb44c92022-11-14 23:44:52 -08001420void AssetManager2::ForEachPackage(base::function_ref<bool(const std::string&, uint8_t)> func,
1421 package_property_t excluded_property_flags) const {
1422 for (const PackageGroup& package_group : package_groups_) {
1423 const auto loaded_package = package_group.packages_.front().loaded_package_;
1424 if ((loaded_package->GetPropertyFlags() & excluded_property_flags) == 0U
1425 && !func(loaded_package->GetPackageName(),
1426 package_group.dynamic_ref_table->mAssignedPackageId)) {
1427 return;
1428 }
1429 }
1430}
1431
Adam Lesinski30080e22017-10-16 16:18:09 -07001432Theme::Theme(AssetManager2* asset_manager) : asset_manager_(asset_manager) {
1433}
1434
1435Theme::~Theme() = default;
1436
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001437struct Theme::Entry {
Adam Lesinski30080e22017-10-16 16:18:09 -07001438 ApkAssetsCookie cookie;
1439 uint32_t type_spec_flags;
1440 Res_value value;
1441};
1442
Ryan Mitchell80094e32020-11-16 23:08:18 +00001443base::expected<std::monostate, NullOrIOError> Theme::ApplyStyle(uint32_t resid, bool force) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001444 ATRACE_NAME("Theme::ApplyStyle");
Adam Lesinski7ad11102016-10-28 16:39:15 -07001445
Ryan Mitchell80094e32020-11-16 23:08:18 +00001446 auto bag = asset_manager_->GetBag(resid);
1447 if (!bag.has_value()) {
1448 return base::unexpected(bag.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001449 }
1450
1451 // Merge the flags from this style.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001452 type_spec_flags_ |= (*bag)->type_spec_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001453
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001454 for (auto it = begin(*bag); it != end(*bag); ++it) {
1455 const uint32_t attr_res_id = it->key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001456
Adam Lesinski30080e22017-10-16 16:18:09 -07001457 // If the resource ID passed in is not a style, the key can be some other identifier that is not
1458 // a resource ID. We should fail fast instead of operating with strange resource IDs.
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001459 if (!is_valid_resid(attr_res_id)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001460 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001461 }
1462
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001463 // DATA_NULL_EMPTY (@empty) is a valid resource value and DATA_NULL_UNDEFINED represents
1464 // an absence of a valid value.
1465 bool is_undefined = it->value.dataType == Res_value::TYPE_NULL &&
1466 it->value.data != Res_value::DATA_NULL_EMPTY;
1467 if (!force && is_undefined) {
1468 continue;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001469 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001470
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001471 const auto key_it = std::lower_bound(keys_.begin(), keys_.end(), attr_res_id);
1472 const auto entry_it = entries_.begin() + (key_it - keys_.begin());
1473 if (key_it != keys_.end() && *key_it == attr_res_id) {
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001474 if (is_undefined) {
1475 // DATA_NULL_UNDEFINED clears the value of the attribute in the theme only when `force` is
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001476 // true.
1477 keys_.erase(key_it);
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001478 entries_.erase(entry_it);
1479 } else if (force) {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001480 *entry_it = Entry{it->cookie, (*bag)->type_spec_flags, it->value};
Adam Lesinski30080e22017-10-16 16:18:09 -07001481 }
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001482 } else {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001483 keys_.insert(key_it, attr_res_id);
1484 entries_.insert(entry_it, Entry{it->cookie, (*bag)->type_spec_flags, it->value});
Adam Lesinski7ad11102016-10-28 16:39:15 -07001485 }
1486 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001487 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001488}
1489
Ryan Mitchell767e34f2021-06-07 12:29:05 -07001490void Theme::Rebase(AssetManager2* am, const uint32_t* style_ids, const uint8_t* force,
1491 size_t style_count) {
1492 ATRACE_NAME("Theme::Rebase");
1493 // Reset the entries without changing the vector capacity to prevent reallocations during
1494 // ApplyStyle.
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001495 keys_.clear();
Ryan Mitchell767e34f2021-06-07 12:29:05 -07001496 entries_.clear();
1497 asset_manager_ = am;
1498 for (size_t i = 0; i < style_count; i++) {
1499 ApplyStyle(style_ids[i], force[i]);
1500 }
1501}
1502
Ryan Mitchell80094e32020-11-16 23:08:18 +00001503std::optional<AssetManager2::SelectedValue> Theme::GetAttribute(uint32_t resid) const {
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001504 constexpr const uint32_t kMaxIterations = 20;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001505 uint32_t type_spec_flags = 0u;
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001506 for (uint32_t i = 0; i <= kMaxIterations; i++) {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001507 const auto key_it = std::lower_bound(keys_.begin(), keys_.end(), resid);
1508 if (key_it == keys_.end() || *key_it != resid) {
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001509 return std::nullopt;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001510 }
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001511 const auto entry_it = entries_.begin() + (key_it - keys_.begin());
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001512 type_spec_flags |= entry_it->type_spec_flags;
1513 if (entry_it->value.dataType == Res_value::TYPE_ATTRIBUTE) {
1514 resid = entry_it->value.data;
1515 continue;
1516 }
1517
1518 return AssetManager2::SelectedValue(entry_it->value.dataType, entry_it->value.data,
1519 entry_it->cookie, type_spec_flags, 0U /* resid */,
1520 {} /* config */);
1521 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001522 return std::nullopt;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001523}
1524
Ryan Mitchell80094e32020-11-16 23:08:18 +00001525base::expected<std::monostate, NullOrIOError> Theme::ResolveAttributeReference(
1526 AssetManager2::SelectedValue& value) const {
1527 if (value.type != Res_value::TYPE_ATTRIBUTE) {
1528 return asset_manager_->ResolveReference(value);
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001529 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001530
1531 std::optional<AssetManager2::SelectedValue> result = GetAttribute(value.data);
1532 if (!result.has_value()) {
1533 return base::unexpected(std::nullopt);
1534 }
1535
Ryan Mitchella45506e2020-11-16 23:08:18 +00001536 auto resolve_result = asset_manager_->ResolveReference(*result, true /* cache_value */);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001537 if (resolve_result.has_value()) {
1538 result->flags |= value.flags;
1539 value = *result;
1540 }
1541 return resolve_result;
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001542}
1543
Adam Lesinski7ad11102016-10-28 16:39:15 -07001544void Theme::Clear() {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001545 keys_.clear();
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001546 entries_.clear();
Adam Lesinski7ad11102016-10-28 16:39:15 -07001547}
1548
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001549base::expected<std::monostate, IOError> Theme::SetTo(const Theme& source) {
1550 if (this == &source) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001551 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001552 }
1553
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001554 type_spec_flags_ = source.type_spec_flags_;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001555
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001556 if (asset_manager_ == source.asset_manager_) {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001557 keys_ = source.keys_;
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001558 entries_ = source.entries_;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001559 } else {
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001560 std::unordered_map<ApkAssetsCookie, ApkAssetsCookie> src_to_dest_asset_cookies;
1561 using SourceToDestinationRuntimePackageMap = std::unordered_map<int, int>;
1562 std::unordered_map<ApkAssetsCookie, SourceToDestinationRuntimePackageMap> src_asset_cookie_id_map;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001563
Ryan Mitchell93bca972019-03-08 17:26:28 -08001564 // Determine which ApkAssets are loaded in both theme AssetManagers.
Yurii Zubrytskyia5bc9582022-11-30 23:53:59 -08001565 const auto& src_assets = source.asset_manager_->GetApkAssets();
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001566 for (size_t i = 0; i < src_assets.size(); i++) {
1567 const ApkAssets* src_asset = src_assets[i];
1568
Yurii Zubrytskyia5bc9582022-11-30 23:53:59 -08001569 const auto& dest_assets = asset_manager_->GetApkAssets();
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001570 for (size_t j = 0; j < dest_assets.size(); j++) {
1571 const ApkAssets* dest_asset = dest_assets[j];
Ryan Mitchellef538432021-03-01 14:52:14 -08001572 if (src_asset != dest_asset) {
1573 // ResourcesManager caches and reuses ApkAssets when the same apk must be present in
1574 // multiple AssetManagers. Two ApkAssets point to the same version of the same resources
1575 // if they are the same instance.
1576 continue;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001577 }
Ryan Mitchellef538432021-03-01 14:52:14 -08001578
1579 // Map the package ids of the asset in the source AssetManager to the package ids of the
1580 // asset in th destination AssetManager.
1581 SourceToDestinationRuntimePackageMap package_map;
1582 for (const auto& loaded_package : src_asset->GetLoadedArsc()->GetPackages()) {
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001583 const int src_package_id = source.asset_manager_->GetAssignedPackageId(
1584 loaded_package.get());
Ryan Mitchellef538432021-03-01 14:52:14 -08001585 const int dest_package_id = asset_manager_->GetAssignedPackageId(loaded_package.get());
1586 package_map[src_package_id] = dest_package_id;
1587 }
1588
1589 src_to_dest_asset_cookies.insert(std::make_pair(i, j));
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001590 src_asset_cookie_id_map.insert(std::make_pair(i, std::move(package_map)));
Ryan Mitchellef538432021-03-01 14:52:14 -08001591 break;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001592 }
1593 }
1594
Ryan Mitchell93bca972019-03-08 17:26:28 -08001595 // Reset the data in the destination theme.
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001596 keys_.clear();
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001597 entries_.clear();
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001598
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001599 for (size_t i = 0, size = source.entries_.size(); i != size; ++i) {
1600 const auto& entry = source.entries_[i];
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001601 bool is_reference = (entry.value.dataType == Res_value::TYPE_ATTRIBUTE
1602 || entry.value.dataType == Res_value::TYPE_REFERENCE
1603 || entry.value.dataType == Res_value::TYPE_DYNAMIC_ATTRIBUTE
1604 || entry.value.dataType == Res_value::TYPE_DYNAMIC_REFERENCE)
1605 && entry.value.data != 0x0;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001606
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001607 // If the attribute value represents an attribute or reference, the package id of the
1608 // value needs to be rewritten to the package id of the value in the destination.
1609 uint32_t attribute_data = entry.value.data;
1610 if (is_reference) {
1611 // Determine the package id of the reference in the destination AssetManager.
1612 auto value_package_map = src_asset_cookie_id_map.find(entry.cookie);
1613 if (value_package_map == src_asset_cookie_id_map.end()) {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001614 continue;
1615 }
1616
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001617 auto value_dest_package = value_package_map->second.find(
1618 get_package_id(entry.value.data));
1619 if (value_dest_package == value_package_map->second.end()) {
1620 continue;
1621 }
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001622
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001623 attribute_data = fix_package_id(entry.value.data, value_dest_package->second);
1624 }
Ryan Mitchellb85d9b22018-11-19 12:11:38 -08001625
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001626 // Find the cookie of the value in the destination. If the source apk is not loaded in the
1627 // destination, only copy resources that do not reference resources in the source.
1628 ApkAssetsCookie data_dest_cookie;
1629 auto value_dest_cookie = src_to_dest_asset_cookies.find(entry.cookie);
1630 if (value_dest_cookie != src_to_dest_asset_cookies.end()) {
1631 data_dest_cookie = value_dest_cookie->second;
1632 } else {
1633 if (is_reference || entry.value.dataType == Res_value::TYPE_STRING) {
1634 continue;
1635 } else {
1636 data_dest_cookie = 0x0;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001637 }
1638 }
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001639
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001640 const auto source_res_id = source.keys_[i];
1641
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001642 // The package id of the attribute needs to be rewritten to the package id of the
1643 // attribute in the destination.
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001644 int attribute_dest_package_id = get_package_id(source_res_id);
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001645 if (attribute_dest_package_id != 0x01) {
1646 // Find the cookie of the attribute resource id in the source AssetManager
1647 base::expected<FindEntryResult, NullOrIOError> attribute_entry_result =
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001648 source.asset_manager_->FindEntry(source_res_id, 0 /* density_override */ ,
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001649 true /* stop_at_first_match */,
1650 true /* ignore_configuration */);
1651 if (UNLIKELY(IsIOError(attribute_entry_result))) {
1652 return base::unexpected(GetIOError(attribute_entry_result.error()));
1653 }
1654 if (!attribute_entry_result.has_value()) {
1655 continue;
1656 }
1657
1658 // Determine the package id of the attribute in the destination AssetManager.
1659 auto attribute_package_map = src_asset_cookie_id_map.find(
1660 attribute_entry_result->cookie);
1661 if (attribute_package_map == src_asset_cookie_id_map.end()) {
1662 continue;
1663 }
1664 auto attribute_dest_package = attribute_package_map->second.find(
1665 attribute_dest_package_id);
1666 if (attribute_dest_package == attribute_package_map->second.end()) {
1667 continue;
1668 }
1669 attribute_dest_package_id = attribute_dest_package->second;
1670 }
1671
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001672 auto dest_attr_id = make_resid(attribute_dest_package_id, get_type_id(source_res_id),
1673 get_entry_id(source_res_id));
1674 const auto key_it = std::lower_bound(keys_.begin(), keys_.end(), dest_attr_id);
1675 const auto entry_it = entries_.begin() + (key_it - keys_.begin());
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001676 // Since the entries were cleared, the attribute resource id has yet been mapped to any value.
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001677 keys_.insert(key_it, dest_attr_id);
1678 entries_.insert(entry_it, Entry{data_dest_cookie, entry.type_spec_flags,
1679 Res_value{.dataType = entry.value.dataType,
1680 .data = attribute_data}});
Adam Lesinski7ad11102016-10-28 16:39:15 -07001681 }
1682 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001683 return {};
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001684}
1685
1686void Theme::Dump() const {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001687 LOG(INFO) << base::StringPrintf("Theme(this=%p, AssetManager2=%p)", this, asset_manager_);
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001688 for (size_t i = 0, size = keys_.size(); i != size; ++i) {
1689 auto res_id = keys_[i];
1690 const auto& entry = entries_[i];
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001691 LOG(INFO) << base::StringPrintf(" entry(0x%08x)=(0x%08x) type=(0x%02x), cookie(%d)",
Yurii Zubrytskyi591895b2022-11-14 22:06:30 -08001692 res_id, entry.value.data, entry.value.dataType,
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001693 entry.cookie);
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001694 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001695}
1696
1697} // namespace android