blob: d74f27cca200ee0fb23edeee37c006d1dd38571a [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>
25#include <sstream>
Adam Lesinski0c405242017-01-13 20:47:26 -080026
Adam Lesinski7ad11102016-10-28 16:39:15 -070027#include "android-base/logging.h"
28#include "android-base/stringprintf.h"
29#include "utils/ByteOrder.h"
30#include "utils/Trace.h"
31
32#ifdef _WIN32
33#ifdef ERROR
34#undef ERROR
35#endif
36#endif
37
Ryan Mitchell2fe23472019-02-27 09:43:01 -080038#ifdef __ANDROID__
39#define ANDROID_LOG(x) LOG(x)
40#else
41#define ANDROID_LOG(x) std::stringstream()
42#endif
43
Adam Lesinski929d6512017-01-16 19:11:19 -080044#include "androidfw/ResourceUtils.h"
45
Adam Lesinski7ad11102016-10-28 16:39:15 -070046namespace android {
47
Adam Lesinskibebfcc42018-02-12 14:27:46 -080048struct FindEntryResult {
49 // A pointer to the resource table entry for this resource.
50 // If the size of the entry is > sizeof(ResTable_entry), it can be cast to
51 // a ResTable_map_entry and processed as a bag/map.
52 const ResTable_entry* entry;
53
54 // The configuration for which the resulting entry was defined. This is already swapped to host
55 // endianness.
56 ResTable_config config;
57
58 // The bitmask of configuration axis with which the resource value varies.
59 uint32_t type_flags;
60
61 // The dynamic package ID map for the package from which this resource came from.
62 const DynamicRefTable* dynamic_ref_table;
63
64 // The string pool reference to the type's name. This uses a different string pool than
65 // the global string pool, but this is hidden from the caller.
66 StringPoolRef type_string_ref;
67
68 // The string pool reference to the entry's name. This uses a different string pool than
69 // the global string pool, but this is hidden from the caller.
70 StringPoolRef entry_string_ref;
71};
72
Adam Lesinski970bd8d2017-09-25 13:21:55 -070073AssetManager2::AssetManager2() {
74 memset(&configuration_, 0, sizeof(configuration_));
75}
Adam Lesinski7ad11102016-10-28 16:39:15 -070076
77bool AssetManager2::SetApkAssets(const std::vector<const ApkAssets*>& apk_assets,
Mårten Kongstad668ec5b2018-06-11 14:11:33 +020078 bool invalidate_caches, bool filter_incompatible_configs) {
Adam Lesinski7ad11102016-10-28 16:39:15 -070079 apk_assets_ = apk_assets;
Adam Lesinskida431a22016-12-29 16:08:16 -050080 BuildDynamicRefTable();
Mårten Kongstad668ec5b2018-06-11 14:11:33 +020081 RebuildFilterList(filter_incompatible_configs);
Adam Lesinski7ad11102016-10-28 16:39:15 -070082 if (invalidate_caches) {
83 InvalidateCaches(static_cast<uint32_t>(-1));
84 }
85 return true;
86}
87
Adam Lesinskida431a22016-12-29 16:08:16 -050088void AssetManager2::BuildDynamicRefTable() {
89 package_groups_.clear();
90 package_ids_.fill(0xff);
91
92 // 0x01 is reserved for the android package.
93 int next_package_id = 0x02;
94 const size_t apk_assets_count = apk_assets_.size();
95 for (size_t i = 0; i < apk_assets_count; i++) {
Adam Lesinski970bd8d2017-09-25 13:21:55 -070096 const LoadedArsc* loaded_arsc = apk_assets_[i]->GetLoadedArsc();
97
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({});
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800112 DynamicRefTable& ref_table = package_groups_.back().dynamic_ref_table;
113 ref_table.mAssignedPackageId = package_id;
114 ref_table.mAppAsLib = package->IsDynamic() && package->GetPackageId() == 0x7f;
Adam Lesinskida431a22016-12-29 16:08:16 -0500115 }
116 PackageGroup* package_group = &package_groups_[idx];
117
118 // Add the package and to the set of packages with the same ID.
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800119 package_group->packages_.push_back(ConfiguredPackage{package.get(), {}});
Adam Lesinskida431a22016-12-29 16:08:16 -0500120 package_group->cookies_.push_back(static_cast<ApkAssetsCookie>(i));
121
122 // Add the package name -> build time ID mappings.
123 for (const DynamicPackageEntry& entry : package->GetDynamicPackageMap()) {
124 String16 package_name(entry.package_name.c_str(), entry.package_name.size());
125 package_group->dynamic_ref_table.mEntries.replaceValueFor(
126 package_name, static_cast<uint8_t>(entry.package_id));
127 }
128 }
129 }
130
131 // Now assign the runtime IDs so that we have a build-time to runtime ID map.
132 const auto package_groups_end = package_groups_.end();
133 for (auto iter = package_groups_.begin(); iter != package_groups_end; ++iter) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800134 const std::string& package_name = iter->packages_[0].loaded_package_->GetPackageName();
Adam Lesinskida431a22016-12-29 16:08:16 -0500135 for (auto iter2 = package_groups_.begin(); iter2 != package_groups_end; ++iter2) {
136 iter2->dynamic_ref_table.addMapping(String16(package_name.c_str(), package_name.size()),
137 iter->dynamic_ref_table.mAssignedPackageId);
138 }
139 }
140}
141
142void AssetManager2::DumpToLog() const {
143 base::ScopedLogSeverity _log(base::INFO);
144
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800145 LOG(INFO) << base::StringPrintf("AssetManager2(this=%p)", this);
146
Adam Lesinskida431a22016-12-29 16:08:16 -0500147 std::string list;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800148 for (const auto& apk_assets : apk_assets_) {
149 base::StringAppendF(&list, "%s,", apk_assets->GetPath().c_str());
150 }
151 LOG(INFO) << "ApkAssets: " << list;
152
153 list = "";
Adam Lesinskida431a22016-12-29 16:08:16 -0500154 for (size_t i = 0; i < package_ids_.size(); i++) {
155 if (package_ids_[i] != 0xff) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800156 base::StringAppendF(&list, "%02x -> %d, ", (int)i, package_ids_[i]);
Adam Lesinskida431a22016-12-29 16:08:16 -0500157 }
158 }
159 LOG(INFO) << "Package ID map: " << list;
160
Adam Lesinski0dd36992018-01-25 15:38:38 -0800161 for (const auto& package_group: package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800162 list = "";
163 for (const auto& package : package_group.packages_) {
164 const LoadedPackage* loaded_package = package.loaded_package_;
165 base::StringAppendF(&list, "%s(%02x%s), ", loaded_package->GetPackageName().c_str(),
166 loaded_package->GetPackageId(),
167 (loaded_package->IsDynamic() ? " dynamic" : ""));
168 }
169 LOG(INFO) << base::StringPrintf("PG (%02x): ",
170 package_group.dynamic_ref_table.mAssignedPackageId)
171 << list;
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800172
173 for (size_t i = 0; i < 256; i++) {
174 if (package_group.dynamic_ref_table.mLookupTable[i] != 0) {
175 LOG(INFO) << base::StringPrintf(" e[0x%02x] -> 0x%02x", (uint8_t) i,
176 package_group.dynamic_ref_table.mLookupTable[i]);
177 }
178 }
Adam Lesinskida431a22016-12-29 16:08:16 -0500179 }
180}
Adam Lesinski7ad11102016-10-28 16:39:15 -0700181
182const ResStringPool* AssetManager2::GetStringPoolForCookie(ApkAssetsCookie cookie) const {
183 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
184 return nullptr;
185 }
186 return apk_assets_[cookie]->GetLoadedArsc()->GetStringPool();
187}
188
Adam Lesinskida431a22016-12-29 16:08:16 -0500189const DynamicRefTable* AssetManager2::GetDynamicRefTableForPackage(uint32_t package_id) const {
190 if (package_id >= package_ids_.size()) {
191 return nullptr;
192 }
193
194 const size_t idx = package_ids_[package_id];
195 if (idx == 0xff) {
196 return nullptr;
197 }
198 return &package_groups_[idx].dynamic_ref_table;
199}
200
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800201const DynamicRefTable* AssetManager2::GetDynamicRefTableForCookie(ApkAssetsCookie cookie) const {
202 for (const PackageGroup& package_group : package_groups_) {
203 for (const ApkAssetsCookie& package_cookie : package_group.cookies_) {
204 if (package_cookie == cookie) {
205 return &package_group.dynamic_ref_table;
206 }
207 }
208 }
209 return nullptr;
210}
211
Mårten Kongstadc92c4dd2019-02-05 01:29:59 +0100212const std::unordered_map<std::string, std::string>*
213 AssetManager2::GetOverlayableMapForPackage(uint32_t package_id) const {
214
215 if (package_id >= package_ids_.size()) {
216 return nullptr;
217 }
218
219 const size_t idx = package_ids_[package_id];
220 if (idx == 0xff) {
221 return nullptr;
222 }
223
224 const PackageGroup& package_group = package_groups_[idx];
225 if (package_group.packages_.size() == 0) {
226 return nullptr;
227 }
228
229 const auto loaded_package = package_group.packages_[0].loaded_package_;
230 return &loaded_package->GetOverlayableMap();
231}
232
Adam Lesinski7ad11102016-10-28 16:39:15 -0700233void AssetManager2::SetConfiguration(const ResTable_config& configuration) {
234 const int diff = configuration_.diff(configuration);
235 configuration_ = configuration;
236
237 if (diff) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800238 RebuildFilterList();
Adam Lesinski7ad11102016-10-28 16:39:15 -0700239 InvalidateCaches(static_cast<uint32_t>(diff));
240 }
241}
242
Adam Lesinski0c405242017-01-13 20:47:26 -0800243std::set<ResTable_config> AssetManager2::GetResourceConfigurations(bool exclude_system,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800244 bool exclude_mipmap) const {
245 ATRACE_NAME("AssetManager::GetResourceConfigurations");
Adam Lesinski0c405242017-01-13 20:47:26 -0800246 std::set<ResTable_config> configurations;
247 for (const PackageGroup& package_group : package_groups_) {
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800248 bool found_system_package = false;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800249 for (const ConfiguredPackage& package : package_group.packages_) {
250 if (exclude_system && package.loaded_package_->IsSystem()) {
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800251 found_system_package = true;
Adam Lesinski0c405242017-01-13 20:47:26 -0800252 continue;
253 }
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800254
255 if (exclude_system && package.loaded_package_->IsOverlay() && found_system_package) {
256 // Overlays must appear after the target package to take effect. Any overlay found in the
257 // same package as a system package is able to overlay system resources.
258 continue;
259 }
260
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800261 package.loaded_package_->CollectConfigurations(exclude_mipmap, &configurations);
Adam Lesinski0c405242017-01-13 20:47:26 -0800262 }
263 }
264 return configurations;
265}
266
267std::set<std::string> AssetManager2::GetResourceLocales(bool exclude_system,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800268 bool merge_equivalent_languages) const {
269 ATRACE_NAME("AssetManager::GetResourceLocales");
Adam Lesinski0c405242017-01-13 20:47:26 -0800270 std::set<std::string> locales;
271 for (const PackageGroup& package_group : package_groups_) {
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800272 bool found_system_package = false;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800273 for (const ConfiguredPackage& package : package_group.packages_) {
274 if (exclude_system && package.loaded_package_->IsSystem()) {
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800275 found_system_package = true;
Adam Lesinski0c405242017-01-13 20:47:26 -0800276 continue;
277 }
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800278
279 if (exclude_system && package.loaded_package_->IsOverlay() && found_system_package) {
280 // Overlays must appear after the target package to take effect. Any overlay found in the
281 // same package as a system package is able to overlay system resources.
282 continue;
283 }
284
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800285 package.loaded_package_->CollectLocales(merge_equivalent_languages, &locales);
Adam Lesinski0c405242017-01-13 20:47:26 -0800286 }
287 }
288 return locales;
289}
290
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800291std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename,
292 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700293 const std::string new_path = "assets/" + filename;
294 return OpenNonAsset(new_path, mode);
295}
296
297std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename, ApkAssetsCookie cookie,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800298 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700299 const std::string new_path = "assets/" + filename;
300 return OpenNonAsset(new_path, cookie, mode);
301}
302
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800303std::unique_ptr<AssetDir> AssetManager2::OpenDir(const std::string& dirname) const {
304 ATRACE_NAME("AssetManager::OpenDir");
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800305
306 std::string full_path = "assets/" + dirname;
307 std::unique_ptr<SortedVector<AssetDir::FileInfo>> files =
308 util::make_unique<SortedVector<AssetDir::FileInfo>>();
309
310 // Start from the back.
311 for (auto iter = apk_assets_.rbegin(); iter != apk_assets_.rend(); ++iter) {
312 const ApkAssets* apk_assets = *iter;
313
314 auto func = [&](const StringPiece& name, FileType type) {
315 AssetDir::FileInfo info;
316 info.setFileName(String8(name.data(), name.size()));
317 info.setFileType(type);
318 info.setSourceName(String8(apk_assets->GetPath().c_str()));
319 files->add(info);
320 };
321
322 if (!apk_assets->ForEachFile(full_path, func)) {
323 return {};
324 }
325 }
326
327 std::unique_ptr<AssetDir> asset_dir = util::make_unique<AssetDir>();
328 asset_dir->setFileList(files.release());
329 return asset_dir;
330}
331
Adam Lesinski7ad11102016-10-28 16:39:15 -0700332// Search in reverse because that's how we used to do it and we need to preserve behaviour.
333// This is unfortunate, because ClassLoaders delegate to the parent first, so the order
334// is inconsistent for split APKs.
335std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
336 Asset::AccessMode mode,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800337 ApkAssetsCookie* out_cookie) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700338 for (int32_t i = apk_assets_.size() - 1; i >= 0; i--) {
339 std::unique_ptr<Asset> asset = apk_assets_[i]->Open(filename, mode);
340 if (asset) {
341 if (out_cookie != nullptr) {
342 *out_cookie = i;
343 }
344 return asset;
345 }
346 }
347
348 if (out_cookie != nullptr) {
349 *out_cookie = kInvalidCookie;
350 }
351 return {};
352}
353
354std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800355 ApkAssetsCookie cookie,
356 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700357 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
358 return {};
359 }
360 return apk_assets_[cookie]->Open(filename, mode);
361}
362
363ApkAssetsCookie AssetManager2::FindEntry(uint32_t resid, uint16_t density_override,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800364 bool /*stop_at_first_match*/,
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800365 bool ignore_configuration,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800366 FindEntryResult* out_entry) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700367 // Might use this if density_override != 0.
368 ResTable_config density_override_config;
369
370 // Select our configuration or generate a density override configuration.
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800371 const ResTable_config* desired_config = &configuration_;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700372 if (density_override != 0 && density_override != configuration_.density) {
373 density_override_config = configuration_;
374 density_override_config.density = density_override;
375 desired_config = &density_override_config;
376 }
377
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800378 if (!is_valid_resid(resid)) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500379 LOG(ERROR) << base::StringPrintf("Invalid ID 0x%08x.", resid);
380 return kInvalidCookie;
381 }
382
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800383 const uint32_t package_id = get_package_id(resid);
384 const uint8_t type_idx = get_type_id(resid) - 1;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800385 const uint16_t entry_idx = get_entry_id(resid);
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800386
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800387 const uint8_t package_idx = package_ids_[package_id];
388 if (package_idx == 0xff) {
Ryan Mitchell2fe23472019-02-27 09:43:01 -0800389 ANDROID_LOG(ERROR) << base::StringPrintf("No package ID %02x found for ID 0x%08x.",
390 package_id, resid);
Adam Lesinskida431a22016-12-29 16:08:16 -0500391 return kInvalidCookie;
392 }
393
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800394 const PackageGroup& package_group = package_groups_[package_idx];
Adam Lesinskib8b3a262018-02-09 11:01:45 -0800395 const size_t package_count = package_group.packages_.size();
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800396
397 ApkAssetsCookie best_cookie = kInvalidCookie;
398 const LoadedPackage* best_package = nullptr;
399 const ResTable_type* best_type = nullptr;
400 const ResTable_config* best_config = nullptr;
401 ResTable_config best_config_copy;
402 uint32_t best_offset = 0u;
403 uint32_t type_flags = 0u;
404
Winson2f3669b2019-01-11 11:28:34 -0800405 Resolution::Step::Type resolution_type;
406 std::vector<Resolution::Step> resolution_steps;
407
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800408 // If desired_config is the same as the set configuration, then we can use our filtered list
409 // and we don't need to match the configurations, since they already matched.
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800410 const bool use_fast_path = !ignore_configuration && desired_config == &configuration_;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800411
412 for (size_t pi = 0; pi < package_count; pi++) {
413 const ConfiguredPackage& loaded_package_impl = package_group.packages_[pi];
414 const LoadedPackage* loaded_package = loaded_package_impl.loaded_package_;
415 ApkAssetsCookie cookie = package_group.cookies_[pi];
416
417 // If the type IDs are offset in this package, we need to take that into account when searching
418 // for a type.
419 const TypeSpec* type_spec = loaded_package->GetTypeSpecByTypeIndex(type_idx);
420 if (UNLIKELY(type_spec == nullptr)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700421 continue;
422 }
423
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800424 uint16_t local_entry_idx = entry_idx;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700425
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800426 // If there is an IDMAP supplied with this package, translate the entry ID.
427 if (type_spec->idmap_entries != nullptr) {
428 if (!LoadedIdmap::Lookup(type_spec->idmap_entries, local_entry_idx, &local_entry_idx)) {
429 // There is no mapping, so the resource is not meant to be in this overlay package.
430 continue;
431 }
432 }
433
434 type_flags |= type_spec->GetFlagsForEntryIndex(local_entry_idx);
435
436 // If the package is an overlay, then even configurations that are the same MUST be chosen.
437 const bool package_is_overlay = loaded_package->IsOverlay();
438
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800439 if (use_fast_path) {
Winson2f3669b2019-01-11 11:28:34 -0800440 const FilteredConfigGroup& filtered_group = loaded_package_impl.filtered_configs_[type_idx];
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800441 const std::vector<ResTable_config>& candidate_configs = filtered_group.configurations;
442 const size_t type_count = candidate_configs.size();
443 for (uint32_t i = 0; i < type_count; i++) {
444 const ResTable_config& this_config = candidate_configs[i];
445
446 // We can skip calling ResTable_config::match() because we know that all candidate
447 // configurations that do NOT match have been filtered-out.
Winson2f3669b2019-01-11 11:28:34 -0800448 if (best_config == nullptr) {
449 resolution_type = Resolution::Step::Type::INITIAL;
450 } else if (this_config.isBetterThan(*best_config, desired_config)) {
451 resolution_type = Resolution::Step::Type::BETTER_MATCH;
452 } else if (package_is_overlay && this_config.compare(*best_config) == 0) {
453 resolution_type = Resolution::Step::Type::OVERLAID;
454 } else {
455 continue;
456 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800457
Winson2f3669b2019-01-11 11:28:34 -0800458 // The configuration matches and is better than the previous selection.
459 // Find the entry value if it exists for this configuration.
460 const ResTable_type* type = filtered_group.types[i];
461 const uint32_t offset = LoadedPackage::GetEntryOffset(type, local_entry_idx);
462 if (offset == ResTable_type::NO_ENTRY) {
463 continue;
464 }
465
466 best_cookie = cookie;
467 best_package = loaded_package;
468 best_type = type;
469 best_config = &this_config;
470 best_offset = offset;
471
472 if (resource_resolution_logging_enabled_) {
473 resolution_steps.push_back(Resolution::Step{resolution_type,
474 this_config.toString(),
475 &loaded_package->GetPackageName()});
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800476 }
477 }
478 } else {
479 // This is the slower path, which doesn't use the filtered list of configurations.
480 // Here we must read the ResTable_config from the mmapped APK, convert it to host endianness
481 // and fill in any new fields that did not exist when the APK was compiled.
482 // Furthermore when selecting configurations we can't just record the pointer to the
483 // ResTable_config, we must copy it.
484 const auto iter_end = type_spec->types + type_spec->type_count;
485 for (auto iter = type_spec->types; iter != iter_end; ++iter) {
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800486 ResTable_config this_config{};
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800487
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800488 if (!ignore_configuration) {
489 this_config.copyFromDtoH((*iter)->config);
490 if (!this_config.match(*desired_config)) {
491 continue;
492 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800493
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800494 if (best_config == nullptr) {
495 resolution_type = Resolution::Step::Type::INITIAL;
496 } else if (this_config.isBetterThan(*best_config, desired_config)) {
497 resolution_type = Resolution::Step::Type::BETTER_MATCH;
498 } else if (package_is_overlay && this_config.compare(*best_config) == 0) {
499 resolution_type = Resolution::Step::Type::OVERLAID;
500 } else {
501 continue;
502 }
Winson2f3669b2019-01-11 11:28:34 -0800503 }
504
505 // The configuration matches and is better than the previous selection.
506 // Find the entry value if it exists for this configuration.
507 const uint32_t offset = LoadedPackage::GetEntryOffset(*iter, local_entry_idx);
508 if (offset == ResTable_type::NO_ENTRY) {
509 continue;
510 }
511
512 best_cookie = cookie;
513 best_package = loaded_package;
514 best_type = *iter;
515 best_config_copy = this_config;
516 best_config = &best_config_copy;
517 best_offset = offset;
518
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800519 if (ignore_configuration) {
520 // Any configuration will suffice, so break.
521 break;
522 }
523
Winson2f3669b2019-01-11 11:28:34 -0800524 if (resource_resolution_logging_enabled_) {
525 resolution_steps.push_back(Resolution::Step{resolution_type,
526 this_config.toString(),
527 &loaded_package->GetPackageName()});
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800528 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700529 }
530 }
531 }
532
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800533 if (UNLIKELY(best_cookie == kInvalidCookie)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700534 return kInvalidCookie;
535 }
536
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800537 const ResTable_entry* best_entry = LoadedPackage::GetEntryFromOffset(best_type, best_offset);
538 if (UNLIKELY(best_entry == nullptr)) {
539 return kInvalidCookie;
540 }
541
542 out_entry->entry = best_entry;
543 out_entry->config = *best_config;
544 out_entry->type_flags = type_flags;
545 out_entry->type_string_ref = StringPoolRef(best_package->GetTypeStringPool(), best_type->id - 1);
546 out_entry->entry_string_ref =
547 StringPoolRef(best_package->GetKeyStringPool(), best_entry->key.index);
Adam Lesinskida431a22016-12-29 16:08:16 -0500548 out_entry->dynamic_ref_table = &package_group.dynamic_ref_table;
Winson2f3669b2019-01-11 11:28:34 -0800549
550 if (resource_resolution_logging_enabled_) {
551 last_resolution.resid = resid;
552 last_resolution.cookie = best_cookie;
553 last_resolution.steps = resolution_steps;
554
555 // Cache only the type/entry refs since that's all that's needed to build name
556 last_resolution.type_string_ref =
557 StringPoolRef(best_package->GetTypeStringPool(), best_type->id - 1);
558 last_resolution.entry_string_ref =
559 StringPoolRef(best_package->GetKeyStringPool(), best_entry->key.index);
560 }
561
Adam Lesinskida431a22016-12-29 16:08:16 -0500562 return best_cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700563}
564
Winson2f3669b2019-01-11 11:28:34 -0800565void AssetManager2::SetResourceResolutionLoggingEnabled(bool enabled) {
566 resource_resolution_logging_enabled_ = enabled;
567
568 if (!enabled) {
569 last_resolution.cookie = kInvalidCookie;
570 last_resolution.resid = 0;
571 last_resolution.steps.clear();
572 last_resolution.type_string_ref = StringPoolRef();
573 last_resolution.entry_string_ref = StringPoolRef();
574 }
575}
576
577std::string AssetManager2::GetLastResourceResolution() const {
578 if (!resource_resolution_logging_enabled_) {
579 LOG(ERROR) << "Must enable resource resolution logging before getting path.";
580 return std::string();
581 }
582
583 auto cookie = last_resolution.cookie;
584 if (cookie == kInvalidCookie) {
585 LOG(ERROR) << "AssetManager hasn't resolved a resource to read resolution path.";
586 return std::string();
587 }
588
589 uint32_t resid = last_resolution.resid;
590 std::vector<Resolution::Step>& steps = last_resolution.steps;
591
592 ResourceName resource_name;
593 std::string resource_name_string;
594
595 const LoadedPackage* package =
596 apk_assets_[cookie]->GetLoadedArsc()->GetPackageById(get_package_id(resid));
597
598 if (package != nullptr) {
599 ToResourceName(last_resolution.type_string_ref,
600 last_resolution.entry_string_ref,
Ryan Mitchell741e96f2019-01-23 16:56:51 -0800601 package->GetPackageName(),
Winson2f3669b2019-01-11 11:28:34 -0800602 &resource_name);
603 resource_name_string = ToFormattedResourceString(&resource_name);
604 }
605
606 std::stringstream log_stream;
607 log_stream << base::StringPrintf("Resolution for 0x%08x ", resid)
608 << resource_name_string
609 << "\n\tFor config -"
610 << configuration_.toString();
611
612 std::string prefix;
613 for (Resolution::Step step : steps) {
614 switch (step.type) {
615 case Resolution::Step::Type::INITIAL:
616 prefix = "Found initial";
617 break;
618 case Resolution::Step::Type::BETTER_MATCH:
619 prefix = "Found better";
620 break;
621 case Resolution::Step::Type::OVERLAID:
622 prefix = "Overlaid";
623 break;
624 }
625
626 if (!prefix.empty()) {
627 log_stream << "\n\t" << prefix << ": " << *step.package_name;
628
629 if (!step.config_name.isEmpty()) {
630 log_stream << " -" << step.config_name;
631 }
632 }
633 }
634
635 return log_stream.str();
636}
637
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800638bool AssetManager2::GetResourceName(uint32_t resid, ResourceName* out_name) const {
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700639 FindEntryResult entry;
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800640 ApkAssetsCookie cookie = FindEntry(resid, 0u /* density_override */,
641 true /* stop_at_first_match */,
642 true /* ignore_configuration */, &entry);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700643 if (cookie == kInvalidCookie) {
644 return false;
645 }
646
Ryan Mitchell741e96f2019-01-23 16:56:51 -0800647 const uint8_t package_idx = package_ids_[get_package_id(resid)];
648 if (package_idx == 0xff) {
649 LOG(ERROR) << base::StringPrintf("No package ID %02x found for ID 0x%08x.",
650 get_package_id(resid), resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700651 return false;
652 }
653
Ryan Mitchell741e96f2019-01-23 16:56:51 -0800654 const PackageGroup& package_group = package_groups_[package_idx];
655 auto cookie_iter = std::find(package_group.cookies_.begin(),
656 package_group.cookies_.end(), cookie);
657 if (cookie_iter == package_group.cookies_.end()) {
658 return false;
659 }
660
661 long package_pos = std::distance(package_group.cookies_.begin(), cookie_iter);
662 const LoadedPackage* package = package_group.packages_[package_pos].loaded_package_;
Winson2f3669b2019-01-11 11:28:34 -0800663 return ToResourceName(entry.type_string_ref,
664 entry.entry_string_ref,
Ryan Mitchell741e96f2019-01-23 16:56:51 -0800665 package->GetPackageName(),
Winson2f3669b2019-01-11 11:28:34 -0800666 out_name);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700667}
668
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800669bool AssetManager2::GetResourceFlags(uint32_t resid, uint32_t* out_flags) const {
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700670 FindEntryResult entry;
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800671 ApkAssetsCookie cookie = FindEntry(resid, 0u /* density_override */,
672 false /* stop_at_first_match */,
673 true /* ignore_configuration */, &entry);
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700674 if (cookie != kInvalidCookie) {
675 *out_flags = entry.type_flags;
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800676 return true;
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700677 }
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800678 return false;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700679}
680
681ApkAssetsCookie AssetManager2::GetResource(uint32_t resid, bool may_be_bag,
682 uint16_t density_override, Res_value* out_value,
683 ResTable_config* out_selected_config,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800684 uint32_t* out_flags) const {
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700685 FindEntryResult entry;
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800686 ApkAssetsCookie cookie = FindEntry(resid, density_override, false /* stop_at_first_match */,
687 false /* ignore_configuration */, &entry);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700688 if (cookie == kInvalidCookie) {
689 return kInvalidCookie;
690 }
691
Adam Lesinski498f6052017-11-29 13:24:29 -0800692 if (dtohs(entry.entry->flags) & ResTable_entry::FLAG_COMPLEX) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700693 if (!may_be_bag) {
694 LOG(ERROR) << base::StringPrintf("Resource %08x is a complex map type.", resid);
Adam Lesinski0c405242017-01-13 20:47:26 -0800695 return kInvalidCookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700696 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800697
698 // Create a reference since we can't represent this complex type as a Res_value.
699 out_value->dataType = Res_value::TYPE_REFERENCE;
700 out_value->data = resid;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800701 *out_selected_config = entry.config;
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700702 *out_flags = entry.type_flags;
Adam Lesinski0c405242017-01-13 20:47:26 -0800703 return cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700704 }
705
706 const Res_value* device_value = reinterpret_cast<const Res_value*>(
707 reinterpret_cast<const uint8_t*>(entry.entry) + dtohs(entry.entry->size));
708 out_value->copyFrom_dtoh(*device_value);
Adam Lesinskida431a22016-12-29 16:08:16 -0500709
710 // Convert the package ID to the runtime assigned package ID.
711 entry.dynamic_ref_table->lookupResourceValue(out_value);
712
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800713 *out_selected_config = entry.config;
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700714 *out_flags = entry.type_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700715 return cookie;
716}
717
Adam Lesinski0c405242017-01-13 20:47:26 -0800718ApkAssetsCookie AssetManager2::ResolveReference(ApkAssetsCookie cookie, Res_value* in_out_value,
719 ResTable_config* in_out_selected_config,
720 uint32_t* in_out_flags,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800721 uint32_t* out_last_reference) const {
Adam Lesinski0c405242017-01-13 20:47:26 -0800722 constexpr const int kMaxIterations = 20;
723
Adam Lesinski0c405242017-01-13 20:47:26 -0800724 for (size_t iteration = 0u; in_out_value->dataType == Res_value::TYPE_REFERENCE &&
725 in_out_value->data != 0u && iteration < kMaxIterations;
726 iteration++) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800727 *out_last_reference = in_out_value->data;
Adam Lesinski0c405242017-01-13 20:47:26 -0800728 uint32_t new_flags = 0u;
729 cookie = GetResource(in_out_value->data, true /*may_be_bag*/, 0u /*density_override*/,
730 in_out_value, in_out_selected_config, &new_flags);
731 if (cookie == kInvalidCookie) {
732 return kInvalidCookie;
733 }
734 if (in_out_flags != nullptr) {
735 *in_out_flags |= new_flags;
736 }
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800737 if (*out_last_reference == in_out_value->data) {
Adam Lesinski0c405242017-01-13 20:47:26 -0800738 // This reference can't be resolved, so exit now and let the caller deal with it.
739 return cookie;
740 }
741 }
742 return cookie;
743}
744
Aurimas Liutikas8f004c82019-01-17 17:20:10 -0800745const std::vector<uint32_t> AssetManager2::GetBagResIdStack(uint32_t resid) {
746 auto cached_iter = cached_bag_resid_stacks_.find(resid);
747 if (cached_iter != cached_bag_resid_stacks_.end()) {
748 return cached_iter->second;
749 } else {
750 auto found_resids = std::vector<uint32_t>();
751 GetBag(resid, found_resids);
752 // Cache style stacks if they are not already cached.
753 cached_bag_resid_stacks_[resid] = found_resids;
754 return found_resids;
755 }
756}
757
Adam Lesinski7ad11102016-10-28 16:39:15 -0700758const ResolvedBag* AssetManager2::GetBag(uint32_t resid) {
y57cd1952018-04-12 14:26:23 -0700759 auto found_resids = std::vector<uint32_t>();
Aurimas Liutikas8f004c82019-01-17 17:20:10 -0800760 auto bag = GetBag(resid, found_resids);
761
762 // Cache style stacks if they are not already cached.
763 auto cached_iter = cached_bag_resid_stacks_.find(resid);
764 if (cached_iter == cached_bag_resid_stacks_.end()) {
765 cached_bag_resid_stacks_[resid] = found_resids;
766 }
767 return bag;
y57cd1952018-04-12 14:26:23 -0700768}
769
770const ResolvedBag* AssetManager2::GetBag(uint32_t resid, std::vector<uint32_t>& child_resids) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800771 ATRACE_NAME("AssetManager::GetBag");
Adam Lesinski7ad11102016-10-28 16:39:15 -0700772
773 auto cached_iter = cached_bags_.find(resid);
774 if (cached_iter != cached_bags_.end()) {
775 return cached_iter->second.get();
776 }
777
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700778 FindEntryResult entry;
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800779 ApkAssetsCookie cookie = FindEntry(resid, 0u /* density_override */,
780 false /* stop_at_first_match */,
781 false /* ignore_configuration */,
782 &entry);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700783 if (cookie == kInvalidCookie) {
784 return nullptr;
785 }
786
787 // Check that the size of the entry header is at least as big as
788 // the desired ResTable_map_entry. Also verify that the entry
789 // was intended to be a map.
790 if (dtohs(entry.entry->size) < sizeof(ResTable_map_entry) ||
791 (dtohs(entry.entry->flags) & ResTable_entry::FLAG_COMPLEX) == 0) {
792 // Not a bag, nothing to do.
793 return nullptr;
794 }
795
796 const ResTable_map_entry* map = reinterpret_cast<const ResTable_map_entry*>(entry.entry);
797 const ResTable_map* map_entry =
798 reinterpret_cast<const ResTable_map*>(reinterpret_cast<const uint8_t*>(map) + map->size);
799 const ResTable_map* const map_entry_end = map_entry + dtohl(map->count);
800
y57cd1952018-04-12 14:26:23 -0700801 // Keep track of ids that have already been seen to prevent infinite loops caused by circular
802 // dependencies between bags
803 child_resids.push_back(resid);
804
Adam Lesinskida431a22016-12-29 16:08:16 -0500805 uint32_t parent_resid = dtohl(map->parent.ident);
y57cd1952018-04-12 14:26:23 -0700806 if (parent_resid == 0 || std::find(child_resids.begin(), child_resids.end(), parent_resid)
807 != child_resids.end()) {
808 // There is no parent or that a circular dependency exist, meaning there is nothing to
809 // inherit and we can do a simple copy of the entries in the map.
Adam Lesinski7ad11102016-10-28 16:39:15 -0700810 const size_t entry_count = map_entry_end - map_entry;
811 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
812 malloc(sizeof(ResolvedBag) + (entry_count * sizeof(ResolvedBag::Entry))))};
813 ResolvedBag::Entry* new_entry = new_bag->entries;
814 for (; map_entry != map_entry_end; ++map_entry) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500815 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -0800816 if (!is_internal_resid(new_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500817 // Attributes, arrays, etc don't have a resource id as the name. They specify
818 // other data, which would be wrong to change via a lookup.
819 if (entry.dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800820 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
821 resid);
Adam Lesinskida431a22016-12-29 16:08:16 -0500822 return nullptr;
823 }
824 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700825 new_entry->cookie = cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -0500826 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700827 new_entry->key_pool = nullptr;
828 new_entry->type_pool = nullptr;
Aurimas Liutikasd42a6702018-11-15 15:48:28 -0800829 new_entry->style = resid;
Adam Lesinski30080e22017-10-16 16:18:09 -0700830 new_entry->value.copyFrom_dtoh(map_entry->value);
831 status_t err = entry.dynamic_ref_table->lookupResourceValue(&new_entry->value);
832 if (err != NO_ERROR) {
833 LOG(ERROR) << base::StringPrintf(
834 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
835 new_entry->value.data, new_key);
836 return nullptr;
837 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700838 ++new_entry;
839 }
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700840 new_bag->type_spec_flags = entry.type_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700841 new_bag->entry_count = static_cast<uint32_t>(entry_count);
842 ResolvedBag* result = new_bag.get();
843 cached_bags_[resid] = std::move(new_bag);
844 return result;
845 }
846
Adam Lesinskida431a22016-12-29 16:08:16 -0500847 // In case the parent is a dynamic reference, resolve it.
848 entry.dynamic_ref_table->lookupResourceId(&parent_resid);
849
Adam Lesinski7ad11102016-10-28 16:39:15 -0700850 // Get the parent and do a merge of the keys.
y57cd1952018-04-12 14:26:23 -0700851 const ResolvedBag* parent_bag = GetBag(parent_resid, child_resids);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700852 if (parent_bag == nullptr) {
853 // Failed to get the parent that should exist.
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800854 LOG(ERROR) << base::StringPrintf("Failed to find parent 0x%08x of bag 0x%08x.", parent_resid,
855 resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700856 return nullptr;
857 }
858
Adam Lesinski7ad11102016-10-28 16:39:15 -0700859 // Create the max possible entries we can make. Once we construct the bag,
860 // we will realloc to fit to size.
861 const size_t max_count = parent_bag->entry_count + dtohl(map->count);
George Burgess IV09b119f2017-07-25 15:00:04 -0700862 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
863 malloc(sizeof(ResolvedBag) + (max_count * sizeof(ResolvedBag::Entry))))};
Adam Lesinski7ad11102016-10-28 16:39:15 -0700864 ResolvedBag::Entry* new_entry = new_bag->entries;
865
866 const ResolvedBag::Entry* parent_entry = parent_bag->entries;
867 const ResolvedBag::Entry* const parent_entry_end = parent_entry + parent_bag->entry_count;
868
869 // The keys are expected to be in sorted order. Merge the two bags.
870 while (map_entry != map_entry_end && parent_entry != parent_entry_end) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500871 uint32_t child_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -0800872 if (!is_internal_resid(child_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500873 if (entry.dynamic_ref_table->lookupResourceId(&child_key) != NO_ERROR) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800874 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", child_key,
875 resid);
Adam Lesinskida431a22016-12-29 16:08:16 -0500876 return nullptr;
877 }
878 }
879
Adam Lesinski7ad11102016-10-28 16:39:15 -0700880 if (child_key <= parent_entry->key) {
881 // Use the child key if it comes before the parent
882 // or is equal to the parent (overrides).
883 new_entry->cookie = cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700884 new_entry->key = child_key;
885 new_entry->key_pool = nullptr;
886 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -0700887 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -0800888 new_entry->style = resid;
Adam Lesinski30080e22017-10-16 16:18:09 -0700889 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, child_key);
894 return nullptr;
895 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700896 ++map_entry;
897 } else {
898 // Take the parent entry as-is.
899 memcpy(new_entry, parent_entry, sizeof(*new_entry));
900 }
901
902 if (child_key >= parent_entry->key) {
903 // Move to the next parent entry if we used it or it was overridden.
904 ++parent_entry;
905 }
906 // Increment to the next entry to fill.
907 ++new_entry;
908 }
909
910 // Finish the child entries if they exist.
911 while (map_entry != map_entry_end) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500912 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -0800913 if (!is_internal_resid(new_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500914 if (entry.dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800915 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
916 resid);
Adam Lesinskida431a22016-12-29 16:08:16 -0500917 return nullptr;
918 }
919 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700920 new_entry->cookie = cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -0500921 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700922 new_entry->key_pool = nullptr;
923 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -0700924 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -0800925 new_entry->style = resid;
Adam Lesinski30080e22017-10-16 16:18:09 -0700926 status_t err = entry.dynamic_ref_table->lookupResourceValue(&new_entry->value);
927 if (err != NO_ERROR) {
928 LOG(ERROR) << base::StringPrintf("Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.",
929 new_entry->value.dataType, new_entry->value.data, new_key);
930 return nullptr;
931 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700932 ++map_entry;
933 ++new_entry;
934 }
935
936 // Finish the parent entries if they exist.
937 if (parent_entry != parent_entry_end) {
938 // Take the rest of the parent entries as-is.
939 const size_t num_entries_to_copy = parent_entry_end - parent_entry;
940 memcpy(new_entry, parent_entry, num_entries_to_copy * sizeof(*new_entry));
941 new_entry += num_entries_to_copy;
942 }
943
944 // Resize the resulting array to fit.
945 const size_t actual_count = new_entry - new_bag->entries;
946 if (actual_count != max_count) {
George Burgess IV09b119f2017-07-25 15:00:04 -0700947 new_bag.reset(reinterpret_cast<ResolvedBag*>(realloc(
948 new_bag.release(), sizeof(ResolvedBag) + (actual_count * sizeof(ResolvedBag::Entry)))));
Adam Lesinski7ad11102016-10-28 16:39:15 -0700949 }
950
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700951 // Combine flags from the parent and our own bag.
952 new_bag->type_spec_flags = entry.type_flags | parent_bag->type_spec_flags;
George Burgess IV09b119f2017-07-25 15:00:04 -0700953 new_bag->entry_count = static_cast<uint32_t>(actual_count);
954 ResolvedBag* result = new_bag.get();
955 cached_bags_[resid] = std::move(new_bag);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700956 return result;
957}
958
Adam Lesinski929d6512017-01-16 19:11:19 -0800959static bool Utf8ToUtf16(const StringPiece& str, std::u16string* out) {
960 ssize_t len =
961 utf8_to_utf16_length(reinterpret_cast<const uint8_t*>(str.data()), str.size(), false);
962 if (len < 0) {
963 return false;
964 }
965 out->resize(static_cast<size_t>(len));
966 utf8_to_utf16(reinterpret_cast<const uint8_t*>(str.data()), str.size(), &*out->begin(),
967 static_cast<size_t>(len + 1));
968 return true;
969}
970
Adam Lesinski0c405242017-01-13 20:47:26 -0800971uint32_t AssetManager2::GetResourceId(const std::string& resource_name,
972 const std::string& fallback_type,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800973 const std::string& fallback_package) const {
Adam Lesinski929d6512017-01-16 19:11:19 -0800974 StringPiece package_name, type, entry;
975 if (!ExtractResourceName(resource_name, &package_name, &type, &entry)) {
976 return 0u;
977 }
978
979 if (entry.empty()) {
980 return 0u;
981 }
982
983 if (package_name.empty()) {
984 package_name = fallback_package;
985 }
986
987 if (type.empty()) {
988 type = fallback_type;
989 }
990
991 std::u16string type16;
992 if (!Utf8ToUtf16(type, &type16)) {
993 return 0u;
994 }
995
996 std::u16string entry16;
997 if (!Utf8ToUtf16(entry, &entry16)) {
998 return 0u;
999 }
1000
1001 const StringPiece16 kAttr16 = u"attr";
1002 const static std::u16string kAttrPrivate16 = u"^attr-private";
1003
1004 for (const PackageGroup& package_group : package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001005 for (const ConfiguredPackage& package_impl : package_group.packages_) {
1006 const LoadedPackage* package = package_impl.loaded_package_;
Adam Lesinski929d6512017-01-16 19:11:19 -08001007 if (package_name != package->GetPackageName()) {
1008 // All packages in the same group are expected to have the same package name.
1009 break;
1010 }
1011
1012 uint32_t resid = package->FindEntryByName(type16, entry16);
1013 if (resid == 0u && kAttr16 == type16) {
1014 // Private attributes in libraries (such as the framework) are sometimes encoded
1015 // under the type '^attr-private' in order to leave the ID space of public 'attr'
1016 // free for future additions. Check '^attr-private' for the same name.
1017 resid = package->FindEntryByName(kAttrPrivate16, entry16);
1018 }
1019
1020 if (resid != 0u) {
1021 return fix_package_id(resid, package_group.dynamic_ref_table.mAssignedPackageId);
1022 }
1023 }
1024 }
Adam Lesinski0c405242017-01-13 20:47:26 -08001025 return 0u;
1026}
1027
Mårten Kongstad668ec5b2018-06-11 14:11:33 +02001028void AssetManager2::RebuildFilterList(bool filter_incompatible_configs) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001029 for (PackageGroup& group : package_groups_) {
1030 for (ConfiguredPackage& impl : group.packages_) {
1031 // Destroy it.
1032 impl.filtered_configs_.~ByteBucketArray();
1033
1034 // Re-create it.
1035 new (&impl.filtered_configs_) ByteBucketArray<FilteredConfigGroup>();
1036
1037 // Create the filters here.
1038 impl.loaded_package_->ForEachTypeSpec([&](const TypeSpec* spec, uint8_t type_index) {
1039 FilteredConfigGroup& group = impl.filtered_configs_.editItemAt(type_index);
1040 const auto iter_end = spec->types + spec->type_count;
1041 for (auto iter = spec->types; iter != iter_end; ++iter) {
1042 ResTable_config this_config;
1043 this_config.copyFromDtoH((*iter)->config);
Mårten Kongstad668ec5b2018-06-11 14:11:33 +02001044 if (!filter_incompatible_configs || this_config.match(configuration_)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001045 group.configurations.push_back(this_config);
1046 group.types.push_back(*iter);
1047 }
1048 }
1049 });
1050 }
1051 }
1052}
1053
Adam Lesinski7ad11102016-10-28 16:39:15 -07001054void AssetManager2::InvalidateCaches(uint32_t diff) {
Ryan Mitchell2c4d8742019-03-04 09:41:00 -08001055 cached_bag_resid_stacks_.clear();
1056
Adam Lesinski7ad11102016-10-28 16:39:15 -07001057 if (diff == 0xffffffffu) {
1058 // Everything must go.
1059 cached_bags_.clear();
1060 return;
1061 }
1062
1063 // Be more conservative with what gets purged. Only if the bag has other possible
1064 // variations with respect to what changed (diff) should we remove it.
1065 for (auto iter = cached_bags_.cbegin(); iter != cached_bags_.cend();) {
1066 if (diff & iter->second->type_spec_flags) {
1067 iter = cached_bags_.erase(iter);
1068 } else {
1069 ++iter;
1070 }
1071 }
1072}
1073
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001074uint8_t AssetManager2::GetAssignedPackageId(const LoadedPackage* package) {
1075 for (auto& package_group : package_groups_) {
1076 for (auto& package2 : package_group.packages_) {
1077 if (package2.loaded_package_ == package) {
1078 return package_group.dynamic_ref_table.mAssignedPackageId;
1079 }
1080 }
1081 }
1082 return 0;
1083}
1084
Adam Lesinski30080e22017-10-16 16:18:09 -07001085std::unique_ptr<Theme> AssetManager2::NewTheme() {
1086 return std::unique_ptr<Theme>(new Theme(this));
1087}
1088
1089Theme::Theme(AssetManager2* asset_manager) : asset_manager_(asset_manager) {
1090}
1091
1092Theme::~Theme() = default;
1093
1094namespace {
1095
1096struct ThemeEntry {
1097 ApkAssetsCookie cookie;
1098 uint32_t type_spec_flags;
1099 Res_value value;
1100};
1101
1102struct ThemeType {
1103 int entry_count;
1104 ThemeEntry entries[0];
1105};
1106
1107constexpr size_t kTypeCount = std::numeric_limits<uint8_t>::max() + 1;
1108
1109} // namespace
1110
1111struct Theme::Package {
1112 // Each element of Type will be a dynamically sized object
1113 // allocated to have the entries stored contiguously with the Type.
1114 std::array<util::unique_cptr<ThemeType>, kTypeCount> types;
1115};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001116
1117bool Theme::ApplyStyle(uint32_t resid, bool force) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001118 ATRACE_NAME("Theme::ApplyStyle");
Adam Lesinski7ad11102016-10-28 16:39:15 -07001119
1120 const ResolvedBag* bag = asset_manager_->GetBag(resid);
1121 if (bag == nullptr) {
1122 return false;
1123 }
1124
1125 // Merge the flags from this style.
1126 type_spec_flags_ |= bag->type_spec_flags;
1127
Adam Lesinski30080e22017-10-16 16:18:09 -07001128 int last_type_idx = -1;
1129 int last_package_idx = -1;
1130 Package* last_package = nullptr;
1131 ThemeType* last_type = nullptr;
1132
1133 // Iterate backwards, because each bag is sorted in ascending key ID order, meaning we will only
1134 // need to perform one resize per type.
1135 using reverse_bag_iterator = std::reverse_iterator<const ResolvedBag::Entry*>;
1136 const auto bag_iter_end = reverse_bag_iterator(begin(bag));
1137 for (auto bag_iter = reverse_bag_iterator(end(bag)); bag_iter != bag_iter_end; ++bag_iter) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001138 const uint32_t attr_resid = bag_iter->key;
1139
Adam Lesinski30080e22017-10-16 16:18:09 -07001140 // If the resource ID passed in is not a style, the key can be some other identifier that is not
1141 // a resource ID. We should fail fast instead of operating with strange resource IDs.
Adam Lesinski929d6512017-01-16 19:11:19 -08001142 if (!is_valid_resid(attr_resid)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001143 return false;
1144 }
1145
Adam Lesinski30080e22017-10-16 16:18:09 -07001146 // We don't use the 0-based index for the type so that we can avoid doing ID validation
1147 // upon lookup. Instead, we keep space for the type ID 0 in our data structures. Since
1148 // the construction of this type is guarded with a resource ID check, it will never be
1149 // populated, and querying type ID 0 will always fail.
1150 const int package_idx = get_package_id(attr_resid);
1151 const int type_idx = get_type_id(attr_resid);
1152 const int entry_idx = get_entry_id(attr_resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001153
Adam Lesinski30080e22017-10-16 16:18:09 -07001154 if (last_package_idx != package_idx) {
1155 std::unique_ptr<Package>& package = packages_[package_idx];
1156 if (package == nullptr) {
1157 package.reset(new Package());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001158 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001159 last_package_idx = package_idx;
1160 last_package = package.get();
1161 last_type_idx = -1;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001162 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001163
1164 if (last_type_idx != type_idx) {
1165 util::unique_cptr<ThemeType>& type = last_package->types[type_idx];
1166 if (type == nullptr) {
1167 // Allocate enough memory to contain this entry_idx. Since we're iterating in reverse over
1168 // a sorted list of attributes, this shouldn't be resized again during this method call.
1169 type.reset(reinterpret_cast<ThemeType*>(
1170 calloc(sizeof(ThemeType) + (entry_idx + 1) * sizeof(ThemeEntry), 1)));
1171 type->entry_count = entry_idx + 1;
1172 } else if (entry_idx >= type->entry_count) {
1173 // Reallocate the memory to contain this entry_idx. Since we're iterating in reverse over
1174 // a sorted list of attributes, this shouldn't be resized again during this method call.
1175 const int new_count = entry_idx + 1;
1176 type.reset(reinterpret_cast<ThemeType*>(
1177 realloc(type.release(), sizeof(ThemeType) + (new_count * sizeof(ThemeEntry)))));
1178
1179 // Clear out the newly allocated space (which isn't zeroed).
1180 memset(type->entries + type->entry_count, 0,
1181 (new_count - type->entry_count) * sizeof(ThemeEntry));
1182 type->entry_count = new_count;
1183 }
1184 last_type_idx = type_idx;
1185 last_type = type.get();
1186 }
1187
1188 ThemeEntry& entry = last_type->entries[entry_idx];
1189 if (force || (entry.value.dataType == Res_value::TYPE_NULL &&
1190 entry.value.data != Res_value::DATA_NULL_EMPTY)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001191 entry.cookie = bag_iter->cookie;
1192 entry.type_spec_flags |= bag->type_spec_flags;
1193 entry.value = bag_iter->value;
1194 }
1195 }
1196 return true;
1197}
1198
1199ApkAssetsCookie Theme::GetAttribute(uint32_t resid, Res_value* out_value,
1200 uint32_t* out_flags) const {
Adam Lesinski30080e22017-10-16 16:18:09 -07001201 int cnt = 20;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001202
1203 uint32_t type_spec_flags = 0u;
1204
Adam Lesinski30080e22017-10-16 16:18:09 -07001205 do {
1206 const int package_idx = get_package_id(resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001207 const Package* package = packages_[package_idx].get();
Adam Lesinski30080e22017-10-16 16:18:09 -07001208 if (package != nullptr) {
1209 // The themes are constructed with a 1-based type ID, so no need to decrement here.
1210 const int type_idx = get_type_id(resid);
1211 const ThemeType* type = package->types[type_idx].get();
1212 if (type != nullptr) {
1213 const int entry_idx = get_entry_id(resid);
1214 if (entry_idx < type->entry_count) {
1215 const ThemeEntry& entry = type->entries[entry_idx];
1216 type_spec_flags |= entry.type_spec_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001217
Adam Lesinski30080e22017-10-16 16:18:09 -07001218 if (entry.value.dataType == Res_value::TYPE_ATTRIBUTE) {
1219 if (cnt > 0) {
1220 cnt--;
1221 resid = entry.value.data;
1222 continue;
1223 }
1224 return kInvalidCookie;
1225 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001226
Adam Lesinski30080e22017-10-16 16:18:09 -07001227 // @null is different than @empty.
1228 if (entry.value.dataType == Res_value::TYPE_NULL &&
1229 entry.value.data != Res_value::DATA_NULL_EMPTY) {
1230 return kInvalidCookie;
1231 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001232
Adam Lesinski30080e22017-10-16 16:18:09 -07001233 *out_value = entry.value;
Adam Lesinskida431a22016-12-29 16:08:16 -05001234 *out_flags = type_spec_flags;
Adam Lesinski30080e22017-10-16 16:18:09 -07001235 return entry.cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -05001236 }
Adam Lesinskida431a22016-12-29 16:08:16 -05001237 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001238 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001239 break;
1240 } while (true);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001241 return kInvalidCookie;
1242}
1243
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001244ApkAssetsCookie Theme::ResolveAttributeReference(ApkAssetsCookie cookie, Res_value* in_out_value,
1245 ResTable_config* in_out_selected_config,
1246 uint32_t* in_out_type_spec_flags,
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001247 uint32_t* out_last_ref) const {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001248 if (in_out_value->dataType == Res_value::TYPE_ATTRIBUTE) {
1249 uint32_t new_flags;
1250 cookie = GetAttribute(in_out_value->data, in_out_value, &new_flags);
1251 if (cookie == kInvalidCookie) {
1252 return kInvalidCookie;
1253 }
1254
1255 if (in_out_type_spec_flags != nullptr) {
1256 *in_out_type_spec_flags |= new_flags;
1257 }
1258 }
1259 return asset_manager_->ResolveReference(cookie, in_out_value, in_out_selected_config,
1260 in_out_type_spec_flags, out_last_ref);
1261}
1262
Adam Lesinski7ad11102016-10-28 16:39:15 -07001263void Theme::Clear() {
1264 type_spec_flags_ = 0u;
1265 for (std::unique_ptr<Package>& package : packages_) {
1266 package.reset();
1267 }
1268}
1269
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001270void Theme::SetTo(const Theme& o) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001271 if (this == &o) {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001272 return;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001273 }
1274
Adam Lesinski7ad11102016-10-28 16:39:15 -07001275 type_spec_flags_ = o.type_spec_flags_;
1276
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001277 if (asset_manager_ == o.asset_manager_) {
1278 // The theme comes from the same asset manager so all theme data can be copied exactly
1279 for (size_t p = 0; p < packages_.size(); p++) {
1280 const Package *package = o.packages_[p].get();
1281 if (package == nullptr) {
1282 // The other theme doesn't have this package, clear ours.
1283 packages_[p].reset();
Adam Lesinski7ad11102016-10-28 16:39:15 -07001284 continue;
1285 }
1286
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001287 if (packages_[p] == nullptr) {
1288 // The other theme has this package, but we don't. Make one.
1289 packages_[p].reset(new Package());
1290 }
1291
1292 for (size_t t = 0; t < package->types.size(); t++) {
1293 const ThemeType *type = package->types[t].get();
1294 if (type == nullptr) {
1295 // The other theme doesn't have this type, clear ours.
1296 packages_[p]->types[t].reset();
1297 continue;
1298 }
1299
1300 // Create a new type and update it to theirs.
1301 const size_t type_alloc_size = sizeof(ThemeType) + (type->entry_count * sizeof(ThemeEntry));
1302 void *copied_data = malloc(type_alloc_size);
1303 memcpy(copied_data, type, type_alloc_size);
1304 packages_[p]->types[t].reset(reinterpret_cast<ThemeType *>(copied_data));
1305 }
1306 }
1307 } else {
1308 std::map<ApkAssetsCookie, ApkAssetsCookie> src_to_dest_asset_cookies;
1309 typedef std::map<int, int> SourceToDestinationRuntimePackageMap;
1310 std::map<ApkAssetsCookie, SourceToDestinationRuntimePackageMap> src_asset_cookie_id_map;
1311
1312 // Determine which ApkAssets are loaded in both theme AssetManagers
1313 std::vector<const ApkAssets*> src_assets = o.asset_manager_->GetApkAssets();
1314 for (size_t i = 0; i < src_assets.size(); i++) {
1315 const ApkAssets* src_asset = src_assets[i];
1316
1317 std::vector<const ApkAssets*> dest_assets = asset_manager_->GetApkAssets();
1318 for (size_t j = 0; j < dest_assets.size(); j++) {
1319 const ApkAssets* dest_asset = dest_assets[j];
1320
1321 // Map the runtime package of the source apk asset to the destination apk asset
1322 if (src_asset->GetPath() == dest_asset->GetPath()) {
1323 const std::vector<std::unique_ptr<const LoadedPackage>>& src_packages =
1324 src_asset->GetLoadedArsc()->GetPackages();
1325 const std::vector<std::unique_ptr<const LoadedPackage>>& dest_packages =
1326 dest_asset->GetLoadedArsc()->GetPackages();
1327
1328 SourceToDestinationRuntimePackageMap package_map;
1329
1330 // The source and destination package should have the same number of packages loaded in
1331 // the same order.
1332 const size_t N = src_packages.size();
1333 CHECK(N == dest_packages.size())
1334 << " LoadedArsc " << src_asset->GetPath() << " differs number of packages.";
1335 for (size_t p = 0; p < N; p++) {
1336 auto& src_package = src_packages[p];
1337 auto& dest_package = dest_packages[p];
1338 CHECK(src_package->GetPackageName() == dest_package->GetPackageName())
1339 << " Package " << src_package->GetPackageName() << " differs in load order.";
1340
1341 int src_package_id = o.asset_manager_->GetAssignedPackageId(src_package.get());
1342 int dest_package_id = asset_manager_->GetAssignedPackageId(dest_package.get());
1343 package_map[src_package_id] = dest_package_id;
1344 }
1345
1346 src_to_dest_asset_cookies.insert(std::pair<ApkAssetsCookie, ApkAssetsCookie>(i, j));
1347 src_asset_cookie_id_map.insert(
1348 std::pair<ApkAssetsCookie, SourceToDestinationRuntimePackageMap>(i, package_map));
1349 break;
1350 }
1351 }
1352 }
1353
1354 // Reset the data in the destination theme
1355 for (size_t p = 0; p < packages_.size(); p++) {
1356 if (packages_[p] != nullptr) {
1357 packages_[p].reset();
1358 }
1359 }
1360
1361 for (size_t p = 0; p < packages_.size(); p++) {
1362 const Package *package = o.packages_[p].get();
1363 if (package == nullptr) {
1364 continue;
1365 }
1366
1367 for (size_t t = 0; t < package->types.size(); t++) {
1368 const ThemeType *type = package->types[t].get();
1369 if (type == nullptr) {
1370 continue;
1371 }
1372
1373 for (size_t e = 0; e < type->entry_count; e++) {
1374 const ThemeEntry &entry = type->entries[e];
1375 if (entry.value.dataType == Res_value::TYPE_NULL &&
1376 entry.value.data != Res_value::DATA_NULL_EMPTY) {
1377 continue;
1378 }
1379
Ryan Mitchellb85d9b22018-11-19 12:11:38 -08001380 // If the attribute value represents an attribute or reference, the package id of the
1381 // value needs to be rewritten to the package id of the value in the destination
1382 uint32_t attribue_data = entry.value.data;
1383 if ((entry.value.dataType == Res_value::TYPE_ATTRIBUTE
1384 || entry.value.dataType == Res_value::TYPE_REFERENCE
1385 || entry.value.dataType == Res_value::TYPE_DYNAMIC_ATTRIBUTE
1386 || entry.value.dataType == Res_value::TYPE_DYNAMIC_REFERENCE)
1387 && attribue_data != 0x0) {
1388
1389 // Determine the package id of the reference in the destination AssetManager
1390 auto value_package_map = src_asset_cookie_id_map.find(entry.cookie);
1391 if (value_package_map == src_asset_cookie_id_map.end()) {
1392 continue;
1393 }
1394
1395 auto value_dest_package = value_package_map->second.find(
1396 get_package_id(entry.value.data));
1397 if (value_dest_package == value_package_map->second.end()) {
1398 continue;
1399 }
1400
1401 attribue_data = fix_package_id(entry.value.data, value_dest_package->second);
1402 }
1403
1404 // The package id of the attribute needs to be rewritten to the package id of the
1405 // attribute in the destination
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001406 int attribute_dest_package_id = p;
1407 if (attribute_dest_package_id != 0x01) {
1408 // Find the cookie of the attribute resource id
1409 FindEntryResult attribute_entry_result;
1410 ApkAssetsCookie attribute_cookie =
Ryan Mitchella55dc2e2019-01-24 10:58:23 -08001411 o.asset_manager_->FindEntry(make_resid(p, t, e), 0 /* density_override */ ,
1412 true /* stop_at_first_match */,
1413 true /* ignore_configuration */,
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001414 &attribute_entry_result);
1415
1416 // Determine the package id of the attribute in the destination AssetManager
1417 auto attribute_package_map = src_asset_cookie_id_map.find(attribute_cookie);
1418 if (attribute_package_map == src_asset_cookie_id_map.end()) {
1419 continue;
1420 }
1421 auto attribute_dest_package = attribute_package_map->second.find(
1422 attribute_dest_package_id);
1423 if (attribute_dest_package == attribute_package_map->second.end()) {
1424 continue;
1425 }
1426 attribute_dest_package_id = attribute_dest_package->second;
1427 }
1428
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001429 // Lazily instantiate the destination package
1430 std::unique_ptr<Package>& dest_package = packages_[attribute_dest_package_id];
1431 if (dest_package == nullptr) {
1432 dest_package.reset(new Package());
1433 }
1434
1435 // Lazily instantiate and resize the destination type
1436 util::unique_cptr<ThemeType>& dest_type = dest_package->types[t];
1437 if (dest_type == nullptr || dest_type->entry_count < type->entry_count) {
1438 const size_t type_alloc_size = sizeof(ThemeType)
1439 + (type->entry_count * sizeof(ThemeEntry));
1440 void* dest_data = malloc(type_alloc_size);
1441 memset(dest_data, 0, type->entry_count * sizeof(ThemeEntry));
1442
1443 // Copy the existing destination type values if the type is resized
1444 if (dest_type != nullptr) {
1445 memcpy(dest_data, type, sizeof(ThemeType)
1446 + (dest_type->entry_count * sizeof(ThemeEntry)));
1447 }
1448
1449 dest_type.reset(reinterpret_cast<ThemeType *>(dest_data));
1450 dest_type->entry_count = type->entry_count;
1451 }
1452
1453 // Find the cookie of the value in the destination
1454 auto value_dest_cookie = src_to_dest_asset_cookies.find(entry.cookie);
1455 if (value_dest_cookie == src_to_dest_asset_cookies.end()) {
1456 continue;
1457 }
1458
1459 dest_type->entries[e].cookie = value_dest_cookie->second;
1460 dest_type->entries[e].value.dataType = entry.value.dataType;
1461 dest_type->entries[e].value.data = attribue_data;
1462 dest_type->entries[e].type_spec_flags = entry.type_spec_flags;
1463 }
1464 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001465 }
1466 }
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001467}
1468
1469void Theme::Dump() const {
1470 base::ScopedLogSeverity _log(base::INFO);
1471 LOG(INFO) << base::StringPrintf("Theme(this=%p, AssetManager2=%p)", this, asset_manager_);
1472
1473 for (int p = 0; p < packages_.size(); p++) {
1474 auto& package = packages_[p];
1475 if (package == nullptr) {
1476 continue;
1477 }
1478
1479 for (int t = 0; t < package->types.size(); t++) {
1480 auto& type = package->types[t];
1481 if (type == nullptr) {
1482 continue;
1483 }
1484
1485 for (int e = 0; e < type->entry_count; e++) {
1486 auto& entry = type->entries[e];
1487 if (entry.value.dataType == Res_value::TYPE_NULL &&
1488 entry.value.data != Res_value::DATA_NULL_EMPTY) {
1489 continue;
1490 }
1491
1492 LOG(INFO) << base::StringPrintf(" entry(0x%08x)=(0x%08x) type=(0x%02x), cookie(%d)",
1493 make_resid(p, t, e), entry.value.data,
1494 entry.value.dataType, entry.cookie);
1495 }
1496 }
1497 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001498}
1499
1500} // namespace android