blob: 237effeed88999d65f5322e5ec0b2cc69a974841 [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"
Ryan Mitchell8a891d82019-07-01 09:48:23 -070028#include "androidfw/ResourceUtils.h"
Ryan Mitchell31b11052019-06-13 13:47:26 -070029#include "androidfw/Util.h"
Adam Lesinski7ad11102016-10-28 16:39:15 -070030#include "utils/ByteOrder.h"
31#include "utils/Trace.h"
32
33#ifdef _WIN32
34#ifdef ERROR
35#undef ERROR
36#endif
37#endif
38
39namespace android {
40
Ryan Mitchell80094e32020-11-16 23:08:18 +000041namespace {
42
43using EntryValue = std::variant<Res_value, incfs::verified_map_ptr<ResTable_map_entry>>;
44
45base::expected<EntryValue, IOError> GetEntryValue(
46 incfs::verified_map_ptr<ResTable_entry> table_entry) {
47 const uint16_t entry_size = dtohs(table_entry->size);
48
49 // Check if the entry represents a bag value.
50 if (entry_size >= sizeof(ResTable_map_entry) &&
51 (dtohs(table_entry->flags) & ResTable_entry::FLAG_COMPLEX)) {
52 const auto map_entry = table_entry.convert<ResTable_map_entry>();
53 if (!map_entry) {
54 return base::unexpected(IOError::PAGES_MISSING);
55 }
56 return map_entry.verified();
57 }
58
59 // The entry represents a non-bag value.
60 const auto entry_value = table_entry.offset(entry_size).convert<Res_value>();
61 if (!entry_value) {
62 return base::unexpected(IOError::PAGES_MISSING);
63 }
64 Res_value value;
65 value.copyFrom_dtoh(entry_value.value());
66 return value;
67}
68
69} // namespace
70
Adam Lesinskibebfcc42018-02-12 14:27:46 -080071struct FindEntryResult {
Ryan Mitchell80094e32020-11-16 23:08:18 +000072 // The cookie representing the ApkAssets in which the value resides.
73 ApkAssetsCookie cookie;
74
75 // The value of the resource table entry. Either an android::Res_value for non-bag types or an
76 // incfs::verified_map_ptr<ResTable_map_entry> for bag types.
77 EntryValue entry;
Adam Lesinskibebfcc42018-02-12 14:27:46 -080078
79 // The configuration for which the resulting entry was defined. This is already swapped to host
80 // endianness.
81 ResTable_config config;
82
83 // The bitmask of configuration axis with which the resource value varies.
84 uint32_t type_flags;
85
86 // The dynamic package ID map for the package from which this resource came from.
87 const DynamicRefTable* dynamic_ref_table;
88
Ryan Mitchell8a891d82019-07-01 09:48:23 -070089 // The package name of the resource.
90 const std::string* package_name;
91
Adam Lesinskibebfcc42018-02-12 14:27:46 -080092 // The string pool reference to the type's name. This uses a different string pool than
93 // the global string pool, but this is hidden from the caller.
94 StringPoolRef type_string_ref;
95
96 // The string pool reference to the entry's name. This uses a different string pool than
97 // the global string pool, but this is hidden from the caller.
98 StringPoolRef entry_string_ref;
99};
100
Ryan Mitchellb894c272020-02-12 10:31:44 -0800101AssetManager2::AssetManager2() {
Adam Lesinski970bd8d2017-09-25 13:21:55 -0700102 memset(&configuration_, 0, sizeof(configuration_));
103}
Adam Lesinski7ad11102016-10-28 16:39:15 -0700104
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800105bool AssetManager2::SetApkAssets(std::vector<const ApkAssets*> apk_assets, bool invalidate_caches) {
106 apk_assets_ = std::move(apk_assets);
Adam Lesinskida431a22016-12-29 16:08:16 -0500107 BuildDynamicRefTable();
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800108 RebuildFilterList();
Adam Lesinski7ad11102016-10-28 16:39:15 -0700109 if (invalidate_caches) {
110 InvalidateCaches(static_cast<uint32_t>(-1));
111 }
112 return true;
113}
114
Adam Lesinskida431a22016-12-29 16:08:16 -0500115void AssetManager2::BuildDynamicRefTable() {
116 package_groups_.clear();
117 package_ids_.fill(0xff);
118
Ryan Mitchellef538432021-03-01 14:52:14 -0800119 // A mapping from path of apk assets that could be target packages of overlays to the runtime
120 // package id of its first loaded package. Overlays currently can only override resources in the
121 // first package in the target resource table.
122 std::unordered_map<std::string, uint8_t> target_assets_package_ids;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700123
Ryan Mitchell824cc492020-02-12 10:48:14 -0800124 // Overlay resources are not directly referenced by an application so their resource ids
125 // can change throughout the application's lifetime. Assign overlay package ids last.
126 std::vector<const ApkAssets*> sorted_apk_assets(apk_assets_);
127 std::stable_partition(sorted_apk_assets.begin(), sorted_apk_assets.end(), [](const ApkAssets* a) {
128 return !a->IsOverlay();
129 });
130
131 // The assets cookie must map to the position of the apk assets in the unsorted apk assets list.
132 std::unordered_map<const ApkAssets*, ApkAssetsCookie> apk_assets_cookies;
133 apk_assets_cookies.reserve(apk_assets_.size());
134 for (size_t i = 0, n = apk_assets_.size(); i < n; i++) {
135 apk_assets_cookies[apk_assets_[i]] = static_cast<ApkAssetsCookie>(i);
136 }
137
Ryan Mitchellb894c272020-02-12 10:31:44 -0800138 // 0x01 is reserved for the android package.
139 int next_package_id = 0x02;
Ryan Mitchell824cc492020-02-12 10:48:14 -0800140 for (const ApkAssets* apk_assets : sorted_apk_assets) {
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800141 std::shared_ptr<OverlayDynamicRefTable> overlay_ref_table;
142 if (auto loaded_idmap = apk_assets->GetLoadedIdmap(); loaded_idmap != nullptr) {
143 // The target package must precede the overlay package in the apk assets paths in order
144 // to take effect.
Ryan Mitchellef538432021-03-01 14:52:14 -0800145 auto iter = target_assets_package_ids.find(std::string(loaded_idmap->TargetApkPath()));
146 if (iter == target_assets_package_ids.end()) {
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800147 LOG(INFO) << "failed to find target package for overlay "
148 << loaded_idmap->OverlayApkPath();
149 } else {
150 uint8_t target_package_id = iter->second;
151
152 // Create a special dynamic reference table for the overlay to rewrite references to
153 // overlay resources as references to the target resources they overlay.
154 overlay_ref_table = std::make_shared<OverlayDynamicRefTable>(
155 loaded_idmap->GetOverlayDynamicRefTable(target_package_id));
156
157 // Add the overlay resource map to the target package's set of overlays.
158 const uint8_t target_idx = package_ids_[target_package_id];
159 CHECK(target_idx != 0xff) << "overlay target '" << loaded_idmap->TargetApkPath()
160 << "'added to apk_assets_package_ids but does not have an"
161 << " assigned package group";
162
163 PackageGroup& target_package_group = package_groups_[target_idx];
164 target_package_group.overlays_.push_back(
165 ConfiguredOverlay{loaded_idmap->GetTargetResourcesMap(target_package_id,
166 overlay_ref_table.get()),
167 apk_assets_cookies[apk_assets]});
168 }
169 }
170
Ryan Mitchellb894c272020-02-12 10:31:44 -0800171 const LoadedArsc* loaded_arsc = apk_assets->GetLoadedArsc();
Ryan Mitchellb894c272020-02-12 10:31:44 -0800172 for (const std::unique_ptr<const LoadedPackage>& package : loaded_arsc->GetPackages()) {
173 // Get the package ID or assign one if a shared library.
174 int package_id;
175 if (package->IsDynamic()) {
176 package_id = next_package_id++;
177 } else {
178 package_id = package->GetPackageId();
Adam Lesinskida431a22016-12-29 16:08:16 -0500179 }
180
Adam Lesinskida431a22016-12-29 16:08:16 -0500181 uint8_t idx = package_ids_[package_id];
182 if (idx == 0xff) {
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800183 // Add the mapping for package ID to index if not present.
Adam Lesinskida431a22016-12-29 16:08:16 -0500184 package_ids_[package_id] = idx = static_cast<uint8_t>(package_groups_.size());
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800185 PackageGroup& new_group = package_groups_.emplace_back();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700186
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800187 if (overlay_ref_table != nullptr) {
188 // If this package is from an overlay, use a dynamic reference table that can rewrite
189 // overlay resource ids to their corresponding target resource ids.
190 new_group.dynamic_ref_table = overlay_ref_table;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700191 }
192
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800193 DynamicRefTable* ref_table = new_group.dynamic_ref_table.get();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700194 ref_table->mAssignedPackageId = package_id;
195 ref_table->mAppAsLib = package->IsDynamic() && package->GetPackageId() == 0x7f;
Adam Lesinskida431a22016-12-29 16:08:16 -0500196 }
Adam Lesinskida431a22016-12-29 16:08:16 -0500197
198 // Add the package and to the set of packages with the same ID.
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800199 PackageGroup* package_group = &package_groups_[idx];
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800200 package_group->packages_.push_back(ConfiguredPackage{package.get(), {}});
Ryan Mitchell824cc492020-02-12 10:48:14 -0800201 package_group->cookies_.push_back(apk_assets_cookies[apk_assets]);
Adam Lesinskida431a22016-12-29 16:08:16 -0500202
203 // Add the package name -> build time ID mappings.
204 for (const DynamicPackageEntry& entry : package->GetDynamicPackageMap()) {
205 String16 package_name(entry.package_name.c_str(), entry.package_name.size());
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700206 package_group->dynamic_ref_table->mEntries.replaceValueFor(
Adam Lesinskida431a22016-12-29 16:08:16 -0500207 package_name, static_cast<uint8_t>(entry.package_id));
208 }
Ryan Mitchellb894c272020-02-12 10:31:44 -0800209
Ryan Mitchellef538432021-03-01 14:52:14 -0800210 if (auto apk_assets_path = apk_assets->GetPath()) {
211 // Overlay target ApkAssets must have been created using path based load apis.
212 target_assets_package_ids.insert(std::make_pair(std::string(*apk_assets_path), package_id));
213 }
Adam Lesinskida431a22016-12-29 16:08:16 -0500214 }
215 }
216
217 // Now assign the runtime IDs so that we have a build-time to runtime ID map.
218 const auto package_groups_end = package_groups_.end();
219 for (auto iter = package_groups_.begin(); iter != package_groups_end; ++iter) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800220 const std::string& package_name = iter->packages_[0].loaded_package_->GetPackageName();
Adam Lesinskida431a22016-12-29 16:08:16 -0500221 for (auto iter2 = package_groups_.begin(); iter2 != package_groups_end; ++iter2) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700222 iter2->dynamic_ref_table->addMapping(String16(package_name.c_str(), package_name.size()),
223 iter->dynamic_ref_table->mAssignedPackageId);
Adam Lesinskida431a22016-12-29 16:08:16 -0500224 }
225 }
226}
227
228void AssetManager2::DumpToLog() const {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800229 LOG(INFO) << base::StringPrintf("AssetManager2(this=%p)", this);
230
Adam Lesinskida431a22016-12-29 16:08:16 -0500231 std::string list;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800232 for (const auto& apk_assets : apk_assets_) {
Ryan Mitchellef538432021-03-01 14:52:14 -0800233 base::StringAppendF(&list, "%s,", apk_assets->GetDebugName().c_str());
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800234 }
235 LOG(INFO) << "ApkAssets: " << list;
236
237 list = "";
Adam Lesinskida431a22016-12-29 16:08:16 -0500238 for (size_t i = 0; i < package_ids_.size(); i++) {
239 if (package_ids_[i] != 0xff) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800240 base::StringAppendF(&list, "%02x -> %d, ", (int)i, package_ids_[i]);
Adam Lesinskida431a22016-12-29 16:08:16 -0500241 }
242 }
243 LOG(INFO) << "Package ID map: " << list;
244
Adam Lesinski0dd36992018-01-25 15:38:38 -0800245 for (const auto& package_group: package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800246 list = "";
247 for (const auto& package : package_group.packages_) {
248 const LoadedPackage* loaded_package = package.loaded_package_;
249 base::StringAppendF(&list, "%s(%02x%s), ", loaded_package->GetPackageName().c_str(),
250 loaded_package->GetPackageId(),
251 (loaded_package->IsDynamic() ? " dynamic" : ""));
252 }
253 LOG(INFO) << base::StringPrintf("PG (%02x): ",
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700254 package_group.dynamic_ref_table->mAssignedPackageId)
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800255 << list;
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800256
257 for (size_t i = 0; i < 256; i++) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700258 if (package_group.dynamic_ref_table->mLookupTable[i] != 0) {
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800259 LOG(INFO) << base::StringPrintf(" e[0x%02x] -> 0x%02x", (uint8_t) i,
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700260 package_group.dynamic_ref_table->mLookupTable[i]);
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800261 }
262 }
Adam Lesinskida431a22016-12-29 16:08:16 -0500263 }
264}
Adam Lesinski7ad11102016-10-28 16:39:15 -0700265
266const ResStringPool* AssetManager2::GetStringPoolForCookie(ApkAssetsCookie cookie) const {
267 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
268 return nullptr;
269 }
270 return apk_assets_[cookie]->GetLoadedArsc()->GetStringPool();
271}
272
Adam Lesinskida431a22016-12-29 16:08:16 -0500273const DynamicRefTable* AssetManager2::GetDynamicRefTableForPackage(uint32_t package_id) const {
274 if (package_id >= package_ids_.size()) {
275 return nullptr;
276 }
277
278 const size_t idx = package_ids_[package_id];
279 if (idx == 0xff) {
280 return nullptr;
281 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700282 return package_groups_[idx].dynamic_ref_table.get();
Adam Lesinskida431a22016-12-29 16:08:16 -0500283}
284
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700285std::shared_ptr<const DynamicRefTable> AssetManager2::GetDynamicRefTableForCookie(
286 ApkAssetsCookie cookie) const {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800287 for (const PackageGroup& package_group : package_groups_) {
288 for (const ApkAssetsCookie& package_cookie : package_group.cookies_) {
289 if (package_cookie == cookie) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700290 return package_group.dynamic_ref_table;
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800291 }
292 }
293 }
294 return nullptr;
295}
296
MÃ¥rten Kongstadc92c4dd2019-02-05 01:29:59 +0100297const std::unordered_map<std::string, std::string>*
298 AssetManager2::GetOverlayableMapForPackage(uint32_t package_id) const {
299
300 if (package_id >= package_ids_.size()) {
301 return nullptr;
302 }
303
304 const size_t idx = package_ids_[package_id];
305 if (idx == 0xff) {
306 return nullptr;
307 }
308
309 const PackageGroup& package_group = package_groups_[idx];
Ryan Mitchell80094e32020-11-16 23:08:18 +0000310 if (package_group.packages_.empty()) {
MÃ¥rten Kongstadc92c4dd2019-02-05 01:29:59 +0100311 return nullptr;
312 }
313
314 const auto loaded_package = package_group.packages_[0].loaded_package_;
315 return &loaded_package->GetOverlayableMap();
316}
317
Ryan Mitchell2e394222019-08-28 12:10:51 -0700318bool AssetManager2::GetOverlayablesToString(const android::StringPiece& package_name,
319 std::string* out) const {
320 uint8_t package_id = 0U;
321 for (const auto& apk_assets : apk_assets_) {
322 const LoadedArsc* loaded_arsc = apk_assets->GetLoadedArsc();
323 if (loaded_arsc == nullptr) {
324 continue;
325 }
326
327 const auto& loaded_packages = loaded_arsc->GetPackages();
328 if (loaded_packages.empty()) {
329 continue;
330 }
331
332 const auto& loaded_package = loaded_packages[0];
333 if (loaded_package->GetPackageName() == package_name) {
334 package_id = GetAssignedPackageId(loaded_package.get());
335 break;
336 }
337 }
338
339 if (package_id == 0U) {
340 ANDROID_LOG(ERROR) << base::StringPrintf("No package with name '%s", package_name.data());
341 return false;
342 }
343
344 const size_t idx = package_ids_[package_id];
345 if (idx == 0xff) {
346 return false;
347 }
348
349 std::string output;
350 for (const ConfiguredPackage& package : package_groups_[idx].packages_) {
351 const LoadedPackage* loaded_package = package.loaded_package_;
352 for (auto it = loaded_package->begin(); it != loaded_package->end(); it++) {
353 const OverlayableInfo* info = loaded_package->GetOverlayableInfo(*it);
354 if (info != nullptr) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000355 auto res_name = GetResourceName(*it);
356 if (!res_name.has_value()) {
Ryan Mitchell2e394222019-08-28 12:10:51 -0700357 ANDROID_LOG(ERROR) << base::StringPrintf(
358 "Unable to retrieve name of overlayable resource 0x%08x", *it);
359 return false;
360 }
361
Ryan Mitchell80094e32020-11-16 23:08:18 +0000362 const std::string name = ToFormattedResourceString(*res_name);
Ryan Mitchell2e394222019-08-28 12:10:51 -0700363 output.append(base::StringPrintf(
364 "resource='%s' overlayable='%s' actor='%s' policy='0x%08x'\n",
365 name.c_str(), info->name.c_str(), info->actor.c_str(), info->policy_flags));
366 }
367 }
368 }
369
370 *out = std::move(output);
371 return true;
372}
373
Ryan Mitchell192400c2020-04-02 09:54:23 -0700374bool AssetManager2::ContainsAllocatedTable() const {
375 return std::find_if(apk_assets_.begin(), apk_assets_.end(),
376 std::mem_fn(&ApkAssets::IsTableAllocated)) != apk_assets_.end();
377}
378
Adam Lesinski7ad11102016-10-28 16:39:15 -0700379void AssetManager2::SetConfiguration(const ResTable_config& configuration) {
380 const int diff = configuration_.diff(configuration);
381 configuration_ = configuration;
382
383 if (diff) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800384 RebuildFilterList();
Adam Lesinski7ad11102016-10-28 16:39:15 -0700385 InvalidateCaches(static_cast<uint32_t>(diff));
386 }
387}
388
Ryan Mitchellef538432021-03-01 14:52:14 -0800389std::set<const ApkAssets*> AssetManager2::GetNonSystemOverlays() const {
390 std::set<const ApkAssets*> non_system_overlays;
Adam Lesinski0c405242017-01-13 20:47:26 -0800391 for (const PackageGroup& package_group : package_groups_) {
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800392 bool found_system_package = false;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800393 for (const ConfiguredPackage& package : package_group.packages_) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700394 if (package.loaded_package_->IsSystem()) {
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800395 found_system_package = true;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700396 break;
397 }
398 }
399
400 if (!found_system_package) {
401 for (const ConfiguredOverlay& overlay : package_group.overlays_) {
Ryan Mitchellef538432021-03-01 14:52:14 -0800402 non_system_overlays.insert(apk_assets_[overlay.cookie]);
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700403 }
404 }
405 }
406
407 return non_system_overlays;
408}
409
Ryan Mitchell80094e32020-11-16 23:08:18 +0000410base::expected<std::set<ResTable_config>, IOError> AssetManager2::GetResourceConfigurations(
411 bool exclude_system, bool exclude_mipmap) const {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700412 ATRACE_NAME("AssetManager::GetResourceConfigurations");
413 const auto non_system_overlays =
Ryan Mitchellef538432021-03-01 14:52:14 -0800414 (exclude_system) ? GetNonSystemOverlays() : std::set<const ApkAssets*>();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700415
416 std::set<ResTable_config> configurations;
417 for (const PackageGroup& package_group : package_groups_) {
418 for (size_t i = 0; i < package_group.packages_.size(); i++) {
419 const ConfiguredPackage& package = package_group.packages_[i];
420 if (exclude_system && package.loaded_package_->IsSystem()) {
Adam Lesinski0c405242017-01-13 20:47:26 -0800421 continue;
422 }
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800423
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700424 auto apk_assets = apk_assets_[package_group.cookies_[i]];
Ryan Mitchellef538432021-03-01 14:52:14 -0800425 if (exclude_system && apk_assets->IsOverlay() &&
426 non_system_overlays.find(apk_assets) == non_system_overlays.end()) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700427 // Exclude overlays that target system resources.
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800428 continue;
429 }
430
Ryan Mitchell80094e32020-11-16 23:08:18 +0000431 auto result = package.loaded_package_->CollectConfigurations(exclude_mipmap, &configurations);
432 if (UNLIKELY(!result.has_value())) {
433 return base::unexpected(result.error());
434 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800435 }
436 }
437 return configurations;
438}
439
440std::set<std::string> AssetManager2::GetResourceLocales(bool exclude_system,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800441 bool merge_equivalent_languages) const {
442 ATRACE_NAME("AssetManager::GetResourceLocales");
Adam Lesinski0c405242017-01-13 20:47:26 -0800443 std::set<std::string> locales;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700444 const auto non_system_overlays =
Ryan Mitchellef538432021-03-01 14:52:14 -0800445 (exclude_system) ? GetNonSystemOverlays() : std::set<const ApkAssets*>();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700446
Adam Lesinski0c405242017-01-13 20:47:26 -0800447 for (const PackageGroup& package_group : package_groups_) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700448 for (size_t i = 0; i < package_group.packages_.size(); i++) {
449 const ConfiguredPackage& package = package_group.packages_[i];
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800450 if (exclude_system && package.loaded_package_->IsSystem()) {
Adam Lesinski0c405242017-01-13 20:47:26 -0800451 continue;
452 }
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800453
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700454 auto apk_assets = apk_assets_[package_group.cookies_[i]];
Ryan Mitchellef538432021-03-01 14:52:14 -0800455 if (exclude_system && apk_assets->IsOverlay() &&
456 non_system_overlays.find(apk_assets) == non_system_overlays.end()) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700457 // Exclude overlays that target system resources.
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800458 continue;
459 }
460
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800461 package.loaded_package_->CollectLocales(merge_equivalent_languages, &locales);
Adam Lesinski0c405242017-01-13 20:47:26 -0800462 }
463 }
464 return locales;
465}
466
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800467std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename,
468 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700469 const std::string new_path = "assets/" + filename;
470 return OpenNonAsset(new_path, mode);
471}
472
473std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename, ApkAssetsCookie cookie,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800474 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700475 const std::string new_path = "assets/" + filename;
476 return OpenNonAsset(new_path, cookie, mode);
477}
478
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800479std::unique_ptr<AssetDir> AssetManager2::OpenDir(const std::string& dirname) const {
480 ATRACE_NAME("AssetManager::OpenDir");
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800481
482 std::string full_path = "assets/" + dirname;
483 std::unique_ptr<SortedVector<AssetDir::FileInfo>> files =
484 util::make_unique<SortedVector<AssetDir::FileInfo>>();
485
486 // Start from the back.
487 for (auto iter = apk_assets_.rbegin(); iter != apk_assets_.rend(); ++iter) {
488 const ApkAssets* apk_assets = *iter;
MÃ¥rten Kongstaddbf343b2019-02-21 07:54:18 +0100489 if (apk_assets->IsOverlay()) {
490 continue;
491 }
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800492
493 auto func = [&](const StringPiece& name, FileType type) {
494 AssetDir::FileInfo info;
495 info.setFileName(String8(name.data(), name.size()));
496 info.setFileType(type);
Ryan Mitchellef538432021-03-01 14:52:14 -0800497 info.setSourceName(String8(apk_assets->GetDebugName().c_str()));
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800498 files->add(info);
499 };
500
Ryan Mitchellc07aa702020-03-10 13:49:12 -0700501 if (!apk_assets->GetAssetsProvider()->ForEachFile(full_path, func)) {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800502 return {};
503 }
504 }
505
506 std::unique_ptr<AssetDir> asset_dir = util::make_unique<AssetDir>();
507 asset_dir->setFileList(files.release());
508 return asset_dir;
509}
510
Adam Lesinski7ad11102016-10-28 16:39:15 -0700511// Search in reverse because that's how we used to do it and we need to preserve behaviour.
512// This is unfortunate, because ClassLoaders delegate to the parent first, so the order
513// is inconsistent for split APKs.
514std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
515 Asset::AccessMode mode,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800516 ApkAssetsCookie* out_cookie) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700517 for (int32_t i = apk_assets_.size() - 1; i >= 0; i--) {
MÃ¥rten Kongstaddbf343b2019-02-21 07:54:18 +0100518 // Prevent RRO from modifying assets and other entries accessed by file
519 // path. Explicitly asking for a path in a given package (denoted by a
520 // cookie) is still OK.
521 if (apk_assets_[i]->IsOverlay()) {
522 continue;
523 }
524
Ryan Mitchellc07aa702020-03-10 13:49:12 -0700525 std::unique_ptr<Asset> asset = apk_assets_[i]->GetAssetsProvider()->Open(filename, mode);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700526 if (asset) {
527 if (out_cookie != nullptr) {
528 *out_cookie = i;
529 }
530 return asset;
531 }
532 }
533
534 if (out_cookie != nullptr) {
535 *out_cookie = kInvalidCookie;
536 }
537 return {};
538}
539
540std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800541 ApkAssetsCookie cookie,
542 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700543 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
544 return {};
545 }
Ryan Mitchellc07aa702020-03-10 13:49:12 -0700546 return apk_assets_[cookie]->GetAssetsProvider()->Open(filename, mode);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700547}
548
Ryan Mitchell80094e32020-11-16 23:08:18 +0000549base::expected<FindEntryResult, NullOrIOError> AssetManager2::FindEntry(
550 uint32_t resid, uint16_t density_override, bool stop_at_first_match,
551 bool ignore_configuration) const {
552 const bool logging_enabled = resource_resolution_logging_enabled_;
553 if (UNLIKELY(logging_enabled)) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700554 // Clear the last logged resource resolution.
555 ResetResourceResolution();
556 last_resolution_.resid = resid;
557 }
558
Adam Lesinski7ad11102016-10-28 16:39:15 -0700559 // Might use this if density_override != 0.
560 ResTable_config density_override_config;
561
562 // Select our configuration or generate a density override configuration.
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800563 const ResTable_config* desired_config = &configuration_;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700564 if (density_override != 0 && density_override != configuration_.density) {
565 density_override_config = configuration_;
566 density_override_config.density = density_override;
567 desired_config = &density_override_config;
568 }
569
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700570 // Retrieve the package group from the package id of the resource id.
Ryan Mitchell80094e32020-11-16 23:08:18 +0000571 if (UNLIKELY(!is_valid_resid(resid))) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500572 LOG(ERROR) << base::StringPrintf("Invalid ID 0x%08x.", resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000573 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -0500574 }
575
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800576 const uint32_t package_id = get_package_id(resid);
577 const uint8_t type_idx = get_type_id(resid) - 1;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800578 const uint16_t entry_idx = get_entry_id(resid);
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700579 uint8_t package_idx = package_ids_[package_id];
Ryan Mitchell80094e32020-11-16 23:08:18 +0000580 if (UNLIKELY(package_idx == 0xff)) {
Ryan Mitchell2fe23472019-02-27 09:43:01 -0800581 ANDROID_LOG(ERROR) << base::StringPrintf("No package ID %02x found for ID 0x%08x.",
582 package_id, resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000583 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -0500584 }
585
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800586 const PackageGroup& package_group = package_groups_[package_idx];
Ryan Mitchell80094e32020-11-16 23:08:18 +0000587 auto result = FindEntryInternal(package_group, type_idx, entry_idx, *desired_config,
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800588 stop_at_first_match, ignore_configuration);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000589 if (UNLIKELY(!result.has_value())) {
590 return base::unexpected(result.error());
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700591 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800592
Ryan Mitchell80094e32020-11-16 23:08:18 +0000593 if (!stop_at_first_match && !ignore_configuration && !apk_assets_[result->cookie]->IsLoader()) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700594 for (const auto& id_map : package_group.overlays_) {
595 auto overlay_entry = id_map.overlay_res_maps_.Lookup(resid);
596 if (!overlay_entry) {
597 // No id map entry exists for this target resource.
598 continue;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000599 }
600 if (overlay_entry.IsInlineValue()) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700601 // The target resource is overlaid by an inline value not represented by a resource.
Ryan Mitchell80094e32020-11-16 23:08:18 +0000602 result->entry = overlay_entry.GetInlineValue();
603 result->dynamic_ref_table = id_map.overlay_res_maps_.GetOverlayDynamicRefTable();
604 result->cookie = id_map.cookie;
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800605
606 if (UNLIKELY(logging_enabled)) {
607 last_resolution_.steps.push_back(
608 Resolution::Step{Resolution::Step::Type::OVERLAID_INLINE, String8(), result->cookie});
609 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700610 continue;
611 }
612
Ryan Mitchell80094e32020-11-16 23:08:18 +0000613 auto overlay_result = FindEntry(overlay_entry.GetResourceId(), density_override,
614 false /* stop_at_first_match */,
615 false /* ignore_configuration */);
616 if (UNLIKELY(IsIOError(overlay_result))) {
617 return base::unexpected(overlay_result.error());
618 }
619 if (!overlay_result.has_value()) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700620 continue;
621 }
622
Ryan Mitchell80094e32020-11-16 23:08:18 +0000623 if (!overlay_result->config.isBetterThan(result->config, desired_config)
624 && overlay_result->config.compare(result->config) != 0) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700625 // The configuration of the entry for the overlay must be equal to or better than the target
626 // configuration to be chosen as the better value.
627 continue;
628 }
629
Ryan Mitchell80094e32020-11-16 23:08:18 +0000630 result->cookie = overlay_result->cookie;
631 result->entry = overlay_result->entry;
632 result->config = overlay_result->config;
633 result->dynamic_ref_table = id_map.overlay_res_maps_.GetOverlayDynamicRefTable();
634
635 if (UNLIKELY(logging_enabled)) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700636 last_resolution_.steps.push_back(
Ryan Mitchell80094e32020-11-16 23:08:18 +0000637 Resolution::Step{Resolution::Step::Type::OVERLAID, overlay_result->config.toString(),
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800638 overlay_result->cookie});
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700639 }
640 }
641 }
642
Ryan Mitchell80094e32020-11-16 23:08:18 +0000643 if (UNLIKELY(logging_enabled)) {
644 last_resolution_.cookie = result->cookie;
645 last_resolution_.type_string_ref = result->type_string_ref;
646 last_resolution_.entry_string_ref = result->entry_string_ref;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700647 }
648
Ryan Mitchell80094e32020-11-16 23:08:18 +0000649 return result;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700650}
651
Ryan Mitchell80094e32020-11-16 23:08:18 +0000652base::expected<FindEntryResult, NullOrIOError> AssetManager2::FindEntryInternal(
653 const PackageGroup& package_group, uint8_t type_idx, uint16_t entry_idx,
654 const ResTable_config& desired_config, bool stop_at_first_match,
655 bool ignore_configuration) const {
656 const bool logging_enabled = resource_resolution_logging_enabled_;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800657 ApkAssetsCookie best_cookie = kInvalidCookie;
658 const LoadedPackage* best_package = nullptr;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000659 incfs::verified_map_ptr<ResTable_type> best_type;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800660 const ResTable_config* best_config = nullptr;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000661 uint32_t best_offset = 0U;
662 uint32_t type_flags = 0U;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800663
Winson2f3669b2019-01-11 11:28:34 -0800664 std::vector<Resolution::Step> resolution_steps;
665
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800666 // If `desired_config` is not the same as the set configuration or the caller will accept a value
667 // from any configuration, then we cannot use our filtered list of types since it only it contains
668 // types matched to the set configuration.
669 const bool use_filtered = !ignore_configuration && &desired_config == &configuration_;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800670
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700671 const size_t package_count = package_group.packages_.size();
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800672 for (size_t pi = 0; pi < package_count; pi++) {
673 const ConfiguredPackage& loaded_package_impl = package_group.packages_[pi];
674 const LoadedPackage* loaded_package = loaded_package_impl.loaded_package_;
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800675 const ApkAssetsCookie cookie = package_group.cookies_[pi];
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800676
677 // If the type IDs are offset in this package, we need to take that into account when searching
678 // for a type.
679 const TypeSpec* type_spec = loaded_package->GetTypeSpecByTypeIndex(type_idx);
680 if (UNLIKELY(type_spec == nullptr)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700681 continue;
682 }
683
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800684 // Allow custom loader packages to overlay resource values with configurations equivalent to the
685 // current best configuration.
686 const bool package_is_loader = loaded_package->IsCustomLoader();
687
Ryan Mitchell80094e32020-11-16 23:08:18 +0000688 auto entry_flags = type_spec->GetFlagsForEntryIndex(entry_idx);
Bernie Innocenti58cf8e32020-12-19 15:31:52 +0900689 if (UNLIKELY(!entry_flags.has_value())) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000690 return base::unexpected(entry_flags.error());
691 }
692 type_flags |= entry_flags.value();
693
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800694 const FilteredConfigGroup& filtered_group = loaded_package_impl.filtered_configs_[type_idx];
695 const size_t type_entry_count = (use_filtered) ? filtered_group.type_entries.size()
696 : type_spec->type_entries.size();
697 for (size_t i = 0; i < type_entry_count; i++) {
698 const TypeSpec::TypeEntry* type_entry = (use_filtered) ? filtered_group.type_entries[i]
699 : &type_spec->type_entries[i];
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800700
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800701 // We can skip calling ResTable_config::match() if the caller does not care for the
702 // configuration to match or if we're using the list of types that have already had their
703 // configuration matched.
704 const ResTable_config& this_config = type_entry->config;
705 if (!(use_filtered || ignore_configuration || this_config.match(desired_config))) {
706 continue;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800707 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800708
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800709 Resolution::Step::Type resolution_type;
710 if (best_config == nullptr) {
711 resolution_type = Resolution::Step::Type::INITIAL;
712 } else if (this_config.isBetterThan(*best_config, &desired_config)) {
713 resolution_type = Resolution::Step::Type::BETTER_MATCH;
714 } else if (package_is_loader && this_config.compare(*best_config) == 0) {
715 resolution_type = Resolution::Step::Type::OVERLAID;
716 } else {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000717 if (UNLIKELY(logging_enabled)) {
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800718 resolution_steps.push_back(Resolution::Step{Resolution::Step::Type::SKIPPED,
719 this_config.toString(),
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800720 cookie});
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800721 }
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800722 continue;
723 }
724
725 // The configuration matches and is better than the previous selection.
726 // Find the entry value if it exists for this configuration.
727 const auto& type = type_entry->type;
728 const auto offset = LoadedPackage::GetEntryOffset(type, entry_idx);
729 if (UNLIKELY(IsIOError(offset))) {
730 return base::unexpected(offset.error());
731 }
732
733 if (!offset.has_value()) {
734 if (UNLIKELY(logging_enabled)) {
735 resolution_steps.push_back(Resolution::Step{Resolution::Step::Type::NO_ENTRY,
736 this_config.toString(),
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800737 cookie});
738 }
739 continue;
740 }
741
742 best_cookie = cookie;
743 best_package = loaded_package;
744 best_type = type;
745 best_config = &this_config;
746 best_offset = offset.value();
747
748 if (UNLIKELY(logging_enabled)) {
749 last_resolution_.steps.push_back(Resolution::Step{resolution_type,
750 this_config.toString(),
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800751 cookie});
752 }
753
754 // Any configuration will suffice, so break.
755 if (stop_at_first_match) {
756 break;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700757 }
758 }
759 }
760
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800761 if (UNLIKELY(best_cookie == kInvalidCookie)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000762 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700763 }
764
Ryan Mitchell80094e32020-11-16 23:08:18 +0000765 auto best_entry_result = LoadedPackage::GetEntryFromOffset(best_type, best_offset);
766 if (!best_entry_result.has_value()) {
767 return base::unexpected(best_entry_result.error());
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800768 }
769
Ryan Mitchell80094e32020-11-16 23:08:18 +0000770 const incfs::map_ptr<ResTable_entry> best_entry = *best_entry_result;
771 if (!best_entry) {
772 return base::unexpected(IOError::PAGES_MISSING);
Ryan Mitchellbf1f45b2020-09-29 17:22:52 -0700773 }
774
Ryan Mitchell80094e32020-11-16 23:08:18 +0000775 const auto entry = GetEntryValue(best_entry.verified());
776 if (!entry.has_value()) {
777 return base::unexpected(entry.error());
778 }
Winson2f3669b2019-01-11 11:28:34 -0800779
Ryan Mitchell80094e32020-11-16 23:08:18 +0000780 return FindEntryResult{
781 .cookie = best_cookie,
782 .entry = *entry,
783 .config = *best_config,
784 .type_flags = type_flags,
785 .package_name = &best_package->GetPackageName(),
786 .type_string_ref = StringPoolRef(best_package->GetTypeStringPool(), best_type->id - 1),
787 .entry_string_ref = StringPoolRef(best_package->GetKeyStringPool(),
788 best_entry->key.index),
789 .dynamic_ref_table = package_group.dynamic_ref_table.get(),
790 };
Adam Lesinski7ad11102016-10-28 16:39:15 -0700791}
792
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700793void AssetManager2::ResetResourceResolution() const {
794 last_resolution_.cookie = kInvalidCookie;
795 last_resolution_.resid = 0;
796 last_resolution_.steps.clear();
797 last_resolution_.type_string_ref = StringPoolRef();
798 last_resolution_.entry_string_ref = StringPoolRef();
799}
800
Winson2f3669b2019-01-11 11:28:34 -0800801void AssetManager2::SetResourceResolutionLoggingEnabled(bool enabled) {
802 resource_resolution_logging_enabled_ = enabled;
Winson2f3669b2019-01-11 11:28:34 -0800803 if (!enabled) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700804 ResetResourceResolution();
Winson2f3669b2019-01-11 11:28:34 -0800805 }
806}
807
808std::string AssetManager2::GetLastResourceResolution() const {
809 if (!resource_resolution_logging_enabled_) {
810 LOG(ERROR) << "Must enable resource resolution logging before getting path.";
Ryan Mitchell80094e32020-11-16 23:08:18 +0000811 return {};
Winson2f3669b2019-01-11 11:28:34 -0800812 }
813
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800814 const ApkAssetsCookie cookie = last_resolution_.cookie;
Winson2f3669b2019-01-11 11:28:34 -0800815 if (cookie == kInvalidCookie) {
816 LOG(ERROR) << "AssetManager hasn't resolved a resource to read resolution path.";
Ryan Mitchell80094e32020-11-16 23:08:18 +0000817 return {};
Winson2f3669b2019-01-11 11:28:34 -0800818 }
819
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800820 const uint32_t resid = last_resolution_.resid;
821 const auto package = apk_assets_[cookie]->GetLoadedArsc()->GetPackageById(get_package_id(resid));
822
Winson2f3669b2019-01-11 11:28:34 -0800823 std::string resource_name_string;
Winson2f3669b2019-01-11 11:28:34 -0800824 if (package != nullptr) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000825 auto resource_name = ToResourceName(last_resolution_.type_string_ref,
826 last_resolution_.entry_string_ref,
827 package->GetPackageName());
828 resource_name_string = resource_name.has_value() ?
829 ToFormattedResourceString(resource_name.value()) : "<unknown>";
Winson2f3669b2019-01-11 11:28:34 -0800830 }
831
832 std::stringstream log_stream;
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800833 log_stream << base::StringPrintf("Resolution for 0x%08x %s\n"
834 "\tFor config - %s", resid, resource_name_string.c_str(),
835 configuration_.toString().c_str());
Winson2f3669b2019-01-11 11:28:34 -0800836
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800837 for (const Resolution::Step& step : last_resolution_.steps) {
838 const static std::unordered_map<Resolution::Step::Type, const char*> kStepStrings = {
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800839 {Resolution::Step::Type::INITIAL, "Found initial"},
840 {Resolution::Step::Type::BETTER_MATCH, "Found better"},
841 {Resolution::Step::Type::OVERLAID, "Overlaid"},
842 {Resolution::Step::Type::OVERLAID_INLINE, "Overlaid inline"},
843 {Resolution::Step::Type::SKIPPED, "Skipped"},
844 {Resolution::Step::Type::NO_ENTRY, "No entry"}
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800845 };
846
847 const auto prefix = kStepStrings.find(step.type);
848 if (prefix == kStepStrings.end()) {
849 continue;
Winson2f3669b2019-01-11 11:28:34 -0800850 }
851
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800852 log_stream << "\n\t" << prefix->second << ": " << apk_assets_[step.cookie]->GetDebugName();
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800853 if (!step.config_name.isEmpty()) {
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800854 log_stream << " - " << step.config_name;
Winson2f3669b2019-01-11 11:28:34 -0800855 }
856 }
857
858 return log_stream.str();
859}
860
Ryan Mitchell80094e32020-11-16 23:08:18 +0000861base::expected<AssetManager2::ResourceName, NullOrIOError> AssetManager2::GetResourceName(
862 uint32_t resid) const {
863 auto result = FindEntry(resid, 0u /* density_override */, true /* stop_at_first_match */,
864 true /* ignore_configuration */);
865 if (!result.has_value()) {
866 return base::unexpected(result.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -0700867 }
868
Ryan Mitchell80094e32020-11-16 23:08:18 +0000869 return ToResourceName(result->type_string_ref,
870 result->entry_string_ref,
871 *result->package_name);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700872}
873
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800874base::expected<uint32_t, NullOrIOError> AssetManager2::GetResourceTypeSpecFlags(
875 uint32_t resid) const {
876 auto result = FindEntry(resid, 0u /* density_override */, false /* stop_at_first_match */,
877 true /* ignore_configuration */);
878 if (!result.has_value()) {
879 return base::unexpected(result.error());
880 }
881 return result->type_flags;
882}
883
Ryan Mitchell80094e32020-11-16 23:08:18 +0000884base::expected<AssetManager2::SelectedValue, NullOrIOError> AssetManager2::GetResource(
885 uint32_t resid, bool may_be_bag, uint16_t density_override) const {
886 auto result = FindEntry(resid, density_override, false /* stop_at_first_match */,
887 false /* ignore_configuration */);
888 if (!result.has_value()) {
889 return base::unexpected(result.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -0700890 }
891
Ryan Mitchell80094e32020-11-16 23:08:18 +0000892 auto result_map_entry = std::get_if<incfs::verified_map_ptr<ResTable_map_entry>>(&result->entry);
Ryan Mitchellbf1f45b2020-09-29 17:22:52 -0700893 if (result_map_entry != nullptr) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700894 if (!may_be_bag) {
895 LOG(ERROR) << base::StringPrintf("Resource %08x is a complex map type.", resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000896 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700897 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800898
899 // Create a reference since we can't represent this complex type as a Res_value.
Ryan Mitchell80094e32020-11-16 23:08:18 +0000900 return SelectedValue(Res_value::TYPE_REFERENCE, resid, result->cookie, result->type_flags,
901 resid, result->config);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700902 }
903
Adam Lesinskida431a22016-12-29 16:08:16 -0500904 // Convert the package ID to the runtime assigned package ID.
Ryan Mitchell80094e32020-11-16 23:08:18 +0000905 Res_value value = std::get<Res_value>(result->entry);
906 result->dynamic_ref_table->lookupResourceValue(&value);
Adam Lesinskida431a22016-12-29 16:08:16 -0500907
Ryan Mitchell80094e32020-11-16 23:08:18 +0000908 return SelectedValue(value.dataType, value.data, result->cookie, result->type_flags,
909 resid, result->config);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700910}
911
Ryan Mitchell80094e32020-11-16 23:08:18 +0000912base::expected<std::monostate, NullOrIOError> AssetManager2::ResolveReference(
Ryan Mitchella45506e2020-11-16 23:08:18 +0000913 AssetManager2::SelectedValue& value, bool cache_value) const {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000914 if (value.type != Res_value::TYPE_REFERENCE || value.data == 0U) {
915 // Not a reference. Nothing to do.
916 return {};
Adam Lesinski0c405242017-01-13 20:47:26 -0800917 }
Ryan Mitchell80094e32020-11-16 23:08:18 +0000918
Ryan Mitchella45506e2020-11-16 23:08:18 +0000919 const uint32_t original_flags = value.flags;
920 const uint32_t original_resid = value.data;
921 if (cache_value) {
922 auto cached_value = cached_resolved_values_.find(value.data);
923 if (cached_value != cached_resolved_values_.end()) {
924 value = cached_value->second;
925 value.flags |= original_flags;
926 return {};
927 }
928 }
929
930 uint32_t combined_flags = 0U;
931 uint32_t resolve_resid = original_resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000932 constexpr const uint32_t kMaxIterations = 20;
933 for (uint32_t i = 0U;; i++) {
934 auto result = GetResource(resolve_resid, true /*may_be_bag*/);
935 if (!result.has_value()) {
Ryan Mitchelle7ab6272020-11-13 18:06:15 -0800936 value.resid = resolve_resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000937 return base::unexpected(result.error());
938 }
939
Ryan Mitchelle7ab6272020-11-13 18:06:15 -0800940 // If resource resolution fails, the value should be set to the last reference that was able to
941 // be resolved successfully.
942 value = *result;
943 value.flags |= combined_flags;
944
Ryan Mitchell80094e32020-11-16 23:08:18 +0000945 if (result->type != Res_value::TYPE_REFERENCE ||
946 result->data == Res_value::DATA_NULL_UNDEFINED ||
947 result->data == resolve_resid || i == kMaxIterations) {
948 // This reference can't be resolved, so exit now and let the caller deal with it.
Ryan Mitchella45506e2020-11-16 23:08:18 +0000949 if (cache_value) {
950 cached_resolved_values_[original_resid] = value;
951 }
952
953 // Above value is cached without original_flags to ensure they don't get included in future
954 // queries that hit the cache
955 value.flags |= original_flags;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000956 return {};
957 }
958
Ryan Mitchelle7ab6272020-11-13 18:06:15 -0800959 combined_flags = result->flags;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000960 resolve_resid = result->data;
961 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800962}
963
Ryan Mitchell80094e32020-11-16 23:08:18 +0000964const std::vector<uint32_t> AssetManager2::GetBagResIdStack(uint32_t resid) const {
Aurimas Liutikas8f004c82019-01-17 17:20:10 -0800965 auto cached_iter = cached_bag_resid_stacks_.find(resid);
966 if (cached_iter != cached_bag_resid_stacks_.end()) {
967 return cached_iter->second;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -0800968 }
Ryan Mitchell80094e32020-11-16 23:08:18 +0000969
970 std::vector<uint32_t> found_resids;
971 GetBag(resid, found_resids);
972 cached_bag_resid_stacks_.emplace(resid, found_resids);
973 return found_resids;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -0800974}
975
Ryan Mitchell80094e32020-11-16 23:08:18 +0000976base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::ResolveBag(
977 AssetManager2::SelectedValue& value) const {
978 if (UNLIKELY(value.type != Res_value::TYPE_REFERENCE)) {
979 return base::unexpected(std::nullopt);
980 }
Aurimas Liutikas8f004c82019-01-17 17:20:10 -0800981
Ryan Mitchell80094e32020-11-16 23:08:18 +0000982 auto bag = GetBag(value.data);
983 if (bag.has_value()) {
984 value.flags |= (*bag)->type_spec_flags;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -0800985 }
986 return bag;
y57cd1952018-04-12 14:26:23 -0700987}
988
Ryan Mitchell80094e32020-11-16 23:08:18 +0000989base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::GetBag(uint32_t resid) const {
990 std::vector<uint32_t> found_resids;
991 const auto bag = GetBag(resid, found_resids);
992 cached_bag_resid_stacks_.emplace(resid, found_resids);
993 return bag;
Ryan Mitchell155d5392020-02-10 13:35:24 -0800994}
995
Ryan Mitchell80094e32020-11-16 23:08:18 +0000996base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::GetBag(
997 uint32_t resid, std::vector<uint32_t>& child_resids) const {
998 if (auto cached_iter = cached_bags_.find(resid); cached_iter != cached_bags_.end()) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700999 return cached_iter->second.get();
1000 }
1001
Ryan Mitchell80094e32020-11-16 23:08:18 +00001002 auto entry = FindEntry(resid, 0u /* density_override */, false /* stop_at_first_match */,
1003 false /* ignore_configuration */);
1004 if (!entry.has_value()) {
1005 return base::unexpected(entry.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001006 }
1007
Ryan Mitchell80094e32020-11-16 23:08:18 +00001008 auto entry_map = std::get_if<incfs::verified_map_ptr<ResTable_map_entry>>(&entry->entry);
1009 if (entry_map == nullptr) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001010 // Not a bag, nothing to do.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001011 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001012 }
1013
Ryan Mitchell80094e32020-11-16 23:08:18 +00001014 auto map = *entry_map;
1015 auto map_entry = map.offset(dtohs(map->size)).convert<ResTable_map>();
1016 const auto map_entry_end = map_entry + dtohl(map->count);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001017
y57cd1952018-04-12 14:26:23 -07001018 // Keep track of ids that have already been seen to prevent infinite loops caused by circular
Ryan Mitchell80094e32020-11-16 23:08:18 +00001019 // dependencies between bags.
y57cd1952018-04-12 14:26:23 -07001020 child_resids.push_back(resid);
1021
Adam Lesinskida431a22016-12-29 16:08:16 -05001022 uint32_t parent_resid = dtohl(map->parent.ident);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001023 if (parent_resid == 0U ||
1024 std::find(child_resids.begin(), child_resids.end(), parent_resid) != child_resids.end()) {
1025 // There is no parent or a circular parental dependency exist, meaning there is nothing to
1026 // inherit and we can do a simple copy of the entries in the map.
Adam Lesinski7ad11102016-10-28 16:39:15 -07001027 const size_t entry_count = map_entry_end - map_entry;
1028 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
1029 malloc(sizeof(ResolvedBag) + (entry_count * sizeof(ResolvedBag::Entry))))};
Ryan Mitchell155d5392020-02-10 13:35:24 -08001030
1031 bool sort_entries = false;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001032 for (auto new_entry = new_bag->entries; map_entry != map_entry_end; ++map_entry) {
1033 if (UNLIKELY(!map_entry)) {
1034 return base::unexpected(IOError::PAGES_MISSING);
1035 }
1036
Adam Lesinskida431a22016-12-29 16:08:16 -05001037 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001038 if (!is_internal_resid(new_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -05001039 // Attributes, arrays, etc don't have a resource id as the name. They specify
1040 // other data, which would be wrong to change via a lookup.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001041 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001042 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
1043 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001044 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001045 }
1046 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001047
1048 new_entry->cookie = entry->cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -05001049 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001050 new_entry->key_pool = nullptr;
1051 new_entry->type_pool = nullptr;
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001052 new_entry->style = resid;
Adam Lesinski30080e22017-10-16 16:18:09 -07001053 new_entry->value.copyFrom_dtoh(map_entry->value);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001054 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1055 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001056 LOG(ERROR) << base::StringPrintf(
1057 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
1058 new_entry->value.data, new_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001059 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001060 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001061
Ryan Mitchell155d5392020-02-10 13:35:24 -08001062 sort_entries = sort_entries ||
1063 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001064 ++new_entry;
1065 }
Ryan Mitchell155d5392020-02-10 13:35:24 -08001066
1067 if (sort_entries) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001068 std::sort(new_bag->entries, new_bag->entries + entry_count,
1069 [](auto&& lhs, auto&& rhs) { return lhs.key < rhs.key; });
Ryan Mitchell155d5392020-02-10 13:35:24 -08001070 }
1071
Ryan Mitchell80094e32020-11-16 23:08:18 +00001072 new_bag->type_spec_flags = entry->type_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001073 new_bag->entry_count = static_cast<uint32_t>(entry_count);
1074 ResolvedBag* result = new_bag.get();
1075 cached_bags_[resid] = std::move(new_bag);
1076 return result;
1077 }
1078
Adam Lesinskida431a22016-12-29 16:08:16 -05001079 // In case the parent is a dynamic reference, resolve it.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001080 entry->dynamic_ref_table->lookupResourceId(&parent_resid);
Adam Lesinskida431a22016-12-29 16:08:16 -05001081
Adam Lesinski7ad11102016-10-28 16:39:15 -07001082 // Get the parent and do a merge of the keys.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001083 const auto parent_bag = GetBag(parent_resid, child_resids);
1084 if (UNLIKELY(!parent_bag.has_value())) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001085 // Failed to get the parent that should exist.
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001086 LOG(ERROR) << base::StringPrintf("Failed to find parent 0x%08x of bag 0x%08x.", parent_resid,
1087 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001088 return base::unexpected(parent_bag.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001089 }
1090
Adam Lesinski7ad11102016-10-28 16:39:15 -07001091 // Create the max possible entries we can make. Once we construct the bag,
1092 // we will realloc to fit to size.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001093 const size_t max_count = (*parent_bag)->entry_count + dtohl(map->count);
George Burgess IV09b119f2017-07-25 15:00:04 -07001094 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
1095 malloc(sizeof(ResolvedBag) + (max_count * sizeof(ResolvedBag::Entry))))};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001096 ResolvedBag::Entry* new_entry = new_bag->entries;
1097
Ryan Mitchell80094e32020-11-16 23:08:18 +00001098 const ResolvedBag::Entry* parent_entry = (*parent_bag)->entries;
1099 const ResolvedBag::Entry* const parent_entry_end = parent_entry + (*parent_bag)->entry_count;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001100
1101 // The keys are expected to be in sorted order. Merge the two bags.
Ryan Mitchell155d5392020-02-10 13:35:24 -08001102 bool sort_entries = false;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001103 while (map_entry != map_entry_end && parent_entry != parent_entry_end) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001104 if (UNLIKELY(!map_entry)) {
1105 return base::unexpected(IOError::PAGES_MISSING);
1106 }
1107
Adam Lesinskida431a22016-12-29 16:08:16 -05001108 uint32_t child_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001109 if (!is_internal_resid(child_key)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001110 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&child_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001111 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", child_key,
1112 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001113 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001114 }
1115 }
1116
Adam Lesinski7ad11102016-10-28 16:39:15 -07001117 if (child_key <= parent_entry->key) {
1118 // Use the child key if it comes before the parent
1119 // or is equal to the parent (overrides).
Ryan Mitchell80094e32020-11-16 23:08:18 +00001120 new_entry->cookie = entry->cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001121 new_entry->key = child_key;
1122 new_entry->key_pool = nullptr;
1123 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -07001124 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001125 new_entry->style = resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001126 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1127 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001128 LOG(ERROR) << base::StringPrintf(
1129 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
1130 new_entry->value.data, child_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001131 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001132 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001133 ++map_entry;
1134 } else {
1135 // Take the parent entry as-is.
1136 memcpy(new_entry, parent_entry, sizeof(*new_entry));
1137 }
1138
Ryan Mitchell155d5392020-02-10 13:35:24 -08001139 sort_entries = sort_entries ||
1140 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001141 if (child_key >= parent_entry->key) {
1142 // Move to the next parent entry if we used it or it was overridden.
1143 ++parent_entry;
1144 }
1145 // Increment to the next entry to fill.
1146 ++new_entry;
1147 }
1148
1149 // Finish the child entries if they exist.
1150 while (map_entry != map_entry_end) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001151 if (UNLIKELY(!map_entry)) {
1152 return base::unexpected(IOError::PAGES_MISSING);
1153 }
1154
Adam Lesinskida431a22016-12-29 16:08:16 -05001155 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001156 if (!is_internal_resid(new_key)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001157 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001158 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
1159 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001160 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001161 }
1162 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001163 new_entry->cookie = entry->cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -05001164 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001165 new_entry->key_pool = nullptr;
1166 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -07001167 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001168 new_entry->style = resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001169 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1170 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001171 LOG(ERROR) << base::StringPrintf("Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.",
1172 new_entry->value.dataType, new_entry->value.data, new_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001173 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001174 }
Ryan Mitchell155d5392020-02-10 13:35:24 -08001175 sort_entries = sort_entries ||
1176 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001177 ++map_entry;
1178 ++new_entry;
1179 }
1180
1181 // Finish the parent entries if they exist.
1182 if (parent_entry != parent_entry_end) {
1183 // Take the rest of the parent entries as-is.
1184 const size_t num_entries_to_copy = parent_entry_end - parent_entry;
1185 memcpy(new_entry, parent_entry, num_entries_to_copy * sizeof(*new_entry));
1186 new_entry += num_entries_to_copy;
1187 }
1188
1189 // Resize the resulting array to fit.
1190 const size_t actual_count = new_entry - new_bag->entries;
1191 if (actual_count != max_count) {
George Burgess IV09b119f2017-07-25 15:00:04 -07001192 new_bag.reset(reinterpret_cast<ResolvedBag*>(realloc(
1193 new_bag.release(), sizeof(ResolvedBag) + (actual_count * sizeof(ResolvedBag::Entry)))));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001194 }
1195
Ryan Mitchell155d5392020-02-10 13:35:24 -08001196 if (sort_entries) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001197 std::sort(new_bag->entries, new_bag->entries + actual_count,
1198 [](auto&& lhs, auto&& rhs) { return lhs.key < rhs.key; });
Ryan Mitchell155d5392020-02-10 13:35:24 -08001199 }
1200
Adam Lesinski1a1e9c22017-10-13 15:45:34 -07001201 // Combine flags from the parent and our own bag.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001202 new_bag->type_spec_flags = entry->type_flags | (*parent_bag)->type_spec_flags;
George Burgess IV09b119f2017-07-25 15:00:04 -07001203 new_bag->entry_count = static_cast<uint32_t>(actual_count);
1204 ResolvedBag* result = new_bag.get();
1205 cached_bags_[resid] = std::move(new_bag);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001206 return result;
1207}
1208
Adam Lesinski929d6512017-01-16 19:11:19 -08001209static bool Utf8ToUtf16(const StringPiece& str, std::u16string* out) {
1210 ssize_t len =
1211 utf8_to_utf16_length(reinterpret_cast<const uint8_t*>(str.data()), str.size(), false);
1212 if (len < 0) {
1213 return false;
1214 }
1215 out->resize(static_cast<size_t>(len));
1216 utf8_to_utf16(reinterpret_cast<const uint8_t*>(str.data()), str.size(), &*out->begin(),
1217 static_cast<size_t>(len + 1));
1218 return true;
1219}
1220
Ryan Mitchell80094e32020-11-16 23:08:18 +00001221base::expected<uint32_t, NullOrIOError> AssetManager2::GetResourceId(
1222 const std::string& resource_name, const std::string& fallback_type,
1223 const std::string& fallback_package) const {
Adam Lesinski929d6512017-01-16 19:11:19 -08001224 StringPiece package_name, type, entry;
1225 if (!ExtractResourceName(resource_name, &package_name, &type, &entry)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001226 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001227 }
1228
1229 if (entry.empty()) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001230 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001231 }
1232
1233 if (package_name.empty()) {
1234 package_name = fallback_package;
1235 }
1236
1237 if (type.empty()) {
1238 type = fallback_type;
1239 }
1240
1241 std::u16string type16;
1242 if (!Utf8ToUtf16(type, &type16)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001243 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001244 }
1245
1246 std::u16string entry16;
1247 if (!Utf8ToUtf16(entry, &entry16)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001248 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001249 }
1250
1251 const StringPiece16 kAttr16 = u"attr";
1252 const static std::u16string kAttrPrivate16 = u"^attr-private";
1253
1254 for (const PackageGroup& package_group : package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001255 for (const ConfiguredPackage& package_impl : package_group.packages_) {
1256 const LoadedPackage* package = package_impl.loaded_package_;
Adam Lesinski929d6512017-01-16 19:11:19 -08001257 if (package_name != package->GetPackageName()) {
1258 // All packages in the same group are expected to have the same package name.
1259 break;
1260 }
1261
Ryan Mitchell80094e32020-11-16 23:08:18 +00001262 base::expected<uint32_t, NullOrIOError> resid = package->FindEntryByName(type16, entry16);
1263 if (UNLIKELY(IsIOError(resid))) {
1264 return base::unexpected(resid.error());
1265 }
1266
1267 if (!resid.has_value() && kAttr16 == type16) {
Adam Lesinski929d6512017-01-16 19:11:19 -08001268 // Private attributes in libraries (such as the framework) are sometimes encoded
1269 // under the type '^attr-private' in order to leave the ID space of public 'attr'
1270 // free for future additions. Check '^attr-private' for the same name.
1271 resid = package->FindEntryByName(kAttrPrivate16, entry16);
1272 }
1273
Ryan Mitchell80094e32020-11-16 23:08:18 +00001274 if (resid.has_value()) {
1275 return fix_package_id(*resid, package_group.dynamic_ref_table->mAssignedPackageId);
Adam Lesinski929d6512017-01-16 19:11:19 -08001276 }
1277 }
1278 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001279 return base::unexpected(std::nullopt);
Adam Lesinski0c405242017-01-13 20:47:26 -08001280}
1281
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001282void AssetManager2::RebuildFilterList() {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001283 for (PackageGroup& group : package_groups_) {
1284 for (ConfiguredPackage& impl : group.packages_) {
1285 // Destroy it.
1286 impl.filtered_configs_.~ByteBucketArray();
1287
1288 // Re-create it.
1289 new (&impl.filtered_configs_) ByteBucketArray<FilteredConfigGroup>();
1290
1291 // Create the filters here.
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001292 impl.loaded_package_->ForEachTypeSpec([&](const TypeSpec& type_spec, uint8_t type_id) {
1293 FilteredConfigGroup& group = impl.filtered_configs_.editItemAt(type_id - 1);
1294 for (const auto& type_entry : type_spec.type_entries) {
1295 if (type_entry.config.match(configuration_)) {
1296 group.type_entries.push_back(&type_entry);
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001297 }
1298 }
1299 });
1300 }
1301 }
1302}
1303
Adam Lesinski7ad11102016-10-28 16:39:15 -07001304void AssetManager2::InvalidateCaches(uint32_t diff) {
Ryan Mitchell2c4d8742019-03-04 09:41:00 -08001305 cached_bag_resid_stacks_.clear();
1306
Adam Lesinski7ad11102016-10-28 16:39:15 -07001307 if (diff == 0xffffffffu) {
1308 // Everything must go.
1309 cached_bags_.clear();
1310 return;
1311 }
1312
1313 // Be more conservative with what gets purged. Only if the bag has other possible
1314 // variations with respect to what changed (diff) should we remove it.
1315 for (auto iter = cached_bags_.cbegin(); iter != cached_bags_.cend();) {
1316 if (diff & iter->second->type_spec_flags) {
1317 iter = cached_bags_.erase(iter);
1318 } else {
1319 ++iter;
1320 }
1321 }
Ryan Mitchella45506e2020-11-16 23:08:18 +00001322
1323 cached_resolved_values_.clear();
Adam Lesinski7ad11102016-10-28 16:39:15 -07001324}
1325
Ryan Mitchell2e394222019-08-28 12:10:51 -07001326uint8_t AssetManager2::GetAssignedPackageId(const LoadedPackage* package) const {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001327 for (auto& package_group : package_groups_) {
1328 for (auto& package2 : package_group.packages_) {
1329 if (package2.loaded_package_ == package) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -07001330 return package_group.dynamic_ref_table->mAssignedPackageId;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001331 }
1332 }
1333 }
1334 return 0;
1335}
1336
Adam Lesinski30080e22017-10-16 16:18:09 -07001337std::unique_ptr<Theme> AssetManager2::NewTheme() {
1338 return std::unique_ptr<Theme>(new Theme(this));
1339}
1340
1341Theme::Theme(AssetManager2* asset_manager) : asset_manager_(asset_manager) {
1342}
1343
1344Theme::~Theme() = default;
1345
1346namespace {
1347
1348struct ThemeEntry {
1349 ApkAssetsCookie cookie;
1350 uint32_t type_spec_flags;
1351 Res_value value;
1352};
1353
1354struct ThemeType {
1355 int entry_count;
1356 ThemeEntry entries[0];
1357};
1358
1359constexpr size_t kTypeCount = std::numeric_limits<uint8_t>::max() + 1;
1360
1361} // namespace
1362
1363struct Theme::Package {
1364 // Each element of Type will be a dynamically sized object
1365 // allocated to have the entries stored contiguously with the Type.
1366 std::array<util::unique_cptr<ThemeType>, kTypeCount> types;
1367};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001368
Ryan Mitchell80094e32020-11-16 23:08:18 +00001369base::expected<std::monostate, NullOrIOError> Theme::ApplyStyle(uint32_t resid, bool force) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001370 ATRACE_NAME("Theme::ApplyStyle");
Adam Lesinski7ad11102016-10-28 16:39:15 -07001371
Ryan Mitchell80094e32020-11-16 23:08:18 +00001372 auto bag = asset_manager_->GetBag(resid);
1373 if (!bag.has_value()) {
1374 return base::unexpected(bag.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001375 }
1376
1377 // Merge the flags from this style.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001378 type_spec_flags_ |= (*bag)->type_spec_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001379
Adam Lesinski30080e22017-10-16 16:18:09 -07001380 int last_type_idx = -1;
1381 int last_package_idx = -1;
1382 Package* last_package = nullptr;
1383 ThemeType* last_type = nullptr;
1384
1385 // Iterate backwards, because each bag is sorted in ascending key ID order, meaning we will only
1386 // need to perform one resize per type.
1387 using reverse_bag_iterator = std::reverse_iterator<const ResolvedBag::Entry*>;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001388 const auto rbegin = reverse_bag_iterator(begin(*bag));
1389 for (auto it = reverse_bag_iterator(end(*bag)); it != rbegin; ++it) {
1390 const uint32_t attr_resid = it->key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001391
Adam Lesinski30080e22017-10-16 16:18:09 -07001392 // If the resource ID passed in is not a style, the key can be some other identifier that is not
1393 // a resource ID. We should fail fast instead of operating with strange resource IDs.
Adam Lesinski929d6512017-01-16 19:11:19 -08001394 if (!is_valid_resid(attr_resid)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001395 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001396 }
1397
Adam Lesinski30080e22017-10-16 16:18:09 -07001398 // We don't use the 0-based index for the type so that we can avoid doing ID validation
1399 // upon lookup. Instead, we keep space for the type ID 0 in our data structures. Since
1400 // the construction of this type is guarded with a resource ID check, it will never be
1401 // populated, and querying type ID 0 will always fail.
1402 const int package_idx = get_package_id(attr_resid);
1403 const int type_idx = get_type_id(attr_resid);
1404 const int entry_idx = get_entry_id(attr_resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001405
Adam Lesinski30080e22017-10-16 16:18:09 -07001406 if (last_package_idx != package_idx) {
1407 std::unique_ptr<Package>& package = packages_[package_idx];
1408 if (package == nullptr) {
1409 package.reset(new Package());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001410 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001411 last_package_idx = package_idx;
1412 last_package = package.get();
1413 last_type_idx = -1;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001414 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001415
1416 if (last_type_idx != type_idx) {
1417 util::unique_cptr<ThemeType>& type = last_package->types[type_idx];
1418 if (type == nullptr) {
1419 // Allocate enough memory to contain this entry_idx. Since we're iterating in reverse over
1420 // a sorted list of attributes, this shouldn't be resized again during this method call.
1421 type.reset(reinterpret_cast<ThemeType*>(
1422 calloc(sizeof(ThemeType) + (entry_idx + 1) * sizeof(ThemeEntry), 1)));
1423 type->entry_count = entry_idx + 1;
1424 } else if (entry_idx >= type->entry_count) {
1425 // Reallocate the memory to contain this entry_idx. Since we're iterating in reverse over
1426 // a sorted list of attributes, this shouldn't be resized again during this method call.
1427 const int new_count = entry_idx + 1;
1428 type.reset(reinterpret_cast<ThemeType*>(
1429 realloc(type.release(), sizeof(ThemeType) + (new_count * sizeof(ThemeEntry)))));
1430
1431 // Clear out the newly allocated space (which isn't zeroed).
1432 memset(type->entries + type->entry_count, 0,
1433 (new_count - type->entry_count) * sizeof(ThemeEntry));
1434 type->entry_count = new_count;
1435 }
1436 last_type_idx = type_idx;
1437 last_type = type.get();
1438 }
1439
1440 ThemeEntry& entry = last_type->entries[entry_idx];
1441 if (force || (entry.value.dataType == Res_value::TYPE_NULL &&
1442 entry.value.data != Res_value::DATA_NULL_EMPTY)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001443 entry.cookie = it->cookie;
1444 entry.type_spec_flags |= (*bag)->type_spec_flags;
1445 entry.value = it->value;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001446 }
1447 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001448 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001449}
1450
Ryan Mitchell80094e32020-11-16 23:08:18 +00001451std::optional<AssetManager2::SelectedValue> Theme::GetAttribute(uint32_t resid) const {
1452
Adam Lesinski30080e22017-10-16 16:18:09 -07001453 int cnt = 20;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001454 uint32_t type_spec_flags = 0u;
Adam Lesinski30080e22017-10-16 16:18:09 -07001455 do {
1456 const int package_idx = get_package_id(resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001457 const Package* package = packages_[package_idx].get();
Adam Lesinski30080e22017-10-16 16:18:09 -07001458 if (package != nullptr) {
1459 // The themes are constructed with a 1-based type ID, so no need to decrement here.
1460 const int type_idx = get_type_id(resid);
1461 const ThemeType* type = package->types[type_idx].get();
1462 if (type != nullptr) {
1463 const int entry_idx = get_entry_id(resid);
1464 if (entry_idx < type->entry_count) {
1465 const ThemeEntry& entry = type->entries[entry_idx];
1466 type_spec_flags |= entry.type_spec_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001467
Adam Lesinski30080e22017-10-16 16:18:09 -07001468 if (entry.value.dataType == Res_value::TYPE_ATTRIBUTE) {
1469 if (cnt > 0) {
1470 cnt--;
1471 resid = entry.value.data;
1472 continue;
1473 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001474 return std::nullopt;
Adam Lesinski30080e22017-10-16 16:18:09 -07001475 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001476
Adam Lesinski30080e22017-10-16 16:18:09 -07001477 // @null is different than @empty.
1478 if (entry.value.dataType == Res_value::TYPE_NULL &&
1479 entry.value.data != Res_value::DATA_NULL_EMPTY) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001480 return std::nullopt;
Adam Lesinski30080e22017-10-16 16:18:09 -07001481 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001482
Ryan Mitchell80094e32020-11-16 23:08:18 +00001483 return AssetManager2::SelectedValue(entry.value.dataType, entry.value.data, entry.cookie,
1484 type_spec_flags, 0U /* resid */, {} /* config */);
Adam Lesinskida431a22016-12-29 16:08:16 -05001485 }
Adam Lesinskida431a22016-12-29 16:08:16 -05001486 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001487 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001488 break;
1489 } while (true);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001490 return std::nullopt;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001491}
1492
Ryan Mitchell80094e32020-11-16 23:08:18 +00001493base::expected<std::monostate, NullOrIOError> Theme::ResolveAttributeReference(
1494 AssetManager2::SelectedValue& value) const {
1495 if (value.type != Res_value::TYPE_ATTRIBUTE) {
1496 return asset_manager_->ResolveReference(value);
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001497 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001498
1499 std::optional<AssetManager2::SelectedValue> result = GetAttribute(value.data);
1500 if (!result.has_value()) {
1501 return base::unexpected(std::nullopt);
1502 }
1503
Ryan Mitchella45506e2020-11-16 23:08:18 +00001504 auto resolve_result = asset_manager_->ResolveReference(*result, true /* cache_value */);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001505 if (resolve_result.has_value()) {
1506 result->flags |= value.flags;
1507 value = *result;
1508 }
1509 return resolve_result;
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001510}
1511
Adam Lesinski7ad11102016-10-28 16:39:15 -07001512void Theme::Clear() {
1513 type_spec_flags_ = 0u;
1514 for (std::unique_ptr<Package>& package : packages_) {
1515 package.reset();
1516 }
1517}
1518
Ryan Mitchell80094e32020-11-16 23:08:18 +00001519base::expected<std::monostate, IOError> Theme::SetTo(const Theme& o) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001520 if (this == &o) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001521 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001522 }
1523
Adam Lesinski7ad11102016-10-28 16:39:15 -07001524 type_spec_flags_ = o.type_spec_flags_;
1525
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001526 if (asset_manager_ == o.asset_manager_) {
1527 // The theme comes from the same asset manager so all theme data can be copied exactly
1528 for (size_t p = 0; p < packages_.size(); p++) {
1529 const Package *package = o.packages_[p].get();
1530 if (package == nullptr) {
1531 // The other theme doesn't have this package, clear ours.
1532 packages_[p].reset();
Adam Lesinski7ad11102016-10-28 16:39:15 -07001533 continue;
1534 }
1535
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001536 if (packages_[p] == nullptr) {
1537 // The other theme has this package, but we don't. Make one.
1538 packages_[p].reset(new Package());
1539 }
1540
1541 for (size_t t = 0; t < package->types.size(); t++) {
1542 const ThemeType *type = package->types[t].get();
1543 if (type == nullptr) {
1544 // The other theme doesn't have this type, clear ours.
1545 packages_[p]->types[t].reset();
1546 continue;
1547 }
1548
1549 // Create a new type and update it to theirs.
1550 const size_t type_alloc_size = sizeof(ThemeType) + (type->entry_count * sizeof(ThemeEntry));
1551 void *copied_data = malloc(type_alloc_size);
1552 memcpy(copied_data, type, type_alloc_size);
1553 packages_[p]->types[t].reset(reinterpret_cast<ThemeType *>(copied_data));
1554 }
1555 }
1556 } else {
1557 std::map<ApkAssetsCookie, ApkAssetsCookie> src_to_dest_asset_cookies;
1558 typedef std::map<int, int> SourceToDestinationRuntimePackageMap;
1559 std::map<ApkAssetsCookie, SourceToDestinationRuntimePackageMap> src_asset_cookie_id_map;
1560
Ryan Mitchell93bca972019-03-08 17:26:28 -08001561 // Determine which ApkAssets are loaded in both theme AssetManagers.
Ryan Mitchellef538432021-03-01 14:52:14 -08001562 const auto src_assets = o.asset_manager_->GetApkAssets();
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001563 for (size_t i = 0; i < src_assets.size(); i++) {
1564 const ApkAssets* src_asset = src_assets[i];
1565
Ryan Mitchellef538432021-03-01 14:52:14 -08001566 const auto dest_assets = asset_manager_->GetApkAssets();
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001567 for (size_t j = 0; j < dest_assets.size(); j++) {
1568 const ApkAssets* dest_asset = dest_assets[j];
Ryan Mitchellef538432021-03-01 14:52:14 -08001569 if (src_asset != dest_asset) {
1570 // ResourcesManager caches and reuses ApkAssets when the same apk must be present in
1571 // multiple AssetManagers. Two ApkAssets point to the same version of the same resources
1572 // if they are the same instance.
1573 continue;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001574 }
Ryan Mitchellef538432021-03-01 14:52:14 -08001575
1576 // Map the package ids of the asset in the source AssetManager to the package ids of the
1577 // asset in th destination AssetManager.
1578 SourceToDestinationRuntimePackageMap package_map;
1579 for (const auto& loaded_package : src_asset->GetLoadedArsc()->GetPackages()) {
1580 const int src_package_id = o.asset_manager_->GetAssignedPackageId(loaded_package.get());
1581 const int dest_package_id = asset_manager_->GetAssignedPackageId(loaded_package.get());
1582 package_map[src_package_id] = dest_package_id;
1583 }
1584
1585 src_to_dest_asset_cookies.insert(std::make_pair(i, j));
1586 src_asset_cookie_id_map.insert(std::make_pair(i, package_map));
1587 break;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001588 }
1589 }
1590
Ryan Mitchell93bca972019-03-08 17:26:28 -08001591 // Reset the data in the destination theme.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001592 for (size_t p = 0; p < packages_.size(); p++) {
1593 if (packages_[p] != nullptr) {
1594 packages_[p].reset();
1595 }
1596 }
1597
1598 for (size_t p = 0; p < packages_.size(); p++) {
1599 const Package *package = o.packages_[p].get();
1600 if (package == nullptr) {
1601 continue;
1602 }
1603
1604 for (size_t t = 0; t < package->types.size(); t++) {
1605 const ThemeType *type = package->types[t].get();
1606 if (type == nullptr) {
1607 continue;
1608 }
1609
1610 for (size_t e = 0; e < type->entry_count; e++) {
1611 const ThemeEntry &entry = type->entries[e];
1612 if (entry.value.dataType == Res_value::TYPE_NULL &&
1613 entry.value.data != Res_value::DATA_NULL_EMPTY) {
1614 continue;
1615 }
1616
Ryan Mitchell93bca972019-03-08 17:26:28 -08001617 bool is_reference = (entry.value.dataType == Res_value::TYPE_ATTRIBUTE
1618 || entry.value.dataType == Res_value::TYPE_REFERENCE
1619 || entry.value.dataType == Res_value::TYPE_DYNAMIC_ATTRIBUTE
1620 || entry.value.dataType == Res_value::TYPE_DYNAMIC_REFERENCE)
1621 && entry.value.data != 0x0;
Ryan Mitchellb85d9b22018-11-19 12:11:38 -08001622
Ryan Mitchell93bca972019-03-08 17:26:28 -08001623 // If the attribute value represents an attribute or reference, the package id of the
1624 // value needs to be rewritten to the package id of the value in the destination.
1625 uint32_t attribute_data = entry.value.data;
1626 if (is_reference) {
1627 // Determine the package id of the reference in the destination AssetManager.
Ryan Mitchellb85d9b22018-11-19 12:11:38 -08001628 auto value_package_map = src_asset_cookie_id_map.find(entry.cookie);
1629 if (value_package_map == src_asset_cookie_id_map.end()) {
1630 continue;
1631 }
1632
1633 auto value_dest_package = value_package_map->second.find(
1634 get_package_id(entry.value.data));
1635 if (value_dest_package == value_package_map->second.end()) {
1636 continue;
1637 }
1638
Ryan Mitchell93bca972019-03-08 17:26:28 -08001639 attribute_data = fix_package_id(entry.value.data, value_dest_package->second);
1640 }
1641
1642 // Find the cookie of the value in the destination. If the source apk is not loaded in the
1643 // destination, only copy resources that do not reference resources in the source.
1644 ApkAssetsCookie data_dest_cookie;
1645 auto value_dest_cookie = src_to_dest_asset_cookies.find(entry.cookie);
1646 if (value_dest_cookie != src_to_dest_asset_cookies.end()) {
1647 data_dest_cookie = value_dest_cookie->second;
1648 } else {
1649 if (is_reference || entry.value.dataType == Res_value::TYPE_STRING) {
1650 continue;
1651 } else {
1652 data_dest_cookie = 0x0;
1653 }
Ryan Mitchellb85d9b22018-11-19 12:11:38 -08001654 }
1655
1656 // The package id of the attribute needs to be rewritten to the package id of the
Ryan Mitchell93bca972019-03-08 17:26:28 -08001657 // attribute in the destination.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001658 int attribute_dest_package_id = p;
1659 if (attribute_dest_package_id != 0x01) {
Ryan Mitchell93bca972019-03-08 17:26:28 -08001660 // Find the cookie of the attribute resource id in the source AssetManager
Ryan Mitchell80094e32020-11-16 23:08:18 +00001661 base::expected<FindEntryResult, NullOrIOError> attribute_entry_result =
Ryan Mitchella55dc2e2019-01-24 10:58:23 -08001662 o.asset_manager_->FindEntry(make_resid(p, t, e), 0 /* density_override */ ,
1663 true /* stop_at_first_match */,
Ryan Mitchell80094e32020-11-16 23:08:18 +00001664 true /* ignore_configuration */);
1665 if (UNLIKELY(IsIOError(attribute_entry_result))) {
1666 return base::unexpected(GetIOError(attribute_entry_result.error()));
1667 }
1668 if (!attribute_entry_result.has_value()) {
1669 continue;
1670 }
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001671
Ryan Mitchell93bca972019-03-08 17:26:28 -08001672 // Determine the package id of the attribute in the destination AssetManager.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001673 auto attribute_package_map = src_asset_cookie_id_map.find(
1674 attribute_entry_result->cookie);
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001675 if (attribute_package_map == src_asset_cookie_id_map.end()) {
1676 continue;
1677 }
1678 auto attribute_dest_package = attribute_package_map->second.find(
1679 attribute_dest_package_id);
1680 if (attribute_dest_package == attribute_package_map->second.end()) {
1681 continue;
1682 }
1683 attribute_dest_package_id = attribute_dest_package->second;
1684 }
1685
Ryan Mitchell93bca972019-03-08 17:26:28 -08001686 // Lazily instantiate the destination package.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001687 std::unique_ptr<Package>& dest_package = packages_[attribute_dest_package_id];
1688 if (dest_package == nullptr) {
1689 dest_package.reset(new Package());
1690 }
1691
Ryan Mitchell93bca972019-03-08 17:26:28 -08001692 // Lazily instantiate and resize the destination type.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001693 util::unique_cptr<ThemeType>& dest_type = dest_package->types[t];
1694 if (dest_type == nullptr || dest_type->entry_count < type->entry_count) {
1695 const size_t type_alloc_size = sizeof(ThemeType)
1696 + (type->entry_count * sizeof(ThemeEntry));
1697 void* dest_data = malloc(type_alloc_size);
1698 memset(dest_data, 0, type->entry_count * sizeof(ThemeEntry));
1699
Ryan Mitchell93bca972019-03-08 17:26:28 -08001700 // Copy the existing destination type values if the type is resized.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001701 if (dest_type != nullptr) {
1702 memcpy(dest_data, type, sizeof(ThemeType)
1703 + (dest_type->entry_count * sizeof(ThemeEntry)));
1704 }
1705
1706 dest_type.reset(reinterpret_cast<ThemeType *>(dest_data));
1707 dest_type->entry_count = type->entry_count;
1708 }
1709
Ryan Mitchell93bca972019-03-08 17:26:28 -08001710 dest_type->entries[e].cookie = data_dest_cookie;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001711 dest_type->entries[e].value.dataType = entry.value.dataType;
Ryan Mitchell93bca972019-03-08 17:26:28 -08001712 dest_type->entries[e].value.data = attribute_data;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001713 dest_type->entries[e].type_spec_flags = entry.type_spec_flags;
1714 }
1715 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001716 }
1717 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001718 return {};
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001719}
1720
1721void Theme::Dump() const {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001722 LOG(INFO) << base::StringPrintf("Theme(this=%p, AssetManager2=%p)", this, asset_manager_);
1723
1724 for (int p = 0; p < packages_.size(); p++) {
1725 auto& package = packages_[p];
1726 if (package == nullptr) {
1727 continue;
1728 }
1729
1730 for (int t = 0; t < package->types.size(); t++) {
1731 auto& type = package->types[t];
1732 if (type == nullptr) {
1733 continue;
1734 }
1735
1736 for (int e = 0; e < type->entry_count; e++) {
1737 auto& entry = type->entries[e];
1738 if (entry.value.dataType == Res_value::TYPE_NULL &&
1739 entry.value.data != Res_value::DATA_NULL_EMPTY) {
1740 continue;
1741 }
1742
1743 LOG(INFO) << base::StringPrintf(" entry(0x%08x)=(0x%08x) type=(0x%02x), cookie(%d)",
1744 make_resid(p, t, e), entry.value.data,
1745 entry.value.dataType, entry.cookie);
1746 }
1747 }
1748 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001749}
1750
1751} // namespace android