blob: 61e842a359cecff4fe6cc36e2beb5b5931f43760 [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.
115 std::unordered_map<std::string, 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.
Ryan Mitchellef538432021-03-01 14:52:14 -0800138 auto iter = target_assets_package_ids.find(std::string(loaded_idmap->TargetApkPath()));
139 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.
183 new_group.dynamic_ref_table = 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
191 // Add the package and to the set of packages with the same ID.
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800192 PackageGroup* package_group = &package_groups_[idx];
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800193 package_group->packages_.push_back(ConfiguredPackage{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.
205 target_assets_package_ids.insert(std::make_pair(std::string(*apk_assets_path), package_id));
206 }
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();
222 aliases.insert(package_aliases.begin(), package_aliases.end());
223 }
224 }
225
226 if (!aliases.empty()) {
227 // Add the alias resources to the dynamic reference table of every package group. Since
228 // staging aliases can only be defined by the framework package (which is not a shared
229 // library), the compile-time package id of the framework is the same across all packages
230 // that compile against the framework.
231 for (auto& group : std::span(package_groups_.data(), package_groups_.size() - 1)) {
232 group.dynamic_ref_table->setAliases(aliases);
233 }
234 package_groups_.back().dynamic_ref_table->setAliases(std::move(aliases));
Adam Lesinskida431a22016-12-29 16:08:16 -0500235 }
236}
237
238void AssetManager2::DumpToLog() const {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800239 LOG(INFO) << base::StringPrintf("AssetManager2(this=%p)", this);
240
Adam Lesinskida431a22016-12-29 16:08:16 -0500241 std::string list;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800242 for (const auto& apk_assets : apk_assets_) {
Ryan Mitchellef538432021-03-01 14:52:14 -0800243 base::StringAppendF(&list, "%s,", apk_assets->GetDebugName().c_str());
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800244 }
245 LOG(INFO) << "ApkAssets: " << list;
246
247 list = "";
Adam Lesinskida431a22016-12-29 16:08:16 -0500248 for (size_t i = 0; i < package_ids_.size(); i++) {
249 if (package_ids_[i] != 0xff) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800250 base::StringAppendF(&list, "%02x -> %d, ", (int)i, package_ids_[i]);
Adam Lesinskida431a22016-12-29 16:08:16 -0500251 }
252 }
253 LOG(INFO) << "Package ID map: " << list;
254
Adam Lesinski0dd36992018-01-25 15:38:38 -0800255 for (const auto& package_group: package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800256 list = "";
257 for (const auto& package : package_group.packages_) {
258 const LoadedPackage* loaded_package = package.loaded_package_;
259 base::StringAppendF(&list, "%s(%02x%s), ", loaded_package->GetPackageName().c_str(),
260 loaded_package->GetPackageId(),
261 (loaded_package->IsDynamic() ? " dynamic" : ""));
262 }
263 LOG(INFO) << base::StringPrintf("PG (%02x): ",
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700264 package_group.dynamic_ref_table->mAssignedPackageId)
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800265 << list;
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800266
267 for (size_t i = 0; i < 256; i++) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700268 if (package_group.dynamic_ref_table->mLookupTable[i] != 0) {
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800269 LOG(INFO) << base::StringPrintf(" e[0x%02x] -> 0x%02x", (uint8_t) i,
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700270 package_group.dynamic_ref_table->mLookupTable[i]);
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800271 }
272 }
Adam Lesinskida431a22016-12-29 16:08:16 -0500273 }
274}
Adam Lesinski7ad11102016-10-28 16:39:15 -0700275
276const ResStringPool* AssetManager2::GetStringPoolForCookie(ApkAssetsCookie cookie) const {
277 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
278 return nullptr;
279 }
280 return apk_assets_[cookie]->GetLoadedArsc()->GetStringPool();
281}
282
Adam Lesinskida431a22016-12-29 16:08:16 -0500283const DynamicRefTable* AssetManager2::GetDynamicRefTableForPackage(uint32_t package_id) const {
284 if (package_id >= package_ids_.size()) {
285 return nullptr;
286 }
287
288 const size_t idx = package_ids_[package_id];
289 if (idx == 0xff) {
290 return nullptr;
291 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700292 return package_groups_[idx].dynamic_ref_table.get();
Adam Lesinskida431a22016-12-29 16:08:16 -0500293}
294
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700295std::shared_ptr<const DynamicRefTable> AssetManager2::GetDynamicRefTableForCookie(
296 ApkAssetsCookie cookie) const {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800297 for (const PackageGroup& package_group : package_groups_) {
298 for (const ApkAssetsCookie& package_cookie : package_group.cookies_) {
299 if (package_cookie == cookie) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700300 return package_group.dynamic_ref_table;
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800301 }
302 }
303 }
304 return nullptr;
305}
306
MÃ¥rten Kongstadc92c4dd2019-02-05 01:29:59 +0100307const std::unordered_map<std::string, std::string>*
308 AssetManager2::GetOverlayableMapForPackage(uint32_t package_id) const {
309
310 if (package_id >= package_ids_.size()) {
311 return nullptr;
312 }
313
314 const size_t idx = package_ids_[package_id];
315 if (idx == 0xff) {
316 return nullptr;
317 }
318
319 const PackageGroup& package_group = package_groups_[idx];
Ryan Mitchell80094e32020-11-16 23:08:18 +0000320 if (package_group.packages_.empty()) {
MÃ¥rten Kongstadc92c4dd2019-02-05 01:29:59 +0100321 return nullptr;
322 }
323
324 const auto loaded_package = package_group.packages_[0].loaded_package_;
325 return &loaded_package->GetOverlayableMap();
326}
327
Yurii Zubrytskyia5775142022-11-02 17:49:49 -0700328bool AssetManager2::GetOverlayablesToString(android::StringPiece package_name,
Ryan Mitchell2e394222019-08-28 12:10:51 -0700329 std::string* out) const {
330 uint8_t package_id = 0U;
331 for (const auto& apk_assets : apk_assets_) {
332 const LoadedArsc* loaded_arsc = apk_assets->GetLoadedArsc();
333 if (loaded_arsc == nullptr) {
334 continue;
335 }
336
337 const auto& loaded_packages = loaded_arsc->GetPackages();
338 if (loaded_packages.empty()) {
339 continue;
340 }
341
342 const auto& loaded_package = loaded_packages[0];
343 if (loaded_package->GetPackageName() == package_name) {
344 package_id = GetAssignedPackageId(loaded_package.get());
345 break;
346 }
347 }
348
349 if (package_id == 0U) {
350 ANDROID_LOG(ERROR) << base::StringPrintf("No package with name '%s", package_name.data());
351 return false;
352 }
353
354 const size_t idx = package_ids_[package_id];
355 if (idx == 0xff) {
356 return false;
357 }
358
359 std::string output;
360 for (const ConfiguredPackage& package : package_groups_[idx].packages_) {
361 const LoadedPackage* loaded_package = package.loaded_package_;
362 for (auto it = loaded_package->begin(); it != loaded_package->end(); it++) {
363 const OverlayableInfo* info = loaded_package->GetOverlayableInfo(*it);
364 if (info != nullptr) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000365 auto res_name = GetResourceName(*it);
366 if (!res_name.has_value()) {
Ryan Mitchell2e394222019-08-28 12:10:51 -0700367 ANDROID_LOG(ERROR) << base::StringPrintf(
368 "Unable to retrieve name of overlayable resource 0x%08x", *it);
369 return false;
370 }
371
Ryan Mitchell80094e32020-11-16 23:08:18 +0000372 const std::string name = ToFormattedResourceString(*res_name);
Ryan Mitchell2e394222019-08-28 12:10:51 -0700373 output.append(base::StringPrintf(
374 "resource='%s' overlayable='%s' actor='%s' policy='0x%08x'\n",
375 name.c_str(), info->name.c_str(), info->actor.c_str(), info->policy_flags));
376 }
377 }
378 }
379
380 *out = std::move(output);
381 return true;
382}
383
Ryan Mitchell192400c2020-04-02 09:54:23 -0700384bool AssetManager2::ContainsAllocatedTable() const {
385 return std::find_if(apk_assets_.begin(), apk_assets_.end(),
386 std::mem_fn(&ApkAssets::IsTableAllocated)) != apk_assets_.end();
387}
388
Adam Lesinski7ad11102016-10-28 16:39:15 -0700389void AssetManager2::SetConfiguration(const ResTable_config& configuration) {
390 const int diff = configuration_.diff(configuration);
391 configuration_ = configuration;
392
393 if (diff) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800394 RebuildFilterList();
Adam Lesinski7ad11102016-10-28 16:39:15 -0700395 InvalidateCaches(static_cast<uint32_t>(diff));
396 }
397}
398
Ryan Mitchellef538432021-03-01 14:52:14 -0800399std::set<const ApkAssets*> AssetManager2::GetNonSystemOverlays() const {
400 std::set<const ApkAssets*> non_system_overlays;
Adam Lesinski0c405242017-01-13 20:47:26 -0800401 for (const PackageGroup& package_group : package_groups_) {
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800402 bool found_system_package = false;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800403 for (const ConfiguredPackage& package : package_group.packages_) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700404 if (package.loaded_package_->IsSystem()) {
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800405 found_system_package = true;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700406 break;
407 }
408 }
409
410 if (!found_system_package) {
411 for (const ConfiguredOverlay& overlay : package_group.overlays_) {
Ryan Mitchellef538432021-03-01 14:52:14 -0800412 non_system_overlays.insert(apk_assets_[overlay.cookie]);
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700413 }
414 }
415 }
416
417 return non_system_overlays;
418}
419
Ryan Mitchell80094e32020-11-16 23:08:18 +0000420base::expected<std::set<ResTable_config>, IOError> AssetManager2::GetResourceConfigurations(
421 bool exclude_system, bool exclude_mipmap) const {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700422 ATRACE_NAME("AssetManager::GetResourceConfigurations");
423 const auto non_system_overlays =
Ryan Mitchellef538432021-03-01 14:52:14 -0800424 (exclude_system) ? GetNonSystemOverlays() : std::set<const ApkAssets*>();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700425
426 std::set<ResTable_config> configurations;
427 for (const PackageGroup& package_group : package_groups_) {
428 for (size_t i = 0; i < package_group.packages_.size(); i++) {
429 const ConfiguredPackage& package = package_group.packages_[i];
430 if (exclude_system && package.loaded_package_->IsSystem()) {
Adam Lesinski0c405242017-01-13 20:47:26 -0800431 continue;
432 }
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800433
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700434 auto apk_assets = apk_assets_[package_group.cookies_[i]];
Ryan Mitchellef538432021-03-01 14:52:14 -0800435 if (exclude_system && apk_assets->IsOverlay() &&
436 non_system_overlays.find(apk_assets) == non_system_overlays.end()) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700437 // Exclude overlays that target system resources.
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800438 continue;
439 }
440
Ryan Mitchell80094e32020-11-16 23:08:18 +0000441 auto result = package.loaded_package_->CollectConfigurations(exclude_mipmap, &configurations);
442 if (UNLIKELY(!result.has_value())) {
443 return base::unexpected(result.error());
444 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800445 }
446 }
447 return configurations;
448}
449
450std::set<std::string> AssetManager2::GetResourceLocales(bool exclude_system,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800451 bool merge_equivalent_languages) const {
452 ATRACE_NAME("AssetManager::GetResourceLocales");
Adam Lesinski0c405242017-01-13 20:47:26 -0800453 std::set<std::string> locales;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700454 const auto non_system_overlays =
Ryan Mitchellef538432021-03-01 14:52:14 -0800455 (exclude_system) ? GetNonSystemOverlays() : std::set<const ApkAssets*>();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700456
Adam Lesinski0c405242017-01-13 20:47:26 -0800457 for (const PackageGroup& package_group : package_groups_) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700458 for (size_t i = 0; i < package_group.packages_.size(); i++) {
459 const ConfiguredPackage& package = package_group.packages_[i];
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800460 if (exclude_system && package.loaded_package_->IsSystem()) {
Adam Lesinski0c405242017-01-13 20:47:26 -0800461 continue;
462 }
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800463
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700464 auto apk_assets = apk_assets_[package_group.cookies_[i]];
Ryan Mitchellef538432021-03-01 14:52:14 -0800465 if (exclude_system && apk_assets->IsOverlay() &&
466 non_system_overlays.find(apk_assets) == non_system_overlays.end()) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700467 // Exclude overlays that target system resources.
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800468 continue;
469 }
470
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800471 package.loaded_package_->CollectLocales(merge_equivalent_languages, &locales);
Adam Lesinski0c405242017-01-13 20:47:26 -0800472 }
473 }
474 return locales;
475}
476
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800477std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename,
478 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700479 const std::string new_path = "assets/" + filename;
480 return OpenNonAsset(new_path, mode);
481}
482
483std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename, ApkAssetsCookie cookie,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800484 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700485 const std::string new_path = "assets/" + filename;
486 return OpenNonAsset(new_path, cookie, mode);
487}
488
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800489std::unique_ptr<AssetDir> AssetManager2::OpenDir(const std::string& dirname) const {
490 ATRACE_NAME("AssetManager::OpenDir");
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800491
492 std::string full_path = "assets/" + dirname;
493 std::unique_ptr<SortedVector<AssetDir::FileInfo>> files =
494 util::make_unique<SortedVector<AssetDir::FileInfo>>();
495
496 // Start from the back.
497 for (auto iter = apk_assets_.rbegin(); iter != apk_assets_.rend(); ++iter) {
498 const ApkAssets* apk_assets = *iter;
MÃ¥rten Kongstaddbf343b2019-02-21 07:54:18 +0100499 if (apk_assets->IsOverlay()) {
500 continue;
501 }
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800502
Yurii Zubrytskyia5775142022-11-02 17:49:49 -0700503 auto func = [&](StringPiece name, FileType type) {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800504 AssetDir::FileInfo info;
505 info.setFileName(String8(name.data(), name.size()));
506 info.setFileType(type);
Ryan Mitchellef538432021-03-01 14:52:14 -0800507 info.setSourceName(String8(apk_assets->GetDebugName().c_str()));
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800508 files->add(info);
509 };
510
Ryan Mitchellc07aa702020-03-10 13:49:12 -0700511 if (!apk_assets->GetAssetsProvider()->ForEachFile(full_path, func)) {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800512 return {};
513 }
514 }
515
516 std::unique_ptr<AssetDir> asset_dir = util::make_unique<AssetDir>();
517 asset_dir->setFileList(files.release());
518 return asset_dir;
519}
520
Adam Lesinski7ad11102016-10-28 16:39:15 -0700521// Search in reverse because that's how we used to do it and we need to preserve behaviour.
522// This is unfortunate, because ClassLoaders delegate to the parent first, so the order
523// is inconsistent for split APKs.
524std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
525 Asset::AccessMode mode,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800526 ApkAssetsCookie* out_cookie) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700527 for (int32_t i = apk_assets_.size() - 1; i >= 0; i--) {
MÃ¥rten Kongstaddbf343b2019-02-21 07:54:18 +0100528 // Prevent RRO from modifying assets and other entries accessed by file
529 // path. Explicitly asking for a path in a given package (denoted by a
530 // cookie) is still OK.
531 if (apk_assets_[i]->IsOverlay()) {
532 continue;
533 }
534
Ryan Mitchellc07aa702020-03-10 13:49:12 -0700535 std::unique_ptr<Asset> asset = apk_assets_[i]->GetAssetsProvider()->Open(filename, mode);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700536 if (asset) {
537 if (out_cookie != nullptr) {
538 *out_cookie = i;
539 }
540 return asset;
541 }
542 }
543
544 if (out_cookie != nullptr) {
545 *out_cookie = kInvalidCookie;
546 }
547 return {};
548}
549
550std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800551 ApkAssetsCookie cookie,
552 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700553 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
554 return {};
555 }
Ryan Mitchellc07aa702020-03-10 13:49:12 -0700556 return apk_assets_[cookie]->GetAssetsProvider()->Open(filename, mode);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700557}
558
Ryan Mitchell80094e32020-11-16 23:08:18 +0000559base::expected<FindEntryResult, NullOrIOError> AssetManager2::FindEntry(
560 uint32_t resid, uint16_t density_override, bool stop_at_first_match,
561 bool ignore_configuration) const {
562 const bool logging_enabled = resource_resolution_logging_enabled_;
563 if (UNLIKELY(logging_enabled)) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700564 // Clear the last logged resource resolution.
565 ResetResourceResolution();
566 last_resolution_.resid = resid;
567 }
568
Adam Lesinski7ad11102016-10-28 16:39:15 -0700569 // Might use this if density_override != 0.
570 ResTable_config density_override_config;
571
572 // Select our configuration or generate a density override configuration.
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800573 const ResTable_config* desired_config = &configuration_;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700574 if (density_override != 0 && density_override != configuration_.density) {
575 density_override_config = configuration_;
576 density_override_config.density = density_override;
577 desired_config = &density_override_config;
578 }
579
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700580 // Retrieve the package group from the package id of the resource id.
Ryan Mitchell80094e32020-11-16 23:08:18 +0000581 if (UNLIKELY(!is_valid_resid(resid))) {
Mark Hansenb406b0e2022-10-14 02:18:37 +0000582 LOG(ERROR) << base::StringPrintf("Invalid resource ID 0x%08x.", resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000583 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -0500584 }
585
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800586 const uint32_t package_id = get_package_id(resid);
587 const uint8_t type_idx = get_type_id(resid) - 1;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800588 const uint16_t entry_idx = get_entry_id(resid);
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700589 uint8_t package_idx = package_ids_[package_id];
Ryan Mitchell80094e32020-11-16 23:08:18 +0000590 if (UNLIKELY(package_idx == 0xff)) {
Mark Hansenb406b0e2022-10-14 02:18:37 +0000591 ANDROID_LOG(ERROR) << base::StringPrintf("No package ID %02x found for resource ID 0x%08x.",
Ryan Mitchell2fe23472019-02-27 09:43:01 -0800592 package_id, resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000593 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -0500594 }
595
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800596 const PackageGroup& package_group = package_groups_[package_idx];
Ryan Mitchell80094e32020-11-16 23:08:18 +0000597 auto result = FindEntryInternal(package_group, type_idx, entry_idx, *desired_config,
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800598 stop_at_first_match, ignore_configuration);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000599 if (UNLIKELY(!result.has_value())) {
600 return base::unexpected(result.error());
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700601 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800602
Jackal Guo552b45d2021-09-29 10:52:19 +0800603 bool overlaid = false;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000604 if (!stop_at_first_match && !ignore_configuration && !apk_assets_[result->cookie]->IsLoader()) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700605 for (const auto& id_map : package_group.overlays_) {
606 auto overlay_entry = id_map.overlay_res_maps_.Lookup(resid);
607 if (!overlay_entry) {
608 // No id map entry exists for this target resource.
609 continue;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000610 }
611 if (overlay_entry.IsInlineValue()) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700612 // The target resource is overlaid by an inline value not represented by a resource.
Jeremy Meyerbe2b7792022-08-23 17:42:50 +0000613 ConfigDescription best_frro_config;
614 Res_value best_frro_value;
615 bool frro_found = false;
616 for( const auto& [config, value] : overlay_entry.GetInlineValue()) {
617 if ((!frro_found || config.isBetterThan(best_frro_config, desired_config))
618 && config.match(*desired_config)) {
619 frro_found = true;
620 best_frro_config = config;
621 best_frro_value = value;
622 }
623 }
624 if (!frro_found) {
625 continue;
626 }
627 result->entry = best_frro_value;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000628 result->dynamic_ref_table = id_map.overlay_res_maps_.GetOverlayDynamicRefTable();
629 result->cookie = id_map.cookie;
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800630
631 if (UNLIKELY(logging_enabled)) {
632 last_resolution_.steps.push_back(
633 Resolution::Step{Resolution::Step::Type::OVERLAID_INLINE, String8(), result->cookie});
Jackal Guo552b45d2021-09-29 10:52:19 +0800634 if (auto path = apk_assets_[result->cookie]->GetPath()) {
635 const std::string overlay_path = path->data();
636 if (IsFabricatedOverlay(overlay_path)) {
637 // FRRO don't have package name so we use the creating package here.
638 String8 frro_name = String8("FRRO");
639 // Get the first part of it since the expected one should be like
640 // {overlayPackageName}-{overlayName}-{4 alphanumeric chars}.frro
641 // under /data/resource-cache/.
642 const std::string name = overlay_path.substr(overlay_path.rfind('/') + 1);
643 const size_t end = name.find('-');
644 if (frro_name.size() != overlay_path.size() && end != std::string::npos) {
645 frro_name.append(base::StringPrintf(" created by %s",
646 name.substr(0 /* pos */,
647 end).c_str()).c_str());
648 }
649 last_resolution_.best_package_name = frro_name;
650 } else {
651 last_resolution_.best_package_name = result->package_name->c_str();
652 }
653 }
654 overlaid = true;
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800655 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700656 continue;
657 }
658
Ryan Mitchell80094e32020-11-16 23:08:18 +0000659 auto overlay_result = FindEntry(overlay_entry.GetResourceId(), density_override,
660 false /* stop_at_first_match */,
661 false /* ignore_configuration */);
662 if (UNLIKELY(IsIOError(overlay_result))) {
663 return base::unexpected(overlay_result.error());
664 }
665 if (!overlay_result.has_value()) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700666 continue;
667 }
668
Ryan Mitchell80094e32020-11-16 23:08:18 +0000669 if (!overlay_result->config.isBetterThan(result->config, desired_config)
670 && overlay_result->config.compare(result->config) != 0) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700671 // The configuration of the entry for the overlay must be equal to or better than the target
672 // configuration to be chosen as the better value.
673 continue;
674 }
675
Ryan Mitchell80094e32020-11-16 23:08:18 +0000676 result->cookie = overlay_result->cookie;
677 result->entry = overlay_result->entry;
678 result->config = overlay_result->config;
679 result->dynamic_ref_table = id_map.overlay_res_maps_.GetOverlayDynamicRefTable();
680
681 if (UNLIKELY(logging_enabled)) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700682 last_resolution_.steps.push_back(
Ryan Mitchell80094e32020-11-16 23:08:18 +0000683 Resolution::Step{Resolution::Step::Type::OVERLAID, overlay_result->config.toString(),
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800684 overlay_result->cookie});
Jackal Guo552b45d2021-09-29 10:52:19 +0800685 last_resolution_.best_package_name =
686 overlay_result->package_name->c_str();
687 overlaid = true;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700688 }
689 }
690 }
691
Ryan Mitchell80094e32020-11-16 23:08:18 +0000692 if (UNLIKELY(logging_enabled)) {
693 last_resolution_.cookie = result->cookie;
694 last_resolution_.type_string_ref = result->type_string_ref;
695 last_resolution_.entry_string_ref = result->entry_string_ref;
Jackal Guo552b45d2021-09-29 10:52:19 +0800696 last_resolution_.best_config_name = result->config.toString();
697 if (!overlaid) {
698 last_resolution_.best_package_name = result->package_name->c_str();
699 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700700 }
701
Ryan Mitchell80094e32020-11-16 23:08:18 +0000702 return result;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700703}
704
Ryan Mitchell80094e32020-11-16 23:08:18 +0000705base::expected<FindEntryResult, NullOrIOError> AssetManager2::FindEntryInternal(
706 const PackageGroup& package_group, uint8_t type_idx, uint16_t entry_idx,
707 const ResTable_config& desired_config, bool stop_at_first_match,
708 bool ignore_configuration) const {
709 const bool logging_enabled = resource_resolution_logging_enabled_;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800710 ApkAssetsCookie best_cookie = kInvalidCookie;
711 const LoadedPackage* best_package = nullptr;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000712 incfs::verified_map_ptr<ResTable_type> best_type;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800713 const ResTable_config* best_config = nullptr;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000714 uint32_t best_offset = 0U;
715 uint32_t type_flags = 0U;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800716
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800717 // If `desired_config` is not the same as the set configuration or the caller will accept a value
718 // from any configuration, then we cannot use our filtered list of types since it only it contains
719 // types matched to the set configuration.
720 const bool use_filtered = !ignore_configuration && &desired_config == &configuration_;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800721
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700722 const size_t package_count = package_group.packages_.size();
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800723 for (size_t pi = 0; pi < package_count; pi++) {
724 const ConfiguredPackage& loaded_package_impl = package_group.packages_[pi];
725 const LoadedPackage* loaded_package = loaded_package_impl.loaded_package_;
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800726 const ApkAssetsCookie cookie = package_group.cookies_[pi];
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800727
728 // If the type IDs are offset in this package, we need to take that into account when searching
729 // for a type.
730 const TypeSpec* type_spec = loaded_package->GetTypeSpecByTypeIndex(type_idx);
731 if (UNLIKELY(type_spec == nullptr)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700732 continue;
733 }
734
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800735 // Allow custom loader packages to overlay resource values with configurations equivalent to the
736 // current best configuration.
737 const bool package_is_loader = loaded_package->IsCustomLoader();
738
Ryan Mitchell80094e32020-11-16 23:08:18 +0000739 auto entry_flags = type_spec->GetFlagsForEntryIndex(entry_idx);
Bernie Innocenti58cf8e32020-12-19 15:31:52 +0900740 if (UNLIKELY(!entry_flags.has_value())) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000741 return base::unexpected(entry_flags.error());
742 }
743 type_flags |= entry_flags.value();
744
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800745 const FilteredConfigGroup& filtered_group = loaded_package_impl.filtered_configs_[type_idx];
746 const size_t type_entry_count = (use_filtered) ? filtered_group.type_entries.size()
747 : type_spec->type_entries.size();
748 for (size_t i = 0; i < type_entry_count; i++) {
749 const TypeSpec::TypeEntry* type_entry = (use_filtered) ? filtered_group.type_entries[i]
750 : &type_spec->type_entries[i];
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800751
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800752 // We can skip calling ResTable_config::match() if the caller does not care for the
753 // configuration to match or if we're using the list of types that have already had their
754 // configuration matched.
755 const ResTable_config& this_config = type_entry->config;
756 if (!(use_filtered || ignore_configuration || this_config.match(desired_config))) {
757 continue;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800758 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800759
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800760 Resolution::Step::Type resolution_type;
761 if (best_config == nullptr) {
762 resolution_type = Resolution::Step::Type::INITIAL;
763 } else if (this_config.isBetterThan(*best_config, &desired_config)) {
764 resolution_type = Resolution::Step::Type::BETTER_MATCH;
765 } else if (package_is_loader && this_config.compare(*best_config) == 0) {
766 resolution_type = Resolution::Step::Type::OVERLAID;
767 } else {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000768 if (UNLIKELY(logging_enabled)) {
Jackal Guo552b45d2021-09-29 10:52:19 +0800769 last_resolution_.steps.push_back(Resolution::Step{Resolution::Step::Type::SKIPPED,
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800770 this_config.toString(),
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800771 cookie});
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800772 }
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800773 continue;
774 }
775
776 // The configuration matches and is better than the previous selection.
777 // Find the entry value if it exists for this configuration.
778 const auto& type = type_entry->type;
779 const auto offset = LoadedPackage::GetEntryOffset(type, entry_idx);
780 if (UNLIKELY(IsIOError(offset))) {
781 return base::unexpected(offset.error());
782 }
783
784 if (!offset.has_value()) {
785 if (UNLIKELY(logging_enabled)) {
Jackal Guo552b45d2021-09-29 10:52:19 +0800786 last_resolution_.steps.push_back(Resolution::Step{Resolution::Step::Type::NO_ENTRY,
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800787 this_config.toString(),
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800788 cookie});
789 }
790 continue;
791 }
792
793 best_cookie = cookie;
794 best_package = loaded_package;
795 best_type = type;
796 best_config = &this_config;
797 best_offset = offset.value();
798
799 if (UNLIKELY(logging_enabled)) {
800 last_resolution_.steps.push_back(Resolution::Step{resolution_type,
801 this_config.toString(),
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800802 cookie});
803 }
804
805 // Any configuration will suffice, so break.
806 if (stop_at_first_match) {
807 break;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700808 }
809 }
810 }
811
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800812 if (UNLIKELY(best_cookie == kInvalidCookie)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000813 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700814 }
815
Eric Miao368cd192022-09-09 15:46:14 -0700816 auto best_entry_verified = LoadedPackage::GetEntryFromOffset(best_type, best_offset);
817 if (!best_entry_verified.has_value()) {
818 return base::unexpected(best_entry_verified.error());
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800819 }
820
Eric Miao368cd192022-09-09 15:46:14 -0700821 const auto entry = GetEntryValue(*best_entry_verified);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000822 if (!entry.has_value()) {
823 return base::unexpected(entry.error());
824 }
Winson2f3669b2019-01-11 11:28:34 -0800825
Ryan Mitchell80094e32020-11-16 23:08:18 +0000826 return FindEntryResult{
827 .cookie = best_cookie,
828 .entry = *entry,
829 .config = *best_config,
830 .type_flags = type_flags,
831 .package_name = &best_package->GetPackageName(),
832 .type_string_ref = StringPoolRef(best_package->GetTypeStringPool(), best_type->id - 1),
833 .entry_string_ref = StringPoolRef(best_package->GetKeyStringPool(),
Eric Miao368cd192022-09-09 15:46:14 -0700834 (*best_entry_verified)->key()),
Ryan Mitchell80094e32020-11-16 23:08:18 +0000835 .dynamic_ref_table = package_group.dynamic_ref_table.get(),
836 };
Adam Lesinski7ad11102016-10-28 16:39:15 -0700837}
838
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700839void AssetManager2::ResetResourceResolution() const {
840 last_resolution_.cookie = kInvalidCookie;
841 last_resolution_.resid = 0;
842 last_resolution_.steps.clear();
843 last_resolution_.type_string_ref = StringPoolRef();
844 last_resolution_.entry_string_ref = StringPoolRef();
Jackal Guo552b45d2021-09-29 10:52:19 +0800845 last_resolution_.best_config_name.clear();
846 last_resolution_.best_package_name.clear();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700847}
848
Winson2f3669b2019-01-11 11:28:34 -0800849void AssetManager2::SetResourceResolutionLoggingEnabled(bool enabled) {
850 resource_resolution_logging_enabled_ = enabled;
Winson2f3669b2019-01-11 11:28:34 -0800851 if (!enabled) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700852 ResetResourceResolution();
Winson2f3669b2019-01-11 11:28:34 -0800853 }
854}
855
856std::string AssetManager2::GetLastResourceResolution() const {
857 if (!resource_resolution_logging_enabled_) {
858 LOG(ERROR) << "Must enable resource resolution logging before getting path.";
Ryan Mitchell80094e32020-11-16 23:08:18 +0000859 return {};
Winson2f3669b2019-01-11 11:28:34 -0800860 }
861
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800862 const ApkAssetsCookie cookie = last_resolution_.cookie;
Winson2f3669b2019-01-11 11:28:34 -0800863 if (cookie == kInvalidCookie) {
864 LOG(ERROR) << "AssetManager hasn't resolved a resource to read resolution path.";
Ryan Mitchell80094e32020-11-16 23:08:18 +0000865 return {};
Winson2f3669b2019-01-11 11:28:34 -0800866 }
867
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800868 const uint32_t resid = last_resolution_.resid;
869 const auto package = apk_assets_[cookie]->GetLoadedArsc()->GetPackageById(get_package_id(resid));
870
Winson2f3669b2019-01-11 11:28:34 -0800871 std::string resource_name_string;
Winson2f3669b2019-01-11 11:28:34 -0800872 if (package != nullptr) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000873 auto resource_name = ToResourceName(last_resolution_.type_string_ref,
874 last_resolution_.entry_string_ref,
875 package->GetPackageName());
876 resource_name_string = resource_name.has_value() ?
877 ToFormattedResourceString(resource_name.value()) : "<unknown>";
Winson2f3669b2019-01-11 11:28:34 -0800878 }
879
880 std::stringstream log_stream;
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800881 log_stream << base::StringPrintf("Resolution for 0x%08x %s\n"
882 "\tFor config - %s", resid, resource_name_string.c_str(),
883 configuration_.toString().c_str());
Winson2f3669b2019-01-11 11:28:34 -0800884
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800885 for (const Resolution::Step& step : last_resolution_.steps) {
886 const static std::unordered_map<Resolution::Step::Type, const char*> kStepStrings = {
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800887 {Resolution::Step::Type::INITIAL, "Found initial"},
888 {Resolution::Step::Type::BETTER_MATCH, "Found better"},
889 {Resolution::Step::Type::OVERLAID, "Overlaid"},
890 {Resolution::Step::Type::OVERLAID_INLINE, "Overlaid inline"},
891 {Resolution::Step::Type::SKIPPED, "Skipped"},
892 {Resolution::Step::Type::NO_ENTRY, "No entry"}
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800893 };
894
895 const auto prefix = kStepStrings.find(step.type);
896 if (prefix == kStepStrings.end()) {
897 continue;
Winson2f3669b2019-01-11 11:28:34 -0800898 }
899
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800900 log_stream << "\n\t" << prefix->second << ": " << apk_assets_[step.cookie]->GetDebugName();
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800901 if (!step.config_name.isEmpty()) {
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800902 log_stream << " - " << step.config_name;
Winson2f3669b2019-01-11 11:28:34 -0800903 }
904 }
905
Jackal Guo552b45d2021-09-29 10:52:19 +0800906 log_stream << "\nBest matching is from "
907 << (last_resolution_.best_config_name.isEmpty() ? "default"
908 : last_resolution_.best_config_name)
909 << " configuration of " << last_resolution_.best_package_name;
Winson2f3669b2019-01-11 11:28:34 -0800910 return log_stream.str();
911}
912
Felka Chang00964e92021-12-10 01:19:08 +0800913base::expected<uint32_t, NullOrIOError> AssetManager2::GetParentThemeResourceId(uint32_t resid)
914const {
915 auto entry = FindEntry(resid, 0u /* density_override */,
916 false /* stop_at_first_match */,
917 false /* ignore_configuration */);
918 if (!entry.has_value()) {
919 return base::unexpected(entry.error());
920 }
921
922 auto entry_map = std::get_if<incfs::verified_map_ptr<ResTable_map_entry>>(&entry->entry);
923 if (entry_map == nullptr) {
924 // Not a bag, nothing to do.
925 return base::unexpected(std::nullopt);
926 }
927
928 auto map = *entry_map;
929 const uint32_t parent_resid = dtohl(map->parent.ident);
930
931 return parent_resid;
932}
933
Ryan Mitchell80094e32020-11-16 23:08:18 +0000934base::expected<AssetManager2::ResourceName, NullOrIOError> AssetManager2::GetResourceName(
935 uint32_t resid) const {
936 auto result = FindEntry(resid, 0u /* density_override */, true /* stop_at_first_match */,
937 true /* ignore_configuration */);
938 if (!result.has_value()) {
939 return base::unexpected(result.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -0700940 }
941
Ryan Mitchell80094e32020-11-16 23:08:18 +0000942 return ToResourceName(result->type_string_ref,
943 result->entry_string_ref,
944 *result->package_name);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700945}
946
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800947base::expected<uint32_t, NullOrIOError> AssetManager2::GetResourceTypeSpecFlags(
948 uint32_t resid) const {
949 auto result = FindEntry(resid, 0u /* density_override */, false /* stop_at_first_match */,
950 true /* ignore_configuration */);
951 if (!result.has_value()) {
952 return base::unexpected(result.error());
953 }
954 return result->type_flags;
955}
956
Ryan Mitchell80094e32020-11-16 23:08:18 +0000957base::expected<AssetManager2::SelectedValue, NullOrIOError> AssetManager2::GetResource(
958 uint32_t resid, bool may_be_bag, uint16_t density_override) const {
959 auto result = FindEntry(resid, density_override, false /* stop_at_first_match */,
960 false /* ignore_configuration */);
961 if (!result.has_value()) {
962 return base::unexpected(result.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -0700963 }
964
Ryan Mitchell80094e32020-11-16 23:08:18 +0000965 auto result_map_entry = std::get_if<incfs::verified_map_ptr<ResTable_map_entry>>(&result->entry);
Ryan Mitchellbf1f45b2020-09-29 17:22:52 -0700966 if (result_map_entry != nullptr) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700967 if (!may_be_bag) {
968 LOG(ERROR) << base::StringPrintf("Resource %08x is a complex map type.", resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000969 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700970 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800971
972 // Create a reference since we can't represent this complex type as a Res_value.
Ryan Mitchell80094e32020-11-16 23:08:18 +0000973 return SelectedValue(Res_value::TYPE_REFERENCE, resid, result->cookie, result->type_flags,
974 resid, result->config);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700975 }
976
Adam Lesinskida431a22016-12-29 16:08:16 -0500977 // Convert the package ID to the runtime assigned package ID.
Ryan Mitchell80094e32020-11-16 23:08:18 +0000978 Res_value value = std::get<Res_value>(result->entry);
979 result->dynamic_ref_table->lookupResourceValue(&value);
Adam Lesinskida431a22016-12-29 16:08:16 -0500980
Ryan Mitchell80094e32020-11-16 23:08:18 +0000981 return SelectedValue(value.dataType, value.data, result->cookie, result->type_flags,
982 resid, result->config);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700983}
984
Ryan Mitchell80094e32020-11-16 23:08:18 +0000985base::expected<std::monostate, NullOrIOError> AssetManager2::ResolveReference(
Ryan Mitchella45506e2020-11-16 23:08:18 +0000986 AssetManager2::SelectedValue& value, bool cache_value) const {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000987 if (value.type != Res_value::TYPE_REFERENCE || value.data == 0U) {
988 // Not a reference. Nothing to do.
989 return {};
Adam Lesinski0c405242017-01-13 20:47:26 -0800990 }
Ryan Mitchell80094e32020-11-16 23:08:18 +0000991
Ryan Mitchella45506e2020-11-16 23:08:18 +0000992 const uint32_t original_flags = value.flags;
993 const uint32_t original_resid = value.data;
994 if (cache_value) {
995 auto cached_value = cached_resolved_values_.find(value.data);
996 if (cached_value != cached_resolved_values_.end()) {
997 value = cached_value->second;
998 value.flags |= original_flags;
999 return {};
1000 }
1001 }
1002
1003 uint32_t combined_flags = 0U;
1004 uint32_t resolve_resid = original_resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001005 constexpr const uint32_t kMaxIterations = 20;
1006 for (uint32_t i = 0U;; i++) {
1007 auto result = GetResource(resolve_resid, true /*may_be_bag*/);
1008 if (!result.has_value()) {
Ryan Mitchelle7ab6272020-11-13 18:06:15 -08001009 value.resid = resolve_resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001010 return base::unexpected(result.error());
1011 }
1012
Ryan Mitchelle7ab6272020-11-13 18:06:15 -08001013 // If resource resolution fails, the value should be set to the last reference that was able to
1014 // be resolved successfully.
1015 value = *result;
1016 value.flags |= combined_flags;
1017
Ryan Mitchell80094e32020-11-16 23:08:18 +00001018 if (result->type != Res_value::TYPE_REFERENCE ||
1019 result->data == Res_value::DATA_NULL_UNDEFINED ||
1020 result->data == resolve_resid || i == kMaxIterations) {
1021 // This reference can't be resolved, so exit now and let the caller deal with it.
Ryan Mitchella45506e2020-11-16 23:08:18 +00001022 if (cache_value) {
1023 cached_resolved_values_[original_resid] = value;
1024 }
1025
1026 // Above value is cached without original_flags to ensure they don't get included in future
1027 // queries that hit the cache
1028 value.flags |= original_flags;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001029 return {};
1030 }
1031
Ryan Mitchelle7ab6272020-11-13 18:06:15 -08001032 combined_flags = result->flags;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001033 resolve_resid = result->data;
1034 }
Adam Lesinski0c405242017-01-13 20:47:26 -08001035}
1036
Ryan Mitchell80094e32020-11-16 23:08:18 +00001037const std::vector<uint32_t> AssetManager2::GetBagResIdStack(uint32_t resid) const {
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001038 auto cached_iter = cached_bag_resid_stacks_.find(resid);
1039 if (cached_iter != cached_bag_resid_stacks_.end()) {
1040 return cached_iter->second;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001041 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001042
1043 std::vector<uint32_t> found_resids;
1044 GetBag(resid, found_resids);
1045 cached_bag_resid_stacks_.emplace(resid, found_resids);
1046 return found_resids;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001047}
1048
Ryan Mitchell80094e32020-11-16 23:08:18 +00001049base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::ResolveBag(
1050 AssetManager2::SelectedValue& value) const {
1051 if (UNLIKELY(value.type != Res_value::TYPE_REFERENCE)) {
1052 return base::unexpected(std::nullopt);
1053 }
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001054
Ryan Mitchell80094e32020-11-16 23:08:18 +00001055 auto bag = GetBag(value.data);
1056 if (bag.has_value()) {
1057 value.flags |= (*bag)->type_spec_flags;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001058 }
1059 return bag;
y57cd1952018-04-12 14:26:23 -07001060}
1061
Ryan Mitchell80094e32020-11-16 23:08:18 +00001062base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::GetBag(uint32_t resid) const {
1063 std::vector<uint32_t> found_resids;
1064 const auto bag = GetBag(resid, found_resids);
Yurii Zubrytskyiab3cb302022-10-11 12:15:52 -07001065 cached_bag_resid_stacks_.emplace(resid, std::move(found_resids));
Ryan Mitchell80094e32020-11-16 23:08:18 +00001066 return bag;
Ryan Mitchell155d5392020-02-10 13:35:24 -08001067}
1068
Ryan Mitchell80094e32020-11-16 23:08:18 +00001069base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::GetBag(
1070 uint32_t resid, std::vector<uint32_t>& child_resids) const {
1071 if (auto cached_iter = cached_bags_.find(resid); cached_iter != cached_bags_.end()) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001072 return cached_iter->second.get();
1073 }
1074
Ryan Mitchell80094e32020-11-16 23:08:18 +00001075 auto entry = FindEntry(resid, 0u /* density_override */, false /* stop_at_first_match */,
1076 false /* ignore_configuration */);
1077 if (!entry.has_value()) {
1078 return base::unexpected(entry.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001079 }
1080
Ryan Mitchell80094e32020-11-16 23:08:18 +00001081 auto entry_map = std::get_if<incfs::verified_map_ptr<ResTable_map_entry>>(&entry->entry);
1082 if (entry_map == nullptr) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001083 // Not a bag, nothing to do.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001084 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001085 }
1086
Ryan Mitchell80094e32020-11-16 23:08:18 +00001087 auto map = *entry_map;
1088 auto map_entry = map.offset(dtohs(map->size)).convert<ResTable_map>();
1089 const auto map_entry_end = map_entry + dtohl(map->count);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001090
y57cd1952018-04-12 14:26:23 -07001091 // Keep track of ids that have already been seen to prevent infinite loops caused by circular
Ryan Mitchell80094e32020-11-16 23:08:18 +00001092 // dependencies between bags.
y57cd1952018-04-12 14:26:23 -07001093 child_resids.push_back(resid);
1094
Adam Lesinskida431a22016-12-29 16:08:16 -05001095 uint32_t parent_resid = dtohl(map->parent.ident);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001096 if (parent_resid == 0U ||
1097 std::find(child_resids.begin(), child_resids.end(), parent_resid) != child_resids.end()) {
1098 // There is no parent or a circular parental dependency exist, meaning there is nothing to
1099 // inherit and we can do a simple copy of the entries in the map.
Adam Lesinski7ad11102016-10-28 16:39:15 -07001100 const size_t entry_count = map_entry_end - map_entry;
1101 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
1102 malloc(sizeof(ResolvedBag) + (entry_count * sizeof(ResolvedBag::Entry))))};
Ryan Mitchell155d5392020-02-10 13:35:24 -08001103
1104 bool sort_entries = false;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001105 for (auto new_entry = new_bag->entries; map_entry != map_entry_end; ++map_entry) {
1106 if (UNLIKELY(!map_entry)) {
1107 return base::unexpected(IOError::PAGES_MISSING);
1108 }
1109
Adam Lesinskida431a22016-12-29 16:08:16 -05001110 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001111 if (!is_internal_resid(new_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -05001112 // Attributes, arrays, etc don't have a resource id as the name. They specify
1113 // other data, which would be wrong to change via a lookup.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001114 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001115 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
1116 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001117 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001118 }
1119 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001120
1121 new_entry->cookie = entry->cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -05001122 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001123 new_entry->key_pool = nullptr;
1124 new_entry->type_pool = nullptr;
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001125 new_entry->style = resid;
Adam Lesinski30080e22017-10-16 16:18:09 -07001126 new_entry->value.copyFrom_dtoh(map_entry->value);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001127 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1128 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001129 LOG(ERROR) << base::StringPrintf(
1130 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
1131 new_entry->value.data, new_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001132 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001133 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001134
Ryan Mitchell155d5392020-02-10 13:35:24 -08001135 sort_entries = sort_entries ||
1136 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001137 ++new_entry;
1138 }
Ryan Mitchell155d5392020-02-10 13:35:24 -08001139
1140 if (sort_entries) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001141 std::sort(new_bag->entries, new_bag->entries + entry_count,
1142 [](auto&& lhs, auto&& rhs) { return lhs.key < rhs.key; });
Ryan Mitchell155d5392020-02-10 13:35:24 -08001143 }
1144
Ryan Mitchell80094e32020-11-16 23:08:18 +00001145 new_bag->type_spec_flags = entry->type_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001146 new_bag->entry_count = static_cast<uint32_t>(entry_count);
1147 ResolvedBag* result = new_bag.get();
1148 cached_bags_[resid] = std::move(new_bag);
1149 return result;
1150 }
1151
Adam Lesinskida431a22016-12-29 16:08:16 -05001152 // In case the parent is a dynamic reference, resolve it.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001153 entry->dynamic_ref_table->lookupResourceId(&parent_resid);
Adam Lesinskida431a22016-12-29 16:08:16 -05001154
Adam Lesinski7ad11102016-10-28 16:39:15 -07001155 // Get the parent and do a merge of the keys.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001156 const auto parent_bag = GetBag(parent_resid, child_resids);
1157 if (UNLIKELY(!parent_bag.has_value())) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001158 // Failed to get the parent that should exist.
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001159 LOG(ERROR) << base::StringPrintf("Failed to find parent 0x%08x of bag 0x%08x.", parent_resid,
1160 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001161 return base::unexpected(parent_bag.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001162 }
1163
Adam Lesinski7ad11102016-10-28 16:39:15 -07001164 // Create the max possible entries we can make. Once we construct the bag,
1165 // we will realloc to fit to size.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001166 const size_t max_count = (*parent_bag)->entry_count + dtohl(map->count);
George Burgess IV09b119f2017-07-25 15:00:04 -07001167 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
1168 malloc(sizeof(ResolvedBag) + (max_count * sizeof(ResolvedBag::Entry))))};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001169 ResolvedBag::Entry* new_entry = new_bag->entries;
1170
Ryan Mitchell80094e32020-11-16 23:08:18 +00001171 const ResolvedBag::Entry* parent_entry = (*parent_bag)->entries;
1172 const ResolvedBag::Entry* const parent_entry_end = parent_entry + (*parent_bag)->entry_count;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001173
1174 // The keys are expected to be in sorted order. Merge the two bags.
Ryan Mitchell155d5392020-02-10 13:35:24 -08001175 bool sort_entries = false;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001176 while (map_entry != map_entry_end && parent_entry != parent_entry_end) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001177 if (UNLIKELY(!map_entry)) {
1178 return base::unexpected(IOError::PAGES_MISSING);
1179 }
1180
Adam Lesinskida431a22016-12-29 16:08:16 -05001181 uint32_t child_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001182 if (!is_internal_resid(child_key)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001183 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&child_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001184 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", child_key,
1185 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001186 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001187 }
1188 }
1189
Adam Lesinski7ad11102016-10-28 16:39:15 -07001190 if (child_key <= parent_entry->key) {
1191 // Use the child key if it comes before the parent
1192 // or is equal to the parent (overrides).
Ryan Mitchell80094e32020-11-16 23:08:18 +00001193 new_entry->cookie = entry->cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001194 new_entry->key = child_key;
1195 new_entry->key_pool = nullptr;
1196 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -07001197 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001198 new_entry->style = resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001199 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1200 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001201 LOG(ERROR) << base::StringPrintf(
1202 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
1203 new_entry->value.data, child_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001204 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001205 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001206 ++map_entry;
1207 } else {
1208 // Take the parent entry as-is.
1209 memcpy(new_entry, parent_entry, sizeof(*new_entry));
1210 }
1211
Ryan Mitchell155d5392020-02-10 13:35:24 -08001212 sort_entries = sort_entries ||
1213 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001214 if (child_key >= parent_entry->key) {
1215 // Move to the next parent entry if we used it or it was overridden.
1216 ++parent_entry;
1217 }
1218 // Increment to the next entry to fill.
1219 ++new_entry;
1220 }
1221
1222 // Finish the child entries if they exist.
1223 while (map_entry != map_entry_end) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001224 if (UNLIKELY(!map_entry)) {
1225 return base::unexpected(IOError::PAGES_MISSING);
1226 }
1227
Adam Lesinskida431a22016-12-29 16:08:16 -05001228 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001229 if (!is_internal_resid(new_key)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001230 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001231 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
1232 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001233 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001234 }
1235 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001236 new_entry->cookie = entry->cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -05001237 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001238 new_entry->key_pool = nullptr;
1239 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -07001240 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001241 new_entry->style = resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001242 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1243 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001244 LOG(ERROR) << base::StringPrintf("Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.",
1245 new_entry->value.dataType, new_entry->value.data, new_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001246 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001247 }
Ryan Mitchell155d5392020-02-10 13:35:24 -08001248 sort_entries = sort_entries ||
1249 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001250 ++map_entry;
1251 ++new_entry;
1252 }
1253
1254 // Finish the parent entries if they exist.
1255 if (parent_entry != parent_entry_end) {
1256 // Take the rest of the parent entries as-is.
1257 const size_t num_entries_to_copy = parent_entry_end - parent_entry;
1258 memcpy(new_entry, parent_entry, num_entries_to_copy * sizeof(*new_entry));
1259 new_entry += num_entries_to_copy;
1260 }
1261
1262 // Resize the resulting array to fit.
1263 const size_t actual_count = new_entry - new_bag->entries;
1264 if (actual_count != max_count) {
George Burgess IV09b119f2017-07-25 15:00:04 -07001265 new_bag.reset(reinterpret_cast<ResolvedBag*>(realloc(
1266 new_bag.release(), sizeof(ResolvedBag) + (actual_count * sizeof(ResolvedBag::Entry)))));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001267 }
1268
Ryan Mitchell155d5392020-02-10 13:35:24 -08001269 if (sort_entries) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001270 std::sort(new_bag->entries, new_bag->entries + actual_count,
1271 [](auto&& lhs, auto&& rhs) { return lhs.key < rhs.key; });
Ryan Mitchell155d5392020-02-10 13:35:24 -08001272 }
1273
Adam Lesinski1a1e9c22017-10-13 15:45:34 -07001274 // Combine flags from the parent and our own bag.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001275 new_bag->type_spec_flags = entry->type_flags | (*parent_bag)->type_spec_flags;
George Burgess IV09b119f2017-07-25 15:00:04 -07001276 new_bag->entry_count = static_cast<uint32_t>(actual_count);
1277 ResolvedBag* result = new_bag.get();
1278 cached_bags_[resid] = std::move(new_bag);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001279 return result;
1280}
1281
Yurii Zubrytskyia5775142022-11-02 17:49:49 -07001282static bool Utf8ToUtf16(StringPiece str, std::u16string* out) {
Adam Lesinski929d6512017-01-16 19:11:19 -08001283 ssize_t len =
1284 utf8_to_utf16_length(reinterpret_cast<const uint8_t*>(str.data()), str.size(), false);
1285 if (len < 0) {
1286 return false;
1287 }
1288 out->resize(static_cast<size_t>(len));
1289 utf8_to_utf16(reinterpret_cast<const uint8_t*>(str.data()), str.size(), &*out->begin(),
1290 static_cast<size_t>(len + 1));
1291 return true;
1292}
1293
Ryan Mitchell80094e32020-11-16 23:08:18 +00001294base::expected<uint32_t, NullOrIOError> AssetManager2::GetResourceId(
1295 const std::string& resource_name, const std::string& fallback_type,
1296 const std::string& fallback_package) const {
Adam Lesinski929d6512017-01-16 19:11:19 -08001297 StringPiece package_name, type, entry;
1298 if (!ExtractResourceName(resource_name, &package_name, &type, &entry)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001299 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001300 }
1301
1302 if (entry.empty()) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001303 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001304 }
1305
1306 if (package_name.empty()) {
1307 package_name = fallback_package;
1308 }
1309
1310 if (type.empty()) {
1311 type = fallback_type;
1312 }
1313
1314 std::u16string type16;
1315 if (!Utf8ToUtf16(type, &type16)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001316 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001317 }
1318
1319 std::u16string entry16;
1320 if (!Utf8ToUtf16(entry, &entry16)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001321 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001322 }
1323
1324 const StringPiece16 kAttr16 = u"attr";
1325 const static std::u16string kAttrPrivate16 = u"^attr-private";
1326
1327 for (const PackageGroup& package_group : package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001328 for (const ConfiguredPackage& package_impl : package_group.packages_) {
1329 const LoadedPackage* package = package_impl.loaded_package_;
Adam Lesinski929d6512017-01-16 19:11:19 -08001330 if (package_name != package->GetPackageName()) {
1331 // All packages in the same group are expected to have the same package name.
1332 break;
1333 }
1334
Ryan Mitchell80094e32020-11-16 23:08:18 +00001335 base::expected<uint32_t, NullOrIOError> resid = package->FindEntryByName(type16, entry16);
1336 if (UNLIKELY(IsIOError(resid))) {
1337 return base::unexpected(resid.error());
1338 }
1339
1340 if (!resid.has_value() && kAttr16 == type16) {
Adam Lesinski929d6512017-01-16 19:11:19 -08001341 // Private attributes in libraries (such as the framework) are sometimes encoded
1342 // under the type '^attr-private' in order to leave the ID space of public 'attr'
1343 // free for future additions. Check '^attr-private' for the same name.
1344 resid = package->FindEntryByName(kAttrPrivate16, entry16);
1345 }
1346
Ryan Mitchell80094e32020-11-16 23:08:18 +00001347 if (resid.has_value()) {
1348 return fix_package_id(*resid, package_group.dynamic_ref_table->mAssignedPackageId);
Adam Lesinski929d6512017-01-16 19:11:19 -08001349 }
1350 }
1351 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001352 return base::unexpected(std::nullopt);
Adam Lesinski0c405242017-01-13 20:47:26 -08001353}
1354
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001355void AssetManager2::RebuildFilterList() {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001356 for (PackageGroup& group : package_groups_) {
1357 for (ConfiguredPackage& impl : group.packages_) {
Yurii Zubrytskyi59dab3b2022-11-03 00:08:49 -07001358 impl.filtered_configs_.clear();
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001359
1360 // Create the filters here.
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001361 impl.loaded_package_->ForEachTypeSpec([&](const TypeSpec& type_spec, uint8_t type_id) {
Yurii Zubrytskyi59dab3b2022-11-03 00:08:49 -07001362 FilteredConfigGroup* group = nullptr;
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001363 for (const auto& type_entry : type_spec.type_entries) {
1364 if (type_entry.config.match(configuration_)) {
Yurii Zubrytskyi59dab3b2022-11-03 00:08:49 -07001365 if (!group) {
1366 group = &impl.filtered_configs_.editItemAt(type_id - 1);
1367 }
1368 group->type_entries.push_back(&type_entry);
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001369 }
1370 }
1371 });
1372 }
1373 }
1374}
1375
Adam Lesinski7ad11102016-10-28 16:39:15 -07001376void AssetManager2::InvalidateCaches(uint32_t diff) {
Ryan Mitchell2c4d8742019-03-04 09:41:00 -08001377 cached_bag_resid_stacks_.clear();
1378
Adam Lesinski7ad11102016-10-28 16:39:15 -07001379 if (diff == 0xffffffffu) {
1380 // Everything must go.
1381 cached_bags_.clear();
1382 return;
1383 }
1384
1385 // Be more conservative with what gets purged. Only if the bag has other possible
1386 // variations with respect to what changed (diff) should we remove it.
1387 for (auto iter = cached_bags_.cbegin(); iter != cached_bags_.cend();) {
1388 if (diff & iter->second->type_spec_flags) {
1389 iter = cached_bags_.erase(iter);
1390 } else {
1391 ++iter;
1392 }
1393 }
Ryan Mitchella45506e2020-11-16 23:08:18 +00001394
1395 cached_resolved_values_.clear();
Adam Lesinski7ad11102016-10-28 16:39:15 -07001396}
1397
Ryan Mitchell2e394222019-08-28 12:10:51 -07001398uint8_t AssetManager2::GetAssignedPackageId(const LoadedPackage* package) const {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001399 for (auto& package_group : package_groups_) {
1400 for (auto& package2 : package_group.packages_) {
1401 if (package2.loaded_package_ == package) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -07001402 return package_group.dynamic_ref_table->mAssignedPackageId;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001403 }
1404 }
1405 }
1406 return 0;
1407}
1408
Adam Lesinski30080e22017-10-16 16:18:09 -07001409std::unique_ptr<Theme> AssetManager2::NewTheme() {
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001410 constexpr size_t kInitialReserveSize = 32;
1411 auto theme = std::unique_ptr<Theme>(new Theme(this));
1412 theme->entries_.reserve(kInitialReserveSize);
1413 return theme;
Adam Lesinski30080e22017-10-16 16:18:09 -07001414}
1415
1416Theme::Theme(AssetManager2* asset_manager) : asset_manager_(asset_manager) {
1417}
1418
1419Theme::~Theme() = default;
1420
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001421struct Theme::Entry {
1422 uint32_t attr_res_id;
Adam Lesinski30080e22017-10-16 16:18:09 -07001423 ApkAssetsCookie cookie;
1424 uint32_t type_spec_flags;
1425 Res_value value;
1426};
1427
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001428namespace {
1429struct ThemeEntryKeyComparer {
1430 bool operator() (const Theme::Entry& entry, uint32_t attr_res_id) const noexcept {
1431 return entry.attr_res_id < attr_res_id;
1432 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001433};
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001434} // namespace
Adam Lesinski7ad11102016-10-28 16:39:15 -07001435
Ryan Mitchell80094e32020-11-16 23:08:18 +00001436base::expected<std::monostate, NullOrIOError> Theme::ApplyStyle(uint32_t resid, bool force) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001437 ATRACE_NAME("Theme::ApplyStyle");
Adam Lesinski7ad11102016-10-28 16:39:15 -07001438
Ryan Mitchell80094e32020-11-16 23:08:18 +00001439 auto bag = asset_manager_->GetBag(resid);
1440 if (!bag.has_value()) {
1441 return base::unexpected(bag.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001442 }
1443
1444 // Merge the flags from this style.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001445 type_spec_flags_ |= (*bag)->type_spec_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001446
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001447 for (auto it = begin(*bag); it != end(*bag); ++it) {
1448 const uint32_t attr_res_id = it->key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001449
Adam Lesinski30080e22017-10-16 16:18:09 -07001450 // If the resource ID passed in is not a style, the key can be some other identifier that is not
1451 // a resource ID. We should fail fast instead of operating with strange resource IDs.
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001452 if (!is_valid_resid(attr_res_id)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001453 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001454 }
1455
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001456 // DATA_NULL_EMPTY (@empty) is a valid resource value and DATA_NULL_UNDEFINED represents
1457 // an absence of a valid value.
1458 bool is_undefined = it->value.dataType == Res_value::TYPE_NULL &&
1459 it->value.data != Res_value::DATA_NULL_EMPTY;
1460 if (!force && is_undefined) {
1461 continue;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001462 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001463
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001464 auto entry_it = std::lower_bound(entries_.begin(), entries_.end(), attr_res_id,
1465 ThemeEntryKeyComparer{});
1466 if (entry_it != entries_.end() && entry_it->attr_res_id == attr_res_id) {
1467 if (is_undefined) {
1468 // DATA_NULL_UNDEFINED clears the value of the attribute in the theme only when `force` is
1469 /// true.
1470 entries_.erase(entry_it);
1471 } else if (force) {
Yurii Zubrytskyiab3cb302022-10-11 12:15:52 -07001472 *entry_it = Entry{attr_res_id, it->cookie, (*bag)->type_spec_flags, it->value};
Adam Lesinski30080e22017-10-16 16:18:09 -07001473 }
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001474 } else {
Yurii Zubrytskyiab3cb302022-10-11 12:15:52 -07001475 entries_.insert(entry_it, Entry{attr_res_id, it->cookie, (*bag)->type_spec_flags, it->value});
Adam Lesinski7ad11102016-10-28 16:39:15 -07001476 }
1477 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001478 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001479}
1480
Ryan Mitchell767e34f2021-06-07 12:29:05 -07001481void Theme::Rebase(AssetManager2* am, const uint32_t* style_ids, const uint8_t* force,
1482 size_t style_count) {
1483 ATRACE_NAME("Theme::Rebase");
1484 // Reset the entries without changing the vector capacity to prevent reallocations during
1485 // ApplyStyle.
1486 entries_.clear();
1487 asset_manager_ = am;
1488 for (size_t i = 0; i < style_count; i++) {
1489 ApplyStyle(style_ids[i], force[i]);
1490 }
1491}
1492
Ryan Mitchell80094e32020-11-16 23:08:18 +00001493std::optional<AssetManager2::SelectedValue> Theme::GetAttribute(uint32_t resid) const {
1494
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001495 constexpr const uint32_t kMaxIterations = 20;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001496 uint32_t type_spec_flags = 0u;
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001497 for (uint32_t i = 0; i <= kMaxIterations; i++) {
1498 auto entry_it = std::lower_bound(entries_.begin(), entries_.end(), resid,
1499 ThemeEntryKeyComparer{});
1500 if (entry_it == entries_.end() || entry_it->attr_res_id != resid) {
1501 return std::nullopt;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001502 }
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001503
1504 type_spec_flags |= entry_it->type_spec_flags;
1505 if (entry_it->value.dataType == Res_value::TYPE_ATTRIBUTE) {
1506 resid = entry_it->value.data;
1507 continue;
1508 }
1509
1510 return AssetManager2::SelectedValue(entry_it->value.dataType, entry_it->value.data,
1511 entry_it->cookie, type_spec_flags, 0U /* resid */,
1512 {} /* config */);
1513 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001514 return std::nullopt;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001515}
1516
Ryan Mitchell80094e32020-11-16 23:08:18 +00001517base::expected<std::monostate, NullOrIOError> Theme::ResolveAttributeReference(
1518 AssetManager2::SelectedValue& value) const {
1519 if (value.type != Res_value::TYPE_ATTRIBUTE) {
1520 return asset_manager_->ResolveReference(value);
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001521 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001522
1523 std::optional<AssetManager2::SelectedValue> result = GetAttribute(value.data);
1524 if (!result.has_value()) {
1525 return base::unexpected(std::nullopt);
1526 }
1527
Ryan Mitchella45506e2020-11-16 23:08:18 +00001528 auto resolve_result = asset_manager_->ResolveReference(*result, true /* cache_value */);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001529 if (resolve_result.has_value()) {
1530 result->flags |= value.flags;
1531 value = *result;
1532 }
1533 return resolve_result;
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001534}
1535
Adam Lesinski7ad11102016-10-28 16:39:15 -07001536void Theme::Clear() {
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001537 entries_.clear();
Adam Lesinski7ad11102016-10-28 16:39:15 -07001538}
1539
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001540base::expected<std::monostate, IOError> Theme::SetTo(const Theme& source) {
1541 if (this == &source) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001542 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001543 }
1544
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001545 type_spec_flags_ = source.type_spec_flags_;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001546
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001547 if (asset_manager_ == source.asset_manager_) {
1548 entries_ = source.entries_;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001549 } else {
1550 std::map<ApkAssetsCookie, ApkAssetsCookie> src_to_dest_asset_cookies;
1551 typedef std::map<int, int> SourceToDestinationRuntimePackageMap;
1552 std::map<ApkAssetsCookie, SourceToDestinationRuntimePackageMap> src_asset_cookie_id_map;
1553
Ryan Mitchell93bca972019-03-08 17:26:28 -08001554 // Determine which ApkAssets are loaded in both theme AssetManagers.
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001555 const auto src_assets = source.asset_manager_->GetApkAssets();
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001556 for (size_t i = 0; i < src_assets.size(); i++) {
1557 const ApkAssets* src_asset = src_assets[i];
1558
Ryan Mitchellef538432021-03-01 14:52:14 -08001559 const auto dest_assets = asset_manager_->GetApkAssets();
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001560 for (size_t j = 0; j < dest_assets.size(); j++) {
1561 const ApkAssets* dest_asset = dest_assets[j];
Ryan Mitchellef538432021-03-01 14:52:14 -08001562 if (src_asset != dest_asset) {
1563 // ResourcesManager caches and reuses ApkAssets when the same apk must be present in
1564 // multiple AssetManagers. Two ApkAssets point to the same version of the same resources
1565 // if they are the same instance.
1566 continue;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001567 }
Ryan Mitchellef538432021-03-01 14:52:14 -08001568
1569 // Map the package ids of the asset in the source AssetManager to the package ids of the
1570 // asset in th destination AssetManager.
1571 SourceToDestinationRuntimePackageMap package_map;
1572 for (const auto& loaded_package : src_asset->GetLoadedArsc()->GetPackages()) {
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001573 const int src_package_id = source.asset_manager_->GetAssignedPackageId(
1574 loaded_package.get());
Ryan Mitchellef538432021-03-01 14:52:14 -08001575 const int dest_package_id = asset_manager_->GetAssignedPackageId(loaded_package.get());
1576 package_map[src_package_id] = dest_package_id;
1577 }
1578
1579 src_to_dest_asset_cookies.insert(std::make_pair(i, j));
1580 src_asset_cookie_id_map.insert(std::make_pair(i, package_map));
1581 break;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001582 }
1583 }
1584
Ryan Mitchell93bca972019-03-08 17:26:28 -08001585 // Reset the data in the destination theme.
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001586 entries_.clear();
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001587
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001588 for (const auto& entry : source.entries_) {
1589 bool is_reference = (entry.value.dataType == Res_value::TYPE_ATTRIBUTE
1590 || entry.value.dataType == Res_value::TYPE_REFERENCE
1591 || entry.value.dataType == Res_value::TYPE_DYNAMIC_ATTRIBUTE
1592 || entry.value.dataType == Res_value::TYPE_DYNAMIC_REFERENCE)
1593 && entry.value.data != 0x0;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001594
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001595 // If the attribute value represents an attribute or reference, the package id of the
1596 // value needs to be rewritten to the package id of the value in the destination.
1597 uint32_t attribute_data = entry.value.data;
1598 if (is_reference) {
1599 // Determine the package id of the reference in the destination AssetManager.
1600 auto value_package_map = src_asset_cookie_id_map.find(entry.cookie);
1601 if (value_package_map == src_asset_cookie_id_map.end()) {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001602 continue;
1603 }
1604
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001605 auto value_dest_package = value_package_map->second.find(
1606 get_package_id(entry.value.data));
1607 if (value_dest_package == value_package_map->second.end()) {
1608 continue;
1609 }
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001610
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001611 attribute_data = fix_package_id(entry.value.data, value_dest_package->second);
1612 }
Ryan Mitchellb85d9b22018-11-19 12:11:38 -08001613
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001614 // Find the cookie of the value in the destination. If the source apk is not loaded in the
1615 // destination, only copy resources that do not reference resources in the source.
1616 ApkAssetsCookie data_dest_cookie;
1617 auto value_dest_cookie = src_to_dest_asset_cookies.find(entry.cookie);
1618 if (value_dest_cookie != src_to_dest_asset_cookies.end()) {
1619 data_dest_cookie = value_dest_cookie->second;
1620 } else {
1621 if (is_reference || entry.value.dataType == Res_value::TYPE_STRING) {
1622 continue;
1623 } else {
1624 data_dest_cookie = 0x0;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001625 }
1626 }
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001627
1628 // The package id of the attribute needs to be rewritten to the package id of the
1629 // attribute in the destination.
1630 int attribute_dest_package_id = get_package_id(entry.attr_res_id);
1631 if (attribute_dest_package_id != 0x01) {
1632 // Find the cookie of the attribute resource id in the source AssetManager
1633 base::expected<FindEntryResult, NullOrIOError> attribute_entry_result =
1634 source.asset_manager_->FindEntry(entry.attr_res_id, 0 /* density_override */ ,
1635 true /* stop_at_first_match */,
1636 true /* ignore_configuration */);
1637 if (UNLIKELY(IsIOError(attribute_entry_result))) {
1638 return base::unexpected(GetIOError(attribute_entry_result.error()));
1639 }
1640 if (!attribute_entry_result.has_value()) {
1641 continue;
1642 }
1643
1644 // Determine the package id of the attribute in the destination AssetManager.
1645 auto attribute_package_map = src_asset_cookie_id_map.find(
1646 attribute_entry_result->cookie);
1647 if (attribute_package_map == src_asset_cookie_id_map.end()) {
1648 continue;
1649 }
1650 auto attribute_dest_package = attribute_package_map->second.find(
1651 attribute_dest_package_id);
1652 if (attribute_dest_package == attribute_package_map->second.end()) {
1653 continue;
1654 }
1655 attribute_dest_package_id = attribute_dest_package->second;
1656 }
1657
1658 auto dest_attr_id = make_resid(attribute_dest_package_id, get_type_id(entry.attr_res_id),
1659 get_entry_id(entry.attr_res_id));
1660 Theme::Entry new_entry{dest_attr_id, data_dest_cookie, entry.type_spec_flags,
1661 Res_value{.dataType = entry.value.dataType,
1662 .data = attribute_data}};
1663
1664 // Since the entries were cleared, the attribute resource id has yet been mapped to any value.
1665 auto entry_it = std::lower_bound(entries_.begin(), entries_.end(), dest_attr_id,
1666 ThemeEntryKeyComparer{});
1667 entries_.insert(entry_it, new_entry);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001668 }
1669 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001670 return {};
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001671}
1672
1673void Theme::Dump() const {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001674 LOG(INFO) << base::StringPrintf("Theme(this=%p, AssetManager2=%p)", this, asset_manager_);
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001675 for (auto& entry : entries_) {
1676 LOG(INFO) << base::StringPrintf(" entry(0x%08x)=(0x%08x) type=(0x%02x), cookie(%d)",
1677 entry.attr_res_id, entry.value.data, entry.value.dataType,
1678 entry.cookie);
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001679 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001680}
1681
1682} // namespace android