Merge changes I717ece9c,I1e3166cb,Ife86bca2,I692bc68a,I1dd8fb3b, ... into cuttlefish-testing
am: 8b0c9e2a43

Change-Id: Idadb635bf55b564a32e5035509e79b87fbdec166
diff --git a/host/commands/launch/Android.bp b/host/commands/launch/Android.bp
index 6455672..d055973 100644
--- a/host/commands/launch/Android.bp
+++ b/host/commands/launch/Android.bp
@@ -25,6 +25,7 @@
         "process_monitor.cc",
         "launch.cc",
         "data_image.cc",
+        "flags.cc",
     ],
     header_libs: [
         "cuttlefish_glog",
diff --git a/host/commands/launch/boot_image_unpacker.cc b/host/commands/launch/boot_image_unpacker.cc
index 5558029..e830646 100644
--- a/host/commands/launch/boot_image_unpacker.cc
+++ b/host/commands/launch/boot_image_unpacker.cc
@@ -100,4 +100,26 @@
                      path);
 }
 
+bool BootImageUnpacker::Unpack(const std::string& ramdisk_image_path,
+                               const std::string& kernel_image_path) {
+  if (HasRamdiskImage()) {
+    if (!ExtractRamdiskImage(ramdisk_image_path)) {
+      LOG(ERROR) << "Error extracting ramdisk from boot image";
+      return false;
+    }
+  }
+  if (!kernel_image_path.empty()) {
+    if (HasKernelImage()) {
+      if (!ExtractKernelImage(kernel_image_path)) {
+        LOG(ERROR) << "Error extracting kernel from boot image";
+        return false;
+      }
+    } else {
+      LOG(ERROR) << "No kernel found on boot image";
+      return false;
+    }
+  }
+  return true;
+}
+
 }  // namespace cvd
diff --git a/host/commands/launch/boot_image_unpacker.h b/host/commands/launch/boot_image_unpacker.h
index 69fc7bd..05fe671 100644
--- a/host/commands/launch/boot_image_unpacker.h
+++ b/host/commands/launch/boot_image_unpacker.h
@@ -45,6 +45,9 @@
   // as root.
   bool ExtractRamdiskImage(const std::string& path) const;
 
+  bool Unpack(const std::string& ramdisk_image_path,
+              const std::string& kernel_image_path);
+
  private:
   BootImageUnpacker(SharedFD boot_image, const std::string& cmdline,
                     uint32_t kernel_image_size, uint32_t kernel_image_offset,
diff --git a/host/commands/launch/data_image.cc b/host/commands/launch/data_image.cc
index 32a9465..47ee06e 100644
--- a/host/commands/launch/data_image.cc
+++ b/host/commands/launch/data_image.cc
@@ -77,21 +77,19 @@
 }
 } // namespace
 
-bool ApplyDataImagePolicy(const char* data_image,
-                          const std::string& data_policy,
-                          int blank_data_image_mb,
-                          const std::string& blank_data_image_fmt) {
-  bool data_exists = cvd::FileHasContent(data_image);
+bool ApplyDataImagePolicy(const vsoc::CuttlefishConfig& config) {
+  std::string data_image = config.data_image_path();
+  bool data_exists = cvd::FileHasContent(data_image.c_str());
   bool remove{};
   bool create{};
   bool resize{};
 
-  if (data_policy == kDataPolicyUseExisting) {
+  if (config.data_policy() == kDataPolicyUseExisting) {
     if (!data_exists) {
       LOG(ERROR) << "Specified data image file does not exists: " << data_image;
       return false;
     }
-    if (blank_data_image_mb > 0) {
+    if (config.blank_data_image_mb() > 0) {
       LOG(ERROR) << "You should NOT use -blank_data_image_mb with -data_policy="
                  << kDataPolicyUseExisting;
       return false;
@@ -99,39 +97,40 @@
     create = false;
     remove = false;
     resize = false;
-  } else if (data_policy == kDataPolicyAlwaysCreate) {
+  } else if (config.data_policy() == kDataPolicyAlwaysCreate) {
     remove = data_exists;
     create = true;
     resize = false;
-  } else if (data_policy == kDataPolicyCreateIfMissing) {
+  } else if (config.data_policy() == kDataPolicyCreateIfMissing) {
     create = !data_exists;
     remove = false;
     resize = false;
-  } else if (data_policy == kDataPolicyResizeUpTo) {
+  } else if (config.data_policy() == kDataPolicyResizeUpTo) {
     create = false;
     remove = false;
     resize = true;
   } else {
-    LOG(ERROR) << "Invalid data_policy: " << data_policy;
+    LOG(ERROR) << "Invalid data_policy: " << config.data_policy();
     return false;
   }
 
   if (remove) {
-    RemoveFile(data_image);
+    RemoveFile(data_image.c_str());
   }
 
   if (create) {
-    if (blank_data_image_mb <= 0) {
+    if (config.blank_data_image_mb() <= 0) {
       LOG(ERROR) << "-blank_data_image_mb is required to create data image";
       return false;
     }
-    CreateBlankImage(data_image, blank_data_image_mb, blank_data_image_fmt);
+    CreateBlankImage(data_image.c_str(), config.blank_data_image_mb(),
+                     config.blank_data_image_fmt());
   } else if (resize) {
     if (!data_exists) {
       LOG(ERROR) << data_image << " does not exist, but resizing was requested";
       return false;
     }
-    return ResizeImage(data_image, blank_data_image_mb);
+    return ResizeImage(data_image.c_str(), config.blank_data_image_mb());
   } else {
     LOG(INFO) << data_image << " exists. Not creating it.";
   }
diff --git a/host/commands/launch/data_image.h b/host/commands/launch/data_image.h
index d8bae0a..bc09ce9 100644
--- a/host/commands/launch/data_image.h
+++ b/host/commands/launch/data_image.h
@@ -2,7 +2,6 @@
 
 #include <string>
 
-bool ApplyDataImagePolicy(const char* data_image,
-                          const std::string& data_policy,
-                          int blank_data_image_mb,
-                          const std::string& blank_data_image_fmt);
+#include "host/libs/config/cuttlefish_config.h"
+
+bool ApplyDataImagePolicy(const vsoc::CuttlefishConfig& config);
diff --git a/host/commands/launch/flags.cc b/host/commands/launch/flags.cc
new file mode 100644
index 0000000..96a4fb2
--- /dev/null
+++ b/host/commands/launch/flags.cc
@@ -0,0 +1,541 @@
+#include "host/commands/launch/flags.h"
+
+#include <iostream>
+
+#include <gflags/gflags.h>
+#include <glog/logging.h>
+
+#include "common/libs/utils/environment.h"
+#include "common/libs/utils/files.h"
+#include "common/vsoc/lib/vsoc_memory.h"
+#include "host/commands/launch/boot_image_unpacker.h"
+#include "host/commands/launch/data_image.h"
+#include "host/commands/launch/launch.h"
+#include "host/commands/launch/launcher_defs.h"
+#include "host/libs/vm_manager/qemu_manager.h"
+#include "host/libs/vm_manager/vm_manager.h"
+
+using vsoc::GetPerInstanceDefault;
+using cvd::LauncherExitCodes;
+
+DEFINE_string(
+    system_image, "",
+    "Path to the system image, if empty it is assumed to be a file named "
+    "system.img in the directory specified by -system_image_dir");
+DEFINE_string(cache_image, "", "Location of the cache partition image.");
+DEFINE_int32(cpus, 2, "Virtual CPU count.");
+DEFINE_string(data_image, "", "Location of the data partition image.");
+DEFINE_string(data_policy, "use_existing", "How to handle userdata partition."
+            " Either 'use_existing', 'create_if_missing', 'resize_up_to', or "
+            "'always_create'.");
+DEFINE_int32(blank_data_image_mb, 0,
+             "The size of the blank data image to generate, MB.");
+DEFINE_string(blank_data_image_fmt, "ext4",
+              "The fs format for the blank data image. Used with mkfs.");
+DEFINE_string(qemu_gdb, "",
+              "Debug flag to pass to qemu. e.g. --qemu_gdb=tcp::1234");
+
+DEFINE_int32(x_res, 720, "Width of the screen in pixels");
+DEFINE_int32(y_res, 1280, "Height of the screen in pixels");
+DEFINE_int32(dpi, 160, "Pixels per inch for the screen");
+DEFINE_int32(refresh_rate_hz, 60, "Screen refresh rate in Hertz");
+DEFINE_int32(num_screen_buffers, 3, "The number of screen buffers");
+DEFINE_string(kernel_path, "",
+              "Path to the kernel. Overrides the one from the boot image");
+DEFINE_string(extra_kernel_cmdline, "",
+              "Additional flags to put on the kernel command line");
+DEFINE_int32(loop_max_part, 7, "Maximum number of loop partitions");
+DEFINE_string(console, "ttyS0", "Console device for the guest kernel.");
+DEFINE_string(androidboot_console, "ttyS1",
+              "Console device for the Android framework");
+DEFINE_string(hardware_name, "vsoc",
+              "The codename of the device's hardware");
+DEFINE_string(guest_security, "selinux",
+              "The security module to use in the guest");
+DEFINE_bool(guest_enforce_security, false,
+            "Whether to run in enforcing mode (non permissive). Ignored if "
+            "-guest_security is empty.");
+DEFINE_bool(guest_audit_security, true,
+            "Whether to log security audits.");
+DEFINE_string(boot_image, "", "Location of cuttlefish boot image.");
+DEFINE_int32(memory_mb, 2048,
+             "Total amount of memory available for guest, MB.");
+std::string g_default_mempath{vsoc::GetDefaultMempath()};
+DEFINE_string(mempath, g_default_mempath.c_str(),
+              "Target location for the shmem file.");
+DEFINE_string(mobile_interface, "", // default handled on ParseCommandLine
+              "Network interface to use for mobile networking");
+DEFINE_string(mobile_tap_name, "", // default handled on ParseCommandLine
+              "The name of the tap interface to use for mobile");
+std::string g_default_serial_number{GetPerInstanceDefault("CUTTLEFISHCVD")};
+DEFINE_string(serial_number, g_default_serial_number.c_str(),
+              "Serial number to use for the device");
+DEFINE_string(instance_dir, "", // default handled on ParseCommandLine
+              "A directory to put all instance specific files");
+DEFINE_string(
+    vm_manager, vm_manager::QemuManager::name(),
+    "What virtual machine manager to use, one of {qemu_cli}");
+DEFINE_string(system_image_dir, vsoc::DefaultGuestImagePath(""),
+              "Location of the system partition images.");
+DEFINE_string(vendor_image, "", "Location of the vendor partition image.");
+
+DEFINE_bool(deprecated_boot_completed, false, "Log boot completed message to"
+            " host kernel. This is only used during transition of our clients."
+            " Will be deprecated soon.");
+DEFINE_bool(start_vnc_server, true, "Whether to start the vnc server process.");
+DEFINE_string(vnc_server_binary,
+              vsoc::DefaultHostArtifactsPath("bin/vnc_server"),
+              "Location of the vnc server binary.");
+DEFINE_bool(start_stream_audio, true,
+            "Whether to start the stream audio process.");
+DEFINE_string(stream_audio_binary,
+              vsoc::DefaultHostArtifactsPath("bin/stream_audio"),
+              "Location of the stream_audio binary.");
+DEFINE_string(virtual_usb_manager_binary,
+              vsoc::DefaultHostArtifactsPath("bin/virtual_usb_manager"),
+              "Location of the virtual usb manager binary.");
+DEFINE_string(kernel_log_monitor_binary,
+              vsoc::DefaultHostArtifactsPath("bin/kernel_log_monitor"),
+              "Location of the log monitor binary.");
+DEFINE_string(ivserver_binary,
+              vsoc::DefaultHostArtifactsPath("bin/ivserver"),
+              "Location of the ivshmem server binary.");
+DEFINE_int32(vnc_server_port, GetPerInstanceDefault(6444),
+             "The port on which the vnc server should listen");
+DEFINE_int32(stream_audio_port, GetPerInstanceDefault(7444),
+             "The port on which stream_audio should listen.");
+DEFINE_string(socket_forward_proxy_binary,
+              vsoc::DefaultHostArtifactsPath("bin/socket_forward_proxy"),
+              "Location of the socket_forward_proxy binary.");
+DEFINE_string(socket_vsock_proxy_binary,
+              vsoc::DefaultHostArtifactsPath("bin/socket_vsock_proxy"),
+              "Location of the socket_vsock_proxy binary.");
+DEFINE_string(adb_mode, "tunnel",
+              "Mode for adb connection. Can be 'usb' for usb forwarding, "
+              "'tunnel' for tcp connection, 'vsock_tunnel' for vsock tcp,"
+              "or a comma separated list of types as in 'usb,tunnel'");
+DEFINE_bool(run_adb_connector, true,
+            "Maintain adb connection by sending 'adb connect' commands to the "
+            "server. Only relevant with --adb_mode=tunnel or vsock_tunnel");
+DEFINE_string(adb_connector_binary,
+              vsoc::DefaultHostArtifactsPath("bin/adb_connector"),
+              "Location of the adb_connector binary. Only relevant if "
+              "--run_adb_connector is true");
+DEFINE_int32(vhci_port, GetPerInstanceDefault(0), "VHCI port to use for usb");
+DEFINE_string(guest_mac_address,
+              GetPerInstanceDefault("00:43:56:44:80:"), // 00:43:56:44:80:0x
+              "MAC address of the wifi interface to be created on the guest.");
+DEFINE_string(host_mac_address,
+              "42:00:00:00:00:00",
+              "MAC address of the wifi interface running on the host.");
+DEFINE_string(wifi_interface, "", // default handled on ParseCommandLine
+              "Network interface to use for wifi");
+DEFINE_string(wifi_tap_name, "", // default handled on ParseCommandLine
+              "The name of the tap interface to use for wifi");
+DEFINE_int32(vsock_guest_cid,
+             vsoc::GetDefaultPerInstanceVsockCid(),
+             "Guest identifier for vsock. Disabled if under 3.");
+
+// TODO(b/72969289) This should be generated
+DEFINE_string(dtb, "", "Path to the cuttlefish.dtb file");
+
+DEFINE_string(uuid, vsoc::GetPerInstanceDefault(vsoc::kDefaultUuidPrefix),
+              "UUID to use for the device. Random if not specified");
+DEFINE_bool(daemon, false,
+            "Run cuttlefish in background, the launcher exits on boot "
+            "completed/failed");
+
+DEFINE_string(device_title, "", "Human readable name for the instance, "
+              "used by the vnc_server for its server title");
+DEFINE_string(setupwizard_mode, "DISABLED",
+            "One of DISABLED,OPTIONAL,REQUIRED");
+
+DEFINE_string(qemu_binary,
+              "/usr/bin/qemu-system-x86_64",
+              "The qemu binary to use");
+DEFINE_bool(restart_subprocesses, true, "Restart any crashed host process");
+DEFINE_bool(run_e2e_test, true, "Run e2e test after device launches");
+DEFINE_string(e2e_test_binary,
+              vsoc::DefaultHostArtifactsPath("bin/host_region_e2e_test"),
+              "Location of the region end to end test binary");
+
+namespace {
+
+template<typename S, typename T>
+static std::string concat(const S& s, const T& t) {
+  std::ostringstream os;
+  os << s << t;
+  return os.str();
+}
+
+bool ResolveInstanceFiles() {
+  if (FLAGS_system_image_dir.empty()) {
+    LOG(ERROR) << "--system_image_dir must be specified.";
+    return false;
+  }
+
+  // If user did not specify location of either of these files, expect them to
+  // be placed in --system_image_dir location.
+  std::string default_system_image = FLAGS_system_image_dir + "/system.img";
+  SetCommandLineOptionWithMode("system_image", default_system_image.c_str(),
+                               google::FlagSettingMode::SET_FLAGS_DEFAULT);
+  std::string default_boot_image = FLAGS_system_image_dir + "/boot.img";
+  SetCommandLineOptionWithMode("boot_image", default_boot_image.c_str(),
+                               google::FlagSettingMode::SET_FLAGS_DEFAULT);
+  std::string default_cache_image = FLAGS_system_image_dir + "/cache.img";
+  SetCommandLineOptionWithMode("cache_image", default_cache_image.c_str(),
+                               google::FlagSettingMode::SET_FLAGS_DEFAULT);
+  std::string default_data_image = FLAGS_system_image_dir + "/userdata.img";
+  SetCommandLineOptionWithMode("data_image", default_data_image.c_str(),
+                               google::FlagSettingMode::SET_FLAGS_DEFAULT);
+  std::string default_vendor_image = FLAGS_system_image_dir + "/vendor.img";
+  SetCommandLineOptionWithMode("vendor_image", default_vendor_image.c_str(),
+                               google::FlagSettingMode::SET_FLAGS_DEFAULT);
+
+  return true;
+}
+
+std::string GetCuttlefishEnvPath() {
+  return cvd::StringFromEnv("HOME", ".") + "/.cuttlefish.sh";
+}
+
+// Initializes the config object and saves it to file. It doesn't return it, all
+// further uses of the config should happen through the singleton
+bool InitializeCuttlefishConfiguration(
+    const cvd::BootImageUnpacker& boot_image_unpacker) {
+  vsoc::CuttlefishConfig tmp_config_obj;
+  auto& memory_layout = *vsoc::VSoCMemoryLayout::Get();
+  // Set this first so that calls to PerInstancePath below are correct
+  tmp_config_obj.set_instance_dir(FLAGS_instance_dir);
+  if (!vm_manager::VmManager::IsValidName(FLAGS_vm_manager)) {
+    LOG(ERROR) << "Invalid vm_manager: " << FLAGS_vm_manager;
+    return false;
+  }
+  tmp_config_obj.set_vm_manager(FLAGS_vm_manager);
+
+  tmp_config_obj.set_serial_number(FLAGS_serial_number);
+
+  tmp_config_obj.set_cpus(FLAGS_cpus);
+  tmp_config_obj.set_memory_mb(FLAGS_memory_mb);
+
+  tmp_config_obj.set_dpi(FLAGS_dpi);
+  tmp_config_obj.set_setupwizard_mode(FLAGS_setupwizard_mode);
+  tmp_config_obj.set_x_res(FLAGS_x_res);
+  tmp_config_obj.set_y_res(FLAGS_y_res);
+  tmp_config_obj.set_num_screen_buffers(FLAGS_num_screen_buffers);
+  tmp_config_obj.set_refresh_rate_hz(FLAGS_refresh_rate_hz);
+  tmp_config_obj.set_gdb_flag(FLAGS_qemu_gdb);
+  tmp_config_obj.set_adb_mode(FLAGS_adb_mode);
+  tmp_config_obj.set_adb_ip_and_port("127.0.0.1:" + std::to_string(GetHostPort()));
+
+  tmp_config_obj.set_device_title(FLAGS_device_title);
+  if (FLAGS_kernel_path.size()) {
+    tmp_config_obj.set_kernel_image_path(FLAGS_kernel_path);
+    tmp_config_obj.set_use_unpacked_kernel(false);
+  } else {
+    tmp_config_obj.set_kernel_image_path(
+        tmp_config_obj.PerInstancePath("kernel"));
+    tmp_config_obj.set_use_unpacked_kernel(true);
+  }
+
+  auto ramdisk_path = tmp_config_obj.PerInstancePath("ramdisk.img");
+  bool use_ramdisk = boot_image_unpacker.HasRamdiskImage();
+  if (!use_ramdisk) {
+    LOG(INFO) << "No ramdisk present; assuming system-as-root build";
+    ramdisk_path = "";
+  }
+
+  // This needs to be done here because the dtb path depends on the presence of
+  // the ramdisk
+  if (FLAGS_dtb.empty()) {
+    if (use_ramdisk) {
+      FLAGS_dtb = vsoc::DefaultHostArtifactsPath("config/initrd-root.dtb");
+    } else {
+      FLAGS_dtb = vsoc::DefaultHostArtifactsPath("config/system-root.dtb");
+    }
+  }
+
+  tmp_config_obj.add_kernel_cmdline(boot_image_unpacker.kernel_cmdline());
+  if (!use_ramdisk) {
+    tmp_config_obj.add_kernel_cmdline("root=/dev/vda");
+  }
+  tmp_config_obj.add_kernel_cmdline("init=/init");
+  tmp_config_obj.add_kernel_cmdline(
+      concat("androidboot.serialno=", FLAGS_serial_number));
+  tmp_config_obj.add_kernel_cmdline("mac80211_hwsim.radios=0");
+  tmp_config_obj.add_kernel_cmdline(concat("androidboot.lcd_density=", FLAGS_dpi));
+  tmp_config_obj.add_kernel_cmdline(
+      concat("androidboot.setupwizard_mode=", FLAGS_setupwizard_mode));
+  tmp_config_obj.add_kernel_cmdline(concat("loop.max_part=", FLAGS_loop_max_part));
+  if (!FLAGS_console.empty()) {
+    tmp_config_obj.add_kernel_cmdline(concat("console=", FLAGS_console));
+  }
+  if (!FLAGS_androidboot_console.empty()) {
+    tmp_config_obj.add_kernel_cmdline(
+        concat("androidboot.console=", FLAGS_androidboot_console));
+  }
+  if (!FLAGS_hardware_name.empty()) {
+    tmp_config_obj.add_kernel_cmdline(
+        concat("androidboot.hardware=", FLAGS_hardware_name));
+  }
+  if (!FLAGS_guest_security.empty()) {
+    tmp_config_obj.add_kernel_cmdline(concat("security=", FLAGS_guest_security));
+    if (FLAGS_guest_enforce_security) {
+      tmp_config_obj.add_kernel_cmdline("enforcing=1");
+    } else {
+      tmp_config_obj.add_kernel_cmdline("enforcing=0");
+      tmp_config_obj.add_kernel_cmdline("androidboot.selinux=permissive");
+    }
+    if (FLAGS_guest_audit_security) {
+      tmp_config_obj.add_kernel_cmdline("audit=1");
+    } else {
+      tmp_config_obj.add_kernel_cmdline("audit=0");
+    }
+  }
+  if (FLAGS_run_e2e_test) {
+    tmp_config_obj.add_kernel_cmdline("androidboot.vsoc_e2e_test=1");
+  }
+  if (FLAGS_extra_kernel_cmdline.size()) {
+    tmp_config_obj.add_kernel_cmdline(FLAGS_extra_kernel_cmdline);
+  }
+
+  tmp_config_obj.set_ramdisk_image_path(ramdisk_path);
+  tmp_config_obj.set_system_image_path(FLAGS_system_image);
+  tmp_config_obj.set_cache_image_path(FLAGS_cache_image);
+  tmp_config_obj.set_data_image_path(FLAGS_data_image);
+  tmp_config_obj.set_vendor_image_path(FLAGS_vendor_image);
+  tmp_config_obj.set_dtb_path(FLAGS_dtb);
+
+  tmp_config_obj.set_mempath(FLAGS_mempath);
+  tmp_config_obj.set_ivshmem_qemu_socket_path(
+      tmp_config_obj.PerInstancePath("ivshmem_socket_qemu"));
+  tmp_config_obj.set_ivshmem_client_socket_path(
+      tmp_config_obj.PerInstancePath("ivshmem_socket_client"));
+  tmp_config_obj.set_ivshmem_vector_count(memory_layout.GetRegions().size());
+
+  if (AdbUsbEnabled(tmp_config_obj)) {
+    tmp_config_obj.set_usb_v1_socket_name(tmp_config_obj.PerInstancePath("usb-v1"));
+    tmp_config_obj.set_vhci_port(FLAGS_vhci_port);
+    tmp_config_obj.set_usb_ip_socket_name(tmp_config_obj.PerInstancePath("usb-ip"));
+  }
+
+  tmp_config_obj.set_kernel_log_socket_name(tmp_config_obj.PerInstancePath("kernel-log"));
+  tmp_config_obj.set_deprecated_boot_completed(FLAGS_deprecated_boot_completed);
+  tmp_config_obj.set_console_path(tmp_config_obj.PerInstancePath("console"));
+  tmp_config_obj.set_logcat_path(tmp_config_obj.PerInstancePath("logcat"));
+  tmp_config_obj.set_launcher_log_path(tmp_config_obj.PerInstancePath("launcher.log"));
+  tmp_config_obj.set_launcher_monitor_socket_path(
+      tmp_config_obj.PerInstancePath("launcher_monitor.sock"));
+
+  tmp_config_obj.set_mobile_bridge_name(FLAGS_mobile_interface);
+  tmp_config_obj.set_mobile_tap_name(FLAGS_mobile_tap_name);
+
+  tmp_config_obj.set_wifi_bridge_name(FLAGS_wifi_interface);
+  tmp_config_obj.set_wifi_tap_name(FLAGS_wifi_tap_name);
+
+  tmp_config_obj.set_wifi_guest_mac_addr(FLAGS_guest_mac_address);
+  tmp_config_obj.set_wifi_host_mac_addr(FLAGS_host_mac_address);
+
+  tmp_config_obj.set_vsock_guest_cid(FLAGS_vsock_guest_cid);
+
+  tmp_config_obj.set_entropy_source("/dev/urandom");
+  tmp_config_obj.set_uuid(FLAGS_uuid);
+
+  tmp_config_obj.set_qemu_binary(FLAGS_qemu_binary);
+  tmp_config_obj.set_ivserver_binary(FLAGS_ivserver_binary);
+  tmp_config_obj.set_kernel_log_monitor_binary(FLAGS_kernel_log_monitor_binary);
+
+  tmp_config_obj.set_enable_vnc_server(FLAGS_start_vnc_server);
+  tmp_config_obj.set_vnc_server_binary(FLAGS_vnc_server_binary);
+  tmp_config_obj.set_vnc_server_port(FLAGS_vnc_server_port);
+
+  tmp_config_obj.set_enable_stream_audio(FLAGS_start_stream_audio);
+  tmp_config_obj.set_stream_audio_binary(FLAGS_stream_audio_binary);
+  tmp_config_obj.set_stream_audio_port(FLAGS_stream_audio_port);
+
+  tmp_config_obj.set_restart_subprocesses(FLAGS_restart_subprocesses);
+  tmp_config_obj.set_run_adb_connector(FLAGS_run_adb_connector);
+  tmp_config_obj.set_adb_connector_binary(FLAGS_adb_connector_binary);
+  tmp_config_obj.set_virtual_usb_manager_binary(
+      FLAGS_virtual_usb_manager_binary);
+  tmp_config_obj.set_socket_forward_proxy_binary(
+      FLAGS_socket_forward_proxy_binary);
+  tmp_config_obj.set_socket_vsock_proxy_binary(FLAGS_socket_vsock_proxy_binary);
+  tmp_config_obj.set_run_as_daemon(FLAGS_daemon);
+  tmp_config_obj.set_run_e2e_test(FLAGS_run_e2e_test);
+  tmp_config_obj.set_e2e_test_binary(FLAGS_e2e_test_binary);
+
+  tmp_config_obj.set_data_policy(FLAGS_data_policy);
+  tmp_config_obj.set_blank_data_image_mb(FLAGS_blank_data_image_mb);
+  tmp_config_obj.set_blank_data_image_fmt(FLAGS_blank_data_image_fmt);
+
+  if(!AdbUsbEnabled(tmp_config_obj)) {
+    tmp_config_obj.disable_usb_adb();
+  }
+
+  tmp_config_obj.set_cuttlefish_env_path(GetCuttlefishEnvPath());
+
+  auto config_file = GetConfigFilePath(tmp_config_obj);
+  auto config_link = vsoc::GetGlobalConfigFileLink();
+  // Save the config object before starting any host process
+  if (!tmp_config_obj.SaveToFile(config_file)) {
+    LOG(ERROR) << "Unable to save config object";
+    return false;
+  }
+  setenv(vsoc::kCuttlefishConfigEnvVarName, config_file.c_str(), true);
+  if (symlink(config_file.c_str(), config_link.c_str()) != 0) {
+    LOG(ERROR) << "Failed to create symlink to config file at " << config_link
+               << ": " << strerror(errno);
+    return false;
+  }
+
+  return true;
+}
+
+void SetDefaultFlagsForQemu() {
+  auto default_mobile_interface = GetPerInstanceDefault("cvd-mbr-");
+  SetCommandLineOptionWithMode("mobile_interface",
+                               default_mobile_interface.c_str(),
+                               google::FlagSettingMode::SET_FLAGS_DEFAULT);
+  auto default_mobile_tap_name = GetPerInstanceDefault("cvd-mtap-");
+  SetCommandLineOptionWithMode("mobile_tap_name",
+                               default_mobile_tap_name.c_str(),
+                               google::FlagSettingMode::SET_FLAGS_DEFAULT);
+  auto default_wifi_interface = GetPerInstanceDefault("cvd-wbr-");
+  SetCommandLineOptionWithMode("wifi_interface",
+                               default_wifi_interface.c_str(),
+                               google::FlagSettingMode::SET_FLAGS_DEFAULT);
+  auto default_wifi_tap_name = GetPerInstanceDefault("cvd-wtap-");
+  SetCommandLineOptionWithMode("wifi_tap_name",
+                               default_wifi_tap_name.c_str(),
+                               google::FlagSettingMode::SET_FLAGS_DEFAULT);
+  auto default_instance_dir =
+      cvd::StringFromEnv("HOME", ".") + "/cuttlefish_runtime";
+  SetCommandLineOptionWithMode("instance_dir",
+                               default_instance_dir.c_str(),
+                               google::FlagSettingMode::SET_FLAGS_DEFAULT);
+}
+
+bool ParseCommandLineFlags(int* argc, char*** argv) {
+  // The config_file is created by the launcher, so the launcher is the only
+  // host process that doesn't use the flag.
+  // Set the default to empty.
+  google::SetCommandLineOptionWithMode("config_file", "",
+                                       gflags::SET_FLAGS_DEFAULT);
+  google::ParseCommandLineNonHelpFlags(argc, argv, true);
+  bool invalid_manager = false;
+  if (FLAGS_vm_manager == vm_manager::QemuManager::name()) {
+    SetDefaultFlagsForQemu();
+  } else {
+    std::cerr << "Unknown Virtual Machine Manager: " << FLAGS_vm_manager
+              << std::endl;
+    invalid_manager = true;
+  }
+  google::HandleCommandLineHelpFlags();
+  if (invalid_manager) {
+    return false;
+  }
+  // Set the env variable to empty (in case the caller passed a value for it).
+  unsetenv(vsoc::kCuttlefishConfigEnvVarName);
+
+  return ResolveInstanceFiles();
+}
+
+bool CleanPriorFiles() {
+  // Everything on the instance directory
+  std::string prior_files = FLAGS_instance_dir + "/*";
+  // The shared memory file
+  prior_files += " " + FLAGS_mempath;
+  // The environment file
+  prior_files += " " + GetCuttlefishEnvPath();
+  // The global link to the config file
+  prior_files += " " + vsoc::GetGlobalConfigFileLink();
+  LOG(INFO) << "Assuming prior files of " << prior_files;
+  std::string fuser_cmd = "fuser " + prior_files + " 2> /dev/null";
+  int rval = std::system(fuser_cmd.c_str());
+  // fuser returns 0 if any of the files are open
+  if (WEXITSTATUS(rval) == 0) {
+    LOG(ERROR) << "Clean aborted: files are in use";
+    return false;
+  }
+  std::string clean_command = "rm -rf " + prior_files;
+  rval = std::system(clean_command.c_str());
+  if (WEXITSTATUS(rval) != 0) {
+    LOG(ERROR) << "Remove of files failed";
+    return false;
+  }
+  return true;
+}
+} // namespace
+
+vsoc::CuttlefishConfig* InitFilesystemAndCreateConfig(int* argc, char*** argv) {
+  if (!ParseCommandLineFlags(argc, argv)) {
+    LOG(ERROR) << "Failed to parse command arguments";
+    exit(LauncherExitCodes::kArgumentParsingError);
+  }
+
+  // Clean up prior files before saving the config file (doing it after would
+  // delete it)
+  if (!CleanPriorFiles()) {
+    LOG(ERROR) << "Failed to clean prior files";
+    exit(LauncherExitCodes::kPrioFilesCleanupError);
+  }
+  // Create instance directory if it doesn't exist.
+  if (!cvd::DirectoryExists(FLAGS_instance_dir.c_str())) {
+    LOG(INFO) << "Setting up " << FLAGS_instance_dir;
+    if (mkdir(FLAGS_instance_dir.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) < 0) {
+      LOG(ERROR) << "Failed to create instance directory: "
+                 << FLAGS_instance_dir << ". Error: " << errno;
+      exit(LauncherExitCodes::kInstanceDirCreationError);
+    }
+  }
+
+  if (!cvd::FileHasContent(FLAGS_boot_image)) {
+    LOG(ERROR) << "File not found: " << FLAGS_boot_image;
+    exit(cvd::kCuttlefishConfigurationInitError);
+  }
+
+  auto boot_img_unpacker = cvd::BootImageUnpacker::FromImage(FLAGS_boot_image);
+
+  if (!InitializeCuttlefishConfiguration(*boot_img_unpacker)) {
+    LOG(ERROR) << "Failed to initialize configuration";
+    exit(LauncherExitCodes::kCuttlefishConfigurationInitError);
+  }
+  // Do this early so that the config object is ready for anything that needs it
+  auto config = vsoc::CuttlefishConfig::Get();
+  if (!config) {
+    LOG(ERROR) << "Failed to obtain config singleton";
+    exit(LauncherExitCodes::kCuttlefishConfigurationInitError);
+  }
+
+  if (!boot_img_unpacker->Unpack(config->ramdisk_image_path(),
+                                 config->use_unpacked_kernel()
+                                     ? config->kernel_image_path()
+                                     : "")) {
+    LOG(ERROR) << "Failed to unpack boot image";
+    exit(LauncherExitCodes::kBootImageUnpackError);
+  }
+
+  ValidateAdbModeFlag(*config);
+
+  // Create data if necessary
+  if (!ApplyDataImagePolicy(*config)) {
+    exit(cvd::kCuttlefishConfigurationInitError);
+  }
+
+  // Check that the files exist
+  for (const auto& file :
+       {config->system_image_path(), config->vendor_image_path(),
+        config->cache_image_path(), config->data_image_path()}) {
+    if (!cvd::FileHasContent(file.c_str())) {
+      LOG(ERROR) << "File not found: " << file;
+      exit(cvd::kCuttlefishConfigurationInitError);
+    }
+  }
+
+  return config;
+}
+
+std::string GetConfigFilePath(const vsoc::CuttlefishConfig& config) {
+  return config.PerInstancePath("cuttlefish_config.json");
+}
diff --git a/host/commands/launch/flags.h b/host/commands/launch/flags.h
new file mode 100644
index 0000000..9ca6f58
--- /dev/null
+++ b/host/commands/launch/flags.h
@@ -0,0 +1,6 @@
+#pragma once
+
+#include "host/libs/config/cuttlefish_config.h"
+
+vsoc::CuttlefishConfig* InitFilesystemAndCreateConfig(int* argc, char*** argv);
+std::string GetConfigFilePath(const vsoc::CuttlefishConfig& config);
diff --git a/host/commands/launch/launch.cc b/host/commands/launch/launch.cc
index 6178df7..e5a13b1 100644
--- a/host/commands/launch/launch.cc
+++ b/host/commands/launch/launch.cc
@@ -3,6 +3,7 @@
 #include <glog/logging.h>
 
 #include "common/libs/fs/shared_fd.h"
+#include "common/libs/strings/str_split.h"
 #include "common/libs/utils/size_utils.h"
 #include "common/vsoc/shm/screen_layout.h"
 #include "host/commands/launch/launcher_defs.h"
@@ -12,12 +13,74 @@
 using cvd::MonitorEntry;
 
 namespace {
+
+constexpr char kAdbModeTunnel[] = "tunnel";
+constexpr char kAdbModeVsockTunnel[] = "vsock_tunnel";
+constexpr char kAdbModeUsb[] = "usb";
+
 cvd::SharedFD CreateIvServerUnixSocket(const std::string& path) {
   return cvd::SharedFD::SocketLocalServer(path.c_str(), false, SOCK_STREAM,
                                           0666);
 }
+
+std::string GetGuestPortArg() {
+  constexpr int kEmulatorPort = 5555;
+  return std::string{"--guest_ports="} + std::to_string(kEmulatorPort);
+}
+
+std::string GetHostPortArg() {
+  return std::string{"--host_ports="} + std::to_string(GetHostPort());
+}
+
+std::string GetAdbConnectorPortArg() {
+  return std::string{"--ports="} + std::to_string(GetHostPort());
+}
+
+bool AdbModeEnabled(const vsoc::CuttlefishConfig& config, const char* mode) {
+  auto modes = cvd::StrSplit(config.adb_mode(), ',');
+  return std::find(modes.begin(), modes.end(), mode) != modes.end();
+}
+
+bool AdbTunnelEnabled(const vsoc::CuttlefishConfig& config) {
+  return AdbModeEnabled(config, kAdbModeTunnel);
+}
+
+bool AdbVsockTunnelEnabled(const vsoc::CuttlefishConfig& config) {
+  return config.vsock_guest_cid() > 2
+      && AdbModeEnabled(config, kAdbModeVsockTunnel);
+}
+
+bool AdbConnectorEnabled(const vsoc::CuttlefishConfig& config) {
+  return config.run_adb_connector()
+      && (AdbTunnelEnabled(config) || AdbVsockTunnelEnabled(config));
+}
+
+cvd::OnSocketReadyCb GetOnSubprocessExitCallback(
+    const vsoc::CuttlefishConfig& config) {
+  if (config.restart_subprocesses()) {
+    return cvd::ProcessMonitor::RestartOnExitCb;
+  } else {
+    return cvd::ProcessMonitor::DoNotMonitorCb;
+  }
+}
 } // namespace
 
+int GetHostPort() {
+  constexpr int kFirstHostPort = 6520;
+  return vsoc::GetPerInstanceDefault(kFirstHostPort);
+}
+
+bool AdbUsbEnabled(const vsoc::CuttlefishConfig& config) {
+  return AdbModeEnabled(config, kAdbModeUsb);
+}
+
+void ValidateAdbModeFlag(const vsoc::CuttlefishConfig& config) {
+  if (!AdbUsbEnabled(config) && !AdbTunnelEnabled(config)
+      && !AdbVsockTunnelEnabled(config)) {
+    LOG(INFO) << "ADB not enabled";
+  }
+}
+
 cvd::Command GetIvServerCommand(const vsoc::CuttlefishConfig& config) {
   // Resize gralloc region
   auto actual_width = cvd::AlignToPowerOf2(config.x_res() * 4, 4);// align to 16
@@ -65,6 +128,25 @@
   return kernel_log_monitor;
 }
 
+void LaunchUsbServerIfEnabled(const vsoc::CuttlefishConfig& config,
+                              cvd::ProcessMonitor* process_monitor) {
+  if (!AdbUsbEnabled(config)) {
+    return;
+  }
+  auto socket_name = config.usb_v1_socket_name();
+  auto usb_v1_server = cvd::SharedFD::SocketLocalServer(
+      socket_name.c_str(), false, SOCK_STREAM, 0666);
+  if (!usb_v1_server->IsOpen()) {
+    LOG(ERROR) << "Unable to create USB v1 server socket: "
+               << usb_v1_server->StrError();
+    std::exit(cvd::LauncherExitCodes::kUsbV1SocketError);
+  }
+  cvd::Command usb_server(config.virtual_usb_manager_binary());
+  usb_server.AddParameter("-usb_v1_fd=", usb_v1_server);
+  process_monitor->StartSubprocess(std::move(usb_server),
+                                   GetOnSubprocessExitCallback(config));
+}
+
 void LaunchVNCServerIfEnabled(const vsoc::CuttlefishConfig& config,
                               cvd::ProcessMonitor* process_monitor,
                               std::function<bool(MonitorEntry*)> callback) {
@@ -87,3 +169,38 @@
     process_monitor->StartSubprocess(std::move(stream_audio), callback);
   }
 }
+
+void LaunchAdbConnectorIfEnabled(cvd::ProcessMonitor* process_monitor,
+                                 const vsoc::CuttlefishConfig& config) {
+  if (AdbConnectorEnabled(config)) {
+    cvd::Command adb_connector(config.adb_connector_binary());
+    adb_connector.AddParameter(GetAdbConnectorPortArg());
+    process_monitor->StartSubprocess(std::move(adb_connector),
+                                     GetOnSubprocessExitCallback(config));
+  }
+}
+
+void LaunchSocketForwardProxyIfEnabled(cvd::ProcessMonitor* process_monitor,
+                                 const vsoc::CuttlefishConfig& config) {
+  if (AdbTunnelEnabled(config)) {
+    cvd::Command adb_tunnel(config.socket_forward_proxy_binary());
+    adb_tunnel.AddParameter(GetGuestPortArg());
+    adb_tunnel.AddParameter(GetHostPortArg());
+    process_monitor->StartSubprocess(std::move(adb_tunnel),
+                                     GetOnSubprocessExitCallback(config));
+  }
+}
+
+void LaunchSocketVsockProxyIfEnabled(cvd::ProcessMonitor* process_monitor,
+                                 const vsoc::CuttlefishConfig& config) {
+  if (AdbVsockTunnelEnabled(config)) {
+    cvd::Command adb_tunnel(config.socket_vsock_proxy_binary());
+    adb_tunnel.AddParameter("--guest_port=5555");
+    adb_tunnel.AddParameter(
+        std::string{"--host_port="} + std::to_string(GetHostPort()));
+    adb_tunnel.AddParameter(std::string{"--vsock_guest_cid="} +
+                            std::to_string(config.vsock_guest_cid()));
+    process_monitor->StartSubprocess(std::move(adb_tunnel),
+                                     GetOnSubprocessExitCallback(config));
+  }
+}
diff --git a/host/commands/launch/launch.h b/host/commands/launch/launch.h
index 554d358..739790a 100644
--- a/host/commands/launch/launch.h
+++ b/host/commands/launch/launch.h
@@ -6,12 +6,24 @@
 #include "host/commands/launch/process_monitor.h"
 #include "host/libs/config/cuttlefish_config.h"
 
+int GetHostPort();
+bool AdbUsbEnabled(const vsoc::CuttlefishConfig& config);
+void ValidateAdbModeFlag(const vsoc::CuttlefishConfig& config);
+
 cvd::Command GetIvServerCommand(const vsoc::CuttlefishConfig& config);
 cvd::Command GetKernelLogMonitorCommand(const vsoc::CuttlefishConfig& config,
                                         cvd::SharedFD* boot_events_pipe);
+void LaunchUsbServerIfEnabled(const vsoc::CuttlefishConfig& config,
+                              cvd::ProcessMonitor* process_monitor);
 void LaunchVNCServerIfEnabled(const vsoc::CuttlefishConfig& config,
                               cvd::ProcessMonitor* process_monitor,
                               std::function<bool(cvd::MonitorEntry*)> callback);
 void LaunchStreamAudioIfEnabled(const vsoc::CuttlefishConfig& config,
                                 cvd::ProcessMonitor* process_monitor,
                                 std::function<bool(cvd::MonitorEntry*)> callback);
+void LaunchAdbConnectorIfEnabled(cvd::ProcessMonitor* process_monitor,
+                                 const vsoc::CuttlefishConfig& config);
+void LaunchSocketForwardProxyIfEnabled(cvd::ProcessMonitor* process_monitor,
+                                 const vsoc::CuttlefishConfig& config);
+void LaunchSocketVsockProxyIfEnabled(cvd::ProcessMonitor* process_monitor,
+                                 const vsoc::CuttlefishConfig& config);
diff --git a/host/commands/launch/main.cc b/host/commands/launch/main.cc
index 41c6294..b97305e 100644
--- a/host/commands/launch/main.cc
+++ b/host/commands/launch/main.cc
@@ -49,6 +49,7 @@
 #include "common/vsoc/shm/screen_layout.h"
 #include "host/commands/launch/boot_image_unpacker.h"
 #include "host/commands/launch/data_image.h"
+#include "host/commands/launch/flags.h"
 #include "host/commands/launch/launch.h"
 #include "host/commands/launch/launcher_defs.h"
 #include "host/commands/launch/pre_launch_initializers.h"
@@ -62,229 +63,17 @@
 using vsoc::GetPerInstanceDefault;
 using cvd::LauncherExitCodes;
 
-DEFINE_string(
-    system_image, "",
-    "Path to the system image, if empty it is assumed to be a file named "
-    "system.img in the directory specified by -system_image_dir");
-DEFINE_string(cache_image, "", "Location of the cache partition image.");
-DEFINE_int32(cpus, 2, "Virtual CPU count.");
-DEFINE_string(data_image, "", "Location of the data partition image.");
-DEFINE_string(data_policy, "use_existing", "How to handle userdata partition."
-            " Either 'use_existing', 'create_if_missing', 'resize_up_to', or "
-            "'always_create'.");
-DEFINE_int32(blank_data_image_mb, 0,
-             "The size of the blank data image to generate, MB.");
-DEFINE_string(blank_data_image_fmt, "ext4",
-              "The fs format for the blank data image. Used with mkfs.");
-DEFINE_string(qemu_gdb, "",
-              "Debug flag to pass to qemu. e.g. --qemu_gdb=tcp::1234");
-
-DEFINE_int32(x_res, 720, "Width of the screen in pixels");
-DEFINE_int32(y_res, 1280, "Height of the screen in pixels");
-DEFINE_int32(dpi, 160, "Pixels per inch for the screen");
-DEFINE_int32(refresh_rate_hz, 60, "Screen refresh rate in Hertz");
-DEFINE_int32(num_screen_buffers, 3, "The number of screen buffers");
-DEFINE_string(kernel_path, "",
-              "Path to the kernel. Overrides the one from the boot image");
-DEFINE_string(extra_kernel_cmdline, "",
-              "Additional flags to put on the kernel command line");
-DEFINE_int32(loop_max_part, 7, "Maximum number of loop partitions");
-DEFINE_string(console, "ttyS0", "Console device for the guest kernel.");
-DEFINE_string(androidboot_console, "ttyS1",
-              "Console device for the Android framework");
-DEFINE_string(hardware_name, "vsoc",
-              "The codename of the device's hardware");
-DEFINE_string(guest_security, "selinux",
-              "The security module to use in the guest");
-DEFINE_bool(guest_enforce_security, false,
-            "Whether to run in enforcing mode (non permissive). Ignored if "
-            "-guest_security is empty.");
-DEFINE_bool(guest_audit_security, true,
-            "Whether to log security audits.");
-DEFINE_string(boot_image, "", "Location of cuttlefish boot image.");
-DEFINE_int32(memory_mb, 2048,
-             "Total amount of memory available for guest, MB.");
-std::string g_default_mempath{vsoc::GetDefaultMempath()};
-DEFINE_string(mempath, g_default_mempath.c_str(),
-              "Target location for the shmem file.");
-DEFINE_string(mobile_interface, "", // default handled on ParseCommandLine
-              "Network interface to use for mobile networking");
-DEFINE_string(mobile_tap_name, "", // default handled on ParseCommandLine
-              "The name of the tap interface to use for mobile");
-std::string g_default_serial_number{GetPerInstanceDefault("CUTTLEFISHCVD")};
-DEFINE_string(serial_number, g_default_serial_number.c_str(),
-              "Serial number to use for the device");
-DEFINE_string(instance_dir, "", // default handled on ParseCommandLine
-              "A directory to put all instance specific files");
-DEFINE_string(
-    vm_manager, vm_manager::QemuManager::name(),
-    "What virtual machine manager to use, one of {qemu_cli}");
-DEFINE_string(system_image_dir, vsoc::DefaultGuestImagePath(""),
-              "Location of the system partition images.");
-DEFINE_string(vendor_image, "", "Location of the vendor partition image.");
-
-DEFINE_bool(deprecated_boot_completed, false, "Log boot completed message to"
-            " host kernel. This is only used during transition of our clients."
-            " Will be deprecated soon.");
-DEFINE_bool(start_vnc_server, true, "Whether to start the vnc server process.");
-DEFINE_string(vnc_server_binary,
-              vsoc::DefaultHostArtifactsPath("bin/vnc_server"),
-              "Location of the vnc server binary.");
-DEFINE_bool(start_stream_audio, true,
-            "Whether to start the stream audio process.");
-DEFINE_string(stream_audio_binary,
-              vsoc::DefaultHostArtifactsPath("bin/stream_audio"),
-              "Location of the stream_audio binary.");
-DEFINE_string(virtual_usb_manager_binary,
-              vsoc::DefaultHostArtifactsPath("bin/virtual_usb_manager"),
-              "Location of the virtual usb manager binary.");
-DEFINE_string(kernel_log_monitor_binary,
-              vsoc::DefaultHostArtifactsPath("bin/kernel_log_monitor"),
-              "Location of the log monitor binary.");
-DEFINE_string(ivserver_binary,
-              vsoc::DefaultHostArtifactsPath("bin/ivserver"),
-              "Location of the ivshmem server binary.");
-DEFINE_int32(vnc_server_port, GetPerInstanceDefault(6444),
-             "The port on which the vnc server should listen");
-DEFINE_int32(stream_audio_port, GetPerInstanceDefault(7444),
-             "The port on which stream_audio should listen.");
-DEFINE_string(socket_forward_proxy_binary,
-              vsoc::DefaultHostArtifactsPath("bin/socket_forward_proxy"),
-              "Location of the socket_forward_proxy binary.");
-DEFINE_string(socket_vsock_proxy_binary,
-              vsoc::DefaultHostArtifactsPath("bin/socket_vsock_proxy"),
-              "Location of the socket_vsock_proxy binary.");
-DEFINE_string(adb_mode, "tunnel",
-              "Mode for adb connection. Can be 'usb' for usb forwarding, "
-              "'tunnel' for tcp connection, 'vsock_tunnel' for vsock tcp,"
-              "or a comma separated list of types as in 'usb,tunnel'");
-DEFINE_bool(run_adb_connector, true,
-            "Maintain adb connection by sending 'adb connect' commands to the "
-            "server. Only relevant with --adb_mode=tunnel or vsock_tunnel");
-DEFINE_string(adb_connector_binary,
-              vsoc::DefaultHostArtifactsPath("bin/adb_connector"),
-              "Location of the adb_connector binary. Only relevant if "
-              "--run_adb_connector is true");
-DEFINE_int32(vhci_port, GetPerInstanceDefault(0), "VHCI port to use for usb");
-DEFINE_string(guest_mac_address,
-              GetPerInstanceDefault("00:43:56:44:80:"), // 00:43:56:44:80:0x
-              "MAC address of the wifi interface to be created on the guest.");
-DEFINE_string(host_mac_address,
-              "42:00:00:00:00:00",
-              "MAC address of the wifi interface running on the host.");
-DEFINE_string(wifi_interface, "", // default handled on ParseCommandLine
-              "Network interface to use for wifi");
-DEFINE_string(wifi_tap_name, "", // default handled on ParseCommandLine
-              "The name of the tap interface to use for wifi");
-DEFINE_int32(vsock_guest_cid,
-             vsoc::GetDefaultPerInstanceVsockCid(),
-             "Guest identifier for vsock. Disabled if under 3.");
-
-// TODO(b/72969289) This should be generated
-DEFINE_string(dtb, "", "Path to the cuttlefish.dtb file");
-
-DEFINE_string(uuid, vsoc::GetPerInstanceDefault(vsoc::kDefaultUuidPrefix),
-              "UUID to use for the device. Random if not specified");
-DEFINE_bool(daemon, false,
-            "Run cuttlefish in background, the launcher exits on boot "
-            "completed/failed");
-
-DEFINE_string(device_title, "", "Human readable name for the instance, "
-              "used by the vnc_server for its server title");
-DEFINE_string(setupwizard_mode, "DISABLED",
-            "One of DISABLED,OPTIONAL,REQUIRED");
-
-DEFINE_string(qemu_binary,
-              "/usr/bin/qemu-system-x86_64",
-              "The qemu binary to use");
-DEFINE_bool(restart_subprocesses, true, "Restart any crashed host process");
-DEFINE_bool(run_e2e_test, true, "Run e2e test after device launches");
-DEFINE_string(e2e_test_binary,
-              vsoc::DefaultHostArtifactsPath("bin/host_region_e2e_test"),
-              "Location of the region end to end test binary");
-
 namespace {
 
-constexpr char kAdbModeTunnel[] = "tunnel";
-constexpr char kAdbModeVsockTunnel[] = "vsock_tunnel";
-constexpr char kAdbModeUsb[] = "usb";
-
-std::string GetConfigFilePath(const vsoc::CuttlefishConfig& config) {
-  return config.PerInstancePath("cuttlefish_config.json");
-}
-
-std::string GetGuestPortArg() {
-  constexpr int kEmulatorPort = 5555;
-  return std::string{"--guest_ports="} + std::to_string(kEmulatorPort);
-}
-
-int GetHostPort() {
-  constexpr int kFirstHostPort = 6520;
-  return vsoc::GetPerInstanceDefault(kFirstHostPort);
-}
-
-std::string GetHostPortArg() {
-  return std::string{"--host_ports="} + std::to_string(GetHostPort());
-}
-
-std::string GetAdbConnectorPortArg() {
-  return std::string{"--ports="} + std::to_string(GetHostPort());
-}
-
-bool AdbModeEnabled(const char* mode) {
-  auto modes = cvd::StrSplit(FLAGS_adb_mode, ',');
-  return std::find(modes.begin(), modes.end(), mode) != modes.end();
-}
-
-bool AdbTunnelEnabled() {
-  return AdbModeEnabled(kAdbModeTunnel);
-}
-
-bool AdbVsockTunnelEnabled() {
-  return FLAGS_vsock_guest_cid > 2 && AdbModeEnabled(kAdbModeVsockTunnel);
-}
-
-bool AdbUsbEnabled() {
-  return AdbModeEnabled(kAdbModeUsb);
-}
-
-void ValidateAdbModeFlag() {
-  if (!AdbUsbEnabled() && !AdbTunnelEnabled() && !AdbVsockTunnelEnabled()) {
-    LOG(INFO) << "ADB not enabled";
-  }
-}
-
-bool AdbConnectorEnabled() {
-  return FLAGS_run_adb_connector && (AdbTunnelEnabled() || AdbVsockTunnelEnabled());
-}
-
-bool OnSubprocessExitCallback(cvd::MonitorEntry* entry) {
-  if (FLAGS_restart_subprocesses) {
-    return cvd::ProcessMonitor::RestartOnExitCb(entry);
+cvd::OnSocketReadyCb GetOnSubprocessExitCallback(
+    const vsoc::CuttlefishConfig& config) {
+  if (config.restart_subprocesses()) {
+    return cvd::ProcessMonitor::RestartOnExitCb;
   } else {
-    return cvd::ProcessMonitor::DoNotMonitorCb(entry);
+    return cvd::ProcessMonitor::DoNotMonitorCb;
   }
 }
 
-void LaunchUsbServerIfEnabled(const vsoc::CuttlefishConfig& config,
-                              cvd::ProcessMonitor* process_monitor) {
-  if (!AdbUsbEnabled()) {
-    return;
-  }
-  auto socket_name = config.usb_v1_socket_name();
-  auto usb_v1_server = cvd::SharedFD::SocketLocalServer(
-      socket_name.c_str(), false, SOCK_STREAM, 0666);
-  if (!usb_v1_server->IsOpen()) {
-    LOG(ERROR) << "Unable to create USB v1 server socket: "
-               << usb_v1_server->StrError();
-    std::exit(cvd::LauncherExitCodes::kUsbV1SocketError);
-  }
-  cvd::Command usb_server(FLAGS_virtual_usb_manager_binary);
-  usb_server.AddParameter("-usb_v1_fd=", usb_v1_server);
-  process_monitor->StartSubprocess(std::move(usb_server),
-                                   OnSubprocessExitCallback);
-}
-
 // Maintains the state of the boot process, once a final state is reached
 // (success or failure) it sends the appropriate exit code to the foreground
 // launcher process
@@ -381,10 +170,11 @@
 }
 
 void LaunchE2eTest(cvd::ProcessMonitor* process_monitor,
-                   std::shared_ptr<CvdBootStateMachine> state_machine) {
+                   std::shared_ptr<CvdBootStateMachine> state_machine,
+                   const vsoc::CuttlefishConfig& config) {
   // Run a command that always succeeds if we are not running e2e tests
   std::string e2e_test_cmd =
-      FLAGS_run_e2e_test ? FLAGS_e2e_test_binary : "/bin/true";
+      config.run_e2e_test() ? config.e2e_test_binary() : "/bin/true";
   process_monitor->StartSubprocess(
       cvd::Command(e2e_test_cmd),
       [state_machine](cvd::MonitorEntry* entry) {
@@ -394,369 +184,6 @@
       });
 }
 
-void LaunchAdbConnectorIfEnabled(cvd::ProcessMonitor* process_monitor) {
-  if (AdbConnectorEnabled()) {
-    cvd::Command adb_connector(FLAGS_adb_connector_binary);
-    adb_connector.AddParameter(GetAdbConnectorPortArg());
-    process_monitor->StartSubprocess(std::move(adb_connector),
-                                     OnSubprocessExitCallback);
-  }
-}
-
-void LaunchSocketForwardProxyIfEnabled(cvd::ProcessMonitor* process_monitor) {
-  if (AdbTunnelEnabled()) {
-    cvd::Command adb_tunnel(FLAGS_socket_forward_proxy_binary);
-    adb_tunnel.AddParameter(GetGuestPortArg());
-    adb_tunnel.AddParameter(GetHostPortArg());
-    process_monitor->StartSubprocess(std::move(adb_tunnel),
-                                     OnSubprocessExitCallback);
-  }
-}
-
-void LaunchSocketVsockProxyIfEnabled(cvd::ProcessMonitor* process_monitor) {
-  if (AdbVsockTunnelEnabled()) {
-    cvd::Command adb_tunnel(FLAGS_socket_vsock_proxy_binary);
-    adb_tunnel.AddParameter("--guest_port=5555");
-    adb_tunnel.AddParameter(
-        std::string{"--host_port="} + std::to_string(GetHostPort()));
-    adb_tunnel.AddParameter(
-        std::string{"--vsock_guest_cid="} + std::to_string(FLAGS_vsock_guest_cid));
-    process_monitor->StartSubprocess(std::move(adb_tunnel),
-                                     OnSubprocessExitCallback);
-  }
-}
-
-bool ResolveInstanceFiles() {
-  if (FLAGS_system_image_dir.empty()) {
-    LOG(ERROR) << "--system_image_dir must be specified.";
-    return false;
-  }
-
-  // If user did not specify location of either of these files, expect them to
-  // be placed in --system_image_dir location.
-  if (FLAGS_system_image.empty()) {
-    FLAGS_system_image = FLAGS_system_image_dir + "/system.img";
-  }
-  if (FLAGS_boot_image.empty()) {
-    FLAGS_boot_image = FLAGS_system_image_dir + "/boot.img";
-  }
-  if (FLAGS_cache_image.empty()) {
-    FLAGS_cache_image = FLAGS_system_image_dir + "/cache.img";
-  }
-  if (FLAGS_data_image.empty()) {
-    FLAGS_data_image = FLAGS_system_image_dir + "/userdata.img";
-  }
-  if (FLAGS_vendor_image.empty()) {
-    FLAGS_vendor_image = FLAGS_system_image_dir + "/vendor.img";
-  }
-
-  // Create data if necessary
-  if (!ApplyDataImagePolicy(FLAGS_data_image.c_str(),
-                            FLAGS_data_policy,
-                            FLAGS_blank_data_image_mb,
-                            FLAGS_blank_data_image_fmt)) {
-    return false;
-  }
-
-  // Check that the files exist
-  for (const auto& file :
-       {FLAGS_system_image, FLAGS_vendor_image, FLAGS_cache_image,
-        FLAGS_data_image, FLAGS_boot_image}) {
-    if (!cvd::FileHasContent(file.c_str())) {
-      LOG(ERROR) << "File not found: " << file;
-      return false;
-    }
-  }
-  return true;
-}
-
-bool UnpackBootImage(const cvd::BootImageUnpacker& boot_image_unpacker,
-                     const vsoc::CuttlefishConfig& config) {
-  if (boot_image_unpacker.HasRamdiskImage()) {
-    if (!boot_image_unpacker.ExtractRamdiskImage(
-            config.ramdisk_image_path())) {
-      LOG(ERROR) << "Error extracting ramdisk from boot image";
-      return false;
-    }
-  }
-  if (!FLAGS_kernel_path.size()) {
-    if (boot_image_unpacker.HasKernelImage()) {
-      if (!boot_image_unpacker.ExtractKernelImage(
-              config.kernel_image_path())) {
-        LOG(ERROR) << "Error extracting kernel from boot image";
-        return false;
-      }
-    } else {
-      LOG(ERROR) << "No kernel found on boot image";
-      return false;
-    }
-  }
-  return true;
-}
-
-template<typename S, typename T>
-static std::string concat(const S& s, const T& t) {
-  std::ostringstream os;
-  os << s << t;
-  return os.str();
-}
-
-std::string GetCuttlefishEnvPath() {
-  return cvd::StringFromEnv("HOME", ".") + "/.cuttlefish.sh";
-}
-
-// Initializes the config object and saves it to file. It doesn't return it, all
-// further uses of the config should happen through the singleton
-bool InitializeCuttlefishConfiguration(
-    const cvd::BootImageUnpacker& boot_image_unpacker) {
-  vsoc::CuttlefishConfig tmp_config_obj;
-  auto& memory_layout = *vsoc::VSoCMemoryLayout::Get();
-  // Set this first so that calls to PerInstancePath below are correct
-  tmp_config_obj.set_instance_dir(FLAGS_instance_dir);
-  if (!vm_manager::VmManager::IsValidName(FLAGS_vm_manager)) {
-    LOG(ERROR) << "Invalid vm_manager: " << FLAGS_vm_manager;
-    return false;
-  }
-  tmp_config_obj.set_vm_manager(FLAGS_vm_manager);
-
-  tmp_config_obj.set_serial_number(FLAGS_serial_number);
-
-  tmp_config_obj.set_cpus(FLAGS_cpus);
-  tmp_config_obj.set_memory_mb(FLAGS_memory_mb);
-
-  tmp_config_obj.set_dpi(FLAGS_dpi);
-  tmp_config_obj.set_setupwizard_mode(FLAGS_setupwizard_mode);
-  tmp_config_obj.set_x_res(FLAGS_x_res);
-  tmp_config_obj.set_y_res(FLAGS_y_res);
-  tmp_config_obj.set_num_screen_buffers(FLAGS_num_screen_buffers);
-  tmp_config_obj.set_refresh_rate_hz(FLAGS_refresh_rate_hz);
-  tmp_config_obj.set_gdb_flag(FLAGS_qemu_gdb);
-  tmp_config_obj.set_adb_mode(FLAGS_adb_mode);
-  tmp_config_obj.set_adb_ip_and_port("127.0.0.1:" + std::to_string(GetHostPort()));
-
-  tmp_config_obj.set_device_title(FLAGS_device_title);
-  if (FLAGS_kernel_path.size()) {
-    tmp_config_obj.set_kernel_image_path(FLAGS_kernel_path);
-  } else {
-    tmp_config_obj.set_kernel_image_path(
-        tmp_config_obj.PerInstancePath("kernel"));
-  }
-
-  auto ramdisk_path = tmp_config_obj.PerInstancePath("ramdisk.img");
-  bool use_ramdisk = boot_image_unpacker.HasRamdiskImage();
-  if (!use_ramdisk) {
-    LOG(INFO) << "No ramdisk present; assuming system-as-root build";
-    ramdisk_path = "";
-  }
-
-  // This needs to be done here because the dtb path depends on the presence of
-  // the ramdisk
-  if (FLAGS_dtb.empty()) {
-    if (use_ramdisk) {
-      FLAGS_dtb = vsoc::DefaultHostArtifactsPath("config/initrd-root.dtb");
-    } else {
-      FLAGS_dtb = vsoc::DefaultHostArtifactsPath("config/system-root.dtb");
-    }
-  }
-
-  tmp_config_obj.add_kernel_cmdline(boot_image_unpacker.kernel_cmdline());
-  if (!use_ramdisk) {
-    tmp_config_obj.add_kernel_cmdline("root=/dev/vda");
-  }
-  tmp_config_obj.add_kernel_cmdline("init=/init");
-  tmp_config_obj.add_kernel_cmdline(
-      concat("androidboot.serialno=", FLAGS_serial_number));
-  tmp_config_obj.add_kernel_cmdline("mac80211_hwsim.radios=0");
-  tmp_config_obj.add_kernel_cmdline(concat("androidboot.lcd_density=", FLAGS_dpi));
-  tmp_config_obj.add_kernel_cmdline(
-      concat("androidboot.setupwizard_mode=", FLAGS_setupwizard_mode));
-  tmp_config_obj.add_kernel_cmdline(concat("loop.max_part=", FLAGS_loop_max_part));
-  if (!FLAGS_console.empty()) {
-    tmp_config_obj.add_kernel_cmdline(concat("console=", FLAGS_console));
-  }
-  if (!FLAGS_androidboot_console.empty()) {
-    tmp_config_obj.add_kernel_cmdline(
-        concat("androidboot.console=", FLAGS_androidboot_console));
-  }
-  if (!FLAGS_hardware_name.empty()) {
-    tmp_config_obj.add_kernel_cmdline(
-        concat("androidboot.hardware=", FLAGS_hardware_name));
-  }
-  if (!FLAGS_guest_security.empty()) {
-    tmp_config_obj.add_kernel_cmdline(concat("security=", FLAGS_guest_security));
-    if (FLAGS_guest_enforce_security) {
-      tmp_config_obj.add_kernel_cmdline("enforcing=1");
-    } else {
-      tmp_config_obj.add_kernel_cmdline("enforcing=0");
-      tmp_config_obj.add_kernel_cmdline("androidboot.selinux=permissive");
-    }
-    if (FLAGS_guest_audit_security) {
-      tmp_config_obj.add_kernel_cmdline("audit=1");
-    } else {
-      tmp_config_obj.add_kernel_cmdline("audit=0");
-    }
-  }
-  if (FLAGS_run_e2e_test) {
-    tmp_config_obj.add_kernel_cmdline("androidboot.vsoc_e2e_test=1");
-  }
-  if (FLAGS_extra_kernel_cmdline.size()) {
-    tmp_config_obj.add_kernel_cmdline(FLAGS_extra_kernel_cmdline);
-  }
-
-  tmp_config_obj.set_ramdisk_image_path(ramdisk_path);
-  tmp_config_obj.set_system_image_path(FLAGS_system_image);
-  tmp_config_obj.set_cache_image_path(FLAGS_cache_image);
-  tmp_config_obj.set_data_image_path(FLAGS_data_image);
-  tmp_config_obj.set_vendor_image_path(FLAGS_vendor_image);
-  tmp_config_obj.set_dtb_path(FLAGS_dtb);
-
-  tmp_config_obj.set_mempath(FLAGS_mempath);
-  tmp_config_obj.set_ivshmem_qemu_socket_path(
-      tmp_config_obj.PerInstancePath("ivshmem_socket_qemu"));
-  tmp_config_obj.set_ivshmem_client_socket_path(
-      tmp_config_obj.PerInstancePath("ivshmem_socket_client"));
-  tmp_config_obj.set_ivshmem_vector_count(memory_layout.GetRegions().size());
-
-  if (AdbUsbEnabled()) {
-    tmp_config_obj.set_usb_v1_socket_name(tmp_config_obj.PerInstancePath("usb-v1"));
-    tmp_config_obj.set_vhci_port(FLAGS_vhci_port);
-    tmp_config_obj.set_usb_ip_socket_name(tmp_config_obj.PerInstancePath("usb-ip"));
-  }
-
-  tmp_config_obj.set_kernel_log_socket_name(tmp_config_obj.PerInstancePath("kernel-log"));
-  tmp_config_obj.set_deprecated_boot_completed(FLAGS_deprecated_boot_completed);
-  tmp_config_obj.set_console_path(tmp_config_obj.PerInstancePath("console"));
-  tmp_config_obj.set_logcat_path(tmp_config_obj.PerInstancePath("logcat"));
-  tmp_config_obj.set_launcher_log_path(tmp_config_obj.PerInstancePath("launcher.log"));
-  tmp_config_obj.set_launcher_monitor_socket_path(
-      tmp_config_obj.PerInstancePath("launcher_monitor.sock"));
-
-  tmp_config_obj.set_mobile_bridge_name(FLAGS_mobile_interface);
-  tmp_config_obj.set_mobile_tap_name(FLAGS_mobile_tap_name);
-
-  tmp_config_obj.set_wifi_bridge_name(FLAGS_wifi_interface);
-  tmp_config_obj.set_wifi_tap_name(FLAGS_wifi_tap_name);
-
-  tmp_config_obj.set_wifi_guest_mac_addr(FLAGS_guest_mac_address);
-  tmp_config_obj.set_wifi_host_mac_addr(FLAGS_host_mac_address);
-
-  tmp_config_obj.set_vsock_guest_cid(FLAGS_vsock_guest_cid);
-
-  tmp_config_obj.set_entropy_source("/dev/urandom");
-  tmp_config_obj.set_uuid(FLAGS_uuid);
-
-  tmp_config_obj.set_qemu_binary(FLAGS_qemu_binary);
-  tmp_config_obj.set_ivserver_binary(FLAGS_ivserver_binary);
-  tmp_config_obj.set_kernel_log_monitor_binary(FLAGS_kernel_log_monitor_binary);
-
-  tmp_config_obj.set_enable_vnc_server(FLAGS_start_vnc_server);
-  tmp_config_obj.set_vnc_server_binary(FLAGS_vnc_server_binary);
-  tmp_config_obj.set_vnc_server_port(FLAGS_vnc_server_port);
-
-  tmp_config_obj.set_enable_stream_audio(FLAGS_start_stream_audio);
-  tmp_config_obj.set_stream_audio_binary(FLAGS_stream_audio_binary);
-  tmp_config_obj.set_stream_audio_port(FLAGS_stream_audio_port);
-
-  if(!AdbUsbEnabled()) {
-    tmp_config_obj.disable_usb_adb();
-  }
-
-  tmp_config_obj.set_cuttlefish_env_path(GetCuttlefishEnvPath());
-
-  auto config_file = GetConfigFilePath(tmp_config_obj);
-  auto config_link = vsoc::GetGlobalConfigFileLink();
-  // Save the config object before starting any host process
-  if (!tmp_config_obj.SaveToFile(config_file)) {
-    LOG(ERROR) << "Unable to save config object";
-    return false;
-  }
-  setenv(vsoc::kCuttlefishConfigEnvVarName, config_file.c_str(), true);
-  if (symlink(config_file.c_str(), config_link.c_str()) != 0) {
-    LOG(ERROR) << "Failed to create symlink to config file at " << config_link
-               << ": " << strerror(errno);
-    return false;
-  }
-
-  return true;
-}
-
-void SetDefaultFlagsForQemu() {
-  auto default_mobile_interface = GetPerInstanceDefault("cvd-mbr-");
-  SetCommandLineOptionWithMode("mobile_interface",
-                               default_mobile_interface.c_str(),
-                               google::FlagSettingMode::SET_FLAGS_DEFAULT);
-  auto default_mobile_tap_name = GetPerInstanceDefault("cvd-mtap-");
-  SetCommandLineOptionWithMode("mobile_tap_name",
-                               default_mobile_tap_name.c_str(),
-                               google::FlagSettingMode::SET_FLAGS_DEFAULT);
-  auto default_wifi_interface = GetPerInstanceDefault("cvd-wbr-");
-  SetCommandLineOptionWithMode("wifi_interface",
-                               default_wifi_interface.c_str(),
-                               google::FlagSettingMode::SET_FLAGS_DEFAULT);
-  auto default_wifi_tap_name = GetPerInstanceDefault("cvd-wtap-");
-  SetCommandLineOptionWithMode("wifi_tap_name",
-                               default_wifi_tap_name.c_str(),
-                               google::FlagSettingMode::SET_FLAGS_DEFAULT);
-  auto default_instance_dir =
-      cvd::StringFromEnv("HOME", ".") + "/cuttlefish_runtime";
-  SetCommandLineOptionWithMode("instance_dir",
-                               default_instance_dir.c_str(),
-                               google::FlagSettingMode::SET_FLAGS_DEFAULT);
-}
-
-bool ParseCommandLineFlags(int* argc, char*** argv) {
-  // The config_file is created by the launcher, so the launcher is the only
-  // host process that doesn't use the flag.
-  // Set the default to empty.
-  google::SetCommandLineOptionWithMode("config_file", "",
-                                       gflags::SET_FLAGS_DEFAULT);
-  google::ParseCommandLineNonHelpFlags(argc, argv, true);
-  bool invalid_manager = false;
-  if (FLAGS_vm_manager == vm_manager::QemuManager::name()) {
-    SetDefaultFlagsForQemu();
-  } else {
-    std::cerr << "Unknown Virtual Machine Manager: " << FLAGS_vm_manager
-              << std::endl;
-    invalid_manager = true;
-  }
-  google::HandleCommandLineHelpFlags();
-  if (invalid_manager) {
-    return false;
-  }
-  // Set the env variable to empty (in case the caller passed a value for it).
-  unsetenv(vsoc::kCuttlefishConfigEnvVarName);
-
-  ValidateAdbModeFlag();
-
-  return ResolveInstanceFiles();
-}
-
-bool CleanPriorFiles() {
-  // Everything on the instance directory
-  std::string prior_files = FLAGS_instance_dir + "/*";
-  // The shared memory file
-  prior_files += " " + FLAGS_mempath;
-  // The environment file
-  prior_files += " " + GetCuttlefishEnvPath();
-  // The global link to the config file
-  prior_files += " " + vsoc::GetGlobalConfigFileLink();
-  LOG(INFO) << "Assuming prior files of " << prior_files;
-  std::string fuser_cmd = "fuser " + prior_files + " 2> /dev/null";
-  int rval = std::system(fuser_cmd.c_str());
-  // fuser returns 0 if any of the files are open
-  if (WEXITSTATUS(rval) == 0) {
-    LOG(ERROR) << "Clean aborted: files are in use";
-    return false;
-  }
-  std::string clean_command = "rm -rf " + prior_files;
-  rval = std::system(clean_command.c_str());
-  if (WEXITSTATUS(rval) != 0) {
-    LOG(ERROR) << "Remove of files failed";
-    return false;
-  }
-  return true;
-}
-
 bool WriteCuttlefishEnvironment(const vsoc::CuttlefishConfig& config) {
   auto env = cvd::SharedFD::Open(config.cuttlefish_env_path().c_str(),
                                  O_CREAT | O_RDWR, 0755);
@@ -767,7 +194,7 @@
   std::string config_env = "export CUTTLEFISH_PER_INSTANCE_PATH=\"" +
                            config.PerInstancePath(".") + "\"\n";
   config_env += "export ANDROID_SERIAL=";
-  if (AdbUsbEnabled()) {
+  if (AdbUsbEnabled(config)) {
     config_env += config.serial_number();
   } else {
     config_env += "127.0.0.1:" + std::to_string(GetHostPort());
@@ -908,39 +335,8 @@
 
 int main(int argc, char** argv) {
   ::android::base::InitLogging(argv, android::base::StderrLogger);
-  if (!ParseCommandLineFlags(&argc, &argv)) {
-    LOG(ERROR) << "Failed to parse command arguments";
-    return LauncherExitCodes::kArgumentParsingError;
-  }
 
-  // Clean up prior files before saving the config file (doing it after would
-  // delete it)
-  if (!CleanPriorFiles()) {
-    LOG(ERROR) << "Failed to clean prior files";
-    return LauncherExitCodes::kPrioFilesCleanupError;
-  }
-  // Create instance directory if it doesn't exist.
-  if (!cvd::DirectoryExists(FLAGS_instance_dir.c_str())) {
-    LOG(INFO) << "Setting up " << FLAGS_instance_dir;
-    if (mkdir(FLAGS_instance_dir.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) < 0) {
-      LOG(ERROR) << "Failed to create instance directory: "
-                 << FLAGS_instance_dir << ". Error: " << errno;
-      return LauncherExitCodes::kInstanceDirCreationError;
-    }
-  }
-
-  auto boot_img_unpacker = cvd::BootImageUnpacker::FromImage(FLAGS_boot_image);
-
-  if (!InitializeCuttlefishConfiguration(*boot_img_unpacker)) {
-    LOG(ERROR) << "Failed to initialize configuration";
-    return LauncherExitCodes::kCuttlefishConfigurationInitError;
-  }
-  // Do this early so that the config object is ready for anything that needs it
-  auto config = vsoc::CuttlefishConfig::Get();
-  if (!config) {
-    LOG(ERROR) << "Failed to obtain config singleton";
-    return LauncherExitCodes::kCuttlefishConfigurationInitError;
-  }
+  auto config = InitFilesystemAndCreateConfig(&argc, &argv);
 
   auto vm_manager = vm_manager::VmManager::Get(config->vm_manager(), config);
 
@@ -957,17 +353,12 @@
     return LauncherExitCodes::kInvalidHostConfiguration;
   }
 
-  if (!UnpackBootImage(*boot_img_unpacker, *config)) {
-    LOG(ERROR) << "Failed to unpack boot image";
-    return LauncherExitCodes::kBootImageUnpackError;
-  }
-
   if (!WriteCuttlefishEnvironment(*config)) {
     LOG(ERROR) << "Unable to write cuttlefish environment file";
   }
 
   LOG(INFO) << "The following files contain useful debugging information:";
-  if (FLAGS_daemon) {
+  if (config->run_as_daemon()) {
     LOG(INFO) << "  Launcher log: " << config->launcher_log_path();
   }
   LOG(INFO) << "  Android's logcat output: " << config->logcat_path();
@@ -986,7 +377,7 @@
     return cvd::LauncherExitCodes::kMonitorCreationFailed;
   }
   cvd::SharedFD foreground_launcher_pipe;
-  if (FLAGS_daemon) {
+  if (config->run_as_daemon()) {
     foreground_launcher_pipe = DaemonizeLauncher(*config);
     if (!foreground_launcher_pipe->IsOpen()) {
       return LauncherExitCodes::kDaemonizationError;
@@ -1013,8 +404,10 @@
   // Only subscribe to boot events if running as daemon
   process_monitor.StartSubprocess(
       GetKernelLogMonitorCommand(*config,
-                                 FLAGS_daemon ? &boot_events_pipe : nullptr),
-      OnSubprocessExitCallback);
+                                 config->run_as_daemon()
+                                   ? &boot_events_pipe
+                                   : nullptr),
+      GetOnSubprocessExitCallback(*config));
 
   SetUpHandlingOfBootEvents(&process_monitor, boot_events_pipe,
                             boot_state_machine);
@@ -1023,25 +416,26 @@
 
   process_monitor.StartSubprocess(
       GetIvServerCommand(*config),
-      OnSubprocessExitCallback);
+      GetOnSubprocessExitCallback(*config));
 
   // Initialize the regions that require so before the VM starts.
   PreLaunchInitializers::Initialize(*config);
 
   // Launch the e2e test after the shared memory is initialized
-  LaunchE2eTest(&process_monitor, boot_state_machine);
+  LaunchE2eTest(&process_monitor, boot_state_machine, *config);
 
   // Start the guest VM
   process_monitor.StartSubprocess(vm_manager->StartCommand(),
-                                  OnSubprocessExitCallback);
+                                  GetOnSubprocessExitCallback(*config));
 
   // Start other host processes
-  LaunchSocketForwardProxyIfEnabled(&process_monitor);
-  LaunchSocketVsockProxyIfEnabled(&process_monitor);
-  LaunchVNCServerIfEnabled(*config, &process_monitor, OnSubprocessExitCallback);
+  LaunchSocketForwardProxyIfEnabled(&process_monitor, *config);
+  LaunchSocketVsockProxyIfEnabled(&process_monitor, *config);
+  LaunchVNCServerIfEnabled(*config, &process_monitor,
+                           GetOnSubprocessExitCallback(*config));
   LaunchStreamAudioIfEnabled(*config, &process_monitor,
-                             OnSubprocessExitCallback);
-  LaunchAdbConnectorIfEnabled(&process_monitor);
+                             GetOnSubprocessExitCallback(*config));
+  LaunchAdbConnectorIfEnabled(&process_monitor, *config);
 
   ServerLoop(launcher_monitor_socket, vm_manager); // Should not return
   LOG(ERROR) << "The server loop returned, it should never happen!!";
diff --git a/host/libs/config/cuttlefish_config.cpp b/host/libs/config/cuttlefish_config.cpp
index ec6e588..8c3cb96 100644
--- a/host/libs/config/cuttlefish_config.cpp
+++ b/host/libs/config/cuttlefish_config.cpp
@@ -78,6 +78,7 @@
 const char* kRefreshRateHz = "refresh_rate_hz";
 
 const char* kKernelImagePath = "kernel_image_path";
+const char* kUseUnpackedKernel = "use_unpacked_kernel";
 const char* kGdbFlag = "gdb_flag";
 const char* kKernelCmdline = "kernel_cmdline";
 const char* kRamdiskImagePath = "ramdisk_image_path";
@@ -129,6 +130,21 @@
 const char* kEnableStreamAudio = "enable_stream_audio";
 const char* kStreamAudioBinary = "stream_audio_binary";
 const char* kStreamAudioPort = "stream_audio_port";
+
+const char* kRestartSubprocesses = "restart_subprocesses";
+const char* kRunAdbConnector = "run_adb_connector";
+const char* kAdbConnectorBinary = "adb_connector_binary";
+const char* kVirtualUsbManagerBinary = "virtual_usb_manager_binary";
+const char* kSocketForwardProxyBinary = "socket_forward_proxy_binary";
+const char* kSocketVsockProxyBinary = "socket_vsock_proxy_binary";
+
+const char* kRunAsDaemon = "run_as_daemon";
+const char* kRunE2eTest = "run_e2e_test";
+const char* kE2eTestBinary = "e2e_test_binary";
+
+const char* kDataPolicy = "data_policy";
+const char* kBlankDataImageMb = "blank_data_image_mb";
+const char* kBlankDataImageFmt = "blank_data_image_fmt";
 }  // namespace
 
 namespace vsoc {
@@ -203,6 +219,14 @@
   SetPath(kKernelImagePath, kernel_image_path);
 }
 
+bool CuttlefishConfig::use_unpacked_kernel() const {
+  return (*dictionary_)[kUseUnpackedKernel].asBool();
+}
+
+void CuttlefishConfig::set_use_unpacked_kernel(bool use_unpacked_kernel) {
+  (*dictionary_)[kUseUnpackedKernel] = use_unpacked_kernel;
+}
+
 std::string CuttlefishConfig::gdb_flag() const {
   return (*dictionary_)[kGdbFlag].asString();
 }
@@ -591,6 +615,106 @@
   (*dictionary_)[kStreamAudioPort] = stream_audio_port;
 }
 
+bool CuttlefishConfig::restart_subprocesses() const {
+  return (*dictionary_)[kRestartSubprocesses].asBool();
+}
+
+void CuttlefishConfig::set_restart_subprocesses(bool restart_subprocesses) {
+  (*dictionary_)[kRestartSubprocesses] = restart_subprocesses;
+}
+
+bool CuttlefishConfig::run_adb_connector() const {
+  return (*dictionary_)[kRestartSubprocesses].asBool();
+}
+
+void CuttlefishConfig::set_run_adb_connector(bool run_adb_connector) {
+  (*dictionary_)[kRunAdbConnector] = run_adb_connector;
+}
+
+std::string CuttlefishConfig::adb_connector_binary() const {
+  return (*dictionary_)[kAdbConnectorBinary].asString();
+}
+
+void CuttlefishConfig::set_adb_connector_binary(
+    const std::string& adb_connector_binary) {
+  (*dictionary_)[kAdbConnectorBinary] = adb_connector_binary;
+}
+
+std::string CuttlefishConfig::virtual_usb_manager_binary() const {
+  return (*dictionary_)[kVirtualUsbManagerBinary].asString();
+}
+
+void CuttlefishConfig::set_virtual_usb_manager_binary(
+    const std::string& virtual_usb_manager_binary) {
+  (*dictionary_)[kVirtualUsbManagerBinary] = virtual_usb_manager_binary;
+}
+
+std::string CuttlefishConfig::socket_forward_proxy_binary() const {
+  return (*dictionary_)[kSocketForwardProxyBinary].asString();
+}
+
+void CuttlefishConfig::set_socket_forward_proxy_binary(
+    const std::string& socket_forward_proxy_binary) {
+  (*dictionary_)[kSocketForwardProxyBinary] = socket_forward_proxy_binary;
+}
+
+std::string CuttlefishConfig::socket_vsock_proxy_binary() const {
+  return (*dictionary_)[kSocketVsockProxyBinary].asString();
+}
+
+void CuttlefishConfig::set_socket_vsock_proxy_binary(
+    const std::string& socket_vsock_proxy_binary) {
+  (*dictionary_)[kSocketVsockProxyBinary] = socket_vsock_proxy_binary;
+}
+
+bool CuttlefishConfig::run_as_daemon() const {
+  return (*dictionary_)[kRunAsDaemon].asBool();
+}
+
+void CuttlefishConfig::set_run_as_daemon(bool run_as_daemon) {
+  (*dictionary_)[kRunAsDaemon] = run_as_daemon;
+}
+
+bool CuttlefishConfig::run_e2e_test() const {
+  return (*dictionary_)[kRunE2eTest].asBool();
+}
+
+void CuttlefishConfig::set_run_e2e_test(bool run_e2e_test) {
+  (*dictionary_)[kRunE2eTest] = run_e2e_test;
+}
+
+std::string CuttlefishConfig::e2e_test_binary() const {
+  return (*dictionary_)[kE2eTestBinary].asString();
+}
+
+void CuttlefishConfig::set_e2e_test_binary(const std::string& e2e_test_binary) {
+  (*dictionary_)[kE2eTestBinary] = e2e_test_binary;
+}
+
+std::string CuttlefishConfig::data_policy() const {
+  return (*dictionary_)[kDataPolicy].asString();
+}
+
+void CuttlefishConfig::set_data_policy(const std::string& data_policy) {
+  (*dictionary_)[kDataPolicy] = data_policy;
+}
+
+int CuttlefishConfig::blank_data_image_mb() const {
+  return (*dictionary_)[kBlankDataImageMb].asBool();
+}
+
+void CuttlefishConfig::set_blank_data_image_mb(int blank_data_image_mb) {
+  (*dictionary_)[kBlankDataImageMb] = blank_data_image_mb;
+}
+
+std::string CuttlefishConfig::blank_data_image_fmt() const {
+  return (*dictionary_)[kBlankDataImageFmt].asString();
+}
+
+void CuttlefishConfig::set_blank_data_image_fmt(const std::string& blank_data_image_fmt) {
+  (*dictionary_)[kBlankDataImageFmt] = blank_data_image_fmt;
+}
+
 // Creates the (initially empty) config object and populates it with values from
 // the config file if the CUTTLEFISH_CONFIG_FILE env variable is present.
 // Returns nullptr if there was an error loading from file
diff --git a/host/libs/config/cuttlefish_config.h b/host/libs/config/cuttlefish_config.h
index 9a9fa53..2a4e558 100644
--- a/host/libs/config/cuttlefish_config.h
+++ b/host/libs/config/cuttlefish_config.h
@@ -84,6 +84,9 @@
   std::string kernel_image_path() const;
   void set_kernel_image_path(const std::string& kernel_image_path);
 
+  bool use_unpacked_kernel() const;
+  void set_use_unpacked_kernel(bool use_unpacked_kernel);
+
   std::set<std::string> kernel_cmdline() const;
   void set_kernel_cmdline(const std::set<std::string>& kernel_cmdline);
   void add_kernel_cmdline(const std::string& arg);
@@ -227,6 +230,42 @@
   void set_stream_audio_binary(const std::string& stream_audio_binary);
   std::string stream_audio_binary() const;
 
+  void set_restart_subprocesses(bool restart_subprocesses);
+  bool restart_subprocesses() const;
+
+  void set_run_adb_connector(bool run_adb_connector);
+  bool run_adb_connector() const;
+
+  void set_adb_connector_binary(const std::string& adb_connector_binary);
+  std::string adb_connector_binary() const;
+
+  void set_virtual_usb_manager_binary(const std::string& binary);
+  std::string virtual_usb_manager_binary() const;
+
+  void set_socket_forward_proxy_binary(const std::string& binary);
+  std::string socket_forward_proxy_binary() const;
+
+  void set_socket_vsock_proxy_binary(const std::string& binary);
+  std::string socket_vsock_proxy_binary() const;
+
+  void set_run_as_daemon(bool run_as_daemon);
+  bool run_as_daemon() const;
+
+  void set_run_e2e_test(bool run_e2e_test);
+  bool run_e2e_test() const;
+
+  void set_e2e_test_binary(const std::string& e2e_test_binary);
+  std::string e2e_test_binary() const;
+
+  void set_data_policy(const std::string& data_policy);
+  std::string data_policy() const;
+
+  void set_blank_data_image_mb(int blank_data_image_mb);
+  int blank_data_image_mb() const;
+
+  void set_blank_data_image_fmt(const std::string& blank_data_image_fmt);
+  std::string blank_data_image_fmt() const;
+
  private:
   std::unique_ptr<Json::Value> dictionary_;