blob: 288ba32c47a6fdeaec22a9e18f36556439d73830 [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>
Adam Lesinski0c405242017-01-13 20:47:26 -080023#include <set>
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -070024#include <map>
Adam Lesinski0c405242017-01-13 20:47:26 -080025
Adam Lesinski7ad11102016-10-28 16:39:15 -070026#include "android-base/logging.h"
27#include "android-base/stringprintf.h"
28#include "utils/ByteOrder.h"
29#include "utils/Trace.h"
30
31#ifdef _WIN32
32#ifdef ERROR
33#undef ERROR
34#endif
35#endif
36
Adam Lesinski929d6512017-01-16 19:11:19 -080037#include "androidfw/ResourceUtils.h"
38
Adam Lesinski7ad11102016-10-28 16:39:15 -070039namespace android {
40
Adam Lesinskibebfcc42018-02-12 14:27:46 -080041struct FindEntryResult {
42 // A pointer to the resource table entry for this resource.
43 // If the size of the entry is > sizeof(ResTable_entry), it can be cast to
44 // a ResTable_map_entry and processed as a bag/map.
45 const ResTable_entry* entry;
46
47 // The configuration for which the resulting entry was defined. This is already swapped to host
48 // endianness.
49 ResTable_config config;
50
51 // The bitmask of configuration axis with which the resource value varies.
52 uint32_t type_flags;
53
54 // The dynamic package ID map for the package from which this resource came from.
55 const DynamicRefTable* dynamic_ref_table;
56
57 // The string pool reference to the type's name. This uses a different string pool than
58 // the global string pool, but this is hidden from the caller.
59 StringPoolRef type_string_ref;
60
61 // The string pool reference to the entry's name. This uses a different string pool than
62 // the global string pool, but this is hidden from the caller.
63 StringPoolRef entry_string_ref;
64};
65
Adam Lesinski970bd8d2017-09-25 13:21:55 -070066AssetManager2::AssetManager2() {
67 memset(&configuration_, 0, sizeof(configuration_));
68}
Adam Lesinski7ad11102016-10-28 16:39:15 -070069
70bool AssetManager2::SetApkAssets(const std::vector<const ApkAssets*>& apk_assets,
Mårten Kongstad668ec5b2018-06-11 14:11:33 +020071 bool invalidate_caches, bool filter_incompatible_configs) {
Adam Lesinski7ad11102016-10-28 16:39:15 -070072 apk_assets_ = apk_assets;
Adam Lesinskida431a22016-12-29 16:08:16 -050073 BuildDynamicRefTable();
Mårten Kongstad668ec5b2018-06-11 14:11:33 +020074 RebuildFilterList(filter_incompatible_configs);
Adam Lesinski7ad11102016-10-28 16:39:15 -070075 if (invalidate_caches) {
76 InvalidateCaches(static_cast<uint32_t>(-1));
77 }
78 return true;
79}
80
Adam Lesinskida431a22016-12-29 16:08:16 -050081void AssetManager2::BuildDynamicRefTable() {
82 package_groups_.clear();
83 package_ids_.fill(0xff);
84
85 // 0x01 is reserved for the android package.
86 int next_package_id = 0x02;
87 const size_t apk_assets_count = apk_assets_.size();
88 for (size_t i = 0; i < apk_assets_count; i++) {
Adam Lesinski970bd8d2017-09-25 13:21:55 -070089 const LoadedArsc* loaded_arsc = apk_assets_[i]->GetLoadedArsc();
90
91 for (const std::unique_ptr<const LoadedPackage>& package : loaded_arsc->GetPackages()) {
Adam Lesinskida431a22016-12-29 16:08:16 -050092 // Get the package ID or assign one if a shared library.
93 int package_id;
94 if (package->IsDynamic()) {
95 package_id = next_package_id++;
96 } else {
97 package_id = package->GetPackageId();
98 }
99
100 // Add the mapping for package ID to index if not present.
101 uint8_t idx = package_ids_[package_id];
102 if (idx == 0xff) {
103 package_ids_[package_id] = idx = static_cast<uint8_t>(package_groups_.size());
104 package_groups_.push_back({});
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800105 DynamicRefTable& ref_table = package_groups_.back().dynamic_ref_table;
106 ref_table.mAssignedPackageId = package_id;
107 ref_table.mAppAsLib = package->IsDynamic() && package->GetPackageId() == 0x7f;
Adam Lesinskida431a22016-12-29 16:08:16 -0500108 }
109 PackageGroup* package_group = &package_groups_[idx];
110
111 // Add the package and to the set of packages with the same ID.
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800112 package_group->packages_.push_back(ConfiguredPackage{package.get(), {}});
Adam Lesinskida431a22016-12-29 16:08:16 -0500113 package_group->cookies_.push_back(static_cast<ApkAssetsCookie>(i));
114
115 // Add the package name -> build time ID mappings.
116 for (const DynamicPackageEntry& entry : package->GetDynamicPackageMap()) {
117 String16 package_name(entry.package_name.c_str(), entry.package_name.size());
118 package_group->dynamic_ref_table.mEntries.replaceValueFor(
119 package_name, static_cast<uint8_t>(entry.package_id));
120 }
121 }
122 }
123
124 // Now assign the runtime IDs so that we have a build-time to runtime ID map.
125 const auto package_groups_end = package_groups_.end();
126 for (auto iter = package_groups_.begin(); iter != package_groups_end; ++iter) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800127 const std::string& package_name = iter->packages_[0].loaded_package_->GetPackageName();
Adam Lesinskida431a22016-12-29 16:08:16 -0500128 for (auto iter2 = package_groups_.begin(); iter2 != package_groups_end; ++iter2) {
129 iter2->dynamic_ref_table.addMapping(String16(package_name.c_str(), package_name.size()),
130 iter->dynamic_ref_table.mAssignedPackageId);
131 }
132 }
133}
134
135void AssetManager2::DumpToLog() const {
136 base::ScopedLogSeverity _log(base::INFO);
137
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800138 LOG(INFO) << base::StringPrintf("AssetManager2(this=%p)", this);
139
Adam Lesinskida431a22016-12-29 16:08:16 -0500140 std::string list;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800141 for (const auto& apk_assets : apk_assets_) {
142 base::StringAppendF(&list, "%s,", apk_assets->GetPath().c_str());
143 }
144 LOG(INFO) << "ApkAssets: " << list;
145
146 list = "";
Adam Lesinskida431a22016-12-29 16:08:16 -0500147 for (size_t i = 0; i < package_ids_.size(); i++) {
148 if (package_ids_[i] != 0xff) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800149 base::StringAppendF(&list, "%02x -> %d, ", (int)i, package_ids_[i]);
Adam Lesinskida431a22016-12-29 16:08:16 -0500150 }
151 }
152 LOG(INFO) << "Package ID map: " << list;
153
Adam Lesinski0dd36992018-01-25 15:38:38 -0800154 for (const auto& package_group: package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800155 list = "";
156 for (const auto& package : package_group.packages_) {
157 const LoadedPackage* loaded_package = package.loaded_package_;
158 base::StringAppendF(&list, "%s(%02x%s), ", loaded_package->GetPackageName().c_str(),
159 loaded_package->GetPackageId(),
160 (loaded_package->IsDynamic() ? " dynamic" : ""));
161 }
162 LOG(INFO) << base::StringPrintf("PG (%02x): ",
163 package_group.dynamic_ref_table.mAssignedPackageId)
164 << list;
Adam Lesinskida431a22016-12-29 16:08:16 -0500165 }
166}
Adam Lesinski7ad11102016-10-28 16:39:15 -0700167
168const ResStringPool* AssetManager2::GetStringPoolForCookie(ApkAssetsCookie cookie) const {
169 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
170 return nullptr;
171 }
172 return apk_assets_[cookie]->GetLoadedArsc()->GetStringPool();
173}
174
Adam Lesinskida431a22016-12-29 16:08:16 -0500175const DynamicRefTable* AssetManager2::GetDynamicRefTableForPackage(uint32_t package_id) const {
176 if (package_id >= package_ids_.size()) {
177 return nullptr;
178 }
179
180 const size_t idx = package_ids_[package_id];
181 if (idx == 0xff) {
182 return nullptr;
183 }
184 return &package_groups_[idx].dynamic_ref_table;
185}
186
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800187const DynamicRefTable* AssetManager2::GetDynamicRefTableForCookie(ApkAssetsCookie cookie) const {
188 for (const PackageGroup& package_group : package_groups_) {
189 for (const ApkAssetsCookie& package_cookie : package_group.cookies_) {
190 if (package_cookie == cookie) {
191 return &package_group.dynamic_ref_table;
192 }
193 }
194 }
195 return nullptr;
196}
197
Adam Lesinski7ad11102016-10-28 16:39:15 -0700198void AssetManager2::SetConfiguration(const ResTable_config& configuration) {
199 const int diff = configuration_.diff(configuration);
200 configuration_ = configuration;
201
202 if (diff) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800203 RebuildFilterList();
Adam Lesinski7ad11102016-10-28 16:39:15 -0700204 InvalidateCaches(static_cast<uint32_t>(diff));
205 }
206}
207
Adam Lesinski0c405242017-01-13 20:47:26 -0800208std::set<ResTable_config> AssetManager2::GetResourceConfigurations(bool exclude_system,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800209 bool exclude_mipmap) const {
210 ATRACE_NAME("AssetManager::GetResourceConfigurations");
Adam Lesinski0c405242017-01-13 20:47:26 -0800211 std::set<ResTable_config> configurations;
212 for (const PackageGroup& package_group : package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800213 for (const ConfiguredPackage& package : package_group.packages_) {
214 if (exclude_system && package.loaded_package_->IsSystem()) {
Adam Lesinski0c405242017-01-13 20:47:26 -0800215 continue;
216 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800217 package.loaded_package_->CollectConfigurations(exclude_mipmap, &configurations);
Adam Lesinski0c405242017-01-13 20:47:26 -0800218 }
219 }
220 return configurations;
221}
222
223std::set<std::string> AssetManager2::GetResourceLocales(bool exclude_system,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800224 bool merge_equivalent_languages) const {
225 ATRACE_NAME("AssetManager::GetResourceLocales");
Adam Lesinski0c405242017-01-13 20:47:26 -0800226 std::set<std::string> locales;
227 for (const PackageGroup& package_group : package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800228 for (const ConfiguredPackage& package : package_group.packages_) {
229 if (exclude_system && package.loaded_package_->IsSystem()) {
Adam Lesinski0c405242017-01-13 20:47:26 -0800230 continue;
231 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800232 package.loaded_package_->CollectLocales(merge_equivalent_languages, &locales);
Adam Lesinski0c405242017-01-13 20:47:26 -0800233 }
234 }
235 return locales;
236}
237
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800238std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename,
239 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700240 const std::string new_path = "assets/" + filename;
241 return OpenNonAsset(new_path, mode);
242}
243
244std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename, ApkAssetsCookie cookie,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800245 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700246 const std::string new_path = "assets/" + filename;
247 return OpenNonAsset(new_path, cookie, mode);
248}
249
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800250std::unique_ptr<AssetDir> AssetManager2::OpenDir(const std::string& dirname) const {
251 ATRACE_NAME("AssetManager::OpenDir");
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800252
253 std::string full_path = "assets/" + dirname;
254 std::unique_ptr<SortedVector<AssetDir::FileInfo>> files =
255 util::make_unique<SortedVector<AssetDir::FileInfo>>();
256
257 // Start from the back.
258 for (auto iter = apk_assets_.rbegin(); iter != apk_assets_.rend(); ++iter) {
259 const ApkAssets* apk_assets = *iter;
260
261 auto func = [&](const StringPiece& name, FileType type) {
262 AssetDir::FileInfo info;
263 info.setFileName(String8(name.data(), name.size()));
264 info.setFileType(type);
265 info.setSourceName(String8(apk_assets->GetPath().c_str()));
266 files->add(info);
267 };
268
269 if (!apk_assets->ForEachFile(full_path, func)) {
270 return {};
271 }
272 }
273
274 std::unique_ptr<AssetDir> asset_dir = util::make_unique<AssetDir>();
275 asset_dir->setFileList(files.release());
276 return asset_dir;
277}
278
Adam Lesinski7ad11102016-10-28 16:39:15 -0700279// Search in reverse because that's how we used to do it and we need to preserve behaviour.
280// This is unfortunate, because ClassLoaders delegate to the parent first, so the order
281// is inconsistent for split APKs.
282std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
283 Asset::AccessMode mode,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800284 ApkAssetsCookie* out_cookie) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700285 for (int32_t i = apk_assets_.size() - 1; i >= 0; i--) {
286 std::unique_ptr<Asset> asset = apk_assets_[i]->Open(filename, mode);
287 if (asset) {
288 if (out_cookie != nullptr) {
289 *out_cookie = i;
290 }
291 return asset;
292 }
293 }
294
295 if (out_cookie != nullptr) {
296 *out_cookie = kInvalidCookie;
297 }
298 return {};
299}
300
301std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800302 ApkAssetsCookie cookie,
303 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700304 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
305 return {};
306 }
307 return apk_assets_[cookie]->Open(filename, mode);
308}
309
310ApkAssetsCookie AssetManager2::FindEntry(uint32_t resid, uint16_t density_override,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800311 bool /*stop_at_first_match*/,
312 FindEntryResult* out_entry) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700313 // Might use this if density_override != 0.
314 ResTable_config density_override_config;
315
316 // Select our configuration or generate a density override configuration.
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800317 const ResTable_config* desired_config = &configuration_;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700318 if (density_override != 0 && density_override != configuration_.density) {
319 density_override_config = configuration_;
320 density_override_config.density = density_override;
321 desired_config = &density_override_config;
322 }
323
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800324 if (!is_valid_resid(resid)) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500325 LOG(ERROR) << base::StringPrintf("Invalid ID 0x%08x.", resid);
326 return kInvalidCookie;
327 }
328
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800329 const uint32_t package_id = get_package_id(resid);
330 const uint8_t type_idx = get_type_id(resid) - 1;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800331 const uint16_t entry_idx = get_entry_id(resid);
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800332
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800333 const uint8_t package_idx = package_ids_[package_id];
334 if (package_idx == 0xff) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500335 LOG(ERROR) << base::StringPrintf("No package ID %02x found for ID 0x%08x.", package_id, resid);
336 return kInvalidCookie;
337 }
338
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800339 const PackageGroup& package_group = package_groups_[package_idx];
Adam Lesinskib8b3a262018-02-09 11:01:45 -0800340 const size_t package_count = package_group.packages_.size();
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800341
342 ApkAssetsCookie best_cookie = kInvalidCookie;
343 const LoadedPackage* best_package = nullptr;
344 const ResTable_type* best_type = nullptr;
345 const ResTable_config* best_config = nullptr;
346 ResTable_config best_config_copy;
347 uint32_t best_offset = 0u;
348 uint32_t type_flags = 0u;
349
350 // If desired_config is the same as the set configuration, then we can use our filtered list
351 // and we don't need to match the configurations, since they already matched.
352 const bool use_fast_path = desired_config == &configuration_;
353
354 for (size_t pi = 0; pi < package_count; pi++) {
355 const ConfiguredPackage& loaded_package_impl = package_group.packages_[pi];
356 const LoadedPackage* loaded_package = loaded_package_impl.loaded_package_;
357 ApkAssetsCookie cookie = package_group.cookies_[pi];
358
359 // If the type IDs are offset in this package, we need to take that into account when searching
360 // for a type.
361 const TypeSpec* type_spec = loaded_package->GetTypeSpecByTypeIndex(type_idx);
362 if (UNLIKELY(type_spec == nullptr)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700363 continue;
364 }
365
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800366 uint16_t local_entry_idx = entry_idx;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700367
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800368 // If there is an IDMAP supplied with this package, translate the entry ID.
369 if (type_spec->idmap_entries != nullptr) {
370 if (!LoadedIdmap::Lookup(type_spec->idmap_entries, local_entry_idx, &local_entry_idx)) {
371 // There is no mapping, so the resource is not meant to be in this overlay package.
372 continue;
373 }
374 }
375
376 type_flags |= type_spec->GetFlagsForEntryIndex(local_entry_idx);
377
378 // If the package is an overlay, then even configurations that are the same MUST be chosen.
379 const bool package_is_overlay = loaded_package->IsOverlay();
380
381 const FilteredConfigGroup& filtered_group = loaded_package_impl.filtered_configs_[type_idx];
382 if (use_fast_path) {
383 const std::vector<ResTable_config>& candidate_configs = filtered_group.configurations;
384 const size_t type_count = candidate_configs.size();
385 for (uint32_t i = 0; i < type_count; i++) {
386 const ResTable_config& this_config = candidate_configs[i];
387
388 // We can skip calling ResTable_config::match() because we know that all candidate
389 // configurations that do NOT match have been filtered-out.
390 if ((best_config == nullptr || this_config.isBetterThan(*best_config, desired_config)) ||
391 (package_is_overlay && this_config.compare(*best_config) == 0)) {
392 // The configuration matches and is better than the previous selection.
393 // Find the entry value if it exists for this configuration.
394 const ResTable_type* type_chunk = filtered_group.types[i];
395 const uint32_t offset = LoadedPackage::GetEntryOffset(type_chunk, local_entry_idx);
396 if (offset == ResTable_type::NO_ENTRY) {
397 continue;
398 }
399
400 best_cookie = cookie;
401 best_package = loaded_package;
402 best_type = type_chunk;
403 best_config = &this_config;
404 best_offset = offset;
405 }
406 }
407 } else {
408 // This is the slower path, which doesn't use the filtered list of configurations.
409 // Here we must read the ResTable_config from the mmapped APK, convert it to host endianness
410 // and fill in any new fields that did not exist when the APK was compiled.
411 // Furthermore when selecting configurations we can't just record the pointer to the
412 // ResTable_config, we must copy it.
413 const auto iter_end = type_spec->types + type_spec->type_count;
414 for (auto iter = type_spec->types; iter != iter_end; ++iter) {
415 ResTable_config this_config;
416 this_config.copyFromDtoH((*iter)->config);
417
418 if (this_config.match(*desired_config)) {
419 if ((best_config == nullptr || this_config.isBetterThan(*best_config, desired_config)) ||
420 (package_is_overlay && this_config.compare(*best_config) == 0)) {
421 // The configuration matches and is better than the previous selection.
422 // Find the entry value if it exists for this configuration.
423 const uint32_t offset = LoadedPackage::GetEntryOffset(*iter, local_entry_idx);
424 if (offset == ResTable_type::NO_ENTRY) {
425 continue;
426 }
427
428 best_cookie = cookie;
429 best_package = loaded_package;
430 best_type = *iter;
431 best_config_copy = this_config;
432 best_config = &best_config_copy;
433 best_offset = offset;
434 }
435 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700436 }
437 }
438 }
439
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800440 if (UNLIKELY(best_cookie == kInvalidCookie)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700441 return kInvalidCookie;
442 }
443
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800444 const ResTable_entry* best_entry = LoadedPackage::GetEntryFromOffset(best_type, best_offset);
445 if (UNLIKELY(best_entry == nullptr)) {
446 return kInvalidCookie;
447 }
448
449 out_entry->entry = best_entry;
450 out_entry->config = *best_config;
451 out_entry->type_flags = type_flags;
452 out_entry->type_string_ref = StringPoolRef(best_package->GetTypeStringPool(), best_type->id - 1);
453 out_entry->entry_string_ref =
454 StringPoolRef(best_package->GetKeyStringPool(), best_entry->key.index);
Adam Lesinskida431a22016-12-29 16:08:16 -0500455 out_entry->dynamic_ref_table = &package_group.dynamic_ref_table;
Adam Lesinskida431a22016-12-29 16:08:16 -0500456 return best_cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700457}
458
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800459bool AssetManager2::GetResourceName(uint32_t resid, ResourceName* out_name) const {
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700460 FindEntryResult entry;
461 ApkAssetsCookie cookie =
462 FindEntry(resid, 0u /* density_override */, true /* stop_at_first_match */, &entry);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700463 if (cookie == kInvalidCookie) {
464 return false;
465 }
466
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800467 const LoadedPackage* package =
468 apk_assets_[cookie]->GetLoadedArsc()->GetPackageById(get_package_id(resid));
Adam Lesinskida431a22016-12-29 16:08:16 -0500469 if (package == nullptr) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700470 return false;
471 }
472
Adam Lesinskida431a22016-12-29 16:08:16 -0500473 out_name->package = package->GetPackageName().data();
474 out_name->package_len = package->GetPackageName().size();
Adam Lesinski7ad11102016-10-28 16:39:15 -0700475
476 out_name->type = entry.type_string_ref.string8(&out_name->type_len);
477 out_name->type16 = nullptr;
478 if (out_name->type == nullptr) {
479 out_name->type16 = entry.type_string_ref.string16(&out_name->type_len);
480 if (out_name->type16 == nullptr) {
481 return false;
482 }
483 }
484
485 out_name->entry = entry.entry_string_ref.string8(&out_name->entry_len);
486 out_name->entry16 = nullptr;
487 if (out_name->entry == nullptr) {
488 out_name->entry16 = entry.entry_string_ref.string16(&out_name->entry_len);
489 if (out_name->entry16 == nullptr) {
490 return false;
491 }
492 }
493 return true;
494}
495
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800496bool AssetManager2::GetResourceFlags(uint32_t resid, uint32_t* out_flags) const {
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700497 FindEntryResult entry;
498 ApkAssetsCookie cookie =
499 FindEntry(resid, 0u /* density_override */, false /* stop_at_first_match */, &entry);
500 if (cookie != kInvalidCookie) {
501 *out_flags = entry.type_flags;
502 return cookie;
503 }
504 return kInvalidCookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700505}
506
507ApkAssetsCookie AssetManager2::GetResource(uint32_t resid, bool may_be_bag,
508 uint16_t density_override, Res_value* out_value,
509 ResTable_config* out_selected_config,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800510 uint32_t* out_flags) const {
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700511 FindEntryResult entry;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700512 ApkAssetsCookie cookie =
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700513 FindEntry(resid, density_override, false /* stop_at_first_match */, &entry);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700514 if (cookie == kInvalidCookie) {
515 return kInvalidCookie;
516 }
517
Adam Lesinski498f6052017-11-29 13:24:29 -0800518 if (dtohs(entry.entry->flags) & ResTable_entry::FLAG_COMPLEX) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700519 if (!may_be_bag) {
520 LOG(ERROR) << base::StringPrintf("Resource %08x is a complex map type.", resid);
Adam Lesinski0c405242017-01-13 20:47:26 -0800521 return kInvalidCookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700522 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800523
524 // Create a reference since we can't represent this complex type as a Res_value.
525 out_value->dataType = Res_value::TYPE_REFERENCE;
526 out_value->data = resid;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800527 *out_selected_config = entry.config;
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700528 *out_flags = entry.type_flags;
Adam Lesinski0c405242017-01-13 20:47:26 -0800529 return cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700530 }
531
532 const Res_value* device_value = reinterpret_cast<const Res_value*>(
533 reinterpret_cast<const uint8_t*>(entry.entry) + dtohs(entry.entry->size));
534 out_value->copyFrom_dtoh(*device_value);
Adam Lesinskida431a22016-12-29 16:08:16 -0500535
536 // Convert the package ID to the runtime assigned package ID.
537 entry.dynamic_ref_table->lookupResourceValue(out_value);
538
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800539 *out_selected_config = entry.config;
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700540 *out_flags = entry.type_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700541 return cookie;
542}
543
Adam Lesinski0c405242017-01-13 20:47:26 -0800544ApkAssetsCookie AssetManager2::ResolveReference(ApkAssetsCookie cookie, Res_value* in_out_value,
545 ResTable_config* in_out_selected_config,
546 uint32_t* in_out_flags,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800547 uint32_t* out_last_reference) const {
Adam Lesinski0c405242017-01-13 20:47:26 -0800548 constexpr const int kMaxIterations = 20;
549
Adam Lesinski0c405242017-01-13 20:47:26 -0800550 for (size_t iteration = 0u; in_out_value->dataType == Res_value::TYPE_REFERENCE &&
551 in_out_value->data != 0u && iteration < kMaxIterations;
552 iteration++) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800553 *out_last_reference = in_out_value->data;
Adam Lesinski0c405242017-01-13 20:47:26 -0800554 uint32_t new_flags = 0u;
555 cookie = GetResource(in_out_value->data, true /*may_be_bag*/, 0u /*density_override*/,
556 in_out_value, in_out_selected_config, &new_flags);
557 if (cookie == kInvalidCookie) {
558 return kInvalidCookie;
559 }
560 if (in_out_flags != nullptr) {
561 *in_out_flags |= new_flags;
562 }
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800563 if (*out_last_reference == in_out_value->data) {
Adam Lesinski0c405242017-01-13 20:47:26 -0800564 // This reference can't be resolved, so exit now and let the caller deal with it.
565 return cookie;
566 }
567 }
568 return cookie;
569}
570
Adam Lesinski7ad11102016-10-28 16:39:15 -0700571const ResolvedBag* AssetManager2::GetBag(uint32_t resid) {
y57cd1952018-04-12 14:26:23 -0700572 auto found_resids = std::vector<uint32_t>();
573 return GetBag(resid, found_resids);
574}
575
576const ResolvedBag* AssetManager2::GetBag(uint32_t resid, std::vector<uint32_t>& child_resids) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800577 ATRACE_NAME("AssetManager::GetBag");
Adam Lesinski7ad11102016-10-28 16:39:15 -0700578
579 auto cached_iter = cached_bags_.find(resid);
580 if (cached_iter != cached_bags_.end()) {
581 return cached_iter->second.get();
582 }
583
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700584 FindEntryResult entry;
585 ApkAssetsCookie cookie =
586 FindEntry(resid, 0u /* density_override */, false /* stop_at_first_match */, &entry);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700587 if (cookie == kInvalidCookie) {
588 return nullptr;
589 }
590
591 // Check that the size of the entry header is at least as big as
592 // the desired ResTable_map_entry. Also verify that the entry
593 // was intended to be a map.
594 if (dtohs(entry.entry->size) < sizeof(ResTable_map_entry) ||
595 (dtohs(entry.entry->flags) & ResTable_entry::FLAG_COMPLEX) == 0) {
596 // Not a bag, nothing to do.
597 return nullptr;
598 }
599
600 const ResTable_map_entry* map = reinterpret_cast<const ResTable_map_entry*>(entry.entry);
601 const ResTable_map* map_entry =
602 reinterpret_cast<const ResTable_map*>(reinterpret_cast<const uint8_t*>(map) + map->size);
603 const ResTable_map* const map_entry_end = map_entry + dtohl(map->count);
604
y57cd1952018-04-12 14:26:23 -0700605 // Keep track of ids that have already been seen to prevent infinite loops caused by circular
606 // dependencies between bags
607 child_resids.push_back(resid);
608
Adam Lesinskida431a22016-12-29 16:08:16 -0500609 uint32_t parent_resid = dtohl(map->parent.ident);
y57cd1952018-04-12 14:26:23 -0700610 if (parent_resid == 0 || std::find(child_resids.begin(), child_resids.end(), parent_resid)
611 != child_resids.end()) {
612 // There is no parent or that a circular dependency exist, meaning there is nothing to
613 // inherit and we can do a simple copy of the entries in the map.
Adam Lesinski7ad11102016-10-28 16:39:15 -0700614 const size_t entry_count = map_entry_end - map_entry;
615 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
616 malloc(sizeof(ResolvedBag) + (entry_count * sizeof(ResolvedBag::Entry))))};
617 ResolvedBag::Entry* new_entry = new_bag->entries;
618 for (; map_entry != map_entry_end; ++map_entry) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500619 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -0800620 if (!is_internal_resid(new_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500621 // Attributes, arrays, etc don't have a resource id as the name. They specify
622 // other data, which would be wrong to change via a lookup.
623 if (entry.dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800624 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
625 resid);
Adam Lesinskida431a22016-12-29 16:08:16 -0500626 return nullptr;
627 }
628 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700629 new_entry->cookie = cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -0500630 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700631 new_entry->key_pool = nullptr;
632 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -0700633 new_entry->value.copyFrom_dtoh(map_entry->value);
634 status_t err = entry.dynamic_ref_table->lookupResourceValue(&new_entry->value);
635 if (err != NO_ERROR) {
636 LOG(ERROR) << base::StringPrintf(
637 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
638 new_entry->value.data, new_key);
639 return nullptr;
640 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700641 ++new_entry;
642 }
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700643 new_bag->type_spec_flags = entry.type_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700644 new_bag->entry_count = static_cast<uint32_t>(entry_count);
645 ResolvedBag* result = new_bag.get();
646 cached_bags_[resid] = std::move(new_bag);
647 return result;
648 }
649
Adam Lesinskida431a22016-12-29 16:08:16 -0500650 // In case the parent is a dynamic reference, resolve it.
651 entry.dynamic_ref_table->lookupResourceId(&parent_resid);
652
Adam Lesinski7ad11102016-10-28 16:39:15 -0700653 // Get the parent and do a merge of the keys.
y57cd1952018-04-12 14:26:23 -0700654 const ResolvedBag* parent_bag = GetBag(parent_resid, child_resids);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700655 if (parent_bag == nullptr) {
656 // Failed to get the parent that should exist.
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800657 LOG(ERROR) << base::StringPrintf("Failed to find parent 0x%08x of bag 0x%08x.", parent_resid,
658 resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700659 return nullptr;
660 }
661
Adam Lesinski7ad11102016-10-28 16:39:15 -0700662 // Create the max possible entries we can make. Once we construct the bag,
663 // we will realloc to fit to size.
664 const size_t max_count = parent_bag->entry_count + dtohl(map->count);
George Burgess IV09b119f2017-07-25 15:00:04 -0700665 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
666 malloc(sizeof(ResolvedBag) + (max_count * sizeof(ResolvedBag::Entry))))};
Adam Lesinski7ad11102016-10-28 16:39:15 -0700667 ResolvedBag::Entry* new_entry = new_bag->entries;
668
669 const ResolvedBag::Entry* parent_entry = parent_bag->entries;
670 const ResolvedBag::Entry* const parent_entry_end = parent_entry + parent_bag->entry_count;
671
672 // The keys are expected to be in sorted order. Merge the two bags.
673 while (map_entry != map_entry_end && parent_entry != parent_entry_end) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500674 uint32_t child_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -0800675 if (!is_internal_resid(child_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500676 if (entry.dynamic_ref_table->lookupResourceId(&child_key) != NO_ERROR) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800677 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", child_key,
678 resid);
Adam Lesinskida431a22016-12-29 16:08:16 -0500679 return nullptr;
680 }
681 }
682
Adam Lesinski7ad11102016-10-28 16:39:15 -0700683 if (child_key <= parent_entry->key) {
684 // Use the child key if it comes before the parent
685 // or is equal to the parent (overrides).
686 new_entry->cookie = cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700687 new_entry->key = child_key;
688 new_entry->key_pool = nullptr;
689 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -0700690 new_entry->value.copyFrom_dtoh(map_entry->value);
691 status_t err = entry.dynamic_ref_table->lookupResourceValue(&new_entry->value);
692 if (err != NO_ERROR) {
693 LOG(ERROR) << base::StringPrintf(
694 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
695 new_entry->value.data, child_key);
696 return nullptr;
697 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700698 ++map_entry;
699 } else {
700 // Take the parent entry as-is.
701 memcpy(new_entry, parent_entry, sizeof(*new_entry));
702 }
703
704 if (child_key >= parent_entry->key) {
705 // Move to the next parent entry if we used it or it was overridden.
706 ++parent_entry;
707 }
708 // Increment to the next entry to fill.
709 ++new_entry;
710 }
711
712 // Finish the child entries if they exist.
713 while (map_entry != map_entry_end) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500714 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -0800715 if (!is_internal_resid(new_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500716 if (entry.dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800717 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
718 resid);
Adam Lesinskida431a22016-12-29 16:08:16 -0500719 return nullptr;
720 }
721 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700722 new_entry->cookie = cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -0500723 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700724 new_entry->key_pool = nullptr;
725 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -0700726 new_entry->value.copyFrom_dtoh(map_entry->value);
727 status_t err = entry.dynamic_ref_table->lookupResourceValue(&new_entry->value);
728 if (err != NO_ERROR) {
729 LOG(ERROR) << base::StringPrintf("Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.",
730 new_entry->value.dataType, new_entry->value.data, new_key);
731 return nullptr;
732 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700733 ++map_entry;
734 ++new_entry;
735 }
736
737 // Finish the parent entries if they exist.
738 if (parent_entry != parent_entry_end) {
739 // Take the rest of the parent entries as-is.
740 const size_t num_entries_to_copy = parent_entry_end - parent_entry;
741 memcpy(new_entry, parent_entry, num_entries_to_copy * sizeof(*new_entry));
742 new_entry += num_entries_to_copy;
743 }
744
745 // Resize the resulting array to fit.
746 const size_t actual_count = new_entry - new_bag->entries;
747 if (actual_count != max_count) {
George Burgess IV09b119f2017-07-25 15:00:04 -0700748 new_bag.reset(reinterpret_cast<ResolvedBag*>(realloc(
749 new_bag.release(), sizeof(ResolvedBag) + (actual_count * sizeof(ResolvedBag::Entry)))));
Adam Lesinski7ad11102016-10-28 16:39:15 -0700750 }
751
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700752 // Combine flags from the parent and our own bag.
753 new_bag->type_spec_flags = entry.type_flags | parent_bag->type_spec_flags;
George Burgess IV09b119f2017-07-25 15:00:04 -0700754 new_bag->entry_count = static_cast<uint32_t>(actual_count);
755 ResolvedBag* result = new_bag.get();
756 cached_bags_[resid] = std::move(new_bag);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700757 return result;
758}
759
Adam Lesinski929d6512017-01-16 19:11:19 -0800760static bool Utf8ToUtf16(const StringPiece& str, std::u16string* out) {
761 ssize_t len =
762 utf8_to_utf16_length(reinterpret_cast<const uint8_t*>(str.data()), str.size(), false);
763 if (len < 0) {
764 return false;
765 }
766 out->resize(static_cast<size_t>(len));
767 utf8_to_utf16(reinterpret_cast<const uint8_t*>(str.data()), str.size(), &*out->begin(),
768 static_cast<size_t>(len + 1));
769 return true;
770}
771
Adam Lesinski0c405242017-01-13 20:47:26 -0800772uint32_t AssetManager2::GetResourceId(const std::string& resource_name,
773 const std::string& fallback_type,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800774 const std::string& fallback_package) const {
Adam Lesinski929d6512017-01-16 19:11:19 -0800775 StringPiece package_name, type, entry;
776 if (!ExtractResourceName(resource_name, &package_name, &type, &entry)) {
777 return 0u;
778 }
779
780 if (entry.empty()) {
781 return 0u;
782 }
783
784 if (package_name.empty()) {
785 package_name = fallback_package;
786 }
787
788 if (type.empty()) {
789 type = fallback_type;
790 }
791
792 std::u16string type16;
793 if (!Utf8ToUtf16(type, &type16)) {
794 return 0u;
795 }
796
797 std::u16string entry16;
798 if (!Utf8ToUtf16(entry, &entry16)) {
799 return 0u;
800 }
801
802 const StringPiece16 kAttr16 = u"attr";
803 const static std::u16string kAttrPrivate16 = u"^attr-private";
804
805 for (const PackageGroup& package_group : package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800806 for (const ConfiguredPackage& package_impl : package_group.packages_) {
807 const LoadedPackage* package = package_impl.loaded_package_;
Adam Lesinski929d6512017-01-16 19:11:19 -0800808 if (package_name != package->GetPackageName()) {
809 // All packages in the same group are expected to have the same package name.
810 break;
811 }
812
813 uint32_t resid = package->FindEntryByName(type16, entry16);
814 if (resid == 0u && kAttr16 == type16) {
815 // Private attributes in libraries (such as the framework) are sometimes encoded
816 // under the type '^attr-private' in order to leave the ID space of public 'attr'
817 // free for future additions. Check '^attr-private' for the same name.
818 resid = package->FindEntryByName(kAttrPrivate16, entry16);
819 }
820
821 if (resid != 0u) {
822 return fix_package_id(resid, package_group.dynamic_ref_table.mAssignedPackageId);
823 }
824 }
825 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800826 return 0u;
827}
828
Mårten Kongstad668ec5b2018-06-11 14:11:33 +0200829void AssetManager2::RebuildFilterList(bool filter_incompatible_configs) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800830 for (PackageGroup& group : package_groups_) {
831 for (ConfiguredPackage& impl : group.packages_) {
832 // Destroy it.
833 impl.filtered_configs_.~ByteBucketArray();
834
835 // Re-create it.
836 new (&impl.filtered_configs_) ByteBucketArray<FilteredConfigGroup>();
837
838 // Create the filters here.
839 impl.loaded_package_->ForEachTypeSpec([&](const TypeSpec* spec, uint8_t type_index) {
840 FilteredConfigGroup& group = impl.filtered_configs_.editItemAt(type_index);
841 const auto iter_end = spec->types + spec->type_count;
842 for (auto iter = spec->types; iter != iter_end; ++iter) {
843 ResTable_config this_config;
844 this_config.copyFromDtoH((*iter)->config);
Mårten Kongstad668ec5b2018-06-11 14:11:33 +0200845 if (!filter_incompatible_configs || this_config.match(configuration_)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800846 group.configurations.push_back(this_config);
847 group.types.push_back(*iter);
848 }
849 }
850 });
851 }
852 }
853}
854
Adam Lesinski7ad11102016-10-28 16:39:15 -0700855void AssetManager2::InvalidateCaches(uint32_t diff) {
856 if (diff == 0xffffffffu) {
857 // Everything must go.
858 cached_bags_.clear();
859 return;
860 }
861
862 // Be more conservative with what gets purged. Only if the bag has other possible
863 // variations with respect to what changed (diff) should we remove it.
864 for (auto iter = cached_bags_.cbegin(); iter != cached_bags_.cend();) {
865 if (diff & iter->second->type_spec_flags) {
866 iter = cached_bags_.erase(iter);
867 } else {
868 ++iter;
869 }
870 }
871}
872
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -0700873uint8_t AssetManager2::GetAssignedPackageId(const LoadedPackage* package) {
874 for (auto& package_group : package_groups_) {
875 for (auto& package2 : package_group.packages_) {
876 if (package2.loaded_package_ == package) {
877 return package_group.dynamic_ref_table.mAssignedPackageId;
878 }
879 }
880 }
881 return 0;
882}
883
Adam Lesinski30080e22017-10-16 16:18:09 -0700884std::unique_ptr<Theme> AssetManager2::NewTheme() {
885 return std::unique_ptr<Theme>(new Theme(this));
886}
887
888Theme::Theme(AssetManager2* asset_manager) : asset_manager_(asset_manager) {
889}
890
891Theme::~Theme() = default;
892
893namespace {
894
895struct ThemeEntry {
896 ApkAssetsCookie cookie;
897 uint32_t type_spec_flags;
898 Res_value value;
899};
900
901struct ThemeType {
902 int entry_count;
903 ThemeEntry entries[0];
904};
905
906constexpr size_t kTypeCount = std::numeric_limits<uint8_t>::max() + 1;
907
908} // namespace
909
910struct Theme::Package {
911 // Each element of Type will be a dynamically sized object
912 // allocated to have the entries stored contiguously with the Type.
913 std::array<util::unique_cptr<ThemeType>, kTypeCount> types;
914};
Adam Lesinski7ad11102016-10-28 16:39:15 -0700915
916bool Theme::ApplyStyle(uint32_t resid, bool force) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800917 ATRACE_NAME("Theme::ApplyStyle");
Adam Lesinski7ad11102016-10-28 16:39:15 -0700918
919 const ResolvedBag* bag = asset_manager_->GetBag(resid);
920 if (bag == nullptr) {
921 return false;
922 }
923
924 // Merge the flags from this style.
925 type_spec_flags_ |= bag->type_spec_flags;
926
Adam Lesinski30080e22017-10-16 16:18:09 -0700927 int last_type_idx = -1;
928 int last_package_idx = -1;
929 Package* last_package = nullptr;
930 ThemeType* last_type = nullptr;
931
932 // Iterate backwards, because each bag is sorted in ascending key ID order, meaning we will only
933 // need to perform one resize per type.
934 using reverse_bag_iterator = std::reverse_iterator<const ResolvedBag::Entry*>;
935 const auto bag_iter_end = reverse_bag_iterator(begin(bag));
936 for (auto bag_iter = reverse_bag_iterator(end(bag)); bag_iter != bag_iter_end; ++bag_iter) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700937 const uint32_t attr_resid = bag_iter->key;
938
Adam Lesinski30080e22017-10-16 16:18:09 -0700939 // If the resource ID passed in is not a style, the key can be some other identifier that is not
940 // a resource ID. We should fail fast instead of operating with strange resource IDs.
Adam Lesinski929d6512017-01-16 19:11:19 -0800941 if (!is_valid_resid(attr_resid)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700942 return false;
943 }
944
Adam Lesinski30080e22017-10-16 16:18:09 -0700945 // We don't use the 0-based index for the type so that we can avoid doing ID validation
946 // upon lookup. Instead, we keep space for the type ID 0 in our data structures. Since
947 // the construction of this type is guarded with a resource ID check, it will never be
948 // populated, and querying type ID 0 will always fail.
949 const int package_idx = get_package_id(attr_resid);
950 const int type_idx = get_type_id(attr_resid);
951 const int entry_idx = get_entry_id(attr_resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700952
Adam Lesinski30080e22017-10-16 16:18:09 -0700953 if (last_package_idx != package_idx) {
954 std::unique_ptr<Package>& package = packages_[package_idx];
955 if (package == nullptr) {
956 package.reset(new Package());
Adam Lesinski7ad11102016-10-28 16:39:15 -0700957 }
Adam Lesinski30080e22017-10-16 16:18:09 -0700958 last_package_idx = package_idx;
959 last_package = package.get();
960 last_type_idx = -1;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700961 }
Adam Lesinski30080e22017-10-16 16:18:09 -0700962
963 if (last_type_idx != type_idx) {
964 util::unique_cptr<ThemeType>& type = last_package->types[type_idx];
965 if (type == nullptr) {
966 // Allocate enough memory to contain this entry_idx. Since we're iterating in reverse over
967 // a sorted list of attributes, this shouldn't be resized again during this method call.
968 type.reset(reinterpret_cast<ThemeType*>(
969 calloc(sizeof(ThemeType) + (entry_idx + 1) * sizeof(ThemeEntry), 1)));
970 type->entry_count = entry_idx + 1;
971 } else if (entry_idx >= type->entry_count) {
972 // Reallocate the memory to contain this entry_idx. Since we're iterating in reverse over
973 // a sorted list of attributes, this shouldn't be resized again during this method call.
974 const int new_count = entry_idx + 1;
975 type.reset(reinterpret_cast<ThemeType*>(
976 realloc(type.release(), sizeof(ThemeType) + (new_count * sizeof(ThemeEntry)))));
977
978 // Clear out the newly allocated space (which isn't zeroed).
979 memset(type->entries + type->entry_count, 0,
980 (new_count - type->entry_count) * sizeof(ThemeEntry));
981 type->entry_count = new_count;
982 }
983 last_type_idx = type_idx;
984 last_type = type.get();
985 }
986
987 ThemeEntry& entry = last_type->entries[entry_idx];
988 if (force || (entry.value.dataType == Res_value::TYPE_NULL &&
989 entry.value.data != Res_value::DATA_NULL_EMPTY)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700990 entry.cookie = bag_iter->cookie;
991 entry.type_spec_flags |= bag->type_spec_flags;
992 entry.value = bag_iter->value;
993 }
994 }
995 return true;
996}
997
998ApkAssetsCookie Theme::GetAttribute(uint32_t resid, Res_value* out_value,
999 uint32_t* out_flags) const {
Adam Lesinski30080e22017-10-16 16:18:09 -07001000 int cnt = 20;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001001
1002 uint32_t type_spec_flags = 0u;
1003
Adam Lesinski30080e22017-10-16 16:18:09 -07001004 do {
1005 const int package_idx = get_package_id(resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001006 const Package* package = packages_[package_idx].get();
Adam Lesinski30080e22017-10-16 16:18:09 -07001007 if (package != nullptr) {
1008 // The themes are constructed with a 1-based type ID, so no need to decrement here.
1009 const int type_idx = get_type_id(resid);
1010 const ThemeType* type = package->types[type_idx].get();
1011 if (type != nullptr) {
1012 const int entry_idx = get_entry_id(resid);
1013 if (entry_idx < type->entry_count) {
1014 const ThemeEntry& entry = type->entries[entry_idx];
1015 type_spec_flags |= entry.type_spec_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001016
Adam Lesinski30080e22017-10-16 16:18:09 -07001017 if (entry.value.dataType == Res_value::TYPE_ATTRIBUTE) {
1018 if (cnt > 0) {
1019 cnt--;
1020 resid = entry.value.data;
1021 continue;
1022 }
1023 return kInvalidCookie;
1024 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001025
Adam Lesinski30080e22017-10-16 16:18:09 -07001026 // @null is different than @empty.
1027 if (entry.value.dataType == Res_value::TYPE_NULL &&
1028 entry.value.data != Res_value::DATA_NULL_EMPTY) {
1029 return kInvalidCookie;
1030 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001031
Adam Lesinski30080e22017-10-16 16:18:09 -07001032 *out_value = entry.value;
Adam Lesinskida431a22016-12-29 16:08:16 -05001033 *out_flags = type_spec_flags;
Adam Lesinski30080e22017-10-16 16:18:09 -07001034 return entry.cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -05001035 }
Adam Lesinskida431a22016-12-29 16:08:16 -05001036 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001037 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001038 break;
1039 } while (true);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001040 return kInvalidCookie;
1041}
1042
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001043ApkAssetsCookie Theme::ResolveAttributeReference(ApkAssetsCookie cookie, Res_value* in_out_value,
1044 ResTable_config* in_out_selected_config,
1045 uint32_t* in_out_type_spec_flags,
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001046 uint32_t* out_last_ref) const {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001047 if (in_out_value->dataType == Res_value::TYPE_ATTRIBUTE) {
1048 uint32_t new_flags;
1049 cookie = GetAttribute(in_out_value->data, in_out_value, &new_flags);
1050 if (cookie == kInvalidCookie) {
1051 return kInvalidCookie;
1052 }
1053
1054 if (in_out_type_spec_flags != nullptr) {
1055 *in_out_type_spec_flags |= new_flags;
1056 }
1057 }
1058 return asset_manager_->ResolveReference(cookie, in_out_value, in_out_selected_config,
1059 in_out_type_spec_flags, out_last_ref);
1060}
1061
Adam Lesinski7ad11102016-10-28 16:39:15 -07001062void Theme::Clear() {
1063 type_spec_flags_ = 0u;
1064 for (std::unique_ptr<Package>& package : packages_) {
1065 package.reset();
1066 }
1067}
1068
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001069void Theme::SetTo(const Theme& o) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001070 if (this == &o) {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001071 return;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001072 }
1073
Adam Lesinski7ad11102016-10-28 16:39:15 -07001074 type_spec_flags_ = o.type_spec_flags_;
1075
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001076 if (asset_manager_ == o.asset_manager_) {
1077 // The theme comes from the same asset manager so all theme data can be copied exactly
1078 for (size_t p = 0; p < packages_.size(); p++) {
1079 const Package *package = o.packages_[p].get();
1080 if (package == nullptr) {
1081 // The other theme doesn't have this package, clear ours.
1082 packages_[p].reset();
Adam Lesinski7ad11102016-10-28 16:39:15 -07001083 continue;
1084 }
1085
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001086 if (packages_[p] == nullptr) {
1087 // The other theme has this package, but we don't. Make one.
1088 packages_[p].reset(new Package());
1089 }
1090
1091 for (size_t t = 0; t < package->types.size(); t++) {
1092 const ThemeType *type = package->types[t].get();
1093 if (type == nullptr) {
1094 // The other theme doesn't have this type, clear ours.
1095 packages_[p]->types[t].reset();
1096 continue;
1097 }
1098
1099 // Create a new type and update it to theirs.
1100 const size_t type_alloc_size = sizeof(ThemeType) + (type->entry_count * sizeof(ThemeEntry));
1101 void *copied_data = malloc(type_alloc_size);
1102 memcpy(copied_data, type, type_alloc_size);
1103 packages_[p]->types[t].reset(reinterpret_cast<ThemeType *>(copied_data));
1104 }
1105 }
1106 } else {
1107 std::map<ApkAssetsCookie, ApkAssetsCookie> src_to_dest_asset_cookies;
1108 typedef std::map<int, int> SourceToDestinationRuntimePackageMap;
1109 std::map<ApkAssetsCookie, SourceToDestinationRuntimePackageMap> src_asset_cookie_id_map;
1110
1111 // Determine which ApkAssets are loaded in both theme AssetManagers
1112 std::vector<const ApkAssets*> src_assets = o.asset_manager_->GetApkAssets();
1113 for (size_t i = 0; i < src_assets.size(); i++) {
1114 const ApkAssets* src_asset = src_assets[i];
1115
1116 std::vector<const ApkAssets*> dest_assets = asset_manager_->GetApkAssets();
1117 for (size_t j = 0; j < dest_assets.size(); j++) {
1118 const ApkAssets* dest_asset = dest_assets[j];
1119
1120 // Map the runtime package of the source apk asset to the destination apk asset
1121 if (src_asset->GetPath() == dest_asset->GetPath()) {
1122 const std::vector<std::unique_ptr<const LoadedPackage>>& src_packages =
1123 src_asset->GetLoadedArsc()->GetPackages();
1124 const std::vector<std::unique_ptr<const LoadedPackage>>& dest_packages =
1125 dest_asset->GetLoadedArsc()->GetPackages();
1126
1127 SourceToDestinationRuntimePackageMap package_map;
1128
1129 // The source and destination package should have the same number of packages loaded in
1130 // the same order.
1131 const size_t N = src_packages.size();
1132 CHECK(N == dest_packages.size())
1133 << " LoadedArsc " << src_asset->GetPath() << " differs number of packages.";
1134 for (size_t p = 0; p < N; p++) {
1135 auto& src_package = src_packages[p];
1136 auto& dest_package = dest_packages[p];
1137 CHECK(src_package->GetPackageName() == dest_package->GetPackageName())
1138 << " Package " << src_package->GetPackageName() << " differs in load order.";
1139
1140 int src_package_id = o.asset_manager_->GetAssignedPackageId(src_package.get());
1141 int dest_package_id = asset_manager_->GetAssignedPackageId(dest_package.get());
1142 package_map[src_package_id] = dest_package_id;
1143 }
1144
1145 src_to_dest_asset_cookies.insert(std::pair<ApkAssetsCookie, ApkAssetsCookie>(i, j));
1146 src_asset_cookie_id_map.insert(
1147 std::pair<ApkAssetsCookie, SourceToDestinationRuntimePackageMap>(i, package_map));
1148 break;
1149 }
1150 }
1151 }
1152
1153 // Reset the data in the destination theme
1154 for (size_t p = 0; p < packages_.size(); p++) {
1155 if (packages_[p] != nullptr) {
1156 packages_[p].reset();
1157 }
1158 }
1159
1160 for (size_t p = 0; p < packages_.size(); p++) {
1161 const Package *package = o.packages_[p].get();
1162 if (package == nullptr) {
1163 continue;
1164 }
1165
1166 for (size_t t = 0; t < package->types.size(); t++) {
1167 const ThemeType *type = package->types[t].get();
1168 if (type == nullptr) {
1169 continue;
1170 }
1171
1172 for (size_t e = 0; e < type->entry_count; e++) {
1173 const ThemeEntry &entry = type->entries[e];
1174 if (entry.value.dataType == Res_value::TYPE_NULL &&
1175 entry.value.data != Res_value::DATA_NULL_EMPTY) {
1176 continue;
1177 }
1178
1179 // The package id of the attribute needs to be rewritten to the package id of the value in
1180 // the destination
1181 int attribute_dest_package_id = p;
1182 if (attribute_dest_package_id != 0x01) {
1183 // Find the cookie of the attribute resource id
1184 FindEntryResult attribute_entry_result;
1185 ApkAssetsCookie attribute_cookie =
1186 o.asset_manager_->FindEntry(make_resid(p, t, e), 0 /* density_override */ , false,
1187 &attribute_entry_result);
1188
1189 // Determine the package id of the attribute in the destination AssetManager
1190 auto attribute_package_map = src_asset_cookie_id_map.find(attribute_cookie);
1191 if (attribute_package_map == src_asset_cookie_id_map.end()) {
1192 continue;
1193 }
1194 auto attribute_dest_package = attribute_package_map->second.find(
1195 attribute_dest_package_id);
1196 if (attribute_dest_package == attribute_package_map->second.end()) {
1197 continue;
1198 }
1199 attribute_dest_package_id = attribute_dest_package->second;
1200 }
1201
1202 // If the attribute value represents an attribute or reference, the package id of the
1203 // value needs to be rewritten to the package id of the value in the destination
1204 uint32_t attribue_data = entry.value.data;
1205 if (entry.value.dataType == Res_value::TYPE_DYNAMIC_ATTRIBUTE
1206 || entry.value.dataType == Res_value::TYPE_DYNAMIC_REFERENCE
1207 || entry.value.dataType == Res_value::TYPE_ATTRIBUTE
1208 || entry.value.dataType == Res_value::TYPE_REFERENCE) {
1209
1210 // Determine the package id of the reference in the destination AssetManager
1211 auto value_package_map = src_asset_cookie_id_map.find(entry.cookie);
1212 if (value_package_map == src_asset_cookie_id_map.end()) {
1213 continue;
1214 }
1215
1216 auto value_dest_package = value_package_map->second.find(
1217 get_package_id(entry.value.data));
1218 if (value_dest_package == value_package_map->second.end()) {
1219 continue;
1220 }
1221
1222 attribue_data = fix_package_id(entry.value.data, value_dest_package->second);
1223 }
1224
1225 // Lazily instantiate the destination package
1226 std::unique_ptr<Package>& dest_package = packages_[attribute_dest_package_id];
1227 if (dest_package == nullptr) {
1228 dest_package.reset(new Package());
1229 }
1230
1231 // Lazily instantiate and resize the destination type
1232 util::unique_cptr<ThemeType>& dest_type = dest_package->types[t];
1233 if (dest_type == nullptr || dest_type->entry_count < type->entry_count) {
1234 const size_t type_alloc_size = sizeof(ThemeType)
1235 + (type->entry_count * sizeof(ThemeEntry));
1236 void* dest_data = malloc(type_alloc_size);
1237 memset(dest_data, 0, type->entry_count * sizeof(ThemeEntry));
1238
1239 // Copy the existing destination type values if the type is resized
1240 if (dest_type != nullptr) {
1241 memcpy(dest_data, type, sizeof(ThemeType)
1242 + (dest_type->entry_count * sizeof(ThemeEntry)));
1243 }
1244
1245 dest_type.reset(reinterpret_cast<ThemeType *>(dest_data));
1246 dest_type->entry_count = type->entry_count;
1247 }
1248
1249 // Find the cookie of the value in the destination
1250 auto value_dest_cookie = src_to_dest_asset_cookies.find(entry.cookie);
1251 if (value_dest_cookie == src_to_dest_asset_cookies.end()) {
1252 continue;
1253 }
1254
1255 dest_type->entries[e].cookie = value_dest_cookie->second;
1256 dest_type->entries[e].value.dataType = entry.value.dataType;
1257 dest_type->entries[e].value.data = attribue_data;
1258 dest_type->entries[e].type_spec_flags = entry.type_spec_flags;
1259 }
1260 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001261 }
1262 }
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001263}
1264
1265void Theme::Dump() const {
1266 base::ScopedLogSeverity _log(base::INFO);
1267 LOG(INFO) << base::StringPrintf("Theme(this=%p, AssetManager2=%p)", this, asset_manager_);
1268
1269 for (int p = 0; p < packages_.size(); p++) {
1270 auto& package = packages_[p];
1271 if (package == nullptr) {
1272 continue;
1273 }
1274
1275 for (int t = 0; t < package->types.size(); t++) {
1276 auto& type = package->types[t];
1277 if (type == nullptr) {
1278 continue;
1279 }
1280
1281 for (int e = 0; e < type->entry_count; e++) {
1282 auto& entry = type->entries[e];
1283 if (entry.value.dataType == Res_value::TYPE_NULL &&
1284 entry.value.data != Res_value::DATA_NULL_EMPTY) {
1285 continue;
1286 }
1287
1288 LOG(INFO) << base::StringPrintf(" entry(0x%08x)=(0x%08x) type=(0x%02x), cookie(%d)",
1289 make_resid(p, t, e), entry.value.data,
1290 entry.value.dataType, entry.cookie);
1291 }
1292 }
1293 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001294}
1295
1296} // namespace android