blob: eec49df79630b9de03edad3323869be04766c43c [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 Mitchell31b11052019-06-13 13:47:26 -070028#include "androidfw/Util.h"
Adam Lesinski7ad11102016-10-28 16:39:15 -070029#include "utils/ByteOrder.h"
30#include "utils/Trace.h"
31
32#ifdef _WIN32
33#ifdef ERROR
34#undef ERROR
35#endif
36#endif
37
Adam Lesinski929d6512017-01-16 19:11:19 -080038#include "androidfw/ResourceUtils.h"
39
Adam Lesinski7ad11102016-10-28 16:39:15 -070040namespace android {
41
Adam Lesinskibebfcc42018-02-12 14:27:46 -080042struct FindEntryResult {
43 // A pointer to the resource table entry for this resource.
44 // If the size of the entry is > sizeof(ResTable_entry), it can be cast to
45 // a ResTable_map_entry and processed as a bag/map.
46 const ResTable_entry* entry;
47
48 // The configuration for which the resulting entry was defined. This is already swapped to host
49 // endianness.
50 ResTable_config config;
51
52 // The bitmask of configuration axis with which the resource value varies.
53 uint32_t type_flags;
54
55 // The dynamic package ID map for the package from which this resource came from.
56 const DynamicRefTable* dynamic_ref_table;
57
58 // The string pool reference to the type's name. This uses a different string pool than
59 // the global string pool, but this is hidden from the caller.
60 StringPoolRef type_string_ref;
61
62 // The string pool reference to the entry's name. This uses a different string pool than
63 // the global string pool, but this is hidden from the caller.
64 StringPoolRef entry_string_ref;
65};
66
Adam Lesinski970bd8d2017-09-25 13:21:55 -070067AssetManager2::AssetManager2() {
68 memset(&configuration_, 0, sizeof(configuration_));
69}
Adam Lesinski7ad11102016-10-28 16:39:15 -070070
71bool AssetManager2::SetApkAssets(const std::vector<const ApkAssets*>& apk_assets,
Mårten Kongstad668ec5b2018-06-11 14:11:33 +020072 bool invalidate_caches, bool filter_incompatible_configs) {
Adam Lesinski7ad11102016-10-28 16:39:15 -070073 apk_assets_ = apk_assets;
Adam Lesinskida431a22016-12-29 16:08:16 -050074 BuildDynamicRefTable();
Mårten Kongstad668ec5b2018-06-11 14:11:33 +020075 RebuildFilterList(filter_incompatible_configs);
Adam Lesinski7ad11102016-10-28 16:39:15 -070076 if (invalidate_caches) {
77 InvalidateCaches(static_cast<uint32_t>(-1));
78 }
79 return true;
80}
81
Adam Lesinskida431a22016-12-29 16:08:16 -050082void AssetManager2::BuildDynamicRefTable() {
83 package_groups_.clear();
84 package_ids_.fill(0xff);
85
86 // 0x01 is reserved for the android package.
87 int next_package_id = 0x02;
88 const size_t apk_assets_count = apk_assets_.size();
89 for (size_t i = 0; i < apk_assets_count; i++) {
Adam Lesinski970bd8d2017-09-25 13:21:55 -070090 const LoadedArsc* loaded_arsc = apk_assets_[i]->GetLoadedArsc();
91
92 for (const std::unique_ptr<const LoadedPackage>& package : loaded_arsc->GetPackages()) {
Adam Lesinskida431a22016-12-29 16:08:16 -050093 // Get the package ID or assign one if a shared library.
94 int package_id;
95 if (package->IsDynamic()) {
96 package_id = next_package_id++;
97 } else {
98 package_id = package->GetPackageId();
99 }
100
101 // Add the mapping for package ID to index if not present.
102 uint8_t idx = package_ids_[package_id];
103 if (idx == 0xff) {
104 package_ids_[package_id] = idx = static_cast<uint8_t>(package_groups_.size());
105 package_groups_.push_back({});
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800106 DynamicRefTable& ref_table = package_groups_.back().dynamic_ref_table;
107 ref_table.mAssignedPackageId = package_id;
108 ref_table.mAppAsLib = package->IsDynamic() && package->GetPackageId() == 0x7f;
Adam Lesinskida431a22016-12-29 16:08:16 -0500109 }
110 PackageGroup* package_group = &package_groups_[idx];
111
112 // Add the package and to the set of packages with the same ID.
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800113 package_group->packages_.push_back(ConfiguredPackage{package.get(), {}});
Adam Lesinskida431a22016-12-29 16:08:16 -0500114 package_group->cookies_.push_back(static_cast<ApkAssetsCookie>(i));
115
116 // Add the package name -> build time ID mappings.
117 for (const DynamicPackageEntry& entry : package->GetDynamicPackageMap()) {
118 String16 package_name(entry.package_name.c_str(), entry.package_name.size());
119 package_group->dynamic_ref_table.mEntries.replaceValueFor(
120 package_name, static_cast<uint8_t>(entry.package_id));
121 }
122 }
123 }
124
125 // Now assign the runtime IDs so that we have a build-time to runtime ID map.
126 const auto package_groups_end = package_groups_.end();
127 for (auto iter = package_groups_.begin(); iter != package_groups_end; ++iter) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800128 const std::string& package_name = iter->packages_[0].loaded_package_->GetPackageName();
Adam Lesinskida431a22016-12-29 16:08:16 -0500129 for (auto iter2 = package_groups_.begin(); iter2 != package_groups_end; ++iter2) {
130 iter2->dynamic_ref_table.addMapping(String16(package_name.c_str(), package_name.size()),
131 iter->dynamic_ref_table.mAssignedPackageId);
132 }
133 }
134}
135
136void AssetManager2::DumpToLog() const {
137 base::ScopedLogSeverity _log(base::INFO);
138
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800139 LOG(INFO) << base::StringPrintf("AssetManager2(this=%p)", this);
140
Adam Lesinskida431a22016-12-29 16:08:16 -0500141 std::string list;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800142 for (const auto& apk_assets : apk_assets_) {
143 base::StringAppendF(&list, "%s,", apk_assets->GetPath().c_str());
144 }
145 LOG(INFO) << "ApkAssets: " << list;
146
147 list = "";
Adam Lesinskida431a22016-12-29 16:08:16 -0500148 for (size_t i = 0; i < package_ids_.size(); i++) {
149 if (package_ids_[i] != 0xff) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800150 base::StringAppendF(&list, "%02x -> %d, ", (int)i, package_ids_[i]);
Adam Lesinskida431a22016-12-29 16:08:16 -0500151 }
152 }
153 LOG(INFO) << "Package ID map: " << list;
154
Adam Lesinski0dd36992018-01-25 15:38:38 -0800155 for (const auto& package_group: package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800156 list = "";
157 for (const auto& package : package_group.packages_) {
158 const LoadedPackage* loaded_package = package.loaded_package_;
159 base::StringAppendF(&list, "%s(%02x%s), ", loaded_package->GetPackageName().c_str(),
160 loaded_package->GetPackageId(),
161 (loaded_package->IsDynamic() ? " dynamic" : ""));
162 }
163 LOG(INFO) << base::StringPrintf("PG (%02x): ",
164 package_group.dynamic_ref_table.mAssignedPackageId)
165 << list;
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800166
167 for (size_t i = 0; i < 256; i++) {
168 if (package_group.dynamic_ref_table.mLookupTable[i] != 0) {
169 LOG(INFO) << base::StringPrintf(" e[0x%02x] -> 0x%02x", (uint8_t) i,
170 package_group.dynamic_ref_table.mLookupTable[i]);
171 }
172 }
Adam Lesinskida431a22016-12-29 16:08:16 -0500173 }
174}
Adam Lesinski7ad11102016-10-28 16:39:15 -0700175
176const ResStringPool* AssetManager2::GetStringPoolForCookie(ApkAssetsCookie cookie) const {
177 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
178 return nullptr;
179 }
180 return apk_assets_[cookie]->GetLoadedArsc()->GetStringPool();
181}
182
Adam Lesinskida431a22016-12-29 16:08:16 -0500183const DynamicRefTable* AssetManager2::GetDynamicRefTableForPackage(uint32_t package_id) const {
184 if (package_id >= package_ids_.size()) {
185 return nullptr;
186 }
187
188 const size_t idx = package_ids_[package_id];
189 if (idx == 0xff) {
190 return nullptr;
191 }
192 return &package_groups_[idx].dynamic_ref_table;
193}
194
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800195const DynamicRefTable* AssetManager2::GetDynamicRefTableForCookie(ApkAssetsCookie cookie) const {
196 for (const PackageGroup& package_group : package_groups_) {
197 for (const ApkAssetsCookie& package_cookie : package_group.cookies_) {
198 if (package_cookie == cookie) {
199 return &package_group.dynamic_ref_table;
200 }
201 }
202 }
203 return nullptr;
204}
205
Mårten Kongstadc92c4dd2019-02-05 01:29:59 +0100206const std::unordered_map<std::string, std::string>*
207 AssetManager2::GetOverlayableMapForPackage(uint32_t package_id) const {
208
209 if (package_id >= package_ids_.size()) {
210 return nullptr;
211 }
212
213 const size_t idx = package_ids_[package_id];
214 if (idx == 0xff) {
215 return nullptr;
216 }
217
218 const PackageGroup& package_group = package_groups_[idx];
219 if (package_group.packages_.size() == 0) {
220 return nullptr;
221 }
222
223 const auto loaded_package = package_group.packages_[0].loaded_package_;
224 return &loaded_package->GetOverlayableMap();
225}
226
Ryan Mitchell2e394222019-08-28 12:10:51 -0700227bool AssetManager2::GetOverlayablesToString(const android::StringPiece& package_name,
228 std::string* out) const {
229 uint8_t package_id = 0U;
230 for (const auto& apk_assets : apk_assets_) {
231 const LoadedArsc* loaded_arsc = apk_assets->GetLoadedArsc();
232 if (loaded_arsc == nullptr) {
233 continue;
234 }
235
236 const auto& loaded_packages = loaded_arsc->GetPackages();
237 if (loaded_packages.empty()) {
238 continue;
239 }
240
241 const auto& loaded_package = loaded_packages[0];
242 if (loaded_package->GetPackageName() == package_name) {
243 package_id = GetAssignedPackageId(loaded_package.get());
244 break;
245 }
246 }
247
248 if (package_id == 0U) {
249 ANDROID_LOG(ERROR) << base::StringPrintf("No package with name '%s", package_name.data());
250 return false;
251 }
252
253 const size_t idx = package_ids_[package_id];
254 if (idx == 0xff) {
255 return false;
256 }
257
258 std::string output;
259 for (const ConfiguredPackage& package : package_groups_[idx].packages_) {
260 const LoadedPackage* loaded_package = package.loaded_package_;
261 for (auto it = loaded_package->begin(); it != loaded_package->end(); it++) {
262 const OverlayableInfo* info = loaded_package->GetOverlayableInfo(*it);
263 if (info != nullptr) {
264 ResourceName res_name;
265 if (!GetResourceName(*it, &res_name)) {
266 ANDROID_LOG(ERROR) << base::StringPrintf(
267 "Unable to retrieve name of overlayable resource 0x%08x", *it);
268 return false;
269 }
270
271 const std::string name = ToFormattedResourceString(&res_name);
272 output.append(base::StringPrintf(
273 "resource='%s' overlayable='%s' actor='%s' policy='0x%08x'\n",
274 name.c_str(), info->name.c_str(), info->actor.c_str(), info->policy_flags));
275 }
276 }
277 }
278
279 *out = std::move(output);
280 return true;
281}
282
Adam Lesinski7ad11102016-10-28 16:39:15 -0700283void AssetManager2::SetConfiguration(const ResTable_config& configuration) {
284 const int diff = configuration_.diff(configuration);
285 configuration_ = configuration;
286
287 if (diff) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800288 RebuildFilterList();
Adam Lesinski7ad11102016-10-28 16:39:15 -0700289 InvalidateCaches(static_cast<uint32_t>(diff));
290 }
291}
292
Adam Lesinski0c405242017-01-13 20:47:26 -0800293std::set<ResTable_config> AssetManager2::GetResourceConfigurations(bool exclude_system,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800294 bool exclude_mipmap) const {
295 ATRACE_NAME("AssetManager::GetResourceConfigurations");
Adam Lesinski0c405242017-01-13 20:47:26 -0800296 std::set<ResTable_config> configurations;
297 for (const PackageGroup& package_group : package_groups_) {
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800298 bool found_system_package = false;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800299 for (const ConfiguredPackage& package : package_group.packages_) {
300 if (exclude_system && package.loaded_package_->IsSystem()) {
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800301 found_system_package = true;
Adam Lesinski0c405242017-01-13 20:47:26 -0800302 continue;
303 }
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800304
305 if (exclude_system && package.loaded_package_->IsOverlay() && found_system_package) {
306 // Overlays must appear after the target package to take effect. Any overlay found in the
307 // same package as a system package is able to overlay system resources.
308 continue;
309 }
310
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800311 package.loaded_package_->CollectConfigurations(exclude_mipmap, &configurations);
Adam Lesinski0c405242017-01-13 20:47:26 -0800312 }
313 }
314 return configurations;
315}
316
317std::set<std::string> AssetManager2::GetResourceLocales(bool exclude_system,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800318 bool merge_equivalent_languages) const {
319 ATRACE_NAME("AssetManager::GetResourceLocales");
Adam Lesinski0c405242017-01-13 20:47:26 -0800320 std::set<std::string> locales;
321 for (const PackageGroup& package_group : package_groups_) {
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800322 bool found_system_package = false;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800323 for (const ConfiguredPackage& package : package_group.packages_) {
324 if (exclude_system && package.loaded_package_->IsSystem()) {
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800325 found_system_package = true;
Adam Lesinski0c405242017-01-13 20:47:26 -0800326 continue;
327 }
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800328
329 if (exclude_system && package.loaded_package_->IsOverlay() && found_system_package) {
330 // Overlays must appear after the target package to take effect. Any overlay found in the
331 // same package as a system package is able to overlay system resources.
332 continue;
333 }
334
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800335 package.loaded_package_->CollectLocales(merge_equivalent_languages, &locales);
Adam Lesinski0c405242017-01-13 20:47:26 -0800336 }
337 }
338 return locales;
339}
340
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800341std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename,
342 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700343 const std::string new_path = "assets/" + filename;
344 return OpenNonAsset(new_path, mode);
345}
346
347std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename, ApkAssetsCookie cookie,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800348 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700349 const std::string new_path = "assets/" + filename;
350 return OpenNonAsset(new_path, cookie, mode);
351}
352
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800353std::unique_ptr<AssetDir> AssetManager2::OpenDir(const std::string& dirname) const {
354 ATRACE_NAME("AssetManager::OpenDir");
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800355
356 std::string full_path = "assets/" + dirname;
357 std::unique_ptr<SortedVector<AssetDir::FileInfo>> files =
358 util::make_unique<SortedVector<AssetDir::FileInfo>>();
359
360 // Start from the back.
361 for (auto iter = apk_assets_.rbegin(); iter != apk_assets_.rend(); ++iter) {
362 const ApkAssets* apk_assets = *iter;
Mårten Kongstaddbf343b2019-02-21 07:54:18 +0100363 if (apk_assets->IsOverlay()) {
364 continue;
365 }
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800366
367 auto func = [&](const StringPiece& name, FileType type) {
368 AssetDir::FileInfo info;
369 info.setFileName(String8(name.data(), name.size()));
370 info.setFileType(type);
371 info.setSourceName(String8(apk_assets->GetPath().c_str()));
372 files->add(info);
373 };
374
375 if (!apk_assets->ForEachFile(full_path, func)) {
376 return {};
377 }
378 }
379
380 std::unique_ptr<AssetDir> asset_dir = util::make_unique<AssetDir>();
381 asset_dir->setFileList(files.release());
382 return asset_dir;
383}
384
Adam Lesinski7ad11102016-10-28 16:39:15 -0700385// Search in reverse because that's how we used to do it and we need to preserve behaviour.
386// This is unfortunate, because ClassLoaders delegate to the parent first, so the order
387// is inconsistent for split APKs.
388std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
389 Asset::AccessMode mode,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800390 ApkAssetsCookie* out_cookie) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700391 for (int32_t i = apk_assets_.size() - 1; i >= 0; i--) {
Mårten Kongstaddbf343b2019-02-21 07:54:18 +0100392 // Prevent RRO from modifying assets and other entries accessed by file
393 // path. Explicitly asking for a path in a given package (denoted by a
394 // cookie) is still OK.
395 if (apk_assets_[i]->IsOverlay()) {
396 continue;
397 }
398
Adam Lesinski7ad11102016-10-28 16:39:15 -0700399 std::unique_ptr<Asset> asset = apk_assets_[i]->Open(filename, mode);
400 if (asset) {
401 if (out_cookie != nullptr) {
402 *out_cookie = i;
403 }
404 return asset;
405 }
406 }
407
408 if (out_cookie != nullptr) {
409 *out_cookie = kInvalidCookie;
410 }
411 return {};
412}
413
414std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800415 ApkAssetsCookie cookie,
416 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700417 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
418 return {};
419 }
420 return apk_assets_[cookie]->Open(filename, mode);
421}
422
423ApkAssetsCookie AssetManager2::FindEntry(uint32_t resid, uint16_t density_override,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800424 bool /*stop_at_first_match*/,
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800425 bool ignore_configuration,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800426 FindEntryResult* out_entry) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700427 // Might use this if density_override != 0.
428 ResTable_config density_override_config;
429
430 // Select our configuration or generate a density override configuration.
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800431 const ResTable_config* desired_config = &configuration_;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700432 if (density_override != 0 && density_override != configuration_.density) {
433 density_override_config = configuration_;
434 density_override_config.density = density_override;
435 desired_config = &density_override_config;
436 }
437
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800438 if (!is_valid_resid(resid)) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500439 LOG(ERROR) << base::StringPrintf("Invalid ID 0x%08x.", resid);
440 return kInvalidCookie;
441 }
442
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800443 const uint32_t package_id = get_package_id(resid);
444 const uint8_t type_idx = get_type_id(resid) - 1;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800445 const uint16_t entry_idx = get_entry_id(resid);
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800446
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800447 const uint8_t package_idx = package_ids_[package_id];
448 if (package_idx == 0xff) {
Ryan Mitchell2fe23472019-02-27 09:43:01 -0800449 ANDROID_LOG(ERROR) << base::StringPrintf("No package ID %02x found for ID 0x%08x.",
450 package_id, resid);
Adam Lesinskida431a22016-12-29 16:08:16 -0500451 return kInvalidCookie;
452 }
453
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800454 const PackageGroup& package_group = package_groups_[package_idx];
Adam Lesinskib8b3a262018-02-09 11:01:45 -0800455 const size_t package_count = package_group.packages_.size();
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800456
457 ApkAssetsCookie best_cookie = kInvalidCookie;
458 const LoadedPackage* best_package = nullptr;
459 const ResTable_type* best_type = nullptr;
460 const ResTable_config* best_config = nullptr;
461 ResTable_config best_config_copy;
462 uint32_t best_offset = 0u;
463 uint32_t type_flags = 0u;
464
Winson2f3669b2019-01-11 11:28:34 -0800465 Resolution::Step::Type resolution_type;
466 std::vector<Resolution::Step> resolution_steps;
467
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800468 // If desired_config is the same as the set configuration, then we can use our filtered list
469 // and we don't need to match the configurations, since they already matched.
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800470 const bool use_fast_path = !ignore_configuration && desired_config == &configuration_;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800471
472 for (size_t pi = 0; pi < package_count; pi++) {
473 const ConfiguredPackage& loaded_package_impl = package_group.packages_[pi];
474 const LoadedPackage* loaded_package = loaded_package_impl.loaded_package_;
475 ApkAssetsCookie cookie = package_group.cookies_[pi];
476
477 // If the type IDs are offset in this package, we need to take that into account when searching
478 // for a type.
479 const TypeSpec* type_spec = loaded_package->GetTypeSpecByTypeIndex(type_idx);
480 if (UNLIKELY(type_spec == nullptr)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700481 continue;
482 }
483
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800484 uint16_t local_entry_idx = entry_idx;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700485
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800486 // If there is an IDMAP supplied with this package, translate the entry ID.
487 if (type_spec->idmap_entries != nullptr) {
488 if (!LoadedIdmap::Lookup(type_spec->idmap_entries, local_entry_idx, &local_entry_idx)) {
489 // There is no mapping, so the resource is not meant to be in this overlay package.
490 continue;
491 }
492 }
493
494 type_flags |= type_spec->GetFlagsForEntryIndex(local_entry_idx);
495
496 // If the package is an overlay, then even configurations that are the same MUST be chosen.
497 const bool package_is_overlay = loaded_package->IsOverlay();
498
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800499 if (use_fast_path) {
Winson2f3669b2019-01-11 11:28:34 -0800500 const FilteredConfigGroup& filtered_group = loaded_package_impl.filtered_configs_[type_idx];
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800501 const std::vector<ResTable_config>& candidate_configs = filtered_group.configurations;
502 const size_t type_count = candidate_configs.size();
503 for (uint32_t i = 0; i < type_count; i++) {
504 const ResTable_config& this_config = candidate_configs[i];
505
506 // We can skip calling ResTable_config::match() because we know that all candidate
507 // configurations that do NOT match have been filtered-out.
Winson2f3669b2019-01-11 11:28:34 -0800508 if (best_config == nullptr) {
509 resolution_type = Resolution::Step::Type::INITIAL;
510 } else if (this_config.isBetterThan(*best_config, desired_config)) {
511 resolution_type = Resolution::Step::Type::BETTER_MATCH;
512 } else if (package_is_overlay && this_config.compare(*best_config) == 0) {
513 resolution_type = Resolution::Step::Type::OVERLAID;
514 } else {
515 continue;
516 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800517
Winson2f3669b2019-01-11 11:28:34 -0800518 // The configuration matches and is better than the previous selection.
519 // Find the entry value if it exists for this configuration.
520 const ResTable_type* type = filtered_group.types[i];
521 const uint32_t offset = LoadedPackage::GetEntryOffset(type, local_entry_idx);
522 if (offset == ResTable_type::NO_ENTRY) {
523 continue;
524 }
525
526 best_cookie = cookie;
527 best_package = loaded_package;
528 best_type = type;
529 best_config = &this_config;
530 best_offset = offset;
531
532 if (resource_resolution_logging_enabled_) {
533 resolution_steps.push_back(Resolution::Step{resolution_type,
534 this_config.toString(),
535 &loaded_package->GetPackageName()});
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800536 }
537 }
538 } else {
539 // This is the slower path, which doesn't use the filtered list of configurations.
540 // Here we must read the ResTable_config from the mmapped APK, convert it to host endianness
541 // and fill in any new fields that did not exist when the APK was compiled.
542 // Furthermore when selecting configurations we can't just record the pointer to the
543 // ResTable_config, we must copy it.
544 const auto iter_end = type_spec->types + type_spec->type_count;
545 for (auto iter = type_spec->types; iter != iter_end; ++iter) {
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800546 ResTable_config this_config{};
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800547
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800548 if (!ignore_configuration) {
549 this_config.copyFromDtoH((*iter)->config);
550 if (!this_config.match(*desired_config)) {
551 continue;
552 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800553
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800554 if (best_config == nullptr) {
555 resolution_type = Resolution::Step::Type::INITIAL;
556 } else if (this_config.isBetterThan(*best_config, desired_config)) {
557 resolution_type = Resolution::Step::Type::BETTER_MATCH;
558 } else if (package_is_overlay && this_config.compare(*best_config) == 0) {
559 resolution_type = Resolution::Step::Type::OVERLAID;
560 } else {
561 continue;
562 }
Winson2f3669b2019-01-11 11:28:34 -0800563 }
564
565 // The configuration matches and is better than the previous selection.
566 // Find the entry value if it exists for this configuration.
567 const uint32_t offset = LoadedPackage::GetEntryOffset(*iter, local_entry_idx);
568 if (offset == ResTable_type::NO_ENTRY) {
569 continue;
570 }
571
572 best_cookie = cookie;
573 best_package = loaded_package;
574 best_type = *iter;
575 best_config_copy = this_config;
576 best_config = &best_config_copy;
577 best_offset = offset;
578
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800579 if (ignore_configuration) {
580 // Any configuration will suffice, so break.
581 break;
582 }
583
Winson2f3669b2019-01-11 11:28:34 -0800584 if (resource_resolution_logging_enabled_) {
585 resolution_steps.push_back(Resolution::Step{resolution_type,
586 this_config.toString(),
587 &loaded_package->GetPackageName()});
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800588 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700589 }
590 }
591 }
592
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800593 if (UNLIKELY(best_cookie == kInvalidCookie)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700594 return kInvalidCookie;
595 }
596
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800597 const ResTable_entry* best_entry = LoadedPackage::GetEntryFromOffset(best_type, best_offset);
598 if (UNLIKELY(best_entry == nullptr)) {
599 return kInvalidCookie;
600 }
601
602 out_entry->entry = best_entry;
603 out_entry->config = *best_config;
604 out_entry->type_flags = type_flags;
605 out_entry->type_string_ref = StringPoolRef(best_package->GetTypeStringPool(), best_type->id - 1);
606 out_entry->entry_string_ref =
607 StringPoolRef(best_package->GetKeyStringPool(), best_entry->key.index);
Adam Lesinskida431a22016-12-29 16:08:16 -0500608 out_entry->dynamic_ref_table = &package_group.dynamic_ref_table;
Winson2f3669b2019-01-11 11:28:34 -0800609
610 if (resource_resolution_logging_enabled_) {
611 last_resolution.resid = resid;
612 last_resolution.cookie = best_cookie;
613 last_resolution.steps = resolution_steps;
614
615 // Cache only the type/entry refs since that's all that's needed to build name
616 last_resolution.type_string_ref =
617 StringPoolRef(best_package->GetTypeStringPool(), best_type->id - 1);
618 last_resolution.entry_string_ref =
619 StringPoolRef(best_package->GetKeyStringPool(), best_entry->key.index);
620 }
621
Adam Lesinskida431a22016-12-29 16:08:16 -0500622 return best_cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700623}
624
Winson2f3669b2019-01-11 11:28:34 -0800625void AssetManager2::SetResourceResolutionLoggingEnabled(bool enabled) {
626 resource_resolution_logging_enabled_ = enabled;
627
628 if (!enabled) {
629 last_resolution.cookie = kInvalidCookie;
630 last_resolution.resid = 0;
631 last_resolution.steps.clear();
632 last_resolution.type_string_ref = StringPoolRef();
633 last_resolution.entry_string_ref = StringPoolRef();
634 }
635}
636
637std::string AssetManager2::GetLastResourceResolution() const {
638 if (!resource_resolution_logging_enabled_) {
639 LOG(ERROR) << "Must enable resource resolution logging before getting path.";
640 return std::string();
641 }
642
643 auto cookie = last_resolution.cookie;
644 if (cookie == kInvalidCookie) {
645 LOG(ERROR) << "AssetManager hasn't resolved a resource to read resolution path.";
646 return std::string();
647 }
648
649 uint32_t resid = last_resolution.resid;
650 std::vector<Resolution::Step>& steps = last_resolution.steps;
651
652 ResourceName resource_name;
653 std::string resource_name_string;
654
655 const LoadedPackage* package =
656 apk_assets_[cookie]->GetLoadedArsc()->GetPackageById(get_package_id(resid));
657
658 if (package != nullptr) {
659 ToResourceName(last_resolution.type_string_ref,
660 last_resolution.entry_string_ref,
Ryan Mitchell741e96f2019-01-23 16:56:51 -0800661 package->GetPackageName(),
Winson2f3669b2019-01-11 11:28:34 -0800662 &resource_name);
663 resource_name_string = ToFormattedResourceString(&resource_name);
664 }
665
666 std::stringstream log_stream;
667 log_stream << base::StringPrintf("Resolution for 0x%08x ", resid)
668 << resource_name_string
669 << "\n\tFor config -"
670 << configuration_.toString();
671
672 std::string prefix;
673 for (Resolution::Step step : steps) {
674 switch (step.type) {
675 case Resolution::Step::Type::INITIAL:
676 prefix = "Found initial";
677 break;
678 case Resolution::Step::Type::BETTER_MATCH:
679 prefix = "Found better";
680 break;
681 case Resolution::Step::Type::OVERLAID:
682 prefix = "Overlaid";
683 break;
684 }
685
686 if (!prefix.empty()) {
687 log_stream << "\n\t" << prefix << ": " << *step.package_name;
688
689 if (!step.config_name.isEmpty()) {
690 log_stream << " -" << step.config_name;
691 }
692 }
693 }
694
695 return log_stream.str();
696}
697
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800698bool AssetManager2::GetResourceName(uint32_t resid, ResourceName* out_name) const {
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700699 FindEntryResult entry;
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800700 ApkAssetsCookie cookie = FindEntry(resid, 0u /* density_override */,
701 true /* stop_at_first_match */,
702 true /* ignore_configuration */, &entry);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700703 if (cookie == kInvalidCookie) {
704 return false;
705 }
706
Ryan Mitchell741e96f2019-01-23 16:56:51 -0800707 const uint8_t package_idx = package_ids_[get_package_id(resid)];
708 if (package_idx == 0xff) {
709 LOG(ERROR) << base::StringPrintf("No package ID %02x found for ID 0x%08x.",
710 get_package_id(resid), resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700711 return false;
712 }
713
Ryan Mitchell741e96f2019-01-23 16:56:51 -0800714 const PackageGroup& package_group = package_groups_[package_idx];
715 auto cookie_iter = std::find(package_group.cookies_.begin(),
716 package_group.cookies_.end(), cookie);
717 if (cookie_iter == package_group.cookies_.end()) {
718 return false;
719 }
720
721 long package_pos = std::distance(package_group.cookies_.begin(), cookie_iter);
722 const LoadedPackage* package = package_group.packages_[package_pos].loaded_package_;
Winson2f3669b2019-01-11 11:28:34 -0800723 return ToResourceName(entry.type_string_ref,
724 entry.entry_string_ref,
Ryan Mitchell741e96f2019-01-23 16:56:51 -0800725 package->GetPackageName(),
Winson2f3669b2019-01-11 11:28:34 -0800726 out_name);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700727}
728
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800729bool AssetManager2::GetResourceFlags(uint32_t resid, uint32_t* out_flags) const {
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700730 FindEntryResult entry;
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800731 ApkAssetsCookie cookie = FindEntry(resid, 0u /* density_override */,
732 false /* stop_at_first_match */,
733 true /* ignore_configuration */, &entry);
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700734 if (cookie != kInvalidCookie) {
735 *out_flags = entry.type_flags;
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800736 return true;
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700737 }
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800738 return false;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700739}
740
741ApkAssetsCookie AssetManager2::GetResource(uint32_t resid, bool may_be_bag,
742 uint16_t density_override, Res_value* out_value,
743 ResTable_config* out_selected_config,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800744 uint32_t* out_flags) const {
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700745 FindEntryResult entry;
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800746 ApkAssetsCookie cookie = FindEntry(resid, density_override, false /* stop_at_first_match */,
747 false /* ignore_configuration */, &entry);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700748 if (cookie == kInvalidCookie) {
749 return kInvalidCookie;
750 }
751
Adam Lesinski498f6052017-11-29 13:24:29 -0800752 if (dtohs(entry.entry->flags) & ResTable_entry::FLAG_COMPLEX) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700753 if (!may_be_bag) {
754 LOG(ERROR) << base::StringPrintf("Resource %08x is a complex map type.", resid);
Adam Lesinski0c405242017-01-13 20:47:26 -0800755 return kInvalidCookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700756 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800757
758 // Create a reference since we can't represent this complex type as a Res_value.
759 out_value->dataType = Res_value::TYPE_REFERENCE;
760 out_value->data = resid;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800761 *out_selected_config = entry.config;
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700762 *out_flags = entry.type_flags;
Adam Lesinski0c405242017-01-13 20:47:26 -0800763 return cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700764 }
765
766 const Res_value* device_value = reinterpret_cast<const Res_value*>(
767 reinterpret_cast<const uint8_t*>(entry.entry) + dtohs(entry.entry->size));
768 out_value->copyFrom_dtoh(*device_value);
Adam Lesinskida431a22016-12-29 16:08:16 -0500769
770 // Convert the package ID to the runtime assigned package ID.
771 entry.dynamic_ref_table->lookupResourceValue(out_value);
772
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800773 *out_selected_config = entry.config;
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700774 *out_flags = entry.type_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700775 return cookie;
776}
777
Adam Lesinski0c405242017-01-13 20:47:26 -0800778ApkAssetsCookie AssetManager2::ResolveReference(ApkAssetsCookie cookie, Res_value* in_out_value,
779 ResTable_config* in_out_selected_config,
780 uint32_t* in_out_flags,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800781 uint32_t* out_last_reference) const {
Adam Lesinski0c405242017-01-13 20:47:26 -0800782 constexpr const int kMaxIterations = 20;
783
Adam Lesinski0c405242017-01-13 20:47:26 -0800784 for (size_t iteration = 0u; in_out_value->dataType == Res_value::TYPE_REFERENCE &&
785 in_out_value->data != 0u && iteration < kMaxIterations;
786 iteration++) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800787 *out_last_reference = in_out_value->data;
Adam Lesinski0c405242017-01-13 20:47:26 -0800788 uint32_t new_flags = 0u;
789 cookie = GetResource(in_out_value->data, true /*may_be_bag*/, 0u /*density_override*/,
790 in_out_value, in_out_selected_config, &new_flags);
791 if (cookie == kInvalidCookie) {
792 return kInvalidCookie;
793 }
794 if (in_out_flags != nullptr) {
795 *in_out_flags |= new_flags;
796 }
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800797 if (*out_last_reference == in_out_value->data) {
Adam Lesinski0c405242017-01-13 20:47:26 -0800798 // This reference can't be resolved, so exit now and let the caller deal with it.
799 return cookie;
800 }
801 }
802 return cookie;
803}
804
Aurimas Liutikas8f004c82019-01-17 17:20:10 -0800805const std::vector<uint32_t> AssetManager2::GetBagResIdStack(uint32_t resid) {
806 auto cached_iter = cached_bag_resid_stacks_.find(resid);
807 if (cached_iter != cached_bag_resid_stacks_.end()) {
808 return cached_iter->second;
809 } else {
810 auto found_resids = std::vector<uint32_t>();
811 GetBag(resid, found_resids);
812 // Cache style stacks if they are not already cached.
813 cached_bag_resid_stacks_[resid] = found_resids;
814 return found_resids;
815 }
816}
817
Adam Lesinski7ad11102016-10-28 16:39:15 -0700818const ResolvedBag* AssetManager2::GetBag(uint32_t resid) {
y57cd1952018-04-12 14:26:23 -0700819 auto found_resids = std::vector<uint32_t>();
Aurimas Liutikas8f004c82019-01-17 17:20:10 -0800820 auto bag = GetBag(resid, found_resids);
821
822 // Cache style stacks if they are not already cached.
823 auto cached_iter = cached_bag_resid_stacks_.find(resid);
824 if (cached_iter == cached_bag_resid_stacks_.end()) {
825 cached_bag_resid_stacks_[resid] = found_resids;
826 }
827 return bag;
y57cd1952018-04-12 14:26:23 -0700828}
829
830const ResolvedBag* AssetManager2::GetBag(uint32_t resid, std::vector<uint32_t>& child_resids) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700831 auto cached_iter = cached_bags_.find(resid);
832 if (cached_iter != cached_bags_.end()) {
833 return cached_iter->second.get();
834 }
835
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700836 FindEntryResult entry;
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800837 ApkAssetsCookie cookie = FindEntry(resid, 0u /* density_override */,
838 false /* stop_at_first_match */,
839 false /* ignore_configuration */,
840 &entry);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700841 if (cookie == kInvalidCookie) {
842 return nullptr;
843 }
844
845 // Check that the size of the entry header is at least as big as
846 // the desired ResTable_map_entry. Also verify that the entry
847 // was intended to be a map.
848 if (dtohs(entry.entry->size) < sizeof(ResTable_map_entry) ||
849 (dtohs(entry.entry->flags) & ResTable_entry::FLAG_COMPLEX) == 0) {
850 // Not a bag, nothing to do.
851 return nullptr;
852 }
853
854 const ResTable_map_entry* map = reinterpret_cast<const ResTable_map_entry*>(entry.entry);
855 const ResTable_map* map_entry =
856 reinterpret_cast<const ResTable_map*>(reinterpret_cast<const uint8_t*>(map) + map->size);
857 const ResTable_map* const map_entry_end = map_entry + dtohl(map->count);
858
y57cd1952018-04-12 14:26:23 -0700859 // Keep track of ids that have already been seen to prevent infinite loops caused by circular
860 // dependencies between bags
861 child_resids.push_back(resid);
862
Adam Lesinskida431a22016-12-29 16:08:16 -0500863 uint32_t parent_resid = dtohl(map->parent.ident);
y57cd1952018-04-12 14:26:23 -0700864 if (parent_resid == 0 || std::find(child_resids.begin(), child_resids.end(), parent_resid)
865 != child_resids.end()) {
866 // There is no parent or that a circular dependency exist, meaning there is nothing to
867 // inherit and we can do a simple copy of the entries in the map.
Adam Lesinski7ad11102016-10-28 16:39:15 -0700868 const size_t entry_count = map_entry_end - map_entry;
869 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
870 malloc(sizeof(ResolvedBag) + (entry_count * sizeof(ResolvedBag::Entry))))};
871 ResolvedBag::Entry* new_entry = new_bag->entries;
872 for (; map_entry != map_entry_end; ++map_entry) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500873 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -0800874 if (!is_internal_resid(new_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500875 // Attributes, arrays, etc don't have a resource id as the name. They specify
876 // other data, which would be wrong to change via a lookup.
877 if (entry.dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800878 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
879 resid);
Adam Lesinskida431a22016-12-29 16:08:16 -0500880 return nullptr;
881 }
882 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700883 new_entry->cookie = cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -0500884 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700885 new_entry->key_pool = nullptr;
886 new_entry->type_pool = nullptr;
Aurimas Liutikasd42a6702018-11-15 15:48:28 -0800887 new_entry->style = resid;
Adam Lesinski30080e22017-10-16 16:18:09 -0700888 new_entry->value.copyFrom_dtoh(map_entry->value);
889 status_t err = entry.dynamic_ref_table->lookupResourceValue(&new_entry->value);
890 if (err != NO_ERROR) {
891 LOG(ERROR) << base::StringPrintf(
892 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
893 new_entry->value.data, new_key);
894 return nullptr;
895 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700896 ++new_entry;
897 }
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700898 new_bag->type_spec_flags = entry.type_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700899 new_bag->entry_count = static_cast<uint32_t>(entry_count);
900 ResolvedBag* result = new_bag.get();
901 cached_bags_[resid] = std::move(new_bag);
902 return result;
903 }
904
Adam Lesinskida431a22016-12-29 16:08:16 -0500905 // In case the parent is a dynamic reference, resolve it.
906 entry.dynamic_ref_table->lookupResourceId(&parent_resid);
907
Adam Lesinski7ad11102016-10-28 16:39:15 -0700908 // Get the parent and do a merge of the keys.
y57cd1952018-04-12 14:26:23 -0700909 const ResolvedBag* parent_bag = GetBag(parent_resid, child_resids);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700910 if (parent_bag == nullptr) {
911 // Failed to get the parent that should exist.
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800912 LOG(ERROR) << base::StringPrintf("Failed to find parent 0x%08x of bag 0x%08x.", parent_resid,
913 resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700914 return nullptr;
915 }
916
Adam Lesinski7ad11102016-10-28 16:39:15 -0700917 // Create the max possible entries we can make. Once we construct the bag,
918 // we will realloc to fit to size.
919 const size_t max_count = parent_bag->entry_count + dtohl(map->count);
George Burgess IV09b119f2017-07-25 15:00:04 -0700920 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
921 malloc(sizeof(ResolvedBag) + (max_count * sizeof(ResolvedBag::Entry))))};
Adam Lesinski7ad11102016-10-28 16:39:15 -0700922 ResolvedBag::Entry* new_entry = new_bag->entries;
923
924 const ResolvedBag::Entry* parent_entry = parent_bag->entries;
925 const ResolvedBag::Entry* const parent_entry_end = parent_entry + parent_bag->entry_count;
926
927 // The keys are expected to be in sorted order. Merge the two bags.
928 while (map_entry != map_entry_end && parent_entry != parent_entry_end) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500929 uint32_t child_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -0800930 if (!is_internal_resid(child_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500931 if (entry.dynamic_ref_table->lookupResourceId(&child_key) != NO_ERROR) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800932 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", child_key,
933 resid);
Adam Lesinskida431a22016-12-29 16:08:16 -0500934 return nullptr;
935 }
936 }
937
Adam Lesinski7ad11102016-10-28 16:39:15 -0700938 if (child_key <= parent_entry->key) {
939 // Use the child key if it comes before the parent
940 // or is equal to the parent (overrides).
941 new_entry->cookie = cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700942 new_entry->key = child_key;
943 new_entry->key_pool = nullptr;
944 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -0700945 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -0800946 new_entry->style = resid;
Adam Lesinski30080e22017-10-16 16:18:09 -0700947 status_t err = entry.dynamic_ref_table->lookupResourceValue(&new_entry->value);
948 if (err != NO_ERROR) {
949 LOG(ERROR) << base::StringPrintf(
950 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
951 new_entry->value.data, child_key);
952 return nullptr;
953 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700954 ++map_entry;
955 } else {
956 // Take the parent entry as-is.
957 memcpy(new_entry, parent_entry, sizeof(*new_entry));
958 }
959
960 if (child_key >= parent_entry->key) {
961 // Move to the next parent entry if we used it or it was overridden.
962 ++parent_entry;
963 }
964 // Increment to the next entry to fill.
965 ++new_entry;
966 }
967
968 // Finish the child entries if they exist.
969 while (map_entry != map_entry_end) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500970 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -0800971 if (!is_internal_resid(new_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500972 if (entry.dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800973 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
974 resid);
Adam Lesinskida431a22016-12-29 16:08:16 -0500975 return nullptr;
976 }
977 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700978 new_entry->cookie = cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -0500979 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700980 new_entry->key_pool = nullptr;
981 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -0700982 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -0800983 new_entry->style = resid;
Adam Lesinski30080e22017-10-16 16:18:09 -0700984 status_t err = entry.dynamic_ref_table->lookupResourceValue(&new_entry->value);
985 if (err != NO_ERROR) {
986 LOG(ERROR) << base::StringPrintf("Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.",
987 new_entry->value.dataType, new_entry->value.data, new_key);
988 return nullptr;
989 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700990 ++map_entry;
991 ++new_entry;
992 }
993
994 // Finish the parent entries if they exist.
995 if (parent_entry != parent_entry_end) {
996 // Take the rest of the parent entries as-is.
997 const size_t num_entries_to_copy = parent_entry_end - parent_entry;
998 memcpy(new_entry, parent_entry, num_entries_to_copy * sizeof(*new_entry));
999 new_entry += num_entries_to_copy;
1000 }
1001
1002 // Resize the resulting array to fit.
1003 const size_t actual_count = new_entry - new_bag->entries;
1004 if (actual_count != max_count) {
George Burgess IV09b119f2017-07-25 15:00:04 -07001005 new_bag.reset(reinterpret_cast<ResolvedBag*>(realloc(
1006 new_bag.release(), sizeof(ResolvedBag) + (actual_count * sizeof(ResolvedBag::Entry)))));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001007 }
1008
Adam Lesinski1a1e9c22017-10-13 15:45:34 -07001009 // Combine flags from the parent and our own bag.
1010 new_bag->type_spec_flags = entry.type_flags | parent_bag->type_spec_flags;
George Burgess IV09b119f2017-07-25 15:00:04 -07001011 new_bag->entry_count = static_cast<uint32_t>(actual_count);
1012 ResolvedBag* result = new_bag.get();
1013 cached_bags_[resid] = std::move(new_bag);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001014 return result;
1015}
1016
Adam Lesinski929d6512017-01-16 19:11:19 -08001017static bool Utf8ToUtf16(const StringPiece& str, std::u16string* out) {
1018 ssize_t len =
1019 utf8_to_utf16_length(reinterpret_cast<const uint8_t*>(str.data()), str.size(), false);
1020 if (len < 0) {
1021 return false;
1022 }
1023 out->resize(static_cast<size_t>(len));
1024 utf8_to_utf16(reinterpret_cast<const uint8_t*>(str.data()), str.size(), &*out->begin(),
1025 static_cast<size_t>(len + 1));
1026 return true;
1027}
1028
Adam Lesinski0c405242017-01-13 20:47:26 -08001029uint32_t AssetManager2::GetResourceId(const std::string& resource_name,
1030 const std::string& fallback_type,
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001031 const std::string& fallback_package) const {
Adam Lesinski929d6512017-01-16 19:11:19 -08001032 StringPiece package_name, type, entry;
1033 if (!ExtractResourceName(resource_name, &package_name, &type, &entry)) {
1034 return 0u;
1035 }
1036
1037 if (entry.empty()) {
1038 return 0u;
1039 }
1040
1041 if (package_name.empty()) {
1042 package_name = fallback_package;
1043 }
1044
1045 if (type.empty()) {
1046 type = fallback_type;
1047 }
1048
1049 std::u16string type16;
1050 if (!Utf8ToUtf16(type, &type16)) {
1051 return 0u;
1052 }
1053
1054 std::u16string entry16;
1055 if (!Utf8ToUtf16(entry, &entry16)) {
1056 return 0u;
1057 }
1058
1059 const StringPiece16 kAttr16 = u"attr";
1060 const static std::u16string kAttrPrivate16 = u"^attr-private";
1061
1062 for (const PackageGroup& package_group : package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001063 for (const ConfiguredPackage& package_impl : package_group.packages_) {
1064 const LoadedPackage* package = package_impl.loaded_package_;
Adam Lesinski929d6512017-01-16 19:11:19 -08001065 if (package_name != package->GetPackageName()) {
1066 // All packages in the same group are expected to have the same package name.
1067 break;
1068 }
1069
1070 uint32_t resid = package->FindEntryByName(type16, entry16);
1071 if (resid == 0u && kAttr16 == type16) {
1072 // Private attributes in libraries (such as the framework) are sometimes encoded
1073 // under the type '^attr-private' in order to leave the ID space of public 'attr'
1074 // free for future additions. Check '^attr-private' for the same name.
1075 resid = package->FindEntryByName(kAttrPrivate16, entry16);
1076 }
1077
1078 if (resid != 0u) {
1079 return fix_package_id(resid, package_group.dynamic_ref_table.mAssignedPackageId);
1080 }
1081 }
1082 }
Adam Lesinski0c405242017-01-13 20:47:26 -08001083 return 0u;
1084}
1085
Mårten Kongstad668ec5b2018-06-11 14:11:33 +02001086void AssetManager2::RebuildFilterList(bool filter_incompatible_configs) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001087 for (PackageGroup& group : package_groups_) {
1088 for (ConfiguredPackage& impl : group.packages_) {
1089 // Destroy it.
1090 impl.filtered_configs_.~ByteBucketArray();
1091
1092 // Re-create it.
1093 new (&impl.filtered_configs_) ByteBucketArray<FilteredConfigGroup>();
1094
1095 // Create the filters here.
1096 impl.loaded_package_->ForEachTypeSpec([&](const TypeSpec* spec, uint8_t type_index) {
1097 FilteredConfigGroup& group = impl.filtered_configs_.editItemAt(type_index);
1098 const auto iter_end = spec->types + spec->type_count;
1099 for (auto iter = spec->types; iter != iter_end; ++iter) {
1100 ResTable_config this_config;
1101 this_config.copyFromDtoH((*iter)->config);
Mårten Kongstad668ec5b2018-06-11 14:11:33 +02001102 if (!filter_incompatible_configs || this_config.match(configuration_)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001103 group.configurations.push_back(this_config);
1104 group.types.push_back(*iter);
1105 }
1106 }
1107 });
1108 }
1109 }
1110}
1111
Adam Lesinski7ad11102016-10-28 16:39:15 -07001112void AssetManager2::InvalidateCaches(uint32_t diff) {
Ryan Mitchell2c4d8742019-03-04 09:41:00 -08001113 cached_bag_resid_stacks_.clear();
1114
Adam Lesinski7ad11102016-10-28 16:39:15 -07001115 if (diff == 0xffffffffu) {
1116 // Everything must go.
1117 cached_bags_.clear();
1118 return;
1119 }
1120
1121 // Be more conservative with what gets purged. Only if the bag has other possible
1122 // variations with respect to what changed (diff) should we remove it.
1123 for (auto iter = cached_bags_.cbegin(); iter != cached_bags_.cend();) {
1124 if (diff & iter->second->type_spec_flags) {
1125 iter = cached_bags_.erase(iter);
1126 } else {
1127 ++iter;
1128 }
1129 }
1130}
1131
Ryan Mitchell2e394222019-08-28 12:10:51 -07001132uint8_t AssetManager2::GetAssignedPackageId(const LoadedPackage* package) const {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001133 for (auto& package_group : package_groups_) {
1134 for (auto& package2 : package_group.packages_) {
1135 if (package2.loaded_package_ == package) {
1136 return package_group.dynamic_ref_table.mAssignedPackageId;
1137 }
1138 }
1139 }
1140 return 0;
1141}
1142
Adam Lesinski30080e22017-10-16 16:18:09 -07001143std::unique_ptr<Theme> AssetManager2::NewTheme() {
1144 return std::unique_ptr<Theme>(new Theme(this));
1145}
1146
1147Theme::Theme(AssetManager2* asset_manager) : asset_manager_(asset_manager) {
1148}
1149
1150Theme::~Theme() = default;
1151
1152namespace {
1153
1154struct ThemeEntry {
1155 ApkAssetsCookie cookie;
1156 uint32_t type_spec_flags;
1157 Res_value value;
1158};
1159
1160struct ThemeType {
1161 int entry_count;
1162 ThemeEntry entries[0];
1163};
1164
1165constexpr size_t kTypeCount = std::numeric_limits<uint8_t>::max() + 1;
1166
1167} // namespace
1168
1169struct Theme::Package {
1170 // Each element of Type will be a dynamically sized object
1171 // allocated to have the entries stored contiguously with the Type.
1172 std::array<util::unique_cptr<ThemeType>, kTypeCount> types;
1173};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001174
1175bool Theme::ApplyStyle(uint32_t resid, bool force) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001176 ATRACE_NAME("Theme::ApplyStyle");
Adam Lesinski7ad11102016-10-28 16:39:15 -07001177
1178 const ResolvedBag* bag = asset_manager_->GetBag(resid);
1179 if (bag == nullptr) {
1180 return false;
1181 }
1182
1183 // Merge the flags from this style.
1184 type_spec_flags_ |= bag->type_spec_flags;
1185
Adam Lesinski30080e22017-10-16 16:18:09 -07001186 int last_type_idx = -1;
1187 int last_package_idx = -1;
1188 Package* last_package = nullptr;
1189 ThemeType* last_type = nullptr;
1190
1191 // Iterate backwards, because each bag is sorted in ascending key ID order, meaning we will only
1192 // need to perform one resize per type.
1193 using reverse_bag_iterator = std::reverse_iterator<const ResolvedBag::Entry*>;
1194 const auto bag_iter_end = reverse_bag_iterator(begin(bag));
1195 for (auto bag_iter = reverse_bag_iterator(end(bag)); bag_iter != bag_iter_end; ++bag_iter) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001196 const uint32_t attr_resid = bag_iter->key;
1197
Adam Lesinski30080e22017-10-16 16:18:09 -07001198 // If the resource ID passed in is not a style, the key can be some other identifier that is not
1199 // a resource ID. We should fail fast instead of operating with strange resource IDs.
Adam Lesinski929d6512017-01-16 19:11:19 -08001200 if (!is_valid_resid(attr_resid)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001201 return false;
1202 }
1203
Adam Lesinski30080e22017-10-16 16:18:09 -07001204 // We don't use the 0-based index for the type so that we can avoid doing ID validation
1205 // upon lookup. Instead, we keep space for the type ID 0 in our data structures. Since
1206 // the construction of this type is guarded with a resource ID check, it will never be
1207 // populated, and querying type ID 0 will always fail.
1208 const int package_idx = get_package_id(attr_resid);
1209 const int type_idx = get_type_id(attr_resid);
1210 const int entry_idx = get_entry_id(attr_resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001211
Adam Lesinski30080e22017-10-16 16:18:09 -07001212 if (last_package_idx != package_idx) {
1213 std::unique_ptr<Package>& package = packages_[package_idx];
1214 if (package == nullptr) {
1215 package.reset(new Package());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001216 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001217 last_package_idx = package_idx;
1218 last_package = package.get();
1219 last_type_idx = -1;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001220 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001221
1222 if (last_type_idx != type_idx) {
1223 util::unique_cptr<ThemeType>& type = last_package->types[type_idx];
1224 if (type == nullptr) {
1225 // Allocate enough memory to contain this entry_idx. Since we're iterating in reverse over
1226 // a sorted list of attributes, this shouldn't be resized again during this method call.
1227 type.reset(reinterpret_cast<ThemeType*>(
1228 calloc(sizeof(ThemeType) + (entry_idx + 1) * sizeof(ThemeEntry), 1)));
1229 type->entry_count = entry_idx + 1;
1230 } else if (entry_idx >= type->entry_count) {
1231 // Reallocate the memory to contain this entry_idx. Since we're iterating in reverse over
1232 // a sorted list of attributes, this shouldn't be resized again during this method call.
1233 const int new_count = entry_idx + 1;
1234 type.reset(reinterpret_cast<ThemeType*>(
1235 realloc(type.release(), sizeof(ThemeType) + (new_count * sizeof(ThemeEntry)))));
1236
1237 // Clear out the newly allocated space (which isn't zeroed).
1238 memset(type->entries + type->entry_count, 0,
1239 (new_count - type->entry_count) * sizeof(ThemeEntry));
1240 type->entry_count = new_count;
1241 }
1242 last_type_idx = type_idx;
1243 last_type = type.get();
1244 }
1245
1246 ThemeEntry& entry = last_type->entries[entry_idx];
1247 if (force || (entry.value.dataType == Res_value::TYPE_NULL &&
1248 entry.value.data != Res_value::DATA_NULL_EMPTY)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001249 entry.cookie = bag_iter->cookie;
1250 entry.type_spec_flags |= bag->type_spec_flags;
1251 entry.value = bag_iter->value;
1252 }
1253 }
1254 return true;
1255}
1256
1257ApkAssetsCookie Theme::GetAttribute(uint32_t resid, Res_value* out_value,
1258 uint32_t* out_flags) const {
Adam Lesinski30080e22017-10-16 16:18:09 -07001259 int cnt = 20;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001260
1261 uint32_t type_spec_flags = 0u;
1262
Adam Lesinski30080e22017-10-16 16:18:09 -07001263 do {
1264 const int package_idx = get_package_id(resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001265 const Package* package = packages_[package_idx].get();
Adam Lesinski30080e22017-10-16 16:18:09 -07001266 if (package != nullptr) {
1267 // The themes are constructed with a 1-based type ID, so no need to decrement here.
1268 const int type_idx = get_type_id(resid);
1269 const ThemeType* type = package->types[type_idx].get();
1270 if (type != nullptr) {
1271 const int entry_idx = get_entry_id(resid);
1272 if (entry_idx < type->entry_count) {
1273 const ThemeEntry& entry = type->entries[entry_idx];
1274 type_spec_flags |= entry.type_spec_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001275
Adam Lesinski30080e22017-10-16 16:18:09 -07001276 if (entry.value.dataType == Res_value::TYPE_ATTRIBUTE) {
1277 if (cnt > 0) {
1278 cnt--;
1279 resid = entry.value.data;
1280 continue;
1281 }
1282 return kInvalidCookie;
1283 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001284
Adam Lesinski30080e22017-10-16 16:18:09 -07001285 // @null is different than @empty.
1286 if (entry.value.dataType == Res_value::TYPE_NULL &&
1287 entry.value.data != Res_value::DATA_NULL_EMPTY) {
1288 return kInvalidCookie;
1289 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001290
Adam Lesinski30080e22017-10-16 16:18:09 -07001291 *out_value = entry.value;
Adam Lesinskida431a22016-12-29 16:08:16 -05001292 *out_flags = type_spec_flags;
Adam Lesinski30080e22017-10-16 16:18:09 -07001293 return entry.cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -05001294 }
Adam Lesinskida431a22016-12-29 16:08:16 -05001295 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001296 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001297 break;
1298 } while (true);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001299 return kInvalidCookie;
1300}
1301
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001302ApkAssetsCookie Theme::ResolveAttributeReference(ApkAssetsCookie cookie, Res_value* in_out_value,
1303 ResTable_config* in_out_selected_config,
1304 uint32_t* in_out_type_spec_flags,
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001305 uint32_t* out_last_ref) const {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001306 if (in_out_value->dataType == Res_value::TYPE_ATTRIBUTE) {
1307 uint32_t new_flags;
1308 cookie = GetAttribute(in_out_value->data, in_out_value, &new_flags);
1309 if (cookie == kInvalidCookie) {
1310 return kInvalidCookie;
1311 }
1312
1313 if (in_out_type_spec_flags != nullptr) {
1314 *in_out_type_spec_flags |= new_flags;
1315 }
1316 }
1317 return asset_manager_->ResolveReference(cookie, in_out_value, in_out_selected_config,
1318 in_out_type_spec_flags, out_last_ref);
1319}
1320
Adam Lesinski7ad11102016-10-28 16:39:15 -07001321void Theme::Clear() {
1322 type_spec_flags_ = 0u;
1323 for (std::unique_ptr<Package>& package : packages_) {
1324 package.reset();
1325 }
1326}
1327
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001328void Theme::SetTo(const Theme& o) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001329 if (this == &o) {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001330 return;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001331 }
1332
Adam Lesinski7ad11102016-10-28 16:39:15 -07001333 type_spec_flags_ = o.type_spec_flags_;
1334
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001335 if (asset_manager_ == o.asset_manager_) {
1336 // The theme comes from the same asset manager so all theme data can be copied exactly
1337 for (size_t p = 0; p < packages_.size(); p++) {
1338 const Package *package = o.packages_[p].get();
1339 if (package == nullptr) {
1340 // The other theme doesn't have this package, clear ours.
1341 packages_[p].reset();
Adam Lesinski7ad11102016-10-28 16:39:15 -07001342 continue;
1343 }
1344
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001345 if (packages_[p] == nullptr) {
1346 // The other theme has this package, but we don't. Make one.
1347 packages_[p].reset(new Package());
1348 }
1349
1350 for (size_t t = 0; t < package->types.size(); t++) {
1351 const ThemeType *type = package->types[t].get();
1352 if (type == nullptr) {
1353 // The other theme doesn't have this type, clear ours.
1354 packages_[p]->types[t].reset();
1355 continue;
1356 }
1357
1358 // Create a new type and update it to theirs.
1359 const size_t type_alloc_size = sizeof(ThemeType) + (type->entry_count * sizeof(ThemeEntry));
1360 void *copied_data = malloc(type_alloc_size);
1361 memcpy(copied_data, type, type_alloc_size);
1362 packages_[p]->types[t].reset(reinterpret_cast<ThemeType *>(copied_data));
1363 }
1364 }
1365 } else {
1366 std::map<ApkAssetsCookie, ApkAssetsCookie> src_to_dest_asset_cookies;
1367 typedef std::map<int, int> SourceToDestinationRuntimePackageMap;
1368 std::map<ApkAssetsCookie, SourceToDestinationRuntimePackageMap> src_asset_cookie_id_map;
1369
Ryan Mitchell93bca972019-03-08 17:26:28 -08001370 // Determine which ApkAssets are loaded in both theme AssetManagers.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001371 std::vector<const ApkAssets*> src_assets = o.asset_manager_->GetApkAssets();
1372 for (size_t i = 0; i < src_assets.size(); i++) {
1373 const ApkAssets* src_asset = src_assets[i];
1374
1375 std::vector<const ApkAssets*> dest_assets = asset_manager_->GetApkAssets();
1376 for (size_t j = 0; j < dest_assets.size(); j++) {
1377 const ApkAssets* dest_asset = dest_assets[j];
1378
Ryan Mitchell93bca972019-03-08 17:26:28 -08001379 // Map the runtime package of the source apk asset to the destination apk asset.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001380 if (src_asset->GetPath() == dest_asset->GetPath()) {
1381 const std::vector<std::unique_ptr<const LoadedPackage>>& src_packages =
1382 src_asset->GetLoadedArsc()->GetPackages();
1383 const std::vector<std::unique_ptr<const LoadedPackage>>& dest_packages =
1384 dest_asset->GetLoadedArsc()->GetPackages();
1385
1386 SourceToDestinationRuntimePackageMap package_map;
1387
1388 // The source and destination package should have the same number of packages loaded in
1389 // the same order.
1390 const size_t N = src_packages.size();
1391 CHECK(N == dest_packages.size())
1392 << " LoadedArsc " << src_asset->GetPath() << " differs number of packages.";
1393 for (size_t p = 0; p < N; p++) {
1394 auto& src_package = src_packages[p];
1395 auto& dest_package = dest_packages[p];
1396 CHECK(src_package->GetPackageName() == dest_package->GetPackageName())
1397 << " Package " << src_package->GetPackageName() << " differs in load order.";
1398
1399 int src_package_id = o.asset_manager_->GetAssignedPackageId(src_package.get());
1400 int dest_package_id = asset_manager_->GetAssignedPackageId(dest_package.get());
1401 package_map[src_package_id] = dest_package_id;
1402 }
1403
Ryan Mitchell93bca972019-03-08 17:26:28 -08001404 src_to_dest_asset_cookies.insert(std::make_pair(i, j));
1405 src_asset_cookie_id_map.insert(std::make_pair(i, package_map));
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001406 break;
1407 }
1408 }
1409 }
1410
Ryan Mitchell93bca972019-03-08 17:26:28 -08001411 // Reset the data in the destination theme.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001412 for (size_t p = 0; p < packages_.size(); p++) {
1413 if (packages_[p] != nullptr) {
1414 packages_[p].reset();
1415 }
1416 }
1417
1418 for (size_t p = 0; p < packages_.size(); p++) {
1419 const Package *package = o.packages_[p].get();
1420 if (package == nullptr) {
1421 continue;
1422 }
1423
1424 for (size_t t = 0; t < package->types.size(); t++) {
1425 const ThemeType *type = package->types[t].get();
1426 if (type == nullptr) {
1427 continue;
1428 }
1429
1430 for (size_t e = 0; e < type->entry_count; e++) {
1431 const ThemeEntry &entry = type->entries[e];
1432 if (entry.value.dataType == Res_value::TYPE_NULL &&
1433 entry.value.data != Res_value::DATA_NULL_EMPTY) {
1434 continue;
1435 }
1436
Ryan Mitchell93bca972019-03-08 17:26:28 -08001437 bool is_reference = (entry.value.dataType == Res_value::TYPE_ATTRIBUTE
1438 || entry.value.dataType == Res_value::TYPE_REFERENCE
1439 || entry.value.dataType == Res_value::TYPE_DYNAMIC_ATTRIBUTE
1440 || entry.value.dataType == Res_value::TYPE_DYNAMIC_REFERENCE)
1441 && entry.value.data != 0x0;
Ryan Mitchellb85d9b22018-11-19 12:11:38 -08001442
Ryan Mitchell93bca972019-03-08 17:26:28 -08001443 // If the attribute value represents an attribute or reference, the package id of the
1444 // value needs to be rewritten to the package id of the value in the destination.
1445 uint32_t attribute_data = entry.value.data;
1446 if (is_reference) {
1447 // Determine the package id of the reference in the destination AssetManager.
Ryan Mitchellb85d9b22018-11-19 12:11:38 -08001448 auto value_package_map = src_asset_cookie_id_map.find(entry.cookie);
1449 if (value_package_map == src_asset_cookie_id_map.end()) {
1450 continue;
1451 }
1452
1453 auto value_dest_package = value_package_map->second.find(
1454 get_package_id(entry.value.data));
1455 if (value_dest_package == value_package_map->second.end()) {
1456 continue;
1457 }
1458
Ryan Mitchell93bca972019-03-08 17:26:28 -08001459 attribute_data = fix_package_id(entry.value.data, value_dest_package->second);
1460 }
1461
1462 // Find the cookie of the value in the destination. If the source apk is not loaded in the
1463 // destination, only copy resources that do not reference resources in the source.
1464 ApkAssetsCookie data_dest_cookie;
1465 auto value_dest_cookie = src_to_dest_asset_cookies.find(entry.cookie);
1466 if (value_dest_cookie != src_to_dest_asset_cookies.end()) {
1467 data_dest_cookie = value_dest_cookie->second;
1468 } else {
1469 if (is_reference || entry.value.dataType == Res_value::TYPE_STRING) {
1470 continue;
1471 } else {
1472 data_dest_cookie = 0x0;
1473 }
Ryan Mitchellb85d9b22018-11-19 12:11:38 -08001474 }
1475
1476 // The package id of the attribute needs to be rewritten to the package id of the
Ryan Mitchell93bca972019-03-08 17:26:28 -08001477 // attribute in the destination.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001478 int attribute_dest_package_id = p;
1479 if (attribute_dest_package_id != 0x01) {
Ryan Mitchell93bca972019-03-08 17:26:28 -08001480 // Find the cookie of the attribute resource id in the source AssetManager
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001481 FindEntryResult attribute_entry_result;
1482 ApkAssetsCookie attribute_cookie =
Ryan Mitchella55dc2e2019-01-24 10:58:23 -08001483 o.asset_manager_->FindEntry(make_resid(p, t, e), 0 /* density_override */ ,
1484 true /* stop_at_first_match */,
1485 true /* ignore_configuration */,
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001486 &attribute_entry_result);
1487
Ryan Mitchell93bca972019-03-08 17:26:28 -08001488 // Determine the package id of the attribute in the destination AssetManager.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001489 auto attribute_package_map = src_asset_cookie_id_map.find(attribute_cookie);
1490 if (attribute_package_map == src_asset_cookie_id_map.end()) {
1491 continue;
1492 }
1493 auto attribute_dest_package = attribute_package_map->second.find(
1494 attribute_dest_package_id);
1495 if (attribute_dest_package == attribute_package_map->second.end()) {
1496 continue;
1497 }
1498 attribute_dest_package_id = attribute_dest_package->second;
1499 }
1500
Ryan Mitchell93bca972019-03-08 17:26:28 -08001501 // Lazily instantiate the destination package.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001502 std::unique_ptr<Package>& dest_package = packages_[attribute_dest_package_id];
1503 if (dest_package == nullptr) {
1504 dest_package.reset(new Package());
1505 }
1506
Ryan Mitchell93bca972019-03-08 17:26:28 -08001507 // Lazily instantiate and resize the destination type.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001508 util::unique_cptr<ThemeType>& dest_type = dest_package->types[t];
1509 if (dest_type == nullptr || dest_type->entry_count < type->entry_count) {
1510 const size_t type_alloc_size = sizeof(ThemeType)
1511 + (type->entry_count * sizeof(ThemeEntry));
1512 void* dest_data = malloc(type_alloc_size);
1513 memset(dest_data, 0, type->entry_count * sizeof(ThemeEntry));
1514
Ryan Mitchell93bca972019-03-08 17:26:28 -08001515 // Copy the existing destination type values if the type is resized.
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001516 if (dest_type != nullptr) {
1517 memcpy(dest_data, type, sizeof(ThemeType)
1518 + (dest_type->entry_count * sizeof(ThemeEntry)));
1519 }
1520
1521 dest_type.reset(reinterpret_cast<ThemeType *>(dest_data));
1522 dest_type->entry_count = type->entry_count;
1523 }
1524
Ryan Mitchell93bca972019-03-08 17:26:28 -08001525 dest_type->entries[e].cookie = data_dest_cookie;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001526 dest_type->entries[e].value.dataType = entry.value.dataType;
Ryan Mitchell93bca972019-03-08 17:26:28 -08001527 dest_type->entries[e].value.data = attribute_data;
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001528 dest_type->entries[e].type_spec_flags = entry.type_spec_flags;
1529 }
1530 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001531 }
1532 }
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001533}
1534
1535void Theme::Dump() const {
1536 base::ScopedLogSeverity _log(base::INFO);
1537 LOG(INFO) << base::StringPrintf("Theme(this=%p, AssetManager2=%p)", this, asset_manager_);
1538
1539 for (int p = 0; p < packages_.size(); p++) {
1540 auto& package = packages_[p];
1541 if (package == nullptr) {
1542 continue;
1543 }
1544
1545 for (int t = 0; t < package->types.size(); t++) {
1546 auto& type = package->types[t];
1547 if (type == nullptr) {
1548 continue;
1549 }
1550
1551 for (int e = 0; e < type->entry_count; e++) {
1552 auto& entry = type->entries[e];
1553 if (entry.value.dataType == Res_value::TYPE_NULL &&
1554 entry.value.data != Res_value::DATA_NULL_EMPTY) {
1555 continue;
1556 }
1557
1558 LOG(INFO) << base::StringPrintf(" entry(0x%08x)=(0x%08x) type=(0x%02x), cookie(%d)",
1559 make_resid(p, t, e), entry.value.data,
1560 entry.value.dataType, entry.cookie);
1561 }
1562 }
1563 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001564}
1565
1566} // namespace android