1 /*
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 
21 #include <algorithm>
22 #include <iterator>
23 #include <map>
24 #include <set>
25 #include <sstream>
26 
27 #include "android-base/logging.h"
28 #include "android-base/stringprintf.h"
29 #include "utils/ByteOrder.h"
30 #include "utils/Trace.h"
31 
32 #ifdef _WIN32
33 #ifdef ERROR
34 #undef ERROR
35 #endif
36 #endif
37 
38 #ifdef __ANDROID__
39 #define ANDROID_LOG(x) LOG(x)
40 #else
41 #define ANDROID_LOG(x) std::stringstream()
42 #endif
43 
44 #include "androidfw/ResourceUtils.h"
45 
46 namespace android {
47 
48 struct FindEntryResult {
49   // A pointer to the resource table entry for this resource.
50   // If the size of the entry is > sizeof(ResTable_entry), it can be cast to
51   // a ResTable_map_entry and processed as a bag/map.
52   const ResTable_entry* entry;
53 
54   // The configuration for which the resulting entry was defined. This is already swapped to host
55   // endianness.
56   ResTable_config config;
57 
58   // The bitmask of configuration axis with which the resource value varies.
59   uint32_t type_flags;
60 
61   // The dynamic package ID map for the package from which this resource came from.
62   const DynamicRefTable* dynamic_ref_table;
63 
64   // The string pool reference to the type's name. This uses a different string pool than
65   // the global string pool, but this is hidden from the caller.
66   StringPoolRef type_string_ref;
67 
68   // The string pool reference to the entry's name. This uses a different string pool than
69   // the global string pool, but this is hidden from the caller.
70   StringPoolRef entry_string_ref;
71 };
72 
AssetManager2()73 AssetManager2::AssetManager2() {
74   memset(&configuration_, 0, sizeof(configuration_));
75 }
76 
SetApkAssets(const std::vector<const ApkAssets * > & apk_assets,bool invalidate_caches,bool filter_incompatible_configs)77 bool AssetManager2::SetApkAssets(const std::vector<const ApkAssets*>& apk_assets,
78                                  bool invalidate_caches, bool filter_incompatible_configs) {
79   apk_assets_ = apk_assets;
80   BuildDynamicRefTable();
81   RebuildFilterList(filter_incompatible_configs);
82   if (invalidate_caches) {
83     InvalidateCaches(static_cast<uint32_t>(-1));
84   }
85   return true;
86 }
87 
BuildDynamicRefTable()88 void AssetManager2::BuildDynamicRefTable() {
89   package_groups_.clear();
90   package_ids_.fill(0xff);
91 
92   // 0x01 is reserved for the android package.
93   int next_package_id = 0x02;
94   const size_t apk_assets_count = apk_assets_.size();
95   for (size_t i = 0; i < apk_assets_count; i++) {
96     const LoadedArsc* loaded_arsc = apk_assets_[i]->GetLoadedArsc();
97 
98     for (const std::unique_ptr<const LoadedPackage>& package : loaded_arsc->GetPackages()) {
99       // Get the package ID or assign one if a shared library.
100       int package_id;
101       if (package->IsDynamic()) {
102         package_id = next_package_id++;
103       } else {
104         package_id = package->GetPackageId();
105       }
106 
107       // Add the mapping for package ID to index if not present.
108       uint8_t idx = package_ids_[package_id];
109       if (idx == 0xff) {
110         package_ids_[package_id] = idx = static_cast<uint8_t>(package_groups_.size());
111         package_groups_.push_back({});
112         DynamicRefTable& ref_table = package_groups_.back().dynamic_ref_table;
113         ref_table.mAssignedPackageId = package_id;
114         ref_table.mAppAsLib = package->IsDynamic() && package->GetPackageId() == 0x7f;
115       }
116       PackageGroup* package_group = &package_groups_[idx];
117 
118       // Add the package and to the set of packages with the same ID.
119       package_group->packages_.push_back(ConfiguredPackage{package.get(), {}});
120       package_group->cookies_.push_back(static_cast<ApkAssetsCookie>(i));
121 
122       // Add the package name -> build time ID mappings.
123       for (const DynamicPackageEntry& entry : package->GetDynamicPackageMap()) {
124         String16 package_name(entry.package_name.c_str(), entry.package_name.size());
125         package_group->dynamic_ref_table.mEntries.replaceValueFor(
126             package_name, static_cast<uint8_t>(entry.package_id));
127       }
128     }
129   }
130 
131   // Now assign the runtime IDs so that we have a build-time to runtime ID map.
132   const auto package_groups_end = package_groups_.end();
133   for (auto iter = package_groups_.begin(); iter != package_groups_end; ++iter) {
134     const std::string& package_name = iter->packages_[0].loaded_package_->GetPackageName();
135     for (auto iter2 = package_groups_.begin(); iter2 != package_groups_end; ++iter2) {
136       iter2->dynamic_ref_table.addMapping(String16(package_name.c_str(), package_name.size()),
137                                           iter->dynamic_ref_table.mAssignedPackageId);
138     }
139   }
140 }
141 
DumpToLog() const142 void AssetManager2::DumpToLog() const {
143   base::ScopedLogSeverity _log(base::INFO);
144 
145   LOG(INFO) << base::StringPrintf("AssetManager2(this=%p)", this);
146 
147   std::string list;
148   for (const auto& apk_assets : apk_assets_) {
149     base::StringAppendF(&list, "%s,", apk_assets->GetPath().c_str());
150   }
151   LOG(INFO) << "ApkAssets: " << list;
152 
153   list = "";
154   for (size_t i = 0; i < package_ids_.size(); i++) {
155     if (package_ids_[i] != 0xff) {
156       base::StringAppendF(&list, "%02x -> %d, ", (int)i, package_ids_[i]);
157     }
158   }
159   LOG(INFO) << "Package ID map: " << list;
160 
161   for (const auto& package_group: package_groups_) {
162     list = "";
163     for (const auto& package : package_group.packages_) {
164       const LoadedPackage* loaded_package = package.loaded_package_;
165       base::StringAppendF(&list, "%s(%02x%s), ", loaded_package->GetPackageName().c_str(),
166                           loaded_package->GetPackageId(),
167                           (loaded_package->IsDynamic() ? " dynamic" : ""));
168     }
169     LOG(INFO) << base::StringPrintf("PG (%02x): ",
170                                     package_group.dynamic_ref_table.mAssignedPackageId)
171               << list;
172 
173     for (size_t i = 0; i < 256; i++) {
174       if (package_group.dynamic_ref_table.mLookupTable[i] != 0) {
175         LOG(INFO) << base::StringPrintf("    e[0x%02x] -> 0x%02x", (uint8_t) i,
176                                         package_group.dynamic_ref_table.mLookupTable[i]);
177       }
178     }
179   }
180 }
181 
GetStringPoolForCookie(ApkAssetsCookie cookie) const182 const ResStringPool* AssetManager2::GetStringPoolForCookie(ApkAssetsCookie cookie) const {
183   if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
184     return nullptr;
185   }
186   return apk_assets_[cookie]->GetLoadedArsc()->GetStringPool();
187 }
188 
GetDynamicRefTableForPackage(uint32_t package_id) const189 const DynamicRefTable* AssetManager2::GetDynamicRefTableForPackage(uint32_t package_id) const {
190   if (package_id >= package_ids_.size()) {
191     return nullptr;
192   }
193 
194   const size_t idx = package_ids_[package_id];
195   if (idx == 0xff) {
196     return nullptr;
197   }
198   return &package_groups_[idx].dynamic_ref_table;
199 }
200 
GetDynamicRefTableForCookie(ApkAssetsCookie cookie) const201 const DynamicRefTable* AssetManager2::GetDynamicRefTableForCookie(ApkAssetsCookie cookie) const {
202   for (const PackageGroup& package_group : package_groups_) {
203     for (const ApkAssetsCookie& package_cookie : package_group.cookies_) {
204       if (package_cookie == cookie) {
205         return &package_group.dynamic_ref_table;
206       }
207     }
208   }
209   return nullptr;
210 }
211 
212 const std::unordered_map<std::string, std::string>*
GetOverlayableMapForPackage(uint32_t package_id) const213   AssetManager2::GetOverlayableMapForPackage(uint32_t package_id) const {
214 
215   if (package_id >= package_ids_.size()) {
216     return nullptr;
217   }
218 
219   const size_t idx = package_ids_[package_id];
220   if (idx == 0xff) {
221     return nullptr;
222   }
223 
224   const PackageGroup& package_group = package_groups_[idx];
225   if (package_group.packages_.size() == 0) {
226     return nullptr;
227   }
228 
229   const auto loaded_package = package_group.packages_[0].loaded_package_;
230   return &loaded_package->GetOverlayableMap();
231 }
232 
SetConfiguration(const ResTable_config & configuration)233 void AssetManager2::SetConfiguration(const ResTable_config& configuration) {
234   const int diff = configuration_.diff(configuration);
235   configuration_ = configuration;
236 
237   if (diff) {
238     RebuildFilterList();
239     InvalidateCaches(static_cast<uint32_t>(diff));
240   }
241 }
242 
GetResourceConfigurations(bool exclude_system,bool exclude_mipmap) const243 std::set<ResTable_config> AssetManager2::GetResourceConfigurations(bool exclude_system,
244                                                                    bool exclude_mipmap) const {
245   ATRACE_NAME("AssetManager::GetResourceConfigurations");
246   std::set<ResTable_config> configurations;
247   for (const PackageGroup& package_group : package_groups_) {
248     bool found_system_package = false;
249     for (const ConfiguredPackage& package : package_group.packages_) {
250       if (exclude_system && package.loaded_package_->IsSystem()) {
251         found_system_package = true;
252         continue;
253       }
254 
255       if (exclude_system && package.loaded_package_->IsOverlay() && found_system_package) {
256         // Overlays must appear after the target package to take effect. Any overlay found in the
257         // same package as a system package is able to overlay system resources.
258         continue;
259       }
260 
261       package.loaded_package_->CollectConfigurations(exclude_mipmap, &configurations);
262     }
263   }
264   return configurations;
265 }
266 
GetResourceLocales(bool exclude_system,bool merge_equivalent_languages) const267 std::set<std::string> AssetManager2::GetResourceLocales(bool exclude_system,
268                                                         bool merge_equivalent_languages) const {
269   ATRACE_NAME("AssetManager::GetResourceLocales");
270   std::set<std::string> locales;
271   for (const PackageGroup& package_group : package_groups_) {
272     bool found_system_package = false;
273     for (const ConfiguredPackage& package : package_group.packages_) {
274       if (exclude_system && package.loaded_package_->IsSystem()) {
275         found_system_package = true;
276         continue;
277       }
278 
279       if (exclude_system && package.loaded_package_->IsOverlay() && found_system_package) {
280         // Overlays must appear after the target package to take effect. Any overlay found in the
281         // same package as a system package is able to overlay system resources.
282         continue;
283       }
284 
285       package.loaded_package_->CollectLocales(merge_equivalent_languages, &locales);
286     }
287   }
288   return locales;
289 }
290 
Open(const std::string & filename,Asset::AccessMode mode) const291 std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename,
292                                            Asset::AccessMode mode) const {
293   const std::string new_path = "assets/" + filename;
294   return OpenNonAsset(new_path, mode);
295 }
296 
Open(const std::string & filename,ApkAssetsCookie cookie,Asset::AccessMode mode) const297 std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename, ApkAssetsCookie cookie,
298                                            Asset::AccessMode mode) const {
299   const std::string new_path = "assets/" + filename;
300   return OpenNonAsset(new_path, cookie, mode);
301 }
302 
OpenDir(const std::string & dirname) const303 std::unique_ptr<AssetDir> AssetManager2::OpenDir(const std::string& dirname) const {
304   ATRACE_NAME("AssetManager::OpenDir");
305 
306   std::string full_path = "assets/" + dirname;
307   std::unique_ptr<SortedVector<AssetDir::FileInfo>> files =
308       util::make_unique<SortedVector<AssetDir::FileInfo>>();
309 
310   // Start from the back.
311   for (auto iter = apk_assets_.rbegin(); iter != apk_assets_.rend(); ++iter) {
312     const ApkAssets* apk_assets = *iter;
313     if (apk_assets->IsOverlay()) {
314       continue;
315     }
316 
317     auto func = [&](const StringPiece& name, FileType type) {
318       AssetDir::FileInfo info;
319       info.setFileName(String8(name.data(), name.size()));
320       info.setFileType(type);
321       info.setSourceName(String8(apk_assets->GetPath().c_str()));
322       files->add(info);
323     };
324 
325     if (!apk_assets->ForEachFile(full_path, func)) {
326       return {};
327     }
328   }
329 
330   std::unique_ptr<AssetDir> asset_dir = util::make_unique<AssetDir>();
331   asset_dir->setFileList(files.release());
332   return asset_dir;
333 }
334 
335 // Search in reverse because that's how we used to do it and we need to preserve behaviour.
336 // This is unfortunate, because ClassLoaders delegate to the parent first, so the order
337 // is inconsistent for split APKs.
OpenNonAsset(const std::string & filename,Asset::AccessMode mode,ApkAssetsCookie * out_cookie) const338 std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
339                                                    Asset::AccessMode mode,
340                                                    ApkAssetsCookie* out_cookie) const {
341   for (int32_t i = apk_assets_.size() - 1; i >= 0; i--) {
342     // Prevent RRO from modifying assets and other entries accessed by file
343     // path. Explicitly asking for a path in a given package (denoted by a
344     // cookie) is still OK.
345     if (apk_assets_[i]->IsOverlay()) {
346       continue;
347     }
348 
349     std::unique_ptr<Asset> asset = apk_assets_[i]->Open(filename, mode);
350     if (asset) {
351       if (out_cookie != nullptr) {
352         *out_cookie = i;
353       }
354       return asset;
355     }
356   }
357 
358   if (out_cookie != nullptr) {
359     *out_cookie = kInvalidCookie;
360   }
361   return {};
362 }
363 
OpenNonAsset(const std::string & filename,ApkAssetsCookie cookie,Asset::AccessMode mode) const364 std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
365                                                    ApkAssetsCookie cookie,
366                                                    Asset::AccessMode mode) const {
367   if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
368     return {};
369   }
370   return apk_assets_[cookie]->Open(filename, mode);
371 }
372 
FindEntry(uint32_t resid,uint16_t density_override,bool,bool ignore_configuration,FindEntryResult * out_entry) const373 ApkAssetsCookie AssetManager2::FindEntry(uint32_t resid, uint16_t density_override,
374                                          bool /*stop_at_first_match*/,
375                                          bool ignore_configuration,
376                                          FindEntryResult* out_entry) const {
377   // Might use this if density_override != 0.
378   ResTable_config density_override_config;
379 
380   // Select our configuration or generate a density override configuration.
381   const ResTable_config* desired_config = &configuration_;
382   if (density_override != 0 && density_override != configuration_.density) {
383     density_override_config = configuration_;
384     density_override_config.density = density_override;
385     desired_config = &density_override_config;
386   }
387 
388   if (!is_valid_resid(resid)) {
389     LOG(ERROR) << base::StringPrintf("Invalid ID 0x%08x.", resid);
390     return kInvalidCookie;
391   }
392 
393   const uint32_t package_id = get_package_id(resid);
394   const uint8_t type_idx = get_type_id(resid) - 1;
395   const uint16_t entry_idx = get_entry_id(resid);
396 
397   const uint8_t package_idx = package_ids_[package_id];
398   if (package_idx == 0xff) {
399     ANDROID_LOG(ERROR) << base::StringPrintf("No package ID %02x found for ID 0x%08x.",
400                                              package_id, resid);
401     return kInvalidCookie;
402   }
403 
404   const PackageGroup& package_group = package_groups_[package_idx];
405   const size_t package_count = package_group.packages_.size();
406 
407   ApkAssetsCookie best_cookie = kInvalidCookie;
408   const LoadedPackage* best_package = nullptr;
409   const ResTable_type* best_type = nullptr;
410   const ResTable_config* best_config = nullptr;
411   ResTable_config best_config_copy;
412   uint32_t best_offset = 0u;
413   uint32_t type_flags = 0u;
414 
415   Resolution::Step::Type resolution_type;
416   std::vector<Resolution::Step> resolution_steps;
417 
418   // If desired_config is the same as the set configuration, then we can use our filtered list
419   // and we don't need to match the configurations, since they already matched.
420   const bool use_fast_path = !ignore_configuration && desired_config == &configuration_;
421 
422   for (size_t pi = 0; pi < package_count; pi++) {
423     const ConfiguredPackage& loaded_package_impl = package_group.packages_[pi];
424     const LoadedPackage* loaded_package = loaded_package_impl.loaded_package_;
425     ApkAssetsCookie cookie = package_group.cookies_[pi];
426 
427     // If the type IDs are offset in this package, we need to take that into account when searching
428     // for a type.
429     const TypeSpec* type_spec = loaded_package->GetTypeSpecByTypeIndex(type_idx);
430     if (UNLIKELY(type_spec == nullptr)) {
431       continue;
432     }
433 
434     uint16_t local_entry_idx = entry_idx;
435 
436     // If there is an IDMAP supplied with this package, translate the entry ID.
437     if (type_spec->idmap_entries != nullptr) {
438       if (!LoadedIdmap::Lookup(type_spec->idmap_entries, local_entry_idx, &local_entry_idx)) {
439         // There is no mapping, so the resource is not meant to be in this overlay package.
440         continue;
441       }
442     }
443 
444     type_flags |= type_spec->GetFlagsForEntryIndex(local_entry_idx);
445 
446     // If the package is an overlay, then even configurations that are the same MUST be chosen.
447     const bool package_is_overlay = loaded_package->IsOverlay();
448 
449     if (use_fast_path) {
450       const FilteredConfigGroup& filtered_group = loaded_package_impl.filtered_configs_[type_idx];
451       const std::vector<ResTable_config>& candidate_configs = filtered_group.configurations;
452       const size_t type_count = candidate_configs.size();
453       for (uint32_t i = 0; i < type_count; i++) {
454         const ResTable_config& this_config = candidate_configs[i];
455 
456         // We can skip calling ResTable_config::match() because we know that all candidate
457         // configurations that do NOT match have been filtered-out.
458         if (best_config == nullptr) {
459           resolution_type = Resolution::Step::Type::INITIAL;
460         } else if (this_config.isBetterThan(*best_config, desired_config)) {
461           resolution_type = Resolution::Step::Type::BETTER_MATCH;
462         } else if (package_is_overlay && this_config.compare(*best_config) == 0) {
463           resolution_type = Resolution::Step::Type::OVERLAID;
464         } else {
465           continue;
466         }
467 
468         // The configuration matches and is better than the previous selection.
469         // Find the entry value if it exists for this configuration.
470         const ResTable_type* type = filtered_group.types[i];
471         const uint32_t offset = LoadedPackage::GetEntryOffset(type, local_entry_idx);
472         if (offset == ResTable_type::NO_ENTRY) {
473           continue;
474         }
475 
476         best_cookie = cookie;
477         best_package = loaded_package;
478         best_type = type;
479         best_config = &this_config;
480         best_offset = offset;
481 
482         if (resource_resolution_logging_enabled_) {
483           resolution_steps.push_back(Resolution::Step{resolution_type,
484                                                       this_config.toString(),
485                                                       &loaded_package->GetPackageName()});
486         }
487       }
488     } else {
489       // This is the slower path, which doesn't use the filtered list of configurations.
490       // Here we must read the ResTable_config from the mmapped APK, convert it to host endianness
491       // and fill in any new fields that did not exist when the APK was compiled.
492       // Furthermore when selecting configurations we can't just record the pointer to the
493       // ResTable_config, we must copy it.
494       const auto iter_end = type_spec->types + type_spec->type_count;
495       for (auto iter = type_spec->types; iter != iter_end; ++iter) {
496         ResTable_config this_config{};
497 
498         if (!ignore_configuration) {
499           this_config.copyFromDtoH((*iter)->config);
500           if (!this_config.match(*desired_config)) {
501             continue;
502           }
503 
504           if (best_config == nullptr) {
505             resolution_type = Resolution::Step::Type::INITIAL;
506           } else if (this_config.isBetterThan(*best_config, desired_config)) {
507             resolution_type = Resolution::Step::Type::BETTER_MATCH;
508           } else if (package_is_overlay && this_config.compare(*best_config) == 0) {
509             resolution_type = Resolution::Step::Type::OVERLAID;
510           } else {
511             continue;
512           }
513         }
514 
515         // The configuration matches and is better than the previous selection.
516         // Find the entry value if it exists for this configuration.
517         const uint32_t offset = LoadedPackage::GetEntryOffset(*iter, local_entry_idx);
518         if (offset == ResTable_type::NO_ENTRY) {
519           continue;
520         }
521 
522         best_cookie = cookie;
523         best_package = loaded_package;
524         best_type = *iter;
525         best_config_copy = this_config;
526         best_config = &best_config_copy;
527         best_offset = offset;
528 
529         if (ignore_configuration) {
530           // Any configuration will suffice, so break.
531           break;
532         }
533 
534         if (resource_resolution_logging_enabled_) {
535           resolution_steps.push_back(Resolution::Step{resolution_type,
536                                                       this_config.toString(),
537                                                       &loaded_package->GetPackageName()});
538         }
539       }
540     }
541   }
542 
543   if (UNLIKELY(best_cookie == kInvalidCookie)) {
544     return kInvalidCookie;
545   }
546 
547   const ResTable_entry* best_entry = LoadedPackage::GetEntryFromOffset(best_type, best_offset);
548   if (UNLIKELY(best_entry == nullptr)) {
549     return kInvalidCookie;
550   }
551 
552   out_entry->entry = best_entry;
553   out_entry->config = *best_config;
554   out_entry->type_flags = type_flags;
555   out_entry->type_string_ref = StringPoolRef(best_package->GetTypeStringPool(), best_type->id - 1);
556   out_entry->entry_string_ref =
557       StringPoolRef(best_package->GetKeyStringPool(), best_entry->key.index);
558   out_entry->dynamic_ref_table = &package_group.dynamic_ref_table;
559 
560   if (resource_resolution_logging_enabled_) {
561     last_resolution.resid = resid;
562     last_resolution.cookie = best_cookie;
563     last_resolution.steps = resolution_steps;
564 
565     // Cache only the type/entry refs since that's all that's needed to build name
566     last_resolution.type_string_ref =
567         StringPoolRef(best_package->GetTypeStringPool(), best_type->id - 1);
568     last_resolution.entry_string_ref =
569         StringPoolRef(best_package->GetKeyStringPool(), best_entry->key.index);
570   }
571 
572   return best_cookie;
573 }
574 
SetResourceResolutionLoggingEnabled(bool enabled)575 void AssetManager2::SetResourceResolutionLoggingEnabled(bool enabled) {
576   resource_resolution_logging_enabled_ = enabled;
577 
578   if (!enabled) {
579     last_resolution.cookie = kInvalidCookie;
580     last_resolution.resid = 0;
581     last_resolution.steps.clear();
582     last_resolution.type_string_ref = StringPoolRef();
583     last_resolution.entry_string_ref = StringPoolRef();
584   }
585 }
586 
GetLastResourceResolution() const587 std::string AssetManager2::GetLastResourceResolution() const {
588   if (!resource_resolution_logging_enabled_) {
589     LOG(ERROR) << "Must enable resource resolution logging before getting path.";
590     return std::string();
591   }
592 
593   auto cookie = last_resolution.cookie;
594   if (cookie == kInvalidCookie) {
595     LOG(ERROR) << "AssetManager hasn't resolved a resource to read resolution path.";
596     return std::string();
597   }
598 
599   uint32_t resid = last_resolution.resid;
600   std::vector<Resolution::Step>& steps = last_resolution.steps;
601 
602   ResourceName resource_name;
603   std::string resource_name_string;
604 
605   const LoadedPackage* package =
606       apk_assets_[cookie]->GetLoadedArsc()->GetPackageById(get_package_id(resid));
607 
608   if (package != nullptr) {
609     ToResourceName(last_resolution.type_string_ref,
610                    last_resolution.entry_string_ref,
611                    package->GetPackageName(),
612                    &resource_name);
613     resource_name_string = ToFormattedResourceString(&resource_name);
614   }
615 
616   std::stringstream log_stream;
617   log_stream << base::StringPrintf("Resolution for 0x%08x ", resid)
618             << resource_name_string
619             << "\n\tFor config -"
620             << configuration_.toString();
621 
622   std::string prefix;
623   for (Resolution::Step step : steps) {
624     switch (step.type) {
625       case Resolution::Step::Type::INITIAL:
626         prefix = "Found initial";
627         break;
628       case Resolution::Step::Type::BETTER_MATCH:
629         prefix = "Found better";
630         break;
631       case Resolution::Step::Type::OVERLAID:
632         prefix = "Overlaid";
633         break;
634     }
635 
636     if (!prefix.empty()) {
637       log_stream << "\n\t" << prefix << ": " << *step.package_name;
638 
639       if (!step.config_name.isEmpty()) {
640         log_stream << " -" << step.config_name;
641       }
642     }
643   }
644 
645   return log_stream.str();
646 }
647 
GetResourceName(uint32_t resid,ResourceName * out_name) const648 bool AssetManager2::GetResourceName(uint32_t resid, ResourceName* out_name) const {
649   FindEntryResult entry;
650   ApkAssetsCookie cookie = FindEntry(resid, 0u /* density_override */,
651                                      true /* stop_at_first_match */,
652                                      true /* ignore_configuration */, &entry);
653   if (cookie == kInvalidCookie) {
654     return false;
655   }
656 
657   const uint8_t package_idx = package_ids_[get_package_id(resid)];
658   if (package_idx == 0xff) {
659     LOG(ERROR) << base::StringPrintf("No package ID %02x found for ID 0x%08x.",
660                                      get_package_id(resid), resid);
661     return false;
662   }
663 
664   const PackageGroup& package_group = package_groups_[package_idx];
665   auto cookie_iter = std::find(package_group.cookies_.begin(),
666                                package_group.cookies_.end(), cookie);
667   if (cookie_iter == package_group.cookies_.end()) {
668     return false;
669   }
670 
671   long package_pos = std::distance(package_group.cookies_.begin(), cookie_iter);
672   const LoadedPackage* package = package_group.packages_[package_pos].loaded_package_;
673   return ToResourceName(entry.type_string_ref,
674                         entry.entry_string_ref,
675                         package->GetPackageName(),
676                         out_name);
677 }
678 
GetResourceFlags(uint32_t resid,uint32_t * out_flags) const679 bool AssetManager2::GetResourceFlags(uint32_t resid, uint32_t* out_flags) const {
680   FindEntryResult entry;
681   ApkAssetsCookie cookie = FindEntry(resid, 0u /* density_override */,
682                                      false /* stop_at_first_match */,
683                                      true /* ignore_configuration */, &entry);
684   if (cookie != kInvalidCookie) {
685     *out_flags = entry.type_flags;
686     return true;
687   }
688   return false;
689 }
690 
GetResource(uint32_t resid,bool may_be_bag,uint16_t density_override,Res_value * out_value,ResTable_config * out_selected_config,uint32_t * out_flags) const691 ApkAssetsCookie AssetManager2::GetResource(uint32_t resid, bool may_be_bag,
692                                            uint16_t density_override, Res_value* out_value,
693                                            ResTable_config* out_selected_config,
694                                            uint32_t* out_flags) const {
695   FindEntryResult entry;
696   ApkAssetsCookie cookie = FindEntry(resid, density_override, false /* stop_at_first_match */,
697                                      false /* ignore_configuration */, &entry);
698   if (cookie == kInvalidCookie) {
699     return kInvalidCookie;
700   }
701 
702   if (dtohs(entry.entry->flags) & ResTable_entry::FLAG_COMPLEX) {
703     if (!may_be_bag) {
704       LOG(ERROR) << base::StringPrintf("Resource %08x is a complex map type.", resid);
705       return kInvalidCookie;
706     }
707 
708     // Create a reference since we can't represent this complex type as a Res_value.
709     out_value->dataType = Res_value::TYPE_REFERENCE;
710     out_value->data = resid;
711     *out_selected_config = entry.config;
712     *out_flags = entry.type_flags;
713     return cookie;
714   }
715 
716   const Res_value* device_value = reinterpret_cast<const Res_value*>(
717       reinterpret_cast<const uint8_t*>(entry.entry) + dtohs(entry.entry->size));
718   out_value->copyFrom_dtoh(*device_value);
719 
720   // Convert the package ID to the runtime assigned package ID.
721   entry.dynamic_ref_table->lookupResourceValue(out_value);
722 
723   *out_selected_config = entry.config;
724   *out_flags = entry.type_flags;
725   return cookie;
726 }
727 
ResolveReference(ApkAssetsCookie cookie,Res_value * in_out_value,ResTable_config * in_out_selected_config,uint32_t * in_out_flags,uint32_t * out_last_reference) const728 ApkAssetsCookie AssetManager2::ResolveReference(ApkAssetsCookie cookie, Res_value* in_out_value,
729                                                 ResTable_config* in_out_selected_config,
730                                                 uint32_t* in_out_flags,
731                                                 uint32_t* out_last_reference) const {
732   constexpr const int kMaxIterations = 20;
733 
734   for (size_t iteration = 0u; in_out_value->dataType == Res_value::TYPE_REFERENCE &&
735                               in_out_value->data != 0u && iteration < kMaxIterations;
736        iteration++) {
737     *out_last_reference = in_out_value->data;
738     uint32_t new_flags = 0u;
739     cookie = GetResource(in_out_value->data, true /*may_be_bag*/, 0u /*density_override*/,
740                          in_out_value, in_out_selected_config, &new_flags);
741     if (cookie == kInvalidCookie) {
742       return kInvalidCookie;
743     }
744     if (in_out_flags != nullptr) {
745       *in_out_flags |= new_flags;
746     }
747     if (*out_last_reference == in_out_value->data) {
748       // This reference can't be resolved, so exit now and let the caller deal with it.
749       return cookie;
750     }
751   }
752   return cookie;
753 }
754 
GetBagResIdStack(uint32_t resid)755 const std::vector<uint32_t> AssetManager2::GetBagResIdStack(uint32_t resid) {
756   auto cached_iter = cached_bag_resid_stacks_.find(resid);
757   if (cached_iter != cached_bag_resid_stacks_.end()) {
758     return cached_iter->second;
759   } else {
760     auto found_resids = std::vector<uint32_t>();
761     GetBag(resid, found_resids);
762     // Cache style stacks if they are not already cached.
763     cached_bag_resid_stacks_[resid] = found_resids;
764     return found_resids;
765   }
766 }
767 
GetBag(uint32_t resid)768 const ResolvedBag* AssetManager2::GetBag(uint32_t resid) {
769   auto found_resids = std::vector<uint32_t>();
770   auto bag = GetBag(resid, found_resids);
771 
772   // Cache style stacks if they are not already cached.
773   auto cached_iter = cached_bag_resid_stacks_.find(resid);
774   if (cached_iter == cached_bag_resid_stacks_.end()) {
775     cached_bag_resid_stacks_[resid] = found_resids;
776   }
777   return bag;
778 }
779 
GetBag(uint32_t resid,std::vector<uint32_t> & child_resids)780 const ResolvedBag* AssetManager2::GetBag(uint32_t resid, std::vector<uint32_t>& child_resids) {
781   auto cached_iter = cached_bags_.find(resid);
782   if (cached_iter != cached_bags_.end()) {
783     return cached_iter->second.get();
784   }
785 
786   FindEntryResult entry;
787   ApkAssetsCookie cookie = FindEntry(resid, 0u /* density_override */,
788                                      false /* stop_at_first_match */,
789                                      false /* ignore_configuration */,
790                                      &entry);
791   if (cookie == kInvalidCookie) {
792     return nullptr;
793   }
794 
795   // Check that the size of the entry header is at least as big as
796   // the desired ResTable_map_entry. Also verify that the entry
797   // was intended to be a map.
798   if (dtohs(entry.entry->size) < sizeof(ResTable_map_entry) ||
799       (dtohs(entry.entry->flags) & ResTable_entry::FLAG_COMPLEX) == 0) {
800     // Not a bag, nothing to do.
801     return nullptr;
802   }
803 
804   const ResTable_map_entry* map = reinterpret_cast<const ResTable_map_entry*>(entry.entry);
805   const ResTable_map* map_entry =
806       reinterpret_cast<const ResTable_map*>(reinterpret_cast<const uint8_t*>(map) + map->size);
807   const ResTable_map* const map_entry_end = map_entry + dtohl(map->count);
808 
809   // Keep track of ids that have already been seen to prevent infinite loops caused by circular
810   // dependencies between bags
811   child_resids.push_back(resid);
812 
813   uint32_t parent_resid = dtohl(map->parent.ident);
814   if (parent_resid == 0 || std::find(child_resids.begin(), child_resids.end(), parent_resid)
815       != child_resids.end()) {
816     // There is no parent or that a circular dependency exist, meaning there is nothing to
817     // inherit and we can do a simple copy of the entries in the map.
818     const size_t entry_count = map_entry_end - map_entry;
819     util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
820         malloc(sizeof(ResolvedBag) + (entry_count * sizeof(ResolvedBag::Entry))))};
821     ResolvedBag::Entry* new_entry = new_bag->entries;
822     for (; map_entry != map_entry_end; ++map_entry) {
823       uint32_t new_key = dtohl(map_entry->name.ident);
824       if (!is_internal_resid(new_key)) {
825         // Attributes, arrays, etc don't have a resource id as the name. They specify
826         // other data, which would be wrong to change via a lookup.
827         if (entry.dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR) {
828           LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
829                                            resid);
830           return nullptr;
831         }
832       }
833       new_entry->cookie = cookie;
834       new_entry->key = new_key;
835       new_entry->key_pool = nullptr;
836       new_entry->type_pool = nullptr;
837       new_entry->style = resid;
838       new_entry->value.copyFrom_dtoh(map_entry->value);
839       status_t err = entry.dynamic_ref_table->lookupResourceValue(&new_entry->value);
840       if (err != NO_ERROR) {
841         LOG(ERROR) << base::StringPrintf(
842             "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
843             new_entry->value.data, new_key);
844         return nullptr;
845       }
846       ++new_entry;
847     }
848     new_bag->type_spec_flags = entry.type_flags;
849     new_bag->entry_count = static_cast<uint32_t>(entry_count);
850     ResolvedBag* result = new_bag.get();
851     cached_bags_[resid] = std::move(new_bag);
852     return result;
853   }
854 
855   // In case the parent is a dynamic reference, resolve it.
856   entry.dynamic_ref_table->lookupResourceId(&parent_resid);
857 
858   // Get the parent and do a merge of the keys.
859   const ResolvedBag* parent_bag = GetBag(parent_resid, child_resids);
860   if (parent_bag == nullptr) {
861     // Failed to get the parent that should exist.
862     LOG(ERROR) << base::StringPrintf("Failed to find parent 0x%08x of bag 0x%08x.", parent_resid,
863                                      resid);
864     return nullptr;
865   }
866 
867   // Create the max possible entries we can make. Once we construct the bag,
868   // we will realloc to fit to size.
869   const size_t max_count = parent_bag->entry_count + dtohl(map->count);
870   util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
871       malloc(sizeof(ResolvedBag) + (max_count * sizeof(ResolvedBag::Entry))))};
872   ResolvedBag::Entry* new_entry = new_bag->entries;
873 
874   const ResolvedBag::Entry* parent_entry = parent_bag->entries;
875   const ResolvedBag::Entry* const parent_entry_end = parent_entry + parent_bag->entry_count;
876 
877   // The keys are expected to be in sorted order. Merge the two bags.
878   while (map_entry != map_entry_end && parent_entry != parent_entry_end) {
879     uint32_t child_key = dtohl(map_entry->name.ident);
880     if (!is_internal_resid(child_key)) {
881       if (entry.dynamic_ref_table->lookupResourceId(&child_key) != NO_ERROR) {
882         LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", child_key,
883                                          resid);
884         return nullptr;
885       }
886     }
887 
888     if (child_key <= parent_entry->key) {
889       // Use the child key if it comes before the parent
890       // or is equal to the parent (overrides).
891       new_entry->cookie = cookie;
892       new_entry->key = child_key;
893       new_entry->key_pool = nullptr;
894       new_entry->type_pool = nullptr;
895       new_entry->value.copyFrom_dtoh(map_entry->value);
896       new_entry->style = resid;
897       status_t err = entry.dynamic_ref_table->lookupResourceValue(&new_entry->value);
898       if (err != NO_ERROR) {
899         LOG(ERROR) << base::StringPrintf(
900             "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
901             new_entry->value.data, child_key);
902         return nullptr;
903       }
904       ++map_entry;
905     } else {
906       // Take the parent entry as-is.
907       memcpy(new_entry, parent_entry, sizeof(*new_entry));
908     }
909 
910     if (child_key >= parent_entry->key) {
911       // Move to the next parent entry if we used it or it was overridden.
912       ++parent_entry;
913     }
914     // Increment to the next entry to fill.
915     ++new_entry;
916   }
917 
918   // Finish the child entries if they exist.
919   while (map_entry != map_entry_end) {
920     uint32_t new_key = dtohl(map_entry->name.ident);
921     if (!is_internal_resid(new_key)) {
922       if (entry.dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR) {
923         LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
924                                          resid);
925         return nullptr;
926       }
927     }
928     new_entry->cookie = cookie;
929     new_entry->key = new_key;
930     new_entry->key_pool = nullptr;
931     new_entry->type_pool = nullptr;
932     new_entry->value.copyFrom_dtoh(map_entry->value);
933     new_entry->style = resid;
934     status_t err = entry.dynamic_ref_table->lookupResourceValue(&new_entry->value);
935     if (err != NO_ERROR) {
936       LOG(ERROR) << base::StringPrintf("Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.",
937                                        new_entry->value.dataType, new_entry->value.data, new_key);
938       return nullptr;
939     }
940     ++map_entry;
941     ++new_entry;
942   }
943 
944   // Finish the parent entries if they exist.
945   if (parent_entry != parent_entry_end) {
946     // Take the rest of the parent entries as-is.
947     const size_t num_entries_to_copy = parent_entry_end - parent_entry;
948     memcpy(new_entry, parent_entry, num_entries_to_copy * sizeof(*new_entry));
949     new_entry += num_entries_to_copy;
950   }
951 
952   // Resize the resulting array to fit.
953   const size_t actual_count = new_entry - new_bag->entries;
954   if (actual_count != max_count) {
955     new_bag.reset(reinterpret_cast<ResolvedBag*>(realloc(
956         new_bag.release(), sizeof(ResolvedBag) + (actual_count * sizeof(ResolvedBag::Entry)))));
957   }
958 
959   // Combine flags from the parent and our own bag.
960   new_bag->type_spec_flags = entry.type_flags | parent_bag->type_spec_flags;
961   new_bag->entry_count = static_cast<uint32_t>(actual_count);
962   ResolvedBag* result = new_bag.get();
963   cached_bags_[resid] = std::move(new_bag);
964   return result;
965 }
966 
Utf8ToUtf16(const StringPiece & str,std::u16string * out)967 static bool Utf8ToUtf16(const StringPiece& str, std::u16string* out) {
968   ssize_t len =
969       utf8_to_utf16_length(reinterpret_cast<const uint8_t*>(str.data()), str.size(), false);
970   if (len < 0) {
971     return false;
972   }
973   out->resize(static_cast<size_t>(len));
974   utf8_to_utf16(reinterpret_cast<const uint8_t*>(str.data()), str.size(), &*out->begin(),
975                 static_cast<size_t>(len + 1));
976   return true;
977 }
978 
GetResourceId(const std::string & resource_name,const std::string & fallback_type,const std::string & fallback_package) const979 uint32_t AssetManager2::GetResourceId(const std::string& resource_name,
980                                       const std::string& fallback_type,
981                                       const std::string& fallback_package) const {
982   StringPiece package_name, type, entry;
983   if (!ExtractResourceName(resource_name, &package_name, &type, &entry)) {
984     return 0u;
985   }
986 
987   if (entry.empty()) {
988     return 0u;
989   }
990 
991   if (package_name.empty()) {
992     package_name = fallback_package;
993   }
994 
995   if (type.empty()) {
996     type = fallback_type;
997   }
998 
999   std::u16string type16;
1000   if (!Utf8ToUtf16(type, &type16)) {
1001     return 0u;
1002   }
1003 
1004   std::u16string entry16;
1005   if (!Utf8ToUtf16(entry, &entry16)) {
1006     return 0u;
1007   }
1008 
1009   const StringPiece16 kAttr16 = u"attr";
1010   const static std::u16string kAttrPrivate16 = u"^attr-private";
1011 
1012   for (const PackageGroup& package_group : package_groups_) {
1013     for (const ConfiguredPackage& package_impl : package_group.packages_) {
1014       const LoadedPackage* package = package_impl.loaded_package_;
1015       if (package_name != package->GetPackageName()) {
1016         // All packages in the same group are expected to have the same package name.
1017         break;
1018       }
1019 
1020       uint32_t resid = package->FindEntryByName(type16, entry16);
1021       if (resid == 0u && kAttr16 == type16) {
1022         // Private attributes in libraries (such as the framework) are sometimes encoded
1023         // under the type '^attr-private' in order to leave the ID space of public 'attr'
1024         // free for future additions. Check '^attr-private' for the same name.
1025         resid = package->FindEntryByName(kAttrPrivate16, entry16);
1026       }
1027 
1028       if (resid != 0u) {
1029         return fix_package_id(resid, package_group.dynamic_ref_table.mAssignedPackageId);
1030       }
1031     }
1032   }
1033   return 0u;
1034 }
1035 
RebuildFilterList(bool filter_incompatible_configs)1036 void AssetManager2::RebuildFilterList(bool filter_incompatible_configs) {
1037   for (PackageGroup& group : package_groups_) {
1038     for (ConfiguredPackage& impl : group.packages_) {
1039       // Destroy it.
1040       impl.filtered_configs_.~ByteBucketArray();
1041 
1042       // Re-create it.
1043       new (&impl.filtered_configs_) ByteBucketArray<FilteredConfigGroup>();
1044 
1045       // Create the filters here.
1046       impl.loaded_package_->ForEachTypeSpec([&](const TypeSpec* spec, uint8_t type_index) {
1047         FilteredConfigGroup& group = impl.filtered_configs_.editItemAt(type_index);
1048         const auto iter_end = spec->types + spec->type_count;
1049         for (auto iter = spec->types; iter != iter_end; ++iter) {
1050           ResTable_config this_config;
1051           this_config.copyFromDtoH((*iter)->config);
1052           if (!filter_incompatible_configs || this_config.match(configuration_)) {
1053             group.configurations.push_back(this_config);
1054             group.types.push_back(*iter);
1055           }
1056         }
1057       });
1058     }
1059   }
1060 }
1061 
InvalidateCaches(uint32_t diff)1062 void AssetManager2::InvalidateCaches(uint32_t diff) {
1063   cached_bag_resid_stacks_.clear();
1064 
1065   if (diff == 0xffffffffu) {
1066     // Everything must go.
1067     cached_bags_.clear();
1068     return;
1069   }
1070 
1071   // Be more conservative with what gets purged. Only if the bag has other possible
1072   // variations with respect to what changed (diff) should we remove it.
1073   for (auto iter = cached_bags_.cbegin(); iter != cached_bags_.cend();) {
1074     if (diff & iter->second->type_spec_flags) {
1075       iter = cached_bags_.erase(iter);
1076     } else {
1077       ++iter;
1078     }
1079   }
1080 }
1081 
GetAssignedPackageId(const LoadedPackage * package)1082 uint8_t AssetManager2::GetAssignedPackageId(const LoadedPackage* package) {
1083   for (auto& package_group : package_groups_) {
1084     for (auto& package2 : package_group.packages_) {
1085       if (package2.loaded_package_ == package) {
1086         return package_group.dynamic_ref_table.mAssignedPackageId;
1087       }
1088     }
1089   }
1090   return 0;
1091 }
1092 
NewTheme()1093 std::unique_ptr<Theme> AssetManager2::NewTheme() {
1094   return std::unique_ptr<Theme>(new Theme(this));
1095 }
1096 
Theme(AssetManager2 * asset_manager)1097 Theme::Theme(AssetManager2* asset_manager) : asset_manager_(asset_manager) {
1098 }
1099 
1100 Theme::~Theme() = default;
1101 
1102 namespace {
1103 
1104 struct ThemeEntry {
1105   ApkAssetsCookie cookie;
1106   uint32_t type_spec_flags;
1107   Res_value value;
1108 };
1109 
1110 struct ThemeType {
1111   int entry_count;
1112   ThemeEntry entries[0];
1113 };
1114 
1115 constexpr size_t kTypeCount = std::numeric_limits<uint8_t>::max() + 1;
1116 
1117 }  // namespace
1118 
1119 struct Theme::Package {
1120   // Each element of Type will be a dynamically sized object
1121   // allocated to have the entries stored contiguously with the Type.
1122   std::array<util::unique_cptr<ThemeType>, kTypeCount> types;
1123 };
1124 
ApplyStyle(uint32_t resid,bool force)1125 bool Theme::ApplyStyle(uint32_t resid, bool force) {
1126   ATRACE_NAME("Theme::ApplyStyle");
1127 
1128   const ResolvedBag* bag = asset_manager_->GetBag(resid);
1129   if (bag == nullptr) {
1130     return false;
1131   }
1132 
1133   // Merge the flags from this style.
1134   type_spec_flags_ |= bag->type_spec_flags;
1135 
1136   int last_type_idx = -1;
1137   int last_package_idx = -1;
1138   Package* last_package = nullptr;
1139   ThemeType* last_type = nullptr;
1140 
1141   // Iterate backwards, because each bag is sorted in ascending key ID order, meaning we will only
1142   // need to perform one resize per type.
1143   using reverse_bag_iterator = std::reverse_iterator<const ResolvedBag::Entry*>;
1144   const auto bag_iter_end = reverse_bag_iterator(begin(bag));
1145   for (auto bag_iter = reverse_bag_iterator(end(bag)); bag_iter != bag_iter_end; ++bag_iter) {
1146     const uint32_t attr_resid = bag_iter->key;
1147 
1148     // If the resource ID passed in is not a style, the key can be some other identifier that is not
1149     // a resource ID. We should fail fast instead of operating with strange resource IDs.
1150     if (!is_valid_resid(attr_resid)) {
1151       return false;
1152     }
1153 
1154     // We don't use the 0-based index for the type so that we can avoid doing ID validation
1155     // upon lookup. Instead, we keep space for the type ID 0 in our data structures. Since
1156     // the construction of this type is guarded with a resource ID check, it will never be
1157     // populated, and querying type ID 0 will always fail.
1158     const int package_idx = get_package_id(attr_resid);
1159     const int type_idx = get_type_id(attr_resid);
1160     const int entry_idx = get_entry_id(attr_resid);
1161 
1162     if (last_package_idx != package_idx) {
1163       std::unique_ptr<Package>& package = packages_[package_idx];
1164       if (package == nullptr) {
1165         package.reset(new Package());
1166       }
1167       last_package_idx = package_idx;
1168       last_package = package.get();
1169       last_type_idx = -1;
1170     }
1171 
1172     if (last_type_idx != type_idx) {
1173       util::unique_cptr<ThemeType>& type = last_package->types[type_idx];
1174       if (type == nullptr) {
1175         // Allocate enough memory to contain this entry_idx. Since we're iterating in reverse over
1176         // a sorted list of attributes, this shouldn't be resized again during this method call.
1177         type.reset(reinterpret_cast<ThemeType*>(
1178             calloc(sizeof(ThemeType) + (entry_idx + 1) * sizeof(ThemeEntry), 1)));
1179         type->entry_count = entry_idx + 1;
1180       } else if (entry_idx >= type->entry_count) {
1181         // Reallocate the memory to contain this entry_idx. Since we're iterating in reverse over
1182         // a sorted list of attributes, this shouldn't be resized again during this method call.
1183         const int new_count = entry_idx + 1;
1184         type.reset(reinterpret_cast<ThemeType*>(
1185             realloc(type.release(), sizeof(ThemeType) + (new_count * sizeof(ThemeEntry)))));
1186 
1187         // Clear out the newly allocated space (which isn't zeroed).
1188         memset(type->entries + type->entry_count, 0,
1189                (new_count - type->entry_count) * sizeof(ThemeEntry));
1190         type->entry_count = new_count;
1191       }
1192       last_type_idx = type_idx;
1193       last_type = type.get();
1194     }
1195 
1196     ThemeEntry& entry = last_type->entries[entry_idx];
1197     if (force || (entry.value.dataType == Res_value::TYPE_NULL &&
1198                   entry.value.data != Res_value::DATA_NULL_EMPTY)) {
1199       entry.cookie = bag_iter->cookie;
1200       entry.type_spec_flags |= bag->type_spec_flags;
1201       entry.value = bag_iter->value;
1202     }
1203   }
1204   return true;
1205 }
1206 
GetAttribute(uint32_t resid,Res_value * out_value,uint32_t * out_flags) const1207 ApkAssetsCookie Theme::GetAttribute(uint32_t resid, Res_value* out_value,
1208                                     uint32_t* out_flags) const {
1209   int cnt = 20;
1210 
1211   uint32_t type_spec_flags = 0u;
1212 
1213   do {
1214     const int package_idx = get_package_id(resid);
1215     const Package* package = packages_[package_idx].get();
1216     if (package != nullptr) {
1217       // The themes are constructed with a 1-based type ID, so no need to decrement here.
1218       const int type_idx = get_type_id(resid);
1219       const ThemeType* type = package->types[type_idx].get();
1220       if (type != nullptr) {
1221         const int entry_idx = get_entry_id(resid);
1222         if (entry_idx < type->entry_count) {
1223           const ThemeEntry& entry = type->entries[entry_idx];
1224           type_spec_flags |= entry.type_spec_flags;
1225 
1226           if (entry.value.dataType == Res_value::TYPE_ATTRIBUTE) {
1227             if (cnt > 0) {
1228               cnt--;
1229               resid = entry.value.data;
1230               continue;
1231             }
1232             return kInvalidCookie;
1233           }
1234 
1235           // @null is different than @empty.
1236           if (entry.value.dataType == Res_value::TYPE_NULL &&
1237               entry.value.data != Res_value::DATA_NULL_EMPTY) {
1238             return kInvalidCookie;
1239           }
1240 
1241           *out_value = entry.value;
1242           *out_flags = type_spec_flags;
1243           return entry.cookie;
1244         }
1245       }
1246     }
1247     break;
1248   } while (true);
1249   return kInvalidCookie;
1250 }
1251 
ResolveAttributeReference(ApkAssetsCookie cookie,Res_value * in_out_value,ResTable_config * in_out_selected_config,uint32_t * in_out_type_spec_flags,uint32_t * out_last_ref) const1252 ApkAssetsCookie Theme::ResolveAttributeReference(ApkAssetsCookie cookie, Res_value* in_out_value,
1253                                                  ResTable_config* in_out_selected_config,
1254                                                  uint32_t* in_out_type_spec_flags,
1255                                                  uint32_t* out_last_ref) const {
1256   if (in_out_value->dataType == Res_value::TYPE_ATTRIBUTE) {
1257     uint32_t new_flags;
1258     cookie = GetAttribute(in_out_value->data, in_out_value, &new_flags);
1259     if (cookie == kInvalidCookie) {
1260       return kInvalidCookie;
1261     }
1262 
1263     if (in_out_type_spec_flags != nullptr) {
1264       *in_out_type_spec_flags |= new_flags;
1265     }
1266   }
1267   return asset_manager_->ResolveReference(cookie, in_out_value, in_out_selected_config,
1268                                           in_out_type_spec_flags, out_last_ref);
1269 }
1270 
Clear()1271 void Theme::Clear() {
1272   type_spec_flags_ = 0u;
1273   for (std::unique_ptr<Package>& package : packages_) {
1274     package.reset();
1275   }
1276 }
1277 
SetTo(const Theme & o)1278 void Theme::SetTo(const Theme& o) {
1279   if (this == &o) {
1280     return;
1281   }
1282 
1283   type_spec_flags_ = o.type_spec_flags_;
1284 
1285   if (asset_manager_ == o.asset_manager_) {
1286     // The theme comes from the same asset manager so all theme data can be copied exactly
1287     for (size_t p = 0; p < packages_.size(); p++) {
1288       const Package *package = o.packages_[p].get();
1289       if (package == nullptr) {
1290         // The other theme doesn't have this package, clear ours.
1291         packages_[p].reset();
1292         continue;
1293       }
1294 
1295       if (packages_[p] == nullptr) {
1296         // The other theme has this package, but we don't. Make one.
1297         packages_[p].reset(new Package());
1298       }
1299 
1300       for (size_t t = 0; t < package->types.size(); t++) {
1301         const ThemeType *type = package->types[t].get();
1302         if (type == nullptr) {
1303           // The other theme doesn't have this type, clear ours.
1304           packages_[p]->types[t].reset();
1305           continue;
1306         }
1307 
1308         // Create a new type and update it to theirs.
1309         const size_t type_alloc_size = sizeof(ThemeType) + (type->entry_count * sizeof(ThemeEntry));
1310         void *copied_data = malloc(type_alloc_size);
1311         memcpy(copied_data, type, type_alloc_size);
1312         packages_[p]->types[t].reset(reinterpret_cast<ThemeType *>(copied_data));
1313       }
1314     }
1315   } else {
1316     std::map<ApkAssetsCookie, ApkAssetsCookie> src_to_dest_asset_cookies;
1317     typedef std::map<int, int> SourceToDestinationRuntimePackageMap;
1318     std::map<ApkAssetsCookie, SourceToDestinationRuntimePackageMap> src_asset_cookie_id_map;
1319 
1320     // Determine which ApkAssets are loaded in both theme AssetManagers.
1321     std::vector<const ApkAssets*> src_assets = o.asset_manager_->GetApkAssets();
1322     for (size_t i = 0; i < src_assets.size(); i++) {
1323       const ApkAssets* src_asset = src_assets[i];
1324 
1325       std::vector<const ApkAssets*> dest_assets = asset_manager_->GetApkAssets();
1326       for (size_t j = 0; j < dest_assets.size(); j++) {
1327         const ApkAssets* dest_asset = dest_assets[j];
1328 
1329         // Map the runtime package of the source apk asset to the destination apk asset.
1330         if (src_asset->GetPath() == dest_asset->GetPath()) {
1331           const std::vector<std::unique_ptr<const LoadedPackage>>& src_packages =
1332               src_asset->GetLoadedArsc()->GetPackages();
1333           const std::vector<std::unique_ptr<const LoadedPackage>>& dest_packages =
1334               dest_asset->GetLoadedArsc()->GetPackages();
1335 
1336           SourceToDestinationRuntimePackageMap package_map;
1337 
1338           // The source and destination package should have the same number of packages loaded in
1339           // the same order.
1340           const size_t N = src_packages.size();
1341           CHECK(N == dest_packages.size())
1342               << " LoadedArsc " << src_asset->GetPath() << " differs number of packages.";
1343           for (size_t p = 0; p < N; p++) {
1344             auto& src_package = src_packages[p];
1345             auto& dest_package = dest_packages[p];
1346             CHECK(src_package->GetPackageName() == dest_package->GetPackageName())
1347                 << " Package " << src_package->GetPackageName() << " differs in load order.";
1348 
1349             int src_package_id = o.asset_manager_->GetAssignedPackageId(src_package.get());
1350             int dest_package_id = asset_manager_->GetAssignedPackageId(dest_package.get());
1351             package_map[src_package_id] = dest_package_id;
1352           }
1353 
1354           src_to_dest_asset_cookies.insert(std::make_pair(i, j));
1355           src_asset_cookie_id_map.insert(std::make_pair(i, package_map));
1356           break;
1357         }
1358       }
1359     }
1360 
1361     // Reset the data in the destination theme.
1362     for (size_t p = 0; p < packages_.size(); p++) {
1363       if (packages_[p] != nullptr) {
1364         packages_[p].reset();
1365       }
1366     }
1367 
1368     for (size_t p = 0; p < packages_.size(); p++) {
1369       const Package *package = o.packages_[p].get();
1370       if (package == nullptr) {
1371         continue;
1372       }
1373 
1374       for (size_t t = 0; t < package->types.size(); t++) {
1375         const ThemeType *type = package->types[t].get();
1376         if (type == nullptr) {
1377           continue;
1378         }
1379 
1380         for (size_t e = 0; e < type->entry_count; e++) {
1381           const ThemeEntry &entry = type->entries[e];
1382           if (entry.value.dataType == Res_value::TYPE_NULL &&
1383               entry.value.data != Res_value::DATA_NULL_EMPTY) {
1384             continue;
1385           }
1386 
1387           bool is_reference = (entry.value.dataType == Res_value::TYPE_ATTRIBUTE
1388                                || entry.value.dataType == Res_value::TYPE_REFERENCE
1389                                || entry.value.dataType == Res_value::TYPE_DYNAMIC_ATTRIBUTE
1390                                || entry.value.dataType == Res_value::TYPE_DYNAMIC_REFERENCE)
1391                               && entry.value.data != 0x0;
1392 
1393           // If the attribute value represents an attribute or reference, the package id of the
1394           // value needs to be rewritten to the package id of the value in the destination.
1395           uint32_t attribute_data = entry.value.data;
1396           if (is_reference) {
1397             // Determine the package id of the reference in the destination AssetManager.
1398             auto value_package_map = src_asset_cookie_id_map.find(entry.cookie);
1399             if (value_package_map == src_asset_cookie_id_map.end()) {
1400               continue;
1401             }
1402 
1403             auto value_dest_package = value_package_map->second.find(
1404                 get_package_id(entry.value.data));
1405             if (value_dest_package == value_package_map->second.end()) {
1406               continue;
1407             }
1408 
1409             attribute_data = fix_package_id(entry.value.data, value_dest_package->second);
1410           }
1411 
1412           // Find the cookie of the value in the destination. If the source apk is not loaded in the
1413           // destination, only copy resources that do not reference resources in the source.
1414           ApkAssetsCookie data_dest_cookie;
1415           auto value_dest_cookie = src_to_dest_asset_cookies.find(entry.cookie);
1416           if (value_dest_cookie != src_to_dest_asset_cookies.end()) {
1417             data_dest_cookie = value_dest_cookie->second;
1418           } else {
1419             if (is_reference || entry.value.dataType == Res_value::TYPE_STRING) {
1420               continue;
1421             } else {
1422               data_dest_cookie = 0x0;
1423             }
1424           }
1425 
1426           // The package id of the attribute needs to be rewritten to the package id of the
1427           // attribute in the destination.
1428           int attribute_dest_package_id = p;
1429           if (attribute_dest_package_id != 0x01) {
1430             // Find the cookie of the attribute resource id in the source AssetManager
1431             FindEntryResult attribute_entry_result;
1432             ApkAssetsCookie attribute_cookie =
1433                 o.asset_manager_->FindEntry(make_resid(p, t, e), 0 /* density_override */ ,
1434                                             true /* stop_at_first_match */,
1435                                             true /* ignore_configuration */,
1436                                             &attribute_entry_result);
1437 
1438             // Determine the package id of the attribute in the destination AssetManager.
1439             auto attribute_package_map = src_asset_cookie_id_map.find(attribute_cookie);
1440             if (attribute_package_map == src_asset_cookie_id_map.end()) {
1441               continue;
1442             }
1443             auto attribute_dest_package = attribute_package_map->second.find(
1444                 attribute_dest_package_id);
1445             if (attribute_dest_package == attribute_package_map->second.end()) {
1446               continue;
1447             }
1448             attribute_dest_package_id = attribute_dest_package->second;
1449           }
1450 
1451           // Lazily instantiate the destination package.
1452           std::unique_ptr<Package>& dest_package = packages_[attribute_dest_package_id];
1453           if (dest_package == nullptr) {
1454             dest_package.reset(new Package());
1455           }
1456 
1457           // Lazily instantiate and resize the destination type.
1458           util::unique_cptr<ThemeType>& dest_type = dest_package->types[t];
1459           if (dest_type == nullptr || dest_type->entry_count < type->entry_count) {
1460             const size_t type_alloc_size = sizeof(ThemeType)
1461                 + (type->entry_count * sizeof(ThemeEntry));
1462             void* dest_data = malloc(type_alloc_size);
1463             memset(dest_data, 0, type->entry_count * sizeof(ThemeEntry));
1464 
1465             // Copy the existing destination type values if the type is resized.
1466             if (dest_type != nullptr) {
1467               memcpy(dest_data, type, sizeof(ThemeType)
1468                                       + (dest_type->entry_count * sizeof(ThemeEntry)));
1469             }
1470 
1471             dest_type.reset(reinterpret_cast<ThemeType *>(dest_data));
1472             dest_type->entry_count = type->entry_count;
1473           }
1474 
1475           dest_type->entries[e].cookie = data_dest_cookie;
1476           dest_type->entries[e].value.dataType = entry.value.dataType;
1477           dest_type->entries[e].value.data = attribute_data;
1478           dest_type->entries[e].type_spec_flags = entry.type_spec_flags;
1479         }
1480       }
1481     }
1482   }
1483 }
1484 
Dump() const1485 void Theme::Dump() const {
1486   base::ScopedLogSeverity _log(base::INFO);
1487   LOG(INFO) << base::StringPrintf("Theme(this=%p, AssetManager2=%p)", this, asset_manager_);
1488 
1489   for (int p = 0; p < packages_.size(); p++) {
1490     auto& package = packages_[p];
1491     if (package == nullptr) {
1492       continue;
1493     }
1494 
1495     for (int t = 0; t < package->types.size(); t++) {
1496       auto& type = package->types[t];
1497       if (type == nullptr) {
1498         continue;
1499       }
1500 
1501       for (int e = 0; e < type->entry_count; e++) {
1502         auto& entry = type->entries[e];
1503         if (entry.value.dataType == Res_value::TYPE_NULL &&
1504             entry.value.data != Res_value::DATA_NULL_EMPTY) {
1505           continue;
1506         }
1507 
1508         LOG(INFO) << base::StringPrintf("  entry(0x%08x)=(0x%08x) type=(0x%02x), cookie(%d)",
1509                                         make_resid(p, t, e), entry.value.data,
1510                                         entry.value.dataType, entry.cookie);
1511       }
1512     }
1513   }
1514 }
1515 
1516 }  // namespace android
1517