blob: 36bde5ccf267b84ea633e931b6bd66f47c07c4f3 [file] [log] [blame]
Adam Lesinski7ad11102016-10-28 16:39:15 -07001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define ATRACE_TAG ATRACE_TAG_RESOURCES
18
19#include "androidfw/AssetManager2.h"
20
y57cd1952018-04-12 14:26:23 -070021#include <algorithm>
Adam Lesinski30080e22017-10-16 16:18:09 -070022#include <iterator>
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -070023#include <map>
Winson2f3669b2019-01-11 11:28:34 -080024#include <set>
Adam Lesinski0c405242017-01-13 20:47:26 -080025
Adam Lesinski7ad11102016-10-28 16:39:15 -070026#include "android-base/logging.h"
27#include "android-base/stringprintf.h"
Ryan Mitchell8a891d82019-07-01 09:48:23 -070028#include "androidfw/ResourceUtils.h"
Ryan Mitchell31b11052019-06-13 13:47:26 -070029#include "androidfw/Util.h"
Adam Lesinski7ad11102016-10-28 16:39:15 -070030#include "utils/ByteOrder.h"
31#include "utils/Trace.h"
32
33#ifdef _WIN32
34#ifdef ERROR
35#undef ERROR
36#endif
37#endif
38
39namespace android {
40
Ryan Mitchell80094e32020-11-16 23:08:18 +000041namespace {
42
43using EntryValue = std::variant<Res_value, incfs::verified_map_ptr<ResTable_map_entry>>;
44
45base::expected<EntryValue, IOError> GetEntryValue(
46 incfs::verified_map_ptr<ResTable_entry> table_entry) {
47 const uint16_t entry_size = dtohs(table_entry->size);
48
49 // Check if the entry represents a bag value.
50 if (entry_size >= sizeof(ResTable_map_entry) &&
51 (dtohs(table_entry->flags) & ResTable_entry::FLAG_COMPLEX)) {
52 const auto map_entry = table_entry.convert<ResTable_map_entry>();
53 if (!map_entry) {
54 return base::unexpected(IOError::PAGES_MISSING);
55 }
56 return map_entry.verified();
57 }
58
59 // The entry represents a non-bag value.
60 const auto entry_value = table_entry.offset(entry_size).convert<Res_value>();
61 if (!entry_value) {
62 return base::unexpected(IOError::PAGES_MISSING);
63 }
64 Res_value value;
65 value.copyFrom_dtoh(entry_value.value());
66 return value;
67}
68
69} // namespace
70
Adam Lesinskibebfcc42018-02-12 14:27:46 -080071struct FindEntryResult {
Ryan Mitchell80094e32020-11-16 23:08:18 +000072 // The cookie representing the ApkAssets in which the value resides.
73 ApkAssetsCookie cookie;
74
75 // The value of the resource table entry. Either an android::Res_value for non-bag types or an
76 // incfs::verified_map_ptr<ResTable_map_entry> for bag types.
77 EntryValue entry;
Adam Lesinskibebfcc42018-02-12 14:27:46 -080078
79 // The configuration for which the resulting entry was defined. This is already swapped to host
80 // endianness.
81 ResTable_config config;
82
83 // The bitmask of configuration axis with which the resource value varies.
84 uint32_t type_flags;
85
86 // The dynamic package ID map for the package from which this resource came from.
87 const DynamicRefTable* dynamic_ref_table;
88
Ryan Mitchell8a891d82019-07-01 09:48:23 -070089 // The package name of the resource.
90 const std::string* package_name;
91
Adam Lesinskibebfcc42018-02-12 14:27:46 -080092 // The string pool reference to the type's name. This uses a different string pool than
93 // the global string pool, but this is hidden from the caller.
94 StringPoolRef type_string_ref;
95
96 // The string pool reference to the entry's name. This uses a different string pool than
97 // the global string pool, but this is hidden from the caller.
98 StringPoolRef entry_string_ref;
99};
100
Ryan Mitchellb894c272020-02-12 10:31:44 -0800101AssetManager2::AssetManager2() {
Adam Lesinski970bd8d2017-09-25 13:21:55 -0700102 memset(&configuration_, 0, sizeof(configuration_));
103}
Adam Lesinski7ad11102016-10-28 16:39:15 -0700104
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800105bool AssetManager2::SetApkAssets(std::vector<const ApkAssets*> apk_assets, bool invalidate_caches) {
106 apk_assets_ = std::move(apk_assets);
Adam Lesinskida431a22016-12-29 16:08:16 -0500107 BuildDynamicRefTable();
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800108 RebuildFilterList();
Adam Lesinski7ad11102016-10-28 16:39:15 -0700109 if (invalidate_caches) {
110 InvalidateCaches(static_cast<uint32_t>(-1));
111 }
112 return true;
113}
114
Adam Lesinskida431a22016-12-29 16:08:16 -0500115void AssetManager2::BuildDynamicRefTable() {
116 package_groups_.clear();
117 package_ids_.fill(0xff);
118
Ryan Mitchellb894c272020-02-12 10:31:44 -0800119 // A mapping from apk assets path to the runtime package id of its first loaded package.
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700120 std::unordered_map<std::string, uint8_t> apk_assets_package_ids;
121
Ryan Mitchell824cc492020-02-12 10:48:14 -0800122 // Overlay resources are not directly referenced by an application so their resource ids
123 // can change throughout the application's lifetime. Assign overlay package ids last.
124 std::vector<const ApkAssets*> sorted_apk_assets(apk_assets_);
125 std::stable_partition(sorted_apk_assets.begin(), sorted_apk_assets.end(), [](const ApkAssets* a) {
126 return !a->IsOverlay();
127 });
128
129 // The assets cookie must map to the position of the apk assets in the unsorted apk assets list.
130 std::unordered_map<const ApkAssets*, ApkAssetsCookie> apk_assets_cookies;
131 apk_assets_cookies.reserve(apk_assets_.size());
132 for (size_t i = 0, n = apk_assets_.size(); i < n; i++) {
133 apk_assets_cookies[apk_assets_[i]] = static_cast<ApkAssetsCookie>(i);
134 }
135
Ryan Mitchellb894c272020-02-12 10:31:44 -0800136 // 0x01 is reserved for the android package.
137 int next_package_id = 0x02;
Ryan Mitchell824cc492020-02-12 10:48:14 -0800138 for (const ApkAssets* apk_assets : sorted_apk_assets) {
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800139 std::shared_ptr<OverlayDynamicRefTable> overlay_ref_table;
140 if (auto loaded_idmap = apk_assets->GetLoadedIdmap(); loaded_idmap != nullptr) {
141 // The target package must precede the overlay package in the apk assets paths in order
142 // to take effect.
143 auto iter = apk_assets_package_ids.find(std::string(loaded_idmap->TargetApkPath()));
144 if (iter == apk_assets_package_ids.end()) {
145 LOG(INFO) << "failed to find target package for overlay "
146 << loaded_idmap->OverlayApkPath();
147 } else {
148 uint8_t target_package_id = iter->second;
149
150 // Create a special dynamic reference table for the overlay to rewrite references to
151 // overlay resources as references to the target resources they overlay.
152 overlay_ref_table = std::make_shared<OverlayDynamicRefTable>(
153 loaded_idmap->GetOverlayDynamicRefTable(target_package_id));
154
155 // Add the overlay resource map to the target package's set of overlays.
156 const uint8_t target_idx = package_ids_[target_package_id];
157 CHECK(target_idx != 0xff) << "overlay target '" << loaded_idmap->TargetApkPath()
158 << "'added to apk_assets_package_ids but does not have an"
159 << " assigned package group";
160
161 PackageGroup& target_package_group = package_groups_[target_idx];
162 target_package_group.overlays_.push_back(
163 ConfiguredOverlay{loaded_idmap->GetTargetResourcesMap(target_package_id,
164 overlay_ref_table.get()),
165 apk_assets_cookies[apk_assets]});
166 }
167 }
168
Ryan Mitchellb894c272020-02-12 10:31:44 -0800169 const LoadedArsc* loaded_arsc = apk_assets->GetLoadedArsc();
Ryan Mitchellb894c272020-02-12 10:31:44 -0800170 for (const std::unique_ptr<const LoadedPackage>& package : loaded_arsc->GetPackages()) {
171 // Get the package ID or assign one if a shared library.
172 int package_id;
173 if (package->IsDynamic()) {
174 package_id = next_package_id++;
175 } else {
176 package_id = package->GetPackageId();
Adam Lesinskida431a22016-12-29 16:08:16 -0500177 }
178
Adam Lesinskida431a22016-12-29 16:08:16 -0500179 uint8_t idx = package_ids_[package_id];
180 if (idx == 0xff) {
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800181 // Add the mapping for package ID to index if not present.
Adam Lesinskida431a22016-12-29 16:08:16 -0500182 package_ids_[package_id] = idx = static_cast<uint8_t>(package_groups_.size());
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800183 PackageGroup& new_group = package_groups_.emplace_back();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700184
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800185 if (overlay_ref_table != nullptr) {
186 // If this package is from an overlay, use a dynamic reference table that can rewrite
187 // overlay resource ids to their corresponding target resource ids.
188 new_group.dynamic_ref_table = overlay_ref_table;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700189 }
190
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800191 DynamicRefTable* ref_table = new_group.dynamic_ref_table.get();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700192 ref_table->mAssignedPackageId = package_id;
193 ref_table->mAppAsLib = package->IsDynamic() && package->GetPackageId() == 0x7f;
Adam Lesinskida431a22016-12-29 16:08:16 -0500194 }
Adam Lesinskida431a22016-12-29 16:08:16 -0500195
196 // Add the package and to the set of packages with the same ID.
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800197 PackageGroup* package_group = &package_groups_[idx];
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800198 package_group->packages_.push_back(ConfiguredPackage{package.get(), {}});
Ryan Mitchell824cc492020-02-12 10:48:14 -0800199 package_group->cookies_.push_back(apk_assets_cookies[apk_assets]);
Adam Lesinskida431a22016-12-29 16:08:16 -0500200
201 // Add the package name -> build time ID mappings.
202 for (const DynamicPackageEntry& entry : package->GetDynamicPackageMap()) {
203 String16 package_name(entry.package_name.c_str(), entry.package_name.size());
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700204 package_group->dynamic_ref_table->mEntries.replaceValueFor(
Adam Lesinskida431a22016-12-29 16:08:16 -0500205 package_name, static_cast<uint8_t>(entry.package_id));
206 }
Ryan Mitchellb894c272020-02-12 10:31:44 -0800207
208 apk_assets_package_ids.insert(std::make_pair(apk_assets->GetPath(), package_id));
Adam Lesinskida431a22016-12-29 16:08:16 -0500209 }
210 }
211
212 // Now assign the runtime IDs so that we have a build-time to runtime ID map.
213 const auto package_groups_end = package_groups_.end();
214 for (auto iter = package_groups_.begin(); iter != package_groups_end; ++iter) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800215 const std::string& package_name = iter->packages_[0].loaded_package_->GetPackageName();
Adam Lesinskida431a22016-12-29 16:08:16 -0500216 for (auto iter2 = package_groups_.begin(); iter2 != package_groups_end; ++iter2) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700217 iter2->dynamic_ref_table->addMapping(String16(package_name.c_str(), package_name.size()),
218 iter->dynamic_ref_table->mAssignedPackageId);
Adam Lesinskida431a22016-12-29 16:08:16 -0500219 }
220 }
221}
222
223void AssetManager2::DumpToLog() const {
224 base::ScopedLogSeverity _log(base::INFO);
225
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800226 LOG(INFO) << base::StringPrintf("AssetManager2(this=%p)", this);
227
Adam Lesinskida431a22016-12-29 16:08:16 -0500228 std::string list;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800229 for (const auto& apk_assets : apk_assets_) {
230 base::StringAppendF(&list, "%s,", apk_assets->GetPath().c_str());
231 }
232 LOG(INFO) << "ApkAssets: " << list;
233
234 list = "";
Adam Lesinskida431a22016-12-29 16:08:16 -0500235 for (size_t i = 0; i < package_ids_.size(); i++) {
236 if (package_ids_[i] != 0xff) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800237 base::StringAppendF(&list, "%02x -> %d, ", (int)i, package_ids_[i]);
Adam Lesinskida431a22016-12-29 16:08:16 -0500238 }
239 }
240 LOG(INFO) << "Package ID map: " << list;
241
Adam Lesinski0dd36992018-01-25 15:38:38 -0800242 for (const auto& package_group: package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800243 list = "";
244 for (const auto& package : package_group.packages_) {
245 const LoadedPackage* loaded_package = package.loaded_package_;
246 base::StringAppendF(&list, "%s(%02x%s), ", loaded_package->GetPackageName().c_str(),
247 loaded_package->GetPackageId(),
248 (loaded_package->IsDynamic() ? " dynamic" : ""));
249 }
250 LOG(INFO) << base::StringPrintf("PG (%02x): ",
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700251 package_group.dynamic_ref_table->mAssignedPackageId)
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800252 << list;
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800253
254 for (size_t i = 0; i < 256; i++) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700255 if (package_group.dynamic_ref_table->mLookupTable[i] != 0) {
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800256 LOG(INFO) << base::StringPrintf(" e[0x%02x] -> 0x%02x", (uint8_t) i,
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700257 package_group.dynamic_ref_table->mLookupTable[i]);
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800258 }
259 }
Adam Lesinskida431a22016-12-29 16:08:16 -0500260 }
261}
Adam Lesinski7ad11102016-10-28 16:39:15 -0700262
263const ResStringPool* AssetManager2::GetStringPoolForCookie(ApkAssetsCookie cookie) const {
264 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
265 return nullptr;
266 }
267 return apk_assets_[cookie]->GetLoadedArsc()->GetStringPool();
268}
269
Adam Lesinskida431a22016-12-29 16:08:16 -0500270const DynamicRefTable* AssetManager2::GetDynamicRefTableForPackage(uint32_t package_id) const {
271 if (package_id >= package_ids_.size()) {
272 return nullptr;
273 }
274
275 const size_t idx = package_ids_[package_id];
276 if (idx == 0xff) {
277 return nullptr;
278 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700279 return package_groups_[idx].dynamic_ref_table.get();
Adam Lesinskida431a22016-12-29 16:08:16 -0500280}
281
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700282std::shared_ptr<const DynamicRefTable> AssetManager2::GetDynamicRefTableForCookie(
283 ApkAssetsCookie cookie) const {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800284 for (const PackageGroup& package_group : package_groups_) {
285 for (const ApkAssetsCookie& package_cookie : package_group.cookies_) {
286 if (package_cookie == cookie) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700287 return package_group.dynamic_ref_table;
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800288 }
289 }
290 }
291 return nullptr;
292}
293
MÃ¥rten Kongstadc92c4dd2019-02-05 01:29:59 +0100294const std::unordered_map<std::string, std::string>*
295 AssetManager2::GetOverlayableMapForPackage(uint32_t package_id) const {
296
297 if (package_id >= package_ids_.size()) {
298 return nullptr;
299 }
300
301 const size_t idx = package_ids_[package_id];
302 if (idx == 0xff) {
303 return nullptr;
304 }
305
306 const PackageGroup& package_group = package_groups_[idx];
Ryan Mitchell80094e32020-11-16 23:08:18 +0000307 if (package_group.packages_.empty()) {
MÃ¥rten Kongstadc92c4dd2019-02-05 01:29:59 +0100308 return nullptr;
309 }
310
311 const auto loaded_package = package_group.packages_[0].loaded_package_;
312 return &loaded_package->GetOverlayableMap();
313}
314
Ryan Mitchell2e394222019-08-28 12:10:51 -0700315bool AssetManager2::GetOverlayablesToString(const android::StringPiece& package_name,
316 std::string* out) const {
317 uint8_t package_id = 0U;
318 for (const auto& apk_assets : apk_assets_) {
319 const LoadedArsc* loaded_arsc = apk_assets->GetLoadedArsc();
320 if (loaded_arsc == nullptr) {
321 continue;
322 }
323
324 const auto& loaded_packages = loaded_arsc->GetPackages();
325 if (loaded_packages.empty()) {
326 continue;
327 }
328
329 const auto& loaded_package = loaded_packages[0];
330 if (loaded_package->GetPackageName() == package_name) {
331 package_id = GetAssignedPackageId(loaded_package.get());
332 break;
333 }
334 }
335
336 if (package_id == 0U) {
337 ANDROID_LOG(ERROR) << base::StringPrintf("No package with name '%s", package_name.data());
338 return false;
339 }
340
341 const size_t idx = package_ids_[package_id];
342 if (idx == 0xff) {
343 return false;
344 }
345
346 std::string output;
347 for (const ConfiguredPackage& package : package_groups_[idx].packages_) {
348 const LoadedPackage* loaded_package = package.loaded_package_;
349 for (auto it = loaded_package->begin(); it != loaded_package->end(); it++) {
350 const OverlayableInfo* info = loaded_package->GetOverlayableInfo(*it);
351 if (info != nullptr) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000352 auto res_name = GetResourceName(*it);
353 if (!res_name.has_value()) {
Ryan Mitchell2e394222019-08-28 12:10:51 -0700354 ANDROID_LOG(ERROR) << base::StringPrintf(
355 "Unable to retrieve name of overlayable resource 0x%08x", *it);
356 return false;
357 }
358
Ryan Mitchell80094e32020-11-16 23:08:18 +0000359 const std::string name = ToFormattedResourceString(*res_name);
Ryan Mitchell2e394222019-08-28 12:10:51 -0700360 output.append(base::StringPrintf(
361 "resource='%s' overlayable='%s' actor='%s' policy='0x%08x'\n",
362 name.c_str(), info->name.c_str(), info->actor.c_str(), info->policy_flags));
363 }
364 }
365 }
366
367 *out = std::move(output);
368 return true;
369}
370
Ryan Mitchell192400c2020-04-02 09:54:23 -0700371bool AssetManager2::ContainsAllocatedTable() const {
372 return std::find_if(apk_assets_.begin(), apk_assets_.end(),
373 std::mem_fn(&ApkAssets::IsTableAllocated)) != apk_assets_.end();
374}
375
Adam Lesinski7ad11102016-10-28 16:39:15 -0700376void AssetManager2::SetConfiguration(const ResTable_config& configuration) {
377 const int diff = configuration_.diff(configuration);
378 configuration_ = configuration;
379
380 if (diff) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800381 RebuildFilterList();
Adam Lesinski7ad11102016-10-28 16:39:15 -0700382 InvalidateCaches(static_cast<uint32_t>(diff));
383 }
384}
385
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700386std::set<std::string> AssetManager2::GetNonSystemOverlayPaths() const {
387 std::set<std::string> non_system_overlays;
Adam Lesinski0c405242017-01-13 20:47:26 -0800388 for (const PackageGroup& package_group : package_groups_) {
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800389 bool found_system_package = false;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800390 for (const ConfiguredPackage& package : package_group.packages_) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700391 if (package.loaded_package_->IsSystem()) {
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800392 found_system_package = true;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700393 break;
394 }
395 }
396
397 if (!found_system_package) {
398 for (const ConfiguredOverlay& overlay : package_group.overlays_) {
399 non_system_overlays.insert(apk_assets_[overlay.cookie]->GetPath());
400 }
401 }
402 }
403
404 return non_system_overlays;
405}
406
Ryan Mitchell80094e32020-11-16 23:08:18 +0000407base::expected<std::set<ResTable_config>, IOError> AssetManager2::GetResourceConfigurations(
408 bool exclude_system, bool exclude_mipmap) const {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700409 ATRACE_NAME("AssetManager::GetResourceConfigurations");
410 const auto non_system_overlays =
411 (exclude_system) ? GetNonSystemOverlayPaths() : std::set<std::string>();
412
413 std::set<ResTable_config> configurations;
414 for (const PackageGroup& package_group : package_groups_) {
415 for (size_t i = 0; i < package_group.packages_.size(); i++) {
416 const ConfiguredPackage& package = package_group.packages_[i];
417 if (exclude_system && package.loaded_package_->IsSystem()) {
Adam Lesinski0c405242017-01-13 20:47:26 -0800418 continue;
419 }
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800420
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700421 auto apk_assets = apk_assets_[package_group.cookies_[i]];
422 if (exclude_system && apk_assets->IsOverlay()
423 && non_system_overlays.find(apk_assets->GetPath()) == non_system_overlays.end()) {
424 // Exclude overlays that target system resources.
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800425 continue;
426 }
427
Ryan Mitchell80094e32020-11-16 23:08:18 +0000428 auto result = package.loaded_package_->CollectConfigurations(exclude_mipmap, &configurations);
429 if (UNLIKELY(!result.has_value())) {
430 return base::unexpected(result.error());
431 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800432 }
433 }
434 return configurations;
435}
436
437std::set<std::string> AssetManager2::GetResourceLocales(bool exclude_system,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800438 bool merge_equivalent_languages) const {
439 ATRACE_NAME("AssetManager::GetResourceLocales");
Adam Lesinski0c405242017-01-13 20:47:26 -0800440 std::set<std::string> locales;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700441 const auto non_system_overlays =
442 (exclude_system) ? GetNonSystemOverlayPaths() : std::set<std::string>();
443
Adam Lesinski0c405242017-01-13 20:47:26 -0800444 for (const PackageGroup& package_group : package_groups_) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700445 for (size_t i = 0; i < package_group.packages_.size(); i++) {
446 const ConfiguredPackage& package = package_group.packages_[i];
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800447 if (exclude_system && package.loaded_package_->IsSystem()) {
Adam Lesinski0c405242017-01-13 20:47:26 -0800448 continue;
449 }
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800450
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700451 auto apk_assets = apk_assets_[package_group.cookies_[i]];
452 if (exclude_system && apk_assets->IsOverlay()
453 && non_system_overlays.find(apk_assets->GetPath()) == non_system_overlays.end()) {
454 // Exclude overlays that target system resources.
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800455 continue;
456 }
457
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800458 package.loaded_package_->CollectLocales(merge_equivalent_languages, &locales);
Adam Lesinski0c405242017-01-13 20:47:26 -0800459 }
460 }
461 return locales;
462}
463
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800464std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename,
465 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700466 const std::string new_path = "assets/" + filename;
467 return OpenNonAsset(new_path, mode);
468}
469
470std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename, ApkAssetsCookie cookie,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800471 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700472 const std::string new_path = "assets/" + filename;
473 return OpenNonAsset(new_path, cookie, mode);
474}
475
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800476std::unique_ptr<AssetDir> AssetManager2::OpenDir(const std::string& dirname) const {
477 ATRACE_NAME("AssetManager::OpenDir");
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800478
479 std::string full_path = "assets/" + dirname;
480 std::unique_ptr<SortedVector<AssetDir::FileInfo>> files =
481 util::make_unique<SortedVector<AssetDir::FileInfo>>();
482
483 // Start from the back.
484 for (auto iter = apk_assets_.rbegin(); iter != apk_assets_.rend(); ++iter) {
485 const ApkAssets* apk_assets = *iter;
MÃ¥rten Kongstaddbf343b2019-02-21 07:54:18 +0100486 if (apk_assets->IsOverlay()) {
487 continue;
488 }
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800489
490 auto func = [&](const StringPiece& name, FileType type) {
491 AssetDir::FileInfo info;
492 info.setFileName(String8(name.data(), name.size()));
493 info.setFileType(type);
494 info.setSourceName(String8(apk_assets->GetPath().c_str()));
495 files->add(info);
496 };
497
Ryan Mitchellc07aa702020-03-10 13:49:12 -0700498 if (!apk_assets->GetAssetsProvider()->ForEachFile(full_path, func)) {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800499 return {};
500 }
501 }
502
503 std::unique_ptr<AssetDir> asset_dir = util::make_unique<AssetDir>();
504 asset_dir->setFileList(files.release());
505 return asset_dir;
506}
507
Adam Lesinski7ad11102016-10-28 16:39:15 -0700508// Search in reverse because that's how we used to do it and we need to preserve behaviour.
509// This is unfortunate, because ClassLoaders delegate to the parent first, so the order
510// is inconsistent for split APKs.
511std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
512 Asset::AccessMode mode,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800513 ApkAssetsCookie* out_cookie) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700514 for (int32_t i = apk_assets_.size() - 1; i >= 0; i--) {
MÃ¥rten Kongstaddbf343b2019-02-21 07:54:18 +0100515 // Prevent RRO from modifying assets and other entries accessed by file
516 // path. Explicitly asking for a path in a given package (denoted by a
517 // cookie) is still OK.
518 if (apk_assets_[i]->IsOverlay()) {
519 continue;
520 }
521
Ryan Mitchellc07aa702020-03-10 13:49:12 -0700522 std::unique_ptr<Asset> asset = apk_assets_[i]->GetAssetsProvider()->Open(filename, mode);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700523 if (asset) {
524 if (out_cookie != nullptr) {
525 *out_cookie = i;
526 }
527 return asset;
528 }
529 }
530
531 if (out_cookie != nullptr) {
532 *out_cookie = kInvalidCookie;
533 }
534 return {};
535}
536
537std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800538 ApkAssetsCookie cookie,
539 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700540 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
541 return {};
542 }
Ryan Mitchellc07aa702020-03-10 13:49:12 -0700543 return apk_assets_[cookie]->GetAssetsProvider()->Open(filename, mode);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700544}
545
Ryan Mitchell80094e32020-11-16 23:08:18 +0000546base::expected<FindEntryResult, NullOrIOError> AssetManager2::FindEntry(
547 uint32_t resid, uint16_t density_override, bool stop_at_first_match,
548 bool ignore_configuration) const {
549 const bool logging_enabled = resource_resolution_logging_enabled_;
550 if (UNLIKELY(logging_enabled)) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700551 // Clear the last logged resource resolution.
552 ResetResourceResolution();
553 last_resolution_.resid = resid;
554 }
555
Adam Lesinski7ad11102016-10-28 16:39:15 -0700556 // Might use this if density_override != 0.
557 ResTable_config density_override_config;
558
559 // Select our configuration or generate a density override configuration.
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800560 const ResTable_config* desired_config = &configuration_;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700561 if (density_override != 0 && density_override != configuration_.density) {
562 density_override_config = configuration_;
563 density_override_config.density = density_override;
564 desired_config = &density_override_config;
565 }
566
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700567 // Retrieve the package group from the package id of the resource id.
Ryan Mitchell80094e32020-11-16 23:08:18 +0000568 if (UNLIKELY(!is_valid_resid(resid))) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500569 LOG(ERROR) << base::StringPrintf("Invalid ID 0x%08x.", resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000570 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -0500571 }
572
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800573 const uint32_t package_id = get_package_id(resid);
574 const uint8_t type_idx = get_type_id(resid) - 1;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800575 const uint16_t entry_idx = get_entry_id(resid);
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700576 uint8_t package_idx = package_ids_[package_id];
Ryan Mitchell80094e32020-11-16 23:08:18 +0000577 if (UNLIKELY(package_idx == 0xff)) {
Ryan Mitchell2fe23472019-02-27 09:43:01 -0800578 ANDROID_LOG(ERROR) << base::StringPrintf("No package ID %02x found for ID 0x%08x.",
579 package_id, resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000580 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -0500581 }
582
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800583 const PackageGroup& package_group = package_groups_[package_idx];
Ryan Mitchell80094e32020-11-16 23:08:18 +0000584 auto result = FindEntryInternal(package_group, type_idx, entry_idx, *desired_config,
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800585 stop_at_first_match, ignore_configuration);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000586 if (UNLIKELY(!result.has_value())) {
587 return base::unexpected(result.error());
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700588 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800589
Ryan Mitchell80094e32020-11-16 23:08:18 +0000590 if (!stop_at_first_match && !ignore_configuration && !apk_assets_[result->cookie]->IsLoader()) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700591 for (const auto& id_map : package_group.overlays_) {
592 auto overlay_entry = id_map.overlay_res_maps_.Lookup(resid);
593 if (!overlay_entry) {
594 // No id map entry exists for this target resource.
595 continue;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000596 }
597 if (overlay_entry.IsInlineValue()) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700598 // The target resource is overlaid by an inline value not represented by a resource.
Ryan Mitchell80094e32020-11-16 23:08:18 +0000599 result->entry = overlay_entry.GetInlineValue();
600 result->dynamic_ref_table = id_map.overlay_res_maps_.GetOverlayDynamicRefTable();
601 result->cookie = id_map.cookie;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700602 continue;
603 }
604
Ryan Mitchell80094e32020-11-16 23:08:18 +0000605 auto overlay_result = FindEntry(overlay_entry.GetResourceId(), density_override,
606 false /* stop_at_first_match */,
607 false /* ignore_configuration */);
608 if (UNLIKELY(IsIOError(overlay_result))) {
609 return base::unexpected(overlay_result.error());
610 }
611 if (!overlay_result.has_value()) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700612 continue;
613 }
614
Ryan Mitchell80094e32020-11-16 23:08:18 +0000615 if (!overlay_result->config.isBetterThan(result->config, desired_config)
616 && overlay_result->config.compare(result->config) != 0) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700617 // The configuration of the entry for the overlay must be equal to or better than the target
618 // configuration to be chosen as the better value.
619 continue;
620 }
621
Ryan Mitchell80094e32020-11-16 23:08:18 +0000622 result->cookie = overlay_result->cookie;
623 result->entry = overlay_result->entry;
624 result->config = overlay_result->config;
625 result->dynamic_ref_table = id_map.overlay_res_maps_.GetOverlayDynamicRefTable();
626
627 if (UNLIKELY(logging_enabled)) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700628 last_resolution_.steps.push_back(
Ryan Mitchell80094e32020-11-16 23:08:18 +0000629 Resolution::Step{Resolution::Step::Type::OVERLAID, overlay_result->config.toString(),
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800630 overlay_result->package_name,
631 overlay_result->cookie});
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700632 }
633 }
634 }
635
Ryan Mitchell80094e32020-11-16 23:08:18 +0000636 if (UNLIKELY(logging_enabled)) {
637 last_resolution_.cookie = result->cookie;
638 last_resolution_.type_string_ref = result->type_string_ref;
639 last_resolution_.entry_string_ref = result->entry_string_ref;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700640 }
641
Ryan Mitchell80094e32020-11-16 23:08:18 +0000642 return result;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700643}
644
Ryan Mitchell80094e32020-11-16 23:08:18 +0000645base::expected<FindEntryResult, NullOrIOError> AssetManager2::FindEntryInternal(
646 const PackageGroup& package_group, uint8_t type_idx, uint16_t entry_idx,
647 const ResTable_config& desired_config, bool stop_at_first_match,
648 bool ignore_configuration) const {
649 const bool logging_enabled = resource_resolution_logging_enabled_;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800650 ApkAssetsCookie best_cookie = kInvalidCookie;
651 const LoadedPackage* best_package = nullptr;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000652 incfs::verified_map_ptr<ResTable_type> best_type;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800653 const ResTable_config* best_config = nullptr;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000654 uint32_t best_offset = 0U;
655 uint32_t type_flags = 0U;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800656
Winson2f3669b2019-01-11 11:28:34 -0800657 std::vector<Resolution::Step> resolution_steps;
658
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800659 // If `desired_config` is not the same as the set configuration or the caller will accept a value
660 // from any configuration, then we cannot use our filtered list of types since it only it contains
661 // types matched to the set configuration.
662 const bool use_filtered = !ignore_configuration && &desired_config == &configuration_;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800663
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700664 const size_t package_count = package_group.packages_.size();
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800665 for (size_t pi = 0; pi < package_count; pi++) {
666 const ConfiguredPackage& loaded_package_impl = package_group.packages_[pi];
667 const LoadedPackage* loaded_package = loaded_package_impl.loaded_package_;
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800668 const ApkAssetsCookie cookie = package_group.cookies_[pi];
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800669
670 // If the type IDs are offset in this package, we need to take that into account when searching
671 // for a type.
672 const TypeSpec* type_spec = loaded_package->GetTypeSpecByTypeIndex(type_idx);
673 if (UNLIKELY(type_spec == nullptr)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700674 continue;
675 }
676
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800677 // Allow custom loader packages to overlay resource values with configurations equivalent to the
678 // current best configuration.
679 const bool package_is_loader = loaded_package->IsCustomLoader();
680
Ryan Mitchell80094e32020-11-16 23:08:18 +0000681 auto entry_flags = type_spec->GetFlagsForEntryIndex(entry_idx);
Bernie Innocenti58cf8e32020-12-19 15:31:52 +0900682 if (UNLIKELY(!entry_flags.has_value())) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000683 return base::unexpected(entry_flags.error());
684 }
685 type_flags |= entry_flags.value();
686
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800687 const FilteredConfigGroup& filtered_group = loaded_package_impl.filtered_configs_[type_idx];
688 const size_t type_entry_count = (use_filtered) ? filtered_group.type_entries.size()
689 : type_spec->type_entries.size();
690 for (size_t i = 0; i < type_entry_count; i++) {
691 const TypeSpec::TypeEntry* type_entry = (use_filtered) ? filtered_group.type_entries[i]
692 : &type_spec->type_entries[i];
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800693
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800694 // We can skip calling ResTable_config::match() if the caller does not care for the
695 // configuration to match or if we're using the list of types that have already had their
696 // configuration matched.
697 const ResTable_config& this_config = type_entry->config;
698 if (!(use_filtered || ignore_configuration || this_config.match(desired_config))) {
699 continue;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800700 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800701
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800702 Resolution::Step::Type resolution_type;
703 if (best_config == nullptr) {
704 resolution_type = Resolution::Step::Type::INITIAL;
705 } else if (this_config.isBetterThan(*best_config, &desired_config)) {
706 resolution_type = Resolution::Step::Type::BETTER_MATCH;
707 } else if (package_is_loader && this_config.compare(*best_config) == 0) {
708 resolution_type = Resolution::Step::Type::OVERLAID;
709 } else {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000710 if (UNLIKELY(logging_enabled)) {
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800711 resolution_steps.push_back(Resolution::Step{Resolution::Step::Type::SKIPPED,
712 this_config.toString(),
713 &loaded_package->GetPackageName(),
714 cookie});
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800715 }
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800716 continue;
717 }
718
719 // The configuration matches and is better than the previous selection.
720 // Find the entry value if it exists for this configuration.
721 const auto& type = type_entry->type;
722 const auto offset = LoadedPackage::GetEntryOffset(type, entry_idx);
723 if (UNLIKELY(IsIOError(offset))) {
724 return base::unexpected(offset.error());
725 }
726
727 if (!offset.has_value()) {
728 if (UNLIKELY(logging_enabled)) {
729 resolution_steps.push_back(Resolution::Step{Resolution::Step::Type::NO_ENTRY,
730 this_config.toString(),
731 &loaded_package->GetPackageName(),
732 cookie});
733 }
734 continue;
735 }
736
737 best_cookie = cookie;
738 best_package = loaded_package;
739 best_type = type;
740 best_config = &this_config;
741 best_offset = offset.value();
742
743 if (UNLIKELY(logging_enabled)) {
744 last_resolution_.steps.push_back(Resolution::Step{resolution_type,
745 this_config.toString(),
746 &loaded_package->GetPackageName(),
747 cookie});
748 }
749
750 // Any configuration will suffice, so break.
751 if (stop_at_first_match) {
752 break;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700753 }
754 }
755 }
756
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800757 if (UNLIKELY(best_cookie == kInvalidCookie)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000758 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700759 }
760
Ryan Mitchell80094e32020-11-16 23:08:18 +0000761 auto best_entry_result = LoadedPackage::GetEntryFromOffset(best_type, best_offset);
762 if (!best_entry_result.has_value()) {
763 return base::unexpected(best_entry_result.error());
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800764 }
765
Ryan Mitchell80094e32020-11-16 23:08:18 +0000766 const incfs::map_ptr<ResTable_entry> best_entry = *best_entry_result;
767 if (!best_entry) {
768 return base::unexpected(IOError::PAGES_MISSING);
Ryan Mitchellbf1f45b2020-09-29 17:22:52 -0700769 }
770
Ryan Mitchell80094e32020-11-16 23:08:18 +0000771 const auto entry = GetEntryValue(best_entry.verified());
772 if (!entry.has_value()) {
773 return base::unexpected(entry.error());
774 }
Winson2f3669b2019-01-11 11:28:34 -0800775
Ryan Mitchell80094e32020-11-16 23:08:18 +0000776 return FindEntryResult{
777 .cookie = best_cookie,
778 .entry = *entry,
779 .config = *best_config,
780 .type_flags = type_flags,
781 .package_name = &best_package->GetPackageName(),
782 .type_string_ref = StringPoolRef(best_package->GetTypeStringPool(), best_type->id - 1),
783 .entry_string_ref = StringPoolRef(best_package->GetKeyStringPool(),
784 best_entry->key.index),
785 .dynamic_ref_table = package_group.dynamic_ref_table.get(),
786 };
Adam Lesinski7ad11102016-10-28 16:39:15 -0700787}
788
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700789void AssetManager2::ResetResourceResolution() const {
790 last_resolution_.cookie = kInvalidCookie;
791 last_resolution_.resid = 0;
792 last_resolution_.steps.clear();
793 last_resolution_.type_string_ref = StringPoolRef();
794 last_resolution_.entry_string_ref = StringPoolRef();
795}
796
Winson2f3669b2019-01-11 11:28:34 -0800797void AssetManager2::SetResourceResolutionLoggingEnabled(bool enabled) {
798 resource_resolution_logging_enabled_ = enabled;
Winson2f3669b2019-01-11 11:28:34 -0800799 if (!enabled) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700800 ResetResourceResolution();
Winson2f3669b2019-01-11 11:28:34 -0800801 }
802}
803
804std::string AssetManager2::GetLastResourceResolution() const {
805 if (!resource_resolution_logging_enabled_) {
806 LOG(ERROR) << "Must enable resource resolution logging before getting path.";
Ryan Mitchell80094e32020-11-16 23:08:18 +0000807 return {};
Winson2f3669b2019-01-11 11:28:34 -0800808 }
809
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800810 const ApkAssetsCookie cookie = last_resolution_.cookie;
Winson2f3669b2019-01-11 11:28:34 -0800811 if (cookie == kInvalidCookie) {
812 LOG(ERROR) << "AssetManager hasn't resolved a resource to read resolution path.";
Ryan Mitchell80094e32020-11-16 23:08:18 +0000813 return {};
Winson2f3669b2019-01-11 11:28:34 -0800814 }
815
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800816 const uint32_t resid = last_resolution_.resid;
817 const auto package = apk_assets_[cookie]->GetLoadedArsc()->GetPackageById(get_package_id(resid));
818
Winson2f3669b2019-01-11 11:28:34 -0800819 std::string resource_name_string;
Winson2f3669b2019-01-11 11:28:34 -0800820 if (package != nullptr) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000821 auto resource_name = ToResourceName(last_resolution_.type_string_ref,
822 last_resolution_.entry_string_ref,
823 package->GetPackageName());
824 resource_name_string = resource_name.has_value() ?
825 ToFormattedResourceString(resource_name.value()) : "<unknown>";
Winson2f3669b2019-01-11 11:28:34 -0800826 }
827
828 std::stringstream log_stream;
829 log_stream << base::StringPrintf("Resolution for 0x%08x ", resid)
830 << resource_name_string
831 << "\n\tFor config -"
832 << configuration_.toString();
833
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800834 for (const Resolution::Step& step : last_resolution_.steps) {
835 const static std::unordered_map<Resolution::Step::Type, const char*> kStepStrings = {
836 {Resolution::Step::Type::INITIAL, "Found initial"},
837 {Resolution::Step::Type::BETTER_MATCH, "Found better"},
838 {Resolution::Step::Type::OVERLAID, "Overlaid"},
839 {Resolution::Step::Type::SKIPPED, "Skipped"},
840 {Resolution::Step::Type::NO_ENTRY, "No entry"}
841 };
842
843 const auto prefix = kStepStrings.find(step.type);
844 if (prefix == kStepStrings.end()) {
845 continue;
Winson2f3669b2019-01-11 11:28:34 -0800846 }
847
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800848 log_stream << "\n\t" << prefix->second << ": " << *step.package_name << " ("
849 << apk_assets_[step.cookie]->GetPath() << ")";
850 if (!step.config_name.isEmpty()) {
851 log_stream << " -" << step.config_name;
Winson2f3669b2019-01-11 11:28:34 -0800852 }
853 }
854
855 return log_stream.str();
856}
857
Ryan Mitchell80094e32020-11-16 23:08:18 +0000858base::expected<AssetManager2::ResourceName, NullOrIOError> AssetManager2::GetResourceName(
859 uint32_t resid) const {
860 auto result = FindEntry(resid, 0u /* density_override */, true /* stop_at_first_match */,
861 true /* ignore_configuration */);
862 if (!result.has_value()) {
863 return base::unexpected(result.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -0700864 }
865
Ryan Mitchell80094e32020-11-16 23:08:18 +0000866 return ToResourceName(result->type_string_ref,
867 result->entry_string_ref,
868 *result->package_name);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700869}
870
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800871base::expected<uint32_t, NullOrIOError> AssetManager2::GetResourceTypeSpecFlags(
872 uint32_t resid) const {
873 auto result = FindEntry(resid, 0u /* density_override */, false /* stop_at_first_match */,
874 true /* ignore_configuration */);
875 if (!result.has_value()) {
876 return base::unexpected(result.error());
877 }
878 return result->type_flags;
879}
880
Ryan Mitchell80094e32020-11-16 23:08:18 +0000881base::expected<AssetManager2::SelectedValue, NullOrIOError> AssetManager2::GetResource(
882 uint32_t resid, bool may_be_bag, uint16_t density_override) const {
883 auto result = FindEntry(resid, density_override, false /* stop_at_first_match */,
884 false /* ignore_configuration */);
885 if (!result.has_value()) {
886 return base::unexpected(result.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -0700887 }
888
Ryan Mitchell80094e32020-11-16 23:08:18 +0000889 auto result_map_entry = std::get_if<incfs::verified_map_ptr<ResTable_map_entry>>(&result->entry);
Ryan Mitchellbf1f45b2020-09-29 17:22:52 -0700890 if (result_map_entry != nullptr) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700891 if (!may_be_bag) {
892 LOG(ERROR) << base::StringPrintf("Resource %08x is a complex map type.", resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000893 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700894 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800895
896 // Create a reference since we can't represent this complex type as a Res_value.
Ryan Mitchell80094e32020-11-16 23:08:18 +0000897 return SelectedValue(Res_value::TYPE_REFERENCE, resid, result->cookie, result->type_flags,
898 resid, result->config);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700899 }
900
Adam Lesinskida431a22016-12-29 16:08:16 -0500901 // Convert the package ID to the runtime assigned package ID.
Ryan Mitchell80094e32020-11-16 23:08:18 +0000902 Res_value value = std::get<Res_value>(result->entry);
903 result->dynamic_ref_table->lookupResourceValue(&value);
Adam Lesinskida431a22016-12-29 16:08:16 -0500904
Ryan Mitchell80094e32020-11-16 23:08:18 +0000905 return SelectedValue(value.dataType, value.data, result->cookie, result->type_flags,
906 resid, result->config);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700907}
908
Ryan Mitchell80094e32020-11-16 23:08:18 +0000909base::expected<std::monostate, NullOrIOError> AssetManager2::ResolveReference(
Ryan Mitchella45506e2020-11-16 23:08:18 +0000910 AssetManager2::SelectedValue& value, bool cache_value) const {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000911 if (value.type != Res_value::TYPE_REFERENCE || value.data == 0U) {
912 // Not a reference. Nothing to do.
913 return {};
Adam Lesinski0c405242017-01-13 20:47:26 -0800914 }
Ryan Mitchell80094e32020-11-16 23:08:18 +0000915
Ryan Mitchella45506e2020-11-16 23:08:18 +0000916 const uint32_t original_flags = value.flags;
917 const uint32_t original_resid = value.data;
918 if (cache_value) {
919 auto cached_value = cached_resolved_values_.find(value.data);
920 if (cached_value != cached_resolved_values_.end()) {
921 value = cached_value->second;
922 value.flags |= original_flags;
923 return {};
924 }
925 }
926
927 uint32_t combined_flags = 0U;
928 uint32_t resolve_resid = original_resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000929 constexpr const uint32_t kMaxIterations = 20;
930 for (uint32_t i = 0U;; i++) {
931 auto result = GetResource(resolve_resid, true /*may_be_bag*/);
932 if (!result.has_value()) {
Ryan Mitchelle7ab6272020-11-13 18:06:15 -0800933 value.resid = resolve_resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000934 return base::unexpected(result.error());
935 }
936
Ryan Mitchelle7ab6272020-11-13 18:06:15 -0800937 // If resource resolution fails, the value should be set to the last reference that was able to
938 // be resolved successfully.
939 value = *result;
940 value.flags |= combined_flags;
941
Ryan Mitchell80094e32020-11-16 23:08:18 +0000942 if (result->type != Res_value::TYPE_REFERENCE ||
943 result->data == Res_value::DATA_NULL_UNDEFINED ||
944 result->data == resolve_resid || i == kMaxIterations) {
945 // This reference can't be resolved, so exit now and let the caller deal with it.
Ryan Mitchella45506e2020-11-16 23:08:18 +0000946 if (cache_value) {
947 cached_resolved_values_[original_resid] = value;
948 }
949
950 // Above value is cached without original_flags to ensure they don't get included in future
951 // queries that hit the cache
952 value.flags |= original_flags;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000953 return {};
954 }
955
Ryan Mitchelle7ab6272020-11-13 18:06:15 -0800956 combined_flags = result->flags;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000957 resolve_resid = result->data;
958 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800959}
960
Ryan Mitchell80094e32020-11-16 23:08:18 +0000961const std::vector<uint32_t> AssetManager2::GetBagResIdStack(uint32_t resid) const {
Aurimas Liutikas8f004c82019-01-17 17:20:10 -0800962 auto cached_iter = cached_bag_resid_stacks_.find(resid);
963 if (cached_iter != cached_bag_resid_stacks_.end()) {
964 return cached_iter->second;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -0800965 }
Ryan Mitchell80094e32020-11-16 23:08:18 +0000966
967 std::vector<uint32_t> found_resids;
968 GetBag(resid, found_resids);
969 cached_bag_resid_stacks_.emplace(resid, found_resids);
970 return found_resids;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -0800971}
972
Ryan Mitchell80094e32020-11-16 23:08:18 +0000973base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::ResolveBag(
974 AssetManager2::SelectedValue& value) const {
975 if (UNLIKELY(value.type != Res_value::TYPE_REFERENCE)) {
976 return base::unexpected(std::nullopt);
977 }
Aurimas Liutikas8f004c82019-01-17 17:20:10 -0800978
Ryan Mitchell80094e32020-11-16 23:08:18 +0000979 auto bag = GetBag(value.data);
980 if (bag.has_value()) {
981 value.flags |= (*bag)->type_spec_flags;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -0800982 }
983 return bag;
y57cd1952018-04-12 14:26:23 -0700984}
985
Ryan Mitchell80094e32020-11-16 23:08:18 +0000986base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::GetBag(uint32_t resid) const {
987 std::vector<uint32_t> found_resids;
988 const auto bag = GetBag(resid, found_resids);
989 cached_bag_resid_stacks_.emplace(resid, found_resids);
990 return bag;
Ryan Mitchell155d5392020-02-10 13:35:24 -0800991}
992
Ryan Mitchell80094e32020-11-16 23:08:18 +0000993base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::GetBag(
994 uint32_t resid, std::vector<uint32_t>& child_resids) const {
995 if (auto cached_iter = cached_bags_.find(resid); cached_iter != cached_bags_.end()) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700996 return cached_iter->second.get();
997 }
998
Ryan Mitchell80094e32020-11-16 23:08:18 +0000999 auto entry = FindEntry(resid, 0u /* density_override */, false /* stop_at_first_match */,
1000 false /* ignore_configuration */);
1001 if (!entry.has_value()) {
1002 return base::unexpected(entry.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001003 }
1004
Ryan Mitchell80094e32020-11-16 23:08:18 +00001005 auto entry_map = std::get_if<incfs::verified_map_ptr<ResTable_map_entry>>(&entry->entry);
1006 if (entry_map == nullptr) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001007 // Not a bag, nothing to do.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001008 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001009 }
1010
Ryan Mitchell80094e32020-11-16 23:08:18 +00001011 auto map = *entry_map;
1012 auto map_entry = map.offset(dtohs(map->size)).convert<ResTable_map>();
1013 const auto map_entry_end = map_entry + dtohl(map->count);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001014
y57cd1952018-04-12 14:26:23 -07001015 // Keep track of ids that have already been seen to prevent infinite loops caused by circular
Ryan Mitchell80094e32020-11-16 23:08:18 +00001016 // dependencies between bags.
y57cd1952018-04-12 14:26:23 -07001017 child_resids.push_back(resid);
1018
Adam Lesinskida431a22016-12-29 16:08:16 -05001019 uint32_t parent_resid = dtohl(map->parent.ident);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001020 if (parent_resid == 0U ||
1021 std::find(child_resids.begin(), child_resids.end(), parent_resid) != child_resids.end()) {
1022 // There is no parent or a circular parental dependency exist, meaning there is nothing to
1023 // inherit and we can do a simple copy of the entries in the map.
Adam Lesinski7ad11102016-10-28 16:39:15 -07001024 const size_t entry_count = map_entry_end - map_entry;
1025 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
1026 malloc(sizeof(ResolvedBag) + (entry_count * sizeof(ResolvedBag::Entry))))};
Ryan Mitchell155d5392020-02-10 13:35:24 -08001027
1028 bool sort_entries = false;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001029 for (auto new_entry = new_bag->entries; map_entry != map_entry_end; ++map_entry) {
1030 if (UNLIKELY(!map_entry)) {
1031 return base::unexpected(IOError::PAGES_MISSING);
1032 }
1033
Adam Lesinskida431a22016-12-29 16:08:16 -05001034 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001035 if (!is_internal_resid(new_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -05001036 // Attributes, arrays, etc don't have a resource id as the name. They specify
1037 // other data, which would be wrong to change via a lookup.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001038 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001039 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
1040 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001041 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001042 }
1043 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001044
1045 new_entry->cookie = entry->cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -05001046 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001047 new_entry->key_pool = nullptr;
1048 new_entry->type_pool = nullptr;
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001049 new_entry->style = resid;
Adam Lesinski30080e22017-10-16 16:18:09 -07001050 new_entry->value.copyFrom_dtoh(map_entry->value);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001051 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1052 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001053 LOG(ERROR) << base::StringPrintf(
1054 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
1055 new_entry->value.data, new_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001056 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001057 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001058
Ryan Mitchell155d5392020-02-10 13:35:24 -08001059 sort_entries = sort_entries ||
1060 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001061 ++new_entry;
1062 }
Ryan Mitchell155d5392020-02-10 13:35:24 -08001063
1064 if (sort_entries) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001065 std::sort(new_bag->entries, new_bag->entries + entry_count,
1066 [](auto&& lhs, auto&& rhs) { return lhs.key < rhs.key; });
Ryan Mitchell155d5392020-02-10 13:35:24 -08001067 }
1068
Ryan Mitchell80094e32020-11-16 23:08:18 +00001069 new_bag->type_spec_flags = entry->type_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001070 new_bag->entry_count = static_cast<uint32_t>(entry_count);
1071 ResolvedBag* result = new_bag.get();
1072 cached_bags_[resid] = std::move(new_bag);
1073 return result;
1074 }
1075
Adam Lesinskida431a22016-12-29 16:08:16 -05001076 // In case the parent is a dynamic reference, resolve it.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001077 entry->dynamic_ref_table->lookupResourceId(&parent_resid);
Adam Lesinskida431a22016-12-29 16:08:16 -05001078
Adam Lesinski7ad11102016-10-28 16:39:15 -07001079 // Get the parent and do a merge of the keys.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001080 const auto parent_bag = GetBag(parent_resid, child_resids);
1081 if (UNLIKELY(!parent_bag.has_value())) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001082 // Failed to get the parent that should exist.
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001083 LOG(ERROR) << base::StringPrintf("Failed to find parent 0x%08x of bag 0x%08x.", parent_resid,
1084 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001085 return base::unexpected(parent_bag.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001086 }
1087
Adam Lesinski7ad11102016-10-28 16:39:15 -07001088 // Create the max possible entries we can make. Once we construct the bag,
1089 // we will realloc to fit to size.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001090 const size_t max_count = (*parent_bag)->entry_count + dtohl(map->count);
George Burgess IV09b119f2017-07-25 15:00:04 -07001091 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
1092 malloc(sizeof(ResolvedBag) + (max_count * sizeof(ResolvedBag::Entry))))};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001093 ResolvedBag::Entry* new_entry = new_bag->entries;
1094
Ryan Mitchell80094e32020-11-16 23:08:18 +00001095 const ResolvedBag::Entry* parent_entry = (*parent_bag)->entries;
1096 const ResolvedBag::Entry* const parent_entry_end = parent_entry + (*parent_bag)->entry_count;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001097
1098 // The keys are expected to be in sorted order. Merge the two bags.
Ryan Mitchell155d5392020-02-10 13:35:24 -08001099 bool sort_entries = false;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001100 while (map_entry != map_entry_end && parent_entry != parent_entry_end) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001101 if (UNLIKELY(!map_entry)) {
1102 return base::unexpected(IOError::PAGES_MISSING);
1103 }
1104
Adam Lesinskida431a22016-12-29 16:08:16 -05001105 uint32_t child_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001106 if (!is_internal_resid(child_key)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001107 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&child_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001108 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", child_key,
1109 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001110 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001111 }
1112 }
1113
Adam Lesinski7ad11102016-10-28 16:39:15 -07001114 if (child_key <= parent_entry->key) {
1115 // Use the child key if it comes before the parent
1116 // or is equal to the parent (overrides).
Ryan Mitchell80094e32020-11-16 23:08:18 +00001117 new_entry->cookie = entry->cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001118 new_entry->key = child_key;
1119 new_entry->key_pool = nullptr;
1120 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -07001121 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001122 new_entry->style = resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001123 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1124 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001125 LOG(ERROR) << base::StringPrintf(
1126 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
1127 new_entry->value.data, child_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001128 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001129 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001130 ++map_entry;
1131 } else {
1132 // Take the parent entry as-is.
1133 memcpy(new_entry, parent_entry, sizeof(*new_entry));
1134 }
1135
Ryan Mitchell155d5392020-02-10 13:35:24 -08001136 sort_entries = sort_entries ||
1137 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001138 if (child_key >= parent_entry->key) {
1139 // Move to the next parent entry if we used it or it was overridden.
1140 ++parent_entry;
1141 }
1142 // Increment to the next entry to fill.
1143 ++new_entry;
1144 }
1145
1146 // Finish the child entries if they exist.
1147 while (map_entry != map_entry_end) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001148 if (UNLIKELY(!map_entry)) {
1149 return base::unexpected(IOError::PAGES_MISSING);
1150 }
1151
Adam Lesinskida431a22016-12-29 16:08:16 -05001152 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001153 if (!is_internal_resid(new_key)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001154 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001155 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
1156 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001157 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001158 }
1159 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001160 new_entry->cookie = entry->cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -05001161 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001162 new_entry->key_pool = nullptr;
1163 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -07001164 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001165 new_entry->style = resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001166 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1167 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001168 LOG(ERROR) << base::StringPrintf("Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.",
1169 new_entry->value.dataType, new_entry->value.data, new_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001170 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001171 }
Ryan Mitchell155d5392020-02-10 13:35:24 -08001172 sort_entries = sort_entries ||
1173 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001174 ++map_entry;
1175 ++new_entry;
1176 }
1177
1178 // Finish the parent entries if they exist.
1179 if (parent_entry != parent_entry_end) {
1180 // Take the rest of the parent entries as-is.
1181 const size_t num_entries_to_copy = parent_entry_end - parent_entry;
1182 memcpy(new_entry, parent_entry, num_entries_to_copy * sizeof(*new_entry));
1183 new_entry += num_entries_to_copy;
1184 }
1185
1186 // Resize the resulting array to fit.
1187 const size_t actual_count = new_entry - new_bag->entries;
1188 if (actual_count != max_count) {
George Burgess IV09b119f2017-07-25 15:00:04 -07001189 new_bag.reset(reinterpret_cast<ResolvedBag*>(realloc(
1190 new_bag.release(), sizeof(ResolvedBag) + (actual_count * sizeof(ResolvedBag::Entry)))));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001191 }
1192
Ryan Mitchell155d5392020-02-10 13:35:24 -08001193 if (sort_entries) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001194 std::sort(new_bag->entries, new_bag->entries + actual_count,
1195 [](auto&& lhs, auto&& rhs) { return lhs.key < rhs.key; });
Ryan Mitchell155d5392020-02-10 13:35:24 -08001196 }
1197
Adam Lesinski1a1e9c22017-10-13 15:45:34 -07001198 // Combine flags from the parent and our own bag.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001199 new_bag->type_spec_flags = entry->type_flags | (*parent_bag)->type_spec_flags;
George Burgess IV09b119f2017-07-25 15:00:04 -07001200 new_bag->entry_count = static_cast<uint32_t>(actual_count);
1201 ResolvedBag* result = new_bag.get();
1202 cached_bags_[resid] = std::move(new_bag);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001203 return result;
1204}
1205
Adam Lesinski929d6512017-01-16 19:11:19 -08001206static bool Utf8ToUtf16(const StringPiece& str, std::u16string* out) {
1207 ssize_t len =
1208 utf8_to_utf16_length(reinterpret_cast<const uint8_t*>(str.data()), str.size(), false);
1209 if (len < 0) {
1210 return false;
1211 }
1212 out->resize(static_cast<size_t>(len));
1213 utf8_to_utf16(reinterpret_cast<const uint8_t*>(str.data()), str.size(), &*out->begin(),
1214 static_cast<size_t>(len + 1));
1215 return true;
1216}
1217
Ryan Mitchell80094e32020-11-16 23:08:18 +00001218base::expected<uint32_t, NullOrIOError> AssetManager2::GetResourceId(
1219 const std::string& resource_name, const std::string& fallback_type,
1220 const std::string& fallback_package) const {
Adam Lesinski929d6512017-01-16 19:11:19 -08001221 StringPiece package_name, type, entry;
1222 if (!ExtractResourceName(resource_name, &package_name, &type, &entry)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001223 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001224 }
1225
1226 if (entry.empty()) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001227 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001228 }
1229
1230 if (package_name.empty()) {
1231 package_name = fallback_package;
1232 }
1233
1234 if (type.empty()) {
1235 type = fallback_type;
1236 }
1237
1238 std::u16string type16;
1239 if (!Utf8ToUtf16(type, &type16)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001240 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001241 }
1242
1243 std::u16string entry16;
1244 if (!Utf8ToUtf16(entry, &entry16)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001245 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001246 }
1247
1248 const StringPiece16 kAttr16 = u"attr";
1249 const static std::u16string kAttrPrivate16 = u"^attr-private";
1250
1251 for (const PackageGroup& package_group : package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001252 for (const ConfiguredPackage& package_impl : package_group.packages_) {
1253 const LoadedPackage* package = package_impl.loaded_package_;
Adam Lesinski929d6512017-01-16 19:11:19 -08001254 if (package_name != package->GetPackageName()) {
1255 // All packages in the same group are expected to have the same package name.
1256 break;
1257 }
1258
Ryan Mitchell80094e32020-11-16 23:08:18 +00001259 base::expected<uint32_t, NullOrIOError> resid = package->FindEntryByName(type16, entry16);
1260 if (UNLIKELY(IsIOError(resid))) {
1261 return base::unexpected(resid.error());
1262 }
1263
1264 if (!resid.has_value() && kAttr16 == type16) {
Adam Lesinski929d6512017-01-16 19:11:19 -08001265 // Private attributes in libraries (such as the framework) are sometimes encoded
1266 // under the type '^attr-private' in order to leave the ID space of public 'attr'
1267 // free for future additions. Check '^attr-private' for the same name.
1268 resid = package->FindEntryByName(kAttrPrivate16, entry16);
1269 }
1270
Ryan Mitchell80094e32020-11-16 23:08:18 +00001271 if (resid.has_value()) {
1272 return fix_package_id(*resid, package_group.dynamic_ref_table->mAssignedPackageId);
Adam Lesinski929d6512017-01-16 19:11:19 -08001273 }
1274 }
1275 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001276 return base::unexpected(std::nullopt);
Adam Lesinski0c405242017-01-13 20:47:26 -08001277}
1278
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001279void AssetManager2::RebuildFilterList() {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001280 for (PackageGroup& group : package_groups_) {
1281 for (ConfiguredPackage& impl : group.packages_) {
1282 // Destroy it.
1283 impl.filtered_configs_.~ByteBucketArray();
1284
1285 // Re-create it.
1286 new (&impl.filtered_configs_) ByteBucketArray<FilteredConfigGroup>();
1287
1288 // Create the filters here.
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001289 impl.loaded_package_->ForEachTypeSpec([&](const TypeSpec& type_spec, uint8_t type_id) {
1290 FilteredConfigGroup& group = impl.filtered_configs_.editItemAt(type_id - 1);
1291 for (const auto& type_entry : type_spec.type_entries) {
1292 if (type_entry.config.match(configuration_)) {
1293 group.type_entries.push_back(&type_entry);
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001294 }
1295 }
1296 });
1297 }
1298 }
1299}
1300
Adam Lesinski7ad11102016-10-28 16:39:15 -07001301void AssetManager2::InvalidateCaches(uint32_t diff) {
Ryan Mitchell2c4d8742019-03-04 09:41:00 -08001302 cached_bag_resid_stacks_.clear();
1303
Adam Lesinski7ad11102016-10-28 16:39:15 -07001304 if (diff == 0xffffffffu) {
1305 // Everything must go.
1306 cached_bags_.clear();
1307 return;
1308 }
1309
1310 // Be more conservative with what gets purged. Only if the bag has other possible
1311 // variations with respect to what changed (diff) should we remove it.
1312 for (auto iter = cached_bags_.cbegin(); iter != cached_bags_.cend();) {
1313 if (diff & iter->second->type_spec_flags) {
1314 iter = cached_bags_.erase(iter);
1315 } else {
1316 ++iter;
1317 }
1318 }
Ryan Mitchella45506e2020-11-16 23:08:18 +00001319
1320 cached_resolved_values_.clear();
Adam Lesinski7ad11102016-10-28 16:39:15 -07001321}
1322
Ryan Mitchell2e394222019-08-28 12:10:51 -07001323uint8_t AssetManager2::GetAssignedPackageId(const LoadedPackage* package) const {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001324 for (auto& package_group : package_groups_) {
1325 for (auto& package2 : package_group.packages_) {
1326 if (package2.loaded_package_ == package) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -07001327 return package_group.dynamic_ref_table->mAssignedPackageId;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001328 }
1329 }
1330 }
1331 return 0;
1332}
1333
Adam Lesinski30080e22017-10-16 16:18:09 -07001334std::unique_ptr<Theme> AssetManager2::NewTheme() {
1335 return std::unique_ptr<Theme>(new Theme(this));
1336}
1337
1338Theme::Theme(AssetManager2* asset_manager) : asset_manager_(asset_manager) {
1339}
1340
1341Theme::~Theme() = default;
1342
1343namespace {
1344
1345struct ThemeEntry {
1346 ApkAssetsCookie cookie;
1347 uint32_t type_spec_flags;
1348 Res_value value;
1349};
1350
1351struct ThemeType {
1352 int entry_count;
1353 ThemeEntry entries[0];
1354};
1355
1356constexpr size_t kTypeCount = std::numeric_limits<uint8_t>::max() + 1;
1357
1358} // namespace
1359
1360struct Theme::Package {
1361 // Each element of Type will be a dynamically sized object
1362 // allocated to have the entries stored contiguously with the Type.
1363 std::array<util::unique_cptr<ThemeType>, kTypeCount> types;
1364};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001365
Ryan Mitchell80094e32020-11-16 23:08:18 +00001366base::expected<std::monostate, NullOrIOError> Theme::ApplyStyle(uint32_t resid, bool force) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001367 ATRACE_NAME("Theme::ApplyStyle");
Adam Lesinski7ad11102016-10-28 16:39:15 -07001368
Ryan Mitchell80094e32020-11-16 23:08:18 +00001369 auto bag = asset_manager_->GetBag(resid);
1370 if (!bag.has_value()) {
1371 return base::unexpected(bag.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001372 }
1373
1374 // Merge the flags from this style.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001375 type_spec_flags_ |= (*bag)->type_spec_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001376
Adam Lesinski30080e22017-10-16 16:18:09 -07001377 int last_type_idx = -1;
1378 int last_package_idx = -1;
1379 Package* last_package = nullptr;
1380 ThemeType* last_type = nullptr;
1381
1382 // Iterate backwards, because each bag is sorted in ascending key ID order, meaning we will only
1383 // need to perform one resize per type.
1384 using reverse_bag_iterator = std::reverse_iterator<const ResolvedBag::Entry*>;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001385 const auto rbegin = reverse_bag_iterator(begin(*bag));
1386 for (auto it = reverse_bag_iterator(end(*bag)); it != rbegin; ++it) {
1387 const uint32_t attr_resid = it->key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001388
Adam Lesinski30080e22017-10-16 16:18:09 -07001389 // If the resource ID passed in is not a style, the key can be some other identifier that is not
1390 // a resource ID. We should fail fast instead of operating with strange resource IDs.
Adam Lesinski929d6512017-01-16 19:11:19 -08001391 if (!is_valid_resid(attr_resid)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001392 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001393 }
1394
Adam Lesinski30080e22017-10-16 16:18:09 -07001395 // We don't use the 0-based index for the type so that we can avoid doing ID validation
1396 // upon lookup. Instead, we keep space for the type ID 0 in our data structures. Since
1397 // the construction of this type is guarded with a resource ID check, it will never be
1398 // populated, and querying type ID 0 will always fail.
1399 const int package_idx = get_package_id(attr_resid);
1400 const int type_idx = get_type_id(attr_resid);
1401 const int entry_idx = get_entry_id(attr_resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001402
Adam Lesinski30080e22017-10-16 16:18:09 -07001403 if (last_package_idx != package_idx) {
1404 std::unique_ptr<Package>& package = packages_[package_idx];
1405 if (package == nullptr) {
1406 package.reset(new Package());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001407 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001408 last_package_idx = package_idx;
1409 last_package = package.get();
1410 last_type_idx = -1;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001411 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001412
1413 if (last_type_idx != type_idx) {
1414 util::unique_cptr<ThemeType>& type = last_package->types[type_idx];
1415 if (type == nullptr) {
1416 // Allocate enough memory to contain this entry_idx. Since we're iterating in reverse over
1417 // a sorted list of attributes, this shouldn't be resized again during this method call.
1418 type.reset(reinterpret_cast<ThemeType*>(
1419 calloc(sizeof(ThemeType) + (entry_idx + 1) * sizeof(ThemeEntry), 1)));
1420 type->entry_count = entry_idx + 1;
1421 } else if (entry_idx >= type->entry_count) {
1422 // Reallocate the memory to contain this entry_idx. Since we're iterating in reverse over
1423 // a sorted list of attributes, this shouldn't be resized again during this method call.
1424 const int new_count = entry_idx + 1;
1425 type.reset(reinterpret_cast<ThemeType*>(
1426 realloc(type.release(), sizeof(ThemeType) + (new_count * sizeof(ThemeEntry)))));
1427
1428 // Clear out the newly allocated space (which isn't zeroed).
1429 memset(type->entries + type->entry_count, 0,
1430 (new_count - type->entry_count) * sizeof(ThemeEntry));
1431 type->entry_count = new_count;
1432 }
1433 last_type_idx = type_idx;
1434 last_type = type.get();
1435 }
1436
1437 ThemeEntry& entry = last_type->entries[entry_idx];
1438 if (force || (entry.value.dataType == Res_value::TYPE_NULL &&
1439 entry.value.data != Res_value::DATA_NULL_EMPTY)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001440 entry.cookie = it->cookie;
1441 entry.type_spec_flags |= (*bag)->type_spec_flags;
1442 entry.value = it->value;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001443 }
1444 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001445 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001446}
1447
Ryan Mitchell80094e32020-11-16 23:08:18 +00001448std::optional<AssetManager2::SelectedValue> Theme::GetAttribute(uint32_t resid) const {
1449
Adam Lesinski30080e22017-10-16 16:18:09 -07001450 int cnt = 20;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001451 uint32_t type_spec_flags = 0u;
Adam Lesinski30080e22017-10-16 16:18:09 -07001452 do {
1453 const int package_idx = get_package_id(resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001454 const Package* package = packages_[package_idx].get();
Adam Lesinski30080e22017-10-16 16:18:09 -07001455 if (package != nullptr) {
1456 // The themes are constructed with a 1-based type ID, so no need to decrement here.
1457 const int type_idx = get_type_id(resid);
1458 const ThemeType* type = package->types[type_idx].get();
1459 if (type != nullptr) {
1460 const int entry_idx = get_entry_id(resid);
1461 if (entry_idx < type->entry_count) {
1462 const ThemeEntry& entry = type->entries[entry_idx];
1463 type_spec_flags |= entry.type_spec_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001464
Adam Lesinski30080e22017-10-16 16:18:09 -07001465 if (entry.value.dataType == Res_value::TYPE_ATTRIBUTE) {
1466 if (cnt > 0) {
1467 cnt--;
1468 resid = entry.value.data;
1469 continue;
1470 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001471 return std::nullopt;
Adam Lesinski30080e22017-10-16 16:18:09 -07001472 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001473
Adam Lesinski30080e22017-10-16 16:18:09 -07001474 // @null is different than @empty.
1475 if (entry.value.dataType == Res_value::TYPE_NULL &&
1476 entry.value.data != Res_value::DATA_NULL_EMPTY) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001477 return std::nullopt;
Adam Lesinski30080e22017-10-16 16:18:09 -07001478 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001479
Ryan Mitchell80094e32020-11-16 23:08:18 +00001480 return AssetManager2::SelectedValue(entry.value.dataType, entry.value.data, entry.cookie,
1481 type_spec_flags, 0U /* resid */, {} /* config */);
Adam Lesinskida431a22016-12-29 16:08:16 -05001482 }
Adam Lesinskida431a22016-12-29 16:08:16 -05001483 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001484 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001485 break;
1486 } while (true);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001487 return std::nullopt;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001488}
1489
Ryan Mitchell80094e32020-11-16 23:08:18 +00001490base::expected<std::monostate, NullOrIOError> Theme::ResolveAttributeReference(
1491 AssetManager2::SelectedValue& value) const {
1492 if (value.type != Res_value::TYPE_ATTRIBUTE) {
1493 return asset_manager_->ResolveReference(value);
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001494 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001495
1496 std::optional<AssetManager2::SelectedValue> result = GetAttribute(value.data);
1497 if (!result.has_value()) {
1498 return base::unexpected(std::nullopt);
1499 }
1500
Ryan Mitchella45506e2020-11-16 23:08:18 +00001501 auto resolve_result = asset_manager_->ResolveReference(*result, true /* cache_value */);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001502 if (resolve_result.has_value()) {
1503 result->flags |= value.flags;
1504 value = *result;
1505 }
1506 return resolve_result;
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001507}
1508
Adam Lesinski7ad11102016-10-28 16:39:15 -07001509void Theme::Clear() {
1510 type_spec_flags_ = 0u;
1511 for (std::unique_ptr<Package>& package : packages_) {
1512 package.reset();
1513 }
1514}
1515
Ryan Mitchell80094e32020-11-16 23:08:18 +00001516base::expected<std::monostate, IOError> Theme::SetTo(const Theme& o) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001517 if (this == &o) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001518 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001519 }
1520
Adam Lesinski7ad11102016-10-28 16:39:15 -07001521 type_spec_flags_ = o.type_spec_flags_;
1522
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001523 if (asset_manager_ == o.asset_manager_) {
1524 // The theme comes from the same asset manager so all theme data can be copied exactly
1525 for (size_t p = 0; p < packages_.size(); p++) {
1526 const Package *package = o.packages_[p].get();
1527 if (package == nullptr) {
1528 // The other theme doesn't have this package, clear ours.
1529 packages_[p].reset();
Adam Lesinski7ad11102016-10-28 16:39:15 -07001530 continue;
1531 }
1532
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001533 if (packages_[p] == nullptr) {
1534 // The other theme has this package, but we don't. Make one.
1535 packages_[p].reset(new Package());
1536 }
1537
1538 for (size_t t = 0; t < package->types.size(); t++) {
1539 const ThemeType *type = package->types[t].get();
1540 if (type == nullptr) {
1541 // The other theme doesn't have this type, clear ours.
1542 packages_[p]->types[t].reset();
1543 continue;
1544 }
1545
1546 // Create a new type and update it to theirs.
1547 const size_t type_alloc_size = sizeof(ThemeType) + (type->entry_count * sizeof(ThemeEntry));
1548 void *copied_data = malloc(type_alloc_size);
1549 memcpy(copied_data, type, type_alloc_size);
1550 packages_[p]->types[t].reset(reinterpret_cast<ThemeType *>(copied_data));
1551 }
1552 }
1553 } else {
1554 std::map<ApkAssetsCookie, ApkAssetsCookie> src_to_dest_asset_cookies;
1555 typedef std::map<int, int> SourceToDestinationRuntimePackageMap;
1556 std::map<ApkAssetsCookie, SourceToDestinationRuntimePackageMap> src_asset_cookie_id_map;
1557
Ryan Mitchell93bca972019-03-08 17:26:28 -08001558 // Determine which ApkAssets are loaded in both theme AssetManagers.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001559 std::vector<const ApkAssets*> src_assets = o.asset_manager_->GetApkAssets();
1560 for (size_t i = 0; i < src_assets.size(); i++) {
1561 const ApkAssets* src_asset = src_assets[i];
1562
1563 std::vector<const ApkAssets*> dest_assets = asset_manager_->GetApkAssets();
1564 for (size_t j = 0; j < dest_assets.size(); j++) {
1565 const ApkAssets* dest_asset = dest_assets[j];
1566
Ryan Mitchell93bca972019-03-08 17:26:28 -08001567 // Map the runtime package of the source apk asset to the destination apk asset.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001568 if (src_asset->GetPath() == dest_asset->GetPath()) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001569 const auto& src_packages = src_asset->GetLoadedArsc()->GetPackages();
1570 const auto& dest_packages = dest_asset->GetLoadedArsc()->GetPackages();
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001571
1572 SourceToDestinationRuntimePackageMap package_map;
1573
1574 // The source and destination package should have the same number of packages loaded in
1575 // the same order.
1576 const size_t N = src_packages.size();
1577 CHECK(N == dest_packages.size())
1578 << " LoadedArsc " << src_asset->GetPath() << " differs number of packages.";
1579 for (size_t p = 0; p < N; p++) {
1580 auto& src_package = src_packages[p];
1581 auto& dest_package = dest_packages[p];
1582 CHECK(src_package->GetPackageName() == dest_package->GetPackageName())
1583 << " Package " << src_package->GetPackageName() << " differs in load order.";
1584
1585 int src_package_id = o.asset_manager_->GetAssignedPackageId(src_package.get());
1586 int dest_package_id = asset_manager_->GetAssignedPackageId(dest_package.get());
1587 package_map[src_package_id] = dest_package_id;
1588 }
1589
Ryan Mitchell93bca972019-03-08 17:26:28 -08001590 src_to_dest_asset_cookies.insert(std::make_pair(i, j));
1591 src_asset_cookie_id_map.insert(std::make_pair(i, package_map));
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001592 break;
1593 }
1594 }
1595 }
1596
Ryan Mitchell93bca972019-03-08 17:26:28 -08001597 // Reset the data in the destination theme.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001598 for (size_t p = 0; p < packages_.size(); p++) {
1599 if (packages_[p] != nullptr) {
1600 packages_[p].reset();
1601 }
1602 }
1603
1604 for (size_t p = 0; p < packages_.size(); p++) {
1605 const Package *package = o.packages_[p].get();
1606 if (package == nullptr) {
1607 continue;
1608 }
1609
1610 for (size_t t = 0; t < package->types.size(); t++) {
1611 const ThemeType *type = package->types[t].get();
1612 if (type == nullptr) {
1613 continue;
1614 }
1615
1616 for (size_t e = 0; e < type->entry_count; e++) {
1617 const ThemeEntry &entry = type->entries[e];
1618 if (entry.value.dataType == Res_value::TYPE_NULL &&
1619 entry.value.data != Res_value::DATA_NULL_EMPTY) {
1620 continue;
1621 }
1622
Ryan Mitchell93bca972019-03-08 17:26:28 -08001623 bool is_reference = (entry.value.dataType == Res_value::TYPE_ATTRIBUTE
1624 || entry.value.dataType == Res_value::TYPE_REFERENCE
1625 || entry.value.dataType == Res_value::TYPE_DYNAMIC_ATTRIBUTE
1626 || entry.value.dataType == Res_value::TYPE_DYNAMIC_REFERENCE)
1627 && entry.value.data != 0x0;
Ryan Mitchellb85d9b22018-11-19 12:11:38 -08001628
Ryan Mitchell93bca972019-03-08 17:26:28 -08001629 // If the attribute value represents an attribute or reference, the package id of the
1630 // value needs to be rewritten to the package id of the value in the destination.
1631 uint32_t attribute_data = entry.value.data;
1632 if (is_reference) {
1633 // Determine the package id of the reference in the destination AssetManager.
Ryan Mitchellb85d9b22018-11-19 12:11:38 -08001634 auto value_package_map = src_asset_cookie_id_map.find(entry.cookie);
1635 if (value_package_map == src_asset_cookie_id_map.end()) {
1636 continue;
1637 }
1638
1639 auto value_dest_package = value_package_map->second.find(
1640 get_package_id(entry.value.data));
1641 if (value_dest_package == value_package_map->second.end()) {
1642 continue;
1643 }
1644
Ryan Mitchell93bca972019-03-08 17:26:28 -08001645 attribute_data = fix_package_id(entry.value.data, value_dest_package->second);
1646 }
1647
1648 // Find the cookie of the value in the destination. If the source apk is not loaded in the
1649 // destination, only copy resources that do not reference resources in the source.
1650 ApkAssetsCookie data_dest_cookie;
1651 auto value_dest_cookie = src_to_dest_asset_cookies.find(entry.cookie);
1652 if (value_dest_cookie != src_to_dest_asset_cookies.end()) {
1653 data_dest_cookie = value_dest_cookie->second;
1654 } else {
1655 if (is_reference || entry.value.dataType == Res_value::TYPE_STRING) {
1656 continue;
1657 } else {
1658 data_dest_cookie = 0x0;
1659 }
Ryan Mitchellb85d9b22018-11-19 12:11:38 -08001660 }
1661
1662 // The package id of the attribute needs to be rewritten to the package id of the
Ryan Mitchell93bca972019-03-08 17:26:28 -08001663 // attribute in the destination.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001664 int attribute_dest_package_id = p;
1665 if (attribute_dest_package_id != 0x01) {
Ryan Mitchell93bca972019-03-08 17:26:28 -08001666 // Find the cookie of the attribute resource id in the source AssetManager
Ryan Mitchell80094e32020-11-16 23:08:18 +00001667 base::expected<FindEntryResult, NullOrIOError> attribute_entry_result =
Ryan Mitchella55dc2e2019-01-24 10:58:23 -08001668 o.asset_manager_->FindEntry(make_resid(p, t, e), 0 /* density_override */ ,
1669 true /* stop_at_first_match */,
Ryan Mitchell80094e32020-11-16 23:08:18 +00001670 true /* ignore_configuration */);
1671 if (UNLIKELY(IsIOError(attribute_entry_result))) {
1672 return base::unexpected(GetIOError(attribute_entry_result.error()));
1673 }
1674 if (!attribute_entry_result.has_value()) {
1675 continue;
1676 }
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001677
Ryan Mitchell93bca972019-03-08 17:26:28 -08001678 // Determine the package id of the attribute in the destination AssetManager.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001679 auto attribute_package_map = src_asset_cookie_id_map.find(
1680 attribute_entry_result->cookie);
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001681 if (attribute_package_map == src_asset_cookie_id_map.end()) {
1682 continue;
1683 }
1684 auto attribute_dest_package = attribute_package_map->second.find(
1685 attribute_dest_package_id);
1686 if (attribute_dest_package == attribute_package_map->second.end()) {
1687 continue;
1688 }
1689 attribute_dest_package_id = attribute_dest_package->second;
1690 }
1691
Ryan Mitchell93bca972019-03-08 17:26:28 -08001692 // Lazily instantiate the destination package.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001693 std::unique_ptr<Package>& dest_package = packages_[attribute_dest_package_id];
1694 if (dest_package == nullptr) {
1695 dest_package.reset(new Package());
1696 }
1697
Ryan Mitchell93bca972019-03-08 17:26:28 -08001698 // Lazily instantiate and resize the destination type.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001699 util::unique_cptr<ThemeType>& dest_type = dest_package->types[t];
1700 if (dest_type == nullptr || dest_type->entry_count < type->entry_count) {
1701 const size_t type_alloc_size = sizeof(ThemeType)
1702 + (type->entry_count * sizeof(ThemeEntry));
1703 void* dest_data = malloc(type_alloc_size);
1704 memset(dest_data, 0, type->entry_count * sizeof(ThemeEntry));
1705
Ryan Mitchell93bca972019-03-08 17:26:28 -08001706 // Copy the existing destination type values if the type is resized.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001707 if (dest_type != nullptr) {
1708 memcpy(dest_data, type, sizeof(ThemeType)
1709 + (dest_type->entry_count * sizeof(ThemeEntry)));
1710 }
1711
1712 dest_type.reset(reinterpret_cast<ThemeType *>(dest_data));
1713 dest_type->entry_count = type->entry_count;
1714 }
1715
Ryan Mitchell93bca972019-03-08 17:26:28 -08001716 dest_type->entries[e].cookie = data_dest_cookie;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001717 dest_type->entries[e].value.dataType = entry.value.dataType;
Ryan Mitchell93bca972019-03-08 17:26:28 -08001718 dest_type->entries[e].value.data = attribute_data;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001719 dest_type->entries[e].type_spec_flags = entry.type_spec_flags;
1720 }
1721 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001722 }
1723 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001724 return {};
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001725}
1726
1727void Theme::Dump() const {
1728 base::ScopedLogSeverity _log(base::INFO);
1729 LOG(INFO) << base::StringPrintf("Theme(this=%p, AssetManager2=%p)", this, asset_manager_);
1730
1731 for (int p = 0; p < packages_.size(); p++) {
1732 auto& package = packages_[p];
1733 if (package == nullptr) {
1734 continue;
1735 }
1736
1737 for (int t = 0; t < package->types.size(); t++) {
1738 auto& type = package->types[t];
1739 if (type == nullptr) {
1740 continue;
1741 }
1742
1743 for (int e = 0; e < type->entry_count; e++) {
1744 auto& entry = type->entries[e];
1745 if (entry.value.dataType == Res_value::TYPE_NULL &&
1746 entry.value.data != Res_value::DATA_NULL_EMPTY) {
1747 continue;
1748 }
1749
1750 LOG(INFO) << base::StringPrintf(" entry(0x%08x)=(0x%08x) type=(0x%02x), cookie(%d)",
1751 make_resid(p, t, e), entry.value.data,
1752 entry.value.dataType, entry.cookie);
1753 }
1754 }
1755 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001756}
1757
1758} // namespace android