forked from florianl/bluebox
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtemplate.go
97 lines (86 loc) · 2.49 KB
/
template.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package main
var initTemplate string = `package main
import (
"fmt"
"os"
"io"
"os/exec"
"strings"
"syscall"
)
var execs []string= []string{
{{block "executables" .Executables}}{{range .}}{{printf "\t\"%s\",\n" .}}{{end}}{{end -}}
}
var exeArg [][]string = [][]string {
{{block "arguments" .Arguments}}{{range . -}}
{{printf "\t{"}} {{- range . -}}{{printf " \"%s\"," .}}{{end}}
{{- printf "},\n"}}
{{- end}}{{end -}}
}
func printClose(r io.ReadCloser, prefix string){
defer r.Close()
slurp, _ := io.ReadAll(r)
if len(slurp) == 0 {
return
}
fmt.Printf("[ ] %s\n%s", prefix, slurp)
}
func main() {
// Safe guard to make sure this dynamically created executable does not harm the system
// when executed by accident.
if os.Getpid() != 1 {
fmt.Fprintf(os.Stderr, "%s must only run with PID 1 for safety\n", os.Args[0])
return
}
// Create a minimal environment for the Linux kernel
{{- block "environment" .Environment}}
{{range .}}{{ print . }}{{end}}
{{- end}}
// Execute the testing executables
for i, exe := range execs {
cmd := exec.Command(fmt.Sprintf("./%s", exe), strings.Join(exeArg[i], ", "))
fmt.Printf("[ ]\t%s\n", cmd.Path)
stderr, err := cmd.StderrPipe()
if err != nil {
fmt.Printf("[ ]\tFailed to redirect stderr for '%s': %v\n", exe, err)
continue
}
stdout, err := cmd.StdoutPipe()
if err != nil {
fmt.Printf("[ ]\tFailed to redirect stdout for '%s': %v\n", exe, err)
continue
}
if err := cmd.Start(); err != nil {
fmt.Printf("[ ]\tFailure starting %s: %v\n", exe, err)
printClose(stderr, "stderr")
stdout.Close()
continue
}
for {
var s syscall.WaitStatus
var r syscall.Rusage
if p, err := syscall.Wait4(-1, &s, 0, &r); p == cmd.Process.Pid {
fmt.Printf("[ ]\t%s exited, exit status %d\n", cmd.Path, s.ExitStatus())
printClose(stderr, "stderr")
break
} else if p != -1 {
fmt.Printf("[ ]\tReaped PID %d, exit status %d\n", p, s.ExitStatus())
printClose(stderr, "stderr")
break
} else {
fmt.Printf("[ ]\tError from Wait4 for orphaned child: %v\n", err)
printClose(stderr, "stderr")
break
}
}
if err := cmd.Process.Release(); err != nil {
fmt.Printf("[ ]\tError releasing process %v: %v\n", cmd, err)
}
printClose(stdout, "stdout")
}
// Shut VM down
if err := syscall.Reboot(syscall.LINUX_REBOOT_CMD_POWER_OFF); err != nil {
fmt.Printf( "[ ]\tPower off failed: %v\n", err)
}
}
`