blob: c31dcff40a9335a65c794982ea7dd7da78b3d8fa [file] [log] [blame]
Jooyung Han017916b2021-04-20 03:57:19 +09001/*
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 <sys/stat.h>
18#include <sys/types.h>
19#include <unistd.h>
20
21#include <fstream>
22#include <iostream>
23#include <optional>
24#include <string>
25#include <vector>
26
27#include <android-base/file.h>
28#include <android-base/result.h>
29#include <com_android_apex.h>
30#include <image_aggregator.h>
31#include <json/json.h>
32
Jooyung Han74573482021-06-08 17:10:21 +090033#include "microdroid/metadata.h"
Jooyung Han017916b2021-04-20 03:57:19 +090034
35using android::base::Dirname;
36using android::base::ErrnoError;
37using android::base::Error;
38using android::base::Result;
Jooyung Hana54dcaf2021-05-13 21:57:02 +090039using android::base::unique_fd;
Jooyung Han74573482021-06-08 17:10:21 +090040using android::microdroid::ApexPayload;
41using android::microdroid::ApkPayload;
42using android::microdroid::Metadata;
43using android::microdroid::WriteMetadata;
Jooyung Han017916b2021-04-20 03:57:19 +090044
45using com::android::apex::ApexInfoList;
46using com::android::apex::readApexInfoList;
47
Jooyung Hana54dcaf2021-05-13 21:57:02 +090048using cuttlefish::AlignToPartitionSize;
Jooyung Han017916b2021-04-20 03:57:19 +090049using cuttlefish::CreateCompositeDisk;
Jooyung Han017916b2021-04-20 03:57:19 +090050using cuttlefish::kLinuxFilesystem;
Jooyung Hana54dcaf2021-05-13 21:57:02 +090051using cuttlefish::MultipleImagePartition;
Jooyung Han017916b2021-04-20 03:57:19 +090052
53Result<uint32_t> GetFileSize(const std::string& path) {
54 struct stat st;
55 if (lstat(path.c_str(), &st) == -1) {
56 return ErrnoError() << "Can't lstat " << path;
57 }
58 return static_cast<uint32_t>(st.st_size);
59}
60
61std::string ToAbsolute(const std::string& path, const std::string& dirname) {
62 bool is_absolute = !path.empty() && path[0] == '/';
63 if (is_absolute) {
64 return path;
65 } else {
66 return dirname + "/" + path;
67 }
68}
69
70// Returns `append` is appended to the end of filename preserving the extension.
71std::string AppendFileName(const std::string& filename, const std::string& append) {
72 size_t pos = filename.find_last_of('.');
73 if (pos == std::string::npos) {
74 return filename + append;
75 } else {
76 return filename.substr(0, pos) + append + filename.substr(pos);
77 }
78}
79
80struct ApexConfig {
81 std::string name; // the apex name
82 std::string path; // the path to the apex file
83 // absolute or relative to the config file
84 std::optional<std::string> public_key;
85 std::optional<std::string> root_digest;
86};
87
Jooyung Han57d895e2021-05-13 21:58:41 +090088struct ApkConfig {
89 std::string name;
Jooyung Han57d895e2021-05-13 21:58:41 +090090 std::string path;
Jooyung Han7ce2e532021-06-16 16:52:02 +090091 // TODO(jooyung) make this required?
92 std::optional<std::string> idsig_path;
Jooyung Han57d895e2021-05-13 21:58:41 +090093};
94
Jooyung Han017916b2021-04-20 03:57:19 +090095struct Config {
96 std::string dirname; // config file's direname to resolve relative paths in the config
97
Jooyung Han74573482021-06-08 17:10:21 +090098 // TODO(b/185956069) remove this when VirtualizationService can provide apex paths
Jooyung Han017916b2021-04-20 03:57:19 +090099 std::vector<std::string> system_apexes;
Jooyung Han74573482021-06-08 17:10:21 +0900100
Jooyung Han017916b2021-04-20 03:57:19 +0900101 std::vector<ApexConfig> apexes;
Jooyung Han57d895e2021-05-13 21:58:41 +0900102 std::optional<ApkConfig> apk;
Jooyung Han347d9f22021-05-28 00:05:14 +0900103 std::optional<std::string> payload_config_path;
Jooyung Han017916b2021-04-20 03:57:19 +0900104};
105
106#define DO(expr) \
107 if (auto res = (expr); !res.ok()) return res.error()
108
109Result<void> ParseJson(const Json::Value& value, std::string& s) {
110 if (!value.isString()) {
111 return Error() << "should be a string: " << value;
112 }
113 s = value.asString();
114 return {};
115}
116
Jooyung Han57d895e2021-05-13 21:58:41 +0900117template <typename T>
118Result<void> ParseJson(const Json::Value& value, std::optional<T>& s) {
Jooyung Han017916b2021-04-20 03:57:19 +0900119 if (value.isNull()) {
120 s.reset();
121 return {};
122 }
123 s.emplace();
124 return ParseJson(value, *s);
125}
126
Jooyung Han347d9f22021-05-28 00:05:14 +0900127template <typename T>
128Result<void> ParseJson(const Json::Value& values, std::vector<T>& parsed) {
129 for (const Json::Value& value : values) {
130 T t;
131 DO(ParseJson(value, t));
132 parsed.push_back(std::move(t));
133 }
134 return {};
135}
136
Jooyung Han017916b2021-04-20 03:57:19 +0900137Result<void> ParseJson(const Json::Value& value, ApexConfig& apex_config) {
138 DO(ParseJson(value["name"], apex_config.name));
139 DO(ParseJson(value["path"], apex_config.path));
140 DO(ParseJson(value["publicKey"], apex_config.public_key));
141 DO(ParseJson(value["rootDigest"], apex_config.root_digest));
142 return {};
143}
144
Jooyung Han57d895e2021-05-13 21:58:41 +0900145Result<void> ParseJson(const Json::Value& value, ApkConfig& apk_config) {
146 DO(ParseJson(value["name"], apk_config.name));
147 DO(ParseJson(value["path"], apk_config.path));
Jooyung Han7ce2e532021-06-16 16:52:02 +0900148 DO(ParseJson(value["idsig_path"], apk_config.idsig_path));
Jooyung Han57d895e2021-05-13 21:58:41 +0900149 return {};
150}
151
Jooyung Han017916b2021-04-20 03:57:19 +0900152Result<void> ParseJson(const Json::Value& value, Config& config) {
153 DO(ParseJson(value["system_apexes"], config.system_apexes));
154 DO(ParseJson(value["apexes"], config.apexes));
Jooyung Han57d895e2021-05-13 21:58:41 +0900155 DO(ParseJson(value["apk"], config.apk));
Jooyung Han347d9f22021-05-28 00:05:14 +0900156 DO(ParseJson(value["payload_config_path"], config.payload_config_path));
Jooyung Han017916b2021-04-20 03:57:19 +0900157 return {};
158}
159
160Result<Config> LoadConfig(const std::string& config_file) {
161 std::ifstream in(config_file);
162 Json::CharReaderBuilder builder;
163 Json::Value root;
164 Json::String errs;
165 if (!parseFromStream(builder, in, &root, &errs)) {
166 return Error() << "bad config: " << errs;
167 }
168
169 Config config;
170 config.dirname = Dirname(config_file);
171 DO(ParseJson(root, config));
172 return config;
173}
174
175#undef DO
176
177Result<void> LoadSystemApexes(Config& config) {
178 static const char* kApexInfoListFile = "/apex/apex-info-list.xml";
179 std::optional<ApexInfoList> apex_info_list = readApexInfoList(kApexInfoListFile);
180 if (!apex_info_list.has_value()) {
181 return Error() << "Failed to read " << kApexInfoListFile;
182 }
183 auto get_apex_path = [&](const std::string& apex_name) -> std::optional<std::string> {
184 for (const auto& apex_info : apex_info_list->getApexInfo()) {
185 if (apex_info.getIsActive() && apex_info.getModuleName() == apex_name) {
186 return apex_info.getModulePath();
187 }
188 }
189 return std::nullopt;
190 };
191 for (const auto& apex_name : config.system_apexes) {
192 const auto& apex_path = get_apex_path(apex_name);
193 if (!apex_path.has_value()) {
194 return Error() << "Can't find the system apex: " << apex_name;
195 }
196 config.apexes.push_back(ApexConfig{
197 .name = apex_name,
198 .path = *apex_path,
199 .public_key = std::nullopt,
200 .root_digest = std::nullopt,
201 });
202 }
203 return {};
204}
205
Jooyung Han74573482021-06-08 17:10:21 +0900206Result<void> MakeMetadata(const Config& config, const std::string& filename) {
207 Metadata metadata;
208 metadata.set_version(1);
Jooyung Han017916b2021-04-20 03:57:19 +0900209
210 for (const auto& apex_config : config.apexes) {
Jooyung Han74573482021-06-08 17:10:21 +0900211 auto* apex = metadata.add_apexes();
Jooyung Han017916b2021-04-20 03:57:19 +0900212
213 // name
Jooyung Han74573482021-06-08 17:10:21 +0900214 apex->set_name(apex_config.name);
Jooyung Han017916b2021-04-20 03:57:19 +0900215
216 // publicKey
217 if (apex_config.public_key.has_value()) {
Jooyung Han74573482021-06-08 17:10:21 +0900218 apex->set_publickey(apex_config.public_key.value());
Jooyung Han017916b2021-04-20 03:57:19 +0900219 }
220
221 // rootDigest
222 if (apex_config.root_digest.has_value()) {
Jooyung Han74573482021-06-08 17:10:21 +0900223 apex->set_rootdigest(apex_config.root_digest.value());
Jooyung Han017916b2021-04-20 03:57:19 +0900224 }
225 }
226
Jooyung Han57d895e2021-05-13 21:58:41 +0900227 if (config.apk.has_value()) {
Jooyung Han74573482021-06-08 17:10:21 +0900228 auto* apk = metadata.mutable_apk();
229 apk->set_name(config.apk->name);
230 apk->set_payload_partition_name("microdroid-apk");
Jooyung Han7ce2e532021-06-16 16:52:02 +0900231 if (config.apk->idsig_path.has_value()) {
232 apk->set_idsig_partition_name("microdroid-apk-idsig");
233 }
Jooyung Han57d895e2021-05-13 21:58:41 +0900234 }
235
Jooyung Han347d9f22021-05-28 00:05:14 +0900236 if (config.payload_config_path.has_value()) {
Jooyung Han74573482021-06-08 17:10:21 +0900237 *metadata.mutable_payload_config_path() = config.payload_config_path.value();
Jooyung Han347d9f22021-05-28 00:05:14 +0900238 }
239
Jooyung Han017916b2021-04-20 03:57:19 +0900240 std::ofstream out(filename);
Jooyung Han74573482021-06-08 17:10:21 +0900241 return WriteMetadata(metadata, out);
Jooyung Han017916b2021-04-20 03:57:19 +0900242}
243
Jooyung Han7ce2e532021-06-16 16:52:02 +0900244// fill (zeros + original file's size) with aligning BLOCK_SIZE(4096) boundary
245// return true when the filler is generated.
246Result<bool> SizeFiller(const std::string& file_path, const std::string& filler_path) {
Jooyung Hana54dcaf2021-05-13 21:57:02 +0900247 auto file_size = GetFileSize(file_path);
248 if (!file_size.ok()) {
249 return file_size.error();
250 }
251 auto disk_size = AlignToPartitionSize(*file_size + sizeof(uint32_t));
252
253 unique_fd fd(TEMP_FAILURE_RETRY(open(filler_path.c_str(), O_CREAT | O_WRONLY | O_TRUNC, 0600)));
254 if (fd.get() == -1) {
255 return ErrnoError() << "open(" << filler_path << ") failed.";
256 }
257 uint32_t size = htobe32(static_cast<uint32_t>(*file_size));
258 if (ftruncate(fd.get(), disk_size - *file_size) == -1) {
259 return ErrnoError() << "ftruncate(" << filler_path << ") failed.";
260 }
261 if (lseek(fd.get(), -sizeof(size), SEEK_END) == -1) {
262 return ErrnoError() << "lseek(" << filler_path << ") failed.";
263 }
264 if (write(fd.get(), &size, sizeof(size)) <= 0) {
265 return ErrnoError() << "write(" << filler_path << ") failed.";
266 }
Jooyung Han7ce2e532021-06-16 16:52:02 +0900267 return true;
Jooyung Hana54dcaf2021-05-13 21:57:02 +0900268}
269
Jooyung Han7ce2e532021-06-16 16:52:02 +0900270// fill zeros to align |file_path|'s size to BLOCK_SIZE(4096) boundary.
271// return true when the filler is generated.
272Result<bool> ZeroFiller(const std::string& file_path, const std::string& filler_path) {
273 auto file_size = GetFileSize(file_path);
274 if (!file_size.ok()) {
275 return file_size.error();
276 }
277 auto disk_size = AlignToPartitionSize(*file_size);
278 if (disk_size <= *file_size) {
279 return false;
280 }
Jooyung Han7ce2e532021-06-16 16:52:02 +0900281 unique_fd fd(TEMP_FAILURE_RETRY(open(filler_path.c_str(), O_CREAT | O_WRONLY | O_TRUNC, 0600)));
282 if (fd.get() == -1) {
283 return ErrnoError() << "open(" << filler_path << ") failed.";
284 }
Jooyung Hanf0f76822021-06-17 22:00:54 +0900285 if (ftruncate(fd.get(), disk_size - *file_size) == -1) {
286 return ErrnoError() << "ftruncate(" << filler_path << ") failed.";
Jooyung Han7ce2e532021-06-16 16:52:02 +0900287 }
288 return true;
289}
290
291// Do not generate any fillers
292// Note that CreateCompositeDisk() handles gaps between partitions.
293Result<bool> NoFiller(const std::string& file_path, const std::string& filler_path) {
294 (void)file_path;
295 (void)filler_path;
296 return false;
297}
298
Jooyung Han74573482021-06-08 17:10:21 +0900299Result<void> MakePayload(const Config& config, const std::string& metadata_file,
Jooyung Han017916b2021-04-20 03:57:19 +0900300 const std::string& output_file) {
Jooyung Hana54dcaf2021-05-13 21:57:02 +0900301 std::vector<MultipleImagePartition> partitions;
Jooyung Han017916b2021-04-20 03:57:19 +0900302
Jooyung Han74573482021-06-08 17:10:21 +0900303 // put metadata at the first partition
Jooyung Hana54dcaf2021-05-13 21:57:02 +0900304 partitions.push_back(MultipleImagePartition{
Jooyung Han74573482021-06-08 17:10:21 +0900305 .label = "metadata",
306 .image_file_paths = {metadata_file},
Jooyung Han017916b2021-04-20 03:57:19 +0900307 .type = kLinuxFilesystem,
308 .read_only = true,
309 });
310
Jooyung Han57d895e2021-05-13 21:58:41 +0900311 int filler_count = 0;
Jooyung Han7ce2e532021-06-16 16:52:02 +0900312 auto add_partition = [&](auto partition_name, auto file_path, auto filler) -> Result<void> {
313 std::vector<std::string> image_files{file_path};
314
Jooyung Han57d895e2021-05-13 21:58:41 +0900315 std::string filler_path = output_file + "." + std::to_string(filler_count++);
Jooyung Han7ce2e532021-06-16 16:52:02 +0900316 if (auto ret = filler(file_path, filler_path); !ret.ok()) {
Jooyung Han57d895e2021-05-13 21:58:41 +0900317 return ret.error();
Jooyung Han7ce2e532021-06-16 16:52:02 +0900318 } else if (*ret) {
319 image_files.push_back(filler_path);
Jooyung Han57d895e2021-05-13 21:58:41 +0900320 }
321 partitions.push_back(MultipleImagePartition{
322 .label = partition_name,
Jooyung Han7ce2e532021-06-16 16:52:02 +0900323 .image_file_paths = image_files,
Jooyung Han57d895e2021-05-13 21:58:41 +0900324 .type = kLinuxFilesystem,
325 .read_only = true,
326 });
327 return {};
328 };
329
Jooyung Hana54dcaf2021-05-13 21:57:02 +0900330 // put apexes at the subsequent partitions with "size" filler
Jooyung Han017916b2021-04-20 03:57:19 +0900331 for (size_t i = 0; i < config.apexes.size(); i++) {
332 const auto& apex_config = config.apexes[i];
Jooyung Hana54dcaf2021-05-13 21:57:02 +0900333 std::string apex_path = ToAbsolute(apex_config.path, config.dirname);
Jooyung Han7ce2e532021-06-16 16:52:02 +0900334 if (auto ret = add_partition("microdroid-apex-" + std::to_string(i), apex_path, SizeFiller);
Jooyung Han57d895e2021-05-13 21:58:41 +0900335 !ret.ok()) {
Jooyung Hana54dcaf2021-05-13 21:57:02 +0900336 return ret.error();
337 }
Jooyung Han57d895e2021-05-13 21:58:41 +0900338 }
Jooyung Han7ce2e532021-06-16 16:52:02 +0900339 // put apk with "zero" filler.
Jooyung Han57d895e2021-05-13 21:58:41 +0900340 // TODO(jooyung): partition name("microdroid-apk") is TBD
341 if (config.apk.has_value()) {
342 std::string apk_path = ToAbsolute(config.apk->path, config.dirname);
Jooyung Han7ce2e532021-06-16 16:52:02 +0900343 if (auto ret = add_partition("microdroid-apk", apk_path, ZeroFiller); !ret.ok()) {
Jooyung Han57d895e2021-05-13 21:58:41 +0900344 return ret.error();
345 }
Jooyung Han7ce2e532021-06-16 16:52:02 +0900346 if (config.apk->idsig_path.has_value()) {
347 std::string idsig_path = ToAbsolute(config.apk->idsig_path.value(), config.dirname);
348 if (auto ret = add_partition("microdroid-apk-idsig", idsig_path, NoFiller); !ret.ok()) {
349 return ret.error();
350 }
351 }
Jooyung Han017916b2021-04-20 03:57:19 +0900352 }
353
354 const std::string gpt_header = AppendFileName(output_file, "-header");
355 const std::string gpt_footer = AppendFileName(output_file, "-footer");
356 CreateCompositeDisk(partitions, gpt_header, gpt_footer, output_file);
357 return {};
358}
359
360int main(int argc, char** argv) {
361 if (argc != 3) {
362 std::cerr << "Usage: " << argv[0] << " <config> <output>\n";
363 return 1;
364 }
365
366 auto config = LoadConfig(argv[1]);
367 if (!config.ok()) {
368 std::cerr << config.error() << '\n';
369 return 1;
370 }
371
372 if (const auto res = LoadSystemApexes(*config); !res.ok()) {
373 std::cerr << res.error() << '\n';
374 return 1;
375 }
376
377 const std::string output_file(argv[2]);
Jooyung Han74573482021-06-08 17:10:21 +0900378 const std::string metadata_file = AppendFileName(output_file, "-metadata");
Jooyung Han017916b2021-04-20 03:57:19 +0900379
Jooyung Han74573482021-06-08 17:10:21 +0900380 if (const auto res = MakeMetadata(*config, metadata_file); !res.ok()) {
Jooyung Han017916b2021-04-20 03:57:19 +0900381 std::cerr << res.error() << '\n';
382 return 1;
383 }
Jooyung Han74573482021-06-08 17:10:21 +0900384 if (const auto res = MakePayload(*config, metadata_file, output_file); !res.ok()) {
Jooyung Han017916b2021-04-20 03:57:19 +0900385 std::cerr << res.error() << '\n';
386 return 1;
387 }
388
389 return 0;
390}