blob: 03ab62f48870b9e0dd8ce083d9583942506fd4a4 [file] [log] [blame]
Adam Lesinski7ad11102016-10-28 16:39:15 -07001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define ATRACE_TAG ATRACE_TAG_RESOURCES
18
19#include "androidfw/AssetManager2.h"
20
y57cd1952018-04-12 14:26:23 -070021#include <algorithm>
Adam Lesinski30080e22017-10-16 16:18:09 -070022#include <iterator>
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -070023#include <map>
Winson2f3669b2019-01-11 11:28:34 -080024#include <set>
Adam Lesinski0c405242017-01-13 20:47:26 -080025
Adam Lesinski7ad11102016-10-28 16:39:15 -070026#include "android-base/logging.h"
27#include "android-base/stringprintf.h"
Ryan Mitchell8a891d82019-07-01 09:48:23 -070028#include "androidfw/ResourceUtils.h"
Ryan Mitchell31b11052019-06-13 13:47:26 -070029#include "androidfw/Util.h"
Adam Lesinski7ad11102016-10-28 16:39:15 -070030#include "utils/ByteOrder.h"
31#include "utils/Trace.h"
32
33#ifdef _WIN32
34#ifdef ERROR
35#undef ERROR
36#endif
37#endif
38
39namespace android {
40
Ryan Mitchell80094e32020-11-16 23:08:18 +000041namespace {
42
43using EntryValue = std::variant<Res_value, incfs::verified_map_ptr<ResTable_map_entry>>;
44
45base::expected<EntryValue, IOError> GetEntryValue(
46 incfs::verified_map_ptr<ResTable_entry> table_entry) {
47 const uint16_t entry_size = dtohs(table_entry->size);
48
49 // Check if the entry represents a bag value.
50 if (entry_size >= sizeof(ResTable_map_entry) &&
51 (dtohs(table_entry->flags) & ResTable_entry::FLAG_COMPLEX)) {
52 const auto map_entry = table_entry.convert<ResTable_map_entry>();
53 if (!map_entry) {
54 return base::unexpected(IOError::PAGES_MISSING);
55 }
56 return map_entry.verified();
57 }
58
59 // The entry represents a non-bag value.
60 const auto entry_value = table_entry.offset(entry_size).convert<Res_value>();
61 if (!entry_value) {
62 return base::unexpected(IOError::PAGES_MISSING);
63 }
64 Res_value value;
65 value.copyFrom_dtoh(entry_value.value());
66 return value;
67}
68
69} // namespace
70
Adam Lesinskibebfcc42018-02-12 14:27:46 -080071struct FindEntryResult {
Ryan Mitchell80094e32020-11-16 23:08:18 +000072 // The cookie representing the ApkAssets in which the value resides.
73 ApkAssetsCookie cookie;
74
75 // The value of the resource table entry. Either an android::Res_value for non-bag types or an
76 // incfs::verified_map_ptr<ResTable_map_entry> for bag types.
77 EntryValue entry;
Adam Lesinskibebfcc42018-02-12 14:27:46 -080078
79 // The configuration for which the resulting entry was defined. This is already swapped to host
80 // endianness.
81 ResTable_config config;
82
83 // The bitmask of configuration axis with which the resource value varies.
84 uint32_t type_flags;
85
86 // The dynamic package ID map for the package from which this resource came from.
87 const DynamicRefTable* dynamic_ref_table;
88
Ryan Mitchell8a891d82019-07-01 09:48:23 -070089 // The package name of the resource.
90 const std::string* package_name;
91
Adam Lesinskibebfcc42018-02-12 14:27:46 -080092 // The string pool reference to the type's name. This uses a different string pool than
93 // the global string pool, but this is hidden from the caller.
94 StringPoolRef type_string_ref;
95
96 // The string pool reference to the entry's name. This uses a different string pool than
97 // the global string pool, but this is hidden from the caller.
98 StringPoolRef entry_string_ref;
99};
100
Ryan Mitchellb894c272020-02-12 10:31:44 -0800101AssetManager2::AssetManager2() {
Adam Lesinski970bd8d2017-09-25 13:21:55 -0700102 memset(&configuration_, 0, sizeof(configuration_));
103}
Adam Lesinski7ad11102016-10-28 16:39:15 -0700104
105bool AssetManager2::SetApkAssets(const std::vector<const ApkAssets*>& apk_assets,
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800106 bool invalidate_caches) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700107 apk_assets_ = apk_assets;
Adam Lesinskida431a22016-12-29 16:08:16 -0500108 BuildDynamicRefTable();
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800109 RebuildFilterList();
Adam Lesinski7ad11102016-10-28 16:39:15 -0700110 if (invalidate_caches) {
111 InvalidateCaches(static_cast<uint32_t>(-1));
112 }
113 return true;
114}
115
Adam Lesinskida431a22016-12-29 16:08:16 -0500116void AssetManager2::BuildDynamicRefTable() {
117 package_groups_.clear();
118 package_ids_.fill(0xff);
119
Ryan Mitchellb894c272020-02-12 10:31:44 -0800120 // A mapping from apk assets path to the runtime package id of its first loaded package.
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700121 std::unordered_map<std::string, uint8_t> apk_assets_package_ids;
122
Ryan Mitchell824cc492020-02-12 10:48:14 -0800123 // Overlay resources are not directly referenced by an application so their resource ids
124 // can change throughout the application's lifetime. Assign overlay package ids last.
125 std::vector<const ApkAssets*> sorted_apk_assets(apk_assets_);
126 std::stable_partition(sorted_apk_assets.begin(), sorted_apk_assets.end(), [](const ApkAssets* a) {
127 return !a->IsOverlay();
128 });
129
130 // The assets cookie must map to the position of the apk assets in the unsorted apk assets list.
131 std::unordered_map<const ApkAssets*, ApkAssetsCookie> apk_assets_cookies;
132 apk_assets_cookies.reserve(apk_assets_.size());
133 for (size_t i = 0, n = apk_assets_.size(); i < n; i++) {
134 apk_assets_cookies[apk_assets_[i]] = static_cast<ApkAssetsCookie>(i);
135 }
136
Ryan Mitchellb894c272020-02-12 10:31:44 -0800137 // 0x01 is reserved for the android package.
138 int next_package_id = 0x02;
Ryan Mitchell824cc492020-02-12 10:48:14 -0800139 for (const ApkAssets* apk_assets : sorted_apk_assets) {
Ryan Mitchellb894c272020-02-12 10:31:44 -0800140 const LoadedArsc* loaded_arsc = apk_assets->GetLoadedArsc();
Ryan Mitchellb894c272020-02-12 10:31:44 -0800141 for (const std::unique_ptr<const LoadedPackage>& package : loaded_arsc->GetPackages()) {
142 // Get the package ID or assign one if a shared library.
143 int package_id;
144 if (package->IsDynamic()) {
145 package_id = next_package_id++;
146 } else {
147 package_id = package->GetPackageId();
Adam Lesinskida431a22016-12-29 16:08:16 -0500148 }
149
150 // Add the mapping for package ID to index if not present.
151 uint8_t idx = package_ids_[package_id];
152 if (idx == 0xff) {
153 package_ids_[package_id] = idx = static_cast<uint8_t>(package_groups_.size());
154 package_groups_.push_back({});
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700155
156 if (apk_assets->IsOverlay()) {
157 // The target package must precede the overlay package in the apk assets paths in order
158 // to take effect.
159 const auto& loaded_idmap = apk_assets->GetLoadedIdmap();
Ryan Mitchell0699f1d2020-12-03 15:41:42 -0800160 auto target_package_iter = apk_assets_package_ids.find(
161 std::string(loaded_idmap->TargetApkPath()));
Ryan Mitchellee4a5642019-10-16 08:32:55 -0700162 if (target_package_iter == apk_assets_package_ids.end()) {
163 LOG(INFO) << "failed to find target package for overlay "
164 << loaded_idmap->OverlayApkPath();
165 } else {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700166 const uint8_t target_package_id = target_package_iter->second;
167 const uint8_t target_idx = package_ids_[target_package_id];
168 CHECK(target_idx != 0xff) << "overlay added to apk_assets_package_ids but does not"
169 << " have an assigned package group";
170
171 PackageGroup& target_package_group = package_groups_[target_idx];
172
Ryan Mitchell824cc492020-02-12 10:48:14 -0800173 // Create a special dynamic reference table for the overlay to rewrite references to
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700174 // overlay resources as references to the target resources they overlay.
175 auto overlay_table = std::make_shared<OverlayDynamicRefTable>(
176 loaded_idmap->GetOverlayDynamicRefTable(target_package_id));
177 package_groups_.back().dynamic_ref_table = overlay_table;
178
179 // Add the overlay resource map to the target package's set of overlays.
180 target_package_group.overlays_.push_back(
181 ConfiguredOverlay{loaded_idmap->GetTargetResourcesMap(target_package_id,
182 overlay_table.get()),
Ryan Mitchell824cc492020-02-12 10:48:14 -0800183 apk_assets_cookies[apk_assets]});
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700184 }
185 }
186
187 DynamicRefTable* ref_table = package_groups_.back().dynamic_ref_table.get();
188 ref_table->mAssignedPackageId = package_id;
189 ref_table->mAppAsLib = package->IsDynamic() && package->GetPackageId() == 0x7f;
Adam Lesinskida431a22016-12-29 16:08:16 -0500190 }
191 PackageGroup* package_group = &package_groups_[idx];
192
193 // Add the package and to the set of packages with the same ID.
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800194 package_group->packages_.push_back(ConfiguredPackage{package.get(), {}});
Ryan Mitchell824cc492020-02-12 10:48:14 -0800195 package_group->cookies_.push_back(apk_assets_cookies[apk_assets]);
Adam Lesinskida431a22016-12-29 16:08:16 -0500196
197 // Add the package name -> build time ID mappings.
198 for (const DynamicPackageEntry& entry : package->GetDynamicPackageMap()) {
199 String16 package_name(entry.package_name.c_str(), entry.package_name.size());
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700200 package_group->dynamic_ref_table->mEntries.replaceValueFor(
Adam Lesinskida431a22016-12-29 16:08:16 -0500201 package_name, static_cast<uint8_t>(entry.package_id));
202 }
Ryan Mitchellb894c272020-02-12 10:31:44 -0800203
204 apk_assets_package_ids.insert(std::make_pair(apk_assets->GetPath(), package_id));
Adam Lesinskida431a22016-12-29 16:08:16 -0500205 }
206 }
207
208 // Now assign the runtime IDs so that we have a build-time to runtime ID map.
209 const auto package_groups_end = package_groups_.end();
210 for (auto iter = package_groups_.begin(); iter != package_groups_end; ++iter) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800211 const std::string& package_name = iter->packages_[0].loaded_package_->GetPackageName();
Adam Lesinskida431a22016-12-29 16:08:16 -0500212 for (auto iter2 = package_groups_.begin(); iter2 != package_groups_end; ++iter2) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700213 iter2->dynamic_ref_table->addMapping(String16(package_name.c_str(), package_name.size()),
214 iter->dynamic_ref_table->mAssignedPackageId);
Adam Lesinskida431a22016-12-29 16:08:16 -0500215 }
216 }
217}
218
219void AssetManager2::DumpToLog() const {
220 base::ScopedLogSeverity _log(base::INFO);
221
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800222 LOG(INFO) << base::StringPrintf("AssetManager2(this=%p)", this);
223
Adam Lesinskida431a22016-12-29 16:08:16 -0500224 std::string list;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800225 for (const auto& apk_assets : apk_assets_) {
226 base::StringAppendF(&list, "%s,", apk_assets->GetPath().c_str());
227 }
228 LOG(INFO) << "ApkAssets: " << list;
229
230 list = "";
Adam Lesinskida431a22016-12-29 16:08:16 -0500231 for (size_t i = 0; i < package_ids_.size(); i++) {
232 if (package_ids_[i] != 0xff) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800233 base::StringAppendF(&list, "%02x -> %d, ", (int)i, package_ids_[i]);
Adam Lesinskida431a22016-12-29 16:08:16 -0500234 }
235 }
236 LOG(INFO) << "Package ID map: " << list;
237
Adam Lesinski0dd36992018-01-25 15:38:38 -0800238 for (const auto& package_group: package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800239 list = "";
240 for (const auto& package : package_group.packages_) {
241 const LoadedPackage* loaded_package = package.loaded_package_;
242 base::StringAppendF(&list, "%s(%02x%s), ", loaded_package->GetPackageName().c_str(),
243 loaded_package->GetPackageId(),
244 (loaded_package->IsDynamic() ? " dynamic" : ""));
245 }
246 LOG(INFO) << base::StringPrintf("PG (%02x): ",
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700247 package_group.dynamic_ref_table->mAssignedPackageId)
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800248 << list;
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800249
250 for (size_t i = 0; i < 256; i++) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700251 if (package_group.dynamic_ref_table->mLookupTable[i] != 0) {
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800252 LOG(INFO) << base::StringPrintf(" e[0x%02x] -> 0x%02x", (uint8_t) i,
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700253 package_group.dynamic_ref_table->mLookupTable[i]);
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800254 }
255 }
Adam Lesinskida431a22016-12-29 16:08:16 -0500256 }
257}
Adam Lesinski7ad11102016-10-28 16:39:15 -0700258
259const ResStringPool* AssetManager2::GetStringPoolForCookie(ApkAssetsCookie cookie) const {
260 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
261 return nullptr;
262 }
263 return apk_assets_[cookie]->GetLoadedArsc()->GetStringPool();
264}
265
Adam Lesinskida431a22016-12-29 16:08:16 -0500266const DynamicRefTable* AssetManager2::GetDynamicRefTableForPackage(uint32_t package_id) const {
267 if (package_id >= package_ids_.size()) {
268 return nullptr;
269 }
270
271 const size_t idx = package_ids_[package_id];
272 if (idx == 0xff) {
273 return nullptr;
274 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700275 return package_groups_[idx].dynamic_ref_table.get();
Adam Lesinskida431a22016-12-29 16:08:16 -0500276}
277
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700278std::shared_ptr<const DynamicRefTable> AssetManager2::GetDynamicRefTableForCookie(
279 ApkAssetsCookie cookie) const {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800280 for (const PackageGroup& package_group : package_groups_) {
281 for (const ApkAssetsCookie& package_cookie : package_group.cookies_) {
282 if (package_cookie == cookie) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700283 return package_group.dynamic_ref_table;
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800284 }
285 }
286 }
287 return nullptr;
288}
289
MÃ¥rten Kongstadc92c4dd2019-02-05 01:29:59 +0100290const std::unordered_map<std::string, std::string>*
291 AssetManager2::GetOverlayableMapForPackage(uint32_t package_id) const {
292
293 if (package_id >= package_ids_.size()) {
294 return nullptr;
295 }
296
297 const size_t idx = package_ids_[package_id];
298 if (idx == 0xff) {
299 return nullptr;
300 }
301
302 const PackageGroup& package_group = package_groups_[idx];
Ryan Mitchell80094e32020-11-16 23:08:18 +0000303 if (package_group.packages_.empty()) {
MÃ¥rten Kongstadc92c4dd2019-02-05 01:29:59 +0100304 return nullptr;
305 }
306
307 const auto loaded_package = package_group.packages_[0].loaded_package_;
308 return &loaded_package->GetOverlayableMap();
309}
310
Ryan Mitchell2e394222019-08-28 12:10:51 -0700311bool AssetManager2::GetOverlayablesToString(const android::StringPiece& package_name,
312 std::string* out) const {
313 uint8_t package_id = 0U;
314 for (const auto& apk_assets : apk_assets_) {
315 const LoadedArsc* loaded_arsc = apk_assets->GetLoadedArsc();
316 if (loaded_arsc == nullptr) {
317 continue;
318 }
319
320 const auto& loaded_packages = loaded_arsc->GetPackages();
321 if (loaded_packages.empty()) {
322 continue;
323 }
324
325 const auto& loaded_package = loaded_packages[0];
326 if (loaded_package->GetPackageName() == package_name) {
327 package_id = GetAssignedPackageId(loaded_package.get());
328 break;
329 }
330 }
331
332 if (package_id == 0U) {
333 ANDROID_LOG(ERROR) << base::StringPrintf("No package with name '%s", package_name.data());
334 return false;
335 }
336
337 const size_t idx = package_ids_[package_id];
338 if (idx == 0xff) {
339 return false;
340 }
341
342 std::string output;
343 for (const ConfiguredPackage& package : package_groups_[idx].packages_) {
344 const LoadedPackage* loaded_package = package.loaded_package_;
345 for (auto it = loaded_package->begin(); it != loaded_package->end(); it++) {
346 const OverlayableInfo* info = loaded_package->GetOverlayableInfo(*it);
347 if (info != nullptr) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000348 auto res_name = GetResourceName(*it);
349 if (!res_name.has_value()) {
Ryan Mitchell2e394222019-08-28 12:10:51 -0700350 ANDROID_LOG(ERROR) << base::StringPrintf(
351 "Unable to retrieve name of overlayable resource 0x%08x", *it);
352 return false;
353 }
354
Ryan Mitchell80094e32020-11-16 23:08:18 +0000355 const std::string name = ToFormattedResourceString(*res_name);
Ryan Mitchell2e394222019-08-28 12:10:51 -0700356 output.append(base::StringPrintf(
357 "resource='%s' overlayable='%s' actor='%s' policy='0x%08x'\n",
358 name.c_str(), info->name.c_str(), info->actor.c_str(), info->policy_flags));
359 }
360 }
361 }
362
363 *out = std::move(output);
364 return true;
365}
366
Ryan Mitchell192400c2020-04-02 09:54:23 -0700367bool AssetManager2::ContainsAllocatedTable() const {
368 return std::find_if(apk_assets_.begin(), apk_assets_.end(),
369 std::mem_fn(&ApkAssets::IsTableAllocated)) != apk_assets_.end();
370}
371
Adam Lesinski7ad11102016-10-28 16:39:15 -0700372void AssetManager2::SetConfiguration(const ResTable_config& configuration) {
373 const int diff = configuration_.diff(configuration);
374 configuration_ = configuration;
375
376 if (diff) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800377 RebuildFilterList();
Adam Lesinski7ad11102016-10-28 16:39:15 -0700378 InvalidateCaches(static_cast<uint32_t>(diff));
379 }
380}
381
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700382std::set<std::string> AssetManager2::GetNonSystemOverlayPaths() const {
383 std::set<std::string> non_system_overlays;
Adam Lesinski0c405242017-01-13 20:47:26 -0800384 for (const PackageGroup& package_group : package_groups_) {
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800385 bool found_system_package = false;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800386 for (const ConfiguredPackage& package : package_group.packages_) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700387 if (package.loaded_package_->IsSystem()) {
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800388 found_system_package = true;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700389 break;
390 }
391 }
392
393 if (!found_system_package) {
394 for (const ConfiguredOverlay& overlay : package_group.overlays_) {
395 non_system_overlays.insert(apk_assets_[overlay.cookie]->GetPath());
396 }
397 }
398 }
399
400 return non_system_overlays;
401}
402
Ryan Mitchell80094e32020-11-16 23:08:18 +0000403base::expected<std::set<ResTable_config>, IOError> AssetManager2::GetResourceConfigurations(
404 bool exclude_system, bool exclude_mipmap) const {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700405 ATRACE_NAME("AssetManager::GetResourceConfigurations");
406 const auto non_system_overlays =
407 (exclude_system) ? GetNonSystemOverlayPaths() : std::set<std::string>();
408
409 std::set<ResTable_config> configurations;
410 for (const PackageGroup& package_group : package_groups_) {
411 for (size_t i = 0; i < package_group.packages_.size(); i++) {
412 const ConfiguredPackage& package = package_group.packages_[i];
413 if (exclude_system && package.loaded_package_->IsSystem()) {
Adam Lesinski0c405242017-01-13 20:47:26 -0800414 continue;
415 }
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800416
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700417 auto apk_assets = apk_assets_[package_group.cookies_[i]];
418 if (exclude_system && apk_assets->IsOverlay()
419 && non_system_overlays.find(apk_assets->GetPath()) == non_system_overlays.end()) {
420 // Exclude overlays that target system resources.
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800421 continue;
422 }
423
Ryan Mitchell80094e32020-11-16 23:08:18 +0000424 auto result = package.loaded_package_->CollectConfigurations(exclude_mipmap, &configurations);
425 if (UNLIKELY(!result.has_value())) {
426 return base::unexpected(result.error());
427 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800428 }
429 }
430 return configurations;
431}
432
433std::set<std::string> AssetManager2::GetResourceLocales(bool exclude_system,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800434 bool merge_equivalent_languages) const {
435 ATRACE_NAME("AssetManager::GetResourceLocales");
Adam Lesinski0c405242017-01-13 20:47:26 -0800436 std::set<std::string> locales;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700437 const auto non_system_overlays =
438 (exclude_system) ? GetNonSystemOverlayPaths() : std::set<std::string>();
439
Adam Lesinski0c405242017-01-13 20:47:26 -0800440 for (const PackageGroup& package_group : package_groups_) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700441 for (size_t i = 0; i < package_group.packages_.size(); i++) {
442 const ConfiguredPackage& package = package_group.packages_[i];
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800443 if (exclude_system && package.loaded_package_->IsSystem()) {
Adam Lesinski0c405242017-01-13 20:47:26 -0800444 continue;
445 }
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800446
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700447 auto apk_assets = apk_assets_[package_group.cookies_[i]];
448 if (exclude_system && apk_assets->IsOverlay()
449 && non_system_overlays.find(apk_assets->GetPath()) == non_system_overlays.end()) {
450 // Exclude overlays that target system resources.
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800451 continue;
452 }
453
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800454 package.loaded_package_->CollectLocales(merge_equivalent_languages, &locales);
Adam Lesinski0c405242017-01-13 20:47:26 -0800455 }
456 }
457 return locales;
458}
459
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800460std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename,
461 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700462 const std::string new_path = "assets/" + filename;
463 return OpenNonAsset(new_path, mode);
464}
465
466std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename, ApkAssetsCookie cookie,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800467 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700468 const std::string new_path = "assets/" + filename;
469 return OpenNonAsset(new_path, cookie, mode);
470}
471
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800472std::unique_ptr<AssetDir> AssetManager2::OpenDir(const std::string& dirname) const {
473 ATRACE_NAME("AssetManager::OpenDir");
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800474
475 std::string full_path = "assets/" + dirname;
476 std::unique_ptr<SortedVector<AssetDir::FileInfo>> files =
477 util::make_unique<SortedVector<AssetDir::FileInfo>>();
478
479 // Start from the back.
480 for (auto iter = apk_assets_.rbegin(); iter != apk_assets_.rend(); ++iter) {
481 const ApkAssets* apk_assets = *iter;
MÃ¥rten Kongstaddbf343b2019-02-21 07:54:18 +0100482 if (apk_assets->IsOverlay()) {
483 continue;
484 }
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800485
486 auto func = [&](const StringPiece& name, FileType type) {
487 AssetDir::FileInfo info;
488 info.setFileName(String8(name.data(), name.size()));
489 info.setFileType(type);
490 info.setSourceName(String8(apk_assets->GetPath().c_str()));
491 files->add(info);
492 };
493
Ryan Mitchellc07aa702020-03-10 13:49:12 -0700494 if (!apk_assets->GetAssetsProvider()->ForEachFile(full_path, func)) {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800495 return {};
496 }
497 }
498
499 std::unique_ptr<AssetDir> asset_dir = util::make_unique<AssetDir>();
500 asset_dir->setFileList(files.release());
501 return asset_dir;
502}
503
Adam Lesinski7ad11102016-10-28 16:39:15 -0700504// Search in reverse because that's how we used to do it and we need to preserve behaviour.
505// This is unfortunate, because ClassLoaders delegate to the parent first, so the order
506// is inconsistent for split APKs.
507std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
508 Asset::AccessMode mode,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800509 ApkAssetsCookie* out_cookie) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700510 for (int32_t i = apk_assets_.size() - 1; i >= 0; i--) {
MÃ¥rten Kongstaddbf343b2019-02-21 07:54:18 +0100511 // Prevent RRO from modifying assets and other entries accessed by file
512 // path. Explicitly asking for a path in a given package (denoted by a
513 // cookie) is still OK.
514 if (apk_assets_[i]->IsOverlay()) {
515 continue;
516 }
517
Ryan Mitchellc07aa702020-03-10 13:49:12 -0700518 std::unique_ptr<Asset> asset = apk_assets_[i]->GetAssetsProvider()->Open(filename, mode);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700519 if (asset) {
520 if (out_cookie != nullptr) {
521 *out_cookie = i;
522 }
523 return asset;
524 }
525 }
526
527 if (out_cookie != nullptr) {
528 *out_cookie = kInvalidCookie;
529 }
530 return {};
531}
532
533std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800534 ApkAssetsCookie cookie,
535 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700536 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
537 return {};
538 }
Ryan Mitchellc07aa702020-03-10 13:49:12 -0700539 return apk_assets_[cookie]->GetAssetsProvider()->Open(filename, mode);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700540}
541
Ryan Mitchell80094e32020-11-16 23:08:18 +0000542base::expected<FindEntryResult, NullOrIOError> AssetManager2::FindEntry(
543 uint32_t resid, uint16_t density_override, bool stop_at_first_match,
544 bool ignore_configuration) const {
545 const bool logging_enabled = resource_resolution_logging_enabled_;
546 if (UNLIKELY(logging_enabled)) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700547 // Clear the last logged resource resolution.
548 ResetResourceResolution();
549 last_resolution_.resid = resid;
550 }
551
Adam Lesinski7ad11102016-10-28 16:39:15 -0700552 // Might use this if density_override != 0.
553 ResTable_config density_override_config;
554
555 // Select our configuration or generate a density override configuration.
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800556 const ResTable_config* desired_config = &configuration_;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700557 if (density_override != 0 && density_override != configuration_.density) {
558 density_override_config = configuration_;
559 density_override_config.density = density_override;
560 desired_config = &density_override_config;
561 }
562
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700563 // Retrieve the package group from the package id of the resource id.
Ryan Mitchell80094e32020-11-16 23:08:18 +0000564 if (UNLIKELY(!is_valid_resid(resid))) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500565 LOG(ERROR) << base::StringPrintf("Invalid ID 0x%08x.", resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000566 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -0500567 }
568
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800569 const uint32_t package_id = get_package_id(resid);
570 const uint8_t type_idx = get_type_id(resid) - 1;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800571 const uint16_t entry_idx = get_entry_id(resid);
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700572 uint8_t package_idx = package_ids_[package_id];
Ryan Mitchell80094e32020-11-16 23:08:18 +0000573 if (UNLIKELY(package_idx == 0xff)) {
Ryan Mitchell2fe23472019-02-27 09:43:01 -0800574 ANDROID_LOG(ERROR) << base::StringPrintf("No package ID %02x found for ID 0x%08x.",
575 package_id, resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000576 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -0500577 }
578
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800579 const PackageGroup& package_group = package_groups_[package_idx];
Ryan Mitchell80094e32020-11-16 23:08:18 +0000580 auto result = FindEntryInternal(package_group, type_idx, entry_idx, *desired_config,
581 stop_at_first_match, ignore_configuration);
582 if (UNLIKELY(!result.has_value())) {
583 return base::unexpected(result.error());
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700584 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800585
Ryan Mitchell80094e32020-11-16 23:08:18 +0000586 if (!stop_at_first_match && !ignore_configuration && !apk_assets_[result->cookie]->IsLoader()) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700587 for (const auto& id_map : package_group.overlays_) {
588 auto overlay_entry = id_map.overlay_res_maps_.Lookup(resid);
589 if (!overlay_entry) {
590 // No id map entry exists for this target resource.
591 continue;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000592 }
593 if (overlay_entry.IsInlineValue()) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700594 // The target resource is overlaid by an inline value not represented by a resource.
Ryan Mitchell80094e32020-11-16 23:08:18 +0000595 result->entry = overlay_entry.GetInlineValue();
596 result->dynamic_ref_table = id_map.overlay_res_maps_.GetOverlayDynamicRefTable();
597 result->cookie = id_map.cookie;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700598 continue;
599 }
600
Ryan Mitchell80094e32020-11-16 23:08:18 +0000601 auto overlay_result = FindEntry(overlay_entry.GetResourceId(), density_override,
602 false /* stop_at_first_match */,
603 false /* ignore_configuration */);
604 if (UNLIKELY(IsIOError(overlay_result))) {
605 return base::unexpected(overlay_result.error());
606 }
607 if (!overlay_result.has_value()) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700608 continue;
609 }
610
Ryan Mitchell80094e32020-11-16 23:08:18 +0000611 if (!overlay_result->config.isBetterThan(result->config, desired_config)
612 && overlay_result->config.compare(result->config) != 0) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700613 // The configuration of the entry for the overlay must be equal to or better than the target
614 // configuration to be chosen as the better value.
615 continue;
616 }
617
Ryan Mitchell80094e32020-11-16 23:08:18 +0000618 result->cookie = overlay_result->cookie;
619 result->entry = overlay_result->entry;
620 result->config = overlay_result->config;
621 result->dynamic_ref_table = id_map.overlay_res_maps_.GetOverlayDynamicRefTable();
622
623 if (UNLIKELY(logging_enabled)) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700624 last_resolution_.steps.push_back(
Ryan Mitchell80094e32020-11-16 23:08:18 +0000625 Resolution::Step{Resolution::Step::Type::OVERLAID, overlay_result->config.toString(),
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800626 overlay_result->package_name,
627 overlay_result->cookie});
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700628 }
629 }
630 }
631
Ryan Mitchell80094e32020-11-16 23:08:18 +0000632 if (UNLIKELY(logging_enabled)) {
633 last_resolution_.cookie = result->cookie;
634 last_resolution_.type_string_ref = result->type_string_ref;
635 last_resolution_.entry_string_ref = result->entry_string_ref;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700636 }
637
Ryan Mitchell80094e32020-11-16 23:08:18 +0000638 return result;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700639}
640
Ryan Mitchell80094e32020-11-16 23:08:18 +0000641base::expected<FindEntryResult, NullOrIOError> AssetManager2::FindEntryInternal(
642 const PackageGroup& package_group, uint8_t type_idx, uint16_t entry_idx,
643 const ResTable_config& desired_config, bool stop_at_first_match,
644 bool ignore_configuration) const {
645 const bool logging_enabled = resource_resolution_logging_enabled_;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800646 ApkAssetsCookie best_cookie = kInvalidCookie;
647 const LoadedPackage* best_package = nullptr;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000648 incfs::verified_map_ptr<ResTable_type> best_type;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800649 const ResTable_config* best_config = nullptr;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000650 uint32_t best_offset = 0U;
651 uint32_t type_flags = 0U;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800652
Winson2f3669b2019-01-11 11:28:34 -0800653 std::vector<Resolution::Step> resolution_steps;
654
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800655 // If `desired_config` is not the same as the set configuration or the caller will accept a value
656 // from any configuration, then we cannot use our filtered list of types since it only it contains
657 // types matched to the set configuration.
658 const bool use_filtered = !ignore_configuration && &desired_config == &configuration_;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800659
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700660 const size_t package_count = package_group.packages_.size();
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800661 for (size_t pi = 0; pi < package_count; pi++) {
662 const ConfiguredPackage& loaded_package_impl = package_group.packages_[pi];
663 const LoadedPackage* loaded_package = loaded_package_impl.loaded_package_;
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800664 const ApkAssetsCookie cookie = package_group.cookies_[pi];
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800665
666 // If the type IDs are offset in this package, we need to take that into account when searching
667 // for a type.
668 const TypeSpec* type_spec = loaded_package->GetTypeSpecByTypeIndex(type_idx);
669 if (UNLIKELY(type_spec == nullptr)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700670 continue;
671 }
672
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800673 // Allow custom loader packages to overlay resource values with configurations equivalent to the
674 // current best configuration.
675 const bool package_is_loader = loaded_package->IsCustomLoader();
676
Ryan Mitchell80094e32020-11-16 23:08:18 +0000677 auto entry_flags = type_spec->GetFlagsForEntryIndex(entry_idx);
Bernie Innocenti58cf8e32020-12-19 15:31:52 +0900678 if (UNLIKELY(!entry_flags.has_value())) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000679 return base::unexpected(entry_flags.error());
680 }
681 type_flags |= entry_flags.value();
682
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800683 const FilteredConfigGroup& filtered_group = loaded_package_impl.filtered_configs_[type_idx];
684 const size_t type_entry_count = (use_filtered) ? filtered_group.type_entries.size()
685 : type_spec->type_entries.size();
686 for (size_t i = 0; i < type_entry_count; i++) {
687 const TypeSpec::TypeEntry* type_entry = (use_filtered) ? filtered_group.type_entries[i]
688 : &type_spec->type_entries[i];
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800689
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800690 // We can skip calling ResTable_config::match() if the caller does not care for the
691 // configuration to match or if we're using the list of types that have already had their
692 // configuration matched.
693 const ResTable_config& this_config = type_entry->config;
694 if (!(use_filtered || ignore_configuration || this_config.match(desired_config))) {
695 continue;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800696 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800697
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800698 Resolution::Step::Type resolution_type;
699 if (best_config == nullptr) {
700 resolution_type = Resolution::Step::Type::INITIAL;
701 } else if (this_config.isBetterThan(*best_config, &desired_config)) {
702 resolution_type = Resolution::Step::Type::BETTER_MATCH;
703 } else if (package_is_loader && this_config.compare(*best_config) == 0) {
704 resolution_type = Resolution::Step::Type::OVERLAID;
705 } else {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000706 if (UNLIKELY(logging_enabled)) {
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800707 resolution_steps.push_back(Resolution::Step{Resolution::Step::Type::SKIPPED,
708 this_config.toString(),
709 &loaded_package->GetPackageName(),
710 cookie});
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800711 }
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800712 continue;
713 }
714
715 // The configuration matches and is better than the previous selection.
716 // Find the entry value if it exists for this configuration.
717 const auto& type = type_entry->type;
718 const auto offset = LoadedPackage::GetEntryOffset(type, entry_idx);
719 if (UNLIKELY(IsIOError(offset))) {
720 return base::unexpected(offset.error());
721 }
722
723 if (!offset.has_value()) {
724 if (UNLIKELY(logging_enabled)) {
725 resolution_steps.push_back(Resolution::Step{Resolution::Step::Type::NO_ENTRY,
726 this_config.toString(),
727 &loaded_package->GetPackageName(),
728 cookie});
729 }
730 continue;
731 }
732
733 best_cookie = cookie;
734 best_package = loaded_package;
735 best_type = type;
736 best_config = &this_config;
737 best_offset = offset.value();
738
739 if (UNLIKELY(logging_enabled)) {
740 last_resolution_.steps.push_back(Resolution::Step{resolution_type,
741 this_config.toString(),
742 &loaded_package->GetPackageName(),
743 cookie});
744 }
745
746 // Any configuration will suffice, so break.
747 if (stop_at_first_match) {
748 break;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700749 }
750 }
751 }
752
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800753 if (UNLIKELY(best_cookie == kInvalidCookie)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000754 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700755 }
756
Ryan Mitchell80094e32020-11-16 23:08:18 +0000757 auto best_entry_result = LoadedPackage::GetEntryFromOffset(best_type, best_offset);
758 if (!best_entry_result.has_value()) {
759 return base::unexpected(best_entry_result.error());
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800760 }
761
Ryan Mitchell80094e32020-11-16 23:08:18 +0000762 const incfs::map_ptr<ResTable_entry> best_entry = *best_entry_result;
763 if (!best_entry) {
764 return base::unexpected(IOError::PAGES_MISSING);
Ryan Mitchellbf1f45b2020-09-29 17:22:52 -0700765 }
766
Ryan Mitchell80094e32020-11-16 23:08:18 +0000767 const auto entry = GetEntryValue(best_entry.verified());
768 if (!entry.has_value()) {
769 return base::unexpected(entry.error());
770 }
Winson2f3669b2019-01-11 11:28:34 -0800771
Ryan Mitchell80094e32020-11-16 23:08:18 +0000772 return FindEntryResult{
773 .cookie = best_cookie,
774 .entry = *entry,
775 .config = *best_config,
776 .type_flags = type_flags,
777 .package_name = &best_package->GetPackageName(),
778 .type_string_ref = StringPoolRef(best_package->GetTypeStringPool(), best_type->id - 1),
779 .entry_string_ref = StringPoolRef(best_package->GetKeyStringPool(),
780 best_entry->key.index),
781 .dynamic_ref_table = package_group.dynamic_ref_table.get(),
782 };
Adam Lesinski7ad11102016-10-28 16:39:15 -0700783}
784
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700785void AssetManager2::ResetResourceResolution() const {
786 last_resolution_.cookie = kInvalidCookie;
787 last_resolution_.resid = 0;
788 last_resolution_.steps.clear();
789 last_resolution_.type_string_ref = StringPoolRef();
790 last_resolution_.entry_string_ref = StringPoolRef();
791}
792
Winson2f3669b2019-01-11 11:28:34 -0800793void AssetManager2::SetResourceResolutionLoggingEnabled(bool enabled) {
794 resource_resolution_logging_enabled_ = enabled;
Winson2f3669b2019-01-11 11:28:34 -0800795 if (!enabled) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700796 ResetResourceResolution();
Winson2f3669b2019-01-11 11:28:34 -0800797 }
798}
799
800std::string AssetManager2::GetLastResourceResolution() const {
801 if (!resource_resolution_logging_enabled_) {
802 LOG(ERROR) << "Must enable resource resolution logging before getting path.";
Ryan Mitchell80094e32020-11-16 23:08:18 +0000803 return {};
Winson2f3669b2019-01-11 11:28:34 -0800804 }
805
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800806 const ApkAssetsCookie cookie = last_resolution_.cookie;
Winson2f3669b2019-01-11 11:28:34 -0800807 if (cookie == kInvalidCookie) {
808 LOG(ERROR) << "AssetManager hasn't resolved a resource to read resolution path.";
Ryan Mitchell80094e32020-11-16 23:08:18 +0000809 return {};
Winson2f3669b2019-01-11 11:28:34 -0800810 }
811
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800812 const uint32_t resid = last_resolution_.resid;
813 const auto package = apk_assets_[cookie]->GetLoadedArsc()->GetPackageById(get_package_id(resid));
814
Winson2f3669b2019-01-11 11:28:34 -0800815 std::string resource_name_string;
Winson2f3669b2019-01-11 11:28:34 -0800816 if (package != nullptr) {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000817 auto resource_name = ToResourceName(last_resolution_.type_string_ref,
818 last_resolution_.entry_string_ref,
819 package->GetPackageName());
820 resource_name_string = resource_name.has_value() ?
821 ToFormattedResourceString(resource_name.value()) : "<unknown>";
Winson2f3669b2019-01-11 11:28:34 -0800822 }
823
824 std::stringstream log_stream;
825 log_stream << base::StringPrintf("Resolution for 0x%08x ", resid)
826 << resource_name_string
827 << "\n\tFor config -"
828 << configuration_.toString();
829
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800830 for (const Resolution::Step& step : last_resolution_.steps) {
831 const static std::unordered_map<Resolution::Step::Type, const char*> kStepStrings = {
832 {Resolution::Step::Type::INITIAL, "Found initial"},
833 {Resolution::Step::Type::BETTER_MATCH, "Found better"},
834 {Resolution::Step::Type::OVERLAID, "Overlaid"},
835 {Resolution::Step::Type::SKIPPED, "Skipped"},
836 {Resolution::Step::Type::NO_ENTRY, "No entry"}
837 };
838
839 const auto prefix = kStepStrings.find(step.type);
840 if (prefix == kStepStrings.end()) {
841 continue;
Winson2f3669b2019-01-11 11:28:34 -0800842 }
843
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800844 log_stream << "\n\t" << prefix->second << ": " << *step.package_name << " ("
845 << apk_assets_[step.cookie]->GetPath() << ")";
846 if (!step.config_name.isEmpty()) {
847 log_stream << " -" << step.config_name;
Winson2f3669b2019-01-11 11:28:34 -0800848 }
849 }
850
851 return log_stream.str();
852}
853
Ryan Mitchell80094e32020-11-16 23:08:18 +0000854base::expected<AssetManager2::ResourceName, NullOrIOError> AssetManager2::GetResourceName(
855 uint32_t resid) const {
856 auto result = FindEntry(resid, 0u /* density_override */, true /* stop_at_first_match */,
857 true /* ignore_configuration */);
858 if (!result.has_value()) {
859 return base::unexpected(result.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -0700860 }
861
Ryan Mitchell80094e32020-11-16 23:08:18 +0000862 return ToResourceName(result->type_string_ref,
863 result->entry_string_ref,
864 *result->package_name);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700865}
866
Ryan Mitchell14e8ade2021-01-11 16:01:35 -0800867base::expected<uint32_t, NullOrIOError> AssetManager2::GetResourceTypeSpecFlags(
868 uint32_t resid) const {
869 auto result = FindEntry(resid, 0u /* density_override */, false /* stop_at_first_match */,
870 true /* ignore_configuration */);
871 if (!result.has_value()) {
872 return base::unexpected(result.error());
873 }
874 return result->type_flags;
875}
876
Ryan Mitchell80094e32020-11-16 23:08:18 +0000877base::expected<AssetManager2::SelectedValue, NullOrIOError> AssetManager2::GetResource(
878 uint32_t resid, bool may_be_bag, uint16_t density_override) const {
879 auto result = FindEntry(resid, density_override, false /* stop_at_first_match */,
880 false /* ignore_configuration */);
881 if (!result.has_value()) {
882 return base::unexpected(result.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -0700883 }
884
Ryan Mitchell80094e32020-11-16 23:08:18 +0000885 auto result_map_entry = std::get_if<incfs::verified_map_ptr<ResTable_map_entry>>(&result->entry);
Ryan Mitchellbf1f45b2020-09-29 17:22:52 -0700886 if (result_map_entry != nullptr) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700887 if (!may_be_bag) {
888 LOG(ERROR) << base::StringPrintf("Resource %08x is a complex map type.", resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +0000889 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700890 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800891
892 // Create a reference since we can't represent this complex type as a Res_value.
Ryan Mitchell80094e32020-11-16 23:08:18 +0000893 return SelectedValue(Res_value::TYPE_REFERENCE, resid, result->cookie, result->type_flags,
894 resid, result->config);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700895 }
896
Adam Lesinskida431a22016-12-29 16:08:16 -0500897 // Convert the package ID to the runtime assigned package ID.
Ryan Mitchell80094e32020-11-16 23:08:18 +0000898 Res_value value = std::get<Res_value>(result->entry);
899 result->dynamic_ref_table->lookupResourceValue(&value);
Adam Lesinskida431a22016-12-29 16:08:16 -0500900
Ryan Mitchell80094e32020-11-16 23:08:18 +0000901 return SelectedValue(value.dataType, value.data, result->cookie, result->type_flags,
902 resid, result->config);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700903}
904
Ryan Mitchell80094e32020-11-16 23:08:18 +0000905base::expected<std::monostate, NullOrIOError> AssetManager2::ResolveReference(
Ryan Mitchella45506e2020-11-16 23:08:18 +0000906 AssetManager2::SelectedValue& value, bool cache_value) const {
Ryan Mitchell80094e32020-11-16 23:08:18 +0000907 if (value.type != Res_value::TYPE_REFERENCE || value.data == 0U) {
908 // Not a reference. Nothing to do.
909 return {};
Adam Lesinski0c405242017-01-13 20:47:26 -0800910 }
Ryan Mitchell80094e32020-11-16 23:08:18 +0000911
Ryan Mitchella45506e2020-11-16 23:08:18 +0000912 const uint32_t original_flags = value.flags;
913 const uint32_t original_resid = value.data;
914 if (cache_value) {
915 auto cached_value = cached_resolved_values_.find(value.data);
916 if (cached_value != cached_resolved_values_.end()) {
917 value = cached_value->second;
918 value.flags |= original_flags;
919 return {};
920 }
921 }
922
923 uint32_t combined_flags = 0U;
924 uint32_t resolve_resid = original_resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000925 constexpr const uint32_t kMaxIterations = 20;
926 for (uint32_t i = 0U;; i++) {
927 auto result = GetResource(resolve_resid, true /*may_be_bag*/);
928 if (!result.has_value()) {
Ryan Mitchelle7ab6272020-11-13 18:06:15 -0800929 value.resid = resolve_resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000930 return base::unexpected(result.error());
931 }
932
Ryan Mitchelle7ab6272020-11-13 18:06:15 -0800933 // If resource resolution fails, the value should be set to the last reference that was able to
934 // be resolved successfully.
935 value = *result;
936 value.flags |= combined_flags;
937
Ryan Mitchell80094e32020-11-16 23:08:18 +0000938 if (result->type != Res_value::TYPE_REFERENCE ||
939 result->data == Res_value::DATA_NULL_UNDEFINED ||
940 result->data == resolve_resid || i == kMaxIterations) {
941 // This reference can't be resolved, so exit now and let the caller deal with it.
Ryan Mitchella45506e2020-11-16 23:08:18 +0000942 if (cache_value) {
943 cached_resolved_values_[original_resid] = value;
944 }
945
946 // Above value is cached without original_flags to ensure they don't get included in future
947 // queries that hit the cache
948 value.flags |= original_flags;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000949 return {};
950 }
951
Ryan Mitchelle7ab6272020-11-13 18:06:15 -0800952 combined_flags = result->flags;
Ryan Mitchell80094e32020-11-16 23:08:18 +0000953 resolve_resid = result->data;
954 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800955}
956
Ryan Mitchell80094e32020-11-16 23:08:18 +0000957const std::vector<uint32_t> AssetManager2::GetBagResIdStack(uint32_t resid) const {
Aurimas Liutikas8f004c82019-01-17 17:20:10 -0800958 auto cached_iter = cached_bag_resid_stacks_.find(resid);
959 if (cached_iter != cached_bag_resid_stacks_.end()) {
960 return cached_iter->second;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -0800961 }
Ryan Mitchell80094e32020-11-16 23:08:18 +0000962
963 std::vector<uint32_t> found_resids;
964 GetBag(resid, found_resids);
965 cached_bag_resid_stacks_.emplace(resid, found_resids);
966 return found_resids;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -0800967}
968
Ryan Mitchell80094e32020-11-16 23:08:18 +0000969base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::ResolveBag(
970 AssetManager2::SelectedValue& value) const {
971 if (UNLIKELY(value.type != Res_value::TYPE_REFERENCE)) {
972 return base::unexpected(std::nullopt);
973 }
Aurimas Liutikas8f004c82019-01-17 17:20:10 -0800974
Ryan Mitchell80094e32020-11-16 23:08:18 +0000975 auto bag = GetBag(value.data);
976 if (bag.has_value()) {
977 value.flags |= (*bag)->type_spec_flags;
Aurimas Liutikas8f004c82019-01-17 17:20:10 -0800978 }
979 return bag;
y57cd1952018-04-12 14:26:23 -0700980}
981
Ryan Mitchell80094e32020-11-16 23:08:18 +0000982base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::GetBag(uint32_t resid) const {
983 std::vector<uint32_t> found_resids;
984 const auto bag = GetBag(resid, found_resids);
985 cached_bag_resid_stacks_.emplace(resid, found_resids);
986 return bag;
Ryan Mitchell155d5392020-02-10 13:35:24 -0800987}
988
Ryan Mitchell80094e32020-11-16 23:08:18 +0000989base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::GetBag(
990 uint32_t resid, std::vector<uint32_t>& child_resids) const {
991 if (auto cached_iter = cached_bags_.find(resid); cached_iter != cached_bags_.end()) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700992 return cached_iter->second.get();
993 }
994
Ryan Mitchell80094e32020-11-16 23:08:18 +0000995 auto entry = FindEntry(resid, 0u /* density_override */, false /* stop_at_first_match */,
996 false /* ignore_configuration */);
997 if (!entry.has_value()) {
998 return base::unexpected(entry.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -0700999 }
1000
Ryan Mitchell80094e32020-11-16 23:08:18 +00001001 auto entry_map = std::get_if<incfs::verified_map_ptr<ResTable_map_entry>>(&entry->entry);
1002 if (entry_map == nullptr) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001003 // Not a bag, nothing to do.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001004 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001005 }
1006
Ryan Mitchell80094e32020-11-16 23:08:18 +00001007 auto map = *entry_map;
1008 auto map_entry = map.offset(dtohs(map->size)).convert<ResTable_map>();
1009 const auto map_entry_end = map_entry + dtohl(map->count);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001010
y57cd1952018-04-12 14:26:23 -07001011 // Keep track of ids that have already been seen to prevent infinite loops caused by circular
Ryan Mitchell80094e32020-11-16 23:08:18 +00001012 // dependencies between bags.
y57cd1952018-04-12 14:26:23 -07001013 child_resids.push_back(resid);
1014
Adam Lesinskida431a22016-12-29 16:08:16 -05001015 uint32_t parent_resid = dtohl(map->parent.ident);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001016 if (parent_resid == 0U ||
1017 std::find(child_resids.begin(), child_resids.end(), parent_resid) != child_resids.end()) {
1018 // There is no parent or a circular parental dependency exist, meaning there is nothing to
1019 // inherit and we can do a simple copy of the entries in the map.
Adam Lesinski7ad11102016-10-28 16:39:15 -07001020 const size_t entry_count = map_entry_end - map_entry;
1021 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
1022 malloc(sizeof(ResolvedBag) + (entry_count * sizeof(ResolvedBag::Entry))))};
Ryan Mitchell155d5392020-02-10 13:35:24 -08001023
1024 bool sort_entries = false;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001025 for (auto new_entry = new_bag->entries; map_entry != map_entry_end; ++map_entry) {
1026 if (UNLIKELY(!map_entry)) {
1027 return base::unexpected(IOError::PAGES_MISSING);
1028 }
1029
Adam Lesinskida431a22016-12-29 16:08:16 -05001030 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001031 if (!is_internal_resid(new_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -05001032 // Attributes, arrays, etc don't have a resource id as the name. They specify
1033 // other data, which would be wrong to change via a lookup.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001034 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001035 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
1036 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001037 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001038 }
1039 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001040
1041 new_entry->cookie = entry->cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -05001042 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001043 new_entry->key_pool = nullptr;
1044 new_entry->type_pool = nullptr;
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001045 new_entry->style = resid;
Adam Lesinski30080e22017-10-16 16:18:09 -07001046 new_entry->value.copyFrom_dtoh(map_entry->value);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001047 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1048 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001049 LOG(ERROR) << base::StringPrintf(
1050 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
1051 new_entry->value.data, new_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001052 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001053 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001054
Ryan Mitchell155d5392020-02-10 13:35:24 -08001055 sort_entries = sort_entries ||
1056 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001057 ++new_entry;
1058 }
Ryan Mitchell155d5392020-02-10 13:35:24 -08001059
1060 if (sort_entries) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001061 std::sort(new_bag->entries, new_bag->entries + entry_count,
1062 [](auto&& lhs, auto&& rhs) { return lhs.key < rhs.key; });
Ryan Mitchell155d5392020-02-10 13:35:24 -08001063 }
1064
Ryan Mitchell80094e32020-11-16 23:08:18 +00001065 new_bag->type_spec_flags = entry->type_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001066 new_bag->entry_count = static_cast<uint32_t>(entry_count);
1067 ResolvedBag* result = new_bag.get();
1068 cached_bags_[resid] = std::move(new_bag);
1069 return result;
1070 }
1071
Adam Lesinskida431a22016-12-29 16:08:16 -05001072 // In case the parent is a dynamic reference, resolve it.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001073 entry->dynamic_ref_table->lookupResourceId(&parent_resid);
Adam Lesinskida431a22016-12-29 16:08:16 -05001074
Adam Lesinski7ad11102016-10-28 16:39:15 -07001075 // Get the parent and do a merge of the keys.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001076 const auto parent_bag = GetBag(parent_resid, child_resids);
1077 if (UNLIKELY(!parent_bag.has_value())) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001078 // Failed to get the parent that should exist.
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001079 LOG(ERROR) << base::StringPrintf("Failed to find parent 0x%08x of bag 0x%08x.", parent_resid,
1080 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001081 return base::unexpected(parent_bag.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001082 }
1083
Adam Lesinski7ad11102016-10-28 16:39:15 -07001084 // Create the max possible entries we can make. Once we construct the bag,
1085 // we will realloc to fit to size.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001086 const size_t max_count = (*parent_bag)->entry_count + dtohl(map->count);
George Burgess IV09b119f2017-07-25 15:00:04 -07001087 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
1088 malloc(sizeof(ResolvedBag) + (max_count * sizeof(ResolvedBag::Entry))))};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001089 ResolvedBag::Entry* new_entry = new_bag->entries;
1090
Ryan Mitchell80094e32020-11-16 23:08:18 +00001091 const ResolvedBag::Entry* parent_entry = (*parent_bag)->entries;
1092 const ResolvedBag::Entry* const parent_entry_end = parent_entry + (*parent_bag)->entry_count;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001093
1094 // The keys are expected to be in sorted order. Merge the two bags.
Ryan Mitchell155d5392020-02-10 13:35:24 -08001095 bool sort_entries = false;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001096 while (map_entry != map_entry_end && parent_entry != parent_entry_end) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001097 if (UNLIKELY(!map_entry)) {
1098 return base::unexpected(IOError::PAGES_MISSING);
1099 }
1100
Adam Lesinskida431a22016-12-29 16:08:16 -05001101 uint32_t child_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001102 if (!is_internal_resid(child_key)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001103 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&child_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001104 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", child_key,
1105 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001106 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001107 }
1108 }
1109
Adam Lesinski7ad11102016-10-28 16:39:15 -07001110 if (child_key <= parent_entry->key) {
1111 // Use the child key if it comes before the parent
1112 // or is equal to the parent (overrides).
Ryan Mitchell80094e32020-11-16 23:08:18 +00001113 new_entry->cookie = entry->cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001114 new_entry->key = child_key;
1115 new_entry->key_pool = nullptr;
1116 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -07001117 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001118 new_entry->style = resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001119 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1120 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001121 LOG(ERROR) << base::StringPrintf(
1122 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
1123 new_entry->value.data, child_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001124 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001125 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001126 ++map_entry;
1127 } else {
1128 // Take the parent entry as-is.
1129 memcpy(new_entry, parent_entry, sizeof(*new_entry));
1130 }
1131
Ryan Mitchell155d5392020-02-10 13:35:24 -08001132 sort_entries = sort_entries ||
1133 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001134 if (child_key >= parent_entry->key) {
1135 // Move to the next parent entry if we used it or it was overridden.
1136 ++parent_entry;
1137 }
1138 // Increment to the next entry to fill.
1139 ++new_entry;
1140 }
1141
1142 // Finish the child entries if they exist.
1143 while (map_entry != map_entry_end) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001144 if (UNLIKELY(!map_entry)) {
1145 return base::unexpected(IOError::PAGES_MISSING);
1146 }
1147
Adam Lesinskida431a22016-12-29 16:08:16 -05001148 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001149 if (!is_internal_resid(new_key)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001150 if (UNLIKELY(entry->dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001151 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
1152 resid);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001153 return base::unexpected(std::nullopt);
Adam Lesinskida431a22016-12-29 16:08:16 -05001154 }
1155 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001156 new_entry->cookie = entry->cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -05001157 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001158 new_entry->key_pool = nullptr;
1159 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -07001160 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001161 new_entry->style = resid;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001162 status_t err = entry->dynamic_ref_table->lookupResourceValue(&new_entry->value);
1163 if (UNLIKELY(err != NO_ERROR)) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001164 LOG(ERROR) << base::StringPrintf("Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.",
1165 new_entry->value.dataType, new_entry->value.data, new_key);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001166 return base::unexpected(std::nullopt);
Adam Lesinski30080e22017-10-16 16:18:09 -07001167 }
Ryan Mitchell155d5392020-02-10 13:35:24 -08001168 sort_entries = sort_entries ||
1169 (new_entry != new_bag->entries && (new_entry->key < (new_entry - 1U)->key));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001170 ++map_entry;
1171 ++new_entry;
1172 }
1173
1174 // Finish the parent entries if they exist.
1175 if (parent_entry != parent_entry_end) {
1176 // Take the rest of the parent entries as-is.
1177 const size_t num_entries_to_copy = parent_entry_end - parent_entry;
1178 memcpy(new_entry, parent_entry, num_entries_to_copy * sizeof(*new_entry));
1179 new_entry += num_entries_to_copy;
1180 }
1181
1182 // Resize the resulting array to fit.
1183 const size_t actual_count = new_entry - new_bag->entries;
1184 if (actual_count != max_count) {
George Burgess IV09b119f2017-07-25 15:00:04 -07001185 new_bag.reset(reinterpret_cast<ResolvedBag*>(realloc(
1186 new_bag.release(), sizeof(ResolvedBag) + (actual_count * sizeof(ResolvedBag::Entry)))));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001187 }
1188
Ryan Mitchell155d5392020-02-10 13:35:24 -08001189 if (sort_entries) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001190 std::sort(new_bag->entries, new_bag->entries + actual_count,
1191 [](auto&& lhs, auto&& rhs) { return lhs.key < rhs.key; });
Ryan Mitchell155d5392020-02-10 13:35:24 -08001192 }
1193
Adam Lesinski1a1e9c22017-10-13 15:45:34 -07001194 // Combine flags from the parent and our own bag.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001195 new_bag->type_spec_flags = entry->type_flags | (*parent_bag)->type_spec_flags;
George Burgess IV09b119f2017-07-25 15:00:04 -07001196 new_bag->entry_count = static_cast<uint32_t>(actual_count);
1197 ResolvedBag* result = new_bag.get();
1198 cached_bags_[resid] = std::move(new_bag);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001199 return result;
1200}
1201
Adam Lesinski929d6512017-01-16 19:11:19 -08001202static bool Utf8ToUtf16(const StringPiece& str, std::u16string* out) {
1203 ssize_t len =
1204 utf8_to_utf16_length(reinterpret_cast<const uint8_t*>(str.data()), str.size(), false);
1205 if (len < 0) {
1206 return false;
1207 }
1208 out->resize(static_cast<size_t>(len));
1209 utf8_to_utf16(reinterpret_cast<const uint8_t*>(str.data()), str.size(), &*out->begin(),
1210 static_cast<size_t>(len + 1));
1211 return true;
1212}
1213
Ryan Mitchell80094e32020-11-16 23:08:18 +00001214base::expected<uint32_t, NullOrIOError> AssetManager2::GetResourceId(
1215 const std::string& resource_name, const std::string& fallback_type,
1216 const std::string& fallback_package) const {
Adam Lesinski929d6512017-01-16 19:11:19 -08001217 StringPiece package_name, type, entry;
1218 if (!ExtractResourceName(resource_name, &package_name, &type, &entry)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001219 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001220 }
1221
1222 if (entry.empty()) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001223 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001224 }
1225
1226 if (package_name.empty()) {
1227 package_name = fallback_package;
1228 }
1229
1230 if (type.empty()) {
1231 type = fallback_type;
1232 }
1233
1234 std::u16string type16;
1235 if (!Utf8ToUtf16(type, &type16)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001236 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001237 }
1238
1239 std::u16string entry16;
1240 if (!Utf8ToUtf16(entry, &entry16)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001241 return base::unexpected(std::nullopt);
Adam Lesinski929d6512017-01-16 19:11:19 -08001242 }
1243
1244 const StringPiece16 kAttr16 = u"attr";
1245 const static std::u16string kAttrPrivate16 = u"^attr-private";
1246
1247 for (const PackageGroup& package_group : package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001248 for (const ConfiguredPackage& package_impl : package_group.packages_) {
1249 const LoadedPackage* package = package_impl.loaded_package_;
Adam Lesinski929d6512017-01-16 19:11:19 -08001250 if (package_name != package->GetPackageName()) {
1251 // All packages in the same group are expected to have the same package name.
1252 break;
1253 }
1254
Ryan Mitchell80094e32020-11-16 23:08:18 +00001255 base::expected<uint32_t, NullOrIOError> resid = package->FindEntryByName(type16, entry16);
1256 if (UNLIKELY(IsIOError(resid))) {
1257 return base::unexpected(resid.error());
1258 }
1259
1260 if (!resid.has_value() && kAttr16 == type16) {
Adam Lesinski929d6512017-01-16 19:11:19 -08001261 // Private attributes in libraries (such as the framework) are sometimes encoded
1262 // under the type '^attr-private' in order to leave the ID space of public 'attr'
1263 // free for future additions. Check '^attr-private' for the same name.
1264 resid = package->FindEntryByName(kAttrPrivate16, entry16);
1265 }
1266
Ryan Mitchell80094e32020-11-16 23:08:18 +00001267 if (resid.has_value()) {
1268 return fix_package_id(*resid, package_group.dynamic_ref_table->mAssignedPackageId);
Adam Lesinski929d6512017-01-16 19:11:19 -08001269 }
1270 }
1271 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001272 return base::unexpected(std::nullopt);
Adam Lesinski0c405242017-01-13 20:47:26 -08001273}
1274
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001275void AssetManager2::RebuildFilterList() {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001276 for (PackageGroup& group : package_groups_) {
1277 for (ConfiguredPackage& impl : group.packages_) {
1278 // Destroy it.
1279 impl.filtered_configs_.~ByteBucketArray();
1280
1281 // Re-create it.
1282 new (&impl.filtered_configs_) ByteBucketArray<FilteredConfigGroup>();
1283
1284 // Create the filters here.
Ryan Mitchell14e8ade2021-01-11 16:01:35 -08001285 impl.loaded_package_->ForEachTypeSpec([&](const TypeSpec& type_spec, uint8_t type_id) {
1286 FilteredConfigGroup& group = impl.filtered_configs_.editItemAt(type_id - 1);
1287 for (const auto& type_entry : type_spec.type_entries) {
1288 if (type_entry.config.match(configuration_)) {
1289 group.type_entries.push_back(&type_entry);
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001290 }
1291 }
1292 });
1293 }
1294 }
1295}
1296
Adam Lesinski7ad11102016-10-28 16:39:15 -07001297void AssetManager2::InvalidateCaches(uint32_t diff) {
Ryan Mitchell2c4d8742019-03-04 09:41:00 -08001298 cached_bag_resid_stacks_.clear();
1299
Adam Lesinski7ad11102016-10-28 16:39:15 -07001300 if (diff == 0xffffffffu) {
1301 // Everything must go.
1302 cached_bags_.clear();
1303 return;
1304 }
1305
1306 // Be more conservative with what gets purged. Only if the bag has other possible
1307 // variations with respect to what changed (diff) should we remove it.
1308 for (auto iter = cached_bags_.cbegin(); iter != cached_bags_.cend();) {
1309 if (diff & iter->second->type_spec_flags) {
1310 iter = cached_bags_.erase(iter);
1311 } else {
1312 ++iter;
1313 }
1314 }
Ryan Mitchella45506e2020-11-16 23:08:18 +00001315
1316 cached_resolved_values_.clear();
Adam Lesinski7ad11102016-10-28 16:39:15 -07001317}
1318
Ryan Mitchell2e394222019-08-28 12:10:51 -07001319uint8_t AssetManager2::GetAssignedPackageId(const LoadedPackage* package) const {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001320 for (auto& package_group : package_groups_) {
1321 for (auto& package2 : package_group.packages_) {
1322 if (package2.loaded_package_ == package) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -07001323 return package_group.dynamic_ref_table->mAssignedPackageId;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001324 }
1325 }
1326 }
1327 return 0;
1328}
1329
Adam Lesinski30080e22017-10-16 16:18:09 -07001330std::unique_ptr<Theme> AssetManager2::NewTheme() {
1331 return std::unique_ptr<Theme>(new Theme(this));
1332}
1333
1334Theme::Theme(AssetManager2* asset_manager) : asset_manager_(asset_manager) {
1335}
1336
1337Theme::~Theme() = default;
1338
1339namespace {
1340
1341struct ThemeEntry {
1342 ApkAssetsCookie cookie;
1343 uint32_t type_spec_flags;
1344 Res_value value;
1345};
1346
1347struct ThemeType {
1348 int entry_count;
1349 ThemeEntry entries[0];
1350};
1351
1352constexpr size_t kTypeCount = std::numeric_limits<uint8_t>::max() + 1;
1353
1354} // namespace
1355
1356struct Theme::Package {
1357 // Each element of Type will be a dynamically sized object
1358 // allocated to have the entries stored contiguously with the Type.
1359 std::array<util::unique_cptr<ThemeType>, kTypeCount> types;
1360};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001361
Ryan Mitchell80094e32020-11-16 23:08:18 +00001362base::expected<std::monostate, NullOrIOError> Theme::ApplyStyle(uint32_t resid, bool force) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001363 ATRACE_NAME("Theme::ApplyStyle");
Adam Lesinski7ad11102016-10-28 16:39:15 -07001364
Ryan Mitchell80094e32020-11-16 23:08:18 +00001365 auto bag = asset_manager_->GetBag(resid);
1366 if (!bag.has_value()) {
1367 return base::unexpected(bag.error());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001368 }
1369
1370 // Merge the flags from this style.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001371 type_spec_flags_ |= (*bag)->type_spec_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001372
Adam Lesinski30080e22017-10-16 16:18:09 -07001373 int last_type_idx = -1;
1374 int last_package_idx = -1;
1375 Package* last_package = nullptr;
1376 ThemeType* last_type = nullptr;
1377
1378 // Iterate backwards, because each bag is sorted in ascending key ID order, meaning we will only
1379 // need to perform one resize per type.
1380 using reverse_bag_iterator = std::reverse_iterator<const ResolvedBag::Entry*>;
Ryan Mitchell80094e32020-11-16 23:08:18 +00001381 const auto rbegin = reverse_bag_iterator(begin(*bag));
1382 for (auto it = reverse_bag_iterator(end(*bag)); it != rbegin; ++it) {
1383 const uint32_t attr_resid = it->key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001384
Adam Lesinski30080e22017-10-16 16:18:09 -07001385 // If the resource ID passed in is not a style, the key can be some other identifier that is not
1386 // a resource ID. We should fail fast instead of operating with strange resource IDs.
Adam Lesinski929d6512017-01-16 19:11:19 -08001387 if (!is_valid_resid(attr_resid)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001388 return base::unexpected(std::nullopt);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001389 }
1390
Adam Lesinski30080e22017-10-16 16:18:09 -07001391 // We don't use the 0-based index for the type so that we can avoid doing ID validation
1392 // upon lookup. Instead, we keep space for the type ID 0 in our data structures. Since
1393 // the construction of this type is guarded with a resource ID check, it will never be
1394 // populated, and querying type ID 0 will always fail.
1395 const int package_idx = get_package_id(attr_resid);
1396 const int type_idx = get_type_id(attr_resid);
1397 const int entry_idx = get_entry_id(attr_resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001398
Adam Lesinski30080e22017-10-16 16:18:09 -07001399 if (last_package_idx != package_idx) {
1400 std::unique_ptr<Package>& package = packages_[package_idx];
1401 if (package == nullptr) {
1402 package.reset(new Package());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001403 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001404 last_package_idx = package_idx;
1405 last_package = package.get();
1406 last_type_idx = -1;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001407 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001408
1409 if (last_type_idx != type_idx) {
1410 util::unique_cptr<ThemeType>& type = last_package->types[type_idx];
1411 if (type == nullptr) {
1412 // Allocate enough memory to contain this entry_idx. Since we're iterating in reverse over
1413 // a sorted list of attributes, this shouldn't be resized again during this method call.
1414 type.reset(reinterpret_cast<ThemeType*>(
1415 calloc(sizeof(ThemeType) + (entry_idx + 1) * sizeof(ThemeEntry), 1)));
1416 type->entry_count = entry_idx + 1;
1417 } else if (entry_idx >= type->entry_count) {
1418 // Reallocate the memory to contain this entry_idx. Since we're iterating in reverse over
1419 // a sorted list of attributes, this shouldn't be resized again during this method call.
1420 const int new_count = entry_idx + 1;
1421 type.reset(reinterpret_cast<ThemeType*>(
1422 realloc(type.release(), sizeof(ThemeType) + (new_count * sizeof(ThemeEntry)))));
1423
1424 // Clear out the newly allocated space (which isn't zeroed).
1425 memset(type->entries + type->entry_count, 0,
1426 (new_count - type->entry_count) * sizeof(ThemeEntry));
1427 type->entry_count = new_count;
1428 }
1429 last_type_idx = type_idx;
1430 last_type = type.get();
1431 }
1432
1433 ThemeEntry& entry = last_type->entries[entry_idx];
1434 if (force || (entry.value.dataType == Res_value::TYPE_NULL &&
1435 entry.value.data != Res_value::DATA_NULL_EMPTY)) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001436 entry.cookie = it->cookie;
1437 entry.type_spec_flags |= (*bag)->type_spec_flags;
1438 entry.value = it->value;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001439 }
1440 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001441 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001442}
1443
Ryan Mitchell80094e32020-11-16 23:08:18 +00001444std::optional<AssetManager2::SelectedValue> Theme::GetAttribute(uint32_t resid) const {
1445
Adam Lesinski30080e22017-10-16 16:18:09 -07001446 int cnt = 20;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001447 uint32_t type_spec_flags = 0u;
Adam Lesinski30080e22017-10-16 16:18:09 -07001448 do {
1449 const int package_idx = get_package_id(resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001450 const Package* package = packages_[package_idx].get();
Adam Lesinski30080e22017-10-16 16:18:09 -07001451 if (package != nullptr) {
1452 // The themes are constructed with a 1-based type ID, so no need to decrement here.
1453 const int type_idx = get_type_id(resid);
1454 const ThemeType* type = package->types[type_idx].get();
1455 if (type != nullptr) {
1456 const int entry_idx = get_entry_id(resid);
1457 if (entry_idx < type->entry_count) {
1458 const ThemeEntry& entry = type->entries[entry_idx];
1459 type_spec_flags |= entry.type_spec_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001460
Adam Lesinski30080e22017-10-16 16:18:09 -07001461 if (entry.value.dataType == Res_value::TYPE_ATTRIBUTE) {
1462 if (cnt > 0) {
1463 cnt--;
1464 resid = entry.value.data;
1465 continue;
1466 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001467 return std::nullopt;
Adam Lesinski30080e22017-10-16 16:18:09 -07001468 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001469
Adam Lesinski30080e22017-10-16 16:18:09 -07001470 // @null is different than @empty.
1471 if (entry.value.dataType == Res_value::TYPE_NULL &&
1472 entry.value.data != Res_value::DATA_NULL_EMPTY) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001473 return std::nullopt;
Adam Lesinski30080e22017-10-16 16:18:09 -07001474 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001475
Ryan Mitchell80094e32020-11-16 23:08:18 +00001476 return AssetManager2::SelectedValue(entry.value.dataType, entry.value.data, entry.cookie,
1477 type_spec_flags, 0U /* resid */, {} /* config */);
Adam Lesinskida431a22016-12-29 16:08:16 -05001478 }
Adam Lesinskida431a22016-12-29 16:08:16 -05001479 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001480 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001481 break;
1482 } while (true);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001483 return std::nullopt;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001484}
1485
Ryan Mitchell80094e32020-11-16 23:08:18 +00001486base::expected<std::monostate, NullOrIOError> Theme::ResolveAttributeReference(
1487 AssetManager2::SelectedValue& value) const {
1488 if (value.type != Res_value::TYPE_ATTRIBUTE) {
1489 return asset_manager_->ResolveReference(value);
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001490 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001491
1492 std::optional<AssetManager2::SelectedValue> result = GetAttribute(value.data);
1493 if (!result.has_value()) {
1494 return base::unexpected(std::nullopt);
1495 }
1496
Ryan Mitchella45506e2020-11-16 23:08:18 +00001497 auto resolve_result = asset_manager_->ResolveReference(*result, true /* cache_value */);
Ryan Mitchell80094e32020-11-16 23:08:18 +00001498 if (resolve_result.has_value()) {
1499 result->flags |= value.flags;
1500 value = *result;
1501 }
1502 return resolve_result;
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001503}
1504
Adam Lesinski7ad11102016-10-28 16:39:15 -07001505void Theme::Clear() {
1506 type_spec_flags_ = 0u;
1507 for (std::unique_ptr<Package>& package : packages_) {
1508 package.reset();
1509 }
1510}
1511
Ryan Mitchell80094e32020-11-16 23:08:18 +00001512base::expected<std::monostate, IOError> Theme::SetTo(const Theme& o) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001513 if (this == &o) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001514 return {};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001515 }
1516
Adam Lesinski7ad11102016-10-28 16:39:15 -07001517 type_spec_flags_ = o.type_spec_flags_;
1518
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001519 if (asset_manager_ == o.asset_manager_) {
1520 // The theme comes from the same asset manager so all theme data can be copied exactly
1521 for (size_t p = 0; p < packages_.size(); p++) {
1522 const Package *package = o.packages_[p].get();
1523 if (package == nullptr) {
1524 // The other theme doesn't have this package, clear ours.
1525 packages_[p].reset();
Adam Lesinski7ad11102016-10-28 16:39:15 -07001526 continue;
1527 }
1528
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001529 if (packages_[p] == nullptr) {
1530 // The other theme has this package, but we don't. Make one.
1531 packages_[p].reset(new Package());
1532 }
1533
1534 for (size_t t = 0; t < package->types.size(); t++) {
1535 const ThemeType *type = package->types[t].get();
1536 if (type == nullptr) {
1537 // The other theme doesn't have this type, clear ours.
1538 packages_[p]->types[t].reset();
1539 continue;
1540 }
1541
1542 // Create a new type and update it to theirs.
1543 const size_t type_alloc_size = sizeof(ThemeType) + (type->entry_count * sizeof(ThemeEntry));
1544 void *copied_data = malloc(type_alloc_size);
1545 memcpy(copied_data, type, type_alloc_size);
1546 packages_[p]->types[t].reset(reinterpret_cast<ThemeType *>(copied_data));
1547 }
1548 }
1549 } else {
1550 std::map<ApkAssetsCookie, ApkAssetsCookie> src_to_dest_asset_cookies;
1551 typedef std::map<int, int> SourceToDestinationRuntimePackageMap;
1552 std::map<ApkAssetsCookie, SourceToDestinationRuntimePackageMap> src_asset_cookie_id_map;
1553
Ryan Mitchell93bca972019-03-08 17:26:28 -08001554 // Determine which ApkAssets are loaded in both theme AssetManagers.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001555 std::vector<const ApkAssets*> src_assets = o.asset_manager_->GetApkAssets();
1556 for (size_t i = 0; i < src_assets.size(); i++) {
1557 const ApkAssets* src_asset = src_assets[i];
1558
1559 std::vector<const ApkAssets*> dest_assets = asset_manager_->GetApkAssets();
1560 for (size_t j = 0; j < dest_assets.size(); j++) {
1561 const ApkAssets* dest_asset = dest_assets[j];
1562
Ryan Mitchell93bca972019-03-08 17:26:28 -08001563 // Map the runtime package of the source apk asset to the destination apk asset.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001564 if (src_asset->GetPath() == dest_asset->GetPath()) {
Ryan Mitchell80094e32020-11-16 23:08:18 +00001565 const auto& src_packages = src_asset->GetLoadedArsc()->GetPackages();
1566 const auto& dest_packages = dest_asset->GetLoadedArsc()->GetPackages();
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001567
1568 SourceToDestinationRuntimePackageMap package_map;
1569
1570 // The source and destination package should have the same number of packages loaded in
1571 // the same order.
1572 const size_t N = src_packages.size();
1573 CHECK(N == dest_packages.size())
1574 << " LoadedArsc " << src_asset->GetPath() << " differs number of packages.";
1575 for (size_t p = 0; p < N; p++) {
1576 auto& src_package = src_packages[p];
1577 auto& dest_package = dest_packages[p];
1578 CHECK(src_package->GetPackageName() == dest_package->GetPackageName())
1579 << " Package " << src_package->GetPackageName() << " differs in load order.";
1580
1581 int src_package_id = o.asset_manager_->GetAssignedPackageId(src_package.get());
1582 int dest_package_id = asset_manager_->GetAssignedPackageId(dest_package.get());
1583 package_map[src_package_id] = dest_package_id;
1584 }
1585
Ryan Mitchell93bca972019-03-08 17:26:28 -08001586 src_to_dest_asset_cookies.insert(std::make_pair(i, j));
1587 src_asset_cookie_id_map.insert(std::make_pair(i, package_map));
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001588 break;
1589 }
1590 }
1591 }
1592
Ryan Mitchell93bca972019-03-08 17:26:28 -08001593 // Reset the data in the destination theme.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001594 for (size_t p = 0; p < packages_.size(); p++) {
1595 if (packages_[p] != nullptr) {
1596 packages_[p].reset();
1597 }
1598 }
1599
1600 for (size_t p = 0; p < packages_.size(); p++) {
1601 const Package *package = o.packages_[p].get();
1602 if (package == nullptr) {
1603 continue;
1604 }
1605
1606 for (size_t t = 0; t < package->types.size(); t++) {
1607 const ThemeType *type = package->types[t].get();
1608 if (type == nullptr) {
1609 continue;
1610 }
1611
1612 for (size_t e = 0; e < type->entry_count; e++) {
1613 const ThemeEntry &entry = type->entries[e];
1614 if (entry.value.dataType == Res_value::TYPE_NULL &&
1615 entry.value.data != Res_value::DATA_NULL_EMPTY) {
1616 continue;
1617 }
1618
Ryan Mitchell93bca972019-03-08 17:26:28 -08001619 bool is_reference = (entry.value.dataType == Res_value::TYPE_ATTRIBUTE
1620 || entry.value.dataType == Res_value::TYPE_REFERENCE
1621 || entry.value.dataType == Res_value::TYPE_DYNAMIC_ATTRIBUTE
1622 || entry.value.dataType == Res_value::TYPE_DYNAMIC_REFERENCE)
1623 && entry.value.data != 0x0;
Ryan Mitchellb85d9b22018-11-19 12:11:38 -08001624
Ryan Mitchell93bca972019-03-08 17:26:28 -08001625 // If the attribute value represents an attribute or reference, the package id of the
1626 // value needs to be rewritten to the package id of the value in the destination.
1627 uint32_t attribute_data = entry.value.data;
1628 if (is_reference) {
1629 // Determine the package id of the reference in the destination AssetManager.
Ryan Mitchellb85d9b22018-11-19 12:11:38 -08001630 auto value_package_map = src_asset_cookie_id_map.find(entry.cookie);
1631 if (value_package_map == src_asset_cookie_id_map.end()) {
1632 continue;
1633 }
1634
1635 auto value_dest_package = value_package_map->second.find(
1636 get_package_id(entry.value.data));
1637 if (value_dest_package == value_package_map->second.end()) {
1638 continue;
1639 }
1640
Ryan Mitchell93bca972019-03-08 17:26:28 -08001641 attribute_data = fix_package_id(entry.value.data, value_dest_package->second);
1642 }
1643
1644 // Find the cookie of the value in the destination. If the source apk is not loaded in the
1645 // destination, only copy resources that do not reference resources in the source.
1646 ApkAssetsCookie data_dest_cookie;
1647 auto value_dest_cookie = src_to_dest_asset_cookies.find(entry.cookie);
1648 if (value_dest_cookie != src_to_dest_asset_cookies.end()) {
1649 data_dest_cookie = value_dest_cookie->second;
1650 } else {
1651 if (is_reference || entry.value.dataType == Res_value::TYPE_STRING) {
1652 continue;
1653 } else {
1654 data_dest_cookie = 0x0;
1655 }
Ryan Mitchellb85d9b22018-11-19 12:11:38 -08001656 }
1657
1658 // The package id of the attribute needs to be rewritten to the package id of the
Ryan Mitchell93bca972019-03-08 17:26:28 -08001659 // attribute in the destination.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001660 int attribute_dest_package_id = p;
1661 if (attribute_dest_package_id != 0x01) {
Ryan Mitchell93bca972019-03-08 17:26:28 -08001662 // Find the cookie of the attribute resource id in the source AssetManager
Ryan Mitchell80094e32020-11-16 23:08:18 +00001663 base::expected<FindEntryResult, NullOrIOError> attribute_entry_result =
Ryan Mitchella55dc2e2019-01-24 10:58:23 -08001664 o.asset_manager_->FindEntry(make_resid(p, t, e), 0 /* density_override */ ,
1665 true /* stop_at_first_match */,
Ryan Mitchell80094e32020-11-16 23:08:18 +00001666 true /* ignore_configuration */);
1667 if (UNLIKELY(IsIOError(attribute_entry_result))) {
1668 return base::unexpected(GetIOError(attribute_entry_result.error()));
1669 }
1670 if (!attribute_entry_result.has_value()) {
1671 continue;
1672 }
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001673
Ryan Mitchell93bca972019-03-08 17:26:28 -08001674 // Determine the package id of the attribute in the destination AssetManager.
Ryan Mitchell80094e32020-11-16 23:08:18 +00001675 auto attribute_package_map = src_asset_cookie_id_map.find(
1676 attribute_entry_result->cookie);
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001677 if (attribute_package_map == src_asset_cookie_id_map.end()) {
1678 continue;
1679 }
1680 auto attribute_dest_package = attribute_package_map->second.find(
1681 attribute_dest_package_id);
1682 if (attribute_dest_package == attribute_package_map->second.end()) {
1683 continue;
1684 }
1685 attribute_dest_package_id = attribute_dest_package->second;
1686 }
1687
Ryan Mitchell93bca972019-03-08 17:26:28 -08001688 // Lazily instantiate the destination package.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001689 std::unique_ptr<Package>& dest_package = packages_[attribute_dest_package_id];
1690 if (dest_package == nullptr) {
1691 dest_package.reset(new Package());
1692 }
1693
Ryan Mitchell93bca972019-03-08 17:26:28 -08001694 // Lazily instantiate and resize the destination type.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001695 util::unique_cptr<ThemeType>& dest_type = dest_package->types[t];
1696 if (dest_type == nullptr || dest_type->entry_count < type->entry_count) {
1697 const size_t type_alloc_size = sizeof(ThemeType)
1698 + (type->entry_count * sizeof(ThemeEntry));
1699 void* dest_data = malloc(type_alloc_size);
1700 memset(dest_data, 0, type->entry_count * sizeof(ThemeEntry));
1701
Ryan Mitchell93bca972019-03-08 17:26:28 -08001702 // Copy the existing destination type values if the type is resized.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001703 if (dest_type != nullptr) {
1704 memcpy(dest_data, type, sizeof(ThemeType)
1705 + (dest_type->entry_count * sizeof(ThemeEntry)));
1706 }
1707
1708 dest_type.reset(reinterpret_cast<ThemeType *>(dest_data));
1709 dest_type->entry_count = type->entry_count;
1710 }
1711
Ryan Mitchell93bca972019-03-08 17:26:28 -08001712 dest_type->entries[e].cookie = data_dest_cookie;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001713 dest_type->entries[e].value.dataType = entry.value.dataType;
Ryan Mitchell93bca972019-03-08 17:26:28 -08001714 dest_type->entries[e].value.data = attribute_data;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001715 dest_type->entries[e].type_spec_flags = entry.type_spec_flags;
1716 }
1717 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001718 }
1719 }
Ryan Mitchell80094e32020-11-16 23:08:18 +00001720 return {};
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001721}
1722
1723void Theme::Dump() const {
1724 base::ScopedLogSeverity _log(base::INFO);
1725 LOG(INFO) << base::StringPrintf("Theme(this=%p, AssetManager2=%p)", this, asset_manager_);
1726
1727 for (int p = 0; p < packages_.size(); p++) {
1728 auto& package = packages_[p];
1729 if (package == nullptr) {
1730 continue;
1731 }
1732
1733 for (int t = 0; t < package->types.size(); t++) {
1734 auto& type = package->types[t];
1735 if (type == nullptr) {
1736 continue;
1737 }
1738
1739 for (int e = 0; e < type->entry_count; e++) {
1740 auto& entry = type->entries[e];
1741 if (entry.value.dataType == Res_value::TYPE_NULL &&
1742 entry.value.data != Res_value::DATA_NULL_EMPTY) {
1743 continue;
1744 }
1745
1746 LOG(INFO) << base::StringPrintf(" entry(0x%08x)=(0x%08x) type=(0x%02x), cookie(%d)",
1747 make_resid(p, t, e), entry.value.data,
1748 entry.value.dataType, entry.cookie);
1749 }
1750 }
1751 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001752}
1753
1754} // namespace android