blob: b67c3606b29729c09e25f02937402d1ce774da04 [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 Schuffelen9e2f73e2020-02-04 17:19:54 -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 Schuffelen9e2f73e2020-02-04 17:19:54 -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 Schuffelen20ecaca2019-01-29 17:43:38 -080096
97DEFINE_bool(deprecated_boot_completed, false, "Log boot completed message to"
98 " host kernel. This is only used during transition of our clients."
99 " Will be deprecated soon.");
A. Cody Schuffelen9e2f73e2020-02-04 17:19:54 -0800100DEFINE_bool(start_vnc_server, false, "Whether to start the vnc server process. "
101 "The VNC server runs at port 6443 + i for "
102 "the vsoc-i user or CUTTLEFISH_INSTANCE=i, "
103 "starting from 1.");
Jorge E. Moreirae049b792019-12-18 18:17:48 -0800104
Jorge E. Moreira692ca662020-02-19 15:36:26 -0800105DEFINE_bool(start_webrtc, false, "[Experimental] Whether to start the webrtc process.");
Jorge E. Moreirae049b792019-12-18 18:17:48 -0800106
107DEFINE_string(
108 webrtc_assets_dir,
Jorge E. Moreira1f65a4a2019-11-08 15:23:32 -0800109 vsoc::DefaultHostArtifactsPath("usr/share/webrtc/assets"),
Jorge E. Moreira692ca662020-02-19 15:36:26 -0800110 "[Experimental] Path to WebRTC webpage assets.");
Jorge E. Moreirae049b792019-12-18 18:17:48 -0800111
112DEFINE_string(
113 webrtc_certs_dir,
Jorge E. Moreira1f65a4a2019-11-08 15:23:32 -0800114 vsoc::DefaultHostArtifactsPath("usr/share/webrtc/certs"),
Jorge E. Moreira692ca662020-02-19 15:36:26 -0800115 "[Experimental] Path to WebRTC certificates directory.");
Jorge E. Moreirae049b792019-12-18 18:17:48 -0800116
117DEFINE_string(
118 webrtc_public_ip,
Jorge E. Moreira1f65a4a2019-11-08 15:23:32 -0800119 "127.0.0.1",
Jorge E. Moreira692ca662020-02-19 15:36:26 -0800120 "[Experimental] Public IPv4 address of your server, a.b.c.d format");
Jorge E. Moreirae049b792019-12-18 18:17:48 -0800121
122DEFINE_bool(
123 webrtc_enable_adb_websocket,
124 false,
Jorge E. Moreira692ca662020-02-19 15:36:26 -0800125 "[Experimental] If enabled, exposes local adb service through a websocket.");
Jorge E. Moreirae049b792019-12-18 18:17:48 -0800126
Cody Schuffelen10743332019-04-15 16:50:49 -0700127DEFINE_string(adb_mode, "vsock_half_tunnel",
Cody Schuffelen3c35fd82019-12-11 18:39:46 -0800128 "Mode for ADB connection."
Cody Schuffelen63d10052019-02-26 12:21:53 -0800129 "'vsock_tunnel' for a TCP connection tunneled through vsock, "
130 "'native_vsock' for a direct connection to the guest ADB over "
131 "vsock, 'vsock_half_tunnel' for a TCP connection forwarded to "
132 "the guest ADB server, or a comma separated list of types as in "
Cody Schuffelen3c35fd82019-12-11 18:39:46 -0800133 "'native_vsock,vsock_half_tunnel'");
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800134DEFINE_bool(run_adb_connector, true,
135 "Maintain adb connection by sending 'adb connect' commands to the "
Matthias Maennich454d7872019-02-06 16:35:17 +0000136 "server. Only relevant with -adb_mode=tunnel or vsock_tunnel");
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800137
Cody Schuffelen47c57852019-12-13 13:50:50 -0800138DEFINE_string(uuid, vsoc::ForCurrentInstance(vsoc::kDefaultUuidPrefix),
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800139 "UUID to use for the device. Random if not specified");
140DEFINE_bool(daemon, false,
141 "Run cuttlefish in background, the launcher exits on boot "
142 "completed/failed");
143
144DEFINE_string(device_title, "", "Human readable name for the instance, "
145 "used by the vnc_server for its server title");
146DEFINE_string(setupwizard_mode, "DISABLED",
147 "One of DISABLED,OPTIONAL,REQUIRED");
148
149DEFINE_string(qemu_binary,
150 "/usr/bin/qemu-system-x86_64",
151 "The qemu binary to use");
Jorge E. Moreiraba626622019-01-28 17:47:50 -0800152DEFINE_string(crosvm_binary,
153 vsoc::DefaultHostArtifactsPath("bin/crosvm"),
154 "The Crosvm binary to use");
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800155DEFINE_bool(restart_subprocesses, true, "Restart any crashed host process");
Jorge E. Moreirafd10cae2019-02-19 15:35:42 -0800156DEFINE_string(logcat_mode, "", "How to send android's log messages from "
157 "guest to host. One of [serial, vsock]");
Ram Muthiah6e9c98c2019-05-28 15:18:27 -0700158DEFINE_bool(enable_tombstone_receiver, true, "Enables the tombstone logger on "
Ram Muthiah792e2ad2019-04-19 11:19:46 -0700159 "both the guest and the host");
Cody Schuffelen1300f122019-05-28 18:24:34 -0700160DEFINE_bool(use_bootloader, false, "Boots the device using a bootloader");
161DEFINE_string(bootloader, "", "Bootloader binary path");
David Anderson637bfd62019-09-26 13:23:21 -0700162DEFINE_string(boot_slot, "", "Force booting into the given slot. If empty, "
163 "the slot will be chosen based on the misc partition if using a "
164 "bootloader. It will default to 'a' if empty and not using a "
165 "bootloader.");
A. Cody Schuffelen9e2f73e2020-02-04 17:19:54 -0800166DEFINE_int32(num_instances, 1, "Number of Android guests to launch");
167DEFINE_bool(resume, true, "Resume using the disk from the last session, if "
168 "possible. i.e., if --noresume is passed, the disk "
169 "will be reset to the state it was initially launched "
170 "in. This flag is ignored if the underlying partition "
171 "images have been updated since the first launch.");
Yifan Hong19d713e2019-05-01 14:12:07 -0700172
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800173namespace {
174
Cody Schuffelencd3563a2019-10-29 16:35:06 -0700175const std::string kKernelDefaultPath = "kernel";
176const std::string kInitramfsImg = "initramfs.img";
177const std::string kRamdiskConcatExt = ".concat";
Cody Schuffelen9fd95472019-10-04 13:49:57 -0700178
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800179bool ResolveInstanceFiles() {
180 if (FLAGS_system_image_dir.empty()) {
181 LOG(ERROR) << "--system_image_dir must be specified.";
182 return false;
183 }
184
185 // If user did not specify location of either of these files, expect them to
186 // be placed in --system_image_dir location.
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800187 std::string default_boot_image = FLAGS_system_image_dir + "/boot.img";
188 SetCommandLineOptionWithMode("boot_image", default_boot_image.c_str(),
189 google::FlagSettingMode::SET_FLAGS_DEFAULT);
190 std::string default_cache_image = FLAGS_system_image_dir + "/cache.img";
191 SetCommandLineOptionWithMode("cache_image", default_cache_image.c_str(),
192 google::FlagSettingMode::SET_FLAGS_DEFAULT);
193 std::string default_data_image = FLAGS_system_image_dir + "/userdata.img";
194 SetCommandLineOptionWithMode("data_image", default_data_image.c_str(),
195 google::FlagSettingMode::SET_FLAGS_DEFAULT);
Paul Trautrimba8f8e92019-03-12 17:55:48 +0900196 std::string default_metadata_image = FLAGS_system_image_dir + "/metadata.img";
197 SetCommandLineOptionWithMode("metadata_image", default_metadata_image.c_str(),
198 google::FlagSettingMode::SET_FLAGS_DEFAULT);
Alistair Strachan050ca932018-11-27 12:41:19 -0800199 std::string default_super_image = FLAGS_system_image_dir + "/super.img";
200 SetCommandLineOptionWithMode("super_image", default_super_image.c_str(),
201 google::FlagSettingMode::SET_FLAGS_DEFAULT);
Yifan Hong19d713e2019-05-01 14:12:07 -0700202 std::string default_misc_image = FLAGS_system_image_dir + "/misc.img";
203 SetCommandLineOptionWithMode("misc_image", default_misc_image.c_str(),
204 google::FlagSettingMode::SET_FLAGS_DEFAULT);
Ram Muthiah1aa02f82019-10-22 20:26:28 +0000205 std::string default_vendor_boot_image = FLAGS_system_image_dir
206 + "/vendor_boot.img";
207 SetCommandLineOptionWithMode("vendor_boot_image",
208 default_vendor_boot_image.c_str(),
209 google::FlagSettingMode::SET_FLAGS_DEFAULT);
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800210
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800211 return true;
212}
213
214std::string GetCuttlefishEnvPath() {
215 return cvd::StringFromEnv("HOME", ".") + "/.cuttlefish.sh";
216}
217
Cody Schuffelen2168c242019-12-13 16:15:27 -0800218std::string GetLegacyConfigFilePath(const vsoc::CuttlefishConfig& config) {
219 return config.ForDefaultInstance().PerInstancePath("cuttlefish_config.json");
220}
221
Jorge E. Moreirae049b792019-12-18 18:17:48 -0800222int NumStreamers() {
223 auto start_flags = {FLAGS_start_vnc_server, FLAGS_start_webrtc};
224 return std::count(start_flags.begin(), start_flags.end(), true);
225}
226
A. Cody Schuffelen9e2f73e2020-02-04 17:19:54 -0800227std::string StrForInstance(const std::string& prefix, int num) {
228 std::ostringstream stream;
229 stream << prefix << std::setfill('0') << std::setw(2) << num;
230 return stream.str();
231}
232
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800233// Initializes the config object and saves it to file. It doesn't return it, all
234// further uses of the config should happen through the singleton
A. Cody Schuffelen9e2f73e2020-02-04 17:19:54 -0800235vsoc::CuttlefishConfig InitializeCuttlefishConfiguration(
Cody Schuffelencd3563a2019-10-29 16:35:06 -0700236 const cvd::BootImageUnpacker& boot_image_unpacker,
237 const cvd::FetcherConfig& fetcher_config) {
Jorge E. Moreirae049b792019-12-18 18:17:48 -0800238 // At most one streamer can be started.
239 CHECK(NumStreamers() <= 1);
240
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800241 vsoc::CuttlefishConfig tmp_config_obj;
Cody Schuffelenab6d3452019-12-13 15:54:27 -0800242 tmp_config_obj.set_assembly_dir(FLAGS_assembly_dir);
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800243 if (!vm_manager::VmManager::IsValidName(FLAGS_vm_manager)) {
A. Cody Schuffelen9e2f73e2020-02-04 17:19:54 -0800244 LOG(FATAL) << "Invalid vm_manager: " << FLAGS_vm_manager;
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800245 }
Greg Hartmana3c552d2019-03-28 18:20:48 -0700246 if (!vm_manager::VmManager::IsValidName(FLAGS_vm_manager)) {
A. Cody Schuffelen9e2f73e2020-02-04 17:19:54 -0800247 LOG(FATAL) << "Invalid vm_manager: " << FLAGS_vm_manager;
Greg Hartmana3c552d2019-03-28 18:20:48 -0700248 }
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800249 tmp_config_obj.set_vm_manager(FLAGS_vm_manager);
Greg Hartmana3c552d2019-03-28 18:20:48 -0700250 tmp_config_obj.set_gpu_mode(FLAGS_gpu_mode);
Cody Schuffelen2de6ead2019-12-04 16:16:47 -0800251 if (vm_manager::VmManager::ConfigureGpuMode(tmp_config_obj.vm_manager(),
252 tmp_config_obj.gpu_mode()).empty()) {
A. Cody Schuffelen9e2f73e2020-02-04 17:19:54 -0800253 LOG(FATAL) << "Invalid gpu_mode=" << FLAGS_gpu_mode <<
Greg Hartmana3c552d2019-03-28 18:20:48 -0700254 " does not work with vm_manager=" << FLAGS_vm_manager;
Greg Hartmana3c552d2019-03-28 18:20:48 -0700255 }
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800256
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800257 tmp_config_obj.set_cpus(FLAGS_cpus);
258 tmp_config_obj.set_memory_mb(FLAGS_memory_mb);
259
260 tmp_config_obj.set_dpi(FLAGS_dpi);
261 tmp_config_obj.set_setupwizard_mode(FLAGS_setupwizard_mode);
262 tmp_config_obj.set_x_res(FLAGS_x_res);
263 tmp_config_obj.set_y_res(FLAGS_y_res);
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800264 tmp_config_obj.set_refresh_rate_hz(FLAGS_refresh_rate_hz);
265 tmp_config_obj.set_gdb_flag(FLAGS_qemu_gdb);
Cody Schuffelenf4a1cdb2019-11-13 16:51:16 -0800266 std::vector<std::string> adb = android::base::Split(FLAGS_adb_mode, ",");
Cody Schuffelen90b2fb22019-02-28 18:55:21 -0800267 tmp_config_obj.set_adb_mode(std::set<std::string>(adb.begin(), adb.end()));
Cody Schuffelencd3563a2019-10-29 16:35:06 -0700268 std::string discovered_kernel = fetcher_config.FindCvdFileWithSuffix(kKernelDefaultPath);
269 std::string foreign_kernel = FLAGS_kernel_path.size() ? FLAGS_kernel_path : discovered_kernel;
270 if (foreign_kernel.size()) {
271 tmp_config_obj.set_kernel_image_path(foreign_kernel);
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800272 tmp_config_obj.set_use_unpacked_kernel(false);
273 } else {
274 tmp_config_obj.set_kernel_image_path(
Cody Schuffelenf53ded12019-12-13 16:05:22 -0800275 tmp_config_obj.AssemblyPath(kKernelDefaultPath.c_str()));
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800276 tmp_config_obj.set_use_unpacked_kernel(true);
277 }
Alistair Delva3aac3e12020-05-13 12:17:02 -0700278
Jorge E. Moreira80ddd7f2019-02-04 16:30:13 -0800279 tmp_config_obj.set_decompress_kernel(FLAGS_decompress_kernel);
Alistair Delva3aac3e12020-05-13 12:17:02 -0700280 if (tmp_config_obj.decompress_kernel()) {
Jorge E. Moreira80ddd7f2019-02-04 16:30:13 -0800281 tmp_config_obj.set_decompressed_kernel_image_path(
Cody Schuffelenf53ded12019-12-13 16:05:22 -0800282 tmp_config_obj.AssemblyPath("vmlinux"));
Jorge E. Moreira80ddd7f2019-02-04 16:30:13 -0800283 }
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800284
Cody Schuffelenf53ded12019-12-13 16:05:22 -0800285 auto ramdisk_path = tmp_config_obj.AssemblyPath("ramdisk.img");
286 auto vendor_ramdisk_path = tmp_config_obj.AssemblyPath("vendor_ramdisk.img");
Cody Schuffelen1e645542019-11-19 15:44:22 -0800287 if (!boot_image_unpacker.HasRamdiskImage()) {
A. Cody Schuffelen9e2f73e2020-02-04 17:19:54 -0800288 LOG(FATAL) << "A ramdisk is required, but the boot image did not have one.";
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800289 }
290
Cody Schuffelen2de6ead2019-12-04 16:16:47 -0800291 tmp_config_obj.set_boot_image_kernel_cmdline(boot_image_unpacker.kernel_cmdline());
292 tmp_config_obj.set_loop_max_part(FLAGS_loop_max_part);
293 tmp_config_obj.set_guest_enforce_security(FLAGS_guest_enforce_security);
294 tmp_config_obj.set_guest_audit_security(FLAGS_guest_audit_security);
Alistair Delva33b861f2019-12-26 12:23:59 -0800295 tmp_config_obj.set_guest_force_normal_boot(FLAGS_guest_force_normal_boot);
Cody Schuffelen2de6ead2019-12-04 16:16:47 -0800296 tmp_config_obj.set_extra_kernel_cmdline(FLAGS_extra_kernel_cmdline);
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800297
298 tmp_config_obj.set_ramdisk_image_path(ramdisk_path);
Ram Muthiahd512c132019-10-23 17:20:45 -0700299 tmp_config_obj.set_vendor_ramdisk_image_path(vendor_ramdisk_path);
300
Cody Schuffelencd3563a2019-10-29 16:35:06 -0700301 std::string discovered_ramdisk = fetcher_config.FindCvdFileWithSuffix(kInitramfsImg);
302 std::string foreign_ramdisk = FLAGS_initramfs_path.size () ? FLAGS_initramfs_path : discovered_ramdisk;
303 if (foreign_kernel.size() && !foreign_ramdisk.size()) {
Ram Muthiahd512c132019-10-23 17:20:45 -0700304 // If there's a kernel that's passed in without an initramfs, that implies
305 // user error or a kernel built with no modules. In either case, let's
306 // choose to avoid loading the modules from the vendor ramdisk which are
307 // built for the default cf kernel. Once boot occurs, user error will
308 // become obvious.
309 tmp_config_obj.set_final_ramdisk_path(ramdisk_path);
310 } else {
311 tmp_config_obj.set_final_ramdisk_path(ramdisk_path + kRamdiskConcatExt);
Cody Schuffelencd3563a2019-10-29 16:35:06 -0700312 if(foreign_ramdisk.size()) {
313 tmp_config_obj.set_initramfs_path(foreign_ramdisk);
Ram Muthiahd512c132019-10-23 17:20:45 -0700314 }
Cody Schuffelen9fd95472019-10-04 13:49:57 -0700315 }
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800316
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800317 tmp_config_obj.set_deprecated_boot_completed(FLAGS_deprecated_boot_completed);
Cody Schuffelen3dff6982019-12-05 16:24:12 -0800318 tmp_config_obj.set_logcat_receiver_binary(
319 vsoc::DefaultHostArtifactsPath("bin/logcat_receiver"));
320 tmp_config_obj.set_config_server_binary(
321 vsoc::DefaultHostArtifactsPath("bin/config_server"));
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800322
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800323 tmp_config_obj.set_qemu_binary(FLAGS_qemu_binary);
Jorge E. Moreiraba626622019-01-28 17:47:50 -0800324 tmp_config_obj.set_crosvm_binary(FLAGS_crosvm_binary);
Cody Schuffelen3dff6982019-12-05 16:24:12 -0800325 tmp_config_obj.set_console_forwarder_binary(
326 vsoc::DefaultHostArtifactsPath("bin/console_forwarder"));
327 tmp_config_obj.set_kernel_log_monitor_binary(
328 vsoc::DefaultHostArtifactsPath("bin/kernel_log_monitor"));
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800329
330 tmp_config_obj.set_enable_vnc_server(FLAGS_start_vnc_server);
Cody Schuffelen3dff6982019-12-05 16:24:12 -0800331 tmp_config_obj.set_vnc_server_binary(
332 vsoc::DefaultHostArtifactsPath("bin/vnc_server"));
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800333
Jorge E. Moreirae049b792019-12-18 18:17:48 -0800334 tmp_config_obj.set_enable_webrtc(FLAGS_start_webrtc);
335 tmp_config_obj.set_webrtc_binary(
336 vsoc::DefaultHostArtifactsPath("bin/webRTC"));
337 tmp_config_obj.set_webrtc_assets_dir(FLAGS_webrtc_assets_dir);
338 tmp_config_obj.set_webrtc_public_ip(FLAGS_webrtc_public_ip);
339 tmp_config_obj.set_webrtc_certs_dir(FLAGS_webrtc_certs_dir);
340
341 tmp_config_obj.set_webrtc_enable_adb_websocket(
342 FLAGS_webrtc_enable_adb_websocket);
343
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800344 tmp_config_obj.set_restart_subprocesses(FLAGS_restart_subprocesses);
345 tmp_config_obj.set_run_adb_connector(FLAGS_run_adb_connector);
Cody Schuffelen3dff6982019-12-05 16:24:12 -0800346 tmp_config_obj.set_adb_connector_binary(
347 vsoc::DefaultHostArtifactsPath("bin/adb_connector"));
Cody Schuffelen3dff6982019-12-05 16:24:12 -0800348 tmp_config_obj.set_socket_vsock_proxy_binary(
349 vsoc::DefaultHostArtifactsPath("bin/socket_vsock_proxy"));
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800350 tmp_config_obj.set_run_as_daemon(FLAGS_daemon);
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800351
Cody Schuffelen2b51bab2019-01-29 18:14:48 -0800352 tmp_config_obj.set_data_policy(FLAGS_data_policy);
353 tmp_config_obj.set_blank_data_image_mb(FLAGS_blank_data_image_mb);
354 tmp_config_obj.set_blank_data_image_fmt(FLAGS_blank_data_image_fmt);
355
Jorge E. Moreirafd10cae2019-02-19 15:35:42 -0800356 tmp_config_obj.set_logcat_mode(FLAGS_logcat_mode);
Jorge E. Moreirafd10cae2019-02-19 15:35:42 -0800357
Ram Muthiah792e2ad2019-04-19 11:19:46 -0700358 tmp_config_obj.set_enable_tombstone_receiver(FLAGS_enable_tombstone_receiver);
Cody Schuffelen3dff6982019-12-05 16:24:12 -0800359 tmp_config_obj.set_tombstone_receiver_binary(
360 vsoc::DefaultHostArtifactsPath("bin/tombstone_receiver"));
Ram Muthiah792e2ad2019-04-19 11:19:46 -0700361
Cody Schuffelen1300f122019-05-28 18:24:34 -0700362 tmp_config_obj.set_use_bootloader(FLAGS_use_bootloader);
363 tmp_config_obj.set_bootloader(FLAGS_bootloader);
364
David Anderson637bfd62019-09-26 13:23:21 -0700365 if (!FLAGS_boot_slot.empty()) {
366 tmp_config_obj.set_boot_slot(FLAGS_boot_slot);
367 }
368
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800369 tmp_config_obj.set_cuttlefish_env_path(GetCuttlefishEnvPath());
370
A. Cody Schuffelen9e2f73e2020-02-04 17:19:54 -0800371 std::vector<int> instance_nums;
372 for (int i = 0; i < FLAGS_num_instances; i++) {
373 instance_nums.push_back(vsoc::GetInstance() + i);
374 }
375
376 for (const auto& num : instance_nums) {
377 auto instance = tmp_config_obj.ForInstance(num);
378 auto const_instance = const_cast<const vsoc::CuttlefishConfig&>(tmp_config_obj)
379 .ForInstance(num);
380 // Set this first so that calls to PerInstancePath below are correct
381 instance.set_instance_dir(FLAGS_instance_dir + "." + std::to_string(num));
382 instance.set_serial_number(FLAGS_serial_number + std::to_string(num));
383
384 instance.set_mobile_bridge_name(StrForInstance("cvd-mbr-", num));
385 instance.set_mobile_tap_name(StrForInstance("cvd-mtap-", num));
386
387 instance.set_wifi_tap_name(StrForInstance("cvd-wtap-", num));
388
389 instance.set_vsock_guest_cid(3 + num - 1);
390
391 instance.set_uuid(FLAGS_uuid);
392
393 instance.set_vnc_server_port(6444 + num - 1);
394 instance.set_host_port(6520 + num - 1);
395 instance.set_adb_ip_and_port("127.0.0.1:" + std::to_string(6520 + num - 1));
396
397 instance.set_device_title(FLAGS_device_title);
398
399 instance.set_virtual_disk_paths({const_instance.PerInstancePath("overlay.img")});
400 }
401
402 return tmp_config_obj;
403}
404
405bool SaveConfig(const vsoc::CuttlefishConfig& tmp_config_obj) {
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800406 auto config_file = GetConfigFilePath(tmp_config_obj);
407 auto config_link = vsoc::GetGlobalConfigFileLink();
408 // Save the config object before starting any host process
409 if (!tmp_config_obj.SaveToFile(config_file)) {
410 LOG(ERROR) << "Unable to save config object";
411 return false;
412 }
Cody Schuffelen2168c242019-12-13 16:15:27 -0800413 auto legacy_config_file = GetLegacyConfigFilePath(tmp_config_obj);
414 if (!tmp_config_obj.SaveToFile(legacy_config_file)) {
415 LOG(ERROR) << "Unable to save legacy config object";
416 return false;
417 }
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800418 setenv(vsoc::kCuttlefishConfigEnvVarName, config_file.c_str(), true);
419 if (symlink(config_file.c_str(), config_link.c_str()) != 0) {
420 LOG(ERROR) << "Failed to create symlink to config file at " << config_link
421 << ": " << strerror(errno);
422 return false;
423 }
424
425 return true;
426}
427
428void SetDefaultFlagsForQemu() {
Cody Schuffelen038d4d92019-11-04 15:09:03 -0800429 // TODO(b/144119457) Use the serial port.
430 SetCommandLineOptionWithMode("logcat_mode", cvd::kLogcatVsockMode,
Jorge E. Moreirafd10cae2019-02-19 15:35:42 -0800431 google::FlagSettingMode::SET_FLAGS_DEFAULT);
Jorge E. Moreiraba626622019-01-28 17:47:50 -0800432}
433
434void SetDefaultFlagsForCrosvm() {
Jorge E. Moreirafd10cae2019-02-19 15:35:42 -0800435 SetCommandLineOptionWithMode("logcat_mode", cvd::kLogcatVsockMode,
436 google::FlagSettingMode::SET_FLAGS_DEFAULT);
Alistair Delva3aac3e12020-05-13 12:17:02 -0700437
438 // Crosvm requires a specific setting for kernel decompression; it must be
439 // on for aarch64 and off for x86, no other mode is supported.
440 bool decompress_kernel = false;
441 if (cvd::HostArch() == "aarch64") {
442 decompress_kernel = true;
443 }
444 SetCommandLineOptionWithMode("decompress_kernel",
445 (decompress_kernel ? "true" : "false"),
446 google::FlagSettingMode::SET_FLAGS_DEFAULT);
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800447}
448
449bool ParseCommandLineFlags(int* argc, char*** argv) {
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800450 google::ParseCommandLineNonHelpFlags(argc, argv, true);
451 bool invalid_manager = false;
452 if (FLAGS_vm_manager == vm_manager::QemuManager::name()) {
453 SetDefaultFlagsForQemu();
Jorge E. Moreiraba626622019-01-28 17:47:50 -0800454 } else if (FLAGS_vm_manager == vm_manager::CrosvmManager::name()) {
455 SetDefaultFlagsForCrosvm();
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800456 } else {
457 std::cerr << "Unknown Virtual Machine Manager: " << FLAGS_vm_manager
458 << std::endl;
459 invalid_manager = true;
460 }
Jorge E. Moreira1f65a4a2019-11-08 15:23:32 -0800461 if (NumStreamers() == 0) {
462 // This makes the vnc server the default streamer unless the user requests
463 // another via a --star_<streamer> flag, while at the same time it's
464 // possible to run without any streamer by setting --start_vnc_server=false.
465 SetCommandLineOptionWithMode("start_vnc_server", "true",
466 google::FlagSettingMode::SET_FLAGS_DEFAULT);
467 }
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800468 google::HandleCommandLineHelpFlags();
469 if (invalid_manager) {
470 return false;
471 }
472 // Set the env variable to empty (in case the caller passed a value for it).
473 unsetenv(vsoc::kCuttlefishConfigEnvVarName);
474
475 return ResolveInstanceFiles();
476}
477
A. Cody Schuffelen9e2f73e2020-02-04 17:19:54 -0800478std::string cpp_basename(const std::string& str) {
479 char* copy = strdup(str.c_str()); // basename may modify its argument
480 std::string ret(basename(copy));
481 free(copy);
482 return ret;
483}
484
485bool CleanPriorFiles(const std::string& path, const std::set<std::string>& preserving) {
486 if (preserving.count(cpp_basename(path))) {
487 LOG(INFO) << "Preserving: " << path;
488 return true;
489 }
490 struct stat statbuf;
491 if (lstat(path.c_str(), &statbuf) < 0) {
492 int error_num = errno;
493 if (error_num == ENOENT) {
494 return true;
495 } else {
496 LOG(ERROR) << "Could not stat \"" << path << "\": " << strerror(error_num);
497 return false;
498 }
499 }
500 if ((statbuf.st_mode & S_IFMT) != S_IFDIR) {
501 LOG(INFO) << "Deleting: " << path;
502 if (unlink(path.c_str()) < 0) {
503 int error_num = errno;
504 LOG(ERROR) << "Could not unlink \"" << path << "\", error was " << strerror(error_num);
505 return false;
506 }
507 return true;
508 }
509 std::unique_ptr<DIR, int(*)(DIR*)> dir(opendir(path.c_str()), closedir);
510 if (!dir) {
511 int error_num = errno;
512 LOG(ERROR) << "Could not clean \"" << path << "\": error was " << strerror(error_num);
513 return false;
514 }
515 for (auto entity = readdir(dir.get()); entity != nullptr; entity = readdir(dir.get())) {
516 std::string entity_name(entity->d_name);
517 if (entity_name == "." || entity_name == "..") {
518 continue;
519 }
520 std::string entity_path = path + "/" + entity_name;
521 if (!CleanPriorFiles(entity_path.c_str(), preserving)) {
522 return false;
523 }
524 }
525 if (rmdir(path.c_str()) < 0) {
526 if (!(errno == EEXIST || errno == ENOTEMPTY)) {
527 // If EEXIST or ENOTEMPTY, probably because a file was preserved
528 int error_num = errno;
529 LOG(ERROR) << "Could not rmdir \"" << path << "\", error was " << strerror(error_num);
530 return false;
531 }
532 }
533 return true;
534}
535
536bool CleanPriorFiles(const std::vector<std::string>& paths, const std::set<std::string>& preserving) {
537 std::string prior_files;
538 for (auto path : paths) {
539 struct stat statbuf;
540 if (stat(path.c_str(), &statbuf) < 0 && errno != ENOENT) {
541 // If ENOENT, it doesn't exist yet, so there is no work to do'
542 int error_num = errno;
543 LOG(ERROR) << "Could not stat \"" << path << "\": " << strerror(error_num);
544 return false;
545 }
546 bool is_directory = (statbuf.st_mode & S_IFMT) == S_IFDIR;
547 prior_files += (is_directory ? (path + "/*") : path) + " ";
548 }
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800549 LOG(INFO) << "Assuming prior files of " << prior_files;
Alistair Delva7f09b732020-01-30 18:18:12 -0800550 std::string lsof_cmd = "lsof -t " + prior_files + " >/dev/null 2>&1";
551 int rval = std::system(lsof_cmd.c_str());
552 // lsof returns 0 if any of the files are open
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800553 if (WEXITSTATUS(rval) == 0) {
554 LOG(ERROR) << "Clean aborted: files are in use";
555 return false;
556 }
A. Cody Schuffelen9e2f73e2020-02-04 17:19:54 -0800557 for (const auto& path : paths) {
558 if (!CleanPriorFiles(path, preserving)) {
559 LOG(ERROR) << "Remove of file under \"" << path << "\" failed";
560 return false;
561 }
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800562 }
563 return true;
564}
Jorge E. Moreira80ddd7f2019-02-04 16:30:13 -0800565
A. Cody Schuffelen9e2f73e2020-02-04 17:19:54 -0800566bool CleanPriorFiles(const vsoc::CuttlefishConfig& config, const std::set<std::string>& preserving) {
567 std::vector<std::string> paths = {
568 // Everything in the assembly directory
569 FLAGS_assembly_dir,
570 // The environment file
571 GetCuttlefishEnvPath(),
572 // The global link to the config file
573 vsoc::GetGlobalConfigFileLink(),
574 };
575 for (const auto& instance : config.Instances()) {
576 paths.push_back(instance.instance_dir());
577 }
578 paths.push_back(FLAGS_instance_dir);
579 return CleanPriorFiles(paths, preserving);
580}
581
Jorge E. Moreira80ddd7f2019-02-04 16:30:13 -0800582bool DecompressKernel(const std::string& src, const std::string& dst) {
Cody Schuffelen3dff6982019-12-05 16:24:12 -0800583 cvd::Command decomp_cmd(vsoc::DefaultHostArtifactsPath("bin/extract-vmlinux"));
Jorge E. Moreira80ddd7f2019-02-04 16:30:13 -0800584 decomp_cmd.AddParameter(src);
585 auto output_file = cvd::SharedFD::Creat(dst.c_str(), 0666);
586 if (!output_file->IsOpen()) {
587 LOG(ERROR) << "Unable to create decompressed image file: "
588 << output_file->StrError();
589 return false;
590 }
591 decomp_cmd.RedirectStdIO(cvd::Subprocess::StdIOChannel::kStdOut, output_file);
Cody Schuffelene5670872019-12-10 15:04:59 -0800592 auto decomp_proc = decomp_cmd.Start();
Jorge E. Moreira80ddd7f2019-02-04 16:30:13 -0800593 return decomp_proc.Started() && decomp_proc.Wait() == 0;
594}
Cody Schuffelen78824ed2019-09-06 17:43:15 -0700595
596void ValidateAdbModeFlag(const vsoc::CuttlefishConfig& config) {
597 auto adb_modes = config.adb_mode();
598 adb_modes.erase(vsoc::AdbMode::Unknown);
599 if (adb_modes.size() < 1) {
600 LOG(INFO) << "ADB not enabled";
601 }
602}
603
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800604} // namespace
605
Cody Schuffelen3c99f5b2019-06-14 17:26:01 -0700606namespace {
607
608std::vector<ImagePartition> disk_config() {
609 std::vector<ImagePartition> partitions;
Cody Schuffelen4f7e4412019-08-30 16:10:59 -0700610 partitions.push_back(ImagePartition {
611 .label = "super",
612 .image_file_path = FLAGS_super_image,
613 });
Cody Schuffelen3c99f5b2019-06-14 17:26:01 -0700614 partitions.push_back(ImagePartition {
615 .label = "userdata",
616 .image_file_path = FLAGS_data_image,
617 });
618 partitions.push_back(ImagePartition {
619 .label = "cache",
620 .image_file_path = FLAGS_cache_image,
621 });
622 partitions.push_back(ImagePartition {
623 .label = "metadata",
624 .image_file_path = FLAGS_metadata_image,
625 });
Cody Schuffelen3c99f5b2019-06-14 17:26:01 -0700626 partitions.push_back(ImagePartition {
627 .label = "boot",
628 .image_file_path = FLAGS_boot_image,
629 });
Yifan Hong19d713e2019-05-01 14:12:07 -0700630 partitions.push_back(ImagePartition {
631 .label = "misc",
632 .image_file_path = FLAGS_misc_image
633 });
Cody Schuffelen3c99f5b2019-06-14 17:26:01 -0700634 return partitions;
635}
636
A. Cody Schuffelen9e2f73e2020-02-04 17:19:54 -0800637std::chrono::system_clock::time_point LastUpdatedInputDisk() {
638 std::chrono::system_clock::time_point ret;
Cody Schuffelen3c99f5b2019-06-14 17:26:01 -0700639 for (auto& partition : disk_config()) {
A. Cody Schuffelen9e2f73e2020-02-04 17:19:54 -0800640 auto partition_mod_time = cvd::FileModificationTime(partition.image_file_path);
641 if (partition_mod_time > ret) {
642 ret = partition_mod_time;
Cody Schuffelen3c99f5b2019-06-14 17:26:01 -0700643 }
644 }
A. Cody Schuffelen9e2f73e2020-02-04 17:19:54 -0800645 return ret;
646}
647
A. Cody Schuffelen4c287132020-02-07 17:04:23 -0800648bool ShouldCreateCompositeDisk(const vsoc::CuttlefishConfig& config) {
649 if (!cvd::FileExists(config.composite_disk_path())) {
650 return true;
651 }
652 auto composite_age = cvd::FileModificationTime(config.composite_disk_path());
A. Cody Schuffelen9e2f73e2020-02-04 17:19:54 -0800653 return composite_age < LastUpdatedInputDisk();
Cody Schuffelen3c99f5b2019-06-14 17:26:01 -0700654}
655
Ram Muthiah3db0a562019-08-26 13:35:19 -0700656bool ConcatRamdisks(const std::string& new_ramdisk_path, const std::string& ramdisk_a_path,
657 const std::string& ramdisk_b_path) {
658 // clear out file of any pre-existing content
659 std::ofstream new_ramdisk(new_ramdisk_path, std::ios_base::binary | std::ios_base::trunc);
660 std::ifstream ramdisk_a(ramdisk_a_path, std::ios_base::binary);
661 std::ifstream ramdisk_b(ramdisk_b_path, std::ios_base::binary);
Ram Muthiahaad97c52019-08-14 17:05:01 -0700662
Ram Muthiah3db0a562019-08-26 13:35:19 -0700663 if(!new_ramdisk.is_open() || !ramdisk_a.is_open() || !ramdisk_b.is_open()) {
Ram Muthiahaad97c52019-08-14 17:05:01 -0700664 return false;
665 }
666
Ram Muthiah3db0a562019-08-26 13:35:19 -0700667 new_ramdisk << ramdisk_a.rdbuf() << ramdisk_b.rdbuf();
Ram Muthiahaad97c52019-08-14 17:05:01 -0700668 return true;
669}
670
Cody Schuffelen25c46432020-01-14 13:49:52 -0800671off_t AvailableSpaceAtPath(const std::string& path) {
672 struct statvfs vfs;
673 if (statvfs(path.c_str(), &vfs) != 0) {
674 int error_num = errno;
675 LOG(ERROR) << "Could not find space available at " << path << ", error was "
676 << strerror(error_num);
677 return 0;
678 }
679 return vfs.f_bsize * vfs.f_bavail; // block size * free blocks for unprivileged users
680}
681
682off_t USERDATA_IMAGE_RESERVED = 4l * (1l << 30l); // 4 GiB
683off_t AGGREGATE_IMAGE_RESERVED = 12l * (1l << 30l); // 12 GiB
684
685bool CreateCompositeDisk(const vsoc::CuttlefishConfig& config) {
A. Cody Schuffelen4c287132020-02-07 17:04:23 -0800686 if (!cvd::SharedFD::Open(config.composite_disk_path().c_str(), O_WRONLY | O_CREAT, 0644)->IsOpen()) {
687 LOG(ERROR) << "Could not ensure " << config.composite_disk_path() << " exists";
Cody Schuffelen25c46432020-01-14 13:49:52 -0800688 return false;
Cody Schuffelen3c99f5b2019-06-14 17:26:01 -0700689 }
Cody Schuffelenc3fd6e52019-08-30 15:14:07 -0700690 if (FLAGS_vm_manager == vm_manager::CrosvmManager::name()) {
Cody Schuffelen25c46432020-01-14 13:49:52 -0800691 auto existing_size = cvd::FileSize(FLAGS_data_image);
692 auto available_space = AvailableSpaceAtPath(FLAGS_data_image);
693 if (available_space < USERDATA_IMAGE_RESERVED - existing_size) {
694 // TODO(schuffelen): Duplicate this check in run_cvd when it can run on a separate machine
695 LOG(ERROR) << "Not enough space in fs containing " << FLAGS_data_image;
696 LOG(ERROR) << "Wanted " << (USERDATA_IMAGE_RESERVED - existing_size);
697 LOG(ERROR) << "Got " << available_space;
698 return false;
699 }
Cody Schuffelena08d9dd2019-12-16 17:55:40 -0800700 std::string header_path = config.AssemblyPath("gpt_header.img");
701 std::string footer_path = config.AssemblyPath("gpt_footer.img");
A. Cody Schuffelen4c287132020-02-07 17:04:23 -0800702 CreateCompositeDisk(disk_config(), header_path, footer_path, config.composite_disk_path());
Cody Schuffelenc3fd6e52019-08-30 15:14:07 -0700703 } else {
A. Cody Schuffelen4c287132020-02-07 17:04:23 -0800704 auto existing_size = cvd::FileSize(config.composite_disk_path());
705 auto available_space = AvailableSpaceAtPath(config.composite_disk_path());
Cody Schuffelen25c46432020-01-14 13:49:52 -0800706 if (available_space < AGGREGATE_IMAGE_RESERVED - existing_size) {
A. Cody Schuffelen4c287132020-02-07 17:04:23 -0800707 LOG(ERROR) << "Not enough space to create " << config.composite_disk_path();
Cody Schuffelen25c46432020-01-14 13:49:52 -0800708 LOG(ERROR) << "Wanted " << (AGGREGATE_IMAGE_RESERVED - existing_size);
709 LOG(ERROR) << "Got " << available_space;
710 return false;
711 }
A. Cody Schuffelen4c287132020-02-07 17:04:23 -0800712 AggregateImage(disk_config(), config.composite_disk_path());
Cody Schuffelenc3fd6e52019-08-30 15:14:07 -0700713 }
Cody Schuffelen25c46432020-01-14 13:49:52 -0800714 return true;
Cody Schuffelen3c99f5b2019-06-14 17:26:01 -0700715}
716
717} // namespace
718
Cody Schuffelen605e6852019-10-16 16:22:24 -0700719const vsoc::CuttlefishConfig* InitFilesystemAndCreateConfig(
Cody Schuffelenb737ef52019-09-25 14:54:38 -0700720 int* argc, char*** argv, cvd::FetcherConfig fetcher_config) {
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800721 if (!ParseCommandLineFlags(argc, argv)) {
722 LOG(ERROR) << "Failed to parse command arguments";
Cody Schuffelene71fa352019-09-10 16:11:58 -0700723 exit(AssemblerExitCodes::kArgumentParsingError);
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800724 }
725
A. Cody Schuffelen9e2f73e2020-02-04 17:19:54 -0800726 auto boot_img_unpacker =
727 cvd::BootImageUnpacker::FromImages(FLAGS_boot_image,
728 FLAGS_vendor_boot_image);
729 {
730 // The config object is created here, but only exists in memory until the
731 // SaveConfig line below. Don't launch cuttlefish subprocesses between these
732 // two operations, as those will assume they can read the config object from
733 // disk.
734 auto config = InitializeCuttlefishConfiguration(*boot_img_unpacker, fetcher_config);
735 std::set<std::string> preserving;
A. Cody Schuffelen4c287132020-02-07 17:04:23 -0800736 if (FLAGS_resume && ShouldCreateCompositeDisk(config)) {
A. Cody Schuffelen9e2f73e2020-02-04 17:19:54 -0800737 LOG(WARNING) << "Requested resuming a previous session (the default behavior) "
738 << "but the base images have changed under the overlay, making the "
739 << "overlay incompatible. Wiping the overlay files.";
A. Cody Schuffelen4c287132020-02-07 17:04:23 -0800740 } else if (FLAGS_resume && !ShouldCreateCompositeDisk(config)) {
A. Cody Schuffelen9e2f73e2020-02-04 17:19:54 -0800741 preserving.insert("overlay.img");
742 preserving.insert("gpt_header.img");
743 preserving.insert("gpt_footer.img");
744 preserving.insert("composite.img");
745 preserving.insert("access-kregistry");
A. Cody Schuffelenc17acda2020-01-23 15:54:40 -0800746 }
A. Cody Schuffelen9e2f73e2020-02-04 17:19:54 -0800747 if (!CleanPriorFiles(config, preserving)) {
748 LOG(ERROR) << "Failed to clean prior files";
749 exit(AssemblerExitCodes::kPrioFilesCleanupError);
750 }
751 // Create assembly directory if it doesn't exist.
752 if (!cvd::DirectoryExists(FLAGS_assembly_dir.c_str())) {
753 LOG(INFO) << "Setting up " << FLAGS_assembly_dir;
754 if (mkdir(FLAGS_assembly_dir.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) < 0
755 && errno != EEXIST) {
756 LOG(ERROR) << "Failed to create assembly directory: "
757 << FLAGS_assembly_dir << ". Error: " << errno;
758 exit(AssemblerExitCodes::kAssemblyDirCreationError);
759 }
760 }
761 for (const auto& instance : config.Instances()) {
762 // Create instance directory if it doesn't exist.
763 if (!cvd::DirectoryExists(instance.instance_dir().c_str())) {
764 LOG(INFO) << "Setting up " << FLAGS_instance_dir << ".N";
765 if (mkdir(instance.instance_dir().c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) < 0
766 && errno != EEXIST) {
767 LOG(ERROR) << "Failed to create instance directory: "
768 << FLAGS_instance_dir << ". Error: " << errno;
769 exit(AssemblerExitCodes::kInstanceDirCreationError);
770 }
771 }
772 auto internal_dir = instance.instance_dir() + "/" + vsoc::kInternalDirName;
773 if (!cvd::DirectoryExists(internal_dir)) {
774 if (mkdir(internal_dir.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) < 0
775 && errno != EEXIST) {
776 LOG(ERROR) << "Failed to create internal instance directory: "
777 << internal_dir << ". Error: " << errno;
778 exit(AssemblerExitCodes::kInstanceDirCreationError);
779 }
780 }
781 }
782 if (!SaveConfig(config)) {
783 LOG(ERROR) << "Failed to initialize configuration";
784 exit(AssemblerExitCodes::kCuttlefishConfigurationInitError);
Jorge E. Moreira1e8e2f12019-10-07 18:09:49 -0700785 }
786 }
787
A. Cody Schuffelen9e2f73e2020-02-04 17:19:54 -0800788 std::string first_instance = FLAGS_instance_dir + "." + std::to_string(vsoc::GetInstance());
789 if (symlink(first_instance.c_str(), FLAGS_instance_dir.c_str()) < 0) {
790 LOG(ERROR) << "Could not symlink \"" << first_instance << "\" to \"" << FLAGS_instance_dir << "\"";
791 exit(cvd::kCuttlefishConfigurationInitError);
A. Cody Schuffelen3a60a872020-01-23 19:03:50 -0800792 }
793
Cody Schuffelen2b51bab2019-01-29 18:14:48 -0800794 if (!cvd::FileHasContent(FLAGS_boot_image)) {
795 LOG(ERROR) << "File not found: " << FLAGS_boot_image;
796 exit(cvd::kCuttlefishConfigurationInitError);
797 }
798
Ram Muthiah1aa02f82019-10-22 20:26:28 +0000799 if (!cvd::FileHasContent(FLAGS_vendor_boot_image)) {
800 LOG(ERROR) << "File not found: " << FLAGS_vendor_boot_image;
801 exit(cvd::kCuttlefishConfigurationInitError);
802 }
803
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800804 // Do this early so that the config object is ready for anything that needs it
805 auto config = vsoc::CuttlefishConfig::Get();
806 if (!config) {
807 LOG(ERROR) << "Failed to obtain config singleton";
Cody Schuffelene71fa352019-09-10 16:11:58 -0700808 exit(AssemblerExitCodes::kCuttlefishConfigurationInitError);
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800809 }
810
811 if (!boot_img_unpacker->Unpack(config->ramdisk_image_path(),
Ram Muthiah1aa02f82019-10-22 20:26:28 +0000812 config->vendor_ramdisk_image_path(),
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800813 config->use_unpacked_kernel()
814 ? config->kernel_image_path()
815 : "")) {
816 LOG(ERROR) << "Failed to unpack boot image";
Cody Schuffelene71fa352019-09-10 16:11:58 -0700817 exit(AssemblerExitCodes::kBootImageUnpackError);
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800818 }
819
Ram Muthiah1aa02f82019-10-22 20:26:28 +0000820 // TODO(134522463) as part of the bootloader refactor, repack the vendor boot
821 // image and use the bootloader to load both the boot and vendor ramdisk.
822 // Until then, this hack to get gki modules into cuttlefish will suffice.
823
824 // If a vendor ramdisk comes in via this mechanism, let it supercede the one
825 // in the vendor boot image. This flag is what kernel presubmit testing uses
826 // to pass in the kernel ramdisk.
Ram Muthiahd512c132019-10-23 17:20:45 -0700827
828 // If no kernel is passed in or an initramfs is made available, the default
829 // vendor boot ramdisk or the initramfs provided should be appended to the
830 // boot ramdisk. If a kernel IS provided with no initramfs, it is safe to
831 // safe to assume that the kernel was built with no modules and expects no
832 // modules for cf to run properly.
Cody Schuffelencd3563a2019-10-29 16:35:06 -0700833 std::string discovered_kernel = fetcher_config.FindCvdFileWithSuffix(kKernelDefaultPath);
834 std::string foreign_kernel = FLAGS_kernel_path.size() ? FLAGS_kernel_path : discovered_kernel;
835 std::string discovered_ramdisk = fetcher_config.FindCvdFileWithSuffix(kInitramfsImg);
836 std::string foreign_ramdisk = FLAGS_initramfs_path.size () ? FLAGS_initramfs_path : discovered_ramdisk;
837 if(!foreign_kernel.size() || foreign_ramdisk.size()) {
Ram Muthiahd512c132019-10-23 17:20:45 -0700838 const std::string& vendor_ramdisk_path =
839 config->initramfs_path().size() ? config->initramfs_path()
840 : config->vendor_ramdisk_image_path();
841 if(!ConcatRamdisks(config->final_ramdisk_path(),
842 config->ramdisk_image_path(), vendor_ramdisk_path)) {
843 LOG(ERROR) << "Failed to concatenate ramdisk and vendor ramdisk";
844 exit(AssemblerExitCodes::kInitRamFsConcatError);
845 }
Ram Muthiahaad97c52019-08-14 17:05:01 -0700846 }
847
Jorge E. Moreira80ddd7f2019-02-04 16:30:13 -0800848 if (config->decompress_kernel()) {
849 if (!DecompressKernel(config->kernel_image_path(),
850 config->decompressed_kernel_image_path())) {
851 LOG(ERROR) << "Failed to decompress kernel";
Cody Schuffelene71fa352019-09-10 16:11:58 -0700852 exit(AssemblerExitCodes::kKernelDecompressError);
Jorge E. Moreira80ddd7f2019-02-04 16:30:13 -0800853 }
854 }
855
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800856 ValidateAdbModeFlag(*config);
857
Yifan Hong19d713e2019-05-01 14:12:07 -0700858 // Create misc if necessary
859 if (!InitializeMiscImage(FLAGS_misc_image)) {
860 exit(cvd::kCuttlefishConfigurationInitError);
861 }
862
Cody Schuffelen2b51bab2019-01-29 18:14:48 -0800863 // Create data if necessary
Cody Schuffelen3c99f5b2019-06-14 17:26:01 -0700864 if (!ApplyDataImagePolicy(*config, FLAGS_data_image)) {
Cody Schuffelen2b51bab2019-01-29 18:14:48 -0800865 exit(cvd::kCuttlefishConfigurationInitError);
866 }
867
Cody Schuffelen69c19592019-05-31 16:00:30 -0700868 if (!cvd::FileExists(FLAGS_metadata_image)) {
869 CreateBlankImage(FLAGS_metadata_image, FLAGS_blank_metadata_image_mb, "none");
870 }
Paul Trautrimba8f8e92019-03-12 17:55:48 +0900871
A. Cody Schuffelen9e2f73e2020-02-04 17:19:54 -0800872 for (const auto& instance : config->Instances()) {
873 if (!cvd::FileExists(instance.access_kregistry_path())) {
Iliyan Malchevfc226192020-04-20 09:51:35 -0700874 CreateBlankImage(instance.access_kregistry_path(), 2, "none", "1M");
A. Cody Schuffelen9e2f73e2020-02-04 17:19:54 -0800875 }
Kenny Root1f50ee62020-01-24 12:06:19 -0800876 }
877
Cody Schuffelenb737ef52019-09-25 14:54:38 -0700878 if (SuperImageNeedsRebuilding(fetcher_config, *config)) {
879 if (!RebuildSuperImage(fetcher_config, *config, FLAGS_super_image)) {
880 LOG(ERROR) << "Super image rebuilding requested but could not be completed.";
881 exit(cvd::kCuttlefishConfigurationInitError);
882 }
883 }
884
A. Cody Schuffelen4c287132020-02-07 17:04:23 -0800885 if (ShouldCreateCompositeDisk(*config)) {
Cody Schuffelen25c46432020-01-14 13:49:52 -0800886 if (!CreateCompositeDisk(*config)) {
887 exit(cvd::kDiskSpaceError);
888 }
Cody Schuffelen3c99f5b2019-06-14 17:26:01 -0700889 }
890
A. Cody Schuffelen9e2f73e2020-02-04 17:19:54 -0800891 for (auto instance : config->Instances()) {
892 auto overlay_path = instance.PerInstancePath("overlay.img");
A. Cody Schuffelen4c287132020-02-07 17:04:23 -0800893 if (!cvd::FileExists(overlay_path) || ShouldCreateCompositeDisk(*config) || !FLAGS_resume
894 || cvd::FileModificationTime(overlay_path) < cvd::FileModificationTime(config->composite_disk_path())) {
A. Cody Schuffelen9e2f73e2020-02-04 17:19:54 -0800895 if (FLAGS_resume) {
896 LOG(WARNING) << "Requested to continue an existing session, but the overlay was "
897 << "newer than its underlying composite disk. Wiping the overlay.";
898 }
A. Cody Schuffelen4c287132020-02-07 17:04:23 -0800899 CreateQcowOverlay(config->crosvm_binary(), config->composite_disk_path(), overlay_path);
Iliyan Malchevfc226192020-04-20 09:51:35 -0700900 CreateBlankImage(instance.access_kregistry_path(), 2, "none", "1M");
A. Cody Schuffelen9e2f73e2020-02-04 17:19:54 -0800901 }
902 }
903
904 for (auto instance : config->Instances()) {
905 // Check that the files exist
906 for (const auto& file : instance.virtual_disk_paths()) {
907 if (!file.empty() && !cvd::FileHasContent(file.c_str())) {
908 LOG(ERROR) << "File not found: " << file;
909 exit(cvd::kCuttlefishConfigurationInitError);
910 }
Cody Schuffelen2b51bab2019-01-29 18:14:48 -0800911 }
912 }
913
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800914 return config;
915}
916
917std::string GetConfigFilePath(const vsoc::CuttlefishConfig& config) {
Cody Schuffelen2168c242019-12-13 16:15:27 -0800918 return config.AssemblyPath("cuttlefish_config.json");
Cody Schuffelen20ecaca2019-01-29 17:43:38 -0800919}