blob: 06ffb72d183bf8917229ea3a0cc927e6f5dd5789 [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>
Adam Lesinski0c405242017-01-13 20:47:26 -080025
Adam Lesinski7ad11102016-10-28 16:39:15 -070026#include "android-base/logging.h"
27#include "android-base/stringprintf.h"
Jackal Guo552b45d2021-09-29 10:52:19 +080028#include "androidfw/ResourceTypes.h"
Ryan Mitchell8a891d82019-07-01 09:48:23 -070029#include "androidfw/ResourceUtils.h"
Ryan Mitchell31b11052019-06-13 13:47:26 -070030#include "androidfw/Util.h"
Adam Lesinski7ad11102016-10-28 16:39:15 -070031#include "utils/ByteOrder.h"
32#include "utils/Trace.h"
33
34#ifdef _WIN32
35#ifdef ERROR
36#undef ERROR
37#endif
38#endif
39
40namespace android {
41
Ryan Mitchell80094e32020-11-16 23:08:18 +000042namespace {
43
44using EntryValue = std::variant<Res_value, incfs::verified_map_ptr<ResTable_map_entry>>;
45
Eric Miao368cd192022-09-09 15:46:14 -070046/* NOTE: table_entry has been verified in LoadedPackage::GetEntryFromOffset(),
47 * and so access to ->value() and ->map_entry() are safe here
48 */
Ryan Mitchell80094e32020-11-16 23:08:18 +000049base::expected<EntryValue, IOError> GetEntryValue(
50 incfs::verified_map_ptr<ResTable_entry> table_entry) {
Eric Miao368cd192022-09-09 15:46:14 -070051 const uint16_t entry_size = table_entry->size();
Ryan Mitchell80094e32020-11-16 23:08:18 +000052
53 // Check if the entry represents a bag value.
Eric Miao368cd192022-09-09 15:46:14 -070054 if (entry_size >= sizeof(ResTable_map_entry) && table_entry->is_complex()) {
55 return table_entry.convert<ResTable_map_entry>().verified();
Ryan Mitchell80094e32020-11-16 23:08:18 +000056 }
57
Eric Miao368cd192022-09-09 15:46:14 -070058 return table_entry->value();
Ryan Mitchell80094e32020-11-16 23:08:18 +000059}
60
61} // namespace
62
Adam Lesinskibebfcc42018-02-12 14:27:46 -080063struct FindEntryResult {
Ryan Mitchell80094e32020-11-16 23:08:18 +000064 // The cookie representing the ApkAssets in which the value resides.
65 ApkAssetsCookie cookie;
66
67 // The value of the resource table entry. Either an android::Res_value for non-bag types or an
68 // incfs::verified_map_ptr<ResTable_map_entry> for bag types.
69 EntryValue entry;
Adam Lesinskibebfcc42018-02-12 14:27:46 -080070
71 // The configuration for which the resulting entry was defined. This is already swapped to host
72 // endianness.
73 ResTable_config config;
74
75 // The bitmask of configuration axis with which the resource value varies.
76 uint32_t type_flags;
77
78 // The dynamic package ID map for the package from which this resource came from.
79 const DynamicRefTable* dynamic_ref_table;
80
Ryan Mitchell8a891d82019-07-01 09:48:23 -070081 // The package name of the resource.
82 const std::string* package_name;
83
Adam Lesinskibebfcc42018-02-12 14:27:46 -080084 // The string pool reference to the type's name. This uses a different string pool than
85 // the global string pool, but this is hidden from the caller.
86 StringPoolRef type_string_ref;
87
88 // The string pool reference to the entry's name. This uses a different string pool than
89 // the global string pool, but this is hidden from the caller.
90 StringPoolRef entry_string_ref;
91};
92
Ryan Mitchellb894c272020-02-12 10:31:44 -080093AssetManager2::AssetManager2() {
Adam Lesinski970bd8d2017-09-25 13:21:55 -070094 memset(&configuration_, 0, sizeof(configuration_));
95}
Adam Lesinski7ad11102016-10-28 16:39:15 -070096
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -080097bool AssetManager2::SetApkAssets(std::vector<const ApkAssets*> apk_assets, bool invalidate_caches) {
98 apk_assets_ = std::move(apk_assets);
Adam Lesinskida431a22016-12-29 16:08:16 -050099 BuildDynamicRefTable();
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800100 RebuildFilterList();
Adam Lesinski7ad11102016-10-28 16:39:15 -0700101 if (invalidate_caches) {
102 InvalidateCaches(static_cast<uint32_t>(-1));
103 }
104 return true;
105}
106
Adam Lesinskida431a22016-12-29 16:08:16 -0500107void AssetManager2::BuildDynamicRefTable() {
108 package_groups_.clear();
109 package_ids_.fill(0xff);
110
Ryan Mitchellef538432021-03-01 14:52:14 -0800111 // A mapping from path of apk assets that could be target packages of overlays to the runtime
112 // package id of its first loaded package. Overlays currently can only override resources in the
113 // first package in the target resource table.
114 std::unordered_map<std::string, uint8_t> target_assets_package_ids;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700115
Ryan Mitchell824cc492020-02-12 10:48:14 -0800116 // Overlay resources are not directly referenced by an application so their resource ids
117 // can change throughout the application's lifetime. Assign overlay package ids last.
118 std::vector<const ApkAssets*> sorted_apk_assets(apk_assets_);
119 std::stable_partition(sorted_apk_assets.begin(), sorted_apk_assets.end(), [](const ApkAssets* a) {
120 return !a->IsOverlay();
121 });
122
123 // The assets cookie must map to the position of the apk assets in the unsorted apk assets list.
124 std::unordered_map<const ApkAssets*, ApkAssetsCookie> apk_assets_cookies;
125 apk_assets_cookies.reserve(apk_assets_.size());
126 for (size_t i = 0, n = apk_assets_.size(); i < n; i++) {
127 apk_assets_cookies[apk_assets_[i]] = static_cast<ApkAssetsCookie>(i);
128 }
129
Ryan Mitchellb894c272020-02-12 10:31:44 -0800130 // 0x01 is reserved for the android package.
131 int next_package_id = 0x02;
Ryan Mitchell824cc492020-02-12 10:48:14 -0800132 for (const ApkAssets* apk_assets : sorted_apk_assets) {
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800133 std::shared_ptr<OverlayDynamicRefTable> overlay_ref_table;
134 if (auto loaded_idmap = apk_assets->GetLoadedIdmap(); loaded_idmap != nullptr) {
135 // The target package must precede the overlay package in the apk assets paths in order
136 // to take effect.
Ryan Mitchellef538432021-03-01 14:52:14 -0800137 auto iter = target_assets_package_ids.find(std::string(loaded_idmap->TargetApkPath()));
138 if (iter == target_assets_package_ids.end()) {
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800139 LOG(INFO) << "failed to find target package for overlay "
140 << loaded_idmap->OverlayApkPath();
141 } else {
142 uint8_t target_package_id = iter->second;
143
144 // Create a special dynamic reference table for the overlay to rewrite references to
145 // overlay resources as references to the target resources they overlay.
146 overlay_ref_table = std::make_shared<OverlayDynamicRefTable>(
147 loaded_idmap->GetOverlayDynamicRefTable(target_package_id));
148
149 // Add the overlay resource map to the target package's set of overlays.
150 const uint8_t target_idx = package_ids_[target_package_id];
151 CHECK(target_idx != 0xff) << "overlay target '" << loaded_idmap->TargetApkPath()
152 << "'added to apk_assets_package_ids but does not have an"
153 << " assigned package group";
154
155 PackageGroup& target_package_group = package_groups_[target_idx];
156 target_package_group.overlays_.push_back(
157 ConfiguredOverlay{loaded_idmap->GetTargetResourcesMap(target_package_id,
158 overlay_ref_table.get()),
159 apk_assets_cookies[apk_assets]});
160 }
161 }
162
Ryan Mitchellb894c272020-02-12 10:31:44 -0800163 const LoadedArsc* loaded_arsc = apk_assets->GetLoadedArsc();
Ryan Mitchellb894c272020-02-12 10:31:44 -0800164 for (const std::unique_ptr<const LoadedPackage>& package : loaded_arsc->GetPackages()) {
165 // Get the package ID or assign one if a shared library.
166 int package_id;
167 if (package->IsDynamic()) {
168 package_id = next_package_id++;
169 } else {
170 package_id = package->GetPackageId();
Adam Lesinskida431a22016-12-29 16:08:16 -0500171 }
172
Adam Lesinskida431a22016-12-29 16:08:16 -0500173 uint8_t idx = package_ids_[package_id];
174 if (idx == 0xff) {
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800175 // Add the mapping for package ID to index if not present.
Adam Lesinskida431a22016-12-29 16:08:16 -0500176 package_ids_[package_id] = idx = static_cast<uint8_t>(package_groups_.size());
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800177 PackageGroup& new_group = package_groups_.emplace_back();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700178
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800179 if (overlay_ref_table != nullptr) {
180 // If this package is from an overlay, use a dynamic reference table that can rewrite
181 // overlay resource ids to their corresponding target resource ids.
182 new_group.dynamic_ref_table = overlay_ref_table;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700183 }
184
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800185 DynamicRefTable* ref_table = new_group.dynamic_ref_table.get();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700186 ref_table->mAssignedPackageId = package_id;
187 ref_table->mAppAsLib = package->IsDynamic() && package->GetPackageId() == 0x7f;
Adam Lesinskida431a22016-12-29 16:08:16 -0500188 }
Adam Lesinskida431a22016-12-29 16:08:16 -0500189
190 // Add the package and to the set of packages with the same ID.
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800191 PackageGroup* package_group = &package_groups_[idx];
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800192 package_group->packages_.push_back(ConfiguredPackage{package.get(), {}});
Ryan Mitchell824cc492020-02-12 10:48:14 -0800193 package_group->cookies_.push_back(apk_assets_cookies[apk_assets]);
Adam Lesinskida431a22016-12-29 16:08:16 -0500194
195 // Add the package name -> build time ID mappings.
196 for (const DynamicPackageEntry& entry : package->GetDynamicPackageMap()) {
197 String16 package_name(entry.package_name.c_str(), entry.package_name.size());
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700198 package_group->dynamic_ref_table->mEntries.replaceValueFor(
Adam Lesinskida431a22016-12-29 16:08:16 -0500199 package_name, static_cast<uint8_t>(entry.package_id));
200 }
Ryan Mitchellb894c272020-02-12 10:31:44 -0800201
Ryan Mitchellef538432021-03-01 14:52:14 -0800202 if (auto apk_assets_path = apk_assets->GetPath()) {
203 // Overlay target ApkAssets must have been created using path based load apis.
204 target_assets_package_ids.insert(std::make_pair(std::string(*apk_assets_path), package_id));
205 }
Adam Lesinskida431a22016-12-29 16:08:16 -0500206 }
207 }
208
209 // Now assign the runtime IDs so that we have a build-time to runtime ID map.
210 const auto package_groups_end = package_groups_.end();
211 for (auto iter = package_groups_.begin(); iter != package_groups_end; ++iter) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800212 const std::string& package_name = iter->packages_[0].loaded_package_->GetPackageName();
Adam Lesinskida431a22016-12-29 16:08:16 -0500213 for (auto iter2 = package_groups_.begin(); iter2 != package_groups_end; ++iter2) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700214 iter2->dynamic_ref_table->addMapping(String16(package_name.c_str(), package_name.size()),
215 iter->dynamic_ref_table->mAssignedPackageId);
Ryan Mitchell2fedba92021-04-23 07:47:38 -0700216
217 // Add the alias resources to the dynamic reference table of every package group. Since
218 // staging aliases can only be defined by the framework package (which is not a shared
219 // library), the compile-time package id of the framework is the same across all packages
220 // that compile against the framework.
Ryan Mitchell2ec8e1b2021-05-11 08:28:00 -0700221 for (const auto& package : iter->packages_) {
Ryan Mitchell2fedba92021-04-23 07:47:38 -0700222 for (const auto& entry : package.loaded_package_->GetAliasResourceIdMap()) {
Ryan Mitchell2ec8e1b2021-05-11 08:28:00 -0700223 iter2->dynamic_ref_table->addAlias(entry.first, entry.second);
Ryan Mitchell2fedba92021-04-23 07:47:38 -0700224 }
225 }
Adam Lesinskida431a22016-12-29 16:08:16 -0500226 }
227 }
228}
229
230void AssetManager2::DumpToLog() const {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800231 LOG(INFO) << base::StringPrintf("AssetManager2(this=%p)", this);
232
Adam Lesinskida431a22016-12-29 16:08:16 -0500233 std::string list;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800234 for (const auto& apk_assets : apk_assets_) {
Ryan Mitchellef538432021-03-01 14:52:14 -0800235 base::StringAppendF(&list, "%s,", apk_assets->GetDebugName().c_str());
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800236 }
237 LOG(INFO) << "ApkAssets: " << list;
238
239 list = "";
Adam Lesinskida431a22016-12-29 16:08:16 -0500240 for (size_t i = 0; i < package_ids_.size(); i++) {
241 if (package_ids_[i] != 0xff) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800242 base::StringAppendF(&list, "%02x -> %d, ", (int)i, package_ids_[i]);
Adam Lesinskida431a22016-12-29 16:08:16 -0500243 }
244 }
245 LOG(INFO) << "Package ID map: " << list;
246
Adam Lesinski0dd36992018-01-25 15:38:38 -0800247 for (const auto& package_group: package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800248 list = "";
249 for (const auto& package : package_group.packages_) {
250 const LoadedPackage* loaded_package = package.loaded_package_;
251 base::StringAppendF(&list, "%s(%02x%s), ", loaded_package->GetPackageName().c_str(),
252 loaded_package->GetPackageId(),
253 (loaded_package->IsDynamic() ? " dynamic" : ""));
254 }
255 LOG(INFO) << base::StringPrintf("PG (%02x): ",
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700256 package_group.dynamic_ref_table->mAssignedPackageId)
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800257 << list;
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800258
259 for (size_t i = 0; i < 256; i++) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700260 if (package_group.dynamic_ref_table->mLookupTable[i] != 0) {
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800261 LOG(INFO) << base::StringPrintf(" e[0x%02x] -> 0x%02x", (uint8_t) i,
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700262 package_group.dynamic_ref_table->mLookupTable[i]);
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800263 }
264 }
Adam Lesinskida431a22016-12-29 16:08:16 -0500265 }
266}
Adam Lesinski7ad11102016-10-28 16:39:15 -0700267
268const ResStringPool* AssetManager2::GetStringPoolForCookie(ApkAssetsCookie cookie) const {
269 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
270 return nullptr;
271 }
272 return apk_assets_[cookie]->GetLoadedArsc()->GetStringPool();
273}
274
Adam Lesinskida431a22016-12-29 16:08:16 -0500275const DynamicRefTable* AssetManager2::GetDynamicRefTableForPackage(uint32_t package_id) const {
276 if (package_id >= package_ids_.size()) {
277 return nullptr;
278 }
279
280 const size_t idx = package_ids_[package_id];
281 if (idx == 0xff) {
282 return nullptr;
283 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700284 return package_groups_[idx].dynamic_ref_table.get();
Adam Lesinskida431a22016-12-29 16:08:16 -0500285}
286
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700287std::shared_ptr<const DynamicRefTable> AssetManager2::GetDynamicRefTableForCookie(
288 ApkAssetsCookie cookie) const {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800289 for (const PackageGroup& package_group : package_groups_) {
290 for (const ApkAssetsCookie& package_cookie : package_group.cookies_) {
291 if (package_cookie == cookie) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700292 return package_group.dynamic_ref_table;
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800293 }
294 }
295 }
296 return nullptr;
297}
298
MÃ¥rten Kongstadc92c4dd2019-02-05 01:29:59 +0100299const std::unordered_map<std::string, std::string>*
300 AssetManager2::GetOverlayableMapForPackage(uint32_t package_id) const {
301
302 if (package_id >= package_ids_.size()) {
303 return nullptr;
304 }
305
306 const size_t idx = package_ids_[package_id];
307 if (idx == 0xff) {
308 return nullptr;
309 }
310
311 const PackageGroup& package_group = package_groups_[idx];
Ryan Mitchell80094e32020-11-16 23:08:18 +0000312 if (package_group.packages_.empty()) {
MÃ¥rten Kongstadc92c4dd2019-02-05 01:29:59 +0100313 return nullptr;
314 }
315
316 const auto loaded_package = package_group.packages_[0].loaded_package_;
317 return &loaded_package->GetOverlayableMap();
318}
319
Ryan Mitchell2e394222019-08-28 12:10:51 -0700320bool AssetManager2::GetOverlayablesToString(const android::StringPiece& package_name,
321 std::string* out) const {
322 uint8_t package_id = 0U;
323 for (const auto& apk_assets : apk_assets_) {
324 const LoadedArsc* loaded_arsc = apk_assets->GetLoadedArsc();
325 if (loaded_arsc == nullptr) {
326 continue;
327 }
328
329 const auto& loaded_packages = loaded_arsc->GetPackages();
330 if (loaded_packages.empty()) {
331 continue;
332 }
333
334 const auto& loaded_package = loaded_packages[0];
335 if (loaded_package->GetPackageName() == package_name) {
336 package_id = GetAssignedPackageId(loaded_package.get());
337 break;
338 }
339 }
340
341 if (package_id == 0U) {
342 ANDROID_LOG(ERROR) << base::StringPrintf("No package with name '%s", package_name.data());
343 return false;
344 }
345
346 const size_t idx = package_ids_[package_id];
347 if (idx == 0xff) {
348 return false;
349 }
350
351 std::string output;
352 for (const ConfiguredPackage& package : package_groups_[idx].packages_) {
353 const LoadedPackage* loaded_package = package.loaded_package_;
354 for (auto it = loaded_package->begin(); it != loaded_package->end(); it++) {
355 const OverlayableInfo* info = loaded_package->GetOverlayableInfo(*it);
356 if (info != nullptr) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000357 auto res_name = GetResourceName(*it);
358 if (!res_name.has_value()) {
Ryan Mitchell2e394222019-08-28 12:10:51 -0700359 ANDROID_LOG(ERROR) << base::StringPrintf(
360 "Unable to retrieve name of overlayable resource 0x%08x", *it);
361 return false;
362 }
363
Ryan Mitchell80094e32020-11-16 23:08:18 +0000364 const std::string name = ToFormattedResourceString(*res_name);
Ryan Mitchell2e394222019-08-28 12:10:51 -0700365 output.append(base::StringPrintf(
366 "resource='%s' overlayable='%s' actor='%s' policy='0x%08x'\n",
367 name.c_str(), info->name.c_str(), info->actor.c_str(), info->policy_flags));
368 }
369 }
370 }
371
372 *out = std::move(output);
373 return true;
374}
375
Ryan Mitchell192400c2020-04-02 09:54:23 -0700376bool AssetManager2::ContainsAllocatedTable() const {
377 return std::find_if(apk_assets_.begin(), apk_assets_.end(),
378 std::mem_fn(&ApkAssets::IsTableAllocated)) != apk_assets_.end();
379}
380
Adam Lesinski7ad11102016-10-28 16:39:15 -0700381void AssetManager2::SetConfiguration(const ResTable_config& configuration) {
382 const int diff = configuration_.diff(configuration);
383 configuration_ = configuration;
384
385 if (diff) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800386 RebuildFilterList();
Adam Lesinski7ad11102016-10-28 16:39:15 -0700387 InvalidateCaches(static_cast<uint32_t>(diff));
388 }
389}
390
Ryan Mitchellef538432021-03-01 14:52:14 -0800391std::set<const ApkAssets*> AssetManager2::GetNonSystemOverlays() const {
392 std::set<const ApkAssets*> non_system_overlays;
Adam Lesinski0c405242017-01-13 20:47:26 -0800393 for (const PackageGroup& package_group : package_groups_) {
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800394 bool found_system_package = false;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800395 for (const ConfiguredPackage& package : package_group.packages_) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700396 if (package.loaded_package_->IsSystem()) {
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800397 found_system_package = true;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700398 break;
399 }
400 }
401
402 if (!found_system_package) {
403 for (const ConfiguredOverlay& overlay : package_group.overlays_) {
Ryan Mitchellef538432021-03-01 14:52:14 -0800404 non_system_overlays.insert(apk_assets_[overlay.cookie]);
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700405 }
406 }
407 }
408
409 return non_system_overlays;
410}
411
Ryan Mitchell80094e32020-11-16 23:08:18 +0000412base::expected<std::set<ResTable_config>, IOError> AssetManager2::GetResourceConfigurations(
413 bool exclude_system, bool exclude_mipmap) const {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700414 ATRACE_NAME("AssetManager::GetResourceConfigurations");
415 const auto non_system_overlays =
Ryan Mitchellef538432021-03-01 14:52:14 -0800416 (exclude_system) ? GetNonSystemOverlays() : std::set<const ApkAssets*>();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700417
418 std::set<ResTable_config> configurations;
419 for (const PackageGroup& package_group : package_groups_) {
420 for (size_t i = 0; i < package_group.packages_.size(); i++) {
421 const ConfiguredPackage& package = package_group.packages_[i];
422 if (exclude_system && package.loaded_package_->IsSystem()) {
Adam Lesinski0c405242017-01-13 20:47:26 -0800423 continue;
424 }
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800425
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700426 auto apk_assets = apk_assets_[package_group.cookies_[i]];
Ryan Mitchellef538432021-03-01 14:52:14 -0800427 if (exclude_system && apk_assets->IsOverlay() &&
428 non_system_overlays.find(apk_assets) == non_system_overlays.end()) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700429 // Exclude overlays that target system resources.
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800430 continue;
431 }
432
Ryan Mitchell80094e32020-11-16 23:08:18 +0000433 auto result = package.loaded_package_->CollectConfigurations(exclude_mipmap, &configurations);
434 if (UNLIKELY(!result.has_value())) {
435 return base::unexpected(result.error());
436 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800437 }
438 }
439 return configurations;
440}
441
442std::set<std::string> AssetManager2::GetResourceLocales(bool exclude_system,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800443 bool merge_equivalent_languages) const {
444 ATRACE_NAME("AssetManager::GetResourceLocales");
Adam Lesinski0c405242017-01-13 20:47:26 -0800445 std::set<std::string> locales;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700446 const auto non_system_overlays =
Ryan Mitchellef538432021-03-01 14:52:14 -0800447 (exclude_system) ? GetNonSystemOverlays() : std::set<const ApkAssets*>();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700448
Adam Lesinski0c405242017-01-13 20:47:26 -0800449 for (const PackageGroup& package_group : package_groups_) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700450 for (size_t i = 0; i < package_group.packages_.size(); i++) {
451 const ConfiguredPackage& package = package_group.packages_[i];
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800452 if (exclude_system && package.loaded_package_->IsSystem()) {
Adam Lesinski0c405242017-01-13 20:47:26 -0800453 continue;
454 }
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800455
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700456 auto apk_assets = apk_assets_[package_group.cookies_[i]];
Ryan Mitchellef538432021-03-01 14:52:14 -0800457 if (exclude_system && apk_assets->IsOverlay() &&
458 non_system_overlays.find(apk_assets) == non_system_overlays.end()) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700459 // Exclude overlays that target system resources.
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800460 continue;
461 }
462
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800463 package.loaded_package_->CollectLocales(merge_equivalent_languages, &locales);
Adam Lesinski0c405242017-01-13 20:47:26 -0800464 }
465 }
466 return locales;
467}
468
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800469std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename,
470 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700471 const std::string new_path = "assets/" + filename;
472 return OpenNonAsset(new_path, mode);
473}
474
475std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename, ApkAssetsCookie cookie,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800476 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700477 const std::string new_path = "assets/" + filename;
478 return OpenNonAsset(new_path, cookie, mode);
479}
480
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800481std::unique_ptr<AssetDir> AssetManager2::OpenDir(const std::string& dirname) const {
482 ATRACE_NAME("AssetManager::OpenDir");
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800483
484 std::string full_path = "assets/" + dirname;
485 std::unique_ptr<SortedVector<AssetDir::FileInfo>> files =
486 util::make_unique<SortedVector<AssetDir::FileInfo>>();
487
488 // Start from the back.
489 for (auto iter = apk_assets_.rbegin(); iter != apk_assets_.rend(); ++iter) {
490 const ApkAssets* apk_assets = *iter;
MÃ¥rten Kongstaddbf343b2019-02-21 07:54:18 +0100491 if (apk_assets->IsOverlay()) {
492 continue;
493 }
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800494
495 auto func = [&](const StringPiece& name, FileType type) {
496 AssetDir::FileInfo info;
497 info.setFileName(String8(name.data(), name.size()));
498 info.setFileType(type);
Ryan Mitchellef538432021-03-01 14:52:14 -0800499 info.setSourceName(String8(apk_assets->GetDebugName().c_str()));
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800500 files->add(info);
501 };
502
Ryan Mitchellc07aa702020-03-10 13:49:12 -0700503 if (!apk_assets->GetAssetsProvider()->ForEachFile(full_path, func)) {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800504 return {};
505 }
506 }
507
508 std::unique_ptr<AssetDir> asset_dir = util::make_unique<AssetDir>();
509 asset_dir->setFileList(files.release());
510 return asset_dir;
511}
512
Adam Lesinski7ad11102016-10-28 16:39:15 -0700513// Search in reverse because that's how we used to do it and we need to preserve behaviour.
514// This is unfortunate, because ClassLoaders delegate to the parent first, so the order
515// is inconsistent for split APKs.
516std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
517 Asset::AccessMode mode,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800518 ApkAssetsCookie* out_cookie) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700519 for (int32_t i = apk_assets_.size() - 1; i >= 0; i--) {
MÃ¥rten Kongstaddbf343b2019-02-21 07:54:18 +0100520 // Prevent RRO from modifying assets and other entries accessed by file
521 // path. Explicitly asking for a path in a given package (denoted by a
522 // cookie) is still OK.
523 if (apk_assets_[i]->IsOverlay()) {
524 continue;
525 }
526
Ryan Mitchellc07aa702020-03-10 13:49:12 -0700527 std::unique_ptr<Asset> asset = apk_assets_[i]->GetAssetsProvider()->Open(filename, mode);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700528 if (asset) {
529 if (out_cookie != nullptr) {
530 *out_cookie = i;
531 }
532 return asset;
533 }
534 }
535
536 if (out_cookie != nullptr) {
537 *out_cookie = kInvalidCookie;
538 }
539 return {};
540}
541
542std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800543 ApkAssetsCookie cookie,
544 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700545 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
546 return {};
547 }
Ryan Mitchellc07aa702020-03-10 13:49:12 -0700548 return apk_assets_[cookie]->GetAssetsProvider()->Open(filename, mode);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700549}
550
Ryan Mitchell80094e32020-11-16 23:08:18 +0000551base::expected<FindEntryResult, NullOrIOError> AssetManager2::FindEntry(
552 uint32_t resid, uint16_t density_override, bool stop_at_first_match,
553 bool ignore_configuration) const {
554 const bool logging_enabled = resource_resolution_logging_enabled_;
555 if (UNLIKELY(logging_enabled)) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700556 // Clear the last logged resource resolution.
557 ResetResourceResolution();
558 last_resolution_.resid = resid;
559 }
560
Adam Lesinski7ad11102016-10-28 16:39:15 -0700561 // Might use this if density_override != 0.
562 ResTable_config density_override_config;
563
564 // Select our configuration or generate a density override configuration.
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800565 const ResTable_config* desired_config = &configuration_;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700566 if (density_override != 0 && density_override != configuration_.density) {
567 density_override_config = configuration_;
568 density_override_config.density = density_override;
569 desired_config = &density_override_config;
570 }
571
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700572 // Retrieve the package group from the package id of the resource id.
Ryan Mitchell80094e32020-11-16 23:08:18 +0000573 if (UNLIKELY(!is_valid_resid(resid))) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500574 LOG(ERROR) << base::StringPrintf("Invalid ID 0x%08x.", resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000575 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -0500576 }
577
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800578 const uint32_t package_id = get_package_id(resid);
579 const uint8_t type_idx = get_type_id(resid) - 1;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800580 const uint16_t entry_idx = get_entry_id(resid);
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700581 uint8_t package_idx = package_ids_[package_id];
Ryan Mitchell80094e32020-11-16 23:08:18 +0000582 if (UNLIKELY(package_idx == 0xff)) {
Ryan Mitchell2fe23472019-02-27 09:43:01 -0800583 ANDROID_LOG(ERROR) << base::StringPrintf("No package ID %02x found for ID 0x%08x.",
584 package_id, resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000585 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -0500586 }
587
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800588 const PackageGroup& package_group = package_groups_[package_idx];
Ryan Mitchell80094e32020-11-16 23:08:18 +0000589 auto result = FindEntryInternal(package_group, type_idx, entry_idx, *desired_config,
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800590 stop_at_first_match, ignore_configuration);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000591 if (UNLIKELY(!result.has_value())) {
592 return base::unexpected(result.error());
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700593 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800594
Jackal Guo552b45d2021-09-29 10:52:19 +0800595 bool overlaid = false;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000596 if (!stop_at_first_match && !ignore_configuration && !apk_assets_[result->cookie]->IsLoader()) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700597 for (const auto& id_map : package_group.overlays_) {
598 auto overlay_entry = id_map.overlay_res_maps_.Lookup(resid);
599 if (!overlay_entry) {
600 // No id map entry exists for this target resource.
601 continue;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000602 }
603 if (overlay_entry.IsInlineValue()) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700604 // The target resource is overlaid by an inline value not represented by a resource.
Jeremy Meyerbe2b7792022-08-23 17:42:50 +0000605 ConfigDescription best_frro_config;
606 Res_value best_frro_value;
607 bool frro_found = false;
608 for( const auto& [config, value] : overlay_entry.GetInlineValue()) {
609 if ((!frro_found || config.isBetterThan(best_frro_config, desired_config))
610 && config.match(*desired_config)) {
611 frro_found = true;
612 best_frro_config = config;
613 best_frro_value = value;
614 }
615 }
616 if (!frro_found) {
617 continue;
618 }
619 result->entry = best_frro_value;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000620 result->dynamic_ref_table = id_map.overlay_res_maps_.GetOverlayDynamicRefTable();
621 result->cookie = id_map.cookie;
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800622
623 if (UNLIKELY(logging_enabled)) {
624 last_resolution_.steps.push_back(
625 Resolution::Step{Resolution::Step::Type::OVERLAID_INLINE, String8(), result->cookie});
Jackal Guo552b45d2021-09-29 10:52:19 +0800626 if (auto path = apk_assets_[result->cookie]->GetPath()) {
627 const std::string overlay_path = path->data();
628 if (IsFabricatedOverlay(overlay_path)) {
629 // FRRO don't have package name so we use the creating package here.
630 String8 frro_name = String8("FRRO");
631 // Get the first part of it since the expected one should be like
632 // {overlayPackageName}-{overlayName}-{4 alphanumeric chars}.frro
633 // under /data/resource-cache/.
634 const std::string name = overlay_path.substr(overlay_path.rfind('/') + 1);
635 const size_t end = name.find('-');
636 if (frro_name.size() != overlay_path.size() && end != std::string::npos) {
637 frro_name.append(base::StringPrintf(" created by %s",
638 name.substr(0 /* pos */,
639 end).c_str()).c_str());
640 }
641 last_resolution_.best_package_name = frro_name;
642 } else {
643 last_resolution_.best_package_name = result->package_name->c_str();
644 }
645 }
646 overlaid = true;
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800647 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700648 continue;
649 }
650
Ryan Mitchell80094e32020-11-16 23:08:18 +0000651 auto overlay_result = FindEntry(overlay_entry.GetResourceId(), density_override,
652 false /* stop_at_first_match */,
653 false /* ignore_configuration */);
654 if (UNLIKELY(IsIOError(overlay_result))) {
655 return base::unexpected(overlay_result.error());
656 }
657 if (!overlay_result.has_value()) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700658 continue;
659 }
660
Ryan Mitchell80094e32020-11-16 23:08:18 +0000661 if (!overlay_result->config.isBetterThan(result->config, desired_config)
662 && overlay_result->config.compare(result->config) != 0) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700663 // The configuration of the entry for the overlay must be equal to or better than the target
664 // configuration to be chosen as the better value.
665 continue;
666 }
667
Ryan Mitchell80094e32020-11-16 23:08:18 +0000668 result->cookie = overlay_result->cookie;
669 result->entry = overlay_result->entry;
670 result->config = overlay_result->config;
671 result->dynamic_ref_table = id_map.overlay_res_maps_.GetOverlayDynamicRefTable();
672
673 if (UNLIKELY(logging_enabled)) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700674 last_resolution_.steps.push_back(
Ryan Mitchell80094e32020-11-16 23:08:18 +0000675 Resolution::Step{Resolution::Step::Type::OVERLAID, overlay_result->config.toString(),
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800676 overlay_result->cookie});
Jackal Guo552b45d2021-09-29 10:52:19 +0800677 last_resolution_.best_package_name =
678 overlay_result->package_name->c_str();
679 overlaid = true;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700680 }
681 }
682 }
683
Ryan Mitchell80094e32020-11-16 23:08:18 +0000684 if (UNLIKELY(logging_enabled)) {
685 last_resolution_.cookie = result->cookie;
686 last_resolution_.type_string_ref = result->type_string_ref;
687 last_resolution_.entry_string_ref = result->entry_string_ref;
Jackal Guo552b45d2021-09-29 10:52:19 +0800688 last_resolution_.best_config_name = result->config.toString();
689 if (!overlaid) {
690 last_resolution_.best_package_name = result->package_name->c_str();
691 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700692 }
693
Ryan Mitchell80094e32020-11-16 23:08:18 +0000694 return result;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700695}
696
Ryan Mitchell80094e32020-11-16 23:08:18 +0000697base::expected<FindEntryResult, NullOrIOError> AssetManager2::FindEntryInternal(
698 const PackageGroup& package_group, uint8_t type_idx, uint16_t entry_idx,
699 const ResTable_config& desired_config, bool stop_at_first_match,
700 bool ignore_configuration) const {
701 const bool logging_enabled = resource_resolution_logging_enabled_;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800702 ApkAssetsCookie best_cookie = kInvalidCookie;
703 const LoadedPackage* best_package = nullptr;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000704 incfs::verified_map_ptr<ResTable_type> best_type;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800705 const ResTable_config* best_config = nullptr;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000706 uint32_t best_offset = 0U;
707 uint32_t type_flags = 0U;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800708
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800709 // If `desired_config` is not the same as the set configuration or the caller will accept a value
710 // from any configuration, then we cannot use our filtered list of types since it only it contains
711 // types matched to the set configuration.
712 const bool use_filtered = !ignore_configuration && &desired_config == &configuration_;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800713
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700714 const size_t package_count = package_group.packages_.size();
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800715 for (size_t pi = 0; pi < package_count; pi++) {
716 const ConfiguredPackage& loaded_package_impl = package_group.packages_[pi];
717 const LoadedPackage* loaded_package = loaded_package_impl.loaded_package_;
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800718 const ApkAssetsCookie cookie = package_group.cookies_[pi];
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800719
720 // If the type IDs are offset in this package, we need to take that into account when searching
721 // for a type.
722 const TypeSpec* type_spec = loaded_package->GetTypeSpecByTypeIndex(type_idx);
723 if (UNLIKELY(type_spec == nullptr)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700724 continue;
725 }
726
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800727 // Allow custom loader packages to overlay resource values with configurations equivalent to the
728 // current best configuration.
729 const bool package_is_loader = loaded_package->IsCustomLoader();
730
Ryan Mitchell80094e32020-11-16 23:08:18 +0000731 auto entry_flags = type_spec->GetFlagsForEntryIndex(entry_idx);
Bernie Innocenti58cf8e32020-12-19 15:31:52 +0900732 if (UNLIKELY(!entry_flags.has_value())) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000733 return base::unexpected(entry_flags.error());
734 }
735 type_flags |= entry_flags.value();
736
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800737 const FilteredConfigGroup& filtered_group = loaded_package_impl.filtered_configs_[type_idx];
738 const size_t type_entry_count = (use_filtered) ? filtered_group.type_entries.size()
739 : type_spec->type_entries.size();
740 for (size_t i = 0; i < type_entry_count; i++) {
741 const TypeSpec::TypeEntry* type_entry = (use_filtered) ? filtered_group.type_entries[i]
742 : &type_spec->type_entries[i];
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800743
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800744 // We can skip calling ResTable_config::match() if the caller does not care for the
745 // configuration to match or if we're using the list of types that have already had their
746 // configuration matched.
747 const ResTable_config& this_config = type_entry->config;
748 if (!(use_filtered || ignore_configuration || this_config.match(desired_config))) {
749 continue;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800750 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800751
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800752 Resolution::Step::Type resolution_type;
753 if (best_config == nullptr) {
754 resolution_type = Resolution::Step::Type::INITIAL;
755 } else if (this_config.isBetterThan(*best_config, &desired_config)) {
756 resolution_type = Resolution::Step::Type::BETTER_MATCH;
757 } else if (package_is_loader && this_config.compare(*best_config) == 0) {
758 resolution_type = Resolution::Step::Type::OVERLAID;
759 } else {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000760 if (UNLIKELY(logging_enabled)) {
Jackal Guo552b45d2021-09-29 10:52:19 +0800761 last_resolution_.steps.push_back(Resolution::Step{Resolution::Step::Type::SKIPPED,
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800762 this_config.toString(),
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800763 cookie});
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800764 }
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800765 continue;
766 }
767
768 // The configuration matches and is better than the previous selection.
769 // Find the entry value if it exists for this configuration.
770 const auto& type = type_entry->type;
771 const auto offset = LoadedPackage::GetEntryOffset(type, entry_idx);
772 if (UNLIKELY(IsIOError(offset))) {
773 return base::unexpected(offset.error());
774 }
775
776 if (!offset.has_value()) {
777 if (UNLIKELY(logging_enabled)) {
Jackal Guo552b45d2021-09-29 10:52:19 +0800778 last_resolution_.steps.push_back(Resolution::Step{Resolution::Step::Type::NO_ENTRY,
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800779 this_config.toString(),
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800780 cookie});
781 }
782 continue;
783 }
784
785 best_cookie = cookie;
786 best_package = loaded_package;
787 best_type = type;
788 best_config = &this_config;
789 best_offset = offset.value();
790
791 if (UNLIKELY(logging_enabled)) {
792 last_resolution_.steps.push_back(Resolution::Step{resolution_type,
793 this_config.toString(),
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800794 cookie});
795 }
796
797 // Any configuration will suffice, so break.
798 if (stop_at_first_match) {
799 break;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700800 }
801 }
802 }
803
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800804 if (UNLIKELY(best_cookie == kInvalidCookie)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000805 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700806 }
807
Eric Miao368cd192022-09-09 15:46:14 -0700808 auto best_entry_verified = LoadedPackage::GetEntryFromOffset(best_type, best_offset);
809 if (!best_entry_verified.has_value()) {
810 return base::unexpected(best_entry_verified.error());
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800811 }
812
Eric Miao368cd192022-09-09 15:46:14 -0700813 const auto entry = GetEntryValue(*best_entry_verified);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000814 if (!entry.has_value()) {
815 return base::unexpected(entry.error());
816 }
Winson2f3669b2019-01-11 11:28:34 -0800817
Ryan Mitchell80094e32020-11-16 23:08:18 +0000818 return FindEntryResult{
819 .cookie = best_cookie,
820 .entry = *entry,
821 .config = *best_config,
822 .type_flags = type_flags,
823 .package_name = &best_package->GetPackageName(),
824 .type_string_ref = StringPoolRef(best_package->GetTypeStringPool(), best_type->id - 1),
825 .entry_string_ref = StringPoolRef(best_package->GetKeyStringPool(),
Eric Miao368cd192022-09-09 15:46:14 -0700826 (*best_entry_verified)->key()),
Ryan Mitchell80094e32020-11-16 23:08:18 +0000827 .dynamic_ref_table = package_group.dynamic_ref_table.get(),
828 };
Adam Lesinski7ad11102016-10-28 16:39:15 -0700829}
830
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700831void AssetManager2::ResetResourceResolution() const {
832 last_resolution_.cookie = kInvalidCookie;
833 last_resolution_.resid = 0;
834 last_resolution_.steps.clear();
835 last_resolution_.type_string_ref = StringPoolRef();
836 last_resolution_.entry_string_ref = StringPoolRef();
Jackal Guo552b45d2021-09-29 10:52:19 +0800837 last_resolution_.best_config_name.clear();
838 last_resolution_.best_package_name.clear();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700839}
840
Winson2f3669b2019-01-11 11:28:34 -0800841void AssetManager2::SetResourceResolutionLoggingEnabled(bool enabled) {
842 resource_resolution_logging_enabled_ = enabled;
Winson2f3669b2019-01-11 11:28:34 -0800843 if (!enabled) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700844 ResetResourceResolution();
Winson2f3669b2019-01-11 11:28:34 -0800845 }
846}
847
848std::string AssetManager2::GetLastResourceResolution() const {
849 if (!resource_resolution_logging_enabled_) {
850 LOG(ERROR) << "Must enable resource resolution logging before getting path.";
Ryan Mitchell80094e32020-11-16 23:08:18 +0000851 return {};
Winson2f3669b2019-01-11 11:28:34 -0800852 }
853
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800854 const ApkAssetsCookie cookie = last_resolution_.cookie;
Winson2f3669b2019-01-11 11:28:34 -0800855 if (cookie == kInvalidCookie) {
856 LOG(ERROR) << "AssetManager hasn't resolved a resource to read resolution path.";
Ryan Mitchell80094e32020-11-16 23:08:18 +0000857 return {};
Winson2f3669b2019-01-11 11:28:34 -0800858 }
859
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800860 const uint32_t resid = last_resolution_.resid;
861 const auto package = apk_assets_[cookie]->GetLoadedArsc()->GetPackageById(get_package_id(resid));
862
Winson2f3669b2019-01-11 11:28:34 -0800863 std::string resource_name_string;
Winson2f3669b2019-01-11 11:28:34 -0800864 if (package != nullptr) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000865 auto resource_name = ToResourceName(last_resolution_.type_string_ref,
866 last_resolution_.entry_string_ref,
867 package->GetPackageName());
868 resource_name_string = resource_name.has_value() ?
869 ToFormattedResourceString(resource_name.value()) : "<unknown>";
Winson2f3669b2019-01-11 11:28:34 -0800870 }
871
872 std::stringstream log_stream;
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800873 log_stream << base::StringPrintf("Resolution for 0x%08x %s\n"
874 "\tFor config - %s", resid, resource_name_string.c_str(),
875 configuration_.toString().c_str());
Winson2f3669b2019-01-11 11:28:34 -0800876
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800877 for (const Resolution::Step& step : last_resolution_.steps) {
878 const static std::unordered_map<Resolution::Step::Type, const char*> kStepStrings = {
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800879 {Resolution::Step::Type::INITIAL, "Found initial"},
880 {Resolution::Step::Type::BETTER_MATCH, "Found better"},
881 {Resolution::Step::Type::OVERLAID, "Overlaid"},
882 {Resolution::Step::Type::OVERLAID_INLINE, "Overlaid inline"},
883 {Resolution::Step::Type::SKIPPED, "Skipped"},
884 {Resolution::Step::Type::NO_ENTRY, "No entry"}
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800885 };
886
887 const auto prefix = kStepStrings.find(step.type);
888 if (prefix == kStepStrings.end()) {
889 continue;
Winson2f3669b2019-01-11 11:28:34 -0800890 }
891
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800892 log_stream << "\n\t" << prefix->second << ": " << apk_assets_[step.cookie]->GetDebugName();
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800893 if (!step.config_name.isEmpty()) {
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800894 log_stream << " - " << step.config_name;
Winson2f3669b2019-01-11 11:28:34 -0800895 }
896 }
897
Jackal Guo552b45d2021-09-29 10:52:19 +0800898 log_stream << "\nBest matching is from "
899 << (last_resolution_.best_config_name.isEmpty() ? "default"
900 : last_resolution_.best_config_name)
901 << " configuration of " << last_resolution_.best_package_name;
Winson2f3669b2019-01-11 11:28:34 -0800902 return log_stream.str();
903}
904
Felka Chang00964e92021-12-10 01:19:08 +0800905base::expected<uint32_t, NullOrIOError> AssetManager2::GetParentThemeResourceId(uint32_t resid)
906const {
907 auto entry = FindEntry(resid, 0u /* density_override */,
908 false /* stop_at_first_match */,
909 false /* ignore_configuration */);
910 if (!entry.has_value()) {
911 return base::unexpected(entry.error());
912 }
913
914 auto entry_map = std::get_if<incfs::verified_map_ptr<ResTable_map_entry>>(&entry->entry);
915 if (entry_map == nullptr) {
916 // Not a bag, nothing to do.
917 return base::unexpected(std::nullopt);
918 }
919
920 auto map = *entry_map;
921 const uint32_t parent_resid = dtohl(map->parent.ident);
922
923 return parent_resid;
924}
925
Ryan Mitchell80094e32020-11-16 23:08:18 +0000926base::expected<AssetManager2::ResourceName, NullOrIOError> AssetManager2::GetResourceName(
927 uint32_t resid) const {
928 auto result = FindEntry(resid, 0u /* density_override */, true /* stop_at_first_match */,
929 true /* ignore_configuration */);
930 if (!result.has_value()) {
931 return base::unexpected(result.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -0700932 }
933
Ryan Mitchell80094e32020-11-16 23:08:18 +0000934 return ToResourceName(result->type_string_ref,
935 result->entry_string_ref,
936 *result->package_name);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700937}
938
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800939base::expected<uint32_t, NullOrIOError> AssetManager2::GetResourceTypeSpecFlags(
940 uint32_t resid) const {
941 auto result = FindEntry(resid, 0u /* density_override */, false /* stop_at_first_match */,
942 true /* ignore_configuration */);
943 if (!result.has_value()) {
944 return base::unexpected(result.error());
945 }
946 return result->type_flags;
947}
948
Ryan Mitchell80094e32020-11-16 23:08:18 +0000949base::expected<AssetManager2::SelectedValue, NullOrIOError> AssetManager2::GetResource(
950 uint32_t resid, bool may_be_bag, uint16_t density_override) const {
951 auto result = FindEntry(resid, density_override, false /* stop_at_first_match */,
952 false /* ignore_configuration */);
953 if (!result.has_value()) {
954 return base::unexpected(result.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -0700955 }
956
Ryan Mitchell80094e32020-11-16 23:08:18 +0000957 auto result_map_entry = std::get_if<incfs::verified_map_ptr<ResTable_map_entry>>(&result->entry);
Ryan Mitchellbf1f45b2020-09-29 17:22:52 -0700958 if (result_map_entry != nullptr) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700959 if (!may_be_bag) {
960 LOG(ERROR) << base::StringPrintf("Resource %08x is a complex map type.", resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000961 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700962 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800963
964 // Create a reference since we can't represent this complex type as a Res_value.
Ryan Mitchell80094e32020-11-16 23:08:18 +0000965 return SelectedValue(Res_value::TYPE_REFERENCE, resid, result->cookie, result->type_flags,
966 resid, result->config);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700967 }
968
Adam Lesinskida431a22016-12-29 16:08:16 -0500969 // Convert the package ID to the runtime assigned package ID.
Ryan Mitchell80094e32020-11-16 23:08:18 +0000970 Res_value value = std::get<Res_value>(result->entry);
971 result->dynamic_ref_table->lookupResourceValue(&value);
Adam Lesinskida431a22016-12-29 16:08:16 -0500972
Ryan Mitchell80094e32020-11-16 23:08:18 +0000973 return SelectedValue(value.dataType, value.data, result->cookie, result->type_flags,
974 resid, result->config);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700975}
976
Ryan Mitchell80094e32020-11-16 23:08:18 +0000977base::expected<std::monostate, NullOrIOError> AssetManager2::ResolveReference(
Ryan Mitchella45506e2020-11-16 23:08:18 +0000978 AssetManager2::SelectedValue& value, bool cache_value) const {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000979 if (value.type != Res_value::TYPE_REFERENCE || value.data == 0U) {
980 // Not a reference. Nothing to do.
981 return {};
Adam Lesinski0c405242017-01-13 20:47:26 -0800982 }
Ryan Mitchell80094e32020-11-16 23:08:18 +0000983
Ryan Mitchella45506e2020-11-16 23:08:18 +0000984 const uint32_t original_flags = value.flags;
985 const uint32_t original_resid = value.data;
986 if (cache_value) {
987 auto cached_value = cached_resolved_values_.find(value.data);
988 if (cached_value != cached_resolved_values_.end()) {
989 value = cached_value->second;
990 value.flags |= original_flags;
991 return {};
992 }
993 }
994
995 uint32_t combined_flags = 0U;
996 uint32_t resolve_resid = original_resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000997 constexpr const uint32_t kMaxIterations = 20;
998 for (uint32_t i = 0U;; i++) {
999 auto result = GetResource(resolve_resid, true /*may_be_bag*/);
1000 if (!result.has_value()) {
Ryan Mitchelle7ab6272020-11-13 18:06:15 -08001001 value.resid = resolve_resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001002 return base::unexpected(result.error());
1003 }
1004
Ryan Mitchelle7ab6272020-11-13 18:06:15 -08001005 // If resource resolution fails, the value should be set to the last reference that was able to
1006 // be resolved successfully.
1007 value = *result;
1008 value.flags |= combined_flags;
1009
Ryan Mitchell80094e32020-11-16 23:08:18 +00001010 if (result->type != Res_value::TYPE_REFERENCE ||
1011 result->data == Res_value::DATA_NULL_UNDEFINED ||
1012 result->data == resolve_resid || i == kMaxIterations) {
1013 // This reference can't be resolved, so exit now and let the caller deal with it.
Ryan Mitchella45506e2020-11-16 23:08:18 +00001014 if (cache_value) {
1015 cached_resolved_values_[original_resid] = value;
1016 }
1017
1018 // Above value is cached without original_flags to ensure they don't get included in future
1019 // queries that hit the cache
1020 value.flags |= original_flags;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001021 return {};
1022 }
1023
Ryan Mitchelle7ab6272020-11-13 18:06:15 -08001024 combined_flags = result->flags;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001025 resolve_resid = result->data;
1026 }
Adam Lesinski0c405242017-01-13 20:47:26 -08001027}
1028
Ryan Mitchell80094e32020-11-16 23:08:18 +00001029const std::vector<uint32_t> AssetManager2::GetBagResIdStack(uint32_t resid) const {
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001030 auto cached_iter = cached_bag_resid_stacks_.find(resid);
1031 if (cached_iter != cached_bag_resid_stacks_.end()) {
1032 return cached_iter->second;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001033 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001034
1035 std::vector<uint32_t> found_resids;
1036 GetBag(resid, found_resids);
1037 cached_bag_resid_stacks_.emplace(resid, found_resids);
1038 return found_resids;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001039}
1040
Ryan Mitchell80094e32020-11-16 23:08:18 +00001041base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::ResolveBag(
1042 AssetManager2::SelectedValue& value) const {
1043 if (UNLIKELY(value.type != Res_value::TYPE_REFERENCE)) {
1044 return base::unexpected(std::nullopt);
1045 }
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001046
Ryan Mitchell80094e32020-11-16 23:08:18 +00001047 auto bag = GetBag(value.data);
1048 if (bag.has_value()) {
1049 value.flags |= (*bag)->type_spec_flags;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001050 }
1051 return bag;
y57cd1952018-04-12 14:26:23 -07001052}
1053
Ryan Mitchell80094e32020-11-16 23:08:18 +00001054base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::GetBag(uint32_t resid) const {
1055 std::vector<uint32_t> found_resids;
1056 const auto bag = GetBag(resid, found_resids);
Yurii Zubrytskyiab3cb302022-10-11 12:15:52 -07001057 cached_bag_resid_stacks_.emplace(resid, std::move(found_resids));
Ryan Mitchell80094e32020-11-16 23:08:18 +00001058 return bag;
Ryan Mitchell155d5392020-02-10 13:35:24 -08001059}
1060
Ryan Mitchell80094e32020-11-16 23:08:18 +00001061base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::GetBag(
1062 uint32_t resid, std::vector<uint32_t>& child_resids) const {
1063 if (auto cached_iter = cached_bags_.find(resid); cached_iter != cached_bags_.end()) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001064 return cached_iter->second.get();
1065 }
1066
Ryan Mitchell80094e32020-11-16 23:08:18 +00001067 auto entry = FindEntry(resid, 0u /* density_override */, false /* stop_at_first_match */,
1068 false /* ignore_configuration */);
1069 if (!entry.has_value()) {
1070 return base::unexpected(entry.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001071 }
1072
Ryan Mitchell80094e32020-11-16 23:08:18 +00001073 auto entry_map = std::get_if<incfs::verified_map_ptr<ResTable_map_entry>>(&entry->entry);
1074 if (entry_map == nullptr) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001075 // Not a bag, nothing to do.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001076 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001077 }
1078
Ryan Mitchell80094e32020-11-16 23:08:18 +00001079 auto map = *entry_map;
1080 auto map_entry = map.offset(dtohs(map->size)).convert<ResTable_map>();
1081 const auto map_entry_end = map_entry + dtohl(map->count);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001082
y57cd1952018-04-12 14:26:23 -07001083 // Keep track of ids that have already been seen to prevent infinite loops caused by circular
Ryan Mitchell80094e32020-11-16 23:08:18 +00001084 // dependencies between bags.
y57cd1952018-04-12 14:26:23 -07001085 child_resids.push_back(resid);
1086
Adam Lesinskida431a22016-12-29 16:08:16 -05001087 uint32_t parent_resid = dtohl(map->parent.ident);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001088 if (parent_resid == 0U ||
1089 std::find(child_resids.begin(), child_resids.end(), parent_resid) != child_resids.end()) {
1090 // There is no parent or a circular parental dependency exist, meaning there is nothing to
1091 // inherit and we can do a simple copy of the entries in the map.
Adam Lesinski7ad11102016-10-28 16:39:15 -07001092 const size_t entry_count = map_entry_end - map_entry;
1093 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
1094 malloc(sizeof(ResolvedBag) + (entry_count * sizeof(ResolvedBag::Entry))))};
Ryan Mitchell155d5392020-02-10 13:35:24 -08001095
1096 bool sort_entries = false;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001097 for (auto new_entry = new_bag->entries; map_entry != map_entry_end; ++map_entry) {
1098 if (UNLIKELY(!map_entry)) {
1099 return base::unexpected(IOError::PAGES_MISSING);
1100 }
1101
Adam Lesinskida431a22016-12-29 16:08:16 -05001102 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001103 if (!is_internal_resid(new_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -05001104 // Attributes, arrays, etc don't have a resource id as the name. They specify
1105 // other data, which would be wrong to change via a lookup.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001106 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001107 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
1108 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001109 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001110 }
1111 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001112
1113 new_entry->cookie = entry->cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -05001114 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001115 new_entry->key_pool = nullptr;
1116 new_entry->type_pool = nullptr;
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001117 new_entry->style = resid;
Adam Lesinski30080e22017-10-16 16:18:09 -07001118 new_entry->value.copyFrom_dtoh(map_entry->value);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001119 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1120 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001121 LOG(ERROR) << base::StringPrintf(
1122 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
1123 new_entry->value.data, new_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001124 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001125 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001126
Ryan Mitchell155d5392020-02-10 13:35:24 -08001127 sort_entries = sort_entries ||
1128 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001129 ++new_entry;
1130 }
Ryan Mitchell155d5392020-02-10 13:35:24 -08001131
1132 if (sort_entries) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001133 std::sort(new_bag->entries, new_bag->entries + entry_count,
1134 [](auto&& lhs, auto&& rhs) { return lhs.key < rhs.key; });
Ryan Mitchell155d5392020-02-10 13:35:24 -08001135 }
1136
Ryan Mitchell80094e32020-11-16 23:08:18 +00001137 new_bag->type_spec_flags = entry->type_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001138 new_bag->entry_count = static_cast<uint32_t>(entry_count);
1139 ResolvedBag* result = new_bag.get();
1140 cached_bags_[resid] = std::move(new_bag);
1141 return result;
1142 }
1143
Adam Lesinskida431a22016-12-29 16:08:16 -05001144 // In case the parent is a dynamic reference, resolve it.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001145 entry->dynamic_ref_table->lookupResourceId(&parent_resid);
Adam Lesinskida431a22016-12-29 16:08:16 -05001146
Adam Lesinski7ad11102016-10-28 16:39:15 -07001147 // Get the parent and do a merge of the keys.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001148 const auto parent_bag = GetBag(parent_resid, child_resids);
1149 if (UNLIKELY(!parent_bag.has_value())) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001150 // Failed to get the parent that should exist.
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001151 LOG(ERROR) << base::StringPrintf("Failed to find parent 0x%08x of bag 0x%08x.", parent_resid,
1152 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001153 return base::unexpected(parent_bag.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001154 }
1155
Adam Lesinski7ad11102016-10-28 16:39:15 -07001156 // Create the max possible entries we can make. Once we construct the bag,
1157 // we will realloc to fit to size.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001158 const size_t max_count = (*parent_bag)->entry_count + dtohl(map->count);
George Burgess IV09b119f2017-07-25 15:00:04 -07001159 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
1160 malloc(sizeof(ResolvedBag) + (max_count * sizeof(ResolvedBag::Entry))))};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001161 ResolvedBag::Entry* new_entry = new_bag->entries;
1162
Ryan Mitchell80094e32020-11-16 23:08:18 +00001163 const ResolvedBag::Entry* parent_entry = (*parent_bag)->entries;
1164 const ResolvedBag::Entry* const parent_entry_end = parent_entry + (*parent_bag)->entry_count;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001165
1166 // The keys are expected to be in sorted order. Merge the two bags.
Ryan Mitchell155d5392020-02-10 13:35:24 -08001167 bool sort_entries = false;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001168 while (map_entry != map_entry_end && parent_entry != parent_entry_end) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001169 if (UNLIKELY(!map_entry)) {
1170 return base::unexpected(IOError::PAGES_MISSING);
1171 }
1172
Adam Lesinskida431a22016-12-29 16:08:16 -05001173 uint32_t child_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001174 if (!is_internal_resid(child_key)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001175 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&child_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001176 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", child_key,
1177 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001178 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001179 }
1180 }
1181
Adam Lesinski7ad11102016-10-28 16:39:15 -07001182 if (child_key <= parent_entry->key) {
1183 // Use the child key if it comes before the parent
1184 // or is equal to the parent (overrides).
Ryan Mitchell80094e32020-11-16 23:08:18 +00001185 new_entry->cookie = entry->cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001186 new_entry->key = child_key;
1187 new_entry->key_pool = nullptr;
1188 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -07001189 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001190 new_entry->style = resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001191 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1192 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001193 LOG(ERROR) << base::StringPrintf(
1194 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
1195 new_entry->value.data, child_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001196 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001197 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001198 ++map_entry;
1199 } else {
1200 // Take the parent entry as-is.
1201 memcpy(new_entry, parent_entry, sizeof(*new_entry));
1202 }
1203
Ryan Mitchell155d5392020-02-10 13:35:24 -08001204 sort_entries = sort_entries ||
1205 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001206 if (child_key >= parent_entry->key) {
1207 // Move to the next parent entry if we used it or it was overridden.
1208 ++parent_entry;
1209 }
1210 // Increment to the next entry to fill.
1211 ++new_entry;
1212 }
1213
1214 // Finish the child entries if they exist.
1215 while (map_entry != map_entry_end) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001216 if (UNLIKELY(!map_entry)) {
1217 return base::unexpected(IOError::PAGES_MISSING);
1218 }
1219
Adam Lesinskida431a22016-12-29 16:08:16 -05001220 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001221 if (!is_internal_resid(new_key)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001222 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001223 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
1224 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001225 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001226 }
1227 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001228 new_entry->cookie = entry->cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -05001229 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001230 new_entry->key_pool = nullptr;
1231 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -07001232 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001233 new_entry->style = resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001234 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1235 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001236 LOG(ERROR) << base::StringPrintf("Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.",
1237 new_entry->value.dataType, new_entry->value.data, new_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001238 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001239 }
Ryan Mitchell155d5392020-02-10 13:35:24 -08001240 sort_entries = sort_entries ||
1241 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001242 ++map_entry;
1243 ++new_entry;
1244 }
1245
1246 // Finish the parent entries if they exist.
1247 if (parent_entry != parent_entry_end) {
1248 // Take the rest of the parent entries as-is.
1249 const size_t num_entries_to_copy = parent_entry_end - parent_entry;
1250 memcpy(new_entry, parent_entry, num_entries_to_copy * sizeof(*new_entry));
1251 new_entry += num_entries_to_copy;
1252 }
1253
1254 // Resize the resulting array to fit.
1255 const size_t actual_count = new_entry - new_bag->entries;
1256 if (actual_count != max_count) {
George Burgess IV09b119f2017-07-25 15:00:04 -07001257 new_bag.reset(reinterpret_cast<ResolvedBag*>(realloc(
1258 new_bag.release(), sizeof(ResolvedBag) + (actual_count * sizeof(ResolvedBag::Entry)))));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001259 }
1260
Ryan Mitchell155d5392020-02-10 13:35:24 -08001261 if (sort_entries) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001262 std::sort(new_bag->entries, new_bag->entries + actual_count,
1263 [](auto&& lhs, auto&& rhs) { return lhs.key < rhs.key; });
Ryan Mitchell155d5392020-02-10 13:35:24 -08001264 }
1265
Adam Lesinski1a1e9c22017-10-13 15:45:34 -07001266 // Combine flags from the parent and our own bag.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001267 new_bag->type_spec_flags = entry->type_flags | (*parent_bag)->type_spec_flags;
George Burgess IV09b119f2017-07-25 15:00:04 -07001268 new_bag->entry_count = static_cast<uint32_t>(actual_count);
1269 ResolvedBag* result = new_bag.get();
1270 cached_bags_[resid] = std::move(new_bag);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001271 return result;
1272}
1273
Adam Lesinski929d6512017-01-16 19:11:19 -08001274static bool Utf8ToUtf16(const StringPiece& str, std::u16string* out) {
1275 ssize_t len =
1276 utf8_to_utf16_length(reinterpret_cast<const uint8_t*>(str.data()), str.size(), false);
1277 if (len < 0) {
1278 return false;
1279 }
1280 out->resize(static_cast<size_t>(len));
1281 utf8_to_utf16(reinterpret_cast<const uint8_t*>(str.data()), str.size(), &*out->begin(),
1282 static_cast<size_t>(len + 1));
1283 return true;
1284}
1285
Ryan Mitchell80094e32020-11-16 23:08:18 +00001286base::expected<uint32_t, NullOrIOError> AssetManager2::GetResourceId(
1287 const std::string& resource_name, const std::string& fallback_type,
1288 const std::string& fallback_package) const {
Adam Lesinski929d6512017-01-16 19:11:19 -08001289 StringPiece package_name, type, entry;
1290 if (!ExtractResourceName(resource_name, &package_name, &type, &entry)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001291 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001292 }
1293
1294 if (entry.empty()) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001295 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001296 }
1297
1298 if (package_name.empty()) {
1299 package_name = fallback_package;
1300 }
1301
1302 if (type.empty()) {
1303 type = fallback_type;
1304 }
1305
1306 std::u16string type16;
1307 if (!Utf8ToUtf16(type, &type16)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001308 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001309 }
1310
1311 std::u16string entry16;
1312 if (!Utf8ToUtf16(entry, &entry16)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001313 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001314 }
1315
1316 const StringPiece16 kAttr16 = u"attr";
1317 const static std::u16string kAttrPrivate16 = u"^attr-private";
1318
1319 for (const PackageGroup& package_group : package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001320 for (const ConfiguredPackage& package_impl : package_group.packages_) {
1321 const LoadedPackage* package = package_impl.loaded_package_;
Adam Lesinski929d6512017-01-16 19:11:19 -08001322 if (package_name != package->GetPackageName()) {
1323 // All packages in the same group are expected to have the same package name.
1324 break;
1325 }
1326
Ryan Mitchell80094e32020-11-16 23:08:18 +00001327 base::expected<uint32_t, NullOrIOError> resid = package->FindEntryByName(type16, entry16);
1328 if (UNLIKELY(IsIOError(resid))) {
1329 return base::unexpected(resid.error());
1330 }
1331
1332 if (!resid.has_value() && kAttr16 == type16) {
Adam Lesinski929d6512017-01-16 19:11:19 -08001333 // Private attributes in libraries (such as the framework) are sometimes encoded
1334 // under the type '^attr-private' in order to leave the ID space of public 'attr'
1335 // free for future additions. Check '^attr-private' for the same name.
1336 resid = package->FindEntryByName(kAttrPrivate16, entry16);
1337 }
1338
Ryan Mitchell80094e32020-11-16 23:08:18 +00001339 if (resid.has_value()) {
1340 return fix_package_id(*resid, package_group.dynamic_ref_table->mAssignedPackageId);
Adam Lesinski929d6512017-01-16 19:11:19 -08001341 }
1342 }
1343 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001344 return base::unexpected(std::nullopt);
Adam Lesinski0c405242017-01-13 20:47:26 -08001345}
1346
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001347void AssetManager2::RebuildFilterList() {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001348 for (PackageGroup& group : package_groups_) {
1349 for (ConfiguredPackage& impl : group.packages_) {
1350 // Destroy it.
1351 impl.filtered_configs_.~ByteBucketArray();
1352
1353 // Re-create it.
1354 new (&impl.filtered_configs_) ByteBucketArray<FilteredConfigGroup>();
1355
1356 // Create the filters here.
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001357 impl.loaded_package_->ForEachTypeSpec([&](const TypeSpec& type_spec, uint8_t type_id) {
1358 FilteredConfigGroup& group = impl.filtered_configs_.editItemAt(type_id - 1);
1359 for (const auto& type_entry : type_spec.type_entries) {
1360 if (type_entry.config.match(configuration_)) {
1361 group.type_entries.push_back(&type_entry);
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001362 }
1363 }
1364 });
1365 }
1366 }
1367}
1368
Adam Lesinski7ad11102016-10-28 16:39:15 -07001369void AssetManager2::InvalidateCaches(uint32_t diff) {
Ryan Mitchell2c4d8742019-03-04 09:41:00 -08001370 cached_bag_resid_stacks_.clear();
1371
Adam Lesinski7ad11102016-10-28 16:39:15 -07001372 if (diff == 0xffffffffu) {
1373 // Everything must go.
1374 cached_bags_.clear();
1375 return;
1376 }
1377
1378 // Be more conservative with what gets purged. Only if the bag has other possible
1379 // variations with respect to what changed (diff) should we remove it.
1380 for (auto iter = cached_bags_.cbegin(); iter != cached_bags_.cend();) {
1381 if (diff & iter->second->type_spec_flags) {
1382 iter = cached_bags_.erase(iter);
1383 } else {
1384 ++iter;
1385 }
1386 }
Ryan Mitchella45506e2020-11-16 23:08:18 +00001387
1388 cached_resolved_values_.clear();
Adam Lesinski7ad11102016-10-28 16:39:15 -07001389}
1390
Ryan Mitchell2e394222019-08-28 12:10:51 -07001391uint8_t AssetManager2::GetAssignedPackageId(const LoadedPackage* package) const {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001392 for (auto& package_group : package_groups_) {
1393 for (auto& package2 : package_group.packages_) {
1394 if (package2.loaded_package_ == package) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -07001395 return package_group.dynamic_ref_table->mAssignedPackageId;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001396 }
1397 }
1398 }
1399 return 0;
1400}
1401
Adam Lesinski30080e22017-10-16 16:18:09 -07001402std::unique_ptr<Theme> AssetManager2::NewTheme() {
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001403 constexpr size_t kInitialReserveSize = 32;
1404 auto theme = std::unique_ptr<Theme>(new Theme(this));
1405 theme->entries_.reserve(kInitialReserveSize);
1406 return theme;
Adam Lesinski30080e22017-10-16 16:18:09 -07001407}
1408
1409Theme::Theme(AssetManager2* asset_manager) : asset_manager_(asset_manager) {
1410}
1411
1412Theme::~Theme() = default;
1413
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001414struct Theme::Entry {
1415 uint32_t attr_res_id;
Adam Lesinski30080e22017-10-16 16:18:09 -07001416 ApkAssetsCookie cookie;
1417 uint32_t type_spec_flags;
1418 Res_value value;
1419};
1420
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001421namespace {
1422struct ThemeEntryKeyComparer {
1423 bool operator() (const Theme::Entry& entry, uint32_t attr_res_id) const noexcept {
1424 return entry.attr_res_id < attr_res_id;
1425 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001426};
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001427} // namespace
Adam Lesinski7ad11102016-10-28 16:39:15 -07001428
Ryan Mitchell80094e32020-11-16 23:08:18 +00001429base::expected<std::monostate, NullOrIOError> Theme::ApplyStyle(uint32_t resid, bool force) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001430 ATRACE_NAME("Theme::ApplyStyle");
Adam Lesinski7ad11102016-10-28 16:39:15 -07001431
Ryan Mitchell80094e32020-11-16 23:08:18 +00001432 auto bag = asset_manager_->GetBag(resid);
1433 if (!bag.has_value()) {
1434 return base::unexpected(bag.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001435 }
1436
1437 // Merge the flags from this style.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001438 type_spec_flags_ |= (*bag)->type_spec_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001439
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001440 for (auto it = begin(*bag); it != end(*bag); ++it) {
1441 const uint32_t attr_res_id = it->key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001442
Adam Lesinski30080e22017-10-16 16:18:09 -07001443 // If the resource ID passed in is not a style, the key can be some other identifier that is not
1444 // a resource ID. We should fail fast instead of operating with strange resource IDs.
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001445 if (!is_valid_resid(attr_res_id)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001446 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001447 }
1448
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001449 // DATA_NULL_EMPTY (@empty) is a valid resource value and DATA_NULL_UNDEFINED represents
1450 // an absence of a valid value.
1451 bool is_undefined = it->value.dataType == Res_value::TYPE_NULL &&
1452 it->value.data != Res_value::DATA_NULL_EMPTY;
1453 if (!force && is_undefined) {
1454 continue;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001455 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001456
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001457 auto entry_it = std::lower_bound(entries_.begin(), entries_.end(), attr_res_id,
1458 ThemeEntryKeyComparer{});
1459 if (entry_it != entries_.end() && entry_it->attr_res_id == attr_res_id) {
1460 if (is_undefined) {
1461 // DATA_NULL_UNDEFINED clears the value of the attribute in the theme only when `force` is
1462 /// true.
1463 entries_.erase(entry_it);
1464 } else if (force) {
Yurii Zubrytskyiab3cb302022-10-11 12:15:52 -07001465 *entry_it = Entry{attr_res_id, it->cookie, (*bag)->type_spec_flags, it->value};
Adam Lesinski30080e22017-10-16 16:18:09 -07001466 }
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001467 } else {
Yurii Zubrytskyiab3cb302022-10-11 12:15:52 -07001468 entries_.insert(entry_it, Entry{attr_res_id, it->cookie, (*bag)->type_spec_flags, it->value});
Adam Lesinski7ad11102016-10-28 16:39:15 -07001469 }
1470 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001471 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001472}
1473
Ryan Mitchell767e34f2021-06-07 12:29:05 -07001474void Theme::Rebase(AssetManager2* am, const uint32_t* style_ids, const uint8_t* force,
1475 size_t style_count) {
1476 ATRACE_NAME("Theme::Rebase");
1477 // Reset the entries without changing the vector capacity to prevent reallocations during
1478 // ApplyStyle.
1479 entries_.clear();
1480 asset_manager_ = am;
1481 for (size_t i = 0; i < style_count; i++) {
1482 ApplyStyle(style_ids[i], force[i]);
1483 }
1484}
1485
Ryan Mitchell80094e32020-11-16 23:08:18 +00001486std::optional<AssetManager2::SelectedValue> Theme::GetAttribute(uint32_t resid) const {
1487
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001488 constexpr const uint32_t kMaxIterations = 20;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001489 uint32_t type_spec_flags = 0u;
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001490 for (uint32_t i = 0; i <= kMaxIterations; i++) {
1491 auto entry_it = std::lower_bound(entries_.begin(), entries_.end(), resid,
1492 ThemeEntryKeyComparer{});
1493 if (entry_it == entries_.end() || entry_it->attr_res_id != resid) {
1494 return std::nullopt;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001495 }
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001496
1497 type_spec_flags |= entry_it->type_spec_flags;
1498 if (entry_it->value.dataType == Res_value::TYPE_ATTRIBUTE) {
1499 resid = entry_it->value.data;
1500 continue;
1501 }
1502
1503 return AssetManager2::SelectedValue(entry_it->value.dataType, entry_it->value.data,
1504 entry_it->cookie, type_spec_flags, 0U /* resid */,
1505 {} /* config */);
1506 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001507 return std::nullopt;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001508}
1509
Ryan Mitchell80094e32020-11-16 23:08:18 +00001510base::expected<std::monostate, NullOrIOError> Theme::ResolveAttributeReference(
1511 AssetManager2::SelectedValue& value) const {
1512 if (value.type != Res_value::TYPE_ATTRIBUTE) {
1513 return asset_manager_->ResolveReference(value);
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001514 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001515
1516 std::optional<AssetManager2::SelectedValue> result = GetAttribute(value.data);
1517 if (!result.has_value()) {
1518 return base::unexpected(std::nullopt);
1519 }
1520
Ryan Mitchella45506e2020-11-16 23:08:18 +00001521 auto resolve_result = asset_manager_->ResolveReference(*result, true /* cache_value */);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001522 if (resolve_result.has_value()) {
1523 result->flags |= value.flags;
1524 value = *result;
1525 }
1526 return resolve_result;
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001527}
1528
Adam Lesinski7ad11102016-10-28 16:39:15 -07001529void Theme::Clear() {
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001530 entries_.clear();
Adam Lesinski7ad11102016-10-28 16:39:15 -07001531}
1532
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001533base::expected<std::monostate, IOError> Theme::SetTo(const Theme& source) {
1534 if (this == &source) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001535 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001536 }
1537
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001538 type_spec_flags_ = source.type_spec_flags_;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001539
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001540 if (asset_manager_ == source.asset_manager_) {
1541 entries_ = source.entries_;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001542 } else {
1543 std::map<ApkAssetsCookie, ApkAssetsCookie> src_to_dest_asset_cookies;
1544 typedef std::map<int, int> SourceToDestinationRuntimePackageMap;
1545 std::map<ApkAssetsCookie, SourceToDestinationRuntimePackageMap> src_asset_cookie_id_map;
1546
Ryan Mitchell93bca972019-03-08 17:26:28 -08001547 // Determine which ApkAssets are loaded in both theme AssetManagers.
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001548 const auto src_assets = source.asset_manager_->GetApkAssets();
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001549 for (size_t i = 0; i < src_assets.size(); i++) {
1550 const ApkAssets* src_asset = src_assets[i];
1551
Ryan Mitchellef538432021-03-01 14:52:14 -08001552 const auto dest_assets = asset_manager_->GetApkAssets();
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001553 for (size_t j = 0; j < dest_assets.size(); j++) {
1554 const ApkAssets* dest_asset = dest_assets[j];
Ryan Mitchellef538432021-03-01 14:52:14 -08001555 if (src_asset != dest_asset) {
1556 // ResourcesManager caches and reuses ApkAssets when the same apk must be present in
1557 // multiple AssetManagers. Two ApkAssets point to the same version of the same resources
1558 // if they are the same instance.
1559 continue;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001560 }
Ryan Mitchellef538432021-03-01 14:52:14 -08001561
1562 // Map the package ids of the asset in the source AssetManager to the package ids of the
1563 // asset in th destination AssetManager.
1564 SourceToDestinationRuntimePackageMap package_map;
1565 for (const auto& loaded_package : src_asset->GetLoadedArsc()->GetPackages()) {
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001566 const int src_package_id = source.asset_manager_->GetAssignedPackageId(
1567 loaded_package.get());
Ryan Mitchellef538432021-03-01 14:52:14 -08001568 const int dest_package_id = asset_manager_->GetAssignedPackageId(loaded_package.get());
1569 package_map[src_package_id] = dest_package_id;
1570 }
1571
1572 src_to_dest_asset_cookies.insert(std::make_pair(i, j));
1573 src_asset_cookie_id_map.insert(std::make_pair(i, package_map));
1574 break;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001575 }
1576 }
1577
Ryan Mitchell93bca972019-03-08 17:26:28 -08001578 // Reset the data in the destination theme.
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001579 entries_.clear();
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001580
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001581 for (const auto& entry : source.entries_) {
1582 bool is_reference = (entry.value.dataType == Res_value::TYPE_ATTRIBUTE
1583 || entry.value.dataType == Res_value::TYPE_REFERENCE
1584 || entry.value.dataType == Res_value::TYPE_DYNAMIC_ATTRIBUTE
1585 || entry.value.dataType == Res_value::TYPE_DYNAMIC_REFERENCE)
1586 && entry.value.data != 0x0;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001587
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001588 // If the attribute value represents an attribute or reference, the package id of the
1589 // value needs to be rewritten to the package id of the value in the destination.
1590 uint32_t attribute_data = entry.value.data;
1591 if (is_reference) {
1592 // Determine the package id of the reference in the destination AssetManager.
1593 auto value_package_map = src_asset_cookie_id_map.find(entry.cookie);
1594 if (value_package_map == src_asset_cookie_id_map.end()) {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001595 continue;
1596 }
1597
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001598 auto value_dest_package = value_package_map->second.find(
1599 get_package_id(entry.value.data));
1600 if (value_dest_package == value_package_map->second.end()) {
1601 continue;
1602 }
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001603
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001604 attribute_data = fix_package_id(entry.value.data, value_dest_package->second);
1605 }
Ryan Mitchellb85d9b22018-11-19 12:11:38 -08001606
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001607 // Find the cookie of the value in the destination. If the source apk is not loaded in the
1608 // destination, only copy resources that do not reference resources in the source.
1609 ApkAssetsCookie data_dest_cookie;
1610 auto value_dest_cookie = src_to_dest_asset_cookies.find(entry.cookie);
1611 if (value_dest_cookie != src_to_dest_asset_cookies.end()) {
1612 data_dest_cookie = value_dest_cookie->second;
1613 } else {
1614 if (is_reference || entry.value.dataType == Res_value::TYPE_STRING) {
1615 continue;
1616 } else {
1617 data_dest_cookie = 0x0;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001618 }
1619 }
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001620
1621 // The package id of the attribute needs to be rewritten to the package id of the
1622 // attribute in the destination.
1623 int attribute_dest_package_id = get_package_id(entry.attr_res_id);
1624 if (attribute_dest_package_id != 0x01) {
1625 // Find the cookie of the attribute resource id in the source AssetManager
1626 base::expected<FindEntryResult, NullOrIOError> attribute_entry_result =
1627 source.asset_manager_->FindEntry(entry.attr_res_id, 0 /* density_override */ ,
1628 true /* stop_at_first_match */,
1629 true /* ignore_configuration */);
1630 if (UNLIKELY(IsIOError(attribute_entry_result))) {
1631 return base::unexpected(GetIOError(attribute_entry_result.error()));
1632 }
1633 if (!attribute_entry_result.has_value()) {
1634 continue;
1635 }
1636
1637 // Determine the package id of the attribute in the destination AssetManager.
1638 auto attribute_package_map = src_asset_cookie_id_map.find(
1639 attribute_entry_result->cookie);
1640 if (attribute_package_map == src_asset_cookie_id_map.end()) {
1641 continue;
1642 }
1643 auto attribute_dest_package = attribute_package_map->second.find(
1644 attribute_dest_package_id);
1645 if (attribute_dest_package == attribute_package_map->second.end()) {
1646 continue;
1647 }
1648 attribute_dest_package_id = attribute_dest_package->second;
1649 }
1650
1651 auto dest_attr_id = make_resid(attribute_dest_package_id, get_type_id(entry.attr_res_id),
1652 get_entry_id(entry.attr_res_id));
1653 Theme::Entry new_entry{dest_attr_id, data_dest_cookie, entry.type_spec_flags,
1654 Res_value{.dataType = entry.value.dataType,
1655 .data = attribute_data}};
1656
1657 // Since the entries were cleared, the attribute resource id has yet been mapped to any value.
1658 auto entry_it = std::lower_bound(entries_.begin(), entries_.end(), dest_attr_id,
1659 ThemeEntryKeyComparer{});
1660 entries_.insert(entry_it, new_entry);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001661 }
1662 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001663 return {};
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001664}
1665
1666void Theme::Dump() const {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001667 LOG(INFO) << base::StringPrintf("Theme(this=%p, AssetManager2=%p)", this, asset_manager_);
Ryan Mitchell3c6480c2021-06-07 11:22:30 -07001668 for (auto& entry : entries_) {
1669 LOG(INFO) << base::StringPrintf(" entry(0x%08x)=(0x%08x) type=(0x%02x), cookie(%d)",
1670 entry.attr_res_id, entry.value.data, entry.value.dataType,
1671 entry.cookie);
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001672 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001673}
1674
1675} // namespace android