blob: 91cb43c216ef738eaeee9874420ad8ef77d6abee [file] [log] [blame]
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -08001/*
2 * Copyright (C) 2021 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/ResourceContainer.h"
18
19#include "androidfw/ApkAssets.h"
20#include "androidfw/AssetManager.h"
21#include "androidfw/Util.h"
22#include "idmap2/FabricatedOverlay.h"
23#include "idmap2/XmlParser.h"
24
25namespace android::idmap2 {
26namespace {
27#define REWRITE_PACKAGE(resid, package_id) \
28 (((resid)&0x00ffffffU) | (((uint32_t)(package_id)) << 24U))
29
30#define EXTRACT_PACKAGE(resid) ((0xff000000 & (resid)) >> 24)
31
32constexpr ResourceId kAttrName = 0x01010003;
33constexpr ResourceId kAttrResourcesMap = 0x01010609;
34constexpr ResourceId kAttrTargetName = 0x0101044d;
35constexpr ResourceId kAttrTargetPackage = 0x01010021;
36
37// idmap version 0x01 naively assumes that the package to use is always the first ResTable_package
38// in the resources.arsc blob. In most cases, there is only a single ResTable_package anyway, so
39// this assumption tends to work out. That said, the correct thing to do is to scan
40// resources.arsc for a package with a given name as read from the package manifest instead of
41// relying on a hard-coded index. This however requires storing the package name in the idmap
42// header, which in turn requires incrementing the idmap version. Because the initial version of
43// idmap2 is compatible with idmap, this will have to wait for now.
44const LoadedPackage* GetPackageAtIndex0(const LoadedArsc* loaded_arsc) {
45 const std::vector<std::unique_ptr<const LoadedPackage>>& packages = loaded_arsc->GetPackages();
46 if (packages.empty()) {
47 return nullptr;
48 }
49 return loaded_arsc->GetPackageById(packages[0]->GetPackageId());
50}
51
52Result<uint32_t> CalculateCrc(const ZipAssetsProvider* zip_assets) {
53 constexpr const char* kResourcesArsc = "resources.arsc";
54 std::optional<uint32_t> res_crc = zip_assets->GetCrc(kResourcesArsc);
55 if (!res_crc) {
56 return Error("failed to get CRC for '%s'", kResourcesArsc);
57 }
58
59 constexpr const char* kManifest = "AndroidManifest.xml";
60 std::optional<uint32_t> man_crc = zip_assets->GetCrc(kManifest);
61 if (!man_crc) {
62 return Error("failed to get CRC for '%s'", kManifest);
63 }
64
65 return *res_crc ^ *man_crc;
66}
67
68Result<XmlParser> OpenXmlParser(const std::string& entry_path, const ZipAssetsProvider* zip) {
69 auto manifest = zip->Open(entry_path);
70 if (manifest == nullptr) {
71 return Error("failed to find %s ", entry_path.c_str());
72 }
73
74 auto size = manifest->getLength();
75 auto buffer = manifest->getIncFsBuffer(true /* aligned */).convert<uint8_t>();
76 if (!buffer.verify(size)) {
77 return Error("failed to read entire %s", entry_path.c_str());
78 }
79
80 return XmlParser::Create(buffer.unsafe_ptr(), size, true /* copyData */);
81}
82
83Result<XmlParser> OpenXmlParser(ResourceId id, const ZipAssetsProvider* zip,
84 const AssetManager2* am) {
85 const auto ref_table = am->GetDynamicRefTableForCookie(0);
86 if (ref_table == nullptr) {
87 return Error("failed to find dynamic ref table for cookie 0");
88 }
89
90 ref_table->lookupResourceId(&id);
91 auto value = am->GetResource(id);
92 if (!value.has_value()) {
93 return Error("failed to find resource for id 0x%08x", id);
94 }
95
96 if (value->type != Res_value::TYPE_STRING) {
97 return Error("resource for is 0x%08x is not a file", id);
98 }
99
100 auto string_pool = am->GetStringPoolForCookie(value->cookie);
101 auto file = string_pool->string8ObjectAt(value->data);
102 if (!file.has_value()) {
103 return Error("failed to find string for index %d", value->data);
104 }
105
106 return OpenXmlParser(file->c_str(), zip);
107}
108
109Result<OverlayManifestInfo> ExtractOverlayManifestInfo(const ZipAssetsProvider* zip,
110 const std::string& name) {
111 Result<XmlParser> xml = OpenXmlParser("AndroidManifest.xml", zip);
112 if (!xml) {
113 return xml.GetError();
114 }
115
116 auto manifest_it = xml->tree_iterator();
117 if (manifest_it->event() != XmlParser::Event::START_TAG || manifest_it->name() != "manifest") {
118 return Error("root element tag is not <manifest> in AndroidManifest.xml");
119 }
120
121 for (auto&& it : manifest_it) {
122 if (it.event() != XmlParser::Event::START_TAG || it.name() != "overlay") {
123 continue;
124 }
125
126 OverlayManifestInfo info{};
127 if (auto result_str = it.GetAttributeStringValue(kAttrName, "android:name")) {
128 if (*result_str != name) {
129 // A value for android:name was found, but either the name does not match the requested
130 // name, or an <overlay> tag with no name was requested.
131 continue;
132 }
133 info.name = *result_str;
134 } else if (!name.empty()) {
135 // This tag does not have a value for android:name, but an <overlay> tag with a specific name
136 // has been requested.
137 continue;
138 }
139
140 if (auto result_str = it.GetAttributeStringValue(kAttrTargetPackage, "android:targetPackage")) {
141 info.target_package = *result_str;
142 } else {
143 return Error("android:targetPackage missing from <overlay> in AndroidManifest.xml");
144 }
145
146 if (auto result_str = it.GetAttributeStringValue(kAttrTargetName, "android:targetName")) {
147 info.target_name = *result_str;
148 }
149
150 if (auto result_value = it.GetAttributeValue(kAttrResourcesMap, "android:resourcesMap")) {
151 if (utils::IsReference((*result_value).dataType)) {
152 info.resource_mapping = (*result_value).data;
153 } else {
154 return Error("android:resourcesMap is not a reference in AndroidManifest.xml");
155 }
156 }
157 return info;
158 }
159
160 return Error("<overlay> with android:name \"%s\" missing from AndroidManifest.xml", name.c_str());
161}
162
163Result<OverlayData> CreateResourceMapping(ResourceId id, const ZipAssetsProvider* zip,
164 const AssetManager2* overlay_am,
165 const LoadedArsc* overlay_arsc,
166 const LoadedPackage* overlay_package) {
167 auto parser = OpenXmlParser(id, zip, overlay_am);
168 if (!parser) {
169 return parser.GetError();
170 }
171
172 OverlayData overlay_data{};
173 const uint32_t string_pool_offset = overlay_arsc->GetStringPool()->size();
174 const uint8_t package_id = overlay_package->GetPackageId();
175 auto root_it = parser->tree_iterator();
176 if (root_it->event() != XmlParser::Event::START_TAG || root_it->name() != "overlay") {
177 return Error("root element is not <overlay> tag");
178 }
179
180 auto overlay_it_end = root_it.end();
181 for (auto overlay_it = root_it.begin(); overlay_it != overlay_it_end; ++overlay_it) {
182 if (overlay_it->event() == XmlParser::Event::BAD_DOCUMENT) {
183 return Error("failed to parse overlay xml document");
184 }
185
186 if (overlay_it->event() != XmlParser::Event::START_TAG) {
187 continue;
188 }
189
190 if (overlay_it->name() != "item") {
191 return Error("unexpected tag <%s> in <overlay>", overlay_it->name().c_str());
192 }
193
194 Result<std::string> target_resource = overlay_it->GetAttributeStringValue("target");
195 if (!target_resource) {
196 return Error(R"(<item> tag missing expected attribute "target")");
197 }
198
199 Result<android::Res_value> overlay_resource = overlay_it->GetAttributeValue("value");
200 if (!overlay_resource) {
201 return Error(R"(<item> tag missing expected attribute "value")");
202 }
203
204 if (overlay_resource->dataType == Res_value::TYPE_STRING) {
205 overlay_resource->data += string_pool_offset;
206 }
207
208 if (utils::IsReference(overlay_resource->dataType)) {
209 // Only rewrite resources defined within the overlay package to their corresponding target
210 // resource ids at runtime.
211 bool rewrite_id = package_id == EXTRACT_PACKAGE(overlay_resource->data);
212 overlay_data.pairs.emplace_back(OverlayData::Value{
213 *target_resource, OverlayData::ResourceIdValue{overlay_resource->data, rewrite_id}});
214 } else {
215 overlay_data.pairs.emplace_back(
216 OverlayData::Value{*target_resource, TargetValue{.data_type = overlay_resource->dataType,
217 .data_value = overlay_resource->data}});
218 }
219 }
220
221 const auto& string_pool = parser->get_strings();
222 const uint32_t string_pool_data_length = string_pool.bytes();
223 overlay_data.string_pool_data = OverlayData::InlineStringPoolData{
224 .data = std::unique_ptr<uint8_t[]>(new uint8_t[string_pool_data_length]),
225 .data_length = string_pool_data_length,
226 .string_pool_offset = string_pool_offset,
227 };
228
229 // Overlays should not be incrementally installed, so calling unsafe_ptr is fine here.
230 memcpy(overlay_data.string_pool_data->data.get(), string_pool.data().unsafe_ptr(),
231 string_pool_data_length);
232 return overlay_data;
233}
234
235OverlayData CreateResourceMappingLegacy(const AssetManager2* overlay_am,
236 const LoadedPackage* overlay_package) {
237 OverlayData overlay_data{};
238 for (const ResourceId overlay_resid : *overlay_package) {
239 if (auto name = utils::ResToTypeEntryName(*overlay_am, overlay_resid)) {
240 // Disable rewriting. Overlays did not support internal references before
241 // android:resourcesMap. Do not introduce new behavior.
242 overlay_data.pairs.emplace_back(OverlayData::Value{
243 *name, OverlayData::ResourceIdValue{overlay_resid, false /* rewrite_id */}});
244 }
245 }
246 return overlay_data;
247}
248
249struct ResState {
250 std::unique_ptr<ApkAssets> apk_assets;
251 const LoadedArsc* arsc;
252 const LoadedPackage* package;
253 std::unique_ptr<AssetManager2> am;
254 ZipAssetsProvider* zip_assets;
255
256 static Result<ResState> Initialize(std::unique_ptr<ZipAssetsProvider> zip) {
257 ResState state;
258 state.zip_assets = zip.get();
259 if ((state.apk_assets = ApkAssets::Load(std::move(zip))) == nullptr) {
260 return Error("failed to load apk asset");
261 }
262
263 if ((state.arsc = state.apk_assets->GetLoadedArsc()) == nullptr) {
264 return Error("failed to retrieve loaded arsc");
265 }
266
267 if ((state.package = GetPackageAtIndex0(state.arsc)) == nullptr) {
268 return Error("failed to retrieve loaded package at index 0");
269 }
270
271 state.am = std::make_unique<AssetManager2>();
272 if (!state.am->SetApkAssets({state.apk_assets.get()})) {
273 return Error("failed to create asset manager");
274 }
275
276 return state;
277 }
278};
279
280} // namespace
281
282struct ApkResourceContainer : public TargetResourceContainer, public OverlayResourceContainer {
283 static Result<std::unique_ptr<ApkResourceContainer>> FromPath(const std::string& path);
284
285 // inherited from TargetResourceContainer
286 Result<bool> DefinesOverlayable() const override;
287 Result<const android::OverlayableInfo*> GetOverlayableInfo(ResourceId id) const override;
288 Result<ResourceId> GetResourceId(const std::string& name) const override;
289
290 // inherited from OverlayResourceContainer
291 Result<OverlayData> GetOverlayData(const OverlayManifestInfo& info) const override;
292 Result<OverlayManifestInfo> FindOverlayInfo(const std::string& name) const override;
293
294 // inherited from ResourceContainer
295 Result<uint32_t> GetCrc() const override;
296 Result<std::string> GetResourceName(ResourceId id) const override;
297 const std::string& GetPath() const override;
298
299 ~ApkResourceContainer() override = default;
300
301 private:
302 ApkResourceContainer(std::unique_ptr<ZipAssetsProvider> zip_assets, std::string path);
303
304 Result<const ResState*> GetState() const;
305 ZipAssetsProvider* GetZipAssets() const;
306
307 mutable std::variant<std::unique_ptr<ZipAssetsProvider>, ResState> state_;
308 std::string path_;
309};
310
311ApkResourceContainer::ApkResourceContainer(std::unique_ptr<ZipAssetsProvider> zip_assets,
312 std::string path)
313 : state_(std::move(zip_assets)), path_(std::move(path)) {
314}
315
316Result<std::unique_ptr<ApkResourceContainer>> ApkResourceContainer::FromPath(
317 const std::string& path) {
318 auto zip_assets = ZipAssetsProvider::Create(path);
319 if (zip_assets == nullptr) {
320 return Error("failed to load zip assets");
321 }
322 return std::unique_ptr<ApkResourceContainer>(
323 new ApkResourceContainer(std::move(zip_assets), path));
324}
325
326Result<const ResState*> ApkResourceContainer::GetState() const {
327 if (auto state = std::get_if<ResState>(&state_); state != nullptr) {
328 return state;
329 }
330
331 auto state =
332 ResState::Initialize(std::move(std::get<std::unique_ptr<ZipAssetsProvider>>(state_)));
333 if (!state) {
334 return state.GetError();
335 }
336
337 state_ = std::move(*state);
338 return &std::get<ResState>(state_);
339}
340
341ZipAssetsProvider* ApkResourceContainer::GetZipAssets() const {
342 if (auto zip = std::get_if<std::unique_ptr<ZipAssetsProvider>>(&state_); zip != nullptr) {
343 return zip->get();
344 }
345 return std::get<ResState>(state_).zip_assets;
346}
347
348Result<bool> ApkResourceContainer::DefinesOverlayable() const {
349 auto state = GetState();
350 if (!state) {
351 return state.GetError();
352 }
353 return (*state)->package->DefinesOverlayable();
354}
355
356Result<const android::OverlayableInfo*> ApkResourceContainer::GetOverlayableInfo(
357 ResourceId id) const {
358 auto state = GetState();
359 if (!state) {
360 return state.GetError();
361 }
362 return (*state)->package->GetOverlayableInfo(id);
363}
364
365Result<OverlayManifestInfo> ApkResourceContainer::FindOverlayInfo(const std::string& name) const {
366 return ExtractOverlayManifestInfo(GetZipAssets(), name);
367}
368
369Result<OverlayData> ApkResourceContainer::GetOverlayData(const OverlayManifestInfo& info) const {
370 const auto state = GetState();
371 if (!state) {
372 return state.GetError();
373 }
374
375 if (info.resource_mapping != 0) {
376 return CreateResourceMapping(info.resource_mapping, GetZipAssets(), (*state)->am.get(),
377 (*state)->arsc, (*state)->package);
378 }
379 return CreateResourceMappingLegacy((*state)->am.get(), (*state)->package);
380}
381
382Result<uint32_t> ApkResourceContainer::GetCrc() const {
383 return CalculateCrc(GetZipAssets());
384}
385
386const std::string& ApkResourceContainer::GetPath() const {
387 return path_;
388}
389
390Result<ResourceId> ApkResourceContainer::GetResourceId(const std::string& name) const {
391 auto state = GetState();
392 if (!state) {
393 return state.GetError();
394 }
395 auto id = (*state)->am->GetResourceId(name, "", (*state)->package->GetPackageName());
396 if (!id.has_value()) {
397 return Error("failed to find resource '%s'", name.c_str());
398 }
399
400 // Retrieve the compile-time resource id of the target resource.
401 return REWRITE_PACKAGE(*id, (*state)->package->GetPackageId());
402}
403
404Result<std::string> ApkResourceContainer::GetResourceName(ResourceId id) const {
405 auto state = GetState();
406 if (!state) {
407 return state.GetError();
408 }
409 return utils::ResToTypeEntryName(*(*state)->am, id);
410}
411
412Result<std::unique_ptr<TargetResourceContainer>> TargetResourceContainer::FromPath(
413 std::string path) {
414 auto result = ApkResourceContainer::FromPath(path);
415 if (!result) {
416 return result.GetError();
417 }
418 return std::unique_ptr<TargetResourceContainer>(result->release());
419}
420
421Result<std::unique_ptr<OverlayResourceContainer>> OverlayResourceContainer::FromPath(
422 std::string path) {
423 // Load the path as a fabricated overlay if the file magic indicates this is a fabricated overlay.
424 if (android::IsFabricatedOverlay(path)) {
425 auto result = FabricatedOverlayContainer::FromPath(path);
426 if (!result) {
427 return result.GetError();
428 }
429 return std::unique_ptr<OverlayResourceContainer>(result->release());
430 }
431
432 // Fallback to loading the container as an APK.
433 auto result = ApkResourceContainer::FromPath(path);
434 if (!result) {
435 return result.GetError();
436 }
437 return std::unique_ptr<OverlayResourceContainer>(result->release());
438}
439
440} // namespace android::idmap2