blob: 3f0600040139c27a6cf4b56e9bf8d8edb7dcab87 [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();
Ryan Mitchell0699f1d2020-12-03 15:41:42 -0800160 auto target_package_iter = apk_assets_package_ids.find(
161 std::string(loaded_idmap->TargetApkPath()));
Ryan Mitchellee4a5642019-10-16 08:32:55 -0700162 if (target_package_iter == apk_assets_package_ids.end()) {
163 LOG(INFO) << "failed to find target package for overlay "
164 << loaded_idmap->OverlayApkPath();
165 } else {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700166 const uint8_t target_package_id = target_package_iter->second;
167 const uint8_t target_idx = package_ids_[target_package_id];
168 CHECK(target_idx != 0xff) << "overlay added to apk_assets_package_ids but does not"
169 << " have an assigned package group";
170
171 PackageGroup& target_package_group = package_groups_[target_idx];
172
Ryan Mitchell824cc492020-02-12 10:48:14 -0800173 // Create a special dynamic reference table for the overlay to rewrite references to
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700174 // overlay resources as references to the target resources they overlay.
175 auto overlay_table = std::make_shared<OverlayDynamicRefTable>(
176 loaded_idmap->GetOverlayDynamicRefTable(target_package_id));
177 package_groups_.back().dynamic_ref_table = overlay_table;
178
179 // Add the overlay resource map to the target package's set of overlays.
180 target_package_group.overlays_.push_back(
181 ConfiguredOverlay{loaded_idmap->GetTargetResourcesMap(target_package_id,
182 overlay_table.get()),
Ryan Mitchell824cc492020-02-12 10:48:14 -0800183 apk_assets_cookies[apk_assets]});
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700184 }
185 }
186
187 DynamicRefTable* ref_table = package_groups_.back().dynamic_ref_table.get();
188 ref_table->mAssignedPackageId = package_id;
189 ref_table->mAppAsLib = package->IsDynamic() && package->GetPackageId() == 0x7f;
Adam Lesinskida431a22016-12-29 16:08:16 -0500190 }
191 PackageGroup* package_group = &package_groups_[idx];
192
193 // Add the package and to the set of packages with the same ID.
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800194 package_group->packages_.push_back(ConfiguredPackage{package.get(), {}});
Ryan Mitchell824cc492020-02-12 10:48:14 -0800195 package_group->cookies_.push_back(apk_assets_cookies[apk_assets]);
Adam Lesinskida431a22016-12-29 16:08:16 -0500196
197 // Add the package name -> build time ID mappings.
198 for (const DynamicPackageEntry& entry : package->GetDynamicPackageMap()) {
199 String16 package_name(entry.package_name.c_str(), entry.package_name.size());
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700200 package_group->dynamic_ref_table->mEntries.replaceValueFor(
Adam Lesinskida431a22016-12-29 16:08:16 -0500201 package_name, static_cast<uint8_t>(entry.package_id));
202 }
Ryan Mitchellb894c272020-02-12 10:31:44 -0800203
204 apk_assets_package_ids.insert(std::make_pair(apk_assets->GetPath(), package_id));
Adam Lesinskida431a22016-12-29 16:08:16 -0500205 }
206 }
207
208 // Now assign the runtime IDs so that we have a build-time to runtime ID map.
209 const auto package_groups_end = package_groups_.end();
210 for (auto iter = package_groups_.begin(); iter != package_groups_end; ++iter) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800211 const std::string& package_name = iter->packages_[0].loaded_package_->GetPackageName();
Adam Lesinskida431a22016-12-29 16:08:16 -0500212 for (auto iter2 = package_groups_.begin(); iter2 != package_groups_end; ++iter2) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700213 iter2->dynamic_ref_table->addMapping(String16(package_name.c_str(), package_name.size()),
214 iter->dynamic_ref_table->mAssignedPackageId);
Adam Lesinskida431a22016-12-29 16:08:16 -0500215 }
216 }
217}
218
219void AssetManager2::DumpToLog() const {
220 base::ScopedLogSeverity _log(base::INFO);
221
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800222 LOG(INFO) << base::StringPrintf("AssetManager2(this=%p)", this);
223
Adam Lesinskida431a22016-12-29 16:08:16 -0500224 std::string list;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800225 for (const auto& apk_assets : apk_assets_) {
226 base::StringAppendF(&list, "%s,", apk_assets->GetPath().c_str());
227 }
228 LOG(INFO) << "ApkAssets: " << list;
229
230 list = "";
Adam Lesinskida431a22016-12-29 16:08:16 -0500231 for (size_t i = 0; i < package_ids_.size(); i++) {
232 if (package_ids_[i] != 0xff) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800233 base::StringAppendF(&list, "%02x -> %d, ", (int)i, package_ids_[i]);
Adam Lesinskida431a22016-12-29 16:08:16 -0500234 }
235 }
236 LOG(INFO) << "Package ID map: " << list;
237
Adam Lesinski0dd36992018-01-25 15:38:38 -0800238 for (const auto& package_group: package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800239 list = "";
240 for (const auto& package : package_group.packages_) {
241 const LoadedPackage* loaded_package = package.loaded_package_;
242 base::StringAppendF(&list, "%s(%02x%s), ", loaded_package->GetPackageName().c_str(),
243 loaded_package->GetPackageId(),
244 (loaded_package->IsDynamic() ? " dynamic" : ""));
245 }
246 LOG(INFO) << base::StringPrintf("PG (%02x): ",
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700247 package_group.dynamic_ref_table->mAssignedPackageId)
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800248 << list;
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800249
250 for (size_t i = 0; i < 256; i++) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700251 if (package_group.dynamic_ref_table->mLookupTable[i] != 0) {
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800252 LOG(INFO) << base::StringPrintf(" e[0x%02x] -> 0x%02x", (uint8_t) i,
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700253 package_group.dynamic_ref_table->mLookupTable[i]);
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800254 }
255 }
Adam Lesinskida431a22016-12-29 16:08:16 -0500256 }
257}
Adam Lesinski7ad11102016-10-28 16:39:15 -0700258
259const ResStringPool* AssetManager2::GetStringPoolForCookie(ApkAssetsCookie cookie) const {
260 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
261 return nullptr;
262 }
263 return apk_assets_[cookie]->GetLoadedArsc()->GetStringPool();
264}
265
Adam Lesinskida431a22016-12-29 16:08:16 -0500266const DynamicRefTable* AssetManager2::GetDynamicRefTableForPackage(uint32_t package_id) const {
267 if (package_id >= package_ids_.size()) {
268 return nullptr;
269 }
270
271 const size_t idx = package_ids_[package_id];
272 if (idx == 0xff) {
273 return nullptr;
274 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700275 return package_groups_[idx].dynamic_ref_table.get();
Adam Lesinskida431a22016-12-29 16:08:16 -0500276}
277
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700278std::shared_ptr<const DynamicRefTable> AssetManager2::GetDynamicRefTableForCookie(
279 ApkAssetsCookie cookie) const {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800280 for (const PackageGroup& package_group : package_groups_) {
281 for (const ApkAssetsCookie& package_cookie : package_group.cookies_) {
282 if (package_cookie == cookie) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700283 return package_group.dynamic_ref_table;
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800284 }
285 }
286 }
287 return nullptr;
288}
289
Mårten Kongstadc92c4dd2019-02-05 01:29:59 +0100290const std::unordered_map<std::string, std::string>*
291 AssetManager2::GetOverlayableMapForPackage(uint32_t package_id) const {
292
293 if (package_id >= package_ids_.size()) {
294 return nullptr;
295 }
296
297 const size_t idx = package_ids_[package_id];
298 if (idx == 0xff) {
299 return nullptr;
300 }
301
302 const PackageGroup& package_group = package_groups_[idx];
Ryan Mitchell80094e32020-11-16 23:08:18 +0000303 if (package_group.packages_.empty()) {
Mårten Kongstadc92c4dd2019-02-05 01:29:59 +0100304 return nullptr;
305 }
306
307 const auto loaded_package = package_group.packages_[0].loaded_package_;
308 return &loaded_package->GetOverlayableMap();
309}
310
Ryan Mitchell2e394222019-08-28 12:10:51 -0700311bool AssetManager2::GetOverlayablesToString(const android::StringPiece& package_name,
312 std::string* out) const {
313 uint8_t package_id = 0U;
314 for (const auto& apk_assets : apk_assets_) {
315 const LoadedArsc* loaded_arsc = apk_assets->GetLoadedArsc();
316 if (loaded_arsc == nullptr) {
317 continue;
318 }
319
320 const auto& loaded_packages = loaded_arsc->GetPackages();
321 if (loaded_packages.empty()) {
322 continue;
323 }
324
325 const auto& loaded_package = loaded_packages[0];
326 if (loaded_package->GetPackageName() == package_name) {
327 package_id = GetAssignedPackageId(loaded_package.get());
328 break;
329 }
330 }
331
332 if (package_id == 0U) {
333 ANDROID_LOG(ERROR) << base::StringPrintf("No package with name '%s", package_name.data());
334 return false;
335 }
336
337 const size_t idx = package_ids_[package_id];
338 if (idx == 0xff) {
339 return false;
340 }
341
342 std::string output;
343 for (const ConfiguredPackage& package : package_groups_[idx].packages_) {
344 const LoadedPackage* loaded_package = package.loaded_package_;
345 for (auto it = loaded_package->begin(); it != loaded_package->end(); it++) {
346 const OverlayableInfo* info = loaded_package->GetOverlayableInfo(*it);
347 if (info != nullptr) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000348 auto res_name = GetResourceName(*it);
349 if (!res_name.has_value()) {
Ryan Mitchell2e394222019-08-28 12:10:51 -0700350 ANDROID_LOG(ERROR) << base::StringPrintf(
351 "Unable to retrieve name of overlayable resource 0x%08x", *it);
352 return false;
353 }
354
Ryan Mitchell80094e32020-11-16 23:08:18 +0000355 const std::string name = ToFormattedResourceString(*res_name);
Ryan Mitchell2e394222019-08-28 12:10:51 -0700356 output.append(base::StringPrintf(
357 "resource='%s' overlayable='%s' actor='%s' policy='0x%08x'\n",
358 name.c_str(), info->name.c_str(), info->actor.c_str(), info->policy_flags));
359 }
360 }
361 }
362
363 *out = std::move(output);
364 return true;
365}
366
Ryan Mitchell192400c2020-04-02 09:54:23 -0700367bool AssetManager2::ContainsAllocatedTable() const {
368 return std::find_if(apk_assets_.begin(), apk_assets_.end(),
369 std::mem_fn(&ApkAssets::IsTableAllocated)) != apk_assets_.end();
370}
371
Adam Lesinski7ad11102016-10-28 16:39:15 -0700372void AssetManager2::SetConfiguration(const ResTable_config& configuration) {
373 const int diff = configuration_.diff(configuration);
374 configuration_ = configuration;
375
376 if (diff) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800377 RebuildFilterList();
Adam Lesinski7ad11102016-10-28 16:39:15 -0700378 InvalidateCaches(static_cast<uint32_t>(diff));
379 }
380}
381
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700382std::set<std::string> AssetManager2::GetNonSystemOverlayPaths() const {
383 std::set<std::string> non_system_overlays;
Adam Lesinski0c405242017-01-13 20:47:26 -0800384 for (const PackageGroup& package_group : package_groups_) {
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800385 bool found_system_package = false;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800386 for (const ConfiguredPackage& package : package_group.packages_) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700387 if (package.loaded_package_->IsSystem()) {
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800388 found_system_package = true;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700389 break;
390 }
391 }
392
393 if (!found_system_package) {
394 for (const ConfiguredOverlay& overlay : package_group.overlays_) {
395 non_system_overlays.insert(apk_assets_[overlay.cookie]->GetPath());
396 }
397 }
398 }
399
400 return non_system_overlays;
401}
402
Ryan Mitchell80094e32020-11-16 23:08:18 +0000403base::expected<std::set<ResTable_config>, IOError> AssetManager2::GetResourceConfigurations(
404 bool exclude_system, bool exclude_mipmap) const {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700405 ATRACE_NAME("AssetManager::GetResourceConfigurations");
406 const auto non_system_overlays =
407 (exclude_system) ? GetNonSystemOverlayPaths() : std::set<std::string>();
408
409 std::set<ResTable_config> configurations;
410 for (const PackageGroup& package_group : package_groups_) {
411 for (size_t i = 0; i < package_group.packages_.size(); i++) {
412 const ConfiguredPackage& package = package_group.packages_[i];
413 if (exclude_system && package.loaded_package_->IsSystem()) {
Adam Lesinski0c405242017-01-13 20:47:26 -0800414 continue;
415 }
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800416
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700417 auto apk_assets = apk_assets_[package_group.cookies_[i]];
418 if (exclude_system && apk_assets->IsOverlay()
419 && non_system_overlays.find(apk_assets->GetPath()) == non_system_overlays.end()) {
420 // Exclude overlays that target system resources.
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800421 continue;
422 }
423
Ryan Mitchell80094e32020-11-16 23:08:18 +0000424 auto result = package.loaded_package_->CollectConfigurations(exclude_mipmap, &configurations);
425 if (UNLIKELY(!result.has_value())) {
426 return base::unexpected(result.error());
427 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800428 }
429 }
430 return configurations;
431}
432
433std::set<std::string> AssetManager2::GetResourceLocales(bool exclude_system,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800434 bool merge_equivalent_languages) const {
435 ATRACE_NAME("AssetManager::GetResourceLocales");
Adam Lesinski0c405242017-01-13 20:47:26 -0800436 std::set<std::string> locales;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700437 const auto non_system_overlays =
438 (exclude_system) ? GetNonSystemOverlayPaths() : std::set<std::string>();
439
Adam Lesinski0c405242017-01-13 20:47:26 -0800440 for (const PackageGroup& package_group : package_groups_) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700441 for (size_t i = 0; i < package_group.packages_.size(); i++) {
442 const ConfiguredPackage& package = package_group.packages_[i];
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800443 if (exclude_system && package.loaded_package_->IsSystem()) {
Adam Lesinski0c405242017-01-13 20:47:26 -0800444 continue;
445 }
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800446
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700447 auto apk_assets = apk_assets_[package_group.cookies_[i]];
448 if (exclude_system && apk_assets->IsOverlay()
449 && non_system_overlays.find(apk_assets->GetPath()) == non_system_overlays.end()) {
450 // Exclude overlays that target system resources.
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800451 continue;
452 }
453
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800454 package.loaded_package_->CollectLocales(merge_equivalent_languages, &locales);
Adam Lesinski0c405242017-01-13 20:47:26 -0800455 }
456 }
457 return locales;
458}
459
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800460std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename,
461 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700462 const std::string new_path = "assets/" + filename;
463 return OpenNonAsset(new_path, mode);
464}
465
466std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename, ApkAssetsCookie cookie,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800467 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700468 const std::string new_path = "assets/" + filename;
469 return OpenNonAsset(new_path, cookie, mode);
470}
471
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800472std::unique_ptr<AssetDir> AssetManager2::OpenDir(const std::string& dirname) const {
473 ATRACE_NAME("AssetManager::OpenDir");
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800474
475 std::string full_path = "assets/" + dirname;
476 std::unique_ptr<SortedVector<AssetDir::FileInfo>> files =
477 util::make_unique<SortedVector<AssetDir::FileInfo>>();
478
479 // Start from the back.
480 for (auto iter = apk_assets_.rbegin(); iter != apk_assets_.rend(); ++iter) {
481 const ApkAssets* apk_assets = *iter;
Mårten Kongstaddbf343b2019-02-21 07:54:18 +0100482 if (apk_assets->IsOverlay()) {
483 continue;
484 }
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800485
486 auto func = [&](const StringPiece& name, FileType type) {
487 AssetDir::FileInfo info;
488 info.setFileName(String8(name.data(), name.size()));
489 info.setFileType(type);
490 info.setSourceName(String8(apk_assets->GetPath().c_str()));
491 files->add(info);
492 };
493
Ryan Mitchellc07aa702020-03-10 13:49:12 -0700494 if (!apk_assets->GetAssetsProvider()->ForEachFile(full_path, func)) {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800495 return {};
496 }
497 }
498
499 std::unique_ptr<AssetDir> asset_dir = util::make_unique<AssetDir>();
500 asset_dir->setFileList(files.release());
501 return asset_dir;
502}
503
Adam Lesinski7ad11102016-10-28 16:39:15 -0700504// Search in reverse because that's how we used to do it and we need to preserve behaviour.
505// This is unfortunate, because ClassLoaders delegate to the parent first, so the order
506// is inconsistent for split APKs.
507std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
508 Asset::AccessMode mode,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800509 ApkAssetsCookie* out_cookie) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700510 for (int32_t i = apk_assets_.size() - 1; i >= 0; i--) {
Mårten Kongstaddbf343b2019-02-21 07:54:18 +0100511 // Prevent RRO from modifying assets and other entries accessed by file
512 // path. Explicitly asking for a path in a given package (denoted by a
513 // cookie) is still OK.
514 if (apk_assets_[i]->IsOverlay()) {
515 continue;
516 }
517
Ryan Mitchellc07aa702020-03-10 13:49:12 -0700518 std::unique_ptr<Asset> asset = apk_assets_[i]->GetAssetsProvider()->Open(filename, mode);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700519 if (asset) {
520 if (out_cookie != nullptr) {
521 *out_cookie = i;
522 }
523 return asset;
524 }
525 }
526
527 if (out_cookie != nullptr) {
528 *out_cookie = kInvalidCookie;
529 }
530 return {};
531}
532
533std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800534 ApkAssetsCookie cookie,
535 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700536 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
537 return {};
538 }
Ryan Mitchellc07aa702020-03-10 13:49:12 -0700539 return apk_assets_[cookie]->GetAssetsProvider()->Open(filename, mode);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700540}
541
Ryan Mitchell80094e32020-11-16 23:08:18 +0000542base::expected<FindEntryResult, NullOrIOError> AssetManager2::FindEntry(
543 uint32_t resid, uint16_t density_override, bool stop_at_first_match,
544 bool ignore_configuration) const {
545 const bool logging_enabled = resource_resolution_logging_enabled_;
546 if (UNLIKELY(logging_enabled)) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700547 // Clear the last logged resource resolution.
548 ResetResourceResolution();
549 last_resolution_.resid = resid;
550 }
551
Adam Lesinski7ad11102016-10-28 16:39:15 -0700552 // Might use this if density_override != 0.
553 ResTable_config density_override_config;
554
555 // Select our configuration or generate a density override configuration.
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800556 const ResTable_config* desired_config = &configuration_;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700557 if (density_override != 0 && density_override != configuration_.density) {
558 density_override_config = configuration_;
559 density_override_config.density = density_override;
560 desired_config = &density_override_config;
561 }
562
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700563 // Retrieve the package group from the package id of the resource id.
Ryan Mitchell80094e32020-11-16 23:08:18 +0000564 if (UNLIKELY(!is_valid_resid(resid))) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500565 LOG(ERROR) << base::StringPrintf("Invalid ID 0x%08x.", resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000566 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -0500567 }
568
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800569 const uint32_t package_id = get_package_id(resid);
570 const uint8_t type_idx = get_type_id(resid) - 1;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800571 const uint16_t entry_idx = get_entry_id(resid);
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700572 uint8_t package_idx = package_ids_[package_id];
Ryan Mitchell80094e32020-11-16 23:08:18 +0000573 if (UNLIKELY(package_idx == 0xff)) {
Ryan Mitchell2fe23472019-02-27 09:43:01 -0800574 ANDROID_LOG(ERROR) << base::StringPrintf("No package ID %02x found for ID 0x%08x.",
575 package_id, resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000576 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -0500577 }
578
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800579 const PackageGroup& package_group = package_groups_[package_idx];
Ryan Mitchell80094e32020-11-16 23:08:18 +0000580 auto result = FindEntryInternal(package_group, type_idx, entry_idx, *desired_config,
581 stop_at_first_match, ignore_configuration);
582 if (UNLIKELY(!result.has_value())) {
583 return base::unexpected(result.error());
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700584 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800585
Ryan Mitchell80094e32020-11-16 23:08:18 +0000586 if (!stop_at_first_match && !ignore_configuration && !apk_assets_[result->cookie]->IsLoader()) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700587 for (const auto& id_map : package_group.overlays_) {
588 auto overlay_entry = id_map.overlay_res_maps_.Lookup(resid);
589 if (!overlay_entry) {
590 // No id map entry exists for this target resource.
591 continue;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000592 }
593 if (overlay_entry.IsInlineValue()) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700594 // The target resource is overlaid by an inline value not represented by a resource.
Ryan Mitchell80094e32020-11-16 23:08:18 +0000595 result->entry = overlay_entry.GetInlineValue();
596 result->dynamic_ref_table = id_map.overlay_res_maps_.GetOverlayDynamicRefTable();
597 result->cookie = id_map.cookie;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700598 continue;
599 }
600
Ryan Mitchell80094e32020-11-16 23:08:18 +0000601 auto overlay_result = FindEntry(overlay_entry.GetResourceId(), density_override,
602 false /* stop_at_first_match */,
603 false /* ignore_configuration */);
604 if (UNLIKELY(IsIOError(overlay_result))) {
605 return base::unexpected(overlay_result.error());
606 }
607 if (!overlay_result.has_value()) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700608 continue;
609 }
610
Ryan Mitchell80094e32020-11-16 23:08:18 +0000611 if (!overlay_result->config.isBetterThan(result->config, desired_config)
612 && overlay_result->config.compare(result->config) != 0) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700613 // The configuration of the entry for the overlay must be equal to or better than the target
614 // configuration to be chosen as the better value.
615 continue;
616 }
617
Ryan Mitchell80094e32020-11-16 23:08:18 +0000618 result->cookie = overlay_result->cookie;
619 result->entry = overlay_result->entry;
620 result->config = overlay_result->config;
621 result->dynamic_ref_table = id_map.overlay_res_maps_.GetOverlayDynamicRefTable();
622
623 if (UNLIKELY(logging_enabled)) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700624 last_resolution_.steps.push_back(
Ryan Mitchell80094e32020-11-16 23:08:18 +0000625 Resolution::Step{Resolution::Step::Type::OVERLAID, overlay_result->config.toString(),
626 overlay_result->package_name});
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700627 }
628 }
629 }
630
Ryan Mitchell80094e32020-11-16 23:08:18 +0000631 if (UNLIKELY(logging_enabled)) {
632 last_resolution_.cookie = result->cookie;
633 last_resolution_.type_string_ref = result->type_string_ref;
634 last_resolution_.entry_string_ref = result->entry_string_ref;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700635 }
636
Ryan Mitchell80094e32020-11-16 23:08:18 +0000637 return result;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700638}
639
Ryan Mitchell80094e32020-11-16 23:08:18 +0000640base::expected<FindEntryResult, NullOrIOError> AssetManager2::FindEntryInternal(
641 const PackageGroup& package_group, uint8_t type_idx, uint16_t entry_idx,
642 const ResTable_config& desired_config, bool stop_at_first_match,
643 bool ignore_configuration) const {
644 const bool logging_enabled = resource_resolution_logging_enabled_;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800645 ApkAssetsCookie best_cookie = kInvalidCookie;
646 const LoadedPackage* best_package = nullptr;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000647 incfs::verified_map_ptr<ResTable_type> best_type;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800648 const ResTable_config* best_config = nullptr;
649 ResTable_config best_config_copy;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000650 uint32_t best_offset = 0U;
651 uint32_t type_flags = 0U;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800652
Ryan Mitchell80094e32020-11-16 23:08:18 +0000653 auto resolution_type = Resolution::Step::Type::NO_ENTRY;
Winson2f3669b2019-01-11 11:28:34 -0800654 std::vector<Resolution::Step> resolution_steps;
655
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800656 // If desired_config is the same as the set configuration, then we can use our filtered list
657 // and we don't need to match the configurations, since they already matched.
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700658 const bool use_fast_path = !ignore_configuration && &desired_config == &configuration_;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800659
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700660 const size_t package_count = package_group.packages_.size();
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800661 for (size_t pi = 0; pi < package_count; pi++) {
662 const ConfiguredPackage& loaded_package_impl = package_group.packages_[pi];
663 const LoadedPackage* loaded_package = loaded_package_impl.loaded_package_;
664 ApkAssetsCookie cookie = package_group.cookies_[pi];
665
666 // If the type IDs are offset in this package, we need to take that into account when searching
667 // for a type.
668 const TypeSpec* type_spec = loaded_package->GetTypeSpecByTypeIndex(type_idx);
669 if (UNLIKELY(type_spec == nullptr)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700670 continue;
671 }
672
Ryan Mitchell80094e32020-11-16 23:08:18 +0000673 auto entry_flags = type_spec->GetFlagsForEntryIndex(entry_idx);
Bernie Innocenti58cf8e32020-12-19 15:31:52 +0900674 if (UNLIKELY(!entry_flags.has_value())) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000675 return base::unexpected(entry_flags.error());
676 }
677 type_flags |= entry_flags.value();
678
Winson9947f1e2019-08-16 10:20:39 -0700679 // If the package is an overlay or custom loader,
680 // then even configurations that are the same MUST be chosen.
Winson9947f1e2019-08-16 10:20:39 -0700681 const bool package_is_loader = loaded_package->IsCustomLoader();
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800682
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800683 if (use_fast_path) {
Winson2f3669b2019-01-11 11:28:34 -0800684 const FilteredConfigGroup& filtered_group = loaded_package_impl.filtered_configs_[type_idx];
Ryan Mitchell80094e32020-11-16 23:08:18 +0000685 for (const auto& type_config : filtered_group.type_configs) {
686 const ResTable_config& this_config = type_config.config;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800687
688 // We can skip calling ResTable_config::match() because we know that all candidate
689 // configurations that do NOT match have been filtered-out.
Winson2f3669b2019-01-11 11:28:34 -0800690 if (best_config == nullptr) {
691 resolution_type = Resolution::Step::Type::INITIAL;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700692 } else if (this_config.isBetterThan(*best_config, &desired_config)) {
693 resolution_type = (package_is_loader) ? Resolution::Step::Type::BETTER_MATCH_LOADER
694 : Resolution::Step::Type::BETTER_MATCH;
695 } else if (package_is_loader && this_config.compare(*best_config) == 0) {
696 resolution_type = Resolution::Step::Type::OVERLAID_LOADER;
Winson2f3669b2019-01-11 11:28:34 -0800697 } else {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000698 if (UNLIKELY(logging_enabled)) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700699 resolution_type = (package_is_loader) ? Resolution::Step::Type::SKIPPED_LOADER
700 : Resolution::Step::Type::SKIPPED;
Winson9947f1e2019-08-16 10:20:39 -0700701 resolution_steps.push_back(Resolution::Step{resolution_type,
702 this_config.toString(),
703 &loaded_package->GetPackageName()});
704 }
Winson2f3669b2019-01-11 11:28:34 -0800705 continue;
706 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800707
Winson2f3669b2019-01-11 11:28:34 -0800708 // The configuration matches and is better than the previous selection.
709 // Find the entry value if it exists for this configuration.
Ryan Mitchell80094e32020-11-16 23:08:18 +0000710 const auto& type = type_config.type;
711 const auto offset = LoadedPackage::GetEntryOffset(type, entry_idx);
712 if (UNLIKELY(IsIOError(offset))) {
713 return base::unexpected(offset.error());
714 }
715 if (!offset.has_value()) {
716 if (UNLIKELY(logging_enabled)) {
Winson9947f1e2019-08-16 10:20:39 -0700717 if (package_is_loader) {
718 resolution_type = Resolution::Step::Type::NO_ENTRY_LOADER;
719 } else {
720 resolution_type = Resolution::Step::Type::NO_ENTRY;
721 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700722 resolution_steps.push_back(Resolution::Step{resolution_type,
Winson9947f1e2019-08-16 10:20:39 -0700723 this_config.toString(),
724 &loaded_package->GetPackageName()});
725 }
Winson2f3669b2019-01-11 11:28:34 -0800726 continue;
727 }
728
729 best_cookie = cookie;
730 best_package = loaded_package;
731 best_type = type;
732 best_config = &this_config;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000733 best_offset = offset.value();
Winson2f3669b2019-01-11 11:28:34 -0800734
Ryan Mitchell80094e32020-11-16 23:08:18 +0000735 if (UNLIKELY(logging_enabled)) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700736 last_resolution_.steps.push_back(Resolution::Step{resolution_type,
737 this_config.toString(),
738 &loaded_package->GetPackageName()});
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800739 }
740 }
741 } else {
742 // This is the slower path, which doesn't use the filtered list of configurations.
743 // Here we must read the ResTable_config from the mmapped APK, convert it to host endianness
744 // and fill in any new fields that did not exist when the APK was compiled.
745 // Furthermore when selecting configurations we can't just record the pointer to the
746 // ResTable_config, we must copy it.
747 const auto iter_end = type_spec->types + type_spec->type_count;
748 for (auto iter = type_spec->types; iter != iter_end; ++iter) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000749 const incfs::verified_map_ptr<ResTable_type>& type = *iter;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800750
Ryan Mitchell80094e32020-11-16 23:08:18 +0000751 ResTable_config this_config{};
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800752 if (!ignore_configuration) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000753 this_config.copyFromDtoH(type->config);
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700754 if (!this_config.match(desired_config)) {
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800755 continue;
756 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800757
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800758 if (best_config == nullptr) {
759 resolution_type = Resolution::Step::Type::INITIAL;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700760 } else if (this_config.isBetterThan(*best_config, &desired_config)) {
761 resolution_type = (package_is_loader) ? Resolution::Step::Type::BETTER_MATCH_LOADER
762 : Resolution::Step::Type::BETTER_MATCH;
763 } else if (package_is_loader && this_config.compare(*best_config) == 0) {
764 resolution_type = Resolution::Step::Type::OVERLAID_LOADER;
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800765 } else {
766 continue;
767 }
Winson2f3669b2019-01-11 11:28:34 -0800768 }
769
770 // The configuration matches and is better than the previous selection.
771 // Find the entry value if it exists for this configuration.
Ryan Mitchell80094e32020-11-16 23:08:18 +0000772 const auto offset = LoadedPackage::GetEntryOffset(type, entry_idx);
773 if (UNLIKELY(IsIOError(offset))) {
774 return base::unexpected(offset.error());
775 }
776 if (!offset.has_value()) {
Winson2f3669b2019-01-11 11:28:34 -0800777 continue;
778 }
779
780 best_cookie = cookie;
781 best_package = loaded_package;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000782 best_type = type;
Winson2f3669b2019-01-11 11:28:34 -0800783 best_config_copy = this_config;
784 best_config = &best_config_copy;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000785 best_offset = offset.value();
Winson2f3669b2019-01-11 11:28:34 -0800786
Ryan Mitchell80094e32020-11-16 23:08:18 +0000787 if (stop_at_first_match) {
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800788 // Any configuration will suffice, so break.
789 break;
790 }
791
Ryan Mitchell80094e32020-11-16 23:08:18 +0000792 if (UNLIKELY(logging_enabled)) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700793 last_resolution_.steps.push_back(Resolution::Step{resolution_type,
794 this_config.toString(),
795 &loaded_package->GetPackageName()});
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800796 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700797 }
798 }
799 }
800
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800801 if (UNLIKELY(best_cookie == kInvalidCookie)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000802 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700803 }
804
Ryan Mitchell80094e32020-11-16 23:08:18 +0000805 auto best_entry_result = LoadedPackage::GetEntryFromOffset(best_type, best_offset);
806 if (!best_entry_result.has_value()) {
807 return base::unexpected(best_entry_result.error());
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800808 }
809
Ryan Mitchell80094e32020-11-16 23:08:18 +0000810 const incfs::map_ptr<ResTable_entry> best_entry = *best_entry_result;
811 if (!best_entry) {
812 return base::unexpected(IOError::PAGES_MISSING);
Ryan Mitchellbf1f45b2020-09-29 17:22:52 -0700813 }
814
Ryan Mitchell80094e32020-11-16 23:08:18 +0000815 const auto entry = GetEntryValue(best_entry.verified());
816 if (!entry.has_value()) {
817 return base::unexpected(entry.error());
818 }
Winson2f3669b2019-01-11 11:28:34 -0800819
Ryan Mitchell80094e32020-11-16 23:08:18 +0000820 return FindEntryResult{
821 .cookie = best_cookie,
822 .entry = *entry,
823 .config = *best_config,
824 .type_flags = type_flags,
825 .package_name = &best_package->GetPackageName(),
826 .type_string_ref = StringPoolRef(best_package->GetTypeStringPool(), best_type->id - 1),
827 .entry_string_ref = StringPoolRef(best_package->GetKeyStringPool(),
828 best_entry->key.index),
829 .dynamic_ref_table = package_group.dynamic_ref_table.get(),
830 };
Adam Lesinski7ad11102016-10-28 16:39:15 -0700831}
832
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700833void AssetManager2::ResetResourceResolution() const {
834 last_resolution_.cookie = kInvalidCookie;
835 last_resolution_.resid = 0;
836 last_resolution_.steps.clear();
837 last_resolution_.type_string_ref = StringPoolRef();
838 last_resolution_.entry_string_ref = StringPoolRef();
839}
840
Winson2f3669b2019-01-11 11:28:34 -0800841void AssetManager2::SetResourceResolutionLoggingEnabled(bool enabled) {
842 resource_resolution_logging_enabled_ = enabled;
Winson2f3669b2019-01-11 11:28:34 -0800843 if (!enabled) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700844 ResetResourceResolution();
Winson2f3669b2019-01-11 11:28:34 -0800845 }
846}
847
848std::string AssetManager2::GetLastResourceResolution() const {
849 if (!resource_resolution_logging_enabled_) {
850 LOG(ERROR) << "Must enable resource resolution logging before getting path.";
Ryan Mitchell80094e32020-11-16 23:08:18 +0000851 return {};
Winson2f3669b2019-01-11 11:28:34 -0800852 }
853
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700854 auto cookie = last_resolution_.cookie;
Winson2f3669b2019-01-11 11:28:34 -0800855 if (cookie == kInvalidCookie) {
856 LOG(ERROR) << "AssetManager hasn't resolved a resource to read resolution path.";
Ryan Mitchell80094e32020-11-16 23:08:18 +0000857 return {};
Winson2f3669b2019-01-11 11:28:34 -0800858 }
859
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700860 uint32_t resid = last_resolution_.resid;
861 std::vector<Resolution::Step>& steps = last_resolution_.steps;
Winson2f3669b2019-01-11 11:28:34 -0800862 std::string resource_name_string;
863
864 const LoadedPackage* package =
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700865 apk_assets_[cookie]->GetLoadedArsc()->GetPackageById(get_package_id(resid));
Winson2f3669b2019-01-11 11:28:34 -0800866
867 if (package != nullptr) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000868 auto resource_name = ToResourceName(last_resolution_.type_string_ref,
869 last_resolution_.entry_string_ref,
870 package->GetPackageName());
871 resource_name_string = resource_name.has_value() ?
872 ToFormattedResourceString(resource_name.value()) : "<unknown>";
Winson2f3669b2019-01-11 11:28:34 -0800873 }
874
875 std::stringstream log_stream;
876 log_stream << base::StringPrintf("Resolution for 0x%08x ", resid)
877 << resource_name_string
878 << "\n\tFor config -"
879 << configuration_.toString();
880
881 std::string prefix;
882 for (Resolution::Step step : steps) {
883 switch (step.type) {
884 case Resolution::Step::Type::INITIAL:
885 prefix = "Found initial";
886 break;
887 case Resolution::Step::Type::BETTER_MATCH:
888 prefix = "Found better";
889 break;
Winson9947f1e2019-08-16 10:20:39 -0700890 case Resolution::Step::Type::BETTER_MATCH_LOADER:
891 prefix = "Found better in loader";
892 break;
Winson2f3669b2019-01-11 11:28:34 -0800893 case Resolution::Step::Type::OVERLAID:
894 prefix = "Overlaid";
895 break;
Winson9947f1e2019-08-16 10:20:39 -0700896 case Resolution::Step::Type::OVERLAID_LOADER:
897 prefix = "Overlaid by loader";
898 break;
899 case Resolution::Step::Type::SKIPPED:
900 prefix = "Skipped";
901 break;
902 case Resolution::Step::Type::SKIPPED_LOADER:
903 prefix = "Skipped loader";
904 break;
905 case Resolution::Step::Type::NO_ENTRY:
906 prefix = "No entry";
907 break;
908 case Resolution::Step::Type::NO_ENTRY_LOADER:
909 prefix = "No entry for loader";
910 break;
Winson2f3669b2019-01-11 11:28:34 -0800911 }
912
913 if (!prefix.empty()) {
914 log_stream << "\n\t" << prefix << ": " << *step.package_name;
915
916 if (!step.config_name.isEmpty()) {
917 log_stream << " -" << step.config_name;
918 }
919 }
920 }
921
922 return log_stream.str();
923}
924
Ryan Mitchell80094e32020-11-16 23:08:18 +0000925base::expected<AssetManager2::ResourceName, NullOrIOError> AssetManager2::GetResourceName(
926 uint32_t resid) const {
927 auto result = FindEntry(resid, 0u /* density_override */, true /* stop_at_first_match */,
928 true /* ignore_configuration */);
929 if (!result.has_value()) {
930 return base::unexpected(result.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -0700931 }
932
Ryan Mitchell80094e32020-11-16 23:08:18 +0000933 return ToResourceName(result->type_string_ref,
934 result->entry_string_ref,
935 *result->package_name);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700936}
937
Ryan Mitchell80094e32020-11-16 23:08:18 +0000938base::expected<AssetManager2::SelectedValue, NullOrIOError> AssetManager2::GetResource(
939 uint32_t resid, bool may_be_bag, uint16_t density_override) const {
940 auto result = FindEntry(resid, density_override, false /* stop_at_first_match */,
941 false /* ignore_configuration */);
942 if (!result.has_value()) {
943 return base::unexpected(result.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -0700944 }
945
Ryan Mitchell80094e32020-11-16 23:08:18 +0000946 auto result_map_entry = std::get_if<incfs::verified_map_ptr<ResTable_map_entry>>(&result->entry);
Ryan Mitchellbf1f45b2020-09-29 17:22:52 -0700947 if (result_map_entry != nullptr) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700948 if (!may_be_bag) {
949 LOG(ERROR) << base::StringPrintf("Resource %08x is a complex map type.", resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000950 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700951 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800952
953 // Create a reference since we can't represent this complex type as a Res_value.
Ryan Mitchell80094e32020-11-16 23:08:18 +0000954 return SelectedValue(Res_value::TYPE_REFERENCE, resid, result->cookie, result->type_flags,
955 resid, result->config);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700956 }
957
Adam Lesinskida431a22016-12-29 16:08:16 -0500958 // Convert the package ID to the runtime assigned package ID.
Ryan Mitchell80094e32020-11-16 23:08:18 +0000959 Res_value value = std::get<Res_value>(result->entry);
960 result->dynamic_ref_table->lookupResourceValue(&value);
Adam Lesinskida431a22016-12-29 16:08:16 -0500961
Ryan Mitchell80094e32020-11-16 23:08:18 +0000962 return SelectedValue(value.dataType, value.data, result->cookie, result->type_flags,
963 resid, result->config);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700964}
965
Ryan Mitchell80094e32020-11-16 23:08:18 +0000966base::expected<std::monostate, NullOrIOError> AssetManager2::ResolveReference(
Ryan Mitchella45506e2020-11-16 23:08:18 +0000967 AssetManager2::SelectedValue& value, bool cache_value) const {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000968 if (value.type != Res_value::TYPE_REFERENCE || value.data == 0U) {
969 // Not a reference. Nothing to do.
970 return {};
Adam Lesinski0c405242017-01-13 20:47:26 -0800971 }
Ryan Mitchell80094e32020-11-16 23:08:18 +0000972
Ryan Mitchella45506e2020-11-16 23:08:18 +0000973 const uint32_t original_flags = value.flags;
974 const uint32_t original_resid = value.data;
975 if (cache_value) {
976 auto cached_value = cached_resolved_values_.find(value.data);
977 if (cached_value != cached_resolved_values_.end()) {
978 value = cached_value->second;
979 value.flags |= original_flags;
980 return {};
981 }
982 }
983
984 uint32_t combined_flags = 0U;
985 uint32_t resolve_resid = original_resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000986 constexpr const uint32_t kMaxIterations = 20;
987 for (uint32_t i = 0U;; i++) {
988 auto result = GetResource(resolve_resid, true /*may_be_bag*/);
989 if (!result.has_value()) {
Ryan Mitchelle7ab6272020-11-13 18:06:15 -0800990 value.resid = resolve_resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000991 return base::unexpected(result.error());
992 }
993
Ryan Mitchelle7ab6272020-11-13 18:06:15 -0800994 // If resource resolution fails, the value should be set to the last reference that was able to
995 // be resolved successfully.
996 value = *result;
997 value.flags |= combined_flags;
998
Ryan Mitchell80094e32020-11-16 23:08:18 +0000999 if (result->type != Res_value::TYPE_REFERENCE ||
1000 result->data == Res_value::DATA_NULL_UNDEFINED ||
1001 result->data == resolve_resid || i == kMaxIterations) {
1002 // This reference can't be resolved, so exit now and let the caller deal with it.
Ryan Mitchella45506e2020-11-16 23:08:18 +00001003 if (cache_value) {
1004 cached_resolved_values_[original_resid] = value;
1005 }
1006
1007 // Above value is cached without original_flags to ensure they don't get included in future
1008 // queries that hit the cache
1009 value.flags |= original_flags;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001010 return {};
1011 }
1012
Ryan Mitchelle7ab6272020-11-13 18:06:15 -08001013 combined_flags = result->flags;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001014 resolve_resid = result->data;
1015 }
Adam Lesinski0c405242017-01-13 20:47:26 -08001016}
1017
Ryan Mitchell80094e32020-11-16 23:08:18 +00001018const std::vector<uint32_t> AssetManager2::GetBagResIdStack(uint32_t resid) const {
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001019 auto cached_iter = cached_bag_resid_stacks_.find(resid);
1020 if (cached_iter != cached_bag_resid_stacks_.end()) {
1021 return cached_iter->second;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001022 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001023
1024 std::vector<uint32_t> found_resids;
1025 GetBag(resid, found_resids);
1026 cached_bag_resid_stacks_.emplace(resid, found_resids);
1027 return found_resids;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001028}
1029
Ryan Mitchell80094e32020-11-16 23:08:18 +00001030base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::ResolveBag(
1031 AssetManager2::SelectedValue& value) const {
1032 if (UNLIKELY(value.type != Res_value::TYPE_REFERENCE)) {
1033 return base::unexpected(std::nullopt);
1034 }
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001035
Ryan Mitchell80094e32020-11-16 23:08:18 +00001036 auto bag = GetBag(value.data);
1037 if (bag.has_value()) {
1038 value.flags |= (*bag)->type_spec_flags;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001039 }
1040 return bag;
y57cd1952018-04-12 14:26:23 -07001041}
1042
Ryan Mitchell80094e32020-11-16 23:08:18 +00001043base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::GetBag(uint32_t resid) const {
1044 std::vector<uint32_t> found_resids;
1045 const auto bag = GetBag(resid, found_resids);
1046 cached_bag_resid_stacks_.emplace(resid, found_resids);
1047 return bag;
Ryan Mitchell155d5392020-02-10 13:35:24 -08001048}
1049
Ryan Mitchell80094e32020-11-16 23:08:18 +00001050base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::GetBag(
1051 uint32_t resid, std::vector<uint32_t>& child_resids) const {
1052 if (auto cached_iter = cached_bags_.find(resid); cached_iter != cached_bags_.end()) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001053 return cached_iter->second.get();
1054 }
1055
Ryan Mitchell80094e32020-11-16 23:08:18 +00001056 auto entry = FindEntry(resid, 0u /* density_override */, false /* stop_at_first_match */,
1057 false /* ignore_configuration */);
1058 if (!entry.has_value()) {
1059 return base::unexpected(entry.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001060 }
1061
Ryan Mitchell80094e32020-11-16 23:08:18 +00001062 auto entry_map = std::get_if<incfs::verified_map_ptr<ResTable_map_entry>>(&entry->entry);
1063 if (entry_map == nullptr) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001064 // Not a bag, nothing to do.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001065 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001066 }
1067
Ryan Mitchell80094e32020-11-16 23:08:18 +00001068 auto map = *entry_map;
1069 auto map_entry = map.offset(dtohs(map->size)).convert<ResTable_map>();
1070 const auto map_entry_end = map_entry + dtohl(map->count);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001071
y57cd1952018-04-12 14:26:23 -07001072 // Keep track of ids that have already been seen to prevent infinite loops caused by circular
Ryan Mitchell80094e32020-11-16 23:08:18 +00001073 // dependencies between bags.
y57cd1952018-04-12 14:26:23 -07001074 child_resids.push_back(resid);
1075
Adam Lesinskida431a22016-12-29 16:08:16 -05001076 uint32_t parent_resid = dtohl(map->parent.ident);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001077 if (parent_resid == 0U ||
1078 std::find(child_resids.begin(), child_resids.end(), parent_resid) != child_resids.end()) {
1079 // There is no parent or a circular parental dependency exist, meaning there is nothing to
1080 // inherit and we can do a simple copy of the entries in the map.
Adam Lesinski7ad11102016-10-28 16:39:15 -07001081 const size_t entry_count = map_entry_end - map_entry;
1082 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
1083 malloc(sizeof(ResolvedBag) + (entry_count * sizeof(ResolvedBag::Entry))))};
Ryan Mitchell155d5392020-02-10 13:35:24 -08001084
1085 bool sort_entries = false;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001086 for (auto new_entry = new_bag->entries; map_entry != map_entry_end; ++map_entry) {
1087 if (UNLIKELY(!map_entry)) {
1088 return base::unexpected(IOError::PAGES_MISSING);
1089 }
1090
Adam Lesinskida431a22016-12-29 16:08:16 -05001091 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001092 if (!is_internal_resid(new_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -05001093 // Attributes, arrays, etc don't have a resource id as the name. They specify
1094 // other data, which would be wrong to change via a lookup.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001095 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001096 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
1097 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001098 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001099 }
1100 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001101
1102 new_entry->cookie = entry->cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -05001103 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001104 new_entry->key_pool = nullptr;
1105 new_entry->type_pool = nullptr;
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001106 new_entry->style = resid;
Adam Lesinski30080e22017-10-16 16:18:09 -07001107 new_entry->value.copyFrom_dtoh(map_entry->value);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001108 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1109 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001110 LOG(ERROR) << base::StringPrintf(
1111 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
1112 new_entry->value.data, new_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001113 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001114 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001115
Ryan Mitchell155d5392020-02-10 13:35:24 -08001116 sort_entries = sort_entries ||
1117 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001118 ++new_entry;
1119 }
Ryan Mitchell155d5392020-02-10 13:35:24 -08001120
1121 if (sort_entries) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001122 std::sort(new_bag->entries, new_bag->entries + entry_count,
1123 [](auto&& lhs, auto&& rhs) { return lhs.key < rhs.key; });
Ryan Mitchell155d5392020-02-10 13:35:24 -08001124 }
1125
Ryan Mitchell80094e32020-11-16 23:08:18 +00001126 new_bag->type_spec_flags = entry->type_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001127 new_bag->entry_count = static_cast<uint32_t>(entry_count);
1128 ResolvedBag* result = new_bag.get();
1129 cached_bags_[resid] = std::move(new_bag);
1130 return result;
1131 }
1132
Adam Lesinskida431a22016-12-29 16:08:16 -05001133 // In case the parent is a dynamic reference, resolve it.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001134 entry->dynamic_ref_table->lookupResourceId(&parent_resid);
Adam Lesinskida431a22016-12-29 16:08:16 -05001135
Adam Lesinski7ad11102016-10-28 16:39:15 -07001136 // Get the parent and do a merge of the keys.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001137 const auto parent_bag = GetBag(parent_resid, child_resids);
1138 if (UNLIKELY(!parent_bag.has_value())) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001139 // Failed to get the parent that should exist.
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001140 LOG(ERROR) << base::StringPrintf("Failed to find parent 0x%08x of bag 0x%08x.", parent_resid,
1141 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001142 return base::unexpected(parent_bag.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001143 }
1144
Adam Lesinski7ad11102016-10-28 16:39:15 -07001145 // Create the max possible entries we can make. Once we construct the bag,
1146 // we will realloc to fit to size.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001147 const size_t max_count = (*parent_bag)->entry_count + dtohl(map->count);
George Burgess IV09b119f2017-07-25 15:00:04 -07001148 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
1149 malloc(sizeof(ResolvedBag) + (max_count * sizeof(ResolvedBag::Entry))))};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001150 ResolvedBag::Entry* new_entry = new_bag->entries;
1151
Ryan Mitchell80094e32020-11-16 23:08:18 +00001152 const ResolvedBag::Entry* parent_entry = (*parent_bag)->entries;
1153 const ResolvedBag::Entry* const parent_entry_end = parent_entry + (*parent_bag)->entry_count;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001154
1155 // The keys are expected to be in sorted order. Merge the two bags.
Ryan Mitchell155d5392020-02-10 13:35:24 -08001156 bool sort_entries = false;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001157 while (map_entry != map_entry_end && parent_entry != parent_entry_end) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001158 if (UNLIKELY(!map_entry)) {
1159 return base::unexpected(IOError::PAGES_MISSING);
1160 }
1161
Adam Lesinskida431a22016-12-29 16:08:16 -05001162 uint32_t child_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001163 if (!is_internal_resid(child_key)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001164 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&child_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001165 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", child_key,
1166 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001167 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001168 }
1169 }
1170
Adam Lesinski7ad11102016-10-28 16:39:15 -07001171 if (child_key <= parent_entry->key) {
1172 // Use the child key if it comes before the parent
1173 // or is equal to the parent (overrides).
Ryan Mitchell80094e32020-11-16 23:08:18 +00001174 new_entry->cookie = entry->cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001175 new_entry->key = child_key;
1176 new_entry->key_pool = nullptr;
1177 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -07001178 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001179 new_entry->style = resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001180 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1181 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001182 LOG(ERROR) << base::StringPrintf(
1183 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
1184 new_entry->value.data, child_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001185 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001186 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001187 ++map_entry;
1188 } else {
1189 // Take the parent entry as-is.
1190 memcpy(new_entry, parent_entry, sizeof(*new_entry));
1191 }
1192
Ryan Mitchell155d5392020-02-10 13:35:24 -08001193 sort_entries = sort_entries ||
1194 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001195 if (child_key >= parent_entry->key) {
1196 // Move to the next parent entry if we used it or it was overridden.
1197 ++parent_entry;
1198 }
1199 // Increment to the next entry to fill.
1200 ++new_entry;
1201 }
1202
1203 // Finish the child entries if they exist.
1204 while (map_entry != map_entry_end) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001205 if (UNLIKELY(!map_entry)) {
1206 return base::unexpected(IOError::PAGES_MISSING);
1207 }
1208
Adam Lesinskida431a22016-12-29 16:08:16 -05001209 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001210 if (!is_internal_resid(new_key)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001211 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001212 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
1213 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001214 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001215 }
1216 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001217 new_entry->cookie = entry->cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -05001218 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001219 new_entry->key_pool = nullptr;
1220 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -07001221 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001222 new_entry->style = resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001223 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1224 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001225 LOG(ERROR) << base::StringPrintf("Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.",
1226 new_entry->value.dataType, new_entry->value.data, new_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001227 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001228 }
Ryan Mitchell155d5392020-02-10 13:35:24 -08001229 sort_entries = sort_entries ||
1230 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001231 ++map_entry;
1232 ++new_entry;
1233 }
1234
1235 // Finish the parent entries if they exist.
1236 if (parent_entry != parent_entry_end) {
1237 // Take the rest of the parent entries as-is.
1238 const size_t num_entries_to_copy = parent_entry_end - parent_entry;
1239 memcpy(new_entry, parent_entry, num_entries_to_copy * sizeof(*new_entry));
1240 new_entry += num_entries_to_copy;
1241 }
1242
1243 // Resize the resulting array to fit.
1244 const size_t actual_count = new_entry - new_bag->entries;
1245 if (actual_count != max_count) {
George Burgess IV09b119f2017-07-25 15:00:04 -07001246 new_bag.reset(reinterpret_cast<ResolvedBag*>(realloc(
1247 new_bag.release(), sizeof(ResolvedBag) + (actual_count * sizeof(ResolvedBag::Entry)))));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001248 }
1249
Ryan Mitchell155d5392020-02-10 13:35:24 -08001250 if (sort_entries) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001251 std::sort(new_bag->entries, new_bag->entries + actual_count,
1252 [](auto&& lhs, auto&& rhs) { return lhs.key < rhs.key; });
Ryan Mitchell155d5392020-02-10 13:35:24 -08001253 }
1254
Adam Lesinski1a1e9c22017-10-13 15:45:34 -07001255 // Combine flags from the parent and our own bag.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001256 new_bag->type_spec_flags = entry->type_flags | (*parent_bag)->type_spec_flags;
George Burgess IV09b119f2017-07-25 15:00:04 -07001257 new_bag->entry_count = static_cast<uint32_t>(actual_count);
1258 ResolvedBag* result = new_bag.get();
1259 cached_bags_[resid] = std::move(new_bag);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001260 return result;
1261}
1262
Adam Lesinski929d6512017-01-16 19:11:19 -08001263static bool Utf8ToUtf16(const StringPiece& str, std::u16string* out) {
1264 ssize_t len =
1265 utf8_to_utf16_length(reinterpret_cast<const uint8_t*>(str.data()), str.size(), false);
1266 if (len < 0) {
1267 return false;
1268 }
1269 out->resize(static_cast<size_t>(len));
1270 utf8_to_utf16(reinterpret_cast<const uint8_t*>(str.data()), str.size(), &*out->begin(),
1271 static_cast<size_t>(len + 1));
1272 return true;
1273}
1274
Ryan Mitchell80094e32020-11-16 23:08:18 +00001275base::expected<uint32_t, NullOrIOError> AssetManager2::GetResourceId(
1276 const std::string& resource_name, const std::string& fallback_type,
1277 const std::string& fallback_package) const {
Adam Lesinski929d6512017-01-16 19:11:19 -08001278 StringPiece package_name, type, entry;
1279 if (!ExtractResourceName(resource_name, &package_name, &type, &entry)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001280 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001281 }
1282
1283 if (entry.empty()) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001284 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001285 }
1286
1287 if (package_name.empty()) {
1288 package_name = fallback_package;
1289 }
1290
1291 if (type.empty()) {
1292 type = fallback_type;
1293 }
1294
1295 std::u16string type16;
1296 if (!Utf8ToUtf16(type, &type16)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001297 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001298 }
1299
1300 std::u16string entry16;
1301 if (!Utf8ToUtf16(entry, &entry16)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001302 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001303 }
1304
1305 const StringPiece16 kAttr16 = u"attr";
1306 const static std::u16string kAttrPrivate16 = u"^attr-private";
1307
1308 for (const PackageGroup& package_group : package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001309 for (const ConfiguredPackage& package_impl : package_group.packages_) {
1310 const LoadedPackage* package = package_impl.loaded_package_;
Adam Lesinski929d6512017-01-16 19:11:19 -08001311 if (package_name != package->GetPackageName()) {
1312 // All packages in the same group are expected to have the same package name.
1313 break;
1314 }
1315
Ryan Mitchell80094e32020-11-16 23:08:18 +00001316 base::expected<uint32_t, NullOrIOError> resid = package->FindEntryByName(type16, entry16);
1317 if (UNLIKELY(IsIOError(resid))) {
1318 return base::unexpected(resid.error());
1319 }
1320
1321 if (!resid.has_value() && kAttr16 == type16) {
Adam Lesinski929d6512017-01-16 19:11:19 -08001322 // Private attributes in libraries (such as the framework) are sometimes encoded
1323 // under the type '^attr-private' in order to leave the ID space of public 'attr'
1324 // free for future additions. Check '^attr-private' for the same name.
1325 resid = package->FindEntryByName(kAttrPrivate16, entry16);
1326 }
1327
Ryan Mitchell80094e32020-11-16 23:08:18 +00001328 if (resid.has_value()) {
1329 return fix_package_id(*resid, package_group.dynamic_ref_table->mAssignedPackageId);
Adam Lesinski929d6512017-01-16 19:11:19 -08001330 }
1331 }
1332 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001333 return base::unexpected(std::nullopt);
Adam Lesinski0c405242017-01-13 20:47:26 -08001334}
1335
Mårten Kongstad668ec5b2018-06-11 14:11:33 +02001336void AssetManager2::RebuildFilterList(bool filter_incompatible_configs) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001337 for (PackageGroup& group : package_groups_) {
1338 for (ConfiguredPackage& impl : group.packages_) {
1339 // Destroy it.
1340 impl.filtered_configs_.~ByteBucketArray();
1341
1342 // Re-create it.
1343 new (&impl.filtered_configs_) ByteBucketArray<FilteredConfigGroup>();
1344
1345 // Create the filters here.
1346 impl.loaded_package_->ForEachTypeSpec([&](const TypeSpec* spec, uint8_t type_index) {
1347 FilteredConfigGroup& group = impl.filtered_configs_.editItemAt(type_index);
1348 const auto iter_end = spec->types + spec->type_count;
1349 for (auto iter = spec->types; iter != iter_end; ++iter) {
1350 ResTable_config this_config;
1351 this_config.copyFromDtoH((*iter)->config);
Mårten Kongstad668ec5b2018-06-11 14:11:33 +02001352 if (!filter_incompatible_configs || this_config.match(configuration_)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001353 group.type_configs.push_back(TypeConfig{*iter, this_config});
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001354 }
1355 }
1356 });
1357 }
1358 }
1359}
1360
Adam Lesinski7ad11102016-10-28 16:39:15 -07001361void AssetManager2::InvalidateCaches(uint32_t diff) {
Ryan Mitchell2c4d8742019-03-04 09:41:00 -08001362 cached_bag_resid_stacks_.clear();
1363
Adam Lesinski7ad11102016-10-28 16:39:15 -07001364 if (diff == 0xffffffffu) {
1365 // Everything must go.
1366 cached_bags_.clear();
1367 return;
1368 }
1369
1370 // Be more conservative with what gets purged. Only if the bag has other possible
1371 // variations with respect to what changed (diff) should we remove it.
1372 for (auto iter = cached_bags_.cbegin(); iter != cached_bags_.cend();) {
1373 if (diff & iter->second->type_spec_flags) {
1374 iter = cached_bags_.erase(iter);
1375 } else {
1376 ++iter;
1377 }
1378 }
Ryan Mitchella45506e2020-11-16 23:08:18 +00001379
1380 cached_resolved_values_.clear();
Adam Lesinski7ad11102016-10-28 16:39:15 -07001381}
1382
Ryan Mitchell2e394222019-08-28 12:10:51 -07001383uint8_t AssetManager2::GetAssignedPackageId(const LoadedPackage* package) const {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001384 for (auto& package_group : package_groups_) {
1385 for (auto& package2 : package_group.packages_) {
1386 if (package2.loaded_package_ == package) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -07001387 return package_group.dynamic_ref_table->mAssignedPackageId;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001388 }
1389 }
1390 }
1391 return 0;
1392}
1393
Adam Lesinski30080e22017-10-16 16:18:09 -07001394std::unique_ptr<Theme> AssetManager2::NewTheme() {
1395 return std::unique_ptr<Theme>(new Theme(this));
1396}
1397
1398Theme::Theme(AssetManager2* asset_manager) : asset_manager_(asset_manager) {
1399}
1400
1401Theme::~Theme() = default;
1402
1403namespace {
1404
1405struct ThemeEntry {
1406 ApkAssetsCookie cookie;
1407 uint32_t type_spec_flags;
1408 Res_value value;
1409};
1410
1411struct ThemeType {
1412 int entry_count;
1413 ThemeEntry entries[0];
1414};
1415
1416constexpr size_t kTypeCount = std::numeric_limits<uint8_t>::max() + 1;
1417
1418} // namespace
1419
1420struct Theme::Package {
1421 // Each element of Type will be a dynamically sized object
1422 // allocated to have the entries stored contiguously with the Type.
1423 std::array<util::unique_cptr<ThemeType>, kTypeCount> types;
1424};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001425
Ryan Mitchell80094e32020-11-16 23:08:18 +00001426base::expected<std::monostate, NullOrIOError> Theme::ApplyStyle(uint32_t resid, bool force) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001427 ATRACE_NAME("Theme::ApplyStyle");
Adam Lesinski7ad11102016-10-28 16:39:15 -07001428
Ryan Mitchell80094e32020-11-16 23:08:18 +00001429 auto bag = asset_manager_->GetBag(resid);
1430 if (!bag.has_value()) {
1431 return base::unexpected(bag.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001432 }
1433
1434 // Merge the flags from this style.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001435 type_spec_flags_ |= (*bag)->type_spec_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001436
Adam Lesinski30080e22017-10-16 16:18:09 -07001437 int last_type_idx = -1;
1438 int last_package_idx = -1;
1439 Package* last_package = nullptr;
1440 ThemeType* last_type = nullptr;
1441
1442 // Iterate backwards, because each bag is sorted in ascending key ID order, meaning we will only
1443 // need to perform one resize per type.
1444 using reverse_bag_iterator = std::reverse_iterator<const ResolvedBag::Entry*>;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001445 const auto rbegin = reverse_bag_iterator(begin(*bag));
1446 for (auto it = reverse_bag_iterator(end(*bag)); it != rbegin; ++it) {
1447 const uint32_t attr_resid = it->key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001448
Adam Lesinski30080e22017-10-16 16:18:09 -07001449 // If the resource ID passed in is not a style, the key can be some other identifier that is not
1450 // a resource ID. We should fail fast instead of operating with strange resource IDs.
Adam Lesinski929d6512017-01-16 19:11:19 -08001451 if (!is_valid_resid(attr_resid)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001452 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001453 }
1454
Adam Lesinski30080e22017-10-16 16:18:09 -07001455 // We don't use the 0-based index for the type so that we can avoid doing ID validation
1456 // upon lookup. Instead, we keep space for the type ID 0 in our data structures. Since
1457 // the construction of this type is guarded with a resource ID check, it will never be
1458 // populated, and querying type ID 0 will always fail.
1459 const int package_idx = get_package_id(attr_resid);
1460 const int type_idx = get_type_id(attr_resid);
1461 const int entry_idx = get_entry_id(attr_resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001462
Adam Lesinski30080e22017-10-16 16:18:09 -07001463 if (last_package_idx != package_idx) {
1464 std::unique_ptr<Package>& package = packages_[package_idx];
1465 if (package == nullptr) {
1466 package.reset(new Package());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001467 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001468 last_package_idx = package_idx;
1469 last_package = package.get();
1470 last_type_idx = -1;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001471 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001472
1473 if (last_type_idx != type_idx) {
1474 util::unique_cptr<ThemeType>& type = last_package->types[type_idx];
1475 if (type == nullptr) {
1476 // Allocate enough 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 type.reset(reinterpret_cast<ThemeType*>(
1479 calloc(sizeof(ThemeType) + (entry_idx + 1) * sizeof(ThemeEntry), 1)));
1480 type->entry_count = entry_idx + 1;
1481 } else if (entry_idx >= type->entry_count) {
1482 // Reallocate the memory to contain this entry_idx. Since we're iterating in reverse over
1483 // a sorted list of attributes, this shouldn't be resized again during this method call.
1484 const int new_count = entry_idx + 1;
1485 type.reset(reinterpret_cast<ThemeType*>(
1486 realloc(type.release(), sizeof(ThemeType) + (new_count * sizeof(ThemeEntry)))));
1487
1488 // Clear out the newly allocated space (which isn't zeroed).
1489 memset(type->entries + type->entry_count, 0,
1490 (new_count - type->entry_count) * sizeof(ThemeEntry));
1491 type->entry_count = new_count;
1492 }
1493 last_type_idx = type_idx;
1494 last_type = type.get();
1495 }
1496
1497 ThemeEntry& entry = last_type->entries[entry_idx];
1498 if (force || (entry.value.dataType == Res_value::TYPE_NULL &&
1499 entry.value.data != Res_value::DATA_NULL_EMPTY)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001500 entry.cookie = it->cookie;
1501 entry.type_spec_flags |= (*bag)->type_spec_flags;
1502 entry.value = it->value;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001503 }
1504 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001505 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001506}
1507
Ryan Mitchell80094e32020-11-16 23:08:18 +00001508std::optional<AssetManager2::SelectedValue> Theme::GetAttribute(uint32_t resid) const {
1509
Adam Lesinski30080e22017-10-16 16:18:09 -07001510 int cnt = 20;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001511 uint32_t type_spec_flags = 0u;
Adam Lesinski30080e22017-10-16 16:18:09 -07001512 do {
1513 const int package_idx = get_package_id(resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001514 const Package* package = packages_[package_idx].get();
Adam Lesinski30080e22017-10-16 16:18:09 -07001515 if (package != nullptr) {
1516 // The themes are constructed with a 1-based type ID, so no need to decrement here.
1517 const int type_idx = get_type_id(resid);
1518 const ThemeType* type = package->types[type_idx].get();
1519 if (type != nullptr) {
1520 const int entry_idx = get_entry_id(resid);
1521 if (entry_idx < type->entry_count) {
1522 const ThemeEntry& entry = type->entries[entry_idx];
1523 type_spec_flags |= entry.type_spec_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001524
Adam Lesinski30080e22017-10-16 16:18:09 -07001525 if (entry.value.dataType == Res_value::TYPE_ATTRIBUTE) {
1526 if (cnt > 0) {
1527 cnt--;
1528 resid = entry.value.data;
1529 continue;
1530 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001531 return std::nullopt;
Adam Lesinski30080e22017-10-16 16:18:09 -07001532 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001533
Adam Lesinski30080e22017-10-16 16:18:09 -07001534 // @null is different than @empty.
1535 if (entry.value.dataType == Res_value::TYPE_NULL &&
1536 entry.value.data != Res_value::DATA_NULL_EMPTY) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001537 return std::nullopt;
Adam Lesinski30080e22017-10-16 16:18:09 -07001538 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001539
Ryan Mitchell80094e32020-11-16 23:08:18 +00001540 return AssetManager2::SelectedValue(entry.value.dataType, entry.value.data, entry.cookie,
1541 type_spec_flags, 0U /* resid */, {} /* config */);
Adam Lesinskida431a22016-12-29 16:08:16 -05001542 }
Adam Lesinskida431a22016-12-29 16:08:16 -05001543 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001544 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001545 break;
1546 } while (true);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001547 return std::nullopt;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001548}
1549
Ryan Mitchell80094e32020-11-16 23:08:18 +00001550base::expected<std::monostate, NullOrIOError> Theme::ResolveAttributeReference(
1551 AssetManager2::SelectedValue& value) const {
1552 if (value.type != Res_value::TYPE_ATTRIBUTE) {
1553 return asset_manager_->ResolveReference(value);
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001554 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001555
1556 std::optional<AssetManager2::SelectedValue> result = GetAttribute(value.data);
1557 if (!result.has_value()) {
1558 return base::unexpected(std::nullopt);
1559 }
1560
Ryan Mitchella45506e2020-11-16 23:08:18 +00001561 auto resolve_result = asset_manager_->ResolveReference(*result, true /* cache_value */);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001562 if (resolve_result.has_value()) {
1563 result->flags |= value.flags;
1564 value = *result;
1565 }
1566 return resolve_result;
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001567}
1568
Adam Lesinski7ad11102016-10-28 16:39:15 -07001569void Theme::Clear() {
1570 type_spec_flags_ = 0u;
1571 for (std::unique_ptr<Package>& package : packages_) {
1572 package.reset();
1573 }
1574}
1575
Ryan Mitchell80094e32020-11-16 23:08:18 +00001576base::expected<std::monostate, IOError> Theme::SetTo(const Theme& o) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001577 if (this == &o) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001578 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001579 }
1580
Adam Lesinski7ad11102016-10-28 16:39:15 -07001581 type_spec_flags_ = o.type_spec_flags_;
1582
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001583 if (asset_manager_ == o.asset_manager_) {
1584 // The theme comes from the same asset manager so all theme data can be copied exactly
1585 for (size_t p = 0; p < packages_.size(); p++) {
1586 const Package *package = o.packages_[p].get();
1587 if (package == nullptr) {
1588 // The other theme doesn't have this package, clear ours.
1589 packages_[p].reset();
Adam Lesinski7ad11102016-10-28 16:39:15 -07001590 continue;
1591 }
1592
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001593 if (packages_[p] == nullptr) {
1594 // The other theme has this package, but we don't. Make one.
1595 packages_[p].reset(new Package());
1596 }
1597
1598 for (size_t t = 0; t < package->types.size(); t++) {
1599 const ThemeType *type = package->types[t].get();
1600 if (type == nullptr) {
1601 // The other theme doesn't have this type, clear ours.
1602 packages_[p]->types[t].reset();
1603 continue;
1604 }
1605
1606 // Create a new type and update it to theirs.
1607 const size_t type_alloc_size = sizeof(ThemeType) + (type->entry_count * sizeof(ThemeEntry));
1608 void *copied_data = malloc(type_alloc_size);
1609 memcpy(copied_data, type, type_alloc_size);
1610 packages_[p]->types[t].reset(reinterpret_cast<ThemeType *>(copied_data));
1611 }
1612 }
1613 } else {
1614 std::map<ApkAssetsCookie, ApkAssetsCookie> src_to_dest_asset_cookies;
1615 typedef std::map<int, int> SourceToDestinationRuntimePackageMap;
1616 std::map<ApkAssetsCookie, SourceToDestinationRuntimePackageMap> src_asset_cookie_id_map;
1617
Ryan Mitchell93bca972019-03-08 17:26:28 -08001618 // Determine which ApkAssets are loaded in both theme AssetManagers.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001619 std::vector<const ApkAssets*> src_assets = o.asset_manager_->GetApkAssets();
1620 for (size_t i = 0; i < src_assets.size(); i++) {
1621 const ApkAssets* src_asset = src_assets[i];
1622
1623 std::vector<const ApkAssets*> dest_assets = asset_manager_->GetApkAssets();
1624 for (size_t j = 0; j < dest_assets.size(); j++) {
1625 const ApkAssets* dest_asset = dest_assets[j];
1626
Ryan Mitchell93bca972019-03-08 17:26:28 -08001627 // Map the runtime package of the source apk asset to the destination apk asset.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001628 if (src_asset->GetPath() == dest_asset->GetPath()) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001629 const auto& src_packages = src_asset->GetLoadedArsc()->GetPackages();
1630 const auto& dest_packages = dest_asset->GetLoadedArsc()->GetPackages();
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001631
1632 SourceToDestinationRuntimePackageMap package_map;
1633
1634 // The source and destination package should have the same number of packages loaded in
1635 // the same order.
1636 const size_t N = src_packages.size();
1637 CHECK(N == dest_packages.size())
1638 << " LoadedArsc " << src_asset->GetPath() << " differs number of packages.";
1639 for (size_t p = 0; p < N; p++) {
1640 auto& src_package = src_packages[p];
1641 auto& dest_package = dest_packages[p];
1642 CHECK(src_package->GetPackageName() == dest_package->GetPackageName())
1643 << " Package " << src_package->GetPackageName() << " differs in load order.";
1644
1645 int src_package_id = o.asset_manager_->GetAssignedPackageId(src_package.get());
1646 int dest_package_id = asset_manager_->GetAssignedPackageId(dest_package.get());
1647 package_map[src_package_id] = dest_package_id;
1648 }
1649
Ryan Mitchell93bca972019-03-08 17:26:28 -08001650 src_to_dest_asset_cookies.insert(std::make_pair(i, j));
1651 src_asset_cookie_id_map.insert(std::make_pair(i, package_map));
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001652 break;
1653 }
1654 }
1655 }
1656
Ryan Mitchell93bca972019-03-08 17:26:28 -08001657 // Reset the data in the destination theme.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001658 for (size_t p = 0; p < packages_.size(); p++) {
1659 if (packages_[p] != nullptr) {
1660 packages_[p].reset();
1661 }
1662 }
1663
1664 for (size_t p = 0; p < packages_.size(); p++) {
1665 const Package *package = o.packages_[p].get();
1666 if (package == nullptr) {
1667 continue;
1668 }
1669
1670 for (size_t t = 0; t < package->types.size(); t++) {
1671 const ThemeType *type = package->types[t].get();
1672 if (type == nullptr) {
1673 continue;
1674 }
1675
1676 for (size_t e = 0; e < type->entry_count; e++) {
1677 const ThemeEntry &entry = type->entries[e];
1678 if (entry.value.dataType == Res_value::TYPE_NULL &&
1679 entry.value.data != Res_value::DATA_NULL_EMPTY) {
1680 continue;
1681 }
1682
Ryan Mitchell93bca972019-03-08 17:26:28 -08001683 bool is_reference = (entry.value.dataType == Res_value::TYPE_ATTRIBUTE
1684 || entry.value.dataType == Res_value::TYPE_REFERENCE
1685 || entry.value.dataType == Res_value::TYPE_DYNAMIC_ATTRIBUTE
1686 || entry.value.dataType == Res_value::TYPE_DYNAMIC_REFERENCE)
1687 && entry.value.data != 0x0;
Ryan Mitchellb85d9b22018-11-19 12:11:38 -08001688
Ryan Mitchell93bca972019-03-08 17:26:28 -08001689 // If the attribute value represents an attribute or reference, the package id of the
1690 // value needs to be rewritten to the package id of the value in the destination.
1691 uint32_t attribute_data = entry.value.data;
1692 if (is_reference) {
1693 // Determine the package id of the reference in the destination AssetManager.
Ryan Mitchellb85d9b22018-11-19 12:11:38 -08001694 auto value_package_map = src_asset_cookie_id_map.find(entry.cookie);
1695 if (value_package_map == src_asset_cookie_id_map.end()) {
1696 continue;
1697 }
1698
1699 auto value_dest_package = value_package_map->second.find(
1700 get_package_id(entry.value.data));
1701 if (value_dest_package == value_package_map->second.end()) {
1702 continue;
1703 }
1704
Ryan Mitchell93bca972019-03-08 17:26:28 -08001705 attribute_data = fix_package_id(entry.value.data, value_dest_package->second);
1706 }
1707
1708 // Find the cookie of the value in the destination. If the source apk is not loaded in the
1709 // destination, only copy resources that do not reference resources in the source.
1710 ApkAssetsCookie data_dest_cookie;
1711 auto value_dest_cookie = src_to_dest_asset_cookies.find(entry.cookie);
1712 if (value_dest_cookie != src_to_dest_asset_cookies.end()) {
1713 data_dest_cookie = value_dest_cookie->second;
1714 } else {
1715 if (is_reference || entry.value.dataType == Res_value::TYPE_STRING) {
1716 continue;
1717 } else {
1718 data_dest_cookie = 0x0;
1719 }
Ryan Mitchellb85d9b22018-11-19 12:11:38 -08001720 }
1721
1722 // The package id of the attribute needs to be rewritten to the package id of the
Ryan Mitchell93bca972019-03-08 17:26:28 -08001723 // attribute in the destination.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001724 int attribute_dest_package_id = p;
1725 if (attribute_dest_package_id != 0x01) {
Ryan Mitchell93bca972019-03-08 17:26:28 -08001726 // Find the cookie of the attribute resource id in the source AssetManager
Ryan Mitchell80094e32020-11-16 23:08:18 +00001727 base::expected<FindEntryResult, NullOrIOError> attribute_entry_result =
Ryan Mitchella55dc2e2019-01-24 10:58:23 -08001728 o.asset_manager_->FindEntry(make_resid(p, t, e), 0 /* density_override */ ,
1729 true /* stop_at_first_match */,
Ryan Mitchell80094e32020-11-16 23:08:18 +00001730 true /* ignore_configuration */);
1731 if (UNLIKELY(IsIOError(attribute_entry_result))) {
1732 return base::unexpected(GetIOError(attribute_entry_result.error()));
1733 }
1734 if (!attribute_entry_result.has_value()) {
1735 continue;
1736 }
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001737
Ryan Mitchell93bca972019-03-08 17:26:28 -08001738 // Determine the package id of the attribute in the destination AssetManager.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001739 auto attribute_package_map = src_asset_cookie_id_map.find(
1740 attribute_entry_result->cookie);
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001741 if (attribute_package_map == src_asset_cookie_id_map.end()) {
1742 continue;
1743 }
1744 auto attribute_dest_package = attribute_package_map->second.find(
1745 attribute_dest_package_id);
1746 if (attribute_dest_package == attribute_package_map->second.end()) {
1747 continue;
1748 }
1749 attribute_dest_package_id = attribute_dest_package->second;
1750 }
1751
Ryan Mitchell93bca972019-03-08 17:26:28 -08001752 // Lazily instantiate the destination package.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001753 std::unique_ptr<Package>& dest_package = packages_[attribute_dest_package_id];
1754 if (dest_package == nullptr) {
1755 dest_package.reset(new Package());
1756 }
1757
Ryan Mitchell93bca972019-03-08 17:26:28 -08001758 // Lazily instantiate and resize the destination type.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001759 util::unique_cptr<ThemeType>& dest_type = dest_package->types[t];
1760 if (dest_type == nullptr || dest_type->entry_count < type->entry_count) {
1761 const size_t type_alloc_size = sizeof(ThemeType)
1762 + (type->entry_count * sizeof(ThemeEntry));
1763 void* dest_data = malloc(type_alloc_size);
1764 memset(dest_data, 0, type->entry_count * sizeof(ThemeEntry));
1765
Ryan Mitchell93bca972019-03-08 17:26:28 -08001766 // Copy the existing destination type values if the type is resized.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001767 if (dest_type != nullptr) {
1768 memcpy(dest_data, type, sizeof(ThemeType)
1769 + (dest_type->entry_count * sizeof(ThemeEntry)));
1770 }
1771
1772 dest_type.reset(reinterpret_cast<ThemeType *>(dest_data));
1773 dest_type->entry_count = type->entry_count;
1774 }
1775
Ryan Mitchell93bca972019-03-08 17:26:28 -08001776 dest_type->entries[e].cookie = data_dest_cookie;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001777 dest_type->entries[e].value.dataType = entry.value.dataType;
Ryan Mitchell93bca972019-03-08 17:26:28 -08001778 dest_type->entries[e].value.data = attribute_data;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001779 dest_type->entries[e].type_spec_flags = entry.type_spec_flags;
1780 }
1781 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001782 }
1783 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001784 return {};
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001785}
1786
1787void Theme::Dump() const {
1788 base::ScopedLogSeverity _log(base::INFO);
1789 LOG(INFO) << base::StringPrintf("Theme(this=%p, AssetManager2=%p)", this, asset_manager_);
1790
1791 for (int p = 0; p < packages_.size(); p++) {
1792 auto& package = packages_[p];
1793 if (package == nullptr) {
1794 continue;
1795 }
1796
1797 for (int t = 0; t < package->types.size(); t++) {
1798 auto& type = package->types[t];
1799 if (type == nullptr) {
1800 continue;
1801 }
1802
1803 for (int e = 0; e < type->entry_count; e++) {
1804 auto& entry = type->entries[e];
1805 if (entry.value.dataType == Res_value::TYPE_NULL &&
1806 entry.value.data != Res_value::DATA_NULL_EMPTY) {
1807 continue;
1808 }
1809
1810 LOG(INFO) << base::StringPrintf(" entry(0x%08x)=(0x%08x) type=(0x%02x), cookie(%d)",
1811 make_resid(p, t, e), entry.value.data,
1812 entry.value.dataType, entry.cookie);
1813 }
1814 }
1815 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001816}
1817
1818} // namespace android