blob: caeb61baf6fd747f4ac94f204b7e52238fa035b7 [file] [log] [blame]
Tim Windelschmidt6d33a432025-02-04 14:34:25 +01001// Copyright The Monogon Project Authors.
Lorenz Brun547b33f2020-04-23 15:27:06 +02002// SPDX-License-Identifier: Apache-2.0
Lorenz Brun547b33f2020-04-23 15:27:06 +02003
Serge Bazanski216fe7b2021-05-21 18:36:16 +02004// ktestinit is an init designed to run inside a lightweight VM for running
5// tests in there. It performs basic platform initialization like mounting
6// kernel filesystems and launches the test executable at /tester, passes the
7// exit code back out over the control socket to ktest and then terminates the
8// default VM kernel.
Lorenz Brun547b33f2020-04-23 15:27:06 +02009package main
10
11import (
12 "errors"
13 "fmt"
14 "os"
15 "os/exec"
16
17 "golang.org/x/sys/unix"
18)
19
20func mountInit() error {
21 for _, el := range []struct {
22 dir string
23 fs string
24 flags uintptr
25 }{
26 {"/sys", "sysfs", unix.MS_NOEXEC | unix.MS_NOSUID | unix.MS_NODEV},
Lorenz Brun8bc82862024-04-30 11:47:09 +000027 {"/sys/kernel/debug", "debugfs", unix.MS_NOEXEC | unix.MS_NOSUID | unix.MS_NODEV},
Lorenz Brun547b33f2020-04-23 15:27:06 +020028 {"/proc", "proc", unix.MS_NOEXEC | unix.MS_NOSUID | unix.MS_NODEV},
29 {"/dev", "devtmpfs", unix.MS_NOEXEC | unix.MS_NOSUID},
30 {"/dev/pts", "devpts", unix.MS_NOEXEC | unix.MS_NOSUID},
Lorenz Brun9956e722021-03-24 18:48:55 +010031 {"/tmp", "tmpfs", 0},
Lorenz Brun547b33f2020-04-23 15:27:06 +020032 } {
33 if err := os.Mkdir(el.dir, 0755); err != nil && !os.IsExist(err) {
34 return fmt.Errorf("could not make %s: %w", el.dir, err)
35 }
36 if err := unix.Mount(el.fs, el.dir, el.fs, el.flags, ""); err != nil {
37 return fmt.Errorf("could not mount %s on %s: %w", el.fs, el.dir, err)
38 }
39 }
40 return nil
41}
42
43func main() {
44 if err := mountInit(); err != nil {
45 panic(err)
46 }
47
48 // First virtual serial is always stdout, second is control
49 ioConn, err := os.OpenFile("/dev/vport1p1", os.O_RDWR, 0)
50 if err != nil {
51 fmt.Printf("Failed to open communication device: %v\n", err)
52 return
53 }
54 cmd := exec.Command("/tester", "-test.v")
55 cmd.Stderr = os.Stderr
56 cmd.Stdout = os.Stdout
57 cmd.Env = append(cmd.Env, "IN_KTEST=true")
58 if err := cmd.Run(); err != nil {
59 var exerr *exec.ExitError
60 if errors.As(err, &exerr) {
61 if _, err := ioConn.Write([]byte{uint8(exerr.ExitCode())}); err != nil {
62 panic(err)
63 }
Lorenz Brun547b33f2020-04-23 15:27:06 +020064 }
Tim Windelschmidta27272c2024-04-11 22:54:29 +020065 fmt.Printf("Failed to execute tests (tests didn't run): %v", err)
Lorenz Brun3ff5af32020-06-24 16:34:11 +020066 } else {
67 ioConn.Write([]byte{0})
Lorenz Brun547b33f2020-04-23 15:27:06 +020068 }
Lorenz Brun3ff5af32020-06-24 16:34:11 +020069 ioConn.Close()
Lorenz Brun547b33f2020-04-23 15:27:06 +020070
71 unix.Reboot(unix.LINUX_REBOOT_CMD_RESTART)
72}