blob: d9f1293183b7fd6654c790f8fa2c3ed24b145408 [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
Adam Lesinski30080e22017-10-16 16:18:09 -070021#include <iterator>
Adam Lesinski0c405242017-01-13 20:47:26 -080022#include <set>
23
Adam Lesinski7ad11102016-10-28 16:39:15 -070024#include "android-base/logging.h"
25#include "android-base/stringprintf.h"
26#include "utils/ByteOrder.h"
27#include "utils/Trace.h"
28
29#ifdef _WIN32
30#ifdef ERROR
31#undef ERROR
32#endif
33#endif
34
Adam Lesinski929d6512017-01-16 19:11:19 -080035#include "androidfw/ResourceUtils.h"
36
Adam Lesinski7ad11102016-10-28 16:39:15 -070037namespace android {
38
Adam Lesinskibebfcc42018-02-12 14:27:46 -080039struct FindEntryResult {
40 // A pointer to the resource table entry for this resource.
41 // If the size of the entry is > sizeof(ResTable_entry), it can be cast to
42 // a ResTable_map_entry and processed as a bag/map.
43 const ResTable_entry* entry;
44
45 // The configuration for which the resulting entry was defined. This is already swapped to host
46 // endianness.
47 ResTable_config config;
48
49 // The bitmask of configuration axis with which the resource value varies.
50 uint32_t type_flags;
51
52 // The dynamic package ID map for the package from which this resource came from.
53 const DynamicRefTable* dynamic_ref_table;
54
55 // The string pool reference to the type's name. This uses a different string pool than
56 // the global string pool, but this is hidden from the caller.
57 StringPoolRef type_string_ref;
58
59 // The string pool reference to the entry's name. This uses a different string pool than
60 // the global string pool, but this is hidden from the caller.
61 StringPoolRef entry_string_ref;
62};
63
Adam Lesinski970bd8d2017-09-25 13:21:55 -070064AssetManager2::AssetManager2() {
65 memset(&configuration_, 0, sizeof(configuration_));
66}
Adam Lesinski7ad11102016-10-28 16:39:15 -070067
68bool AssetManager2::SetApkAssets(const std::vector<const ApkAssets*>& apk_assets,
69 bool invalidate_caches) {
70 apk_assets_ = apk_assets;
Adam Lesinskida431a22016-12-29 16:08:16 -050071 BuildDynamicRefTable();
Adam Lesinskibebfcc42018-02-12 14:27:46 -080072 RebuildFilterList();
Adam Lesinski7ad11102016-10-28 16:39:15 -070073 if (invalidate_caches) {
74 InvalidateCaches(static_cast<uint32_t>(-1));
75 }
76 return true;
77}
78
Adam Lesinskida431a22016-12-29 16:08:16 -050079void AssetManager2::BuildDynamicRefTable() {
80 package_groups_.clear();
81 package_ids_.fill(0xff);
82
83 // 0x01 is reserved for the android package.
84 int next_package_id = 0x02;
85 const size_t apk_assets_count = apk_assets_.size();
86 for (size_t i = 0; i < apk_assets_count; i++) {
Adam Lesinski970bd8d2017-09-25 13:21:55 -070087 const LoadedArsc* loaded_arsc = apk_assets_[i]->GetLoadedArsc();
88
89 for (const std::unique_ptr<const LoadedPackage>& package : loaded_arsc->GetPackages()) {
Adam Lesinskida431a22016-12-29 16:08:16 -050090 // Get the package ID or assign one if a shared library.
91 int package_id;
92 if (package->IsDynamic()) {
93 package_id = next_package_id++;
94 } else {
95 package_id = package->GetPackageId();
96 }
97
98 // Add the mapping for package ID to index if not present.
99 uint8_t idx = package_ids_[package_id];
100 if (idx == 0xff) {
101 package_ids_[package_id] = idx = static_cast<uint8_t>(package_groups_.size());
102 package_groups_.push_back({});
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800103 DynamicRefTable& ref_table = package_groups_.back().dynamic_ref_table;
104 ref_table.mAssignedPackageId = package_id;
105 ref_table.mAppAsLib = package->IsDynamic() && package->GetPackageId() == 0x7f;
Adam Lesinskida431a22016-12-29 16:08:16 -0500106 }
107 PackageGroup* package_group = &package_groups_[idx];
108
109 // Add the package and to the set of packages with the same ID.
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800110 package_group->packages_.push_back(ConfiguredPackage{package.get(), {}});
Adam Lesinskida431a22016-12-29 16:08:16 -0500111 package_group->cookies_.push_back(static_cast<ApkAssetsCookie>(i));
112
113 // Add the package name -> build time ID mappings.
114 for (const DynamicPackageEntry& entry : package->GetDynamicPackageMap()) {
115 String16 package_name(entry.package_name.c_str(), entry.package_name.size());
116 package_group->dynamic_ref_table.mEntries.replaceValueFor(
117 package_name, static_cast<uint8_t>(entry.package_id));
118 }
119 }
120 }
121
122 // Now assign the runtime IDs so that we have a build-time to runtime ID map.
123 const auto package_groups_end = package_groups_.end();
124 for (auto iter = package_groups_.begin(); iter != package_groups_end; ++iter) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800125 const std::string& package_name = iter->packages_[0].loaded_package_->GetPackageName();
Adam Lesinskida431a22016-12-29 16:08:16 -0500126 for (auto iter2 = package_groups_.begin(); iter2 != package_groups_end; ++iter2) {
127 iter2->dynamic_ref_table.addMapping(String16(package_name.c_str(), package_name.size()),
128 iter->dynamic_ref_table.mAssignedPackageId);
129 }
130 }
131}
132
133void AssetManager2::DumpToLog() const {
134 base::ScopedLogSeverity _log(base::INFO);
135
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800136 LOG(INFO) << base::StringPrintf("AssetManager2(this=%p)", this);
137
Adam Lesinskida431a22016-12-29 16:08:16 -0500138 std::string list;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800139 for (const auto& apk_assets : apk_assets_) {
140 base::StringAppendF(&list, "%s,", apk_assets->GetPath().c_str());
141 }
142 LOG(INFO) << "ApkAssets: " << list;
143
144 list = "";
Adam Lesinskida431a22016-12-29 16:08:16 -0500145 for (size_t i = 0; i < package_ids_.size(); i++) {
146 if (package_ids_[i] != 0xff) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800147 base::StringAppendF(&list, "%02x -> %d, ", (int)i, package_ids_[i]);
Adam Lesinskida431a22016-12-29 16:08:16 -0500148 }
149 }
150 LOG(INFO) << "Package ID map: " << list;
151
Adam Lesinski0dd36992018-01-25 15:38:38 -0800152 for (const auto& package_group: package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800153 list = "";
154 for (const auto& package : package_group.packages_) {
155 const LoadedPackage* loaded_package = package.loaded_package_;
156 base::StringAppendF(&list, "%s(%02x%s), ", loaded_package->GetPackageName().c_str(),
157 loaded_package->GetPackageId(),
158 (loaded_package->IsDynamic() ? " dynamic" : ""));
159 }
160 LOG(INFO) << base::StringPrintf("PG (%02x): ",
161 package_group.dynamic_ref_table.mAssignedPackageId)
162 << list;
Adam Lesinskida431a22016-12-29 16:08:16 -0500163 }
164}
Adam Lesinski7ad11102016-10-28 16:39:15 -0700165
166const ResStringPool* AssetManager2::GetStringPoolForCookie(ApkAssetsCookie cookie) const {
167 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
168 return nullptr;
169 }
170 return apk_assets_[cookie]->GetLoadedArsc()->GetStringPool();
171}
172
Adam Lesinskida431a22016-12-29 16:08:16 -0500173const DynamicRefTable* AssetManager2::GetDynamicRefTableForPackage(uint32_t package_id) const {
174 if (package_id >= package_ids_.size()) {
175 return nullptr;
176 }
177
178 const size_t idx = package_ids_[package_id];
179 if (idx == 0xff) {
180 return nullptr;
181 }
182 return &package_groups_[idx].dynamic_ref_table;
183}
184
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800185const DynamicRefTable* AssetManager2::GetDynamicRefTableForCookie(ApkAssetsCookie cookie) const {
186 for (const PackageGroup& package_group : package_groups_) {
187 for (const ApkAssetsCookie& package_cookie : package_group.cookies_) {
188 if (package_cookie == cookie) {
189 return &package_group.dynamic_ref_table;
190 }
191 }
192 }
193 return nullptr;
194}
195
Adam Lesinski7ad11102016-10-28 16:39:15 -0700196void AssetManager2::SetConfiguration(const ResTable_config& configuration) {
197 const int diff = configuration_.diff(configuration);
198 configuration_ = configuration;
199
200 if (diff) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800201 RebuildFilterList();
Adam Lesinski7ad11102016-10-28 16:39:15 -0700202 InvalidateCaches(static_cast<uint32_t>(diff));
203 }
204}
205
Adam Lesinski0c405242017-01-13 20:47:26 -0800206std::set<ResTable_config> AssetManager2::GetResourceConfigurations(bool exclude_system,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800207 bool exclude_mipmap) const {
208 ATRACE_NAME("AssetManager::GetResourceConfigurations");
Adam Lesinski0c405242017-01-13 20:47:26 -0800209 std::set<ResTable_config> configurations;
210 for (const PackageGroup& package_group : package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800211 for (const ConfiguredPackage& package : package_group.packages_) {
212 if (exclude_system && package.loaded_package_->IsSystem()) {
Adam Lesinski0c405242017-01-13 20:47:26 -0800213 continue;
214 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800215 package.loaded_package_->CollectConfigurations(exclude_mipmap, &configurations);
Adam Lesinski0c405242017-01-13 20:47:26 -0800216 }
217 }
218 return configurations;
219}
220
221std::set<std::string> AssetManager2::GetResourceLocales(bool exclude_system,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800222 bool merge_equivalent_languages) const {
223 ATRACE_NAME("AssetManager::GetResourceLocales");
Adam Lesinski0c405242017-01-13 20:47:26 -0800224 std::set<std::string> locales;
225 for (const PackageGroup& package_group : package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800226 for (const ConfiguredPackage& package : package_group.packages_) {
227 if (exclude_system && package.loaded_package_->IsSystem()) {
Adam Lesinski0c405242017-01-13 20:47:26 -0800228 continue;
229 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800230 package.loaded_package_->CollectLocales(merge_equivalent_languages, &locales);
Adam Lesinski0c405242017-01-13 20:47:26 -0800231 }
232 }
233 return locales;
234}
235
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800236std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename,
237 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700238 const std::string new_path = "assets/" + filename;
239 return OpenNonAsset(new_path, mode);
240}
241
242std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename, ApkAssetsCookie cookie,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800243 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700244 const std::string new_path = "assets/" + filename;
245 return OpenNonAsset(new_path, cookie, mode);
246}
247
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800248std::unique_ptr<AssetDir> AssetManager2::OpenDir(const std::string& dirname) const {
249 ATRACE_NAME("AssetManager::OpenDir");
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800250
251 std::string full_path = "assets/" + dirname;
252 std::unique_ptr<SortedVector<AssetDir::FileInfo>> files =
253 util::make_unique<SortedVector<AssetDir::FileInfo>>();
254
255 // Start from the back.
256 for (auto iter = apk_assets_.rbegin(); iter != apk_assets_.rend(); ++iter) {
257 const ApkAssets* apk_assets = *iter;
258
259 auto func = [&](const StringPiece& name, FileType type) {
260 AssetDir::FileInfo info;
261 info.setFileName(String8(name.data(), name.size()));
262 info.setFileType(type);
263 info.setSourceName(String8(apk_assets->GetPath().c_str()));
264 files->add(info);
265 };
266
267 if (!apk_assets->ForEachFile(full_path, func)) {
268 return {};
269 }
270 }
271
272 std::unique_ptr<AssetDir> asset_dir = util::make_unique<AssetDir>();
273 asset_dir->setFileList(files.release());
274 return asset_dir;
275}
276
Adam Lesinski7ad11102016-10-28 16:39:15 -0700277// Search in reverse because that's how we used to do it and we need to preserve behaviour.
278// This is unfortunate, because ClassLoaders delegate to the parent first, so the order
279// is inconsistent for split APKs.
280std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
281 Asset::AccessMode mode,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800282 ApkAssetsCookie* out_cookie) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700283 for (int32_t i = apk_assets_.size() - 1; i >= 0; i--) {
284 std::unique_ptr<Asset> asset = apk_assets_[i]->Open(filename, mode);
285 if (asset) {
286 if (out_cookie != nullptr) {
287 *out_cookie = i;
288 }
289 return asset;
290 }
291 }
292
293 if (out_cookie != nullptr) {
294 *out_cookie = kInvalidCookie;
295 }
296 return {};
297}
298
299std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800300 ApkAssetsCookie cookie,
301 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700302 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
303 return {};
304 }
305 return apk_assets_[cookie]->Open(filename, mode);
306}
307
308ApkAssetsCookie AssetManager2::FindEntry(uint32_t resid, uint16_t density_override,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800309 bool /*stop_at_first_match*/,
310 FindEntryResult* out_entry) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700311 // Might use this if density_override != 0.
312 ResTable_config density_override_config;
313
314 // Select our configuration or generate a density override configuration.
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800315 const ResTable_config* desired_config = &configuration_;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700316 if (density_override != 0 && density_override != configuration_.density) {
317 density_override_config = configuration_;
318 density_override_config.density = density_override;
319 desired_config = &density_override_config;
320 }
321
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800322 if (!is_valid_resid(resid)) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500323 LOG(ERROR) << base::StringPrintf("Invalid ID 0x%08x.", resid);
324 return kInvalidCookie;
325 }
326
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800327 const uint32_t package_id = get_package_id(resid);
328 const uint8_t type_idx = get_type_id(resid) - 1;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800329 const uint16_t entry_idx = get_entry_id(resid);
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800330
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800331 const uint8_t package_idx = package_ids_[package_id];
332 if (package_idx == 0xff) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500333 LOG(ERROR) << base::StringPrintf("No package ID %02x found for ID 0x%08x.", package_id, resid);
334 return kInvalidCookie;
335 }
336
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800337 const PackageGroup& package_group = package_groups_[package_idx];
Adam Lesinskib8b3a262018-02-09 11:01:45 -0800338 const size_t package_count = package_group.packages_.size();
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800339
340 ApkAssetsCookie best_cookie = kInvalidCookie;
341 const LoadedPackage* best_package = nullptr;
342 const ResTable_type* best_type = nullptr;
343 const ResTable_config* best_config = nullptr;
344 ResTable_config best_config_copy;
345 uint32_t best_offset = 0u;
346 uint32_t type_flags = 0u;
347
348 // If desired_config is the same as the set configuration, then we can use our filtered list
349 // and we don't need to match the configurations, since they already matched.
350 const bool use_fast_path = desired_config == &configuration_;
351
352 for (size_t pi = 0; pi < package_count; pi++) {
353 const ConfiguredPackage& loaded_package_impl = package_group.packages_[pi];
354 const LoadedPackage* loaded_package = loaded_package_impl.loaded_package_;
355 ApkAssetsCookie cookie = package_group.cookies_[pi];
356
357 // If the type IDs are offset in this package, we need to take that into account when searching
358 // for a type.
359 const TypeSpec* type_spec = loaded_package->GetTypeSpecByTypeIndex(type_idx);
360 if (UNLIKELY(type_spec == nullptr)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700361 continue;
362 }
363
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800364 uint16_t local_entry_idx = entry_idx;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700365
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800366 // If there is an IDMAP supplied with this package, translate the entry ID.
367 if (type_spec->idmap_entries != nullptr) {
368 if (!LoadedIdmap::Lookup(type_spec->idmap_entries, local_entry_idx, &local_entry_idx)) {
369 // There is no mapping, so the resource is not meant to be in this overlay package.
370 continue;
371 }
372 }
373
374 type_flags |= type_spec->GetFlagsForEntryIndex(local_entry_idx);
375
376 // If the package is an overlay, then even configurations that are the same MUST be chosen.
377 const bool package_is_overlay = loaded_package->IsOverlay();
378
379 const FilteredConfigGroup& filtered_group = loaded_package_impl.filtered_configs_[type_idx];
380 if (use_fast_path) {
381 const std::vector<ResTable_config>& candidate_configs = filtered_group.configurations;
382 const size_t type_count = candidate_configs.size();
383 for (uint32_t i = 0; i < type_count; i++) {
384 const ResTable_config& this_config = candidate_configs[i];
385
386 // We can skip calling ResTable_config::match() because we know that all candidate
387 // configurations that do NOT match have been filtered-out.
388 if ((best_config == nullptr || this_config.isBetterThan(*best_config, desired_config)) ||
389 (package_is_overlay && this_config.compare(*best_config) == 0)) {
390 // The configuration matches and is better than the previous selection.
391 // Find the entry value if it exists for this configuration.
392 const ResTable_type* type_chunk = filtered_group.types[i];
393 const uint32_t offset = LoadedPackage::GetEntryOffset(type_chunk, local_entry_idx);
394 if (offset == ResTable_type::NO_ENTRY) {
395 continue;
396 }
397
398 best_cookie = cookie;
399 best_package = loaded_package;
400 best_type = type_chunk;
401 best_config = &this_config;
402 best_offset = offset;
403 }
404 }
405 } else {
406 // This is the slower path, which doesn't use the filtered list of configurations.
407 // Here we must read the ResTable_config from the mmapped APK, convert it to host endianness
408 // and fill in any new fields that did not exist when the APK was compiled.
409 // Furthermore when selecting configurations we can't just record the pointer to the
410 // ResTable_config, we must copy it.
411 const auto iter_end = type_spec->types + type_spec->type_count;
412 for (auto iter = type_spec->types; iter != iter_end; ++iter) {
413 ResTable_config this_config;
414 this_config.copyFromDtoH((*iter)->config);
415
416 if (this_config.match(*desired_config)) {
417 if ((best_config == nullptr || this_config.isBetterThan(*best_config, desired_config)) ||
418 (package_is_overlay && this_config.compare(*best_config) == 0)) {
419 // The configuration matches and is better than the previous selection.
420 // Find the entry value if it exists for this configuration.
421 const uint32_t offset = LoadedPackage::GetEntryOffset(*iter, local_entry_idx);
422 if (offset == ResTable_type::NO_ENTRY) {
423 continue;
424 }
425
426 best_cookie = cookie;
427 best_package = loaded_package;
428 best_type = *iter;
429 best_config_copy = this_config;
430 best_config = &best_config_copy;
431 best_offset = offset;
432 }
433 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700434 }
435 }
436 }
437
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800438 if (UNLIKELY(best_cookie == kInvalidCookie)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700439 return kInvalidCookie;
440 }
441
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800442 const ResTable_entry* best_entry = LoadedPackage::GetEntryFromOffset(best_type, best_offset);
443 if (UNLIKELY(best_entry == nullptr)) {
444 return kInvalidCookie;
445 }
446
447 out_entry->entry = best_entry;
448 out_entry->config = *best_config;
449 out_entry->type_flags = type_flags;
450 out_entry->type_string_ref = StringPoolRef(best_package->GetTypeStringPool(), best_type->id - 1);
451 out_entry->entry_string_ref =
452 StringPoolRef(best_package->GetKeyStringPool(), best_entry->key.index);
Adam Lesinskida431a22016-12-29 16:08:16 -0500453 out_entry->dynamic_ref_table = &package_group.dynamic_ref_table;
Adam Lesinskida431a22016-12-29 16:08:16 -0500454 return best_cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700455}
456
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800457bool AssetManager2::GetResourceName(uint32_t resid, ResourceName* out_name) const {
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700458 FindEntryResult entry;
459 ApkAssetsCookie cookie =
460 FindEntry(resid, 0u /* density_override */, true /* stop_at_first_match */, &entry);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700461 if (cookie == kInvalidCookie) {
462 return false;
463 }
464
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800465 const LoadedPackage* package =
466 apk_assets_[cookie]->GetLoadedArsc()->GetPackageById(get_package_id(resid));
Adam Lesinskida431a22016-12-29 16:08:16 -0500467 if (package == nullptr) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700468 return false;
469 }
470
Adam Lesinskida431a22016-12-29 16:08:16 -0500471 out_name->package = package->GetPackageName().data();
472 out_name->package_len = package->GetPackageName().size();
Adam Lesinski7ad11102016-10-28 16:39:15 -0700473
474 out_name->type = entry.type_string_ref.string8(&out_name->type_len);
475 out_name->type16 = nullptr;
476 if (out_name->type == nullptr) {
477 out_name->type16 = entry.type_string_ref.string16(&out_name->type_len);
478 if (out_name->type16 == nullptr) {
479 return false;
480 }
481 }
482
483 out_name->entry = entry.entry_string_ref.string8(&out_name->entry_len);
484 out_name->entry16 = nullptr;
485 if (out_name->entry == nullptr) {
486 out_name->entry16 = entry.entry_string_ref.string16(&out_name->entry_len);
487 if (out_name->entry16 == nullptr) {
488 return false;
489 }
490 }
491 return true;
492}
493
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800494bool AssetManager2::GetResourceFlags(uint32_t resid, uint32_t* out_flags) const {
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700495 FindEntryResult entry;
496 ApkAssetsCookie cookie =
497 FindEntry(resid, 0u /* density_override */, false /* stop_at_first_match */, &entry);
498 if (cookie != kInvalidCookie) {
499 *out_flags = entry.type_flags;
500 return cookie;
501 }
502 return kInvalidCookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700503}
504
505ApkAssetsCookie AssetManager2::GetResource(uint32_t resid, bool may_be_bag,
506 uint16_t density_override, Res_value* out_value,
507 ResTable_config* out_selected_config,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800508 uint32_t* out_flags) const {
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700509 FindEntryResult entry;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700510 ApkAssetsCookie cookie =
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700511 FindEntry(resid, density_override, false /* stop_at_first_match */, &entry);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700512 if (cookie == kInvalidCookie) {
513 return kInvalidCookie;
514 }
515
Adam Lesinski498f6052017-11-29 13:24:29 -0800516 if (dtohs(entry.entry->flags) & ResTable_entry::FLAG_COMPLEX) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700517 if (!may_be_bag) {
518 LOG(ERROR) << base::StringPrintf("Resource %08x is a complex map type.", resid);
Adam Lesinski0c405242017-01-13 20:47:26 -0800519 return kInvalidCookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700520 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800521
522 // Create a reference since we can't represent this complex type as a Res_value.
523 out_value->dataType = Res_value::TYPE_REFERENCE;
524 out_value->data = resid;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800525 *out_selected_config = entry.config;
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700526 *out_flags = entry.type_flags;
Adam Lesinski0c405242017-01-13 20:47:26 -0800527 return cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700528 }
529
530 const Res_value* device_value = reinterpret_cast<const Res_value*>(
531 reinterpret_cast<const uint8_t*>(entry.entry) + dtohs(entry.entry->size));
532 out_value->copyFrom_dtoh(*device_value);
Adam Lesinskida431a22016-12-29 16:08:16 -0500533
534 // Convert the package ID to the runtime assigned package ID.
535 entry.dynamic_ref_table->lookupResourceValue(out_value);
536
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800537 *out_selected_config = entry.config;
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700538 *out_flags = entry.type_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700539 return cookie;
540}
541
Adam Lesinski0c405242017-01-13 20:47:26 -0800542ApkAssetsCookie AssetManager2::ResolveReference(ApkAssetsCookie cookie, Res_value* in_out_value,
543 ResTable_config* in_out_selected_config,
544 uint32_t* in_out_flags,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800545 uint32_t* out_last_reference) const {
Adam Lesinski0c405242017-01-13 20:47:26 -0800546 constexpr const int kMaxIterations = 20;
547
Adam Lesinski0c405242017-01-13 20:47:26 -0800548 for (size_t iteration = 0u; in_out_value->dataType == Res_value::TYPE_REFERENCE &&
549 in_out_value->data != 0u && iteration < kMaxIterations;
550 iteration++) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800551 *out_last_reference = in_out_value->data;
Adam Lesinski0c405242017-01-13 20:47:26 -0800552 uint32_t new_flags = 0u;
553 cookie = GetResource(in_out_value->data, true /*may_be_bag*/, 0u /*density_override*/,
554 in_out_value, in_out_selected_config, &new_flags);
555 if (cookie == kInvalidCookie) {
556 return kInvalidCookie;
557 }
558 if (in_out_flags != nullptr) {
559 *in_out_flags |= new_flags;
560 }
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800561 if (*out_last_reference == in_out_value->data) {
Adam Lesinski0c405242017-01-13 20:47:26 -0800562 // This reference can't be resolved, so exit now and let the caller deal with it.
563 return cookie;
564 }
565 }
566 return cookie;
567}
568
Adam Lesinski7ad11102016-10-28 16:39:15 -0700569const ResolvedBag* AssetManager2::GetBag(uint32_t resid) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800570 ATRACE_NAME("AssetManager::GetBag");
Adam Lesinski7ad11102016-10-28 16:39:15 -0700571
572 auto cached_iter = cached_bags_.find(resid);
573 if (cached_iter != cached_bags_.end()) {
574 return cached_iter->second.get();
575 }
576
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700577 FindEntryResult entry;
578 ApkAssetsCookie cookie =
579 FindEntry(resid, 0u /* density_override */, false /* stop_at_first_match */, &entry);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700580 if (cookie == kInvalidCookie) {
581 return nullptr;
582 }
583
584 // Check that the size of the entry header is at least as big as
585 // the desired ResTable_map_entry. Also verify that the entry
586 // was intended to be a map.
587 if (dtohs(entry.entry->size) < sizeof(ResTable_map_entry) ||
588 (dtohs(entry.entry->flags) & ResTable_entry::FLAG_COMPLEX) == 0) {
589 // Not a bag, nothing to do.
590 return nullptr;
591 }
592
593 const ResTable_map_entry* map = reinterpret_cast<const ResTable_map_entry*>(entry.entry);
594 const ResTable_map* map_entry =
595 reinterpret_cast<const ResTable_map*>(reinterpret_cast<const uint8_t*>(map) + map->size);
596 const ResTable_map* const map_entry_end = map_entry + dtohl(map->count);
597
Adam Lesinskida431a22016-12-29 16:08:16 -0500598 uint32_t parent_resid = dtohl(map->parent.ident);
599 if (parent_resid == 0) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700600 // There is no parent, meaning there is nothing to inherit and we can do a simple
601 // copy of the entries in the map.
602 const size_t entry_count = map_entry_end - map_entry;
603 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
604 malloc(sizeof(ResolvedBag) + (entry_count * sizeof(ResolvedBag::Entry))))};
605 ResolvedBag::Entry* new_entry = new_bag->entries;
606 for (; map_entry != map_entry_end; ++map_entry) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500607 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -0800608 if (!is_internal_resid(new_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500609 // Attributes, arrays, etc don't have a resource id as the name. They specify
610 // other data, which would be wrong to change via a lookup.
611 if (entry.dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800612 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
613 resid);
Adam Lesinskida431a22016-12-29 16:08:16 -0500614 return nullptr;
615 }
616 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700617 new_entry->cookie = cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -0500618 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700619 new_entry->key_pool = nullptr;
620 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -0700621 new_entry->value.copyFrom_dtoh(map_entry->value);
622 status_t err = entry.dynamic_ref_table->lookupResourceValue(&new_entry->value);
623 if (err != NO_ERROR) {
624 LOG(ERROR) << base::StringPrintf(
625 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
626 new_entry->value.data, new_key);
627 return nullptr;
628 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700629 ++new_entry;
630 }
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700631 new_bag->type_spec_flags = entry.type_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700632 new_bag->entry_count = static_cast<uint32_t>(entry_count);
633 ResolvedBag* result = new_bag.get();
634 cached_bags_[resid] = std::move(new_bag);
635 return result;
636 }
637
Adam Lesinskida431a22016-12-29 16:08:16 -0500638 // In case the parent is a dynamic reference, resolve it.
639 entry.dynamic_ref_table->lookupResourceId(&parent_resid);
640
Adam Lesinski7ad11102016-10-28 16:39:15 -0700641 // Get the parent and do a merge of the keys.
Adam Lesinskida431a22016-12-29 16:08:16 -0500642 const ResolvedBag* parent_bag = GetBag(parent_resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700643 if (parent_bag == nullptr) {
644 // Failed to get the parent that should exist.
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800645 LOG(ERROR) << base::StringPrintf("Failed to find parent 0x%08x of bag 0x%08x.", parent_resid,
646 resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700647 return nullptr;
648 }
649
Adam Lesinski7ad11102016-10-28 16:39:15 -0700650 // Create the max possible entries we can make. Once we construct the bag,
651 // we will realloc to fit to size.
652 const size_t max_count = parent_bag->entry_count + dtohl(map->count);
George Burgess IV09b119f2017-07-25 15:00:04 -0700653 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
654 malloc(sizeof(ResolvedBag) + (max_count * sizeof(ResolvedBag::Entry))))};
Adam Lesinski7ad11102016-10-28 16:39:15 -0700655 ResolvedBag::Entry* new_entry = new_bag->entries;
656
657 const ResolvedBag::Entry* parent_entry = parent_bag->entries;
658 const ResolvedBag::Entry* const parent_entry_end = parent_entry + parent_bag->entry_count;
659
660 // The keys are expected to be in sorted order. Merge the two bags.
661 while (map_entry != map_entry_end && parent_entry != parent_entry_end) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500662 uint32_t child_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -0800663 if (!is_internal_resid(child_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500664 if (entry.dynamic_ref_table->lookupResourceId(&child_key) != NO_ERROR) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800665 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", child_key,
666 resid);
Adam Lesinskida431a22016-12-29 16:08:16 -0500667 return nullptr;
668 }
669 }
670
Adam Lesinski7ad11102016-10-28 16:39:15 -0700671 if (child_key <= parent_entry->key) {
672 // Use the child key if it comes before the parent
673 // or is equal to the parent (overrides).
674 new_entry->cookie = cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700675 new_entry->key = child_key;
676 new_entry->key_pool = nullptr;
677 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -0700678 new_entry->value.copyFrom_dtoh(map_entry->value);
679 status_t err = entry.dynamic_ref_table->lookupResourceValue(&new_entry->value);
680 if (err != NO_ERROR) {
681 LOG(ERROR) << base::StringPrintf(
682 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
683 new_entry->value.data, child_key);
684 return nullptr;
685 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700686 ++map_entry;
687 } else {
688 // Take the parent entry as-is.
689 memcpy(new_entry, parent_entry, sizeof(*new_entry));
690 }
691
692 if (child_key >= parent_entry->key) {
693 // Move to the next parent entry if we used it or it was overridden.
694 ++parent_entry;
695 }
696 // Increment to the next entry to fill.
697 ++new_entry;
698 }
699
700 // Finish the child entries if they exist.
701 while (map_entry != map_entry_end) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500702 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -0800703 if (!is_internal_resid(new_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500704 if (entry.dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800705 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
706 resid);
Adam Lesinskida431a22016-12-29 16:08:16 -0500707 return nullptr;
708 }
709 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700710 new_entry->cookie = cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -0500711 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700712 new_entry->key_pool = nullptr;
713 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -0700714 new_entry->value.copyFrom_dtoh(map_entry->value);
715 status_t err = entry.dynamic_ref_table->lookupResourceValue(&new_entry->value);
716 if (err != NO_ERROR) {
717 LOG(ERROR) << base::StringPrintf("Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.",
718 new_entry->value.dataType, new_entry->value.data, new_key);
719 return nullptr;
720 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700721 ++map_entry;
722 ++new_entry;
723 }
724
725 // Finish the parent entries if they exist.
726 if (parent_entry != parent_entry_end) {
727 // Take the rest of the parent entries as-is.
728 const size_t num_entries_to_copy = parent_entry_end - parent_entry;
729 memcpy(new_entry, parent_entry, num_entries_to_copy * sizeof(*new_entry));
730 new_entry += num_entries_to_copy;
731 }
732
733 // Resize the resulting array to fit.
734 const size_t actual_count = new_entry - new_bag->entries;
735 if (actual_count != max_count) {
George Burgess IV09b119f2017-07-25 15:00:04 -0700736 new_bag.reset(reinterpret_cast<ResolvedBag*>(realloc(
737 new_bag.release(), sizeof(ResolvedBag) + (actual_count * sizeof(ResolvedBag::Entry)))));
Adam Lesinski7ad11102016-10-28 16:39:15 -0700738 }
739
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700740 // Combine flags from the parent and our own bag.
741 new_bag->type_spec_flags = entry.type_flags | parent_bag->type_spec_flags;
George Burgess IV09b119f2017-07-25 15:00:04 -0700742 new_bag->entry_count = static_cast<uint32_t>(actual_count);
743 ResolvedBag* result = new_bag.get();
744 cached_bags_[resid] = std::move(new_bag);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700745 return result;
746}
747
Adam Lesinski929d6512017-01-16 19:11:19 -0800748static bool Utf8ToUtf16(const StringPiece& str, std::u16string* out) {
749 ssize_t len =
750 utf8_to_utf16_length(reinterpret_cast<const uint8_t*>(str.data()), str.size(), false);
751 if (len < 0) {
752 return false;
753 }
754 out->resize(static_cast<size_t>(len));
755 utf8_to_utf16(reinterpret_cast<const uint8_t*>(str.data()), str.size(), &*out->begin(),
756 static_cast<size_t>(len + 1));
757 return true;
758}
759
Adam Lesinski0c405242017-01-13 20:47:26 -0800760uint32_t AssetManager2::GetResourceId(const std::string& resource_name,
761 const std::string& fallback_type,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800762 const std::string& fallback_package) const {
Adam Lesinski929d6512017-01-16 19:11:19 -0800763 StringPiece package_name, type, entry;
764 if (!ExtractResourceName(resource_name, &package_name, &type, &entry)) {
765 return 0u;
766 }
767
768 if (entry.empty()) {
769 return 0u;
770 }
771
772 if (package_name.empty()) {
773 package_name = fallback_package;
774 }
775
776 if (type.empty()) {
777 type = fallback_type;
778 }
779
780 std::u16string type16;
781 if (!Utf8ToUtf16(type, &type16)) {
782 return 0u;
783 }
784
785 std::u16string entry16;
786 if (!Utf8ToUtf16(entry, &entry16)) {
787 return 0u;
788 }
789
790 const StringPiece16 kAttr16 = u"attr";
791 const static std::u16string kAttrPrivate16 = u"^attr-private";
792
793 for (const PackageGroup& package_group : package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800794 for (const ConfiguredPackage& package_impl : package_group.packages_) {
795 const LoadedPackage* package = package_impl.loaded_package_;
Adam Lesinski929d6512017-01-16 19:11:19 -0800796 if (package_name != package->GetPackageName()) {
797 // All packages in the same group are expected to have the same package name.
798 break;
799 }
800
801 uint32_t resid = package->FindEntryByName(type16, entry16);
802 if (resid == 0u && kAttr16 == type16) {
803 // Private attributes in libraries (such as the framework) are sometimes encoded
804 // under the type '^attr-private' in order to leave the ID space of public 'attr'
805 // free for future additions. Check '^attr-private' for the same name.
806 resid = package->FindEntryByName(kAttrPrivate16, entry16);
807 }
808
809 if (resid != 0u) {
810 return fix_package_id(resid, package_group.dynamic_ref_table.mAssignedPackageId);
811 }
812 }
813 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800814 return 0u;
815}
816
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800817void AssetManager2::RebuildFilterList() {
818 for (PackageGroup& group : package_groups_) {
819 for (ConfiguredPackage& impl : group.packages_) {
820 // Destroy it.
821 impl.filtered_configs_.~ByteBucketArray();
822
823 // Re-create it.
824 new (&impl.filtered_configs_) ByteBucketArray<FilteredConfigGroup>();
825
826 // Create the filters here.
827 impl.loaded_package_->ForEachTypeSpec([&](const TypeSpec* spec, uint8_t type_index) {
828 FilteredConfigGroup& group = impl.filtered_configs_.editItemAt(type_index);
829 const auto iter_end = spec->types + spec->type_count;
830 for (auto iter = spec->types; iter != iter_end; ++iter) {
831 ResTable_config this_config;
832 this_config.copyFromDtoH((*iter)->config);
833 if (this_config.match(configuration_)) {
834 group.configurations.push_back(this_config);
835 group.types.push_back(*iter);
836 }
837 }
838 });
839 }
840 }
841}
842
Adam Lesinski7ad11102016-10-28 16:39:15 -0700843void AssetManager2::InvalidateCaches(uint32_t diff) {
844 if (diff == 0xffffffffu) {
845 // Everything must go.
846 cached_bags_.clear();
847 return;
848 }
849
850 // Be more conservative with what gets purged. Only if the bag has other possible
851 // variations with respect to what changed (diff) should we remove it.
852 for (auto iter = cached_bags_.cbegin(); iter != cached_bags_.cend();) {
853 if (diff & iter->second->type_spec_flags) {
854 iter = cached_bags_.erase(iter);
855 } else {
856 ++iter;
857 }
858 }
859}
860
Adam Lesinski30080e22017-10-16 16:18:09 -0700861std::unique_ptr<Theme> AssetManager2::NewTheme() {
862 return std::unique_ptr<Theme>(new Theme(this));
863}
864
865Theme::Theme(AssetManager2* asset_manager) : asset_manager_(asset_manager) {
866}
867
868Theme::~Theme() = default;
869
870namespace {
871
872struct ThemeEntry {
873 ApkAssetsCookie cookie;
874 uint32_t type_spec_flags;
875 Res_value value;
876};
877
878struct ThemeType {
879 int entry_count;
880 ThemeEntry entries[0];
881};
882
883constexpr size_t kTypeCount = std::numeric_limits<uint8_t>::max() + 1;
884
885} // namespace
886
887struct Theme::Package {
888 // Each element of Type will be a dynamically sized object
889 // allocated to have the entries stored contiguously with the Type.
890 std::array<util::unique_cptr<ThemeType>, kTypeCount> types;
891};
Adam Lesinski7ad11102016-10-28 16:39:15 -0700892
893bool Theme::ApplyStyle(uint32_t resid, bool force) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800894 ATRACE_NAME("Theme::ApplyStyle");
Adam Lesinski7ad11102016-10-28 16:39:15 -0700895
896 const ResolvedBag* bag = asset_manager_->GetBag(resid);
897 if (bag == nullptr) {
898 return false;
899 }
900
901 // Merge the flags from this style.
902 type_spec_flags_ |= bag->type_spec_flags;
903
Adam Lesinski30080e22017-10-16 16:18:09 -0700904 int last_type_idx = -1;
905 int last_package_idx = -1;
906 Package* last_package = nullptr;
907 ThemeType* last_type = nullptr;
908
909 // Iterate backwards, because each bag is sorted in ascending key ID order, meaning we will only
910 // need to perform one resize per type.
911 using reverse_bag_iterator = std::reverse_iterator<const ResolvedBag::Entry*>;
912 const auto bag_iter_end = reverse_bag_iterator(begin(bag));
913 for (auto bag_iter = reverse_bag_iterator(end(bag)); bag_iter != bag_iter_end; ++bag_iter) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700914 const uint32_t attr_resid = bag_iter->key;
915
Adam Lesinski30080e22017-10-16 16:18:09 -0700916 // If the resource ID passed in is not a style, the key can be some other identifier that is not
917 // a resource ID. We should fail fast instead of operating with strange resource IDs.
Adam Lesinski929d6512017-01-16 19:11:19 -0800918 if (!is_valid_resid(attr_resid)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700919 return false;
920 }
921
Adam Lesinski30080e22017-10-16 16:18:09 -0700922 // We don't use the 0-based index for the type so that we can avoid doing ID validation
923 // upon lookup. Instead, we keep space for the type ID 0 in our data structures. Since
924 // the construction of this type is guarded with a resource ID check, it will never be
925 // populated, and querying type ID 0 will always fail.
926 const int package_idx = get_package_id(attr_resid);
927 const int type_idx = get_type_id(attr_resid);
928 const int entry_idx = get_entry_id(attr_resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700929
Adam Lesinski30080e22017-10-16 16:18:09 -0700930 if (last_package_idx != package_idx) {
931 std::unique_ptr<Package>& package = packages_[package_idx];
932 if (package == nullptr) {
933 package.reset(new Package());
Adam Lesinski7ad11102016-10-28 16:39:15 -0700934 }
Adam Lesinski30080e22017-10-16 16:18:09 -0700935 last_package_idx = package_idx;
936 last_package = package.get();
937 last_type_idx = -1;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700938 }
Adam Lesinski30080e22017-10-16 16:18:09 -0700939
940 if (last_type_idx != type_idx) {
941 util::unique_cptr<ThemeType>& type = last_package->types[type_idx];
942 if (type == nullptr) {
943 // Allocate enough memory to contain this entry_idx. Since we're iterating in reverse over
944 // a sorted list of attributes, this shouldn't be resized again during this method call.
945 type.reset(reinterpret_cast<ThemeType*>(
946 calloc(sizeof(ThemeType) + (entry_idx + 1) * sizeof(ThemeEntry), 1)));
947 type->entry_count = entry_idx + 1;
948 } else if (entry_idx >= type->entry_count) {
949 // Reallocate the memory to contain this entry_idx. Since we're iterating in reverse over
950 // a sorted list of attributes, this shouldn't be resized again during this method call.
951 const int new_count = entry_idx + 1;
952 type.reset(reinterpret_cast<ThemeType*>(
953 realloc(type.release(), sizeof(ThemeType) + (new_count * sizeof(ThemeEntry)))));
954
955 // Clear out the newly allocated space (which isn't zeroed).
956 memset(type->entries + type->entry_count, 0,
957 (new_count - type->entry_count) * sizeof(ThemeEntry));
958 type->entry_count = new_count;
959 }
960 last_type_idx = type_idx;
961 last_type = type.get();
962 }
963
964 ThemeEntry& entry = last_type->entries[entry_idx];
965 if (force || (entry.value.dataType == Res_value::TYPE_NULL &&
966 entry.value.data != Res_value::DATA_NULL_EMPTY)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700967 entry.cookie = bag_iter->cookie;
968 entry.type_spec_flags |= bag->type_spec_flags;
969 entry.value = bag_iter->value;
970 }
971 }
972 return true;
973}
974
975ApkAssetsCookie Theme::GetAttribute(uint32_t resid, Res_value* out_value,
976 uint32_t* out_flags) const {
Adam Lesinski30080e22017-10-16 16:18:09 -0700977 int cnt = 20;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700978
979 uint32_t type_spec_flags = 0u;
980
Adam Lesinski30080e22017-10-16 16:18:09 -0700981 do {
982 const int package_idx = get_package_id(resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700983 const Package* package = packages_[package_idx].get();
Adam Lesinski30080e22017-10-16 16:18:09 -0700984 if (package != nullptr) {
985 // The themes are constructed with a 1-based type ID, so no need to decrement here.
986 const int type_idx = get_type_id(resid);
987 const ThemeType* type = package->types[type_idx].get();
988 if (type != nullptr) {
989 const int entry_idx = get_entry_id(resid);
990 if (entry_idx < type->entry_count) {
991 const ThemeEntry& entry = type->entries[entry_idx];
992 type_spec_flags |= entry.type_spec_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700993
Adam Lesinski30080e22017-10-16 16:18:09 -0700994 if (entry.value.dataType == Res_value::TYPE_ATTRIBUTE) {
995 if (cnt > 0) {
996 cnt--;
997 resid = entry.value.data;
998 continue;
999 }
1000 return kInvalidCookie;
1001 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001002
Adam Lesinski30080e22017-10-16 16:18:09 -07001003 // @null is different than @empty.
1004 if (entry.value.dataType == Res_value::TYPE_NULL &&
1005 entry.value.data != Res_value::DATA_NULL_EMPTY) {
1006 return kInvalidCookie;
1007 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001008
Adam Lesinski30080e22017-10-16 16:18:09 -07001009 *out_value = entry.value;
Adam Lesinskida431a22016-12-29 16:08:16 -05001010 *out_flags = type_spec_flags;
Adam Lesinski30080e22017-10-16 16:18:09 -07001011 return entry.cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -05001012 }
Adam Lesinskida431a22016-12-29 16:08:16 -05001013 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001014 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001015 break;
1016 } while (true);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001017 return kInvalidCookie;
1018}
1019
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001020ApkAssetsCookie Theme::ResolveAttributeReference(ApkAssetsCookie cookie, Res_value* in_out_value,
1021 ResTable_config* in_out_selected_config,
1022 uint32_t* in_out_type_spec_flags,
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001023 uint32_t* out_last_ref) const {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001024 if (in_out_value->dataType == Res_value::TYPE_ATTRIBUTE) {
1025 uint32_t new_flags;
1026 cookie = GetAttribute(in_out_value->data, in_out_value, &new_flags);
1027 if (cookie == kInvalidCookie) {
1028 return kInvalidCookie;
1029 }
1030
1031 if (in_out_type_spec_flags != nullptr) {
1032 *in_out_type_spec_flags |= new_flags;
1033 }
1034 }
1035 return asset_manager_->ResolveReference(cookie, in_out_value, in_out_selected_config,
1036 in_out_type_spec_flags, out_last_ref);
1037}
1038
Adam Lesinski7ad11102016-10-28 16:39:15 -07001039void Theme::Clear() {
1040 type_spec_flags_ = 0u;
1041 for (std::unique_ptr<Package>& package : packages_) {
1042 package.reset();
1043 }
1044}
1045
1046bool Theme::SetTo(const Theme& o) {
1047 if (this == &o) {
1048 return true;
1049 }
1050
Adam Lesinski7ad11102016-10-28 16:39:15 -07001051 type_spec_flags_ = o.type_spec_flags_;
1052
Adam Lesinski03ebac82017-09-25 13:10:14 -07001053 const bool copy_only_system = asset_manager_ != o.asset_manager_;
1054
Adam Lesinskida431a22016-12-29 16:08:16 -05001055 for (size_t p = 0; p < packages_.size(); p++) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001056 const Package* package = o.packages_[p].get();
Adam Lesinski03ebac82017-09-25 13:10:14 -07001057 if (package == nullptr || (copy_only_system && p != 0x01)) {
1058 // The other theme doesn't have this package, clear ours.
Adam Lesinski7ad11102016-10-28 16:39:15 -07001059 packages_[p].reset();
1060 continue;
1061 }
1062
Adam Lesinski03ebac82017-09-25 13:10:14 -07001063 if (packages_[p] == nullptr) {
1064 // The other theme has this package, but we don't. Make one.
1065 packages_[p].reset(new Package());
1066 }
1067
Adam Lesinskida431a22016-12-29 16:08:16 -05001068 for (size_t t = 0; t < package->types.size(); t++) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001069 const ThemeType* type = package->types[t].get();
Adam Lesinski7ad11102016-10-28 16:39:15 -07001070 if (type == nullptr) {
Adam Lesinski03ebac82017-09-25 13:10:14 -07001071 // The other theme doesn't have this type, clear ours.
Adam Lesinski7ad11102016-10-28 16:39:15 -07001072 packages_[p]->types[t].reset();
1073 continue;
1074 }
1075
Adam Lesinski03ebac82017-09-25 13:10:14 -07001076 // Create a new type and update it to theirs.
Adam Lesinski30080e22017-10-16 16:18:09 -07001077 const size_t type_alloc_size = sizeof(ThemeType) + (type->entry_count * sizeof(ThemeEntry));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001078 void* copied_data = malloc(type_alloc_size);
1079 memcpy(copied_data, type, type_alloc_size);
Adam Lesinski30080e22017-10-16 16:18:09 -07001080 packages_[p]->types[t].reset(reinterpret_cast<ThemeType*>(copied_data));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001081 }
1082 }
1083 return true;
1084}
1085
1086} // namespace android