blob: 229628c7dd8b21ad6aded76a97640f45e762fab5 [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
36#define EXTRACT_PACKAGE(resid) ((0xff000000 & (resid)) >> 24)
37
38std::string ConcatPolicies(const std::vector<std::string>& policies) {
39 std::string message;
40 for (const std::string& policy : policies) {
41 if (!message.empty()) {
42 message.append("|");
43 }
44 message.append(policy);
45 }
46
47 return message;
48}
49
50Result<Unit> CheckOverlayable(const LoadedPackage& target_package,
51 const OverlayManifestInfo& overlay_info,
52 const PolicyBitmask& fulfilled_policies,
53 const ResourceId& target_resource) {
54 static constexpr const PolicyBitmask sDefaultPolicies =
55 PolicyFlags::POLICY_ODM_PARTITION | PolicyFlags::POLICY_OEM_PARTITION |
56 PolicyFlags::POLICY_SYSTEM_PARTITION | PolicyFlags::POLICY_VENDOR_PARTITION |
57 PolicyFlags::POLICY_PRODUCT_PARTITION | PolicyFlags::POLICY_SIGNATURE;
58
59 // If the resource does not have an overlayable definition, allow the resource to be overlaid if
60 // the overlay is preinstalled or signed with the same signature as the target.
61 if (!target_package.DefinesOverlayable()) {
62 return (sDefaultPolicies & fulfilled_policies) != 0
63 ? Result<Unit>({})
64 : Error(
65 "overlay must be preinstalled or signed with the same signature as the "
66 "target");
67 }
68
69 const OverlayableInfo* overlayable_info = target_package.GetOverlayableInfo(target_resource);
70 if (overlayable_info == nullptr) {
71 // Do not allow non-overlayable resources to be overlaid.
72 return Error("target resource has no overlayable declaration");
73 }
74
75 if (overlay_info.target_name != overlayable_info->name) {
76 // If the overlay supplies a target overlayable name, the resource must belong to the
77 // overlayable defined with the specified name to be overlaid.
78 return Error(R"(<overlay> android:targetName "%s" does not match overlayable name "%s")",
79 overlay_info.target_name.c_str(), overlayable_info->name.c_str());
80 }
81
82 // Enforce policy restrictions if the resource is declared as overlayable.
83 if ((overlayable_info->policy_flags & fulfilled_policies) == 0) {
84 return Error(R"(overlay with policies "%s" does not fulfill any overlayable policies "%s")",
85 ConcatPolicies(BitmaskToPolicies(fulfilled_policies)).c_str(),
86 ConcatPolicies(BitmaskToPolicies(overlayable_info->policy_flags)).c_str());
87 }
88
89 return Result<Unit>({});
90}
91
92// TODO(martenkongstad): scan for package name instead of assuming package at index 0
93//
94// idmap version 0x01 naively assumes that the package to use is always the first ResTable_package
95// in the resources.arsc blob. In most cases, there is only a single ResTable_package anyway, so
96// this assumption tends to work out. That said, the correct thing to do is to scan
97// resources.arsc for a package with a given name as read from the package manifest instead of
98// relying on a hard-coded index. This however requires storing the package name in the idmap
99// header, which in turn requires incrementing the idmap version. Because the initial version of
100// idmap2 is compatible with idmap, this will have to wait for now.
101const LoadedPackage* GetPackageAtIndex0(const LoadedArsc& loaded_arsc) {
102 const std::vector<std::unique_ptr<const LoadedPackage>>& packages = loaded_arsc.GetPackages();
103 if (packages.empty()) {
104 return nullptr;
105 }
106 int id = packages[0]->GetPackageId();
107 return loaded_arsc.GetPackageById(id);
108}
109
110Result<std::unique_ptr<Asset>> OpenNonAssetFromResource(const ResourceId& resource_id,
111 const AssetManager2& asset_manager) {
112 Res_value value{};
113 ResTable_config selected_config{};
114 uint32_t flags;
115 auto cookie =
116 asset_manager.GetResource(resource_id, /* may_be_bag */ false,
117 /* density_override */ 0U, &value, &selected_config, &flags);
118 if (cookie == kInvalidCookie) {
119 return Error("failed to find resource for id 0x%08x", resource_id);
120 }
121
122 if (value.dataType != Res_value::TYPE_STRING) {
123 return Error("resource for is 0x%08x is not a file", resource_id);
124 }
125
126 auto string_pool = asset_manager.GetStringPoolForCookie(cookie);
127 size_t len;
128 auto file_path16 = string_pool->stringAt(value.data, &len);
129 if (file_path16 == nullptr) {
130 return Error("failed to find string for index %d", value.data);
131 }
132
133 // Load the overlay resource mappings from the file specified using android:resourcesMap.
134 auto file_path = String8(String16(file_path16));
135 auto asset = asset_manager.OpenNonAsset(file_path.c_str(), Asset::AccessMode::ACCESS_BUFFER);
136 if (asset == nullptr) {
137 return Error("file \"%s\" not found", file_path.c_str());
138 }
139
140 return asset;
141}
142
143} // namespace
144
145Result<ResourceMapping> ResourceMapping::CreateResourceMapping(const AssetManager2* target_am,
146 const LoadedPackage* target_package,
147 const LoadedPackage* overlay_package,
148 size_t string_pool_offset,
Mårten Kongstadd7e8a532019-10-11 08:32:04 +0200149 const XmlParser& overlay_parser,
150 LogInfo& log_info) {
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700151 ResourceMapping resource_mapping;
152 auto root_it = overlay_parser.tree_iterator();
153 if (root_it->event() != XmlParser::Event::START_TAG || root_it->name() != "overlay") {
154 return Error("root element is not <overlay> tag");
155 }
156
157 const uint8_t overlay_package_id = overlay_package->GetPackageId();
158 auto overlay_it_end = root_it.end();
159 for (auto overlay_it = root_it.begin(); overlay_it != overlay_it_end; ++overlay_it) {
160 if (overlay_it->event() == XmlParser::Event::BAD_DOCUMENT) {
161 return Error("failed to parse overlay xml document");
162 }
163
164 if (overlay_it->event() != XmlParser::Event::START_TAG) {
165 continue;
166 }
167
168 if (overlay_it->name() != "item") {
169 return Error("unexpected tag <%s> in <overlay>", overlay_it->name().c_str());
170 }
171
172 Result<std::string> target_resource = overlay_it->GetAttributeStringValue("target");
173 if (!target_resource) {
174 return Error(R"(<item> tag missing expected attribute "target")");
175 }
176
177 Result<android::Res_value> overlay_resource = overlay_it->GetAttributeValue("value");
178 if (!overlay_resource) {
179 return Error(R"(<item> tag missing expected attribute "value")");
180 }
181
182 ResourceId target_id =
183 target_am->GetResourceId(*target_resource, "", target_package->GetPackageName());
184 if (target_id == 0U) {
Mårten Kongstadd7e8a532019-10-11 08:32:04 +0200185 log_info.Warning(LogMessage() << "failed to find resource \"" << *target_resource
186 << "\" in target resources");
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700187 continue;
188 }
189
190 if (overlay_resource->dataType == Res_value::TYPE_STRING) {
191 overlay_resource->data += string_pool_offset;
192 }
193
194 // Only rewrite resources defined within the overlay package to their corresponding target
195 // resource ids at runtime.
196 bool rewrite_overlay_reference =
Ryan Mitchelle753ffe2019-09-23 09:47:02 -0700197 (overlay_resource->dataType == Res_value::TYPE_REFERENCE ||
198 overlay_resource->dataType == Res_value::TYPE_DYNAMIC_REFERENCE)
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700199 ? overlay_package_id == EXTRACT_PACKAGE(overlay_resource->data)
200 : false;
Mårten Kongstadd7e8a532019-10-11 08:32:04 +0200201
Ryan Mitchelle753ffe2019-09-23 09:47:02 -0700202 if (rewrite_overlay_reference) {
203 overlay_resource->dataType = Res_value::TYPE_DYNAMIC_REFERENCE;
204 }
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700205
206 resource_mapping.AddMapping(target_id, overlay_resource->dataType, overlay_resource->data,
207 rewrite_overlay_reference);
208 }
209
210 return resource_mapping;
211}
212
213Result<ResourceMapping> ResourceMapping::CreateResourceMappingLegacy(
214 const AssetManager2* target_am, const AssetManager2* overlay_am,
215 const LoadedPackage* target_package, const LoadedPackage* overlay_package) {
216 ResourceMapping resource_mapping;
217 const auto end = overlay_package->end();
218 for (auto iter = overlay_package->begin(); iter != end; ++iter) {
219 const ResourceId overlay_resid = *iter;
220 Result<std::string> name = utils::ResToTypeEntryName(*overlay_am, overlay_resid);
221 if (!name) {
222 continue;
223 }
224
225 // Find the resource with the same type and entry name within the target package.
226 const std::string full_name =
227 base::StringPrintf("%s:%s", target_package->GetPackageName().c_str(), name->c_str());
228 const ResourceId target_resource = target_am->GetResourceId(full_name);
229 if (target_resource == 0U) {
230 continue;
231 }
232
233 resource_mapping.AddMapping(target_resource, Res_value::TYPE_REFERENCE, overlay_resid,
Ryan Mitchelle753ffe2019-09-23 09:47:02 -0700234 /* rewrite_overlay_reference */ false);
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700235 }
236
237 return resource_mapping;
238}
239
240void ResourceMapping::FilterOverlayableResources(const AssetManager2* target_am,
241 const LoadedPackage* target_package,
242 const LoadedPackage* overlay_package,
243 const OverlayManifestInfo& overlay_info,
Mårten Kongstadd7e8a532019-10-11 08:32:04 +0200244 const PolicyBitmask& fulfilled_policies,
245 LogInfo& log_info) {
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700246 std::set<ResourceId> remove_ids;
247 for (const auto& target_map : target_map_) {
248 const ResourceId target_resid = target_map.first;
249 Result<Unit> success =
250 CheckOverlayable(*target_package, overlay_info, fulfilled_policies, target_resid);
251 if (success) {
252 continue;
253 }
254
255 // Attempting to overlay a resource that is not allowed to be overlaid is treated as a
256 // warning.
257 Result<std::string> name = utils::ResToTypeEntryName(*target_am, target_resid);
258 if (!name) {
259 name = StringPrintf("0x%08x", target_resid);
260 }
261
Mårten Kongstadd7e8a532019-10-11 08:32:04 +0200262 log_info.Warning(LogMessage() << "overlay \"" << overlay_package->GetPackageName()
263 << "\" is not allowed to overlay resource \"" << *name
264 << "\" in target: " << success.GetErrorMessage());
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700265
266 remove_ids.insert(target_resid);
267 }
268
269 for (const ResourceId target_resid : remove_ids) {
270 RemoveMapping(target_resid);
271 }
272}
273
274Result<ResourceMapping> ResourceMapping::FromApkAssets(const ApkAssets& target_apk_assets,
275 const ApkAssets& overlay_apk_assets,
276 const OverlayManifestInfo& overlay_info,
277 const PolicyBitmask& fulfilled_policies,
Mårten Kongstadd7e8a532019-10-11 08:32:04 +0200278 bool enforce_overlayable,
279 LogInfo& log_info) {
280 if (enforce_overlayable) {
281 log_info.Info(LogMessage() << "fulfilled_policies="
282 << ConcatPolicies(BitmaskToPolicies(fulfilled_policies))
283 << " enforce_overlayable="
284 << (enforce_overlayable ? "true" : "false"));
285 }
286
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700287 AssetManager2 target_asset_manager;
288 if (!target_asset_manager.SetApkAssets({&target_apk_assets}, true /* invalidate_caches */,
289 false /* filter_incompatible_configs*/)) {
290 return Error("failed to create target asset manager");
291 }
292
293 AssetManager2 overlay_asset_manager;
294 if (!overlay_asset_manager.SetApkAssets({&overlay_apk_assets}, true /* invalidate_caches */,
295 false /* filter_incompatible_configs */)) {
296 return Error("failed to create overlay asset manager");
297 }
298
299 const LoadedArsc* target_arsc = target_apk_assets.GetLoadedArsc();
300 if (target_arsc == nullptr) {
301 return Error("failed to load target resources.arsc");
302 }
303
304 const LoadedArsc* overlay_arsc = overlay_apk_assets.GetLoadedArsc();
305 if (overlay_arsc == nullptr) {
306 return Error("failed to load overlay resources.arsc");
307 }
308
309 const LoadedPackage* target_pkg = GetPackageAtIndex0(*target_arsc);
310 if (target_pkg == nullptr) {
311 return Error("failed to load target package from resources.arsc");
312 }
313
314 const LoadedPackage* overlay_pkg = GetPackageAtIndex0(*overlay_arsc);
315 if (overlay_pkg == nullptr) {
316 return Error("failed to load overlay package from resources.arsc");
317 }
318
319 size_t string_pool_data_length = 0U;
320 size_t string_pool_offset = 0U;
321 std::unique_ptr<uint8_t[]> string_pool_data;
322 Result<ResourceMapping> resource_mapping = {{}};
323 if (overlay_info.resource_mapping != 0U) {
324 // Load the overlay resource mappings from the file specified using android:resourcesMap.
325 auto asset = OpenNonAssetFromResource(overlay_info.resource_mapping, overlay_asset_manager);
326 if (!asset) {
327 return Error("failed opening xml for android:resourcesMap: %s",
328 asset.GetErrorMessage().c_str());
329 }
330
331 auto parser =
332 XmlParser::Create((*asset)->getBuffer(true /* wordAligned*/), (*asset)->getLength());
333 if (!parser) {
334 return Error("failed opening ResXMLTree");
335 }
336
337 // Copy the xml string pool data before the parse goes out of scope.
338 auto& string_pool = (*parser)->get_strings();
339 string_pool_data_length = string_pool.bytes();
340 string_pool_data.reset(new uint8_t[string_pool_data_length]);
341 memcpy(string_pool_data.get(), string_pool.data(), string_pool_data_length);
342
343 // Offset string indices by the size of the overlay resource table string pool.
344 string_pool_offset = overlay_arsc->GetStringPool()->size();
345
346 resource_mapping = CreateResourceMapping(&target_asset_manager, target_pkg, overlay_pkg,
Mårten Kongstadd7e8a532019-10-11 08:32:04 +0200347 string_pool_offset, *(*parser), log_info);
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700348 } else {
349 // If no file is specified using android:resourcesMap, it is assumed that the overlay only
350 // defines resources intended to override target resources of the same type and name.
351 resource_mapping = CreateResourceMappingLegacy(&target_asset_manager, &overlay_asset_manager,
352 target_pkg, overlay_pkg);
353 }
354
355 if (!resource_mapping) {
356 return resource_mapping.GetError();
357 }
358
359 if (enforce_overlayable) {
360 // Filter out resources the overlay is not allowed to override.
361 (*resource_mapping)
362 .FilterOverlayableResources(&target_asset_manager, target_pkg, overlay_pkg, overlay_info,
Mårten Kongstadd7e8a532019-10-11 08:32:04 +0200363 fulfilled_policies, log_info);
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700364 }
365
366 resource_mapping->target_package_id_ = target_pkg->GetPackageId();
367 resource_mapping->overlay_package_id_ = overlay_pkg->GetPackageId();
368 resource_mapping->string_pool_offset_ = string_pool_offset;
369 resource_mapping->string_pool_data_ = std::move(string_pool_data);
370 resource_mapping->string_pool_data_length_ = string_pool_data_length;
371 return std::move(*resource_mapping);
372}
373
374OverlayResourceMap ResourceMapping::GetOverlayToTargetMap() const {
375 // An overlay resource can override multiple target resources at once. Rewrite the overlay
376 // resource as the first target resource it overrides.
377 OverlayResourceMap map;
378 for (const auto& mappings : overlay_map_) {
379 map.insert(std::make_pair(mappings.first, mappings.second));
380 }
381 return map;
382}
383
384Result<Unit> ResourceMapping::AddMapping(ResourceId target_resource,
385 TargetValue::DataType data_type,
386 TargetValue::DataValue data_value,
387 bool rewrite_overlay_reference) {
388 if (target_map_.find(target_resource) != target_map_.end()) {
389 return Error(R"(target resource id "0x%08x" mapped to multiple values)", target_resource);
390 }
391
392 // TODO(141485591): Ensure that the overlay type is compatible with the target type. If the
393 // runtime types are not compatible, it could cause runtime crashes when the resource is resolved.
394
395 target_map_.insert(std::make_pair(target_resource, TargetValue{data_type, data_value}));
396
Ryan Mitchelle753ffe2019-09-23 09:47:02 -0700397 if (rewrite_overlay_reference &&
398 (data_type == Res_value::TYPE_REFERENCE || data_type == Res_value::TYPE_DYNAMIC_REFERENCE)) {
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700399 overlay_map_.insert(std::make_pair(data_value, target_resource));
400 }
401
402 return Result<Unit>({});
403}
404
405void ResourceMapping::RemoveMapping(ResourceId target_resource) {
406 auto target_iter = target_map_.find(target_resource);
407 if (target_iter == target_map_.end()) {
408 return;
409 }
410
411 const TargetValue value = target_iter->second;
412 target_map_.erase(target_iter);
413
Ryan Mitchelle753ffe2019-09-23 09:47:02 -0700414 if (value.data_type != Res_value::TYPE_REFERENCE &&
415 value.data_type != Res_value::TYPE_DYNAMIC_REFERENCE) {
Ryan Mitchell9e4f52b2019-09-19 12:15:52 -0700416 return;
417 }
418
419 auto overlay_iter = overlay_map_.equal_range(value.data_value);
420 for (auto i = overlay_iter.first; i != overlay_iter.second; ++i) {
421 if (i->second == target_resource) {
422 overlay_map_.erase(i);
423 return;
424 }
425 }
426}
427
428} // namespace android::idmap2