-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
97 lines (74 loc) · 1.51 KB
/
main.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
import (
"context"
"flag"
"fmt"
"io"
"log"
"os"
"os/signal"
"github.com/aryanA101a/lulu/vm"
"golang.org/x/sys/unix"
)
func main() {
logfile:=handle_commandline_args()
if logfile!=nil{
defer logfile.Close()
}
inPath := flag.Args()[0]
program, err := read_program(inPath)
if err != nil {
fmt.Printf("Error opening file(%s): %v\n", inPath, err)
os.Exit(2)
}
vm := vm.NewVM()
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, unix.SIGINT, unix.SIGTSTP)
defer stop()
go exit(ctx,vm.Stop)
vm.Start(program)
}
func handle_commandline_args() *os.File{
var (
f *os.File
verboseFlag,
helpFlag bool
logfile string
)
flag.BoolVar(&verboseFlag, "v", false, "logging")
flag.BoolVar(&helpFlag, "h", false, "help")
flag.StringVar(&logfile, "logfile", "", "path to logfile")
flag.Parse()
if helpFlag || flag.NArg() != 1 {
flag.Usage()
os.Exit(0)
}
if verboseFlag {
if logfile != "" {
var err error
f, err = os.OpenFile(logfile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
log.Printf("Error opening logfile: %v\n", err)
f.Close()
os.Exit(2)
}
log.SetOutput(f)
}
} else {
log.SetOutput(io.Discard)
}
return f
}
func read_program(file_name string) (*[]byte, error) {
log.Printf("Loading: %s", file_name)
file, err := os.ReadFile(file_name)
if err != nil {
return nil, err
}
return &file, nil
}
func exit(ctx context.Context,stopVM func()) {
<-ctx.Done()
stopVM()
log.Println("exiting!!")
os.Exit(0)
}