blob: d349628c2ab449d23114095d9bfa26b51386440b [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 Mitchellc75c2e02020-08-17 08:42:48 -070041namespace {
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 Mitchellc75c2e02020-08-17 08:42:48 -070072 // 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 Mitchellc75c2e02020-08-17 08:42:48 -0700302 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 Mitchellc75c2e02020-08-17 08:42:48 -0700347 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 Mitchellc75c2e02020-08-17 08:42:48 -0700354 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 Mitchellc75c2e02020-08-17 08:42:48 -0700402base::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 Mitchellc75c2e02020-08-17 08:42:48 -0700423 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 Mitchellc75c2e02020-08-17 08:42:48 -0700541base::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 Mitchellc75c2e02020-08-17 08:42:48 -0700563 if (UNLIKELY(!is_valid_resid(resid))) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500564 LOG(ERROR) << base::StringPrintf("Invalid ID 0x%08x.", resid);
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700565 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 Mitchellc75c2e02020-08-17 08:42:48 -0700572 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 Mitchellc75c2e02020-08-17 08:42:48 -0700575 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 Mitchellc75c2e02020-08-17 08:42:48 -0700579 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 Mitchellc75c2e02020-08-17 08:42:48 -0700585 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 Mitchellc75c2e02020-08-17 08:42:48 -0700591 }
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 Mitchellc75c2e02020-08-17 08:42:48 -0700594 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 Mitchellc75c2e02020-08-17 08:42:48 -0700600 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 Mitchellc75c2e02020-08-17 08:42:48 -0700610 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 Mitchellc75c2e02020-08-17 08:42:48 -0700617 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 Mitchellc75c2e02020-08-17 08:42:48 -0700624 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 Mitchellc75c2e02020-08-17 08:42:48 -0700630 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 Mitchellc75c2e02020-08-17 08:42:48 -0700636 return result;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700637}
638
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700639base::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 Mitchellc75c2e02020-08-17 08:42:48 -0700646 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 Mitchellc75c2e02020-08-17 08:42:48 -0700649 uint32_t best_offset = 0U;
650 uint32_t type_flags = 0U;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800651
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700652 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 Mitchellc75c2e02020-08-17 08:42:48 -0700672 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 Mitchellc75c2e02020-08-17 08:42:48 -0700684 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 Mitchellc75c2e02020-08-17 08:42:48 -0700697 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 Mitchellc75c2e02020-08-17 08:42:48 -0700709 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 Mitchellc75c2e02020-08-17 08:42:48 -0700732 best_offset = offset.value();
Winson2f3669b2019-01-11 11:28:34 -0800733
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700734 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 Mitchellc75c2e02020-08-17 08:42:48 -0700748 const incfs::verified_map_ptr<ResTable_type>& type = *iter;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800749
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700750 ResTable_config this_config{};
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800751 if (!ignore_configuration) {
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700752 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 Mitchellc75c2e02020-08-17 08:42:48 -0700771 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 Mitchellc75c2e02020-08-17 08:42:48 -0700781 best_type = type;
Winson2f3669b2019-01-11 11:28:34 -0800782 best_config_copy = this_config;
783 best_config = &best_config_copy;
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700784 best_offset = offset.value();
Winson2f3669b2019-01-11 11:28:34 -0800785
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700786 if (stop_at_first_match) {
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800787 // Any configuration will suffice, so break.
788 break;
789 }
790
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700791 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 Mitchellc75c2e02020-08-17 08:42:48 -0700801 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700802 }
803
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700804 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 Mitchellc75c2e02020-08-17 08:42:48 -0700809 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 Mitchellc75c2e02020-08-17 08:42:48 -0700814 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 Mitchellc75c2e02020-08-17 08:42:48 -0700819 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 Mitchellc75c2e02020-08-17 08:42:48 -0700850 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 Mitchellc75c2e02020-08-17 08:42:48 -0700856 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 Mitchellc75c2e02020-08-17 08:42:48 -0700867 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 Mitchellc75c2e02020-08-17 08:42:48 -0700924base::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 Mitchellc75c2e02020-08-17 08:42:48 -0700932 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 Mitchellc75c2e02020-08-17 08:42:48 -0700937base::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 Mitchellc75c2e02020-08-17 08:42:48 -0700945 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 Mitchellc75c2e02020-08-17 08:42:48 -0700949 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 Mitchellc75c2e02020-08-17 08:42:48 -0700953 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 Mitchellc75c2e02020-08-17 08:42:48 -0700958 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 Mitchellc75c2e02020-08-17 08:42:48 -0700961 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 Mitchellc75c2e02020-08-17 08:42:48 -0700965base::expected<std::monostate, NullOrIOError> AssetManager2::ResolveReference(
Ryan Mitchell87e89542020-10-05 14:24:35 -0700966 AssetManager2::SelectedValue& value, bool cache_value) const {
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700967 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 Mitchellc75c2e02020-08-17 08:42:48 -0700971
Ryan Mitchell87e89542020-10-05 14:24:35 -0700972 const uint32_t original_flags = value.flags;
973 const uint32_t original_resid = value.data;
974 if (cache_value) {
975 auto cached_value = cached_resolved_values_.find(value.data);
976 if (cached_value != cached_resolved_values_.end()) {
977 value = cached_value->second;
978 value.flags |= original_flags;
979 return {};
980 }
981 }
982
983 uint32_t combined_flags = 0U;
984 uint32_t resolve_resid = original_resid;
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700985 constexpr const uint32_t kMaxIterations = 20;
986 for (uint32_t i = 0U;; i++) {
987 auto result = GetResource(resolve_resid, true /*may_be_bag*/);
988 if (!result.has_value()) {
989 return base::unexpected(result.error());
990 }
991
992 if (result->type != Res_value::TYPE_REFERENCE ||
993 result->data == Res_value::DATA_NULL_UNDEFINED ||
994 result->data == resolve_resid || i == kMaxIterations) {
Ryan Mitchell87e89542020-10-05 14:24:35 -0700995 result->flags |= combined_flags;
996 if (cache_value) {
997 cached_resolved_values_[original_resid] = *result;
998 }
999
1000 // Add the original flags after caching the result so queries with a different set of original
1001 // flags do not include these original flags.
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001002 value = *result;
Ryan Mitchell87e89542020-10-05 14:24:35 -07001003 value.flags |= original_flags;
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001004 return {};
1005 }
1006
1007 combined_flags |= result->flags;
1008 resolve_resid = result->data;
1009 }
Adam Lesinski0c405242017-01-13 20:47:26 -08001010}
1011
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001012const std::vector<uint32_t> AssetManager2::GetBagResIdStack(uint32_t resid) const {
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001013 auto cached_iter = cached_bag_resid_stacks_.find(resid);
1014 if (cached_iter != cached_bag_resid_stacks_.end()) {
1015 return cached_iter->second;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001016 }
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001017
1018 std::vector<uint32_t> found_resids;
1019 GetBag(resid, found_resids);
1020 cached_bag_resid_stacks_.emplace(resid, found_resids);
1021 return found_resids;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001022}
1023
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001024base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::ResolveBag(
1025 AssetManager2::SelectedValue& value) const {
1026 if (UNLIKELY(value.type != Res_value::TYPE_REFERENCE)) {
1027 return base::unexpected(std::nullopt);
1028 }
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001029
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001030 auto bag = GetBag(value.data);
1031 if (bag.has_value()) {
1032 value.flags |= (*bag)->type_spec_flags;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001033 }
1034 return bag;
y57cd1952018-04-12 14:26:23 -07001035}
1036
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001037base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::GetBag(uint32_t resid) const {
1038 std::vector<uint32_t> found_resids;
Ryan Mitchell06a73312020-11-13 23:55:20 +00001039 const auto bag = GetBag(resid, found_resids);
1040 cached_bag_resid_stacks_.emplace(resid, found_resids);
1041 return bag;
Ryan Mitchell155d5392020-02-10 13:35:24 -08001042}
1043
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001044base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::GetBag(
1045 uint32_t resid, std::vector<uint32_t>& child_resids) const {
1046 if (auto cached_iter = cached_bags_.find(resid); cached_iter != cached_bags_.end()) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001047 return cached_iter->second.get();
1048 }
1049
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001050 auto entry = FindEntry(resid, 0u /* density_override */, false /* stop_at_first_match */,
1051 false /* ignore_configuration */);
1052 if (!entry.has_value()) {
1053 return base::unexpected(entry.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001054 }
1055
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001056 auto entry_map = std::get_if<incfs::verified_map_ptr<ResTable_map_entry>>(&entry->entry);
1057 if (entry_map == nullptr) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001058 // Not a bag, nothing to do.
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001059 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001060 }
1061
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001062 auto map = *entry_map;
1063 auto map_entry = map.offset(dtohs(map->size)).convert<ResTable_map>();
1064 const auto map_entry_end = map_entry + dtohl(map->count);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001065
y57cd1952018-04-12 14:26:23 -07001066 // Keep track of ids that have already been seen to prevent infinite loops caused by circular
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001067 // dependencies between bags.
y57cd1952018-04-12 14:26:23 -07001068 child_resids.push_back(resid);
1069
Adam Lesinskida431a22016-12-29 16:08:16 -05001070 uint32_t parent_resid = dtohl(map->parent.ident);
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001071 if (parent_resid == 0U ||
1072 std::find(child_resids.begin(), child_resids.end(), parent_resid) != child_resids.end()) {
1073 // There is no parent or a circular parental dependency exist, meaning there is nothing to
1074 // inherit and we can do a simple copy of the entries in the map.
Adam Lesinski7ad11102016-10-28 16:39:15 -07001075 const size_t entry_count = map_entry_end - map_entry;
1076 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
1077 malloc(sizeof(ResolvedBag) + (entry_count * sizeof(ResolvedBag::Entry))))};
Ryan Mitchell155d5392020-02-10 13:35:24 -08001078
1079 bool sort_entries = false;
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001080 for (auto new_entry = new_bag->entries; map_entry != map_entry_end; ++map_entry) {
1081 if (UNLIKELY(!map_entry)) {
1082 return base::unexpected(IOError::PAGES_MISSING);
1083 }
1084
Adam Lesinskida431a22016-12-29 16:08:16 -05001085 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001086 if (!is_internal_resid(new_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -05001087 // Attributes, arrays, etc don't have a resource id as the name. They specify
1088 // other data, which would be wrong to change via a lookup.
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001089 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001090 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
1091 resid);
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001092 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001093 }
1094 }
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001095
1096 new_entry->cookie = entry->cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -05001097 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001098 new_entry->key_pool = nullptr;
1099 new_entry->type_pool = nullptr;
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001100 new_entry->style = resid;
Adam Lesinski30080e22017-10-16 16:18:09 -07001101 new_entry->value.copyFrom_dtoh(map_entry->value);
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001102 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1103 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001104 LOG(ERROR) << base::StringPrintf(
1105 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
1106 new_entry->value.data, new_key);
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001107 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001108 }
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001109
Ryan Mitchell155d5392020-02-10 13:35:24 -08001110 sort_entries = sort_entries ||
1111 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001112 ++new_entry;
1113 }
Ryan Mitchell155d5392020-02-10 13:35:24 -08001114
1115 if (sort_entries) {
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001116 std::sort(new_bag->entries, new_bag->entries + entry_count,
1117 [](auto&& lhs, auto&& rhs) { return lhs.key < rhs.key; });
Ryan Mitchell155d5392020-02-10 13:35:24 -08001118 }
1119
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001120 new_bag->type_spec_flags = entry->type_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001121 new_bag->entry_count = static_cast<uint32_t>(entry_count);
1122 ResolvedBag* result = new_bag.get();
1123 cached_bags_[resid] = std::move(new_bag);
1124 return result;
1125 }
1126
Adam Lesinskida431a22016-12-29 16:08:16 -05001127 // In case the parent is a dynamic reference, resolve it.
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001128 entry->dynamic_ref_table->lookupResourceId(&parent_resid);
Adam Lesinskida431a22016-12-29 16:08:16 -05001129
Adam Lesinski7ad11102016-10-28 16:39:15 -07001130 // Get the parent and do a merge of the keys.
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001131 const auto parent_bag = GetBag(parent_resid, child_resids);
1132 if (UNLIKELY(!parent_bag.has_value())) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001133 // Failed to get the parent that should exist.
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001134 LOG(ERROR) << base::StringPrintf("Failed to find parent 0x%08x of bag 0x%08x.", parent_resid,
1135 resid);
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001136 return base::unexpected(parent_bag.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001137 }
1138
Adam Lesinski7ad11102016-10-28 16:39:15 -07001139 // Create the max possible entries we can make. Once we construct the bag,
1140 // we will realloc to fit to size.
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001141 const size_t max_count = (*parent_bag)->entry_count + dtohl(map->count);
George Burgess IV09b119f2017-07-25 15:00:04 -07001142 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
1143 malloc(sizeof(ResolvedBag) + (max_count * sizeof(ResolvedBag::Entry))))};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001144 ResolvedBag::Entry* new_entry = new_bag->entries;
1145
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001146 const ResolvedBag::Entry* parent_entry = (*parent_bag)->entries;
1147 const ResolvedBag::Entry* const parent_entry_end = parent_entry + (*parent_bag)->entry_count;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001148
1149 // The keys are expected to be in sorted order. Merge the two bags.
Ryan Mitchell155d5392020-02-10 13:35:24 -08001150 bool sort_entries = false;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001151 while (map_entry != map_entry_end && parent_entry != parent_entry_end) {
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001152 if (UNLIKELY(!map_entry)) {
1153 return base::unexpected(IOError::PAGES_MISSING);
1154 }
1155
Adam Lesinskida431a22016-12-29 16:08:16 -05001156 uint32_t child_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001157 if (!is_internal_resid(child_key)) {
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001158 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&child_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001159 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", child_key,
1160 resid);
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001161 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001162 }
1163 }
1164
Adam Lesinski7ad11102016-10-28 16:39:15 -07001165 if (child_key <= parent_entry->key) {
1166 // Use the child key if it comes before the parent
1167 // or is equal to the parent (overrides).
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001168 new_entry->cookie = entry->cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001169 new_entry->key = child_key;
1170 new_entry->key_pool = nullptr;
1171 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -07001172 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001173 new_entry->style = resid;
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001174 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1175 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001176 LOG(ERROR) << base::StringPrintf(
1177 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
1178 new_entry->value.data, child_key);
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001179 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001180 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001181 ++map_entry;
1182 } else {
1183 // Take the parent entry as-is.
1184 memcpy(new_entry, parent_entry, sizeof(*new_entry));
1185 }
1186
Ryan Mitchell155d5392020-02-10 13:35:24 -08001187 sort_entries = sort_entries ||
1188 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001189 if (child_key >= parent_entry->key) {
1190 // Move to the next parent entry if we used it or it was overridden.
1191 ++parent_entry;
1192 }
1193 // Increment to the next entry to fill.
1194 ++new_entry;
1195 }
1196
1197 // Finish the child entries if they exist.
1198 while (map_entry != map_entry_end) {
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001199 if (UNLIKELY(!map_entry)) {
1200 return base::unexpected(IOError::PAGES_MISSING);
1201 }
1202
Adam Lesinskida431a22016-12-29 16:08:16 -05001203 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001204 if (!is_internal_resid(new_key)) {
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001205 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001206 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
1207 resid);
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001208 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001209 }
1210 }
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001211 new_entry->cookie = entry->cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -05001212 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001213 new_entry->key_pool = nullptr;
1214 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -07001215 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001216 new_entry->style = resid;
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001217 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1218 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001219 LOG(ERROR) << base::StringPrintf("Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.",
1220 new_entry->value.dataType, new_entry->value.data, new_key);
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001221 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001222 }
Ryan Mitchell155d5392020-02-10 13:35:24 -08001223 sort_entries = sort_entries ||
1224 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001225 ++map_entry;
1226 ++new_entry;
1227 }
1228
1229 // Finish the parent entries if they exist.
1230 if (parent_entry != parent_entry_end) {
1231 // Take the rest of the parent entries as-is.
1232 const size_t num_entries_to_copy = parent_entry_end - parent_entry;
1233 memcpy(new_entry, parent_entry, num_entries_to_copy * sizeof(*new_entry));
1234 new_entry += num_entries_to_copy;
1235 }
1236
1237 // Resize the resulting array to fit.
1238 const size_t actual_count = new_entry - new_bag->entries;
1239 if (actual_count != max_count) {
George Burgess IV09b119f2017-07-25 15:00:04 -07001240 new_bag.reset(reinterpret_cast<ResolvedBag*>(realloc(
1241 new_bag.release(), sizeof(ResolvedBag) + (actual_count * sizeof(ResolvedBag::Entry)))));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001242 }
1243
Ryan Mitchell155d5392020-02-10 13:35:24 -08001244 if (sort_entries) {
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001245 std::sort(new_bag->entries, new_bag->entries + actual_count,
1246 [](auto&& lhs, auto&& rhs) { return lhs.key < rhs.key; });
Ryan Mitchell155d5392020-02-10 13:35:24 -08001247 }
1248
Adam Lesinski1a1e9c22017-10-13 15:45:34 -07001249 // Combine flags from the parent and our own bag.
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001250 new_bag->type_spec_flags = entry->type_flags | (*parent_bag)->type_spec_flags;
George Burgess IV09b119f2017-07-25 15:00:04 -07001251 new_bag->entry_count = static_cast<uint32_t>(actual_count);
1252 ResolvedBag* result = new_bag.get();
1253 cached_bags_[resid] = std::move(new_bag);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001254 return result;
1255}
1256
Adam Lesinski929d6512017-01-16 19:11:19 -08001257static bool Utf8ToUtf16(const StringPiece& str, std::u16string* out) {
1258 ssize_t len =
1259 utf8_to_utf16_length(reinterpret_cast<const uint8_t*>(str.data()), str.size(), false);
1260 if (len < 0) {
1261 return false;
1262 }
1263 out->resize(static_cast<size_t>(len));
1264 utf8_to_utf16(reinterpret_cast<const uint8_t*>(str.data()), str.size(), &*out->begin(),
1265 static_cast<size_t>(len + 1));
1266 return true;
1267}
1268
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001269base::expected<uint32_t, NullOrIOError> AssetManager2::GetResourceId(
1270 const std::string& resource_name, const std::string& fallback_type,
1271 const std::string& fallback_package) const {
Adam Lesinski929d6512017-01-16 19:11:19 -08001272 StringPiece package_name, type, entry;
1273 if (!ExtractResourceName(resource_name, &package_name, &type, &entry)) {
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001274 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001275 }
1276
1277 if (entry.empty()) {
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001278 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001279 }
1280
1281 if (package_name.empty()) {
1282 package_name = fallback_package;
1283 }
1284
1285 if (type.empty()) {
1286 type = fallback_type;
1287 }
1288
1289 std::u16string type16;
1290 if (!Utf8ToUtf16(type, &type16)) {
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001291 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001292 }
1293
1294 std::u16string entry16;
1295 if (!Utf8ToUtf16(entry, &entry16)) {
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001296 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001297 }
1298
1299 const StringPiece16 kAttr16 = u"attr";
1300 const static std::u16string kAttrPrivate16 = u"^attr-private";
1301
1302 for (const PackageGroup& package_group : package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001303 for (const ConfiguredPackage& package_impl : package_group.packages_) {
1304 const LoadedPackage* package = package_impl.loaded_package_;
Adam Lesinski929d6512017-01-16 19:11:19 -08001305 if (package_name != package->GetPackageName()) {
1306 // All packages in the same group are expected to have the same package name.
1307 break;
1308 }
1309
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001310 base::expected<uint32_t, NullOrIOError> resid = package->FindEntryByName(type16, entry16);
1311 if (UNLIKELY(IsIOError(resid))) {
1312 return base::unexpected(resid.error());
1313 }
1314
1315 if (!resid.has_value() && kAttr16 == type16) {
Adam Lesinski929d6512017-01-16 19:11:19 -08001316 // Private attributes in libraries (such as the framework) are sometimes encoded
1317 // under the type '^attr-private' in order to leave the ID space of public 'attr'
1318 // free for future additions. Check '^attr-private' for the same name.
1319 resid = package->FindEntryByName(kAttrPrivate16, entry16);
1320 }
1321
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001322 if (resid.has_value()) {
1323 return fix_package_id(*resid, package_group.dynamic_ref_table->mAssignedPackageId);
Adam Lesinski929d6512017-01-16 19:11:19 -08001324 }
1325 }
1326 }
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001327 return base::unexpected(std::nullopt);
Adam Lesinski0c405242017-01-13 20:47:26 -08001328}
1329
Mårten Kongstad668ec5b2018-06-11 14:11:33 +02001330void AssetManager2::RebuildFilterList(bool filter_incompatible_configs) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001331 for (PackageGroup& group : package_groups_) {
1332 for (ConfiguredPackage& impl : group.packages_) {
1333 // Destroy it.
1334 impl.filtered_configs_.~ByteBucketArray();
1335
1336 // Re-create it.
1337 new (&impl.filtered_configs_) ByteBucketArray<FilteredConfigGroup>();
1338
1339 // Create the filters here.
1340 impl.loaded_package_->ForEachTypeSpec([&](const TypeSpec* spec, uint8_t type_index) {
1341 FilteredConfigGroup& group = impl.filtered_configs_.editItemAt(type_index);
1342 const auto iter_end = spec->types + spec->type_count;
1343 for (auto iter = spec->types; iter != iter_end; ++iter) {
1344 ResTable_config this_config;
1345 this_config.copyFromDtoH((*iter)->config);
Mårten Kongstad668ec5b2018-06-11 14:11:33 +02001346 if (!filter_incompatible_configs || this_config.match(configuration_)) {
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001347 group.type_configs.push_back(TypeConfig{*iter, this_config});
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001348 }
1349 }
1350 });
1351 }
1352 }
1353}
1354
Adam Lesinski7ad11102016-10-28 16:39:15 -07001355void AssetManager2::InvalidateCaches(uint32_t diff) {
Ryan Mitchell2c4d8742019-03-04 09:41:00 -08001356 cached_bag_resid_stacks_.clear();
1357
Adam Lesinski7ad11102016-10-28 16:39:15 -07001358 if (diff == 0xffffffffu) {
1359 // Everything must go.
1360 cached_bags_.clear();
1361 return;
1362 }
1363
1364 // Be more conservative with what gets purged. Only if the bag has other possible
1365 // variations with respect to what changed (diff) should we remove it.
1366 for (auto iter = cached_bags_.cbegin(); iter != cached_bags_.cend();) {
1367 if (diff & iter->second->type_spec_flags) {
1368 iter = cached_bags_.erase(iter);
1369 } else {
1370 ++iter;
1371 }
1372 }
Ryan Mitchell87e89542020-10-05 14:24:35 -07001373
1374 cached_resolved_values_.clear();
Adam Lesinski7ad11102016-10-28 16:39:15 -07001375}
1376
Ryan Mitchell2e394222019-08-28 12:10:51 -07001377uint8_t AssetManager2::GetAssignedPackageId(const LoadedPackage* package) const {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001378 for (auto& package_group : package_groups_) {
1379 for (auto& package2 : package_group.packages_) {
1380 if (package2.loaded_package_ == package) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -07001381 return package_group.dynamic_ref_table->mAssignedPackageId;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001382 }
1383 }
1384 }
1385 return 0;
1386}
1387
Adam Lesinski30080e22017-10-16 16:18:09 -07001388std::unique_ptr<Theme> AssetManager2::NewTheme() {
1389 return std::unique_ptr<Theme>(new Theme(this));
1390}
1391
1392Theme::Theme(AssetManager2* asset_manager) : asset_manager_(asset_manager) {
1393}
1394
1395Theme::~Theme() = default;
1396
1397namespace {
1398
1399struct ThemeEntry {
1400 ApkAssetsCookie cookie;
1401 uint32_t type_spec_flags;
1402 Res_value value;
1403};
1404
1405struct ThemeType {
1406 int entry_count;
1407 ThemeEntry entries[0];
1408};
1409
1410constexpr size_t kTypeCount = std::numeric_limits<uint8_t>::max() + 1;
1411
1412} // namespace
1413
1414struct Theme::Package {
1415 // Each element of Type will be a dynamically sized object
1416 // allocated to have the entries stored contiguously with the Type.
1417 std::array<util::unique_cptr<ThemeType>, kTypeCount> types;
1418};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001419
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001420base::expected<std::monostate, NullOrIOError> Theme::ApplyStyle(uint32_t resid, bool force) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001421 ATRACE_NAME("Theme::ApplyStyle");
Adam Lesinski7ad11102016-10-28 16:39:15 -07001422
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001423 auto bag = asset_manager_->GetBag(resid);
1424 if (!bag.has_value()) {
1425 return base::unexpected(bag.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001426 }
1427
1428 // Merge the flags from this style.
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001429 type_spec_flags_ |= (*bag)->type_spec_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001430
Adam Lesinski30080e22017-10-16 16:18:09 -07001431 int last_type_idx = -1;
1432 int last_package_idx = -1;
1433 Package* last_package = nullptr;
1434 ThemeType* last_type = nullptr;
1435
1436 // Iterate backwards, because each bag is sorted in ascending key ID order, meaning we will only
1437 // need to perform one resize per type.
1438 using reverse_bag_iterator = std::reverse_iterator<const ResolvedBag::Entry*>;
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001439 const auto rbegin = reverse_bag_iterator(begin(*bag));
1440 for (auto it = reverse_bag_iterator(end(*bag)); it != rbegin; ++it) {
1441 const uint32_t attr_resid = it->key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001442
Adam Lesinski30080e22017-10-16 16:18:09 -07001443 // If the resource ID passed in is not a style, the key can be some other identifier that is not
1444 // a resource ID. We should fail fast instead of operating with strange resource IDs.
Adam Lesinski929d6512017-01-16 19:11:19 -08001445 if (!is_valid_resid(attr_resid)) {
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001446 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001447 }
1448
Adam Lesinski30080e22017-10-16 16:18:09 -07001449 // We don't use the 0-based index for the type so that we can avoid doing ID validation
1450 // upon lookup. Instead, we keep space for the type ID 0 in our data structures. Since
1451 // the construction of this type is guarded with a resource ID check, it will never be
1452 // populated, and querying type ID 0 will always fail.
1453 const int package_idx = get_package_id(attr_resid);
1454 const int type_idx = get_type_id(attr_resid);
1455 const int entry_idx = get_entry_id(attr_resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001456
Adam Lesinski30080e22017-10-16 16:18:09 -07001457 if (last_package_idx != package_idx) {
1458 std::unique_ptr<Package>& package = packages_[package_idx];
1459 if (package == nullptr) {
1460 package.reset(new Package());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001461 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001462 last_package_idx = package_idx;
1463 last_package = package.get();
1464 last_type_idx = -1;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001465 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001466
1467 if (last_type_idx != type_idx) {
1468 util::unique_cptr<ThemeType>& type = last_package->types[type_idx];
1469 if (type == nullptr) {
1470 // Allocate enough memory to contain this entry_idx. Since we're iterating in reverse over
1471 // a sorted list of attributes, this shouldn't be resized again during this method call.
1472 type.reset(reinterpret_cast<ThemeType*>(
1473 calloc(sizeof(ThemeType) + (entry_idx + 1) * sizeof(ThemeEntry), 1)));
1474 type->entry_count = entry_idx + 1;
1475 } else if (entry_idx >= type->entry_count) {
1476 // Reallocate the memory to contain this entry_idx. Since we're iterating in reverse over
1477 // a sorted list of attributes, this shouldn't be resized again during this method call.
1478 const int new_count = entry_idx + 1;
1479 type.reset(reinterpret_cast<ThemeType*>(
1480 realloc(type.release(), sizeof(ThemeType) + (new_count * sizeof(ThemeEntry)))));
1481
1482 // Clear out the newly allocated space (which isn't zeroed).
1483 memset(type->entries + type->entry_count, 0,
1484 (new_count - type->entry_count) * sizeof(ThemeEntry));
1485 type->entry_count = new_count;
1486 }
1487 last_type_idx = type_idx;
1488 last_type = type.get();
1489 }
1490
1491 ThemeEntry& entry = last_type->entries[entry_idx];
1492 if (force || (entry.value.dataType == Res_value::TYPE_NULL &&
1493 entry.value.data != Res_value::DATA_NULL_EMPTY)) {
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001494 entry.cookie = it->cookie;
1495 entry.type_spec_flags |= (*bag)->type_spec_flags;
1496 entry.value = it->value;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001497 }
1498 }
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001499 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001500}
1501
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001502std::optional<AssetManager2::SelectedValue> Theme::GetAttribute(uint32_t resid) const {
1503
Adam Lesinski30080e22017-10-16 16:18:09 -07001504 int cnt = 20;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001505 uint32_t type_spec_flags = 0u;
Adam Lesinski30080e22017-10-16 16:18:09 -07001506 do {
1507 const int package_idx = get_package_id(resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001508 const Package* package = packages_[package_idx].get();
Adam Lesinski30080e22017-10-16 16:18:09 -07001509 if (package != nullptr) {
1510 // The themes are constructed with a 1-based type ID, so no need to decrement here.
1511 const int type_idx = get_type_id(resid);
1512 const ThemeType* type = package->types[type_idx].get();
1513 if (type != nullptr) {
1514 const int entry_idx = get_entry_id(resid);
1515 if (entry_idx < type->entry_count) {
1516 const ThemeEntry& entry = type->entries[entry_idx];
1517 type_spec_flags |= entry.type_spec_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001518
Adam Lesinski30080e22017-10-16 16:18:09 -07001519 if (entry.value.dataType == Res_value::TYPE_ATTRIBUTE) {
1520 if (cnt > 0) {
1521 cnt--;
1522 resid = entry.value.data;
1523 continue;
1524 }
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001525 return std::nullopt;
Adam Lesinski30080e22017-10-16 16:18:09 -07001526 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001527
Adam Lesinski30080e22017-10-16 16:18:09 -07001528 // @null is different than @empty.
1529 if (entry.value.dataType == Res_value::TYPE_NULL &&
1530 entry.value.data != Res_value::DATA_NULL_EMPTY) {
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001531 return std::nullopt;
Adam Lesinski30080e22017-10-16 16:18:09 -07001532 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001533
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001534 return AssetManager2::SelectedValue(entry.value.dataType, entry.value.data, entry.cookie,
1535 type_spec_flags, 0U /* resid */, {} /* config */);
Adam Lesinskida431a22016-12-29 16:08:16 -05001536 }
Adam Lesinskida431a22016-12-29 16:08:16 -05001537 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001538 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001539 break;
1540 } while (true);
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001541 return std::nullopt;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001542}
1543
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001544base::expected<std::monostate, NullOrIOError> Theme::ResolveAttributeReference(
1545 AssetManager2::SelectedValue& value) const {
1546 if (value.type != Res_value::TYPE_ATTRIBUTE) {
1547 return asset_manager_->ResolveReference(value);
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001548 }
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001549
1550 std::optional<AssetManager2::SelectedValue> result = GetAttribute(value.data);
1551 if (!result.has_value()) {
1552 return base::unexpected(std::nullopt);
1553 }
1554
Ryan Mitchell87e89542020-10-05 14:24:35 -07001555 auto resolve_result = asset_manager_->ResolveReference(*result, true /* cache_value */);
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001556 if (resolve_result.has_value()) {
1557 result->flags |= value.flags;
1558 value = *result;
1559 }
1560 return resolve_result;
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001561}
1562
Adam Lesinski7ad11102016-10-28 16:39:15 -07001563void Theme::Clear() {
1564 type_spec_flags_ = 0u;
1565 for (std::unique_ptr<Package>& package : packages_) {
1566 package.reset();
1567 }
1568}
1569
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001570base::expected<std::monostate, IOError> Theme::SetTo(const Theme& o) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001571 if (this == &o) {
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001572 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001573 }
1574
Adam Lesinski7ad11102016-10-28 16:39:15 -07001575 type_spec_flags_ = o.type_spec_flags_;
1576
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001577 if (asset_manager_ == o.asset_manager_) {
1578 // The theme comes from the same asset manager so all theme data can be copied exactly
1579 for (size_t p = 0; p < packages_.size(); p++) {
1580 const Package *package = o.packages_[p].get();
1581 if (package == nullptr) {
1582 // The other theme doesn't have this package, clear ours.
1583 packages_[p].reset();
Adam Lesinski7ad11102016-10-28 16:39:15 -07001584 continue;
1585 }
1586
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001587 if (packages_[p] == nullptr) {
1588 // The other theme has this package, but we don't. Make one.
1589 packages_[p].reset(new Package());
1590 }
1591
1592 for (size_t t = 0; t < package->types.size(); t++) {
1593 const ThemeType *type = package->types[t].get();
1594 if (type == nullptr) {
1595 // The other theme doesn't have this type, clear ours.
1596 packages_[p]->types[t].reset();
1597 continue;
1598 }
1599
1600 // Create a new type and update it to theirs.
1601 const size_t type_alloc_size = sizeof(ThemeType) + (type->entry_count * sizeof(ThemeEntry));
1602 void *copied_data = malloc(type_alloc_size);
1603 memcpy(copied_data, type, type_alloc_size);
1604 packages_[p]->types[t].reset(reinterpret_cast<ThemeType *>(copied_data));
1605 }
1606 }
1607 } else {
1608 std::map<ApkAssetsCookie, ApkAssetsCookie> src_to_dest_asset_cookies;
1609 typedef std::map<int, int> SourceToDestinationRuntimePackageMap;
1610 std::map<ApkAssetsCookie, SourceToDestinationRuntimePackageMap> src_asset_cookie_id_map;
1611
Ryan Mitchell93bca972019-03-08 17:26:28 -08001612 // Determine which ApkAssets are loaded in both theme AssetManagers.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001613 std::vector<const ApkAssets*> src_assets = o.asset_manager_->GetApkAssets();
1614 for (size_t i = 0; i < src_assets.size(); i++) {
1615 const ApkAssets* src_asset = src_assets[i];
1616
1617 std::vector<const ApkAssets*> dest_assets = asset_manager_->GetApkAssets();
1618 for (size_t j = 0; j < dest_assets.size(); j++) {
1619 const ApkAssets* dest_asset = dest_assets[j];
1620
Ryan Mitchell93bca972019-03-08 17:26:28 -08001621 // Map the runtime package of the source apk asset to the destination apk asset.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001622 if (src_asset->GetPath() == dest_asset->GetPath()) {
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001623 const auto& src_packages = src_asset->GetLoadedArsc()->GetPackages();
1624 const auto& dest_packages = dest_asset->GetLoadedArsc()->GetPackages();
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001625
1626 SourceToDestinationRuntimePackageMap package_map;
1627
1628 // The source and destination package should have the same number of packages loaded in
1629 // the same order.
1630 const size_t N = src_packages.size();
1631 CHECK(N == dest_packages.size())
1632 << " LoadedArsc " << src_asset->GetPath() << " differs number of packages.";
1633 for (size_t p = 0; p < N; p++) {
1634 auto& src_package = src_packages[p];
1635 auto& dest_package = dest_packages[p];
1636 CHECK(src_package->GetPackageName() == dest_package->GetPackageName())
1637 << " Package " << src_package->GetPackageName() << " differs in load order.";
1638
1639 int src_package_id = o.asset_manager_->GetAssignedPackageId(src_package.get());
1640 int dest_package_id = asset_manager_->GetAssignedPackageId(dest_package.get());
1641 package_map[src_package_id] = dest_package_id;
1642 }
1643
Ryan Mitchell93bca972019-03-08 17:26:28 -08001644 src_to_dest_asset_cookies.insert(std::make_pair(i, j));
1645 src_asset_cookie_id_map.insert(std::make_pair(i, package_map));
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001646 break;
1647 }
1648 }
1649 }
1650
Ryan Mitchell93bca972019-03-08 17:26:28 -08001651 // Reset the data in the destination theme.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001652 for (size_t p = 0; p < packages_.size(); p++) {
1653 if (packages_[p] != nullptr) {
1654 packages_[p].reset();
1655 }
1656 }
1657
1658 for (size_t p = 0; p < packages_.size(); p++) {
1659 const Package *package = o.packages_[p].get();
1660 if (package == nullptr) {
1661 continue;
1662 }
1663
1664 for (size_t t = 0; t < package->types.size(); t++) {
1665 const ThemeType *type = package->types[t].get();
1666 if (type == nullptr) {
1667 continue;
1668 }
1669
1670 for (size_t e = 0; e < type->entry_count; e++) {
1671 const ThemeEntry &entry = type->entries[e];
1672 if (entry.value.dataType == Res_value::TYPE_NULL &&
1673 entry.value.data != Res_value::DATA_NULL_EMPTY) {
1674 continue;
1675 }
1676
Ryan Mitchell93bca972019-03-08 17:26:28 -08001677 bool is_reference = (entry.value.dataType == Res_value::TYPE_ATTRIBUTE
1678 || entry.value.dataType == Res_value::TYPE_REFERENCE
1679 || entry.value.dataType == Res_value::TYPE_DYNAMIC_ATTRIBUTE
1680 || entry.value.dataType == Res_value::TYPE_DYNAMIC_REFERENCE)
1681 && entry.value.data != 0x0;
Ryan Mitchellb85d9b22018-11-19 12:11:38 -08001682
Ryan Mitchell93bca972019-03-08 17:26:28 -08001683 // If the attribute value represents an attribute or reference, the package id of the
1684 // value needs to be rewritten to the package id of the value in the destination.
1685 uint32_t attribute_data = entry.value.data;
1686 if (is_reference) {
1687 // Determine the package id of the reference in the destination AssetManager.
Ryan Mitchellb85d9b22018-11-19 12:11:38 -08001688 auto value_package_map = src_asset_cookie_id_map.find(entry.cookie);
1689 if (value_package_map == src_asset_cookie_id_map.end()) {
1690 continue;
1691 }
1692
1693 auto value_dest_package = value_package_map->second.find(
1694 get_package_id(entry.value.data));
1695 if (value_dest_package == value_package_map->second.end()) {
1696 continue;
1697 }
1698
Ryan Mitchell93bca972019-03-08 17:26:28 -08001699 attribute_data = fix_package_id(entry.value.data, value_dest_package->second);
1700 }
1701
1702 // Find the cookie of the value in the destination. If the source apk is not loaded in the
1703 // destination, only copy resources that do not reference resources in the source.
1704 ApkAssetsCookie data_dest_cookie;
1705 auto value_dest_cookie = src_to_dest_asset_cookies.find(entry.cookie);
1706 if (value_dest_cookie != src_to_dest_asset_cookies.end()) {
1707 data_dest_cookie = value_dest_cookie->second;
1708 } else {
1709 if (is_reference || entry.value.dataType == Res_value::TYPE_STRING) {
1710 continue;
1711 } else {
1712 data_dest_cookie = 0x0;
1713 }
Ryan Mitchellb85d9b22018-11-19 12:11:38 -08001714 }
1715
1716 // The package id of the attribute needs to be rewritten to the package id of the
Ryan Mitchell93bca972019-03-08 17:26:28 -08001717 // attribute in the destination.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001718 int attribute_dest_package_id = p;
1719 if (attribute_dest_package_id != 0x01) {
Ryan Mitchell93bca972019-03-08 17:26:28 -08001720 // Find the cookie of the attribute resource id in the source AssetManager
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001721 base::expected<FindEntryResult, NullOrIOError> attribute_entry_result =
Ryan Mitchella55dc2e2019-01-24 10:58:23 -08001722 o.asset_manager_->FindEntry(make_resid(p, t, e), 0 /* density_override */ ,
1723 true /* stop_at_first_match */,
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001724 true /* ignore_configuration */);
1725 if (UNLIKELY(IsIOError(attribute_entry_result))) {
1726 return base::unexpected(GetIOError(attribute_entry_result.error()));
1727 }
1728 if (!attribute_entry_result.has_value()) {
1729 continue;
1730 }
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001731
Ryan Mitchell93bca972019-03-08 17:26:28 -08001732 // Determine the package id of the attribute in the destination AssetManager.
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001733 auto attribute_package_map = src_asset_cookie_id_map.find(
1734 attribute_entry_result->cookie);
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001735 if (attribute_package_map == src_asset_cookie_id_map.end()) {
1736 continue;
1737 }
1738 auto attribute_dest_package = attribute_package_map->second.find(
1739 attribute_dest_package_id);
1740 if (attribute_dest_package == attribute_package_map->second.end()) {
1741 continue;
1742 }
1743 attribute_dest_package_id = attribute_dest_package->second;
1744 }
1745
Ryan Mitchell93bca972019-03-08 17:26:28 -08001746 // Lazily instantiate the destination package.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001747 std::unique_ptr<Package>& dest_package = packages_[attribute_dest_package_id];
1748 if (dest_package == nullptr) {
1749 dest_package.reset(new Package());
1750 }
1751
Ryan Mitchell93bca972019-03-08 17:26:28 -08001752 // Lazily instantiate and resize the destination type.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001753 util::unique_cptr<ThemeType>& dest_type = dest_package->types[t];
1754 if (dest_type == nullptr || dest_type->entry_count < type->entry_count) {
1755 const size_t type_alloc_size = sizeof(ThemeType)
1756 + (type->entry_count * sizeof(ThemeEntry));
1757 void* dest_data = malloc(type_alloc_size);
1758 memset(dest_data, 0, type->entry_count * sizeof(ThemeEntry));
1759
Ryan Mitchell93bca972019-03-08 17:26:28 -08001760 // Copy the existing destination type values if the type is resized.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001761 if (dest_type != nullptr) {
1762 memcpy(dest_data, type, sizeof(ThemeType)
1763 + (dest_type->entry_count * sizeof(ThemeEntry)));
1764 }
1765
1766 dest_type.reset(reinterpret_cast<ThemeType *>(dest_data));
1767 dest_type->entry_count = type->entry_count;
1768 }
1769
Ryan Mitchell93bca972019-03-08 17:26:28 -08001770 dest_type->entries[e].cookie = data_dest_cookie;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001771 dest_type->entries[e].value.dataType = entry.value.dataType;
Ryan Mitchell93bca972019-03-08 17:26:28 -08001772 dest_type->entries[e].value.data = attribute_data;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001773 dest_type->entries[e].type_spec_flags = entry.type_spec_flags;
1774 }
1775 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001776 }
1777 }
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001778 return {};
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001779}
1780
1781void Theme::Dump() const {
1782 base::ScopedLogSeverity _log(base::INFO);
1783 LOG(INFO) << base::StringPrintf("Theme(this=%p, AssetManager2=%p)", this, asset_manager_);
1784
1785 for (int p = 0; p < packages_.size(); p++) {
1786 auto& package = packages_[p];
1787 if (package == nullptr) {
1788 continue;
1789 }
1790
1791 for (int t = 0; t < package->types.size(); t++) {
1792 auto& type = package->types[t];
1793 if (type == nullptr) {
1794 continue;
1795 }
1796
1797 for (int e = 0; e < type->entry_count; e++) {
1798 auto& entry = type->entries[e];
1799 if (entry.value.dataType == Res_value::TYPE_NULL &&
1800 entry.value.data != Res_value::DATA_NULL_EMPTY) {
1801 continue;
1802 }
1803
1804 LOG(INFO) << base::StringPrintf(" entry(0x%08x)=(0x%08x) type=(0x%02x), cookie(%d)",
1805 make_resid(p, t, e), entry.value.data,
1806 entry.value.dataType, entry.cookie);
1807 }
1808 }
1809 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001810}
1811
1812} // namespace android