blob: 5e9cb57c1692d2fba2804a5dc04a0c5a83975c27 [file] [log] [blame]
Cody Schuffelen147b88e2019-09-09 16:00:11 -07001#include "host/commands/assemble_cvd/flags.h"
Cody Schuffelen20ecaca2019-01-29 17:43:38 -08002
A. Cody Schuffelenc17acda2020-01-23 15:54:40 -08003#include <dirent.h>
4#include <sys/types.h>
5#include <sys/stat.h>
Cody Schuffelen25c46432020-01-14 13:49:52 -08006#include <sys/statvfs.h>
A. Cody Schuffelenc17acda2020-01-23 15:54:40 -08007#include <unistd.h>
Cody Schuffelen25c46432020-01-14 13:49:52 -08008
Jorge E. Moreirae049b792019-12-18 18:17:48 -08009#include <algorithm>
Cody Schuffelen20ecaca2019-01-29 17:43:38 -080010#include <iostream>
Ram Muthiahaad97c52019-08-14 17:05:01 -070011#include <fstream>
Cody Schuffelen20ecaca2019-01-29 17:43:38 -080012
Cody Schuffelenf4a1cdb2019-11-13 16:51:16 -080013#include <android-base/strings.h>
Cody Schuffelen20ecaca2019-01-29 17:43:38 -080014#include <gflags/gflags.h>
15#include <glog/logging.h>
16
17#include "common/libs/utils/environment.h"
18#include "common/libs/utils/files.h"
Cody Schuffelen147b88e2019-09-09 16:00:11 -070019#include "host/commands/assemble_cvd/boot_image_unpacker.h"
20#include "host/commands/assemble_cvd/data_image.h"
21#include "host/commands/assemble_cvd/image_aggregator.h"
22#include "host/commands/assemble_cvd/assembler_defs.h"
Cody Schuffelenb737ef52019-09-25 14:54:38 -070023#include "host/commands/assemble_cvd/super_image_mixer.h"
Cody Schuffelen605e6852019-10-16 16:22:24 -070024#include "host/libs/config/fetcher_config.h"
Jorge E. Moreiraba626622019-01-28 17:47:50 -080025#include "host/libs/vm_manager/crosvm_manager.h"
Cody Schuffelen20ecaca2019-01-29 17:43:38 -080026#include "host/libs/vm_manager/qemu_manager.h"
27#include "host/libs/vm_manager/vm_manager.h"
28
Cody Schuffelen47c57852019-12-13 13:50:50 -080029using vsoc::ForCurrentInstance;
Cody Schuffelene71fa352019-09-10 16:11:58 -070030using cvd::AssemblerExitCodes;
Cody Schuffelen20ecaca2019-01-29 17:43:38 -080031
Cody Schuffelen20ecaca2019-01-29 17:43:38 -080032DEFINE_string(cache_image, "", "Location of the cache partition image.");
Paul Trautrimba8f8e92019-03-12 17:55:48 +090033DEFINE_string(metadata_image, "", "Location of the metadata partition image "
34 "to be generated.");
35DEFINE_int32(blank_metadata_image_mb, 16,
36 "The size of the blank metadata image to generate, MB.");
Cody Schuffelen20ecaca2019-01-29 17:43:38 -080037DEFINE_int32(cpus, 2, "Virtual CPU count.");
38DEFINE_string(data_image, "", "Location of the data partition image.");
39DEFINE_string(data_policy, "use_existing", "How to handle userdata partition."
40 " Either 'use_existing', 'create_if_missing', 'resize_up_to', or "
41 "'always_create'.");
42DEFINE_int32(blank_data_image_mb, 0,
43 "The size of the blank data image to generate, MB.");
Alistair Delva4c70e262019-10-15 14:33:59 -070044DEFINE_string(blank_data_image_fmt, "f2fs",
Cody Schuffelen20ecaca2019-01-29 17:43:38 -080045 "The fs format for the blank data image. Used with mkfs.");
46DEFINE_string(qemu_gdb, "",
Matthias Maennich454d7872019-02-06 16:35:17 +000047 "Debug flag to pass to qemu. e.g. -qemu_gdb=tcp::1234");
Cody Schuffelen20ecaca2019-01-29 17:43:38 -080048
49DEFINE_int32(x_res, 720, "Width of the screen in pixels");
50DEFINE_int32(y_res, 1280, "Height of the screen in pixels");
51DEFINE_int32(dpi, 160, "Pixels per inch for the screen");
52DEFINE_int32(refresh_rate_hz, 60, "Screen refresh rate in Hertz");
Cody Schuffelen20ecaca2019-01-29 17:43:38 -080053DEFINE_string(kernel_path, "",
54 "Path to the kernel. Overrides the one from the boot image");
Ram Muthiahaad97c52019-08-14 17:05:01 -070055DEFINE_string(initramfs_path, "", "Path to the initramfs");
Jorge E. Moreira80ddd7f2019-02-04 16:30:13 -080056DEFINE_bool(decompress_kernel, false,
Jorge E. Moreira36294042019-06-07 15:23:18 -070057 "Whether to decompress the kernel image.");
Cody Schuffelen20ecaca2019-01-29 17:43:38 -080058DEFINE_string(extra_kernel_cmdline, "",
59 "Additional flags to put on the kernel command line");
60DEFINE_int32(loop_max_part, 7, "Maximum number of loop partitions");
Jorge E. Moreira300f97f2019-04-09 13:48:01 -070061DEFINE_bool(guest_enforce_security, true,
Cody Schuffelen79d4c192019-12-04 15:13:26 -080062 "Whether to run in enforcing mode (non permissive).");
Cody Schuffelen20ecaca2019-01-29 17:43:38 -080063DEFINE_bool(guest_audit_security, true,
64 "Whether to log security audits.");
Alistair Delva33b861f2019-12-26 12:23:59 -080065DEFINE_bool(guest_force_normal_boot, true,
66 "Whether to force the boot sequence to skip recovery.");
Yifan Hong19d713e2019-05-01 14:12:07 -070067DEFINE_string(boot_image, "",
68 "Location of cuttlefish boot image. If empty it is assumed to be "
69 "boot.img in the directory specified by -system_image_dir.");
Ram Muthiah1aa02f82019-10-22 20:26:28 +000070DEFINE_string(vendor_boot_image, "",
71 "Location of cuttlefish vendor boot image. If empty it is assumed to "
72 "be vendor_boot.img in the directory specified by -system_image_dir.");
Cody Schuffelen20ecaca2019-01-29 17:43:38 -080073DEFINE_int32(memory_mb, 2048,
74 "Total amount of memory available for guest, MB.");
Cody Schuffelen47c57852019-12-13 13:50:50 -080075DEFINE_string(serial_number, ForCurrentInstance("CUTTLEFISHCVD"),
Cody Schuffelen20ecaca2019-01-29 17:43:38 -080076 "Serial number to use for the device");
Cody Schuffelenab6d3452019-12-13 15:54:27 -080077DEFINE_string(assembly_dir,
78 cvd::StringFromEnv("HOME", ".") + "/cuttlefish_assembly",
79 "A directory to put generated files common between instances");
80DEFINE_string(instance_dir,
81 cvd::StringFromEnv("HOME", ".") + "/cuttlefish_runtime",
Cody Schuffelen20ecaca2019-01-29 17:43:38 -080082 "A directory to put all instance specific files");
83DEFINE_string(
Alistair Strachan5ab095c2019-05-23 20:41:20 +000084 vm_manager, vm_manager::CrosvmManager::name(),
Jorge E. Moreiraba626622019-01-28 17:47:50 -080085 "What virtual machine manager to use, one of {qemu_cli, crosvm}");
Greg Hartmana3c552d2019-03-28 18:20:48 -070086DEFINE_string(
Greg Hartmanbc1bed42019-04-05 20:02:00 -070087 gpu_mode, vsoc::kGpuModeGuestSwiftshader,
88 "What gpu configuration to use, one of {guest_swiftshader, drm_virgl}");
Greg Hartmana3c552d2019-03-28 18:20:48 -070089
Cody Schuffelen20ecaca2019-01-29 17:43:38 -080090DEFINE_string(system_image_dir, vsoc::DefaultGuestImagePath(""),
91 "Location of the system partition images.");
Alistair Strachan050ca932018-11-27 12:41:19 -080092DEFINE_string(super_image, "", "Location of the super partition image.");
Yifan Hong19d713e2019-05-01 14:12:07 -070093DEFINE_string(misc_image, "",
94 "Location of the misc partition image. If the image does not "
95 "exist, a blank new misc partition image is created.");
Cody Schuffelenb3f07b62019-12-26 16:28:17 -080096DEFINE_string(composite_disk, "", "Location of the composite disk image. ");
Cody Schuffelen20ecaca2019-01-29 17:43:38 -080097
98DEFINE_bool(deprecated_boot_completed, false, "Log boot completed message to"
99 " host kernel. This is only used during transition of our clients."
100 " Will be deprecated soon.");
Cody Schuffelen3e745bf2020-01-16 17:26:41 -0800101DEFINE_bool(start_vnc_server, false, "Whether to start the vnc server process. "
102 "The VNC server runs at port 6443 + i for "
103 "the vsoc-i user or CUTTLEFISH_INSTANCE=i, "
104 "starting from 1.");
Jorge E. Moreirae049b792019-12-18 18:17:48 -0800105
106DEFINE_bool(start_webrtc, false, "Whether to start the webrtc process.");
107
108DEFINE_string(
109 webrtc_assets_dir,
Jorge E. Moreira1f65a4a2019-11-08 15:23:32 -0800110 vsoc::DefaultHostArtifactsPath("usr/share/webrtc/assets"),
Jorge E. Moreirae049b792019-12-18 18:17:48 -0800111 "Path to WebRTC webpage assets.");
112
113DEFINE_string(
114 webrtc_certs_dir,
Jorge E. Moreira1f65a4a2019-11-08 15:23:32 -0800115 vsoc::DefaultHostArtifactsPath("usr/share/webrtc/certs"),
Jorge E. Moreirae049b792019-12-18 18:17:48 -0800116 "Path to WebRTC certificates directory.");
117
118DEFINE_string(
119 webrtc_public_ip,
Jorge E. Moreira1f65a4a2019-11-08 15:23:32 -0800120 "127.0.0.1",
Jorge E. Moreirae049b792019-12-18 18:17:48 -0800121 "Public IPv4 address of your server, a.b.c.d format");
122
123DEFINE_bool(
124 webrtc_enable_adb_websocket,
125 false,
126 "If enabled, exposes local adb service through a websocket.");
127
Cody Schuffelen10743332019-04-15 16:50:49 -0700128DEFINE_string(adb_mode, "vsock_half_tunnel",
Cody Schuffelen3c35fd82019-12-11 18:39:46 -0800129 "Mode for ADB connection."
Cody Schuffelen63d10052019-02-26 12:21:53 -0800130 "'vsock_tunnel' for a TCP connection tunneled through vsock, "
131 "'native_vsock' for a direct connection to the guest ADB over "
132 "vsock, 'vsock_half_tunnel' for a TCP connection forwarded to "
133 "the guest ADB server, or a comma separated list of types as in "
Cody Schuffelen3c35fd82019-12-11 18:39:46 -0800134 "'native_vsock,vsock_half_tunnel'");
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800135DEFINE_bool(run_adb_connector, true,
136 "Maintain adb connection by sending 'adb connect' commands to the "
Matthias Maennich454d7872019-02-06 16:35:17 +0000137 "server. Only relevant with -adb_mode=tunnel or vsock_tunnel");
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800138
Cody Schuffelen47c57852019-12-13 13:50:50 -0800139DEFINE_string(uuid, vsoc::ForCurrentInstance(vsoc::kDefaultUuidPrefix),
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800140 "UUID to use for the device. Random if not specified");
141DEFINE_bool(daemon, false,
142 "Run cuttlefish in background, the launcher exits on boot "
143 "completed/failed");
144
145DEFINE_string(device_title, "", "Human readable name for the instance, "
146 "used by the vnc_server for its server title");
147DEFINE_string(setupwizard_mode, "DISABLED",
148 "One of DISABLED,OPTIONAL,REQUIRED");
149
150DEFINE_string(qemu_binary,
151 "/usr/bin/qemu-system-x86_64",
152 "The qemu binary to use");
Jorge E. Moreiraba626622019-01-28 17:47:50 -0800153DEFINE_string(crosvm_binary,
154 vsoc::DefaultHostArtifactsPath("bin/crosvm"),
155 "The Crosvm binary to use");
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800156DEFINE_bool(restart_subprocesses, true, "Restart any crashed host process");
Jorge E. Moreirafd10cae2019-02-19 15:35:42 -0800157DEFINE_string(logcat_mode, "", "How to send android's log messages from "
158 "guest to host. One of [serial, vsock]");
Ram Muthiah6e9c98c2019-05-28 15:18:27 -0700159DEFINE_bool(enable_tombstone_receiver, true, "Enables the tombstone logger on "
Ram Muthiah792e2ad2019-04-19 11:19:46 -0700160 "both the guest and the host");
Cody Schuffelen1300f122019-05-28 18:24:34 -0700161DEFINE_bool(use_bootloader, false, "Boots the device using a bootloader");
162DEFINE_string(bootloader, "", "Bootloader binary path");
David Anderson637bfd62019-09-26 13:23:21 -0700163DEFINE_string(boot_slot, "", "Force booting into the given slot. If empty, "
164 "the slot will be chosen based on the misc partition if using a "
165 "bootloader. It will default to 'a' if empty and not using a "
166 "bootloader.");
Cody Schuffelen097ad9f2020-01-16 18:40:38 -0800167DEFINE_int32(num_instances, 1, "Number of Android guests to launch");
A. Cody Schuffelenc17acda2020-01-23 15:54:40 -0800168DEFINE_bool(resume, true, "Resume using the disk from the last session, if "
169 "possible. i.e., if --noresume is passed, the disk "
170 "will be reset to the state it was initially launched "
171 "in. This flag is ignored if the underlying partition "
172 "images have been updated since the first launch.");
Yifan Hong19d713e2019-05-01 14:12:07 -0700173
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800174namespace {
175
Cody Schuffelencd3563a2019-10-29 16:35:06 -0700176const std::string kKernelDefaultPath = "kernel";
177const std::string kInitramfsImg = "initramfs.img";
178const std::string kRamdiskConcatExt = ".concat";
Cody Schuffelen9fd95472019-10-04 13:49:57 -0700179
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800180bool ResolveInstanceFiles() {
181 if (FLAGS_system_image_dir.empty()) {
182 LOG(ERROR) << "--system_image_dir must be specified.";
183 return false;
184 }
185
186 // If user did not specify location of either of these files, expect them to
187 // be placed in --system_image_dir location.
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800188 std::string default_boot_image = FLAGS_system_image_dir + "/boot.img";
189 SetCommandLineOptionWithMode("boot_image", default_boot_image.c_str(),
190 google::FlagSettingMode::SET_FLAGS_DEFAULT);
191 std::string default_cache_image = FLAGS_system_image_dir + "/cache.img";
192 SetCommandLineOptionWithMode("cache_image", default_cache_image.c_str(),
193 google::FlagSettingMode::SET_FLAGS_DEFAULT);
194 std::string default_data_image = FLAGS_system_image_dir + "/userdata.img";
195 SetCommandLineOptionWithMode("data_image", default_data_image.c_str(),
196 google::FlagSettingMode::SET_FLAGS_DEFAULT);
Paul Trautrimba8f8e92019-03-12 17:55:48 +0900197 std::string default_metadata_image = FLAGS_system_image_dir + "/metadata.img";
198 SetCommandLineOptionWithMode("metadata_image", default_metadata_image.c_str(),
199 google::FlagSettingMode::SET_FLAGS_DEFAULT);
Alistair Strachan050ca932018-11-27 12:41:19 -0800200 std::string default_super_image = FLAGS_system_image_dir + "/super.img";
201 SetCommandLineOptionWithMode("super_image", default_super_image.c_str(),
202 google::FlagSettingMode::SET_FLAGS_DEFAULT);
Yifan Hong19d713e2019-05-01 14:12:07 -0700203 std::string default_misc_image = FLAGS_system_image_dir + "/misc.img";
204 SetCommandLineOptionWithMode("misc_image", default_misc_image.c_str(),
205 google::FlagSettingMode::SET_FLAGS_DEFAULT);
David Anderson64581ce2019-10-03 17:52:22 -0700206 std::string default_composite_disk = FLAGS_system_image_dir + "/composite.img";
207 SetCommandLineOptionWithMode("composite_disk", default_composite_disk.c_str(),
208 google::FlagSettingMode::SET_FLAGS_DEFAULT);
Ram Muthiah1aa02f82019-10-22 20:26:28 +0000209 std::string default_vendor_boot_image = FLAGS_system_image_dir
210 + "/vendor_boot.img";
211 SetCommandLineOptionWithMode("vendor_boot_image",
212 default_vendor_boot_image.c_str(),
213 google::FlagSettingMode::SET_FLAGS_DEFAULT);
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800214
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800215 return true;
216}
217
218std::string GetCuttlefishEnvPath() {
219 return cvd::StringFromEnv("HOME", ".") + "/.cuttlefish.sh";
220}
221
Cody Schuffelen2168c242019-12-13 16:15:27 -0800222std::string GetLegacyConfigFilePath(const vsoc::CuttlefishConfig& config) {
223 return config.ForDefaultInstance().PerInstancePath("cuttlefish_config.json");
224}
225
Jorge E. Moreirae049b792019-12-18 18:17:48 -0800226int NumStreamers() {
227 auto start_flags = {FLAGS_start_vnc_server, FLAGS_start_webrtc};
228 return std::count(start_flags.begin(), start_flags.end(), true);
229}
230
Cody Schuffelen3e745bf2020-01-16 17:26:41 -0800231std::string StrForInstance(const std::string& prefix, int num) {
232 std::ostringstream stream;
233 stream << prefix << std::setfill('0') << std::setw(2) << num;
234 return stream.str();
235}
236
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800237// Initializes the config object and saves it to file. It doesn't return it, all
238// further uses of the config should happen through the singleton
Cody Schuffelen1d054bb2020-01-16 17:16:51 -0800239vsoc::CuttlefishConfig InitializeCuttlefishConfiguration(
Cody Schuffelencd3563a2019-10-29 16:35:06 -0700240 const cvd::BootImageUnpacker& boot_image_unpacker,
241 const cvd::FetcherConfig& fetcher_config) {
Jorge E. Moreirae049b792019-12-18 18:17:48 -0800242 // At most one streamer can be started.
243 CHECK(NumStreamers() <= 1);
244
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800245 vsoc::CuttlefishConfig tmp_config_obj;
Cody Schuffelenab6d3452019-12-13 15:54:27 -0800246 tmp_config_obj.set_assembly_dir(FLAGS_assembly_dir);
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800247 if (!vm_manager::VmManager::IsValidName(FLAGS_vm_manager)) {
Cody Schuffelen1d054bb2020-01-16 17:16:51 -0800248 LOG(FATAL) << "Invalid vm_manager: " << FLAGS_vm_manager;
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800249 }
Greg Hartmana3c552d2019-03-28 18:20:48 -0700250 if (!vm_manager::VmManager::IsValidName(FLAGS_vm_manager)) {
Cody Schuffelen1d054bb2020-01-16 17:16:51 -0800251 LOG(FATAL) << "Invalid vm_manager: " << FLAGS_vm_manager;
Greg Hartmana3c552d2019-03-28 18:20:48 -0700252 }
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800253 tmp_config_obj.set_vm_manager(FLAGS_vm_manager);
Greg Hartmana3c552d2019-03-28 18:20:48 -0700254 tmp_config_obj.set_gpu_mode(FLAGS_gpu_mode);
Cody Schuffelen2de6ead2019-12-04 16:16:47 -0800255 if (vm_manager::VmManager::ConfigureGpuMode(tmp_config_obj.vm_manager(),
256 tmp_config_obj.gpu_mode()).empty()) {
Cody Schuffelen1d054bb2020-01-16 17:16:51 -0800257 LOG(FATAL) << "Invalid gpu_mode=" << FLAGS_gpu_mode <<
Greg Hartmana3c552d2019-03-28 18:20:48 -0700258 " does not work with vm_manager=" << FLAGS_vm_manager;
Greg Hartmana3c552d2019-03-28 18:20:48 -0700259 }
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800260
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800261 tmp_config_obj.set_cpus(FLAGS_cpus);
262 tmp_config_obj.set_memory_mb(FLAGS_memory_mb);
263
264 tmp_config_obj.set_dpi(FLAGS_dpi);
265 tmp_config_obj.set_setupwizard_mode(FLAGS_setupwizard_mode);
266 tmp_config_obj.set_x_res(FLAGS_x_res);
267 tmp_config_obj.set_y_res(FLAGS_y_res);
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800268 tmp_config_obj.set_refresh_rate_hz(FLAGS_refresh_rate_hz);
269 tmp_config_obj.set_gdb_flag(FLAGS_qemu_gdb);
Cody Schuffelenf4a1cdb2019-11-13 16:51:16 -0800270 std::vector<std::string> adb = android::base::Split(FLAGS_adb_mode, ",");
Cody Schuffelen90b2fb22019-02-28 18:55:21 -0800271 tmp_config_obj.set_adb_mode(std::set<std::string>(adb.begin(), adb.end()));
Cody Schuffelencd3563a2019-10-29 16:35:06 -0700272 std::string discovered_kernel = fetcher_config.FindCvdFileWithSuffix(kKernelDefaultPath);
273 std::string foreign_kernel = FLAGS_kernel_path.size() ? FLAGS_kernel_path : discovered_kernel;
274 if (foreign_kernel.size()) {
275 tmp_config_obj.set_kernel_image_path(foreign_kernel);
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800276 tmp_config_obj.set_use_unpacked_kernel(false);
277 } else {
278 tmp_config_obj.set_kernel_image_path(
Cody Schuffelenf53ded12019-12-13 16:05:22 -0800279 tmp_config_obj.AssemblyPath(kKernelDefaultPath.c_str()));
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800280 tmp_config_obj.set_use_unpacked_kernel(true);
281 }
Jorge E. Moreira80ddd7f2019-02-04 16:30:13 -0800282 tmp_config_obj.set_decompress_kernel(FLAGS_decompress_kernel);
283 if (FLAGS_decompress_kernel) {
284 tmp_config_obj.set_decompressed_kernel_image_path(
Cody Schuffelenf53ded12019-12-13 16:05:22 -0800285 tmp_config_obj.AssemblyPath("vmlinux"));
Jorge E. Moreira80ddd7f2019-02-04 16:30:13 -0800286 }
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800287
Cody Schuffelenf53ded12019-12-13 16:05:22 -0800288 auto ramdisk_path = tmp_config_obj.AssemblyPath("ramdisk.img");
289 auto vendor_ramdisk_path = tmp_config_obj.AssemblyPath("vendor_ramdisk.img");
Cody Schuffelen1e645542019-11-19 15:44:22 -0800290 if (!boot_image_unpacker.HasRamdiskImage()) {
Cody Schuffelen1d054bb2020-01-16 17:16:51 -0800291 LOG(FATAL) << "A ramdisk is required, but the boot image did not have one.";
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800292 }
293
Cody Schuffelen2de6ead2019-12-04 16:16:47 -0800294 tmp_config_obj.set_boot_image_kernel_cmdline(boot_image_unpacker.kernel_cmdline());
295 tmp_config_obj.set_loop_max_part(FLAGS_loop_max_part);
296 tmp_config_obj.set_guest_enforce_security(FLAGS_guest_enforce_security);
297 tmp_config_obj.set_guest_audit_security(FLAGS_guest_audit_security);
Alistair Delva33b861f2019-12-26 12:23:59 -0800298 tmp_config_obj.set_guest_force_normal_boot(FLAGS_guest_force_normal_boot);
Cody Schuffelen2de6ead2019-12-04 16:16:47 -0800299 tmp_config_obj.set_extra_kernel_cmdline(FLAGS_extra_kernel_cmdline);
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800300
301 tmp_config_obj.set_ramdisk_image_path(ramdisk_path);
Ram Muthiahd512c132019-10-23 17:20:45 -0700302 tmp_config_obj.set_vendor_ramdisk_image_path(vendor_ramdisk_path);
303
Cody Schuffelencd3563a2019-10-29 16:35:06 -0700304 std::string discovered_ramdisk = fetcher_config.FindCvdFileWithSuffix(kInitramfsImg);
305 std::string foreign_ramdisk = FLAGS_initramfs_path.size () ? FLAGS_initramfs_path : discovered_ramdisk;
306 if (foreign_kernel.size() && !foreign_ramdisk.size()) {
Ram Muthiahd512c132019-10-23 17:20:45 -0700307 // If there's a kernel that's passed in without an initramfs, that implies
308 // user error or a kernel built with no modules. In either case, let's
309 // choose to avoid loading the modules from the vendor ramdisk which are
310 // built for the default cf kernel. Once boot occurs, user error will
311 // become obvious.
312 tmp_config_obj.set_final_ramdisk_path(ramdisk_path);
313 } else {
314 tmp_config_obj.set_final_ramdisk_path(ramdisk_path + kRamdiskConcatExt);
Cody Schuffelencd3563a2019-10-29 16:35:06 -0700315 if(foreign_ramdisk.size()) {
316 tmp_config_obj.set_initramfs_path(foreign_ramdisk);
Ram Muthiahd512c132019-10-23 17:20:45 -0700317 }
Cody Schuffelen9fd95472019-10-04 13:49:57 -0700318 }
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800319
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800320 tmp_config_obj.set_deprecated_boot_completed(FLAGS_deprecated_boot_completed);
Cody Schuffelen3dff6982019-12-05 16:24:12 -0800321 tmp_config_obj.set_logcat_receiver_binary(
322 vsoc::DefaultHostArtifactsPath("bin/logcat_receiver"));
323 tmp_config_obj.set_config_server_binary(
324 vsoc::DefaultHostArtifactsPath("bin/config_server"));
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800325
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800326 tmp_config_obj.set_qemu_binary(FLAGS_qemu_binary);
Jorge E. Moreiraba626622019-01-28 17:47:50 -0800327 tmp_config_obj.set_crosvm_binary(FLAGS_crosvm_binary);
Cody Schuffelen3dff6982019-12-05 16:24:12 -0800328 tmp_config_obj.set_console_forwarder_binary(
329 vsoc::DefaultHostArtifactsPath("bin/console_forwarder"));
330 tmp_config_obj.set_kernel_log_monitor_binary(
331 vsoc::DefaultHostArtifactsPath("bin/kernel_log_monitor"));
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800332
333 tmp_config_obj.set_enable_vnc_server(FLAGS_start_vnc_server);
Cody Schuffelen3dff6982019-12-05 16:24:12 -0800334 tmp_config_obj.set_vnc_server_binary(
335 vsoc::DefaultHostArtifactsPath("bin/vnc_server"));
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800336
Jorge E. Moreirae049b792019-12-18 18:17:48 -0800337 tmp_config_obj.set_enable_webrtc(FLAGS_start_webrtc);
338 tmp_config_obj.set_webrtc_binary(
339 vsoc::DefaultHostArtifactsPath("bin/webRTC"));
340 tmp_config_obj.set_webrtc_assets_dir(FLAGS_webrtc_assets_dir);
341 tmp_config_obj.set_webrtc_public_ip(FLAGS_webrtc_public_ip);
342 tmp_config_obj.set_webrtc_certs_dir(FLAGS_webrtc_certs_dir);
343
344 tmp_config_obj.set_webrtc_enable_adb_websocket(
345 FLAGS_webrtc_enable_adb_websocket);
346
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800347 tmp_config_obj.set_restart_subprocesses(FLAGS_restart_subprocesses);
348 tmp_config_obj.set_run_adb_connector(FLAGS_run_adb_connector);
Cody Schuffelen3dff6982019-12-05 16:24:12 -0800349 tmp_config_obj.set_adb_connector_binary(
350 vsoc::DefaultHostArtifactsPath("bin/adb_connector"));
Cody Schuffelen3dff6982019-12-05 16:24:12 -0800351 tmp_config_obj.set_socket_vsock_proxy_binary(
352 vsoc::DefaultHostArtifactsPath("bin/socket_vsock_proxy"));
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800353 tmp_config_obj.set_run_as_daemon(FLAGS_daemon);
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800354
Cody Schuffelen2b51bab2019-01-29 18:14:48 -0800355 tmp_config_obj.set_data_policy(FLAGS_data_policy);
356 tmp_config_obj.set_blank_data_image_mb(FLAGS_blank_data_image_mb);
357 tmp_config_obj.set_blank_data_image_fmt(FLAGS_blank_data_image_fmt);
358
Jorge E. Moreirafd10cae2019-02-19 15:35:42 -0800359 tmp_config_obj.set_logcat_mode(FLAGS_logcat_mode);
Jorge E. Moreirafd10cae2019-02-19 15:35:42 -0800360
Ram Muthiah792e2ad2019-04-19 11:19:46 -0700361 tmp_config_obj.set_enable_tombstone_receiver(FLAGS_enable_tombstone_receiver);
Cody Schuffelen3dff6982019-12-05 16:24:12 -0800362 tmp_config_obj.set_tombstone_receiver_binary(
363 vsoc::DefaultHostArtifactsPath("bin/tombstone_receiver"));
Ram Muthiah792e2ad2019-04-19 11:19:46 -0700364
Cody Schuffelen1300f122019-05-28 18:24:34 -0700365 tmp_config_obj.set_use_bootloader(FLAGS_use_bootloader);
366 tmp_config_obj.set_bootloader(FLAGS_bootloader);
367
David Anderson637bfd62019-09-26 13:23:21 -0700368 if (!FLAGS_boot_slot.empty()) {
369 tmp_config_obj.set_boot_slot(FLAGS_boot_slot);
370 }
371
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800372 tmp_config_obj.set_cuttlefish_env_path(GetCuttlefishEnvPath());
373
Cody Schuffelen097ad9f2020-01-16 18:40:38 -0800374 std::vector<int> instance_nums;
375 for (int i = 0; i < FLAGS_num_instances; i++) {
376 instance_nums.push_back(vsoc::GetInstance() + i);
377 }
Cody Schuffelenb7cfa0d2020-01-16 16:08:14 -0800378
Cody Schuffelenaff3fcf2020-01-16 16:46:15 -0800379 for (const auto& num : instance_nums) {
380 auto instance = tmp_config_obj.ForInstance(num);
381 auto const_instance = const_cast<const vsoc::CuttlefishConfig&>(tmp_config_obj)
382 .ForInstance(num);
383 // Set this first so that calls to PerInstancePath below are correct
Cody Schuffelen3e745bf2020-01-16 17:26:41 -0800384 instance.set_instance_dir(FLAGS_instance_dir + "." + std::to_string(num));
385 instance.set_serial_number(FLAGS_serial_number + std::to_string(num));
Cody Schuffelenb7cfa0d2020-01-16 16:08:14 -0800386
Cody Schuffelen3e745bf2020-01-16 17:26:41 -0800387 instance.set_mobile_bridge_name(StrForInstance("cvd-mbr-", num));
388 instance.set_mobile_tap_name(StrForInstance("cvd-mtap-", num));
Cody Schuffelenb7cfa0d2020-01-16 16:08:14 -0800389
Cody Schuffelen3e745bf2020-01-16 17:26:41 -0800390 instance.set_wifi_tap_name(StrForInstance("cvd-wtap-", num));
Cody Schuffelenb7cfa0d2020-01-16 16:08:14 -0800391
Cody Schuffelen3e745bf2020-01-16 17:26:41 -0800392 instance.set_vsock_guest_cid(3 + num - 1);
Cody Schuffelenb7cfa0d2020-01-16 16:08:14 -0800393
Cody Schuffelenaff3fcf2020-01-16 16:46:15 -0800394 instance.set_uuid(FLAGS_uuid);
Cody Schuffelenb7cfa0d2020-01-16 16:08:14 -0800395
Cody Schuffelen3e745bf2020-01-16 17:26:41 -0800396 instance.set_vnc_server_port(6444 + num - 1);
397 instance.set_host_port(6520 + num - 1);
398 instance.set_adb_ip_and_port("127.0.0.1:" + std::to_string(6520 + num - 1));
Cody Schuffelenb7cfa0d2020-01-16 16:08:14 -0800399
Cody Schuffelenaff3fcf2020-01-16 16:46:15 -0800400 instance.set_device_title(FLAGS_device_title);
401
402 instance.set_virtual_disk_paths({const_instance.PerInstancePath("overlay.img")});
403 }
Cody Schuffelenb7cfa0d2020-01-16 16:08:14 -0800404
Cody Schuffelen1d054bb2020-01-16 17:16:51 -0800405 return tmp_config_obj;
406}
407
408bool SaveConfig(const vsoc::CuttlefishConfig& tmp_config_obj) {
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800409 auto config_file = GetConfigFilePath(tmp_config_obj);
410 auto config_link = vsoc::GetGlobalConfigFileLink();
411 // Save the config object before starting any host process
412 if (!tmp_config_obj.SaveToFile(config_file)) {
413 LOG(ERROR) << "Unable to save config object";
414 return false;
415 }
Cody Schuffelen2168c242019-12-13 16:15:27 -0800416 auto legacy_config_file = GetLegacyConfigFilePath(tmp_config_obj);
417 if (!tmp_config_obj.SaveToFile(legacy_config_file)) {
418 LOG(ERROR) << "Unable to save legacy config object";
419 return false;
420 }
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800421 setenv(vsoc::kCuttlefishConfigEnvVarName, config_file.c_str(), true);
422 if (symlink(config_file.c_str(), config_link.c_str()) != 0) {
423 LOG(ERROR) << "Failed to create symlink to config file at " << config_link
424 << ": " << strerror(errno);
425 return false;
426 }
427
428 return true;
429}
430
431void SetDefaultFlagsForQemu() {
Cody Schuffelen038d4d92019-11-04 15:09:03 -0800432 // TODO(b/144119457) Use the serial port.
433 SetCommandLineOptionWithMode("logcat_mode", cvd::kLogcatVsockMode,
Jorge E. Moreirafd10cae2019-02-19 15:35:42 -0800434 google::FlagSettingMode::SET_FLAGS_DEFAULT);
Jorge E. Moreiraba626622019-01-28 17:47:50 -0800435}
436
437void SetDefaultFlagsForCrosvm() {
Jorge E. Moreirafd10cae2019-02-19 15:35:42 -0800438 SetCommandLineOptionWithMode("logcat_mode", cvd::kLogcatVsockMode,
439 google::FlagSettingMode::SET_FLAGS_DEFAULT);
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800440}
441
442bool ParseCommandLineFlags(int* argc, char*** argv) {
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800443 google::ParseCommandLineNonHelpFlags(argc, argv, true);
444 bool invalid_manager = false;
445 if (FLAGS_vm_manager == vm_manager::QemuManager::name()) {
446 SetDefaultFlagsForQemu();
Jorge E. Moreiraba626622019-01-28 17:47:50 -0800447 } else if (FLAGS_vm_manager == vm_manager::CrosvmManager::name()) {
448 SetDefaultFlagsForCrosvm();
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800449 } else {
450 std::cerr << "Unknown Virtual Machine Manager: " << FLAGS_vm_manager
451 << std::endl;
452 invalid_manager = true;
453 }
Jorge E. Moreira1f65a4a2019-11-08 15:23:32 -0800454 if (NumStreamers() == 0) {
455 // This makes the vnc server the default streamer unless the user requests
456 // another via a --star_<streamer> flag, while at the same time it's
457 // possible to run without any streamer by setting --start_vnc_server=false.
458 SetCommandLineOptionWithMode("start_vnc_server", "true",
459 google::FlagSettingMode::SET_FLAGS_DEFAULT);
460 }
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800461 google::HandleCommandLineHelpFlags();
462 if (invalid_manager) {
463 return false;
464 }
465 // Set the env variable to empty (in case the caller passed a value for it).
466 unsetenv(vsoc::kCuttlefishConfigEnvVarName);
467
468 return ResolveInstanceFiles();
469}
470
A. Cody Schuffelenc17acda2020-01-23 15:54:40 -0800471std::string cpp_basename(const std::string& str) {
472 char* copy = strdup(str.c_str()); // basename may modify its argument
473 std::string ret(basename(copy));
474 free(copy);
475 return ret;
476}
477
478bool CleanPriorFiles(const std::string& path, const std::set<std::string>& preserving) {
479 if (preserving.count(cpp_basename(path))) {
480 LOG(INFO) << "Preserving: " << path;
481 return true;
482 }
483 struct stat statbuf;
484 if (lstat(path.c_str(), &statbuf) < 0) {
485 int error_num = errno;
486 if (error_num == ENOENT) {
487 return true;
488 } else {
489 LOG(ERROR) << "Could not stat \"" << path << "\": " << strerror(error_num);
490 return false;
491 }
492 }
493 if ((statbuf.st_mode & S_IFMT) != S_IFDIR) {
494 LOG(INFO) << "Deleting: " << path;
495 if (unlink(path.c_str()) < 0) {
496 int error_num = errno;
497 LOG(ERROR) << "Could not unlink \"" << path << "\", error was " << strerror(error_num);
498 return false;
499 }
500 return true;
501 }
502 std::unique_ptr<DIR, int(*)(DIR*)> dir(opendir(path.c_str()), closedir);
503 if (!dir) {
504 int error_num = errno;
505 LOG(ERROR) << "Could not clean \"" << path << "\": error was " << strerror(error_num);
506 return false;
507 }
508 for (auto entity = readdir(dir.get()); entity != nullptr; entity = readdir(dir.get())) {
509 std::string entity_name(entity->d_name);
510 if (entity_name == "." || entity_name == "..") {
511 continue;
512 }
513 std::string entity_path = path + "/" + entity_name;
514 if (!CleanPriorFiles(entity_path.c_str(), preserving)) {
515 return false;
516 }
517 }
518 if (rmdir(path.c_str()) < 0) {
519 if (!(errno == EEXIST || errno == ENOTEMPTY)) {
520 // If EEXIST or ENOTEMPTY, probably because a file was preserved
521 int error_num = errno;
522 LOG(ERROR) << "Could not rmdir \"" << path << "\", error was " << strerror(error_num);
523 return false;
524 }
525 }
526 return true;
527}
528
529bool CleanPriorFiles(const std::vector<std::string>& paths, const std::set<std::string>& preserving) {
530 std::string prior_files;
531 for (auto path : paths) {
532 struct stat statbuf;
533 if (stat(path.c_str(), &statbuf) < 0 && errno != ENOENT) {
534 // If ENOENT, it doesn't exist yet, so there is no work to do'
535 int error_num = errno;
536 LOG(ERROR) << "Could not stat \"" << path << "\": " << strerror(error_num);
537 return false;
538 }
539 bool is_directory = (statbuf.st_mode & S_IFMT) == S_IFDIR;
540 prior_files += (is_directory ? (path + "/*") : path) + " ";
541 }
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800542 LOG(INFO) << "Assuming prior files of " << prior_files;
Alistair Delva7f09b732020-01-30 18:18:12 -0800543 std::string lsof_cmd = "lsof -t " + prior_files + " >/dev/null 2>&1";
544 int rval = std::system(lsof_cmd.c_str());
545 // lsof returns 0 if any of the files are open
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800546 if (WEXITSTATUS(rval) == 0) {
547 LOG(ERROR) << "Clean aborted: files are in use";
548 return false;
549 }
A. Cody Schuffelenc17acda2020-01-23 15:54:40 -0800550 for (const auto& path : paths) {
551 if (!CleanPriorFiles(path, preserving)) {
552 LOG(ERROR) << "Remove of file under \"" << path << "\" failed";
553 return false;
554 }
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800555 }
556 return true;
557}
Jorge E. Moreira80ddd7f2019-02-04 16:30:13 -0800558
A. Cody Schuffelenc17acda2020-01-23 15:54:40 -0800559bool CleanPriorFiles(const vsoc::CuttlefishConfig& config, const std::set<std::string>& preserving) {
Cody Schuffelenb2ca6a32020-01-16 16:53:50 -0800560 std::vector<std::string> paths = {
Cody Schuffelenb2ca6a32020-01-16 16:53:50 -0800561 // Everything in the assembly directory
A. Cody Schuffelenc17acda2020-01-23 15:54:40 -0800562 FLAGS_assembly_dir,
Cody Schuffelenb2ca6a32020-01-16 16:53:50 -0800563 // The environment file
564 GetCuttlefishEnvPath(),
565 // The global link to the config file
566 vsoc::GetGlobalConfigFileLink(),
567 };
Cody Schuffelen1d054bb2020-01-16 17:16:51 -0800568 for (const auto& instance : config.Instances()) {
569 paths.push_back(instance.instance_dir());
570 }
A. Cody Schuffelenc17acda2020-01-23 15:54:40 -0800571 return CleanPriorFiles(paths, preserving);
Cody Schuffelenb2ca6a32020-01-16 16:53:50 -0800572}
573
Jorge E. Moreira80ddd7f2019-02-04 16:30:13 -0800574bool DecompressKernel(const std::string& src, const std::string& dst) {
Cody Schuffelen3dff6982019-12-05 16:24:12 -0800575 cvd::Command decomp_cmd(vsoc::DefaultHostArtifactsPath("bin/extract-vmlinux"));
Jorge E. Moreira80ddd7f2019-02-04 16:30:13 -0800576 decomp_cmd.AddParameter(src);
577 auto output_file = cvd::SharedFD::Creat(dst.c_str(), 0666);
578 if (!output_file->IsOpen()) {
579 LOG(ERROR) << "Unable to create decompressed image file: "
580 << output_file->StrError();
581 return false;
582 }
583 decomp_cmd.RedirectStdIO(cvd::Subprocess::StdIOChannel::kStdOut, output_file);
Cody Schuffelene5670872019-12-10 15:04:59 -0800584 auto decomp_proc = decomp_cmd.Start();
Jorge E. Moreira80ddd7f2019-02-04 16:30:13 -0800585 return decomp_proc.Started() && decomp_proc.Wait() == 0;
586}
Cody Schuffelen78824ed2019-09-06 17:43:15 -0700587
588void ValidateAdbModeFlag(const vsoc::CuttlefishConfig& config) {
589 auto adb_modes = config.adb_mode();
590 adb_modes.erase(vsoc::AdbMode::Unknown);
591 if (adb_modes.size() < 1) {
592 LOG(INFO) << "ADB not enabled";
593 }
594}
595
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800596} // namespace
597
Cody Schuffelen3c99f5b2019-06-14 17:26:01 -0700598namespace {
599
600std::vector<ImagePartition> disk_config() {
601 std::vector<ImagePartition> partitions;
Cody Schuffelen4f7e4412019-08-30 16:10:59 -0700602 partitions.push_back(ImagePartition {
603 .label = "super",
604 .image_file_path = FLAGS_super_image,
605 });
Cody Schuffelen3c99f5b2019-06-14 17:26:01 -0700606 partitions.push_back(ImagePartition {
607 .label = "userdata",
608 .image_file_path = FLAGS_data_image,
609 });
610 partitions.push_back(ImagePartition {
611 .label = "cache",
612 .image_file_path = FLAGS_cache_image,
613 });
614 partitions.push_back(ImagePartition {
615 .label = "metadata",
616 .image_file_path = FLAGS_metadata_image,
617 });
Cody Schuffelen3c99f5b2019-06-14 17:26:01 -0700618 partitions.push_back(ImagePartition {
619 .label = "boot",
620 .image_file_path = FLAGS_boot_image,
621 });
Yifan Hong19d713e2019-05-01 14:12:07 -0700622 partitions.push_back(ImagePartition {
623 .label = "misc",
624 .image_file_path = FLAGS_misc_image
625 });
Cody Schuffelen3c99f5b2019-06-14 17:26:01 -0700626 return partitions;
627}
628
A. Cody Schuffelenc17acda2020-01-23 15:54:40 -0800629std::chrono::system_clock::time_point LastUpdatedInputDisk() {
630 std::chrono::system_clock::time_point ret;
Cody Schuffelen3c99f5b2019-06-14 17:26:01 -0700631 for (auto& partition : disk_config()) {
A. Cody Schuffelenc17acda2020-01-23 15:54:40 -0800632 auto partition_mod_time = cvd::FileModificationTime(partition.image_file_path);
633 if (partition_mod_time > ret) {
634 ret = partition_mod_time;
Cody Schuffelen3c99f5b2019-06-14 17:26:01 -0700635 }
636 }
A. Cody Schuffelenc17acda2020-01-23 15:54:40 -0800637 return ret;
638}
639
640bool ShouldCreateCompositeDisk() {
641 auto composite_age = cvd::FileModificationTime(FLAGS_composite_disk);
642 return composite_age < LastUpdatedInputDisk();
Cody Schuffelen3c99f5b2019-06-14 17:26:01 -0700643}
644
Ram Muthiah3db0a562019-08-26 13:35:19 -0700645bool ConcatRamdisks(const std::string& new_ramdisk_path, const std::string& ramdisk_a_path,
646 const std::string& ramdisk_b_path) {
647 // clear out file of any pre-existing content
648 std::ofstream new_ramdisk(new_ramdisk_path, std::ios_base::binary | std::ios_base::trunc);
649 std::ifstream ramdisk_a(ramdisk_a_path, std::ios_base::binary);
650 std::ifstream ramdisk_b(ramdisk_b_path, std::ios_base::binary);
Ram Muthiahaad97c52019-08-14 17:05:01 -0700651
Ram Muthiah3db0a562019-08-26 13:35:19 -0700652 if(!new_ramdisk.is_open() || !ramdisk_a.is_open() || !ramdisk_b.is_open()) {
Ram Muthiahaad97c52019-08-14 17:05:01 -0700653 return false;
654 }
655
Ram Muthiah3db0a562019-08-26 13:35:19 -0700656 new_ramdisk << ramdisk_a.rdbuf() << ramdisk_b.rdbuf();
Ram Muthiahaad97c52019-08-14 17:05:01 -0700657 return true;
658}
659
Cody Schuffelen25c46432020-01-14 13:49:52 -0800660off_t AvailableSpaceAtPath(const std::string& path) {
661 struct statvfs vfs;
662 if (statvfs(path.c_str(), &vfs) != 0) {
663 int error_num = errno;
664 LOG(ERROR) << "Could not find space available at " << path << ", error was "
665 << strerror(error_num);
666 return 0;
667 }
668 return vfs.f_bsize * vfs.f_bavail; // block size * free blocks for unprivileged users
669}
670
671off_t USERDATA_IMAGE_RESERVED = 4l * (1l << 30l); // 4 GiB
672off_t AGGREGATE_IMAGE_RESERVED = 12l * (1l << 30l); // 12 GiB
673
674bool CreateCompositeDisk(const vsoc::CuttlefishConfig& config) {
Cody Schuffelen3c99f5b2019-06-14 17:26:01 -0700675 if (FLAGS_composite_disk.empty()) {
Cody Schuffelen25c46432020-01-14 13:49:52 -0800676 LOG(ERROR) << "asked to create composite disk, but path was empty";
677 return false;
678 }
679 if (!cvd::SharedFD::Open(FLAGS_composite_disk.c_str(), O_WRONLY | O_CREAT, 0644)->IsOpen()) {
680 LOG(ERROR) << "Could not ensure " << FLAGS_composite_disk << " exists";
681 return false;
Cody Schuffelen3c99f5b2019-06-14 17:26:01 -0700682 }
Cody Schuffelenc3fd6e52019-08-30 15:14:07 -0700683 if (FLAGS_vm_manager == vm_manager::CrosvmManager::name()) {
Cody Schuffelen25c46432020-01-14 13:49:52 -0800684 auto existing_size = cvd::FileSize(FLAGS_data_image);
685 auto available_space = AvailableSpaceAtPath(FLAGS_data_image);
686 if (available_space < USERDATA_IMAGE_RESERVED - existing_size) {
687 // TODO(schuffelen): Duplicate this check in run_cvd when it can run on a separate machine
688 LOG(ERROR) << "Not enough space in fs containing " << FLAGS_data_image;
689 LOG(ERROR) << "Wanted " << (USERDATA_IMAGE_RESERVED - existing_size);
690 LOG(ERROR) << "Got " << available_space;
691 return false;
692 }
Cody Schuffelena08d9dd2019-12-16 17:55:40 -0800693 std::string header_path = config.AssemblyPath("gpt_header.img");
694 std::string footer_path = config.AssemblyPath("gpt_footer.img");
Cody Schuffelencc769732020-01-16 15:58:12 -0800695 CreateCompositeDisk(disk_config(), header_path, footer_path, FLAGS_composite_disk);
Cody Schuffelenc3fd6e52019-08-30 15:14:07 -0700696 } else {
Cody Schuffelen25c46432020-01-14 13:49:52 -0800697 auto existing_size = cvd::FileSize(FLAGS_composite_disk);
698 auto available_space = AvailableSpaceAtPath(FLAGS_composite_disk);
699 if (available_space < AGGREGATE_IMAGE_RESERVED - existing_size) {
700 LOG(ERROR) << "Not enough space to create " << FLAGS_composite_disk;
701 LOG(ERROR) << "Wanted " << (AGGREGATE_IMAGE_RESERVED - existing_size);
702 LOG(ERROR) << "Got " << available_space;
703 return false;
704 }
Cody Schuffelencc769732020-01-16 15:58:12 -0800705 AggregateImage(disk_config(), FLAGS_composite_disk);
Cody Schuffelenc3fd6e52019-08-30 15:14:07 -0700706 }
Cody Schuffelen25c46432020-01-14 13:49:52 -0800707 return true;
Cody Schuffelen3c99f5b2019-06-14 17:26:01 -0700708}
709
710} // namespace
711
Cody Schuffelen605e6852019-10-16 16:22:24 -0700712const vsoc::CuttlefishConfig* InitFilesystemAndCreateConfig(
Cody Schuffelenb737ef52019-09-25 14:54:38 -0700713 int* argc, char*** argv, cvd::FetcherConfig fetcher_config) {
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800714 if (!ParseCommandLineFlags(argc, argv)) {
715 LOG(ERROR) << "Failed to parse command arguments";
Cody Schuffelene71fa352019-09-10 16:11:58 -0700716 exit(AssemblerExitCodes::kArgumentParsingError);
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800717 }
718
Cody Schuffelen1d054bb2020-01-16 17:16:51 -0800719 auto boot_img_unpacker =
720 cvd::BootImageUnpacker::FromImages(FLAGS_boot_image,
721 FLAGS_vendor_boot_image);
722 {
723 // The config object is created here, but only exists in memory until the
724 // SaveConfig line below. Don't launch cuttlefish subprocesses between these
725 // two operations, as those will assume they can read the config object from
726 // disk.
727 auto config = InitializeCuttlefishConfiguration(*boot_img_unpacker, fetcher_config);
A. Cody Schuffelenc17acda2020-01-23 15:54:40 -0800728 std::set<std::string> preserving;
729 if (FLAGS_resume && ShouldCreateCompositeDisk()) {
730 LOG(WARNING) << "Requested resuming a previous session (the default behavior) "
731 << "but the base images have changed under the overlay, making the "
732 << "overlay incompatible. Wiping the overlay files.";
733 } else if (FLAGS_resume && !ShouldCreateCompositeDisk()) {
734 preserving.insert("overlay.img");
735 preserving.insert("gpt_header.img");
736 preserving.insert("gpt_footer.img");
737 preserving.insert("composite.img");
738 preserving.insert("access-kregistry");
739 }
740 if (!CleanPriorFiles(config, preserving)) {
Cody Schuffelen1d054bb2020-01-16 17:16:51 -0800741 LOG(ERROR) << "Failed to clean prior files";
742 exit(AssemblerExitCodes::kPrioFilesCleanupError);
Cody Schuffelenab6d3452019-12-13 15:54:27 -0800743 }
Cody Schuffelen1d054bb2020-01-16 17:16:51 -0800744 // Create assembly directory if it doesn't exist.
745 if (!cvd::DirectoryExists(FLAGS_assembly_dir.c_str())) {
746 LOG(INFO) << "Setting up " << FLAGS_assembly_dir;
A. Cody Schuffelenc17acda2020-01-23 15:54:40 -0800747 if (mkdir(FLAGS_assembly_dir.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) < 0
748 && errno != EEXIST) {
Cody Schuffelen1d054bb2020-01-16 17:16:51 -0800749 LOG(ERROR) << "Failed to create assembly directory: "
750 << FLAGS_assembly_dir << ". Error: " << errno;
751 exit(AssemblerExitCodes::kAssemblyDirCreationError);
752 }
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800753 }
Cody Schuffelen1d054bb2020-01-16 17:16:51 -0800754 for (const auto& instance : config.Instances()) {
755 // Create instance directory if it doesn't exist.
756 if (!cvd::DirectoryExists(instance.instance_dir().c_str())) {
Cody Schuffelen3e745bf2020-01-16 17:26:41 -0800757 LOG(INFO) << "Setting up " << FLAGS_instance_dir << ".N";
A. Cody Schuffelenc17acda2020-01-23 15:54:40 -0800758 if (mkdir(instance.instance_dir().c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) < 0
759 && errno != EEXIST) {
Cody Schuffelen1d054bb2020-01-16 17:16:51 -0800760 LOG(ERROR) << "Failed to create instance directory: "
761 << FLAGS_instance_dir << ". Error: " << errno;
762 exit(AssemblerExitCodes::kInstanceDirCreationError);
763 }
764 }
765 auto internal_dir = instance.instance_dir() + "/" + vsoc::kInternalDirName;
766 if (!cvd::DirectoryExists(internal_dir)) {
A. Cody Schuffelenc17acda2020-01-23 15:54:40 -0800767 if (mkdir(internal_dir.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) < 0
768 && errno != EEXIST) {
Cody Schuffelen1d054bb2020-01-16 17:16:51 -0800769 LOG(ERROR) << "Failed to create internal instance directory: "
770 << internal_dir << ". Error: " << errno;
771 exit(AssemblerExitCodes::kInstanceDirCreationError);
772 }
773 }
774 }
775 if (!SaveConfig(config)) {
776 LOG(ERROR) << "Failed to initialize configuration";
777 exit(AssemblerExitCodes::kCuttlefishConfigurationInitError);
Jorge E. Moreira1e8e2f12019-10-07 18:09:49 -0700778 }
779 }
780
Cody Schuffelen2b51bab2019-01-29 18:14:48 -0800781 if (!cvd::FileHasContent(FLAGS_boot_image)) {
782 LOG(ERROR) << "File not found: " << FLAGS_boot_image;
783 exit(cvd::kCuttlefishConfigurationInitError);
784 }
785
Ram Muthiah1aa02f82019-10-22 20:26:28 +0000786 if (!cvd::FileHasContent(FLAGS_vendor_boot_image)) {
787 LOG(ERROR) << "File not found: " << FLAGS_vendor_boot_image;
788 exit(cvd::kCuttlefishConfigurationInitError);
789 }
790
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800791 // Do this early so that the config object is ready for anything that needs it
792 auto config = vsoc::CuttlefishConfig::Get();
793 if (!config) {
794 LOG(ERROR) << "Failed to obtain config singleton";
Cody Schuffelene71fa352019-09-10 16:11:58 -0700795 exit(AssemblerExitCodes::kCuttlefishConfigurationInitError);
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800796 }
797
798 if (!boot_img_unpacker->Unpack(config->ramdisk_image_path(),
Ram Muthiah1aa02f82019-10-22 20:26:28 +0000799 config->vendor_ramdisk_image_path(),
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800800 config->use_unpacked_kernel()
801 ? config->kernel_image_path()
802 : "")) {
803 LOG(ERROR) << "Failed to unpack boot image";
Cody Schuffelene71fa352019-09-10 16:11:58 -0700804 exit(AssemblerExitCodes::kBootImageUnpackError);
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800805 }
806
Ram Muthiah1aa02f82019-10-22 20:26:28 +0000807 // TODO(134522463) as part of the bootloader refactor, repack the vendor boot
808 // image and use the bootloader to load both the boot and vendor ramdisk.
809 // Until then, this hack to get gki modules into cuttlefish will suffice.
810
811 // If a vendor ramdisk comes in via this mechanism, let it supercede the one
812 // in the vendor boot image. This flag is what kernel presubmit testing uses
813 // to pass in the kernel ramdisk.
Ram Muthiahd512c132019-10-23 17:20:45 -0700814
815 // If no kernel is passed in or an initramfs is made available, the default
816 // vendor boot ramdisk or the initramfs provided should be appended to the
817 // boot ramdisk. If a kernel IS provided with no initramfs, it is safe to
818 // safe to assume that the kernel was built with no modules and expects no
819 // modules for cf to run properly.
Cody Schuffelencd3563a2019-10-29 16:35:06 -0700820 std::string discovered_kernel = fetcher_config.FindCvdFileWithSuffix(kKernelDefaultPath);
821 std::string foreign_kernel = FLAGS_kernel_path.size() ? FLAGS_kernel_path : discovered_kernel;
822 std::string discovered_ramdisk = fetcher_config.FindCvdFileWithSuffix(kInitramfsImg);
823 std::string foreign_ramdisk = FLAGS_initramfs_path.size () ? FLAGS_initramfs_path : discovered_ramdisk;
824 if(!foreign_kernel.size() || foreign_ramdisk.size()) {
Ram Muthiahd512c132019-10-23 17:20:45 -0700825 const std::string& vendor_ramdisk_path =
826 config->initramfs_path().size() ? config->initramfs_path()
827 : config->vendor_ramdisk_image_path();
828 if(!ConcatRamdisks(config->final_ramdisk_path(),
829 config->ramdisk_image_path(), vendor_ramdisk_path)) {
830 LOG(ERROR) << "Failed to concatenate ramdisk and vendor ramdisk";
831 exit(AssemblerExitCodes::kInitRamFsConcatError);
832 }
Ram Muthiahaad97c52019-08-14 17:05:01 -0700833 }
834
Jorge E. Moreira80ddd7f2019-02-04 16:30:13 -0800835 if (config->decompress_kernel()) {
836 if (!DecompressKernel(config->kernel_image_path(),
837 config->decompressed_kernel_image_path())) {
838 LOG(ERROR) << "Failed to decompress kernel";
Cody Schuffelene71fa352019-09-10 16:11:58 -0700839 exit(AssemblerExitCodes::kKernelDecompressError);
Jorge E. Moreira80ddd7f2019-02-04 16:30:13 -0800840 }
841 }
842
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800843 ValidateAdbModeFlag(*config);
844
Yifan Hong19d713e2019-05-01 14:12:07 -0700845 // Create misc if necessary
846 if (!InitializeMiscImage(FLAGS_misc_image)) {
847 exit(cvd::kCuttlefishConfigurationInitError);
848 }
849
Cody Schuffelen2b51bab2019-01-29 18:14:48 -0800850 // Create data if necessary
Cody Schuffelen3c99f5b2019-06-14 17:26:01 -0700851 if (!ApplyDataImagePolicy(*config, FLAGS_data_image)) {
Cody Schuffelen2b51bab2019-01-29 18:14:48 -0800852 exit(cvd::kCuttlefishConfigurationInitError);
853 }
854
Cody Schuffelen69c19592019-05-31 16:00:30 -0700855 if (!cvd::FileExists(FLAGS_metadata_image)) {
856 CreateBlankImage(FLAGS_metadata_image, FLAGS_blank_metadata_image_mb, "none");
857 }
Paul Trautrimba8f8e92019-03-12 17:55:48 +0900858
Cody Schuffelen1d054bb2020-01-16 17:16:51 -0800859 for (const auto& instance : config->Instances()) {
860 if (!cvd::FileExists(instance.access_kregistry_path())) {
861 CreateBlankImage(instance.access_kregistry_path(), 1, "none", "64K");
862 }
Kenny Root1f50ee62020-01-24 12:06:19 -0800863 }
864
Cody Schuffelenb737ef52019-09-25 14:54:38 -0700865 if (SuperImageNeedsRebuilding(fetcher_config, *config)) {
866 if (!RebuildSuperImage(fetcher_config, *config, FLAGS_super_image)) {
867 LOG(ERROR) << "Super image rebuilding requested but could not be completed.";
868 exit(cvd::kCuttlefishConfigurationInitError);
869 }
870 }
871
Cody Schuffelen3c99f5b2019-06-14 17:26:01 -0700872 if (ShouldCreateCompositeDisk()) {
Cody Schuffelen25c46432020-01-14 13:49:52 -0800873 if (!CreateCompositeDisk(*config)) {
874 exit(cvd::kDiskSpaceError);
875 }
Cody Schuffelen3c99f5b2019-06-14 17:26:01 -0700876 }
877
Cody Schuffelenaff3fcf2020-01-16 16:46:15 -0800878 for (auto instance : config->Instances()) {
A. Cody Schuffelenc17acda2020-01-23 15:54:40 -0800879 auto overlay_path = instance.PerInstancePath("overlay.img");
880 if (!cvd::FileExists(overlay_path) || ShouldCreateCompositeDisk() || !FLAGS_resume
881 || cvd::FileModificationTime(overlay_path) < cvd::FileModificationTime(FLAGS_composite_disk)) {
882 if (FLAGS_resume) {
883 LOG(WARNING) << "Requested to continue an existing session, but the overlay was "
884 << "newer than its underlying composite disk. Wiping the overlay.";
885 }
886 CreateQcowOverlay(config->crosvm_binary(), FLAGS_composite_disk, overlay_path);
887 CreateBlankImage(instance.access_kregistry_path(), 1, "none", "64K");
888 }
889 }
890
891 for (auto instance : config->Instances()) {
Cody Schuffelenaff3fcf2020-01-16 16:46:15 -0800892 // Check that the files exist
893 for (const auto& file : instance.virtual_disk_paths()) {
894 if (!file.empty() && !cvd::FileHasContent(file.c_str())) {
895 LOG(ERROR) << "File not found: " << file;
896 exit(cvd::kCuttlefishConfigurationInitError);
897 }
Cody Schuffelen2b51bab2019-01-29 18:14:48 -0800898 }
899 }
900
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800901 return config;
902}
903
904std::string GetConfigFilePath(const vsoc::CuttlefishConfig& config) {
Cody Schuffelen2168c242019-12-13 16:15:27 -0800905 return config.AssemblyPath("cuttlefish_config.json");
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800906}