blob: 44acbcaf8ace236b88845e363af2555329f3534b [file] [log] [blame]
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -07001/*
2 * Copyright (C) 2019 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#include "idmap2/ResourceMapping.h"
18
19#include <map>
20#include <memory>
21#include <set>
22#include <string>
23#include <utility>
24#include <vector>
25
26#include "android-base/stringprintf.h"
Winson62ac8b52019-12-04 08:36:48 -080027#include "androidfw/ResourceTypes.h"
28#include "idmap2/PolicyUtils.h"
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -070029#include "idmap2/ResourceUtils.h"
30
31using android::base::StringPrintf;
Winson62ac8b52019-12-04 08:36:48 -080032using android::idmap2::utils::BitmaskToPolicies;
Ryan Mitchell5035d662020-01-22 13:19:41 -080033using android::idmap2::utils::IsReference;
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -070034using android::idmap2::utils::ResToTypeEntryName;
Winson62ac8b52019-12-04 08:36:48 -080035using PolicyBitmask = android::ResTable_overlayable_policy_header::PolicyBitmask;
36using PolicyFlags = android::ResTable_overlayable_policy_header::PolicyFlags;
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -070037
38namespace android::idmap2 {
39
40namespace {
41
Ryan Mitchellee4a5642019-10-16 08:32:55 -070042#define REWRITE_PACKAGE(resid, package_id) \
43 (((resid)&0x00ffffffU) | (((uint32_t)(package_id)) << 24U))
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -070044#define EXTRACT_PACKAGE(resid) ((0xff000000 & (resid)) >> 24)
45
46std::string ConcatPolicies(const std::vector<std::string>& policies) {
47 std::string message;
48 for (const std::string& policy : policies) {
49 if (!message.empty()) {
50 message.append("|");
51 }
52 message.append(policy);
53 }
54
55 return message;
56}
57
58Result<Unit> CheckOverlayable(const LoadedPackage& target_package,
59 const OverlayManifestInfo& overlay_info,
60 const PolicyBitmask& fulfilled_policies,
61 const ResourceId& target_resource) {
62 static constexpr const PolicyBitmask sDefaultPolicies =
Winson62ac8b52019-12-04 08:36:48 -080063 PolicyFlags::ODM_PARTITION | PolicyFlags::OEM_PARTITION | PolicyFlags::SYSTEM_PARTITION |
Ryan Mitchellaf93f5d2020-05-26 14:29:03 -070064 PolicyFlags::VENDOR_PARTITION | PolicyFlags::PRODUCT_PARTITION | PolicyFlags::SIGNATURE |
65 PolicyFlags::ACTOR_SIGNATURE;
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -070066
67 // If the resource does not have an overlayable definition, allow the resource to be overlaid if
68 // the overlay is preinstalled or signed with the same signature as the target.
69 if (!target_package.DefinesOverlayable()) {
70 return (sDefaultPolicies & fulfilled_policies) != 0
71 ? Result<Unit>({})
72 : Error(
73 "overlay must be preinstalled or signed with the same signature as the "
74 "target");
75 }
76
77 const OverlayableInfo* overlayable_info = target_package.GetOverlayableInfo(target_resource);
78 if (overlayable_info == nullptr) {
79 // Do not allow non-overlayable resources to be overlaid.
80 return Error("target resource has no overlayable declaration");
81 }
82
83 if (overlay_info.target_name != overlayable_info->name) {
84 // If the overlay supplies a target overlayable name, the resource must belong to the
85 // overlayable defined with the specified name to be overlaid.
86 return Error(R"(<overlay> android:targetName "%s" does not match overlayable name "%s")",
87 overlay_info.target_name.c_str(), overlayable_info->name.c_str());
88 }
89
90 // Enforce policy restrictions if the resource is declared as overlayable.
91 if ((overlayable_info->policy_flags & fulfilled_policies) == 0) {
92 return Error(R"(overlay with policies "%s" does not fulfill any overlayable policies "%s")",
93 ConcatPolicies(BitmaskToPolicies(fulfilled_policies)).c_str(),
94 ConcatPolicies(BitmaskToPolicies(overlayable_info->policy_flags)).c_str());
95 }
96
97 return Result<Unit>({});
98}
99
100// TODO(martenkongstad): scan for package name instead of assuming package at index 0
101//
102// idmap version 0x01 naively assumes that the package to use is always the first ResTable_package
103// in the resources.arsc blob. In most cases, there is only a single ResTable_package anyway, so
104// this assumption tends to work out. That said, the correct thing to do is to scan
105// resources.arsc for a package with a given name as read from the package manifest instead of
106// relying on a hard-coded index. This however requires storing the package name in the idmap
107// header, which in turn requires incrementing the idmap version. Because the initial version of
108// idmap2 is compatible with idmap, this will have to wait for now.
109const LoadedPackage* GetPackageAtIndex0(const LoadedArsc& loaded_arsc) {
110 const std::vector<std::unique_ptr<const LoadedPackage>>& packages = loaded_arsc.GetPackages();
111 if (packages.empty()) {
112 return nullptr;
113 }
114 int id = packages[0]->GetPackageId();
115 return loaded_arsc.GetPackageById(id);
116}
117
118Result<std::unique_ptr<Asset>> OpenNonAssetFromResource(const ResourceId& resource_id,
119 const AssetManager2& asset_manager) {
120 Res_value value{};
121 ResTable_config selected_config{};
122 uint32_t flags;
123 auto cookie =
124 asset_manager.GetResource(resource_id, /* may_be_bag */ false,
125 /* density_override */ 0U, &value, &selected_config, &flags);
126 if (cookie == kInvalidCookie) {
127 return Error("failed to find resource for id 0x%08x", resource_id);
128 }
129
130 if (value.dataType != Res_value::TYPE_STRING) {
131 return Error("resource for is 0x%08x is not a file", resource_id);
132 }
133
134 auto string_pool = asset_manager.GetStringPoolForCookie(cookie);
135 size_t len;
136 auto file_path16 = string_pool->stringAt(value.data, &len);
137 if (file_path16 == nullptr) {
138 return Error("failed to find string for index %d", value.data);
139 }
140
141 // Load the overlay resource mappings from the file specified using android:resourcesMap.
142 auto file_path = String8(String16(file_path16));
143 auto asset = asset_manager.OpenNonAsset(file_path.c_str(), Asset::AccessMode::ACCESS_BUFFER);
144 if (asset == nullptr) {
145 return Error("file \"%s\" not found", file_path.c_str());
146 }
147
148 return asset;
149}
150
151} // namespace
152
153Result<ResourceMapping> ResourceMapping::CreateResourceMapping(const AssetManager2* target_am,
154 const LoadedPackage* target_package,
155 const LoadedPackage* overlay_package,
156 size_t string_pool_offset,
Mårten Kongstadd7e8a532019-10-11 08:32:04 +0200157 const XmlParser& overlay_parser,
158 LogInfo& log_info) {
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700159 ResourceMapping resource_mapping;
160 auto root_it = overlay_parser.tree_iterator();
161 if (root_it->event() != XmlParser::Event::START_TAG || root_it->name() != "overlay") {
162 return Error("root element is not <overlay> tag");
163 }
164
Ryan Mitchellee4a5642019-10-16 08:32:55 -0700165 const uint8_t target_package_id = target_package->GetPackageId();
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700166 const uint8_t overlay_package_id = overlay_package->GetPackageId();
167 auto overlay_it_end = root_it.end();
168 for (auto overlay_it = root_it.begin(); overlay_it != overlay_it_end; ++overlay_it) {
169 if (overlay_it->event() == XmlParser::Event::BAD_DOCUMENT) {
170 return Error("failed to parse overlay xml document");
171 }
172
173 if (overlay_it->event() != XmlParser::Event::START_TAG) {
174 continue;
175 }
176
177 if (overlay_it->name() != "item") {
178 return Error("unexpected tag <%s> in <overlay>", overlay_it->name().c_str());
179 }
180
181 Result<std::string> target_resource = overlay_it->GetAttributeStringValue("target");
182 if (!target_resource) {
183 return Error(R"(<item> tag missing expected attribute "target")");
184 }
185
186 Result<android::Res_value> overlay_resource = overlay_it->GetAttributeValue("value");
187 if (!overlay_resource) {
188 return Error(R"(<item> tag missing expected attribute "value")");
189 }
190
191 ResourceId target_id =
192 target_am->GetResourceId(*target_resource, "", target_package->GetPackageName());
193 if (target_id == 0U) {
Mårten Kongstadd7e8a532019-10-11 08:32:04 +0200194 log_info.Warning(LogMessage() << "failed to find resource \"" << *target_resource
195 << "\" in target resources");
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700196 continue;
197 }
198
Ryan Mitchellee4a5642019-10-16 08:32:55 -0700199 // Retrieve the compile-time resource id of the target resource.
200 target_id = REWRITE_PACKAGE(target_id, target_package_id);
201
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700202 if (overlay_resource->dataType == Res_value::TYPE_STRING) {
203 overlay_resource->data += string_pool_offset;
204 }
205
206 // Only rewrite resources defined within the overlay package to their corresponding target
207 // resource ids at runtime.
208 bool rewrite_overlay_reference =
Ryan Mitchell5035d662020-01-22 13:19:41 -0800209 IsReference(overlay_resource->dataType)
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700210 ? overlay_package_id == EXTRACT_PACKAGE(overlay_resource->data)
211 : false;
Mårten Kongstadd7e8a532019-10-11 08:32:04 +0200212
Ryan Mitchelle753ffe2019-09-23 09:47:02 -0700213 if (rewrite_overlay_reference) {
214 overlay_resource->dataType = Res_value::TYPE_DYNAMIC_REFERENCE;
215 }
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700216
217 resource_mapping.AddMapping(target_id, overlay_resource->dataType, overlay_resource->data,
218 rewrite_overlay_reference);
219 }
220
221 return resource_mapping;
222}
223
224Result<ResourceMapping> ResourceMapping::CreateResourceMappingLegacy(
225 const AssetManager2* target_am, const AssetManager2* overlay_am,
226 const LoadedPackage* target_package, const LoadedPackage* overlay_package) {
227 ResourceMapping resource_mapping;
Ryan Mitchellee4a5642019-10-16 08:32:55 -0700228 const uint8_t target_package_id = target_package->GetPackageId();
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700229 const auto end = overlay_package->end();
230 for (auto iter = overlay_package->begin(); iter != end; ++iter) {
231 const ResourceId overlay_resid = *iter;
232 Result<std::string> name = utils::ResToTypeEntryName(*overlay_am, overlay_resid);
233 if (!name) {
234 continue;
235 }
236
237 // Find the resource with the same type and entry name within the target package.
238 const std::string full_name =
239 base::StringPrintf("%s:%s", target_package->GetPackageName().c_str(), name->c_str());
Ryan Mitchellee4a5642019-10-16 08:32:55 -0700240 ResourceId target_resource = target_am->GetResourceId(full_name);
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700241 if (target_resource == 0U) {
242 continue;
243 }
244
Ryan Mitchellee4a5642019-10-16 08:32:55 -0700245 // Retrieve the compile-time resource id of the target resource.
246 target_resource = REWRITE_PACKAGE(target_resource, target_package_id);
247
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700248 resource_mapping.AddMapping(target_resource, Res_value::TYPE_REFERENCE, overlay_resid,
Ryan Mitchelle753ffe2019-09-23 09:47:02 -0700249 /* rewrite_overlay_reference */ false);
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700250 }
251
252 return resource_mapping;
253}
254
255void ResourceMapping::FilterOverlayableResources(const AssetManager2* target_am,
256 const LoadedPackage* target_package,
257 const LoadedPackage* overlay_package,
258 const OverlayManifestInfo& overlay_info,
Mårten Kongstadd7e8a532019-10-11 08:32:04 +0200259 const PolicyBitmask& fulfilled_policies,
260 LogInfo& log_info) {
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700261 std::set<ResourceId> remove_ids;
262 for (const auto& target_map : target_map_) {
263 const ResourceId target_resid = target_map.first;
264 Result<Unit> success =
265 CheckOverlayable(*target_package, overlay_info, fulfilled_policies, target_resid);
266 if (success) {
267 continue;
268 }
269
270 // Attempting to overlay a resource that is not allowed to be overlaid is treated as a
271 // warning.
272 Result<std::string> name = utils::ResToTypeEntryName(*target_am, target_resid);
273 if (!name) {
274 name = StringPrintf("0x%08x", target_resid);
275 }
276
Mårten Kongstadd7e8a532019-10-11 08:32:04 +0200277 log_info.Warning(LogMessage() << "overlay \"" << overlay_package->GetPackageName()
278 << "\" is not allowed to overlay resource \"" << *name
279 << "\" in target: " << success.GetErrorMessage());
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700280
281 remove_ids.insert(target_resid);
282 }
283
284 for (const ResourceId target_resid : remove_ids) {
285 RemoveMapping(target_resid);
286 }
287}
288
289Result<ResourceMapping> ResourceMapping::FromApkAssets(const ApkAssets& target_apk_assets,
290 const ApkAssets& overlay_apk_assets,
291 const OverlayManifestInfo& overlay_info,
292 const PolicyBitmask& fulfilled_policies,
Mårten Kongstadd7e8a532019-10-11 08:32:04 +0200293 bool enforce_overlayable,
294 LogInfo& log_info) {
295 if (enforce_overlayable) {
296 log_info.Info(LogMessage() << "fulfilled_policies="
297 << ConcatPolicies(BitmaskToPolicies(fulfilled_policies))
298 << " enforce_overlayable="
299 << (enforce_overlayable ? "true" : "false"));
300 }
301
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700302 AssetManager2 target_asset_manager;
303 if (!target_asset_manager.SetApkAssets({&target_apk_assets}, true /* invalidate_caches */,
304 false /* filter_incompatible_configs*/)) {
305 return Error("failed to create target asset manager");
306 }
307
308 AssetManager2 overlay_asset_manager;
309 if (!overlay_asset_manager.SetApkAssets({&overlay_apk_assets}, true /* invalidate_caches */,
310 false /* filter_incompatible_configs */)) {
311 return Error("failed to create overlay asset manager");
312 }
313
314 const LoadedArsc* target_arsc = target_apk_assets.GetLoadedArsc();
315 if (target_arsc == nullptr) {
316 return Error("failed to load target resources.arsc");
317 }
318
319 const LoadedArsc* overlay_arsc = overlay_apk_assets.GetLoadedArsc();
320 if (overlay_arsc == nullptr) {
321 return Error("failed to load overlay resources.arsc");
322 }
323
324 const LoadedPackage* target_pkg = GetPackageAtIndex0(*target_arsc);
325 if (target_pkg == nullptr) {
326 return Error("failed to load target package from resources.arsc");
327 }
328
329 const LoadedPackage* overlay_pkg = GetPackageAtIndex0(*overlay_arsc);
330 if (overlay_pkg == nullptr) {
331 return Error("failed to load overlay package from resources.arsc");
332 }
333
334 size_t string_pool_data_length = 0U;
335 size_t string_pool_offset = 0U;
336 std::unique_ptr<uint8_t[]> string_pool_data;
337 Result<ResourceMapping> resource_mapping = {{}};
338 if (overlay_info.resource_mapping != 0U) {
Ryan Mitchell5035d662020-01-22 13:19:41 -0800339 // Use the dynamic reference table to find the assigned resource id of the map xml.
340 const auto& ref_table = overlay_asset_manager.GetDynamicRefTableForCookie(0);
341 uint32_t resource_mapping_id = overlay_info.resource_mapping;
342 ref_table->lookupResourceId(&resource_mapping_id);
343
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700344 // Load the overlay resource mappings from the file specified using android:resourcesMap.
Ryan Mitchell5035d662020-01-22 13:19:41 -0800345 auto asset = OpenNonAssetFromResource(resource_mapping_id, overlay_asset_manager);
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700346 if (!asset) {
347 return Error("failed opening xml for android:resourcesMap: %s",
348 asset.GetErrorMessage().c_str());
349 }
350
351 auto parser =
352 XmlParser::Create((*asset)->getBuffer(true /* wordAligned*/), (*asset)->getLength());
353 if (!parser) {
354 return Error("failed opening ResXMLTree");
355 }
356
357 // Copy the xml string pool data before the parse goes out of scope.
358 auto& string_pool = (*parser)->get_strings();
359 string_pool_data_length = string_pool.bytes();
360 string_pool_data.reset(new uint8_t[string_pool_data_length]);
361 memcpy(string_pool_data.get(), string_pool.data(), string_pool_data_length);
362
363 // Offset string indices by the size of the overlay resource table string pool.
364 string_pool_offset = overlay_arsc->GetStringPool()->size();
365
366 resource_mapping = CreateResourceMapping(&target_asset_manager, target_pkg, overlay_pkg,
Mårten Kongstadd7e8a532019-10-11 08:32:04 +0200367 string_pool_offset, *(*parser), log_info);
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700368 } else {
369 // If no file is specified using android:resourcesMap, it is assumed that the overlay only
370 // defines resources intended to override target resources of the same type and name.
371 resource_mapping = CreateResourceMappingLegacy(&target_asset_manager, &overlay_asset_manager,
372 target_pkg, overlay_pkg);
373 }
374
375 if (!resource_mapping) {
376 return resource_mapping.GetError();
377 }
378
379 if (enforce_overlayable) {
380 // Filter out resources the overlay is not allowed to override.
381 (*resource_mapping)
382 .FilterOverlayableResources(&target_asset_manager, target_pkg, overlay_pkg, overlay_info,
Mårten Kongstadd7e8a532019-10-11 08:32:04 +0200383 fulfilled_policies, log_info);
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700384 }
385
386 resource_mapping->target_package_id_ = target_pkg->GetPackageId();
387 resource_mapping->overlay_package_id_ = overlay_pkg->GetPackageId();
388 resource_mapping->string_pool_offset_ = string_pool_offset;
389 resource_mapping->string_pool_data_ = std::move(string_pool_data);
390 resource_mapping->string_pool_data_length_ = string_pool_data_length;
391 return std::move(*resource_mapping);
392}
393
394OverlayResourceMap ResourceMapping::GetOverlayToTargetMap() const {
395 // An overlay resource can override multiple target resources at once. Rewrite the overlay
396 // resource as the first target resource it overrides.
397 OverlayResourceMap map;
398 for (const auto& mappings : overlay_map_) {
399 map.insert(std::make_pair(mappings.first, mappings.second));
400 }
401 return map;
402}
403
404Result<Unit> ResourceMapping::AddMapping(ResourceId target_resource,
405 TargetValue::DataType data_type,
406 TargetValue::DataValue data_value,
407 bool rewrite_overlay_reference) {
408 if (target_map_.find(target_resource) != target_map_.end()) {
409 return Error(R"(target resource id "0x%08x" mapped to multiple values)", target_resource);
410 }
411
412 // TODO(141485591): Ensure that the overlay type is compatible with the target type. If the
413 // runtime types are not compatible, it could cause runtime crashes when the resource is resolved.
414
415 target_map_.insert(std::make_pair(target_resource, TargetValue{data_type, data_value}));
416
Ryan Mitchell5035d662020-01-22 13:19:41 -0800417 if (rewrite_overlay_reference && IsReference(data_type)) {
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700418 overlay_map_.insert(std::make_pair(data_value, target_resource));
419 }
420
421 return Result<Unit>({});
422}
423
424void ResourceMapping::RemoveMapping(ResourceId target_resource) {
425 auto target_iter = target_map_.find(target_resource);
426 if (target_iter == target_map_.end()) {
427 return;
428 }
429
430 const TargetValue value = target_iter->second;
431 target_map_.erase(target_iter);
432
Ryan Mitchell5035d662020-01-22 13:19:41 -0800433 if (!IsReference(value.data_type)) {
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700434 return;
435 }
436
437 auto overlay_iter = overlay_map_.equal_range(value.data_value);
438 for (auto i = overlay_iter.first; i != overlay_iter.second; ++i) {
439 if (i->second == target_resource) {
440 overlay_map_.erase(i);
441 return;
442 }
443 }
444}
445
446} // namespace android::idmap2