blob: 9eb2342d8e46f56a2c4c592a4b4d67a4ec645013 [file] [log] [blame]
Lorenz Brun547b33f2020-04-23 15:27:06 +02001// Copyright 2020 The Monogon Project Authors.
2//
3// SPDX-License-Identifier: Apache-2.0
4//
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16
17// ktestinit is an init designed to run inside a lightweight VM for running tests in there.
18// It performs basic platform initialization like mounting kernel filesystems and launches the
19// test executable at /tester, passes the exit code back out over the control socket to ktest and
20// then terminates the VM kernel.
21package main
22
23import (
24 "errors"
25 "fmt"
26 "os"
27 "os/exec"
28
29 "golang.org/x/sys/unix"
30)
31
32func mountInit() error {
33 for _, el := range []struct {
34 dir string
35 fs string
36 flags uintptr
37 }{
38 {"/sys", "sysfs", unix.MS_NOEXEC | unix.MS_NOSUID | unix.MS_NODEV},
39 {"/proc", "proc", unix.MS_NOEXEC | unix.MS_NOSUID | unix.MS_NODEV},
40 {"/dev", "devtmpfs", unix.MS_NOEXEC | unix.MS_NOSUID},
41 {"/dev/pts", "devpts", unix.MS_NOEXEC | unix.MS_NOSUID},
42 } {
43 if err := os.Mkdir(el.dir, 0755); err != nil && !os.IsExist(err) {
44 return fmt.Errorf("could not make %s: %w", el.dir, err)
45 }
46 if err := unix.Mount(el.fs, el.dir, el.fs, el.flags, ""); err != nil {
47 return fmt.Errorf("could not mount %s on %s: %w", el.fs, el.dir, err)
48 }
49 }
50 return nil
51}
52
53func main() {
54 if err := mountInit(); err != nil {
55 panic(err)
56 }
57
58 // First virtual serial is always stdout, second is control
59 ioConn, err := os.OpenFile("/dev/vport1p1", os.O_RDWR, 0)
60 if err != nil {
61 fmt.Printf("Failed to open communication device: %v\n", err)
62 return
63 }
64 cmd := exec.Command("/tester", "-test.v")
65 cmd.Stderr = os.Stderr
66 cmd.Stdout = os.Stdout
67 cmd.Env = append(cmd.Env, "IN_KTEST=true")
68 if err := cmd.Run(); err != nil {
69 var exerr *exec.ExitError
70 if errors.As(err, &exerr) {
71 if _, err := ioConn.Write([]byte{uint8(exerr.ExitCode())}); err != nil {
72 panic(err)
73 }
74 } else if err != nil {
75 fmt.Printf("Failed to execute tests (tests didn't run): %v", err)
76 }
77 }
78
79 unix.Reboot(unix.LINUX_REBOOT_CMD_RESTART)
80}