blob: 8bab73cd15f09fa8998f28e73ce17b2098d2ea27 [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
105bool AssetManager2::SetApkAssets(const std::vector<const ApkAssets*>& apk_assets,
Mårten Kongstad668ec5b2018-06-11 14:11:33 +0200106 bool invalidate_caches, bool filter_incompatible_configs) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700107 apk_assets_ = apk_assets;
Adam Lesinskida431a22016-12-29 16:08:16 -0500108 BuildDynamicRefTable();
Mårten Kongstad668ec5b2018-06-11 14:11:33 +0200109 RebuildFilterList(filter_incompatible_configs);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700110 if (invalidate_caches) {
111 InvalidateCaches(static_cast<uint32_t>(-1));
112 }
113 return true;
114}
115
Adam Lesinskida431a22016-12-29 16:08:16 -0500116void AssetManager2::BuildDynamicRefTable() {
117 package_groups_.clear();
118 package_ids_.fill(0xff);
119
Ryan Mitchellb894c272020-02-12 10:31:44 -0800120 // A mapping from apk assets path to the runtime package id of its first loaded package.
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700121 std::unordered_map<std::string, uint8_t> apk_assets_package_ids;
122
Ryan Mitchell824cc492020-02-12 10:48:14 -0800123 // Overlay resources are not directly referenced by an application so their resource ids
124 // can change throughout the application's lifetime. Assign overlay package ids last.
125 std::vector<const ApkAssets*> sorted_apk_assets(apk_assets_);
126 std::stable_partition(sorted_apk_assets.begin(), sorted_apk_assets.end(), [](const ApkAssets* a) {
127 return !a->IsOverlay();
128 });
129
130 // The assets cookie must map to the position of the apk assets in the unsorted apk assets list.
131 std::unordered_map<const ApkAssets*, ApkAssetsCookie> apk_assets_cookies;
132 apk_assets_cookies.reserve(apk_assets_.size());
133 for (size_t i = 0, n = apk_assets_.size(); i < n; i++) {
134 apk_assets_cookies[apk_assets_[i]] = static_cast<ApkAssetsCookie>(i);
135 }
136
Ryan Mitchellb894c272020-02-12 10:31:44 -0800137 // 0x01 is reserved for the android package.
138 int next_package_id = 0x02;
Ryan Mitchell824cc492020-02-12 10:48:14 -0800139 for (const ApkAssets* apk_assets : sorted_apk_assets) {
Ryan Mitchellb894c272020-02-12 10:31:44 -0800140 const LoadedArsc* loaded_arsc = apk_assets->GetLoadedArsc();
Ryan Mitchellb894c272020-02-12 10:31:44 -0800141 for (const std::unique_ptr<const LoadedPackage>& package : loaded_arsc->GetPackages()) {
142 // Get the package ID or assign one if a shared library.
143 int package_id;
144 if (package->IsDynamic()) {
145 package_id = next_package_id++;
146 } else {
147 package_id = package->GetPackageId();
Adam Lesinskida431a22016-12-29 16:08:16 -0500148 }
149
150 // Add the mapping for package ID to index if not present.
151 uint8_t idx = package_ids_[package_id];
152 if (idx == 0xff) {
153 package_ids_[package_id] = idx = static_cast<uint8_t>(package_groups_.size());
154 package_groups_.push_back({});
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700155
156 if (apk_assets->IsOverlay()) {
157 // The target package must precede the overlay package in the apk assets paths in order
158 // to take effect.
159 const auto& loaded_idmap = apk_assets->GetLoadedIdmap();
160 auto target_package_iter = apk_assets_package_ids.find(loaded_idmap->TargetApkPath());
Ryan Mitchellee4a5642019-10-16 08:32:55 -0700161 if (target_package_iter == apk_assets_package_ids.end()) {
162 LOG(INFO) << "failed to find target package for overlay "
163 << loaded_idmap->OverlayApkPath();
164 } else {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700165 const uint8_t target_package_id = target_package_iter->second;
166 const uint8_t target_idx = package_ids_[target_package_id];
167 CHECK(target_idx != 0xff) << "overlay added to apk_assets_package_ids but does not"
168 << " have an assigned package group";
169
170 PackageGroup& target_package_group = package_groups_[target_idx];
171
Ryan Mitchell824cc492020-02-12 10:48:14 -0800172 // Create a special dynamic reference table for the overlay to rewrite references to
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700173 // overlay resources as references to the target resources they overlay.
174 auto overlay_table = std::make_shared<OverlayDynamicRefTable>(
175 loaded_idmap->GetOverlayDynamicRefTable(target_package_id));
176 package_groups_.back().dynamic_ref_table = overlay_table;
177
178 // Add the overlay resource map to the target package's set of overlays.
179 target_package_group.overlays_.push_back(
180 ConfiguredOverlay{loaded_idmap->GetTargetResourcesMap(target_package_id,
181 overlay_table.get()),
Ryan Mitchell824cc492020-02-12 10:48:14 -0800182 apk_assets_cookies[apk_assets]});
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700183 }
184 }
185
186 DynamicRefTable* ref_table = package_groups_.back().dynamic_ref_table.get();
187 ref_table->mAssignedPackageId = package_id;
188 ref_table->mAppAsLib = package->IsDynamic() && package->GetPackageId() == 0x7f;
Adam Lesinskida431a22016-12-29 16:08:16 -0500189 }
190 PackageGroup* package_group = &package_groups_[idx];
191
192 // Add the package and to the set of packages with the same ID.
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800193 package_group->packages_.push_back(ConfiguredPackage{package.get(), {}});
Ryan Mitchell824cc492020-02-12 10:48:14 -0800194 package_group->cookies_.push_back(apk_assets_cookies[apk_assets]);
Adam Lesinskida431a22016-12-29 16:08:16 -0500195
196 // Add the package name -> build time ID mappings.
197 for (const DynamicPackageEntry& entry : package->GetDynamicPackageMap()) {
198 String16 package_name(entry.package_name.c_str(), entry.package_name.size());
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700199 package_group->dynamic_ref_table->mEntries.replaceValueFor(
Adam Lesinskida431a22016-12-29 16:08:16 -0500200 package_name, static_cast<uint8_t>(entry.package_id));
201 }
Ryan Mitchellb894c272020-02-12 10:31:44 -0800202
203 apk_assets_package_ids.insert(std::make_pair(apk_assets->GetPath(), package_id));
Adam Lesinskida431a22016-12-29 16:08:16 -0500204 }
205 }
206
207 // Now assign the runtime IDs so that we have a build-time to runtime ID map.
208 const auto package_groups_end = package_groups_.end();
209 for (auto iter = package_groups_.begin(); iter != package_groups_end; ++iter) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800210 const std::string& package_name = iter->packages_[0].loaded_package_->GetPackageName();
Adam Lesinskida431a22016-12-29 16:08:16 -0500211 for (auto iter2 = package_groups_.begin(); iter2 != package_groups_end; ++iter2) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700212 iter2->dynamic_ref_table->addMapping(String16(package_name.c_str(), package_name.size()),
213 iter->dynamic_ref_table->mAssignedPackageId);
Adam Lesinskida431a22016-12-29 16:08:16 -0500214 }
215 }
216}
217
218void AssetManager2::DumpToLog() const {
219 base::ScopedLogSeverity _log(base::INFO);
220
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800221 LOG(INFO) << base::StringPrintf("AssetManager2(this=%p)", this);
222
Adam Lesinskida431a22016-12-29 16:08:16 -0500223 std::string list;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800224 for (const auto& apk_assets : apk_assets_) {
225 base::StringAppendF(&list, "%s,", apk_assets->GetPath().c_str());
226 }
227 LOG(INFO) << "ApkAssets: " << list;
228
229 list = "";
Adam Lesinskida431a22016-12-29 16:08:16 -0500230 for (size_t i = 0; i < package_ids_.size(); i++) {
231 if (package_ids_[i] != 0xff) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800232 base::StringAppendF(&list, "%02x -> %d, ", (int)i, package_ids_[i]);
Adam Lesinskida431a22016-12-29 16:08:16 -0500233 }
234 }
235 LOG(INFO) << "Package ID map: " << list;
236
Adam Lesinski0dd36992018-01-25 15:38:38 -0800237 for (const auto& package_group: package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800238 list = "";
239 for (const auto& package : package_group.packages_) {
240 const LoadedPackage* loaded_package = package.loaded_package_;
241 base::StringAppendF(&list, "%s(%02x%s), ", loaded_package->GetPackageName().c_str(),
242 loaded_package->GetPackageId(),
243 (loaded_package->IsDynamic() ? " dynamic" : ""));
244 }
245 LOG(INFO) << base::StringPrintf("PG (%02x): ",
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700246 package_group.dynamic_ref_table->mAssignedPackageId)
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800247 << list;
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800248
249 for (size_t i = 0; i < 256; i++) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700250 if (package_group.dynamic_ref_table->mLookupTable[i] != 0) {
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800251 LOG(INFO) << base::StringPrintf(" e[0x%02x] -> 0x%02x", (uint8_t) i,
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700252 package_group.dynamic_ref_table->mLookupTable[i]);
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800253 }
254 }
Adam Lesinskida431a22016-12-29 16:08:16 -0500255 }
256}
Adam Lesinski7ad11102016-10-28 16:39:15 -0700257
258const ResStringPool* AssetManager2::GetStringPoolForCookie(ApkAssetsCookie cookie) const {
259 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
260 return nullptr;
261 }
262 return apk_assets_[cookie]->GetLoadedArsc()->GetStringPool();
263}
264
Adam Lesinskida431a22016-12-29 16:08:16 -0500265const DynamicRefTable* AssetManager2::GetDynamicRefTableForPackage(uint32_t package_id) const {
266 if (package_id >= package_ids_.size()) {
267 return nullptr;
268 }
269
270 const size_t idx = package_ids_[package_id];
271 if (idx == 0xff) {
272 return nullptr;
273 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700274 return package_groups_[idx].dynamic_ref_table.get();
Adam Lesinskida431a22016-12-29 16:08:16 -0500275}
276
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700277std::shared_ptr<const DynamicRefTable> AssetManager2::GetDynamicRefTableForCookie(
278 ApkAssetsCookie cookie) const {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800279 for (const PackageGroup& package_group : package_groups_) {
280 for (const ApkAssetsCookie& package_cookie : package_group.cookies_) {
281 if (package_cookie == cookie) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700282 return package_group.dynamic_ref_table;
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800283 }
284 }
285 }
286 return nullptr;
287}
288
Mårten Kongstadc92c4dd2019-02-05 01:29:59 +0100289const std::unordered_map<std::string, std::string>*
290 AssetManager2::GetOverlayableMapForPackage(uint32_t package_id) const {
291
292 if (package_id >= package_ids_.size()) {
293 return nullptr;
294 }
295
296 const size_t idx = package_ids_[package_id];
297 if (idx == 0xff) {
298 return nullptr;
299 }
300
301 const PackageGroup& package_group = package_groups_[idx];
Ryan Mitchell80094e32020-11-16 23:08:18 +0000302 if (package_group.packages_.empty()) {
Mårten Kongstadc92c4dd2019-02-05 01:29:59 +0100303 return nullptr;
304 }
305
306 const auto loaded_package = package_group.packages_[0].loaded_package_;
307 return &loaded_package->GetOverlayableMap();
308}
309
Ryan Mitchell2e394222019-08-28 12:10:51 -0700310bool AssetManager2::GetOverlayablesToString(const android::StringPiece& package_name,
311 std::string* out) const {
312 uint8_t package_id = 0U;
313 for (const auto& apk_assets : apk_assets_) {
314 const LoadedArsc* loaded_arsc = apk_assets->GetLoadedArsc();
315 if (loaded_arsc == nullptr) {
316 continue;
317 }
318
319 const auto& loaded_packages = loaded_arsc->GetPackages();
320 if (loaded_packages.empty()) {
321 continue;
322 }
323
324 const auto& loaded_package = loaded_packages[0];
325 if (loaded_package->GetPackageName() == package_name) {
326 package_id = GetAssignedPackageId(loaded_package.get());
327 break;
328 }
329 }
330
331 if (package_id == 0U) {
332 ANDROID_LOG(ERROR) << base::StringPrintf("No package with name '%s", package_name.data());
333 return false;
334 }
335
336 const size_t idx = package_ids_[package_id];
337 if (idx == 0xff) {
338 return false;
339 }
340
341 std::string output;
342 for (const ConfiguredPackage& package : package_groups_[idx].packages_) {
343 const LoadedPackage* loaded_package = package.loaded_package_;
344 for (auto it = loaded_package->begin(); it != loaded_package->end(); it++) {
345 const OverlayableInfo* info = loaded_package->GetOverlayableInfo(*it);
346 if (info != nullptr) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000347 auto res_name = GetResourceName(*it);
348 if (!res_name.has_value()) {
Ryan Mitchell2e394222019-08-28 12:10:51 -0700349 ANDROID_LOG(ERROR) << base::StringPrintf(
350 "Unable to retrieve name of overlayable resource 0x%08x", *it);
351 return false;
352 }
353
Ryan Mitchell80094e32020-11-16 23:08:18 +0000354 const std::string name = ToFormattedResourceString(*res_name);
Ryan Mitchell2e394222019-08-28 12:10:51 -0700355 output.append(base::StringPrintf(
356 "resource='%s' overlayable='%s' actor='%s' policy='0x%08x'\n",
357 name.c_str(), info->name.c_str(), info->actor.c_str(), info->policy_flags));
358 }
359 }
360 }
361
362 *out = std::move(output);
363 return true;
364}
365
Ryan Mitchell192400c2020-04-02 09:54:23 -0700366bool AssetManager2::ContainsAllocatedTable() const {
367 return std::find_if(apk_assets_.begin(), apk_assets_.end(),
368 std::mem_fn(&ApkAssets::IsTableAllocated)) != apk_assets_.end();
369}
370
Adam Lesinski7ad11102016-10-28 16:39:15 -0700371void AssetManager2::SetConfiguration(const ResTable_config& configuration) {
372 const int diff = configuration_.diff(configuration);
373 configuration_ = configuration;
374
375 if (diff) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800376 RebuildFilterList();
Adam Lesinski7ad11102016-10-28 16:39:15 -0700377 InvalidateCaches(static_cast<uint32_t>(diff));
378 }
379}
380
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700381std::set<std::string> AssetManager2::GetNonSystemOverlayPaths() const {
382 std::set<std::string> non_system_overlays;
Adam Lesinski0c405242017-01-13 20:47:26 -0800383 for (const PackageGroup& package_group : package_groups_) {
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800384 bool found_system_package = false;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800385 for (const ConfiguredPackage& package : package_group.packages_) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700386 if (package.loaded_package_->IsSystem()) {
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800387 found_system_package = true;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700388 break;
389 }
390 }
391
392 if (!found_system_package) {
393 for (const ConfiguredOverlay& overlay : package_group.overlays_) {
394 non_system_overlays.insert(apk_assets_[overlay.cookie]->GetPath());
395 }
396 }
397 }
398
399 return non_system_overlays;
400}
401
Ryan Mitchell80094e32020-11-16 23:08:18 +0000402base::expected<std::set<ResTable_config>, IOError> AssetManager2::GetResourceConfigurations(
403 bool exclude_system, bool exclude_mipmap) const {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700404 ATRACE_NAME("AssetManager::GetResourceConfigurations");
405 const auto non_system_overlays =
406 (exclude_system) ? GetNonSystemOverlayPaths() : std::set<std::string>();
407
408 std::set<ResTable_config> configurations;
409 for (const PackageGroup& package_group : package_groups_) {
410 for (size_t i = 0; i < package_group.packages_.size(); i++) {
411 const ConfiguredPackage& package = package_group.packages_[i];
412 if (exclude_system && package.loaded_package_->IsSystem()) {
Adam Lesinski0c405242017-01-13 20:47:26 -0800413 continue;
414 }
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800415
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700416 auto apk_assets = apk_assets_[package_group.cookies_[i]];
417 if (exclude_system && apk_assets->IsOverlay()
418 && non_system_overlays.find(apk_assets->GetPath()) == non_system_overlays.end()) {
419 // Exclude overlays that target system resources.
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800420 continue;
421 }
422
Ryan Mitchell80094e32020-11-16 23:08:18 +0000423 auto result = package.loaded_package_->CollectConfigurations(exclude_mipmap, &configurations);
424 if (UNLIKELY(!result.has_value())) {
425 return base::unexpected(result.error());
426 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800427 }
428 }
429 return configurations;
430}
431
432std::set<std::string> AssetManager2::GetResourceLocales(bool exclude_system,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800433 bool merge_equivalent_languages) const {
434 ATRACE_NAME("AssetManager::GetResourceLocales");
Adam Lesinski0c405242017-01-13 20:47:26 -0800435 std::set<std::string> locales;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700436 const auto non_system_overlays =
437 (exclude_system) ? GetNonSystemOverlayPaths() : std::set<std::string>();
438
Adam Lesinski0c405242017-01-13 20:47:26 -0800439 for (const PackageGroup& package_group : package_groups_) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700440 for (size_t i = 0; i < package_group.packages_.size(); i++) {
441 const ConfiguredPackage& package = package_group.packages_[i];
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800442 if (exclude_system && package.loaded_package_->IsSystem()) {
Adam Lesinski0c405242017-01-13 20:47:26 -0800443 continue;
444 }
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800445
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700446 auto apk_assets = apk_assets_[package_group.cookies_[i]];
447 if (exclude_system && apk_assets->IsOverlay()
448 && non_system_overlays.find(apk_assets->GetPath()) == non_system_overlays.end()) {
449 // Exclude overlays that target system resources.
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800450 continue;
451 }
452
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800453 package.loaded_package_->CollectLocales(merge_equivalent_languages, &locales);
Adam Lesinski0c405242017-01-13 20:47:26 -0800454 }
455 }
456 return locales;
457}
458
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800459std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename,
460 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700461 const std::string new_path = "assets/" + filename;
462 return OpenNonAsset(new_path, mode);
463}
464
465std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename, ApkAssetsCookie cookie,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800466 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700467 const std::string new_path = "assets/" + filename;
468 return OpenNonAsset(new_path, cookie, mode);
469}
470
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800471std::unique_ptr<AssetDir> AssetManager2::OpenDir(const std::string& dirname) const {
472 ATRACE_NAME("AssetManager::OpenDir");
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800473
474 std::string full_path = "assets/" + dirname;
475 std::unique_ptr<SortedVector<AssetDir::FileInfo>> files =
476 util::make_unique<SortedVector<AssetDir::FileInfo>>();
477
478 // Start from the back.
479 for (auto iter = apk_assets_.rbegin(); iter != apk_assets_.rend(); ++iter) {
480 const ApkAssets* apk_assets = *iter;
Mårten Kongstaddbf343b2019-02-21 07:54:18 +0100481 if (apk_assets->IsOverlay()) {
482 continue;
483 }
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800484
485 auto func = [&](const StringPiece& name, FileType type) {
486 AssetDir::FileInfo info;
487 info.setFileName(String8(name.data(), name.size()));
488 info.setFileType(type);
489 info.setSourceName(String8(apk_assets->GetPath().c_str()));
490 files->add(info);
491 };
492
Ryan Mitchellc07aa702020-03-10 13:49:12 -0700493 if (!apk_assets->GetAssetsProvider()->ForEachFile(full_path, func)) {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800494 return {};
495 }
496 }
497
498 std::unique_ptr<AssetDir> asset_dir = util::make_unique<AssetDir>();
499 asset_dir->setFileList(files.release());
500 return asset_dir;
501}
502
Adam Lesinski7ad11102016-10-28 16:39:15 -0700503// Search in reverse because that's how we used to do it and we need to preserve behaviour.
504// This is unfortunate, because ClassLoaders delegate to the parent first, so the order
505// is inconsistent for split APKs.
506std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
507 Asset::AccessMode mode,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800508 ApkAssetsCookie* out_cookie) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700509 for (int32_t i = apk_assets_.size() - 1; i >= 0; i--) {
Mårten Kongstaddbf343b2019-02-21 07:54:18 +0100510 // Prevent RRO from modifying assets and other entries accessed by file
511 // path. Explicitly asking for a path in a given package (denoted by a
512 // cookie) is still OK.
513 if (apk_assets_[i]->IsOverlay()) {
514 continue;
515 }
516
Ryan Mitchellc07aa702020-03-10 13:49:12 -0700517 std::unique_ptr<Asset> asset = apk_assets_[i]->GetAssetsProvider()->Open(filename, mode);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700518 if (asset) {
519 if (out_cookie != nullptr) {
520 *out_cookie = i;
521 }
522 return asset;
523 }
524 }
525
526 if (out_cookie != nullptr) {
527 *out_cookie = kInvalidCookie;
528 }
529 return {};
530}
531
532std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800533 ApkAssetsCookie cookie,
534 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700535 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
536 return {};
537 }
Ryan Mitchellc07aa702020-03-10 13:49:12 -0700538 return apk_assets_[cookie]->GetAssetsProvider()->Open(filename, mode);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700539}
540
Ryan Mitchell80094e32020-11-16 23:08:18 +0000541base::expected<FindEntryResult, NullOrIOError> AssetManager2::FindEntry(
542 uint32_t resid, uint16_t density_override, bool stop_at_first_match,
543 bool ignore_configuration) const {
544 const bool logging_enabled = resource_resolution_logging_enabled_;
545 if (UNLIKELY(logging_enabled)) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700546 // Clear the last logged resource resolution.
547 ResetResourceResolution();
548 last_resolution_.resid = resid;
549 }
550
Adam Lesinski7ad11102016-10-28 16:39:15 -0700551 // Might use this if density_override != 0.
552 ResTable_config density_override_config;
553
554 // Select our configuration or generate a density override configuration.
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800555 const ResTable_config* desired_config = &configuration_;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700556 if (density_override != 0 && density_override != configuration_.density) {
557 density_override_config = configuration_;
558 density_override_config.density = density_override;
559 desired_config = &density_override_config;
560 }
561
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700562 // Retrieve the package group from the package id of the resource id.
Ryan Mitchell80094e32020-11-16 23:08:18 +0000563 if (UNLIKELY(!is_valid_resid(resid))) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500564 LOG(ERROR) << base::StringPrintf("Invalid ID 0x%08x.", resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000565 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -0500566 }
567
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800568 const uint32_t package_id = get_package_id(resid);
569 const uint8_t type_idx = get_type_id(resid) - 1;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800570 const uint16_t entry_idx = get_entry_id(resid);
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700571 uint8_t package_idx = package_ids_[package_id];
Ryan Mitchell80094e32020-11-16 23:08:18 +0000572 if (UNLIKELY(package_idx == 0xff)) {
Ryan Mitchell2fe23472019-02-27 09:43:01 -0800573 ANDROID_LOG(ERROR) << base::StringPrintf("No package ID %02x found for ID 0x%08x.",
574 package_id, resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000575 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -0500576 }
577
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800578 const PackageGroup& package_group = package_groups_[package_idx];
Ryan Mitchell80094e32020-11-16 23:08:18 +0000579 auto result = FindEntryInternal(package_group, type_idx, entry_idx, *desired_config,
580 stop_at_first_match, ignore_configuration);
581 if (UNLIKELY(!result.has_value())) {
582 return base::unexpected(result.error());
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700583 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800584
Ryan Mitchell80094e32020-11-16 23:08:18 +0000585 if (!stop_at_first_match && !ignore_configuration && !apk_assets_[result->cookie]->IsLoader()) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700586 for (const auto& id_map : package_group.overlays_) {
587 auto overlay_entry = id_map.overlay_res_maps_.Lookup(resid);
588 if (!overlay_entry) {
589 // No id map entry exists for this target resource.
590 continue;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000591 }
592 if (overlay_entry.IsInlineValue()) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700593 // The target resource is overlaid by an inline value not represented by a resource.
Ryan Mitchell80094e32020-11-16 23:08:18 +0000594 result->entry = overlay_entry.GetInlineValue();
595 result->dynamic_ref_table = id_map.overlay_res_maps_.GetOverlayDynamicRefTable();
596 result->cookie = id_map.cookie;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700597 continue;
598 }
599
Ryan Mitchell80094e32020-11-16 23:08:18 +0000600 auto overlay_result = FindEntry(overlay_entry.GetResourceId(), density_override,
601 false /* stop_at_first_match */,
602 false /* ignore_configuration */);
603 if (UNLIKELY(IsIOError(overlay_result))) {
604 return base::unexpected(overlay_result.error());
605 }
606 if (!overlay_result.has_value()) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700607 continue;
608 }
609
Ryan Mitchell80094e32020-11-16 23:08:18 +0000610 if (!overlay_result->config.isBetterThan(result->config, desired_config)
611 && overlay_result->config.compare(result->config) != 0) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700612 // The configuration of the entry for the overlay must be equal to or better than the target
613 // configuration to be chosen as the better value.
614 continue;
615 }
616
Ryan Mitchell80094e32020-11-16 23:08:18 +0000617 result->cookie = overlay_result->cookie;
618 result->entry = overlay_result->entry;
619 result->config = overlay_result->config;
620 result->dynamic_ref_table = id_map.overlay_res_maps_.GetOverlayDynamicRefTable();
621
622 if (UNLIKELY(logging_enabled)) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700623 last_resolution_.steps.push_back(
Ryan Mitchell80094e32020-11-16 23:08:18 +0000624 Resolution::Step{Resolution::Step::Type::OVERLAID, overlay_result->config.toString(),
625 overlay_result->package_name});
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700626 }
627 }
628 }
629
Ryan Mitchell80094e32020-11-16 23:08:18 +0000630 if (UNLIKELY(logging_enabled)) {
631 last_resolution_.cookie = result->cookie;
632 last_resolution_.type_string_ref = result->type_string_ref;
633 last_resolution_.entry_string_ref = result->entry_string_ref;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700634 }
635
Ryan Mitchell80094e32020-11-16 23:08:18 +0000636 return result;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700637}
638
Ryan Mitchell80094e32020-11-16 23:08:18 +0000639base::expected<FindEntryResult, NullOrIOError> AssetManager2::FindEntryInternal(
640 const PackageGroup& package_group, uint8_t type_idx, uint16_t entry_idx,
641 const ResTable_config& desired_config, bool stop_at_first_match,
642 bool ignore_configuration) const {
643 const bool logging_enabled = resource_resolution_logging_enabled_;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800644 ApkAssetsCookie best_cookie = kInvalidCookie;
645 const LoadedPackage* best_package = nullptr;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000646 incfs::verified_map_ptr<ResTable_type> best_type;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800647 const ResTable_config* best_config = nullptr;
648 ResTable_config best_config_copy;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000649 uint32_t best_offset = 0U;
650 uint32_t type_flags = 0U;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800651
Ryan Mitchell80094e32020-11-16 23:08:18 +0000652 auto resolution_type = Resolution::Step::Type::NO_ENTRY;
Winson2f3669b2019-01-11 11:28:34 -0800653 std::vector<Resolution::Step> resolution_steps;
654
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800655 // If desired_config is the same as the set configuration, then we can use our filtered list
656 // and we don't need to match the configurations, since they already matched.
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700657 const bool use_fast_path = !ignore_configuration && &desired_config == &configuration_;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800658
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700659 const size_t package_count = package_group.packages_.size();
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800660 for (size_t pi = 0; pi < package_count; pi++) {
661 const ConfiguredPackage& loaded_package_impl = package_group.packages_[pi];
662 const LoadedPackage* loaded_package = loaded_package_impl.loaded_package_;
663 ApkAssetsCookie cookie = package_group.cookies_[pi];
664
665 // If the type IDs are offset in this package, we need to take that into account when searching
666 // for a type.
667 const TypeSpec* type_spec = loaded_package->GetTypeSpecByTypeIndex(type_idx);
668 if (UNLIKELY(type_spec == nullptr)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700669 continue;
670 }
671
Ryan Mitchell80094e32020-11-16 23:08:18 +0000672 auto entry_flags = type_spec->GetFlagsForEntryIndex(entry_idx);
673 if (UNLIKELY(!entry_flags)) {
674 return base::unexpected(entry_flags.error());
675 }
676 type_flags |= entry_flags.value();
677
Winson9947f1e2019-08-16 10:20:39 -0700678 // If the package is an overlay or custom loader,
679 // then even configurations that are the same MUST be chosen.
Winson9947f1e2019-08-16 10:20:39 -0700680 const bool package_is_loader = loaded_package->IsCustomLoader();
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800681
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800682 if (use_fast_path) {
Winson2f3669b2019-01-11 11:28:34 -0800683 const FilteredConfigGroup& filtered_group = loaded_package_impl.filtered_configs_[type_idx];
Ryan Mitchell80094e32020-11-16 23:08:18 +0000684 for (const auto& type_config : filtered_group.type_configs) {
685 const ResTable_config& this_config = type_config.config;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800686
687 // We can skip calling ResTable_config::match() because we know that all candidate
688 // configurations that do NOT match have been filtered-out.
Winson2f3669b2019-01-11 11:28:34 -0800689 if (best_config == nullptr) {
690 resolution_type = Resolution::Step::Type::INITIAL;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700691 } else if (this_config.isBetterThan(*best_config, &desired_config)) {
692 resolution_type = (package_is_loader) ? Resolution::Step::Type::BETTER_MATCH_LOADER
693 : Resolution::Step::Type::BETTER_MATCH;
694 } else if (package_is_loader && this_config.compare(*best_config) == 0) {
695 resolution_type = Resolution::Step::Type::OVERLAID_LOADER;
Winson2f3669b2019-01-11 11:28:34 -0800696 } else {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000697 if (UNLIKELY(logging_enabled)) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700698 resolution_type = (package_is_loader) ? Resolution::Step::Type::SKIPPED_LOADER
699 : Resolution::Step::Type::SKIPPED;
Winson9947f1e2019-08-16 10:20:39 -0700700 resolution_steps.push_back(Resolution::Step{resolution_type,
701 this_config.toString(),
702 &loaded_package->GetPackageName()});
703 }
Winson2f3669b2019-01-11 11:28:34 -0800704 continue;
705 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800706
Winson2f3669b2019-01-11 11:28:34 -0800707 // The configuration matches and is better than the previous selection.
708 // Find the entry value if it exists for this configuration.
Ryan Mitchell80094e32020-11-16 23:08:18 +0000709 const auto& type = type_config.type;
710 const auto offset = LoadedPackage::GetEntryOffset(type, entry_idx);
711 if (UNLIKELY(IsIOError(offset))) {
712 return base::unexpected(offset.error());
713 }
714 if (!offset.has_value()) {
715 if (UNLIKELY(logging_enabled)) {
Winson9947f1e2019-08-16 10:20:39 -0700716 if (package_is_loader) {
717 resolution_type = Resolution::Step::Type::NO_ENTRY_LOADER;
718 } else {
719 resolution_type = Resolution::Step::Type::NO_ENTRY;
720 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700721 resolution_steps.push_back(Resolution::Step{resolution_type,
Winson9947f1e2019-08-16 10:20:39 -0700722 this_config.toString(),
723 &loaded_package->GetPackageName()});
724 }
Winson2f3669b2019-01-11 11:28:34 -0800725 continue;
726 }
727
728 best_cookie = cookie;
729 best_package = loaded_package;
730 best_type = type;
731 best_config = &this_config;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000732 best_offset = offset.value();
Winson2f3669b2019-01-11 11:28:34 -0800733
Ryan Mitchell80094e32020-11-16 23:08:18 +0000734 if (UNLIKELY(logging_enabled)) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700735 last_resolution_.steps.push_back(Resolution::Step{resolution_type,
736 this_config.toString(),
737 &loaded_package->GetPackageName()});
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800738 }
739 }
740 } else {
741 // This is the slower path, which doesn't use the filtered list of configurations.
742 // Here we must read the ResTable_config from the mmapped APK, convert it to host endianness
743 // and fill in any new fields that did not exist when the APK was compiled.
744 // Furthermore when selecting configurations we can't just record the pointer to the
745 // ResTable_config, we must copy it.
746 const auto iter_end = type_spec->types + type_spec->type_count;
747 for (auto iter = type_spec->types; iter != iter_end; ++iter) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000748 const incfs::verified_map_ptr<ResTable_type>& type = *iter;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800749
Ryan Mitchell80094e32020-11-16 23:08:18 +0000750 ResTable_config this_config{};
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800751 if (!ignore_configuration) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000752 this_config.copyFromDtoH(type->config);
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700753 if (!this_config.match(desired_config)) {
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800754 continue;
755 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800756
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800757 if (best_config == nullptr) {
758 resolution_type = Resolution::Step::Type::INITIAL;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700759 } else if (this_config.isBetterThan(*best_config, &desired_config)) {
760 resolution_type = (package_is_loader) ? Resolution::Step::Type::BETTER_MATCH_LOADER
761 : Resolution::Step::Type::BETTER_MATCH;
762 } else if (package_is_loader && this_config.compare(*best_config) == 0) {
763 resolution_type = Resolution::Step::Type::OVERLAID_LOADER;
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800764 } else {
765 continue;
766 }
Winson2f3669b2019-01-11 11:28:34 -0800767 }
768
769 // The configuration matches and is better than the previous selection.
770 // Find the entry value if it exists for this configuration.
Ryan Mitchell80094e32020-11-16 23:08:18 +0000771 const auto offset = LoadedPackage::GetEntryOffset(type, entry_idx);
772 if (UNLIKELY(IsIOError(offset))) {
773 return base::unexpected(offset.error());
774 }
775 if (!offset.has_value()) {
Winson2f3669b2019-01-11 11:28:34 -0800776 continue;
777 }
778
779 best_cookie = cookie;
780 best_package = loaded_package;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000781 best_type = type;
Winson2f3669b2019-01-11 11:28:34 -0800782 best_config_copy = this_config;
783 best_config = &best_config_copy;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000784 best_offset = offset.value();
Winson2f3669b2019-01-11 11:28:34 -0800785
Ryan Mitchell80094e32020-11-16 23:08:18 +0000786 if (stop_at_first_match) {
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800787 // Any configuration will suffice, so break.
788 break;
789 }
790
Ryan Mitchell80094e32020-11-16 23:08:18 +0000791 if (UNLIKELY(logging_enabled)) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700792 last_resolution_.steps.push_back(Resolution::Step{resolution_type,
793 this_config.toString(),
794 &loaded_package->GetPackageName()});
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800795 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700796 }
797 }
798 }
799
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800800 if (UNLIKELY(best_cookie == kInvalidCookie)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000801 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700802 }
803
Ryan Mitchell80094e32020-11-16 23:08:18 +0000804 auto best_entry_result = LoadedPackage::GetEntryFromOffset(best_type, best_offset);
805 if (!best_entry_result.has_value()) {
806 return base::unexpected(best_entry_result.error());
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800807 }
808
Ryan Mitchell80094e32020-11-16 23:08:18 +0000809 const incfs::map_ptr<ResTable_entry> best_entry = *best_entry_result;
810 if (!best_entry) {
811 return base::unexpected(IOError::PAGES_MISSING);
Ryan Mitchellbf1f45b2020-09-29 17:22:52 -0700812 }
813
Ryan Mitchell80094e32020-11-16 23:08:18 +0000814 const auto entry = GetEntryValue(best_entry.verified());
815 if (!entry.has_value()) {
816 return base::unexpected(entry.error());
817 }
Winson2f3669b2019-01-11 11:28:34 -0800818
Ryan Mitchell80094e32020-11-16 23:08:18 +0000819 return FindEntryResult{
820 .cookie = best_cookie,
821 .entry = *entry,
822 .config = *best_config,
823 .type_flags = type_flags,
824 .package_name = &best_package->GetPackageName(),
825 .type_string_ref = StringPoolRef(best_package->GetTypeStringPool(), best_type->id - 1),
826 .entry_string_ref = StringPoolRef(best_package->GetKeyStringPool(),
827 best_entry->key.index),
828 .dynamic_ref_table = package_group.dynamic_ref_table.get(),
829 };
Adam Lesinski7ad11102016-10-28 16:39:15 -0700830}
831
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700832void AssetManager2::ResetResourceResolution() const {
833 last_resolution_.cookie = kInvalidCookie;
834 last_resolution_.resid = 0;
835 last_resolution_.steps.clear();
836 last_resolution_.type_string_ref = StringPoolRef();
837 last_resolution_.entry_string_ref = StringPoolRef();
838}
839
Winson2f3669b2019-01-11 11:28:34 -0800840void AssetManager2::SetResourceResolutionLoggingEnabled(bool enabled) {
841 resource_resolution_logging_enabled_ = enabled;
Winson2f3669b2019-01-11 11:28:34 -0800842 if (!enabled) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700843 ResetResourceResolution();
Winson2f3669b2019-01-11 11:28:34 -0800844 }
845}
846
847std::string AssetManager2::GetLastResourceResolution() const {
848 if (!resource_resolution_logging_enabled_) {
849 LOG(ERROR) << "Must enable resource resolution logging before getting path.";
Ryan Mitchell80094e32020-11-16 23:08:18 +0000850 return {};
Winson2f3669b2019-01-11 11:28:34 -0800851 }
852
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700853 auto cookie = last_resolution_.cookie;
Winson2f3669b2019-01-11 11:28:34 -0800854 if (cookie == kInvalidCookie) {
855 LOG(ERROR) << "AssetManager hasn't resolved a resource to read resolution path.";
Ryan Mitchell80094e32020-11-16 23:08:18 +0000856 return {};
Winson2f3669b2019-01-11 11:28:34 -0800857 }
858
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700859 uint32_t resid = last_resolution_.resid;
860 std::vector<Resolution::Step>& steps = last_resolution_.steps;
Winson2f3669b2019-01-11 11:28:34 -0800861 std::string resource_name_string;
862
863 const LoadedPackage* package =
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700864 apk_assets_[cookie]->GetLoadedArsc()->GetPackageById(get_package_id(resid));
Winson2f3669b2019-01-11 11:28:34 -0800865
866 if (package != nullptr) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000867 auto resource_name = ToResourceName(last_resolution_.type_string_ref,
868 last_resolution_.entry_string_ref,
869 package->GetPackageName());
870 resource_name_string = resource_name.has_value() ?
871 ToFormattedResourceString(resource_name.value()) : "<unknown>";
Winson2f3669b2019-01-11 11:28:34 -0800872 }
873
874 std::stringstream log_stream;
875 log_stream << base::StringPrintf("Resolution for 0x%08x ", resid)
876 << resource_name_string
877 << "\n\tFor config -"
878 << configuration_.toString();
879
880 std::string prefix;
881 for (Resolution::Step step : steps) {
882 switch (step.type) {
883 case Resolution::Step::Type::INITIAL:
884 prefix = "Found initial";
885 break;
886 case Resolution::Step::Type::BETTER_MATCH:
887 prefix = "Found better";
888 break;
Winson9947f1e2019-08-16 10:20:39 -0700889 case Resolution::Step::Type::BETTER_MATCH_LOADER:
890 prefix = "Found better in loader";
891 break;
Winson2f3669b2019-01-11 11:28:34 -0800892 case Resolution::Step::Type::OVERLAID:
893 prefix = "Overlaid";
894 break;
Winson9947f1e2019-08-16 10:20:39 -0700895 case Resolution::Step::Type::OVERLAID_LOADER:
896 prefix = "Overlaid by loader";
897 break;
898 case Resolution::Step::Type::SKIPPED:
899 prefix = "Skipped";
900 break;
901 case Resolution::Step::Type::SKIPPED_LOADER:
902 prefix = "Skipped loader";
903 break;
904 case Resolution::Step::Type::NO_ENTRY:
905 prefix = "No entry";
906 break;
907 case Resolution::Step::Type::NO_ENTRY_LOADER:
908 prefix = "No entry for loader";
909 break;
Winson2f3669b2019-01-11 11:28:34 -0800910 }
911
912 if (!prefix.empty()) {
913 log_stream << "\n\t" << prefix << ": " << *step.package_name;
914
915 if (!step.config_name.isEmpty()) {
916 log_stream << " -" << step.config_name;
917 }
918 }
919 }
920
921 return log_stream.str();
922}
923
Ryan Mitchell80094e32020-11-16 23:08:18 +0000924base::expected<AssetManager2::ResourceName, NullOrIOError> AssetManager2::GetResourceName(
925 uint32_t resid) const {
926 auto result = FindEntry(resid, 0u /* density_override */, true /* stop_at_first_match */,
927 true /* ignore_configuration */);
928 if (!result.has_value()) {
929 return base::unexpected(result.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -0700930 }
931
Ryan Mitchell80094e32020-11-16 23:08:18 +0000932 return ToResourceName(result->type_string_ref,
933 result->entry_string_ref,
934 *result->package_name);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700935}
936
Ryan Mitchell80094e32020-11-16 23:08:18 +0000937base::expected<AssetManager2::SelectedValue, NullOrIOError> AssetManager2::GetResource(
938 uint32_t resid, bool may_be_bag, uint16_t density_override) const {
939 auto result = FindEntry(resid, density_override, false /* stop_at_first_match */,
940 false /* ignore_configuration */);
941 if (!result.has_value()) {
942 return base::unexpected(result.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -0700943 }
944
Ryan Mitchell80094e32020-11-16 23:08:18 +0000945 auto result_map_entry = std::get_if<incfs::verified_map_ptr<ResTable_map_entry>>(&result->entry);
Ryan Mitchellbf1f45b2020-09-29 17:22:52 -0700946 if (result_map_entry != nullptr) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700947 if (!may_be_bag) {
948 LOG(ERROR) << base::StringPrintf("Resource %08x is a complex map type.", resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000949 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700950 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800951
952 // Create a reference since we can't represent this complex type as a Res_value.
Ryan Mitchell80094e32020-11-16 23:08:18 +0000953 return SelectedValue(Res_value::TYPE_REFERENCE, resid, result->cookie, result->type_flags,
954 resid, result->config);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700955 }
956
Adam Lesinskida431a22016-12-29 16:08:16 -0500957 // Convert the package ID to the runtime assigned package ID.
Ryan Mitchell80094e32020-11-16 23:08:18 +0000958 Res_value value = std::get<Res_value>(result->entry);
959 result->dynamic_ref_table->lookupResourceValue(&value);
Adam Lesinskida431a22016-12-29 16:08:16 -0500960
Ryan Mitchell80094e32020-11-16 23:08:18 +0000961 return SelectedValue(value.dataType, value.data, result->cookie, result->type_flags,
962 resid, result->config);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700963}
964
Ryan Mitchell80094e32020-11-16 23:08:18 +0000965base::expected<std::monostate, NullOrIOError> AssetManager2::ResolveReference(
966 AssetManager2::SelectedValue& value) const {
967 if (value.type != Res_value::TYPE_REFERENCE || value.data == 0U) {
968 // Not a reference. Nothing to do.
969 return {};
Adam Lesinski0c405242017-01-13 20:47:26 -0800970 }
Ryan Mitchell80094e32020-11-16 23:08:18 +0000971
972 uint32_t combined_flags = value.flags;
973 uint32_t resolve_resid = value.data;
974 constexpr const uint32_t kMaxIterations = 20;
975 for (uint32_t i = 0U;; i++) {
976 auto result = GetResource(resolve_resid, true /*may_be_bag*/);
977 if (!result.has_value()) {
Ryan Mitchelle7ab6272020-11-13 18:06:15 -0800978 value.resid = resolve_resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000979 return base::unexpected(result.error());
980 }
981
Ryan Mitchelle7ab6272020-11-13 18:06:15 -0800982 // If resource resolution fails, the value should be set to the last reference that was able to
983 // be resolved successfully.
984 value = *result;
985 value.flags |= combined_flags;
986
Ryan Mitchell80094e32020-11-16 23:08:18 +0000987 if (result->type != Res_value::TYPE_REFERENCE ||
988 result->data == Res_value::DATA_NULL_UNDEFINED ||
989 result->data == resolve_resid || i == kMaxIterations) {
990 // This reference can't be resolved, so exit now and let the caller deal with it.
Ryan Mitchell80094e32020-11-16 23:08:18 +0000991 return {};
992 }
993
Ryan Mitchelle7ab6272020-11-13 18:06:15 -0800994 combined_flags = result->flags;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000995 resolve_resid = result->data;
996 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800997}
998
Ryan Mitchell80094e32020-11-16 23:08:18 +0000999const std::vector<uint32_t> AssetManager2::GetBagResIdStack(uint32_t resid) const {
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001000 auto cached_iter = cached_bag_resid_stacks_.find(resid);
1001 if (cached_iter != cached_bag_resid_stacks_.end()) {
1002 return cached_iter->second;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001003 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001004
1005 std::vector<uint32_t> found_resids;
1006 GetBag(resid, found_resids);
1007 cached_bag_resid_stacks_.emplace(resid, found_resids);
1008 return found_resids;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001009}
1010
Ryan Mitchell80094e32020-11-16 23:08:18 +00001011base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::ResolveBag(
1012 AssetManager2::SelectedValue& value) const {
1013 if (UNLIKELY(value.type != Res_value::TYPE_REFERENCE)) {
1014 return base::unexpected(std::nullopt);
1015 }
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001016
Ryan Mitchell80094e32020-11-16 23:08:18 +00001017 auto bag = GetBag(value.data);
1018 if (bag.has_value()) {
1019 value.flags |= (*bag)->type_spec_flags;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001020 }
1021 return bag;
y57cd1952018-04-12 14:26:23 -07001022}
1023
Ryan Mitchell80094e32020-11-16 23:08:18 +00001024base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::GetBag(uint32_t resid) const {
1025 std::vector<uint32_t> found_resids;
1026 const auto bag = GetBag(resid, found_resids);
1027 cached_bag_resid_stacks_.emplace(resid, found_resids);
1028 return bag;
Ryan Mitchell155d5392020-02-10 13:35:24 -08001029}
1030
Ryan Mitchell80094e32020-11-16 23:08:18 +00001031base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::GetBag(
1032 uint32_t resid, std::vector<uint32_t>& child_resids) const {
1033 if (auto cached_iter = cached_bags_.find(resid); cached_iter != cached_bags_.end()) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001034 return cached_iter->second.get();
1035 }
1036
Ryan Mitchell80094e32020-11-16 23:08:18 +00001037 auto entry = FindEntry(resid, 0u /* density_override */, false /* stop_at_first_match */,
1038 false /* ignore_configuration */);
1039 if (!entry.has_value()) {
1040 return base::unexpected(entry.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001041 }
1042
Ryan Mitchell80094e32020-11-16 23:08:18 +00001043 auto entry_map = std::get_if<incfs::verified_map_ptr<ResTable_map_entry>>(&entry->entry);
1044 if (entry_map == nullptr) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001045 // Not a bag, nothing to do.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001046 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001047 }
1048
Ryan Mitchell80094e32020-11-16 23:08:18 +00001049 auto map = *entry_map;
1050 auto map_entry = map.offset(dtohs(map->size)).convert<ResTable_map>();
1051 const auto map_entry_end = map_entry + dtohl(map->count);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001052
y57cd1952018-04-12 14:26:23 -07001053 // Keep track of ids that have already been seen to prevent infinite loops caused by circular
Ryan Mitchell80094e32020-11-16 23:08:18 +00001054 // dependencies between bags.
y57cd1952018-04-12 14:26:23 -07001055 child_resids.push_back(resid);
1056
Adam Lesinskida431a22016-12-29 16:08:16 -05001057 uint32_t parent_resid = dtohl(map->parent.ident);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001058 if (parent_resid == 0U ||
1059 std::find(child_resids.begin(), child_resids.end(), parent_resid) != child_resids.end()) {
1060 // There is no parent or a circular parental dependency exist, meaning there is nothing to
1061 // inherit and we can do a simple copy of the entries in the map.
Adam Lesinski7ad11102016-10-28 16:39:15 -07001062 const size_t entry_count = map_entry_end - map_entry;
1063 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
1064 malloc(sizeof(ResolvedBag) + (entry_count * sizeof(ResolvedBag::Entry))))};
Ryan Mitchell155d5392020-02-10 13:35:24 -08001065
1066 bool sort_entries = false;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001067 for (auto new_entry = new_bag->entries; map_entry != map_entry_end; ++map_entry) {
1068 if (UNLIKELY(!map_entry)) {
1069 return base::unexpected(IOError::PAGES_MISSING);
1070 }
1071
Adam Lesinskida431a22016-12-29 16:08:16 -05001072 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001073 if (!is_internal_resid(new_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -05001074 // Attributes, arrays, etc don't have a resource id as the name. They specify
1075 // other data, which would be wrong to change via a lookup.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001076 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001077 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
1078 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001079 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001080 }
1081 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001082
1083 new_entry->cookie = entry->cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -05001084 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001085 new_entry->key_pool = nullptr;
1086 new_entry->type_pool = nullptr;
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001087 new_entry->style = resid;
Adam Lesinski30080e22017-10-16 16:18:09 -07001088 new_entry->value.copyFrom_dtoh(map_entry->value);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001089 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1090 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001091 LOG(ERROR) << base::StringPrintf(
1092 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
1093 new_entry->value.data, new_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001094 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001095 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001096
Ryan Mitchell155d5392020-02-10 13:35:24 -08001097 sort_entries = sort_entries ||
1098 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001099 ++new_entry;
1100 }
Ryan Mitchell155d5392020-02-10 13:35:24 -08001101
1102 if (sort_entries) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001103 std::sort(new_bag->entries, new_bag->entries + entry_count,
1104 [](auto&& lhs, auto&& rhs) { return lhs.key < rhs.key; });
Ryan Mitchell155d5392020-02-10 13:35:24 -08001105 }
1106
Ryan Mitchell80094e32020-11-16 23:08:18 +00001107 new_bag->type_spec_flags = entry->type_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001108 new_bag->entry_count = static_cast<uint32_t>(entry_count);
1109 ResolvedBag* result = new_bag.get();
1110 cached_bags_[resid] = std::move(new_bag);
1111 return result;
1112 }
1113
Adam Lesinskida431a22016-12-29 16:08:16 -05001114 // In case the parent is a dynamic reference, resolve it.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001115 entry->dynamic_ref_table->lookupResourceId(&parent_resid);
Adam Lesinskida431a22016-12-29 16:08:16 -05001116
Adam Lesinski7ad11102016-10-28 16:39:15 -07001117 // Get the parent and do a merge of the keys.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001118 const auto parent_bag = GetBag(parent_resid, child_resids);
1119 if (UNLIKELY(!parent_bag.has_value())) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001120 // Failed to get the parent that should exist.
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001121 LOG(ERROR) << base::StringPrintf("Failed to find parent 0x%08x of bag 0x%08x.", parent_resid,
1122 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001123 return base::unexpected(parent_bag.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001124 }
1125
Adam Lesinski7ad11102016-10-28 16:39:15 -07001126 // Create the max possible entries we can make. Once we construct the bag,
1127 // we will realloc to fit to size.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001128 const size_t max_count = (*parent_bag)->entry_count + dtohl(map->count);
George Burgess IV09b119f2017-07-25 15:00:04 -07001129 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
1130 malloc(sizeof(ResolvedBag) + (max_count * sizeof(ResolvedBag::Entry))))};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001131 ResolvedBag::Entry* new_entry = new_bag->entries;
1132
Ryan Mitchell80094e32020-11-16 23:08:18 +00001133 const ResolvedBag::Entry* parent_entry = (*parent_bag)->entries;
1134 const ResolvedBag::Entry* const parent_entry_end = parent_entry + (*parent_bag)->entry_count;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001135
1136 // The keys are expected to be in sorted order. Merge the two bags.
Ryan Mitchell155d5392020-02-10 13:35:24 -08001137 bool sort_entries = false;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001138 while (map_entry != map_entry_end && parent_entry != parent_entry_end) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001139 if (UNLIKELY(!map_entry)) {
1140 return base::unexpected(IOError::PAGES_MISSING);
1141 }
1142
Adam Lesinskida431a22016-12-29 16:08:16 -05001143 uint32_t child_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001144 if (!is_internal_resid(child_key)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001145 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&child_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001146 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", child_key,
1147 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001148 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001149 }
1150 }
1151
Adam Lesinski7ad11102016-10-28 16:39:15 -07001152 if (child_key <= parent_entry->key) {
1153 // Use the child key if it comes before the parent
1154 // or is equal to the parent (overrides).
Ryan Mitchell80094e32020-11-16 23:08:18 +00001155 new_entry->cookie = entry->cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001156 new_entry->key = child_key;
1157 new_entry->key_pool = nullptr;
1158 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -07001159 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001160 new_entry->style = resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001161 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1162 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001163 LOG(ERROR) << base::StringPrintf(
1164 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
1165 new_entry->value.data, child_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001166 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001167 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001168 ++map_entry;
1169 } else {
1170 // Take the parent entry as-is.
1171 memcpy(new_entry, parent_entry, sizeof(*new_entry));
1172 }
1173
Ryan Mitchell155d5392020-02-10 13:35:24 -08001174 sort_entries = sort_entries ||
1175 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001176 if (child_key >= parent_entry->key) {
1177 // Move to the next parent entry if we used it or it was overridden.
1178 ++parent_entry;
1179 }
1180 // Increment to the next entry to fill.
1181 ++new_entry;
1182 }
1183
1184 // Finish the child entries if they exist.
1185 while (map_entry != map_entry_end) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001186 if (UNLIKELY(!map_entry)) {
1187 return base::unexpected(IOError::PAGES_MISSING);
1188 }
1189
Adam Lesinskida431a22016-12-29 16:08:16 -05001190 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001191 if (!is_internal_resid(new_key)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001192 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001193 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
1194 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001195 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001196 }
1197 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001198 new_entry->cookie = entry->cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -05001199 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001200 new_entry->key_pool = nullptr;
1201 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -07001202 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001203 new_entry->style = resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001204 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1205 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001206 LOG(ERROR) << base::StringPrintf("Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.",
1207 new_entry->value.dataType, new_entry->value.data, new_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001208 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001209 }
Ryan Mitchell155d5392020-02-10 13:35:24 -08001210 sort_entries = sort_entries ||
1211 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001212 ++map_entry;
1213 ++new_entry;
1214 }
1215
1216 // Finish the parent entries if they exist.
1217 if (parent_entry != parent_entry_end) {
1218 // Take the rest of the parent entries as-is.
1219 const size_t num_entries_to_copy = parent_entry_end - parent_entry;
1220 memcpy(new_entry, parent_entry, num_entries_to_copy * sizeof(*new_entry));
1221 new_entry += num_entries_to_copy;
1222 }
1223
1224 // Resize the resulting array to fit.
1225 const size_t actual_count = new_entry - new_bag->entries;
1226 if (actual_count != max_count) {
George Burgess IV09b119f2017-07-25 15:00:04 -07001227 new_bag.reset(reinterpret_cast<ResolvedBag*>(realloc(
1228 new_bag.release(), sizeof(ResolvedBag) + (actual_count * sizeof(ResolvedBag::Entry)))));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001229 }
1230
Ryan Mitchell155d5392020-02-10 13:35:24 -08001231 if (sort_entries) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001232 std::sort(new_bag->entries, new_bag->entries + actual_count,
1233 [](auto&& lhs, auto&& rhs) { return lhs.key < rhs.key; });
Ryan Mitchell155d5392020-02-10 13:35:24 -08001234 }
1235
Adam Lesinski1a1e9c22017-10-13 15:45:34 -07001236 // Combine flags from the parent and our own bag.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001237 new_bag->type_spec_flags = entry->type_flags | (*parent_bag)->type_spec_flags;
George Burgess IV09b119f2017-07-25 15:00:04 -07001238 new_bag->entry_count = static_cast<uint32_t>(actual_count);
1239 ResolvedBag* result = new_bag.get();
1240 cached_bags_[resid] = std::move(new_bag);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001241 return result;
1242}
1243
Adam Lesinski929d6512017-01-16 19:11:19 -08001244static bool Utf8ToUtf16(const StringPiece& str, std::u16string* out) {
1245 ssize_t len =
1246 utf8_to_utf16_length(reinterpret_cast<const uint8_t*>(str.data()), str.size(), false);
1247 if (len < 0) {
1248 return false;
1249 }
1250 out->resize(static_cast<size_t>(len));
1251 utf8_to_utf16(reinterpret_cast<const uint8_t*>(str.data()), str.size(), &*out->begin(),
1252 static_cast<size_t>(len + 1));
1253 return true;
1254}
1255
Ryan Mitchell80094e32020-11-16 23:08:18 +00001256base::expected<uint32_t, NullOrIOError> AssetManager2::GetResourceId(
1257 const std::string& resource_name, const std::string& fallback_type,
1258 const std::string& fallback_package) const {
Adam Lesinski929d6512017-01-16 19:11:19 -08001259 StringPiece package_name, type, entry;
1260 if (!ExtractResourceName(resource_name, &package_name, &type, &entry)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001261 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001262 }
1263
1264 if (entry.empty()) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001265 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001266 }
1267
1268 if (package_name.empty()) {
1269 package_name = fallback_package;
1270 }
1271
1272 if (type.empty()) {
1273 type = fallback_type;
1274 }
1275
1276 std::u16string type16;
1277 if (!Utf8ToUtf16(type, &type16)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001278 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001279 }
1280
1281 std::u16string entry16;
1282 if (!Utf8ToUtf16(entry, &entry16)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001283 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001284 }
1285
1286 const StringPiece16 kAttr16 = u"attr";
1287 const static std::u16string kAttrPrivate16 = u"^attr-private";
1288
1289 for (const PackageGroup& package_group : package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001290 for (const ConfiguredPackage& package_impl : package_group.packages_) {
1291 const LoadedPackage* package = package_impl.loaded_package_;
Adam Lesinski929d6512017-01-16 19:11:19 -08001292 if (package_name != package->GetPackageName()) {
1293 // All packages in the same group are expected to have the same package name.
1294 break;
1295 }
1296
Ryan Mitchell80094e32020-11-16 23:08:18 +00001297 base::expected<uint32_t, NullOrIOError> resid = package->FindEntryByName(type16, entry16);
1298 if (UNLIKELY(IsIOError(resid))) {
1299 return base::unexpected(resid.error());
1300 }
1301
1302 if (!resid.has_value() && kAttr16 == type16) {
Adam Lesinski929d6512017-01-16 19:11:19 -08001303 // Private attributes in libraries (such as the framework) are sometimes encoded
1304 // under the type '^attr-private' in order to leave the ID space of public 'attr'
1305 // free for future additions. Check '^attr-private' for the same name.
1306 resid = package->FindEntryByName(kAttrPrivate16, entry16);
1307 }
1308
Ryan Mitchell80094e32020-11-16 23:08:18 +00001309 if (resid.has_value()) {
1310 return fix_package_id(*resid, package_group.dynamic_ref_table->mAssignedPackageId);
Adam Lesinski929d6512017-01-16 19:11:19 -08001311 }
1312 }
1313 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001314 return base::unexpected(std::nullopt);
Adam Lesinski0c405242017-01-13 20:47:26 -08001315}
1316
Mårten Kongstad668ec5b2018-06-11 14:11:33 +02001317void AssetManager2::RebuildFilterList(bool filter_incompatible_configs) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001318 for (PackageGroup& group : package_groups_) {
1319 for (ConfiguredPackage& impl : group.packages_) {
1320 // Destroy it.
1321 impl.filtered_configs_.~ByteBucketArray();
1322
1323 // Re-create it.
1324 new (&impl.filtered_configs_) ByteBucketArray<FilteredConfigGroup>();
1325
1326 // Create the filters here.
1327 impl.loaded_package_->ForEachTypeSpec([&](const TypeSpec* spec, uint8_t type_index) {
1328 FilteredConfigGroup& group = impl.filtered_configs_.editItemAt(type_index);
1329 const auto iter_end = spec->types + spec->type_count;
1330 for (auto iter = spec->types; iter != iter_end; ++iter) {
1331 ResTable_config this_config;
1332 this_config.copyFromDtoH((*iter)->config);
Mårten Kongstad668ec5b2018-06-11 14:11:33 +02001333 if (!filter_incompatible_configs || this_config.match(configuration_)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001334 group.type_configs.push_back(TypeConfig{*iter, this_config});
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001335 }
1336 }
1337 });
1338 }
1339 }
1340}
1341
Adam Lesinski7ad11102016-10-28 16:39:15 -07001342void AssetManager2::InvalidateCaches(uint32_t diff) {
Ryan Mitchell2c4d8742019-03-04 09:41:00 -08001343 cached_bag_resid_stacks_.clear();
1344
Adam Lesinski7ad11102016-10-28 16:39:15 -07001345 if (diff == 0xffffffffu) {
1346 // Everything must go.
1347 cached_bags_.clear();
1348 return;
1349 }
1350
1351 // Be more conservative with what gets purged. Only if the bag has other possible
1352 // variations with respect to what changed (diff) should we remove it.
1353 for (auto iter = cached_bags_.cbegin(); iter != cached_bags_.cend();) {
1354 if (diff & iter->second->type_spec_flags) {
1355 iter = cached_bags_.erase(iter);
1356 } else {
1357 ++iter;
1358 }
1359 }
1360}
1361
Ryan Mitchell2e394222019-08-28 12:10:51 -07001362uint8_t AssetManager2::GetAssignedPackageId(const LoadedPackage* package) const {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001363 for (auto& package_group : package_groups_) {
1364 for (auto& package2 : package_group.packages_) {
1365 if (package2.loaded_package_ == package) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -07001366 return package_group.dynamic_ref_table->mAssignedPackageId;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001367 }
1368 }
1369 }
1370 return 0;
1371}
1372
Adam Lesinski30080e22017-10-16 16:18:09 -07001373std::unique_ptr<Theme> AssetManager2::NewTheme() {
1374 return std::unique_ptr<Theme>(new Theme(this));
1375}
1376
1377Theme::Theme(AssetManager2* asset_manager) : asset_manager_(asset_manager) {
1378}
1379
1380Theme::~Theme() = default;
1381
1382namespace {
1383
1384struct ThemeEntry {
1385 ApkAssetsCookie cookie;
1386 uint32_t type_spec_flags;
1387 Res_value value;
1388};
1389
1390struct ThemeType {
1391 int entry_count;
1392 ThemeEntry entries[0];
1393};
1394
1395constexpr size_t kTypeCount = std::numeric_limits<uint8_t>::max() + 1;
1396
1397} // namespace
1398
1399struct Theme::Package {
1400 // Each element of Type will be a dynamically sized object
1401 // allocated to have the entries stored contiguously with the Type.
1402 std::array<util::unique_cptr<ThemeType>, kTypeCount> types;
1403};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001404
Ryan Mitchell80094e32020-11-16 23:08:18 +00001405base::expected<std::monostate, NullOrIOError> Theme::ApplyStyle(uint32_t resid, bool force) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001406 ATRACE_NAME("Theme::ApplyStyle");
Adam Lesinski7ad11102016-10-28 16:39:15 -07001407
Ryan Mitchell80094e32020-11-16 23:08:18 +00001408 auto bag = asset_manager_->GetBag(resid);
1409 if (!bag.has_value()) {
1410 return base::unexpected(bag.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001411 }
1412
1413 // Merge the flags from this style.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001414 type_spec_flags_ |= (*bag)->type_spec_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001415
Adam Lesinski30080e22017-10-16 16:18:09 -07001416 int last_type_idx = -1;
1417 int last_package_idx = -1;
1418 Package* last_package = nullptr;
1419 ThemeType* last_type = nullptr;
1420
1421 // Iterate backwards, because each bag is sorted in ascending key ID order, meaning we will only
1422 // need to perform one resize per type.
1423 using reverse_bag_iterator = std::reverse_iterator<const ResolvedBag::Entry*>;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001424 const auto rbegin = reverse_bag_iterator(begin(*bag));
1425 for (auto it = reverse_bag_iterator(end(*bag)); it != rbegin; ++it) {
1426 const uint32_t attr_resid = it->key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001427
Adam Lesinski30080e22017-10-16 16:18:09 -07001428 // If the resource ID passed in is not a style, the key can be some other identifier that is not
1429 // a resource ID. We should fail fast instead of operating with strange resource IDs.
Adam Lesinski929d6512017-01-16 19:11:19 -08001430 if (!is_valid_resid(attr_resid)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001431 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001432 }
1433
Adam Lesinski30080e22017-10-16 16:18:09 -07001434 // We don't use the 0-based index for the type so that we can avoid doing ID validation
1435 // upon lookup. Instead, we keep space for the type ID 0 in our data structures. Since
1436 // the construction of this type is guarded with a resource ID check, it will never be
1437 // populated, and querying type ID 0 will always fail.
1438 const int package_idx = get_package_id(attr_resid);
1439 const int type_idx = get_type_id(attr_resid);
1440 const int entry_idx = get_entry_id(attr_resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001441
Adam Lesinski30080e22017-10-16 16:18:09 -07001442 if (last_package_idx != package_idx) {
1443 std::unique_ptr<Package>& package = packages_[package_idx];
1444 if (package == nullptr) {
1445 package.reset(new Package());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001446 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001447 last_package_idx = package_idx;
1448 last_package = package.get();
1449 last_type_idx = -1;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001450 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001451
1452 if (last_type_idx != type_idx) {
1453 util::unique_cptr<ThemeType>& type = last_package->types[type_idx];
1454 if (type == nullptr) {
1455 // Allocate enough memory to contain this entry_idx. Since we're iterating in reverse over
1456 // a sorted list of attributes, this shouldn't be resized again during this method call.
1457 type.reset(reinterpret_cast<ThemeType*>(
1458 calloc(sizeof(ThemeType) + (entry_idx + 1) * sizeof(ThemeEntry), 1)));
1459 type->entry_count = entry_idx + 1;
1460 } else if (entry_idx >= type->entry_count) {
1461 // Reallocate the memory to contain this entry_idx. Since we're iterating in reverse over
1462 // a sorted list of attributes, this shouldn't be resized again during this method call.
1463 const int new_count = entry_idx + 1;
1464 type.reset(reinterpret_cast<ThemeType*>(
1465 realloc(type.release(), sizeof(ThemeType) + (new_count * sizeof(ThemeEntry)))));
1466
1467 // Clear out the newly allocated space (which isn't zeroed).
1468 memset(type->entries + type->entry_count, 0,
1469 (new_count - type->entry_count) * sizeof(ThemeEntry));
1470 type->entry_count = new_count;
1471 }
1472 last_type_idx = type_idx;
1473 last_type = type.get();
1474 }
1475
1476 ThemeEntry& entry = last_type->entries[entry_idx];
1477 if (force || (entry.value.dataType == Res_value::TYPE_NULL &&
1478 entry.value.data != Res_value::DATA_NULL_EMPTY)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001479 entry.cookie = it->cookie;
1480 entry.type_spec_flags |= (*bag)->type_spec_flags;
1481 entry.value = it->value;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001482 }
1483 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001484 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001485}
1486
Ryan Mitchell80094e32020-11-16 23:08:18 +00001487std::optional<AssetManager2::SelectedValue> Theme::GetAttribute(uint32_t resid) const {
1488
Adam Lesinski30080e22017-10-16 16:18:09 -07001489 int cnt = 20;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001490 uint32_t type_spec_flags = 0u;
Adam Lesinski30080e22017-10-16 16:18:09 -07001491 do {
1492 const int package_idx = get_package_id(resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001493 const Package* package = packages_[package_idx].get();
Adam Lesinski30080e22017-10-16 16:18:09 -07001494 if (package != nullptr) {
1495 // The themes are constructed with a 1-based type ID, so no need to decrement here.
1496 const int type_idx = get_type_id(resid);
1497 const ThemeType* type = package->types[type_idx].get();
1498 if (type != nullptr) {
1499 const int entry_idx = get_entry_id(resid);
1500 if (entry_idx < type->entry_count) {
1501 const ThemeEntry& entry = type->entries[entry_idx];
1502 type_spec_flags |= entry.type_spec_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001503
Adam Lesinski30080e22017-10-16 16:18:09 -07001504 if (entry.value.dataType == Res_value::TYPE_ATTRIBUTE) {
1505 if (cnt > 0) {
1506 cnt--;
1507 resid = entry.value.data;
1508 continue;
1509 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001510 return std::nullopt;
Adam Lesinski30080e22017-10-16 16:18:09 -07001511 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001512
Adam Lesinski30080e22017-10-16 16:18:09 -07001513 // @null is different than @empty.
1514 if (entry.value.dataType == Res_value::TYPE_NULL &&
1515 entry.value.data != Res_value::DATA_NULL_EMPTY) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001516 return std::nullopt;
Adam Lesinski30080e22017-10-16 16:18:09 -07001517 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001518
Ryan Mitchell80094e32020-11-16 23:08:18 +00001519 return AssetManager2::SelectedValue(entry.value.dataType, entry.value.data, entry.cookie,
1520 type_spec_flags, 0U /* resid */, {} /* config */);
Adam Lesinskida431a22016-12-29 16:08:16 -05001521 }
Adam Lesinskida431a22016-12-29 16:08:16 -05001522 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001523 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001524 break;
1525 } while (true);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001526 return std::nullopt;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001527}
1528
Ryan Mitchell80094e32020-11-16 23:08:18 +00001529base::expected<std::monostate, NullOrIOError> Theme::ResolveAttributeReference(
1530 AssetManager2::SelectedValue& value) const {
1531 if (value.type != Res_value::TYPE_ATTRIBUTE) {
1532 return asset_manager_->ResolveReference(value);
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001533 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001534
1535 std::optional<AssetManager2::SelectedValue> result = GetAttribute(value.data);
1536 if (!result.has_value()) {
1537 return base::unexpected(std::nullopt);
1538 }
1539
1540 auto resolve_result = asset_manager_->ResolveReference(*result);
1541 if (resolve_result.has_value()) {
1542 result->flags |= value.flags;
1543 value = *result;
1544 }
1545 return resolve_result;
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001546}
1547
Adam Lesinski7ad11102016-10-28 16:39:15 -07001548void Theme::Clear() {
1549 type_spec_flags_ = 0u;
1550 for (std::unique_ptr<Package>& package : packages_) {
1551 package.reset();
1552 }
1553}
1554
Ryan Mitchell80094e32020-11-16 23:08:18 +00001555base::expected<std::monostate, IOError> Theme::SetTo(const Theme& o) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001556 if (this == &o) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001557 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001558 }
1559
Adam Lesinski7ad11102016-10-28 16:39:15 -07001560 type_spec_flags_ = o.type_spec_flags_;
1561
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001562 if (asset_manager_ == o.asset_manager_) {
1563 // The theme comes from the same asset manager so all theme data can be copied exactly
1564 for (size_t p = 0; p < packages_.size(); p++) {
1565 const Package *package = o.packages_[p].get();
1566 if (package == nullptr) {
1567 // The other theme doesn't have this package, clear ours.
1568 packages_[p].reset();
Adam Lesinski7ad11102016-10-28 16:39:15 -07001569 continue;
1570 }
1571
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001572 if (packages_[p] == nullptr) {
1573 // The other theme has this package, but we don't. Make one.
1574 packages_[p].reset(new Package());
1575 }
1576
1577 for (size_t t = 0; t < package->types.size(); t++) {
1578 const ThemeType *type = package->types[t].get();
1579 if (type == nullptr) {
1580 // The other theme doesn't have this type, clear ours.
1581 packages_[p]->types[t].reset();
1582 continue;
1583 }
1584
1585 // Create a new type and update it to theirs.
1586 const size_t type_alloc_size = sizeof(ThemeType) + (type->entry_count * sizeof(ThemeEntry));
1587 void *copied_data = malloc(type_alloc_size);
1588 memcpy(copied_data, type, type_alloc_size);
1589 packages_[p]->types[t].reset(reinterpret_cast<ThemeType *>(copied_data));
1590 }
1591 }
1592 } else {
1593 std::map<ApkAssetsCookie, ApkAssetsCookie> src_to_dest_asset_cookies;
1594 typedef std::map<int, int> SourceToDestinationRuntimePackageMap;
1595 std::map<ApkAssetsCookie, SourceToDestinationRuntimePackageMap> src_asset_cookie_id_map;
1596
Ryan Mitchell93bca972019-03-08 17:26:28 -08001597 // Determine which ApkAssets are loaded in both theme AssetManagers.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001598 std::vector<const ApkAssets*> src_assets = o.asset_manager_->GetApkAssets();
1599 for (size_t i = 0; i < src_assets.size(); i++) {
1600 const ApkAssets* src_asset = src_assets[i];
1601
1602 std::vector<const ApkAssets*> dest_assets = asset_manager_->GetApkAssets();
1603 for (size_t j = 0; j < dest_assets.size(); j++) {
1604 const ApkAssets* dest_asset = dest_assets[j];
1605
Ryan Mitchell93bca972019-03-08 17:26:28 -08001606 // Map the runtime package of the source apk asset to the destination apk asset.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001607 if (src_asset->GetPath() == dest_asset->GetPath()) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001608 const auto& src_packages = src_asset->GetLoadedArsc()->GetPackages();
1609 const auto& dest_packages = dest_asset->GetLoadedArsc()->GetPackages();
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001610
1611 SourceToDestinationRuntimePackageMap package_map;
1612
1613 // The source and destination package should have the same number of packages loaded in
1614 // the same order.
1615 const size_t N = src_packages.size();
1616 CHECK(N == dest_packages.size())
1617 << " LoadedArsc " << src_asset->GetPath() << " differs number of packages.";
1618 for (size_t p = 0; p < N; p++) {
1619 auto& src_package = src_packages[p];
1620 auto& dest_package = dest_packages[p];
1621 CHECK(src_package->GetPackageName() == dest_package->GetPackageName())
1622 << " Package " << src_package->GetPackageName() << " differs in load order.";
1623
1624 int src_package_id = o.asset_manager_->GetAssignedPackageId(src_package.get());
1625 int dest_package_id = asset_manager_->GetAssignedPackageId(dest_package.get());
1626 package_map[src_package_id] = dest_package_id;
1627 }
1628
Ryan Mitchell93bca972019-03-08 17:26:28 -08001629 src_to_dest_asset_cookies.insert(std::make_pair(i, j));
1630 src_asset_cookie_id_map.insert(std::make_pair(i, package_map));
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001631 break;
1632 }
1633 }
1634 }
1635
Ryan Mitchell93bca972019-03-08 17:26:28 -08001636 // Reset the data in the destination theme.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001637 for (size_t p = 0; p < packages_.size(); p++) {
1638 if (packages_[p] != nullptr) {
1639 packages_[p].reset();
1640 }
1641 }
1642
1643 for (size_t p = 0; p < packages_.size(); p++) {
1644 const Package *package = o.packages_[p].get();
1645 if (package == nullptr) {
1646 continue;
1647 }
1648
1649 for (size_t t = 0; t < package->types.size(); t++) {
1650 const ThemeType *type = package->types[t].get();
1651 if (type == nullptr) {
1652 continue;
1653 }
1654
1655 for (size_t e = 0; e < type->entry_count; e++) {
1656 const ThemeEntry &entry = type->entries[e];
1657 if (entry.value.dataType == Res_value::TYPE_NULL &&
1658 entry.value.data != Res_value::DATA_NULL_EMPTY) {
1659 continue;
1660 }
1661
Ryan Mitchell93bca972019-03-08 17:26:28 -08001662 bool is_reference = (entry.value.dataType == Res_value::TYPE_ATTRIBUTE
1663 || entry.value.dataType == Res_value::TYPE_REFERENCE
1664 || entry.value.dataType == Res_value::TYPE_DYNAMIC_ATTRIBUTE
1665 || entry.value.dataType == Res_value::TYPE_DYNAMIC_REFERENCE)
1666 && entry.value.data != 0x0;
Ryan Mitchellb85d9b22018-11-19 12:11:38 -08001667
Ryan Mitchell93bca972019-03-08 17:26:28 -08001668 // If the attribute value represents an attribute or reference, the package id of the
1669 // value needs to be rewritten to the package id of the value in the destination.
1670 uint32_t attribute_data = entry.value.data;
1671 if (is_reference) {
1672 // Determine the package id of the reference in the destination AssetManager.
Ryan Mitchellb85d9b22018-11-19 12:11:38 -08001673 auto value_package_map = src_asset_cookie_id_map.find(entry.cookie);
1674 if (value_package_map == src_asset_cookie_id_map.end()) {
1675 continue;
1676 }
1677
1678 auto value_dest_package = value_package_map->second.find(
1679 get_package_id(entry.value.data));
1680 if (value_dest_package == value_package_map->second.end()) {
1681 continue;
1682 }
1683
Ryan Mitchell93bca972019-03-08 17:26:28 -08001684 attribute_data = fix_package_id(entry.value.data, value_dest_package->second);
1685 }
1686
1687 // Find the cookie of the value in the destination. If the source apk is not loaded in the
1688 // destination, only copy resources that do not reference resources in the source.
1689 ApkAssetsCookie data_dest_cookie;
1690 auto value_dest_cookie = src_to_dest_asset_cookies.find(entry.cookie);
1691 if (value_dest_cookie != src_to_dest_asset_cookies.end()) {
1692 data_dest_cookie = value_dest_cookie->second;
1693 } else {
1694 if (is_reference || entry.value.dataType == Res_value::TYPE_STRING) {
1695 continue;
1696 } else {
1697 data_dest_cookie = 0x0;
1698 }
Ryan Mitchellb85d9b22018-11-19 12:11:38 -08001699 }
1700
1701 // The package id of the attribute needs to be rewritten to the package id of the
Ryan Mitchell93bca972019-03-08 17:26:28 -08001702 // attribute in the destination.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001703 int attribute_dest_package_id = p;
1704 if (attribute_dest_package_id != 0x01) {
Ryan Mitchell93bca972019-03-08 17:26:28 -08001705 // Find the cookie of the attribute resource id in the source AssetManager
Ryan Mitchell80094e32020-11-16 23:08:18 +00001706 base::expected<FindEntryResult, NullOrIOError> attribute_entry_result =
Ryan Mitchella55dc2e2019-01-24 10:58:23 -08001707 o.asset_manager_->FindEntry(make_resid(p, t, e), 0 /* density_override */ ,
1708 true /* stop_at_first_match */,
Ryan Mitchell80094e32020-11-16 23:08:18 +00001709 true /* ignore_configuration */);
1710 if (UNLIKELY(IsIOError(attribute_entry_result))) {
1711 return base::unexpected(GetIOError(attribute_entry_result.error()));
1712 }
1713 if (!attribute_entry_result.has_value()) {
1714 continue;
1715 }
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001716
Ryan Mitchell93bca972019-03-08 17:26:28 -08001717 // Determine the package id of the attribute in the destination AssetManager.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001718 auto attribute_package_map = src_asset_cookie_id_map.find(
1719 attribute_entry_result->cookie);
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001720 if (attribute_package_map == src_asset_cookie_id_map.end()) {
1721 continue;
1722 }
1723 auto attribute_dest_package = attribute_package_map->second.find(
1724 attribute_dest_package_id);
1725 if (attribute_dest_package == attribute_package_map->second.end()) {
1726 continue;
1727 }
1728 attribute_dest_package_id = attribute_dest_package->second;
1729 }
1730
Ryan Mitchell93bca972019-03-08 17:26:28 -08001731 // Lazily instantiate the destination package.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001732 std::unique_ptr<Package>& dest_package = packages_[attribute_dest_package_id];
1733 if (dest_package == nullptr) {
1734 dest_package.reset(new Package());
1735 }
1736
Ryan Mitchell93bca972019-03-08 17:26:28 -08001737 // Lazily instantiate and resize the destination type.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001738 util::unique_cptr<ThemeType>& dest_type = dest_package->types[t];
1739 if (dest_type == nullptr || dest_type->entry_count < type->entry_count) {
1740 const size_t type_alloc_size = sizeof(ThemeType)
1741 + (type->entry_count * sizeof(ThemeEntry));
1742 void* dest_data = malloc(type_alloc_size);
1743 memset(dest_data, 0, type->entry_count * sizeof(ThemeEntry));
1744
Ryan Mitchell93bca972019-03-08 17:26:28 -08001745 // Copy the existing destination type values if the type is resized.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001746 if (dest_type != nullptr) {
1747 memcpy(dest_data, type, sizeof(ThemeType)
1748 + (dest_type->entry_count * sizeof(ThemeEntry)));
1749 }
1750
1751 dest_type.reset(reinterpret_cast<ThemeType *>(dest_data));
1752 dest_type->entry_count = type->entry_count;
1753 }
1754
Ryan Mitchell93bca972019-03-08 17:26:28 -08001755 dest_type->entries[e].cookie = data_dest_cookie;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001756 dest_type->entries[e].value.dataType = entry.value.dataType;
Ryan Mitchell93bca972019-03-08 17:26:28 -08001757 dest_type->entries[e].value.data = attribute_data;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001758 dest_type->entries[e].type_spec_flags = entry.type_spec_flags;
1759 }
1760 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001761 }
1762 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001763 return {};
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001764}
1765
1766void Theme::Dump() const {
1767 base::ScopedLogSeverity _log(base::INFO);
1768 LOG(INFO) << base::StringPrintf("Theme(this=%p, AssetManager2=%p)", this, asset_manager_);
1769
1770 for (int p = 0; p < packages_.size(); p++) {
1771 auto& package = packages_[p];
1772 if (package == nullptr) {
1773 continue;
1774 }
1775
1776 for (int t = 0; t < package->types.size(); t++) {
1777 auto& type = package->types[t];
1778 if (type == nullptr) {
1779 continue;
1780 }
1781
1782 for (int e = 0; e < type->entry_count; e++) {
1783 auto& entry = type->entries[e];
1784 if (entry.value.dataType == Res_value::TYPE_NULL &&
1785 entry.value.data != Res_value::DATA_NULL_EMPTY) {
1786 continue;
1787 }
1788
1789 LOG(INFO) << base::StringPrintf(" entry(0x%08x)=(0x%08x) type=(0x%02x), cookie(%d)",
1790 make_resid(p, t, e), entry.value.data,
1791 entry.value.dataType, entry.cookie);
1792 }
1793 }
1794 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001795}
1796
1797} // namespace android