-
Notifications
You must be signed in to change notification settings - Fork 9
/
main.go
268 lines (225 loc) · 6.64 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
package main
import (
"context"
"flag"
"fmt"
"net"
"net/http"
_ "net/http/pprof"
"os"
"path/filepath"
"runtime/debug"
"github.com/stealthrocket/wasi-go"
"github.com/stealthrocket/wasi-go/imports"
"github.com/stealthrocket/wasi-go/imports/wasi_http"
"github.com/tetratelabs/wazero"
"github.com/tetratelabs/wazero/sys"
)
func printUsage() {
fmt.Printf(`wasirun - Run a WebAssembly module
USAGE:
wasirun [OPTIONS]... <MODULE> [--] [ARGS]...
ARGS:
<MODULE>
The path of the WebAssembly module to run
[ARGS]...
Arguments to pass to the module
OPTIONS:
--dir <DIR>
Grant access to the specified host directory
--listen <ADDR:PORT>
Grant access to a socket listening on the specified address
--dial <ADDR:PORT>
Grant access to a socket connected to the specified address
--dns-server <ADDR:PORT>
Sets the address of the DNS server to use for name resolution
--env-inherit
Inherits all environment variables from the calling process
--env <NAME=VAL>
Pass an environment variable to the module. Overrides
any inherited environment variables from --env-inherit
--sockets <NAME>
Enable a sockets extension, either {none, auto, path_open,
wasmedgev1, wasmedgev2}
--pprof-addr <ADDR:PORT>
Start a pprof server listening on the specified address
--trace
Enable logging of system calls (like strace)
--non-blocking-stdio
Enable non-blocking stdio
--max-open-files <N>
Limit the number of files that may be opened by the module
--max-open-dirs <N>
Limit the number of directories that may be opened by the module
--http <MODE>
Optionally enable wasi-http client support and select a
version {none, auto, v1}
--http-server-addr <host:port>
If present, assume run this module as an http server which
listens for requests on this address.
--http-server-path <path>
If present, and --http-server-addr is not empty, serve WebAssembly
on this URL prefix path. Default is '/'
-v, --version
Print the version and exit
-h, --help
Show this usage information
`)
}
var (
envInherit bool
envs stringList
dirs stringList
listens stringList
dials stringList
dnsServer string
socketExt string
pprofAddr string
wasiHttp string
wasiHttpAddr string
wasiHttpPath string
trace bool
tracerStringSize int
nonBlockingStdio bool
version bool
maxOpenFiles int
maxOpenDirs int
)
func main() {
flagSet := flag.NewFlagSet("wasirun", flag.ExitOnError)
flagSet.Usage = printUsage
flagSet.BoolVar(&envInherit, "env-inherit", false, "")
flagSet.Var(&envs, "env", "")
flagSet.Var(&dirs, "dir", "")
flagSet.Var(&listens, "listen", "")
flagSet.Var(&dials, "dial", "")
flagSet.StringVar(&dnsServer, "dns-server", "", "")
flagSet.StringVar(&socketExt, "sockets", "auto", "")
flagSet.StringVar(&pprofAddr, "pprof-addr", "", "")
flagSet.StringVar(&wasiHttp, "http", "auto", "")
flagSet.StringVar(&wasiHttpAddr, "http-server-addr", "", "")
flagSet.StringVar(&wasiHttpPath, "http-server-path", "/", "")
flagSet.BoolVar(&trace, "trace", false, "")
flagSet.IntVar(&tracerStringSize, "tracer-string-size", 32, "")
flagSet.BoolVar(&nonBlockingStdio, "non-blocking-stdio", false, "")
flagSet.BoolVar(&version, "version", false, "")
flagSet.BoolVar(&version, "v", false, "")
flagSet.IntVar(&maxOpenFiles, "max-open-files", 1024, "")
flagSet.IntVar(&maxOpenDirs, "max-open-dirs", 1024, "")
flagSet.Parse(os.Args[1:])
if version {
if info, ok := debug.ReadBuildInfo(); ok && info.Main.Version != "(devel)" {
fmt.Println("wasirun", info.Main.Version)
} else {
fmt.Println("wasirun", "devel")
}
os.Exit(0)
}
args := flagSet.Args()
if len(args) == 0 {
printUsage()
os.Exit(1)
}
if envInherit {
envs = append(append([]string{}, os.Environ()...), envs...)
}
if dnsServer != "" {
_, dnsServerPort, _ := net.SplitHostPort(dnsServer)
net.DefaultResolver.PreferGo = true
net.DefaultResolver.Dial = func(ctx context.Context, network, address string) (net.Conn, error) {
var d net.Dialer
if dnsServerPort != "" {
address = dnsServer
} else {
_, port, err := net.SplitHostPort(address)
if err != nil {
return nil, net.InvalidAddrError(address)
}
address = net.JoinHostPort(dnsServer, port)
}
return d.DialContext(ctx, network, address)
}
}
if err := run(args[0], args[1:]); err != nil {
if exitErr, ok := err.(*sys.ExitError); ok {
os.Exit(int(exitErr.ExitCode()))
}
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
}
func run(wasmFile string, args []string) error {
wasmName := filepath.Base(wasmFile)
wasmCode, err := os.ReadFile(wasmFile)
if err != nil {
return fmt.Errorf("could not read WASM file '%s': %w", wasmFile, err)
}
if len(args) > 0 && args[0] == "--" {
args = args[1:]
}
if pprofAddr != "" {
go http.ListenAndServe(pprofAddr, nil)
}
ctx := context.Background()
runtime := wazero.NewRuntime(ctx)
defer runtime.Close(ctx)
wasmModule, err := runtime.CompileModule(ctx, wasmCode)
if err != nil {
return err
}
defer wasmModule.Close(ctx)
builder := imports.NewBuilder().
WithName(wasmName).
WithArgs(args...).
WithEnv(envs...).
WithDirs(dirs...).
WithListens(listens...).
WithDials(dials...).
WithNonBlockingStdio(nonBlockingStdio).
WithSocketsExtension(socketExt, wasmModule).
WithTracer(trace, os.Stderr, wasi.WithTracerStringSize(tracerStringSize)).
WithMaxOpenFiles(maxOpenFiles).
WithMaxOpenDirs(maxOpenDirs)
var system wasi.System
ctx, system, err = builder.Instantiate(ctx, runtime)
if err != nil {
return err
}
defer system.Close(ctx)
importWasi := false
var wasiHTTP *wasi_http.WasiHTTP = nil
switch wasiHttp {
case "auto":
importWasi = wasi_http.DetectWasiHttp(wasmModule)
case "v1":
importWasi = true
case "none":
importWasi = false
default:
return fmt.Errorf("invalid value for -http '%v', expected 'auto', 'v1' or 'none'", wasiHttp)
}
if importWasi {
wasiHTTP = wasi_http.MakeWasiHTTP()
if err := wasiHTTP.Instantiate(ctx, runtime); err != nil {
return err
}
}
instance, err := runtime.InstantiateModule(ctx, wasmModule, wazero.NewModuleConfig())
if err != nil {
return err
}
if len(wasiHttpAddr) > 0 {
handler := wasiHTTP.MakeHandler(ctx, instance)
http.Handle(wasiHttpPath, handler)
return http.ListenAndServe(wasiHttpAddr, nil)
}
return instance.Close(ctx)
}
type stringList []string
func (s stringList) String() string {
return fmt.Sprintf("%v", []string(s))
}
func (s *stringList) Set(value string) error {
*s = append(*s, value)
return nil
}