Handle system-as-root build kinds.

When building system-as-root, there may be no ramdisk, or a ramdisk that
is created by the 'dist' phase and not injected into the boot.img file.

If the ramdisk.img file is not present or is zero bytes in size,
consider this to be a system-as-root build and switch from passing QEMU
the initrd parameter to specifying "root= init=" on the kernel command
line.

Bug: 110097226
Change-Id: I380505a132aa32bd99475993ace996e3d56552aa
diff --git a/host/commands/launch/main.cc b/host/commands/launch/main.cc
index 9605049..3f7bd4d 100644
--- a/host/commands/launch/main.cc
+++ b/host/commands/launch/main.cc
@@ -295,8 +295,12 @@
 }
 
 bool FileExists(const char* path) {
-  struct stat unused;
-  return stat(path, &unused) != -1 || errno != ENOENT;
+  struct stat st;
+  if (stat(path, &st))
+    return false;
+  if (st.st_size == 0)
+    return false;
+  return true;
 }
 
 void CreateBlankImage(
@@ -490,6 +494,10 @@
   }
   if (FLAGS_initrd.empty()) {
     FLAGS_initrd = FLAGS_system_image_dir + "/ramdisk.img";
+    if (!FileExists(FLAGS_initrd.c_str())) {
+      LOG(WARNING) << "No ramdisk.img found; assuming system-as-root build";
+      FLAGS_initrd.clear();
+    }
   }
   if (FLAGS_cache_image.empty()) {
     FLAGS_cache_image = FLAGS_system_image_dir + "/cache.img";
@@ -509,7 +517,7 @@
   // Check that the files exist
   for (const auto& file :
        {FLAGS_system_image, FLAGS_vendor_image, FLAGS_cache_image, FLAGS_kernel,
-        FLAGS_initrd, FLAGS_data_image, FLAGS_kernel_command_line}) {
+        FLAGS_data_image, FLAGS_kernel_command_line}) {
     if (!FileExists(file.c_str())) {
       LOG(FATAL) << "File not found: " << file;
       return false;
@@ -542,6 +550,9 @@
 
   config->set_kernel_image_path(FLAGS_kernel);
   std::ostringstream extra_cmdline;
+  if (FLAGS_initrd.empty()) {
+    extra_cmdline << " root=/dev/vda init=/init";
+  }
   extra_cmdline << " androidboot.serialno=" << FLAGS_serial_number;
   extra_cmdline << " androidboot.lcd_density=" << FLAGS_dpi;
   if (FLAGS_extra_kernel_command_line.size()) {
diff --git a/host/libs/vm_manager/libvirt_manager.cpp b/host/libs/vm_manager/libvirt_manager.cpp
index 6c6f4a1..a1c830d 100644
--- a/host/libs/vm_manager/libvirt_manager.cpp
+++ b/host/libs/vm_manager/libvirt_manager.cpp
@@ -113,7 +113,9 @@
   xmlNewProp(type, xc("machine"), xc("pc"));
 
   xmlNewChild(os, nullptr, xc("kernel"), xc(kernel.c_str()));
-  xmlNewChild(os, nullptr, xc("initrd"), xc(initrd.c_str()));
+  if (!initrd.empty()) {
+    xmlNewChild(os, nullptr, xc("initrd"), xc(initrd.c_str()));
+  }
   xmlNewChild(os, nullptr, xc("cmdline"), xc(args.c_str()));
   xmlNewChild(os, nullptr, xc("dtb"), xc(dtb.c_str()));
 }