Skip to content

Commit a17de43

Browse files
chrisogopherbot
authored andcommitted
net: implement wasip1 FileListener and FileConn
Implements net.FileListener and net.FileConn for wasip1. net.FileListener can be used with a pre-opened socket. If the WASM module knows the file descriptor, a listener can be constructed with: l, err := net.FileListener(os.NewFile(fd, "")) If the WASM module does not know the file descriptor, but knows that at least one of the preopens is a socket, it can find the file descriptor and construct a listener like so: func findListener() (net.Listener, error) { // We start looking for pre-opened sockets at fd=3 because 0, 1, // and 2 are reserved for stdio. Pre-opened directories also // start at fd=3, so we skip fds that aren't sockets. Once we // reach EBADF we know there are no more pre-opens. for preopenFd := uintptr(3); ; preopenFd++ { l, err := net.FileListener(os.NewFile(preopenFd, "")) var se syscall.Errno switch errors.As(err, &se); se { case syscall.ENOTSOCK: continue case syscall.EBADF: err = nil } return l, err } } A similar strategy can be used with net.FileConn and pre-opened connection sockets. The wasmtime runtime supports pre-opening listener sockets: $ wasmtime --tcplisten 127.0.0.1:8080 module.wasm Change-Id: Iec6ae4ffa84b3753cce4f56a2817e150445db643 Reviewed-on: https://go-review.googlesource.com/c/go/+/493358 Reviewed-by: Matthew Dempsky <mdempsky@google.com> Run-TryBot: Ian Lance Taylor <iant@golang.org> Reviewed-by: Dmitri Shuralyov <dmitshur@golang.org> TryBot-Bypass: Dmitri Shuralyov <dmitshur@google.com> Reviewed-by: Johan Brandhorst-Satzkorn <johan.brandhorst@gmail.com> Auto-Submit: Johan Brandhorst-Satzkorn <johan.brandhorst@gmail.com> Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
1 parent c5c2184 commit a17de43

16 files changed

+665
-176
lines changed

misc/wasm/go_wasip1_wasm_exec

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,10 @@ case "$GOWASIRUNTIME" in
1111
exec wasmer run --dir=/ --env PWD="$PWD" ${GOWASIRUNTIMEARGS:-} "$1" -- "${@:2}"
1212
;;
1313
"wasmtime")
14-
exec wasmtime run --dir=/ --env PWD="$PWD" --max-wasm-stack 1048576 "$1" -- "${@:2}"
14+
exec wasmtime run --dir=/ --env PWD="$PWD" --max-wasm-stack 1048576 ${GOWASIRUNTIMEARGS:-} "$1" -- "${@:2}"
1515
;;
1616
"wazero" | "")
17-
exec wazero run -mount /:/ -env-inherit -cachedir "${TMPDIR:-/tmp}"/wazero "$1" "${@:2}"
17+
exec wazero run -mount /:/ -env-inherit -cachedir "${TMPDIR:-/tmp}"/wazero ${GOWASIRUNTIMEARGS:-} "$1" "${@:2}"
1818
;;
1919
*)
2020
echo "Unknown Go WASI runtime specified: $GOWASIRUNTIME"

src/internal/poll/fd_unix.go

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,8 @@ type FD struct {
5252
// or "file".
5353
// Set pollable to true if fd should be managed by runtime netpoll.
5454
func (fd *FD) Init(net string, pollable bool) error {
55+
fd.SysFile.init()
56+
5557
// We don't actually care about the various network types.
5658
if net == "file" {
5759
fd.isFile = true
@@ -76,12 +78,7 @@ func (fd *FD) destroy() error {
7678
// so this must be executed before CloseFunc.
7779
fd.pd.close()
7880

79-
// We don't use ignoringEINTR here because POSIX does not define
80-
// whether the descriptor is closed if close returns EINTR.
81-
// If the descriptor is indeed closed, using a loop would race
82-
// with some other goroutine opening a new descriptor.
83-
// (The Linux kernel guarantees that it is closed on an EINTR error.)
84-
err := CloseFunc(fd.Sysfd)
81+
err := fd.SysFile.destroy(fd.Sysfd)
8582

8683
fd.Sysfd = -1
8784
runtime_Semrelease(&fd.csema)

src/internal/poll/fd_unixjs.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,17 @@ type SysFile struct {
1313
iovecs *[]syscall.Iovec
1414
}
1515

16+
func (s *SysFile) init() {}
17+
18+
func (s *SysFile) destroy(fd int) error {
19+
// We don't use ignoringEINTR here because POSIX does not define
20+
// whether the descriptor is closed if close returns EINTR.
21+
// If the descriptor is indeed closed, using a loop would race
22+
// with some other goroutine opening a new descriptor.
23+
// (The Linux kernel guarantees that it is closed on an EINTR error.)
24+
return CloseFunc(fd)
25+
}
26+
1627
// dupCloseOnExecOld is the traditional way to dup an fd and
1728
// set its O_CLOEXEC bit, using two system calls.
1829
func dupCloseOnExecOld(fd int) (int, string, error) {

src/internal/poll/fd_wasip1.go

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,18 @@ import (
1111
)
1212

1313
type SysFile struct {
14+
// RefCountPtr is a pointer to the reference count of Sysfd.
15+
//
16+
// WASI preview 1 lacks a dup(2) system call. When the os and net packages
17+
// need to share a file/socket, instead of duplicating the underlying file
18+
// descriptor, we instead provide a way to copy FD instances and manage the
19+
// underlying file descriptor with reference counting.
20+
RefCountPtr *int32
21+
22+
// RefCount is the reference count of Sysfd. When a copy of an FD is made,
23+
// it points to the reference count of the original FD instance.
24+
RefCount int32
25+
1426
// Cache for the file type, lazily initialized when Seek is called.
1527
Filetype uint32
1628

@@ -29,6 +41,47 @@ type SysFile struct {
2941
// always set instead of being lazily initialized.
3042
}
3143

44+
func (s *SysFile) init() {
45+
if s.RefCountPtr == nil {
46+
s.RefCount = 1
47+
s.RefCountPtr = &s.RefCount
48+
}
49+
}
50+
51+
func (s *SysFile) ref() SysFile {
52+
atomic.AddInt32(s.RefCountPtr, +1)
53+
return SysFile{RefCountPtr: s.RefCountPtr}
54+
}
55+
56+
func (s *SysFile) destroy(fd int) error {
57+
if s.RefCountPtr != nil && atomic.AddInt32(s.RefCountPtr, -1) > 0 {
58+
return nil
59+
}
60+
61+
// We don't use ignoringEINTR here because POSIX does not define
62+
// whether the descriptor is closed if close returns EINTR.
63+
// If the descriptor is indeed closed, using a loop would race
64+
// with some other goroutine opening a new descriptor.
65+
// (The Linux kernel guarantees that it is closed on an EINTR error.)
66+
return CloseFunc(fd)
67+
}
68+
69+
// Copy creates a copy of the FD.
70+
//
71+
// The FD instance points to the same underlying file descriptor. The file
72+
// descriptor isn't closed until all FD instances that refer to it have been
73+
// closed/destroyed.
74+
func (fd *FD) Copy() FD {
75+
return FD{
76+
Sysfd: fd.Sysfd,
77+
SysFile: fd.SysFile.ref(),
78+
IsStream: fd.IsStream,
79+
ZeroReadIsEOF: fd.ZeroReadIsEOF,
80+
isBlocking: fd.isBlocking,
81+
isFile: fd.isFile,
82+
}
83+
}
84+
3285
// dupCloseOnExecOld always errors on wasip1 because there is no mechanism to
3386
// duplicate file descriptors.
3487
func dupCloseOnExecOld(fd int) (int, string, error) {

src/net/fd_wasip1.go

Lines changed: 168 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,168 @@
1+
// Copyright 2023 The Go Authors. All rights reserved.
2+
// Use of this source code is governed by a BSD-style
3+
// license that can be found in the LICENSE file.
4+
5+
//go:build wasip1
6+
7+
package net
8+
9+
import (
10+
"internal/poll"
11+
"runtime"
12+
"syscall"
13+
"time"
14+
)
15+
16+
const (
17+
readSyscallName = "fd_read"
18+
writeSyscallName = "fd_write"
19+
)
20+
21+
// Network file descriptor.
22+
type netFD struct {
23+
pfd poll.FD
24+
25+
// immutable until Close
26+
family int
27+
sotype int
28+
isConnected bool // handshake completed or use of association with peer
29+
net string
30+
laddr Addr
31+
raddr Addr
32+
33+
// The only networking available in WASI preview 1 is the ability to
34+
// sock_accept on an pre-opened socket, and then fd_read, fd_write,
35+
// fd_close, and sock_shutdown on the resulting connection. We
36+
// intercept applicable netFD calls on this instance, and then pass
37+
// the remainder of the netFD calls to fakeNetFD.
38+
*fakeNetFD
39+
}
40+
41+
func newFD(sysfd int) (*netFD, error) {
42+
return newPollFD(poll.FD{
43+
Sysfd: sysfd,
44+
IsStream: true,
45+
ZeroReadIsEOF: true,
46+
})
47+
}
48+
49+
func newPollFD(pfd poll.FD) (*netFD, error) {
50+
ret := &netFD{
51+
pfd: pfd,
52+
net: "tcp",
53+
laddr: unknownAddr{},
54+
raddr: unknownAddr{},
55+
}
56+
return ret, nil
57+
}
58+
59+
func (fd *netFD) init() error {
60+
return fd.pfd.Init(fd.net, true)
61+
}
62+
63+
func (fd *netFD) name() string {
64+
return "unknown"
65+
}
66+
67+
func (fd *netFD) accept() (netfd *netFD, err error) {
68+
if fd.fakeNetFD != nil {
69+
return fd.fakeNetFD.accept()
70+
}
71+
d, _, errcall, err := fd.pfd.Accept()
72+
if err != nil {
73+
if errcall != "" {
74+
err = wrapSyscallError(errcall, err)
75+
}
76+
return nil, err
77+
}
78+
if netfd, err = newFD(d); err != nil {
79+
poll.CloseFunc(d)
80+
return nil, err
81+
}
82+
if err = netfd.init(); err != nil {
83+
netfd.Close()
84+
return nil, err
85+
}
86+
return netfd, nil
87+
}
88+
89+
func (fd *netFD) setAddr(laddr, raddr Addr) {
90+
fd.laddr = laddr
91+
fd.raddr = raddr
92+
runtime.SetFinalizer(fd, (*netFD).Close)
93+
}
94+
95+
func (fd *netFD) Close() error {
96+
if fd.fakeNetFD != nil {
97+
return fd.fakeNetFD.Close()
98+
}
99+
runtime.SetFinalizer(fd, nil)
100+
return fd.pfd.Close()
101+
}
102+
103+
func (fd *netFD) shutdown(how int) error {
104+
if fd.fakeNetFD != nil {
105+
return nil
106+
}
107+
err := fd.pfd.Shutdown(how)
108+
runtime.KeepAlive(fd)
109+
return wrapSyscallError("shutdown", err)
110+
}
111+
112+
func (fd *netFD) closeRead() error {
113+
if fd.fakeNetFD != nil {
114+
return fd.fakeNetFD.closeRead()
115+
}
116+
return fd.shutdown(syscall.SHUT_RD)
117+
}
118+
119+
func (fd *netFD) closeWrite() error {
120+
if fd.fakeNetFD != nil {
121+
return fd.fakeNetFD.closeWrite()
122+
}
123+
return fd.shutdown(syscall.SHUT_WR)
124+
}
125+
126+
func (fd *netFD) Read(p []byte) (n int, err error) {
127+
if fd.fakeNetFD != nil {
128+
return fd.fakeNetFD.Read(p)
129+
}
130+
n, err = fd.pfd.Read(p)
131+
runtime.KeepAlive(fd)
132+
return n, wrapSyscallError(readSyscallName, err)
133+
}
134+
135+
func (fd *netFD) Write(p []byte) (nn int, err error) {
136+
if fd.fakeNetFD != nil {
137+
return fd.fakeNetFD.Write(p)
138+
}
139+
nn, err = fd.pfd.Write(p)
140+
runtime.KeepAlive(fd)
141+
return nn, wrapSyscallError(writeSyscallName, err)
142+
}
143+
144+
func (fd *netFD) SetDeadline(t time.Time) error {
145+
if fd.fakeNetFD != nil {
146+
return fd.fakeNetFD.SetDeadline(t)
147+
}
148+
return fd.pfd.SetDeadline(t)
149+
}
150+
151+
func (fd *netFD) SetReadDeadline(t time.Time) error {
152+
if fd.fakeNetFD != nil {
153+
return fd.fakeNetFD.SetReadDeadline(t)
154+
}
155+
return fd.pfd.SetReadDeadline(t)
156+
}
157+
158+
func (fd *netFD) SetWriteDeadline(t time.Time) error {
159+
if fd.fakeNetFD != nil {
160+
return fd.fakeNetFD.SetWriteDeadline(t)
161+
}
162+
return fd.pfd.SetWriteDeadline(t)
163+
}
164+
165+
type unknownAddr struct{}
166+
167+
func (unknownAddr) Network() string { return "unknown" }
168+
func (unknownAddr) String() string { return "unknown" }

src/net/file_stub.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
// Use of this source code is governed by a BSD-style
33
// license that can be found in the LICENSE file.
44

5-
//go:build (js && wasm) || wasip1
5+
//go:build js && wasm
66

77
package net
88

src/net/file_wasip1.go

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
// Copyright 2023 The Go Authors. All rights reserved.
2+
// Use of this source code is governed by a BSD-style
3+
// license that can be found in the LICENSE file.
4+
5+
//go:build wasip1
6+
7+
package net
8+
9+
import (
10+
"os"
11+
"syscall"
12+
_ "unsafe" // for go:linkname
13+
)
14+
15+
func fileListener(f *os.File) (Listener, error) {
16+
fd, err := newFileFD(f)
17+
if err != nil {
18+
return nil, err
19+
}
20+
return &TCPListener{fd: fd}, nil
21+
}
22+
23+
func fileConn(f *os.File) (Conn, error) {
24+
fd, err := newFileFD(f)
25+
if err != nil {
26+
return nil, err
27+
}
28+
return &TCPConn{conn{fd: fd}}, nil
29+
}
30+
31+
func filePacketConn(f *os.File) (PacketConn, error) { return nil, syscall.ENOPROTOOPT }
32+
33+
func newFileFD(f *os.File) (fd *netFD, err error) {
34+
pfd := f.PollFD().Copy()
35+
defer func() {
36+
if err != nil {
37+
pfd.Close()
38+
}
39+
}()
40+
filetype, err := fd_fdstat_get_type(pfd.Sysfd)
41+
if err != nil {
42+
return nil, err
43+
}
44+
if filetype != syscall.FILETYPE_SOCKET_STREAM {
45+
return nil, syscall.ENOTSOCK
46+
}
47+
fd, err = newPollFD(pfd)
48+
if err != nil {
49+
return nil, err
50+
}
51+
if err := fd.init(); err != nil {
52+
return nil, err
53+
}
54+
return fd, nil
55+
}
56+
57+
// This helper is implemented in the syscall package. It means we don't have
58+
// to redefine the fd_fdstat_get host import or the fdstat struct it
59+
// populates.
60+
//
61+
//go:linkname fd_fdstat_get_type syscall.fd_fdstat_get_type
62+
func fd_fdstat_get_type(fd int) (uint8, error)

0 commit comments

Comments
 (0)