blob: 66d8542553d2a8f63f97acf87749f441ece51f37 [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
Adam Lesinski929d6512017-01-16 19:11:19 -080038#include "androidfw/ResourceUtils.h"
39
Adam Lesinski7ad11102016-10-28 16:39:15 -070040namespace android {
41
Adam Lesinskibebfcc42018-02-12 14:27:46 -080042struct FindEntryResult {
43 // A pointer to the resource table entry for this resource.
44 // If the size of the entry is > sizeof(ResTable_entry), it can be cast to
45 // a ResTable_map_entry and processed as a bag/map.
46 const ResTable_entry* entry;
47
48 // The configuration for which the resulting entry was defined. This is already swapped to host
49 // endianness.
50 ResTable_config config;
51
52 // The bitmask of configuration axis with which the resource value varies.
53 uint32_t type_flags;
54
55 // The dynamic package ID map for the package from which this resource came from.
56 const DynamicRefTable* dynamic_ref_table;
57
58 // The string pool reference to the type's name. This uses a different string pool than
59 // the global string pool, but this is hidden from the caller.
60 StringPoolRef type_string_ref;
61
62 // The string pool reference to the entry's name. This uses a different string pool than
63 // the global string pool, but this is hidden from the caller.
64 StringPoolRef entry_string_ref;
65};
66
Adam Lesinski970bd8d2017-09-25 13:21:55 -070067AssetManager2::AssetManager2() {
68 memset(&configuration_, 0, sizeof(configuration_));
69}
Adam Lesinski7ad11102016-10-28 16:39:15 -070070
71bool AssetManager2::SetApkAssets(const std::vector<const ApkAssets*>& apk_assets,
Mårten Kongstad668ec5b2018-06-11 14:11:33 +020072 bool invalidate_caches, bool filter_incompatible_configs) {
Adam Lesinski7ad11102016-10-28 16:39:15 -070073 apk_assets_ = apk_assets;
Adam Lesinskida431a22016-12-29 16:08:16 -050074 BuildDynamicRefTable();
Mårten Kongstad668ec5b2018-06-11 14:11:33 +020075 RebuildFilterList(filter_incompatible_configs);
Adam Lesinski7ad11102016-10-28 16:39:15 -070076 if (invalidate_caches) {
77 InvalidateCaches(static_cast<uint32_t>(-1));
78 }
79 return true;
80}
81
Adam Lesinskida431a22016-12-29 16:08:16 -050082void AssetManager2::BuildDynamicRefTable() {
83 package_groups_.clear();
84 package_ids_.fill(0xff);
85
86 // 0x01 is reserved for the android package.
87 int next_package_id = 0x02;
88 const size_t apk_assets_count = apk_assets_.size();
89 for (size_t i = 0; i < apk_assets_count; i++) {
Adam Lesinski970bd8d2017-09-25 13:21:55 -070090 const LoadedArsc* loaded_arsc = apk_assets_[i]->GetLoadedArsc();
91
92 for (const std::unique_ptr<const LoadedPackage>& package : loaded_arsc->GetPackages()) {
Adam Lesinskida431a22016-12-29 16:08:16 -050093 // Get the package ID or assign one if a shared library.
94 int package_id;
95 if (package->IsDynamic()) {
96 package_id = next_package_id++;
97 } else {
98 package_id = package->GetPackageId();
99 }
100
101 // Add the mapping for package ID to index if not present.
102 uint8_t idx = package_ids_[package_id];
103 if (idx == 0xff) {
104 package_ids_[package_id] = idx = static_cast<uint8_t>(package_groups_.size());
105 package_groups_.push_back({});
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800106 DynamicRefTable& ref_table = package_groups_.back().dynamic_ref_table;
107 ref_table.mAssignedPackageId = package_id;
108 ref_table.mAppAsLib = package->IsDynamic() && package->GetPackageId() == 0x7f;
Adam Lesinskida431a22016-12-29 16:08:16 -0500109 }
110 PackageGroup* package_group = &package_groups_[idx];
111
112 // Add the package and to the set of packages with the same ID.
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800113 package_group->packages_.push_back(ConfiguredPackage{package.get(), {}});
Adam Lesinskida431a22016-12-29 16:08:16 -0500114 package_group->cookies_.push_back(static_cast<ApkAssetsCookie>(i));
115
116 // Add the package name -> build time ID mappings.
117 for (const DynamicPackageEntry& entry : package->GetDynamicPackageMap()) {
118 String16 package_name(entry.package_name.c_str(), entry.package_name.size());
119 package_group->dynamic_ref_table.mEntries.replaceValueFor(
120 package_name, static_cast<uint8_t>(entry.package_id));
121 }
122 }
123 }
124
125 // Now assign the runtime IDs so that we have a build-time to runtime ID map.
126 const auto package_groups_end = package_groups_.end();
127 for (auto iter = package_groups_.begin(); iter != package_groups_end; ++iter) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800128 const std::string& package_name = iter->packages_[0].loaded_package_->GetPackageName();
Adam Lesinskida431a22016-12-29 16:08:16 -0500129 for (auto iter2 = package_groups_.begin(); iter2 != package_groups_end; ++iter2) {
130 iter2->dynamic_ref_table.addMapping(String16(package_name.c_str(), package_name.size()),
131 iter->dynamic_ref_table.mAssignedPackageId);
132 }
133 }
134}
135
136void AssetManager2::DumpToLog() const {
137 base::ScopedLogSeverity _log(base::INFO);
138
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800139 LOG(INFO) << base::StringPrintf("AssetManager2(this=%p)", this);
140
Adam Lesinskida431a22016-12-29 16:08:16 -0500141 std::string list;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800142 for (const auto& apk_assets : apk_assets_) {
143 base::StringAppendF(&list, "%s,", apk_assets->GetPath().c_str());
144 }
145 LOG(INFO) << "ApkAssets: " << list;
146
147 list = "";
Adam Lesinskida431a22016-12-29 16:08:16 -0500148 for (size_t i = 0; i < package_ids_.size(); i++) {
149 if (package_ids_[i] != 0xff) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800150 base::StringAppendF(&list, "%02x -> %d, ", (int)i, package_ids_[i]);
Adam Lesinskida431a22016-12-29 16:08:16 -0500151 }
152 }
153 LOG(INFO) << "Package ID map: " << list;
154
Adam Lesinski0dd36992018-01-25 15:38:38 -0800155 for (const auto& package_group: package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800156 list = "";
157 for (const auto& package : package_group.packages_) {
158 const LoadedPackage* loaded_package = package.loaded_package_;
159 base::StringAppendF(&list, "%s(%02x%s), ", loaded_package->GetPackageName().c_str(),
160 loaded_package->GetPackageId(),
161 (loaded_package->IsDynamic() ? " dynamic" : ""));
162 }
163 LOG(INFO) << base::StringPrintf("PG (%02x): ",
164 package_group.dynamic_ref_table.mAssignedPackageId)
165 << list;
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800166
167 for (size_t i = 0; i < 256; i++) {
168 if (package_group.dynamic_ref_table.mLookupTable[i] != 0) {
169 LOG(INFO) << base::StringPrintf(" e[0x%02x] -> 0x%02x", (uint8_t) i,
170 package_group.dynamic_ref_table.mLookupTable[i]);
171 }
172 }
Adam Lesinskida431a22016-12-29 16:08:16 -0500173 }
174}
Adam Lesinski7ad11102016-10-28 16:39:15 -0700175
176const ResStringPool* AssetManager2::GetStringPoolForCookie(ApkAssetsCookie cookie) const {
177 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
178 return nullptr;
179 }
180 return apk_assets_[cookie]->GetLoadedArsc()->GetStringPool();
181}
182
Adam Lesinskida431a22016-12-29 16:08:16 -0500183const DynamicRefTable* AssetManager2::GetDynamicRefTableForPackage(uint32_t package_id) const {
184 if (package_id >= package_ids_.size()) {
185 return nullptr;
186 }
187
188 const size_t idx = package_ids_[package_id];
189 if (idx == 0xff) {
190 return nullptr;
191 }
192 return &package_groups_[idx].dynamic_ref_table;
193}
194
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800195const DynamicRefTable* AssetManager2::GetDynamicRefTableForCookie(ApkAssetsCookie cookie) const {
196 for (const PackageGroup& package_group : package_groups_) {
197 for (const ApkAssetsCookie& package_cookie : package_group.cookies_) {
198 if (package_cookie == cookie) {
199 return &package_group.dynamic_ref_table;
200 }
201 }
202 }
203 return nullptr;
204}
205
Mårten Kongstadc92c4dd2019-02-05 01:29:59 +0100206const std::unordered_map<std::string, std::string>*
207 AssetManager2::GetOverlayableMapForPackage(uint32_t package_id) const {
208
209 if (package_id >= package_ids_.size()) {
210 return nullptr;
211 }
212
213 const size_t idx = package_ids_[package_id];
214 if (idx == 0xff) {
215 return nullptr;
216 }
217
218 const PackageGroup& package_group = package_groups_[idx];
219 if (package_group.packages_.size() == 0) {
220 return nullptr;
221 }
222
223 const auto loaded_package = package_group.packages_[0].loaded_package_;
224 return &loaded_package->GetOverlayableMap();
225}
226
Adam Lesinski7ad11102016-10-28 16:39:15 -0700227void AssetManager2::SetConfiguration(const ResTable_config& configuration) {
228 const int diff = configuration_.diff(configuration);
229 configuration_ = configuration;
230
231 if (diff) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800232 RebuildFilterList();
Adam Lesinski7ad11102016-10-28 16:39:15 -0700233 InvalidateCaches(static_cast<uint32_t>(diff));
234 }
235}
236
Adam Lesinski0c405242017-01-13 20:47:26 -0800237std::set<ResTable_config> AssetManager2::GetResourceConfigurations(bool exclude_system,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800238 bool exclude_mipmap) const {
239 ATRACE_NAME("AssetManager::GetResourceConfigurations");
Adam Lesinski0c405242017-01-13 20:47:26 -0800240 std::set<ResTable_config> configurations;
241 for (const PackageGroup& package_group : package_groups_) {
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800242 bool found_system_package = false;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800243 for (const ConfiguredPackage& package : package_group.packages_) {
244 if (exclude_system && package.loaded_package_->IsSystem()) {
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800245 found_system_package = true;
Adam Lesinski0c405242017-01-13 20:47:26 -0800246 continue;
247 }
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800248
249 if (exclude_system && package.loaded_package_->IsOverlay() && found_system_package) {
250 // Overlays must appear after the target package to take effect. Any overlay found in the
251 // same package as a system package is able to overlay system resources.
252 continue;
253 }
254
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800255 package.loaded_package_->CollectConfigurations(exclude_mipmap, &configurations);
Adam Lesinski0c405242017-01-13 20:47:26 -0800256 }
257 }
258 return configurations;
259}
260
261std::set<std::string> AssetManager2::GetResourceLocales(bool exclude_system,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800262 bool merge_equivalent_languages) const {
263 ATRACE_NAME("AssetManager::GetResourceLocales");
Adam Lesinski0c405242017-01-13 20:47:26 -0800264 std::set<std::string> locales;
265 for (const PackageGroup& package_group : package_groups_) {
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800266 bool found_system_package = false;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800267 for (const ConfiguredPackage& package : package_group.packages_) {
268 if (exclude_system && package.loaded_package_->IsSystem()) {
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800269 found_system_package = true;
Adam Lesinski0c405242017-01-13 20:47:26 -0800270 continue;
271 }
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800272
273 if (exclude_system && package.loaded_package_->IsOverlay() && found_system_package) {
274 // Overlays must appear after the target package to take effect. Any overlay found in the
275 // same package as a system package is able to overlay system resources.
276 continue;
277 }
278
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800279 package.loaded_package_->CollectLocales(merge_equivalent_languages, &locales);
Adam Lesinski0c405242017-01-13 20:47:26 -0800280 }
281 }
282 return locales;
283}
284
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800285std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename,
286 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700287 const std::string new_path = "assets/" + filename;
288 return OpenNonAsset(new_path, mode);
289}
290
291std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename, ApkAssetsCookie cookie,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800292 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700293 const std::string new_path = "assets/" + filename;
294 return OpenNonAsset(new_path, cookie, mode);
295}
296
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800297std::unique_ptr<AssetDir> AssetManager2::OpenDir(const std::string& dirname) const {
298 ATRACE_NAME("AssetManager::OpenDir");
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800299
300 std::string full_path = "assets/" + dirname;
301 std::unique_ptr<SortedVector<AssetDir::FileInfo>> files =
302 util::make_unique<SortedVector<AssetDir::FileInfo>>();
303
304 // Start from the back.
305 for (auto iter = apk_assets_.rbegin(); iter != apk_assets_.rend(); ++iter) {
306 const ApkAssets* apk_assets = *iter;
307
308 auto func = [&](const StringPiece& name, FileType type) {
309 AssetDir::FileInfo info;
310 info.setFileName(String8(name.data(), name.size()));
311 info.setFileType(type);
312 info.setSourceName(String8(apk_assets->GetPath().c_str()));
313 files->add(info);
314 };
315
316 if (!apk_assets->ForEachFile(full_path, func)) {
317 return {};
318 }
319 }
320
321 std::unique_ptr<AssetDir> asset_dir = util::make_unique<AssetDir>();
322 asset_dir->setFileList(files.release());
323 return asset_dir;
324}
325
Adam Lesinski7ad11102016-10-28 16:39:15 -0700326// Search in reverse because that's how we used to do it and we need to preserve behaviour.
327// This is unfortunate, because ClassLoaders delegate to the parent first, so the order
328// is inconsistent for split APKs.
329std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
330 Asset::AccessMode mode,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800331 ApkAssetsCookie* out_cookie) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700332 for (int32_t i = apk_assets_.size() - 1; i >= 0; i--) {
333 std::unique_ptr<Asset> asset = apk_assets_[i]->Open(filename, mode);
334 if (asset) {
335 if (out_cookie != nullptr) {
336 *out_cookie = i;
337 }
338 return asset;
339 }
340 }
341
342 if (out_cookie != nullptr) {
343 *out_cookie = kInvalidCookie;
344 }
345 return {};
346}
347
348std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800349 ApkAssetsCookie cookie,
350 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700351 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
352 return {};
353 }
354 return apk_assets_[cookie]->Open(filename, mode);
355}
356
357ApkAssetsCookie AssetManager2::FindEntry(uint32_t resid, uint16_t density_override,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800358 bool /*stop_at_first_match*/,
359 FindEntryResult* out_entry) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700360 // Might use this if density_override != 0.
361 ResTable_config density_override_config;
362
363 // Select our configuration or generate a density override configuration.
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800364 const ResTable_config* desired_config = &configuration_;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700365 if (density_override != 0 && density_override != configuration_.density) {
366 density_override_config = configuration_;
367 density_override_config.density = density_override;
368 desired_config = &density_override_config;
369 }
370
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800371 if (!is_valid_resid(resid)) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500372 LOG(ERROR) << base::StringPrintf("Invalid ID 0x%08x.", resid);
373 return kInvalidCookie;
374 }
375
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800376 const uint32_t package_id = get_package_id(resid);
377 const uint8_t type_idx = get_type_id(resid) - 1;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800378 const uint16_t entry_idx = get_entry_id(resid);
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800379
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800380 const uint8_t package_idx = package_ids_[package_id];
381 if (package_idx == 0xff) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500382 LOG(ERROR) << base::StringPrintf("No package ID %02x found for ID 0x%08x.", package_id, resid);
383 return kInvalidCookie;
384 }
385
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800386 const PackageGroup& package_group = package_groups_[package_idx];
Adam Lesinskib8b3a262018-02-09 11:01:45 -0800387 const size_t package_count = package_group.packages_.size();
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800388
389 ApkAssetsCookie best_cookie = kInvalidCookie;
390 const LoadedPackage* best_package = nullptr;
391 const ResTable_type* best_type = nullptr;
392 const ResTable_config* best_config = nullptr;
393 ResTable_config best_config_copy;
394 uint32_t best_offset = 0u;
395 uint32_t type_flags = 0u;
396
Winson2f3669b2019-01-11 11:28:34 -0800397 Resolution::Step::Type resolution_type;
398 std::vector<Resolution::Step> resolution_steps;
399
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800400 // If desired_config is the same as the set configuration, then we can use our filtered list
401 // and we don't need to match the configurations, since they already matched.
402 const bool use_fast_path = desired_config == &configuration_;
403
404 for (size_t pi = 0; pi < package_count; pi++) {
405 const ConfiguredPackage& loaded_package_impl = package_group.packages_[pi];
406 const LoadedPackage* loaded_package = loaded_package_impl.loaded_package_;
407 ApkAssetsCookie cookie = package_group.cookies_[pi];
408
409 // If the type IDs are offset in this package, we need to take that into account when searching
410 // for a type.
411 const TypeSpec* type_spec = loaded_package->GetTypeSpecByTypeIndex(type_idx);
412 if (UNLIKELY(type_spec == nullptr)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700413 continue;
414 }
415
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800416 uint16_t local_entry_idx = entry_idx;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700417
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800418 // If there is an IDMAP supplied with this package, translate the entry ID.
419 if (type_spec->idmap_entries != nullptr) {
420 if (!LoadedIdmap::Lookup(type_spec->idmap_entries, local_entry_idx, &local_entry_idx)) {
421 // There is no mapping, so the resource is not meant to be in this overlay package.
422 continue;
423 }
424 }
425
426 type_flags |= type_spec->GetFlagsForEntryIndex(local_entry_idx);
427
428 // If the package is an overlay, then even configurations that are the same MUST be chosen.
429 const bool package_is_overlay = loaded_package->IsOverlay();
430
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800431 if (use_fast_path) {
Winson2f3669b2019-01-11 11:28:34 -0800432 const FilteredConfigGroup& filtered_group = loaded_package_impl.filtered_configs_[type_idx];
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800433 const std::vector<ResTable_config>& candidate_configs = filtered_group.configurations;
434 const size_t type_count = candidate_configs.size();
435 for (uint32_t i = 0; i < type_count; i++) {
436 const ResTable_config& this_config = candidate_configs[i];
437
438 // We can skip calling ResTable_config::match() because we know that all candidate
439 // configurations that do NOT match have been filtered-out.
Winson2f3669b2019-01-11 11:28:34 -0800440 if (best_config == nullptr) {
441 resolution_type = Resolution::Step::Type::INITIAL;
442 } else if (this_config.isBetterThan(*best_config, desired_config)) {
443 resolution_type = Resolution::Step::Type::BETTER_MATCH;
444 } else if (package_is_overlay && this_config.compare(*best_config) == 0) {
445 resolution_type = Resolution::Step::Type::OVERLAID;
446 } else {
447 continue;
448 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800449
Winson2f3669b2019-01-11 11:28:34 -0800450 // The configuration matches and is better than the previous selection.
451 // Find the entry value if it exists for this configuration.
452 const ResTable_type* type = filtered_group.types[i];
453 const uint32_t offset = LoadedPackage::GetEntryOffset(type, local_entry_idx);
454 if (offset == ResTable_type::NO_ENTRY) {
455 continue;
456 }
457
458 best_cookie = cookie;
459 best_package = loaded_package;
460 best_type = type;
461 best_config = &this_config;
462 best_offset = offset;
463
464 if (resource_resolution_logging_enabled_) {
465 resolution_steps.push_back(Resolution::Step{resolution_type,
466 this_config.toString(),
467 &loaded_package->GetPackageName()});
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800468 }
469 }
470 } else {
471 // This is the slower path, which doesn't use the filtered list of configurations.
472 // Here we must read the ResTable_config from the mmapped APK, convert it to host endianness
473 // and fill in any new fields that did not exist when the APK was compiled.
474 // Furthermore when selecting configurations we can't just record the pointer to the
475 // ResTable_config, we must copy it.
476 const auto iter_end = type_spec->types + type_spec->type_count;
477 for (auto iter = type_spec->types; iter != iter_end; ++iter) {
478 ResTable_config this_config;
479 this_config.copyFromDtoH((*iter)->config);
480
Winson2f3669b2019-01-11 11:28:34 -0800481 if (!this_config.match(*desired_config)) {
482 continue;
483 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800484
Winson2f3669b2019-01-11 11:28:34 -0800485 if (best_config == nullptr) {
486 resolution_type = Resolution::Step::Type::INITIAL;
487 } else if (this_config.isBetterThan(*best_config, desired_config)) {
488 resolution_type = Resolution::Step::Type::BETTER_MATCH;
489 } else if (package_is_overlay && this_config.compare(*best_config) == 0) {
490 resolution_type = Resolution::Step::Type::OVERLAID;
491 } else {
492 continue;
493 }
494
495 // The configuration matches and is better than the previous selection.
496 // Find the entry value if it exists for this configuration.
497 const uint32_t offset = LoadedPackage::GetEntryOffset(*iter, local_entry_idx);
498 if (offset == ResTable_type::NO_ENTRY) {
499 continue;
500 }
501
502 best_cookie = cookie;
503 best_package = loaded_package;
504 best_type = *iter;
505 best_config_copy = this_config;
506 best_config = &best_config_copy;
507 best_offset = offset;
508
509 if (resource_resolution_logging_enabled_) {
510 resolution_steps.push_back(Resolution::Step{resolution_type,
511 this_config.toString(),
512 &loaded_package->GetPackageName()});
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800513 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700514 }
515 }
516 }
517
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800518 if (UNLIKELY(best_cookie == kInvalidCookie)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700519 return kInvalidCookie;
520 }
521
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800522 const ResTable_entry* best_entry = LoadedPackage::GetEntryFromOffset(best_type, best_offset);
523 if (UNLIKELY(best_entry == nullptr)) {
524 return kInvalidCookie;
525 }
526
527 out_entry->entry = best_entry;
528 out_entry->config = *best_config;
529 out_entry->type_flags = type_flags;
530 out_entry->type_string_ref = StringPoolRef(best_package->GetTypeStringPool(), best_type->id - 1);
531 out_entry->entry_string_ref =
532 StringPoolRef(best_package->GetKeyStringPool(), best_entry->key.index);
Adam Lesinskida431a22016-12-29 16:08:16 -0500533 out_entry->dynamic_ref_table = &package_group.dynamic_ref_table;
Winson2f3669b2019-01-11 11:28:34 -0800534
535 if (resource_resolution_logging_enabled_) {
536 last_resolution.resid = resid;
537 last_resolution.cookie = best_cookie;
538 last_resolution.steps = resolution_steps;
539
540 // Cache only the type/entry refs since that's all that's needed to build name
541 last_resolution.type_string_ref =
542 StringPoolRef(best_package->GetTypeStringPool(), best_type->id - 1);
543 last_resolution.entry_string_ref =
544 StringPoolRef(best_package->GetKeyStringPool(), best_entry->key.index);
545 }
546
Adam Lesinskida431a22016-12-29 16:08:16 -0500547 return best_cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700548}
549
Winson2f3669b2019-01-11 11:28:34 -0800550void AssetManager2::SetResourceResolutionLoggingEnabled(bool enabled) {
551 resource_resolution_logging_enabled_ = enabled;
552
553 if (!enabled) {
554 last_resolution.cookie = kInvalidCookie;
555 last_resolution.resid = 0;
556 last_resolution.steps.clear();
557 last_resolution.type_string_ref = StringPoolRef();
558 last_resolution.entry_string_ref = StringPoolRef();
559 }
560}
561
562std::string AssetManager2::GetLastResourceResolution() const {
563 if (!resource_resolution_logging_enabled_) {
564 LOG(ERROR) << "Must enable resource resolution logging before getting path.";
565 return std::string();
566 }
567
568 auto cookie = last_resolution.cookie;
569 if (cookie == kInvalidCookie) {
570 LOG(ERROR) << "AssetManager hasn't resolved a resource to read resolution path.";
571 return std::string();
572 }
573
574 uint32_t resid = last_resolution.resid;
575 std::vector<Resolution::Step>& steps = last_resolution.steps;
576
577 ResourceName resource_name;
578 std::string resource_name_string;
579
580 const LoadedPackage* package =
581 apk_assets_[cookie]->GetLoadedArsc()->GetPackageById(get_package_id(resid));
582
583 if (package != nullptr) {
584 ToResourceName(last_resolution.type_string_ref,
585 last_resolution.entry_string_ref,
Ryan Mitchell741e96f2019-01-23 16:56:51 -0800586 package->GetPackageName(),
Winson2f3669b2019-01-11 11:28:34 -0800587 &resource_name);
588 resource_name_string = ToFormattedResourceString(&resource_name);
589 }
590
591 std::stringstream log_stream;
592 log_stream << base::StringPrintf("Resolution for 0x%08x ", resid)
593 << resource_name_string
594 << "\n\tFor config -"
595 << configuration_.toString();
596
597 std::string prefix;
598 for (Resolution::Step step : steps) {
599 switch (step.type) {
600 case Resolution::Step::Type::INITIAL:
601 prefix = "Found initial";
602 break;
603 case Resolution::Step::Type::BETTER_MATCH:
604 prefix = "Found better";
605 break;
606 case Resolution::Step::Type::OVERLAID:
607 prefix = "Overlaid";
608 break;
609 }
610
611 if (!prefix.empty()) {
612 log_stream << "\n\t" << prefix << ": " << *step.package_name;
613
614 if (!step.config_name.isEmpty()) {
615 log_stream << " -" << step.config_name;
616 }
617 }
618 }
619
620 return log_stream.str();
621}
622
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800623bool AssetManager2::GetResourceName(uint32_t resid, ResourceName* out_name) const {
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700624 FindEntryResult entry;
625 ApkAssetsCookie cookie =
626 FindEntry(resid, 0u /* density_override */, true /* stop_at_first_match */, &entry);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700627 if (cookie == kInvalidCookie) {
628 return false;
629 }
630
Ryan Mitchell741e96f2019-01-23 16:56:51 -0800631 const uint8_t package_idx = package_ids_[get_package_id(resid)];
632 if (package_idx == 0xff) {
633 LOG(ERROR) << base::StringPrintf("No package ID %02x found for ID 0x%08x.",
634 get_package_id(resid), resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700635 return false;
636 }
637
Ryan Mitchell741e96f2019-01-23 16:56:51 -0800638 const PackageGroup& package_group = package_groups_[package_idx];
639 auto cookie_iter = std::find(package_group.cookies_.begin(),
640 package_group.cookies_.end(), cookie);
641 if (cookie_iter == package_group.cookies_.end()) {
642 return false;
643 }
644
645 long package_pos = std::distance(package_group.cookies_.begin(), cookie_iter);
646 const LoadedPackage* package = package_group.packages_[package_pos].loaded_package_;
Winson2f3669b2019-01-11 11:28:34 -0800647 return ToResourceName(entry.type_string_ref,
648 entry.entry_string_ref,
Ryan Mitchell741e96f2019-01-23 16:56:51 -0800649 package->GetPackageName(),
Winson2f3669b2019-01-11 11:28:34 -0800650 out_name);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700651}
652
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800653bool AssetManager2::GetResourceFlags(uint32_t resid, uint32_t* out_flags) const {
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700654 FindEntryResult entry;
655 ApkAssetsCookie cookie =
656 FindEntry(resid, 0u /* density_override */, false /* stop_at_first_match */, &entry);
657 if (cookie != kInvalidCookie) {
658 *out_flags = entry.type_flags;
659 return cookie;
660 }
661 return kInvalidCookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700662}
663
664ApkAssetsCookie AssetManager2::GetResource(uint32_t resid, bool may_be_bag,
665 uint16_t density_override, Res_value* out_value,
666 ResTable_config* out_selected_config,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800667 uint32_t* out_flags) const {
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700668 FindEntryResult entry;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700669 ApkAssetsCookie cookie =
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700670 FindEntry(resid, density_override, false /* stop_at_first_match */, &entry);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700671 if (cookie == kInvalidCookie) {
672 return kInvalidCookie;
673 }
674
Adam Lesinski498f6052017-11-29 13:24:29 -0800675 if (dtohs(entry.entry->flags) & ResTable_entry::FLAG_COMPLEX) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700676 if (!may_be_bag) {
677 LOG(ERROR) << base::StringPrintf("Resource %08x is a complex map type.", resid);
Adam Lesinski0c405242017-01-13 20:47:26 -0800678 return kInvalidCookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700679 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800680
681 // Create a reference since we can't represent this complex type as a Res_value.
682 out_value->dataType = Res_value::TYPE_REFERENCE;
683 out_value->data = resid;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800684 *out_selected_config = entry.config;
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700685 *out_flags = entry.type_flags;
Adam Lesinski0c405242017-01-13 20:47:26 -0800686 return cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700687 }
688
689 const Res_value* device_value = reinterpret_cast<const Res_value*>(
690 reinterpret_cast<const uint8_t*>(entry.entry) + dtohs(entry.entry->size));
691 out_value->copyFrom_dtoh(*device_value);
Adam Lesinskida431a22016-12-29 16:08:16 -0500692
693 // Convert the package ID to the runtime assigned package ID.
694 entry.dynamic_ref_table->lookupResourceValue(out_value);
695
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800696 *out_selected_config = entry.config;
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700697 *out_flags = entry.type_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700698 return cookie;
699}
700
Adam Lesinski0c405242017-01-13 20:47:26 -0800701ApkAssetsCookie AssetManager2::ResolveReference(ApkAssetsCookie cookie, Res_value* in_out_value,
702 ResTable_config* in_out_selected_config,
703 uint32_t* in_out_flags,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800704 uint32_t* out_last_reference) const {
Adam Lesinski0c405242017-01-13 20:47:26 -0800705 constexpr const int kMaxIterations = 20;
706
Adam Lesinski0c405242017-01-13 20:47:26 -0800707 for (size_t iteration = 0u; in_out_value->dataType == Res_value::TYPE_REFERENCE &&
708 in_out_value->data != 0u && iteration < kMaxIterations;
709 iteration++) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800710 *out_last_reference = in_out_value->data;
Adam Lesinski0c405242017-01-13 20:47:26 -0800711 uint32_t new_flags = 0u;
712 cookie = GetResource(in_out_value->data, true /*may_be_bag*/, 0u /*density_override*/,
713 in_out_value, in_out_selected_config, &new_flags);
714 if (cookie == kInvalidCookie) {
715 return kInvalidCookie;
716 }
717 if (in_out_flags != nullptr) {
718 *in_out_flags |= new_flags;
719 }
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800720 if (*out_last_reference == in_out_value->data) {
Adam Lesinski0c405242017-01-13 20:47:26 -0800721 // This reference can't be resolved, so exit now and let the caller deal with it.
722 return cookie;
723 }
724 }
725 return cookie;
726}
727
Aurimas Liutikas8f004c82019-01-17 17:20:10 -0800728const std::vector<uint32_t> AssetManager2::GetBagResIdStack(uint32_t resid) {
729 auto cached_iter = cached_bag_resid_stacks_.find(resid);
730 if (cached_iter != cached_bag_resid_stacks_.end()) {
731 return cached_iter->second;
732 } else {
733 auto found_resids = std::vector<uint32_t>();
734 GetBag(resid, found_resids);
735 // Cache style stacks if they are not already cached.
736 cached_bag_resid_stacks_[resid] = found_resids;
737 return found_resids;
738 }
739}
740
Adam Lesinski7ad11102016-10-28 16:39:15 -0700741const ResolvedBag* AssetManager2::GetBag(uint32_t resid) {
y57cd1952018-04-12 14:26:23 -0700742 auto found_resids = std::vector<uint32_t>();
Aurimas Liutikas8f004c82019-01-17 17:20:10 -0800743 auto bag = GetBag(resid, found_resids);
744
745 // Cache style stacks if they are not already cached.
746 auto cached_iter = cached_bag_resid_stacks_.find(resid);
747 if (cached_iter == cached_bag_resid_stacks_.end()) {
748 cached_bag_resid_stacks_[resid] = found_resids;
749 }
750 return bag;
y57cd1952018-04-12 14:26:23 -0700751}
752
753const ResolvedBag* AssetManager2::GetBag(uint32_t resid, std::vector<uint32_t>& child_resids) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800754 ATRACE_NAME("AssetManager::GetBag");
Adam Lesinski7ad11102016-10-28 16:39:15 -0700755
756 auto cached_iter = cached_bags_.find(resid);
757 if (cached_iter != cached_bags_.end()) {
758 return cached_iter->second.get();
759 }
760
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700761 FindEntryResult entry;
762 ApkAssetsCookie cookie =
763 FindEntry(resid, 0u /* density_override */, false /* stop_at_first_match */, &entry);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700764 if (cookie == kInvalidCookie) {
765 return nullptr;
766 }
767
768 // Check that the size of the entry header is at least as big as
769 // the desired ResTable_map_entry. Also verify that the entry
770 // was intended to be a map.
771 if (dtohs(entry.entry->size) < sizeof(ResTable_map_entry) ||
772 (dtohs(entry.entry->flags) & ResTable_entry::FLAG_COMPLEX) == 0) {
773 // Not a bag, nothing to do.
774 return nullptr;
775 }
776
777 const ResTable_map_entry* map = reinterpret_cast<const ResTable_map_entry*>(entry.entry);
778 const ResTable_map* map_entry =
779 reinterpret_cast<const ResTable_map*>(reinterpret_cast<const uint8_t*>(map) + map->size);
780 const ResTable_map* const map_entry_end = map_entry + dtohl(map->count);
781
y57cd1952018-04-12 14:26:23 -0700782 // Keep track of ids that have already been seen to prevent infinite loops caused by circular
783 // dependencies between bags
784 child_resids.push_back(resid);
785
Adam Lesinskida431a22016-12-29 16:08:16 -0500786 uint32_t parent_resid = dtohl(map->parent.ident);
y57cd1952018-04-12 14:26:23 -0700787 if (parent_resid == 0 || std::find(child_resids.begin(), child_resids.end(), parent_resid)
788 != child_resids.end()) {
789 // There is no parent or that a circular dependency exist, meaning there is nothing to
790 // inherit and we can do a simple copy of the entries in the map.
Adam Lesinski7ad11102016-10-28 16:39:15 -0700791 const size_t entry_count = map_entry_end - map_entry;
792 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
793 malloc(sizeof(ResolvedBag) + (entry_count * sizeof(ResolvedBag::Entry))))};
794 ResolvedBag::Entry* new_entry = new_bag->entries;
795 for (; map_entry != map_entry_end; ++map_entry) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500796 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -0800797 if (!is_internal_resid(new_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500798 // Attributes, arrays, etc don't have a resource id as the name. They specify
799 // other data, which would be wrong to change via a lookup.
800 if (entry.dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800801 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
802 resid);
Adam Lesinskida431a22016-12-29 16:08:16 -0500803 return nullptr;
804 }
805 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700806 new_entry->cookie = cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -0500807 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700808 new_entry->key_pool = nullptr;
809 new_entry->type_pool = nullptr;
Aurimas Liutikasd42a6702018-11-15 15:48:28 -0800810 new_entry->style = resid;
Adam Lesinski30080e22017-10-16 16:18:09 -0700811 new_entry->value.copyFrom_dtoh(map_entry->value);
812 status_t err = entry.dynamic_ref_table->lookupResourceValue(&new_entry->value);
813 if (err != NO_ERROR) {
814 LOG(ERROR) << base::StringPrintf(
815 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
816 new_entry->value.data, new_key);
817 return nullptr;
818 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700819 ++new_entry;
820 }
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700821 new_bag->type_spec_flags = entry.type_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700822 new_bag->entry_count = static_cast<uint32_t>(entry_count);
823 ResolvedBag* result = new_bag.get();
824 cached_bags_[resid] = std::move(new_bag);
825 return result;
826 }
827
Adam Lesinskida431a22016-12-29 16:08:16 -0500828 // In case the parent is a dynamic reference, resolve it.
829 entry.dynamic_ref_table->lookupResourceId(&parent_resid);
830
Adam Lesinski7ad11102016-10-28 16:39:15 -0700831 // Get the parent and do a merge of the keys.
y57cd1952018-04-12 14:26:23 -0700832 const ResolvedBag* parent_bag = GetBag(parent_resid, child_resids);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700833 if (parent_bag == nullptr) {
834 // Failed to get the parent that should exist.
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800835 LOG(ERROR) << base::StringPrintf("Failed to find parent 0x%08x of bag 0x%08x.", parent_resid,
836 resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700837 return nullptr;
838 }
839
Adam Lesinski7ad11102016-10-28 16:39:15 -0700840 // Create the max possible entries we can make. Once we construct the bag,
841 // we will realloc to fit to size.
842 const size_t max_count = parent_bag->entry_count + dtohl(map->count);
George Burgess IV09b119f2017-07-25 15:00:04 -0700843 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
844 malloc(sizeof(ResolvedBag) + (max_count * sizeof(ResolvedBag::Entry))))};
Adam Lesinski7ad11102016-10-28 16:39:15 -0700845 ResolvedBag::Entry* new_entry = new_bag->entries;
846
847 const ResolvedBag::Entry* parent_entry = parent_bag->entries;
848 const ResolvedBag::Entry* const parent_entry_end = parent_entry + parent_bag->entry_count;
849
850 // The keys are expected to be in sorted order. Merge the two bags.
851 while (map_entry != map_entry_end && parent_entry != parent_entry_end) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500852 uint32_t child_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -0800853 if (!is_internal_resid(child_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500854 if (entry.dynamic_ref_table->lookupResourceId(&child_key) != NO_ERROR) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800855 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", child_key,
856 resid);
Adam Lesinskida431a22016-12-29 16:08:16 -0500857 return nullptr;
858 }
859 }
860
Adam Lesinski7ad11102016-10-28 16:39:15 -0700861 if (child_key <= parent_entry->key) {
862 // Use the child key if it comes before the parent
863 // or is equal to the parent (overrides).
864 new_entry->cookie = cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700865 new_entry->key = child_key;
866 new_entry->key_pool = nullptr;
867 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -0700868 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -0800869 new_entry->style = resid;
Adam Lesinski30080e22017-10-16 16:18:09 -0700870 status_t err = entry.dynamic_ref_table->lookupResourceValue(&new_entry->value);
871 if (err != NO_ERROR) {
872 LOG(ERROR) << base::StringPrintf(
873 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
874 new_entry->value.data, child_key);
875 return nullptr;
876 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700877 ++map_entry;
878 } else {
879 // Take the parent entry as-is.
880 memcpy(new_entry, parent_entry, sizeof(*new_entry));
881 }
882
883 if (child_key >= parent_entry->key) {
884 // Move to the next parent entry if we used it or it was overridden.
885 ++parent_entry;
886 }
887 // Increment to the next entry to fill.
888 ++new_entry;
889 }
890
891 // Finish the child entries if they exist.
892 while (map_entry != map_entry_end) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500893 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -0800894 if (!is_internal_resid(new_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500895 if (entry.dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800896 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
897 resid);
Adam Lesinskida431a22016-12-29 16:08:16 -0500898 return nullptr;
899 }
900 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700901 new_entry->cookie = cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -0500902 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700903 new_entry->key_pool = nullptr;
904 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -0700905 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -0800906 new_entry->style = resid;
Adam Lesinski30080e22017-10-16 16:18:09 -0700907 status_t err = entry.dynamic_ref_table->lookupResourceValue(&new_entry->value);
908 if (err != NO_ERROR) {
909 LOG(ERROR) << base::StringPrintf("Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.",
910 new_entry->value.dataType, new_entry->value.data, new_key);
911 return nullptr;
912 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700913 ++map_entry;
914 ++new_entry;
915 }
916
917 // Finish the parent entries if they exist.
918 if (parent_entry != parent_entry_end) {
919 // Take the rest of the parent entries as-is.
920 const size_t num_entries_to_copy = parent_entry_end - parent_entry;
921 memcpy(new_entry, parent_entry, num_entries_to_copy * sizeof(*new_entry));
922 new_entry += num_entries_to_copy;
923 }
924
925 // Resize the resulting array to fit.
926 const size_t actual_count = new_entry - new_bag->entries;
927 if (actual_count != max_count) {
George Burgess IV09b119f2017-07-25 15:00:04 -0700928 new_bag.reset(reinterpret_cast<ResolvedBag*>(realloc(
929 new_bag.release(), sizeof(ResolvedBag) + (actual_count * sizeof(ResolvedBag::Entry)))));
Adam Lesinski7ad11102016-10-28 16:39:15 -0700930 }
931
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700932 // Combine flags from the parent and our own bag.
933 new_bag->type_spec_flags = entry.type_flags | parent_bag->type_spec_flags;
George Burgess IV09b119f2017-07-25 15:00:04 -0700934 new_bag->entry_count = static_cast<uint32_t>(actual_count);
935 ResolvedBag* result = new_bag.get();
936 cached_bags_[resid] = std::move(new_bag);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700937 return result;
938}
939
Adam Lesinski929d6512017-01-16 19:11:19 -0800940static bool Utf8ToUtf16(const StringPiece& str, std::u16string* out) {
941 ssize_t len =
942 utf8_to_utf16_length(reinterpret_cast<const uint8_t*>(str.data()), str.size(), false);
943 if (len < 0) {
944 return false;
945 }
946 out->resize(static_cast<size_t>(len));
947 utf8_to_utf16(reinterpret_cast<const uint8_t*>(str.data()), str.size(), &*out->begin(),
948 static_cast<size_t>(len + 1));
949 return true;
950}
951
Adam Lesinski0c405242017-01-13 20:47:26 -0800952uint32_t AssetManager2::GetResourceId(const std::string& resource_name,
953 const std::string& fallback_type,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800954 const std::string& fallback_package) const {
Adam Lesinski929d6512017-01-16 19:11:19 -0800955 StringPiece package_name, type, entry;
956 if (!ExtractResourceName(resource_name, &package_name, &type, &entry)) {
957 return 0u;
958 }
959
960 if (entry.empty()) {
961 return 0u;
962 }
963
964 if (package_name.empty()) {
965 package_name = fallback_package;
966 }
967
968 if (type.empty()) {
969 type = fallback_type;
970 }
971
972 std::u16string type16;
973 if (!Utf8ToUtf16(type, &type16)) {
974 return 0u;
975 }
976
977 std::u16string entry16;
978 if (!Utf8ToUtf16(entry, &entry16)) {
979 return 0u;
980 }
981
982 const StringPiece16 kAttr16 = u"attr";
983 const static std::u16string kAttrPrivate16 = u"^attr-private";
984
985 for (const PackageGroup& package_group : package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800986 for (const ConfiguredPackage& package_impl : package_group.packages_) {
987 const LoadedPackage* package = package_impl.loaded_package_;
Adam Lesinski929d6512017-01-16 19:11:19 -0800988 if (package_name != package->GetPackageName()) {
989 // All packages in the same group are expected to have the same package name.
990 break;
991 }
992
993 uint32_t resid = package->FindEntryByName(type16, entry16);
994 if (resid == 0u && kAttr16 == type16) {
995 // Private attributes in libraries (such as the framework) are sometimes encoded
996 // under the type '^attr-private' in order to leave the ID space of public 'attr'
997 // free for future additions. Check '^attr-private' for the same name.
998 resid = package->FindEntryByName(kAttrPrivate16, entry16);
999 }
1000
1001 if (resid != 0u) {
1002 return fix_package_id(resid, package_group.dynamic_ref_table.mAssignedPackageId);
1003 }
1004 }
1005 }
Adam Lesinski0c405242017-01-13 20:47:26 -08001006 return 0u;
1007}
1008
Mårten Kongstad668ec5b2018-06-11 14:11:33 +02001009void AssetManager2::RebuildFilterList(bool filter_incompatible_configs) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001010 for (PackageGroup& group : package_groups_) {
1011 for (ConfiguredPackage& impl : group.packages_) {
1012 // Destroy it.
1013 impl.filtered_configs_.~ByteBucketArray();
1014
1015 // Re-create it.
1016 new (&impl.filtered_configs_) ByteBucketArray<FilteredConfigGroup>();
1017
1018 // Create the filters here.
1019 impl.loaded_package_->ForEachTypeSpec([&](const TypeSpec* spec, uint8_t type_index) {
1020 FilteredConfigGroup& group = impl.filtered_configs_.editItemAt(type_index);
1021 const auto iter_end = spec->types + spec->type_count;
1022 for (auto iter = spec->types; iter != iter_end; ++iter) {
1023 ResTable_config this_config;
1024 this_config.copyFromDtoH((*iter)->config);
Mårten Kongstad668ec5b2018-06-11 14:11:33 +02001025 if (!filter_incompatible_configs || this_config.match(configuration_)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001026 group.configurations.push_back(this_config);
1027 group.types.push_back(*iter);
1028 }
1029 }
1030 });
1031 }
1032 }
1033}
1034
Adam Lesinski7ad11102016-10-28 16:39:15 -07001035void AssetManager2::InvalidateCaches(uint32_t diff) {
1036 if (diff == 0xffffffffu) {
1037 // Everything must go.
1038 cached_bags_.clear();
1039 return;
1040 }
1041
1042 // Be more conservative with what gets purged. Only if the bag has other possible
1043 // variations with respect to what changed (diff) should we remove it.
1044 for (auto iter = cached_bags_.cbegin(); iter != cached_bags_.cend();) {
1045 if (diff & iter->second->type_spec_flags) {
1046 iter = cached_bags_.erase(iter);
1047 } else {
1048 ++iter;
1049 }
1050 }
1051}
1052
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001053uint8_t AssetManager2::GetAssignedPackageId(const LoadedPackage* package) {
1054 for (auto& package_group : package_groups_) {
1055 for (auto& package2 : package_group.packages_) {
1056 if (package2.loaded_package_ == package) {
1057 return package_group.dynamic_ref_table.mAssignedPackageId;
1058 }
1059 }
1060 }
1061 return 0;
1062}
1063
Adam Lesinski30080e22017-10-16 16:18:09 -07001064std::unique_ptr<Theme> AssetManager2::NewTheme() {
1065 return std::unique_ptr<Theme>(new Theme(this));
1066}
1067
1068Theme::Theme(AssetManager2* asset_manager) : asset_manager_(asset_manager) {
1069}
1070
1071Theme::~Theme() = default;
1072
1073namespace {
1074
1075struct ThemeEntry {
1076 ApkAssetsCookie cookie;
1077 uint32_t type_spec_flags;
1078 Res_value value;
1079};
1080
1081struct ThemeType {
1082 int entry_count;
1083 ThemeEntry entries[0];
1084};
1085
1086constexpr size_t kTypeCount = std::numeric_limits<uint8_t>::max() + 1;
1087
1088} // namespace
1089
1090struct Theme::Package {
1091 // Each element of Type will be a dynamically sized object
1092 // allocated to have the entries stored contiguously with the Type.
1093 std::array<util::unique_cptr<ThemeType>, kTypeCount> types;
1094};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001095
1096bool Theme::ApplyStyle(uint32_t resid, bool force) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001097 ATRACE_NAME("Theme::ApplyStyle");
Adam Lesinski7ad11102016-10-28 16:39:15 -07001098
1099 const ResolvedBag* bag = asset_manager_->GetBag(resid);
1100 if (bag == nullptr) {
1101 return false;
1102 }
1103
1104 // Merge the flags from this style.
1105 type_spec_flags_ |= bag->type_spec_flags;
1106
Adam Lesinski30080e22017-10-16 16:18:09 -07001107 int last_type_idx = -1;
1108 int last_package_idx = -1;
1109 Package* last_package = nullptr;
1110 ThemeType* last_type = nullptr;
1111
1112 // Iterate backwards, because each bag is sorted in ascending key ID order, meaning we will only
1113 // need to perform one resize per type.
1114 using reverse_bag_iterator = std::reverse_iterator<const ResolvedBag::Entry*>;
1115 const auto bag_iter_end = reverse_bag_iterator(begin(bag));
1116 for (auto bag_iter = reverse_bag_iterator(end(bag)); bag_iter != bag_iter_end; ++bag_iter) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001117 const uint32_t attr_resid = bag_iter->key;
1118
Adam Lesinski30080e22017-10-16 16:18:09 -07001119 // If the resource ID passed in is not a style, the key can be some other identifier that is not
1120 // a resource ID. We should fail fast instead of operating with strange resource IDs.
Adam Lesinski929d6512017-01-16 19:11:19 -08001121 if (!is_valid_resid(attr_resid)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001122 return false;
1123 }
1124
Adam Lesinski30080e22017-10-16 16:18:09 -07001125 // We don't use the 0-based index for the type so that we can avoid doing ID validation
1126 // upon lookup. Instead, we keep space for the type ID 0 in our data structures. Since
1127 // the construction of this type is guarded with a resource ID check, it will never be
1128 // populated, and querying type ID 0 will always fail.
1129 const int package_idx = get_package_id(attr_resid);
1130 const int type_idx = get_type_id(attr_resid);
1131 const int entry_idx = get_entry_id(attr_resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001132
Adam Lesinski30080e22017-10-16 16:18:09 -07001133 if (last_package_idx != package_idx) {
1134 std::unique_ptr<Package>& package = packages_[package_idx];
1135 if (package == nullptr) {
1136 package.reset(new Package());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001137 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001138 last_package_idx = package_idx;
1139 last_package = package.get();
1140 last_type_idx = -1;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001141 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001142
1143 if (last_type_idx != type_idx) {
1144 util::unique_cptr<ThemeType>& type = last_package->types[type_idx];
1145 if (type == nullptr) {
1146 // Allocate enough memory to contain this entry_idx. Since we're iterating in reverse over
1147 // a sorted list of attributes, this shouldn't be resized again during this method call.
1148 type.reset(reinterpret_cast<ThemeType*>(
1149 calloc(sizeof(ThemeType) + (entry_idx + 1) * sizeof(ThemeEntry), 1)));
1150 type->entry_count = entry_idx + 1;
1151 } else if (entry_idx >= type->entry_count) {
1152 // Reallocate the memory to contain this entry_idx. Since we're iterating in reverse over
1153 // a sorted list of attributes, this shouldn't be resized again during this method call.
1154 const int new_count = entry_idx + 1;
1155 type.reset(reinterpret_cast<ThemeType*>(
1156 realloc(type.release(), sizeof(ThemeType) + (new_count * sizeof(ThemeEntry)))));
1157
1158 // Clear out the newly allocated space (which isn't zeroed).
1159 memset(type->entries + type->entry_count, 0,
1160 (new_count - type->entry_count) * sizeof(ThemeEntry));
1161 type->entry_count = new_count;
1162 }
1163 last_type_idx = type_idx;
1164 last_type = type.get();
1165 }
1166
1167 ThemeEntry& entry = last_type->entries[entry_idx];
1168 if (force || (entry.value.dataType == Res_value::TYPE_NULL &&
1169 entry.value.data != Res_value::DATA_NULL_EMPTY)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001170 entry.cookie = bag_iter->cookie;
1171 entry.type_spec_flags |= bag->type_spec_flags;
1172 entry.value = bag_iter->value;
1173 }
1174 }
1175 return true;
1176}
1177
1178ApkAssetsCookie Theme::GetAttribute(uint32_t resid, Res_value* out_value,
1179 uint32_t* out_flags) const {
Adam Lesinski30080e22017-10-16 16:18:09 -07001180 int cnt = 20;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001181
1182 uint32_t type_spec_flags = 0u;
1183
Adam Lesinski30080e22017-10-16 16:18:09 -07001184 do {
1185 const int package_idx = get_package_id(resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001186 const Package* package = packages_[package_idx].get();
Adam Lesinski30080e22017-10-16 16:18:09 -07001187 if (package != nullptr) {
1188 // The themes are constructed with a 1-based type ID, so no need to decrement here.
1189 const int type_idx = get_type_id(resid);
1190 const ThemeType* type = package->types[type_idx].get();
1191 if (type != nullptr) {
1192 const int entry_idx = get_entry_id(resid);
1193 if (entry_idx < type->entry_count) {
1194 const ThemeEntry& entry = type->entries[entry_idx];
1195 type_spec_flags |= entry.type_spec_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001196
Adam Lesinski30080e22017-10-16 16:18:09 -07001197 if (entry.value.dataType == Res_value::TYPE_ATTRIBUTE) {
1198 if (cnt > 0) {
1199 cnt--;
1200 resid = entry.value.data;
1201 continue;
1202 }
1203 return kInvalidCookie;
1204 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001205
Adam Lesinski30080e22017-10-16 16:18:09 -07001206 // @null is different than @empty.
1207 if (entry.value.dataType == Res_value::TYPE_NULL &&
1208 entry.value.data != Res_value::DATA_NULL_EMPTY) {
1209 return kInvalidCookie;
1210 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001211
Adam Lesinski30080e22017-10-16 16:18:09 -07001212 *out_value = entry.value;
Adam Lesinskida431a22016-12-29 16:08:16 -05001213 *out_flags = type_spec_flags;
Adam Lesinski30080e22017-10-16 16:18:09 -07001214 return entry.cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -05001215 }
Adam Lesinskida431a22016-12-29 16:08:16 -05001216 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001217 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001218 break;
1219 } while (true);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001220 return kInvalidCookie;
1221}
1222
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001223ApkAssetsCookie Theme::ResolveAttributeReference(ApkAssetsCookie cookie, Res_value* in_out_value,
1224 ResTable_config* in_out_selected_config,
1225 uint32_t* in_out_type_spec_flags,
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001226 uint32_t* out_last_ref) const {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001227 if (in_out_value->dataType == Res_value::TYPE_ATTRIBUTE) {
1228 uint32_t new_flags;
1229 cookie = GetAttribute(in_out_value->data, in_out_value, &new_flags);
1230 if (cookie == kInvalidCookie) {
1231 return kInvalidCookie;
1232 }
1233
1234 if (in_out_type_spec_flags != nullptr) {
1235 *in_out_type_spec_flags |= new_flags;
1236 }
1237 }
1238 return asset_manager_->ResolveReference(cookie, in_out_value, in_out_selected_config,
1239 in_out_type_spec_flags, out_last_ref);
1240}
1241
Adam Lesinski7ad11102016-10-28 16:39:15 -07001242void Theme::Clear() {
1243 type_spec_flags_ = 0u;
1244 for (std::unique_ptr<Package>& package : packages_) {
1245 package.reset();
1246 }
1247}
1248
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001249void Theme::SetTo(const Theme& o) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001250 if (this == &o) {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001251 return;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001252 }
1253
Adam Lesinski7ad11102016-10-28 16:39:15 -07001254 type_spec_flags_ = o.type_spec_flags_;
1255
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001256 if (asset_manager_ == o.asset_manager_) {
1257 // The theme comes from the same asset manager so all theme data can be copied exactly
1258 for (size_t p = 0; p < packages_.size(); p++) {
1259 const Package *package = o.packages_[p].get();
1260 if (package == nullptr) {
1261 // The other theme doesn't have this package, clear ours.
1262 packages_[p].reset();
Adam Lesinski7ad11102016-10-28 16:39:15 -07001263 continue;
1264 }
1265
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001266 if (packages_[p] == nullptr) {
1267 // The other theme has this package, but we don't. Make one.
1268 packages_[p].reset(new Package());
1269 }
1270
1271 for (size_t t = 0; t < package->types.size(); t++) {
1272 const ThemeType *type = package->types[t].get();
1273 if (type == nullptr) {
1274 // The other theme doesn't have this type, clear ours.
1275 packages_[p]->types[t].reset();
1276 continue;
1277 }
1278
1279 // Create a new type and update it to theirs.
1280 const size_t type_alloc_size = sizeof(ThemeType) + (type->entry_count * sizeof(ThemeEntry));
1281 void *copied_data = malloc(type_alloc_size);
1282 memcpy(copied_data, type, type_alloc_size);
1283 packages_[p]->types[t].reset(reinterpret_cast<ThemeType *>(copied_data));
1284 }
1285 }
1286 } else {
1287 std::map<ApkAssetsCookie, ApkAssetsCookie> src_to_dest_asset_cookies;
1288 typedef std::map<int, int> SourceToDestinationRuntimePackageMap;
1289 std::map<ApkAssetsCookie, SourceToDestinationRuntimePackageMap> src_asset_cookie_id_map;
1290
1291 // Determine which ApkAssets are loaded in both theme AssetManagers
1292 std::vector<const ApkAssets*> src_assets = o.asset_manager_->GetApkAssets();
1293 for (size_t i = 0; i < src_assets.size(); i++) {
1294 const ApkAssets* src_asset = src_assets[i];
1295
1296 std::vector<const ApkAssets*> dest_assets = asset_manager_->GetApkAssets();
1297 for (size_t j = 0; j < dest_assets.size(); j++) {
1298 const ApkAssets* dest_asset = dest_assets[j];
1299
1300 // Map the runtime package of the source apk asset to the destination apk asset
1301 if (src_asset->GetPath() == dest_asset->GetPath()) {
1302 const std::vector<std::unique_ptr<const LoadedPackage>>& src_packages =
1303 src_asset->GetLoadedArsc()->GetPackages();
1304 const std::vector<std::unique_ptr<const LoadedPackage>>& dest_packages =
1305 dest_asset->GetLoadedArsc()->GetPackages();
1306
1307 SourceToDestinationRuntimePackageMap package_map;
1308
1309 // The source and destination package should have the same number of packages loaded in
1310 // the same order.
1311 const size_t N = src_packages.size();
1312 CHECK(N == dest_packages.size())
1313 << " LoadedArsc " << src_asset->GetPath() << " differs number of packages.";
1314 for (size_t p = 0; p < N; p++) {
1315 auto& src_package = src_packages[p];
1316 auto& dest_package = dest_packages[p];
1317 CHECK(src_package->GetPackageName() == dest_package->GetPackageName())
1318 << " Package " << src_package->GetPackageName() << " differs in load order.";
1319
1320 int src_package_id = o.asset_manager_->GetAssignedPackageId(src_package.get());
1321 int dest_package_id = asset_manager_->GetAssignedPackageId(dest_package.get());
1322 package_map[src_package_id] = dest_package_id;
1323 }
1324
1325 src_to_dest_asset_cookies.insert(std::pair<ApkAssetsCookie, ApkAssetsCookie>(i, j));
1326 src_asset_cookie_id_map.insert(
1327 std::pair<ApkAssetsCookie, SourceToDestinationRuntimePackageMap>(i, package_map));
1328 break;
1329 }
1330 }
1331 }
1332
1333 // Reset the data in the destination theme
1334 for (size_t p = 0; p < packages_.size(); p++) {
1335 if (packages_[p] != nullptr) {
1336 packages_[p].reset();
1337 }
1338 }
1339
1340 for (size_t p = 0; p < packages_.size(); p++) {
1341 const Package *package = o.packages_[p].get();
1342 if (package == nullptr) {
1343 continue;
1344 }
1345
1346 for (size_t t = 0; t < package->types.size(); t++) {
1347 const ThemeType *type = package->types[t].get();
1348 if (type == nullptr) {
1349 continue;
1350 }
1351
1352 for (size_t e = 0; e < type->entry_count; e++) {
1353 const ThemeEntry &entry = type->entries[e];
1354 if (entry.value.dataType == Res_value::TYPE_NULL &&
1355 entry.value.data != Res_value::DATA_NULL_EMPTY) {
1356 continue;
1357 }
1358
Ryan Mitchellb85d9b22018-11-19 12:11:38 -08001359 // If the attribute value represents an attribute or reference, the package id of the
1360 // value needs to be rewritten to the package id of the value in the destination
1361 uint32_t attribue_data = entry.value.data;
1362 if ((entry.value.dataType == Res_value::TYPE_ATTRIBUTE
1363 || entry.value.dataType == Res_value::TYPE_REFERENCE
1364 || entry.value.dataType == Res_value::TYPE_DYNAMIC_ATTRIBUTE
1365 || entry.value.dataType == Res_value::TYPE_DYNAMIC_REFERENCE)
1366 && attribue_data != 0x0) {
1367
1368 // Determine the package id of the reference in the destination AssetManager
1369 auto value_package_map = src_asset_cookie_id_map.find(entry.cookie);
1370 if (value_package_map == src_asset_cookie_id_map.end()) {
1371 continue;
1372 }
1373
1374 auto value_dest_package = value_package_map->second.find(
1375 get_package_id(entry.value.data));
1376 if (value_dest_package == value_package_map->second.end()) {
1377 continue;
1378 }
1379
1380 attribue_data = fix_package_id(entry.value.data, value_dest_package->second);
1381 }
1382
1383 // The package id of the attribute needs to be rewritten to the package id of the
1384 // attribute in the destination
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001385 int attribute_dest_package_id = p;
1386 if (attribute_dest_package_id != 0x01) {
1387 // Find the cookie of the attribute resource id
1388 FindEntryResult attribute_entry_result;
1389 ApkAssetsCookie attribute_cookie =
1390 o.asset_manager_->FindEntry(make_resid(p, t, e), 0 /* density_override */ , false,
1391 &attribute_entry_result);
1392
1393 // Determine the package id of the attribute in the destination AssetManager
1394 auto attribute_package_map = src_asset_cookie_id_map.find(attribute_cookie);
1395 if (attribute_package_map == src_asset_cookie_id_map.end()) {
1396 continue;
1397 }
1398 auto attribute_dest_package = attribute_package_map->second.find(
1399 attribute_dest_package_id);
1400 if (attribute_dest_package == attribute_package_map->second.end()) {
1401 continue;
1402 }
1403 attribute_dest_package_id = attribute_dest_package->second;
1404 }
1405
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001406 // Lazily instantiate the destination package
1407 std::unique_ptr<Package>& dest_package = packages_[attribute_dest_package_id];
1408 if (dest_package == nullptr) {
1409 dest_package.reset(new Package());
1410 }
1411
1412 // Lazily instantiate and resize the destination type
1413 util::unique_cptr<ThemeType>& dest_type = dest_package->types[t];
1414 if (dest_type == nullptr || dest_type->entry_count < type->entry_count) {
1415 const size_t type_alloc_size = sizeof(ThemeType)
1416 + (type->entry_count * sizeof(ThemeEntry));
1417 void* dest_data = malloc(type_alloc_size);
1418 memset(dest_data, 0, type->entry_count * sizeof(ThemeEntry));
1419
1420 // Copy the existing destination type values if the type is resized
1421 if (dest_type != nullptr) {
1422 memcpy(dest_data, type, sizeof(ThemeType)
1423 + (dest_type->entry_count * sizeof(ThemeEntry)));
1424 }
1425
1426 dest_type.reset(reinterpret_cast<ThemeType *>(dest_data));
1427 dest_type->entry_count = type->entry_count;
1428 }
1429
1430 // Find the cookie of the value in the destination
1431 auto value_dest_cookie = src_to_dest_asset_cookies.find(entry.cookie);
1432 if (value_dest_cookie == src_to_dest_asset_cookies.end()) {
1433 continue;
1434 }
1435
1436 dest_type->entries[e].cookie = value_dest_cookie->second;
1437 dest_type->entries[e].value.dataType = entry.value.dataType;
1438 dest_type->entries[e].value.data = attribue_data;
1439 dest_type->entries[e].type_spec_flags = entry.type_spec_flags;
1440 }
1441 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001442 }
1443 }
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001444}
1445
1446void Theme::Dump() const {
1447 base::ScopedLogSeverity _log(base::INFO);
1448 LOG(INFO) << base::StringPrintf("Theme(this=%p, AssetManager2=%p)", this, asset_manager_);
1449
1450 for (int p = 0; p < packages_.size(); p++) {
1451 auto& package = packages_[p];
1452 if (package == nullptr) {
1453 continue;
1454 }
1455
1456 for (int t = 0; t < package->types.size(); t++) {
1457 auto& type = package->types[t];
1458 if (type == nullptr) {
1459 continue;
1460 }
1461
1462 for (int e = 0; e < type->entry_count; e++) {
1463 auto& entry = type->entries[e];
1464 if (entry.value.dataType == Res_value::TYPE_NULL &&
1465 entry.value.data != Res_value::DATA_NULL_EMPTY) {
1466 continue;
1467 }
1468
1469 LOG(INFO) << base::StringPrintf(" entry(0x%08x)=(0x%08x) type=(0x%02x), cookie(%d)",
1470 make_resid(p, t, e), entry.value.data,
1471 entry.value.dataType, entry.cookie);
1472 }
1473 }
1474 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001475}
1476
1477} // namespace android