Ryan Mitchell | 9e4f52b | 2019-09-19 12:15:52 -0700 | [diff] [blame] | 1 | /* |
| 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 | |
| 29 | using android::base::StringPrintf; |
| 30 | using android::idmap2::utils::ResToTypeEntryName; |
| 31 | |
| 32 | namespace android::idmap2 { |
| 33 | |
| 34 | namespace { |
| 35 | |
| 36 | #define EXTRACT_PACKAGE(resid) ((0xff000000 & (resid)) >> 24) |
| 37 | |
| 38 | std::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 | |
| 50 | Result<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. |
| 101 | const 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 | |
| 110 | Result<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 | |
| 145 | Result<ResourceMapping> ResourceMapping::CreateResourceMapping(const AssetManager2* target_am, |
| 146 | const LoadedPackage* target_package, |
| 147 | const LoadedPackage* overlay_package, |
| 148 | size_t string_pool_offset, |
| 149 | const XmlParser& overlay_parser) { |
| 150 | ResourceMapping resource_mapping; |
| 151 | auto root_it = overlay_parser.tree_iterator(); |
| 152 | if (root_it->event() != XmlParser::Event::START_TAG || root_it->name() != "overlay") { |
| 153 | return Error("root element is not <overlay> tag"); |
| 154 | } |
| 155 | |
| 156 | const uint8_t overlay_package_id = overlay_package->GetPackageId(); |
| 157 | auto overlay_it_end = root_it.end(); |
| 158 | for (auto overlay_it = root_it.begin(); overlay_it != overlay_it_end; ++overlay_it) { |
| 159 | if (overlay_it->event() == XmlParser::Event::BAD_DOCUMENT) { |
| 160 | return Error("failed to parse overlay xml document"); |
| 161 | } |
| 162 | |
| 163 | if (overlay_it->event() != XmlParser::Event::START_TAG) { |
| 164 | continue; |
| 165 | } |
| 166 | |
| 167 | if (overlay_it->name() != "item") { |
| 168 | return Error("unexpected tag <%s> in <overlay>", overlay_it->name().c_str()); |
| 169 | } |
| 170 | |
| 171 | Result<std::string> target_resource = overlay_it->GetAttributeStringValue("target"); |
| 172 | if (!target_resource) { |
| 173 | return Error(R"(<item> tag missing expected attribute "target")"); |
| 174 | } |
| 175 | |
| 176 | Result<android::Res_value> overlay_resource = overlay_it->GetAttributeValue("value"); |
| 177 | if (!overlay_resource) { |
| 178 | return Error(R"(<item> tag missing expected attribute "value")"); |
| 179 | } |
| 180 | |
| 181 | ResourceId target_id = |
| 182 | target_am->GetResourceId(*target_resource, "", target_package->GetPackageName()); |
| 183 | if (target_id == 0U) { |
| 184 | LOG(WARNING) << "failed to find resource \"" << *target_resource << "\" in target resources"; |
| 185 | continue; |
| 186 | } |
| 187 | |
| 188 | if (overlay_resource->dataType == Res_value::TYPE_STRING) { |
| 189 | overlay_resource->data += string_pool_offset; |
| 190 | } |
| 191 | |
| 192 | // Only rewrite resources defined within the overlay package to their corresponding target |
| 193 | // resource ids at runtime. |
| 194 | bool rewrite_overlay_reference = |
| 195 | (overlay_resource->dataType == Res_value::TYPE_REFERENCE) |
| 196 | ? overlay_package_id == EXTRACT_PACKAGE(overlay_resource->data) |
| 197 | : false; |
| 198 | |
| 199 | resource_mapping.AddMapping(target_id, overlay_resource->dataType, overlay_resource->data, |
| 200 | rewrite_overlay_reference); |
| 201 | } |
| 202 | |
| 203 | return resource_mapping; |
| 204 | } |
| 205 | |
| 206 | Result<ResourceMapping> ResourceMapping::CreateResourceMappingLegacy( |
| 207 | const AssetManager2* target_am, const AssetManager2* overlay_am, |
| 208 | const LoadedPackage* target_package, const LoadedPackage* overlay_package) { |
| 209 | ResourceMapping resource_mapping; |
| 210 | const auto end = overlay_package->end(); |
| 211 | for (auto iter = overlay_package->begin(); iter != end; ++iter) { |
| 212 | const ResourceId overlay_resid = *iter; |
| 213 | Result<std::string> name = utils::ResToTypeEntryName(*overlay_am, overlay_resid); |
| 214 | if (!name) { |
| 215 | continue; |
| 216 | } |
| 217 | |
| 218 | // Find the resource with the same type and entry name within the target package. |
| 219 | const std::string full_name = |
| 220 | base::StringPrintf("%s:%s", target_package->GetPackageName().c_str(), name->c_str()); |
| 221 | const ResourceId target_resource = target_am->GetResourceId(full_name); |
| 222 | if (target_resource == 0U) { |
| 223 | continue; |
| 224 | } |
| 225 | |
| 226 | resource_mapping.AddMapping(target_resource, Res_value::TYPE_REFERENCE, overlay_resid, |
| 227 | /* rewrite_overlay_reference */ true); |
| 228 | } |
| 229 | |
| 230 | return resource_mapping; |
| 231 | } |
| 232 | |
| 233 | void ResourceMapping::FilterOverlayableResources(const AssetManager2* target_am, |
| 234 | const LoadedPackage* target_package, |
| 235 | const LoadedPackage* overlay_package, |
| 236 | const OverlayManifestInfo& overlay_info, |
| 237 | const PolicyBitmask& fulfilled_policies) { |
| 238 | std::set<ResourceId> remove_ids; |
| 239 | for (const auto& target_map : target_map_) { |
| 240 | const ResourceId target_resid = target_map.first; |
| 241 | Result<Unit> success = |
| 242 | CheckOverlayable(*target_package, overlay_info, fulfilled_policies, target_resid); |
| 243 | if (success) { |
| 244 | continue; |
| 245 | } |
| 246 | |
| 247 | // Attempting to overlay a resource that is not allowed to be overlaid is treated as a |
| 248 | // warning. |
| 249 | Result<std::string> name = utils::ResToTypeEntryName(*target_am, target_resid); |
| 250 | if (!name) { |
| 251 | name = StringPrintf("0x%08x", target_resid); |
| 252 | } |
| 253 | |
| 254 | LOG(WARNING) << "overlay \"" << overlay_package->GetPackageName() |
| 255 | << "\" is not allowed to overlay resource \"" << *name |
| 256 | << "\" in target: " << success.GetErrorMessage(); |
| 257 | |
| 258 | remove_ids.insert(target_resid); |
| 259 | } |
| 260 | |
| 261 | for (const ResourceId target_resid : remove_ids) { |
| 262 | RemoveMapping(target_resid); |
| 263 | } |
| 264 | } |
| 265 | |
| 266 | Result<ResourceMapping> ResourceMapping::FromApkAssets(const ApkAssets& target_apk_assets, |
| 267 | const ApkAssets& overlay_apk_assets, |
| 268 | const OverlayManifestInfo& overlay_info, |
| 269 | const PolicyBitmask& fulfilled_policies, |
| 270 | bool enforce_overlayable) { |
| 271 | AssetManager2 target_asset_manager; |
| 272 | if (!target_asset_manager.SetApkAssets({&target_apk_assets}, true /* invalidate_caches */, |
| 273 | false /* filter_incompatible_configs*/)) { |
| 274 | return Error("failed to create target asset manager"); |
| 275 | } |
| 276 | |
| 277 | AssetManager2 overlay_asset_manager; |
| 278 | if (!overlay_asset_manager.SetApkAssets({&overlay_apk_assets}, true /* invalidate_caches */, |
| 279 | false /* filter_incompatible_configs */)) { |
| 280 | return Error("failed to create overlay asset manager"); |
| 281 | } |
| 282 | |
| 283 | const LoadedArsc* target_arsc = target_apk_assets.GetLoadedArsc(); |
| 284 | if (target_arsc == nullptr) { |
| 285 | return Error("failed to load target resources.arsc"); |
| 286 | } |
| 287 | |
| 288 | const LoadedArsc* overlay_arsc = overlay_apk_assets.GetLoadedArsc(); |
| 289 | if (overlay_arsc == nullptr) { |
| 290 | return Error("failed to load overlay resources.arsc"); |
| 291 | } |
| 292 | |
| 293 | const LoadedPackage* target_pkg = GetPackageAtIndex0(*target_arsc); |
| 294 | if (target_pkg == nullptr) { |
| 295 | return Error("failed to load target package from resources.arsc"); |
| 296 | } |
| 297 | |
| 298 | const LoadedPackage* overlay_pkg = GetPackageAtIndex0(*overlay_arsc); |
| 299 | if (overlay_pkg == nullptr) { |
| 300 | return Error("failed to load overlay package from resources.arsc"); |
| 301 | } |
| 302 | |
| 303 | size_t string_pool_data_length = 0U; |
| 304 | size_t string_pool_offset = 0U; |
| 305 | std::unique_ptr<uint8_t[]> string_pool_data; |
| 306 | Result<ResourceMapping> resource_mapping = {{}}; |
| 307 | if (overlay_info.resource_mapping != 0U) { |
| 308 | // Load the overlay resource mappings from the file specified using android:resourcesMap. |
| 309 | auto asset = OpenNonAssetFromResource(overlay_info.resource_mapping, overlay_asset_manager); |
| 310 | if (!asset) { |
| 311 | return Error("failed opening xml for android:resourcesMap: %s", |
| 312 | asset.GetErrorMessage().c_str()); |
| 313 | } |
| 314 | |
| 315 | auto parser = |
| 316 | XmlParser::Create((*asset)->getBuffer(true /* wordAligned*/), (*asset)->getLength()); |
| 317 | if (!parser) { |
| 318 | return Error("failed opening ResXMLTree"); |
| 319 | } |
| 320 | |
| 321 | // Copy the xml string pool data before the parse goes out of scope. |
| 322 | auto& string_pool = (*parser)->get_strings(); |
| 323 | string_pool_data_length = string_pool.bytes(); |
| 324 | string_pool_data.reset(new uint8_t[string_pool_data_length]); |
| 325 | memcpy(string_pool_data.get(), string_pool.data(), string_pool_data_length); |
| 326 | |
| 327 | // Offset string indices by the size of the overlay resource table string pool. |
| 328 | string_pool_offset = overlay_arsc->GetStringPool()->size(); |
| 329 | |
| 330 | resource_mapping = CreateResourceMapping(&target_asset_manager, target_pkg, overlay_pkg, |
| 331 | string_pool_offset, *(*parser)); |
| 332 | } else { |
| 333 | // If no file is specified using android:resourcesMap, it is assumed that the overlay only |
| 334 | // defines resources intended to override target resources of the same type and name. |
| 335 | resource_mapping = CreateResourceMappingLegacy(&target_asset_manager, &overlay_asset_manager, |
| 336 | target_pkg, overlay_pkg); |
| 337 | } |
| 338 | |
| 339 | if (!resource_mapping) { |
| 340 | return resource_mapping.GetError(); |
| 341 | } |
| 342 | |
| 343 | if (enforce_overlayable) { |
| 344 | // Filter out resources the overlay is not allowed to override. |
| 345 | (*resource_mapping) |
| 346 | .FilterOverlayableResources(&target_asset_manager, target_pkg, overlay_pkg, overlay_info, |
| 347 | fulfilled_policies); |
| 348 | } |
| 349 | |
| 350 | resource_mapping->target_package_id_ = target_pkg->GetPackageId(); |
| 351 | resource_mapping->overlay_package_id_ = overlay_pkg->GetPackageId(); |
| 352 | resource_mapping->string_pool_offset_ = string_pool_offset; |
| 353 | resource_mapping->string_pool_data_ = std::move(string_pool_data); |
| 354 | resource_mapping->string_pool_data_length_ = string_pool_data_length; |
| 355 | return std::move(*resource_mapping); |
| 356 | } |
| 357 | |
| 358 | OverlayResourceMap ResourceMapping::GetOverlayToTargetMap() const { |
| 359 | // An overlay resource can override multiple target resources at once. Rewrite the overlay |
| 360 | // resource as the first target resource it overrides. |
| 361 | OverlayResourceMap map; |
| 362 | for (const auto& mappings : overlay_map_) { |
| 363 | map.insert(std::make_pair(mappings.first, mappings.second)); |
| 364 | } |
| 365 | return map; |
| 366 | } |
| 367 | |
| 368 | Result<Unit> ResourceMapping::AddMapping(ResourceId target_resource, |
| 369 | TargetValue::DataType data_type, |
| 370 | TargetValue::DataValue data_value, |
| 371 | bool rewrite_overlay_reference) { |
| 372 | if (target_map_.find(target_resource) != target_map_.end()) { |
| 373 | return Error(R"(target resource id "0x%08x" mapped to multiple values)", target_resource); |
| 374 | } |
| 375 | |
| 376 | // TODO(141485591): Ensure that the overlay type is compatible with the target type. If the |
| 377 | // runtime types are not compatible, it could cause runtime crashes when the resource is resolved. |
| 378 | |
| 379 | target_map_.insert(std::make_pair(target_resource, TargetValue{data_type, data_value})); |
| 380 | |
| 381 | if (rewrite_overlay_reference && data_type == Res_value::TYPE_REFERENCE) { |
| 382 | overlay_map_.insert(std::make_pair(data_value, target_resource)); |
| 383 | } |
| 384 | |
| 385 | return Result<Unit>({}); |
| 386 | } |
| 387 | |
| 388 | void ResourceMapping::RemoveMapping(ResourceId target_resource) { |
| 389 | auto target_iter = target_map_.find(target_resource); |
| 390 | if (target_iter == target_map_.end()) { |
| 391 | return; |
| 392 | } |
| 393 | |
| 394 | const TargetValue value = target_iter->second; |
| 395 | target_map_.erase(target_iter); |
| 396 | |
| 397 | // Remove rewriting of overlay resource id to target resource id. |
| 398 | if (value.data_type != Res_value::TYPE_REFERENCE) { |
| 399 | return; |
| 400 | } |
| 401 | |
| 402 | auto overlay_iter = overlay_map_.equal_range(value.data_value); |
| 403 | for (auto i = overlay_iter.first; i != overlay_iter.second; ++i) { |
| 404 | if (i->second == target_resource) { |
| 405 | overlay_map_.erase(i); |
| 406 | return; |
| 407 | } |
| 408 | } |
| 409 | } |
| 410 | |
| 411 | } // namespace android::idmap2 |