blob: c49dc28124b2d952dcccf820fcea9e992cea1fbf [file] [log] [blame]
Adam Lesinski7ad11102016-10-28 16:39:15 -07001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define ATRACE_TAG ATRACE_TAG_RESOURCES
18
19#include "androidfw/AssetManager2.h"
20
y57cd1952018-04-12 14:26:23 -070021#include <algorithm>
Adam Lesinski30080e22017-10-16 16:18:09 -070022#include <iterator>
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -070023#include <map>
Winson2f3669b2019-01-11 11:28:34 -080024#include <set>
Adam Lesinski0c405242017-01-13 20:47:26 -080025
Adam Lesinski7ad11102016-10-28 16:39:15 -070026#include "android-base/logging.h"
27#include "android-base/stringprintf.h"
Ryan Mitchell8a891d82019-07-01 09:48:23 -070028#include "androidfw/ResourceUtils.h"
Ryan Mitchell31b11052019-06-13 13:47:26 -070029#include "androidfw/Util.h"
Adam Lesinski7ad11102016-10-28 16:39:15 -070030#include "utils/ByteOrder.h"
31#include "utils/Trace.h"
32
33#ifdef _WIN32
34#ifdef ERROR
35#undef ERROR
36#endif
37#endif
38
39namespace android {
40
Ryan Mitchellc75c2e02020-08-17 08:42:48 -070041namespace {
42
43using EntryValue = std::variant<Res_value, incfs::verified_map_ptr<ResTable_map_entry>>;
44
45base::expected<EntryValue, IOError> GetEntryValue(
46 incfs::verified_map_ptr<ResTable_entry> table_entry) {
47 const uint16_t entry_size = dtohs(table_entry->size);
48
49 // Check if the entry represents a bag value.
50 if (entry_size >= sizeof(ResTable_map_entry) &&
51 (dtohs(table_entry->flags) & ResTable_entry::FLAG_COMPLEX)) {
52 const auto map_entry = table_entry.convert<ResTable_map_entry>();
53 if (!map_entry) {
54 return base::unexpected(IOError::PAGES_MISSING);
55 }
56 return map_entry.verified();
57 }
58
59 // The entry represents a non-bag value.
60 const auto entry_value = table_entry.offset(entry_size).convert<Res_value>();
61 if (!entry_value) {
62 return base::unexpected(IOError::PAGES_MISSING);
63 }
64 Res_value value;
65 value.copyFrom_dtoh(entry_value.value());
66 return value;
67}
68
69} // namespace
70
Adam Lesinskibebfcc42018-02-12 14:27:46 -080071struct FindEntryResult {
Ryan Mitchellc75c2e02020-08-17 08:42:48 -070072 // The cookie representing the ApkAssets in which the value resides.
73 ApkAssetsCookie cookie;
74
75 // The value of the resource table entry. Either an android::Res_value for non-bag types or an
76 // incfs::verified_map_ptr<ResTable_map_entry> for bag types.
77 EntryValue entry;
Adam Lesinskibebfcc42018-02-12 14:27:46 -080078
79 // The configuration for which the resulting entry was defined. This is already swapped to host
80 // endianness.
81 ResTable_config config;
82
83 // The bitmask of configuration axis with which the resource value varies.
84 uint32_t type_flags;
85
86 // The dynamic package ID map for the package from which this resource came from.
87 const DynamicRefTable* dynamic_ref_table;
88
Ryan Mitchell8a891d82019-07-01 09:48:23 -070089 // The package name of the resource.
90 const std::string* package_name;
91
Adam Lesinskibebfcc42018-02-12 14:27:46 -080092 // The string pool reference to the type's name. This uses a different string pool than
93 // the global string pool, but this is hidden from the caller.
94 StringPoolRef type_string_ref;
95
96 // The string pool reference to the entry's name. This uses a different string pool than
97 // the global string pool, but this is hidden from the caller.
98 StringPoolRef entry_string_ref;
99};
100
Ryan Mitchellb894c272020-02-12 10:31:44 -0800101AssetManager2::AssetManager2() {
Adam Lesinski970bd8d2017-09-25 13:21:55 -0700102 memset(&configuration_, 0, sizeof(configuration_));
103}
Adam Lesinski7ad11102016-10-28 16:39:15 -0700104
105bool AssetManager2::SetApkAssets(const std::vector<const ApkAssets*>& apk_assets,
Mårten Kongstad668ec5b2018-06-11 14:11:33 +0200106 bool invalidate_caches, bool filter_incompatible_configs) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700107 apk_assets_ = apk_assets;
Adam Lesinskida431a22016-12-29 16:08:16 -0500108 BuildDynamicRefTable();
Mårten Kongstad668ec5b2018-06-11 14:11:33 +0200109 RebuildFilterList(filter_incompatible_configs);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700110 if (invalidate_caches) {
111 InvalidateCaches(static_cast<uint32_t>(-1));
112 }
113 return true;
114}
115
Adam Lesinskida431a22016-12-29 16:08:16 -0500116void AssetManager2::BuildDynamicRefTable() {
117 package_groups_.clear();
118 package_ids_.fill(0xff);
119
Ryan Mitchellb894c272020-02-12 10:31:44 -0800120 // A mapping from apk assets path to the runtime package id of its first loaded package.
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700121 std::unordered_map<std::string, uint8_t> apk_assets_package_ids;
122
Ryan Mitchell824cc492020-02-12 10:48:14 -0800123 // Overlay resources are not directly referenced by an application so their resource ids
124 // can change throughout the application's lifetime. Assign overlay package ids last.
125 std::vector<const ApkAssets*> sorted_apk_assets(apk_assets_);
126 std::stable_partition(sorted_apk_assets.begin(), sorted_apk_assets.end(), [](const ApkAssets* a) {
127 return !a->IsOverlay();
128 });
129
130 // The assets cookie must map to the position of the apk assets in the unsorted apk assets list.
131 std::unordered_map<const ApkAssets*, ApkAssetsCookie> apk_assets_cookies;
132 apk_assets_cookies.reserve(apk_assets_.size());
133 for (size_t i = 0, n = apk_assets_.size(); i < n; i++) {
134 apk_assets_cookies[apk_assets_[i]] = static_cast<ApkAssetsCookie>(i);
135 }
136
Ryan Mitchellb894c272020-02-12 10:31:44 -0800137 // 0x01 is reserved for the android package.
138 int next_package_id = 0x02;
Ryan Mitchell824cc492020-02-12 10:48:14 -0800139 for (const ApkAssets* apk_assets : sorted_apk_assets) {
Ryan Mitchellb894c272020-02-12 10:31:44 -0800140 const LoadedArsc* loaded_arsc = apk_assets->GetLoadedArsc();
Ryan Mitchellb894c272020-02-12 10:31:44 -0800141 for (const std::unique_ptr<const LoadedPackage>& package : loaded_arsc->GetPackages()) {
142 // Get the package ID or assign one if a shared library.
143 int package_id;
144 if (package->IsDynamic()) {
145 package_id = next_package_id++;
146 } else {
147 package_id = package->GetPackageId();
Adam Lesinskida431a22016-12-29 16:08:16 -0500148 }
149
150 // Add the mapping for package ID to index if not present.
151 uint8_t idx = package_ids_[package_id];
152 if (idx == 0xff) {
153 package_ids_[package_id] = idx = static_cast<uint8_t>(package_groups_.size());
154 package_groups_.push_back({});
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700155
156 if (apk_assets->IsOverlay()) {
157 // The target package must precede the overlay package in the apk assets paths in order
158 // to take effect.
159 const auto& loaded_idmap = apk_assets->GetLoadedIdmap();
160 auto target_package_iter = apk_assets_package_ids.find(loaded_idmap->TargetApkPath());
Ryan Mitchellee4a5642019-10-16 08:32:55 -0700161 if (target_package_iter == apk_assets_package_ids.end()) {
162 LOG(INFO) << "failed to find target package for overlay "
163 << loaded_idmap->OverlayApkPath();
164 } else {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700165 const uint8_t target_package_id = target_package_iter->second;
166 const uint8_t target_idx = package_ids_[target_package_id];
167 CHECK(target_idx != 0xff) << "overlay added to apk_assets_package_ids but does not"
168 << " have an assigned package group";
169
170 PackageGroup& target_package_group = package_groups_[target_idx];
171
Ryan Mitchell824cc492020-02-12 10:48:14 -0800172 // Create a special dynamic reference table for the overlay to rewrite references to
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700173 // overlay resources as references to the target resources they overlay.
174 auto overlay_table = std::make_shared<OverlayDynamicRefTable>(
175 loaded_idmap->GetOverlayDynamicRefTable(target_package_id));
176 package_groups_.back().dynamic_ref_table = overlay_table;
177
178 // Add the overlay resource map to the target package's set of overlays.
179 target_package_group.overlays_.push_back(
180 ConfiguredOverlay{loaded_idmap->GetTargetResourcesMap(target_package_id,
181 overlay_table.get()),
Ryan Mitchell824cc492020-02-12 10:48:14 -0800182 apk_assets_cookies[apk_assets]});
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700183 }
184 }
185
186 DynamicRefTable* ref_table = package_groups_.back().dynamic_ref_table.get();
187 ref_table->mAssignedPackageId = package_id;
188 ref_table->mAppAsLib = package->IsDynamic() && package->GetPackageId() == 0x7f;
Adam Lesinskida431a22016-12-29 16:08:16 -0500189 }
190 PackageGroup* package_group = &package_groups_[idx];
191
192 // Add the package and to the set of packages with the same ID.
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800193 package_group->packages_.push_back(ConfiguredPackage{package.get(), {}});
Ryan Mitchell824cc492020-02-12 10:48:14 -0800194 package_group->cookies_.push_back(apk_assets_cookies[apk_assets]);
Adam Lesinskida431a22016-12-29 16:08:16 -0500195
196 // Add the package name -> build time ID mappings.
197 for (const DynamicPackageEntry& entry : package->GetDynamicPackageMap()) {
198 String16 package_name(entry.package_name.c_str(), entry.package_name.size());
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700199 package_group->dynamic_ref_table->mEntries.replaceValueFor(
Adam Lesinskida431a22016-12-29 16:08:16 -0500200 package_name, static_cast<uint8_t>(entry.package_id));
201 }
Ryan Mitchellb894c272020-02-12 10:31:44 -0800202
203 apk_assets_package_ids.insert(std::make_pair(apk_assets->GetPath(), package_id));
Adam Lesinskida431a22016-12-29 16:08:16 -0500204 }
205 }
206
207 // Now assign the runtime IDs so that we have a build-time to runtime ID map.
208 const auto package_groups_end = package_groups_.end();
209 for (auto iter = package_groups_.begin(); iter != package_groups_end; ++iter) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800210 const std::string& package_name = iter->packages_[0].loaded_package_->GetPackageName();
Adam Lesinskida431a22016-12-29 16:08:16 -0500211 for (auto iter2 = package_groups_.begin(); iter2 != package_groups_end; ++iter2) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700212 iter2->dynamic_ref_table->addMapping(String16(package_name.c_str(), package_name.size()),
213 iter->dynamic_ref_table->mAssignedPackageId);
Adam Lesinskida431a22016-12-29 16:08:16 -0500214 }
215 }
216}
217
218void AssetManager2::DumpToLog() const {
219 base::ScopedLogSeverity _log(base::INFO);
220
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800221 LOG(INFO) << base::StringPrintf("AssetManager2(this=%p)", this);
222
Adam Lesinskida431a22016-12-29 16:08:16 -0500223 std::string list;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800224 for (const auto& apk_assets : apk_assets_) {
225 base::StringAppendF(&list, "%s,", apk_assets->GetPath().c_str());
226 }
227 LOG(INFO) << "ApkAssets: " << list;
228
229 list = "";
Adam Lesinskida431a22016-12-29 16:08:16 -0500230 for (size_t i = 0; i < package_ids_.size(); i++) {
231 if (package_ids_[i] != 0xff) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800232 base::StringAppendF(&list, "%02x -> %d, ", (int)i, package_ids_[i]);
Adam Lesinskida431a22016-12-29 16:08:16 -0500233 }
234 }
235 LOG(INFO) << "Package ID map: " << list;
236
Adam Lesinski0dd36992018-01-25 15:38:38 -0800237 for (const auto& package_group: package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800238 list = "";
239 for (const auto& package : package_group.packages_) {
240 const LoadedPackage* loaded_package = package.loaded_package_;
241 base::StringAppendF(&list, "%s(%02x%s), ", loaded_package->GetPackageName().c_str(),
242 loaded_package->GetPackageId(),
243 (loaded_package->IsDynamic() ? " dynamic" : ""));
244 }
245 LOG(INFO) << base::StringPrintf("PG (%02x): ",
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700246 package_group.dynamic_ref_table->mAssignedPackageId)
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800247 << list;
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800248
249 for (size_t i = 0; i < 256; i++) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700250 if (package_group.dynamic_ref_table->mLookupTable[i] != 0) {
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800251 LOG(INFO) << base::StringPrintf(" e[0x%02x] -> 0x%02x", (uint8_t) i,
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700252 package_group.dynamic_ref_table->mLookupTable[i]);
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800253 }
254 }
Adam Lesinskida431a22016-12-29 16:08:16 -0500255 }
256}
Adam Lesinski7ad11102016-10-28 16:39:15 -0700257
258const ResStringPool* AssetManager2::GetStringPoolForCookie(ApkAssetsCookie cookie) const {
259 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
260 return nullptr;
261 }
262 return apk_assets_[cookie]->GetLoadedArsc()->GetStringPool();
263}
264
Adam Lesinskida431a22016-12-29 16:08:16 -0500265const DynamicRefTable* AssetManager2::GetDynamicRefTableForPackage(uint32_t package_id) const {
266 if (package_id >= package_ids_.size()) {
267 return nullptr;
268 }
269
270 const size_t idx = package_ids_[package_id];
271 if (idx == 0xff) {
272 return nullptr;
273 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700274 return package_groups_[idx].dynamic_ref_table.get();
Adam Lesinskida431a22016-12-29 16:08:16 -0500275}
276
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700277std::shared_ptr<const DynamicRefTable> AssetManager2::GetDynamicRefTableForCookie(
278 ApkAssetsCookie cookie) const {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800279 for (const PackageGroup& package_group : package_groups_) {
280 for (const ApkAssetsCookie& package_cookie : package_group.cookies_) {
281 if (package_cookie == cookie) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700282 return package_group.dynamic_ref_table;
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800283 }
284 }
285 }
286 return nullptr;
287}
288
Mårten Kongstadc92c4dd2019-02-05 01:29:59 +0100289const std::unordered_map<std::string, std::string>*
290 AssetManager2::GetOverlayableMapForPackage(uint32_t package_id) const {
291
292 if (package_id >= package_ids_.size()) {
293 return nullptr;
294 }
295
296 const size_t idx = package_ids_[package_id];
297 if (idx == 0xff) {
298 return nullptr;
299 }
300
301 const PackageGroup& package_group = package_groups_[idx];
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700302 if (package_group.packages_.empty()) {
Mårten Kongstadc92c4dd2019-02-05 01:29:59 +0100303 return nullptr;
304 }
305
306 const auto loaded_package = package_group.packages_[0].loaded_package_;
307 return &loaded_package->GetOverlayableMap();
308}
309
Ryan Mitchell2e394222019-08-28 12:10:51 -0700310bool AssetManager2::GetOverlayablesToString(const android::StringPiece& package_name,
311 std::string* out) const {
312 uint8_t package_id = 0U;
313 for (const auto& apk_assets : apk_assets_) {
314 const LoadedArsc* loaded_arsc = apk_assets->GetLoadedArsc();
315 if (loaded_arsc == nullptr) {
316 continue;
317 }
318
319 const auto& loaded_packages = loaded_arsc->GetPackages();
320 if (loaded_packages.empty()) {
321 continue;
322 }
323
324 const auto& loaded_package = loaded_packages[0];
325 if (loaded_package->GetPackageName() == package_name) {
326 package_id = GetAssignedPackageId(loaded_package.get());
327 break;
328 }
329 }
330
331 if (package_id == 0U) {
332 ANDROID_LOG(ERROR) << base::StringPrintf("No package with name '%s", package_name.data());
333 return false;
334 }
335
336 const size_t idx = package_ids_[package_id];
337 if (idx == 0xff) {
338 return false;
339 }
340
341 std::string output;
342 for (const ConfiguredPackage& package : package_groups_[idx].packages_) {
343 const LoadedPackage* loaded_package = package.loaded_package_;
344 for (auto it = loaded_package->begin(); it != loaded_package->end(); it++) {
345 const OverlayableInfo* info = loaded_package->GetOverlayableInfo(*it);
346 if (info != nullptr) {
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700347 auto res_name = GetResourceName(*it);
348 if (!res_name.has_value()) {
Ryan Mitchell2e394222019-08-28 12:10:51 -0700349 ANDROID_LOG(ERROR) << base::StringPrintf(
350 "Unable to retrieve name of overlayable resource 0x%08x", *it);
351 return false;
352 }
353
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700354 const std::string name = ToFormattedResourceString(*res_name);
Ryan Mitchell2e394222019-08-28 12:10:51 -0700355 output.append(base::StringPrintf(
356 "resource='%s' overlayable='%s' actor='%s' policy='0x%08x'\n",
357 name.c_str(), info->name.c_str(), info->actor.c_str(), info->policy_flags));
358 }
359 }
360 }
361
362 *out = std::move(output);
363 return true;
364}
365
Ryan Mitchell192400c2020-04-02 09:54:23 -0700366bool AssetManager2::ContainsAllocatedTable() const {
367 return std::find_if(apk_assets_.begin(), apk_assets_.end(),
368 std::mem_fn(&ApkAssets::IsTableAllocated)) != apk_assets_.end();
369}
370
Adam Lesinski7ad11102016-10-28 16:39:15 -0700371void AssetManager2::SetConfiguration(const ResTable_config& configuration) {
372 const int diff = configuration_.diff(configuration);
373 configuration_ = configuration;
374
375 if (diff) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800376 RebuildFilterList();
Adam Lesinski7ad11102016-10-28 16:39:15 -0700377 InvalidateCaches(static_cast<uint32_t>(diff));
378 }
379}
380
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700381std::set<std::string> AssetManager2::GetNonSystemOverlayPaths() const {
382 std::set<std::string> non_system_overlays;
Adam Lesinski0c405242017-01-13 20:47:26 -0800383 for (const PackageGroup& package_group : package_groups_) {
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800384 bool found_system_package = false;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800385 for (const ConfiguredPackage& package : package_group.packages_) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700386 if (package.loaded_package_->IsSystem()) {
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800387 found_system_package = true;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700388 break;
389 }
390 }
391
392 if (!found_system_package) {
393 for (const ConfiguredOverlay& overlay : package_group.overlays_) {
394 non_system_overlays.insert(apk_assets_[overlay.cookie]->GetPath());
395 }
396 }
397 }
398
399 return non_system_overlays;
400}
401
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700402base::expected<std::set<ResTable_config>, IOError> AssetManager2::GetResourceConfigurations(
403 bool exclude_system, bool exclude_mipmap) const {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700404 ATRACE_NAME("AssetManager::GetResourceConfigurations");
405 const auto non_system_overlays =
406 (exclude_system) ? GetNonSystemOverlayPaths() : std::set<std::string>();
407
408 std::set<ResTable_config> configurations;
409 for (const PackageGroup& package_group : package_groups_) {
410 for (size_t i = 0; i < package_group.packages_.size(); i++) {
411 const ConfiguredPackage& package = package_group.packages_[i];
412 if (exclude_system && package.loaded_package_->IsSystem()) {
Adam Lesinski0c405242017-01-13 20:47:26 -0800413 continue;
414 }
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800415
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700416 auto apk_assets = apk_assets_[package_group.cookies_[i]];
417 if (exclude_system && apk_assets->IsOverlay()
418 && non_system_overlays.find(apk_assets->GetPath()) == non_system_overlays.end()) {
419 // Exclude overlays that target system resources.
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800420 continue;
421 }
422
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700423 auto result = package.loaded_package_->CollectConfigurations(exclude_mipmap, &configurations);
424 if (UNLIKELY(!result.has_value())) {
425 return base::unexpected(result.error());
426 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800427 }
428 }
429 return configurations;
430}
431
432std::set<std::string> AssetManager2::GetResourceLocales(bool exclude_system,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800433 bool merge_equivalent_languages) const {
434 ATRACE_NAME("AssetManager::GetResourceLocales");
Adam Lesinski0c405242017-01-13 20:47:26 -0800435 std::set<std::string> locales;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700436 const auto non_system_overlays =
437 (exclude_system) ? GetNonSystemOverlayPaths() : std::set<std::string>();
438
Adam Lesinski0c405242017-01-13 20:47:26 -0800439 for (const PackageGroup& package_group : package_groups_) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700440 for (size_t i = 0; i < package_group.packages_.size(); i++) {
441 const ConfiguredPackage& package = package_group.packages_[i];
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800442 if (exclude_system && package.loaded_package_->IsSystem()) {
Adam Lesinski0c405242017-01-13 20:47:26 -0800443 continue;
444 }
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800445
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700446 auto apk_assets = apk_assets_[package_group.cookies_[i]];
447 if (exclude_system && apk_assets->IsOverlay()
448 && non_system_overlays.find(apk_assets->GetPath()) == non_system_overlays.end()) {
449 // Exclude overlays that target system resources.
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800450 continue;
451 }
452
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800453 package.loaded_package_->CollectLocales(merge_equivalent_languages, &locales);
Adam Lesinski0c405242017-01-13 20:47:26 -0800454 }
455 }
456 return locales;
457}
458
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800459std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename,
460 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700461 const std::string new_path = "assets/" + filename;
462 return OpenNonAsset(new_path, mode);
463}
464
465std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename, ApkAssetsCookie cookie,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800466 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700467 const std::string new_path = "assets/" + filename;
468 return OpenNonAsset(new_path, cookie, mode);
469}
470
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800471std::unique_ptr<AssetDir> AssetManager2::OpenDir(const std::string& dirname) const {
472 ATRACE_NAME("AssetManager::OpenDir");
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800473
474 std::string full_path = "assets/" + dirname;
475 std::unique_ptr<SortedVector<AssetDir::FileInfo>> files =
476 util::make_unique<SortedVector<AssetDir::FileInfo>>();
477
478 // Start from the back.
479 for (auto iter = apk_assets_.rbegin(); iter != apk_assets_.rend(); ++iter) {
480 const ApkAssets* apk_assets = *iter;
Mårten Kongstaddbf343b2019-02-21 07:54:18 +0100481 if (apk_assets->IsOverlay()) {
482 continue;
483 }
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800484
485 auto func = [&](const StringPiece& name, FileType type) {
486 AssetDir::FileInfo info;
487 info.setFileName(String8(name.data(), name.size()));
488 info.setFileType(type);
489 info.setSourceName(String8(apk_assets->GetPath().c_str()));
490 files->add(info);
491 };
492
Ryan Mitchellc07aa702020-03-10 13:49:12 -0700493 if (!apk_assets->GetAssetsProvider()->ForEachFile(full_path, func)) {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800494 return {};
495 }
496 }
497
498 std::unique_ptr<AssetDir> asset_dir = util::make_unique<AssetDir>();
499 asset_dir->setFileList(files.release());
500 return asset_dir;
501}
502
Adam Lesinski7ad11102016-10-28 16:39:15 -0700503// Search in reverse because that's how we used to do it and we need to preserve behaviour.
504// This is unfortunate, because ClassLoaders delegate to the parent first, so the order
505// is inconsistent for split APKs.
506std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
507 Asset::AccessMode mode,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800508 ApkAssetsCookie* out_cookie) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700509 for (int32_t i = apk_assets_.size() - 1; i >= 0; i--) {
Mårten Kongstaddbf343b2019-02-21 07:54:18 +0100510 // Prevent RRO from modifying assets and other entries accessed by file
511 // path. Explicitly asking for a path in a given package (denoted by a
512 // cookie) is still OK.
513 if (apk_assets_[i]->IsOverlay()) {
514 continue;
515 }
516
Ryan Mitchellc07aa702020-03-10 13:49:12 -0700517 std::unique_ptr<Asset> asset = apk_assets_[i]->GetAssetsProvider()->Open(filename, mode);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700518 if (asset) {
519 if (out_cookie != nullptr) {
520 *out_cookie = i;
521 }
522 return asset;
523 }
524 }
525
526 if (out_cookie != nullptr) {
527 *out_cookie = kInvalidCookie;
528 }
529 return {};
530}
531
532std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800533 ApkAssetsCookie cookie,
534 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700535 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
536 return {};
537 }
Ryan Mitchellc07aa702020-03-10 13:49:12 -0700538 return apk_assets_[cookie]->GetAssetsProvider()->Open(filename, mode);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700539}
540
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700541base::expected<FindEntryResult, NullOrIOError> AssetManager2::FindEntry(
542 uint32_t resid, uint16_t density_override, bool stop_at_first_match,
543 bool ignore_configuration) const {
544 const bool logging_enabled = resource_resolution_logging_enabled_;
545 if (UNLIKELY(logging_enabled)) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700546 // Clear the last logged resource resolution.
547 ResetResourceResolution();
548 last_resolution_.resid = resid;
549 }
550
Adam Lesinski7ad11102016-10-28 16:39:15 -0700551 // Might use this if density_override != 0.
552 ResTable_config density_override_config;
553
554 // Select our configuration or generate a density override configuration.
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800555 const ResTable_config* desired_config = &configuration_;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700556 if (density_override != 0 && density_override != configuration_.density) {
557 density_override_config = configuration_;
558 density_override_config.density = density_override;
559 desired_config = &density_override_config;
560 }
561
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700562 // Retrieve the package group from the package id of the resource id.
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700563 if (UNLIKELY(!is_valid_resid(resid))) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500564 LOG(ERROR) << base::StringPrintf("Invalid ID 0x%08x.", resid);
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700565 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -0500566 }
567
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800568 const uint32_t package_id = get_package_id(resid);
569 const uint8_t type_idx = get_type_id(resid) - 1;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800570 const uint16_t entry_idx = get_entry_id(resid);
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700571 uint8_t package_idx = package_ids_[package_id];
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700572 if (UNLIKELY(package_idx == 0xff)) {
Ryan Mitchell2fe23472019-02-27 09:43:01 -0800573 ANDROID_LOG(ERROR) << base::StringPrintf("No package ID %02x found for ID 0x%08x.",
574 package_id, resid);
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700575 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -0500576 }
577
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800578 const PackageGroup& package_group = package_groups_[package_idx];
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700579 auto result = FindEntryInternal(package_group, type_idx, entry_idx, *desired_config,
580 stop_at_first_match, ignore_configuration);
581 if (UNLIKELY(!result.has_value())) {
582 return base::unexpected(result.error());
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700583 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800584
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700585 if (!stop_at_first_match && !ignore_configuration && !apk_assets_[result->cookie]->IsLoader()) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700586 for (const auto& id_map : package_group.overlays_) {
587 auto overlay_entry = id_map.overlay_res_maps_.Lookup(resid);
588 if (!overlay_entry) {
589 // No id map entry exists for this target resource.
590 continue;
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700591 }
592 if (overlay_entry.IsInlineValue()) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700593 // The target resource is overlaid by an inline value not represented by a resource.
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700594 result->entry = overlay_entry.GetInlineValue();
595 result->dynamic_ref_table = id_map.overlay_res_maps_.GetOverlayDynamicRefTable();
596 result->cookie = id_map.cookie;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700597 continue;
598 }
599
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700600 auto overlay_result = FindEntry(overlay_entry.GetResourceId(), density_override,
601 false /* stop_at_first_match */,
602 false /* ignore_configuration */);
603 if (UNLIKELY(IsIOError(overlay_result))) {
604 return base::unexpected(overlay_result.error());
605 }
606 if (!overlay_result.has_value()) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700607 continue;
608 }
609
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700610 if (!overlay_result->config.isBetterThan(result->config, desired_config)
611 && overlay_result->config.compare(result->config) != 0) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700612 // The configuration of the entry for the overlay must be equal to or better than the target
613 // configuration to be chosen as the better value.
614 continue;
615 }
616
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700617 result->cookie = overlay_result->cookie;
618 result->entry = overlay_result->entry;
619 result->config = overlay_result->config;
620 result->dynamic_ref_table = id_map.overlay_res_maps_.GetOverlayDynamicRefTable();
621
622 if (UNLIKELY(logging_enabled)) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700623 last_resolution_.steps.push_back(
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700624 Resolution::Step{Resolution::Step::Type::OVERLAID, overlay_result->config.toString(),
625 overlay_result->package_name});
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700626 }
627 }
628 }
629
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700630 if (UNLIKELY(logging_enabled)) {
631 last_resolution_.cookie = result->cookie;
632 last_resolution_.type_string_ref = result->type_string_ref;
633 last_resolution_.entry_string_ref = result->entry_string_ref;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700634 }
635
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700636 return result;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700637}
638
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700639base::expected<FindEntryResult, NullOrIOError> AssetManager2::FindEntryInternal(
640 const PackageGroup& package_group, uint8_t type_idx, uint16_t entry_idx,
641 const ResTable_config& desired_config, bool stop_at_first_match,
642 bool ignore_configuration) const {
643 const bool logging_enabled = resource_resolution_logging_enabled_;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800644 ApkAssetsCookie best_cookie = kInvalidCookie;
645 const LoadedPackage* best_package = nullptr;
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700646 incfs::verified_map_ptr<ResTable_type> best_type;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800647 const ResTable_config* best_config = nullptr;
648 ResTable_config best_config_copy;
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700649 uint32_t best_offset = 0U;
650 uint32_t type_flags = 0U;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800651
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700652 auto resolution_type = Resolution::Step::Type::NO_ENTRY;
Winson2f3669b2019-01-11 11:28:34 -0800653 std::vector<Resolution::Step> resolution_steps;
654
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800655 // If desired_config is the same as the set configuration, then we can use our filtered list
656 // and we don't need to match the configurations, since they already matched.
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700657 const bool use_fast_path = !ignore_configuration && &desired_config == &configuration_;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800658
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700659 const size_t package_count = package_group.packages_.size();
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800660 for (size_t pi = 0; pi < package_count; pi++) {
661 const ConfiguredPackage& loaded_package_impl = package_group.packages_[pi];
662 const LoadedPackage* loaded_package = loaded_package_impl.loaded_package_;
663 ApkAssetsCookie cookie = package_group.cookies_[pi];
664
665 // If the type IDs are offset in this package, we need to take that into account when searching
666 // for a type.
667 const TypeSpec* type_spec = loaded_package->GetTypeSpecByTypeIndex(type_idx);
668 if (UNLIKELY(type_spec == nullptr)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700669 continue;
670 }
671
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700672 auto entry_flags = type_spec->GetFlagsForEntryIndex(entry_idx);
673 if (UNLIKELY(!entry_flags)) {
674 return base::unexpected(entry_flags.error());
675 }
676 type_flags |= entry_flags.value();
677
Winson9947f1e2019-08-16 10:20:39 -0700678 // If the package is an overlay or custom loader,
679 // then even configurations that are the same MUST be chosen.
Winson9947f1e2019-08-16 10:20:39 -0700680 const bool package_is_loader = loaded_package->IsCustomLoader();
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800681
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800682 if (use_fast_path) {
Winson2f3669b2019-01-11 11:28:34 -0800683 const FilteredConfigGroup& filtered_group = loaded_package_impl.filtered_configs_[type_idx];
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700684 for (const auto& type_config : filtered_group.type_configs) {
685 const ResTable_config& this_config = type_config.config;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800686
687 // We can skip calling ResTable_config::match() because we know that all candidate
688 // configurations that do NOT match have been filtered-out.
Winson2f3669b2019-01-11 11:28:34 -0800689 if (best_config == nullptr) {
690 resolution_type = Resolution::Step::Type::INITIAL;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700691 } else if (this_config.isBetterThan(*best_config, &desired_config)) {
692 resolution_type = (package_is_loader) ? Resolution::Step::Type::BETTER_MATCH_LOADER
693 : Resolution::Step::Type::BETTER_MATCH;
694 } else if (package_is_loader && this_config.compare(*best_config) == 0) {
695 resolution_type = Resolution::Step::Type::OVERLAID_LOADER;
Winson2f3669b2019-01-11 11:28:34 -0800696 } else {
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700697 if (UNLIKELY(logging_enabled)) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700698 resolution_type = (package_is_loader) ? Resolution::Step::Type::SKIPPED_LOADER
699 : Resolution::Step::Type::SKIPPED;
Winson9947f1e2019-08-16 10:20:39 -0700700 resolution_steps.push_back(Resolution::Step{resolution_type,
701 this_config.toString(),
702 &loaded_package->GetPackageName()});
703 }
Winson2f3669b2019-01-11 11:28:34 -0800704 continue;
705 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800706
Winson2f3669b2019-01-11 11:28:34 -0800707 // The configuration matches and is better than the previous selection.
708 // Find the entry value if it exists for this configuration.
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700709 const auto& type = type_config.type;
710 const auto offset = LoadedPackage::GetEntryOffset(type, entry_idx);
711 if (UNLIKELY(IsIOError(offset))) {
712 return base::unexpected(offset.error());
713 }
714 if (!offset.has_value()) {
715 if (UNLIKELY(logging_enabled)) {
Winson9947f1e2019-08-16 10:20:39 -0700716 if (package_is_loader) {
717 resolution_type = Resolution::Step::Type::NO_ENTRY_LOADER;
718 } else {
719 resolution_type = Resolution::Step::Type::NO_ENTRY;
720 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700721 resolution_steps.push_back(Resolution::Step{resolution_type,
Winson9947f1e2019-08-16 10:20:39 -0700722 this_config.toString(),
723 &loaded_package->GetPackageName()});
724 }
Winson2f3669b2019-01-11 11:28:34 -0800725 continue;
726 }
727
728 best_cookie = cookie;
729 best_package = loaded_package;
730 best_type = type;
731 best_config = &this_config;
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700732 best_offset = offset.value();
Winson2f3669b2019-01-11 11:28:34 -0800733
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700734 if (UNLIKELY(logging_enabled)) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700735 last_resolution_.steps.push_back(Resolution::Step{resolution_type,
736 this_config.toString(),
737 &loaded_package->GetPackageName()});
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800738 }
739 }
740 } else {
741 // This is the slower path, which doesn't use the filtered list of configurations.
742 // Here we must read the ResTable_config from the mmapped APK, convert it to host endianness
743 // and fill in any new fields that did not exist when the APK was compiled.
744 // Furthermore when selecting configurations we can't just record the pointer to the
745 // ResTable_config, we must copy it.
746 const auto iter_end = type_spec->types + type_spec->type_count;
747 for (auto iter = type_spec->types; iter != iter_end; ++iter) {
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700748 const incfs::verified_map_ptr<ResTable_type>& type = *iter;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800749
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700750 ResTable_config this_config{};
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800751 if (!ignore_configuration) {
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700752 this_config.copyFromDtoH(type->config);
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700753 if (!this_config.match(desired_config)) {
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800754 continue;
755 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800756
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800757 if (best_config == nullptr) {
758 resolution_type = Resolution::Step::Type::INITIAL;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700759 } else if (this_config.isBetterThan(*best_config, &desired_config)) {
760 resolution_type = (package_is_loader) ? Resolution::Step::Type::BETTER_MATCH_LOADER
761 : Resolution::Step::Type::BETTER_MATCH;
762 } else if (package_is_loader && this_config.compare(*best_config) == 0) {
763 resolution_type = Resolution::Step::Type::OVERLAID_LOADER;
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800764 } else {
765 continue;
766 }
Winson2f3669b2019-01-11 11:28:34 -0800767 }
768
769 // The configuration matches and is better than the previous selection.
770 // Find the entry value if it exists for this configuration.
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700771 const auto offset = LoadedPackage::GetEntryOffset(type, entry_idx);
772 if (UNLIKELY(IsIOError(offset))) {
773 return base::unexpected(offset.error());
774 }
775 if (!offset.has_value()) {
Winson2f3669b2019-01-11 11:28:34 -0800776 continue;
777 }
778
779 best_cookie = cookie;
780 best_package = loaded_package;
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700781 best_type = type;
Winson2f3669b2019-01-11 11:28:34 -0800782 best_config_copy = this_config;
783 best_config = &best_config_copy;
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700784 best_offset = offset.value();
Winson2f3669b2019-01-11 11:28:34 -0800785
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700786 if (stop_at_first_match) {
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800787 // Any configuration will suffice, so break.
788 break;
789 }
790
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700791 if (UNLIKELY(logging_enabled)) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700792 last_resolution_.steps.push_back(Resolution::Step{resolution_type,
793 this_config.toString(),
794 &loaded_package->GetPackageName()});
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800795 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700796 }
797 }
798 }
799
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800800 if (UNLIKELY(best_cookie == kInvalidCookie)) {
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700801 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700802 }
803
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700804 auto best_entry_result = LoadedPackage::GetEntryFromOffset(best_type, best_offset);
805 if (!best_entry_result.has_value()) {
806 return base::unexpected(best_entry_result.error());
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800807 }
808
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700809 const incfs::map_ptr<ResTable_entry> best_entry = *best_entry_result;
810 if (!best_entry) {
811 return base::unexpected(IOError::PAGES_MISSING);
Ryan Mitchellbf1f45b2020-09-29 17:22:52 -0700812 }
813
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700814 const auto entry = GetEntryValue(best_entry.verified());
815 if (!entry.has_value()) {
816 return base::unexpected(entry.error());
817 }
Winson2f3669b2019-01-11 11:28:34 -0800818
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700819 return FindEntryResult{
820 .cookie = best_cookie,
821 .entry = *entry,
822 .config = *best_config,
823 .type_flags = type_flags,
824 .package_name = &best_package->GetPackageName(),
825 .type_string_ref = StringPoolRef(best_package->GetTypeStringPool(), best_type->id - 1),
826 .entry_string_ref = StringPoolRef(best_package->GetKeyStringPool(),
827 best_entry->key.index),
828 .dynamic_ref_table = package_group.dynamic_ref_table.get(),
829 };
Adam Lesinski7ad11102016-10-28 16:39:15 -0700830}
831
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700832void AssetManager2::ResetResourceResolution() const {
833 last_resolution_.cookie = kInvalidCookie;
834 last_resolution_.resid = 0;
835 last_resolution_.steps.clear();
836 last_resolution_.type_string_ref = StringPoolRef();
837 last_resolution_.entry_string_ref = StringPoolRef();
838}
839
Winson2f3669b2019-01-11 11:28:34 -0800840void AssetManager2::SetResourceResolutionLoggingEnabled(bool enabled) {
841 resource_resolution_logging_enabled_ = enabled;
Winson2f3669b2019-01-11 11:28:34 -0800842 if (!enabled) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700843 ResetResourceResolution();
Winson2f3669b2019-01-11 11:28:34 -0800844 }
845}
846
847std::string AssetManager2::GetLastResourceResolution() const {
848 if (!resource_resolution_logging_enabled_) {
849 LOG(ERROR) << "Must enable resource resolution logging before getting path.";
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700850 return {};
Winson2f3669b2019-01-11 11:28:34 -0800851 }
852
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700853 auto cookie = last_resolution_.cookie;
Winson2f3669b2019-01-11 11:28:34 -0800854 if (cookie == kInvalidCookie) {
855 LOG(ERROR) << "AssetManager hasn't resolved a resource to read resolution path.";
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700856 return {};
Winson2f3669b2019-01-11 11:28:34 -0800857 }
858
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700859 uint32_t resid = last_resolution_.resid;
860 std::vector<Resolution::Step>& steps = last_resolution_.steps;
Winson2f3669b2019-01-11 11:28:34 -0800861 std::string resource_name_string;
862
863 const LoadedPackage* package =
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700864 apk_assets_[cookie]->GetLoadedArsc()->GetPackageById(get_package_id(resid));
Winson2f3669b2019-01-11 11:28:34 -0800865
866 if (package != nullptr) {
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700867 auto resource_name = ToResourceName(last_resolution_.type_string_ref,
868 last_resolution_.entry_string_ref,
869 package->GetPackageName());
870 resource_name_string = resource_name.has_value() ?
871 ToFormattedResourceString(resource_name.value()) : "<unknown>";
Winson2f3669b2019-01-11 11:28:34 -0800872 }
873
874 std::stringstream log_stream;
875 log_stream << base::StringPrintf("Resolution for 0x%08x ", resid)
876 << resource_name_string
877 << "\n\tFor config -"
878 << configuration_.toString();
879
880 std::string prefix;
881 for (Resolution::Step step : steps) {
882 switch (step.type) {
883 case Resolution::Step::Type::INITIAL:
884 prefix = "Found initial";
885 break;
886 case Resolution::Step::Type::BETTER_MATCH:
887 prefix = "Found better";
888 break;
Winson9947f1e2019-08-16 10:20:39 -0700889 case Resolution::Step::Type::BETTER_MATCH_LOADER:
890 prefix = "Found better in loader";
891 break;
Winson2f3669b2019-01-11 11:28:34 -0800892 case Resolution::Step::Type::OVERLAID:
893 prefix = "Overlaid";
894 break;
Winson9947f1e2019-08-16 10:20:39 -0700895 case Resolution::Step::Type::OVERLAID_LOADER:
896 prefix = "Overlaid by loader";
897 break;
898 case Resolution::Step::Type::SKIPPED:
899 prefix = "Skipped";
900 break;
901 case Resolution::Step::Type::SKIPPED_LOADER:
902 prefix = "Skipped loader";
903 break;
904 case Resolution::Step::Type::NO_ENTRY:
905 prefix = "No entry";
906 break;
907 case Resolution::Step::Type::NO_ENTRY_LOADER:
908 prefix = "No entry for loader";
909 break;
Winson2f3669b2019-01-11 11:28:34 -0800910 }
911
912 if (!prefix.empty()) {
913 log_stream << "\n\t" << prefix << ": " << *step.package_name;
914
915 if (!step.config_name.isEmpty()) {
916 log_stream << " -" << step.config_name;
917 }
918 }
919 }
920
921 return log_stream.str();
922}
923
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700924base::expected<AssetManager2::ResourceName, NullOrIOError> AssetManager2::GetResourceName(
925 uint32_t resid) const {
926 auto result = FindEntry(resid, 0u /* density_override */, true /* stop_at_first_match */,
927 true /* ignore_configuration */);
928 if (!result.has_value()) {
929 return base::unexpected(result.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -0700930 }
931
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700932 return ToResourceName(result->type_string_ref,
933 result->entry_string_ref,
934 *result->package_name);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700935}
936
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700937base::expected<AssetManager2::SelectedValue, NullOrIOError> AssetManager2::GetResource(
938 uint32_t resid, bool may_be_bag, uint16_t density_override) const {
939 auto result = FindEntry(resid, density_override, false /* stop_at_first_match */,
940 false /* ignore_configuration */);
941 if (!result.has_value()) {
942 return base::unexpected(result.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -0700943 }
944
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700945 auto result_map_entry = std::get_if<incfs::verified_map_ptr<ResTable_map_entry>>(&result->entry);
Ryan Mitchellbf1f45b2020-09-29 17:22:52 -0700946 if (result_map_entry != nullptr) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700947 if (!may_be_bag) {
948 LOG(ERROR) << base::StringPrintf("Resource %08x is a complex map type.", resid);
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700949 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700950 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800951
952 // Create a reference since we can't represent this complex type as a Res_value.
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700953 return SelectedValue(Res_value::TYPE_REFERENCE, resid, result->cookie, result->type_flags,
954 resid, result->config);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700955 }
956
Adam Lesinskida431a22016-12-29 16:08:16 -0500957 // Convert the package ID to the runtime assigned package ID.
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700958 Res_value value = std::get<Res_value>(result->entry);
959 result->dynamic_ref_table->lookupResourceValue(&value);
Adam Lesinskida431a22016-12-29 16:08:16 -0500960
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700961 return SelectedValue(value.dataType, value.data, result->cookie, result->type_flags,
962 resid, result->config);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700963}
964
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700965base::expected<std::monostate, NullOrIOError> AssetManager2::ResolveReference(
Ryan Mitchell87e89542020-10-05 14:24:35 -0700966 AssetManager2::SelectedValue& value, bool cache_value) const {
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700967 if (value.type != Res_value::TYPE_REFERENCE || value.data == 0U) {
968 // Not a reference. Nothing to do.
969 return {};
Adam Lesinski0c405242017-01-13 20:47:26 -0800970 }
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700971
Ryan Mitchell87e89542020-10-05 14:24:35 -0700972 const uint32_t original_flags = value.flags;
973 const uint32_t original_resid = value.data;
974 if (cache_value) {
975 auto cached_value = cached_resolved_values_.find(value.data);
976 if (cached_value != cached_resolved_values_.end()) {
977 value = cached_value->second;
978 value.flags |= original_flags;
979 return {};
980 }
981 }
982
983 uint32_t combined_flags = 0U;
984 uint32_t resolve_resid = original_resid;
Ryan Mitchellc75c2e02020-08-17 08:42:48 -0700985 constexpr const uint32_t kMaxIterations = 20;
986 for (uint32_t i = 0U;; i++) {
987 auto result = GetResource(resolve_resid, true /*may_be_bag*/);
988 if (!result.has_value()) {
989 return base::unexpected(result.error());
990 }
991
992 if (result->type != Res_value::TYPE_REFERENCE ||
993 result->data == Res_value::DATA_NULL_UNDEFINED ||
994 result->data == resolve_resid || i == kMaxIterations) {
Ryan Mitchell87e89542020-10-05 14:24:35 -0700995 result->flags |= combined_flags;
996 if (cache_value) {
997 cached_resolved_values_[original_resid] = *result;
998 }
999
1000 // Add the original flags after caching the result so queries with a different set of original
1001 // flags do not include these original flags.
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001002 value = *result;
Ryan Mitchell87e89542020-10-05 14:24:35 -07001003 value.flags |= original_flags;
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001004 return {};
1005 }
1006
1007 combined_flags |= result->flags;
1008 resolve_resid = result->data;
1009 }
Adam Lesinski0c405242017-01-13 20:47:26 -08001010}
1011
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001012const std::vector<uint32_t> AssetManager2::GetBagResIdStack(uint32_t resid) const {
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001013 auto cached_iter = cached_bag_resid_stacks_.find(resid);
1014 if (cached_iter != cached_bag_resid_stacks_.end()) {
1015 return cached_iter->second;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001016 }
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001017
1018 std::vector<uint32_t> found_resids;
1019 GetBag(resid, found_resids);
1020 cached_bag_resid_stacks_.emplace(resid, found_resids);
1021 return found_resids;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001022}
1023
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001024base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::ResolveBag(
1025 AssetManager2::SelectedValue& value) const {
1026 if (UNLIKELY(value.type != Res_value::TYPE_REFERENCE)) {
1027 return base::unexpected(std::nullopt);
1028 }
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001029
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001030 auto bag = GetBag(value.data);
1031 if (bag.has_value()) {
1032 value.flags |= (*bag)->type_spec_flags;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08001033 }
1034 return bag;
y57cd1952018-04-12 14:26:23 -07001035}
1036
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001037base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::GetBag(uint32_t resid) const {
1038 std::vector<uint32_t> found_resids;
Ryan Mitchell5602dc932020-10-05 14:29:43 -07001039 return GetBag(resid, found_resids);
Ryan Mitchell155d5392020-02-10 13:35:24 -08001040}
1041
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001042base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::GetBag(
1043 uint32_t resid, std::vector<uint32_t>& child_resids) const {
1044 if (auto cached_iter = cached_bags_.find(resid); cached_iter != cached_bags_.end()) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001045 return cached_iter->second.get();
1046 }
1047
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001048 auto entry = FindEntry(resid, 0u /* density_override */, false /* stop_at_first_match */,
1049 false /* ignore_configuration */);
1050 if (!entry.has_value()) {
1051 return base::unexpected(entry.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001052 }
1053
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001054 auto entry_map = std::get_if<incfs::verified_map_ptr<ResTable_map_entry>>(&entry->entry);
1055 if (entry_map == nullptr) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001056 // Not a bag, nothing to do.
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001057 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001058 }
1059
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001060 auto map = *entry_map;
1061 auto map_entry = map.offset(dtohs(map->size)).convert<ResTable_map>();
1062 const auto map_entry_end = map_entry + dtohl(map->count);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001063
y57cd1952018-04-12 14:26:23 -07001064 // Keep track of ids that have already been seen to prevent infinite loops caused by circular
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001065 // dependencies between bags.
y57cd1952018-04-12 14:26:23 -07001066 child_resids.push_back(resid);
1067
Adam Lesinskida431a22016-12-29 16:08:16 -05001068 uint32_t parent_resid = dtohl(map->parent.ident);
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001069 if (parent_resid == 0U ||
1070 std::find(child_resids.begin(), child_resids.end(), parent_resid) != child_resids.end()) {
1071 // There is no parent or a circular parental dependency exist, meaning there is nothing to
1072 // inherit and we can do a simple copy of the entries in the map.
Adam Lesinski7ad11102016-10-28 16:39:15 -07001073 const size_t entry_count = map_entry_end - map_entry;
1074 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
1075 malloc(sizeof(ResolvedBag) + (entry_count * sizeof(ResolvedBag::Entry))))};
Ryan Mitchell155d5392020-02-10 13:35:24 -08001076
1077 bool sort_entries = false;
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001078 for (auto new_entry = new_bag->entries; map_entry != map_entry_end; ++map_entry) {
1079 if (UNLIKELY(!map_entry)) {
1080 return base::unexpected(IOError::PAGES_MISSING);
1081 }
1082
Adam Lesinskida431a22016-12-29 16:08:16 -05001083 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001084 if (!is_internal_resid(new_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -05001085 // Attributes, arrays, etc don't have a resource id as the name. They specify
1086 // other data, which would be wrong to change via a lookup.
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001087 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001088 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
1089 resid);
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001090 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001091 }
1092 }
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001093
1094 new_entry->cookie = entry->cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -05001095 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001096 new_entry->key_pool = nullptr;
1097 new_entry->type_pool = nullptr;
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001098 new_entry->style = resid;
Adam Lesinski30080e22017-10-16 16:18:09 -07001099 new_entry->value.copyFrom_dtoh(map_entry->value);
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001100 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1101 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001102 LOG(ERROR) << base::StringPrintf(
1103 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
1104 new_entry->value.data, new_key);
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001105 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001106 }
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001107
Ryan Mitchell155d5392020-02-10 13:35:24 -08001108 sort_entries = sort_entries ||
1109 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001110 ++new_entry;
1111 }
Ryan Mitchell155d5392020-02-10 13:35:24 -08001112
1113 if (sort_entries) {
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001114 std::sort(new_bag->entries, new_bag->entries + entry_count,
1115 [](auto&& lhs, auto&& rhs) { return lhs.key < rhs.key; });
Ryan Mitchell155d5392020-02-10 13:35:24 -08001116 }
1117
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001118 new_bag->type_spec_flags = entry->type_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001119 new_bag->entry_count = static_cast<uint32_t>(entry_count);
1120 ResolvedBag* result = new_bag.get();
1121 cached_bags_[resid] = std::move(new_bag);
1122 return result;
1123 }
1124
Adam Lesinskida431a22016-12-29 16:08:16 -05001125 // In case the parent is a dynamic reference, resolve it.
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001126 entry->dynamic_ref_table->lookupResourceId(&parent_resid);
Adam Lesinskida431a22016-12-29 16:08:16 -05001127
Adam Lesinski7ad11102016-10-28 16:39:15 -07001128 // Get the parent and do a merge of the keys.
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001129 const auto parent_bag = GetBag(parent_resid, child_resids);
1130 if (UNLIKELY(!parent_bag.has_value())) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001131 // Failed to get the parent that should exist.
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001132 LOG(ERROR) << base::StringPrintf("Failed to find parent 0x%08x of bag 0x%08x.", parent_resid,
1133 resid);
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001134 return base::unexpected(parent_bag.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001135 }
1136
Adam Lesinski7ad11102016-10-28 16:39:15 -07001137 // Create the max possible entries we can make. Once we construct the bag,
1138 // we will realloc to fit to size.
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001139 const size_t max_count = (*parent_bag)->entry_count + dtohl(map->count);
George Burgess IV09b119f2017-07-25 15:00:04 -07001140 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
1141 malloc(sizeof(ResolvedBag) + (max_count * sizeof(ResolvedBag::Entry))))};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001142 ResolvedBag::Entry* new_entry = new_bag->entries;
1143
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001144 const ResolvedBag::Entry* parent_entry = (*parent_bag)->entries;
1145 const ResolvedBag::Entry* const parent_entry_end = parent_entry + (*parent_bag)->entry_count;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001146
1147 // The keys are expected to be in sorted order. Merge the two bags.
Ryan Mitchell155d5392020-02-10 13:35:24 -08001148 bool sort_entries = false;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001149 while (map_entry != map_entry_end && parent_entry != parent_entry_end) {
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001150 if (UNLIKELY(!map_entry)) {
1151 return base::unexpected(IOError::PAGES_MISSING);
1152 }
1153
Adam Lesinskida431a22016-12-29 16:08:16 -05001154 uint32_t child_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001155 if (!is_internal_resid(child_key)) {
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001156 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&child_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001157 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", child_key,
1158 resid);
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001159 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001160 }
1161 }
1162
Adam Lesinski7ad11102016-10-28 16:39:15 -07001163 if (child_key <= parent_entry->key) {
1164 // Use the child key if it comes before the parent
1165 // or is equal to the parent (overrides).
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001166 new_entry->cookie = entry->cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001167 new_entry->key = child_key;
1168 new_entry->key_pool = nullptr;
1169 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -07001170 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001171 new_entry->style = resid;
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001172 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1173 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001174 LOG(ERROR) << base::StringPrintf(
1175 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
1176 new_entry->value.data, child_key);
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001177 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001178 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001179 ++map_entry;
1180 } else {
1181 // Take the parent entry as-is.
1182 memcpy(new_entry, parent_entry, sizeof(*new_entry));
1183 }
1184
Ryan Mitchell155d5392020-02-10 13:35:24 -08001185 sort_entries = sort_entries ||
1186 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001187 if (child_key >= parent_entry->key) {
1188 // Move to the next parent entry if we used it or it was overridden.
1189 ++parent_entry;
1190 }
1191 // Increment to the next entry to fill.
1192 ++new_entry;
1193 }
1194
1195 // Finish the child entries if they exist.
1196 while (map_entry != map_entry_end) {
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001197 if (UNLIKELY(!map_entry)) {
1198 return base::unexpected(IOError::PAGES_MISSING);
1199 }
1200
Adam Lesinskida431a22016-12-29 16:08:16 -05001201 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001202 if (!is_internal_resid(new_key)) {
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001203 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001204 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
1205 resid);
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001206 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001207 }
1208 }
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001209 new_entry->cookie = entry->cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -05001210 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001211 new_entry->key_pool = nullptr;
1212 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -07001213 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001214 new_entry->style = resid;
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001215 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1216 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001217 LOG(ERROR) << base::StringPrintf("Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.",
1218 new_entry->value.dataType, new_entry->value.data, new_key);
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001219 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001220 }
Ryan Mitchell155d5392020-02-10 13:35:24 -08001221 sort_entries = sort_entries ||
1222 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001223 ++map_entry;
1224 ++new_entry;
1225 }
1226
1227 // Finish the parent entries if they exist.
1228 if (parent_entry != parent_entry_end) {
1229 // Take the rest of the parent entries as-is.
1230 const size_t num_entries_to_copy = parent_entry_end - parent_entry;
1231 memcpy(new_entry, parent_entry, num_entries_to_copy * sizeof(*new_entry));
1232 new_entry += num_entries_to_copy;
1233 }
1234
1235 // Resize the resulting array to fit.
1236 const size_t actual_count = new_entry - new_bag->entries;
1237 if (actual_count != max_count) {
George Burgess IV09b119f2017-07-25 15:00:04 -07001238 new_bag.reset(reinterpret_cast<ResolvedBag*>(realloc(
1239 new_bag.release(), sizeof(ResolvedBag) + (actual_count * sizeof(ResolvedBag::Entry)))));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001240 }
1241
Ryan Mitchell155d5392020-02-10 13:35:24 -08001242 if (sort_entries) {
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001243 std::sort(new_bag->entries, new_bag->entries + actual_count,
1244 [](auto&& lhs, auto&& rhs) { return lhs.key < rhs.key; });
Ryan Mitchell155d5392020-02-10 13:35:24 -08001245 }
1246
Adam Lesinski1a1e9c22017-10-13 15:45:34 -07001247 // Combine flags from the parent and our own bag.
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001248 new_bag->type_spec_flags = entry->type_flags | (*parent_bag)->type_spec_flags;
George Burgess IV09b119f2017-07-25 15:00:04 -07001249 new_bag->entry_count = static_cast<uint32_t>(actual_count);
1250 ResolvedBag* result = new_bag.get();
1251 cached_bags_[resid] = std::move(new_bag);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001252 return result;
1253}
1254
Adam Lesinski929d6512017-01-16 19:11:19 -08001255static bool Utf8ToUtf16(const StringPiece& str, std::u16string* out) {
1256 ssize_t len =
1257 utf8_to_utf16_length(reinterpret_cast<const uint8_t*>(str.data()), str.size(), false);
1258 if (len < 0) {
1259 return false;
1260 }
1261 out->resize(static_cast<size_t>(len));
1262 utf8_to_utf16(reinterpret_cast<const uint8_t*>(str.data()), str.size(), &*out->begin(),
1263 static_cast<size_t>(len + 1));
1264 return true;
1265}
1266
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001267base::expected<uint32_t, NullOrIOError> AssetManager2::GetResourceId(
1268 const std::string& resource_name, const std::string& fallback_type,
1269 const std::string& fallback_package) const {
Adam Lesinski929d6512017-01-16 19:11:19 -08001270 StringPiece package_name, type, entry;
1271 if (!ExtractResourceName(resource_name, &package_name, &type, &entry)) {
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001272 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001273 }
1274
1275 if (entry.empty()) {
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001276 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001277 }
1278
1279 if (package_name.empty()) {
1280 package_name = fallback_package;
1281 }
1282
1283 if (type.empty()) {
1284 type = fallback_type;
1285 }
1286
1287 std::u16string type16;
1288 if (!Utf8ToUtf16(type, &type16)) {
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001289 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001290 }
1291
1292 std::u16string entry16;
1293 if (!Utf8ToUtf16(entry, &entry16)) {
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001294 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001295 }
1296
1297 const StringPiece16 kAttr16 = u"attr";
1298 const static std::u16string kAttrPrivate16 = u"^attr-private";
1299
1300 for (const PackageGroup& package_group : package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001301 for (const ConfiguredPackage& package_impl : package_group.packages_) {
1302 const LoadedPackage* package = package_impl.loaded_package_;
Adam Lesinski929d6512017-01-16 19:11:19 -08001303 if (package_name != package->GetPackageName()) {
1304 // All packages in the same group are expected to have the same package name.
1305 break;
1306 }
1307
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001308 base::expected<uint32_t, NullOrIOError> resid = package->FindEntryByName(type16, entry16);
1309 if (UNLIKELY(IsIOError(resid))) {
1310 return base::unexpected(resid.error());
1311 }
1312
1313 if (!resid.has_value() && kAttr16 == type16) {
Adam Lesinski929d6512017-01-16 19:11:19 -08001314 // Private attributes in libraries (such as the framework) are sometimes encoded
1315 // under the type '^attr-private' in order to leave the ID space of public 'attr'
1316 // free for future additions. Check '^attr-private' for the same name.
1317 resid = package->FindEntryByName(kAttrPrivate16, entry16);
1318 }
1319
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001320 if (resid.has_value()) {
1321 return fix_package_id(*resid, package_group.dynamic_ref_table->mAssignedPackageId);
Adam Lesinski929d6512017-01-16 19:11:19 -08001322 }
1323 }
1324 }
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001325 return base::unexpected(std::nullopt);
Adam Lesinski0c405242017-01-13 20:47:26 -08001326}
1327
Mårten Kongstad668ec5b2018-06-11 14:11:33 +02001328void AssetManager2::RebuildFilterList(bool filter_incompatible_configs) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001329 for (PackageGroup& group : package_groups_) {
1330 for (ConfiguredPackage& impl : group.packages_) {
1331 // Destroy it.
1332 impl.filtered_configs_.~ByteBucketArray();
1333
1334 // Re-create it.
1335 new (&impl.filtered_configs_) ByteBucketArray<FilteredConfigGroup>();
1336
1337 // Create the filters here.
1338 impl.loaded_package_->ForEachTypeSpec([&](const TypeSpec* spec, uint8_t type_index) {
1339 FilteredConfigGroup& group = impl.filtered_configs_.editItemAt(type_index);
1340 const auto iter_end = spec->types + spec->type_count;
1341 for (auto iter = spec->types; iter != iter_end; ++iter) {
1342 ResTable_config this_config;
1343 this_config.copyFromDtoH((*iter)->config);
Mårten Kongstad668ec5b2018-06-11 14:11:33 +02001344 if (!filter_incompatible_configs || this_config.match(configuration_)) {
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001345 group.type_configs.push_back(TypeConfig{*iter, this_config});
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001346 }
1347 }
1348 });
1349 }
1350 }
1351}
1352
Adam Lesinski7ad11102016-10-28 16:39:15 -07001353void AssetManager2::InvalidateCaches(uint32_t diff) {
Ryan Mitchell2c4d8742019-03-04 09:41:00 -08001354 cached_bag_resid_stacks_.clear();
1355
Adam Lesinski7ad11102016-10-28 16:39:15 -07001356 if (diff == 0xffffffffu) {
1357 // Everything must go.
1358 cached_bags_.clear();
1359 return;
1360 }
1361
1362 // Be more conservative with what gets purged. Only if the bag has other possible
1363 // variations with respect to what changed (diff) should we remove it.
1364 for (auto iter = cached_bags_.cbegin(); iter != cached_bags_.cend();) {
1365 if (diff & iter->second->type_spec_flags) {
1366 iter = cached_bags_.erase(iter);
1367 } else {
1368 ++iter;
1369 }
1370 }
Ryan Mitchell87e89542020-10-05 14:24:35 -07001371
1372 cached_resolved_values_.clear();
Adam Lesinski7ad11102016-10-28 16:39:15 -07001373}
1374
Ryan Mitchell2e394222019-08-28 12:10:51 -07001375uint8_t AssetManager2::GetAssignedPackageId(const LoadedPackage* package) const {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001376 for (auto& package_group : package_groups_) {
1377 for (auto& package2 : package_group.packages_) {
1378 if (package2.loaded_package_ == package) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -07001379 return package_group.dynamic_ref_table->mAssignedPackageId;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001380 }
1381 }
1382 }
1383 return 0;
1384}
1385
Adam Lesinski30080e22017-10-16 16:18:09 -07001386std::unique_ptr<Theme> AssetManager2::NewTheme() {
1387 return std::unique_ptr<Theme>(new Theme(this));
1388}
1389
1390Theme::Theme(AssetManager2* asset_manager) : asset_manager_(asset_manager) {
1391}
1392
1393Theme::~Theme() = default;
1394
1395namespace {
1396
1397struct ThemeEntry {
1398 ApkAssetsCookie cookie;
1399 uint32_t type_spec_flags;
1400 Res_value value;
1401};
1402
1403struct ThemeType {
1404 int entry_count;
1405 ThemeEntry entries[0];
1406};
1407
1408constexpr size_t kTypeCount = std::numeric_limits<uint8_t>::max() + 1;
1409
1410} // namespace
1411
1412struct Theme::Package {
1413 // Each element of Type will be a dynamically sized object
1414 // allocated to have the entries stored contiguously with the Type.
1415 std::array<util::unique_cptr<ThemeType>, kTypeCount> types;
1416};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001417
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001418base::expected<std::monostate, NullOrIOError> Theme::ApplyStyle(uint32_t resid, bool force) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001419 ATRACE_NAME("Theme::ApplyStyle");
Adam Lesinski7ad11102016-10-28 16:39:15 -07001420
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001421 auto bag = asset_manager_->GetBag(resid);
1422 if (!bag.has_value()) {
1423 return base::unexpected(bag.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001424 }
1425
1426 // Merge the flags from this style.
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001427 type_spec_flags_ |= (*bag)->type_spec_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001428
Adam Lesinski30080e22017-10-16 16:18:09 -07001429 int last_type_idx = -1;
1430 int last_package_idx = -1;
1431 Package* last_package = nullptr;
1432 ThemeType* last_type = nullptr;
1433
1434 // Iterate backwards, because each bag is sorted in ascending key ID order, meaning we will only
1435 // need to perform one resize per type.
1436 using reverse_bag_iterator = std::reverse_iterator<const ResolvedBag::Entry*>;
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001437 const auto rbegin = reverse_bag_iterator(begin(*bag));
1438 for (auto it = reverse_bag_iterator(end(*bag)); it != rbegin; ++it) {
1439 const uint32_t attr_resid = it->key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001440
Adam Lesinski30080e22017-10-16 16:18:09 -07001441 // If the resource ID passed in is not a style, the key can be some other identifier that is not
1442 // a resource ID. We should fail fast instead of operating with strange resource IDs.
Adam Lesinski929d6512017-01-16 19:11:19 -08001443 if (!is_valid_resid(attr_resid)) {
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001444 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001445 }
1446
Adam Lesinski30080e22017-10-16 16:18:09 -07001447 // We don't use the 0-based index for the type so that we can avoid doing ID validation
1448 // upon lookup. Instead, we keep space for the type ID 0 in our data structures. Since
1449 // the construction of this type is guarded with a resource ID check, it will never be
1450 // populated, and querying type ID 0 will always fail.
1451 const int package_idx = get_package_id(attr_resid);
1452 const int type_idx = get_type_id(attr_resid);
1453 const int entry_idx = get_entry_id(attr_resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001454
Adam Lesinski30080e22017-10-16 16:18:09 -07001455 if (last_package_idx != package_idx) {
1456 std::unique_ptr<Package>& package = packages_[package_idx];
1457 if (package == nullptr) {
1458 package.reset(new Package());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001459 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001460 last_package_idx = package_idx;
1461 last_package = package.get();
1462 last_type_idx = -1;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001463 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001464
1465 if (last_type_idx != type_idx) {
1466 util::unique_cptr<ThemeType>& type = last_package->types[type_idx];
1467 if (type == nullptr) {
1468 // Allocate enough memory to contain this entry_idx. Since we're iterating in reverse over
1469 // a sorted list of attributes, this shouldn't be resized again during this method call.
1470 type.reset(reinterpret_cast<ThemeType*>(
1471 calloc(sizeof(ThemeType) + (entry_idx + 1) * sizeof(ThemeEntry), 1)));
1472 type->entry_count = entry_idx + 1;
1473 } else if (entry_idx >= type->entry_count) {
1474 // Reallocate the memory to contain this entry_idx. Since we're iterating in reverse over
1475 // a sorted list of attributes, this shouldn't be resized again during this method call.
1476 const int new_count = entry_idx + 1;
1477 type.reset(reinterpret_cast<ThemeType*>(
1478 realloc(type.release(), sizeof(ThemeType) + (new_count * sizeof(ThemeEntry)))));
1479
1480 // Clear out the newly allocated space (which isn't zeroed).
1481 memset(type->entries + type->entry_count, 0,
1482 (new_count - type->entry_count) * sizeof(ThemeEntry));
1483 type->entry_count = new_count;
1484 }
1485 last_type_idx = type_idx;
1486 last_type = type.get();
1487 }
1488
1489 ThemeEntry& entry = last_type->entries[entry_idx];
1490 if (force || (entry.value.dataType == Res_value::TYPE_NULL &&
1491 entry.value.data != Res_value::DATA_NULL_EMPTY)) {
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001492 entry.cookie = it->cookie;
1493 entry.type_spec_flags |= (*bag)->type_spec_flags;
1494 entry.value = it->value;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001495 }
1496 }
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001497 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001498}
1499
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001500std::optional<AssetManager2::SelectedValue> Theme::GetAttribute(uint32_t resid) const {
1501
Adam Lesinski30080e22017-10-16 16:18:09 -07001502 int cnt = 20;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001503 uint32_t type_spec_flags = 0u;
Adam Lesinski30080e22017-10-16 16:18:09 -07001504 do {
1505 const int package_idx = get_package_id(resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001506 const Package* package = packages_[package_idx].get();
Adam Lesinski30080e22017-10-16 16:18:09 -07001507 if (package != nullptr) {
1508 // The themes are constructed with a 1-based type ID, so no need to decrement here.
1509 const int type_idx = get_type_id(resid);
1510 const ThemeType* type = package->types[type_idx].get();
1511 if (type != nullptr) {
1512 const int entry_idx = get_entry_id(resid);
1513 if (entry_idx < type->entry_count) {
1514 const ThemeEntry& entry = type->entries[entry_idx];
1515 type_spec_flags |= entry.type_spec_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001516
Adam Lesinski30080e22017-10-16 16:18:09 -07001517 if (entry.value.dataType == Res_value::TYPE_ATTRIBUTE) {
1518 if (cnt > 0) {
1519 cnt--;
1520 resid = entry.value.data;
1521 continue;
1522 }
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001523 return std::nullopt;
Adam Lesinski30080e22017-10-16 16:18:09 -07001524 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001525
Adam Lesinski30080e22017-10-16 16:18:09 -07001526 // @null is different than @empty.
1527 if (entry.value.dataType == Res_value::TYPE_NULL &&
1528 entry.value.data != Res_value::DATA_NULL_EMPTY) {
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001529 return std::nullopt;
Adam Lesinski30080e22017-10-16 16:18:09 -07001530 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001531
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001532 return AssetManager2::SelectedValue(entry.value.dataType, entry.value.data, entry.cookie,
1533 type_spec_flags, 0U /* resid */, {} /* config */);
Adam Lesinskida431a22016-12-29 16:08:16 -05001534 }
Adam Lesinskida431a22016-12-29 16:08:16 -05001535 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001536 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001537 break;
1538 } while (true);
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001539 return std::nullopt;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001540}
1541
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001542base::expected<std::monostate, NullOrIOError> Theme::ResolveAttributeReference(
1543 AssetManager2::SelectedValue& value) const {
1544 if (value.type != Res_value::TYPE_ATTRIBUTE) {
1545 return asset_manager_->ResolveReference(value);
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001546 }
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001547
1548 std::optional<AssetManager2::SelectedValue> result = GetAttribute(value.data);
1549 if (!result.has_value()) {
1550 return base::unexpected(std::nullopt);
1551 }
1552
Ryan Mitchell87e89542020-10-05 14:24:35 -07001553 auto resolve_result = asset_manager_->ResolveReference(*result, true /* cache_value */);
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001554 if (resolve_result.has_value()) {
1555 result->flags |= value.flags;
1556 value = *result;
1557 }
1558 return resolve_result;
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001559}
1560
Adam Lesinski7ad11102016-10-28 16:39:15 -07001561void Theme::Clear() {
1562 type_spec_flags_ = 0u;
1563 for (std::unique_ptr<Package>& package : packages_) {
1564 package.reset();
1565 }
1566}
1567
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001568base::expected<std::monostate, IOError> Theme::SetTo(const Theme& o) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001569 if (this == &o) {
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001570 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001571 }
1572
Adam Lesinski7ad11102016-10-28 16:39:15 -07001573 type_spec_flags_ = o.type_spec_flags_;
1574
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001575 if (asset_manager_ == o.asset_manager_) {
1576 // The theme comes from the same asset manager so all theme data can be copied exactly
1577 for (size_t p = 0; p < packages_.size(); p++) {
1578 const Package *package = o.packages_[p].get();
1579 if (package == nullptr) {
1580 // The other theme doesn't have this package, clear ours.
1581 packages_[p].reset();
Adam Lesinski7ad11102016-10-28 16:39:15 -07001582 continue;
1583 }
1584
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001585 if (packages_[p] == nullptr) {
1586 // The other theme has this package, but we don't. Make one.
1587 packages_[p].reset(new Package());
1588 }
1589
1590 for (size_t t = 0; t < package->types.size(); t++) {
1591 const ThemeType *type = package->types[t].get();
1592 if (type == nullptr) {
1593 // The other theme doesn't have this type, clear ours.
1594 packages_[p]->types[t].reset();
1595 continue;
1596 }
1597
1598 // Create a new type and update it to theirs.
1599 const size_t type_alloc_size = sizeof(ThemeType) + (type->entry_count * sizeof(ThemeEntry));
1600 void *copied_data = malloc(type_alloc_size);
1601 memcpy(copied_data, type, type_alloc_size);
1602 packages_[p]->types[t].reset(reinterpret_cast<ThemeType *>(copied_data));
1603 }
1604 }
1605 } else {
1606 std::map<ApkAssetsCookie, ApkAssetsCookie> src_to_dest_asset_cookies;
1607 typedef std::map<int, int> SourceToDestinationRuntimePackageMap;
1608 std::map<ApkAssetsCookie, SourceToDestinationRuntimePackageMap> src_asset_cookie_id_map;
1609
Ryan Mitchell93bca972019-03-08 17:26:28 -08001610 // Determine which ApkAssets are loaded in both theme AssetManagers.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001611 std::vector<const ApkAssets*> src_assets = o.asset_manager_->GetApkAssets();
1612 for (size_t i = 0; i < src_assets.size(); i++) {
1613 const ApkAssets* src_asset = src_assets[i];
1614
1615 std::vector<const ApkAssets*> dest_assets = asset_manager_->GetApkAssets();
1616 for (size_t j = 0; j < dest_assets.size(); j++) {
1617 const ApkAssets* dest_asset = dest_assets[j];
1618
Ryan Mitchell93bca972019-03-08 17:26:28 -08001619 // Map the runtime package of the source apk asset to the destination apk asset.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001620 if (src_asset->GetPath() == dest_asset->GetPath()) {
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001621 const auto& src_packages = src_asset->GetLoadedArsc()->GetPackages();
1622 const auto& dest_packages = dest_asset->GetLoadedArsc()->GetPackages();
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001623
1624 SourceToDestinationRuntimePackageMap package_map;
1625
1626 // The source and destination package should have the same number of packages loaded in
1627 // the same order.
1628 const size_t N = src_packages.size();
1629 CHECK(N == dest_packages.size())
1630 << " LoadedArsc " << src_asset->GetPath() << " differs number of packages.";
1631 for (size_t p = 0; p < N; p++) {
1632 auto& src_package = src_packages[p];
1633 auto& dest_package = dest_packages[p];
1634 CHECK(src_package->GetPackageName() == dest_package->GetPackageName())
1635 << " Package " << src_package->GetPackageName() << " differs in load order.";
1636
1637 int src_package_id = o.asset_manager_->GetAssignedPackageId(src_package.get());
1638 int dest_package_id = asset_manager_->GetAssignedPackageId(dest_package.get());
1639 package_map[src_package_id] = dest_package_id;
1640 }
1641
Ryan Mitchell93bca972019-03-08 17:26:28 -08001642 src_to_dest_asset_cookies.insert(std::make_pair(i, j));
1643 src_asset_cookie_id_map.insert(std::make_pair(i, package_map));
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001644 break;
1645 }
1646 }
1647 }
1648
Ryan Mitchell93bca972019-03-08 17:26:28 -08001649 // Reset the data in the destination theme.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001650 for (size_t p = 0; p < packages_.size(); p++) {
1651 if (packages_[p] != nullptr) {
1652 packages_[p].reset();
1653 }
1654 }
1655
1656 for (size_t p = 0; p < packages_.size(); p++) {
1657 const Package *package = o.packages_[p].get();
1658 if (package == nullptr) {
1659 continue;
1660 }
1661
1662 for (size_t t = 0; t < package->types.size(); t++) {
1663 const ThemeType *type = package->types[t].get();
1664 if (type == nullptr) {
1665 continue;
1666 }
1667
1668 for (size_t e = 0; e < type->entry_count; e++) {
1669 const ThemeEntry &entry = type->entries[e];
1670 if (entry.value.dataType == Res_value::TYPE_NULL &&
1671 entry.value.data != Res_value::DATA_NULL_EMPTY) {
1672 continue;
1673 }
1674
Ryan Mitchell93bca972019-03-08 17:26:28 -08001675 bool is_reference = (entry.value.dataType == Res_value::TYPE_ATTRIBUTE
1676 || entry.value.dataType == Res_value::TYPE_REFERENCE
1677 || entry.value.dataType == Res_value::TYPE_DYNAMIC_ATTRIBUTE
1678 || entry.value.dataType == Res_value::TYPE_DYNAMIC_REFERENCE)
1679 && entry.value.data != 0x0;
Ryan Mitchellb85d9b22018-11-19 12:11:38 -08001680
Ryan Mitchell93bca972019-03-08 17:26:28 -08001681 // If the attribute value represents an attribute or reference, the package id of the
1682 // value needs to be rewritten to the package id of the value in the destination.
1683 uint32_t attribute_data = entry.value.data;
1684 if (is_reference) {
1685 // Determine the package id of the reference in the destination AssetManager.
Ryan Mitchellb85d9b22018-11-19 12:11:38 -08001686 auto value_package_map = src_asset_cookie_id_map.find(entry.cookie);
1687 if (value_package_map == src_asset_cookie_id_map.end()) {
1688 continue;
1689 }
1690
1691 auto value_dest_package = value_package_map->second.find(
1692 get_package_id(entry.value.data));
1693 if (value_dest_package == value_package_map->second.end()) {
1694 continue;
1695 }
1696
Ryan Mitchell93bca972019-03-08 17:26:28 -08001697 attribute_data = fix_package_id(entry.value.data, value_dest_package->second);
1698 }
1699
1700 // Find the cookie of the value in the destination. If the source apk is not loaded in the
1701 // destination, only copy resources that do not reference resources in the source.
1702 ApkAssetsCookie data_dest_cookie;
1703 auto value_dest_cookie = src_to_dest_asset_cookies.find(entry.cookie);
1704 if (value_dest_cookie != src_to_dest_asset_cookies.end()) {
1705 data_dest_cookie = value_dest_cookie->second;
1706 } else {
1707 if (is_reference || entry.value.dataType == Res_value::TYPE_STRING) {
1708 continue;
1709 } else {
1710 data_dest_cookie = 0x0;
1711 }
Ryan Mitchellb85d9b22018-11-19 12:11:38 -08001712 }
1713
1714 // The package id of the attribute needs to be rewritten to the package id of the
Ryan Mitchell93bca972019-03-08 17:26:28 -08001715 // attribute in the destination.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001716 int attribute_dest_package_id = p;
1717 if (attribute_dest_package_id != 0x01) {
Ryan Mitchell93bca972019-03-08 17:26:28 -08001718 // Find the cookie of the attribute resource id in the source AssetManager
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001719 base::expected<FindEntryResult, NullOrIOError> attribute_entry_result =
Ryan Mitchella55dc2e2019-01-24 10:58:23 -08001720 o.asset_manager_->FindEntry(make_resid(p, t, e), 0 /* density_override */ ,
1721 true /* stop_at_first_match */,
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001722 true /* ignore_configuration */);
1723 if (UNLIKELY(IsIOError(attribute_entry_result))) {
1724 return base::unexpected(GetIOError(attribute_entry_result.error()));
1725 }
1726 if (!attribute_entry_result.has_value()) {
1727 continue;
1728 }
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001729
Ryan Mitchell93bca972019-03-08 17:26:28 -08001730 // Determine the package id of the attribute in the destination AssetManager.
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001731 auto attribute_package_map = src_asset_cookie_id_map.find(
1732 attribute_entry_result->cookie);
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001733 if (attribute_package_map == src_asset_cookie_id_map.end()) {
1734 continue;
1735 }
1736 auto attribute_dest_package = attribute_package_map->second.find(
1737 attribute_dest_package_id);
1738 if (attribute_dest_package == attribute_package_map->second.end()) {
1739 continue;
1740 }
1741 attribute_dest_package_id = attribute_dest_package->second;
1742 }
1743
Ryan Mitchell93bca972019-03-08 17:26:28 -08001744 // Lazily instantiate the destination package.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001745 std::unique_ptr<Package>& dest_package = packages_[attribute_dest_package_id];
1746 if (dest_package == nullptr) {
1747 dest_package.reset(new Package());
1748 }
1749
Ryan Mitchell93bca972019-03-08 17:26:28 -08001750 // Lazily instantiate and resize the destination type.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001751 util::unique_cptr<ThemeType>& dest_type = dest_package->types[t];
1752 if (dest_type == nullptr || dest_type->entry_count < type->entry_count) {
1753 const size_t type_alloc_size = sizeof(ThemeType)
1754 + (type->entry_count * sizeof(ThemeEntry));
1755 void* dest_data = malloc(type_alloc_size);
1756 memset(dest_data, 0, type->entry_count * sizeof(ThemeEntry));
1757
Ryan Mitchell93bca972019-03-08 17:26:28 -08001758 // Copy the existing destination type values if the type is resized.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001759 if (dest_type != nullptr) {
1760 memcpy(dest_data, type, sizeof(ThemeType)
1761 + (dest_type->entry_count * sizeof(ThemeEntry)));
1762 }
1763
1764 dest_type.reset(reinterpret_cast<ThemeType *>(dest_data));
1765 dest_type->entry_count = type->entry_count;
1766 }
1767
Ryan Mitchell93bca972019-03-08 17:26:28 -08001768 dest_type->entries[e].cookie = data_dest_cookie;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001769 dest_type->entries[e].value.dataType = entry.value.dataType;
Ryan Mitchell93bca972019-03-08 17:26:28 -08001770 dest_type->entries[e].value.data = attribute_data;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001771 dest_type->entries[e].type_spec_flags = entry.type_spec_flags;
1772 }
1773 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001774 }
1775 }
Ryan Mitchellc75c2e02020-08-17 08:42:48 -07001776 return {};
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001777}
1778
1779void Theme::Dump() const {
1780 base::ScopedLogSeverity _log(base::INFO);
1781 LOG(INFO) << base::StringPrintf("Theme(this=%p, AssetManager2=%p)", this, asset_manager_);
1782
1783 for (int p = 0; p < packages_.size(); p++) {
1784 auto& package = packages_[p];
1785 if (package == nullptr) {
1786 continue;
1787 }
1788
1789 for (int t = 0; t < package->types.size(); t++) {
1790 auto& type = package->types[t];
1791 if (type == nullptr) {
1792 continue;
1793 }
1794
1795 for (int e = 0; e < type->entry_count; e++) {
1796 auto& entry = type->entries[e];
1797 if (entry.value.dataType == Res_value::TYPE_NULL &&
1798 entry.value.data != Res_value::DATA_NULL_EMPTY) {
1799 continue;
1800 }
1801
1802 LOG(INFO) << base::StringPrintf(" entry(0x%08x)=(0x%08x) type=(0x%02x), cookie(%d)",
1803 make_resid(p, t, e), entry.value.data,
1804 entry.value.dataType, entry.cookie);
1805 }
1806 }
1807 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001808}
1809
1810} // namespace android