blob: fd8b4eb86b4a4430a1ed62f23453e5209955b0b2 [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 |
Zoran Jovanovic0f942f92020-06-09 18:51:57 +020064 PolicyFlags::VENDOR_PARTITION | PolicyFlags::PRODUCT_PARTITION | PolicyFlags::SIGNATURE |
65 PolicyFlags::CONFIG_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
Zoran Jovanovic0f942f92020-06-09 18:51:57 +020068 // the overlay is preinstalled, signed with the same signature as the target or signed with the
69 // same signature as reference package defined in SystemConfig under 'overlay-config-signature'
70 // tag.
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -070071 if (!target_package.DefinesOverlayable()) {
72 return (sDefaultPolicies & fulfilled_policies) != 0
73 ? Result<Unit>({})
74 : Error(
75 "overlay must be preinstalled or signed with the same signature as the "
76 "target");
77 }
78
79 const OverlayableInfo* overlayable_info = target_package.GetOverlayableInfo(target_resource);
80 if (overlayable_info == nullptr) {
81 // Do not allow non-overlayable resources to be overlaid.
82 return Error("target resource has no overlayable declaration");
83 }
84
85 if (overlay_info.target_name != overlayable_info->name) {
86 // If the overlay supplies a target overlayable name, the resource must belong to the
87 // overlayable defined with the specified name to be overlaid.
88 return Error(R"(<overlay> android:targetName "%s" does not match overlayable name "%s")",
89 overlay_info.target_name.c_str(), overlayable_info->name.c_str());
90 }
91
92 // Enforce policy restrictions if the resource is declared as overlayable.
93 if ((overlayable_info->policy_flags & fulfilled_policies) == 0) {
94 return Error(R"(overlay with policies "%s" does not fulfill any overlayable policies "%s")",
95 ConcatPolicies(BitmaskToPolicies(fulfilled_policies)).c_str(),
96 ConcatPolicies(BitmaskToPolicies(overlayable_info->policy_flags)).c_str());
97 }
98
99 return Result<Unit>({});
100}
101
102// TODO(martenkongstad): scan for package name instead of assuming package at index 0
103//
104// idmap version 0x01 naively assumes that the package to use is always the first ResTable_package
105// in the resources.arsc blob. In most cases, there is only a single ResTable_package anyway, so
106// this assumption tends to work out. That said, the correct thing to do is to scan
107// resources.arsc for a package with a given name as read from the package manifest instead of
108// relying on a hard-coded index. This however requires storing the package name in the idmap
109// header, which in turn requires incrementing the idmap version. Because the initial version of
110// idmap2 is compatible with idmap, this will have to wait for now.
111const LoadedPackage* GetPackageAtIndex0(const LoadedArsc& loaded_arsc) {
112 const std::vector<std::unique_ptr<const LoadedPackage>>& packages = loaded_arsc.GetPackages();
113 if (packages.empty()) {
114 return nullptr;
115 }
116 int id = packages[0]->GetPackageId();
117 return loaded_arsc.GetPackageById(id);
118}
119
120Result<std::unique_ptr<Asset>> OpenNonAssetFromResource(const ResourceId& resource_id,
121 const AssetManager2& asset_manager) {
122 Res_value value{};
123 ResTable_config selected_config{};
124 uint32_t flags;
125 auto cookie =
126 asset_manager.GetResource(resource_id, /* may_be_bag */ false,
127 /* density_override */ 0U, &value, &selected_config, &flags);
128 if (cookie == kInvalidCookie) {
129 return Error("failed to find resource for id 0x%08x", resource_id);
130 }
131
132 if (value.dataType != Res_value::TYPE_STRING) {
133 return Error("resource for is 0x%08x is not a file", resource_id);
134 }
135
136 auto string_pool = asset_manager.GetStringPoolForCookie(cookie);
137 size_t len;
138 auto file_path16 = string_pool->stringAt(value.data, &len);
139 if (file_path16 == nullptr) {
140 return Error("failed to find string for index %d", value.data);
141 }
142
143 // Load the overlay resource mappings from the file specified using android:resourcesMap.
144 auto file_path = String8(String16(file_path16));
145 auto asset = asset_manager.OpenNonAsset(file_path.c_str(), Asset::AccessMode::ACCESS_BUFFER);
146 if (asset == nullptr) {
147 return Error("file \"%s\" not found", file_path.c_str());
148 }
149
150 return asset;
151}
152
153} // namespace
154
155Result<ResourceMapping> ResourceMapping::CreateResourceMapping(const AssetManager2* target_am,
156 const LoadedPackage* target_package,
157 const LoadedPackage* overlay_package,
158 size_t string_pool_offset,
Mårten Kongstadd7e8a532019-10-11 08:32:04 +0200159 const XmlParser& overlay_parser,
160 LogInfo& log_info) {
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700161 ResourceMapping resource_mapping;
162 auto root_it = overlay_parser.tree_iterator();
163 if (root_it->event() != XmlParser::Event::START_TAG || root_it->name() != "overlay") {
164 return Error("root element is not <overlay> tag");
165 }
166
Ryan Mitchellee4a5642019-10-16 08:32:55 -0700167 const uint8_t target_package_id = target_package->GetPackageId();
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700168 const uint8_t overlay_package_id = overlay_package->GetPackageId();
169 auto overlay_it_end = root_it.end();
170 for (auto overlay_it = root_it.begin(); overlay_it != overlay_it_end; ++overlay_it) {
171 if (overlay_it->event() == XmlParser::Event::BAD_DOCUMENT) {
172 return Error("failed to parse overlay xml document");
173 }
174
175 if (overlay_it->event() != XmlParser::Event::START_TAG) {
176 continue;
177 }
178
179 if (overlay_it->name() != "item") {
180 return Error("unexpected tag <%s> in <overlay>", overlay_it->name().c_str());
181 }
182
183 Result<std::string> target_resource = overlay_it->GetAttributeStringValue("target");
184 if (!target_resource) {
185 return Error(R"(<item> tag missing expected attribute "target")");
186 }
187
188 Result<android::Res_value> overlay_resource = overlay_it->GetAttributeValue("value");
189 if (!overlay_resource) {
190 return Error(R"(<item> tag missing expected attribute "value")");
191 }
192
193 ResourceId target_id =
194 target_am->GetResourceId(*target_resource, "", target_package->GetPackageName());
195 if (target_id == 0U) {
Mårten Kongstadd7e8a532019-10-11 08:32:04 +0200196 log_info.Warning(LogMessage() << "failed to find resource \"" << *target_resource
197 << "\" in target resources");
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700198 continue;
199 }
200
Ryan Mitchellee4a5642019-10-16 08:32:55 -0700201 // Retrieve the compile-time resource id of the target resource.
202 target_id = REWRITE_PACKAGE(target_id, target_package_id);
203
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700204 if (overlay_resource->dataType == Res_value::TYPE_STRING) {
205 overlay_resource->data += string_pool_offset;
206 }
207
208 // Only rewrite resources defined within the overlay package to their corresponding target
209 // resource ids at runtime.
210 bool rewrite_overlay_reference =
Ryan Mitchell5035d662020-01-22 13:19:41 -0800211 IsReference(overlay_resource->dataType)
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700212 ? overlay_package_id == EXTRACT_PACKAGE(overlay_resource->data)
213 : false;
Mårten Kongstadd7e8a532019-10-11 08:32:04 +0200214
Ryan Mitchelle753ffe2019-09-23 09:47:02 -0700215 if (rewrite_overlay_reference) {
216 overlay_resource->dataType = Res_value::TYPE_DYNAMIC_REFERENCE;
217 }
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700218
219 resource_mapping.AddMapping(target_id, overlay_resource->dataType, overlay_resource->data,
220 rewrite_overlay_reference);
221 }
222
223 return resource_mapping;
224}
225
226Result<ResourceMapping> ResourceMapping::CreateResourceMappingLegacy(
227 const AssetManager2* target_am, const AssetManager2* overlay_am,
228 const LoadedPackage* target_package, const LoadedPackage* overlay_package) {
229 ResourceMapping resource_mapping;
Ryan Mitchellee4a5642019-10-16 08:32:55 -0700230 const uint8_t target_package_id = target_package->GetPackageId();
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700231 const auto end = overlay_package->end();
232 for (auto iter = overlay_package->begin(); iter != end; ++iter) {
233 const ResourceId overlay_resid = *iter;
234 Result<std::string> name = utils::ResToTypeEntryName(*overlay_am, overlay_resid);
235 if (!name) {
236 continue;
237 }
238
239 // Find the resource with the same type and entry name within the target package.
240 const std::string full_name =
241 base::StringPrintf("%s:%s", target_package->GetPackageName().c_str(), name->c_str());
Ryan Mitchellee4a5642019-10-16 08:32:55 -0700242 ResourceId target_resource = target_am->GetResourceId(full_name);
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700243 if (target_resource == 0U) {
244 continue;
245 }
246
Ryan Mitchellee4a5642019-10-16 08:32:55 -0700247 // Retrieve the compile-time resource id of the target resource.
248 target_resource = REWRITE_PACKAGE(target_resource, target_package_id);
249
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700250 resource_mapping.AddMapping(target_resource, Res_value::TYPE_REFERENCE, overlay_resid,
Ryan Mitchelle753ffe2019-09-23 09:47:02 -0700251 /* rewrite_overlay_reference */ false);
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700252 }
253
254 return resource_mapping;
255}
256
257void ResourceMapping::FilterOverlayableResources(const AssetManager2* target_am,
258 const LoadedPackage* target_package,
259 const LoadedPackage* overlay_package,
260 const OverlayManifestInfo& overlay_info,
Mårten Kongstadd7e8a532019-10-11 08:32:04 +0200261 const PolicyBitmask& fulfilled_policies,
262 LogInfo& log_info) {
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700263 std::set<ResourceId> remove_ids;
264 for (const auto& target_map : target_map_) {
265 const ResourceId target_resid = target_map.first;
266 Result<Unit> success =
267 CheckOverlayable(*target_package, overlay_info, fulfilled_policies, target_resid);
268 if (success) {
269 continue;
270 }
271
272 // Attempting to overlay a resource that is not allowed to be overlaid is treated as a
273 // warning.
274 Result<std::string> name = utils::ResToTypeEntryName(*target_am, target_resid);
275 if (!name) {
276 name = StringPrintf("0x%08x", target_resid);
277 }
278
Mårten Kongstadd7e8a532019-10-11 08:32:04 +0200279 log_info.Warning(LogMessage() << "overlay \"" << overlay_package->GetPackageName()
280 << "\" is not allowed to overlay resource \"" << *name
281 << "\" in target: " << success.GetErrorMessage());
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700282
283 remove_ids.insert(target_resid);
284 }
285
286 for (const ResourceId target_resid : remove_ids) {
287 RemoveMapping(target_resid);
288 }
289}
290
291Result<ResourceMapping> ResourceMapping::FromApkAssets(const ApkAssets& target_apk_assets,
292 const ApkAssets& overlay_apk_assets,
293 const OverlayManifestInfo& overlay_info,
294 const PolicyBitmask& fulfilled_policies,
Mårten Kongstadd7e8a532019-10-11 08:32:04 +0200295 bool enforce_overlayable,
296 LogInfo& log_info) {
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700297 AssetManager2 target_asset_manager;
298 if (!target_asset_manager.SetApkAssets({&target_apk_assets}, true /* invalidate_caches */,
299 false /* filter_incompatible_configs*/)) {
300 return Error("failed to create target asset manager");
301 }
302
303 AssetManager2 overlay_asset_manager;
304 if (!overlay_asset_manager.SetApkAssets({&overlay_apk_assets}, true /* invalidate_caches */,
305 false /* filter_incompatible_configs */)) {
306 return Error("failed to create overlay asset manager");
307 }
308
309 const LoadedArsc* target_arsc = target_apk_assets.GetLoadedArsc();
310 if (target_arsc == nullptr) {
311 return Error("failed to load target resources.arsc");
312 }
313
314 const LoadedArsc* overlay_arsc = overlay_apk_assets.GetLoadedArsc();
315 if (overlay_arsc == nullptr) {
316 return Error("failed to load overlay resources.arsc");
317 }
318
319 const LoadedPackage* target_pkg = GetPackageAtIndex0(*target_arsc);
320 if (target_pkg == nullptr) {
321 return Error("failed to load target package from resources.arsc");
322 }
323
324 const LoadedPackage* overlay_pkg = GetPackageAtIndex0(*overlay_arsc);
325 if (overlay_pkg == nullptr) {
326 return Error("failed to load overlay package from resources.arsc");
327 }
328
329 size_t string_pool_data_length = 0U;
330 size_t string_pool_offset = 0U;
331 std::unique_ptr<uint8_t[]> string_pool_data;
332 Result<ResourceMapping> resource_mapping = {{}};
333 if (overlay_info.resource_mapping != 0U) {
Ryan Mitchell5035d662020-01-22 13:19:41 -0800334 // Use the dynamic reference table to find the assigned resource id of the map xml.
335 const auto& ref_table = overlay_asset_manager.GetDynamicRefTableForCookie(0);
336 uint32_t resource_mapping_id = overlay_info.resource_mapping;
337 ref_table->lookupResourceId(&resource_mapping_id);
338
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700339 // Load the overlay resource mappings from the file specified using android:resourcesMap.
Ryan Mitchell5035d662020-01-22 13:19:41 -0800340 auto asset = OpenNonAssetFromResource(resource_mapping_id, overlay_asset_manager);
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700341 if (!asset) {
342 return Error("failed opening xml for android:resourcesMap: %s",
343 asset.GetErrorMessage().c_str());
344 }
345
346 auto parser =
347 XmlParser::Create((*asset)->getBuffer(true /* wordAligned*/), (*asset)->getLength());
348 if (!parser) {
349 return Error("failed opening ResXMLTree");
350 }
351
352 // Copy the xml string pool data before the parse goes out of scope.
353 auto& string_pool = (*parser)->get_strings();
354 string_pool_data_length = string_pool.bytes();
355 string_pool_data.reset(new uint8_t[string_pool_data_length]);
356 memcpy(string_pool_data.get(), string_pool.data(), string_pool_data_length);
357
358 // Offset string indices by the size of the overlay resource table string pool.
359 string_pool_offset = overlay_arsc->GetStringPool()->size();
360
361 resource_mapping = CreateResourceMapping(&target_asset_manager, target_pkg, overlay_pkg,
Mårten Kongstadd7e8a532019-10-11 08:32:04 +0200362 string_pool_offset, *(*parser), log_info);
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700363 } else {
364 // If no file is specified using android:resourcesMap, it is assumed that the overlay only
365 // defines resources intended to override target resources of the same type and name.
366 resource_mapping = CreateResourceMappingLegacy(&target_asset_manager, &overlay_asset_manager,
367 target_pkg, overlay_pkg);
368 }
369
370 if (!resource_mapping) {
371 return resource_mapping.GetError();
372 }
373
374 if (enforce_overlayable) {
375 // Filter out resources the overlay is not allowed to override.
376 (*resource_mapping)
377 .FilterOverlayableResources(&target_asset_manager, target_pkg, overlay_pkg, overlay_info,
Mårten Kongstadd7e8a532019-10-11 08:32:04 +0200378 fulfilled_policies, log_info);
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700379 }
380
381 resource_mapping->target_package_id_ = target_pkg->GetPackageId();
382 resource_mapping->overlay_package_id_ = overlay_pkg->GetPackageId();
383 resource_mapping->string_pool_offset_ = string_pool_offset;
384 resource_mapping->string_pool_data_ = std::move(string_pool_data);
385 resource_mapping->string_pool_data_length_ = string_pool_data_length;
386 return std::move(*resource_mapping);
387}
388
389OverlayResourceMap ResourceMapping::GetOverlayToTargetMap() const {
390 // An overlay resource can override multiple target resources at once. Rewrite the overlay
391 // resource as the first target resource it overrides.
392 OverlayResourceMap map;
393 for (const auto& mappings : overlay_map_) {
394 map.insert(std::make_pair(mappings.first, mappings.second));
395 }
396 return map;
397}
398
399Result<Unit> ResourceMapping::AddMapping(ResourceId target_resource,
400 TargetValue::DataType data_type,
401 TargetValue::DataValue data_value,
402 bool rewrite_overlay_reference) {
403 if (target_map_.find(target_resource) != target_map_.end()) {
404 return Error(R"(target resource id "0x%08x" mapped to multiple values)", target_resource);
405 }
406
407 // TODO(141485591): Ensure that the overlay type is compatible with the target type. If the
408 // runtime types are not compatible, it could cause runtime crashes when the resource is resolved.
409
410 target_map_.insert(std::make_pair(target_resource, TargetValue{data_type, data_value}));
411
Ryan Mitchell5035d662020-01-22 13:19:41 -0800412 if (rewrite_overlay_reference && IsReference(data_type)) {
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700413 overlay_map_.insert(std::make_pair(data_value, target_resource));
414 }
415
416 return Result<Unit>({});
417}
418
419void ResourceMapping::RemoveMapping(ResourceId target_resource) {
420 auto target_iter = target_map_.find(target_resource);
421 if (target_iter == target_map_.end()) {
422 return;
423 }
424
425 const TargetValue value = target_iter->second;
426 target_map_.erase(target_iter);
427
Ryan Mitchell5035d662020-01-22 13:19:41 -0800428 if (!IsReference(value.data_type)) {
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700429 return;
430 }
431
432 auto overlay_iter = overlay_map_.equal_range(value.data_value);
433 for (auto i = overlay_iter.first; i != overlay_iter.second; ++i) {
434 if (i->second == target_resource) {
435 overlay_map_.erase(i);
436 return;
437 }
438 }
439}
440
441} // namespace android::idmap2