Add in-kernel test runner

This adds a way to run tests inside the Smalltown kernel.

Improvements to the Bazel part of this are tracked in T726

Test Plan: Tested by intentionally failing the test.

X-Origin-Diff: phab/D485
GitOrigin-RevId: e4aad7f28d122d82a7fcb6699e678cbe022e2f73
diff --git a/core/tools/ktest/BUILD b/core/tools/ktest/BUILD
new file mode 100644
index 0000000..e139a18
--- /dev/null
+++ b/core/tools/ktest/BUILD
@@ -0,0 +1,62 @@
+load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_library")
+load("//core/tools/kconfig-patcher:kconfig-patcher.bzl", "kconfig_patch")
+
+go_library(
+    name = "go_default_library",
+    srcs = ["main.go"],
+    importpath = "git.monogon.dev/source/nexantic.git/core/tools/ktest",
+    visibility = ["//visibility:private"],
+)
+
+go_binary(
+    name = "ktest",
+    embed = [":go_default_library"],
+    pure = "on",
+    visibility = ["//visibility:public"],
+)
+
+kconfig_patch(
+    name = "testing-config",
+    src = "//third_party/linux:kernel-config",
+    out = "testing.config",
+    override_configs = {
+        # Unlock command line
+        "CONFIG_CMDLINE_OVERRIDE": "n",
+        "CONFIG_CMDLINE_BOOL": "n",
+        # Shave off 1 second from boot time
+        "CONFIG_SERIO_I8042": "",
+        "CONFIG_KEYBOARD_ATKBD": "",
+        "CONFIG_RTC_DRV_CMOS": "",
+        # Shave off an additional 18ms (half of the boot time)
+        "CONFIG_DEBUG_WX": "",
+    },
+)
+
+genrule(
+    name = "linux-testing",
+    srcs = [
+        "@linux//:all",
+        ":testing-config",
+    ],
+    outs = [
+        "linux-testing.elf",
+    ],
+    cmd = """
+    DIR=external/linux
+
+    mkdir $$DIR/.bin
+
+    cp $(location :testing-config) $$DIR/.config
+
+    (cd $$DIR && make -j $$(nproc) vmlinux >/dev/null)
+
+    cp $$DIR/vmlinux $@
+    """,
+    visibility = ["//visibility:public"],
+)
+
+filegroup(
+    name = "test-script",
+    srcs = ["run_ktest.sh"],
+    visibility = ["//visibility:public"],
+)
diff --git a/core/tools/ktest/ktest.bzl b/core/tools/ktest/ktest.bzl
new file mode 100644
index 0000000..03a7d5c
--- /dev/null
+++ b/core/tools/ktest/ktest.bzl
@@ -0,0 +1,61 @@
+#  Copyright 2020 The Monogon Project Authors.
+#
+#  SPDX-License-Identifier: Apache-2.0
+#
+#  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.
+
+"""
+Ktest provides a simple macro to run tests inside the normal Smalltown kernel
+"""
+
+def ktest(deps, tester, initramfs_extra, cmdline):
+    native.genrule(
+        name = "test_initramfs",
+        srcs = [
+            "//core/tools/ktestinit",
+        ] + deps + [tester],
+        outs = [
+            "initramfs.cpio.lz4",
+        ],
+        testonly = True,
+        cmd = """
+        $(location @linux//:gen_init_cpio) - <<- 'EOF' | lz4 -l > \"$@\" 
+dir /dev 0755 0 0
+nod /dev/console 0600 0 0 c 5 1
+nod /dev/null 0644 0 0 c 1 3
+file /init $(location //core/tools/ktestinit) 0755 0 0
+file /tester $(location """ + tester + """) 0755 0 0
+""" + initramfs_extra + """
+EOF
+        """,
+        tools = [
+            "@linux//:gen_init_cpio",
+        ],
+    )
+
+    native.sh_test(
+        name = "ktest",
+        args = [
+            "$(location //core/tools/ktest)",
+            "$(location :test_initramfs)",
+            "$(location //core/tools/ktest:linux-testing)",
+            cmdline,
+        ],
+        size = "small",
+        srcs = ["//core/tools/ktest:test-script"],
+        data = [
+            "//core/tools/ktest",
+            ":test_initramfs",
+            "//core/tools/ktest:linux-testing",
+        ],
+    )
\ No newline at end of file
diff --git a/core/tools/ktest/main.go b/core/tools/ktest/main.go
new file mode 100644
index 0000000..67ad21a
--- /dev/null
+++ b/core/tools/ktest/main.go
@@ -0,0 +1,101 @@
+// Copyright 2020 The Monogon Project Authors.
+//
+// SPDX-License-Identifier: Apache-2.0
+//
+// 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.
+
+// ktest is a test launcher for running tests inside a custom kernel and passes the results
+// back out.
+package main
+
+import (
+	"crypto/rand"
+	"flag"
+	"fmt"
+	"io"
+	"log"
+	"net"
+	"os"
+	"os/exec"
+	"path/filepath"
+)
+
+var (
+	kernelPath = flag.String("kernel-path", "", "Path of the Kernel ELF file")
+	initrdPath = flag.String("initrd-path", "", "Path of the initrd image")
+	cmdline    = flag.String("cmdline", "", "Additional kernel command line options")
+)
+
+func main() {
+	flag.Parse()
+
+	// Create a temporary socket for passing data (currently only exit code)
+	// TODO: Land https://patchwork.ozlabs.org/project/qemu-devel/patch/1357671226-11334-1-git-send-email-alexander_barabash@mentor.com/
+	tmpDir := os.TempDir()
+	token := make([]byte, 16)
+	if _, err := io.ReadFull(rand.Reader, token); err != nil {
+		log.Fatal(err)
+	}
+
+	socketPath := filepath.Join(tmpDir, fmt.Sprintf("qemu-io-%x", token))
+	l, err := net.Listen("unix", socketPath)
+	if err != nil {
+		log.Fatal(err)
+	}
+	defer l.Close()
+	defer os.Remove(socketPath)
+
+	// Start a QEMU microvm (https://github.com/qemu/qemu/blob/master/docs/microvm.rst) with only
+	// a RNG and two character devices (one for console, one for OOB communication) attached.
+	cmd := exec.Command("qemu-system-x86_64", "-nodefaults", "-no-user-config", "-nographic", "-no-reboot",
+		"-accel", "kvm", "-cpu", "host",
+		"-M", "microvm,x-option-roms=off,pic=off,pit=off,rtc=off,isa-serial=off",
+		"-kernel", *kernelPath,
+		"-append", "reboot=t console=hvc0 quiet "+*cmdline,
+		"-initrd", *initrdPath,
+		"-device", "virtio-rng-device,max-bytes=1024,period=1000",
+		"-device", "virtio-serial-device,max_ports=2",
+		"-chardev", "stdio,id=con0", "-device", "virtconsole,chardev=con0",
+		"-chardev", "socket,id=io,path="+socketPath, "-device", "virtserialport,chardev=io",
+	)
+
+	cmd.Stdout = os.Stdout
+	cmd.Stderr = os.Stderr
+
+	exitCodeChan := make(chan uint8, 1)
+
+	go func() {
+		conn, err := l.Accept()
+		if err != nil {
+			log.Fatal(err)
+		}
+		defer conn.Close()
+
+		returnCode := make([]byte, 1)
+		if _, err := conn.Read(returnCode); err != nil && err != io.EOF {
+			log.Fatalf("Failed to read socket: %v", err)
+		}
+		exitCodeChan <- returnCode[0]
+	}()
+
+	if err := cmd.Run(); err != nil {
+		log.Fatalf("Failed to run QEMU: %v", err)
+	}
+	select {
+	case exitCode := <-exitCodeChan:
+		os.Exit(int(exitCode))
+	default:
+		log.Printf("Failed to get an error code back")
+		os.Exit(1)
+	}
+}
diff --git a/core/tools/ktest/run_ktest.sh b/core/tools/ktest/run_ktest.sh
new file mode 100755
index 0000000..02920a1
--- /dev/null
+++ b/core/tools/ktest/run_ktest.sh
@@ -0,0 +1,2 @@
+#!/bin/bash
+exec "$1" -initrd-path "$2" -kernel-path "$3" -cmdline "$4"
\ No newline at end of file