blob: c0ef7be8b673d382d73eeef15271fad4c75c82e3 [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 {
229 base::ScopedLogSeverity _log(base::INFO);
230
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
Ryan Mitchell80094e32020-11-16 23:08:18 +0000595 if (!stop_at_first_match && !ignore_configuration && !apk_assets_[result->cookie]->IsLoader()) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700596 for (const auto& id_map : package_group.overlays_) {
597 auto overlay_entry = id_map.overlay_res_maps_.Lookup(resid);
598 if (!overlay_entry) {
599 // No id map entry exists for this target resource.
600 continue;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000601 }
602 if (overlay_entry.IsInlineValue()) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700603 // The target resource is overlaid by an inline value not represented by a resource.
Ryan Mitchell80094e32020-11-16 23:08:18 +0000604 result->entry = overlay_entry.GetInlineValue();
605 result->dynamic_ref_table = id_map.overlay_res_maps_.GetOverlayDynamicRefTable();
606 result->cookie = id_map.cookie;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700607 continue;
608 }
609
Ryan Mitchell80094e32020-11-16 23:08:18 +0000610 auto overlay_result = FindEntry(overlay_entry.GetResourceId(), density_override,
611 false /* stop_at_first_match */,
612 false /* ignore_configuration */);
613 if (UNLIKELY(IsIOError(overlay_result))) {
614 return base::unexpected(overlay_result.error());
615 }
616 if (!overlay_result.has_value()) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700617 continue;
618 }
619
Ryan Mitchell80094e32020-11-16 23:08:18 +0000620 if (!overlay_result->config.isBetterThan(result->config, desired_config)
621 && overlay_result->config.compare(result->config) != 0) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700622 // The configuration of the entry for the overlay must be equal to or better than the target
623 // configuration to be chosen as the better value.
624 continue;
625 }
626
Ryan Mitchell80094e32020-11-16 23:08:18 +0000627 result->cookie = overlay_result->cookie;
628 result->entry = overlay_result->entry;
629 result->config = overlay_result->config;
630 result->dynamic_ref_table = id_map.overlay_res_maps_.GetOverlayDynamicRefTable();
631
632 if (UNLIKELY(logging_enabled)) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700633 last_resolution_.steps.push_back(
Ryan Mitchell80094e32020-11-16 23:08:18 +0000634 Resolution::Step{Resolution::Step::Type::OVERLAID, overlay_result->config.toString(),
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800635 overlay_result->package_name,
636 overlay_result->cookie});
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700637 }
638 }
639 }
640
Ryan Mitchell80094e32020-11-16 23:08:18 +0000641 if (UNLIKELY(logging_enabled)) {
642 last_resolution_.cookie = result->cookie;
643 last_resolution_.type_string_ref = result->type_string_ref;
644 last_resolution_.entry_string_ref = result->entry_string_ref;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700645 }
646
Ryan Mitchell80094e32020-11-16 23:08:18 +0000647 return result;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700648}
649
Ryan Mitchell80094e32020-11-16 23:08:18 +0000650base::expected<FindEntryResult, NullOrIOError> AssetManager2::FindEntryInternal(
651 const PackageGroup& package_group, uint8_t type_idx, uint16_t entry_idx,
652 const ResTable_config& desired_config, bool stop_at_first_match,
653 bool ignore_configuration) const {
654 const bool logging_enabled = resource_resolution_logging_enabled_;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800655 ApkAssetsCookie best_cookie = kInvalidCookie;
656 const LoadedPackage* best_package = nullptr;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000657 incfs::verified_map_ptr<ResTable_type> best_type;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800658 const ResTable_config* best_config = nullptr;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000659 uint32_t best_offset = 0U;
660 uint32_t type_flags = 0U;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800661
Winson2f3669b2019-01-11 11:28:34 -0800662 std::vector<Resolution::Step> resolution_steps;
663
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800664 // If `desired_config` is not the same as the set configuration or the caller will accept a value
665 // from any configuration, then we cannot use our filtered list of types since it only it contains
666 // types matched to the set configuration.
667 const bool use_filtered = !ignore_configuration && &desired_config == &configuration_;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800668
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700669 const size_t package_count = package_group.packages_.size();
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800670 for (size_t pi = 0; pi < package_count; pi++) {
671 const ConfiguredPackage& loaded_package_impl = package_group.packages_[pi];
672 const LoadedPackage* loaded_package = loaded_package_impl.loaded_package_;
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800673 const ApkAssetsCookie cookie = package_group.cookies_[pi];
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800674
675 // If the type IDs are offset in this package, we need to take that into account when searching
676 // for a type.
677 const TypeSpec* type_spec = loaded_package->GetTypeSpecByTypeIndex(type_idx);
678 if (UNLIKELY(type_spec == nullptr)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700679 continue;
680 }
681
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800682 // Allow custom loader packages to overlay resource values with configurations equivalent to the
683 // current best configuration.
684 const bool package_is_loader = loaded_package->IsCustomLoader();
685
Ryan Mitchell80094e32020-11-16 23:08:18 +0000686 auto entry_flags = type_spec->GetFlagsForEntryIndex(entry_idx);
Bernie Innocenti58cf8e32020-12-19 15:31:52 +0900687 if (UNLIKELY(!entry_flags.has_value())) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000688 return base::unexpected(entry_flags.error());
689 }
690 type_flags |= entry_flags.value();
691
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800692 const FilteredConfigGroup& filtered_group = loaded_package_impl.filtered_configs_[type_idx];
693 const size_t type_entry_count = (use_filtered) ? filtered_group.type_entries.size()
694 : type_spec->type_entries.size();
695 for (size_t i = 0; i < type_entry_count; i++) {
696 const TypeSpec::TypeEntry* type_entry = (use_filtered) ? filtered_group.type_entries[i]
697 : &type_spec->type_entries[i];
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800698
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800699 // We can skip calling ResTable_config::match() if the caller does not care for the
700 // configuration to match or if we're using the list of types that have already had their
701 // configuration matched.
702 const ResTable_config& this_config = type_entry->config;
703 if (!(use_filtered || ignore_configuration || this_config.match(desired_config))) {
704 continue;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800705 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800706
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800707 Resolution::Step::Type resolution_type;
708 if (best_config == nullptr) {
709 resolution_type = Resolution::Step::Type::INITIAL;
710 } else if (this_config.isBetterThan(*best_config, &desired_config)) {
711 resolution_type = Resolution::Step::Type::BETTER_MATCH;
712 } else if (package_is_loader && this_config.compare(*best_config) == 0) {
713 resolution_type = Resolution::Step::Type::OVERLAID;
714 } else {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000715 if (UNLIKELY(logging_enabled)) {
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800716 resolution_steps.push_back(Resolution::Step{Resolution::Step::Type::SKIPPED,
717 this_config.toString(),
718 &loaded_package->GetPackageName(),
719 cookie});
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800720 }
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800721 continue;
722 }
723
724 // The configuration matches and is better than the previous selection.
725 // Find the entry value if it exists for this configuration.
726 const auto& type = type_entry->type;
727 const auto offset = LoadedPackage::GetEntryOffset(type, entry_idx);
728 if (UNLIKELY(IsIOError(offset))) {
729 return base::unexpected(offset.error());
730 }
731
732 if (!offset.has_value()) {
733 if (UNLIKELY(logging_enabled)) {
734 resolution_steps.push_back(Resolution::Step{Resolution::Step::Type::NO_ENTRY,
735 this_config.toString(),
736 &loaded_package->GetPackageName(),
737 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(),
751 &loaded_package->GetPackageName(),
752 cookie});
753 }
754
755 // Any configuration will suffice, so break.
756 if (stop_at_first_match) {
757 break;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700758 }
759 }
760 }
761
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800762 if (UNLIKELY(best_cookie == kInvalidCookie)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000763 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700764 }
765
Ryan Mitchell80094e32020-11-16 23:08:18 +0000766 auto best_entry_result = LoadedPackage::GetEntryFromOffset(best_type, best_offset);
767 if (!best_entry_result.has_value()) {
768 return base::unexpected(best_entry_result.error());
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800769 }
770
Ryan Mitchell80094e32020-11-16 23:08:18 +0000771 const incfs::map_ptr<ResTable_entry> best_entry = *best_entry_result;
772 if (!best_entry) {
773 return base::unexpected(IOError::PAGES_MISSING);
Ryan Mitchellbf1f45b2020-09-29 17:22:52 -0700774 }
775
Ryan Mitchell80094e32020-11-16 23:08:18 +0000776 const auto entry = GetEntryValue(best_entry.verified());
777 if (!entry.has_value()) {
778 return base::unexpected(entry.error());
779 }
Winson2f3669b2019-01-11 11:28:34 -0800780
Ryan Mitchell80094e32020-11-16 23:08:18 +0000781 return FindEntryResult{
782 .cookie = best_cookie,
783 .entry = *entry,
784 .config = *best_config,
785 .type_flags = type_flags,
786 .package_name = &best_package->GetPackageName(),
787 .type_string_ref = StringPoolRef(best_package->GetTypeStringPool(), best_type->id - 1),
788 .entry_string_ref = StringPoolRef(best_package->GetKeyStringPool(),
789 best_entry->key.index),
790 .dynamic_ref_table = package_group.dynamic_ref_table.get(),
791 };
Adam Lesinski7ad11102016-10-28 16:39:15 -0700792}
793
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700794void AssetManager2::ResetResourceResolution() const {
795 last_resolution_.cookie = kInvalidCookie;
796 last_resolution_.resid = 0;
797 last_resolution_.steps.clear();
798 last_resolution_.type_string_ref = StringPoolRef();
799 last_resolution_.entry_string_ref = StringPoolRef();
800}
801
Winson2f3669b2019-01-11 11:28:34 -0800802void AssetManager2::SetResourceResolutionLoggingEnabled(bool enabled) {
803 resource_resolution_logging_enabled_ = enabled;
Winson2f3669b2019-01-11 11:28:34 -0800804 if (!enabled) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700805 ResetResourceResolution();
Winson2f3669b2019-01-11 11:28:34 -0800806 }
807}
808
809std::string AssetManager2::GetLastResourceResolution() const {
810 if (!resource_resolution_logging_enabled_) {
811 LOG(ERROR) << "Must enable resource resolution logging before getting path.";
Ryan Mitchell80094e32020-11-16 23:08:18 +0000812 return {};
Winson2f3669b2019-01-11 11:28:34 -0800813 }
814
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800815 const ApkAssetsCookie cookie = last_resolution_.cookie;
Winson2f3669b2019-01-11 11:28:34 -0800816 if (cookie == kInvalidCookie) {
817 LOG(ERROR) << "AssetManager hasn't resolved a resource to read resolution path.";
Ryan Mitchell80094e32020-11-16 23:08:18 +0000818 return {};
Winson2f3669b2019-01-11 11:28:34 -0800819 }
820
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800821 const uint32_t resid = last_resolution_.resid;
822 const auto package = apk_assets_[cookie]->GetLoadedArsc()->GetPackageById(get_package_id(resid));
823
Winson2f3669b2019-01-11 11:28:34 -0800824 std::string resource_name_string;
Winson2f3669b2019-01-11 11:28:34 -0800825 if (package != nullptr) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000826 auto resource_name = ToResourceName(last_resolution_.type_string_ref,
827 last_resolution_.entry_string_ref,
828 package->GetPackageName());
829 resource_name_string = resource_name.has_value() ?
830 ToFormattedResourceString(resource_name.value()) : "<unknown>";
Winson2f3669b2019-01-11 11:28:34 -0800831 }
832
833 std::stringstream log_stream;
834 log_stream << base::StringPrintf("Resolution for 0x%08x ", resid)
835 << resource_name_string
836 << "\n\tFor config -"
837 << configuration_.toString();
838
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800839 for (const Resolution::Step& step : last_resolution_.steps) {
840 const static std::unordered_map<Resolution::Step::Type, const char*> kStepStrings = {
841 {Resolution::Step::Type::INITIAL, "Found initial"},
842 {Resolution::Step::Type::BETTER_MATCH, "Found better"},
843 {Resolution::Step::Type::OVERLAID, "Overlaid"},
844 {Resolution::Step::Type::SKIPPED, "Skipped"},
845 {Resolution::Step::Type::NO_ENTRY, "No entry"}
846 };
847
848 const auto prefix = kStepStrings.find(step.type);
849 if (prefix == kStepStrings.end()) {
850 continue;
Winson2f3669b2019-01-11 11:28:34 -0800851 }
852
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800853 log_stream << "\n\t" << prefix->second << ": " << *step.package_name << " ("
Ryan Mitchellef538432021-03-01 14:52:14 -0800854 << apk_assets_[step.cookie]->GetDebugName() << ")";
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800855 if (!step.config_name.isEmpty()) {
856 log_stream << " -" << step.config_name;
Winson2f3669b2019-01-11 11:28:34 -0800857 }
858 }
859
860 return log_stream.str();
861}
862
Ryan Mitchell80094e32020-11-16 23:08:18 +0000863base::expected<AssetManager2::ResourceName, NullOrIOError> AssetManager2::GetResourceName(
864 uint32_t resid) const {
865 auto result = FindEntry(resid, 0u /* density_override */, true /* stop_at_first_match */,
866 true /* ignore_configuration */);
867 if (!result.has_value()) {
868 return base::unexpected(result.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -0700869 }
870
Ryan Mitchell80094e32020-11-16 23:08:18 +0000871 return ToResourceName(result->type_string_ref,
872 result->entry_string_ref,
873 *result->package_name);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700874}
875
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800876base::expected<uint32_t, NullOrIOError> AssetManager2::GetResourceTypeSpecFlags(
877 uint32_t resid) const {
878 auto result = FindEntry(resid, 0u /* density_override */, false /* stop_at_first_match */,
879 true /* ignore_configuration */);
880 if (!result.has_value()) {
881 return base::unexpected(result.error());
882 }
883 return result->type_flags;
884}
885
Ryan Mitchell80094e32020-11-16 23:08:18 +0000886base::expected<AssetManager2::SelectedValue, NullOrIOError> AssetManager2::GetResource(
887 uint32_t resid, bool may_be_bag, uint16_t density_override) const {
888 auto result = FindEntry(resid, density_override, false /* stop_at_first_match */,
889 false /* ignore_configuration */);
890 if (!result.has_value()) {
891 return base::unexpected(result.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -0700892 }
893
Ryan Mitchell80094e32020-11-16 23:08:18 +0000894 auto result_map_entry = std::get_if<incfs::verified_map_ptr<ResTable_map_entry>>(&result->entry);
Ryan Mitchellbf1f45b2020-09-29 17:22:52 -0700895 if (result_map_entry != nullptr) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700896 if (!may_be_bag) {
897 LOG(ERROR) << base::StringPrintf("Resource %08x is a complex map type.", resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000898 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700899 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800900
901 // Create a reference since we can't represent this complex type as a Res_value.
Ryan Mitchell80094e32020-11-16 23:08:18 +0000902 return SelectedValue(Res_value::TYPE_REFERENCE, resid, result->cookie, result->type_flags,
903 resid, result->config);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700904 }
905
Adam Lesinskida431a22016-12-29 16:08:16 -0500906 // Convert the package ID to the runtime assigned package ID.
Ryan Mitchell80094e32020-11-16 23:08:18 +0000907 Res_value value = std::get<Res_value>(result->entry);
908 result->dynamic_ref_table->lookupResourceValue(&value);
Adam Lesinskida431a22016-12-29 16:08:16 -0500909
Ryan Mitchell80094e32020-11-16 23:08:18 +0000910 return SelectedValue(value.dataType, value.data, result->cookie, result->type_flags,
911 resid, result->config);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700912}
913
Ryan Mitchell80094e32020-11-16 23:08:18 +0000914base::expected<std::monostate, NullOrIOError> AssetManager2::ResolveReference(
Ryan Mitchella45506e2020-11-16 23:08:18 +0000915 AssetManager2::SelectedValue& value, bool cache_value) const {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000916 if (value.type != Res_value::TYPE_REFERENCE || value.data == 0U) {
917 // Not a reference. Nothing to do.
918 return {};
Adam Lesinski0c405242017-01-13 20:47:26 -0800919 }
Ryan Mitchell80094e32020-11-16 23:08:18 +0000920
Ryan Mitchella45506e2020-11-16 23:08:18 +0000921 const uint32_t original_flags = value.flags;
922 const uint32_t original_resid = value.data;
923 if (cache_value) {
924 auto cached_value = cached_resolved_values_.find(value.data);
925 if (cached_value != cached_resolved_values_.end()) {
926 value = cached_value->second;
927 value.flags |= original_flags;
928 return {};
929 }
930 }
931
932 uint32_t combined_flags = 0U;
933 uint32_t resolve_resid = original_resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000934 constexpr const uint32_t kMaxIterations = 20;
935 for (uint32_t i = 0U;; i++) {
936 auto result = GetResource(resolve_resid, true /*may_be_bag*/);
937 if (!result.has_value()) {
Ryan Mitchelle7ab6272020-11-13 18:06:15 -0800938 value.resid = resolve_resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000939 return base::unexpected(result.error());
940 }
941
Ryan Mitchelle7ab6272020-11-13 18:06:15 -0800942 // If resource resolution fails, the value should be set to the last reference that was able to
943 // be resolved successfully.
944 value = *result;
945 value.flags |= combined_flags;
946
Ryan Mitchell80094e32020-11-16 23:08:18 +0000947 if (result->type != Res_value::TYPE_REFERENCE ||
948 result->data == Res_value::DATA_NULL_UNDEFINED ||
949 result->data == resolve_resid || i == kMaxIterations) {
950 // This reference can't be resolved, so exit now and let the caller deal with it.
Ryan Mitchella45506e2020-11-16 23:08:18 +0000951 if (cache_value) {
952 cached_resolved_values_[original_resid] = value;
953 }
954
955 // Above value is cached without original_flags to ensure they don't get included in future
956 // queries that hit the cache
957 value.flags |= original_flags;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000958 return {};
959 }
960
Ryan Mitchelle7ab6272020-11-13 18:06:15 -0800961 combined_flags = result->flags;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000962 resolve_resid = result->data;
963 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800964}
965
Ryan Mitchell80094e32020-11-16 23:08:18 +0000966const std::vector<uint32_t> AssetManager2::GetBagResIdStack(uint32_t resid) const {
Aurimas Liutikas8f004c82019-01-17 17:20:10 -0800967 auto cached_iter = cached_bag_resid_stacks_.find(resid);
968 if (cached_iter != cached_bag_resid_stacks_.end()) {
969 return cached_iter->second;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -0800970 }
Ryan Mitchell80094e32020-11-16 23:08:18 +0000971
972 std::vector<uint32_t> found_resids;
973 GetBag(resid, found_resids);
974 cached_bag_resid_stacks_.emplace(resid, found_resids);
975 return found_resids;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -0800976}
977
Ryan Mitchell80094e32020-11-16 23:08:18 +0000978base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::ResolveBag(
979 AssetManager2::SelectedValue& value) const {
980 if (UNLIKELY(value.type != Res_value::TYPE_REFERENCE)) {
981 return base::unexpected(std::nullopt);
982 }
Aurimas Liutikas8f004c82019-01-17 17:20:10 -0800983
Ryan Mitchell80094e32020-11-16 23:08:18 +0000984 auto bag = GetBag(value.data);
985 if (bag.has_value()) {
986 value.flags |= (*bag)->type_spec_flags;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -0800987 }
988 return bag;
y57cd1952018-04-12 14:26:23 -0700989}
990
Ryan Mitchell80094e32020-11-16 23:08:18 +0000991base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::GetBag(uint32_t resid) const {
992 std::vector<uint32_t> found_resids;
993 const auto bag = GetBag(resid, found_resids);
994 cached_bag_resid_stacks_.emplace(resid, found_resids);
995 return bag;
Ryan Mitchell155d5392020-02-10 13:35:24 -0800996}
997
Ryan Mitchell80094e32020-11-16 23:08:18 +0000998base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::GetBag(
999 uint32_t resid, std::vector<uint32_t>& child_resids) const {
1000 if (auto cached_iter = cached_bags_.find(resid); cached_iter != cached_bags_.end()) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001001 return cached_iter->second.get();
1002 }
1003
Ryan Mitchell80094e32020-11-16 23:08:18 +00001004 auto entry = FindEntry(resid, 0u /* density_override */, false /* stop_at_first_match */,
1005 false /* ignore_configuration */);
1006 if (!entry.has_value()) {
1007 return base::unexpected(entry.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001008 }
1009
Ryan Mitchell80094e32020-11-16 23:08:18 +00001010 auto entry_map = std::get_if<incfs::verified_map_ptr<ResTable_map_entry>>(&entry->entry);
1011 if (entry_map == nullptr) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001012 // Not a bag, nothing to do.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001013 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001014 }
1015
Ryan Mitchell80094e32020-11-16 23:08:18 +00001016 auto map = *entry_map;
1017 auto map_entry = map.offset(dtohs(map->size)).convert<ResTable_map>();
1018 const auto map_entry_end = map_entry + dtohl(map->count);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001019
y57cd1952018-04-12 14:26:23 -07001020 // Keep track of ids that have already been seen to prevent infinite loops caused by circular
Ryan Mitchell80094e32020-11-16 23:08:18 +00001021 // dependencies between bags.
y57cd1952018-04-12 14:26:23 -07001022 child_resids.push_back(resid);
1023
Adam Lesinskida431a22016-12-29 16:08:16 -05001024 uint32_t parent_resid = dtohl(map->parent.ident);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001025 if (parent_resid == 0U ||
1026 std::find(child_resids.begin(), child_resids.end(), parent_resid) != child_resids.end()) {
1027 // There is no parent or a circular parental dependency exist, meaning there is nothing to
1028 // inherit and we can do a simple copy of the entries in the map.
Adam Lesinski7ad11102016-10-28 16:39:15 -07001029 const size_t entry_count = map_entry_end - map_entry;
1030 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
1031 malloc(sizeof(ResolvedBag) + (entry_count * sizeof(ResolvedBag::Entry))))};
Ryan Mitchell155d5392020-02-10 13:35:24 -08001032
1033 bool sort_entries = false;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001034 for (auto new_entry = new_bag->entries; map_entry != map_entry_end; ++map_entry) {
1035 if (UNLIKELY(!map_entry)) {
1036 return base::unexpected(IOError::PAGES_MISSING);
1037 }
1038
Adam Lesinskida431a22016-12-29 16:08:16 -05001039 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001040 if (!is_internal_resid(new_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -05001041 // Attributes, arrays, etc don't have a resource id as the name. They specify
1042 // other data, which would be wrong to change via a lookup.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001043 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001044 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
1045 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001046 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001047 }
1048 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001049
1050 new_entry->cookie = entry->cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -05001051 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001052 new_entry->key_pool = nullptr;
1053 new_entry->type_pool = nullptr;
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001054 new_entry->style = resid;
Adam Lesinski30080e22017-10-16 16:18:09 -07001055 new_entry->value.copyFrom_dtoh(map_entry->value);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001056 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1057 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001058 LOG(ERROR) << base::StringPrintf(
1059 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
1060 new_entry->value.data, new_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001061 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001062 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001063
Ryan Mitchell155d5392020-02-10 13:35:24 -08001064 sort_entries = sort_entries ||
1065 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001066 ++new_entry;
1067 }
Ryan Mitchell155d5392020-02-10 13:35:24 -08001068
1069 if (sort_entries) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001070 std::sort(new_bag->entries, new_bag->entries + entry_count,
1071 [](auto&& lhs, auto&& rhs) { return lhs.key < rhs.key; });
Ryan Mitchell155d5392020-02-10 13:35:24 -08001072 }
1073
Ryan Mitchell80094e32020-11-16 23:08:18 +00001074 new_bag->type_spec_flags = entry->type_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001075 new_bag->entry_count = static_cast<uint32_t>(entry_count);
1076 ResolvedBag* result = new_bag.get();
1077 cached_bags_[resid] = std::move(new_bag);
1078 return result;
1079 }
1080
Adam Lesinskida431a22016-12-29 16:08:16 -05001081 // In case the parent is a dynamic reference, resolve it.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001082 entry->dynamic_ref_table->lookupResourceId(&parent_resid);
Adam Lesinskida431a22016-12-29 16:08:16 -05001083
Adam Lesinski7ad11102016-10-28 16:39:15 -07001084 // Get the parent and do a merge of the keys.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001085 const auto parent_bag = GetBag(parent_resid, child_resids);
1086 if (UNLIKELY(!parent_bag.has_value())) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001087 // Failed to get the parent that should exist.
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001088 LOG(ERROR) << base::StringPrintf("Failed to find parent 0x%08x of bag 0x%08x.", parent_resid,
1089 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001090 return base::unexpected(parent_bag.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001091 }
1092
Adam Lesinski7ad11102016-10-28 16:39:15 -07001093 // Create the max possible entries we can make. Once we construct the bag,
1094 // we will realloc to fit to size.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001095 const size_t max_count = (*parent_bag)->entry_count + dtohl(map->count);
George Burgess IV09b119f2017-07-25 15:00:04 -07001096 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
1097 malloc(sizeof(ResolvedBag) + (max_count * sizeof(ResolvedBag::Entry))))};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001098 ResolvedBag::Entry* new_entry = new_bag->entries;
1099
Ryan Mitchell80094e32020-11-16 23:08:18 +00001100 const ResolvedBag::Entry* parent_entry = (*parent_bag)->entries;
1101 const ResolvedBag::Entry* const parent_entry_end = parent_entry + (*parent_bag)->entry_count;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001102
1103 // The keys are expected to be in sorted order. Merge the two bags.
Ryan Mitchell155d5392020-02-10 13:35:24 -08001104 bool sort_entries = false;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001105 while (map_entry != map_entry_end && parent_entry != parent_entry_end) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001106 if (UNLIKELY(!map_entry)) {
1107 return base::unexpected(IOError::PAGES_MISSING);
1108 }
1109
Adam Lesinskida431a22016-12-29 16:08:16 -05001110 uint32_t child_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001111 if (!is_internal_resid(child_key)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001112 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&child_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001113 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", child_key,
1114 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001115 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001116 }
1117 }
1118
Adam Lesinski7ad11102016-10-28 16:39:15 -07001119 if (child_key <= parent_entry->key) {
1120 // Use the child key if it comes before the parent
1121 // or is equal to the parent (overrides).
Ryan Mitchell80094e32020-11-16 23:08:18 +00001122 new_entry->cookie = entry->cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001123 new_entry->key = child_key;
1124 new_entry->key_pool = nullptr;
1125 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -07001126 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001127 new_entry->style = resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001128 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1129 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001130 LOG(ERROR) << base::StringPrintf(
1131 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
1132 new_entry->value.data, child_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001133 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001134 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001135 ++map_entry;
1136 } else {
1137 // Take the parent entry as-is.
1138 memcpy(new_entry, parent_entry, sizeof(*new_entry));
1139 }
1140
Ryan Mitchell155d5392020-02-10 13:35:24 -08001141 sort_entries = sort_entries ||
1142 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001143 if (child_key >= parent_entry->key) {
1144 // Move to the next parent entry if we used it or it was overridden.
1145 ++parent_entry;
1146 }
1147 // Increment to the next entry to fill.
1148 ++new_entry;
1149 }
1150
1151 // Finish the child entries if they exist.
1152 while (map_entry != map_entry_end) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001153 if (UNLIKELY(!map_entry)) {
1154 return base::unexpected(IOError::PAGES_MISSING);
1155 }
1156
Adam Lesinskida431a22016-12-29 16:08:16 -05001157 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001158 if (!is_internal_resid(new_key)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001159 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001160 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
1161 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001162 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001163 }
1164 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001165 new_entry->cookie = entry->cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -05001166 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001167 new_entry->key_pool = nullptr;
1168 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -07001169 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001170 new_entry->style = resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001171 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1172 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001173 LOG(ERROR) << base::StringPrintf("Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.",
1174 new_entry->value.dataType, new_entry->value.data, new_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001175 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001176 }
Ryan Mitchell155d5392020-02-10 13:35:24 -08001177 sort_entries = sort_entries ||
1178 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001179 ++map_entry;
1180 ++new_entry;
1181 }
1182
1183 // Finish the parent entries if they exist.
1184 if (parent_entry != parent_entry_end) {
1185 // Take the rest of the parent entries as-is.
1186 const size_t num_entries_to_copy = parent_entry_end - parent_entry;
1187 memcpy(new_entry, parent_entry, num_entries_to_copy * sizeof(*new_entry));
1188 new_entry += num_entries_to_copy;
1189 }
1190
1191 // Resize the resulting array to fit.
1192 const size_t actual_count = new_entry - new_bag->entries;
1193 if (actual_count != max_count) {
George Burgess IV09b119f2017-07-25 15:00:04 -07001194 new_bag.reset(reinterpret_cast<ResolvedBag*>(realloc(
1195 new_bag.release(), sizeof(ResolvedBag) + (actual_count * sizeof(ResolvedBag::Entry)))));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001196 }
1197
Ryan Mitchell155d5392020-02-10 13:35:24 -08001198 if (sort_entries) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001199 std::sort(new_bag->entries, new_bag->entries + actual_count,
1200 [](auto&& lhs, auto&& rhs) { return lhs.key < rhs.key; });
Ryan Mitchell155d5392020-02-10 13:35:24 -08001201 }
1202
Adam Lesinski1a1e9c22017-10-13 15:45:34 -07001203 // Combine flags from the parent and our own bag.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001204 new_bag->type_spec_flags = entry->type_flags | (*parent_bag)->type_spec_flags;
George Burgess IV09b119f2017-07-25 15:00:04 -07001205 new_bag->entry_count = static_cast<uint32_t>(actual_count);
1206 ResolvedBag* result = new_bag.get();
1207 cached_bags_[resid] = std::move(new_bag);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001208 return result;
1209}
1210
Adam Lesinski929d6512017-01-16 19:11:19 -08001211static bool Utf8ToUtf16(const StringPiece& str, std::u16string* out) {
1212 ssize_t len =
1213 utf8_to_utf16_length(reinterpret_cast<const uint8_t*>(str.data()), str.size(), false);
1214 if (len < 0) {
1215 return false;
1216 }
1217 out->resize(static_cast<size_t>(len));
1218 utf8_to_utf16(reinterpret_cast<const uint8_t*>(str.data()), str.size(), &*out->begin(),
1219 static_cast<size_t>(len + 1));
1220 return true;
1221}
1222
Ryan Mitchell80094e32020-11-16 23:08:18 +00001223base::expected<uint32_t, NullOrIOError> AssetManager2::GetResourceId(
1224 const std::string& resource_name, const std::string& fallback_type,
1225 const std::string& fallback_package) const {
Adam Lesinski929d6512017-01-16 19:11:19 -08001226 StringPiece package_name, type, entry;
1227 if (!ExtractResourceName(resource_name, &package_name, &type, &entry)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001228 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001229 }
1230
1231 if (entry.empty()) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001232 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001233 }
1234
1235 if (package_name.empty()) {
1236 package_name = fallback_package;
1237 }
1238
1239 if (type.empty()) {
1240 type = fallback_type;
1241 }
1242
1243 std::u16string type16;
1244 if (!Utf8ToUtf16(type, &type16)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001245 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001246 }
1247
1248 std::u16string entry16;
1249 if (!Utf8ToUtf16(entry, &entry16)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001250 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001251 }
1252
1253 const StringPiece16 kAttr16 = u"attr";
1254 const static std::u16string kAttrPrivate16 = u"^attr-private";
1255
1256 for (const PackageGroup& package_group : package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001257 for (const ConfiguredPackage& package_impl : package_group.packages_) {
1258 const LoadedPackage* package = package_impl.loaded_package_;
Adam Lesinski929d6512017-01-16 19:11:19 -08001259 if (package_name != package->GetPackageName()) {
1260 // All packages in the same group are expected to have the same package name.
1261 break;
1262 }
1263
Ryan Mitchell80094e32020-11-16 23:08:18 +00001264 base::expected<uint32_t, NullOrIOError> resid = package->FindEntryByName(type16, entry16);
1265 if (UNLIKELY(IsIOError(resid))) {
1266 return base::unexpected(resid.error());
1267 }
1268
1269 if (!resid.has_value() && kAttr16 == type16) {
Adam Lesinski929d6512017-01-16 19:11:19 -08001270 // Private attributes in libraries (such as the framework) are sometimes encoded
1271 // under the type '^attr-private' in order to leave the ID space of public 'attr'
1272 // free for future additions. Check '^attr-private' for the same name.
1273 resid = package->FindEntryByName(kAttrPrivate16, entry16);
1274 }
1275
Ryan Mitchell80094e32020-11-16 23:08:18 +00001276 if (resid.has_value()) {
1277 return fix_package_id(*resid, package_group.dynamic_ref_table->mAssignedPackageId);
Adam Lesinski929d6512017-01-16 19:11:19 -08001278 }
1279 }
1280 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001281 return base::unexpected(std::nullopt);
Adam Lesinski0c405242017-01-13 20:47:26 -08001282}
1283
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001284void AssetManager2::RebuildFilterList() {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001285 for (PackageGroup& group : package_groups_) {
1286 for (ConfiguredPackage& impl : group.packages_) {
1287 // Destroy it.
1288 impl.filtered_configs_.~ByteBucketArray();
1289
1290 // Re-create it.
1291 new (&impl.filtered_configs_) ByteBucketArray<FilteredConfigGroup>();
1292
1293 // Create the filters here.
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001294 impl.loaded_package_->ForEachTypeSpec([&](const TypeSpec& type_spec, uint8_t type_id) {
1295 FilteredConfigGroup& group = impl.filtered_configs_.editItemAt(type_id - 1);
1296 for (const auto& type_entry : type_spec.type_entries) {
1297 if (type_entry.config.match(configuration_)) {
1298 group.type_entries.push_back(&type_entry);
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001299 }
1300 }
1301 });
1302 }
1303 }
1304}
1305
Adam Lesinski7ad11102016-10-28 16:39:15 -07001306void AssetManager2::InvalidateCaches(uint32_t diff) {
Ryan Mitchell2c4d8742019-03-04 09:41:00 -08001307 cached_bag_resid_stacks_.clear();
1308
Adam Lesinski7ad11102016-10-28 16:39:15 -07001309 if (diff == 0xffffffffu) {
1310 // Everything must go.
1311 cached_bags_.clear();
1312 return;
1313 }
1314
1315 // Be more conservative with what gets purged. Only if the bag has other possible
1316 // variations with respect to what changed (diff) should we remove it.
1317 for (auto iter = cached_bags_.cbegin(); iter != cached_bags_.cend();) {
1318 if (diff & iter->second->type_spec_flags) {
1319 iter = cached_bags_.erase(iter);
1320 } else {
1321 ++iter;
1322 }
1323 }
Ryan Mitchella45506e2020-11-16 23:08:18 +00001324
1325 cached_resolved_values_.clear();
Adam Lesinski7ad11102016-10-28 16:39:15 -07001326}
1327
Ryan Mitchell2e394222019-08-28 12:10:51 -07001328uint8_t AssetManager2::GetAssignedPackageId(const LoadedPackage* package) const {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001329 for (auto& package_group : package_groups_) {
1330 for (auto& package2 : package_group.packages_) {
1331 if (package2.loaded_package_ == package) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -07001332 return package_group.dynamic_ref_table->mAssignedPackageId;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001333 }
1334 }
1335 }
1336 return 0;
1337}
1338
Adam Lesinski30080e22017-10-16 16:18:09 -07001339std::unique_ptr<Theme> AssetManager2::NewTheme() {
1340 return std::unique_ptr<Theme>(new Theme(this));
1341}
1342
1343Theme::Theme(AssetManager2* asset_manager) : asset_manager_(asset_manager) {
1344}
1345
1346Theme::~Theme() = default;
1347
1348namespace {
1349
1350struct ThemeEntry {
1351 ApkAssetsCookie cookie;
1352 uint32_t type_spec_flags;
1353 Res_value value;
1354};
1355
1356struct ThemeType {
1357 int entry_count;
1358 ThemeEntry entries[0];
1359};
1360
1361constexpr size_t kTypeCount = std::numeric_limits<uint8_t>::max() + 1;
1362
1363} // namespace
1364
1365struct Theme::Package {
1366 // Each element of Type will be a dynamically sized object
1367 // allocated to have the entries stored contiguously with the Type.
1368 std::array<util::unique_cptr<ThemeType>, kTypeCount> types;
1369};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001370
Ryan Mitchell80094e32020-11-16 23:08:18 +00001371base::expected<std::monostate, NullOrIOError> Theme::ApplyStyle(uint32_t resid, bool force) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001372 ATRACE_NAME("Theme::ApplyStyle");
Adam Lesinski7ad11102016-10-28 16:39:15 -07001373
Ryan Mitchell80094e32020-11-16 23:08:18 +00001374 auto bag = asset_manager_->GetBag(resid);
1375 if (!bag.has_value()) {
1376 return base::unexpected(bag.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001377 }
1378
1379 // Merge the flags from this style.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001380 type_spec_flags_ |= (*bag)->type_spec_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001381
Adam Lesinski30080e22017-10-16 16:18:09 -07001382 int last_type_idx = -1;
1383 int last_package_idx = -1;
1384 Package* last_package = nullptr;
1385 ThemeType* last_type = nullptr;
1386
1387 // Iterate backwards, because each bag is sorted in ascending key ID order, meaning we will only
1388 // need to perform one resize per type.
1389 using reverse_bag_iterator = std::reverse_iterator<const ResolvedBag::Entry*>;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001390 const auto rbegin = reverse_bag_iterator(begin(*bag));
1391 for (auto it = reverse_bag_iterator(end(*bag)); it != rbegin; ++it) {
1392 const uint32_t attr_resid = it->key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001393
Adam Lesinski30080e22017-10-16 16:18:09 -07001394 // If the resource ID passed in is not a style, the key can be some other identifier that is not
1395 // a resource ID. We should fail fast instead of operating with strange resource IDs.
Adam Lesinski929d6512017-01-16 19:11:19 -08001396 if (!is_valid_resid(attr_resid)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001397 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001398 }
1399
Adam Lesinski30080e22017-10-16 16:18:09 -07001400 // We don't use the 0-based index for the type so that we can avoid doing ID validation
1401 // upon lookup. Instead, we keep space for the type ID 0 in our data structures. Since
1402 // the construction of this type is guarded with a resource ID check, it will never be
1403 // populated, and querying type ID 0 will always fail.
1404 const int package_idx = get_package_id(attr_resid);
1405 const int type_idx = get_type_id(attr_resid);
1406 const int entry_idx = get_entry_id(attr_resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001407
Adam Lesinski30080e22017-10-16 16:18:09 -07001408 if (last_package_idx != package_idx) {
1409 std::unique_ptr<Package>& package = packages_[package_idx];
1410 if (package == nullptr) {
1411 package.reset(new Package());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001412 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001413 last_package_idx = package_idx;
1414 last_package = package.get();
1415 last_type_idx = -1;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001416 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001417
1418 if (last_type_idx != type_idx) {
1419 util::unique_cptr<ThemeType>& type = last_package->types[type_idx];
1420 if (type == nullptr) {
1421 // Allocate enough memory to contain this entry_idx. Since we're iterating in reverse over
1422 // a sorted list of attributes, this shouldn't be resized again during this method call.
1423 type.reset(reinterpret_cast<ThemeType*>(
1424 calloc(sizeof(ThemeType) + (entry_idx + 1) * sizeof(ThemeEntry), 1)));
1425 type->entry_count = entry_idx + 1;
1426 } else if (entry_idx >= type->entry_count) {
1427 // Reallocate the memory to contain this entry_idx. Since we're iterating in reverse over
1428 // a sorted list of attributes, this shouldn't be resized again during this method call.
1429 const int new_count = entry_idx + 1;
1430 type.reset(reinterpret_cast<ThemeType*>(
1431 realloc(type.release(), sizeof(ThemeType) + (new_count * sizeof(ThemeEntry)))));
1432
1433 // Clear out the newly allocated space (which isn't zeroed).
1434 memset(type->entries + type->entry_count, 0,
1435 (new_count - type->entry_count) * sizeof(ThemeEntry));
1436 type->entry_count = new_count;
1437 }
1438 last_type_idx = type_idx;
1439 last_type = type.get();
1440 }
1441
1442 ThemeEntry& entry = last_type->entries[entry_idx];
1443 if (force || (entry.value.dataType == Res_value::TYPE_NULL &&
1444 entry.value.data != Res_value::DATA_NULL_EMPTY)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001445 entry.cookie = it->cookie;
1446 entry.type_spec_flags |= (*bag)->type_spec_flags;
1447 entry.value = it->value;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001448 }
1449 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001450 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001451}
1452
Ryan Mitchell80094e32020-11-16 23:08:18 +00001453std::optional<AssetManager2::SelectedValue> Theme::GetAttribute(uint32_t resid) const {
1454
Adam Lesinski30080e22017-10-16 16:18:09 -07001455 int cnt = 20;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001456 uint32_t type_spec_flags = 0u;
Adam Lesinski30080e22017-10-16 16:18:09 -07001457 do {
1458 const int package_idx = get_package_id(resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001459 const Package* package = packages_[package_idx].get();
Adam Lesinski30080e22017-10-16 16:18:09 -07001460 if (package != nullptr) {
1461 // The themes are constructed with a 1-based type ID, so no need to decrement here.
1462 const int type_idx = get_type_id(resid);
1463 const ThemeType* type = package->types[type_idx].get();
1464 if (type != nullptr) {
1465 const int entry_idx = get_entry_id(resid);
1466 if (entry_idx < type->entry_count) {
1467 const ThemeEntry& entry = type->entries[entry_idx];
1468 type_spec_flags |= entry.type_spec_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001469
Adam Lesinski30080e22017-10-16 16:18:09 -07001470 if (entry.value.dataType == Res_value::TYPE_ATTRIBUTE) {
1471 if (cnt > 0) {
1472 cnt--;
1473 resid = entry.value.data;
1474 continue;
1475 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001476 return std::nullopt;
Adam Lesinski30080e22017-10-16 16:18:09 -07001477 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001478
Adam Lesinski30080e22017-10-16 16:18:09 -07001479 // @null is different than @empty.
1480 if (entry.value.dataType == Res_value::TYPE_NULL &&
1481 entry.value.data != Res_value::DATA_NULL_EMPTY) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001482 return std::nullopt;
Adam Lesinski30080e22017-10-16 16:18:09 -07001483 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001484
Ryan Mitchell80094e32020-11-16 23:08:18 +00001485 return AssetManager2::SelectedValue(entry.value.dataType, entry.value.data, entry.cookie,
1486 type_spec_flags, 0U /* resid */, {} /* config */);
Adam Lesinskida431a22016-12-29 16:08:16 -05001487 }
Adam Lesinskida431a22016-12-29 16:08:16 -05001488 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001489 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001490 break;
1491 } while (true);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001492 return std::nullopt;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001493}
1494
Ryan Mitchell80094e32020-11-16 23:08:18 +00001495base::expected<std::monostate, NullOrIOError> Theme::ResolveAttributeReference(
1496 AssetManager2::SelectedValue& value) const {
1497 if (value.type != Res_value::TYPE_ATTRIBUTE) {
1498 return asset_manager_->ResolveReference(value);
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001499 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001500
1501 std::optional<AssetManager2::SelectedValue> result = GetAttribute(value.data);
1502 if (!result.has_value()) {
1503 return base::unexpected(std::nullopt);
1504 }
1505
Ryan Mitchella45506e2020-11-16 23:08:18 +00001506 auto resolve_result = asset_manager_->ResolveReference(*result, true /* cache_value */);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001507 if (resolve_result.has_value()) {
1508 result->flags |= value.flags;
1509 value = *result;
1510 }
1511 return resolve_result;
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001512}
1513
Adam Lesinski7ad11102016-10-28 16:39:15 -07001514void Theme::Clear() {
1515 type_spec_flags_ = 0u;
1516 for (std::unique_ptr<Package>& package : packages_) {
1517 package.reset();
1518 }
1519}
1520
Ryan Mitchell80094e32020-11-16 23:08:18 +00001521base::expected<std::monostate, IOError> Theme::SetTo(const Theme& o) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001522 if (this == &o) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001523 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001524 }
1525
Adam Lesinski7ad11102016-10-28 16:39:15 -07001526 type_spec_flags_ = o.type_spec_flags_;
1527
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001528 if (asset_manager_ == o.asset_manager_) {
1529 // The theme comes from the same asset manager so all theme data can be copied exactly
1530 for (size_t p = 0; p < packages_.size(); p++) {
1531 const Package *package = o.packages_[p].get();
1532 if (package == nullptr) {
1533 // The other theme doesn't have this package, clear ours.
1534 packages_[p].reset();
Adam Lesinski7ad11102016-10-28 16:39:15 -07001535 continue;
1536 }
1537
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001538 if (packages_[p] == nullptr) {
1539 // The other theme has this package, but we don't. Make one.
1540 packages_[p].reset(new Package());
1541 }
1542
1543 for (size_t t = 0; t < package->types.size(); t++) {
1544 const ThemeType *type = package->types[t].get();
1545 if (type == nullptr) {
1546 // The other theme doesn't have this type, clear ours.
1547 packages_[p]->types[t].reset();
1548 continue;
1549 }
1550
1551 // Create a new type and update it to theirs.
1552 const size_t type_alloc_size = sizeof(ThemeType) + (type->entry_count * sizeof(ThemeEntry));
1553 void *copied_data = malloc(type_alloc_size);
1554 memcpy(copied_data, type, type_alloc_size);
1555 packages_[p]->types[t].reset(reinterpret_cast<ThemeType *>(copied_data));
1556 }
1557 }
1558 } else {
1559 std::map<ApkAssetsCookie, ApkAssetsCookie> src_to_dest_asset_cookies;
1560 typedef std::map<int, int> SourceToDestinationRuntimePackageMap;
1561 std::map<ApkAssetsCookie, SourceToDestinationRuntimePackageMap> src_asset_cookie_id_map;
1562
Ryan Mitchell93bca972019-03-08 17:26:28 -08001563 // Determine which ApkAssets are loaded in both theme AssetManagers.
Ryan Mitchellef538432021-03-01 14:52:14 -08001564 const auto src_assets = o.asset_manager_->GetApkAssets();
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001565 for (size_t i = 0; i < src_assets.size(); i++) {
1566 const ApkAssets* src_asset = src_assets[i];
1567
Ryan Mitchellef538432021-03-01 14:52:14 -08001568 const auto dest_assets = asset_manager_->GetApkAssets();
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001569 for (size_t j = 0; j < dest_assets.size(); j++) {
1570 const ApkAssets* dest_asset = dest_assets[j];
Ryan Mitchellef538432021-03-01 14:52:14 -08001571 if (src_asset != dest_asset) {
1572 // ResourcesManager caches and reuses ApkAssets when the same apk must be present in
1573 // multiple AssetManagers. Two ApkAssets point to the same version of the same resources
1574 // if they are the same instance.
1575 continue;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001576 }
Ryan Mitchellef538432021-03-01 14:52:14 -08001577
1578 // Map the package ids of the asset in the source AssetManager to the package ids of the
1579 // asset in th destination AssetManager.
1580 SourceToDestinationRuntimePackageMap package_map;
1581 for (const auto& loaded_package : src_asset->GetLoadedArsc()->GetPackages()) {
1582 const int src_package_id = o.asset_manager_->GetAssignedPackageId(loaded_package.get());
1583 const int dest_package_id = asset_manager_->GetAssignedPackageId(loaded_package.get());
1584 package_map[src_package_id] = dest_package_id;
1585 }
1586
1587 src_to_dest_asset_cookies.insert(std::make_pair(i, j));
1588 src_asset_cookie_id_map.insert(std::make_pair(i, package_map));
1589 break;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001590 }
1591 }
1592
Ryan Mitchell93bca972019-03-08 17:26:28 -08001593 // Reset the data in the destination theme.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001594 for (size_t p = 0; p < packages_.size(); p++) {
1595 if (packages_[p] != nullptr) {
1596 packages_[p].reset();
1597 }
1598 }
1599
1600 for (size_t p = 0; p < packages_.size(); p++) {
1601 const Package *package = o.packages_[p].get();
1602 if (package == nullptr) {
1603 continue;
1604 }
1605
1606 for (size_t t = 0; t < package->types.size(); t++) {
1607 const ThemeType *type = package->types[t].get();
1608 if (type == nullptr) {
1609 continue;
1610 }
1611
1612 for (size_t e = 0; e < type->entry_count; e++) {
1613 const ThemeEntry &entry = type->entries[e];
1614 if (entry.value.dataType == Res_value::TYPE_NULL &&
1615 entry.value.data != Res_value::DATA_NULL_EMPTY) {
1616 continue;
1617 }
1618
Ryan Mitchell93bca972019-03-08 17:26:28 -08001619 bool is_reference = (entry.value.dataType == Res_value::TYPE_ATTRIBUTE
1620 || entry.value.dataType == Res_value::TYPE_REFERENCE
1621 || entry.value.dataType == Res_value::TYPE_DYNAMIC_ATTRIBUTE
1622 || entry.value.dataType == Res_value::TYPE_DYNAMIC_REFERENCE)
1623 && entry.value.data != 0x0;
Ryan Mitchellb85d9b22018-11-19 12:11:38 -08001624
Ryan Mitchell93bca972019-03-08 17:26:28 -08001625 // If the attribute value represents an attribute or reference, the package id of the
1626 // value needs to be rewritten to the package id of the value in the destination.
1627 uint32_t attribute_data = entry.value.data;
1628 if (is_reference) {
1629 // Determine the package id of the reference in the destination AssetManager.
Ryan Mitchellb85d9b22018-11-19 12:11:38 -08001630 auto value_package_map = src_asset_cookie_id_map.find(entry.cookie);
1631 if (value_package_map == src_asset_cookie_id_map.end()) {
1632 continue;
1633 }
1634
1635 auto value_dest_package = value_package_map->second.find(
1636 get_package_id(entry.value.data));
1637 if (value_dest_package == value_package_map->second.end()) {
1638 continue;
1639 }
1640
Ryan Mitchell93bca972019-03-08 17:26:28 -08001641 attribute_data = fix_package_id(entry.value.data, value_dest_package->second);
1642 }
1643
1644 // Find the cookie of the value in the destination. If the source apk is not loaded in the
1645 // destination, only copy resources that do not reference resources in the source.
1646 ApkAssetsCookie data_dest_cookie;
1647 auto value_dest_cookie = src_to_dest_asset_cookies.find(entry.cookie);
1648 if (value_dest_cookie != src_to_dest_asset_cookies.end()) {
1649 data_dest_cookie = value_dest_cookie->second;
1650 } else {
1651 if (is_reference || entry.value.dataType == Res_value::TYPE_STRING) {
1652 continue;
1653 } else {
1654 data_dest_cookie = 0x0;
1655 }
Ryan Mitchellb85d9b22018-11-19 12:11:38 -08001656 }
1657
1658 // The package id of the attribute needs to be rewritten to the package id of the
Ryan Mitchell93bca972019-03-08 17:26:28 -08001659 // attribute in the destination.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001660 int attribute_dest_package_id = p;
1661 if (attribute_dest_package_id != 0x01) {
Ryan Mitchell93bca972019-03-08 17:26:28 -08001662 // Find the cookie of the attribute resource id in the source AssetManager
Ryan Mitchell80094e32020-11-16 23:08:18 +00001663 base::expected<FindEntryResult, NullOrIOError> attribute_entry_result =
Ryan Mitchella55dc2e2019-01-24 10:58:23 -08001664 o.asset_manager_->FindEntry(make_resid(p, t, e), 0 /* density_override */ ,
1665 true /* stop_at_first_match */,
Ryan Mitchell80094e32020-11-16 23:08:18 +00001666 true /* ignore_configuration */);
1667 if (UNLIKELY(IsIOError(attribute_entry_result))) {
1668 return base::unexpected(GetIOError(attribute_entry_result.error()));
1669 }
1670 if (!attribute_entry_result.has_value()) {
1671 continue;
1672 }
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001673
Ryan Mitchell93bca972019-03-08 17:26:28 -08001674 // Determine the package id of the attribute in the destination AssetManager.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001675 auto attribute_package_map = src_asset_cookie_id_map.find(
1676 attribute_entry_result->cookie);
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001677 if (attribute_package_map == src_asset_cookie_id_map.end()) {
1678 continue;
1679 }
1680 auto attribute_dest_package = attribute_package_map->second.find(
1681 attribute_dest_package_id);
1682 if (attribute_dest_package == attribute_package_map->second.end()) {
1683 continue;
1684 }
1685 attribute_dest_package_id = attribute_dest_package->second;
1686 }
1687
Ryan Mitchell93bca972019-03-08 17:26:28 -08001688 // Lazily instantiate the destination package.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001689 std::unique_ptr<Package>& dest_package = packages_[attribute_dest_package_id];
1690 if (dest_package == nullptr) {
1691 dest_package.reset(new Package());
1692 }
1693
Ryan Mitchell93bca972019-03-08 17:26:28 -08001694 // Lazily instantiate and resize the destination type.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001695 util::unique_cptr<ThemeType>& dest_type = dest_package->types[t];
1696 if (dest_type == nullptr || dest_type->entry_count < type->entry_count) {
1697 const size_t type_alloc_size = sizeof(ThemeType)
1698 + (type->entry_count * sizeof(ThemeEntry));
1699 void* dest_data = malloc(type_alloc_size);
1700 memset(dest_data, 0, type->entry_count * sizeof(ThemeEntry));
1701
Ryan Mitchell93bca972019-03-08 17:26:28 -08001702 // Copy the existing destination type values if the type is resized.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001703 if (dest_type != nullptr) {
1704 memcpy(dest_data, type, sizeof(ThemeType)
1705 + (dest_type->entry_count * sizeof(ThemeEntry)));
1706 }
1707
1708 dest_type.reset(reinterpret_cast<ThemeType *>(dest_data));
1709 dest_type->entry_count = type->entry_count;
1710 }
1711
Ryan Mitchell93bca972019-03-08 17:26:28 -08001712 dest_type->entries[e].cookie = data_dest_cookie;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001713 dest_type->entries[e].value.dataType = entry.value.dataType;
Ryan Mitchell93bca972019-03-08 17:26:28 -08001714 dest_type->entries[e].value.data = attribute_data;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001715 dest_type->entries[e].type_spec_flags = entry.type_spec_flags;
1716 }
1717 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001718 }
1719 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001720 return {};
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001721}
1722
1723void Theme::Dump() const {
1724 base::ScopedLogSeverity _log(base::INFO);
1725 LOG(INFO) << base::StringPrintf("Theme(this=%p, AssetManager2=%p)", this, asset_manager_);
1726
1727 for (int p = 0; p < packages_.size(); p++) {
1728 auto& package = packages_[p];
1729 if (package == nullptr) {
1730 continue;
1731 }
1732
1733 for (int t = 0; t < package->types.size(); t++) {
1734 auto& type = package->types[t];
1735 if (type == nullptr) {
1736 continue;
1737 }
1738
1739 for (int e = 0; e < type->entry_count; e++) {
1740 auto& entry = type->entries[e];
1741 if (entry.value.dataType == Res_value::TYPE_NULL &&
1742 entry.value.data != Res_value::DATA_NULL_EMPTY) {
1743 continue;
1744 }
1745
1746 LOG(INFO) << base::StringPrintf(" entry(0x%08x)=(0x%08x) type=(0x%02x), cookie(%d)",
1747 make_resid(p, t, e), entry.value.data,
1748 entry.value.dataType, entry.cookie);
1749 }
1750 }
1751 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001752}
1753
1754} // namespace android