blob: 407478945151c46d582e259f2bceefe121d1ea1c [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"
27#include "idmap2/ResourceUtils.h"
28
29using android::base::StringPrintf;
30using android::idmap2::utils::ResToTypeEntryName;
31
32namespace android::idmap2 {
33
34namespace {
35
Ryan Mitchellee4a5642019-10-16 08:32:55 -070036#define REWRITE_PACKAGE(resid, package_id) \
37 (((resid)&0x00ffffffU) | (((uint32_t)(package_id)) << 24U))
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -070038#define EXTRACT_PACKAGE(resid) ((0xff000000 & (resid)) >> 24)
39
40std::string ConcatPolicies(const std::vector<std::string>& policies) {
41 std::string message;
42 for (const std::string& policy : policies) {
43 if (!message.empty()) {
44 message.append("|");
45 }
46 message.append(policy);
47 }
48
49 return message;
50}
51
52Result<Unit> CheckOverlayable(const LoadedPackage& target_package,
53 const OverlayManifestInfo& overlay_info,
54 const PolicyBitmask& fulfilled_policies,
55 const ResourceId& target_resource) {
56 static constexpr const PolicyBitmask sDefaultPolicies =
57 PolicyFlags::POLICY_ODM_PARTITION | PolicyFlags::POLICY_OEM_PARTITION |
58 PolicyFlags::POLICY_SYSTEM_PARTITION | PolicyFlags::POLICY_VENDOR_PARTITION |
59 PolicyFlags::POLICY_PRODUCT_PARTITION | PolicyFlags::POLICY_SIGNATURE;
60
61 // If the resource does not have an overlayable definition, allow the resource to be overlaid if
62 // the overlay is preinstalled or signed with the same signature as the target.
63 if (!target_package.DefinesOverlayable()) {
64 return (sDefaultPolicies & fulfilled_policies) != 0
65 ? Result<Unit>({})
66 : Error(
67 "overlay must be preinstalled or signed with the same signature as the "
68 "target");
69 }
70
71 const OverlayableInfo* overlayable_info = target_package.GetOverlayableInfo(target_resource);
72 if (overlayable_info == nullptr) {
73 // Do not allow non-overlayable resources to be overlaid.
74 return Error("target resource has no overlayable declaration");
75 }
76
77 if (overlay_info.target_name != overlayable_info->name) {
78 // If the overlay supplies a target overlayable name, the resource must belong to the
79 // overlayable defined with the specified name to be overlaid.
80 return Error(R"(<overlay> android:targetName "%s" does not match overlayable name "%s")",
81 overlay_info.target_name.c_str(), overlayable_info->name.c_str());
82 }
83
84 // Enforce policy restrictions if the resource is declared as overlayable.
85 if ((overlayable_info->policy_flags & fulfilled_policies) == 0) {
86 return Error(R"(overlay with policies "%s" does not fulfill any overlayable policies "%s")",
87 ConcatPolicies(BitmaskToPolicies(fulfilled_policies)).c_str(),
88 ConcatPolicies(BitmaskToPolicies(overlayable_info->policy_flags)).c_str());
89 }
90
91 return Result<Unit>({});
92}
93
94// TODO(martenkongstad): scan for package name instead of assuming package at index 0
95//
96// idmap version 0x01 naively assumes that the package to use is always the first ResTable_package
97// in the resources.arsc blob. In most cases, there is only a single ResTable_package anyway, so
98// this assumption tends to work out. That said, the correct thing to do is to scan
99// resources.arsc for a package with a given name as read from the package manifest instead of
100// relying on a hard-coded index. This however requires storing the package name in the idmap
101// header, which in turn requires incrementing the idmap version. Because the initial version of
102// idmap2 is compatible with idmap, this will have to wait for now.
103const LoadedPackage* GetPackageAtIndex0(const LoadedArsc& loaded_arsc) {
104 const std::vector<std::unique_ptr<const LoadedPackage>>& packages = loaded_arsc.GetPackages();
105 if (packages.empty()) {
106 return nullptr;
107 }
108 int id = packages[0]->GetPackageId();
109 return loaded_arsc.GetPackageById(id);
110}
111
112Result<std::unique_ptr<Asset>> OpenNonAssetFromResource(const ResourceId& resource_id,
113 const AssetManager2& asset_manager) {
114 Res_value value{};
115 ResTable_config selected_config{};
116 uint32_t flags;
117 auto cookie =
118 asset_manager.GetResource(resource_id, /* may_be_bag */ false,
119 /* density_override */ 0U, &value, &selected_config, &flags);
120 if (cookie == kInvalidCookie) {
121 return Error("failed to find resource for id 0x%08x", resource_id);
122 }
123
124 if (value.dataType != Res_value::TYPE_STRING) {
125 return Error("resource for is 0x%08x is not a file", resource_id);
126 }
127
128 auto string_pool = asset_manager.GetStringPoolForCookie(cookie);
129 size_t len;
130 auto file_path16 = string_pool->stringAt(value.data, &len);
131 if (file_path16 == nullptr) {
132 return Error("failed to find string for index %d", value.data);
133 }
134
135 // Load the overlay resource mappings from the file specified using android:resourcesMap.
136 auto file_path = String8(String16(file_path16));
137 auto asset = asset_manager.OpenNonAsset(file_path.c_str(), Asset::AccessMode::ACCESS_BUFFER);
138 if (asset == nullptr) {
139 return Error("file \"%s\" not found", file_path.c_str());
140 }
141
142 return asset;
143}
144
145} // namespace
146
147Result<ResourceMapping> ResourceMapping::CreateResourceMapping(const AssetManager2* target_am,
148 const LoadedPackage* target_package,
149 const LoadedPackage* overlay_package,
150 size_t string_pool_offset,
Mårten Kongstadd7e8a532019-10-11 08:32:04 +0200151 const XmlParser& overlay_parser,
152 LogInfo& log_info) {
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700153 ResourceMapping resource_mapping;
154 auto root_it = overlay_parser.tree_iterator();
155 if (root_it->event() != XmlParser::Event::START_TAG || root_it->name() != "overlay") {
156 return Error("root element is not <overlay> tag");
157 }
158
Ryan Mitchellee4a5642019-10-16 08:32:55 -0700159 const uint8_t target_package_id = target_package->GetPackageId();
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700160 const uint8_t overlay_package_id = overlay_package->GetPackageId();
161 auto overlay_it_end = root_it.end();
162 for (auto overlay_it = root_it.begin(); overlay_it != overlay_it_end; ++overlay_it) {
163 if (overlay_it->event() == XmlParser::Event::BAD_DOCUMENT) {
164 return Error("failed to parse overlay xml document");
165 }
166
167 if (overlay_it->event() != XmlParser::Event::START_TAG) {
168 continue;
169 }
170
171 if (overlay_it->name() != "item") {
172 return Error("unexpected tag <%s> in <overlay>", overlay_it->name().c_str());
173 }
174
175 Result<std::string> target_resource = overlay_it->GetAttributeStringValue("target");
176 if (!target_resource) {
177 return Error(R"(<item> tag missing expected attribute "target")");
178 }
179
180 Result<android::Res_value> overlay_resource = overlay_it->GetAttributeValue("value");
181 if (!overlay_resource) {
182 return Error(R"(<item> tag missing expected attribute "value")");
183 }
184
185 ResourceId target_id =
186 target_am->GetResourceId(*target_resource, "", target_package->GetPackageName());
187 if (target_id == 0U) {
Mårten Kongstadd7e8a532019-10-11 08:32:04 +0200188 log_info.Warning(LogMessage() << "failed to find resource \"" << *target_resource
189 << "\" in target resources");
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700190 continue;
191 }
192
Ryan Mitchellee4a5642019-10-16 08:32:55 -0700193 // Retrieve the compile-time resource id of the target resource.
194 target_id = REWRITE_PACKAGE(target_id, target_package_id);
195
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700196 if (overlay_resource->dataType == Res_value::TYPE_STRING) {
197 overlay_resource->data += string_pool_offset;
198 }
199
200 // Only rewrite resources defined within the overlay package to their corresponding target
201 // resource ids at runtime.
202 bool rewrite_overlay_reference =
Ryan Mitchelle753ffe2019-09-23 09:47:02 -0700203 (overlay_resource->dataType == Res_value::TYPE_REFERENCE ||
204 overlay_resource->dataType == Res_value::TYPE_DYNAMIC_REFERENCE)
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700205 ? overlay_package_id == EXTRACT_PACKAGE(overlay_resource->data)
206 : false;
Mårten Kongstadd7e8a532019-10-11 08:32:04 +0200207
Ryan Mitchelle753ffe2019-09-23 09:47:02 -0700208 if (rewrite_overlay_reference) {
209 overlay_resource->dataType = Res_value::TYPE_DYNAMIC_REFERENCE;
210 }
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700211
212 resource_mapping.AddMapping(target_id, overlay_resource->dataType, overlay_resource->data,
213 rewrite_overlay_reference);
214 }
215
216 return resource_mapping;
217}
218
219Result<ResourceMapping> ResourceMapping::CreateResourceMappingLegacy(
220 const AssetManager2* target_am, const AssetManager2* overlay_am,
221 const LoadedPackage* target_package, const LoadedPackage* overlay_package) {
222 ResourceMapping resource_mapping;
Ryan Mitchellee4a5642019-10-16 08:32:55 -0700223 const uint8_t target_package_id = target_package->GetPackageId();
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700224 const auto end = overlay_package->end();
225 for (auto iter = overlay_package->begin(); iter != end; ++iter) {
226 const ResourceId overlay_resid = *iter;
227 Result<std::string> name = utils::ResToTypeEntryName(*overlay_am, overlay_resid);
228 if (!name) {
229 continue;
230 }
231
232 // Find the resource with the same type and entry name within the target package.
233 const std::string full_name =
234 base::StringPrintf("%s:%s", target_package->GetPackageName().c_str(), name->c_str());
Ryan Mitchellee4a5642019-10-16 08:32:55 -0700235 ResourceId target_resource = target_am->GetResourceId(full_name);
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700236 if (target_resource == 0U) {
237 continue;
238 }
239
Ryan Mitchellee4a5642019-10-16 08:32:55 -0700240 // Retrieve the compile-time resource id of the target resource.
241 target_resource = REWRITE_PACKAGE(target_resource, target_package_id);
242
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700243 resource_mapping.AddMapping(target_resource, Res_value::TYPE_REFERENCE, overlay_resid,
Ryan Mitchelle753ffe2019-09-23 09:47:02 -0700244 /* rewrite_overlay_reference */ false);
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700245 }
246
247 return resource_mapping;
248}
249
250void ResourceMapping::FilterOverlayableResources(const AssetManager2* target_am,
251 const LoadedPackage* target_package,
252 const LoadedPackage* overlay_package,
253 const OverlayManifestInfo& overlay_info,
Mårten Kongstadd7e8a532019-10-11 08:32:04 +0200254 const PolicyBitmask& fulfilled_policies,
255 LogInfo& log_info) {
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700256 std::set<ResourceId> remove_ids;
257 for (const auto& target_map : target_map_) {
258 const ResourceId target_resid = target_map.first;
259 Result<Unit> success =
260 CheckOverlayable(*target_package, overlay_info, fulfilled_policies, target_resid);
261 if (success) {
262 continue;
263 }
264
265 // Attempting to overlay a resource that is not allowed to be overlaid is treated as a
266 // warning.
267 Result<std::string> name = utils::ResToTypeEntryName(*target_am, target_resid);
268 if (!name) {
269 name = StringPrintf("0x%08x", target_resid);
270 }
271
Mårten Kongstadd7e8a532019-10-11 08:32:04 +0200272 log_info.Warning(LogMessage() << "overlay \"" << overlay_package->GetPackageName()
273 << "\" is not allowed to overlay resource \"" << *name
274 << "\" in target: " << success.GetErrorMessage());
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700275
276 remove_ids.insert(target_resid);
277 }
278
279 for (const ResourceId target_resid : remove_ids) {
280 RemoveMapping(target_resid);
281 }
282}
283
284Result<ResourceMapping> ResourceMapping::FromApkAssets(const ApkAssets& target_apk_assets,
285 const ApkAssets& overlay_apk_assets,
286 const OverlayManifestInfo& overlay_info,
287 const PolicyBitmask& fulfilled_policies,
Mårten Kongstadd7e8a532019-10-11 08:32:04 +0200288 bool enforce_overlayable,
289 LogInfo& log_info) {
290 if (enforce_overlayable) {
291 log_info.Info(LogMessage() << "fulfilled_policies="
292 << ConcatPolicies(BitmaskToPolicies(fulfilled_policies))
293 << " enforce_overlayable="
294 << (enforce_overlayable ? "true" : "false"));
295 }
296
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) {
334 // Load the overlay resource mappings from the file specified using android:resourcesMap.
335 auto asset = OpenNonAssetFromResource(overlay_info.resource_mapping, overlay_asset_manager);
336 if (!asset) {
337 return Error("failed opening xml for android:resourcesMap: %s",
338 asset.GetErrorMessage().c_str());
339 }
340
341 auto parser =
342 XmlParser::Create((*asset)->getBuffer(true /* wordAligned*/), (*asset)->getLength());
343 if (!parser) {
344 return Error("failed opening ResXMLTree");
345 }
346
347 // Copy the xml string pool data before the parse goes out of scope.
348 auto& string_pool = (*parser)->get_strings();
349 string_pool_data_length = string_pool.bytes();
350 string_pool_data.reset(new uint8_t[string_pool_data_length]);
351 memcpy(string_pool_data.get(), string_pool.data(), string_pool_data_length);
352
353 // Offset string indices by the size of the overlay resource table string pool.
354 string_pool_offset = overlay_arsc->GetStringPool()->size();
355
356 resource_mapping = CreateResourceMapping(&target_asset_manager, target_pkg, overlay_pkg,
Mårten Kongstadd7e8a532019-10-11 08:32:04 +0200357 string_pool_offset, *(*parser), log_info);
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700358 } else {
359 // If no file is specified using android:resourcesMap, it is assumed that the overlay only
360 // defines resources intended to override target resources of the same type and name.
361 resource_mapping = CreateResourceMappingLegacy(&target_asset_manager, &overlay_asset_manager,
362 target_pkg, overlay_pkg);
363 }
364
365 if (!resource_mapping) {
366 return resource_mapping.GetError();
367 }
368
369 if (enforce_overlayable) {
370 // Filter out resources the overlay is not allowed to override.
371 (*resource_mapping)
372 .FilterOverlayableResources(&target_asset_manager, target_pkg, overlay_pkg, overlay_info,
Mårten Kongstadd7e8a532019-10-11 08:32:04 +0200373 fulfilled_policies, log_info);
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700374 }
375
376 resource_mapping->target_package_id_ = target_pkg->GetPackageId();
377 resource_mapping->overlay_package_id_ = overlay_pkg->GetPackageId();
378 resource_mapping->string_pool_offset_ = string_pool_offset;
379 resource_mapping->string_pool_data_ = std::move(string_pool_data);
380 resource_mapping->string_pool_data_length_ = string_pool_data_length;
381 return std::move(*resource_mapping);
382}
383
384OverlayResourceMap ResourceMapping::GetOverlayToTargetMap() const {
385 // An overlay resource can override multiple target resources at once. Rewrite the overlay
386 // resource as the first target resource it overrides.
387 OverlayResourceMap map;
388 for (const auto& mappings : overlay_map_) {
389 map.insert(std::make_pair(mappings.first, mappings.second));
390 }
391 return map;
392}
393
394Result<Unit> ResourceMapping::AddMapping(ResourceId target_resource,
395 TargetValue::DataType data_type,
396 TargetValue::DataValue data_value,
397 bool rewrite_overlay_reference) {
398 if (target_map_.find(target_resource) != target_map_.end()) {
399 return Error(R"(target resource id "0x%08x" mapped to multiple values)", target_resource);
400 }
401
402 // TODO(141485591): Ensure that the overlay type is compatible with the target type. If the
403 // runtime types are not compatible, it could cause runtime crashes when the resource is resolved.
404
405 target_map_.insert(std::make_pair(target_resource, TargetValue{data_type, data_value}));
406
Ryan Mitchelle753ffe2019-09-23 09:47:02 -0700407 if (rewrite_overlay_reference &&
408 (data_type == Res_value::TYPE_REFERENCE || data_type == Res_value::TYPE_DYNAMIC_REFERENCE)) {
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700409 overlay_map_.insert(std::make_pair(data_value, target_resource));
410 }
411
412 return Result<Unit>({});
413}
414
415void ResourceMapping::RemoveMapping(ResourceId target_resource) {
416 auto target_iter = target_map_.find(target_resource);
417 if (target_iter == target_map_.end()) {
418 return;
419 }
420
421 const TargetValue value = target_iter->second;
422 target_map_.erase(target_iter);
423
Ryan Mitchelle753ffe2019-09-23 09:47:02 -0700424 if (value.data_type != Res_value::TYPE_REFERENCE &&
425 value.data_type != Res_value::TYPE_DYNAMIC_REFERENCE) {
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700426 return;
427 }
428
429 auto overlay_iter = overlay_map_.equal_range(value.data_value);
430 for (auto i = overlay_iter.first; i != overlay_iter.second; ++i) {
431 if (i->second == target_resource) {
432 overlay_map_.erase(i);
433 return;
434 }
435 }
436}
437
438} // namespace android::idmap2