blob: ca4143f3e2151261c640127b8a6f947c88ee209a [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
Adam Lesinskibebfcc42018-02-12 14:27:46 -080041struct FindEntryResult {
42 // A pointer to the resource table entry for this resource.
43 // If the size of the entry is > sizeof(ResTable_entry), it can be cast to
44 // a ResTable_map_entry and processed as a bag/map.
Ryan Mitchell8a891d82019-07-01 09:48:23 -070045 ResTable_entry_handle entry;
Adam Lesinskibebfcc42018-02-12 14:27:46 -080046
47 // The configuration for which the resulting entry was defined. This is already swapped to host
48 // endianness.
49 ResTable_config config;
50
51 // The bitmask of configuration axis with which the resource value varies.
52 uint32_t type_flags;
53
54 // The dynamic package ID map for the package from which this resource came from.
55 const DynamicRefTable* dynamic_ref_table;
56
Ryan Mitchell8a891d82019-07-01 09:48:23 -070057 // The package name of the resource.
58 const std::string* package_name;
59
Adam Lesinskibebfcc42018-02-12 14:27:46 -080060 // The string pool reference to the type's name. This uses a different string pool than
61 // the global string pool, but this is hidden from the caller.
62 StringPoolRef type_string_ref;
63
64 // The string pool reference to the entry's name. This uses a different string pool than
65 // the global string pool, but this is hidden from the caller.
66 StringPoolRef entry_string_ref;
67};
68
Adam Lesinski970bd8d2017-09-25 13:21:55 -070069AssetManager2::AssetManager2() {
70 memset(&configuration_, 0, sizeof(configuration_));
71}
Adam Lesinski7ad11102016-10-28 16:39:15 -070072
73bool AssetManager2::SetApkAssets(const std::vector<const ApkAssets*>& apk_assets,
Mårten Kongstad668ec5b2018-06-11 14:11:33 +020074 bool invalidate_caches, bool filter_incompatible_configs) {
Adam Lesinski7ad11102016-10-28 16:39:15 -070075 apk_assets_ = apk_assets;
Adam Lesinskida431a22016-12-29 16:08:16 -050076 BuildDynamicRefTable();
Mårten Kongstad668ec5b2018-06-11 14:11:33 +020077 RebuildFilterList(filter_incompatible_configs);
Adam Lesinski7ad11102016-10-28 16:39:15 -070078 if (invalidate_caches) {
79 InvalidateCaches(static_cast<uint32_t>(-1));
80 }
81 return true;
82}
83
Adam Lesinskida431a22016-12-29 16:08:16 -050084void AssetManager2::BuildDynamicRefTable() {
85 package_groups_.clear();
86 package_ids_.fill(0xff);
87
Ryan Mitchell8a891d82019-07-01 09:48:23 -070088 // A mapping from apk assets path to the runtime package id of its first loaded package.
89 std::unordered_map<std::string, uint8_t> apk_assets_package_ids;
90
Adam Lesinskida431a22016-12-29 16:08:16 -050091 // 0x01 is reserved for the android package.
92 int next_package_id = 0x02;
93 const size_t apk_assets_count = apk_assets_.size();
94 for (size_t i = 0; i < apk_assets_count; i++) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -070095 const ApkAssets* apk_assets = apk_assets_[i];
96 const LoadedArsc* loaded_arsc = apk_assets->GetLoadedArsc();
Adam Lesinski970bd8d2017-09-25 13:21:55 -070097
98 for (const std::unique_ptr<const LoadedPackage>& package : loaded_arsc->GetPackages()) {
Adam Lesinskida431a22016-12-29 16:08:16 -050099 // Get the package ID or assign one if a shared library.
100 int package_id;
101 if (package->IsDynamic()) {
102 package_id = next_package_id++;
103 } else {
104 package_id = package->GetPackageId();
105 }
106
107 // Add the mapping for package ID to index if not present.
108 uint8_t idx = package_ids_[package_id];
109 if (idx == 0xff) {
110 package_ids_[package_id] = idx = static_cast<uint8_t>(package_groups_.size());
111 package_groups_.push_back({});
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700112
113 if (apk_assets->IsOverlay()) {
114 // The target package must precede the overlay package in the apk assets paths in order
115 // to take effect.
116 const auto& loaded_idmap = apk_assets->GetLoadedIdmap();
117 auto target_package_iter = apk_assets_package_ids.find(loaded_idmap->TargetApkPath());
118 if (target_package_iter != apk_assets_package_ids.end()) {
119 const uint8_t target_package_id = target_package_iter->second;
120 const uint8_t target_idx = package_ids_[target_package_id];
121 CHECK(target_idx != 0xff) << "overlay added to apk_assets_package_ids but does not"
122 << " have an assigned package group";
123
124 PackageGroup& target_package_group = package_groups_[target_idx];
125
126 // Create a special dynamic reference table for the overlay to rewite references to
127 // overlay resources as references to the target resources they overlay.
128 auto overlay_table = std::make_shared<OverlayDynamicRefTable>(
129 loaded_idmap->GetOverlayDynamicRefTable(target_package_id));
130 package_groups_.back().dynamic_ref_table = overlay_table;
131
132 // Add the overlay resource map to the target package's set of overlays.
133 target_package_group.overlays_.push_back(
134 ConfiguredOverlay{loaded_idmap->GetTargetResourcesMap(target_package_id,
135 overlay_table.get()),
136 static_cast<ApkAssetsCookie>(i)});
137 }
138 }
139
140 DynamicRefTable* ref_table = package_groups_.back().dynamic_ref_table.get();
141 ref_table->mAssignedPackageId = package_id;
142 ref_table->mAppAsLib = package->IsDynamic() && package->GetPackageId() == 0x7f;
Adam Lesinskida431a22016-12-29 16:08:16 -0500143 }
144 PackageGroup* package_group = &package_groups_[idx];
145
146 // Add the package and to the set of packages with the same ID.
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800147 package_group->packages_.push_back(ConfiguredPackage{package.get(), {}});
Adam Lesinskida431a22016-12-29 16:08:16 -0500148 package_group->cookies_.push_back(static_cast<ApkAssetsCookie>(i));
149
150 // Add the package name -> build time ID mappings.
151 for (const DynamicPackageEntry& entry : package->GetDynamicPackageMap()) {
152 String16 package_name(entry.package_name.c_str(), entry.package_name.size());
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700153 package_group->dynamic_ref_table->mEntries.replaceValueFor(
Adam Lesinskida431a22016-12-29 16:08:16 -0500154 package_name, static_cast<uint8_t>(entry.package_id));
155 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700156
157 apk_assets_package_ids.insert(std::make_pair(apk_assets->GetPath(), package_id));
Adam Lesinskida431a22016-12-29 16:08:16 -0500158 }
159 }
160
161 // Now assign the runtime IDs so that we have a build-time to runtime ID map.
162 const auto package_groups_end = package_groups_.end();
163 for (auto iter = package_groups_.begin(); iter != package_groups_end; ++iter) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800164 const std::string& package_name = iter->packages_[0].loaded_package_->GetPackageName();
Adam Lesinskida431a22016-12-29 16:08:16 -0500165 for (auto iter2 = package_groups_.begin(); iter2 != package_groups_end; ++iter2) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700166 iter2->dynamic_ref_table->addMapping(String16(package_name.c_str(), package_name.size()),
167 iter->dynamic_ref_table->mAssignedPackageId);
Adam Lesinskida431a22016-12-29 16:08:16 -0500168 }
169 }
170}
171
172void AssetManager2::DumpToLog() const {
173 base::ScopedLogSeverity _log(base::INFO);
174
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800175 LOG(INFO) << base::StringPrintf("AssetManager2(this=%p)", this);
176
Adam Lesinskida431a22016-12-29 16:08:16 -0500177 std::string list;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800178 for (const auto& apk_assets : apk_assets_) {
179 base::StringAppendF(&list, "%s,", apk_assets->GetPath().c_str());
180 }
181 LOG(INFO) << "ApkAssets: " << list;
182
183 list = "";
Adam Lesinskida431a22016-12-29 16:08:16 -0500184 for (size_t i = 0; i < package_ids_.size(); i++) {
185 if (package_ids_[i] != 0xff) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800186 base::StringAppendF(&list, "%02x -> %d, ", (int)i, package_ids_[i]);
Adam Lesinskida431a22016-12-29 16:08:16 -0500187 }
188 }
189 LOG(INFO) << "Package ID map: " << list;
190
Adam Lesinski0dd36992018-01-25 15:38:38 -0800191 for (const auto& package_group: package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800192 list = "";
193 for (const auto& package : package_group.packages_) {
194 const LoadedPackage* loaded_package = package.loaded_package_;
195 base::StringAppendF(&list, "%s(%02x%s), ", loaded_package->GetPackageName().c_str(),
196 loaded_package->GetPackageId(),
197 (loaded_package->IsDynamic() ? " dynamic" : ""));
198 }
199 LOG(INFO) << base::StringPrintf("PG (%02x): ",
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700200 package_group.dynamic_ref_table->mAssignedPackageId)
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800201 << list;
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800202
203 for (size_t i = 0; i < 256; i++) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700204 if (package_group.dynamic_ref_table->mLookupTable[i] != 0) {
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800205 LOG(INFO) << base::StringPrintf(" e[0x%02x] -> 0x%02x", (uint8_t) i,
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700206 package_group.dynamic_ref_table->mLookupTable[i]);
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800207 }
208 }
Adam Lesinskida431a22016-12-29 16:08:16 -0500209 }
210}
Adam Lesinski7ad11102016-10-28 16:39:15 -0700211
212const ResStringPool* AssetManager2::GetStringPoolForCookie(ApkAssetsCookie cookie) const {
213 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
214 return nullptr;
215 }
216 return apk_assets_[cookie]->GetLoadedArsc()->GetStringPool();
217}
218
Adam Lesinskida431a22016-12-29 16:08:16 -0500219const DynamicRefTable* AssetManager2::GetDynamicRefTableForPackage(uint32_t package_id) const {
220 if (package_id >= package_ids_.size()) {
221 return nullptr;
222 }
223
224 const size_t idx = package_ids_[package_id];
225 if (idx == 0xff) {
226 return nullptr;
227 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700228 return package_groups_[idx].dynamic_ref_table.get();
Adam Lesinskida431a22016-12-29 16:08:16 -0500229}
230
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700231std::shared_ptr<const DynamicRefTable> AssetManager2::GetDynamicRefTableForCookie(
232 ApkAssetsCookie cookie) const {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800233 for (const PackageGroup& package_group : package_groups_) {
234 for (const ApkAssetsCookie& package_cookie : package_group.cookies_) {
235 if (package_cookie == cookie) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700236 return package_group.dynamic_ref_table;
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800237 }
238 }
239 }
240 return nullptr;
241}
242
Mårten Kongstadc92c4dd2019-02-05 01:29:59 +0100243const std::unordered_map<std::string, std::string>*
244 AssetManager2::GetOverlayableMapForPackage(uint32_t package_id) const {
245
246 if (package_id >= package_ids_.size()) {
247 return nullptr;
248 }
249
250 const size_t idx = package_ids_[package_id];
251 if (idx == 0xff) {
252 return nullptr;
253 }
254
255 const PackageGroup& package_group = package_groups_[idx];
256 if (package_group.packages_.size() == 0) {
257 return nullptr;
258 }
259
260 const auto loaded_package = package_group.packages_[0].loaded_package_;
261 return &loaded_package->GetOverlayableMap();
262}
263
Ryan Mitchell2e394222019-08-28 12:10:51 -0700264bool AssetManager2::GetOverlayablesToString(const android::StringPiece& package_name,
265 std::string* out) const {
266 uint8_t package_id = 0U;
267 for (const auto& apk_assets : apk_assets_) {
268 const LoadedArsc* loaded_arsc = apk_assets->GetLoadedArsc();
269 if (loaded_arsc == nullptr) {
270 continue;
271 }
272
273 const auto& loaded_packages = loaded_arsc->GetPackages();
274 if (loaded_packages.empty()) {
275 continue;
276 }
277
278 const auto& loaded_package = loaded_packages[0];
279 if (loaded_package->GetPackageName() == package_name) {
280 package_id = GetAssignedPackageId(loaded_package.get());
281 break;
282 }
283 }
284
285 if (package_id == 0U) {
286 ANDROID_LOG(ERROR) << base::StringPrintf("No package with name '%s", package_name.data());
287 return false;
288 }
289
290 const size_t idx = package_ids_[package_id];
291 if (idx == 0xff) {
292 return false;
293 }
294
295 std::string output;
296 for (const ConfiguredPackage& package : package_groups_[idx].packages_) {
297 const LoadedPackage* loaded_package = package.loaded_package_;
298 for (auto it = loaded_package->begin(); it != loaded_package->end(); it++) {
299 const OverlayableInfo* info = loaded_package->GetOverlayableInfo(*it);
300 if (info != nullptr) {
301 ResourceName res_name;
302 if (!GetResourceName(*it, &res_name)) {
303 ANDROID_LOG(ERROR) << base::StringPrintf(
304 "Unable to retrieve name of overlayable resource 0x%08x", *it);
305 return false;
306 }
307
308 const std::string name = ToFormattedResourceString(&res_name);
309 output.append(base::StringPrintf(
310 "resource='%s' overlayable='%s' actor='%s' policy='0x%08x'\n",
311 name.c_str(), info->name.c_str(), info->actor.c_str(), info->policy_flags));
312 }
313 }
314 }
315
316 *out = std::move(output);
317 return true;
318}
319
Adam Lesinski7ad11102016-10-28 16:39:15 -0700320void AssetManager2::SetConfiguration(const ResTable_config& configuration) {
321 const int diff = configuration_.diff(configuration);
322 configuration_ = configuration;
323
324 if (diff) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800325 RebuildFilterList();
Adam Lesinski7ad11102016-10-28 16:39:15 -0700326 InvalidateCaches(static_cast<uint32_t>(diff));
327 }
328}
329
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700330std::set<std::string> AssetManager2::GetNonSystemOverlayPaths() const {
331 std::set<std::string> non_system_overlays;
Adam Lesinski0c405242017-01-13 20:47:26 -0800332 for (const PackageGroup& package_group : package_groups_) {
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800333 bool found_system_package = false;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800334 for (const ConfiguredPackage& package : package_group.packages_) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700335 if (package.loaded_package_->IsSystem()) {
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800336 found_system_package = true;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700337 break;
338 }
339 }
340
341 if (!found_system_package) {
342 for (const ConfiguredOverlay& overlay : package_group.overlays_) {
343 non_system_overlays.insert(apk_assets_[overlay.cookie]->GetPath());
344 }
345 }
346 }
347
348 return non_system_overlays;
349}
350
351std::set<ResTable_config> AssetManager2::GetResourceConfigurations(bool exclude_system,
352 bool exclude_mipmap) const {
353 ATRACE_NAME("AssetManager::GetResourceConfigurations");
354 const auto non_system_overlays =
355 (exclude_system) ? GetNonSystemOverlayPaths() : std::set<std::string>();
356
357 std::set<ResTable_config> configurations;
358 for (const PackageGroup& package_group : package_groups_) {
359 for (size_t i = 0; i < package_group.packages_.size(); i++) {
360 const ConfiguredPackage& package = package_group.packages_[i];
361 if (exclude_system && package.loaded_package_->IsSystem()) {
Adam Lesinski0c405242017-01-13 20:47:26 -0800362 continue;
363 }
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800364
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700365 auto apk_assets = apk_assets_[package_group.cookies_[i]];
366 if (exclude_system && apk_assets->IsOverlay()
367 && non_system_overlays.find(apk_assets->GetPath()) == non_system_overlays.end()) {
368 // Exclude overlays that target system resources.
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800369 continue;
370 }
371
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800372 package.loaded_package_->CollectConfigurations(exclude_mipmap, &configurations);
Adam Lesinski0c405242017-01-13 20:47:26 -0800373 }
374 }
375 return configurations;
376}
377
378std::set<std::string> AssetManager2::GetResourceLocales(bool exclude_system,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800379 bool merge_equivalent_languages) const {
380 ATRACE_NAME("AssetManager::GetResourceLocales");
Adam Lesinski0c405242017-01-13 20:47:26 -0800381 std::set<std::string> locales;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700382 const auto non_system_overlays =
383 (exclude_system) ? GetNonSystemOverlayPaths() : std::set<std::string>();
384
Adam Lesinski0c405242017-01-13 20:47:26 -0800385 for (const PackageGroup& package_group : package_groups_) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700386 for (size_t i = 0; i < package_group.packages_.size(); i++) {
387 const ConfiguredPackage& package = package_group.packages_[i];
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800388 if (exclude_system && package.loaded_package_->IsSystem()) {
Adam Lesinski0c405242017-01-13 20:47:26 -0800389 continue;
390 }
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800391
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700392 auto apk_assets = apk_assets_[package_group.cookies_[i]];
393 if (exclude_system && apk_assets->IsOverlay()
394 && non_system_overlays.find(apk_assets->GetPath()) == non_system_overlays.end()) {
395 // Exclude overlays that target system resources.
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800396 continue;
397 }
398
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800399 package.loaded_package_->CollectLocales(merge_equivalent_languages, &locales);
Adam Lesinski0c405242017-01-13 20:47:26 -0800400 }
401 }
402 return locales;
403}
404
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800405std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename,
406 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700407 const std::string new_path = "assets/" + filename;
408 return OpenNonAsset(new_path, mode);
409}
410
411std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename, ApkAssetsCookie cookie,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800412 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700413 const std::string new_path = "assets/" + filename;
414 return OpenNonAsset(new_path, cookie, mode);
415}
416
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800417std::unique_ptr<AssetDir> AssetManager2::OpenDir(const std::string& dirname) const {
418 ATRACE_NAME("AssetManager::OpenDir");
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800419
420 std::string full_path = "assets/" + dirname;
421 std::unique_ptr<SortedVector<AssetDir::FileInfo>> files =
422 util::make_unique<SortedVector<AssetDir::FileInfo>>();
423
424 // Start from the back.
425 for (auto iter = apk_assets_.rbegin(); iter != apk_assets_.rend(); ++iter) {
426 const ApkAssets* apk_assets = *iter;
Mårten Kongstaddbf343b2019-02-21 07:54:18 +0100427 if (apk_assets->IsOverlay()) {
428 continue;
429 }
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800430
431 auto func = [&](const StringPiece& name, FileType type) {
432 AssetDir::FileInfo info;
433 info.setFileName(String8(name.data(), name.size()));
434 info.setFileType(type);
435 info.setSourceName(String8(apk_assets->GetPath().c_str()));
436 files->add(info);
437 };
438
439 if (!apk_assets->ForEachFile(full_path, func)) {
440 return {};
441 }
442 }
443
444 std::unique_ptr<AssetDir> asset_dir = util::make_unique<AssetDir>();
445 asset_dir->setFileList(files.release());
446 return asset_dir;
447}
448
Adam Lesinski7ad11102016-10-28 16:39:15 -0700449// Search in reverse because that's how we used to do it and we need to preserve behaviour.
450// This is unfortunate, because ClassLoaders delegate to the parent first, so the order
451// is inconsistent for split APKs.
452std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
453 Asset::AccessMode mode,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800454 ApkAssetsCookie* out_cookie) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700455 for (int32_t i = apk_assets_.size() - 1; i >= 0; i--) {
Mårten Kongstaddbf343b2019-02-21 07:54:18 +0100456 // Prevent RRO from modifying assets and other entries accessed by file
457 // path. Explicitly asking for a path in a given package (denoted by a
458 // cookie) is still OK.
459 if (apk_assets_[i]->IsOverlay()) {
460 continue;
461 }
462
Adam Lesinski7ad11102016-10-28 16:39:15 -0700463 std::unique_ptr<Asset> asset = apk_assets_[i]->Open(filename, mode);
464 if (asset) {
465 if (out_cookie != nullptr) {
466 *out_cookie = i;
467 }
468 return asset;
469 }
470 }
471
472 if (out_cookie != nullptr) {
473 *out_cookie = kInvalidCookie;
474 }
475 return {};
476}
477
478std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800479 ApkAssetsCookie cookie,
480 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700481 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
482 return {};
483 }
484 return apk_assets_[cookie]->Open(filename, mode);
485}
486
487ApkAssetsCookie AssetManager2::FindEntry(uint32_t resid, uint16_t density_override,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800488 bool /*stop_at_first_match*/,
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800489 bool ignore_configuration,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800490 FindEntryResult* out_entry) const {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700491 if (resource_resolution_logging_enabled_) {
492 // Clear the last logged resource resolution.
493 ResetResourceResolution();
494 last_resolution_.resid = resid;
495 }
496
Adam Lesinski7ad11102016-10-28 16:39:15 -0700497 // Might use this if density_override != 0.
498 ResTable_config density_override_config;
499
500 // Select our configuration or generate a density override configuration.
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800501 const ResTable_config* desired_config = &configuration_;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700502 if (density_override != 0 && density_override != configuration_.density) {
503 density_override_config = configuration_;
504 density_override_config.density = density_override;
505 desired_config = &density_override_config;
506 }
507
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700508 // Retrieve the package group from the package id of the resource id.
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800509 if (!is_valid_resid(resid)) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500510 LOG(ERROR) << base::StringPrintf("Invalid ID 0x%08x.", resid);
511 return kInvalidCookie;
512 }
513
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800514 const uint32_t package_id = get_package_id(resid);
515 const uint8_t type_idx = get_type_id(resid) - 1;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800516 const uint16_t entry_idx = get_entry_id(resid);
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700517 uint8_t package_idx = package_ids_[package_id];
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800518 if (package_idx == 0xff) {
Ryan Mitchell2fe23472019-02-27 09:43:01 -0800519 ANDROID_LOG(ERROR) << base::StringPrintf("No package ID %02x found for ID 0x%08x.",
520 package_id, resid);
Adam Lesinskida431a22016-12-29 16:08:16 -0500521 return kInvalidCookie;
522 }
523
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800524 const PackageGroup& package_group = package_groups_[package_idx];
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700525 ApkAssetsCookie cookie = FindEntryInternal(package_group, type_idx, entry_idx, *desired_config,
526 false /* stop_at_first_match */,
527 ignore_configuration, out_entry);
528 if (UNLIKELY(cookie == kInvalidCookie)) {
529 return kInvalidCookie;
530 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800531
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700532 if (!apk_assets_[cookie]->IsLoader()) {
533 for (const auto& id_map : package_group.overlays_) {
534 auto overlay_entry = id_map.overlay_res_maps_.Lookup(resid);
535 if (!overlay_entry) {
536 // No id map entry exists for this target resource.
537 continue;
538 }
539
540 if (overlay_entry.IsTableEntry()) {
541 // The target resource is overlaid by an inline value not represented by a resource.
542 out_entry->entry = overlay_entry.GetTableEntry();
543 out_entry->dynamic_ref_table = id_map.overlay_res_maps_.GetOverlayDynamicRefTable();
544 cookie = id_map.cookie;
545 continue;
546 }
547
548 FindEntryResult overlay_result;
549 ApkAssetsCookie overlay_cookie = FindEntry(overlay_entry.GetResourceId(), density_override,
550 false /* stop_at_first_match */,
551 ignore_configuration, &overlay_result);
552 if (UNLIKELY(overlay_cookie == kInvalidCookie)) {
553 continue;
554 }
555
556 if (!overlay_result.config.isBetterThan(out_entry->config, desired_config)
557 && overlay_result.config.compare(out_entry->config) != 0) {
558 // The configuration of the entry for the overlay must be equal to or better than the target
559 // configuration to be chosen as the better value.
560 continue;
561 }
562
563 cookie = overlay_cookie;
564 out_entry->entry = std::move(overlay_result.entry);
565 out_entry->config = overlay_result.config;
566 out_entry->dynamic_ref_table = id_map.overlay_res_maps_.GetOverlayDynamicRefTable();
567 if (resource_resolution_logging_enabled_) {
568 last_resolution_.steps.push_back(
569 Resolution::Step{Resolution::Step::Type::OVERLAID, overlay_result.config.toString(),
570 &package_group.packages_[0].loaded_package_->GetPackageName()});
571 }
572 }
573 }
574
575 if (resource_resolution_logging_enabled_) {
576 last_resolution_.cookie = cookie;
577 last_resolution_.type_string_ref = out_entry->type_string_ref;
578 last_resolution_.entry_string_ref = out_entry->entry_string_ref;
579 }
580
581 return cookie;
582}
583
584ApkAssetsCookie AssetManager2::FindEntryInternal(const PackageGroup& package_group,
585 uint8_t type_idx, uint16_t entry_idx,
586 const ResTable_config& desired_config,
587 bool /*stop_at_first_match*/,
588 bool ignore_configuration,
589 FindEntryResult* out_entry) const {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800590 ApkAssetsCookie best_cookie = kInvalidCookie;
591 const LoadedPackage* best_package = nullptr;
592 const ResTable_type* best_type = nullptr;
593 const ResTable_config* best_config = nullptr;
594 ResTable_config best_config_copy;
595 uint32_t best_offset = 0u;
596 uint32_t type_flags = 0u;
597
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700598 Resolution::Step::Type resolution_type = Resolution::Step::Type::NO_ENTRY;
Winson2f3669b2019-01-11 11:28:34 -0800599 std::vector<Resolution::Step> resolution_steps;
600
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800601 // If desired_config is the same as the set configuration, then we can use our filtered list
602 // and we don't need to match the configurations, since they already matched.
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700603 const bool use_fast_path = !ignore_configuration && &desired_config == &configuration_;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800604
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700605 const size_t package_count = package_group.packages_.size();
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800606 for (size_t pi = 0; pi < package_count; pi++) {
607 const ConfiguredPackage& loaded_package_impl = package_group.packages_[pi];
608 const LoadedPackage* loaded_package = loaded_package_impl.loaded_package_;
609 ApkAssetsCookie cookie = package_group.cookies_[pi];
610
611 // If the type IDs are offset in this package, we need to take that into account when searching
612 // for a type.
613 const TypeSpec* type_spec = loaded_package->GetTypeSpecByTypeIndex(type_idx);
614 if (UNLIKELY(type_spec == nullptr)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700615 continue;
616 }
617
Winson9947f1e2019-08-16 10:20:39 -0700618 // If the package is an overlay or custom loader,
619 // then even configurations that are the same MUST be chosen.
Winson9947f1e2019-08-16 10:20:39 -0700620 const bool package_is_loader = loaded_package->IsCustomLoader();
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700621 type_flags |= type_spec->GetFlagsForEntryIndex(entry_idx);
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800622
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800623 if (use_fast_path) {
Winson2f3669b2019-01-11 11:28:34 -0800624 const FilteredConfigGroup& filtered_group = loaded_package_impl.filtered_configs_[type_idx];
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800625 const std::vector<ResTable_config>& candidate_configs = filtered_group.configurations;
626 const size_t type_count = candidate_configs.size();
627 for (uint32_t i = 0; i < type_count; i++) {
628 const ResTable_config& this_config = candidate_configs[i];
629
630 // We can skip calling ResTable_config::match() because we know that all candidate
631 // configurations that do NOT match have been filtered-out.
Winson2f3669b2019-01-11 11:28:34 -0800632 if (best_config == nullptr) {
633 resolution_type = Resolution::Step::Type::INITIAL;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700634 } else if (this_config.isBetterThan(*best_config, &desired_config)) {
635 resolution_type = (package_is_loader) ? Resolution::Step::Type::BETTER_MATCH_LOADER
636 : Resolution::Step::Type::BETTER_MATCH;
637 } else if (package_is_loader && this_config.compare(*best_config) == 0) {
638 resolution_type = Resolution::Step::Type::OVERLAID_LOADER;
Winson2f3669b2019-01-11 11:28:34 -0800639 } else {
Winson9947f1e2019-08-16 10:20:39 -0700640 if (resource_resolution_logging_enabled_) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700641 resolution_type = (package_is_loader) ? Resolution::Step::Type::SKIPPED_LOADER
642 : Resolution::Step::Type::SKIPPED;
Winson9947f1e2019-08-16 10:20:39 -0700643 resolution_steps.push_back(Resolution::Step{resolution_type,
644 this_config.toString(),
645 &loaded_package->GetPackageName()});
646 }
Winson2f3669b2019-01-11 11:28:34 -0800647 continue;
648 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800649
Winson2f3669b2019-01-11 11:28:34 -0800650 // The configuration matches and is better than the previous selection.
651 // Find the entry value if it exists for this configuration.
652 const ResTable_type* type = filtered_group.types[i];
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700653 const uint32_t offset = LoadedPackage::GetEntryOffset(type, entry_idx);
Winson2f3669b2019-01-11 11:28:34 -0800654 if (offset == ResTable_type::NO_ENTRY) {
Winson9947f1e2019-08-16 10:20:39 -0700655 if (resource_resolution_logging_enabled_) {
656 if (package_is_loader) {
657 resolution_type = Resolution::Step::Type::NO_ENTRY_LOADER;
658 } else {
659 resolution_type = Resolution::Step::Type::NO_ENTRY;
660 }
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700661 resolution_steps.push_back(Resolution::Step{resolution_type,
Winson9947f1e2019-08-16 10:20:39 -0700662 this_config.toString(),
663 &loaded_package->GetPackageName()});
664 }
Winson2f3669b2019-01-11 11:28:34 -0800665 continue;
666 }
667
668 best_cookie = cookie;
669 best_package = loaded_package;
670 best_type = type;
671 best_config = &this_config;
672 best_offset = offset;
673
674 if (resource_resolution_logging_enabled_) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700675 last_resolution_.steps.push_back(Resolution::Step{resolution_type,
676 this_config.toString(),
677 &loaded_package->GetPackageName()});
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800678 }
679 }
680 } else {
681 // This is the slower path, which doesn't use the filtered list of configurations.
682 // Here we must read the ResTable_config from the mmapped APK, convert it to host endianness
683 // and fill in any new fields that did not exist when the APK was compiled.
684 // Furthermore when selecting configurations we can't just record the pointer to the
685 // ResTable_config, we must copy it.
686 const auto iter_end = type_spec->types + type_spec->type_count;
687 for (auto iter = type_spec->types; iter != iter_end; ++iter) {
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800688 ResTable_config this_config{};
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800689
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800690 if (!ignore_configuration) {
691 this_config.copyFromDtoH((*iter)->config);
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700692 if (!this_config.match(desired_config)) {
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800693 continue;
694 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800695
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800696 if (best_config == nullptr) {
697 resolution_type = Resolution::Step::Type::INITIAL;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700698 } else if (this_config.isBetterThan(*best_config, &desired_config)) {
699 resolution_type = (package_is_loader) ? Resolution::Step::Type::BETTER_MATCH_LOADER
700 : Resolution::Step::Type::BETTER_MATCH;
701 } else if (package_is_loader && this_config.compare(*best_config) == 0) {
702 resolution_type = Resolution::Step::Type::OVERLAID_LOADER;
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800703 } else {
704 continue;
705 }
Winson2f3669b2019-01-11 11:28:34 -0800706 }
707
708 // The configuration matches and is better than the previous selection.
709 // Find the entry value if it exists for this configuration.
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700710 const uint32_t offset = LoadedPackage::GetEntryOffset(*iter, entry_idx);
Winson2f3669b2019-01-11 11:28:34 -0800711 if (offset == ResTable_type::NO_ENTRY) {
712 continue;
713 }
714
715 best_cookie = cookie;
716 best_package = loaded_package;
717 best_type = *iter;
718 best_config_copy = this_config;
719 best_config = &best_config_copy;
720 best_offset = offset;
721
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800722 if (ignore_configuration) {
723 // Any configuration will suffice, so break.
724 break;
725 }
726
Winson2f3669b2019-01-11 11:28:34 -0800727 if (resource_resolution_logging_enabled_) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700728 last_resolution_.steps.push_back(Resolution::Step{resolution_type,
729 this_config.toString(),
730 &loaded_package->GetPackageName()});
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800731 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700732 }
733 }
734 }
735
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800736 if (UNLIKELY(best_cookie == kInvalidCookie)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700737 return kInvalidCookie;
738 }
739
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800740 const ResTable_entry* best_entry = LoadedPackage::GetEntryFromOffset(best_type, best_offset);
741 if (UNLIKELY(best_entry == nullptr)) {
742 return kInvalidCookie;
743 }
744
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700745 out_entry->entry = ResTable_entry_handle::unmanaged(best_entry);
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800746 out_entry->config = *best_config;
747 out_entry->type_flags = type_flags;
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700748 out_entry->package_name = &best_package->GetPackageName();
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800749 out_entry->type_string_ref = StringPoolRef(best_package->GetTypeStringPool(), best_type->id - 1);
750 out_entry->entry_string_ref =
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700751 StringPoolRef(best_package->GetKeyStringPool(), best_entry->key.index);
752 out_entry->dynamic_ref_table = package_group.dynamic_ref_table.get();
Winson2f3669b2019-01-11 11:28:34 -0800753
Adam Lesinskida431a22016-12-29 16:08:16 -0500754 return best_cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700755}
756
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700757void AssetManager2::ResetResourceResolution() const {
758 last_resolution_.cookie = kInvalidCookie;
759 last_resolution_.resid = 0;
760 last_resolution_.steps.clear();
761 last_resolution_.type_string_ref = StringPoolRef();
762 last_resolution_.entry_string_ref = StringPoolRef();
763}
764
Winson2f3669b2019-01-11 11:28:34 -0800765void AssetManager2::SetResourceResolutionLoggingEnabled(bool enabled) {
766 resource_resolution_logging_enabled_ = enabled;
Winson2f3669b2019-01-11 11:28:34 -0800767 if (!enabled) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700768 ResetResourceResolution();
Winson2f3669b2019-01-11 11:28:34 -0800769 }
770}
771
772std::string AssetManager2::GetLastResourceResolution() const {
773 if (!resource_resolution_logging_enabled_) {
774 LOG(ERROR) << "Must enable resource resolution logging before getting path.";
775 return std::string();
776 }
777
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700778 auto cookie = last_resolution_.cookie;
Winson2f3669b2019-01-11 11:28:34 -0800779 if (cookie == kInvalidCookie) {
780 LOG(ERROR) << "AssetManager hasn't resolved a resource to read resolution path.";
781 return std::string();
782 }
783
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700784 uint32_t resid = last_resolution_.resid;
785 std::vector<Resolution::Step>& steps = last_resolution_.steps;
Winson2f3669b2019-01-11 11:28:34 -0800786
787 ResourceName resource_name;
788 std::string resource_name_string;
789
790 const LoadedPackage* package =
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700791 apk_assets_[cookie]->GetLoadedArsc()->GetPackageById(get_package_id(resid));
Winson2f3669b2019-01-11 11:28:34 -0800792
793 if (package != nullptr) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700794 ToResourceName(last_resolution_.type_string_ref,
795 last_resolution_.entry_string_ref,
Ryan Mitchell741e96f2019-01-23 16:56:51 -0800796 package->GetPackageName(),
Winson2f3669b2019-01-11 11:28:34 -0800797 &resource_name);
798 resource_name_string = ToFormattedResourceString(&resource_name);
799 }
800
801 std::stringstream log_stream;
802 log_stream << base::StringPrintf("Resolution for 0x%08x ", resid)
803 << resource_name_string
804 << "\n\tFor config -"
805 << configuration_.toString();
806
807 std::string prefix;
808 for (Resolution::Step step : steps) {
809 switch (step.type) {
810 case Resolution::Step::Type::INITIAL:
811 prefix = "Found initial";
812 break;
813 case Resolution::Step::Type::BETTER_MATCH:
814 prefix = "Found better";
815 break;
Winson9947f1e2019-08-16 10:20:39 -0700816 case Resolution::Step::Type::BETTER_MATCH_LOADER:
817 prefix = "Found better in loader";
818 break;
Winson2f3669b2019-01-11 11:28:34 -0800819 case Resolution::Step::Type::OVERLAID:
820 prefix = "Overlaid";
821 break;
Winson9947f1e2019-08-16 10:20:39 -0700822 case Resolution::Step::Type::OVERLAID_LOADER:
823 prefix = "Overlaid by loader";
824 break;
825 case Resolution::Step::Type::SKIPPED:
826 prefix = "Skipped";
827 break;
828 case Resolution::Step::Type::SKIPPED_LOADER:
829 prefix = "Skipped loader";
830 break;
831 case Resolution::Step::Type::NO_ENTRY:
832 prefix = "No entry";
833 break;
834 case Resolution::Step::Type::NO_ENTRY_LOADER:
835 prefix = "No entry for loader";
836 break;
Winson2f3669b2019-01-11 11:28:34 -0800837 }
838
839 if (!prefix.empty()) {
840 log_stream << "\n\t" << prefix << ": " << *step.package_name;
841
842 if (!step.config_name.isEmpty()) {
843 log_stream << " -" << step.config_name;
844 }
845 }
846 }
847
848 return log_stream.str();
849}
850
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800851bool AssetManager2::GetResourceName(uint32_t resid, ResourceName* out_name) const {
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700852 FindEntryResult entry;
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800853 ApkAssetsCookie cookie = FindEntry(resid, 0u /* density_override */,
854 true /* stop_at_first_match */,
855 true /* ignore_configuration */, &entry);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700856 if (cookie == kInvalidCookie) {
857 return false;
858 }
859
Winson2f3669b2019-01-11 11:28:34 -0800860 return ToResourceName(entry.type_string_ref,
861 entry.entry_string_ref,
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700862 *entry.package_name,
Winson2f3669b2019-01-11 11:28:34 -0800863 out_name);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700864}
865
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800866bool AssetManager2::GetResourceFlags(uint32_t resid, uint32_t* out_flags) const {
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700867 FindEntryResult entry;
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800868 ApkAssetsCookie cookie = FindEntry(resid, 0u /* density_override */,
869 false /* stop_at_first_match */,
870 true /* ignore_configuration */, &entry);
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700871 if (cookie != kInvalidCookie) {
872 *out_flags = entry.type_flags;
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800873 return true;
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700874 }
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800875 return false;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700876}
877
878ApkAssetsCookie AssetManager2::GetResource(uint32_t resid, bool may_be_bag,
879 uint16_t density_override, Res_value* out_value,
880 ResTable_config* out_selected_config,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800881 uint32_t* out_flags) const {
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700882 FindEntryResult entry;
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800883 ApkAssetsCookie cookie = FindEntry(resid, density_override, false /* stop_at_first_match */,
884 false /* ignore_configuration */, &entry);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700885 if (cookie == kInvalidCookie) {
886 return kInvalidCookie;
887 }
888
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700889 const ResTable_entry* table_entry = *entry.entry;
890 if (dtohs(table_entry->flags) & ResTable_entry::FLAG_COMPLEX) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700891 if (!may_be_bag) {
892 LOG(ERROR) << base::StringPrintf("Resource %08x is a complex map type.", resid);
Adam Lesinski0c405242017-01-13 20:47:26 -0800893 return kInvalidCookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700894 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800895
896 // Create a reference since we can't represent this complex type as a Res_value.
897 out_value->dataType = Res_value::TYPE_REFERENCE;
898 out_value->data = resid;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800899 *out_selected_config = entry.config;
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700900 *out_flags = entry.type_flags;
Adam Lesinski0c405242017-01-13 20:47:26 -0800901 return cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700902 }
903
904 const Res_value* device_value = reinterpret_cast<const Res_value*>(
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700905 reinterpret_cast<const uint8_t*>(table_entry) + dtohs(table_entry->size));
Adam Lesinski7ad11102016-10-28 16:39:15 -0700906 out_value->copyFrom_dtoh(*device_value);
Adam Lesinskida431a22016-12-29 16:08:16 -0500907
908 // Convert the package ID to the runtime assigned package ID.
909 entry.dynamic_ref_table->lookupResourceValue(out_value);
910
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800911 *out_selected_config = entry.config;
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700912 *out_flags = entry.type_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700913 return cookie;
914}
915
Adam Lesinski0c405242017-01-13 20:47:26 -0800916ApkAssetsCookie AssetManager2::ResolveReference(ApkAssetsCookie cookie, Res_value* in_out_value,
917 ResTable_config* in_out_selected_config,
918 uint32_t* in_out_flags,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800919 uint32_t* out_last_reference) const {
Adam Lesinski0c405242017-01-13 20:47:26 -0800920 constexpr const int kMaxIterations = 20;
921
Adam Lesinski0c405242017-01-13 20:47:26 -0800922 for (size_t iteration = 0u; in_out_value->dataType == Res_value::TYPE_REFERENCE &&
923 in_out_value->data != 0u && iteration < kMaxIterations;
924 iteration++) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800925 *out_last_reference = in_out_value->data;
Adam Lesinski0c405242017-01-13 20:47:26 -0800926 uint32_t new_flags = 0u;
927 cookie = GetResource(in_out_value->data, true /*may_be_bag*/, 0u /*density_override*/,
928 in_out_value, in_out_selected_config, &new_flags);
929 if (cookie == kInvalidCookie) {
930 return kInvalidCookie;
931 }
932 if (in_out_flags != nullptr) {
933 *in_out_flags |= new_flags;
934 }
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800935 if (*out_last_reference == in_out_value->data) {
Adam Lesinski0c405242017-01-13 20:47:26 -0800936 // This reference can't be resolved, so exit now and let the caller deal with it.
937 return cookie;
938 }
939 }
940 return cookie;
941}
942
Aurimas Liutikas8f004c82019-01-17 17:20:10 -0800943const std::vector<uint32_t> AssetManager2::GetBagResIdStack(uint32_t resid) {
944 auto cached_iter = cached_bag_resid_stacks_.find(resid);
945 if (cached_iter != cached_bag_resid_stacks_.end()) {
946 return cached_iter->second;
947 } else {
948 auto found_resids = std::vector<uint32_t>();
949 GetBag(resid, found_resids);
950 // Cache style stacks if they are not already cached.
951 cached_bag_resid_stacks_[resid] = found_resids;
952 return found_resids;
953 }
954}
955
Adam Lesinski7ad11102016-10-28 16:39:15 -0700956const ResolvedBag* AssetManager2::GetBag(uint32_t resid) {
y57cd1952018-04-12 14:26:23 -0700957 auto found_resids = std::vector<uint32_t>();
Aurimas Liutikas8f004c82019-01-17 17:20:10 -0800958 auto bag = GetBag(resid, found_resids);
959
960 // Cache style stacks if they are not already cached.
961 auto cached_iter = cached_bag_resid_stacks_.find(resid);
962 if (cached_iter == cached_bag_resid_stacks_.end()) {
963 cached_bag_resid_stacks_[resid] = found_resids;
964 }
965 return bag;
y57cd1952018-04-12 14:26:23 -0700966}
967
968const ResolvedBag* AssetManager2::GetBag(uint32_t resid, std::vector<uint32_t>& child_resids) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700969 auto cached_iter = cached_bags_.find(resid);
970 if (cached_iter != cached_bags_.end()) {
971 return cached_iter->second.get();
972 }
973
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700974 FindEntryResult entry;
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800975 ApkAssetsCookie cookie = FindEntry(resid, 0u /* density_override */,
976 false /* stop_at_first_match */,
977 false /* ignore_configuration */,
978 &entry);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700979 if (cookie == kInvalidCookie) {
980 return nullptr;
981 }
982
983 // Check that the size of the entry header is at least as big as
984 // the desired ResTable_map_entry. Also verify that the entry
985 // was intended to be a map.
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700986 const ResTable_entry* table_entry = *entry.entry;
987 if (dtohs(table_entry->size) < sizeof(ResTable_map_entry) ||
988 (dtohs(table_entry->flags) & ResTable_entry::FLAG_COMPLEX) == 0) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700989 // Not a bag, nothing to do.
990 return nullptr;
991 }
992
Ryan Mitchell8a891d82019-07-01 09:48:23 -0700993 const ResTable_map_entry* map = reinterpret_cast<const ResTable_map_entry*>(table_entry);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700994 const ResTable_map* map_entry =
995 reinterpret_cast<const ResTable_map*>(reinterpret_cast<const uint8_t*>(map) + map->size);
996 const ResTable_map* const map_entry_end = map_entry + dtohl(map->count);
997
y57cd1952018-04-12 14:26:23 -0700998 // Keep track of ids that have already been seen to prevent infinite loops caused by circular
999 // dependencies between bags
1000 child_resids.push_back(resid);
1001
Adam Lesinskida431a22016-12-29 16:08:16 -05001002 uint32_t parent_resid = dtohl(map->parent.ident);
y57cd1952018-04-12 14:26:23 -07001003 if (parent_resid == 0 || std::find(child_resids.begin(), child_resids.end(), parent_resid)
1004 != child_resids.end()) {
1005 // There is no parent or that a circular dependency exist, meaning there is nothing to
1006 // inherit and we can do a simple copy of the entries in the map.
Adam Lesinski7ad11102016-10-28 16:39:15 -07001007 const size_t entry_count = map_entry_end - map_entry;
1008 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
1009 malloc(sizeof(ResolvedBag) + (entry_count * sizeof(ResolvedBag::Entry))))};
1010 ResolvedBag::Entry* new_entry = new_bag->entries;
1011 for (; map_entry != map_entry_end; ++map_entry) {
Adam Lesinskida431a22016-12-29 16:08:16 -05001012 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001013 if (!is_internal_resid(new_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -05001014 // Attributes, arrays, etc don't have a resource id as the name. They specify
1015 // other data, which would be wrong to change via a lookup.
1016 if (entry.dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001017 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
1018 resid);
Adam Lesinskida431a22016-12-29 16:08:16 -05001019 return nullptr;
1020 }
1021 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001022 new_entry->cookie = cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -05001023 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001024 new_entry->key_pool = nullptr;
1025 new_entry->type_pool = nullptr;
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001026 new_entry->style = resid;
Adam Lesinski30080e22017-10-16 16:18:09 -07001027 new_entry->value.copyFrom_dtoh(map_entry->value);
1028 status_t err = entry.dynamic_ref_table->lookupResourceValue(&new_entry->value);
1029 if (err != NO_ERROR) {
1030 LOG(ERROR) << base::StringPrintf(
1031 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
1032 new_entry->value.data, new_key);
1033 return nullptr;
1034 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001035 ++new_entry;
1036 }
Adam Lesinski1a1e9c22017-10-13 15:45:34 -07001037 new_bag->type_spec_flags = entry.type_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001038 new_bag->entry_count = static_cast<uint32_t>(entry_count);
1039 ResolvedBag* result = new_bag.get();
1040 cached_bags_[resid] = std::move(new_bag);
1041 return result;
1042 }
1043
Adam Lesinskida431a22016-12-29 16:08:16 -05001044 // In case the parent is a dynamic reference, resolve it.
1045 entry.dynamic_ref_table->lookupResourceId(&parent_resid);
1046
Adam Lesinski7ad11102016-10-28 16:39:15 -07001047 // Get the parent and do a merge of the keys.
y57cd1952018-04-12 14:26:23 -07001048 const ResolvedBag* parent_bag = GetBag(parent_resid, child_resids);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001049 if (parent_bag == nullptr) {
1050 // Failed to get the parent that should exist.
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001051 LOG(ERROR) << base::StringPrintf("Failed to find parent 0x%08x of bag 0x%08x.", parent_resid,
1052 resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001053 return nullptr;
1054 }
1055
Adam Lesinski7ad11102016-10-28 16:39:15 -07001056 // Create the max possible entries we can make. Once we construct the bag,
1057 // we will realloc to fit to size.
1058 const size_t max_count = parent_bag->entry_count + dtohl(map->count);
George Burgess IV09b119f2017-07-25 15:00:04 -07001059 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
1060 malloc(sizeof(ResolvedBag) + (max_count * sizeof(ResolvedBag::Entry))))};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001061 ResolvedBag::Entry* new_entry = new_bag->entries;
1062
1063 const ResolvedBag::Entry* parent_entry = parent_bag->entries;
1064 const ResolvedBag::Entry* const parent_entry_end = parent_entry + parent_bag->entry_count;
1065
1066 // The keys are expected to be in sorted order. Merge the two bags.
1067 while (map_entry != map_entry_end && parent_entry != parent_entry_end) {
Adam Lesinskida431a22016-12-29 16:08:16 -05001068 uint32_t child_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001069 if (!is_internal_resid(child_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -05001070 if (entry.dynamic_ref_table->lookupResourceId(&child_key) != NO_ERROR) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001071 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", child_key,
1072 resid);
Adam Lesinskida431a22016-12-29 16:08:16 -05001073 return nullptr;
1074 }
1075 }
1076
Adam Lesinski7ad11102016-10-28 16:39:15 -07001077 if (child_key <= parent_entry->key) {
1078 // Use the child key if it comes before the parent
1079 // or is equal to the parent (overrides).
1080 new_entry->cookie = cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001081 new_entry->key = child_key;
1082 new_entry->key_pool = nullptr;
1083 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -07001084 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001085 new_entry->style = resid;
Adam Lesinski30080e22017-10-16 16:18:09 -07001086 status_t err = entry.dynamic_ref_table->lookupResourceValue(&new_entry->value);
1087 if (err != NO_ERROR) {
1088 LOG(ERROR) << base::StringPrintf(
1089 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
1090 new_entry->value.data, child_key);
1091 return nullptr;
1092 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001093 ++map_entry;
1094 } else {
1095 // Take the parent entry as-is.
1096 memcpy(new_entry, parent_entry, sizeof(*new_entry));
1097 }
1098
1099 if (child_key >= parent_entry->key) {
1100 // Move to the next parent entry if we used it or it was overridden.
1101 ++parent_entry;
1102 }
1103 // Increment to the next entry to fill.
1104 ++new_entry;
1105 }
1106
1107 // Finish the child entries if they exist.
1108 while (map_entry != map_entry_end) {
Adam Lesinskida431a22016-12-29 16:08:16 -05001109 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -08001110 if (!is_internal_resid(new_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -05001111 if (entry.dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001112 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
1113 resid);
Adam Lesinskida431a22016-12-29 16:08:16 -05001114 return nullptr;
1115 }
1116 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001117 new_entry->cookie = cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -05001118 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001119 new_entry->key_pool = nullptr;
1120 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -07001121 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -08001122 new_entry->style = resid;
Adam Lesinski30080e22017-10-16 16:18:09 -07001123 status_t err = entry.dynamic_ref_table->lookupResourceValue(&new_entry->value);
1124 if (err != NO_ERROR) {
1125 LOG(ERROR) << base::StringPrintf("Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.",
1126 new_entry->value.dataType, new_entry->value.data, new_key);
1127 return nullptr;
1128 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001129 ++map_entry;
1130 ++new_entry;
1131 }
1132
1133 // Finish the parent entries if they exist.
1134 if (parent_entry != parent_entry_end) {
1135 // Take the rest of the parent entries as-is.
1136 const size_t num_entries_to_copy = parent_entry_end - parent_entry;
1137 memcpy(new_entry, parent_entry, num_entries_to_copy * sizeof(*new_entry));
1138 new_entry += num_entries_to_copy;
1139 }
1140
1141 // Resize the resulting array to fit.
1142 const size_t actual_count = new_entry - new_bag->entries;
1143 if (actual_count != max_count) {
George Burgess IV09b119f2017-07-25 15:00:04 -07001144 new_bag.reset(reinterpret_cast<ResolvedBag*>(realloc(
1145 new_bag.release(), sizeof(ResolvedBag) + (actual_count * sizeof(ResolvedBag::Entry)))));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001146 }
1147
Adam Lesinski1a1e9c22017-10-13 15:45:34 -07001148 // Combine flags from the parent and our own bag.
1149 new_bag->type_spec_flags = entry.type_flags | parent_bag->type_spec_flags;
George Burgess IV09b119f2017-07-25 15:00:04 -07001150 new_bag->entry_count = static_cast<uint32_t>(actual_count);
1151 ResolvedBag* result = new_bag.get();
1152 cached_bags_[resid] = std::move(new_bag);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001153 return result;
1154}
1155
Adam Lesinski929d6512017-01-16 19:11:19 -08001156static bool Utf8ToUtf16(const StringPiece& str, std::u16string* out) {
1157 ssize_t len =
1158 utf8_to_utf16_length(reinterpret_cast<const uint8_t*>(str.data()), str.size(), false);
1159 if (len < 0) {
1160 return false;
1161 }
1162 out->resize(static_cast<size_t>(len));
1163 utf8_to_utf16(reinterpret_cast<const uint8_t*>(str.data()), str.size(), &*out->begin(),
1164 static_cast<size_t>(len + 1));
1165 return true;
1166}
1167
Adam Lesinski0c405242017-01-13 20:47:26 -08001168uint32_t AssetManager2::GetResourceId(const std::string& resource_name,
1169 const std::string& fallback_type,
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001170 const std::string& fallback_package) const {
Adam Lesinski929d6512017-01-16 19:11:19 -08001171 StringPiece package_name, type, entry;
1172 if (!ExtractResourceName(resource_name, &package_name, &type, &entry)) {
1173 return 0u;
1174 }
1175
1176 if (entry.empty()) {
1177 return 0u;
1178 }
1179
1180 if (package_name.empty()) {
1181 package_name = fallback_package;
1182 }
1183
1184 if (type.empty()) {
1185 type = fallback_type;
1186 }
1187
1188 std::u16string type16;
1189 if (!Utf8ToUtf16(type, &type16)) {
1190 return 0u;
1191 }
1192
1193 std::u16string entry16;
1194 if (!Utf8ToUtf16(entry, &entry16)) {
1195 return 0u;
1196 }
1197
1198 const StringPiece16 kAttr16 = u"attr";
1199 const static std::u16string kAttrPrivate16 = u"^attr-private";
1200
1201 for (const PackageGroup& package_group : package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001202 for (const ConfiguredPackage& package_impl : package_group.packages_) {
1203 const LoadedPackage* package = package_impl.loaded_package_;
Adam Lesinski929d6512017-01-16 19:11:19 -08001204 if (package_name != package->GetPackageName()) {
1205 // All packages in the same group are expected to have the same package name.
1206 break;
1207 }
1208
1209 uint32_t resid = package->FindEntryByName(type16, entry16);
1210 if (resid == 0u && kAttr16 == type16) {
1211 // Private attributes in libraries (such as the framework) are sometimes encoded
1212 // under the type '^attr-private' in order to leave the ID space of public 'attr'
1213 // free for future additions. Check '^attr-private' for the same name.
1214 resid = package->FindEntryByName(kAttrPrivate16, entry16);
1215 }
1216
1217 if (resid != 0u) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -07001218 return fix_package_id(resid, package_group.dynamic_ref_table->mAssignedPackageId);
Adam Lesinski929d6512017-01-16 19:11:19 -08001219 }
1220 }
1221 }
Adam Lesinski0c405242017-01-13 20:47:26 -08001222 return 0u;
1223}
1224
Mårten Kongstad668ec5b2018-06-11 14:11:33 +02001225void AssetManager2::RebuildFilterList(bool filter_incompatible_configs) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001226 for (PackageGroup& group : package_groups_) {
1227 for (ConfiguredPackage& impl : group.packages_) {
1228 // Destroy it.
1229 impl.filtered_configs_.~ByteBucketArray();
1230
1231 // Re-create it.
1232 new (&impl.filtered_configs_) ByteBucketArray<FilteredConfigGroup>();
1233
1234 // Create the filters here.
1235 impl.loaded_package_->ForEachTypeSpec([&](const TypeSpec* spec, uint8_t type_index) {
1236 FilteredConfigGroup& group = impl.filtered_configs_.editItemAt(type_index);
1237 const auto iter_end = spec->types + spec->type_count;
1238 for (auto iter = spec->types; iter != iter_end; ++iter) {
1239 ResTable_config this_config;
1240 this_config.copyFromDtoH((*iter)->config);
Mårten Kongstad668ec5b2018-06-11 14:11:33 +02001241 if (!filter_incompatible_configs || this_config.match(configuration_)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001242 group.configurations.push_back(this_config);
1243 group.types.push_back(*iter);
1244 }
1245 }
1246 });
1247 }
1248 }
1249}
1250
Adam Lesinski7ad11102016-10-28 16:39:15 -07001251void AssetManager2::InvalidateCaches(uint32_t diff) {
Ryan Mitchell2c4d8742019-03-04 09:41:00 -08001252 cached_bag_resid_stacks_.clear();
1253
Adam Lesinski7ad11102016-10-28 16:39:15 -07001254 if (diff == 0xffffffffu) {
1255 // Everything must go.
1256 cached_bags_.clear();
1257 return;
1258 }
1259
1260 // Be more conservative with what gets purged. Only if the bag has other possible
1261 // variations with respect to what changed (diff) should we remove it.
1262 for (auto iter = cached_bags_.cbegin(); iter != cached_bags_.cend();) {
1263 if (diff & iter->second->type_spec_flags) {
1264 iter = cached_bags_.erase(iter);
1265 } else {
1266 ++iter;
1267 }
1268 }
1269}
1270
Ryan Mitchell2e394222019-08-28 12:10:51 -07001271uint8_t AssetManager2::GetAssignedPackageId(const LoadedPackage* package) const {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001272 for (auto& package_group : package_groups_) {
1273 for (auto& package2 : package_group.packages_) {
1274 if (package2.loaded_package_ == package) {
Ryan Mitchell8a891d82019-07-01 09:48:23 -07001275 return package_group.dynamic_ref_table->mAssignedPackageId;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001276 }
1277 }
1278 }
1279 return 0;
1280}
1281
Adam Lesinski30080e22017-10-16 16:18:09 -07001282std::unique_ptr<Theme> AssetManager2::NewTheme() {
1283 return std::unique_ptr<Theme>(new Theme(this));
1284}
1285
1286Theme::Theme(AssetManager2* asset_manager) : asset_manager_(asset_manager) {
1287}
1288
1289Theme::~Theme() = default;
1290
1291namespace {
1292
1293struct ThemeEntry {
1294 ApkAssetsCookie cookie;
1295 uint32_t type_spec_flags;
1296 Res_value value;
1297};
1298
1299struct ThemeType {
1300 int entry_count;
1301 ThemeEntry entries[0];
1302};
1303
1304constexpr size_t kTypeCount = std::numeric_limits<uint8_t>::max() + 1;
1305
1306} // namespace
1307
1308struct Theme::Package {
1309 // Each element of Type will be a dynamically sized object
1310 // allocated to have the entries stored contiguously with the Type.
1311 std::array<util::unique_cptr<ThemeType>, kTypeCount> types;
1312};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001313
1314bool Theme::ApplyStyle(uint32_t resid, bool force) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001315 ATRACE_NAME("Theme::ApplyStyle");
Adam Lesinski7ad11102016-10-28 16:39:15 -07001316
1317 const ResolvedBag* bag = asset_manager_->GetBag(resid);
1318 if (bag == nullptr) {
1319 return false;
1320 }
1321
1322 // Merge the flags from this style.
1323 type_spec_flags_ |= bag->type_spec_flags;
1324
Adam Lesinski30080e22017-10-16 16:18:09 -07001325 int last_type_idx = -1;
1326 int last_package_idx = -1;
1327 Package* last_package = nullptr;
1328 ThemeType* last_type = nullptr;
1329
1330 // Iterate backwards, because each bag is sorted in ascending key ID order, meaning we will only
1331 // need to perform one resize per type.
1332 using reverse_bag_iterator = std::reverse_iterator<const ResolvedBag::Entry*>;
1333 const auto bag_iter_end = reverse_bag_iterator(begin(bag));
1334 for (auto bag_iter = reverse_bag_iterator(end(bag)); bag_iter != bag_iter_end; ++bag_iter) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001335 const uint32_t attr_resid = bag_iter->key;
1336
Adam Lesinski30080e22017-10-16 16:18:09 -07001337 // If the resource ID passed in is not a style, the key can be some other identifier that is not
1338 // a resource ID. We should fail fast instead of operating with strange resource IDs.
Adam Lesinski929d6512017-01-16 19:11:19 -08001339 if (!is_valid_resid(attr_resid)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001340 return false;
1341 }
1342
Adam Lesinski30080e22017-10-16 16:18:09 -07001343 // We don't use the 0-based index for the type so that we can avoid doing ID validation
1344 // upon lookup. Instead, we keep space for the type ID 0 in our data structures. Since
1345 // the construction of this type is guarded with a resource ID check, it will never be
1346 // populated, and querying type ID 0 will always fail.
1347 const int package_idx = get_package_id(attr_resid);
1348 const int type_idx = get_type_id(attr_resid);
1349 const int entry_idx = get_entry_id(attr_resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001350
Adam Lesinski30080e22017-10-16 16:18:09 -07001351 if (last_package_idx != package_idx) {
1352 std::unique_ptr<Package>& package = packages_[package_idx];
1353 if (package == nullptr) {
1354 package.reset(new Package());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001355 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001356 last_package_idx = package_idx;
1357 last_package = package.get();
1358 last_type_idx = -1;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001359 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001360
1361 if (last_type_idx != type_idx) {
1362 util::unique_cptr<ThemeType>& type = last_package->types[type_idx];
1363 if (type == nullptr) {
1364 // Allocate enough memory to contain this entry_idx. Since we're iterating in reverse over
1365 // a sorted list of attributes, this shouldn't be resized again during this method call.
1366 type.reset(reinterpret_cast<ThemeType*>(
1367 calloc(sizeof(ThemeType) + (entry_idx + 1) * sizeof(ThemeEntry), 1)));
1368 type->entry_count = entry_idx + 1;
1369 } else if (entry_idx >= type->entry_count) {
1370 // Reallocate the memory to contain this entry_idx. Since we're iterating in reverse over
1371 // a sorted list of attributes, this shouldn't be resized again during this method call.
1372 const int new_count = entry_idx + 1;
1373 type.reset(reinterpret_cast<ThemeType*>(
1374 realloc(type.release(), sizeof(ThemeType) + (new_count * sizeof(ThemeEntry)))));
1375
1376 // Clear out the newly allocated space (which isn't zeroed).
1377 memset(type->entries + type->entry_count, 0,
1378 (new_count - type->entry_count) * sizeof(ThemeEntry));
1379 type->entry_count = new_count;
1380 }
1381 last_type_idx = type_idx;
1382 last_type = type.get();
1383 }
1384
1385 ThemeEntry& entry = last_type->entries[entry_idx];
1386 if (force || (entry.value.dataType == Res_value::TYPE_NULL &&
1387 entry.value.data != Res_value::DATA_NULL_EMPTY)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001388 entry.cookie = bag_iter->cookie;
1389 entry.type_spec_flags |= bag->type_spec_flags;
1390 entry.value = bag_iter->value;
1391 }
1392 }
1393 return true;
1394}
1395
1396ApkAssetsCookie Theme::GetAttribute(uint32_t resid, Res_value* out_value,
1397 uint32_t* out_flags) const {
Adam Lesinski30080e22017-10-16 16:18:09 -07001398 int cnt = 20;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001399
1400 uint32_t type_spec_flags = 0u;
1401
Adam Lesinski30080e22017-10-16 16:18:09 -07001402 do {
1403 const int package_idx = get_package_id(resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001404 const Package* package = packages_[package_idx].get();
Adam Lesinski30080e22017-10-16 16:18:09 -07001405 if (package != nullptr) {
1406 // The themes are constructed with a 1-based type ID, so no need to decrement here.
1407 const int type_idx = get_type_id(resid);
1408 const ThemeType* type = package->types[type_idx].get();
1409 if (type != nullptr) {
1410 const int entry_idx = get_entry_id(resid);
1411 if (entry_idx < type->entry_count) {
1412 const ThemeEntry& entry = type->entries[entry_idx];
1413 type_spec_flags |= entry.type_spec_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001414
Adam Lesinski30080e22017-10-16 16:18:09 -07001415 if (entry.value.dataType == Res_value::TYPE_ATTRIBUTE) {
1416 if (cnt > 0) {
1417 cnt--;
1418 resid = entry.value.data;
1419 continue;
1420 }
1421 return kInvalidCookie;
1422 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001423
Adam Lesinski30080e22017-10-16 16:18:09 -07001424 // @null is different than @empty.
1425 if (entry.value.dataType == Res_value::TYPE_NULL &&
1426 entry.value.data != Res_value::DATA_NULL_EMPTY) {
1427 return kInvalidCookie;
1428 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001429
Adam Lesinski30080e22017-10-16 16:18:09 -07001430 *out_value = entry.value;
Adam Lesinskida431a22016-12-29 16:08:16 -05001431 *out_flags = type_spec_flags;
Adam Lesinski30080e22017-10-16 16:18:09 -07001432 return entry.cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -05001433 }
Adam Lesinskida431a22016-12-29 16:08:16 -05001434 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001435 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001436 break;
1437 } while (true);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001438 return kInvalidCookie;
1439}
1440
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001441ApkAssetsCookie Theme::ResolveAttributeReference(ApkAssetsCookie cookie, Res_value* in_out_value,
1442 ResTable_config* in_out_selected_config,
1443 uint32_t* in_out_type_spec_flags,
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001444 uint32_t* out_last_ref) const {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001445 if (in_out_value->dataType == Res_value::TYPE_ATTRIBUTE) {
1446 uint32_t new_flags;
1447 cookie = GetAttribute(in_out_value->data, in_out_value, &new_flags);
1448 if (cookie == kInvalidCookie) {
1449 return kInvalidCookie;
1450 }
1451
1452 if (in_out_type_spec_flags != nullptr) {
1453 *in_out_type_spec_flags |= new_flags;
1454 }
1455 }
1456 return asset_manager_->ResolveReference(cookie, in_out_value, in_out_selected_config,
1457 in_out_type_spec_flags, out_last_ref);
1458}
1459
Adam Lesinski7ad11102016-10-28 16:39:15 -07001460void Theme::Clear() {
1461 type_spec_flags_ = 0u;
1462 for (std::unique_ptr<Package>& package : packages_) {
1463 package.reset();
1464 }
1465}
1466
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001467void Theme::SetTo(const Theme& o) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001468 if (this == &o) {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001469 return;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001470 }
1471
Adam Lesinski7ad11102016-10-28 16:39:15 -07001472 type_spec_flags_ = o.type_spec_flags_;
1473
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001474 if (asset_manager_ == o.asset_manager_) {
1475 // The theme comes from the same asset manager so all theme data can be copied exactly
1476 for (size_t p = 0; p < packages_.size(); p++) {
1477 const Package *package = o.packages_[p].get();
1478 if (package == nullptr) {
1479 // The other theme doesn't have this package, clear ours.
1480 packages_[p].reset();
Adam Lesinski7ad11102016-10-28 16:39:15 -07001481 continue;
1482 }
1483
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001484 if (packages_[p] == nullptr) {
1485 // The other theme has this package, but we don't. Make one.
1486 packages_[p].reset(new Package());
1487 }
1488
1489 for (size_t t = 0; t < package->types.size(); t++) {
1490 const ThemeType *type = package->types[t].get();
1491 if (type == nullptr) {
1492 // The other theme doesn't have this type, clear ours.
1493 packages_[p]->types[t].reset();
1494 continue;
1495 }
1496
1497 // Create a new type and update it to theirs.
1498 const size_t type_alloc_size = sizeof(ThemeType) + (type->entry_count * sizeof(ThemeEntry));
1499 void *copied_data = malloc(type_alloc_size);
1500 memcpy(copied_data, type, type_alloc_size);
1501 packages_[p]->types[t].reset(reinterpret_cast<ThemeType *>(copied_data));
1502 }
1503 }
1504 } else {
1505 std::map<ApkAssetsCookie, ApkAssetsCookie> src_to_dest_asset_cookies;
1506 typedef std::map<int, int> SourceToDestinationRuntimePackageMap;
1507 std::map<ApkAssetsCookie, SourceToDestinationRuntimePackageMap> src_asset_cookie_id_map;
1508
Ryan Mitchell93bca972019-03-08 17:26:28 -08001509 // Determine which ApkAssets are loaded in both theme AssetManagers.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001510 std::vector<const ApkAssets*> src_assets = o.asset_manager_->GetApkAssets();
1511 for (size_t i = 0; i < src_assets.size(); i++) {
1512 const ApkAssets* src_asset = src_assets[i];
1513
1514 std::vector<const ApkAssets*> dest_assets = asset_manager_->GetApkAssets();
1515 for (size_t j = 0; j < dest_assets.size(); j++) {
1516 const ApkAssets* dest_asset = dest_assets[j];
1517
Ryan Mitchell93bca972019-03-08 17:26:28 -08001518 // Map the runtime package of the source apk asset to the destination apk asset.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001519 if (src_asset->GetPath() == dest_asset->GetPath()) {
1520 const std::vector<std::unique_ptr<const LoadedPackage>>& src_packages =
1521 src_asset->GetLoadedArsc()->GetPackages();
1522 const std::vector<std::unique_ptr<const LoadedPackage>>& dest_packages =
1523 dest_asset->GetLoadedArsc()->GetPackages();
1524
1525 SourceToDestinationRuntimePackageMap package_map;
1526
1527 // The source and destination package should have the same number of packages loaded in
1528 // the same order.
1529 const size_t N = src_packages.size();
1530 CHECK(N == dest_packages.size())
1531 << " LoadedArsc " << src_asset->GetPath() << " differs number of packages.";
1532 for (size_t p = 0; p < N; p++) {
1533 auto& src_package = src_packages[p];
1534 auto& dest_package = dest_packages[p];
1535 CHECK(src_package->GetPackageName() == dest_package->GetPackageName())
1536 << " Package " << src_package->GetPackageName() << " differs in load order.";
1537
1538 int src_package_id = o.asset_manager_->GetAssignedPackageId(src_package.get());
1539 int dest_package_id = asset_manager_->GetAssignedPackageId(dest_package.get());
1540 package_map[src_package_id] = dest_package_id;
1541 }
1542
Ryan Mitchell93bca972019-03-08 17:26:28 -08001543 src_to_dest_asset_cookies.insert(std::make_pair(i, j));
1544 src_asset_cookie_id_map.insert(std::make_pair(i, package_map));
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001545 break;
1546 }
1547 }
1548 }
1549
Ryan Mitchell93bca972019-03-08 17:26:28 -08001550 // Reset the data in the destination theme.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001551 for (size_t p = 0; p < packages_.size(); p++) {
1552 if (packages_[p] != nullptr) {
1553 packages_[p].reset();
1554 }
1555 }
1556
1557 for (size_t p = 0; p < packages_.size(); p++) {
1558 const Package *package = o.packages_[p].get();
1559 if (package == nullptr) {
1560 continue;
1561 }
1562
1563 for (size_t t = 0; t < package->types.size(); t++) {
1564 const ThemeType *type = package->types[t].get();
1565 if (type == nullptr) {
1566 continue;
1567 }
1568
1569 for (size_t e = 0; e < type->entry_count; e++) {
1570 const ThemeEntry &entry = type->entries[e];
1571 if (entry.value.dataType == Res_value::TYPE_NULL &&
1572 entry.value.data != Res_value::DATA_NULL_EMPTY) {
1573 continue;
1574 }
1575
Ryan Mitchell93bca972019-03-08 17:26:28 -08001576 bool is_reference = (entry.value.dataType == Res_value::TYPE_ATTRIBUTE
1577 || entry.value.dataType == Res_value::TYPE_REFERENCE
1578 || entry.value.dataType == Res_value::TYPE_DYNAMIC_ATTRIBUTE
1579 || entry.value.dataType == Res_value::TYPE_DYNAMIC_REFERENCE)
1580 && entry.value.data != 0x0;
Ryan Mitchellb85d9b22018-11-19 12:11:38 -08001581
Ryan Mitchell93bca972019-03-08 17:26:28 -08001582 // If the attribute value represents an attribute or reference, the package id of the
1583 // value needs to be rewritten to the package id of the value in the destination.
1584 uint32_t attribute_data = entry.value.data;
1585 if (is_reference) {
1586 // Determine the package id of the reference in the destination AssetManager.
Ryan Mitchellb85d9b22018-11-19 12:11:38 -08001587 auto value_package_map = src_asset_cookie_id_map.find(entry.cookie);
1588 if (value_package_map == src_asset_cookie_id_map.end()) {
1589 continue;
1590 }
1591
1592 auto value_dest_package = value_package_map->second.find(
1593 get_package_id(entry.value.data));
1594 if (value_dest_package == value_package_map->second.end()) {
1595 continue;
1596 }
1597
Ryan Mitchell93bca972019-03-08 17:26:28 -08001598 attribute_data = fix_package_id(entry.value.data, value_dest_package->second);
1599 }
1600
1601 // Find the cookie of the value in the destination. If the source apk is not loaded in the
1602 // destination, only copy resources that do not reference resources in the source.
1603 ApkAssetsCookie data_dest_cookie;
1604 auto value_dest_cookie = src_to_dest_asset_cookies.find(entry.cookie);
1605 if (value_dest_cookie != src_to_dest_asset_cookies.end()) {
1606 data_dest_cookie = value_dest_cookie->second;
1607 } else {
1608 if (is_reference || entry.value.dataType == Res_value::TYPE_STRING) {
1609 continue;
1610 } else {
1611 data_dest_cookie = 0x0;
1612 }
Ryan Mitchellb85d9b22018-11-19 12:11:38 -08001613 }
1614
1615 // The package id of the attribute needs to be rewritten to the package id of the
Ryan Mitchell93bca972019-03-08 17:26:28 -08001616 // attribute in the destination.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001617 int attribute_dest_package_id = p;
1618 if (attribute_dest_package_id != 0x01) {
Ryan Mitchell93bca972019-03-08 17:26:28 -08001619 // Find the cookie of the attribute resource id in the source AssetManager
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001620 FindEntryResult attribute_entry_result;
1621 ApkAssetsCookie attribute_cookie =
Ryan Mitchella55dc2e2019-01-24 10:58:23 -08001622 o.asset_manager_->FindEntry(make_resid(p, t, e), 0 /* density_override */ ,
1623 true /* stop_at_first_match */,
1624 true /* ignore_configuration */,
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001625 &attribute_entry_result);
1626
Ryan Mitchell93bca972019-03-08 17:26:28 -08001627 // Determine the package id of the attribute in the destination AssetManager.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001628 auto attribute_package_map = src_asset_cookie_id_map.find(attribute_cookie);
1629 if (attribute_package_map == src_asset_cookie_id_map.end()) {
1630 continue;
1631 }
1632 auto attribute_dest_package = attribute_package_map->second.find(
1633 attribute_dest_package_id);
1634 if (attribute_dest_package == attribute_package_map->second.end()) {
1635 continue;
1636 }
1637 attribute_dest_package_id = attribute_dest_package->second;
1638 }
1639
Ryan Mitchell93bca972019-03-08 17:26:28 -08001640 // Lazily instantiate the destination package.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001641 std::unique_ptr<Package>& dest_package = packages_[attribute_dest_package_id];
1642 if (dest_package == nullptr) {
1643 dest_package.reset(new Package());
1644 }
1645
Ryan Mitchell93bca972019-03-08 17:26:28 -08001646 // Lazily instantiate and resize the destination type.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001647 util::unique_cptr<ThemeType>& dest_type = dest_package->types[t];
1648 if (dest_type == nullptr || dest_type->entry_count < type->entry_count) {
1649 const size_t type_alloc_size = sizeof(ThemeType)
1650 + (type->entry_count * sizeof(ThemeEntry));
1651 void* dest_data = malloc(type_alloc_size);
1652 memset(dest_data, 0, type->entry_count * sizeof(ThemeEntry));
1653
Ryan Mitchell93bca972019-03-08 17:26:28 -08001654 // Copy the existing destination type values if the type is resized.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001655 if (dest_type != nullptr) {
1656 memcpy(dest_data, type, sizeof(ThemeType)
1657 + (dest_type->entry_count * sizeof(ThemeEntry)));
1658 }
1659
1660 dest_type.reset(reinterpret_cast<ThemeType *>(dest_data));
1661 dest_type->entry_count = type->entry_count;
1662 }
1663
Ryan Mitchell93bca972019-03-08 17:26:28 -08001664 dest_type->entries[e].cookie = data_dest_cookie;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001665 dest_type->entries[e].value.dataType = entry.value.dataType;
Ryan Mitchell93bca972019-03-08 17:26:28 -08001666 dest_type->entries[e].value.data = attribute_data;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001667 dest_type->entries[e].type_spec_flags = entry.type_spec_flags;
1668 }
1669 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001670 }
1671 }
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001672}
1673
1674void Theme::Dump() const {
1675 base::ScopedLogSeverity _log(base::INFO);
1676 LOG(INFO) << base::StringPrintf("Theme(this=%p, AssetManager2=%p)", this, asset_manager_);
1677
1678 for (int p = 0; p < packages_.size(); p++) {
1679 auto& package = packages_[p];
1680 if (package == nullptr) {
1681 continue;
1682 }
1683
1684 for (int t = 0; t < package->types.size(); t++) {
1685 auto& type = package->types[t];
1686 if (type == nullptr) {
1687 continue;
1688 }
1689
1690 for (int e = 0; e < type->entry_count; e++) {
1691 auto& entry = type->entries[e];
1692 if (entry.value.dataType == Res_value::TYPE_NULL &&
1693 entry.value.data != Res_value::DATA_NULL_EMPTY) {
1694 continue;
1695 }
1696
1697 LOG(INFO) << base::StringPrintf(" entry(0x%08x)=(0x%08x) type=(0x%02x), cookie(%d)",
1698 make_resid(p, t, e), entry.value.data,
1699 entry.value.dataType, entry.cookie);
1700 }
1701 }
1702 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001703}
1704
1705} // namespace android