Add init process for test guest VMs

Guest VMs need an init process to be invoked by the GKI kernel. This
process needs to do two things:

1) load vendor kernel modules
For example, GKI does not come with vsock-virtio built in. The ramdisk
will contain vsock-virtio as a kernel module and it is the init's job to
load it.

2) execute a test binary
The init process is given parameters from the kernel command line
(/proc/cmdline). We will use these parameters to invoke a test binary
packaged in the ramdisk, eg. /bin/vsock_server. When init is done with
everything else, it calls execve() to run the specified binary and
passes remaining arguments to it.

This CL adds an init process as a static C++ binary. C++ was chosen
because of dependency on libmodprobe for loading kernel modules.

Test: m virt_hostside_tests_guest_init
      (may not work until later in the series due to path depth limits)
Change-Id: I7b461504850174c435b0e4d666117b97836dff4f
diff --git a/tests/hostside/native/init/Android.bp b/tests/hostside/native/init/Android.bp
new file mode 100644
index 0000000..a98948b
--- /dev/null
+++ b/tests/hostside/native/init/Android.bp
@@ -0,0 +1,25 @@
+// Copyright (C) 2020 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+cc_binary {
+    name: "virt_hostside_tests_guest_init",
+    srcs: ["main.cc"],
+    static_executable: true,
+    installable: false,
+    static_libs: [
+        "libbase",
+        "liblog",
+        "libmodprobe",
+    ],
+}
diff --git a/tests/hostside/native/init/main.cc b/tests/hostside/native/init/main.cc
new file mode 100644
index 0000000..fe4cc80
--- /dev/null
+++ b/tests/hostside/native/init/main.cc
@@ -0,0 +1,125 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <dirent.h>
+#include <sys/mount.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <sys/utsname.h>
+#include <sys/wait.h>
+#include <unistd.h>
+
+#include <cstdlib>
+#include <filesystem>
+#include <fstream>
+#include <iostream>
+#include <memory>
+#include <string>
+#include <vector>
+
+#include <modprobe/modprobe.h>
+
+#include "android-base/logging.h"
+#include "android-base/strings.h"
+
+using namespace android::base;
+
+static constexpr const char MODULE_BASE_DIR[] = "/lib/modules";
+
+bool LoadKernelModules() {
+    struct utsname uts;
+    if (uname(&uts)) {
+        LOG(ERROR) << "Failed to get kernel version.";
+        return false;
+    }
+    int major, minor;
+    if (sscanf(uts.release, "%d.%d", &major, &minor) != 2) {
+        LOG(ERROR) << "Failed to parse kernel version " << uts.release;
+        return false;
+    }
+
+    std::unique_ptr<DIR, decltype(&closedir)> base_dir(opendir(MODULE_BASE_DIR), closedir);
+    if (!base_dir) {
+        LOG(ERROR) << "Unable to open /lib/modules, skipping module loading.";
+        return false;
+    }
+    dirent* entry;
+    std::vector<std::string> module_dirs;
+    while ((entry = readdir(base_dir.get()))) {
+        if (entry->d_type != DT_DIR) {
+            continue;
+        }
+        int dir_major, dir_minor;
+        if (sscanf(entry->d_name, "%d.%d", &dir_major, &dir_minor) != 2 || dir_major != major ||
+            dir_minor != minor) {
+            continue;
+        }
+        module_dirs.emplace_back(entry->d_name);
+    }
+
+    // Sort the directories so they are iterated over during module loading
+    // in a consistent order. Alphabetical sorting is fine here because the
+    // kernel version at the beginning of the directory name must match the
+    // current kernel version, so the sort only applies to a label that
+    // follows the kernel version, for example /lib/modules/5.4 vs.
+    // /lib/modules/5.4-gki.
+    std::sort(module_dirs.begin(), module_dirs.end());
+
+    for (const auto& module_dir : module_dirs) {
+        std::string dir_path(MODULE_BASE_DIR);
+        dir_path.append("/");
+        dir_path.append(module_dir);
+        Modprobe m({dir_path});
+        bool retval = m.LoadListedModules();
+        int modules_loaded = m.GetModuleCount();
+        if (modules_loaded > 0) {
+            return retval;
+        }
+    }
+
+    Modprobe m({MODULE_BASE_DIR});
+    bool retval = m.LoadListedModules();
+    int modules_loaded = m.GetModuleCount();
+    if (modules_loaded > 0) {
+        return retval;
+    }
+
+    return true;
+}
+
+int main(int argc, const char* argv[]) {
+    SetLogger(StderrLogger);
+
+    LOG(INFO) << "Guest VM init process";
+    LOG(INFO) << "Command line: " << Join(std::vector(argv, argv + argc), " ");
+
+    if (clearenv() != EXIT_SUCCESS) {
+        PLOG(ERROR) << "clearenv";
+        return EXIT_FAILURE;
+    }
+
+    LOG(INFO) << "Loading kernel modules...";
+    if (!LoadKernelModules()) {
+        LOG(ERROR) << "LoadKernelModules failed";
+        return EXIT_FAILURE;
+    }
+
+    LOG(INFO) << "Executing test binary " << argv[1] << "...";
+    execv(argv[1], (char**)(argv + 1));
+
+    PLOG(ERROR) << "execv";
+    return EXIT_FAILURE;
+}