blob: 951970464bfe45d69280e9104a94819a7d4384d0 [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;
Mårten Kongstaddbf343b2019-02-21 07:54:18 +0100313 if (apk_assets->IsOverlay()) {
314 continue;
315 }
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800316
317 auto func = [&](const StringPiece& name, FileType type) {
318 AssetDir::FileInfo info;
319 info.setFileName(String8(name.data(), name.size()));
320 info.setFileType(type);
321 info.setSourceName(String8(apk_assets->GetPath().c_str()));
322 files->add(info);
323 };
324
325 if (!apk_assets->ForEachFile(full_path, func)) {
326 return {};
327 }
328 }
329
330 std::unique_ptr<AssetDir> asset_dir = util::make_unique<AssetDir>();
331 asset_dir->setFileList(files.release());
332 return asset_dir;
333}
334
Adam Lesinski7ad11102016-10-28 16:39:15 -0700335// Search in reverse because that's how we used to do it and we need to preserve behaviour.
336// This is unfortunate, because ClassLoaders delegate to the parent first, so the order
337// is inconsistent for split APKs.
338std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
339 Asset::AccessMode mode,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800340 ApkAssetsCookie* out_cookie) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700341 for (int32_t i = apk_assets_.size() - 1; i >= 0; i--) {
Mårten Kongstaddbf343b2019-02-21 07:54:18 +0100342 // Prevent RRO from modifying assets and other entries accessed by file
343 // path. Explicitly asking for a path in a given package (denoted by a
344 // cookie) is still OK.
345 if (apk_assets_[i]->IsOverlay()) {
346 continue;
347 }
348
Adam Lesinski7ad11102016-10-28 16:39:15 -0700349 std::unique_ptr<Asset> asset = apk_assets_[i]->Open(filename, mode);
350 if (asset) {
351 if (out_cookie != nullptr) {
352 *out_cookie = i;
353 }
354 return asset;
355 }
356 }
357
358 if (out_cookie != nullptr) {
359 *out_cookie = kInvalidCookie;
360 }
361 return {};
362}
363
364std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800365 ApkAssetsCookie cookie,
366 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700367 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
368 return {};
369 }
370 return apk_assets_[cookie]->Open(filename, mode);
371}
372
373ApkAssetsCookie AssetManager2::FindEntry(uint32_t resid, uint16_t density_override,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800374 bool /*stop_at_first_match*/,
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800375 bool ignore_configuration,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800376 FindEntryResult* out_entry) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700377 // Might use this if density_override != 0.
378 ResTable_config density_override_config;
379
380 // Select our configuration or generate a density override configuration.
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800381 const ResTable_config* desired_config = &configuration_;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700382 if (density_override != 0 && density_override != configuration_.density) {
383 density_override_config = configuration_;
384 density_override_config.density = density_override;
385 desired_config = &density_override_config;
386 }
387
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800388 if (!is_valid_resid(resid)) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500389 LOG(ERROR) << base::StringPrintf("Invalid ID 0x%08x.", resid);
390 return kInvalidCookie;
391 }
392
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800393 const uint32_t package_id = get_package_id(resid);
394 const uint8_t type_idx = get_type_id(resid) - 1;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800395 const uint16_t entry_idx = get_entry_id(resid);
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800396
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800397 const uint8_t package_idx = package_ids_[package_id];
398 if (package_idx == 0xff) {
Ryan Mitchell2fe23472019-02-27 09:43:01 -0800399 ANDROID_LOG(ERROR) << base::StringPrintf("No package ID %02x found for ID 0x%08x.",
400 package_id, resid);
Adam Lesinskida431a22016-12-29 16:08:16 -0500401 return kInvalidCookie;
402 }
403
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800404 const PackageGroup& package_group = package_groups_[package_idx];
Adam Lesinskib8b3a262018-02-09 11:01:45 -0800405 const size_t package_count = package_group.packages_.size();
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800406
407 ApkAssetsCookie best_cookie = kInvalidCookie;
408 const LoadedPackage* best_package = nullptr;
409 const ResTable_type* best_type = nullptr;
410 const ResTable_config* best_config = nullptr;
411 ResTable_config best_config_copy;
412 uint32_t best_offset = 0u;
413 uint32_t type_flags = 0u;
414
Winson2f3669b2019-01-11 11:28:34 -0800415 Resolution::Step::Type resolution_type;
416 std::vector<Resolution::Step> resolution_steps;
417
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800418 // If desired_config is the same as the set configuration, then we can use our filtered list
419 // and we don't need to match the configurations, since they already matched.
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800420 const bool use_fast_path = !ignore_configuration && desired_config == &configuration_;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800421
422 for (size_t pi = 0; pi < package_count; pi++) {
423 const ConfiguredPackage& loaded_package_impl = package_group.packages_[pi];
424 const LoadedPackage* loaded_package = loaded_package_impl.loaded_package_;
425 ApkAssetsCookie cookie = package_group.cookies_[pi];
426
427 // If the type IDs are offset in this package, we need to take that into account when searching
428 // for a type.
429 const TypeSpec* type_spec = loaded_package->GetTypeSpecByTypeIndex(type_idx);
430 if (UNLIKELY(type_spec == nullptr)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700431 continue;
432 }
433
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800434 uint16_t local_entry_idx = entry_idx;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700435
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800436 // If there is an IDMAP supplied with this package, translate the entry ID.
437 if (type_spec->idmap_entries != nullptr) {
438 if (!LoadedIdmap::Lookup(type_spec->idmap_entries, local_entry_idx, &local_entry_idx)) {
439 // There is no mapping, so the resource is not meant to be in this overlay package.
440 continue;
441 }
442 }
443
444 type_flags |= type_spec->GetFlagsForEntryIndex(local_entry_idx);
445
446 // If the package is an overlay, then even configurations that are the same MUST be chosen.
447 const bool package_is_overlay = loaded_package->IsOverlay();
448
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800449 if (use_fast_path) {
Winson2f3669b2019-01-11 11:28:34 -0800450 const FilteredConfigGroup& filtered_group = loaded_package_impl.filtered_configs_[type_idx];
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800451 const std::vector<ResTable_config>& candidate_configs = filtered_group.configurations;
452 const size_t type_count = candidate_configs.size();
453 for (uint32_t i = 0; i < type_count; i++) {
454 const ResTable_config& this_config = candidate_configs[i];
455
456 // We can skip calling ResTable_config::match() because we know that all candidate
457 // configurations that do NOT match have been filtered-out.
Winson2f3669b2019-01-11 11:28:34 -0800458 if (best_config == nullptr) {
459 resolution_type = Resolution::Step::Type::INITIAL;
460 } else if (this_config.isBetterThan(*best_config, desired_config)) {
461 resolution_type = Resolution::Step::Type::BETTER_MATCH;
462 } else if (package_is_overlay && this_config.compare(*best_config) == 0) {
463 resolution_type = Resolution::Step::Type::OVERLAID;
464 } else {
465 continue;
466 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800467
Winson2f3669b2019-01-11 11:28:34 -0800468 // The configuration matches and is better than the previous selection.
469 // Find the entry value if it exists for this configuration.
470 const ResTable_type* type = filtered_group.types[i];
471 const uint32_t offset = LoadedPackage::GetEntryOffset(type, local_entry_idx);
472 if (offset == ResTable_type::NO_ENTRY) {
473 continue;
474 }
475
476 best_cookie = cookie;
477 best_package = loaded_package;
478 best_type = type;
479 best_config = &this_config;
480 best_offset = offset;
481
482 if (resource_resolution_logging_enabled_) {
483 resolution_steps.push_back(Resolution::Step{resolution_type,
484 this_config.toString(),
485 &loaded_package->GetPackageName()});
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800486 }
487 }
488 } else {
489 // This is the slower path, which doesn't use the filtered list of configurations.
490 // Here we must read the ResTable_config from the mmapped APK, convert it to host endianness
491 // and fill in any new fields that did not exist when the APK was compiled.
492 // Furthermore when selecting configurations we can't just record the pointer to the
493 // ResTable_config, we must copy it.
494 const auto iter_end = type_spec->types + type_spec->type_count;
495 for (auto iter = type_spec->types; iter != iter_end; ++iter) {
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800496 ResTable_config this_config{};
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800497
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800498 if (!ignore_configuration) {
499 this_config.copyFromDtoH((*iter)->config);
500 if (!this_config.match(*desired_config)) {
501 continue;
502 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800503
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800504 if (best_config == nullptr) {
505 resolution_type = Resolution::Step::Type::INITIAL;
506 } else if (this_config.isBetterThan(*best_config, desired_config)) {
507 resolution_type = Resolution::Step::Type::BETTER_MATCH;
508 } else if (package_is_overlay && this_config.compare(*best_config) == 0) {
509 resolution_type = Resolution::Step::Type::OVERLAID;
510 } else {
511 continue;
512 }
Winson2f3669b2019-01-11 11:28:34 -0800513 }
514
515 // The configuration matches and is better than the previous selection.
516 // Find the entry value if it exists for this configuration.
517 const uint32_t offset = LoadedPackage::GetEntryOffset(*iter, local_entry_idx);
518 if (offset == ResTable_type::NO_ENTRY) {
519 continue;
520 }
521
522 best_cookie = cookie;
523 best_package = loaded_package;
524 best_type = *iter;
525 best_config_copy = this_config;
526 best_config = &best_config_copy;
527 best_offset = offset;
528
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800529 if (ignore_configuration) {
530 // Any configuration will suffice, so break.
531 break;
532 }
533
Winson2f3669b2019-01-11 11:28:34 -0800534 if (resource_resolution_logging_enabled_) {
535 resolution_steps.push_back(Resolution::Step{resolution_type,
536 this_config.toString(),
537 &loaded_package->GetPackageName()});
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800538 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700539 }
540 }
541 }
542
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800543 if (UNLIKELY(best_cookie == kInvalidCookie)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700544 return kInvalidCookie;
545 }
546
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800547 const ResTable_entry* best_entry = LoadedPackage::GetEntryFromOffset(best_type, best_offset);
548 if (UNLIKELY(best_entry == nullptr)) {
549 return kInvalidCookie;
550 }
551
552 out_entry->entry = best_entry;
553 out_entry->config = *best_config;
554 out_entry->type_flags = type_flags;
555 out_entry->type_string_ref = StringPoolRef(best_package->GetTypeStringPool(), best_type->id - 1);
556 out_entry->entry_string_ref =
557 StringPoolRef(best_package->GetKeyStringPool(), best_entry->key.index);
Adam Lesinskida431a22016-12-29 16:08:16 -0500558 out_entry->dynamic_ref_table = &package_group.dynamic_ref_table;
Winson2f3669b2019-01-11 11:28:34 -0800559
560 if (resource_resolution_logging_enabled_) {
561 last_resolution.resid = resid;
562 last_resolution.cookie = best_cookie;
563 last_resolution.steps = resolution_steps;
564
565 // Cache only the type/entry refs since that's all that's needed to build name
566 last_resolution.type_string_ref =
567 StringPoolRef(best_package->GetTypeStringPool(), best_type->id - 1);
568 last_resolution.entry_string_ref =
569 StringPoolRef(best_package->GetKeyStringPool(), best_entry->key.index);
570 }
571
Adam Lesinskida431a22016-12-29 16:08:16 -0500572 return best_cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700573}
574
Winson2f3669b2019-01-11 11:28:34 -0800575void AssetManager2::SetResourceResolutionLoggingEnabled(bool enabled) {
576 resource_resolution_logging_enabled_ = enabled;
577
578 if (!enabled) {
579 last_resolution.cookie = kInvalidCookie;
580 last_resolution.resid = 0;
581 last_resolution.steps.clear();
582 last_resolution.type_string_ref = StringPoolRef();
583 last_resolution.entry_string_ref = StringPoolRef();
584 }
585}
586
587std::string AssetManager2::GetLastResourceResolution() const {
588 if (!resource_resolution_logging_enabled_) {
589 LOG(ERROR) << "Must enable resource resolution logging before getting path.";
590 return std::string();
591 }
592
593 auto cookie = last_resolution.cookie;
594 if (cookie == kInvalidCookie) {
595 LOG(ERROR) << "AssetManager hasn't resolved a resource to read resolution path.";
596 return std::string();
597 }
598
599 uint32_t resid = last_resolution.resid;
600 std::vector<Resolution::Step>& steps = last_resolution.steps;
601
602 ResourceName resource_name;
603 std::string resource_name_string;
604
605 const LoadedPackage* package =
606 apk_assets_[cookie]->GetLoadedArsc()->GetPackageById(get_package_id(resid));
607
608 if (package != nullptr) {
609 ToResourceName(last_resolution.type_string_ref,
610 last_resolution.entry_string_ref,
Ryan Mitchell741e96f2019-01-23 16:56:51 -0800611 package->GetPackageName(),
Winson2f3669b2019-01-11 11:28:34 -0800612 &resource_name);
613 resource_name_string = ToFormattedResourceString(&resource_name);
614 }
615
616 std::stringstream log_stream;
617 log_stream << base::StringPrintf("Resolution for 0x%08x ", resid)
618 << resource_name_string
619 << "\n\tFor config -"
620 << configuration_.toString();
621
622 std::string prefix;
623 for (Resolution::Step step : steps) {
624 switch (step.type) {
625 case Resolution::Step::Type::INITIAL:
626 prefix = "Found initial";
627 break;
628 case Resolution::Step::Type::BETTER_MATCH:
629 prefix = "Found better";
630 break;
631 case Resolution::Step::Type::OVERLAID:
632 prefix = "Overlaid";
633 break;
634 }
635
636 if (!prefix.empty()) {
637 log_stream << "\n\t" << prefix << ": " << *step.package_name;
638
639 if (!step.config_name.isEmpty()) {
640 log_stream << " -" << step.config_name;
641 }
642 }
643 }
644
645 return log_stream.str();
646}
647
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800648bool AssetManager2::GetResourceName(uint32_t resid, ResourceName* out_name) const {
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700649 FindEntryResult entry;
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800650 ApkAssetsCookie cookie = FindEntry(resid, 0u /* density_override */,
651 true /* stop_at_first_match */,
652 true /* ignore_configuration */, &entry);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700653 if (cookie == kInvalidCookie) {
654 return false;
655 }
656
Ryan Mitchell741e96f2019-01-23 16:56:51 -0800657 const uint8_t package_idx = package_ids_[get_package_id(resid)];
658 if (package_idx == 0xff) {
659 LOG(ERROR) << base::StringPrintf("No package ID %02x found for ID 0x%08x.",
660 get_package_id(resid), resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700661 return false;
662 }
663
Ryan Mitchell741e96f2019-01-23 16:56:51 -0800664 const PackageGroup& package_group = package_groups_[package_idx];
665 auto cookie_iter = std::find(package_group.cookies_.begin(),
666 package_group.cookies_.end(), cookie);
667 if (cookie_iter == package_group.cookies_.end()) {
668 return false;
669 }
670
671 long package_pos = std::distance(package_group.cookies_.begin(), cookie_iter);
672 const LoadedPackage* package = package_group.packages_[package_pos].loaded_package_;
Winson2f3669b2019-01-11 11:28:34 -0800673 return ToResourceName(entry.type_string_ref,
674 entry.entry_string_ref,
Ryan Mitchell741e96f2019-01-23 16:56:51 -0800675 package->GetPackageName(),
Winson2f3669b2019-01-11 11:28:34 -0800676 out_name);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700677}
678
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800679bool AssetManager2::GetResourceFlags(uint32_t resid, uint32_t* out_flags) const {
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700680 FindEntryResult entry;
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800681 ApkAssetsCookie cookie = FindEntry(resid, 0u /* density_override */,
682 false /* stop_at_first_match */,
683 true /* ignore_configuration */, &entry);
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700684 if (cookie != kInvalidCookie) {
685 *out_flags = entry.type_flags;
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800686 return true;
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700687 }
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800688 return false;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700689}
690
691ApkAssetsCookie AssetManager2::GetResource(uint32_t resid, bool may_be_bag,
692 uint16_t density_override, Res_value* out_value,
693 ResTable_config* out_selected_config,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800694 uint32_t* out_flags) const {
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700695 FindEntryResult entry;
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800696 ApkAssetsCookie cookie = FindEntry(resid, density_override, false /* stop_at_first_match */,
697 false /* ignore_configuration */, &entry);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700698 if (cookie == kInvalidCookie) {
699 return kInvalidCookie;
700 }
701
Adam Lesinski498f6052017-11-29 13:24:29 -0800702 if (dtohs(entry.entry->flags) & ResTable_entry::FLAG_COMPLEX) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700703 if (!may_be_bag) {
704 LOG(ERROR) << base::StringPrintf("Resource %08x is a complex map type.", resid);
Adam Lesinski0c405242017-01-13 20:47:26 -0800705 return kInvalidCookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700706 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800707
708 // Create a reference since we can't represent this complex type as a Res_value.
709 out_value->dataType = Res_value::TYPE_REFERENCE;
710 out_value->data = resid;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800711 *out_selected_config = entry.config;
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700712 *out_flags = entry.type_flags;
Adam Lesinski0c405242017-01-13 20:47:26 -0800713 return cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700714 }
715
716 const Res_value* device_value = reinterpret_cast<const Res_value*>(
717 reinterpret_cast<const uint8_t*>(entry.entry) + dtohs(entry.entry->size));
718 out_value->copyFrom_dtoh(*device_value);
Adam Lesinskida431a22016-12-29 16:08:16 -0500719
720 // Convert the package ID to the runtime assigned package ID.
721 entry.dynamic_ref_table->lookupResourceValue(out_value);
722
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800723 *out_selected_config = entry.config;
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700724 *out_flags = entry.type_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700725 return cookie;
726}
727
Adam Lesinski0c405242017-01-13 20:47:26 -0800728ApkAssetsCookie AssetManager2::ResolveReference(ApkAssetsCookie cookie, Res_value* in_out_value,
729 ResTable_config* in_out_selected_config,
730 uint32_t* in_out_flags,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800731 uint32_t* out_last_reference) const {
Adam Lesinski0c405242017-01-13 20:47:26 -0800732 constexpr const int kMaxIterations = 20;
733
Adam Lesinski0c405242017-01-13 20:47:26 -0800734 for (size_t iteration = 0u; in_out_value->dataType == Res_value::TYPE_REFERENCE &&
735 in_out_value->data != 0u && iteration < kMaxIterations;
736 iteration++) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800737 *out_last_reference = in_out_value->data;
Adam Lesinski0c405242017-01-13 20:47:26 -0800738 uint32_t new_flags = 0u;
739 cookie = GetResource(in_out_value->data, true /*may_be_bag*/, 0u /*density_override*/,
740 in_out_value, in_out_selected_config, &new_flags);
741 if (cookie == kInvalidCookie) {
742 return kInvalidCookie;
743 }
744 if (in_out_flags != nullptr) {
745 *in_out_flags |= new_flags;
746 }
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800747 if (*out_last_reference == in_out_value->data) {
Adam Lesinski0c405242017-01-13 20:47:26 -0800748 // This reference can't be resolved, so exit now and let the caller deal with it.
749 return cookie;
750 }
751 }
752 return cookie;
753}
754
Aurimas Liutikas8f004c82019-01-17 17:20:10 -0800755const std::vector<uint32_t> AssetManager2::GetBagResIdStack(uint32_t resid) {
756 auto cached_iter = cached_bag_resid_stacks_.find(resid);
757 if (cached_iter != cached_bag_resid_stacks_.end()) {
758 return cached_iter->second;
759 } else {
760 auto found_resids = std::vector<uint32_t>();
761 GetBag(resid, found_resids);
762 // Cache style stacks if they are not already cached.
763 cached_bag_resid_stacks_[resid] = found_resids;
764 return found_resids;
765 }
766}
767
Adam Lesinski7ad11102016-10-28 16:39:15 -0700768const ResolvedBag* AssetManager2::GetBag(uint32_t resid) {
y57cd1952018-04-12 14:26:23 -0700769 auto found_resids = std::vector<uint32_t>();
Aurimas Liutikas8f004c82019-01-17 17:20:10 -0800770 auto bag = GetBag(resid, found_resids);
771
772 // Cache style stacks if they are not already cached.
773 auto cached_iter = cached_bag_resid_stacks_.find(resid);
774 if (cached_iter == cached_bag_resid_stacks_.end()) {
775 cached_bag_resid_stacks_[resid] = found_resids;
776 }
777 return bag;
y57cd1952018-04-12 14:26:23 -0700778}
779
780const ResolvedBag* AssetManager2::GetBag(uint32_t resid, std::vector<uint32_t>& child_resids) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800781 ATRACE_NAME("AssetManager::GetBag");
Adam Lesinski7ad11102016-10-28 16:39:15 -0700782
783 auto cached_iter = cached_bags_.find(resid);
784 if (cached_iter != cached_bags_.end()) {
785 return cached_iter->second.get();
786 }
787
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700788 FindEntryResult entry;
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800789 ApkAssetsCookie cookie = FindEntry(resid, 0u /* density_override */,
790 false /* stop_at_first_match */,
791 false /* ignore_configuration */,
792 &entry);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700793 if (cookie == kInvalidCookie) {
794 return nullptr;
795 }
796
797 // Check that the size of the entry header is at least as big as
798 // the desired ResTable_map_entry. Also verify that the entry
799 // was intended to be a map.
800 if (dtohs(entry.entry->size) < sizeof(ResTable_map_entry) ||
801 (dtohs(entry.entry->flags) & ResTable_entry::FLAG_COMPLEX) == 0) {
802 // Not a bag, nothing to do.
803 return nullptr;
804 }
805
806 const ResTable_map_entry* map = reinterpret_cast<const ResTable_map_entry*>(entry.entry);
807 const ResTable_map* map_entry =
808 reinterpret_cast<const ResTable_map*>(reinterpret_cast<const uint8_t*>(map) + map->size);
809 const ResTable_map* const map_entry_end = map_entry + dtohl(map->count);
810
y57cd1952018-04-12 14:26:23 -0700811 // Keep track of ids that have already been seen to prevent infinite loops caused by circular
812 // dependencies between bags
813 child_resids.push_back(resid);
814
Adam Lesinskida431a22016-12-29 16:08:16 -0500815 uint32_t parent_resid = dtohl(map->parent.ident);
y57cd1952018-04-12 14:26:23 -0700816 if (parent_resid == 0 || std::find(child_resids.begin(), child_resids.end(), parent_resid)
817 != child_resids.end()) {
818 // There is no parent or that a circular dependency exist, meaning there is nothing to
819 // inherit and we can do a simple copy of the entries in the map.
Adam Lesinski7ad11102016-10-28 16:39:15 -0700820 const size_t entry_count = map_entry_end - map_entry;
821 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
822 malloc(sizeof(ResolvedBag) + (entry_count * sizeof(ResolvedBag::Entry))))};
823 ResolvedBag::Entry* new_entry = new_bag->entries;
824 for (; map_entry != map_entry_end; ++map_entry) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500825 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -0800826 if (!is_internal_resid(new_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500827 // Attributes, arrays, etc don't have a resource id as the name. They specify
828 // other data, which would be wrong to change via a lookup.
829 if (entry.dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800830 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
831 resid);
Adam Lesinskida431a22016-12-29 16:08:16 -0500832 return nullptr;
833 }
834 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700835 new_entry->cookie = cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -0500836 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700837 new_entry->key_pool = nullptr;
838 new_entry->type_pool = nullptr;
Aurimas Liutikasd42a6702018-11-15 15:48:28 -0800839 new_entry->style = resid;
Adam Lesinski30080e22017-10-16 16:18:09 -0700840 new_entry->value.copyFrom_dtoh(map_entry->value);
841 status_t err = entry.dynamic_ref_table->lookupResourceValue(&new_entry->value);
842 if (err != NO_ERROR) {
843 LOG(ERROR) << base::StringPrintf(
844 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
845 new_entry->value.data, new_key);
846 return nullptr;
847 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700848 ++new_entry;
849 }
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700850 new_bag->type_spec_flags = entry.type_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700851 new_bag->entry_count = static_cast<uint32_t>(entry_count);
852 ResolvedBag* result = new_bag.get();
853 cached_bags_[resid] = std::move(new_bag);
854 return result;
855 }
856
Adam Lesinskida431a22016-12-29 16:08:16 -0500857 // In case the parent is a dynamic reference, resolve it.
858 entry.dynamic_ref_table->lookupResourceId(&parent_resid);
859
Adam Lesinski7ad11102016-10-28 16:39:15 -0700860 // Get the parent and do a merge of the keys.
y57cd1952018-04-12 14:26:23 -0700861 const ResolvedBag* parent_bag = GetBag(parent_resid, child_resids);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700862 if (parent_bag == nullptr) {
863 // Failed to get the parent that should exist.
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800864 LOG(ERROR) << base::StringPrintf("Failed to find parent 0x%08x of bag 0x%08x.", parent_resid,
865 resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700866 return nullptr;
867 }
868
Adam Lesinski7ad11102016-10-28 16:39:15 -0700869 // Create the max possible entries we can make. Once we construct the bag,
870 // we will realloc to fit to size.
871 const size_t max_count = parent_bag->entry_count + dtohl(map->count);
George Burgess IV09b119f2017-07-25 15:00:04 -0700872 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
873 malloc(sizeof(ResolvedBag) + (max_count * sizeof(ResolvedBag::Entry))))};
Adam Lesinski7ad11102016-10-28 16:39:15 -0700874 ResolvedBag::Entry* new_entry = new_bag->entries;
875
876 const ResolvedBag::Entry* parent_entry = parent_bag->entries;
877 const ResolvedBag::Entry* const parent_entry_end = parent_entry + parent_bag->entry_count;
878
879 // The keys are expected to be in sorted order. Merge the two bags.
880 while (map_entry != map_entry_end && parent_entry != parent_entry_end) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500881 uint32_t child_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -0800882 if (!is_internal_resid(child_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500883 if (entry.dynamic_ref_table->lookupResourceId(&child_key) != NO_ERROR) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800884 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", child_key,
885 resid);
Adam Lesinskida431a22016-12-29 16:08:16 -0500886 return nullptr;
887 }
888 }
889
Adam Lesinski7ad11102016-10-28 16:39:15 -0700890 if (child_key <= parent_entry->key) {
891 // Use the child key if it comes before the parent
892 // or is equal to the parent (overrides).
893 new_entry->cookie = cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700894 new_entry->key = child_key;
895 new_entry->key_pool = nullptr;
896 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -0700897 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -0800898 new_entry->style = resid;
Adam Lesinski30080e22017-10-16 16:18:09 -0700899 status_t err = entry.dynamic_ref_table->lookupResourceValue(&new_entry->value);
900 if (err != NO_ERROR) {
901 LOG(ERROR) << base::StringPrintf(
902 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
903 new_entry->value.data, child_key);
904 return nullptr;
905 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700906 ++map_entry;
907 } else {
908 // Take the parent entry as-is.
909 memcpy(new_entry, parent_entry, sizeof(*new_entry));
910 }
911
912 if (child_key >= parent_entry->key) {
913 // Move to the next parent entry if we used it or it was overridden.
914 ++parent_entry;
915 }
916 // Increment to the next entry to fill.
917 ++new_entry;
918 }
919
920 // Finish the child entries if they exist.
921 while (map_entry != map_entry_end) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500922 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -0800923 if (!is_internal_resid(new_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500924 if (entry.dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800925 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
926 resid);
Adam Lesinskida431a22016-12-29 16:08:16 -0500927 return nullptr;
928 }
929 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700930 new_entry->cookie = cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -0500931 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700932 new_entry->key_pool = nullptr;
933 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -0700934 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -0800935 new_entry->style = resid;
Adam Lesinski30080e22017-10-16 16:18:09 -0700936 status_t err = entry.dynamic_ref_table->lookupResourceValue(&new_entry->value);
937 if (err != NO_ERROR) {
938 LOG(ERROR) << base::StringPrintf("Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.",
939 new_entry->value.dataType, new_entry->value.data, new_key);
940 return nullptr;
941 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700942 ++map_entry;
943 ++new_entry;
944 }
945
946 // Finish the parent entries if they exist.
947 if (parent_entry != parent_entry_end) {
948 // Take the rest of the parent entries as-is.
949 const size_t num_entries_to_copy = parent_entry_end - parent_entry;
950 memcpy(new_entry, parent_entry, num_entries_to_copy * sizeof(*new_entry));
951 new_entry += num_entries_to_copy;
952 }
953
954 // Resize the resulting array to fit.
955 const size_t actual_count = new_entry - new_bag->entries;
956 if (actual_count != max_count) {
George Burgess IV09b119f2017-07-25 15:00:04 -0700957 new_bag.reset(reinterpret_cast<ResolvedBag*>(realloc(
958 new_bag.release(), sizeof(ResolvedBag) + (actual_count * sizeof(ResolvedBag::Entry)))));
Adam Lesinski7ad11102016-10-28 16:39:15 -0700959 }
960
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700961 // Combine flags from the parent and our own bag.
962 new_bag->type_spec_flags = entry.type_flags | parent_bag->type_spec_flags;
George Burgess IV09b119f2017-07-25 15:00:04 -0700963 new_bag->entry_count = static_cast<uint32_t>(actual_count);
964 ResolvedBag* result = new_bag.get();
965 cached_bags_[resid] = std::move(new_bag);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700966 return result;
967}
968
Adam Lesinski929d6512017-01-16 19:11:19 -0800969static bool Utf8ToUtf16(const StringPiece& str, std::u16string* out) {
970 ssize_t len =
971 utf8_to_utf16_length(reinterpret_cast<const uint8_t*>(str.data()), str.size(), false);
972 if (len < 0) {
973 return false;
974 }
975 out->resize(static_cast<size_t>(len));
976 utf8_to_utf16(reinterpret_cast<const uint8_t*>(str.data()), str.size(), &*out->begin(),
977 static_cast<size_t>(len + 1));
978 return true;
979}
980
Adam Lesinski0c405242017-01-13 20:47:26 -0800981uint32_t AssetManager2::GetResourceId(const std::string& resource_name,
982 const std::string& fallback_type,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800983 const std::string& fallback_package) const {
Adam Lesinski929d6512017-01-16 19:11:19 -0800984 StringPiece package_name, type, entry;
985 if (!ExtractResourceName(resource_name, &package_name, &type, &entry)) {
986 return 0u;
987 }
988
989 if (entry.empty()) {
990 return 0u;
991 }
992
993 if (package_name.empty()) {
994 package_name = fallback_package;
995 }
996
997 if (type.empty()) {
998 type = fallback_type;
999 }
1000
1001 std::u16string type16;
1002 if (!Utf8ToUtf16(type, &type16)) {
1003 return 0u;
1004 }
1005
1006 std::u16string entry16;
1007 if (!Utf8ToUtf16(entry, &entry16)) {
1008 return 0u;
1009 }
1010
1011 const StringPiece16 kAttr16 = u"attr";
1012 const static std::u16string kAttrPrivate16 = u"^attr-private";
1013
1014 for (const PackageGroup& package_group : package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001015 for (const ConfiguredPackage& package_impl : package_group.packages_) {
1016 const LoadedPackage* package = package_impl.loaded_package_;
Adam Lesinski929d6512017-01-16 19:11:19 -08001017 if (package_name != package->GetPackageName()) {
1018 // All packages in the same group are expected to have the same package name.
1019 break;
1020 }
1021
1022 uint32_t resid = package->FindEntryByName(type16, entry16);
1023 if (resid == 0u && kAttr16 == type16) {
1024 // Private attributes in libraries (such as the framework) are sometimes encoded
1025 // under the type '^attr-private' in order to leave the ID space of public 'attr'
1026 // free for future additions. Check '^attr-private' for the same name.
1027 resid = package->FindEntryByName(kAttrPrivate16, entry16);
1028 }
1029
1030 if (resid != 0u) {
1031 return fix_package_id(resid, package_group.dynamic_ref_table.mAssignedPackageId);
1032 }
1033 }
1034 }
Adam Lesinski0c405242017-01-13 20:47:26 -08001035 return 0u;
1036}
1037
Mårten Kongstad668ec5b2018-06-11 14:11:33 +02001038void AssetManager2::RebuildFilterList(bool filter_incompatible_configs) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001039 for (PackageGroup& group : package_groups_) {
1040 for (ConfiguredPackage& impl : group.packages_) {
1041 // Destroy it.
1042 impl.filtered_configs_.~ByteBucketArray();
1043
1044 // Re-create it.
1045 new (&impl.filtered_configs_) ByteBucketArray<FilteredConfigGroup>();
1046
1047 // Create the filters here.
1048 impl.loaded_package_->ForEachTypeSpec([&](const TypeSpec* spec, uint8_t type_index) {
1049 FilteredConfigGroup& group = impl.filtered_configs_.editItemAt(type_index);
1050 const auto iter_end = spec->types + spec->type_count;
1051 for (auto iter = spec->types; iter != iter_end; ++iter) {
1052 ResTable_config this_config;
1053 this_config.copyFromDtoH((*iter)->config);
Mårten Kongstad668ec5b2018-06-11 14:11:33 +02001054 if (!filter_incompatible_configs || this_config.match(configuration_)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001055 group.configurations.push_back(this_config);
1056 group.types.push_back(*iter);
1057 }
1058 }
1059 });
1060 }
1061 }
1062}
1063
Adam Lesinski7ad11102016-10-28 16:39:15 -07001064void AssetManager2::InvalidateCaches(uint32_t diff) {
Ryan Mitchell2c4d8742019-03-04 09:41:00 -08001065 cached_bag_resid_stacks_.clear();
1066
Adam Lesinski7ad11102016-10-28 16:39:15 -07001067 if (diff == 0xffffffffu) {
1068 // Everything must go.
1069 cached_bags_.clear();
1070 return;
1071 }
1072
1073 // Be more conservative with what gets purged. Only if the bag has other possible
1074 // variations with respect to what changed (diff) should we remove it.
1075 for (auto iter = cached_bags_.cbegin(); iter != cached_bags_.cend();) {
1076 if (diff & iter->second->type_spec_flags) {
1077 iter = cached_bags_.erase(iter);
1078 } else {
1079 ++iter;
1080 }
1081 }
1082}
1083
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001084uint8_t AssetManager2::GetAssignedPackageId(const LoadedPackage* package) {
1085 for (auto& package_group : package_groups_) {
1086 for (auto& package2 : package_group.packages_) {
1087 if (package2.loaded_package_ == package) {
1088 return package_group.dynamic_ref_table.mAssignedPackageId;
1089 }
1090 }
1091 }
1092 return 0;
1093}
1094
Adam Lesinski30080e22017-10-16 16:18:09 -07001095std::unique_ptr<Theme> AssetManager2::NewTheme() {
1096 return std::unique_ptr<Theme>(new Theme(this));
1097}
1098
1099Theme::Theme(AssetManager2* asset_manager) : asset_manager_(asset_manager) {
1100}
1101
1102Theme::~Theme() = default;
1103
1104namespace {
1105
1106struct ThemeEntry {
1107 ApkAssetsCookie cookie;
1108 uint32_t type_spec_flags;
1109 Res_value value;
1110};
1111
1112struct ThemeType {
1113 int entry_count;
1114 ThemeEntry entries[0];
1115};
1116
1117constexpr size_t kTypeCount = std::numeric_limits<uint8_t>::max() + 1;
1118
1119} // namespace
1120
1121struct Theme::Package {
1122 // Each element of Type will be a dynamically sized object
1123 // allocated to have the entries stored contiguously with the Type.
1124 std::array<util::unique_cptr<ThemeType>, kTypeCount> types;
1125};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001126
1127bool Theme::ApplyStyle(uint32_t resid, bool force) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001128 ATRACE_NAME("Theme::ApplyStyle");
Adam Lesinski7ad11102016-10-28 16:39:15 -07001129
1130 const ResolvedBag* bag = asset_manager_->GetBag(resid);
1131 if (bag == nullptr) {
1132 return false;
1133 }
1134
1135 // Merge the flags from this style.
1136 type_spec_flags_ |= bag->type_spec_flags;
1137
Adam Lesinski30080e22017-10-16 16:18:09 -07001138 int last_type_idx = -1;
1139 int last_package_idx = -1;
1140 Package* last_package = nullptr;
1141 ThemeType* last_type = nullptr;
1142
1143 // Iterate backwards, because each bag is sorted in ascending key ID order, meaning we will only
1144 // need to perform one resize per type.
1145 using reverse_bag_iterator = std::reverse_iterator<const ResolvedBag::Entry*>;
1146 const auto bag_iter_end = reverse_bag_iterator(begin(bag));
1147 for (auto bag_iter = reverse_bag_iterator(end(bag)); bag_iter != bag_iter_end; ++bag_iter) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001148 const uint32_t attr_resid = bag_iter->key;
1149
Adam Lesinski30080e22017-10-16 16:18:09 -07001150 // If the resource ID passed in is not a style, the key can be some other identifier that is not
1151 // a resource ID. We should fail fast instead of operating with strange resource IDs.
Adam Lesinski929d6512017-01-16 19:11:19 -08001152 if (!is_valid_resid(attr_resid)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001153 return false;
1154 }
1155
Adam Lesinski30080e22017-10-16 16:18:09 -07001156 // We don't use the 0-based index for the type so that we can avoid doing ID validation
1157 // upon lookup. Instead, we keep space for the type ID 0 in our data structures. Since
1158 // the construction of this type is guarded with a resource ID check, it will never be
1159 // populated, and querying type ID 0 will always fail.
1160 const int package_idx = get_package_id(attr_resid);
1161 const int type_idx = get_type_id(attr_resid);
1162 const int entry_idx = get_entry_id(attr_resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001163
Adam Lesinski30080e22017-10-16 16:18:09 -07001164 if (last_package_idx != package_idx) {
1165 std::unique_ptr<Package>& package = packages_[package_idx];
1166 if (package == nullptr) {
1167 package.reset(new Package());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001168 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001169 last_package_idx = package_idx;
1170 last_package = package.get();
1171 last_type_idx = -1;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001172 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001173
1174 if (last_type_idx != type_idx) {
1175 util::unique_cptr<ThemeType>& type = last_package->types[type_idx];
1176 if (type == nullptr) {
1177 // Allocate enough memory to contain this entry_idx. Since we're iterating in reverse over
1178 // a sorted list of attributes, this shouldn't be resized again during this method call.
1179 type.reset(reinterpret_cast<ThemeType*>(
1180 calloc(sizeof(ThemeType) + (entry_idx + 1) * sizeof(ThemeEntry), 1)));
1181 type->entry_count = entry_idx + 1;
1182 } else if (entry_idx >= type->entry_count) {
1183 // Reallocate the memory to contain this entry_idx. Since we're iterating in reverse over
1184 // a sorted list of attributes, this shouldn't be resized again during this method call.
1185 const int new_count = entry_idx + 1;
1186 type.reset(reinterpret_cast<ThemeType*>(
1187 realloc(type.release(), sizeof(ThemeType) + (new_count * sizeof(ThemeEntry)))));
1188
1189 // Clear out the newly allocated space (which isn't zeroed).
1190 memset(type->entries + type->entry_count, 0,
1191 (new_count - type->entry_count) * sizeof(ThemeEntry));
1192 type->entry_count = new_count;
1193 }
1194 last_type_idx = type_idx;
1195 last_type = type.get();
1196 }
1197
1198 ThemeEntry& entry = last_type->entries[entry_idx];
1199 if (force || (entry.value.dataType == Res_value::TYPE_NULL &&
1200 entry.value.data != Res_value::DATA_NULL_EMPTY)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001201 entry.cookie = bag_iter->cookie;
1202 entry.type_spec_flags |= bag->type_spec_flags;
1203 entry.value = bag_iter->value;
1204 }
1205 }
1206 return true;
1207}
1208
1209ApkAssetsCookie Theme::GetAttribute(uint32_t resid, Res_value* out_value,
1210 uint32_t* out_flags) const {
Adam Lesinski30080e22017-10-16 16:18:09 -07001211 int cnt = 20;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001212
1213 uint32_t type_spec_flags = 0u;
1214
Adam Lesinski30080e22017-10-16 16:18:09 -07001215 do {
1216 const int package_idx = get_package_id(resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001217 const Package* package = packages_[package_idx].get();
Adam Lesinski30080e22017-10-16 16:18:09 -07001218 if (package != nullptr) {
1219 // The themes are constructed with a 1-based type ID, so no need to decrement here.
1220 const int type_idx = get_type_id(resid);
1221 const ThemeType* type = package->types[type_idx].get();
1222 if (type != nullptr) {
1223 const int entry_idx = get_entry_id(resid);
1224 if (entry_idx < type->entry_count) {
1225 const ThemeEntry& entry = type->entries[entry_idx];
1226 type_spec_flags |= entry.type_spec_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001227
Adam Lesinski30080e22017-10-16 16:18:09 -07001228 if (entry.value.dataType == Res_value::TYPE_ATTRIBUTE) {
1229 if (cnt > 0) {
1230 cnt--;
1231 resid = entry.value.data;
1232 continue;
1233 }
1234 return kInvalidCookie;
1235 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001236
Adam Lesinski30080e22017-10-16 16:18:09 -07001237 // @null is different than @empty.
1238 if (entry.value.dataType == Res_value::TYPE_NULL &&
1239 entry.value.data != Res_value::DATA_NULL_EMPTY) {
1240 return kInvalidCookie;
1241 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001242
Adam Lesinski30080e22017-10-16 16:18:09 -07001243 *out_value = entry.value;
Adam Lesinskida431a22016-12-29 16:08:16 -05001244 *out_flags = type_spec_flags;
Adam Lesinski30080e22017-10-16 16:18:09 -07001245 return entry.cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -05001246 }
Adam Lesinskida431a22016-12-29 16:08:16 -05001247 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001248 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001249 break;
1250 } while (true);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001251 return kInvalidCookie;
1252}
1253
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001254ApkAssetsCookie Theme::ResolveAttributeReference(ApkAssetsCookie cookie, Res_value* in_out_value,
1255 ResTable_config* in_out_selected_config,
1256 uint32_t* in_out_type_spec_flags,
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001257 uint32_t* out_last_ref) const {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001258 if (in_out_value->dataType == Res_value::TYPE_ATTRIBUTE) {
1259 uint32_t new_flags;
1260 cookie = GetAttribute(in_out_value->data, in_out_value, &new_flags);
1261 if (cookie == kInvalidCookie) {
1262 return kInvalidCookie;
1263 }
1264
1265 if (in_out_type_spec_flags != nullptr) {
1266 *in_out_type_spec_flags |= new_flags;
1267 }
1268 }
1269 return asset_manager_->ResolveReference(cookie, in_out_value, in_out_selected_config,
1270 in_out_type_spec_flags, out_last_ref);
1271}
1272
Adam Lesinski7ad11102016-10-28 16:39:15 -07001273void Theme::Clear() {
1274 type_spec_flags_ = 0u;
1275 for (std::unique_ptr<Package>& package : packages_) {
1276 package.reset();
1277 }
1278}
1279
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001280void Theme::SetTo(const Theme& o) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001281 if (this == &o) {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001282 return;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001283 }
1284
Adam Lesinski7ad11102016-10-28 16:39:15 -07001285 type_spec_flags_ = o.type_spec_flags_;
1286
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001287 if (asset_manager_ == o.asset_manager_) {
1288 // The theme comes from the same asset manager so all theme data can be copied exactly
1289 for (size_t p = 0; p < packages_.size(); p++) {
1290 const Package *package = o.packages_[p].get();
1291 if (package == nullptr) {
1292 // The other theme doesn't have this package, clear ours.
1293 packages_[p].reset();
Adam Lesinski7ad11102016-10-28 16:39:15 -07001294 continue;
1295 }
1296
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001297 if (packages_[p] == nullptr) {
1298 // The other theme has this package, but we don't. Make one.
1299 packages_[p].reset(new Package());
1300 }
1301
1302 for (size_t t = 0; t < package->types.size(); t++) {
1303 const ThemeType *type = package->types[t].get();
1304 if (type == nullptr) {
1305 // The other theme doesn't have this type, clear ours.
1306 packages_[p]->types[t].reset();
1307 continue;
1308 }
1309
1310 // Create a new type and update it to theirs.
1311 const size_t type_alloc_size = sizeof(ThemeType) + (type->entry_count * sizeof(ThemeEntry));
1312 void *copied_data = malloc(type_alloc_size);
1313 memcpy(copied_data, type, type_alloc_size);
1314 packages_[p]->types[t].reset(reinterpret_cast<ThemeType *>(copied_data));
1315 }
1316 }
1317 } else {
1318 std::map<ApkAssetsCookie, ApkAssetsCookie> src_to_dest_asset_cookies;
1319 typedef std::map<int, int> SourceToDestinationRuntimePackageMap;
1320 std::map<ApkAssetsCookie, SourceToDestinationRuntimePackageMap> src_asset_cookie_id_map;
1321
1322 // Determine which ApkAssets are loaded in both theme AssetManagers
1323 std::vector<const ApkAssets*> src_assets = o.asset_manager_->GetApkAssets();
1324 for (size_t i = 0; i < src_assets.size(); i++) {
1325 const ApkAssets* src_asset = src_assets[i];
1326
1327 std::vector<const ApkAssets*> dest_assets = asset_manager_->GetApkAssets();
1328 for (size_t j = 0; j < dest_assets.size(); j++) {
1329 const ApkAssets* dest_asset = dest_assets[j];
1330
1331 // Map the runtime package of the source apk asset to the destination apk asset
1332 if (src_asset->GetPath() == dest_asset->GetPath()) {
1333 const std::vector<std::unique_ptr<const LoadedPackage>>& src_packages =
1334 src_asset->GetLoadedArsc()->GetPackages();
1335 const std::vector<std::unique_ptr<const LoadedPackage>>& dest_packages =
1336 dest_asset->GetLoadedArsc()->GetPackages();
1337
1338 SourceToDestinationRuntimePackageMap package_map;
1339
1340 // The source and destination package should have the same number of packages loaded in
1341 // the same order.
1342 const size_t N = src_packages.size();
1343 CHECK(N == dest_packages.size())
1344 << " LoadedArsc " << src_asset->GetPath() << " differs number of packages.";
1345 for (size_t p = 0; p < N; p++) {
1346 auto& src_package = src_packages[p];
1347 auto& dest_package = dest_packages[p];
1348 CHECK(src_package->GetPackageName() == dest_package->GetPackageName())
1349 << " Package " << src_package->GetPackageName() << " differs in load order.";
1350
1351 int src_package_id = o.asset_manager_->GetAssignedPackageId(src_package.get());
1352 int dest_package_id = asset_manager_->GetAssignedPackageId(dest_package.get());
1353 package_map[src_package_id] = dest_package_id;
1354 }
1355
1356 src_to_dest_asset_cookies.insert(std::pair<ApkAssetsCookie, ApkAssetsCookie>(i, j));
1357 src_asset_cookie_id_map.insert(
1358 std::pair<ApkAssetsCookie, SourceToDestinationRuntimePackageMap>(i, package_map));
1359 break;
1360 }
1361 }
1362 }
1363
1364 // Reset the data in the destination theme
1365 for (size_t p = 0; p < packages_.size(); p++) {
1366 if (packages_[p] != nullptr) {
1367 packages_[p].reset();
1368 }
1369 }
1370
1371 for (size_t p = 0; p < packages_.size(); p++) {
1372 const Package *package = o.packages_[p].get();
1373 if (package == nullptr) {
1374 continue;
1375 }
1376
1377 for (size_t t = 0; t < package->types.size(); t++) {
1378 const ThemeType *type = package->types[t].get();
1379 if (type == nullptr) {
1380 continue;
1381 }
1382
1383 for (size_t e = 0; e < type->entry_count; e++) {
1384 const ThemeEntry &entry = type->entries[e];
1385 if (entry.value.dataType == Res_value::TYPE_NULL &&
1386 entry.value.data != Res_value::DATA_NULL_EMPTY) {
1387 continue;
1388 }
1389
Ryan Mitchellb85d9b22018-11-19 12:11:38 -08001390 // If the attribute value represents an attribute or reference, the package id of the
1391 // value needs to be rewritten to the package id of the value in the destination
1392 uint32_t attribue_data = entry.value.data;
1393 if ((entry.value.dataType == Res_value::TYPE_ATTRIBUTE
1394 || entry.value.dataType == Res_value::TYPE_REFERENCE
1395 || entry.value.dataType == Res_value::TYPE_DYNAMIC_ATTRIBUTE
1396 || entry.value.dataType == Res_value::TYPE_DYNAMIC_REFERENCE)
1397 && attribue_data != 0x0) {
1398
1399 // Determine the package id of the reference in the destination AssetManager
1400 auto value_package_map = src_asset_cookie_id_map.find(entry.cookie);
1401 if (value_package_map == src_asset_cookie_id_map.end()) {
1402 continue;
1403 }
1404
1405 auto value_dest_package = value_package_map->second.find(
1406 get_package_id(entry.value.data));
1407 if (value_dest_package == value_package_map->second.end()) {
1408 continue;
1409 }
1410
1411 attribue_data = fix_package_id(entry.value.data, value_dest_package->second);
1412 }
1413
1414 // The package id of the attribute needs to be rewritten to the package id of the
1415 // attribute in the destination
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001416 int attribute_dest_package_id = p;
1417 if (attribute_dest_package_id != 0x01) {
1418 // Find the cookie of the attribute resource id
1419 FindEntryResult attribute_entry_result;
1420 ApkAssetsCookie attribute_cookie =
Ryan Mitchella55dc2e2019-01-24 10:58:23 -08001421 o.asset_manager_->FindEntry(make_resid(p, t, e), 0 /* density_override */ ,
1422 true /* stop_at_first_match */,
1423 true /* ignore_configuration */,
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001424 &attribute_entry_result);
1425
1426 // Determine the package id of the attribute in the destination AssetManager
1427 auto attribute_package_map = src_asset_cookie_id_map.find(attribute_cookie);
1428 if (attribute_package_map == src_asset_cookie_id_map.end()) {
1429 continue;
1430 }
1431 auto attribute_dest_package = attribute_package_map->second.find(
1432 attribute_dest_package_id);
1433 if (attribute_dest_package == attribute_package_map->second.end()) {
1434 continue;
1435 }
1436 attribute_dest_package_id = attribute_dest_package->second;
1437 }
1438
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001439 // Lazily instantiate the destination package
1440 std::unique_ptr<Package>& dest_package = packages_[attribute_dest_package_id];
1441 if (dest_package == nullptr) {
1442 dest_package.reset(new Package());
1443 }
1444
1445 // Lazily instantiate and resize the destination type
1446 util::unique_cptr<ThemeType>& dest_type = dest_package->types[t];
1447 if (dest_type == nullptr || dest_type->entry_count < type->entry_count) {
1448 const size_t type_alloc_size = sizeof(ThemeType)
1449 + (type->entry_count * sizeof(ThemeEntry));
1450 void* dest_data = malloc(type_alloc_size);
1451 memset(dest_data, 0, type->entry_count * sizeof(ThemeEntry));
1452
1453 // Copy the existing destination type values if the type is resized
1454 if (dest_type != nullptr) {
1455 memcpy(dest_data, type, sizeof(ThemeType)
1456 + (dest_type->entry_count * sizeof(ThemeEntry)));
1457 }
1458
1459 dest_type.reset(reinterpret_cast<ThemeType *>(dest_data));
1460 dest_type->entry_count = type->entry_count;
1461 }
1462
1463 // Find the cookie of the value in the destination
1464 auto value_dest_cookie = src_to_dest_asset_cookies.find(entry.cookie);
1465 if (value_dest_cookie == src_to_dest_asset_cookies.end()) {
1466 continue;
1467 }
1468
1469 dest_type->entries[e].cookie = value_dest_cookie->second;
1470 dest_type->entries[e].value.dataType = entry.value.dataType;
1471 dest_type->entries[e].value.data = attribue_data;
1472 dest_type->entries[e].type_spec_flags = entry.type_spec_flags;
1473 }
1474 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001475 }
1476 }
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001477}
1478
1479void Theme::Dump() const {
1480 base::ScopedLogSeverity _log(base::INFO);
1481 LOG(INFO) << base::StringPrintf("Theme(this=%p, AssetManager2=%p)", this, asset_manager_);
1482
1483 for (int p = 0; p < packages_.size(); p++) {
1484 auto& package = packages_[p];
1485 if (package == nullptr) {
1486 continue;
1487 }
1488
1489 for (int t = 0; t < package->types.size(); t++) {
1490 auto& type = package->types[t];
1491 if (type == nullptr) {
1492 continue;
1493 }
1494
1495 for (int e = 0; e < type->entry_count; e++) {
1496 auto& entry = type->entries[e];
1497 if (entry.value.dataType == Res_value::TYPE_NULL &&
1498 entry.value.data != Res_value::DATA_NULL_EMPTY) {
1499 continue;
1500 }
1501
1502 LOG(INFO) << base::StringPrintf(" entry(0x%08x)=(0x%08x) type=(0x%02x), cookie(%d)",
1503 make_resid(p, t, e), entry.value.data,
1504 entry.value.dataType, entry.cookie);
1505 }
1506 }
1507 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001508}
1509
1510} // namespace android