emulator-qemu: Fix data directory lookup.

This patch modifies the qemu launcher/wrapper to use the -L <path>
option to specify the location of the 'data directory' that contains
the BIOS and keymaps file required by QEMU.

By default, QEMU hard-codes the directory that was used for its build
(which was under /tmp/), which explains why the binary worked until
the machine was rebooted!

This requires the pc-bios/ directory from the QEMU source tree to
be copied into $OUT_DIR/qemu/pc-bios/ to work correctly, something
that should be handled by android-configure.sh at build time.

+ If userdata-qemu.img doesn't exist, create it as a copy of
  userdata.img, which is the initial version.

Change-Id: Id41f2523a9cf23ff74aea6b5f04eb211cbb164f6
diff --git a/android/qemu-launcher/emulator-qemu.cpp b/android/qemu-launcher/emulator-qemu.cpp
index 280bd58..e6b5c35 100644
--- a/android/qemu-launcher/emulator-qemu.cpp
+++ b/android/qemu-launcher/emulator-qemu.cpp
@@ -85,6 +85,16 @@
 // The target CPU architecture.
 const char kTargetArch[] = "aarch64";
 
+String getNthParentDir(const char* path, size_t n) {
+    StringVector dir = PathUtils::decompose(path);
+    PathUtils::simplifyComponents(&dir);
+    if (dir.size() < n + 1U) {
+        return String("");
+    }
+    dir.resize(dir.size() - n);
+    return PathUtils::recompose(dir);
+}
+
 // Return the path of the QEMU executable
 String getQemuExecutablePath(const char* programPath) {
     StringVector path = PathUtils::decompose(programPath);
@@ -702,6 +712,23 @@
     String qemuExecutable = getQemuExecutablePath(argv[0]);
     D("QEMU EXECUTABLE=%s\n", qemuExecutable.c_str());
 
+    // Create userdata file from init version if needed.
+    if (!path_exists(hw->disk_dataPartition_path)) {
+        if (!path_exists(hw->disk_dataPartition_initPath)) {
+            derror("Missing initial data partition file: %s",
+                   hw->disk_dataPartition_initPath);
+            exit(1);
+        }
+        D("Creating: %s\n", hw->disk_dataPartition_path);
+
+        if (path_copy_file(hw->disk_dataPartition_path,
+                           hw->disk_dataPartition_initPath) < 0) {
+            derror("Could not create %s: %s", hw->disk_dataPartition_path,
+                   strerror(errno));
+            exit(1);
+        }
+    }
+
     // Now build the QEMU parameters.
     const char* args[128];
     int n = 0;
@@ -769,6 +796,12 @@
     args[n++] = "virtio-net-device,netdev=mynet";
     args[n++] = "-show-cursor";
 
+    // Data directory (for keymaps and PC Bios).
+    args[n++] = "-L";
+    String dataDir = getNthParentDir(qemuExecutable.c_str(), 2U);
+    dataDir += "/pc-bios";
+    args[n++] = dataDir.c_str();
+
     if(VERBOSE_CHECK(init)) {
         int i;
         printf("QEMU options list:\n");