author
int64
658
755k
date
stringlengths
19
19
timezone
int64
-46,800
43.2k
hash
stringlengths
40
40
message
stringlengths
5
490
mods
list
language
stringclasses
20 values
license
stringclasses
3 values
repo
stringlengths
5
68
original_message
stringlengths
12
491
259,939
14.09.2022 10:44:37
-28,800
18657459acbf0645d879eb49f061c071bdef8388
benchmarks: fix wrong file size for fio read According to MakeCmd function of fio, the unit of --size option is MB.
[ { "change_type": "MODIFY", "old_path": "test/benchmarks/fs/fio_test.go", "new_path": "test/benchmarks/fs/fio_test.go", "diff": "@@ -126,7 +126,7 @@ func BenchmarkFio(b *testing.B) {\n// For reads, we need a file to read so make one inside the container.\nif strings.Contains(tc.Test, \"read\") {\n- fallocateCmd := fmt.Sprintf(\"fallocate -l %dK %s\", tc.Size, outfile)\n+ fallocateCmd := fmt.Sprintf(\"fallocate -l %dM %s\", tc.Size, outfile)\nif out, err := container.Exec(ctx, dockerutil.ExecOpts{},\nstrings.Split(fallocateCmd, \" \")...); err != nil {\nb.Fatalf(\"failed to create readable file on mount: %v, %s\", err, out)\n" } ]
Go
Apache License 2.0
google/gvisor
benchmarks: fix wrong file size for fio read According to MakeCmd function of fio, the unit of --size option is MB. Signed-off-by: Chen Hui <cedriccchen@tencent.com>
259,939
14.09.2022 11:16:53
-28,800
5faa4646d99211c5dc783a7273dfae5f0e85a27b
benchmarks: add more blocksize arguments for fio benchmark
[ { "change_type": "MODIFY", "old_path": "test/benchmarks/fs/fio_test.go", "new_path": "test/benchmarks/fs/fio_test.go", "diff": "@@ -37,6 +37,11 @@ func BenchmarkFio(b *testing.B) {\nBlockSize: 4,\nIODepth: 4,\n},\n+ {\n+ Test: \"write\",\n+ BlockSize: 64,\n+ IODepth: 4,\n+ },\n{\nTest: \"write\",\nBlockSize: 1024,\n@@ -47,6 +52,11 @@ func BenchmarkFio(b *testing.B) {\nBlockSize: 4,\nIODepth: 4,\n},\n+ {\n+ Test: \"read\",\n+ BlockSize: 64,\n+ IODepth: 4,\n+ },\n{\nTest: \"read\",\nBlockSize: 1024,\n" } ]
Go
Apache License 2.0
google/gvisor
benchmarks: add more blocksize arguments for fio benchmark Signed-off-by: Chen Hui <cedriccchen@tencent.com>
259,939
19.09.2022 16:09:25
-28,800
bef569af0d9605d9e11c1aaf5cc622811b43a6b6
benchmarks: add BenchmarkIperfParameterized testcase for iperf benchmark
[ { "change_type": "MODIFY", "old_path": "test/benchmarks/network/iperf_test.go", "new_path": "test/benchmarks/network/iperf_test.go", "diff": "@@ -106,6 +106,170 @@ func BenchmarkIperf(b *testing.B) {\n}\n}\n+func BenchmarkIperfParameterized(b *testing.B) {\n+ clientMachine, err := harness.GetMachine()\n+ if err != nil {\n+ b.Fatalf(\"failed to get machine: %v\", err)\n+ }\n+ defer clientMachine.CleanUp()\n+\n+ serverMachine, err := harness.GetMachine()\n+ if err != nil {\n+ b.Fatalf(\"failed to get machine: %v\", err)\n+ }\n+ defer serverMachine.CleanUp()\n+ ctx := context.Background()\n+ for _, bm := range []struct {\n+ name string\n+ length int\n+ parallel int\n+ clientFunc func(context.Context, testutil.Logger) *dockerutil.Container\n+ serverFunc func(context.Context, testutil.Logger) *dockerutil.Container\n+ }{\n+ // We are either measuring the server or the client. The other should be\n+ // runc. e.g. Upload sees how fast the runtime under test uploads to a native\n+ // server.\n+ {\n+ name: \"Upload\",\n+ length: 4,\n+ parallel: 1,\n+ clientFunc: clientMachine.GetContainer,\n+ serverFunc: serverMachine.GetNativeContainer,\n+ },\n+ {\n+ name: \"Upload\",\n+ length: 64,\n+ parallel: 1,\n+ clientFunc: clientMachine.GetContainer,\n+ serverFunc: serverMachine.GetNativeContainer,\n+ },\n+ {\n+ name: \"Upload\",\n+ length: 1024,\n+ parallel: 1,\n+ clientFunc: clientMachine.GetContainer,\n+ serverFunc: serverMachine.GetNativeContainer,\n+ },\n+ {\n+ name: \"Upload\",\n+ length: 4,\n+ parallel: 16,\n+ clientFunc: clientMachine.GetContainer,\n+ serverFunc: serverMachine.GetNativeContainer,\n+ },\n+ {\n+ name: \"Upload\",\n+ length: 64,\n+ parallel: 16,\n+ clientFunc: clientMachine.GetContainer,\n+ serverFunc: serverMachine.GetNativeContainer,\n+ },\n+ {\n+ name: \"Upload\",\n+ length: 1024,\n+ parallel: 16,\n+ clientFunc: clientMachine.GetContainer,\n+ serverFunc: serverMachine.GetNativeContainer,\n+ },\n+ {\n+ name: \"Download\",\n+ length: 4,\n+ parallel: 1,\n+ clientFunc: clientMachine.GetNativeContainer,\n+ serverFunc: serverMachine.GetContainer,\n+ },\n+ {\n+ name: \"Download\",\n+ length: 64,\n+ parallel: 1,\n+ clientFunc: clientMachine.GetNativeContainer,\n+ serverFunc: serverMachine.GetContainer,\n+ },\n+ {\n+ name: \"Download\",\n+ length: 1024,\n+ parallel: 1,\n+ clientFunc: clientMachine.GetNativeContainer,\n+ serverFunc: serverMachine.GetContainer,\n+ },\n+ {\n+ name: \"Download\",\n+ length: 4,\n+ parallel: 16,\n+ clientFunc: clientMachine.GetNativeContainer,\n+ serverFunc: serverMachine.GetContainer,\n+ },\n+ {\n+ name: \"Download\",\n+ length: 64,\n+ parallel: 16,\n+ clientFunc: clientMachine.GetNativeContainer,\n+ serverFunc: serverMachine.GetContainer,\n+ },\n+ {\n+ name: \"Download\",\n+ length: 1024,\n+ parallel: 16,\n+ clientFunc: clientMachine.GetNativeContainer,\n+ serverFunc: serverMachine.GetContainer,\n+ },\n+ } {\n+ name, err := tools.ParametersToName(tools.Parameter{\n+ Name: \"operation\",\n+ Value: bm.name,\n+ }, tools.Parameter{\n+ Name: \"length\",\n+ Value: fmt.Sprintf(\"%dK\", bm.length),\n+ }, tools.Parameter{\n+ Name: \"parallel\",\n+ Value: fmt.Sprintf(\"%d\", bm.parallel),\n+ })\n+ if err != nil {\n+ b.Fatalf(\"Failed to parse parameters: %v\", err)\n+ }\n+ b.Run(name, func(b *testing.B) {\n+ // Set up the containers.\n+ server := bm.serverFunc(ctx, b)\n+ defer server.CleanUp(ctx)\n+ client := bm.clientFunc(ctx, b)\n+ defer client.CleanUp(ctx)\n+\n+ // iperf serves on port 5001 by default.\n+ port := 5001\n+\n+ // Start the server.\n+ if err := server.Spawn(ctx, dockerutil.RunOpts{\n+ Image: \"benchmarks/iperf\",\n+ Ports: []int{port},\n+ }, \"iperf\", \"-s\"); err != nil {\n+ b.Fatalf(\"failed to start server with: %v\", err)\n+ }\n+ if out, err := server.WaitForOutput(ctx, fmt.Sprintf(\"Server listening on TCP port %d\", port), 10*time.Second); err != nil {\n+ b.Fatalf(\"failed to wait for iperf server: %v %s\", err, out)\n+ }\n+\n+ iperf := tools.Iperf{\n+ Num: b.N, // KB for the client to send.\n+ Length: bm.length, // KB for length.\n+ Parallel: bm.parallel,\n+ }\n+\n+ // Run the client.\n+ b.ResetTimer()\n+ out, err := client.Run(ctx, dockerutil.RunOpts{\n+ Image: \"benchmarks/iperf\",\n+ Links: []string{server.MakeLink(\"iperfsrv\")},\n+ }, iperf.MakeCmd(\"iperfsrv\", port)...)\n+ if err != nil {\n+ b.Fatalf(\"failed to run client: %v\", err)\n+ }\n+ b.StopTimer()\n+ iperf.Report(b, out)\n+ b.StartTimer()\n+ })\n+ }\n+}\n+\nfunc TestMain(m *testing.M) {\nharness.Init()\nos.Exit(m.Run())\n" }, { "change_type": "MODIFY", "old_path": "test/benchmarks/tools/iperf.go", "new_path": "test/benchmarks/tools/iperf.go", "diff": "@@ -21,24 +21,30 @@ import (\n\"testing\"\n)\n-const length = 128 * 1024\n-\n// Iperf is for the client side of `iperf`.\ntype Iperf struct {\nNum int // Number of bytes to send in KB.\n+ Length int // Length in KB.\n+ Parallel int // Number of parallel threads.\n}\n// MakeCmd returns a iperf client command.\nfunc (i *Iperf) MakeCmd(host string, port int) []string {\n- return []string{\n- \"iperf\",\n- \"--format\", \"K\", // Output in KBytes.\n- \"--realtime\", // Measured in realtime.\n- \"--num\", fmt.Sprintf(\"%dK\", i.Num), // Number of bytes to send in KB.\n- \"--len\", fmt.Sprintf(\"%d\", length),\n- \"--client\", host,\n- \"--port\", fmt.Sprintf(\"%d\", port),\n+ cmd := []string{\"iperf\"}\n+ cmd = append(cmd, \"--format\", \"K\") // Output in KBytes.\n+ cmd = append(cmd, \"--realtime\") // Measured in realtime.\n+ cmd = append(cmd, \"--num\", fmt.Sprintf(\"%dK\", i.Num)) // Number of bytes to send in KB.\n+ len := 128\n+ if i.Length > 0 {\n+ len = i.Length\n+ }\n+ cmd = append(cmd, \"--len\", fmt.Sprintf(\"%dK\", len)) // Length in KB.\n+ cmd = append(cmd, \"--client\", host)\n+ cmd = append(cmd, \"--port\", fmt.Sprintf(\"%d\", port))\n+ if i.Parallel > 0 {\n+ cmd = append(cmd, \"--parallel\", fmt.Sprintf(\"%d\", i.Parallel))\n}\n+ return cmd\n}\n// Report parses output from iperf client and reports metrics.\n@@ -49,7 +55,7 @@ func (i *Iperf) Report(b *testing.B, output string) {\nif err != nil {\nb.Fatalf(\"failed to parse bandwitdth from %s: %v\", output, err)\n}\n- b.SetBytes(length) // Measure Bytes/sec for b.N, although below is iperf output.\n+ b.SetBytes(int64(i.Length) * 1024) // Measure Bytes/sec for b.N, although below is iperf output.\nReportCustomMetric(b, bW*1024, \"bandwidth\" /*metric name*/, \"bytes_per_second\" /*unit*/)\n}\n" } ]
Go
Apache License 2.0
google/gvisor
benchmarks: add BenchmarkIperfParameterized testcase for iperf benchmark Signed-off-by: Chen Hui <cedriccchen@tencent.com>
259,907
23.09.2022 10:43:46
25,200
de7c2164d7907aff59aa0b40b309ed30057d632f
Allow O_DIRECT with gofer.specialFileFD that represent regular files. gofer.specialFileFD can sometimes represent regular files. O_DIRECT is expected to be supported there.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/gofer/filesystem.go", "new_path": "pkg/sentry/fsimpl/gofer/filesystem.go", "diff": "@@ -1255,7 +1255,7 @@ func (d *dentry) openSocketByConnecting(ctx context.Context, opts *vfs.OpenOptio\nfunc (d *dentry) openSpecialFile(ctx context.Context, mnt *vfs.Mount, opts *vfs.OpenOptions) (*vfs.FileDescription, error) {\nats := vfs.AccessTypesForOpenFlags(opts)\n- if opts.Flags&linux.O_DIRECT != 0 {\n+ if opts.Flags&linux.O_DIRECT != 0 && !d.isRegularFile() {\nreturn nil, linuxerr.EINVAL\n}\n// We assume that the server silently inserts O_NONBLOCK in the open flags\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/gofer/special_file.go", "new_path": "pkg/sentry/fsimpl/gofer/special_file.go", "diff": "@@ -108,6 +108,7 @@ func newSpecialFileFD(h handle, mnt *vfs.Mount, d *dentry, flags uint32) (*speci\n}\n}\nif err := fd.vfsfd.Init(fd, flags, mnt, &d.vfsd, &vfs.FileDescriptionOptions{\n+ AllowDirectIO: true,\nDenyPRead: !seekable,\nDenyPWrite: !seekable,\n}); err != nil {\n" } ]
Go
Apache License 2.0
google/gvisor
Allow O_DIRECT with gofer.specialFileFD that represent regular files. gofer.specialFileFD can sometimes represent regular files. O_DIRECT is expected to be supported there. PiperOrigin-RevId: 476408649
259,907
23.09.2022 23:52:37
25,200
0ec88b757254fd383b66247cad32730fa7adb52e
Add SOCK_DGRAM socket type support in lisafs BindAt.
[ { "change_type": "MODIFY", "old_path": "runsc/fsgofer/fsgofer.go", "new_path": "runsc/fsgofer/fsgofer.go", "diff": "@@ -1130,9 +1130,7 @@ func (l *localFile) Bind(sockType uint32, sockName string, uid p9.UID, gid p9.GI\n}\n// Create socket only for supported types.\n- switch sockType {\n- case unix.SOCK_STREAM, unix.SOCK_DGRAM, unix.SOCK_SEQPACKET:\n- default:\n+ if !isSockTypeSupported(sockType) {\nreturn nil, p9.QID{}, p9.AttrMask{}, p9.Attr{}, unix.ENXIO\n}\nsock, err := unix.Socket(unix.AF_UNIX, int(sockType), 0)\n" }, { "change_type": "MODIFY", "old_path": "runsc/fsgofer/lisafs.go", "new_path": "runsc/fsgofer/lisafs.go", "diff": "@@ -622,6 +622,16 @@ func (fd *controlFDLisa) Readlink(getLinkBuf func(uint32) []byte) (uint16, error\nreturn 0, unix.ENOMEM\n}\n+func isSockTypeSupported(sockType uint32) bool {\n+ switch sockType {\n+ case unix.SOCK_STREAM, unix.SOCK_DGRAM, unix.SOCK_SEQPACKET:\n+ return true\n+ default:\n+ log.Debugf(\"socket type %d is not supported\", sockType)\n+ return false\n+ }\n+}\n+\n// Connect implements lisafs.ControlFDImpl.Connect.\nfunc (fd *controlFDLisa) Connect(sockType uint32) (int, error) {\nif !fd.Conn().ServerImpl().(*LisafsServer).config.HostUDS {\n@@ -637,10 +647,7 @@ func (fd *controlFDLisa) Connect(sockType uint32) (int, error) {\nreturn -1, unix.EINVAL\n}\n- // Only the following types are supported.\n- switch sockType {\n- case unix.SOCK_STREAM, unix.SOCK_DGRAM, unix.SOCK_SEQPACKET:\n- default:\n+ if !isSockTypeSupported(sockType) {\nreturn -1, unix.ENXIO\n}\n@@ -677,9 +684,7 @@ func (fd *controlFDLisa) BindAt(name string, sockType uint32) (*lisafs.ControlFD\n}\n// Only the following types are supported.\n- switch sockType {\n- case unix.SOCK_STREAM, unix.SOCK_SEQPACKET:\n- default:\n+ if !isSockTypeSupported(sockType) {\nreturn nil, linux.Statx{}, nil, -1, unix.ENXIO\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Add SOCK_DGRAM socket type support in lisafs BindAt. PiperOrigin-RevId: 476542032
259,907
24.09.2022 17:25:32
25,200
f841b2511ecf947be341979a8b9165c3277258a0
Use fchmodat(2) to change mode for bound sockets in lisafs gofer.
[ { "change_type": "MODIFY", "old_path": "runsc/fsgofer/filter/config.go", "new_path": "runsc/fsgofer/filter/config.go", "diff": "@@ -53,6 +53,7 @@ var allowedSyscalls = seccomp.SyscallRules{\n},\n},\nunix.SYS_FCHMOD: {},\n+ unix.SYS_FCHMODAT: {},\nunix.SYS_FCHOWNAT: {},\nunix.SYS_FCNTL: []seccomp.Rule{\n{\n" }, { "change_type": "MODIFY", "old_path": "runsc/fsgofer/lisafs.go", "new_path": "runsc/fsgofer/lisafs.go", "diff": "@@ -208,12 +208,29 @@ func (fd *controlFDLisa) Stat() (linux.Statx, error) {\n// SetStat implements lisafs.ControlFDImpl.SetStat.\nfunc (fd *controlFDLisa) SetStat(stat lisafs.SetStatReq) (failureMask uint32, failureErr error) {\nif stat.Mask&unix.STATX_MODE != 0 {\n+ if fd.IsSocket() {\n+ // fchmod(2) on socket files created via bind(2) fails. We need to\n+ // fchmodat(2) it from its parent.\n+ sockPath := fd.Node().FilePath()\n+ parent, err := unix.Open(path.Dir(sockPath), openFlags|unix.O_PATH, 0)\n+ if err == nil {\n+ // Note that AT_SYMLINK_NOFOLLOW flag is not currently supported.\n+ err = unix.Fchmodat(parent, path.Base(sockPath), stat.Mode&^unix.S_IFMT, 0 /* flags */)\n+ unix.Close(parent)\n+ }\n+ if err != nil {\n+ log.Warningf(\"SetStat fchmod failed on socket %q, err: %v\", sockPath, err)\n+ failureMask |= unix.STATX_MODE\n+ failureErr = err\n+ }\n+ } else {\nif err := unix.Fchmod(fd.hostFD, stat.Mode&^unix.S_IFMT); err != nil {\nlog.Warningf(\"SetStat fchmod failed %q, err: %v\", fd.Node().FilePath(), err)\nfailureMask |= unix.STATX_MODE\nfailureErr = err\n}\n}\n+ }\nif stat.Mask&unix.STATX_SIZE != 0 {\n// ftruncate(2) requires the FD to be open for writing.\n" } ]
Go
Apache License 2.0
google/gvisor
Use fchmodat(2) to change mode for bound sockets in lisafs gofer. PiperOrigin-RevId: 476642321
259,907
26.09.2022 16:46:43
25,200
68fd6aba43eeb776b45d74c52525d2e7da5532d8
Update BindAt RPC to include other creation options. BindAt should also be setting the socket file mode and owners. All file creation RPCs do this. This is required for correct behavior.
[ { "change_type": "MODIFY", "old_path": "pkg/lisafs/client_file.go", "new_path": "pkg/lisafs/client_file.go", "diff": "@@ -421,16 +421,18 @@ func (f *ClientFD) Flush(ctx context.Context) error {\n}\n// BindAt makes the BindAt RPC.\n-func (f *ClientFD) BindAt(ctx context.Context, sockType linux.SockType, name string) (Inode, *ClientBoundSocketFD, error) {\n- req := BindAtReq{\n- DirFD: f.fd,\n- SockType: primitive.Uint32(sockType),\n- Name: SizedString(name),\n- }\n+func (f *ClientFD) BindAt(ctx context.Context, sockType linux.SockType, name string, mode linux.FileMode, uid UID, gid GID) (Inode, *ClientBoundSocketFD, error) {\nvar (\n+ req BindAtReq\nresp BindAtResp\nhostSocketFD [1]int\n)\n+ req.DirFD = f.fd\n+ req.SockType = primitive.Uint32(sockType)\n+ req.Name = SizedString(name)\n+ req.Mode = mode\n+ req.UID = uid\n+ req.GID = gid\nctx.UninterruptibleSleepStart(false)\nerr := f.client.SndRcvMessage(BindAt, uint32(req.SizeBytes()), req.MarshalBytes, resp.CheckedUnmarshal, hostSocketFD[:], req.String, resp.String)\nctx.UninterruptibleSleepFinish(false)\n" }, { "change_type": "MODIFY", "old_path": "pkg/lisafs/fd.go", "new_path": "pkg/lisafs/fd.go", "diff": "@@ -492,7 +492,7 @@ type ControlFDImpl interface {\n// connections).\n//\n// On the server, BindAt has a write concurrency guarantee.\n- BindAt(name string, sockType uint32) (*ControlFD, linux.Statx, *BoundSocketFD, int, error)\n+ BindAt(name string, sockType uint32, mode linux.FileMode, uid UID, gid GID) (*ControlFD, linux.Statx, *BoundSocketFD, int, error)\n// UnlinkAt the file identified by name in this directory.\n//\n" }, { "change_type": "MODIFY", "old_path": "pkg/lisafs/handlers.go", "new_path": "pkg/lisafs/handlers.go", "diff": "@@ -1103,7 +1103,7 @@ func BindAtHandler(c *Connection, comm Communicator, payloadLen uint32) (uint32,\nif dir.node.isDeleted() {\nreturn unix.EINVAL\n}\n- childFD, childStat, boundSocketFD, hostSocketFD, err = dir.impl.BindAt(name, uint32(req.SockType))\n+ childFD, childStat, boundSocketFD, hostSocketFD, err = dir.impl.BindAt(name, uint32(req.SockType), req.Mode, req.UID, req.GID)\nreturn err\n}); err != nil {\nreturn 0, err\n" }, { "change_type": "MODIFY", "old_path": "pkg/lisafs/message.go", "new_path": "pkg/lisafs/message.go", "diff": "@@ -1290,19 +1290,19 @@ func (*ConnectResp) String() string {\n// BindAtReq is used to make BindAt requests.\ntype BindAtReq struct {\n- DirFD FDID\n+ createCommon\nSockType primitive.Uint32\nName SizedString\n}\n// SizeBytes implements marshal.Marshallable.SizeBytes.\nfunc (b *BindAtReq) SizeBytes() int {\n- return b.DirFD.SizeBytes() + b.SockType.SizeBytes() + b.Name.SizeBytes()\n+ return b.createCommon.SizeBytes() + b.SockType.SizeBytes() + b.Name.SizeBytes()\n}\n// MarshalBytes implements marshal.Marshallable.MarshalBytes.\nfunc (b *BindAtReq) MarshalBytes(dst []byte) []byte {\n- dst = b.DirFD.MarshalUnsafe(dst)\n+ dst = b.createCommon.MarshalUnsafe(dst)\ndst = b.SockType.MarshalUnsafe(dst)\nreturn b.Name.MarshalBytes(dst)\n}\n@@ -1313,7 +1313,7 @@ func (b *BindAtReq) CheckedUnmarshal(src []byte) ([]byte, bool) {\nif b.SizeBytes() > len(src) {\nreturn src, false\n}\n- srcRemain := b.DirFD.UnmarshalUnsafe(src)\n+ srcRemain := b.createCommon.UnmarshalUnsafe(src)\nsrcRemain = b.SockType.UnmarshalUnsafe(srcRemain)\nif srcRemain, ok := b.Name.CheckedUnmarshal(srcRemain); ok {\nreturn srcRemain, ok\n@@ -1323,7 +1323,7 @@ func (b *BindAtReq) CheckedUnmarshal(src []byte) ([]byte, bool) {\n// String implements fmt.Stringer.String.\nfunc (b *BindAtReq) String() string {\n- return fmt.Sprintf(\"BindAtReq{DirFD: %d, SockType: %d, Name: %q}\", b.DirFD, b.SockType, b.Name)\n+ return fmt.Sprintf(\"BindAtReq{DirFD: %d, Mode: %s, UID: %d, GID: %d, SockType: %d, Name: %q}\", b.DirFD, b.Mode, b.UID, b.GID, b.SockType, b.Name)\n}\n// BindAtResp is used to communicate BindAt response.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/gofer/gofer.go", "new_path": "pkg/sentry/fsimpl/gofer/gofer.go", "diff": "@@ -1638,7 +1638,7 @@ func (d *dentry) mknodLisaLocked(ctx context.Context, name string, creds *auth.C\n// This mknod(2) is coming from unix bind(2), as opts.Endpoint is set.\nsockType := opts.Endpoint.(transport.Endpoint).Type()\n- childInode, boundSocketFD, err := d.controlFDLisa.BindAt(ctx, sockType, name)\n+ childInode, boundSocketFD, err := d.controlFDLisa.BindAt(ctx, sockType, name, opts.Mode, lisafs.UID(creds.EffectiveKUID), lisafs.GID(creds.EffectiveKGID))\nif err != nil {\nreturn err\n}\n" }, { "change_type": "MODIFY", "old_path": "runsc/fsgofer/lisafs.go", "new_path": "runsc/fsgofer/lisafs.go", "diff": "@@ -682,7 +682,7 @@ func (fd *controlFDLisa) Connect(sockType uint32) (int, error) {\n}\n// BindAt implements lisafs.ControlFDImpl.BindAt.\n-func (fd *controlFDLisa) BindAt(name string, sockType uint32) (*lisafs.ControlFD, linux.Statx, *lisafs.BoundSocketFD, int, error) {\n+func (fd *controlFDLisa) BindAt(name string, sockType uint32, mode linux.FileMode, uid lisafs.UID, gid lisafs.GID) (*lisafs.ControlFD, linux.Statx, *lisafs.BoundSocketFD, int, error) {\nif !fd.Conn().ServerImpl().(*LisafsServer).config.HostUDS {\nreturn nil, linux.Statx{}, nil, -1, unix.EPERM\n}\n@@ -716,6 +716,12 @@ func (fd *controlFDLisa) BindAt(name string, sockType uint32) (*lisafs.ControlFD\n})\ndefer cu.Clean()\n+ // fchmod(2) has to happen *before* the bind(2). sockFD's file mode will\n+ // be used in creating the filesystem-object in bind(2).\n+ if err := unix.Fchmod(sockFD, uint32(mode&^linux.FileTypeMask)); err != nil {\n+ return nil, linux.Statx{}, nil, -1, err\n+ }\n+\nif err := unix.Bind(sockFD, &unix.SockaddrUnix{Name: socketPath}); err != nil {\nreturn nil, linux.Statx{}, nil, -1, err\n}\n@@ -733,6 +739,10 @@ func (fd *controlFDLisa) BindAt(name string, sockType uint32) (*lisafs.ControlFD\n_ = unix.Close(sockFileFD)\n})\n+ if err := unix.Fchownat(sockFileFD, \"\", int(uid), int(gid), unix.AT_EMPTY_PATH|unix.AT_SYMLINK_NOFOLLOW); err != nil {\n+ return nil, linux.Statx{}, nil, -1, err\n+ }\n+\n// Stat the socket.\nsockStat, err := fstatTo(sockFileFD)\nif err != nil {\n" } ]
Go
Apache License 2.0
google/gvisor
Update BindAt RPC to include other creation options. BindAt should also be setting the socket file mode and owners. All file creation RPCs do this. This is required for correct behavior. PiperOrigin-RevId: 477023055
259,868
26.09.2022 20:02:45
25,200
77d8b6cd77d876ef2e8fce492d9207693021fe3e
Add custom error type for `ResolveExecutablePath`.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/user/path.go", "new_path": "pkg/sentry/fs/user/path.go", "diff": "@@ -30,8 +30,13 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/vfs\"\n)\n+// ExecutableResolveError represents a failure to resolve the executable\n+// in ResolveExecutablePath.\n+type ExecutableResolveError error\n+\n// ResolveExecutablePath resolves the given executable name given the working\n// dir and environment.\n+// Returns ExecutableResolveError when the executable cannot be resolved.\nfunc ResolveExecutablePath(ctx context.Context, args *kernel.CreateProcessArgs) (string, error) {\nname := args.Filename\nif len(name) == 0 {\n@@ -64,14 +69,14 @@ func ResolveExecutablePath(ctx context.Context, args *kernel.CreateProcessArgs)\nif kernel.VFS2Enabled {\nf, err := resolveVFS2(ctx, args.Credentials, args.MountNamespaceVFS2, paths, name)\nif err != nil {\n- return \"\", fmt.Errorf(\"error finding executable %q in PATH %v: %v\", name, paths, err)\n+ return \"\", ExecutableResolveError(fmt.Errorf(\"error finding executable %q in PATH %v: %v\", name, paths, err))\n}\nreturn f, nil\n}\nf, err := resolve(ctx, args.MountNamespace, paths, name)\nif err != nil {\n- return \"\", fmt.Errorf(\"error finding executable %q in PATH %v: %v\", name, paths, err)\n+ return \"\", ExecutableResolveError(fmt.Errorf(\"error finding executable %q in PATH %v: %v\", name, paths, err))\n}\nreturn f, nil\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Add custom error type for `ResolveExecutablePath`. PiperOrigin-RevId: 477058661
259,868
29.09.2022 17:04:07
25,200
3e2e74279a92b372d6f271272c4a3d421a6b42f7
User pointer error type for `path.ExecutableResolveError`.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/user/path.go", "new_path": "pkg/sentry/fs/user/path.go", "diff": "@@ -32,11 +32,11 @@ import (\n// ExecutableResolveError represents a failure to resolve the executable\n// in ResolveExecutablePath.\n-type ExecutableResolveError error\n+type ExecutableResolveError struct{ error }\n// ResolveExecutablePath resolves the given executable name given the working\n// dir and environment.\n-// Returns ExecutableResolveError when the executable cannot be resolved.\n+// Returns *ExecutableResolveError when the executable cannot be resolved.\nfunc ResolveExecutablePath(ctx context.Context, args *kernel.CreateProcessArgs) (string, error) {\nname := args.Filename\nif len(name) == 0 {\n@@ -69,14 +69,14 @@ func ResolveExecutablePath(ctx context.Context, args *kernel.CreateProcessArgs)\nif kernel.VFS2Enabled {\nf, err := resolveVFS2(ctx, args.Credentials, args.MountNamespaceVFS2, paths, name)\nif err != nil {\n- return \"\", ExecutableResolveError(fmt.Errorf(\"error finding executable %q in PATH %v: %v\", name, paths, err))\n+ return \"\", &ExecutableResolveError{fmt.Errorf(\"error finding executable %q in PATH %v: %v\", name, paths, err)}\n}\nreturn f, nil\n}\nf, err := resolve(ctx, args.MountNamespace, paths, name)\nif err != nil {\n- return \"\", ExecutableResolveError(fmt.Errorf(\"error finding executable %q in PATH %v: %v\", name, paths, err))\n+ return \"\", &ExecutableResolveError{fmt.Errorf(\"error finding executable %q in PATH %v: %v\", name, paths, err)}\n}\nreturn f, nil\n}\n" } ]
Go
Apache License 2.0
google/gvisor
User pointer error type for `path.ExecutableResolveError`. PiperOrigin-RevId: 477857846
259,977
30.09.2022 08:12:51
25,200
61e742b38912c1a54f3d1d3b46c7d837db1ea9de
Align stack variables in RebindProtocol test Previously, this test read packets directly into the stack memory of a packed struct. Since the ethernet header is not 8-byte aligned, this can cause UB on CPUs requiring 8-byte alignment. Resolve this issue by copying each segment of the packet into separate stack variables.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/packet_socket.cc", "new_path": "test/syscalls/linux/packet_socket.cc", "diff": "@@ -200,23 +200,31 @@ TEST_P(PacketSocketTest, RebindProtocol) {\n};\nauto test_recv = [&, this](const uint64_t v) {\n- struct {\n+ // Declare each section of the packet as a separate stack variable in order\n+ // to ensure all sections are 8-byte aligned.\nethhdr eth;\niphdr ip;\nudphdr udp;\nuint64_t payload;\nchar unused;\n- } ABSL_ATTRIBUTE_PACKED read_pkt;\n+\n+ constexpr size_t kStorageLen = sizeof(eth) + sizeof(ip) + sizeof(udp) +\n+ sizeof(payload) + sizeof(unused);\n+ char storage[kStorageLen];\n+\nsockaddr_ll src;\nsocklen_t src_len = sizeof(src);\n- char* buf = reinterpret_cast<char*>(&read_pkt);\n- size_t buflen = sizeof(read_pkt);\n- size_t expected_read_len = sizeof(read_pkt) - sizeof(read_pkt.unused);\n+ char* buf = storage;\n+ size_t buflen = kStorageLen;\n+ auto advance_buf = [&buf, &buflen](size_t amount) {\n+ buf += amount;\n+ buflen -= amount;\n+ };\n+ size_t expected_read_len = buflen - sizeof(unused);\nif (!kEthHdrIncluded) {\n- buf += sizeof(read_pkt.eth);\n- buflen -= sizeof(read_pkt.eth);\n- expected_read_len -= sizeof(read_pkt.eth);\n+ advance_buf(sizeof(eth));\n+ expected_read_len -= sizeof(eth);\n}\niovec received_iov = {\n@@ -247,26 +255,34 @@ TEST_P(PacketSocketTest, RebindProtocol) {\n// This came from the loopback device, so the address is all 0s.\nconstexpr uint8_t allZeroesMAC[ETH_ALEN] = {};\nEXPECT_EQ(memcmp(src.sll_addr, allZeroesMAC, sizeof(allZeroesMAC)), 0);\n+\nif (kEthHdrIncluded) {\n- EXPECT_EQ(memcmp(read_pkt.eth.h_dest, allZeroesMAC, sizeof(allZeroesMAC)),\n- 0);\n- EXPECT_EQ(\n- memcmp(read_pkt.eth.h_source, allZeroesMAC, sizeof(allZeroesMAC)), 0);\n- EXPECT_EQ(ntohs(read_pkt.eth.h_proto), ETH_P_IP);\n+ memcpy(&eth, buf, sizeof(eth));\n+ EXPECT_EQ(memcmp(eth.h_dest, allZeroesMAC, sizeof(allZeroesMAC)), 0);\n+ EXPECT_EQ(memcmp(eth.h_source, allZeroesMAC, sizeof(allZeroesMAC)), 0);\n+ EXPECT_EQ(ntohs(eth.h_proto), ETH_P_IP);\n+ advance_buf(sizeof(eth));\n}\n+\n// IHL hold the size of the header in 4 byte units.\n- EXPECT_EQ(read_pkt.ip.ihl, sizeof(iphdr) / 4);\n- EXPECT_EQ(read_pkt.ip.version, IPVERSION);\n- const uint16_t ip_pkt_size =\n- sizeof(read_pkt) - sizeof(read_pkt.eth) - sizeof(read_pkt.unused);\n- EXPECT_EQ(ntohs(read_pkt.ip.tot_len), ip_pkt_size);\n- EXPECT_EQ(read_pkt.ip.protocol, IPPROTO_UDP);\n- EXPECT_EQ(ntohl(read_pkt.ip.daddr), INADDR_LOOPBACK);\n- EXPECT_EQ(ntohl(read_pkt.ip.saddr), INADDR_LOOPBACK);\n- EXPECT_EQ(read_pkt.udp.source, udp_bind_addr.sin_port);\n- EXPECT_EQ(read_pkt.udp.dest, udp_bind_addr.sin_port);\n- EXPECT_EQ(ntohs(read_pkt.udp.len), ip_pkt_size - sizeof(read_pkt.ip));\n- EXPECT_EQ(read_pkt.payload, v);\n+ memcpy(&ip, buf, sizeof(ip));\n+ EXPECT_EQ(ip.ihl, sizeof(iphdr) / 4);\n+ EXPECT_EQ(ip.version, IPVERSION);\n+ const uint16_t ip_pkt_size = sizeof(ip) + sizeof(udp) + sizeof(payload);\n+ EXPECT_EQ(ntohs(ip.tot_len), ip_pkt_size);\n+ EXPECT_EQ(ip.protocol, IPPROTO_UDP);\n+ EXPECT_EQ(ntohl(ip.daddr), INADDR_LOOPBACK);\n+ EXPECT_EQ(ntohl(ip.saddr), INADDR_LOOPBACK);\n+ advance_buf(sizeof(ip));\n+\n+ memcpy(&udp, buf, sizeof(udp));\n+ EXPECT_EQ(udp.source, udp_bind_addr.sin_port);\n+ EXPECT_EQ(udp.dest, udp_bind_addr.sin_port);\n+ EXPECT_EQ(ntohs(udp.len), ip_pkt_size - sizeof(ip));\n+ advance_buf(sizeof(udp));\n+\n+ memcpy(&payload, buf, sizeof(payload));\n+ EXPECT_EQ(payload, v);\n};\n// The packet socket is not bound to IPv4 so we should not receive the sent\n" } ]
Go
Apache License 2.0
google/gvisor
Align stack variables in RebindProtocol test Previously, this test read packets directly into the stack memory of a packed struct. Since the ethernet header is not 8-byte aligned, this can cause UB on CPUs requiring 8-byte alignment. Resolve this issue by copying each segment of the packet into separate stack variables. PiperOrigin-RevId: 477996715
259,909
30.09.2022 10:48:46
25,200
f53c349d519a01cf603bf845a4b2a382e30b1715
Add support for bind mounting. This change adds limited support for the MS_BIND flag. MS_REC is not yet implemented.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/vfs2/mount.go", "new_path": "pkg/sentry/syscalls/linux/vfs2/mount.go", "diff": "@@ -17,6 +17,7 @@ package vfs2\nimport (\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/errors/linuxerr\"\n+ \"gvisor.dev/gvisor/pkg/fspath\"\n\"gvisor.dev/gvisor/pkg/hostarch\"\n\"gvisor.dev/gvisor/pkg/sentry/arch\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n@@ -71,9 +72,8 @@ func Mount(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Syscall\nreturn 0, nil, linuxerr.EPERM\n}\n- const unsupportedOps = linux.MS_REMOUNT | linux.MS_BIND |\n- linux.MS_SHARED | linux.MS_PRIVATE | linux.MS_SLAVE |\n- linux.MS_UNBINDABLE | linux.MS_MOVE\n+ const unsupportedOps = linux.MS_REMOUNT | linux.MS_SHARED | linux.MS_PRIVATE |\n+ linux.MS_SLAVE | linux.MS_UNBINDABLE | linux.MS_MOVE\n// Silently allow MS_NOSUID, since we don't implement set-id bits\n// anyway.\n@@ -109,7 +109,23 @@ func Mount(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Syscall\nreturn 0, nil, err\n}\ndefer target.Release(t)\n+\n+ if flags&linux.MS_BIND == linux.MS_BIND {\n+ var sourcePath fspath.Path\n+ sourcePath, err = copyInPath(t, sourceAddr)\n+ if err != nil {\n+ return 0, nil, err\n+ }\n+ var sourceTpop taskPathOperation\n+ sourceTpop, err = getTaskPathOperation(t, linux.AT_FDCWD, sourcePath, disallowEmptyPath, nofollowFinalSymlink)\n+ if err != nil {\n+ return 0, nil, err\n+ }\n+ defer sourceTpop.Release(t)\n+ _, err = t.Kernel().VFS().BindAt(t, creds, &sourceTpop.pop, &target.pop)\n+ } else {\n_, err = t.Kernel().VFS().MountAt(t, creds, source, &target.pop, fsType, &opts)\n+ }\nreturn 0, nil, err\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/mount.go", "new_path": "pkg/sentry/vfs/mount.go", "diff": "@@ -271,6 +271,26 @@ func (vfs *VirtualFilesystem) ConnectMountAt(ctx context.Context, creds *auth.Cr\nreturn nil\n}\n+// BindAt creates a clone of the source path's parent mount and mounts it at\n+// the target path. The new mount's root dentry is one pointed to by the source\n+// path.\n+//\n+// TODO(b/249121230): Support recursive bind mounting.\n+func (vfs *VirtualFilesystem) BindAt(ctx context.Context, creds *auth.Credentials, source, target *PathOperation) (*Mount, error) {\n+ vd, err := vfs.GetDentryAt(ctx, creds, source, &GetDentryOptions{})\n+ if err != nil {\n+ return nil, err\n+ }\n+ defer vd.DecRef(ctx)\n+ opts := vd.mount.Options()\n+ mnt := vfs.NewDisconnectedMount(vd.mount.fs, vd.dentry, &opts)\n+ defer mnt.DecRef(ctx)\n+ if err := vfs.ConnectMountAt(ctx, creds, mnt, target); err != nil {\n+ return nil, err\n+ }\n+ return mnt, nil\n+}\n+\n// MountAt creates and mounts a Filesystem configured by the given arguments.\n// The VirtualFilesystem will hold a reference to the Mount until it is\n// unmounted.\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/mount.cc", "new_path": "test/syscalls/linux/mount.cc", "diff": "@@ -759,6 +759,68 @@ TEST(MountTest, TmpfsSizeMmap) {\n::testing::KilledBySignal(SIGBUS), \"\");\nEXPECT_THAT(munmap(addr, 2 * kPageSize), SyscallSucceeds());\n}\n+\n+TEST(MountTest, SimpleBind) {\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_SYS_ADMIN)));\n+\n+ auto const dir1 = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n+ auto const dir2 = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n+ auto const mount = ASSERT_NO_ERRNO_AND_VALUE(\n+ Mount(\"\", dir1.path(), \"tmpfs\", 0, \"mode=0123\", 0));\n+ auto const child1 =\n+ ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDirIn(dir1.path()));\n+ auto const child2 =\n+ ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDirIn(dir1.path()));\n+ auto const bind_mount = Mount(dir1.path(), dir2.path(), \"\", MS_BIND, \"\", 0);\n+\n+ // Write to child1 in dir1.\n+ const std::string filename = \"foo.txt\";\n+ const std::string contents = \"barbaz\";\n+ ASSERT_NO_ERRNO(CreateWithContents(JoinPath(child1.path(), filename),\n+ contents, O_WRONLY));\n+ // Verify both directories have the same nodes.\n+ std::vector<std::string> child_names = {std::string(Basename(child1.path())),\n+ std::string(Basename(child2.path()))};\n+ ASSERT_NO_ERRNO(DirContains(dir1.path(), child_names, {}));\n+ ASSERT_NO_ERRNO(DirContains(dir2.path(), child_names, {}));\n+\n+ const std::string dir1_filepath =\n+ JoinPath(dir1.path(), Basename(child1.path()), filename);\n+ const std::string dir2_filepath =\n+ JoinPath(dir2.path(), Basename(child1.path()), filename);\n+\n+ std::string output;\n+ ASSERT_NO_ERRNO(GetContents(dir1_filepath, &output));\n+ ASSERT_TRUE(output == contents);\n+ ASSERT_NO_ERRNO(GetContents(dir2_filepath, &output));\n+ ASSERT_TRUE(output == contents);\n+}\n+\n+TEST(MountTest, BindToSelf) {\n+ // Test that we can turn a normal directory into a mount with MS_BIND.\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_SYS_ADMIN)));\n+ auto const dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n+\n+ const std::vector<ProcMountsEntry> mounts_before =\n+ ASSERT_NO_ERRNO_AND_VALUE(ProcSelfMountsEntries());\n+ for (const auto& e : mounts_before) {\n+ ASSERT_TRUE(e.mount_point != dir.path());\n+ }\n+\n+ auto const mount = ASSERT_NO_ERRNO_AND_VALUE(\n+ Mount(dir.path(), dir.path(), \"\", MS_BIND, \"\", 0));\n+\n+ const std::vector<ProcMountsEntry> mounts_after =\n+ ASSERT_NO_ERRNO_AND_VALUE(ProcSelfMountsEntries());\n+ bool found = false;\n+ for (const auto& e : mounts_after) {\n+ if (e.mount_point == dir.path()) {\n+ found = true;\n+ }\n+ }\n+ ASSERT_TRUE(found);\n+}\n+\n} // namespace\n} // namespace testing\n" } ]
Go
Apache License 2.0
google/gvisor
Add support for bind mounting. This change adds limited support for the MS_BIND flag. MS_REC is not yet implemented. PiperOrigin-RevId: 478030021
259,909
03.10.2022 11:04:25
25,200
4cff09161e8707607f1a4cc6e86f9e043d987a7e
Cache neighbor entries in route struct. This will avoid allocating closures and having to retrieve the entry from the table every time.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/neighbor_cache.go", "new_path": "pkg/tcpip/stack/neighbor_cache.go", "diff": "@@ -122,9 +122,7 @@ func (n *neighborCache) getOrCreateEntry(remoteAddr tcpip.Address) *neighborEntr\n// If specified, the local address must be an address local to the interface the\n// neighbor cache belongs to. The local address is the source address of a\n// packet prompting NUD/link address resolution.\n-//\n-// TODO(gvisor.dev/issue/5151): Don't return the neighbor entry.\n-func (n *neighborCache) entry(remoteAddr, localAddr tcpip.Address, onResolve func(LinkResolutionResult)) (NeighborEntry, <-chan struct{}, tcpip.Error) {\n+func (n *neighborCache) entry(remoteAddr, localAddr tcpip.Address, onResolve func(LinkResolutionResult)) (*neighborEntry, <-chan struct{}, tcpip.Error) {\nentry := n.getOrCreateEntry(remoteAddr)\nentry.mu.Lock()\ndefer entry.mu.Unlock()\n@@ -142,7 +140,7 @@ func (n *neighborCache) entry(remoteAddr, localAddr tcpip.Address, onResolve fun\nif onResolve != nil {\nonResolve(LinkResolutionResult{LinkAddress: entry.mu.neigh.LinkAddr, Err: nil})\n}\n- return entry.mu.neigh, nil, nil\n+ return entry, nil, nil\ncase Unknown, Incomplete, Unreachable:\nif onResolve != nil {\nentry.mu.onResolve = append(entry.mu.onResolve, onResolve)\n@@ -152,7 +150,7 @@ func (n *neighborCache) entry(remoteAddr, localAddr tcpip.Address, onResolve fun\nentry.mu.done = make(chan struct{})\n}\nentry.handlePacketQueuedLocked(localAddr)\n- return entry.mu.neigh, entry.mu.done, &tcpip.ErrWouldBlock{}\n+ return entry, entry.mu.done, &tcpip.ErrWouldBlock{}\ndefault:\npanic(fmt.Sprintf(\"Invalid cache entry state: %s\", s))\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/neighbor_cache_test.go", "new_path": "pkg/tcpip/stack/neighbor_cache_test.go", "diff": "@@ -874,7 +874,7 @@ func TestNeighborCacheAddStaticEntryThenOverflow(t *testing.T) {\nState: Static,\nUpdatedAt: c.clock.NowMonotonic(),\n}\n- if diff := cmp.Diff(want, e, cmp.AllowUnexported(tcpip.MonotonicTime{})); diff != \"\" {\n+ if diff := cmp.Diff(want, e.mu.neigh, cmp.AllowUnexported(tcpip.MonotonicTime{})); diff != \"\" {\nt.Errorf(\"c.linkRes.neigh.entry(%s, \\\"\\\", nil) mismatch (-want, +got):\\n%s\", entry.Addr, diff)\n}\n@@ -1243,7 +1243,7 @@ func TestNeighborCacheReplace(t *testing.T) {\nState: Delay,\nUpdatedAt: clock.NowMonotonic(),\n}\n- if diff := cmp.Diff(want, e, cmp.AllowUnexported(tcpip.MonotonicTime{})); diff != \"\" {\n+ if diff := cmp.Diff(want, e.mu.neigh, cmp.AllowUnexported(tcpip.MonotonicTime{})); diff != \"\" {\nt.Errorf(\"linkRes.neigh.entry(%s, '', nil) mismatch (-want, +got):\\n%s\", entry.Addr, diff)\n}\n}\n@@ -1262,7 +1262,7 @@ func TestNeighborCacheReplace(t *testing.T) {\nState: Reachable,\nUpdatedAt: clock.NowMonotonic(),\n}\n- if diff := cmp.Diff(want, e, cmp.AllowUnexported(tcpip.MonotonicTime{})); diff != \"\" {\n+ if diff := cmp.Diff(want, e.mu.neigh, cmp.AllowUnexported(tcpip.MonotonicTime{})); diff != \"\" {\nt.Errorf(\"linkRes.neigh.entry(%s, '', nil) mismatch (-want, +got):\\n%s\", entry.Addr, diff)\n}\n}\n@@ -1300,7 +1300,7 @@ func TestNeighborCacheResolutionFailed(t *testing.T) {\nState: Reachable,\nUpdatedAt: clock.NowMonotonic(),\n}\n- if diff := cmp.Diff(want, got, cmp.AllowUnexported(tcpip.MonotonicTime{})); diff != \"\" {\n+ if diff := cmp.Diff(want, got.mu.neigh, cmp.AllowUnexported(tcpip.MonotonicTime{})); diff != \"\" {\nt.Errorf(\"linkRes.neigh.entry(%s, '', nil) mismatch (-want, +got):\\n%s\", entry.Addr, diff)\n}\n@@ -1472,8 +1472,8 @@ func TestNeighborCacheRetryResolution(t *testing.T) {\nif _, ok := err.(*tcpip.ErrWouldBlock); !ok {\nt.Fatalf(\"got linkRes.neigh.entry(%s, '', _) = %v, want = %s\", entry.Addr, err, &tcpip.ErrWouldBlock{})\n}\n- if incompleteEntry.State != Incomplete {\n- t.Fatalf(\"got entry.State = %s, want = %s\", incompleteEntry.State, Incomplete)\n+ if incompleteEntry.mu.neigh.State != Incomplete {\n+ t.Fatalf(\"got entry.State = %s, want = %s\", incompleteEntry.mu.neigh.State, Incomplete)\n}\n{\n@@ -1540,7 +1540,7 @@ func TestNeighborCacheRetryResolution(t *testing.T) {\nState: Reachable,\nUpdatedAt: clock.NowMonotonic(),\n}\n- if diff := cmp.Diff(gotEntry, wantEntry, cmp.AllowUnexported(tcpip.MonotonicTime{})); diff != \"\" {\n+ if diff := cmp.Diff(gotEntry.mu.neigh, wantEntry, cmp.AllowUnexported(tcpip.MonotonicTime{})); diff != \"\" {\nt.Fatalf(\"neighbor entry mismatch (-got, +want):\\n%s\", diff)\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/neighbor_entry.go", "new_path": "pkg/tcpip/stack/neighbor_entry.go", "diff": "@@ -232,6 +232,8 @@ func (e *neighborEntry) cancelTimerLocked() {\nfunc (e *neighborEntry) removeLocked() {\ne.mu.neigh.UpdatedAt = e.cache.nic.stack.clock.NowMonotonic()\ne.dispatchRemoveEventLocked()\n+ // Set state to unknown to invalidate this entry if it's cached in a Route.\n+ e.setStateLocked(Unknown)\ne.cancelTimerLocked()\n// TODO(https://gvisor.dev/issues/5583): test the case where this function is\n// called during resolution; that can happen in at least these scenarios:\n@@ -607,3 +609,18 @@ func (e *neighborEntry) handleUpperLevelConfirmationLocked() {\npanic(fmt.Sprintf(\"Invalid cache entry state: %s\", e.mu.neigh.State))\n}\n}\n+\n+// getRemoteLinkAddress returns the entry's link address and whether that link\n+// address is valid.\n+func (e *neighborEntry) getRemoteLinkAddress() (tcpip.LinkAddress, bool) {\n+ e.mu.RLock()\n+ defer e.mu.RUnlock()\n+ switch e.mu.neigh.State {\n+ case Reachable, Static, Delay, Probe:\n+ return e.mu.neigh.LinkAddr, true\n+ case Unknown, Incomplete, Unreachable, Stale:\n+ return \"\", false\n+ default:\n+ panic(fmt.Sprintf(\"invalid state for neighbor entry %v: %v\", e.mu.neigh, e.mu.neigh.State))\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/neighbor_entry_test.go", "new_path": "pkg/tcpip/stack/neighbor_entry_test.go", "diff": "@@ -1957,6 +1957,47 @@ func TestEntryProbeToReachableWhenSolicitedOverrideConfirmation(t *testing.T) {\n}\n}\n+func TestGetRemoteLinkAddressFailsWhenResolutionRequired(t *testing.T) {\n+ c := DefaultNUDConfigurations()\n+ c.MinRandomFactor = 1\n+ c.MaxRandomFactor = 1\n+ e, nudDisp, linkRes, clock := entryTestSetup(c)\n+\n+ if _, ok := e.getRemoteLinkAddress(); ok {\n+ t.Errorf(\"getRemoteLinkAddress() = _, true, want false\")\n+ }\n+ if err := unknownToStale(e, nudDisp, linkRes, clock); err != nil {\n+ t.Fatalf(\"unknownToStale(...) = %s\", err)\n+ }\n+ if _, ok := e.getRemoteLinkAddress(); ok {\n+ t.Errorf(\"getRemoteLinkAddress() = _, true, want false\")\n+ }\n+ if err := staleToDelay(e, nudDisp, linkRes, clock); err != nil {\n+ t.Fatalf(\"staleToDelay(...) = %s\", err)\n+ }\n+ if _, ok := e.getRemoteLinkAddress(); !ok {\n+ t.Errorf(\"getRemoteLinkAddress() = _, false, want true\")\n+ }\n+ if err := delayToProbe(c, e, nudDisp, linkRes, clock); err != nil {\n+ t.Fatalf(\"delayToProbe(...) = %s\", err)\n+ }\n+ if _, ok := e.getRemoteLinkAddress(); !ok {\n+ t.Errorf(\"getRemoteLinkAddress() = _, false, want true\")\n+ }\n+ if err := probeToReachable(e, nudDisp, linkRes, clock); err != nil {\n+ t.Fatalf(\"probeToReachable(...) = %s\", err)\n+ }\n+ if _, ok := e.getRemoteLinkAddress(); !ok {\n+ t.Errorf(\"getRemoteLinkAddress() = _, false, want true\")\n+ }\n+ if err := reachableToStale(c, e, nudDisp, linkRes, clock); err != nil {\n+ t.Fatalf(\"reachableToStale(...) = %s\", err)\n+ }\n+ if _, ok := e.getRemoteLinkAddress(); ok {\n+ t.Errorf(\"getRemoteLinkAddress() = _, true, want false\")\n+ }\n+}\n+\nfunc probeToReachableWithFlags(e *neighborEntry, nudDisp *testNUDDispatcher, linkRes *entryTestLinkResolver, clock *faketime.ManualClock, linkAddr tcpip.LinkAddress, flags ReachabilityConfirmationFlags) error {\nif err := func() error {\ne.mu.Lock()\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/nic.go", "new_path": "pkg/tcpip/stack/nic.go", "diff": "@@ -30,11 +30,6 @@ type linkResolver struct {\nneigh neighborCache\n}\n-func (l *linkResolver) getNeighborLinkAddress(addr, localAddr tcpip.Address, onResolve func(LinkResolutionResult)) (tcpip.LinkAddress, <-chan struct{}, tcpip.Error) {\n- entry, ch, err := l.neigh.entry(addr, localAddr, onResolve)\n- return entry.LinkAddr, ch, err\n-}\n-\nfunc (l *linkResolver) confirmReachable(addr tcpip.Address) {\nl.neigh.handleUpperLevelConfirmation(addr)\n}\n@@ -625,7 +620,7 @@ func (n *nic) getLinkAddress(addr, localAddr tcpip.Address, protocol tcpip.Netwo\nreturn nil\n}\n- _, _, err := linkRes.getNeighborLinkAddress(addr, localAddr, onResolve)\n+ _, _, err := linkRes.neigh.entry(addr, localAddr, onResolve)\nreturn err\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/route.go", "new_path": "pkg/tcpip/stack/route.go", "diff": "@@ -50,6 +50,10 @@ type Route struct {\n// linkRes is set if link address resolution is enabled for this protocol on\n// the route's NIC.\nlinkRes *linkResolver\n+\n+ // neighborEntry is the cached result of fetching a neighbor entry from the\n+ // neighbor cache.\n+ neighborEntry *neighborEntry\n}\n// +stateify savable\n@@ -390,22 +394,48 @@ func (r *Route) resolvedFields(afterResolve func(ResolvedFieldsResult)) (RouteIn\nlinkAddressResolutionRequestLocalAddr = r.LocalAddress()\n}\n+ nEntry := r.getCachedNeighborEntry()\n+ if nEntry != nil {\n+ if addr, ok := nEntry.getRemoteLinkAddress(); ok {\n+ fields.RemoteLinkAddress = addr\n+ if afterResolve != nil {\n+ afterResolve(ResolvedFieldsResult{RouteInfo: fields, Err: nil})\n+ }\n+ return fields, nil, nil\n+ }\n+ }\nafterResolveFields := fields\n- linkAddr, ch, err := r.linkRes.getNeighborLinkAddress(r.nextHop(), linkAddressResolutionRequestLocalAddr, func(r LinkResolutionResult) {\n+ entry, ch, err := r.linkRes.neigh.entry(r.nextHop(), linkAddressResolutionRequestLocalAddr, func(lrr LinkResolutionResult) {\n+ if lrr.Err != nil {\n+ r.setCachedNeighborEntry(nil)\n+ }\nif afterResolve != nil {\n- if r.Err == nil {\n- afterResolveFields.RemoteLinkAddress = r.LinkAddress\n+ if lrr.Err == nil {\n+ afterResolveFields.RemoteLinkAddress = lrr.LinkAddress\n}\n- afterResolve(ResolvedFieldsResult{RouteInfo: afterResolveFields, Err: r.Err})\n+ afterResolve(ResolvedFieldsResult{RouteInfo: afterResolveFields, Err: lrr.Err})\n}\n})\nif err == nil {\n- fields.RemoteLinkAddress = linkAddr\n+ fields.RemoteLinkAddress, _ = entry.getRemoteLinkAddress()\n}\n+ r.setCachedNeighborEntry(entry)\nreturn fields, ch, err\n}\n+func (r *Route) getCachedNeighborEntry() *neighborEntry {\n+ r.mu.RLock()\n+ defer r.mu.RUnlock()\n+ return r.neighborEntry\n+}\n+\n+func (r *Route) setCachedNeighborEntry(entry *neighborEntry) {\n+ r.mu.Lock()\n+ defer r.mu.Unlock()\n+ r.neighborEntry = entry\n+}\n+\nfunc (r *Route) nextHop() tcpip.Address {\nif len(r.NextHop()) == 0 {\nreturn r.RemoteAddress()\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/tests/integration/BUILD", "new_path": "pkg/tcpip/tests/integration/BUILD", "diff": "@@ -58,12 +58,14 @@ go_test(\nsrcs = [\"link_resolution_test.go\"],\ndeps = [\n\"//pkg/bufferv2\",\n+ \"//pkg/sync\",\n\"//pkg/tcpip\",\n\"//pkg/tcpip/checker\",\n\"//pkg/tcpip/checksum\",\n\"//pkg/tcpip/faketime\",\n\"//pkg/tcpip/header\",\n\"//pkg/tcpip/link/channel\",\n+ \"//pkg/tcpip/link/ethernet\",\n\"//pkg/tcpip/link/pipe\",\n\"//pkg/tcpip/network/arp\",\n\"//pkg/tcpip/network/ipv4\",\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/tests/integration/link_resolution_test.go", "new_path": "pkg/tcpip/tests/integration/link_resolution_test.go", "diff": "@@ -25,12 +25,14 @@ import (\n\"github.com/google/go-cmp/cmp\"\n\"github.com/google/go-cmp/cmp/cmpopts\"\n\"gvisor.dev/gvisor/pkg/bufferv2\"\n+ \"gvisor.dev/gvisor/pkg/sync\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/checker\"\n\"gvisor.dev/gvisor/pkg/tcpip/checksum\"\n\"gvisor.dev/gvisor/pkg/tcpip/faketime\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n\"gvisor.dev/gvisor/pkg/tcpip/link/channel\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/link/ethernet\"\n\"gvisor.dev/gvisor/pkg/tcpip/link/pipe\"\n\"gvisor.dev/gvisor/pkg/tcpip/network/arp\"\n\"gvisor.dev/gvisor/pkg/tcpip/network/ipv4\"\n@@ -45,10 +47,14 @@ import (\n)\nfunc setupStack(t *testing.T, stackOpts stack.Options, host1NICID, host2NICID tcpip.NICID) (*stack.Stack, *stack.Stack) {\n+ return setupStackWithSeparateOpts(t, stackOpts, stackOpts, host1NICID, host2NICID)\n+}\n+\n+func setupStackWithSeparateOpts(t *testing.T, stack1Opts stack.Options, stack2Opts stack.Options, host1NICID, host2NICID tcpip.NICID) (*stack.Stack, *stack.Stack) {\nconst maxFrameSize = header.IPv6MinimumMTU + header.EthernetMinimumSize\n- host1Stack := stack.New(stackOpts)\n- host2Stack := stack.New(stackOpts)\n+ host1Stack := stack.New(stack1Opts)\n+ host2Stack := stack.New(stack2Opts)\nhost1NIC, host2NIC := pipe.New(utils.LinkAddr1, utils.LinkAddr2, maxFrameSize)\n@@ -1644,3 +1650,165 @@ func TestDAD(t *testing.T) {\n})\n}\n}\n+\n+type settableLinkEndpoint struct {\n+ stack.LinkEndpoint\n+ mu sync.Mutex\n+ addr tcpip.LinkAddress\n+}\n+\n+func newSettableLinkEndpoint(e stack.LinkEndpoint) *settableLinkEndpoint {\n+ return &settableLinkEndpoint{\n+ LinkEndpoint: e,\n+ addr: e.LinkAddress(),\n+ }\n+}\n+\n+func (e *settableLinkEndpoint) setLinkAddress(addr tcpip.LinkAddress) {\n+ e.mu.Lock()\n+ defer e.mu.Unlock()\n+ e.addr = addr\n+}\n+\n+func (e *settableLinkEndpoint) LinkAddress() tcpip.LinkAddress {\n+ e.mu.Lock()\n+ defer e.mu.Unlock()\n+ return e.addr\n+}\n+\n+type monitorableLinkEndpoint struct {\n+ stack.LinkEndpoint\n+ ch chan tcpip.LinkAddress\n+}\n+\n+func newMonitorableLinkEndpoint(e stack.LinkEndpoint) *monitorableLinkEndpoint {\n+ return &monitorableLinkEndpoint{e, make(chan tcpip.LinkAddress, 1)}\n+}\n+\n+func (e *monitorableLinkEndpoint) WritePackets(pkts stack.PacketBufferList) (int, tcpip.Error) {\n+ for _, pkt := range pkts.AsSlice() {\n+ dstAddr := header.Ethernet(pkt.LinkHeader().Slice()).DestinationAddress()\n+ e.ch <- dstAddr\n+ }\n+ e.LinkEndpoint.WritePackets(pkts)\n+\n+ return 0, nil\n+}\n+\n+func (e *monitorableLinkEndpoint) waitForLinkAddress(addr tcpip.LinkAddress, wait time.Duration) error {\n+ c := time.After(wait)\n+ for {\n+ select {\n+ case sentAddr := <-e.ch:\n+ if addr == sentAddr {\n+ return nil\n+ }\n+ case <-c:\n+ return fmt.Errorf(\"timed out waiting for endpoint to send packet with destination address: %v\", addr)\n+ }\n+ }\n+}\n+\n+func TestUpdateCachedNeighborEntry(t *testing.T) {\n+ d := []byte{1, 2}\n+ params := stack.NetworkHeaderParams{\n+ Protocol: udp.ProtocolNumber,\n+ TTL: 64,\n+ TOS: stack.DefaultTOS,\n+ }\n+\n+ writePacket := func(t *testing.T, r *stack.Route) {\n+ pkt := stack.NewPacketBuffer(stack.PacketBufferOptions{\n+ ReserveHeaderBytes: header.UDPMinimumSize + int(r.MaxHeaderLength()),\n+ Payload: bufferv2.MakeWithData(d),\n+ })\n+ if err := r.WritePacket(params, pkt); err != nil {\n+ t.Fatalf(\"WritePacket(...): %s\", err)\n+ }\n+ pkt.DecRef()\n+ }\n+\n+ const (\n+ host1NICID = 1\n+ host2NICID = 4\n+ )\n+ stackOpts := stack.Options{\n+ NetworkProtocols: []stack.NetworkProtocolFactory{arp.NewProtocol, ipv4.NewProtocol, ipv6.NewProtocol},\n+ TransportProtocols: []stack.TransportProtocolFactory{udp.NewProtocol},\n+ }\n+\n+ const maxFrameSize = header.IPv6MinimumMTU + header.EthernetMinimumSize\n+\n+ host1Stack := stack.New(stackOpts)\n+ host2Stack := stack.New(stackOpts)\n+\n+ host1Pipe, host2Pipe := pipe.New(utils.LinkAddr1, utils.LinkAddr2, maxFrameSize)\n+\n+ host1NICMonitorable := newMonitorableLinkEndpoint(ethernet.New(host1Pipe))\n+ host2NICSettable := newSettableLinkEndpoint(host2Pipe)\n+\n+ if err := host1Stack.CreateNIC(host1NICID, host1NICMonitorable); err != nil {\n+ t.Fatalf(\"host1Stack.CreateNIC(%d, _): %s\", host1NICID, err)\n+ }\n+ if err := host2Stack.CreateNIC(host2NICID, ethernet.New(host2NICSettable)); err != nil {\n+ t.Fatalf(\"host2Stack.CreateNIC(%d, _): %s\", host2NICID, err)\n+ }\n+\n+ if err := host1Stack.AddProtocolAddress(host1NICID, utils.Ipv4Addr1, stack.AddressProperties{}); err != nil {\n+ t.Fatalf(\"host1Stack.AddProtocolAddress(%d, %+v, {}): %s\", host1NICID, utils.Ipv4Addr1, err)\n+ }\n+ if err := host2Stack.AddProtocolAddress(host2NICID, utils.Ipv4Addr2, stack.AddressProperties{}); err != nil {\n+ t.Fatalf(\"host2Stack.AddProtocolAddress(%d, %+v, {}): %s\", host2NICID, utils.Ipv4Addr2, err)\n+ }\n+\n+ host1Stack.SetRouteTable([]tcpip.Route{\n+ {\n+ Destination: utils.Ipv4Addr1.AddressWithPrefix.Subnet(),\n+ NIC: host1NICID,\n+ },\n+ })\n+ host2Stack.SetRouteTable([]tcpip.Route{\n+ {\n+ Destination: utils.Ipv4Addr2.AddressWithPrefix.Subnet(),\n+ NIC: host2NICID,\n+ },\n+ })\n+\n+ localAddr := utils.Ipv4Addr1.AddressWithPrefix.Address\n+ neighborAddr := utils.Ipv4Addr2.AddressWithPrefix.Address\n+\n+ // Obtain a route to a neighbor.\n+ r, err := host1Stack.FindRoute(host1NICID, localAddr, neighborAddr, header.IPv4ProtocolNumber, false)\n+ if err != nil {\n+ t.Fatalf(\"host1Stack.FindRoute(...): %s\", err)\n+ }\n+\n+ // Send packet to neighbor (start link resolution & resolve, then send\n+ // packet). Send twice to use cached address the second time.\n+ for i := 0; i < 2; i++ {\n+ writePacket(t, r)\n+ if err := host1NICMonitorable.waitForLinkAddress(utils.LinkAddr2, time.Second); err != nil {\n+ t.Fatalf(\"host1NIC.waitForLinkAddress(%s): %s\", utils.LinkAddr2, err)\n+ }\n+ }\n+\n+ // Neighbor no longer reachable, deleted from the neighbor cache.\n+ host1Stack.RemoveNeighbor(host1NICID, header.IPv4ProtocolNumber, neighborAddr)\n+ host2Stack.DisableNIC(host2NICID)\n+\n+ // Send packet to neighbor that's no longer reachable (should fail).\n+ writePacket(t, r)\n+ if err := host1NICMonitorable.waitForLinkAddress(utils.LinkAddr2, time.Second); err == nil {\n+ t.Fatalf(\"got host1NIC.waitForLinkAddress(%s) = nil, want err\", utils.LinkAddr2)\n+ }\n+\n+ // Neighbor reachable again with new MAC address.\n+ host2Stack.EnableNIC(host2NICID)\n+ host2NICSettable.setLinkAddress(utils.LinkAddr3)\n+\n+ // Send packet to neighbor (start link resolution and then send packet).\n+ writePacket(t, r)\n+ if err := host1NICMonitorable.waitForLinkAddress(utils.LinkAddr3, 5*time.Second); err != nil {\n+ t.Fatalf(\"host1NIC.waitForLinkAddress(%s): %s\", utils.LinkAddr3, err)\n+ }\n+}\n" } ]
Go
Apache License 2.0
google/gvisor
Cache neighbor entries in route struct. This will avoid allocating closures and having to retrieve the entry from the table every time. PiperOrigin-RevId: 478551631
259,977
03.10.2022 18:18:05
25,200
8f110cbdaa88bdeecef9b4c09fd2a3cdcd1b13e8
Reduce poll timeouts The 10s timeout eats up significant time when tests are expected to fail.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/tcp_socket.cc", "new_path": "test/syscalls/linux/tcp_socket.cc", "diff": "@@ -40,6 +40,8 @@ namespace testing {\nnamespace {\n+constexpr int kTimeoutMillis = 10000;\n+\nPosixErrorOr<sockaddr_storage> InetLoopbackAddr(int family) {\nstruct sockaddr_storage addr;\nmemset(&addr, 0, sizeof(addr));\n@@ -827,25 +829,23 @@ TEST_P(TcpSocketTest, TcpSCMPriority) {\nTEST_P(TcpSocketTest, TimeWaitPollHUP) {\nshutdown(connected_.get(), SHUT_RDWR);\nScopedThread t([&]() {\n- constexpr int kTimeout = 10000;\nconstexpr int16_t want_events = POLLHUP;\nstruct pollfd pfd = {\n.fd = connected_.get(),\n.events = want_events,\n};\n- ASSERT_THAT(poll(&pfd, 1, kTimeout), SyscallSucceedsWithValue(1));\n+ ASSERT_THAT(poll(&pfd, 1, kTimeoutMillis), SyscallSucceedsWithValue(1));\n});\nshutdown(accepted_.get(), SHUT_RDWR);\nt.Join();\n// At this point first_fd should be in TIME-WAIT and polling for POLLHUP\n// should return with 1 FD.\n- constexpr int kTimeout = 10000;\nconstexpr int16_t want_events = POLLHUP;\nstruct pollfd pfd = {\n.fd = connected_.get(),\n.events = want_events,\n};\n- ASSERT_THAT(poll(&pfd, 1, kTimeout), SyscallSucceedsWithValue(1));\n+ ASSERT_THAT(poll(&pfd, 1, kTimeoutMillis), SyscallSucceedsWithValue(1));\n}\nINSTANTIATE_TEST_SUITE_P(AllInetTests, TcpSocketTest,\n@@ -971,13 +971,13 @@ TEST_P(TcpSocketTest, PollAfterShutdown) {\nEXPECT_THAT(shutdown(connected_.get(), SHUT_WR),\nSyscallSucceedsWithValue(0));\nstruct pollfd poll_fd = {connected_.get(), POLLIN | POLLERR | POLLHUP, 0};\n- EXPECT_THAT(RetryEINTR(poll)(&poll_fd, 1, 10000),\n+ EXPECT_THAT(RetryEINTR(poll)(&poll_fd, 1, kTimeoutMillis),\nSyscallSucceedsWithValue(1));\n});\nEXPECT_THAT(shutdown(accepted_.get(), SHUT_WR), SyscallSucceedsWithValue(0));\nstruct pollfd poll_fd = {accepted_.get(), POLLIN | POLLERR | POLLHUP, 0};\n- EXPECT_THAT(RetryEINTR(poll)(&poll_fd, 1, 10000),\n+ EXPECT_THAT(RetryEINTR(poll)(&poll_fd, 1, kTimeoutMillis),\nSyscallSucceedsWithValue(1));\n}\n@@ -1342,7 +1342,7 @@ void NonBlockingConnect(int family, int16_t pollMask) {\nSyscallSucceeds());\nstruct pollfd poll_fd = {s.get(), pollMask, 0};\n- EXPECT_THAT(RetryEINTR(poll)(&poll_fd, 1, 10000),\n+ EXPECT_THAT(RetryEINTR(poll)(&poll_fd, 1, kTimeoutMillis),\nSyscallSucceedsWithValue(1));\nint err;\n@@ -1401,7 +1401,7 @@ TEST_P(SimpleTcpSocketTest, NonBlockingConnectRemoteClose) {\n// Now polling on the FD with a timeout should return 0 corresponding to no\n// FDs ready.\nstruct pollfd poll_fd = {s.get(), POLLOUT, 0};\n- EXPECT_THAT(RetryEINTR(poll)(&poll_fd, 1, 10000),\n+ EXPECT_THAT(RetryEINTR(poll)(&poll_fd, 1, kTimeoutMillis),\nSyscallSucceedsWithValue(1));\nASSERT_THAT(RetryEINTR(connect)(s.get(), AsSockAddr(&addr), addrlen),\n" } ]
Go
Apache License 2.0
google/gvisor
Reduce poll timeouts The 10s timeout eats up significant time when tests are expected to fail. PiperOrigin-RevId: 478655369
259,977
04.10.2022 11:46:56
25,200
631477c7b87ae43ab0d55f07e131918064a33c82
Store threads with unique_ptr in ListenConnectParallel The existing implementation uses raw pointers, which means: Threads are joined at the end of each loop, and the test therefore doesn't actually exercise the syscalls in parallel. The later call to `Join` is undefined behavior.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/tcp_socket.cc", "new_path": "test/syscalls/linux/tcp_socket.cc", "diff": "@@ -1111,9 +1111,11 @@ TEST_P(SimpleTcpSocketTest, ListenConnectParallel) {\n});\n// Initiate connects in a separate thread.\n- std::vector<ScopedThread*> threads;\n+ std::vector<std::unique_ptr<ScopedThread>> threads;\n+ threads.reserve(num_threads);\nfor (int i = 0; i < num_threads; i++) {\n- ScopedThread t([&addr, &addrlen, family]() {\n+ threads.push_back(std::make_unique<ScopedThread>([&addr, &addrlen,\n+ family]() {\nconst FileDescriptor c = ASSERT_NO_ERRNO_AND_VALUE(\nSocket(family, SOCK_STREAM | SOCK_NONBLOCK, IPPROTO_TCP));\n@@ -1126,11 +1128,7 @@ TEST_P(SimpleTcpSocketTest, ListenConnectParallel) {\nstruct pollfd poll_fd = {c.get(), POLLERR | POLLOUT, 0};\nEXPECT_THAT(RetryEINTR(poll)(&poll_fd, 1, 1000),\nSyscallSucceedsWithValue(1));\n- });\n- threads.push_back(&t);\n- }\n- for (auto t : threads) {\n- t->Join();\n+ }));\n}\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Store threads with unique_ptr in ListenConnectParallel The existing implementation uses raw pointers, which means: - Threads are joined at the end of each loop, and the test therefore doesn't actually exercise the syscalls in parallel. - The later call to `Join` is undefined behavior. PiperOrigin-RevId: 478845631
259,982
04.10.2022 15:55:04
25,200
30182dc10f7b9f47698ec50441a910c90cd328dd
Add /proc/[pid]/maps to runsc trace procfs Updates
[ { "change_type": "MODIFY", "old_path": "pkg/hostarch/access_type.go", "new_path": "pkg/hostarch/access_type.go", "diff": "@@ -122,5 +122,6 @@ var (\nWrite = AccessType{Write: true}\nExecute = AccessType{Execute: true}\nReadWrite = AccessType{Read: true, Write: true}\n+ ReadExecute = AccessType{Read: true, Execute: true}\nAnyAccess = AccessType{Read: true, Write: true, Execute: true}\n)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/proc/task_files.go", "new_path": "pkg/sentry/fsimpl/proc/task_files.go", "diff": "@@ -544,7 +544,7 @@ var _ dynamicInode = (*mapsData)(nil)\n// Generate implements vfs.DynamicBytesSource.Generate.\nfunc (d *mapsData) Generate(ctx context.Context, buf *bytes.Buffer) error {\nif mm := getMM(d.task); mm != nil {\n- mm.ReadMapsDataInto(ctx, buf)\n+ mm.ReadMapsDataInto(ctx, mm.MapsCallbackFuncForBuffer(buf))\n}\nreturn nil\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/mm/mm.go", "new_path": "pkg/sentry/mm/mm.go", "diff": "@@ -50,6 +50,9 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/platform\"\n)\n+// MapsCallbackFunc has all the parameters required for populating an entry of /proc/[pid]/maps.\n+type MapsCallbackFunc func(start, end hostarch.Addr, permissions hostarch.AccessType, private string, offset uint64, devMajor, devMinor uint32, inode uint64, path string)\n+\n// MemoryManager implements a virtual address space.\n//\n// +stateify savable\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/mm/procfs.go", "new_path": "pkg/sentry/mm/procfs.go", "diff": "@@ -20,6 +20,7 @@ import (\n\"gvisor.dev/gvisor/pkg/context\"\n\"gvisor.dev/gvisor/pkg/hostarch\"\n+ \"gvisor.dev/gvisor/pkg/log\"\n\"gvisor.dev/gvisor/pkg/sentry/fs/proc/seqfile\"\n\"gvisor.dev/gvisor/pkg/sentry/memmap\"\n)\n@@ -57,9 +58,32 @@ func (mm *MemoryManager) NeedsUpdate(generation int64) bool {\nreturn true\n}\n+// MapsCallbackFuncForBuffer creates a /proc/[pid]/maps entry including the trailing newline.\n+func (mm *MemoryManager) MapsCallbackFuncForBuffer(buf *bytes.Buffer) MapsCallbackFunc {\n+ return func(start, end hostarch.Addr, permissions hostarch.AccessType, private string, offset uint64, devMajor, devMinor uint32, inode uint64, path string) {\n+ // Do not include the guard page: fs/proc/task_mmu.c:show_map_vma() =>\n+ // stack_guard_page_start().\n+ lineLen, err := fmt.Fprintf(buf, \"%08x-%08x %s%s %08x %02x:%02x %d \",\n+ start, end, permissions, private, offset, devMajor, devMinor, inode)\n+ if err != nil {\n+ log.Warningf(\"Failed to write to buffer with error: %v\", err)\n+ return\n+ }\n+\n+ if path != \"\" {\n+ // Per linux, we pad until the 74th character.\n+ for pad := 73 - lineLen; pad > 0; pad-- {\n+ buf.WriteByte(' ') // never returns a non-nil error\n+ }\n+ buf.WriteString(path) // never returns a non-nil error\n+ }\n+ buf.WriteByte('\\n') // never returns a non-nil error\n+ }\n+}\n+\n// ReadMapsDataInto is called by fsimpl/proc.mapsData.Generate to\n// implement /proc/[pid]/maps.\n-func (mm *MemoryManager) ReadMapsDataInto(ctx context.Context, buf *bytes.Buffer) {\n+func (mm *MemoryManager) ReadMapsDataInto(ctx context.Context, fn MapsCallbackFunc) {\n// FIXME(b/235153601): Need to replace RLockBypass with RLockBypass\n// after fixing b/235153601.\nmm.mappingMu.RLockBypass()\n@@ -67,7 +91,7 @@ func (mm *MemoryManager) ReadMapsDataInto(ctx context.Context, buf *bytes.Buffer\nvar start hostarch.Addr\nfor vseg := mm.vmas.LowerBoundSegment(start); vseg.Ok(); vseg = vseg.NextSegment() {\n- mm.appendVMAMapsEntryLocked(ctx, vseg, buf)\n+ mm.appendVMAMapsEntryLocked(ctx, vseg, fn)\n}\n// We always emulate vsyscall, so advertise it here. Everything about a\n@@ -80,7 +104,7 @@ func (mm *MemoryManager) ReadMapsDataInto(ctx context.Context, buf *bytes.Buffer\n//\n// Artifically adjust the seqfile handle so we only output vsyscall entry once.\nif start != vsyscallEnd {\n- buf.WriteString(vsyscallMapsEntry)\n+ fn(hostarch.Addr(0xffffffffff600000), hostarch.Addr(0xffffffffff601000), hostarch.ReadExecute, \"p\", 0, 0, 0, 0, \"[vsyscall]\")\n}\n}\n@@ -129,12 +153,12 @@ func (mm *MemoryManager) ReadMapsSeqFileData(ctx context.Context, handle seqfile\n// Preconditions: mm.mappingMu must be locked.\nfunc (mm *MemoryManager) vmaMapsEntryLocked(ctx context.Context, vseg vmaIterator) []byte {\nvar b bytes.Buffer\n- mm.appendVMAMapsEntryLocked(ctx, vseg, &b)\n+ mm.appendVMAMapsEntryLocked(ctx, vseg, mm.MapsCallbackFuncForBuffer(&b))\nreturn b.Bytes()\n}\n// Preconditions: mm.mappingMu must be locked.\n-func (mm *MemoryManager) appendVMAMapsEntryLocked(ctx context.Context, vseg vmaIterator, b *bytes.Buffer) {\n+func (mm *MemoryManager) appendVMAMapsEntryLocked(ctx context.Context, vseg vmaIterator, fn MapsCallbackFunc) {\nvma := vseg.ValuePtr()\nprivate := \"p\"\nif !vma.private {\n@@ -149,31 +173,19 @@ func (mm *MemoryManager) appendVMAMapsEntryLocked(ctx context.Context, vseg vmaI\ndevMajor := uint32(dev >> devMinorBits)\ndevMinor := uint32(dev & ((1 << devMinorBits) - 1))\n- // Do not include the guard page: fs/proc/task_mmu.c:show_map_vma() =>\n- // stack_guard_page_start().\n- lineLen, _ := fmt.Fprintf(b, \"%08x-%08x %s%s %08x %02x:%02x %d \",\n- vseg.Start(), vseg.End(), vma.realPerms, private, vma.off, devMajor, devMinor, ino)\n-\n// Figure out our filename or hint.\n- var s string\n+ var path string\nif vma.hint != \"\" {\n- s = vma.hint\n+ path = vma.hint\n} else if vma.id != nil {\n// FIXME(jamieliu): We are holding mm.mappingMu here, which is\n// consistent with Linux's holding mmap_sem in\n// fs/proc/task_mmu.c:show_map_vma() => fs/seq_file.c:seq_file_path().\n// However, it's not clear that fs.File.MappedName() is actually\n// consistent with this lock order.\n- s = vma.id.MappedName(ctx)\n- }\n- if s != \"\" {\n- // Per linux, we pad until the 74th character.\n- for pad := 73 - lineLen; pad > 0; pad-- {\n- b.WriteByte(' ')\n- }\n- b.WriteString(s)\n+ path = vma.id.MappedName(ctx)\n}\n- b.WriteByte('\\n')\n+ fn(vseg.Start(), vseg.End(), vma.realPerms, private, vma.off, devMajor, devMinor, ino, path)\n}\n// ReadSmapsDataInto is called by fsimpl/proc.smapsData.Generate to\n@@ -239,7 +251,7 @@ func (mm *MemoryManager) vmaSmapsEntryLocked(ctx context.Context, vseg vmaIterat\n}\nfunc (mm *MemoryManager) vmaSmapsEntryIntoLocked(ctx context.Context, vseg vmaIterator, b *bytes.Buffer) {\n- mm.appendVMAMapsEntryLocked(ctx, vseg, b)\n+ mm.appendVMAMapsEntryLocked(ctx, vseg, mm.MapsCallbackFuncForBuffer(b))\nvma := vseg.ValuePtr()\n// We take mm.activeMu here in each call to vmaSmapsEntryLocked, instead of\n" }, { "change_type": "MODIFY", "old_path": "runsc/boot/procfs/BUILD", "new_path": "runsc/boot/procfs/BUILD", "diff": "@@ -9,6 +9,7 @@ go_library(\ndeps = [\n\"//pkg/abi/linux\",\n\"//pkg/context\",\n+ \"//pkg/hostarch\",\n\"//pkg/log\",\n\"//pkg/sentry/fsimpl/proc\",\n\"//pkg/sentry/kernel\",\n" }, { "change_type": "MODIFY", "old_path": "runsc/boot/procfs/dump.go", "new_path": "runsc/boot/procfs/dump.go", "diff": "@@ -23,6 +23,7 @@ import (\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/context\"\n+ \"gvisor.dev/gvisor/pkg/hostarch\"\n\"gvisor.dev/gvisor/pkg/log\"\n\"gvisor.dev/gvisor/pkg/sentry/fsimpl/proc\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n@@ -65,6 +66,18 @@ type Stat struct {\nSID int32 `json:\"sid\"`\n}\n+// Mapping contains information for /proc/[pid]/maps.\n+type Mapping struct {\n+ Address hostarch.AddrRange `json:\"address,omitempty\"`\n+ Permissions hostarch.AccessType `json:\"permissions\"`\n+ Private string `json:\"private,omitempty\"`\n+ Offset uint64 `json:\"offset\"`\n+ DevMajor uint32 `json:\"deviceMajor,omitempty\"`\n+ DevMinor uint32 `json:\"deviceMinor,omitempty\"`\n+ Inode uint64 `json:\"inode,omitempty\"`\n+ Pathname string `json:\"pathname,omitempty\"`\n+}\n+\n// ProcessProcfsDump contains the procfs dump for one process. For more details\n// on fields that directly correspond to /proc fields, see proc(5).\ntype ProcessProcfsDump struct {\n@@ -92,6 +105,8 @@ type ProcessProcfsDump struct {\nStatus Status `json:\"status,omitempty\"`\n// Stat is /proc/[pid]/stat.\nStat Stat `json:\"stat,omitempty\"`\n+ // Maps is /proc/[pid]/maps.\n+ Maps []Mapping `json:\"maps,omitempty\"`\n}\n// getMM returns t's MemoryManager. On success, the MemoryManager's users count\n@@ -251,6 +266,27 @@ func getStat(t *kernel.Task, pid kernel.ThreadID, pidns *kernel.PIDNamespace) St\n}\n}\n+func getMappings(ctx context.Context, mm *mm.MemoryManager) []Mapping {\n+ var maps []Mapping\n+ mm.ReadMapsDataInto(ctx, func(start, end hostarch.Addr, permissions hostarch.AccessType, private string, offset uint64, devMajor, devMinor uint32, inode uint64, path string) {\n+ maps = append(maps, Mapping{\n+ Address: hostarch.AddrRange{\n+ Start: start,\n+ End: end,\n+ },\n+ Permissions: permissions,\n+ Private: private,\n+ Offset: offset,\n+ DevMajor: devMajor,\n+ DevMinor: devMinor,\n+ Inode: inode,\n+ Pathname: path,\n+ })\n+ })\n+\n+ return maps\n+}\n+\n// Dump returns a procfs dump for process pid. t must be a task in process pid.\nfunc Dump(t *kernel.Task, pid kernel.ThreadID, pidns *kernel.PIDNamespace) (ProcessProcfsDump, error) {\nctx := t.AsyncContext()\n@@ -282,5 +318,6 @@ func Dump(t *kernel.Task, pid kernel.ThreadID, pidns *kernel.PIDNamespace) (Proc\nCgroup: t.GetCgroupEntries(),\nStatus: getStatus(t, mm, pid, pidns),\nStat: getStat(t, pid, pidns),\n+ Maps: getMappings(ctx, mm),\n}, nil\n}\n" }, { "change_type": "MODIFY", "old_path": "runsc/container/trace_test.go", "new_path": "runsc/container/trace_test.go", "diff": "@@ -439,4 +439,14 @@ func TestProcfsDump(t *testing.T) {\nif procfsDump[0].Status.VMRSS == 0 {\nt.Errorf(\"expected VMSize to be set\")\n}\n+ if len(procfsDump[0].Maps) <= 0 {\n+ t.Errorf(\"no region mapped for pid:%v\", procfsDump[0].Status.PID)\n+ }\n+\n+ maps := procfsDump[0].Maps\n+ for i := 0; i < len(procfsDump[0].Maps)-1; i++ {\n+ if maps[i].Address.Overlaps(maps[i+1].Address) {\n+ t.Errorf(\"overlapped addresses for pid:%v\", procfsDump[0].Status.PID)\n+ }\n+ }\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Add /proc/[pid]/maps to runsc trace procfs Updates #7897 PiperOrigin-RevId: 478903608
259,907
04.10.2022 16:49:41
25,200
0842a94cd00aa8ffcb0e61b7f0191bd56f5754d2
Lisafs gofer should not allow walk/mount on pipes. Fixes
[ { "change_type": "MODIFY", "old_path": "runsc/fsgofer/lisafs.go", "new_path": "runsc/fsgofer/lisafs.go", "diff": "@@ -60,12 +60,22 @@ func (s *LisafsServer) Mount(c *lisafs.Connection, mountNode *lisafs.Node) (*lis\nif err != nil {\nreturn nil, linux.Statx{}, err\n}\n+ cu := cleanup.Make(func() {\n+ _ = unix.Close(rootHostFD)\n+ })\n+ defer cu.Clean()\nstat, err := fstatTo(rootHostFD)\nif err != nil {\nreturn nil, linux.Statx{}, err\n}\n+ if err := checkSupportedFileType(uint32(stat.Mode), s.config.HostUDS); err != nil {\n+ log.Warningf(\"Mount: checkSupportedFileType() failed for file %q with mode %o: %v\", mountPath, stat.Mode, err)\n+ return nil, linux.Statx{}, err\n+ }\n+ cu.Release()\n+\nrootFD := &controlFDLisa{\nhostFD: rootHostFD,\nwritableHostFD: atomicbitops.FromInt32(-1),\n@@ -327,6 +337,13 @@ func (fd *controlFDLisa) Walk(name string) (*lisafs.ControlFD, linux.Statx, erro\nstat, err := fstatTo(childHostFD)\nif err != nil {\n+ _ = unix.Close(childHostFD)\n+ return nil, linux.Statx{}, err\n+ }\n+\n+ if err := checkSupportedFileType(uint32(stat.Mode), fd.Conn().ServerImpl().(*LisafsServer).config.HostUDS); err != nil {\n+ _ = unix.Close(childHostFD)\n+ log.Warningf(\"Walk: checkSupportedFileType() failed for %q with mode %o: %v\", name, stat.Mode, err)\nreturn nil, linux.Statx{}, err\n}\n@@ -361,6 +378,7 @@ func (fd *controlFDLisa) WalkStat(path lisafs.StringArray, recordStat func(linux\nif fd.IsSymlink() {\nreturn nil\n}\n+ server := fd.Conn().ServerImpl().(*LisafsServer)\nfor _, name := range path {\ncurFD, err := unix.Openat(curDirFD, name, unix.O_PATH|openFlags, 0)\nif err == unix.ENOENT {\n@@ -378,6 +396,10 @@ func (fd *controlFDLisa) WalkStat(path lisafs.StringArray, recordStat func(linux\nif err != nil {\nreturn err\n}\n+ if err := checkSupportedFileType(uint32(stat.Mode), server.config.HostUDS); err != nil {\n+ log.Warningf(\"WalkStat: checkSupportedFileType() failed for file %q with mode %o while walking path %+v: %v\", name, stat.Mode, path, err)\n+ return err\n+ }\nrecordStat(stat)\n// Symlinks terminate walk. This client gets the symlink stat result, but\n" }, { "change_type": "MODIFY", "old_path": "test/e2e/BUILD", "new_path": "test/e2e/BUILD", "diff": "@@ -23,6 +23,7 @@ go_test(\n\"//pkg/test/testutil\",\n\"//runsc/specutils\",\n\"@com_github_docker_docker//api/types/mount:go_default_library\",\n+ \"@org_golang_x_sys//unix:go_default_library\",\n],\n)\n" }, { "change_type": "MODIFY", "old_path": "test/e2e/integration_test.go", "new_path": "test/e2e/integration_test.go", "diff": "@@ -30,6 +30,7 @@ import (\n\"net/http\"\n\"os\"\n\"os/exec\"\n+ \"path\"\n\"path/filepath\"\n\"regexp\"\n\"strconv\"\n@@ -38,6 +39,7 @@ import (\n\"time\"\n\"github.com/docker/docker/api/types/mount\"\n+ \"golang.org/x/sys/unix\"\n\"gvisor.dev/gvisor/pkg/test/dockerutil\"\n\"gvisor.dev/gvisor/pkg/test/testutil\"\n)\n@@ -997,3 +999,27 @@ func TestNonSearchableWorkingDirectory(t *testing.T) {\nt.Errorf(\"ls error message not found, want: %q, got: %q\", wantErrorMsg, got)\n}\n}\n+\n+func TestPipeMountFails(t *testing.T) {\n+ ctx := context.Background()\n+ d := dockerutil.MakeContainer(ctx, t)\n+ defer d.CleanUp(ctx)\n+\n+ fifoPath := path.Join(testutil.TmpDir(), \"fifo\")\n+ if err := unix.Mkfifo(fifoPath, 0666); err != nil {\n+ t.Fatalf(\"Mkfifo(%q) failed: %v\", fifoPath, err)\n+ }\n+ opts := dockerutil.RunOpts{\n+ Image: \"basic/alpine\",\n+ Mounts: []mount.Mount{\n+ {\n+ Type: mount.TypeBind,\n+ Source: fifoPath,\n+ Target: \"/foo\",\n+ },\n+ },\n+ }\n+ if _, err := d.Run(ctx, opts, \"ls\"); err == nil {\n+ t.Errorf(\"docker run succeded, but mounting a named pipe should not work\")\n+ }\n+}\n" } ]
Go
Apache License 2.0
google/gvisor
Lisafs gofer should not allow walk/mount on pipes. Fixes #8045 PiperOrigin-RevId: 478915103
259,885
06.10.2022 10:01:06
25,200
718e3b5812de92f29796416ea12bfa46a24887e9
Don't use libc mremap within InForkedProcess() in mremap test.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/mremap.cc", "new_path": "test/syscalls/linux/mremap.cc", "diff": "#include <errno.h>\n#include <string.h>\n#include <sys/mman.h>\n+#ifdef __linux__\n+#include <sys/syscall.h>\n+#endif\n+#include <unistd.h>\n#include <string>\n@@ -35,6 +39,15 @@ namespace testing {\nnamespace {\n+// libc mremap isn't guaranteed to be async-signal-safe by signal-safety(7) and\n+// therefore isn't necessarily safe to call between fork(2) and execve(2);\n+// provide our own version that is.\n+void* safe_mremap(void* old_addr, size_t old_size, size_t new_size,\n+ unsigned long flags, void* new_address = nullptr) { // NOLINT\n+ return reinterpret_cast<void*>(\n+ syscall(SYS_mremap, old_addr, old_size, new_size, flags, new_address));\n+}\n+\n// Fixture for mremap tests parameterized by mmap flags.\nusing MremapParamTest = ::testing::TestWithParam<int>;\n@@ -54,7 +67,7 @@ TEST_P(MremapParamTest, InPlace_ShrinkingWholeVMA) {\nconst auto rest = [&] {\n// N.B. we must be in a single-threaded subprocess to ensure a\n// background thread doesn't concurrently map the second page.\n- void* addr = mremap(m.ptr(), 2 * kPageSize, kPageSize, 0, nullptr);\n+ void* addr = safe_mremap(m.ptr(), 2 * kPageSize, kPageSize, 0, nullptr);\nTEST_PCHECK_MSG(addr != MAP_FAILED, \"mremap failed\");\nTEST_CHECK(addr == m.ptr());\nMaybeSave();\n@@ -71,7 +84,7 @@ TEST_P(MremapParamTest, InPlace_ShrinkingPartialVMA) {\nASSERT_NO_ERRNO_AND_VALUE(MmapAnon(3 * kPageSize, PROT_NONE, GetParam()));\nconst auto rest = [&] {\n- void* addr = mremap(m.ptr(), 2 * kPageSize, kPageSize, 0, nullptr);\n+ void* addr = safe_mremap(m.ptr(), 2 * kPageSize, kPageSize, 0, nullptr);\nTEST_PCHECK_MSG(addr != MAP_FAILED, \"mremap failed\");\nTEST_CHECK(addr == m.ptr());\nMaybeSave();\n@@ -93,7 +106,7 @@ TEST_P(MremapParamTest, InPlace_ShrinkingAcrossVMAs) {\nconst auto rest = [&] {\n// Both old_size and new_size now span two vmas; mremap\n// shouldn't care.\n- void* addr = mremap(m.ptr(), 3 * kPageSize, 2 * kPageSize, 0, nullptr);\n+ void* addr = safe_mremap(m.ptr(), 3 * kPageSize, 2 * kPageSize, 0, nullptr);\nTEST_PCHECK_MSG(addr != MAP_FAILED, \"mremap failed\");\nTEST_CHECK(addr == m.ptr());\nMaybeSave();\n@@ -119,7 +132,7 @@ TEST_P(MremapParamTest, InPlace_ExpansionSuccess) {\nmunmap(reinterpret_cast<void*>(m.addr() + kPageSize), kPageSize) == 0);\nMaybeSave();\n- void* addr = mremap(m.ptr(), kPageSize, 2 * kPageSize, 0, nullptr);\n+ void* addr = safe_mremap(m.ptr(), kPageSize, 2 * kPageSize, 0, nullptr);\nTEST_PCHECK_MSG(addr != MAP_FAILED, \"mremap failed\");\nTEST_CHECK(addr == m.ptr());\nMaybeSave();\n@@ -143,7 +156,7 @@ TEST_P(MremapParamTest, InPlace_ExpansionFailure) {\nmunmap(reinterpret_cast<void*>(m.addr() + kPageSize), kPageSize) == 0);\nMaybeSave();\n- void* addr = mremap(m.ptr(), kPageSize, 3 * kPageSize, 0, nullptr);\n+ void* addr = safe_mremap(m.ptr(), kPageSize, 3 * kPageSize, 0, nullptr);\nTEST_CHECK_MSG(addr == MAP_FAILED, \"mremap unexpectedly succeeded\");\nTEST_PCHECK_MSG(errno == ENOMEM, \"mremap failed with wrong errno\");\nMaybeSave();\n@@ -170,7 +183,7 @@ TEST_P(MremapParamTest, MayMove_Expansion) {\nMaybeSave();\nvoid* addr2 =\n- mremap(m.ptr(), kPageSize, 3 * kPageSize, MREMAP_MAYMOVE, nullptr);\n+ safe_mremap(m.ptr(), kPageSize, 3 * kPageSize, MREMAP_MAYMOVE, nullptr);\nTEST_PCHECK_MSG(addr2 != MAP_FAILED, \"mremap failed\");\nMaybeSave();\n@@ -209,7 +222,7 @@ TEST_P(MremapParamTest, Fixed_SameSize) {\nTEST_PCHECK(munmap(dst.ptr(), kPageSize) == 0);\nMaybeSave();\n- void* addr = mremap(src.ptr(), kPageSize, kPageSize,\n+ void* addr = safe_mremap(src.ptr(), kPageSize, kPageSize,\nMREMAP_MAYMOVE | MREMAP_FIXED, dst.ptr());\nTEST_PCHECK_MSG(addr != MAP_FAILED, \"mremap failed\");\nTEST_CHECK(addr == dst.ptr());\n@@ -231,7 +244,7 @@ TEST_P(MremapParamTest, Fixed_SameSize_Unmapping) {\nASSERT_NO_ERRNO_AND_VALUE(MmapAnon(kPageSize, PROT_NONE, GetParam()));\nconst auto rest = [&] {\n- void* addr = mremap(src.ptr(), kPageSize, kPageSize,\n+ void* addr = safe_mremap(src.ptr(), kPageSize, kPageSize,\nMREMAP_MAYMOVE | MREMAP_FIXED, dst.ptr());\nTEST_PCHECK_MSG(addr != MAP_FAILED, \"mremap failed\");\nTEST_CHECK(addr == dst.ptr());\n@@ -256,7 +269,7 @@ TEST_P(MremapParamTest, Fixed_ShrinkingWholeVMA) {\nTEST_PCHECK(munmap(dst.ptr(), 2 * kPageSize) == 0);\nMaybeSave();\n- void* addr = mremap(src.ptr(), 2 * kPageSize, kPageSize,\n+ void* addr = safe_mremap(src.ptr(), 2 * kPageSize, kPageSize,\nMREMAP_MAYMOVE | MREMAP_FIXED, dst.ptr());\nTEST_PCHECK_MSG(addr != MAP_FAILED, \"mremap failed\");\nTEST_CHECK(addr == dst.ptr());\n@@ -283,7 +296,7 @@ TEST_P(MremapParamTest, Fixed_ShrinkingPartialVMA) {\nTEST_PCHECK(munmap(dst.ptr(), 2 * kPageSize) == 0);\nMaybeSave();\n- void* addr = mremap(src.ptr(), 2 * kPageSize, kPageSize,\n+ void* addr = safe_mremap(src.ptr(), 2 * kPageSize, kPageSize,\nMREMAP_MAYMOVE | MREMAP_FIXED, dst.ptr());\nTEST_PCHECK_MSG(addr != MAP_FAILED, \"mremap failed\");\nTEST_CHECK(addr == dst.ptr());\n@@ -310,7 +323,7 @@ TEST_P(MremapParamTest, Fixed_ShrinkingAcrossVMAs) {\nconst auto rest = [&] {\n// Unlike flags=0, MREMAP_FIXED requires that [old_address,\n// old_address+new_size) only spans a single vma.\n- void* addr = mremap(src.ptr(), 3 * kPageSize, 2 * kPageSize,\n+ void* addr = safe_mremap(src.ptr(), 3 * kPageSize, 2 * kPageSize,\nMREMAP_MAYMOVE | MREMAP_FIXED, dst.ptr());\nTEST_CHECK_MSG(addr == MAP_FAILED, \"mremap unexpectedly succeeded\");\nTEST_PCHECK_MSG(errno == EFAULT, \"mremap failed with wrong errno\");\n@@ -341,7 +354,7 @@ TEST_P(MremapParamTest, Fixed_Expansion) {\nTEST_PCHECK(munmap(dst.ptr(), 2 * kPageSize) == 0);\nMaybeSave();\n- void* addr = mremap(src.ptr(), kPageSize, 2 * kPageSize,\n+ void* addr = safe_mremap(src.ptr(), kPageSize, 2 * kPageSize,\nMREMAP_MAYMOVE | MREMAP_FIXED, dst.ptr());\nTEST_PCHECK_MSG(addr != MAP_FAILED, \"mremap failed\");\nTEST_CHECK(addr == dst.ptr());\n@@ -376,7 +389,7 @@ TEST(MremapTest, MayMove_Copy) {\n// Remainder of this test executes in a subprocess to ensure that if mremap\n// incorrectly removes m, it is not remapped by another thread.\nconst auto rest = [&] {\n- void* ptr = mremap(m.ptr(), 0, kPageSize, MREMAP_MAYMOVE, nullptr);\n+ void* ptr = safe_mremap(m.ptr(), 0, kPageSize, MREMAP_MAYMOVE, nullptr);\nMaybeSave();\nTEST_PCHECK_MSG(ptr != MAP_FAILED, \"mremap failed\");\nTEST_CHECK(ptr != m.ptr());\n@@ -395,8 +408,8 @@ TEST(MremapTest, MustMove_Copy) {\n// Remainder of this test executes in a subprocess to ensure that if mremap\n// incorrectly removes src, it is not remapped by another thread.\nconst auto rest = [&] {\n- void* ptr = mremap(src.ptr(), 0, kPageSize, MREMAP_MAYMOVE | MREMAP_FIXED,\n- dst.ptr());\n+ void* ptr = safe_mremap(src.ptr(), 0, kPageSize,\n+ MREMAP_MAYMOVE | MREMAP_FIXED, dst.ptr());\nMaybeSave();\nTEST_PCHECK_MSG(ptr != MAP_FAILED, \"mremap failed\");\nTEST_CHECK(ptr == dst.ptr());\n" } ]
Go
Apache License 2.0
google/gvisor
Don't use libc mremap within InForkedProcess() in mremap test. PiperOrigin-RevId: 479341121
259,985
06.10.2022 13:01:57
25,200
c174470a2d7ae3940c07aa803923299a228c94d4
Clarify that auth.NewRootUserNamespace creates a distinct ns on each call.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/auth/user_namespace.go", "new_path": "pkg/sentry/kernel/auth/user_namespace.go", "diff": "@@ -52,7 +52,10 @@ type UserNamespace struct {\n}\n// NewRootUserNamespace returns a UserNamespace that is appropriate for a\n-// system's root user namespace.\n+// system's root user namespace. Note that namespaces returned by separate calls\n+// to this function are *distinct* namespaces. Once a root namespace is created\n+// by this function, the returned value must be reused to refer to the same\n+// namespace.\nfunc NewRootUserNamespace() *UserNamespace {\nvar ns UserNamespace\n// \"\"\"\n" } ]
Go
Apache License 2.0
google/gvisor
Clarify that auth.NewRootUserNamespace creates a distinct ns on each call. PiperOrigin-RevId: 479392054
260,004
07.10.2022 10:21:55
25,200
76d800d41013a1f9aad073a4323117c2bac95438
Limit the number of discovered SLAAC prefixes ...to prevent address explosion. Fuchsia bug:
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/ndp.go", "new_path": "pkg/tcpip/network/ipv6/ndp.go", "diff": "@@ -97,6 +97,11 @@ const (\n// prefixes.\nMaxDiscoveredOnLinkPrefixes = 10\n+ // MaxDiscoveredSLAACPrefixes is the maximum number of discovered\n+ // SLAAC prefixes. The stack will stop discovering new SLAAC\n+ // prefixes after discovering MaxDiscoveredSLAACPrefixes SLAAC prefixes.\n+ MaxDiscoveredSLAACPrefixes = 10\n+\n// validPrefixLenForAutoGen is the expected prefix length that an\n// address can be generated for. Must be 64 bits as the interface\n// identifier (IID) is 64 bits and an IPv6 address is 128 bits, so\n@@ -1039,6 +1044,11 @@ func (ndp *ndpState) handleAutonomousPrefixInformation(pi header.NDPPrefixInform\nreturn\n}\n+ // Limit the number of discovered SLAAC prefixes.\n+ if len(ndp.slaacPrefixes) == MaxDiscoveredSLAACPrefixes {\n+ return\n+ }\n+\nndp.doSLAAC(prefix, pl, vl)\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/ndp_test.go", "new_path": "pkg/tcpip/stack/ndp_test.go", "diff": "@@ -2098,6 +2098,87 @@ func expectAutoGenAddrNewEvent(ndpDisp *ndpDispatcher, addr tcpip.AddressWithPre\n}\n}\n+func TestMaxSlaacPrefixes(t *testing.T) {\n+ const (\n+ nicID = 1\n+ // Each SLAAC prefix gets a stable and temporary address.\n+ slaacAddrsPerPrefix = 2\n+ // Send an extra prefix than what we will discover to make sure we do not\n+ // discover the extra prefix.\n+ slaacPrefixesInRA = ipv6.MaxDiscoveredSLAACPrefixes + 1\n+ )\n+\n+ ndpDisp := ndpDispatcher{\n+ autoGenAddrNewC: make(chan ndpAutoGenAddrNewEvent, slaacPrefixesInRA*slaacAddrsPerPrefix),\n+ }\n+ e := channel.New(0, 1280, linkAddr1)\n+ s := stack.New(stack.Options{\n+ NetworkProtocols: []stack.NetworkProtocolFactory{ipv6.NewProtocolWithOptions(ipv6.Options{\n+ NDPConfigs: ipv6.NDPConfigurations{\n+ HandleRAs: ipv6.HandlingRAsEnabledWhenForwardingDisabled,\n+ AutoGenGlobalAddresses: true,\n+ AutoGenTempGlobalAddresses: true,\n+ },\n+ NDPDisp: &ndpDisp,\n+ })},\n+ })\n+\n+ if err := s.CreateNIC(nicID, e); err != nil {\n+ t.Fatalf(\"CreateNIC(%d) = %s\", nicID, err)\n+ }\n+\n+ optSer := make(header.NDPOptionsSerializer, 0, slaacPrefixesInRA)\n+ prefixes := [slaacPrefixesInRA]tcpip.Subnet{}\n+ for i := 0; i < slaacPrefixesInRA; i++ {\n+ prefixAddr := [16]byte{1, 2, 3, 4, 5, 6, 7, byte(i), 0, 0, 0, 0, 0, 0, 0, 0}\n+ prefix := tcpip.AddressWithPrefix{\n+ Address: tcpip.Address(prefixAddr[:]),\n+ PrefixLen: 64,\n+ }\n+ prefixes[i] = prefix.Subnet()\n+ // Serialize a perfix information option.\n+ buf := [30]byte{}\n+ buf[0] = uint8(prefix.PrefixLen)\n+ // Set the autonomous configuration flag.\n+ buf[1] = 64\n+ // Set the preferred and valid lifetimes to the maxiumum possible value.\n+ binary.BigEndian.PutUint32(buf[2:], math.MaxUint32)\n+ binary.BigEndian.PutUint32(buf[6:], math.MaxUint32)\n+ if n := copy(buf[14:], prefix.Address); n != len(prefix.Address) {\n+ t.Fatalf(\"got copy(...) = %d, want = %d\", n, len(prefix.Address))\n+ }\n+ optSer = append(optSer, header.NDPPrefixInformation(buf[:]))\n+ }\n+\n+ e.InjectInbound(header.IPv6ProtocolNumber, raBufWithOpts(llAddr1, 0, optSer))\n+ for i := 0; i < slaacPrefixesInRA; i++ {\n+ for j := 0; j < slaacAddrsPerPrefix; j++ {\n+ if i < ipv6.MaxDiscoveredSLAACPrefixes {\n+ select {\n+ case e := <-ndpDisp.autoGenAddrNewC:\n+ if e.nicID != nicID {\n+ t.Errorf(\"got e.nicID = %d, want = %d\", e.nicID, nicID)\n+ }\n+ if !prefixes[i].Contains(e.addr.Address) {\n+ t.Errorf(\"got prefixes[%d].Contains(%s) = false, want = true\", i, e.addr)\n+ }\n+ if e.addrDisp != nil {\n+ t.Error(\"auto-gen new addr event unexpectedly contains address dispatcher\")\n+ }\n+ default:\n+ t.Fatalf(\"expected auto-gen new addr event; i=%d, j=%d\", i, j)\n+ }\n+ } else {\n+ select {\n+ case <-ndpDisp.autoGenAddrNewC:\n+ t.Fatal(\"should not have discovered a new auto-gen addr after we already discovered the max number of prefixes\")\n+ default:\n+ }\n+ }\n+ }\n+ }\n+}\n+\n// TestAutoGenAddr tests that an address is properly generated and invalidated\n// when configured to do so.\nfunc TestAutoGenAddr(t *testing.T) {\n" } ]
Go
Apache License 2.0
google/gvisor
Limit the number of discovered SLAAC prefixes ...to prevent address explosion. Fuchsia bug: https://fxbug.dev/110896 PiperOrigin-RevId: 479613489
259,885
07.10.2022 11:00:57
25,200
543e8a22565bd8c926350292736a2780982ea021
Fix flakes in tests that use munmap() to create deliberate MM holes.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/BUILD", "new_path": "test/syscalls/linux/BUILD", "diff": "@@ -1057,6 +1057,8 @@ cc_binary(\n\"@com_google_absl//absl/time\",\ngtest,\n\"//test/util:io_uring_util\",\n+ \"//test/util:memory_util\",\n+ \"//test/util:multiprocess_util\",\n\"//test/util:temp_path\",\n\"//test/util:test_main\",\n\"//test/util:test_util\",\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/io_uring.cc", "new_path": "test/syscalls/linux/io_uring.cc", "diff": "#include \"gtest/gtest.h\"\n#include \"test/util/io_uring_util.h\"\n+#include \"test/util/memory_util.h\"\n+#include \"test/util/multiprocess_util.h\"\n#include \"test/util/test_util.h\"\nnamespace gvisor {\n@@ -72,10 +74,18 @@ TEST(IOUringTest, MMapMUnMapWork) {\nEXPECT_NE(ptr, MAP_FAILED);\n- ASSERT_THAT(munmap(ptr, sring_sz), SyscallSucceeds());\n-\n- EXPECT_EXIT(*reinterpret_cast<volatile int *>(ptr) = 42,\n- ::testing::KilledBySignal(SIGSEGV), \"\");\n+ const auto rest = [&] {\n+ // N.B. we must be in a single-threaded subprocess to ensure that another\n+ // thread doesn't racily remap at ptr.\n+ TEST_PCHECK_MSG(MunmapSafe(ptr, sring_sz) == 0, \"munmap failed\");\n+ // This should SIGSEGV.\n+ *reinterpret_cast<volatile int *>(ptr) = 42;\n+ };\n+\n+ int child_exit_status = ASSERT_NO_ERRNO_AND_VALUE(InForkedProcess(rest));\n+ EXPECT_TRUE(WIFSIGNALED(child_exit_status) &&\n+ WTERMSIG(child_exit_status) == SIGSEGV)\n+ << \"exit status: \" << child_exit_status;\n}\n// Testing that both mmap fails with EINVAL when an invalid offset is passed.\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/mmap.cc", "new_path": "test/syscalls/linux/mmap.cc", "diff": "@@ -92,7 +92,7 @@ class MMapTest : public ::testing::Test {\nreturn -1;\n}\n- int ret = munmap(addr_, length_);\n+ int ret = MunmapSafe(addr_, length_);\naddr_ = nullptr;\nlength_ = 0;\n@@ -298,9 +298,10 @@ TEST_F(MMapTest, MapDevZeroSegfaultAfterUnmap) {\n*reinterpret_cast<volatile int*>(addr_saved) = 0xFF;\n};\n- EXPECT_THAT(InForkedProcess(rest),\n- IsPosixErrorOkAndHolds(AnyOf(Eq(W_EXITCODE(0, SIGSEGV)),\n- Eq(W_EXITCODE(0, 128 + SIGSEGV)))));\n+ int child_exit_status = ASSERT_NO_ERRNO_AND_VALUE(InForkedProcess(rest));\n+ EXPECT_TRUE(WIFSIGNALED(child_exit_status) &&\n+ WTERMSIG(child_exit_status) == SIGSEGV)\n+ << \"exit status: \" << child_exit_status;\n}\nTEST_F(MMapTest, MapDevZeroUnaligned) {\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/mremap.cc", "new_path": "test/syscalls/linux/mremap.cc", "diff": "@@ -42,7 +42,7 @@ namespace {\n// libc mremap isn't guaranteed to be async-signal-safe by signal-safety(7) and\n// therefore isn't necessarily safe to call between fork(2) and execve(2);\n// provide our own version that is.\n-void* safe_mremap(void* old_addr, size_t old_size, size_t new_size,\n+void* MremapSafe(void* old_addr, size_t old_size, size_t new_size,\nunsigned long flags, void* new_address = nullptr) { // NOLINT\nreturn reinterpret_cast<void*>(\nsyscall(SYS_mremap, old_addr, old_size, new_size, flags, new_address));\n@@ -67,7 +67,7 @@ TEST_P(MremapParamTest, InPlace_ShrinkingWholeVMA) {\nconst auto rest = [&] {\n// N.B. we must be in a single-threaded subprocess to ensure a\n// background thread doesn't concurrently map the second page.\n- void* addr = safe_mremap(m.ptr(), 2 * kPageSize, kPageSize, 0, nullptr);\n+ void* addr = MremapSafe(m.ptr(), 2 * kPageSize, kPageSize, 0, nullptr);\nTEST_PCHECK_MSG(addr != MAP_FAILED, \"mremap failed\");\nTEST_CHECK(addr == m.ptr());\nMaybeSave();\n@@ -84,7 +84,7 @@ TEST_P(MremapParamTest, InPlace_ShrinkingPartialVMA) {\nASSERT_NO_ERRNO_AND_VALUE(MmapAnon(3 * kPageSize, PROT_NONE, GetParam()));\nconst auto rest = [&] {\n- void* addr = safe_mremap(m.ptr(), 2 * kPageSize, kPageSize, 0, nullptr);\n+ void* addr = MremapSafe(m.ptr(), 2 * kPageSize, kPageSize, 0, nullptr);\nTEST_PCHECK_MSG(addr != MAP_FAILED, \"mremap failed\");\nTEST_CHECK(addr == m.ptr());\nMaybeSave();\n@@ -106,7 +106,7 @@ TEST_P(MremapParamTest, InPlace_ShrinkingAcrossVMAs) {\nconst auto rest = [&] {\n// Both old_size and new_size now span two vmas; mremap\n// shouldn't care.\n- void* addr = safe_mremap(m.ptr(), 3 * kPageSize, 2 * kPageSize, 0, nullptr);\n+ void* addr = MremapSafe(m.ptr(), 3 * kPageSize, 2 * kPageSize, 0, nullptr);\nTEST_PCHECK_MSG(addr != MAP_FAILED, \"mremap failed\");\nTEST_CHECK(addr == m.ptr());\nMaybeSave();\n@@ -128,11 +128,11 @@ TEST_P(MremapParamTest, InPlace_ExpansionSuccess) {\n//\n// N.B. we must be in a single-threaded subprocess to ensure a\n// background thread doesn't concurrently map this page.\n- TEST_PCHECK(\n- munmap(reinterpret_cast<void*>(m.addr() + kPageSize), kPageSize) == 0);\n+ TEST_PCHECK(MunmapSafe(reinterpret_cast<void*>(m.addr() + kPageSize),\n+ kPageSize) == 0);\nMaybeSave();\n- void* addr = safe_mremap(m.ptr(), kPageSize, 2 * kPageSize, 0, nullptr);\n+ void* addr = MremapSafe(m.ptr(), kPageSize, 2 * kPageSize, 0, nullptr);\nTEST_PCHECK_MSG(addr != MAP_FAILED, \"mremap failed\");\nTEST_CHECK(addr == m.ptr());\nMaybeSave();\n@@ -152,11 +152,11 @@ TEST_P(MremapParamTest, InPlace_ExpansionFailure) {\n// Unmap the second page, leaving a one-page hole. Trying to expand the\n// first page to three pages should fail since the original third page\n// is still mapped.\n- TEST_PCHECK(\n- munmap(reinterpret_cast<void*>(m.addr() + kPageSize), kPageSize) == 0);\n+ TEST_PCHECK(MunmapSafe(reinterpret_cast<void*>(m.addr() + kPageSize),\n+ kPageSize) == 0);\nMaybeSave();\n- void* addr = safe_mremap(m.ptr(), kPageSize, 3 * kPageSize, 0, nullptr);\n+ void* addr = MremapSafe(m.ptr(), kPageSize, 3 * kPageSize, 0, nullptr);\nTEST_CHECK_MSG(addr == MAP_FAILED, \"mremap unexpectedly succeeded\");\nTEST_PCHECK_MSG(errno == ENOMEM, \"mremap failed with wrong errno\");\nMaybeSave();\n@@ -178,12 +178,12 @@ TEST_P(MremapParamTest, MayMove_Expansion) {\n// first page to three pages with MREMAP_MAYMOVE should force the\n// mapping to be relocated since the original third page is still\n// mapped.\n- TEST_PCHECK(\n- munmap(reinterpret_cast<void*>(m.addr() + kPageSize), kPageSize) == 0);\n+ TEST_PCHECK(MunmapSafe(reinterpret_cast<void*>(m.addr() + kPageSize),\n+ kPageSize) == 0);\nMaybeSave();\nvoid* addr2 =\n- safe_mremap(m.ptr(), kPageSize, 3 * kPageSize, MREMAP_MAYMOVE, nullptr);\n+ MremapSafe(m.ptr(), kPageSize, 3 * kPageSize, MREMAP_MAYMOVE, nullptr);\nTEST_PCHECK_MSG(addr2 != MAP_FAILED, \"mremap failed\");\nMaybeSave();\n@@ -219,10 +219,10 @@ TEST_P(MremapParamTest, Fixed_SameSize) {\nconst auto rest = [&] {\n// Unmap dst to create a hole.\n- TEST_PCHECK(munmap(dst.ptr(), kPageSize) == 0);\n+ TEST_PCHECK(MunmapSafe(dst.ptr(), kPageSize) == 0);\nMaybeSave();\n- void* addr = safe_mremap(src.ptr(), kPageSize, kPageSize,\n+ void* addr = MremapSafe(src.ptr(), kPageSize, kPageSize,\nMREMAP_MAYMOVE | MREMAP_FIXED, dst.ptr());\nTEST_PCHECK_MSG(addr != MAP_FAILED, \"mremap failed\");\nTEST_CHECK(addr == dst.ptr());\n@@ -244,7 +244,7 @@ TEST_P(MremapParamTest, Fixed_SameSize_Unmapping) {\nASSERT_NO_ERRNO_AND_VALUE(MmapAnon(kPageSize, PROT_NONE, GetParam()));\nconst auto rest = [&] {\n- void* addr = safe_mremap(src.ptr(), kPageSize, kPageSize,\n+ void* addr = MremapSafe(src.ptr(), kPageSize, kPageSize,\nMREMAP_MAYMOVE | MREMAP_FIXED, dst.ptr());\nTEST_PCHECK_MSG(addr != MAP_FAILED, \"mremap failed\");\nTEST_CHECK(addr == dst.ptr());\n@@ -266,10 +266,10 @@ TEST_P(MremapParamTest, Fixed_ShrinkingWholeVMA) {\nconst auto rest = [&] {\n// Unmap dst so we can check that mremap does not keep the\n// second page.\n- TEST_PCHECK(munmap(dst.ptr(), 2 * kPageSize) == 0);\n+ TEST_PCHECK(MunmapSafe(dst.ptr(), 2 * kPageSize) == 0);\nMaybeSave();\n- void* addr = safe_mremap(src.ptr(), 2 * kPageSize, kPageSize,\n+ void* addr = MremapSafe(src.ptr(), 2 * kPageSize, kPageSize,\nMREMAP_MAYMOVE | MREMAP_FIXED, dst.ptr());\nTEST_PCHECK_MSG(addr != MAP_FAILED, \"mremap failed\");\nTEST_CHECK(addr == dst.ptr());\n@@ -293,10 +293,10 @@ TEST_P(MremapParamTest, Fixed_ShrinkingPartialVMA) {\nconst auto rest = [&] {\n// Unmap dst so we can check that mremap does not keep the\n// second page.\n- TEST_PCHECK(munmap(dst.ptr(), 2 * kPageSize) == 0);\n+ TEST_PCHECK(MunmapSafe(dst.ptr(), 2 * kPageSize) == 0);\nMaybeSave();\n- void* addr = safe_mremap(src.ptr(), 2 * kPageSize, kPageSize,\n+ void* addr = MremapSafe(src.ptr(), 2 * kPageSize, kPageSize,\nMREMAP_MAYMOVE | MREMAP_FIXED, dst.ptr());\nTEST_PCHECK_MSG(addr != MAP_FAILED, \"mremap failed\");\nTEST_CHECK(addr == dst.ptr());\n@@ -323,7 +323,7 @@ TEST_P(MremapParamTest, Fixed_ShrinkingAcrossVMAs) {\nconst auto rest = [&] {\n// Unlike flags=0, MREMAP_FIXED requires that [old_address,\n// old_address+new_size) only spans a single vma.\n- void* addr = safe_mremap(src.ptr(), 3 * kPageSize, 2 * kPageSize,\n+ void* addr = MremapSafe(src.ptr(), 3 * kPageSize, 2 * kPageSize,\nMREMAP_MAYMOVE | MREMAP_FIXED, dst.ptr());\nTEST_CHECK_MSG(addr == MAP_FAILED, \"mremap unexpectedly succeeded\");\nTEST_PCHECK_MSG(errno == EFAULT, \"mremap failed with wrong errno\");\n@@ -351,10 +351,10 @@ TEST_P(MremapParamTest, Fixed_Expansion) {\nconst auto rest = [&] {\n// Unmap dst so we can check that mremap actually maps all pages\n// at the destination.\n- TEST_PCHECK(munmap(dst.ptr(), 2 * kPageSize) == 0);\n+ TEST_PCHECK(MunmapSafe(dst.ptr(), 2 * kPageSize) == 0);\nMaybeSave();\n- void* addr = safe_mremap(src.ptr(), kPageSize, 2 * kPageSize,\n+ void* addr = MremapSafe(src.ptr(), kPageSize, 2 * kPageSize,\nMREMAP_MAYMOVE | MREMAP_FIXED, dst.ptr());\nTEST_PCHECK_MSG(addr != MAP_FAILED, \"mremap failed\");\nTEST_CHECK(addr == dst.ptr());\n@@ -389,7 +389,7 @@ TEST(MremapTest, MayMove_Copy) {\n// Remainder of this test executes in a subprocess to ensure that if mremap\n// incorrectly removes m, it is not remapped by another thread.\nconst auto rest = [&] {\n- void* ptr = safe_mremap(m.ptr(), 0, kPageSize, MREMAP_MAYMOVE, nullptr);\n+ void* ptr = MremapSafe(m.ptr(), 0, kPageSize, MREMAP_MAYMOVE, nullptr);\nMaybeSave();\nTEST_PCHECK_MSG(ptr != MAP_FAILED, \"mremap failed\");\nTEST_CHECK(ptr != m.ptr());\n@@ -408,7 +408,7 @@ TEST(MremapTest, MustMove_Copy) {\n// Remainder of this test executes in a subprocess to ensure that if mremap\n// incorrectly removes src, it is not remapped by another thread.\nconst auto rest = [&] {\n- void* ptr = safe_mremap(src.ptr(), 0, kPageSize,\n+ void* ptr = MremapSafe(src.ptr(), 0, kPageSize,\nMREMAP_MAYMOVE | MREMAP_FIXED, dst.ptr());\nMaybeSave();\nTEST_PCHECK_MSG(ptr != MAP_FAILED, \"mremap failed\");\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/proc.cc", "new_path": "test/syscalls/linux/proc.cc", "diff": "@@ -563,13 +563,20 @@ TEST(ProcPidMem, Unmapped) {\nSyscallSucceedsWithValue(sizeof(output)));\nASSERT_EQ(expected, output);\n+ const auto rest = [&] {\n+ // This is a new process, so we need to re-open /proc/self/mem.\n+ int memfd = open(\"/proc/self/mem\", O_RDONLY);\n+ TEST_PCHECK_MSG(memfd >= 0, \"open failed\");\n// Unmap region again\n- ASSERT_THAT(munmap(mapping.ptr(), mapping.len()), SyscallSucceeds());\n-\n+ TEST_PCHECK_MSG(MunmapSafe(mapping.ptr(), mapping.len()) == 0,\n+ \"munmap failed\");\n// Now we want EIO error\n- ASSERT_THAT(pread(memfd.get(), &output, sizeof(output),\n- reinterpret_cast<off_t>(mapping.ptr())),\n- SyscallFailsWithErrno(EIO));\n+ TEST_CHECK(pread(memfd, &output, sizeof(output),\n+ reinterpret_cast<off_t>(mapping.ptr())) == -1);\n+ TEST_PCHECK_MSG(errno == EIO, \"pread failed with unexpected errno\");\n+ };\n+\n+ EXPECT_THAT(InForkedProcess(rest), IsPosixErrorOkAndHolds(0));\n}\n// Perform read repeatedly to verify offset change.\n@@ -623,29 +630,32 @@ TEST(ProcPidMem, RepeatedSeek) {\n// Perform read past an allocated memory region.\nTEST(ProcPidMem, PartialRead) {\n- // Strategy: map large region, then do unmap and remap smaller region\n- auto memfd = ASSERT_NO_ERRNO_AND_VALUE(Open(\"/proc/self/mem\", O_RDONLY));\n-\n+ // Reserve 2 pages.\nMapping mapping = ASSERT_NO_ERRNO_AND_VALUE(\nMmapAnon(2 * kPageSize, PROT_READ | PROT_WRITE, MAP_PRIVATE));\n- ASSERT_THAT(munmap(mapping.ptr(), mapping.len()), SyscallSucceeds());\n- Mapping smaller_mapping = ASSERT_NO_ERRNO_AND_VALUE(\n- Mmap(mapping.ptr(), kPageSize, PROT_READ | PROT_WRITE,\n- MAP_PRIVATE | MAP_ANONYMOUS, -1, 0));\n- // Fill it with things\n- memset(smaller_mapping.ptr(), 'x', smaller_mapping.len());\n+ // Fill the first page with data.\n+ memset(mapping.ptr(), 'x', kPageSize);\n- // Now we want no error\nchar expected[] = {'x'};\nstd::unique_ptr<char[]> output(new char[kPageSize]);\n- off_t read_offset =\n- reinterpret_cast<off_t>(smaller_mapping.ptr()) + kPageSize - 1;\n- ASSERT_THAT(\n- pread(memfd.get(), output.get(), sizeof(output.get()), read_offset),\n- SyscallSucceedsWithValue(sizeof(expected)));\n- // Since output is larger, than expected we have to do manual compare\n- ASSERT_EQ(expected[0], (output).get()[0]);\n+ off_t read_offset = reinterpret_cast<off_t>(mapping.ptr()) + kPageSize - 1;\n+ const auto rest = [&] {\n+ int memfd = open(\"/proc/self/mem\", O_RDONLY);\n+ TEST_PCHECK_MSG(memfd >= 0, \"open failed\");\n+ // Unmap the second page.\n+ TEST_PCHECK_MSG(\n+ MunmapSafe(reinterpret_cast<void*>(mapping.addr() + kPageSize),\n+ kPageSize) == 0,\n+ \"munmap failed\");\n+ // Expect to read up to the end of the first page without getting EIO.\n+ TEST_PCHECK_MSG(\n+ pread(memfd, output.get(), kPageSize, read_offset) == sizeof(expected),\n+ \"pread failed\");\n+ TEST_CHECK(expected[0] == output.get()[0]);\n+ };\n+\n+ EXPECT_THAT(InForkedProcess(rest), IsPosixErrorOkAndHolds(0));\n}\n// Perform read on /proc/[pid]/mem after exit.\n" }, { "change_type": "MODIFY", "old_path": "test/util/memory_util.h", "new_path": "test/util/memory_util.h", "diff": "#include <stddef.h>\n#include <stdint.h>\n#include <sys/mman.h>\n+#include <sys/syscall.h>\n+#include <unistd.h>\n#include \"absl/strings/str_format.h\"\n#include \"absl/strings/string_view.h\"\nnamespace gvisor {\nnamespace testing {\n+// Async-signal-safe version of munmap(2).\n+inline int MunmapSafe(void* addr, size_t length) {\n+ return syscall(SYS_munmap, addr, length);\n+}\n+\n// RAII type for mmap'ed memory. Only usable in tests due to use of a test-only\n// macro that can't be named without invoking the presubmit's wrath.\nclass Mapping {\n@@ -82,7 +89,7 @@ class Mapping {\nvoid reset(void* ptr, size_t len) {\nif (len_) {\n- TEST_PCHECK(munmap(ptr_, len_) == 0);\n+ TEST_PCHECK(MunmapSafe(ptr_, len_) == 0);\n}\nptr_ = ptr;\nlen_ = len;\n" } ]
Go
Apache License 2.0
google/gvisor
Fix flakes in tests that use munmap() to create deliberate MM holes. PiperOrigin-RevId: 479623755
259,985
07.10.2022 13:07:33
25,200
10a1cadd736abfc3490ec855089551e673ce4aee
Add container exit event.
[ { "change_type": "MODIFY", "old_path": "pkg/eventchannel/event.go", "new_path": "pkg/eventchannel/event.go", "diff": "@@ -59,6 +59,15 @@ func AddEmitter(e Emitter) {\nDefaultEmitter.AddEmitter(e)\n}\n+// HaveEmitters indicates if any emitters have been registered to the\n+// default emitter.\n+func HaveEmitters() bool {\n+ DefaultEmitter.mu.Lock()\n+ defer DefaultEmitter.mu.Unlock()\n+\n+ return len(DefaultEmitter.emitters) > 0\n+}\n+\n// multiEmitter is an Emitter that forwards messages to multiple Emitters.\ntype multiEmitter struct {\n// mu protects emitters.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/control/BUILD", "new_path": "pkg/sentry/control/BUILD", "diff": "@@ -26,6 +26,7 @@ go_library(\n\"//:sandbox\",\n],\ndeps = [\n+ \":control_go_proto\",\n\"//pkg/abi/linux\",\n\"//pkg/context\",\n\"//pkg/eventchannel\",\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/control/control.proto", "new_path": "pkg/sentry/control/control.proto", "diff": "@@ -39,3 +39,10 @@ message ControlConfig {\n// server.\nrepeated Endpoint allowed_controls = 1;\n}\n+\n+// ContainerExitEvent is emitted when a container's init task exits. Duplicate\n+// exit events may be emitted for the same container.\n+message ContainerExitEvent {\n+ string container_id = 1;\n+ uint32 exit_status = 2;\n+}\n\\ No newline at end of file\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/control/lifecycle.go", "new_path": "pkg/sentry/control/lifecycle.go", "diff": "@@ -19,8 +19,10 @@ import (\n\"fmt\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/eventchannel\"\n\"gvisor.dev/gvisor/pkg/fd\"\n\"gvisor.dev/gvisor/pkg/log\"\n+ pb \"gvisor.dev/gvisor/pkg/sentry/control/control_go_proto\"\n\"gvisor.dev/gvisor/pkg/sentry/fdimport\"\n\"gvisor.dev/gvisor/pkg/sentry/fs/user\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n@@ -308,10 +310,30 @@ func (l *Lifecycle) StartContainer(args *StartContainerArgs, _ *uint32) error {\nl.Kernel.StartProcess(tg)\nlog.Infof(\"Started the new container %v \", initArgs.ContainerID)\n- l.updateContainerState(initArgs.ContainerID, stateRunning)\n+ if err := l.updateContainerState(initArgs.ContainerID, stateRunning); err != nil {\n+ // Sanity check: shouldn't fail to update the state at this point.\n+ panic(fmt.Sprintf(\"Failed to set running state: %v\", err))\n+\n+ }\n+\n+ // TODO(b/251490950): reap thread needs to synchronize with Save, so the\n+ // container state update doesn't race with state serialization.\n+ go l.reap(initArgs.ContainerID, tg) // S/R-SAFE: see above.\n+\nreturn nil\n}\n+func (l *Lifecycle) reap(containerID string, tg *kernel.ThreadGroup) {\n+ tg.WaitExited()\n+ if err := l.updateContainerState(containerID, stateStopped); err != nil {\n+ panic(err)\n+ }\n+ eventchannel.Emit(&pb.ContainerExitEvent{\n+ ContainerId: containerID,\n+ ExitStatus: uint32(tg.ExitStatus()),\n+ })\n+}\n+\n// Pause pauses all tasks, blocking until they are stopped.\nfunc (l *Lifecycle) Pause(_, _ *struct{}) error {\nl.Kernel.Pause()\n@@ -347,18 +369,59 @@ type ContainerArgs struct {\nContainerID string `json:\"container_id\"`\n}\n-// WaitContainer waits for the container to exit and returns the exit status.\n-func (l *Lifecycle) WaitContainer(args *ContainerArgs, waitStatus *uint32) error {\n- tg, err := l.getInitContainerProcess(args.ContainerID)\n- if err != nil {\n- return err\n+// GetExitStatus returns the container exit status if it has stopped.\n+func (l *Lifecycle) GetExitStatus(args *ContainerArgs, status *uint32) error {\n+ l.mu.Lock()\n+ defer l.mu.Unlock()\n+\n+ c, ok := l.containerMap[args.ContainerID]\n+ if !ok {\n+ return fmt.Errorf(\"container %q doesn't exist, or has not been started\", args.ContainerID)\n}\n- tg.WaitExited()\n- *waitStatus = uint32(tg.ExitStatus())\n- if err := l.updateContainerState(args.ContainerID, stateStopped); err != nil {\n- return err\n+ if c.state != stateStopped {\n+ return fmt.Errorf(\"container %q hasn't exited yet\", args.ContainerID)\n+ }\n+\n+ *status = uint32(c.tg.ExitStatus())\n+ return nil\n}\n+\n+// Reap notifies the sandbox that the caller is interested in the exit status via\n+// an exit event. The caller is responsible for handling any corresponding exit\n+// events, especially if they're interested in waiting for the exit.\n+func (l *Lifecycle) Reap(args *ContainerArgs, _ *struct{}) error {\n+ // Check if there are any real emitters registered. If there are no\n+ // emitters, the caller will never be notified, so fail immediately.\n+ if !eventchannel.HaveEmitters() {\n+ return fmt.Errorf(\"no event emitters configured\")\n+ }\n+\n+ l.mu.Lock()\n+\n+ c, ok := l.containerMap[args.ContainerID]\n+ if !ok {\n+ l.mu.Unlock()\n+ return fmt.Errorf(\"no container with id %q\", args.ContainerID)\n+ }\n+\n+ // Once a container enters the stop state, the state never changes. It's\n+ // safe to cache a stopped state outside a l.mu critical section.\n+ isStopped := c.state == stateStopped\n+ l.mu.Unlock()\n+\n+ if isStopped {\n+ // Already stopped, emit stop to ensure any callbacks registered after\n+ // the actual stop is called. This may be a duplicate event, but is\n+ // necessary in case the reap goroutine transitions the container to the\n+ // stop state before the caller starts observing the event channel.\n+ eventchannel.Emit(&pb.ContainerExitEvent{\n+ ContainerId: args.ContainerID,\n+ ExitStatus: uint32(c.tg.ExitStatus()),\n+ })\n+ }\n+\n+ // Caller now responsible for blocking on the exit event.\nreturn nil\n}\n@@ -368,18 +431,12 @@ func (l *Lifecycle) IsContainerRunning(args *ContainerArgs, isRunning *bool) err\ndefer l.mu.Unlock()\nc, ok := l.containerMap[args.ContainerID]\n- if !ok || c.state != stateRunning {\n+ // We may be racing with the reaper goroutine updating c.state, so also\n+ // check the number non-exited tasks.\n+ if !ok || c.state != stateRunning || c.tg.Count() == 0 {\nreturn nil\n}\n- // The state will not be updated to \"stopped\" if the\n- // WaitContainer(...) method is not called. In this case, check\n- // whether the number of non-exited tasks in tg is zero to get\n- // the correct state of the container.\n- if c.tg.Count() == 0 {\n- c.state = stateStopped\n- return nil\n- }\n*isRunning = true\nreturn nil\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Add container exit event. PiperOrigin-RevId: 479651998
260,004
07.10.2022 13:42:07
25,200
39ac7df1b78c4853b054fa43e5eb14106511b6b7
ConfirmReachable with the cached neighbor entry This avoids a map lookup (RLock) in the TCP data path.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/neighbor_cache.go", "new_path": "pkg/tcpip/stack/neighbor_cache.go", "diff": "@@ -294,19 +294,6 @@ func (n *neighborCache) handleConfirmation(addr tcpip.Address, linkAddr tcpip.Li\n}\n}\n-// handleUpperLevelConfirmation processes a confirmation of reachablity from\n-// some protocol that operates at a layer above the IP/link layer.\n-func (n *neighborCache) handleUpperLevelConfirmation(addr tcpip.Address) {\n- n.mu.RLock()\n- entry, ok := n.mu.cache[addr]\n- n.mu.RUnlock()\n- if ok {\n- entry.mu.Lock()\n- entry.handleUpperLevelConfirmationLocked()\n- entry.mu.Unlock()\n- }\n-}\n-\nfunc (n *neighborCache) init(nic *nic, r LinkAddressResolver) {\n*n = neighborCache{\nnic: nic,\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/neighbor_entry.go", "new_path": "pkg/tcpip/stack/neighbor_entry.go", "diff": "@@ -589,11 +589,12 @@ func (e *neighborEntry) handleConfirmationLocked(linkAddr tcpip.LinkAddress, fla\n}\n}\n-// handleUpperLevelConfirmationLocked processes an incoming upper-level protocol\n+// handleUpperLevelConfirmation processes an incoming upper-level protocol\n// (e.g. TCP acknowledgements) reachability confirmation.\n-//\n-// Precondition: e.mu MUST be locked.\n-func (e *neighborEntry) handleUpperLevelConfirmationLocked() {\n+func (e *neighborEntry) handleUpperLevelConfirmation() {\n+ e.mu.Lock()\n+ defer e.mu.Unlock()\n+\nswitch e.mu.neigh.State {\ncase Stale, Delay, Probe:\ne.setStateLocked(Reachable)\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/neighbor_entry_test.go", "new_path": "pkg/tcpip/stack/neighbor_entry_test.go", "diff": "@@ -1415,12 +1415,12 @@ func TestEntryDelayToReachableWhenUpperLevelConfirmation(t *testing.T) {\nt.Fatalf(\"staleToDelay(...) = %s\", err)\n}\n- e.mu.Lock()\n- e.handleUpperLevelConfirmationLocked()\n+ e.handleUpperLevelConfirmation()\n+ e.mu.RLock()\nif e.mu.neigh.State != Reachable {\nt.Errorf(\"got e.mu.neigh.State = %q, want = %q\", e.mu.neigh.State, Reachable)\n}\n- e.mu.Unlock()\n+ e.mu.RUnlock()\n// No probes should have been sent.\nrunImmediatelyScheduledJobs(clock)\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/nic.go", "new_path": "pkg/tcpip/stack/nic.go", "diff": "@@ -30,10 +30,6 @@ type linkResolver struct {\nneigh neighborCache\n}\n-func (l *linkResolver) confirmReachable(addr tcpip.Address) {\n- l.neigh.handleUpperLevelConfirmation(addr)\n-}\n-\nvar _ NetworkInterface = (*nic)(nil)\nvar _ NetworkDispatcher = (*nic)(nil)\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/route.go", "new_path": "pkg/tcpip/stack/route.go", "diff": "@@ -581,7 +581,7 @@ func (r *Route) IsOutboundBroadcast() bool {\n// \"Reachable\" is defined as having full-duplex communication between the\n// local and remote ends of the route.\nfunc (r *Route) ConfirmReachable() {\n- if r.linkRes != nil {\n- r.linkRes.confirmReachable(r.nextHop())\n+ if entry := r.getCachedNeighborEntry(); entry != nil {\n+ entry.handleUpperLevelConfirmation()\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/tests/integration/link_resolution_test.go", "new_path": "pkg/tcpip/tests/integration/link_resolution_test.go", "diff": "@@ -1391,8 +1391,20 @@ func TestTCPConfirmNeighborReachability(t *testing.T) {\nif err := listenerEP.Bind(listenerAddr); err != nil {\nt.Fatalf(\"listenerEP.Bind(%#v): %s\", listenerAddr, err)\n}\n- if err := listenerEP.Listen(1); err != nil {\n- t.Fatalf(\"listenerEP.Listen(1): %s\", err)\n+ // A backlog of 1 results in SYN cookies being used for all passive\n+ // connections to make sure the only spot in the accept queue is not\n+ // taken by a connection that never completes the handshake. We use\n+ // a backlog of 2 to make sure SYN cookies are not used.\n+ //\n+ // We avoid SYN cookies to make sure that an accepted endpoint is able\n+ // to confirm the neighbor's reachability through the cached neighbor\n+ // entry in the endpoint's route. When SYN cookies are used, the\n+ // accepted endpoint is constructed when the handshake has already been\n+ // established and such an endpoint's route will not have a cached\n+ // neighbor entry as it was not used to send any of packets for the\n+ // handshake.\n+ if err := listenerEP.Listen(2); err != nil {\n+ t.Fatalf(\"listenerEP.Listen(2): %s\", err)\n}\n{\nerr := clientEP.Connect(listenerAddr)\n" } ]
Go
Apache License 2.0
google/gvisor
ConfirmReachable with the cached neighbor entry This avoids a map lookup (RLock) in the TCP data path. PiperOrigin-RevId: 479659280
259,868
07.10.2022 15:14:03
25,200
66aa0427cda4e820ca37f2f6df797db7672d70bf
Make BuildKite's docker runtime reload logic robust against empty runtime dict
[ { "change_type": "MODIFY", "old_path": ".buildkite/hooks/post-command", "new_path": ".buildkite/hooks/post-command", "diff": "@@ -77,8 +77,11 @@ done\nset -euo pipefail\n# Remove all Docker runtimes that may be installed.\n-if grep -qE runtimes /etc/docker/daemon.json; then\n- cat /etc/docker/daemon.json | jq 'del(.runtimes) + {runtimes: {}}' \\\n+num_docker_runtimes=\"$(jq \\\n+ '(if has(\"runtimes\") then .runtimes else {} end) | length' \\\n+ < /etc/docker/daemon.json)\"\n+if [[ \"$num_docker_runtimes\" -gt 0 ]]; then\n+ cat /etc/docker/daemon.json | jq 'del(.runtimes)' \\\n| sudo tee /etc/docker/daemon.json.tmp\nsudo mv /etc/docker/daemon.json.tmp /etc/docker/daemon.json\nbash -c \"$DOCKER_RELOAD_COMMAND\"\n" } ]
Go
Apache License 2.0
google/gvisor
Make BuildKite's docker runtime reload logic robust against empty runtime dict PiperOrigin-RevId: 479678511
260,004
07.10.2022 15:58:22
25,200
3f60372ea355b2125735bdcdb0519352511639fa
Avoid write lock when handling upper layer confirmation Fixes
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/neighbor_entry.go", "new_path": "pkg/tcpip/stack/neighbor_entry.go", "diff": "@@ -592,26 +592,45 @@ func (e *neighborEntry) handleConfirmationLocked(linkAddr tcpip.LinkAddress, fla\n// handleUpperLevelConfirmation processes an incoming upper-level protocol\n// (e.g. TCP acknowledgements) reachability confirmation.\nfunc (e *neighborEntry) handleUpperLevelConfirmation() {\n- e.mu.Lock()\n- defer e.mu.Unlock()\n-\n+ tryHandleConfirmation := func() bool {\nswitch e.mu.neigh.State {\ncase Stale, Delay, Probe:\n- e.setStateLocked(Reachable)\n- e.dispatchChangeEventLocked()\n-\n+ return true\ncase Reachable:\n// Avoid setStateLocked; Timer.Reset is cheaper.\n+ //\n+ // Note that setting the timer does not need to be protected by the\n+ // entry's write lock since we do not modify the timer pointer, but the\n+ // time the timer should fire. The timer should have internal locks to\n+ // synchronize timer resets changes with the clock.\ne.mu.timer.timer.Reset(e.nudState.ReachableTime())\n-\n+ return false\ncase Unknown, Incomplete, Unreachable, Static:\n// Do nothing\n-\n+ return false\ndefault:\npanic(fmt.Sprintf(\"Invalid cache entry state: %s\", e.mu.neigh.State))\n}\n}\n+ e.mu.RLock()\n+ needsTransition := tryHandleConfirmation()\n+ e.mu.RUnlock()\n+ if !needsTransition {\n+ return\n+ }\n+\n+ // We need to transition the neighbor to Reachable so take the write lock and\n+ // perform the transition, but only if we still need the transition since the\n+ // state could have changed since we dropped the read lock above.\n+ e.mu.Lock()\n+ defer e.mu.Unlock()\n+ if needsTransition := tryHandleConfirmation(); needsTransition {\n+ e.setStateLocked(Reachable)\n+ e.dispatchChangeEventLocked()\n+ }\n+}\n+\n// getRemoteLinkAddress returns the entry's link address and whether that link\n// address is valid.\nfunc (e *neighborEntry) getRemoteLinkAddress() (tcpip.LinkAddress, bool) {\n" } ]
Go
Apache License 2.0
google/gvisor
Avoid write lock when handling upper layer confirmation Fixes #8051 PiperOrigin-RevId: 479686806
259,853
10.10.2022 12:31:13
25,200
6e5aadd36f7d20a939a75a70e471e4fc7fe04706
Don't run each test case in a separate sandbox This change was inspired by the Fabricio's change: ("Run shards in a single sandbox")
[ { "change_type": "MODIFY", "old_path": "test/runner/defs.bzl", "new_path": "test/runner/defs.bzl", "diff": "@@ -72,6 +72,7 @@ def _syscall_test(\nlisafs = True,\nfuse = False,\ncontainer = None,\n+ one_sandbox = True,\n**kwargs):\n# Prepend \"runsc\" to non-native platform names.\nfull_platform = platform if platform == \"native\" else \"runsc_\" + platform\n@@ -143,6 +144,7 @@ def _syscall_test(\n\"--strace=\" + str(debug),\n\"--debug=\" + str(debug),\n\"--container=\" + str(container),\n+ \"--one-sandbox=\" + str(one_sandbox),\n]\n# Trace points are platform agnostic, so enable them for ptrace only.\n@@ -170,6 +172,7 @@ def syscall_test(\nadd_overlay = False,\nadd_uds_tree = False,\nadd_hostinet = False,\n+ one_sandbox = True,\nfuse = False,\nallow_native = True,\ndebug = True,\n@@ -204,6 +207,7 @@ def syscall_test(\ntags = tags,\ndebug = debug,\ncontainer = container,\n+ one_sandbox = one_sandbox,\n**kwargs\n)\n@@ -217,6 +221,7 @@ def syscall_test(\nfuse = fuse,\ndebug = debug,\ncontainer = container,\n+ one_sandbox = one_sandbox,\n**kwargs\n)\n@@ -230,6 +235,7 @@ def syscall_test(\ndebug = debug,\nfuse = fuse,\ncontainer = container,\n+ one_sandbox = one_sandbox,\nlisafs = False,\n**kwargs\n)\n@@ -243,6 +249,7 @@ def syscall_test(\ndebug = debug,\nfuse = fuse,\ncontainer = container,\n+ one_sandbox = one_sandbox,\noverlay = True,\n**kwargs\n)\n@@ -257,6 +264,7 @@ def syscall_test(\ndebug = debug,\nfuse = fuse,\ncontainer = container,\n+ one_sandbox = one_sandbox,\n**kwargs\n)\nif not use_tmpfs:\n@@ -269,6 +277,7 @@ def syscall_test(\ntags = platforms.get(default_platform, []) + tags,\ndebug = debug,\ncontainer = container,\n+ one_sandbox = one_sandbox,\nfile_access = \"shared\",\nfuse = fuse,\n**kwargs\n" }, { "change_type": "MODIFY", "old_path": "test/runner/gtest/gtest.go", "new_path": "test/runner/gtest/gtest.go", "diff": "@@ -179,3 +179,36 @@ func ParseBenchmarks(binary string, extraArgs ...string) ([]TestCase, error) {\n}\nreturn t, nil\n}\n+\n+// BuildTestArgs builds arguments to be passed to the test binary to execute\n+// only the test cases in `indices`.\n+func BuildTestArgs(indices []int, testCases []TestCase) []string {\n+ var testFilter, benchFilter string\n+ for _, tci := range indices {\n+ tc := testCases[tci]\n+ if tc.all {\n+ // No argument will make all tests run.\n+ return nil\n+ }\n+ if tc.benchmark {\n+ if len(benchFilter) > 0 {\n+ benchFilter += \"|\"\n+ }\n+ benchFilter += \"^\" + tc.Name + \"$\"\n+ } else {\n+ if len(testFilter) > 0 {\n+ testFilter += \":\"\n+ }\n+ testFilter += tc.FullName()\n+ }\n+ }\n+\n+ var args []string\n+ if len(testFilter) > 0 {\n+ args = append(args, fmt.Sprintf(\"%s=%s\", filterTestFlag, testFilter))\n+ }\n+ if len(benchFilter) > 0 {\n+ args = append(args, fmt.Sprintf(\"%s=%s\", filterBenchmarkFlag, benchFilter))\n+ }\n+ return args\n+}\n" }, { "change_type": "MODIFY", "old_path": "test/runner/main.go", "new_path": "test/runner/main.go", "diff": "@@ -43,6 +43,7 @@ import (\nvar (\ndebug = flag.Bool(\"debug\", false, \"enable debug logs\")\n+ oneSandbox = flag.Bool(\"one-sandbox\", false, \"run all test cases in one sandbox\")\nstrace = flag.Bool(\"strace\", false, \"enable strace logs\")\nplatform = flag.String(\"platform\", \"ptrace\", \"platform to run on\")\nplatformSupport = flag.String(\"platform-support\", \"\", \"String passed to the test as GVISOR_PLATFORM_SUPPORT environment variable. Used to determine which syscall tests are expected to work with the current platform.\")\n@@ -80,7 +81,7 @@ func getSetupContainerPath() string {\n}\n// runTestCaseNative runs the test case directly on the host machine.\n-func runTestCaseNative(testBin string, tc gtest.TestCase, t *testing.T) {\n+func runTestCaseNative(testBin string, tc *gtest.TestCase, args []string, t *testing.T) {\n// These tests might be running in parallel, so make sure they have a\n// unique test temp dir.\ntmpDir, err := ioutil.TempDir(testutil.TmpDir(), \"\")\n@@ -125,7 +126,11 @@ func runTestCaseNative(testBin string, tc gtest.TestCase, t *testing.T) {\nenv = append(env, fmt.Sprintf(\"%s=%s\", platformSupportEnvVar, *platformSupport))\n}\n- cmd := exec.Command(testBin, tc.Args()...)\n+ if args == nil {\n+ args = tc.Args()\n+ }\n+\n+ cmd := exec.Command(testBin, args...)\ncmd.Env = env\ncmd.Stdout = os.Stdout\ncmd.Stderr = os.Stderr\n@@ -169,7 +174,7 @@ func runTestCaseNative(testBin string, tc gtest.TestCase, t *testing.T) {\n// runsc logs will be saved to a path in TEST_UNDECLARED_OUTPUTS_DIR.\n//\n// Returns an error if the sandboxed application exits non-zero.\n-func runRunsc(tc gtest.TestCase, spec *specs.Spec) error {\n+func runRunsc(tc *gtest.TestCase, spec *specs.Spec) error {\nbundleDir, cleanup, err := testutil.SetupBundleDir(spec)\nif err != nil {\nreturn fmt.Errorf(\"SetupBundleDir failed: %v\", err)\n@@ -372,10 +377,13 @@ func setupUDSTree(spec *specs.Spec) (cleanup func(), err error) {\n}\n// runsTestCaseRunsc runs the test case in runsc.\n-func runTestCaseRunsc(testBin string, tc gtest.TestCase, t *testing.T) {\n+func runTestCaseRunsc(testBin string, tc *gtest.TestCase, args []string, t *testing.T) {\n// Run a new container with the test executable and filter for the\n// given test suite and name.\n- spec := testutil.NewSpecWithArgs(append([]string{testBin}, tc.Args()...)...)\n+ if args == nil {\n+ args = tc.Args()\n+ }\n+ spec := testutil.NewSpecWithArgs(append([]string{testBin}, args...)...)\n// Mark the root as writeable, as some tests attempt to\n// write to the rootfs, and expect EACCES, not EROFS.\n@@ -550,8 +558,28 @@ func main() {\nfatalf(\"Abs() failed: %v\", err)\n}\n- // Run the tests.\nvar tests []testing.InternalTest\n+ if *oneSandbox {\n+ tc := gtest.TestCase{\n+ Suite: \"main\",\n+ Name: \"test\",\n+ }\n+\n+ tests = append(tests, testing.InternalTest{\n+ Name: fmt.Sprintf(\"%s_%s\", tc.Suite, tc.Name),\n+ F: func(t *testing.T) {\n+ args := gtest.BuildTestArgs(indices, testCases)\n+ if *platform == \"native\" {\n+ // Run the test case on host.\n+ runTestCaseNative(testBin, &tc, args, t)\n+ } else {\n+ // Run the test case in runsc.\n+ runTestCaseRunsc(testBin, &tc, args, t)\n+ }\n+ },\n+ })\n+ } else {\n+ // Run the tests.\nfor _, tci := range indices {\n// Capture tc.\ntc := testCases[tci]\n@@ -560,14 +588,15 @@ func main() {\nF: func(t *testing.T) {\nif *platform == \"native\" {\n// Run the test case on host.\n- runTestCaseNative(testBin, tc, t)\n+ runTestCaseNative(testBin, &tc, nil, t)\n} else {\n// Run the test case in runsc.\n- runTestCaseRunsc(testBin, tc, t)\n+ runTestCaseRunsc(testBin, &tc, nil, t)\n}\n},\n})\n}\n+ }\ntesting.Main(matchString, tests, nil, nil)\n}\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/BUILD", "new_path": "test/syscalls/BUILD", "diff": "@@ -58,6 +58,7 @@ syscall_test(\n)\nsyscall_test(\n+ one_sandbox = False,\ntest = \"//test/syscalls/linux:cgroup_test\",\n)\n@@ -108,6 +109,7 @@ syscall_test(\nsyscall_test(\nadd_uds_tree = True,\n+ one_sandbox = False,\ntest = \"//test/syscalls/linux:connect_external_test\",\nuse_tmpfs = True,\n)\n@@ -449,6 +451,7 @@ syscall_test(\nsyscall_test(\ncontainer = True,\n+ one_sandbox = False,\ntest = \"//test/syscalls/linux:proc_isolated_test\",\n)\n@@ -675,6 +678,7 @@ syscall_test(\nsyscall_test(\nsize = \"large\",\ncontainer = True,\n+ one_sandbox = False,\nshard_count = most_shards,\ntest = \"//test/syscalls/linux:socket_inet_loopback_isolated_test\",\n)\n" } ]
Go
Apache License 2.0
google/gvisor
Don't run each test case in a separate sandbox This change was inspired by the Fabricio's change: 1b9d45dbe875 ("Run shards in a single sandbox") PiperOrigin-RevId: 480151140
259,868
10.10.2022 17:18:26
25,200
7de3c5af4a2e355088d2320bf19c4c72ac00fcd0
Add small tool to print distribution metric bucket sizes conveniently. Useful to search for decent bucket sizes interactively.
[ { "change_type": "ADD", "old_path": null, "new_path": "pkg/metric/buckettool/BUILD", "diff": "+load(\"//tools:defs.bzl\", \"go_binary\")\n+\n+package(licenses = [\"notice\"])\n+\n+go_binary(\n+ name = \"buckettool\",\n+ srcs = [\"buckettool.go\"],\n+ deps = [\n+ \"//pkg/log\",\n+ \"//pkg/metric\",\n+ \"//runsc/flag\",\n+ ],\n+)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/metric/buckettool/buckettool.go", "diff": "+// Copyright 2019 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+// buckettool prints buckets for distribution metrics.\n+package main\n+\n+import (\n+ \"fmt\"\n+ \"os\"\n+ \"time\"\n+\n+ \"gvisor.dev/gvisor/pkg/log\"\n+ \"gvisor.dev/gvisor/pkg/metric\"\n+ \"gvisor.dev/gvisor/runsc/flag\"\n+)\n+\n+var (\n+ typeFlag = flag.String(\"type\", \"duration\", \"Type of the bucketer: 'duration' or 'exponential'\")\n+ numFiniteBucketsFlag = flag.Int(\"num_finite_buckets\", 8, \"Number of finite buckets\")\n+ minDurationFlag = flag.Duration(\"min_duration\", 5*time.Millisecond, \"For -type=duration: Minimum duration\")\n+ maxDurationFlag = flag.Duration(\"max_duration\", 10*time.Minute, \"For -type=duration: Maximum duration\")\n+ widthFlag = flag.Uint64(\"exponential_width\", 5, \"For -type=exponential: Initial bucket width\")\n+ scaleFlag = flag.Float64(\"exponential_scale\", 10, \"For -type=exponential: Scaling factor\")\n+ growthFlag = flag.Float64(\"exponential_growth\", 4, \"For -type=exponential: Exponential growth factor\")\n+)\n+\n+func exitf(format string, values ...any) {\n+ log.Warningf(format, values...)\n+ os.Exit(1)\n+}\n+\n+func main() {\n+ flag.Parse()\n+ var bucketer metric.Bucketer\n+ var formatVal func(int64) string\n+ switch *typeFlag {\n+ case \"duration\":\n+ bucketer = metric.NewDurationBucketer(*numFiniteBucketsFlag, *minDurationFlag, *maxDurationFlag)\n+ formatVal = func(val int64) string {\n+ return time.Duration(val).String()\n+ }\n+ case \"exponential\":\n+ bucketer = metric.NewExponentialBucketer(*numFiniteBucketsFlag, *widthFlag, *scaleFlag, *growthFlag)\n+ formatVal = func(val int64) string {\n+ return fmt.Sprintf(\"%v\", val)\n+ }\n+ default:\n+ exitf(\"Invalid -type: %s\", *typeFlag)\n+ }\n+ fmt.Printf(\"Number of finite buckets: %d\\n\", bucketer.NumFiniteBuckets())\n+ fmt.Printf(\"Number of total buckets: %d\\n\", bucketer.NumFiniteBuckets()+2)\n+ fmt.Printf(\"> Underflow bucket: (-inf; %s)\\n\", formatVal(bucketer.LowerBound(0)))\n+ for b := 0; b < bucketer.NumFiniteBuckets(); b++ {\n+ fmt.Printf(\"> Bucket index %d: [%s, %s). (Middle: %s)\\n\", b, formatVal(bucketer.LowerBound(b)), formatVal(bucketer.LowerBound(b+1)), formatVal((bucketer.LowerBound(b)+bucketer.LowerBound(b+1))/2))\n+ }\n+ fmt.Printf(\"> Overflow bucket: [%s; +inf)\\n\", formatVal(bucketer.LowerBound(bucketer.NumFiniteBuckets())))\n+}\n" }, { "change_type": "MODIFY", "old_path": "runsc/flag/flag.go", "new_path": "runsc/flag/flag.go", "diff": "@@ -29,6 +29,8 @@ type FlagSet = flag.FlagSet\nvar (\nBool = flag.Bool\nCommandLine = flag.CommandLine\n+ Duration = flag.Duration\n+ Float64 = flag.Float64\nInt = flag.Int\nInt64 = flag.Int64\nNewFlagSet = flag.NewFlagSet\n@@ -36,6 +38,7 @@ var (\nString = flag.String\nStringVar = flag.StringVar\nUint = flag.Uint\n+ Uint64 = flag.Uint64\nVar = flag.Var\n)\n" } ]
Go
Apache License 2.0
google/gvisor
Add small tool to print distribution metric bucket sizes conveniently. Useful to search for decent bucket sizes interactively. PiperOrigin-RevId: 480214658
259,868
11.10.2022 12:11:54
25,200
0e9ef844eb455fc60114e0eb5ce0c46404461c7b
Separate Containerd 1.4.3 tests in cgroupv1/cgroupv2 variants.
[ { "change_type": "MODIFY", "old_path": ".buildkite/pipeline.yaml", "new_path": ".buildkite/pipeline.yaml", "diff": "@@ -289,7 +289,7 @@ steps:\n<<: *ubuntu_agents\narch: \"amd64\"\n- <<: *common\n- label: \":docker: Containerd 1.3.9 tests\"\n+ label: \":docker: Containerd 1.3.9 tests (cgroupv1)\"\ncommand: make containerd-test-1.3.9\nagents:\n<<: *platform_specific_agents\n@@ -297,11 +297,21 @@ steps:\ncgroup: \"v1\"\narch: \"amd64\"\n- <<: *common\n- label: \":docker: Containerd 1.4.3 tests\"\n+ label: \":docker: Containerd 1.4.3 tests (cgroupv1)\"\ncommand: make containerd-test-1.4.3\nagents:\n<<: *platform_specific_agents\n<<: *ubuntu_agents\n+ cgroup: \"v1\"\n+ - <<: *common\n+ # See above: not truly a source test.\n+ <<: *source_test\n+ label: \":docker: Containerd 1.4.3 tests (cgroupv2)\"\n+ command: make containerd-test-1.4.3\n+ agents:\n+ <<: *platform_specific_agents\n+ <<: *ubuntu_agents\n+ cgroup: \"v2\"\n- <<: *common\nlabel: \":docker: Containerd 1.5.4 tests (cgroupv1)\"\ncommand: make containerd-test-1.5.4\n" } ]
Go
Apache License 2.0
google/gvisor
Separate Containerd 1.4.3 tests in cgroupv1/cgroupv2 variants. PiperOrigin-RevId: 480421275
259,885
11.10.2022 12:27:24
25,200
2e844f74fcdd01d94e7d74c96b4ae8fd1137cd1d
Do not use ktime.Timer for CPU clock ticks.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/BUILD", "new_path": "pkg/sentry/kernel/BUILD", "diff": "@@ -4,6 +4,13 @@ load(\"//pkg/sync/locking:locking.bzl\", \"declare_mutex\", \"declare_rwmutex\")\npackage(licenses = [\"notice\"])\n+declare_mutex(\n+ name = \"cpu_clock_mutex\",\n+ out = \"cpu_clock_mutex.go\",\n+ package = \"kernel\",\n+ prefix = \"cpuClock\",\n+)\n+\ndeclare_mutex(\nname = \"user_counters_mutex\",\nout = \"user_counters_mutex.go\",\n@@ -201,6 +208,7 @@ go_library(\n\"cgroup.go\",\n\"cgroup_mutex.go\",\n\"context.go\",\n+ \"cpu_clock_mutex.go\",\n\"fd_table.go\",\n\"fd_table_mutex.go\",\n\"fd_table_refs.go\",\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/kernel.go", "new_path": "pkg/sentry/kernel/kernel.go", "diff": "//\n// Kernel.extMu\n// ThreadGroup.timerMu\n-// ktime.Timer.mu (for kernelCPUClockTicker and IntervalTimer)\n+// ktime.Timer.mu (for IntervalTimer) and Kernel.cpuClockMu\n// TaskSet.mu\n// SignalHandlers.mu\n// Task.mu\n@@ -183,12 +183,6 @@ type Kernel struct {\n// syslog is the kernel log.\nsyslog syslog\n- // runningTasksMu synchronizes disable/enable of cpuClockTicker when\n- // the kernel is idle (runningTasks == 0).\n- //\n- // runningTasksMu is used to exclude critical sections when the timer\n- // disables itself and when the first active task enables the timer,\n- // ensuring that tasks always see a valid cpuClock value.\nrunningTasksMu runningTasksMutex `state:\"nosave\"`\n// runningTasks is the total count of tasks currently in\n@@ -199,36 +193,46 @@ type Kernel struct {\n// further protected by runningTasksMu (see incRunningTasks).\nrunningTasks atomicbitops.Int64\n- // cpuClock is incremented every linux.ClockTick. cpuClock is used to\n- // measure task CPU usage, since sampling monotonicClock twice on every\n- // syscall turns out to be unreasonably expensive. This is similar to how\n- // Linux does task CPU accounting on x86 (CONFIG_IRQ_TIME_ACCOUNTING),\n- // although Linux also uses scheduler timing information to improve\n- // resolution (kernel/sched/cputime.c:cputime_adjust()), which we can't do\n- // since \"preeemptive\" scheduling is managed by the Go runtime, which\n- // doesn't provide this information.\n+ // runningTasksCond is signaled when runningTasks is incremented from 0 to 1.\n+ //\n+ // Invariant: runningTasksCond.L == &runningTasksMu.\n+ runningTasksCond sync.Cond `state:\"nosave\"`\n+\n+ // cpuClock is incremented every linux.ClockTick by a goroutine running\n+ // kernel.runCPUClockTicker() while runningTasks != 0.\n+ //\n+ // cpuClock is used to measure task CPU usage, since sampling monotonicClock\n+ // twice on every syscall turns out to be unreasonably expensive. This is\n+ // similar to how Linux does task CPU accounting on x86\n+ // (CONFIG_IRQ_TIME_ACCOUNTING), although Linux also uses scheduler timing\n+ // information to improve resolution\n+ // (kernel/sched/cputime.c:cputime_adjust()), which we can't do since\n+ // \"preeemptive\" scheduling is managed by the Go runtime, which doesn't\n+ // provide this information.\n//\n// cpuClock is mutable, and is accessed using atomic memory operations.\ncpuClock atomicbitops.Uint64\n- // cpuClockTicker increments cpuClock.\n- cpuClockTicker *ktime.Timer `state:\"nosave\"`\n+ // cpuClockMu is used to make increments of cpuClock, and updates of timers\n+ // based on cpuClock, atomic.\n+ cpuClockMu cpuClockMutex `state:\"nosave\"`\n- // cpuClockTickerDisabled indicates that cpuClockTicker has been\n- // disabled because no tasks are running.\n+ // cpuClockTickerRunning is true if the goroutine that increments cpuClock is\n+ // running and false if it is blocked in runningTasksCond.Wait() or if it\n+ // never started.\n//\n- // cpuClockTickerDisabled is protected by runningTasksMu.\n- cpuClockTickerDisabled bool\n+ // cpuClockTickerRunning is protected by runningTasksMu.\n+ cpuClockTickerRunning bool\n- // cpuClockTickerSetting is the ktime.Setting of cpuClockTicker at the\n- // point it was disabled. It is cached here to avoid a lock ordering\n- // violation with cpuClockTicker.mu when runningTaskMu is held.\n- //\n- // cpuClockTickerSetting is only valid when cpuClockTickerDisabled is\n- // true.\n+ // cpuClockTickerWakeCh is sent to to wake the goroutine that increments\n+ // cpuClock if it's sleeping between ticks.\n+ cpuClockTickerWakeCh chan struct{} `state:\"nosave\"`\n+\n+ // cpuClockTickerStopCond is broadcast when cpuClockTickerRunning transitions\n+ // from true to false.\n//\n- // cpuClockTickerSetting is protected by runningTasksMu.\n- cpuClockTickerSetting ktime.Setting\n+ // Invariant: cpuClockTickerStopCond.L == &runningTasksMu.\n+ cpuClockTickerStopCond sync.Cond `state:\"nosave\"`\n// uniqueID is used to generate unique identifiers.\n//\n@@ -411,6 +415,9 @@ func (k *Kernel) Init(args InitKernelArgs) error {\nif k.rootNetworkNamespace == nil {\nk.rootNetworkNamespace = inet.NewRootNamespace(nil, nil)\n}\n+ k.runningTasksCond.L = &k.runningTasksMu\n+ k.cpuClockTickerWakeCh = make(chan struct{}, 1)\n+ k.cpuClockTickerStopCond.L = &k.runningTasksMu\nk.applicationCores = args.ApplicationCores\nif args.UseHostCores {\nk.useHostCores = true\n@@ -680,6 +687,10 @@ func (k *Kernel) invalidateUnsavableMappings(ctx context.Context) error {\nfunc (k *Kernel) LoadFrom(ctx context.Context, r wire.Reader, timeReady chan struct{}, net inet.Stack, clocks sentrytime.Clocks, vfsOpts *vfs.CompleteRestoreOptions) error {\nloadStart := time.Now()\n+ k.runningTasksCond.L = &k.runningTasksMu\n+ k.cpuClockTickerWakeCh = make(chan struct{}, 1)\n+ k.cpuClockTickerStopCond.L = &k.runningTasksMu\n+\ninitAppCores := k.applicationCores\n// Load the pre-saved CPUID FeatureSet.\n@@ -1119,11 +1130,10 @@ func (k *Kernel) Start() error {\n}\nk.started = true\n- k.cpuClockTicker = ktime.NewTimer(k.timekeeper.monotonicClock, newKernelCPUClockTicker(k))\n- k.cpuClockTicker.Swap(ktime.Setting{\n- Enabled: true,\n- Period: linux.ClockTick,\n- })\n+ k.runningTasksMu.Lock()\n+ k.cpuClockTickerRunning = true\n+ k.runningTasksMu.Unlock()\n+ go k.runCPUClockTicker()\n// If k was created by LoadKernelFrom, timers were stopped during\n// Kernel.SaveTo and need to be resumed. If k was created by NewKernel,\n// this is a no-op.\n@@ -1150,11 +1160,18 @@ func (k *Kernel) Start() error {\n// - Any task goroutines running in k must be stopped.\n// - k.extMu must be locked.\nfunc (k *Kernel) pauseTimeLocked(ctx context.Context) {\n- // k.cpuClockTicker may be nil since Kernel.SaveTo() may be called before\n- // Kernel.Start().\n- if k.cpuClockTicker != nil {\n- k.cpuClockTicker.Pause()\n+ // Since all task goroutines have been stopped by precondition, the CPU clock\n+ // ticker should stop on its own; wait for it to do so, waking it up from\n+ // sleeping betwen ticks if necessary.\n+ k.runningTasksMu.Lock()\n+ for k.cpuClockTickerRunning {\n+ select {\n+ case k.cpuClockTickerWakeCh <- struct{}{}:\n+ default:\n}\n+ k.cpuClockTickerStopCond.Wait()\n+ }\n+ k.runningTasksMu.Unlock()\n// By precondition, nothing else can be interacting with PIDNamespace.tids\n// or FDTable.files, so we can iterate them without synchronization. (We\n@@ -1195,9 +1212,8 @@ func (k *Kernel) pauseTimeLocked(ctx context.Context) {\n// - Any task goroutines running in k must be stopped.\n// - k.extMu must be locked.\nfunc (k *Kernel) resumeTimeLocked(ctx context.Context) {\n- if k.cpuClockTicker != nil {\n- k.cpuClockTicker.Resume()\n- }\n+ // The CPU clock ticker will automatically resume as task goroutines resume\n+ // execution.\nk.timekeeper.ResumeUpdates()\nfor t := range k.tasks.Root.tids {\n@@ -1236,75 +1252,12 @@ func (k *Kernel) incRunningTasks() {\n// Transition from 0 -> 1. Synchronize with other transitions and timer.\nk.runningTasksMu.Lock()\n- tasks = k.runningTasks.Load()\n- if tasks != 0 {\n- // We're no longer the first task, no need to\n- // re-enable.\n- k.runningTasks.Add(1)\n- k.runningTasksMu.Unlock()\n- return\n+ if k.runningTasks.Add(1) == 1 {\n+ k.runningTasksCond.Signal()\n}\n-\n- if !k.cpuClockTickerDisabled {\n- // Timer was never disabled.\n- k.runningTasks.Store(1)\nk.runningTasksMu.Unlock()\nreturn\n}\n-\n- // We need to update cpuClock for all of the ticks missed while we\n- // slept, and then re-enable the timer.\n- //\n- // The Notify in Swap isn't sufficient. kernelCPUClockTicker.Notify\n- // always increments cpuClock by 1 regardless of the number of\n- // expirations as a heuristic to avoid over-accounting in cases of CPU\n- // throttling.\n- //\n- // We want to cover the normal case, when all time should be accounted,\n- // so we increment for all expirations. Throttling is less concerning\n- // here because the ticker is only disabled from Notify. This means\n- // that Notify must schedule and compensate for the throttled period\n- // before the timer is disabled. Throttling while the timer is disabled\n- // doesn't matter, as nothing is running or reading cpuClock anyways.\n- //\n- // S/R also adds complication, as there are two cases. Recall that\n- // monotonicClock will jump forward on restore.\n- //\n- // 1. If the ticker is enabled during save, then on Restore Notify is\n- // called with many expirations, covering the time jump, but cpuClock\n- // is only incremented by 1.\n- //\n- // 2. If the ticker is disabled during save, then after Restore the\n- // first wakeup will call this function and cpuClock will be\n- // incremented by the number of expirations across the S/R.\n- //\n- // These cause very different value of cpuClock. But again, since\n- // nothing was running while the ticker was disabled, those differences\n- // don't matter.\n- setting, exp := k.cpuClockTickerSetting.At(k.timekeeper.monotonicClock.Now())\n- if exp > 0 {\n- k.cpuClock.Add(exp)\n- }\n-\n- // Now that cpuClock is updated it is safe to allow other tasks to\n- // transition to running.\n- k.runningTasks.Store(1)\n-\n- // N.B. we must unlock before calling Swap to maintain lock ordering.\n- //\n- // cpuClockTickerDisabled need not wait until after Swap to become\n- // true. It is sufficient that the timer *will* be enabled.\n- k.cpuClockTickerDisabled = false\n- k.runningTasksMu.Unlock()\n-\n- // This won't call Notify (unless it's been ClockTick since setting.At\n- // above). This means we skip the thread group work in Notify. However,\n- // since nothing was running while we were disabled, none of the timers\n- // could have expired.\n- k.cpuClockTicker.Swap(setting)\n-\n- return\n- }\n}\nfunc (k *Kernel) decRunningTasks() {\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/task_acct.go", "new_path": "pkg/sentry/kernel/task_acct.go", "diff": "@@ -68,42 +68,32 @@ func (t *Task) Setitimer(id int32, newitv linux.ItimerVal) (linux.ItimerVal, err\ntm, olds = t.tg.itimerRealTimer.Swap(news)\ncase linux.ITIMER_VIRTUAL:\nc := t.tg.UserCPUClock()\n- var err error\n- t.k.cpuClockTicker.Atomically(func() {\n+ t.k.cpuClockMu.Lock()\n+ defer t.k.cpuClockMu.Unlock()\ntm = c.Now()\n- var news ktime.Setting\n- news, err = ktime.SettingFromSpecAt(newitv.Value.ToDuration(), newitv.Interval.ToDuration(), tm)\n+ news, err := ktime.SettingFromSpecAt(newitv.Value.ToDuration(), newitv.Interval.ToDuration(), tm)\nif err != nil {\n- return\n+ return linux.ItimerVal{}, err\n}\nt.tg.signalHandlers.mu.Lock()\nolds = t.tg.itimerVirtSetting\nt.tg.itimerVirtSetting = news\nt.tg.updateCPUTimersEnabledLocked()\nt.tg.signalHandlers.mu.Unlock()\n- })\n- if err != nil {\n- return linux.ItimerVal{}, err\n- }\ncase linux.ITIMER_PROF:\nc := t.tg.CPUClock()\n- var err error\n- t.k.cpuClockTicker.Atomically(func() {\n+ t.k.cpuClockMu.Lock()\n+ defer t.k.cpuClockMu.Unlock()\ntm = c.Now()\n- var news ktime.Setting\n- news, err = ktime.SettingFromSpecAt(newitv.Value.ToDuration(), newitv.Interval.ToDuration(), tm)\n+ news, err := ktime.SettingFromSpecAt(newitv.Value.ToDuration(), newitv.Interval.ToDuration(), tm)\nif err != nil {\n- return\n+ return linux.ItimerVal{}, err\n}\nt.tg.signalHandlers.mu.Lock()\nolds = t.tg.itimerProfSetting\nt.tg.itimerProfSetting = news\nt.tg.updateCPUTimersEnabledLocked()\nt.tg.signalHandlers.mu.Unlock()\n- })\n- if err != nil {\n- return linux.ItimerVal{}, err\n- }\ndefault:\nreturn linux.ItimerVal{}, linuxerr.EINVAL\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/task_sched.go", "new_path": "pkg/sentry/kernel/task_sched.go", "diff": "@@ -335,43 +335,57 @@ func (tg *ThreadGroup) CPUClock() ktime.Clock {\nreturn &tgClock{tg: tg, includeSys: true}\n}\n-type kernelCPUClockTicker struct {\n- k *Kernel\n-\n- // These are essentially kernelCPUClockTicker.Notify local variables that\n- // are cached between calls to reduce allocations.\n- rng *rand.Rand\n- tgs []*ThreadGroup\n-}\n-\n-func newKernelCPUClockTicker(k *Kernel) *kernelCPUClockTicker {\n- return &kernelCPUClockTicker{\n- k: k,\n- rng: rand.New(rand.NewSource(rand.Int63())),\n- }\n+func (k *Kernel) runCPUClockTicker() {\n+ tickTimer := time.NewTimer(linux.ClockTick)\n+ rng := rand.New(rand.NewSource(rand.Int63()))\n+ var tgs []*ThreadGroup\n+\n+ for {\n+ // Wait for the next CPU clock tick.\n+ wokenEarly := false\n+ select {\n+ case <-tickTimer.C:\n+ tickTimer.Reset(linux.ClockTick)\n+ case <-k.cpuClockTickerWakeCh:\n+ // Wake up to check if we need to stop with cpuClockTickerRunning =\n+ // false, but then continue waiting for the next CPU clock tick.\n+ wokenEarly = true\n+ }\n+\n+ // Stop the CPU clock while nothing is running.\n+ if k.runningTasks.Load() == 0 {\n+ k.runningTasksMu.Lock()\n+ if k.runningTasks.Load() == 0 {\n+ k.cpuClockTickerRunning = false\n+ k.cpuClockTickerStopCond.Broadcast()\n+ for k.runningTasks.Load() == 0 {\n+ k.runningTasksCond.Wait()\n+ }\n+ k.cpuClockTickerRunning = true\n+ }\n+ k.runningTasksMu.Unlock()\n+ }\n+\n+ if wokenEarly {\n+ continue\n}\n-// NotifyTimer implements ktime.TimerListener.NotifyTimer.\n-func (ticker *kernelCPUClockTicker) NotifyTimer(exp uint64, setting ktime.Setting) (ktime.Setting, bool) {\n- // Only increment cpuClock by 1 regardless of the number of expirations.\n- // This approximately compensates for cases where thread throttling or bad\n- // Go runtime scheduling prevents the kernelCPUClockTicker goroutine, and\n- // presumably task goroutines as well, from executing for a long period of\n- // time. It's also necessary to prevent CPU clocks from seeing large\n- // discontinuous jumps.\n- now := ticker.k.cpuClock.Add(1)\n+ // Advance the CPU clock, and timers based on the CPU clock, atomically\n+ // under cpuClockMu.\n+ k.cpuClockMu.Lock()\n+ now := k.cpuClock.Add(1)\n// Check thread group CPU timers.\n- tgs := ticker.k.tasks.Root.ThreadGroupsAppend(ticker.tgs)\n+ tgs = k.tasks.Root.ThreadGroupsAppend(tgs)\nfor _, tg := range tgs {\nif tg.cpuTimersEnabled.Load() == 0 {\ncontinue\n}\n- ticker.k.tasks.mu.RLock()\n+ k.tasks.mu.RLock()\nif tg.leader == nil {\n// No tasks have ever run in this thread group.\n- ticker.k.tasks.mu.RUnlock()\n+ k.tasks.mu.RUnlock()\ncontinue\n}\n// Accumulate thread group CPU stats, and randomly select running tasks\n@@ -391,14 +405,14 @@ func (ticker *kernelCPUClockTicker) NotifyTimer(exp uint64, setting ktime.Settin\n// Considered by ITIMER_VIRT, ITIMER_PROF, and RLIMIT_CPU\n// timers.\nnrVirtCandidates++\n- if int(randInt31n(ticker.rng, int32(nrVirtCandidates))) == 0 {\n+ if int(randInt31n(rng, int32(nrVirtCandidates))) == 0 {\nvirtReceiver = t\n}\nfallthrough\ncase TaskGoroutineRunningSys:\n// Considered by ITIMER_PROF and RLIMIT_CPU timers.\nnrProfCandidates++\n- if int(randInt31n(ticker.rng, int32(nrProfCandidates))) == 0 {\n+ if int(randInt31n(rng, int32(nrProfCandidates))) == 0 {\nprofReceiver = t\n}\n}\n@@ -440,35 +454,17 @@ func (ticker *kernelCPUClockTicker) NotifyTimer(exp uint64, setting ktime.Settin\n}\ntg.signalHandlers.mu.Unlock()\n- ticker.k.tasks.mu.RUnlock()\n+ k.tasks.mu.RUnlock()\n}\n+ k.cpuClockMu.Unlock()\n+\n// Retain tgs between calls to Notify to reduce allocations.\nfor i := range tgs {\ntgs[i] = nil\n}\n- ticker.tgs = tgs[:0]\n-\n- // If nothing is running, we can disable the timer.\n- tasks := ticker.k.runningTasks.Load()\n- if tasks == 0 {\n- ticker.k.runningTasksMu.Lock()\n- defer ticker.k.runningTasksMu.Unlock()\n- tasks := ticker.k.runningTasks.Load()\n- if tasks != 0 {\n- // Raced with a 0 -> 1 transition.\n- return setting, false\n+ tgs = tgs[:0]\n}\n-\n- // Stop the timer. We must cache the current setting so the\n- // kernel can access it without violating the lock order.\n- ticker.k.cpuClockTickerSetting = setting\n- ticker.k.cpuClockTickerDisabled = true\n- setting.Enabled = false\n- return setting, true\n- }\n-\n- return setting, false\n}\n// randInt31n returns a random integer in [0, n).\n@@ -494,7 +490,8 @@ func randInt31n(rng *rand.Rand, n int32) int32 {\n//\n// Preconditions: The caller must be running on the task goroutine.\nfunc (t *Task) NotifyRlimitCPUUpdated() {\n- t.k.cpuClockTicker.Atomically(func() {\n+ t.k.cpuClockMu.Lock()\n+ defer t.k.cpuClockMu.Unlock()\nt.tg.pidns.owner.mu.RLock()\ndefer t.tg.pidns.owner.mu.RUnlock()\nt.tg.signalHandlers.mu.Lock()\n@@ -514,7 +511,6 @@ func (t *Task) NotifyRlimitCPUUpdated() {\n}\n}\nt.tg.updateCPUTimersEnabledLocked()\n- })\n}\n// Preconditions: The signal mutex must be locked.\n" } ]
Go
Apache License 2.0
google/gvisor
Do not use ktime.Timer for CPU clock ticks. PiperOrigin-RevId: 480424573
259,992
11.10.2022 16:07:47
25,200
7bb273341ee026d49e144b987b22ef561448bee3
Add flag to filter debug logs This allows for only a subset of commands to be logged to reduce the amount of logging generated. Updates
[ { "change_type": "MODIFY", "old_path": "runsc/cli/main.go", "new_path": "runsc/cli/main.go", "diff": "@@ -147,8 +147,10 @@ func Main(version string) {\n// propagate it to child processes.\nrefs.SetLeakMode(conf.ReferenceLeak)\n+ subcommand := flag.CommandLine.Arg(0)\n+\n// Set up logging.\n- if conf.Debug {\n+ if conf.Debug && specutils.IsDebugCommand(conf, subcommand) {\nlog.SetLevel(log.Debug)\n}\n@@ -164,15 +166,13 @@ func Main(version string) {\n// case that does not occur.\n_ = time.Local.String()\n- subcommand := flag.CommandLine.Arg(0)\n-\nvar e log.Emitter\nif *debugLogFD > -1 {\nf := os.NewFile(uintptr(*debugLogFD), \"debug log file\")\ne = newEmitter(conf.DebugLogFormat, f)\n- } else if conf.DebugLog != \"\" {\n+ } else if len(conf.DebugLog) > 0 && specutils.IsDebugCommand(conf, subcommand) {\nf, err := specutils.DebugLogFile(conf.DebugLog, subcommand, \"\" /* name */)\nif err != nil {\nutil.Fatalf(\"error opening debug log file in %q: %v\", conf.DebugLog, err)\n" }, { "change_type": "MODIFY", "old_path": "runsc/config/config.go", "new_path": "runsc/config/config.go", "diff": "@@ -53,6 +53,11 @@ type Config struct {\n// DebugLog is the path to log debug information to, if not empty.\nDebugLog string `flag:\"debug-log\"`\n+ // DebugCommand is a comma-separated list of commands to be debugged if\n+ // --debug-log is also set. Empty means debug all. \"!\" negates the expression.\n+ // E.g. \"create,start\" or \"!boot,events\".\n+ DebugCommand string `flag:\"debug-command\"`\n+\n// PanicLog is the path to log GO's runtime messages, if not empty.\nPanicLog string `flag:\"panic-log\"`\n" }, { "change_type": "MODIFY", "old_path": "runsc/config/flags.go", "new_path": "runsc/config/flags.go", "diff": "@@ -41,6 +41,7 @@ func RegisterFlags(flagSet *flag.FlagSet) {\n// Debugging flags.\nflagSet.String(\"debug-log\", \"\", \"additional location for logs. If it ends with '/', log files are created inside the directory with default names. The following variables are available: %TIMESTAMP%, %COMMAND%.\")\n+ flagSet.String(\"debug-command\", \"\", `comma-separated list of commands to be debugged if --debug-log is also set. Empty means debug all. \"!\" negates the expression. E.g. \"create,start\" or \"!boot,events\"`)\nflagSet.String(\"panic-log\", \"\", \"file path where panic reports and other Go's runtime messages are written.\")\nflagSet.String(\"coverage-report\", \"\", \"file path where Go coverage reports are written. Reports will only be generated if runsc is built with --collect_code_coverage and --instrumentation_filter Bazel flags.\")\nflagSet.Bool(\"log-packets\", false, \"enable network packet logging.\")\n" }, { "change_type": "MODIFY", "old_path": "runsc/container/container.go", "new_path": "runsc/container/container.go", "diff": "@@ -871,10 +871,12 @@ func (c *Container) createGoferProcess(spec *specs.Spec, conf *config.Config, bu\ntest = t\n}\n}\n+ if specutils.IsDebugCommand(conf, \"gofer\") {\nif err := donations.DonateDebugLogFile(\"debug-log-fd\", conf.DebugLog, \"gofer\", test); err != nil {\nreturn nil, nil, err\n}\n}\n+ }\n// Start with the general config flags.\ncmd := exec.Command(specutils.ExePath, conf.ToFlags()...)\n" }, { "change_type": "MODIFY", "old_path": "runsc/sandbox/sandbox.go", "new_path": "runsc/sandbox/sandbox.go", "diff": "@@ -550,9 +550,11 @@ func (s *Sandbox) createSandboxProcess(conf *config.Config, args *Args, startSyn\ntest = t\n}\n}\n+ if specutils.IsDebugCommand(conf, \"boot\") {\nif err := donations.DonateDebugLogFile(\"debug-log-fd\", conf.DebugLog, \"boot\", test); err != nil {\nreturn err\n}\n+ }\nif err := donations.DonateDebugLogFile(\"panic-log-fd\", conf.PanicLog, \"panic\", test); err != nil {\nreturn err\n}\n" }, { "change_type": "MODIFY", "old_path": "runsc/specutils/specutils.go", "new_path": "runsc/specutils/specutils.go", "diff": "@@ -412,6 +412,28 @@ func DebugLogFile(logPattern, command, test string) (*os.File, error) {\nreturn os.OpenFile(logPattern, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0664)\n}\n+// IsDebugCommand returns true if the command should be debugged or not, based\n+// on the current configuration.\n+func IsDebugCommand(conf *config.Config, command string) bool {\n+ if len(conf.DebugCommand) == 0 {\n+ // Debug everything by default.\n+ return true\n+ }\n+ filter := conf.DebugCommand\n+ rv := true\n+ if filter[0] == '!' {\n+ // Negate the match, e.g. !boot should log all, but \"boot\".\n+ filter = filter[1:]\n+ rv = false\n+ }\n+ for _, cmd := range strings.Split(filter, \",\") {\n+ if cmd == command {\n+ return rv\n+ }\n+ }\n+ return !rv\n+}\n+\n// SafeSetupAndMount creates the mount point and calls Mount with the given\n// flags. procPath is the path to procfs. If it is \"\", procfs is assumed to be\n// mounted at /proc.\n" } ]
Go
Apache License 2.0
google/gvisor
Add flag to filter debug logs This allows for only a subset of commands to be logged to reduce the amount of logging generated. Updates #7999 PiperOrigin-RevId: 480476369
259,891
11.10.2022 20:24:48
25,200
607fdc536d9a1c9373484fbe663dce99d369bf8a
DecRef ptr niling
[ { "change_type": "MODIFY", "old_path": "nogo.yaml", "new_path": "nogo.yaml", "diff": "@@ -218,7 +218,3 @@ analyzers:\nsuppress:\n- \"comment on exported type Translation\" # Intentional.\n- \"comment on exported type PinnedRange\" # Intentional.\n- ST1016: # CheckReceiverNamesIdentical\n- internal:\n- exclude:\n- - pkg/tcpip/stack/packet_buffer.go # TODO(b/233086175): Remove.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/link/channel/channel.go", "new_path": "pkg/tcpip/link/channel/channel.go", "diff": "@@ -63,7 +63,7 @@ func (q *queue) Read() stack.PacketBufferPtr {\ncase p := <-q.c:\nreturn p\ndefault:\n- return nil\n+ return stack.PacketBufferPtr{}\n}\n}\n@@ -72,7 +72,7 @@ func (q *queue) ReadContext(ctx context.Context) stack.PacketBufferPtr {\ncase pkt := <-q.c:\nreturn pkt\ncase <-ctx.Done():\n- return nil\n+ return stack.PacketBufferPtr{}\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/link/qdisc/fifo/packet_buffer_circular_list.go", "new_path": "pkg/tcpip/link/qdisc/fifo/packet_buffer_circular_list.go", "diff": "@@ -71,10 +71,10 @@ func (pl *packetBufferCircularList) pushBack(pb stack.PacketBufferPtr) {\n//go:nosplit\nfunc (pl *packetBufferCircularList) removeFront() stack.PacketBufferPtr {\nif pl.isEmpty() {\n- return nil\n+ return stack.PacketBufferPtr{}\n}\nret := pl.pbs[pl.head]\n- pl.pbs[pl.head] = nil\n+ pl.pbs[pl.head] = stack.PacketBufferPtr{}\npl.head = (pl.head + 1) % len(pl.pbs)\npl.size--\nreturn ret\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/link/qdisc/fifo/qdisc_test.go", "new_path": "pkg/tcpip/link/qdisc/fifo/qdisc_test.go", "diff": "@@ -84,7 +84,7 @@ func TestWriteRefusedAfterClosed(t *testing.T) {\nlinkEp := fifo.New(nil, 1, 2)\nlinkEp.Close()\n- err := linkEp.WritePacket(nil)\n+ err := linkEp.WritePacket(stack.PacketBufferPtr{})\n_, ok := err.(*tcpip.ErrClosedForSend)\nif !ok {\nt.Errorf(\"got err = %s, want %s\", err, &tcpip.ErrClosedForSend{})\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/internal/fragmentation/fragmentation.go", "new_path": "pkg/tcpip/network/internal/fragmentation/fragmentation.go", "diff": "@@ -158,25 +158,25 @@ func (f *Fragmentation) Process(\nid FragmentID, first, last uint16, more bool, proto uint8, pkt stack.PacketBufferPtr) (\nstack.PacketBufferPtr, uint8, bool, error) {\nif first > last {\n- return nil, 0, false, fmt.Errorf(\"first=%d is greater than last=%d: %w\", first, last, ErrInvalidArgs)\n+ return stack.PacketBufferPtr{}, 0, false, fmt.Errorf(\"first=%d is greater than last=%d: %w\", first, last, ErrInvalidArgs)\n}\nif first%f.blockSize != 0 {\n- return nil, 0, false, fmt.Errorf(\"first=%d is not a multiple of block size=%d: %w\", first, f.blockSize, ErrInvalidArgs)\n+ return stack.PacketBufferPtr{}, 0, false, fmt.Errorf(\"first=%d is not a multiple of block size=%d: %w\", first, f.blockSize, ErrInvalidArgs)\n}\nfragmentSize := last - first + 1\nif more && fragmentSize%f.blockSize != 0 {\n- return nil, 0, false, fmt.Errorf(\"fragment size=%d bytes is not a multiple of block size=%d on non-final fragment: %w\", fragmentSize, f.blockSize, ErrInvalidArgs)\n+ return stack.PacketBufferPtr{}, 0, false, fmt.Errorf(\"fragment size=%d bytes is not a multiple of block size=%d on non-final fragment: %w\", fragmentSize, f.blockSize, ErrInvalidArgs)\n}\nif l := pkt.Data().Size(); l != int(fragmentSize) {\n- return nil, 0, false, fmt.Errorf(\"got fragment size=%d bytes not equal to the expected fragment size=%d bytes (first=%d last=%d): %w\", l, fragmentSize, first, last, ErrInvalidArgs)\n+ return stack.PacketBufferPtr{}, 0, false, fmt.Errorf(\"got fragment size=%d bytes not equal to the expected fragment size=%d bytes (first=%d last=%d): %w\", l, fragmentSize, first, last, ErrInvalidArgs)\n}\nf.mu.Lock()\nif f.reassemblers == nil {\n- return nil, 0, false, fmt.Errorf(\"Release() called before fragmentation processing could finish\")\n+ return stack.PacketBufferPtr{}, 0, false, fmt.Errorf(\"Release() called before fragmentation processing could finish\")\n}\nr, ok := f.reassemblers[id]\n@@ -201,7 +201,7 @@ func (f *Fragmentation) Process(\nf.mu.Lock()\nf.release(r, false /* timedOut */)\nf.mu.Unlock()\n- return nil, 0, false, fmt.Errorf(\"fragmentation processing error: %w\", err)\n+ return stack.PacketBufferPtr{}, 0, false, fmt.Errorf(\"fragmentation processing error: %w\", err)\n}\nf.mu.Lock()\nf.memSize += memConsumed\n@@ -253,12 +253,12 @@ func (f *Fragmentation) release(r *reassembler, timedOut bool) {\n}\nif !r.pkt.IsNil() {\nr.pkt.DecRef()\n- r.pkt = nil\n+ r.pkt = stack.PacketBufferPtr{}\n}\nfor _, h := range r.holes {\nif !h.pkt.IsNil() {\nh.pkt.DecRef()\n- h.pkt = nil\n+ h.pkt = stack.PacketBufferPtr{}\n}\n}\nr.holes = nil\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/internal/fragmentation/fragmentation_test.go", "new_path": "pkg/tcpip/network/internal/fragmentation/fragmentation_test.go", "diff": "@@ -113,6 +113,7 @@ func TestFragmentationProcess(t *testing.T) {\nf := NewFragmentation(minBlockSize, 2048, 512, reassembleTimeout, &faketime.NullClock{}, nil)\nfirstFragmentProto := c.in[0].proto\nfor i, in := range c.in {\n+ in := in\ndefer in.pkt.DecRef()\ndefer c.out[i].buf.Release()\nresPkt, proto, done, err := f.Process(in.id, in.first, in.last, in.more, in.proto, in.pkt)\n@@ -631,7 +632,7 @@ func TestTimeoutHandler(t *testing.T) {\n},\n},\nwantError: false,\n- wantPkt: nil,\n+ wantPkt: stack.PacketBufferPtr{},\n},\n{\nname: \"second pkt is ignored\",\n@@ -663,7 +664,7 @@ func TestTimeoutHandler(t *testing.T) {\n},\n},\nwantError: true,\n- wantPkt: nil,\n+ wantPkt: stack.PacketBufferPtr{},\n},\n}\n@@ -671,7 +672,7 @@ func TestTimeoutHandler(t *testing.T) {\nfor _, test := range tests {\nt.Run(test.name, func(t *testing.T) {\n- handler := &testTimeoutHandler{pkt: nil}\n+ handler := &testTimeoutHandler{pkt: stack.PacketBufferPtr{}}\nf := NewFragmentation(minBlockSize, HighFragThreshold, LowFragThreshold, reassembleTimeout, &faketime.NullClock{}, handler)\n@@ -702,7 +703,7 @@ func TestTimeoutHandler(t *testing.T) {\n}\nfunc TestFragmentSurvivesReleaseJob(t *testing.T) {\n- handler := &testTimeoutHandler{pkt: nil}\n+ handler := &testTimeoutHandler{pkt: stack.PacketBufferPtr{}}\nc := faketime.NewManualClock()\nf := NewFragmentation(minBlockSize, HighFragThreshold, LowFragThreshold, reassembleTimeout, c, handler)\npkt := pkt(2, \"01\")\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/internal/fragmentation/reassembler.go", "new_path": "pkg/tcpip/network/internal/fragmentation/reassembler.go", "diff": "@@ -67,7 +67,7 @@ func (r *reassembler) process(first, last uint16, more bool, proto uint8, pkt st\n// A concurrent goroutine might have already reassembled\n// the packet and emptied the heap while this goroutine\n// was waiting on the mutex. We don't have to do anything in this case.\n- return nil, 0, false, 0, nil\n+ return stack.PacketBufferPtr{}, 0, false, 0, nil\n}\nvar holeFound bool\n@@ -91,12 +91,12 @@ func (r *reassembler) process(first, last uint16, more bool, proto uint8, pkt st\n// https://github.com/torvalds/linux/blob/38525c6/net/ipv4/inet_fragment.c#L349\nif first < currentHole.first || currentHole.last < last {\n// Incoming fragment only partially fits in the free hole.\n- return nil, 0, false, 0, ErrFragmentOverlap\n+ return stack.PacketBufferPtr{}, 0, false, 0, ErrFragmentOverlap\n}\nif !more {\nif !currentHole.final || currentHole.filled && currentHole.last != last {\n// We have another final fragment, which does not perfectly overlap.\n- return nil, 0, false, 0, ErrFragmentConflict\n+ return stack.PacketBufferPtr{}, 0, false, 0, ErrFragmentConflict\n}\n}\n@@ -155,12 +155,12 @@ func (r *reassembler) process(first, last uint16, more bool, proto uint8, pkt st\n}\nif !holeFound {\n// Incoming fragment is beyond end.\n- return nil, 0, false, 0, ErrFragmentConflict\n+ return stack.PacketBufferPtr{}, 0, false, 0, ErrFragmentConflict\n}\n// Check if all the holes have been filled and we are ready to reassemble.\nif r.filled < len(r.holes) {\n- return nil, 0, false, memConsumed, nil\n+ return stack.PacketBufferPtr{}, 0, false, memConsumed, nil\n}\nsort.Slice(r.holes, func(i, j int) bool {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv4/icmp.go", "new_path": "pkg/tcpip/network/ipv4/icmp.go", "diff": "@@ -256,7 +256,8 @@ func (e *endpoint) handleICMP(pkt stack.PacketBufferPtr) {\n// It's possible that a raw socket expects to receive this.\ne.dispatcher.DeliverTransportPacket(header.ICMPv4ProtocolNumber, pkt)\n- pkt = nil\n+ pkt = stack.PacketBufferPtr{}\n+ _ = pkt // Suppress unused variable warning.\nsent := e.stats.icmp.packetsSent\nif !e.protocol.allowICMPReply(header.ICMPv4EchoReply, header.ICMPv4UnusedCode) {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/BUILD", "new_path": "pkg/tcpip/stack/BUILD", "diff": "@@ -34,7 +34,7 @@ go_template_instance(\nprefix = \"packetBuffer\",\ntemplate = \"//pkg/refsvfs2:refs_template\",\ntypes = {\n- \"T\": \"PacketBuffer\",\n+ \"T\": \"packetBuffer\",\n},\n)\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/packet_buffer.go", "new_path": "pkg/tcpip/stack/packet_buffer.go", "diff": "@@ -35,7 +35,7 @@ const (\nvar pkPool = sync.Pool{\nNew: func() interface{} {\n- return &PacketBuffer{}\n+ return &packetBuffer{}\n},\n}\n@@ -59,9 +59,14 @@ type PacketBufferOptions struct {\n}\n// PacketBufferPtr is a pointer to a PacketBuffer.\n-type PacketBufferPtr = *PacketBuffer\n+//\n+// +stateify savable\n+type PacketBufferPtr struct {\n+ // packetBuffer is the underlying packet buffer.\n+ *packetBuffer\n+}\n-// A PacketBuffer contains all the data of a network packet.\n+// A packetBuffer contains all the data of a network packet.\n//\n// As a PacketBuffer traverses up the stack, it may be necessary to pass it to\n// multiple endpoints.\n@@ -103,7 +108,7 @@ type PacketBufferPtr = *PacketBuffer\n// starting offset of each header in `buf`.\n//\n// +stateify savable\n-type PacketBuffer struct {\n+type packetBuffer struct {\n_ sync.NoCopy\npacketBufferRefs\n@@ -173,7 +178,7 @@ type PacketBuffer struct {\n// NewPacketBuffer creates a new PacketBuffer with opts.\nfunc NewPacketBuffer(opts PacketBufferOptions) PacketBufferPtr {\n- pk := pkPool.Get().(PacketBufferPtr)\n+ pk := pkPool.Get().(*packetBuffer)\npk.reset()\nif opts.ReserveHeaderBytes != 0 {\nv := bufferv2.NewViewSize(opts.ReserveHeaderBytes)\n@@ -186,31 +191,36 @@ func NewPacketBuffer(opts PacketBufferOptions) PacketBufferPtr {\npk.NetworkPacketInfo.IsForwardedPacket = opts.IsForwardedPacket\npk.onRelease = opts.OnRelease\npk.InitRefs()\n- return pk\n+ return PacketBufferPtr{\n+ packetBuffer: pk,\n+ }\n}\n// IncRef increments the PacketBuffer's refcount.\nfunc (pk PacketBufferPtr) IncRef() PacketBufferPtr {\npk.packetBufferRefs.IncRef()\n- return pk\n+ return PacketBufferPtr{\n+ packetBuffer: pk.packetBuffer,\n+ }\n}\n// DecRef decrements the PacketBuffer's refcount. If the refcount is\n// decremented to zero, the PacketBuffer is returned to the PacketBuffer\n// pool.\n-func (pk PacketBufferPtr) DecRef() {\n+func (pk *PacketBufferPtr) DecRef() {\npk.packetBufferRefs.DecRef(func() {\nif pk.onRelease != nil {\npk.onRelease()\n}\npk.buf.Release()\n- pkPool.Put(pk)\n+ pkPool.Put(pk.packetBuffer)\n})\n+ pk.packetBuffer = nil\n}\n-func (pk PacketBufferPtr) reset() {\n- *pk = PacketBuffer{}\n+func (pk *packetBuffer) reset() {\n+ *pk = packetBuffer{}\n}\n// ReservedHeaderBytes returns the number of bytes initially reserved for\n@@ -364,7 +374,7 @@ func (pk PacketBufferPtr) headerView(typ headerType) bufferv2.View {\n// Clone makes a semi-deep copy of pk. The underlying packet payload is\n// shared. Hence, no modifications is done to underlying packet payload.\nfunc (pk PacketBufferPtr) Clone() PacketBufferPtr {\n- newPk := pkPool.Get().(PacketBufferPtr)\n+ newPk := pkPool.Get().(*packetBuffer)\nnewPk.reset()\nnewPk.buf = pk.buf.Clone()\nnewPk.reserved = pk.reserved\n@@ -384,7 +394,9 @@ func (pk PacketBufferPtr) Clone() PacketBufferPtr {\nnewPk.NetworkPacketInfo = pk.NetworkPacketInfo\nnewPk.tuple = pk.tuple\nnewPk.InitRefs()\n- return newPk\n+ return PacketBufferPtr{\n+ packetBuffer: newPk,\n+ }\n}\n// ReserveHeaderBytes prepends reserved space for headers at the front\n@@ -417,14 +429,16 @@ func (pk PacketBufferPtr) Network() header.Network {\n// See PacketBuffer.Data for details about how a packet buffer holds an inbound\n// packet.\nfunc (pk PacketBufferPtr) CloneToInbound() PacketBufferPtr {\n- newPk := pkPool.Get().(PacketBufferPtr)\n+ newPk := pkPool.Get().(*packetBuffer)\nnewPk.reset()\nnewPk.buf = pk.buf.Clone()\nnewPk.InitRefs()\n// Treat unfilled header portion as reserved.\nnewPk.reserved = pk.AvailableHeaderBytes()\nnewPk.tuple = pk.tuple\n- return newPk\n+ return PacketBufferPtr{\n+ packetBuffer: newPk,\n+ }\n}\n// DeepCopyForForwarding creates a deep copy of the packet buffer for\n@@ -462,7 +476,7 @@ func (pk PacketBufferPtr) DeepCopyForForwarding(reservedHeaderBytes int) PacketB\n// IsNil returns whether the pointer is logically nil.\nfunc (pk PacketBufferPtr) IsNil() bool {\n- return pk == nil\n+ return pk.packetBuffer == nil\n}\n// headerInfo stores metadata about a header in a packet.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/packet_buffer_list.go", "new_path": "pkg/tcpip/stack/packet_buffer_list.go", "diff": "@@ -37,7 +37,7 @@ func (pl *PacketBufferList) AsSlice() []PacketBufferPtr {\nfunc (pl *PacketBufferList) Reset() {\nfor i, pb := range pl.pbs {\npb.DecRef()\n- pl.pbs[i] = nil\n+ pl.pbs[i] = PacketBufferPtr{}\n}\npl.pbs = pl.pbs[:0]\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/packet_buffer_unsafe.go", "new_path": "pkg/tcpip/stack/packet_buffer_unsafe.go", "diff": "@@ -17,4 +17,4 @@ package stack\nimport \"unsafe\"\n// PacketBufferStructSize is the minimal size of the packet buffer overhead.\n-const PacketBufferStructSize = int(unsafe.Sizeof(PacketBuffer{}))\n+const PacketBufferStructSize = int(unsafe.Sizeof(packetBuffer{}))\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/internal/network/endpoint.go", "new_path": "pkg/tcpip/transport/internal/network/endpoint.go", "diff": "@@ -276,7 +276,7 @@ func (c *WriteContext) TryNewPacketBuffer(reserveHdrBytes int, data bufferv2.Buf\ndefer e.sendBufferSizeInUseMu.Unlock()\nif !e.hasSendSpaceRLocked() {\n- return nil\n+ return stack.PacketBufferPtr{}\n}\n// Note that we allow oversubscription - if there is any space at all in the\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/segment.go", "new_path": "pkg/tcpip/transport/tcp/segment.go", "diff": "@@ -116,8 +116,7 @@ func newIncomingSegment(id stack.TransportEndpointID, clock tcpip.Clock, pkt sta\ns.window = seqnum.Size(hdr.WindowSize())\ns.rcvdTime = clock.NowMonotonic()\ns.dataMemSize = pkt.MemSize()\n- s.pkt = pkt\n- pkt.IncRef()\n+ s.pkt = pkt.IncRef()\ns.csumValid = csumValid\nif !s.pkt.RXTransportChecksumValidated {\n@@ -195,7 +194,6 @@ func (s *segment) DecRef() {\n}\n}\ns.pkt.DecRef()\n- s.pkt = nil\nsegmentPool.Put(s)\n})\n}\n" } ]
Go
Apache License 2.0
google/gvisor
DecRef ptr niling PiperOrigin-RevId: 480518221
259,977
12.10.2022 14:23:50
25,200
49874d2cff79a7cafadc0c88f28199c454e981ab
Avoid UB when bit shifting The 0 literal is a signed integer; bitshifting its (negative) complement is undefined behavior.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_ip_unbound.cc", "new_path": "test/syscalls/linux/socket_ip_unbound.cc", "diff": "@@ -284,7 +284,7 @@ TEST_P(IPUnboundSocketTest, SmallTOSOptionSize) {\nEXPECT_EQ(get_sz, expect_sz);\n// Account for partial copies by getsockopt, retrieve the lower\n// bits specified by get_sz, while comparing against expect_tos.\n- EXPECT_EQ(get & ~(~0 << (get_sz * 8)), expect_tos);\n+ EXPECT_EQ(get & ~(~static_cast<uint>(0) << (get_sz * 8)), expect_tos);\n}\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Avoid UB when bit shifting The 0 literal is a signed integer; bitshifting its (negative) complement is undefined behavior. PiperOrigin-RevId: 480717288
259,885
13.10.2022 22:12:29
25,200
2f57fc1f17a4ee84015def47970e9cee99cd31aa
Handle pending CPU clock tick in incRunningTasks().
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/kernel.go", "new_path": "pkg/sentry/kernel/kernel.go", "diff": "@@ -213,6 +213,9 @@ type Kernel struct {\n// cpuClock is mutable, and is accessed using atomic memory operations.\ncpuClock atomicbitops.Uint64\n+ // cpuClockTickTimer drives increments of cpuClock.\n+ cpuClockTickTimer *time.Timer `state:\"nosave\"`\n+\n// cpuClockMu is used to make increments of cpuClock, and updates of timers\n// based on cpuClock, atomic.\ncpuClockMu cpuClockMutex `state:\"nosave\"`\n@@ -1130,6 +1133,7 @@ func (k *Kernel) Start() error {\n}\nk.started = true\n+ k.cpuClockTickTimer = time.NewTimer(linux.ClockTick)\nk.runningTasksMu.Lock()\nk.cpuClockTickerRunning = true\nk.runningTasksMu.Unlock()\n@@ -1250,11 +1254,51 @@ func (k *Kernel) incRunningTasks() {\nreturn\n}\n- // Transition from 0 -> 1. Synchronize with other transitions and timer.\n+ // Transition from 0 -> 1.\nk.runningTasksMu.Lock()\n- if k.runningTasks.Add(1) == 1 {\n+ if k.runningTasks.Load() != 0 {\n+ // Raced with another transition and lost.\n+ k.runningTasks.Add(1)\n+ k.runningTasksMu.Unlock()\n+ return\n+ }\n+ if !k.cpuClockTickerRunning {\n+ select {\n+ case tickTime := <-k.cpuClockTickTimer.C:\n+ // Rearm the timer since we consumed the wakeup. Estimate how much time\n+ // remains on the current tick so that periodic workloads interact with\n+ // the (periodic) CPU clock ticker in the same way that they would\n+ // without the optimization of putting the ticker to sleep.\n+ missedNS := time.Since(tickTime).Nanoseconds()\n+ missedTicks := missedNS / linux.ClockTick.Nanoseconds()\n+ thisTickNS := missedNS - missedTicks*linux.ClockTick.Nanoseconds()\n+ k.cpuClockTickTimer.Reset(time.Duration(linux.ClockTick.Nanoseconds() - thisTickNS))\n+ // Increment k.cpuClock on the CPU clock ticker goroutine's behalf.\n+ // (Whole missed ticks don't matter, and adding them to k.cpuClock will\n+ // just confuse the watchdog.) At the time the tick occurred, all task\n+ // goroutines were asleep, so there's nothing else to do. This ensures\n+ // that our caller (Task.accountTaskGoroutineLeave()) records an\n+ // updated k.cpuClock in Task.gosched.Timestamp, so that it's correctly\n+ // accounted as having resumed execution in the sentry during this tick\n+ // instead of at the end of the previous one.\n+ k.cpuClock.Add(1)\n+ default:\n+ }\n+ // We are transitioning from idle to active. Set k.cpuClockTickerRunning\n+ // = true here so that if we transition to idle and then active again\n+ // before the CPU clock ticker goroutine has a chance to run, the first\n+ // call to k.incRunningTasks() at the end of that cycle does not try to\n+ // steal k.cpuClockTickTimer.C again, as this would allow workloads that\n+ // rapidly cycle between idle and active to starve the CPU clock ticker\n+ // of chances to observe task goroutines in a running state and account\n+ // their CPU usage.\n+ k.cpuClockTickerRunning = true\nk.runningTasksCond.Signal()\n}\n+ // This store must happen after the increment of k.cpuClock above to ensure\n+ // that concurrent calls to Task.accountTaskGoroutineLeave() also observe\n+ // the updated k.cpuClock.\n+ k.runningTasks.Store(1)\nk.runningTasksMu.Unlock()\nreturn\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/task_sched.go", "new_path": "pkg/sentry/kernel/task_sched.go", "diff": "@@ -336,37 +336,30 @@ func (tg *ThreadGroup) CPUClock() ktime.Clock {\n}\nfunc (k *Kernel) runCPUClockTicker() {\n- tickTimer := time.NewTimer(linux.ClockTick)\nrng := rand.New(rand.NewSource(rand.Int63()))\nvar tgs []*ThreadGroup\nfor {\n- // Wait for the next CPU clock tick.\n- wokenEarly := false\n- select {\n- case <-tickTimer.C:\n- tickTimer.Reset(linux.ClockTick)\n- case <-k.cpuClockTickerWakeCh:\n- // Wake up to check if we need to stop with cpuClockTickerRunning =\n- // false, but then continue waiting for the next CPU clock tick.\n- wokenEarly = true\n- }\n-\n// Stop the CPU clock while nothing is running.\nif k.runningTasks.Load() == 0 {\nk.runningTasksMu.Lock()\nif k.runningTasks.Load() == 0 {\nk.cpuClockTickerRunning = false\nk.cpuClockTickerStopCond.Broadcast()\n- for k.runningTasks.Load() == 0 {\nk.runningTasksCond.Wait()\n- }\n- k.cpuClockTickerRunning = true\n+ // k.cpuClockTickerRunning was set to true by our waker\n+ // (Kernel.incRunningTasks()). For reasons described there, we must\n+ // process at least one CPU clock tick between calls to\n+ // k.runningTasksCond.Wait().\n}\nk.runningTasksMu.Unlock()\n}\n- if wokenEarly {\n+ // Wait for the next CPU clock tick.\n+ select {\n+ case <-k.cpuClockTickTimer.C:\n+ k.cpuClockTickTimer.Reset(linux.ClockTick)\n+ case <-k.cpuClockTickerWakeCh:\ncontinue\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Handle pending CPU clock tick in incRunningTasks(). PiperOrigin-RevId: 481060107
259,907
14.10.2022 10:30:57
25,200
94600be1b8203327c0a19e64f012d7ad79e94245
Fix the runs to 1GB for rand write/read for the FIO benchmark.
[ { "change_type": "MODIFY", "old_path": ".buildkite/pipeline.yaml", "new_path": ".buildkite/pipeline.yaml", "diff": "@@ -450,7 +450,7 @@ steps:\n# For rand(read|write) fio benchmarks, running 15s does not overwhelm the system for tmpfs mounts.\n- <<: *benchmarks\nlabel: \":cd: FIO benchmarks (randread/randwrite)\"\n- command: make -i benchmark-platforms BENCHMARKS_SUITE=fio BENCHMARKS_TARGETS=test/benchmarks/fs:fio_test BENCHMARKS_FILTER=Fio/operation\\.rand BENCHMARKS_OPTIONS=--test.benchtime=15s\n+ command: make -i benchmark-platforms BENCHMARKS_SUITE=fio BENCHMARKS_TARGETS=test/benchmarks/fs:fio_test BENCHMARKS_FILTER=Fio/operation\\.rand BENCHMARKS_OPTIONS=--test.benchtime=1000x\n- <<: *benchmarks\nlabel: \":cd: Ruby CI/CD benchmarks\"\ncommand: make -i benchmark-platforms BENCHMARKS_SUITE=fio BENCHMARKS_TARGETS=test/benchmarks/fs:rubydev_test BENCHMARKS_OPTIONS=-test.benchtime=1ns\n" } ]
Go
Apache License 2.0
google/gvisor
Fix the runs to 1GB for rand write/read for the FIO benchmark. PiperOrigin-RevId: 481178578
259,907
14.10.2022 11:24:22
25,200
0444ca8c9f0b5cda80f480df8ae57f9004712d0d
Make tensorflow benchmark order deterministic. Makes it easier to compare output from different runs. Consistent with what other benchmarks do.
[ { "change_type": "MODIFY", "old_path": "test/benchmarks/ml/tensorflow_test.go", "new_path": "test/benchmarks/ml/tensorflow_test.go", "diff": "@@ -26,15 +26,17 @@ import (\n// BenchmarkTensorflow runs workloads from a TensorFlow tutorial.\n// See: https://github.com/aymericdamien/TensorFlow-Examples\nfunc BenchmarkTensorflow(b *testing.B) {\n- workloads := map[string]string{\n- \"GradientDecisionTree\": \"2_BasicModels/gradient_boosted_decision_tree.py\",\n- \"Kmeans\": \"2_BasicModels/kmeans.py\",\n- \"LogisticRegression\": \"2_BasicModels/logistic_regression.py\",\n- \"NearestNeighbor\": \"2_BasicModels/nearest_neighbor.py\",\n- \"RandomForest\": \"2_BasicModels/random_forest.py\",\n- \"ConvolutionalNetwork\": \"3_NeuralNetworks/convolutional_network.py\",\n- \"MultilayerPerceptron\": \"3_NeuralNetworks/multilayer_perceptron.py\",\n- \"NeuralNetwork\": \"3_NeuralNetworks/neural_network.py\",\n+ workloads := []struct {\n+ name, file string\n+ }{\n+ {\"GradientDecisionTree\", \"2_BasicModels/gradient_boosted_decision_tree.py\"},\n+ {\"Kmeans\", \"2_BasicModels/kmeans.py\"},\n+ {\"LogisticRegression\", \"2_BasicModels/logistic_regression.py\"},\n+ {\"NearestNeighbor\", \"2_BasicModels/nearest_neighbor.py\"},\n+ {\"RandomForest\", \"2_BasicModels/random_forest.py\"},\n+ {\"ConvolutionalNetwork\", \"3_NeuralNetworks/convolutional_network.py\"},\n+ {\"MultilayerPerceptron\", \"3_NeuralNetworks/multilayer_perceptron.py\"},\n+ {\"NeuralNetwork\", \"3_NeuralNetworks/neural_network.py\"},\n}\nmachine, err := harness.GetMachine()\n@@ -43,10 +45,10 @@ func BenchmarkTensorflow(b *testing.B) {\n}\ndefer machine.CleanUp()\n- for name, workload := range workloads {\n+ for _, workload := range workloads {\nrunName, err := tools.ParametersToName(tools.Parameter{\nName: \"operation\",\n- Value: name,\n+ Value: workload.name,\n})\nif err != nil {\nb.Fatalf(\"Failed to parse param: %v\", err)\n@@ -71,7 +73,7 @@ func BenchmarkTensorflow(b *testing.B) {\nImage: \"benchmarks/tensorflow\",\nEnv: []string{\"PYTHONPATH=$PYTHONPATH:/TensorFlow-Examples/examples\"},\nWorkDir: \"/TensorFlow-Examples/examples\",\n- }, \"python\", workload); err != nil {\n+ }, \"python\", workload.file); err != nil {\nb.Errorf(\"failed to run container: %v logs: %s\", err, out)\n}\nb.StopTimer()\n" } ]
Go
Apache License 2.0
google/gvisor
Make tensorflow benchmark order deterministic. Makes it easier to compare output from different runs. Consistent with what other benchmarks do. PiperOrigin-RevId: 481192191
259,992
18.10.2022 14:44:57
25,200
c6c38d5c4b35b5604e79d5b3da674d3e7ebb3b12
Fix panic in lisafs When mount fails, `filesystem.Release()` attempts to dereference a nil `filesystem.clientLisa`.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/gofer/gofer.go", "new_path": "pkg/sentry/fsimpl/gofer/gofer.go", "diff": "@@ -743,11 +743,15 @@ func (fs *filesystem) Release(ctx context.Context) {\nif !fs.iopts.LeakConnection {\n// Close the connection to the server. This implicitly clunks all fids.\nif fs.opts.lisaEnabled {\n+ if fs.clientLisa != nil {\nfs.clientLisa.Close()\n+ }\n} else {\n+ if fs.client != nil {\nfs.client.Close()\n}\n}\n+ }\nfs.vfsfs.VirtualFilesystem().PutAnonBlockDevMinor(fs.devMinor)\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Fix panic in lisafs When mount fails, `filesystem.Release()` attempts to dereference a nil `filesystem.clientLisa`. PiperOrigin-RevId: 482027422
259,909
19.10.2022 09:45:20
25,200
5e2506ce0b281b05590ded6c34036043c203ad8b
Make buffer pooling true by default in runsc.
[ { "change_type": "MODIFY", "old_path": "runsc/config/flags.go", "new_path": "runsc/config/flags.go", "diff": "@@ -97,7 +97,7 @@ func RegisterFlags(flagSet *flag.FlagSet) {\nflagSet.Bool(\"rx-checksum-offload\", true, \"enable RX checksum offload.\")\nflagSet.Var(queueingDisciplinePtr(QDiscFIFO), \"qdisc\", \"specifies which queueing discipline to apply by default to the non loopback nics used by the sandbox.\")\nflagSet.Int(\"num-network-channels\", 1, \"number of underlying channels(FDs) to use for network link endpoints.\")\n- flagSet.Bool(\"buffer-pooling\", false, \"enable allocation of buffers from a shared pool instead of the heap.\")\n+ flagSet.Bool(\"buffer-pooling\", true, \"enable allocation of buffers from a shared pool instead of the heap.\")\nflagSet.Bool(\"EXPERIMENTAL-afxdp\", false, \"EXPERIMENTAL. Use an AF_XDP socket to receive packets.\")\n// Test flags, not to be used outside tests, ever.\n" } ]
Go
Apache License 2.0
google/gvisor
Make buffer pooling true by default in runsc. PiperOrigin-RevId: 482229293
259,909
21.10.2022 12:53:23
25,200
d4a7318c6be8dd907d1de50b0100f61b4a8ce778
Fix tun reference counting. The tun code does not properly abide by reference counting rules. Change it so the ownership is more clear and to prevent potential use-after-free.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/devices/tundev/tundev.go", "new_path": "pkg/sentry/devices/tundev/tundev.go", "diff": "@@ -157,6 +157,7 @@ func (fd *tunFD) Write(ctx context.Context, src usermem.IOSequence, opts vfs.Wri\nreturn 0, unix.EMSGSIZE\n}\ndata := bufferv2.NewView(int(src.NumBytes()))\n+ defer data.Release()\nif _, err := io.CopyN(data, src.Reader(ctx), src.NumBytes()); err != nil {\nreturn 0, err\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/dev/net_tun.go", "new_path": "pkg/sentry/fs/dev/net_tun.go", "diff": "@@ -139,6 +139,7 @@ func (n *netTunFileOperations) Write(ctx context.Context, file *fs.File, src use\nreturn 0, unix.EINVAL\n}\ndata := bufferv2.NewView(int(src.NumBytes()))\n+ defer data.Release()\nif _, err := io.CopyN(data, src.Reader(ctx), src.NumBytes()); err != nil {\nreturn 0, err\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/link/tun/device.go", "new_path": "pkg/tcpip/link/tun/device.go", "diff": "@@ -201,7 +201,10 @@ func (d *Device) Write(data *bufferv2.View) (int64, error) {\n// Ignore bad packet.\nreturn dataLen, nil\n}\n- pktInfoHdr = PacketInfoHeader(data.AsSlice()[:PacketInfoHeaderSize])\n+ pktInfoHdrView := data.Clone()\n+ defer pktInfoHdrView.Release()\n+ pktInfoHdrView.CapLength(PacketInfoHeaderSize)\n+ pktInfoHdr = PacketInfoHeader(pktInfoHdrView.AsSlice())\ndata.TrimFront(PacketInfoHeaderSize)\n}\n@@ -212,7 +215,10 @@ func (d *Device) Write(data *bufferv2.View) (int64, error) {\n// Ignore bad packet.\nreturn dataLen, nil\n}\n- ethHdr = header.Ethernet(data.AsSlice()[:header.EthernetMinimumSize])\n+ ethHdrView := data.Clone()\n+ defer ethHdrView.Release()\n+ ethHdrView.CapLength(header.EthernetMinimumSize)\n+ ethHdr = header.Ethernet(ethHdrView.AsSlice())\ndata.TrimFront(header.EthernetMinimumSize)\n}\n@@ -236,7 +242,7 @@ func (d *Device) Write(data *bufferv2.View) (int64, error) {\npkt := stack.NewPacketBuffer(stack.PacketBufferOptions{\nReserveHeaderBytes: len(ethHdr),\n- Payload: bufferv2.MakeWithView(data),\n+ Payload: bufferv2.MakeWithView(data.Clone()),\n})\ndefer pkt.DecRef()\ncopy(pkt.LinkHeader().Push(len(ethHdr)), ethHdr)\n" } ]
Go
Apache License 2.0
google/gvisor
Fix tun reference counting. The tun code does not properly abide by reference counting rules. Change it so the ownership is more clear and to prevent potential use-after-free. PiperOrigin-RevId: 482865862
259,909
24.10.2022 16:58:12
25,200
2ec925ee25c59ffcce138c424bb540b55683486d
Create buffer pooling blog.
[ { "change_type": "MODIFY", "old_path": "website/_config.yml", "new_path": "website/_config.yml", "diff": "@@ -25,6 +25,10 @@ defaults:\nlayout: default\nanalytics: \"UA-150193582-1\"\nauthors:\n+ lucasmanning:\n+ name: Lucas Manning\n+ email: lucasmanning@google.com\n+ url: https://twitter.com/lucassmanning\njsprad:\nname: Jeremiah Spradlin\nemail: jsprad@google.com\n" }, { "change_type": "ADD", "old_path": "website/assets/images/2022-10-24-buffer-pooling-figure1.png", "new_path": "website/assets/images/2022-10-24-buffer-pooling-figure1.png", "diff": "Binary files /dev/null and b/website/assets/images/2022-10-24-buffer-pooling-figure1.png differ\n" }, { "change_type": "ADD", "old_path": "website/assets/images/2022-10-24-buffer-pooling-figure2.png", "new_path": "website/assets/images/2022-10-24-buffer-pooling-figure2.png", "diff": "Binary files /dev/null and b/website/assets/images/2022-10-24-buffer-pooling-figure2.png differ\n" }, { "change_type": "MODIFY", "old_path": "website/blog/BUILD", "new_path": "website/blog/BUILD", "diff": "@@ -80,6 +80,16 @@ doc(\npermalink = \"/blog/2022/08/01/threat-detection/\",\n)\n+doc(\n+ name = \"buffer_pooling\",\n+ src = \"2022-10-24-buffer-pooling.md\",\n+ authors = [\n+ \"lucasmanning\",\n+ ],\n+ layout = \"post\",\n+ permalink = \"/blog/2022/10/24/buffer-pooling/\",\n+)\n+\ndocs(\nname = \"posts\",\ndeps = [\n" } ]
Go
Apache License 2.0
google/gvisor
Create buffer pooling blog. PiperOrigin-RevId: 483522945
259,909
25.10.2022 11:19:45
25,200
84767a8f2388dde73c7e7be04e6f5ece91d183ab
Fix title in buffer pooling blog.
[ { "change_type": "MODIFY", "old_path": "website/blog/2022-10-24-buffer-pooling.md", "new_path": "website/blog/2022-10-24-buffer-pooling.md", "diff": "-\\# How we Eliminated 99% of gVisor Networking Memory Allocations with Enhanced\n-Buffer Pooling\n+# How we Eliminated 99% of gVisor Networking Memory Allocations with Enhanced Buffer Pooling\nIn an\n[earlier blog post](https://gvisor.dev/blog/2020/04/02/gvisor-networking-security/)\n" } ]
Go
Apache License 2.0
google/gvisor
Fix title in buffer pooling blog. PiperOrigin-RevId: 483728986
259,992
25.10.2022 11:33:21
25,200
7e3bd4db0f6b9c70cb3f70471db3f6ff4cf20a9a
Add rudimentary UDS test to lisafs
[ { "change_type": "MODIFY", "old_path": "pkg/lisafs/testsuite/testsuite.go", "new_path": "pkg/lisafs/testsuite/testsuite.go", "diff": "@@ -77,6 +77,7 @@ var localFSTests = map[string]TestFunc{\n\"Walk\": testWalk,\n\"Rename\": testRename,\n\"Mknod\": testMknod,\n+ \"UDS\": testUDS,\n\"Getdents\": testGetdents,\n}\n@@ -200,6 +201,14 @@ func mknod(ctx context.Context, t *testing.T, dir lisafs.ClientFD, name string)\nreturn dir.Client().NewFD(nodeIno.ControlFD), nodeIno.Stat\n}\n+func bind(ctx context.Context, t *testing.T, dir lisafs.ClientFD, name string, sockType linux.SockType) (lisafs.ClientFD, *lisafs.ClientBoundSocketFD, linux.Statx) {\n+ nodeIno, socket, err := dir.BindAt(ctx, sockType, name, 0777, lisafs.UID(unix.Getuid()), lisafs.GID(unix.Getgid()))\n+ if err != nil {\n+ t.Fatalf(\"bind failed: %v\", err)\n+ }\n+ return dir.Client().NewFD(nodeIno.ControlFD), socket, nodeIno.Stat\n+}\n+\nfunc walk(ctx context.Context, t *testing.T, dir lisafs.ClientFD, names []string) []lisafs.Inode {\n_, inodes, err := dir.WalkMultiple(ctx, names)\nif err != nil {\n@@ -563,10 +572,22 @@ func testRename(ctx context.Context, t *testing.T, tester Tester, root lisafs.Cl\n}\nfunc testMknod(ctx context.Context, t *testing.T, tester Tester, root lisafs.ClientFD) {\n- name := \"namedPipe\"\n+ name := \"regular-file\"\npipeFile, pipeStat := mknod(ctx, t, root, name)\ndefer closeFD(ctx, t, pipeFile)\n+ if got := pipeStat.Mode & unix.S_IFMT; got != unix.S_IFREG {\n+ t.Errorf(\"socket file mode is incorrect: want %#x, got %#x\", unix.S_IFSOCK, got)\n+ }\n+ if tester.SetUserGroupIDSupported() {\n+ if want := unix.Getuid(); int(pipeStat.UID) != want {\n+ t.Errorf(\"socket file uid is incorrect: want %d, got %d\", want, pipeStat.UID)\n+ }\n+ if want := unix.Getgid(); int(pipeStat.GID) != want {\n+ t.Errorf(\"socket file gid is incorrect: want %d, got %d\", want, pipeStat.GID)\n+ }\n+ }\n+\nvar stat linux.Statx\nstatTo(ctx, t, pipeFile, &stat)\n@@ -581,6 +602,40 @@ func testMknod(ctx context.Context, t *testing.T, tester Tester, root lisafs.Cli\n}\n}\n+func testUDS(ctx context.Context, t *testing.T, tester Tester, root lisafs.ClientFD) {\n+ const name = \"sock\"\n+ file, socket, stat := bind(ctx, t, root, name, unix.SOCK_STREAM)\n+ defer closeFD(ctx, t, file)\n+ defer socket.Close(ctx)\n+\n+ if got := stat.Mode & unix.S_IFMT; got != unix.S_IFSOCK {\n+ t.Errorf(\"socket file mode is incorrect: want %#x, got %#x\", unix.S_IFSOCK, got)\n+ }\n+ if tester.SetUserGroupIDSupported() {\n+ if want := unix.Getuid(); int(stat.UID) != want {\n+ t.Errorf(\"socket file uid is incorrect: want %d, got %d\", want, stat.UID)\n+ }\n+ if want := unix.Getgid(); int(stat.GID) != want {\n+ t.Errorf(\"socket file gid is incorrect: want %d, got %d\", want, stat.GID)\n+ }\n+ }\n+\n+ var got linux.Statx\n+ statTo(ctx, t, file, &got)\n+ if stat.Mode != got.Mode {\n+ t.Errorf(\"UDS mode is incorrect: want %d, got %d\", stat.Mode, got.Mode)\n+ }\n+ if stat.UID != got.UID {\n+ t.Errorf(\"mknod UID is incorrect: want %d, got %d\", stat.UID, got.UID)\n+ }\n+ if stat.GID != got.GID {\n+ t.Errorf(\"mknod GID is incorrect: want %d, got %d\", stat.GID, got.GID)\n+ }\n+\n+ // TODO(b/194709873): Once listen and accept are implemented, test connecting\n+ // and accepting a connection using sockF.\n+}\n+\nfunc testGetdents(ctx context.Context, t *testing.T, tester Tester, root lisafs.ClientFD) {\ntempDir, _ := mkdir(ctx, t, root, \"tempDir\")\ndefer closeFD(ctx, t, tempDir)\n" }, { "change_type": "MODIFY", "old_path": "runsc/fsgofer/BUILD", "new_path": "runsc/fsgofer/BUILD", "diff": "@@ -53,5 +53,6 @@ go_test(\n\"//pkg/lisafs\",\n\"//pkg/lisafs/testsuite\",\n\"//pkg/log\",\n+ \"//runsc/config\",\n],\n)\n" }, { "change_type": "MODIFY", "old_path": "runsc/fsgofer/lisafs_test.go", "new_path": "runsc/fsgofer/lisafs_test.go", "diff": "@@ -20,6 +20,7 @@ import (\n\"gvisor.dev/gvisor/pkg/lisafs\"\n\"gvisor.dev/gvisor/pkg/lisafs/testsuite\"\n\"gvisor.dev/gvisor/pkg/log\"\n+ \"gvisor.dev/gvisor/runsc/config\"\n\"gvisor.dev/gvisor/runsc/fsgofer\"\n)\n@@ -38,7 +39,7 @@ type tester struct{}\n// NewServer implements testsuite.Tester.NewServer.\nfunc (tester) NewServer(t *testing.T) *lisafs.Server {\n- return &fsgofer.NewLisafsServer(fsgofer.Config{}).Server\n+ return &fsgofer.NewLisafsServer(fsgofer.Config{HostUDS: config.HostUDSCreate}).Server\n}\n// LinkSupported implements testsuite.Tester.LinkSupported.\n" } ]
Go
Apache License 2.0
google/gvisor
Add rudimentary UDS test to lisafs PiperOrigin-RevId: 483732841
259,909
25.10.2022 14:30:33
25,200
db4a71af39abddf01d6a7ff6f00314e0b88c8717
Fix mount_util mountinfo parsing to account for multiple optional tags. Before this change, the parsing fails with a PosixError saying the line has too many entries.
[ { "change_type": "MODIFY", "old_path": "test/util/BUILD", "new_path": "test/util/BUILD", "diff": "@@ -164,6 +164,7 @@ cc_library(\n\"@com_google_absl//absl/container:flat_hash_map\",\n\"@com_google_absl//absl/strings\",\ngtest,\n+ \"@com_google_absl//absl/types:span\",\n],\n)\n" }, { "change_type": "MODIFY", "old_path": "test/util/mount_util.cc", "new_path": "test/util/mount_util.cc", "diff": "#include <unistd.h>\n#include \"absl/strings/numbers.h\"\n+#include \"absl/strings/str_join.h\"\n#include \"absl/strings/str_split.h\"\n+#include \"absl/types/span.h\"\nnamespace gvisor {\nnamespace testing {\n@@ -103,11 +105,11 @@ PosixErrorOr<std::vector<ProcMountInfoEntry>> ProcSelfMountInfoEntriesFrom(\nProcMountInfoEntry entry;\nstd::vector<std::string> fields =\nabsl::StrSplit(line, absl::ByChar(' '), absl::AllowEmpty());\n- if (fields.size() < 10 || fields.size() > 11) {\n+ if (fields.size() < 10 || fields.size() > 13) {\nreturn PosixError(\n- EINVAL, absl::StrFormat(\n- \"Unexpected number of tokens, got %d, content: <<%s>>\",\n- fields.size(), content));\n+ EINVAL,\n+ absl::StrFormat(\"Unexpected number of tokens, got %d, line: <<%s>>\",\n+ fields.size(), line));\n}\nASSIGN_OR_RETURN_ERRNO(entry.id, Atoi<uint64_t>(fields[0]));\n@@ -129,12 +131,14 @@ PosixErrorOr<std::vector<ProcMountInfoEntry>> ProcSelfMountInfoEntriesFrom(\nentry.mount_point = fields[4];\nentry.mount_opts = fields[5];\n- // The optional field (fields[6]) may or may not be present. We know based\n- // on the total number of tokens.\n+ // The optional field (fields[6]) may or may not be present and can have up\n+ // to 3 elements. We know based on the total number of tokens.\nint off = -1;\n- if (fields.size() == 11) {\n- entry.optional = fields[6];\n- off = 0;\n+ if (fields.size() > 10) {\n+ int num_optional_tags = fields.size() - 10;\n+ entry.optional = absl::StrJoin(\n+ absl::MakeSpan(fields).subspan(6, num_optional_tags), \" \");\n+ off += num_optional_tags;\n}\n// Field 7 is the optional field terminator char '-'.\nentry.fstype = fields[8 + off];\n" }, { "change_type": "MODIFY", "old_path": "test/util/mount_util_test.cc", "new_path": "test/util/mount_util_test.cc", "diff": "@@ -37,6 +37,13 @@ TEST(ParseMounts, MountInfo) {\nR\"proc(22 28 0:20 / /sys rw,relatime shared:7 - sysfs sysfs rw\n23 28 0:21 / /proc rw,relatime shared:14 - proc proc rw\n2007 8844 0:278 / /mnt rw,noexec - tmpfs rw,mode=123,uid=268601820,gid=5000\n+)proc\"));\n+ EXPECT_EQ(entries.size(), 3);\n+\n+ entries = ASSERT_NO_ERRNO_AND_VALUE(ProcSelfMountInfoEntriesFrom(\n+ R\"proc(22 28 0:20 / /sys rw,relatime shared:7 master:20 - sysfs sysfs rw\n+23 28 0:21 / /proc rw,relatime shared:14 master:20 propagate_from:1 - proc proc rw\n+2007 8844 0:278 / /mnt rw,noexec - tmpfs rw,mode=123,uid=268601820,gid=5000\n)proc\"));\nEXPECT_EQ(entries.size(), 3);\n}\n" }, { "change_type": "MODIFY", "old_path": "test/util/posix_error.h", "new_path": "test/util/posix_error.h", "diff": "@@ -64,6 +64,7 @@ class ABSL_MUST_USE_RESULT PosixError {\nprivate:\nint errno_ = 0;\n+ // std::string is not async-signal-safe. We must use a c string instead.\nchar msg_[1024] = {};\n};\n" } ]
Go
Apache License 2.0
google/gvisor
Fix mount_util mountinfo parsing to account for multiple optional tags. Before this change, the parsing fails with a PosixError saying the line has too many entries. PiperOrigin-RevId: 483777338
259,909
25.10.2022 17:38:31
25,200
2ee38d5b6d5672b5b52843d4d879fb7e61f98fe3
Allow external packages to clone and set the propagation type of mounts.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/vfs2/mount.go", "new_path": "pkg/sentry/syscalls/linux/vfs2/mount.go", "diff": "@@ -91,7 +91,7 @@ func Mount(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Syscall\nreturn 0, nil, linuxerr.EINVAL\n}\npropType := vfs.PropagationTypeFromLinux(propFlag)\n- return 0, nil, t.Kernel().VFS().SetMountPropagation(t, creds, &target.pop, propType)\n+ return 0, nil, t.Kernel().VFS().SetMountPropagationAt(t, creds, &target.pop, propType)\n}\n// Only copy in source, fstype, and data if we are doing a normal mount.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/mount.go", "new_path": "pkg/sentry/vfs/mount.go", "diff": "@@ -465,9 +465,9 @@ func (vfs *VirtualFilesystem) connectMountAt(ctx context.Context, mnt *Mount, vd\nreturn nil\n}\n-// SetMountPropagation changes the propagation type of the mount pointed to by\n+// SetMountPropagationAt changes the propagation type of the mount pointed to by\n// pop.\n-func (vfs *VirtualFilesystem) SetMountPropagation(ctx context.Context, creds *auth.Credentials, pop *PathOperation, propType PropagationType) error {\n+func (vfs *VirtualFilesystem) SetMountPropagationAt(ctx context.Context, creds *auth.Credentials, pop *PathOperation, propType PropagationType) error {\nvd, err := vfs.GetDentryAt(ctx, creds, pop, &GetDentryOptions{})\nif err != nil {\nreturn err\n@@ -484,10 +484,14 @@ func (vfs *VirtualFilesystem) SetMountPropagation(ctx context.Context, creds *au\n} else if vd.dentry != vd.mount.root {\nreturn linuxerr.EINVAL\n}\n+ vfs.SetMountPropagation(vd.mount, propType)\n+ return nil\n+}\n+// SetMountPropagation changes the propagation type of the mount.\n+func (vfs *VirtualFilesystem) SetMountPropagation(mnt *Mount, propType PropagationType) {\nvfs.mountMu.Lock()\ndefer vfs.mountMu.Unlock()\n- mnt := vd.mount\nif propType != mnt.propType {\nswitch propType {\ncase Shared, Private:\n@@ -497,7 +501,16 @@ func (vfs *VirtualFilesystem) SetMountPropagation(ctx context.Context, creds *au\n}\n}\nmnt.propType = propType\n- return nil\n+}\n+\n+// CloneMount returns a new mount with the same fs and root. If mnt's\n+// propagation type is shared the new mount is automatically made a peer of mnt.\n+func (vfs *VirtualFilesystem) CloneMount(mnt *Mount) *Mount {\n+ vfs.mountMu.Lock()\n+ defer vfs.mountMu.Unlock()\n+ clone := vfs.cloneMount(mnt, mnt.root)\n+ vfs.addPeer(mnt, clone)\n+ return clone\n}\n// cloneMount returns a new mount with mnt.fs as the filesystem and root as the\n" } ]
Go
Apache License 2.0
google/gvisor
Allow external packages to clone and set the propagation type of mounts. PiperOrigin-RevId: 483821346
259,853
25.10.2022 21:42:58
25,200
c1427a04dfba87bd2ebce767086b5351c725db25
Disable fasync for signalfd descriptors In Linux, signalfd doesn't support fasync events. Reported-by:
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/signalfd/signalfd.go", "new_path": "pkg/sentry/fsimpl/signalfd/signalfd.go", "diff": "@@ -34,6 +34,7 @@ type SignalFileDescription struct {\nvfs.FileDescriptionDefaultImpl\nvfs.DentryMetadataFileDescriptionImpl\nvfs.NoLockFD\n+ vfs.NoAsyncEventFD\n// target is the original signal target task.\n//\n@@ -155,3 +156,13 @@ func (sfd *SignalFileDescription) Epollable() bool {\nfunc (sfd *SignalFileDescription) Release(context.Context) {\nsfd.target.SignalUnregister(&sfd.entry)\n}\n+\n+// RegisterFileAsyncHandler implements vfs.FileDescriptionImpl.RegisterFileAsyncHandler.\n+func (sfd *SignalFileDescription) RegisterFileAsyncHandler(fd *vfs.FileDescription) error {\n+ return sfd.NoAsyncEventFD.RegisterFileAsyncHandler(fd)\n+}\n+\n+// UnregisterFileAsyncHandler implements vfs.FileDescriptionImpl.UnregisterFileAsyncHandler.\n+func (sfd *SignalFileDescription) UnregisterFileAsyncHandler(fd *vfs.FileDescription) {\n+ sfd.NoAsyncEventFD.UnregisterFileAsyncHandler(fd)\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/file_description.go", "new_path": "pkg/sentry/vfs/file_description.go", "diff": "@@ -196,7 +196,7 @@ func (fd *FileDescription) DecRef(ctx context.Context) {\nfd.vd.DecRef(ctx)\nfd.flagsMu.Lock()\nif fd.statusFlags.RacyLoad()&linux.O_ASYNC != 0 && fd.asyncHandler != nil {\n- fd.asyncHandler.Unregister(fd)\n+ fd.impl.UnregisterFileAsyncHandler(fd)\n}\nfd.asyncHandler = nil\nfd.flagsMu.Unlock()\n@@ -280,11 +280,11 @@ func (fd *FileDescription) SetStatusFlags(ctx context.Context, creds *auth.Crede\n// Use fd.statusFlags instead of oldFlags, which may have become outdated,\n// to avoid double registering/unregistering.\nif fd.statusFlags.RacyLoad()&linux.O_ASYNC == 0 && flags&linux.O_ASYNC != 0 {\n- if err := fd.asyncHandler.Register(fd); err != nil {\n+ if err := fd.impl.RegisterFileAsyncHandler(fd); err != nil {\nreturn err\n}\n} else if fd.statusFlags.RacyLoad()&linux.O_ASYNC != 0 && flags&linux.O_ASYNC == 0 {\n- fd.asyncHandler.Unregister(fd)\n+ fd.impl.UnregisterFileAsyncHandler(fd)\n}\n}\nfd.statusFlags.Store((oldFlags &^ settableFlags) | (flags & settableFlags))\n@@ -474,6 +474,9 @@ type FileDescriptionImpl interface {\n// TestPOSIX returns information about whether the specified lock can be held, in the style of the F_GETLK fcntl.\nTestPOSIX(ctx context.Context, uid lock.UniqueID, t lock.LockType, r lock.LockRange) (linux.Flock, error)\n+\n+ RegisterFileAsyncHandler(fd *FileDescription) error\n+ UnregisterFileAsyncHandler(fd *FileDescription)\n}\n// Dirent holds the information contained in struct linux_dirent64.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/file_description_impl_util.go", "new_path": "pkg/sentry/vfs/file_description_impl_util.go", "diff": "@@ -172,6 +172,16 @@ func (FileDescriptionDefaultImpl) RemoveXattr(ctx context.Context, name string)\nreturn linuxerr.ENOTSUP\n}\n+// RegisterFileAsyncHandler implements FileDescriptionImpl.RegisterFileAsyncHandler.\n+func (FileDescriptionDefaultImpl) RegisterFileAsyncHandler(fd *FileDescription) error {\n+ return fd.asyncHandler.Register(fd)\n+}\n+\n+// UnregisterFileAsyncHandler implements FileDescriptionImpl.UnregisterFileAsyncHandler.\n+func (FileDescriptionDefaultImpl) UnregisterFileAsyncHandler(fd *FileDescription) {\n+ fd.asyncHandler.Unregister(fd)\n+}\n+\n// DirectoryFileDescriptionDefaultImpl may be embedded by implementations of\n// FileDescriptionImpl that always represent directories to obtain\n// implementations of non-directory I/O methods that return EISDIR.\n@@ -466,6 +476,18 @@ func (fd *LockFD) TestPOSIX(ctx context.Context, uid fslock.UniqueID, t fslock.L\nreturn fd.locks.TestPOSIX(ctx, uid, t, r)\n}\n+// NoAsyncEventFD implements [Un]RegisterFileAsyncHandler of FileDescriptionImpl.\n+type NoAsyncEventFD struct{}\n+\n+// RegisterFileAsyncHandler implements FileDescriptionImpl.RegisterFileAsyncHandler.\n+func (NoAsyncEventFD) RegisterFileAsyncHandler(fd *FileDescription) error {\n+ return nil\n+}\n+\n+// UnregisterFileAsyncHandler implements FileDescriptionImpl.UnregisterFileAsyncHandler.\n+func (NoAsyncEventFD) UnregisterFileAsyncHandler(fd *FileDescription) {\n+}\n+\n// NoLockFD implements Lock*/Unlock* portion of FileDescriptionImpl interface\n// returning ENOLCK.\n//\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/fcntl.cc", "new_path": "test/syscalls/linux/fcntl.cc", "diff": "#include <signal.h>\n#include <sys/epoll.h>\n#include <sys/mman.h>\n+#include <sys/signalfd.h>\n#include <sys/types.h>\n#include <syscall.h>\n#include <unistd.h>\n@@ -1496,6 +1497,19 @@ TEST_F(FcntlSignalTest, SetSigDefault) {\n// siginfo contents is undefined in this case.\n}\n+TEST_F(FcntlSignalTest, SignalFD) {\n+ // Create the signalfd.\n+ sigset_t mask;\n+ sigemptyset(&mask);\n+ sigaddset(&mask, SIGIO);\n+ FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(NewSignalFD(&mask, 0));\n+ const auto signal_cleanup =\n+ ASSERT_NO_ERRNO_AND_VALUE(RegisterSignalHandler(SIGIO));\n+ RegisterFD(fd.get(), 0);\n+ int tid = syscall(SYS_gettid);\n+ syscall(SYS_tkill, tid, SIGIO);\n+}\n+\nTEST_F(FcntlSignalTest, SetSigCustom) {\nconst auto signal_cleanup =\nASSERT_NO_ERRNO_AND_VALUE(RegisterSignalHandler(SIGUSR1));\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/signalfd.cc", "new_path": "test/syscalls/linux/signalfd.cc", "diff": "@@ -42,16 +42,6 @@ constexpr int kSigno = SIGUSR1;\nconstexpr int kSignoMax = 64; // SIGRTMAX\nconstexpr int kSignoAlt = SIGUSR2;\n-// Returns a new signalfd.\n-inline PosixErrorOr<FileDescriptor> NewSignalFD(sigset_t* mask, int flags = 0) {\n- int fd = signalfd(-1, mask, flags);\n- MaybeSave();\n- if (fd < 0) {\n- return PosixError(errno, \"signalfd\");\n- }\n- return FileDescriptor(fd);\n-}\n-\nclass SignalfdTest : public ::testing::TestWithParam<int> {};\nTEST_P(SignalfdTest, Basic) {\n" }, { "change_type": "MODIFY", "old_path": "test/util/BUILD", "new_path": "test/util/BUILD", "diff": "@@ -263,6 +263,7 @@ cc_library(\nhdrs = [\"signal_util.h\"],\ndeps = [\n\":cleanup\",\n+ \":file_descriptor\",\n\":posix_error\",\n\":test_util\",\ngtest,\n" }, { "change_type": "MODIFY", "old_path": "test/util/signal_util.cc", "new_path": "test/util/signal_util.cc", "diff": "#include \"test/util/signal_util.h\"\n#include <signal.h>\n+#include <sys/signalfd.h>\n#include <ostream>\n@@ -100,5 +101,15 @@ PosixErrorOr<Cleanup> ScopedSignalMask(int how, sigset_t const& set) {\n});\n}\n+// Returns a new signalfd.\n+PosixErrorOr<FileDescriptor> NewSignalFD(sigset_t* mask, int flags) {\n+ int fd = signalfd(-1, mask, flags);\n+ MaybeSave();\n+ if (fd < 0) {\n+ return PosixError(errno, \"signalfd\");\n+ }\n+ return FileDescriptor(fd);\n+}\n+\n} // namespace testing\n} // namespace gvisor\n" }, { "change_type": "MODIFY", "old_path": "test/util/signal_util.h", "new_path": "test/util/signal_util.h", "diff": "#include \"gmock/gmock.h\"\n#include \"test/util/cleanup.h\"\n+#include \"test/util/file_descriptor.h\"\n#include \"test/util/posix_error.h\"\n// Format a sigset_t as a comma separated list of numeric ranges.\n@@ -101,6 +102,9 @@ inline void FixupFault(ucontext_t* ctx) {\n}\n#endif\n+// Wrapper around signalfd(2) that returns a FileDescriptor.\n+PosixErrorOr<FileDescriptor> NewSignalFD(sigset_t* mask, int flags = 0);\n+\n} // namespace testing\n} // namespace gvisor\n" } ]
Go
Apache License 2.0
google/gvisor
Disable fasync for signalfd descriptors In Linux, signalfd doesn't support fasync events. Reported-by: syzbot+eeb463868529314bd733@syzkaller.appspotmail.com PiperOrigin-RevId: 483861398
259,907
27.10.2022 10:43:31
25,200
32e4a28deaafa64209d54ec67984dc727194059e
Update docs to reference LISAFS instead of 9P.
[ { "change_type": "MODIFY", "old_path": "g3doc/user_guide/filesystem.md", "new_path": "g3doc/user_guide/filesystem.md", "diff": "gVisor accesses the filesystem through a file proxy, called the Gofer. The gofer\nruns as a separate process, that is isolated from the sandbox. Gofer instances\n-communicate with their respective sentry using the 9P protocol.\n+communicate with their respective sentry using the LISAFS protocol.\nConfiguring the filesystem provides performance benefits, but isn't the only\nstep to optimizing gVisor performance. See the [Production guide] for more.\n" }, { "change_type": "MODIFY", "old_path": "runsc/boot/vfs.go", "new_path": "runsc/boot/vfs.go", "diff": "@@ -412,7 +412,7 @@ func (c *containerMounter) createMountNamespace(ctx context.Context, conf *confi\n// Configure the gofer dentry cache size.\ngofer.SetDentryCacheSize(conf.DCache)\n- log.Infof(\"Mounting root over 9P, ioFD: %d\", fd)\n+ log.Infof(\"Mounting root with gofer, ioFD: %d\", fd)\nopts := &vfs.MountOptions{\nReadOnly: c.root.Readonly,\nGetFilesystemOptions: vfs.GetFilesystemOptions{\n@@ -709,7 +709,7 @@ func (c *containerMounter) getMountNameAndOptions(conf *config.Config, m *mountA\nif m.fd == 0 {\n// Check that an FD was provided to fails fast. Technically FD=0 is valid,\n// but unlikely to be correct in this context.\n- return \"\", nil, false, fmt.Errorf(\"9P mount requires a connection FD\")\n+ return \"\", nil, false, fmt.Errorf(\"gofer mount requires a connection FD\")\n}\ndata = goferMountData(m.fd, c.getMountAccessType(conf, m.mount), conf.Lisafs)\ninternalData = gofer.InternalFilesystemOptions{\n" }, { "change_type": "MODIFY", "old_path": "runsc/cmd/boot.go", "new_path": "runsc/cmd/boot.go", "diff": "@@ -133,7 +133,7 @@ func (b *Boot) SetFlags(f *flag.FlagSet) {\nf.IntVar(&b.specFD, \"spec-fd\", -1, \"required fd with the container spec\")\nf.IntVar(&b.controllerFD, \"controller-fd\", -1, \"required FD of a stream socket for the control server that must be donated to this process\")\nf.IntVar(&b.deviceFD, \"device-fd\", -1, \"FD for the platform device file\")\n- f.Var(&b.ioFDs, \"io-fds\", \"list of FDs to connect 9P clients. They must follow this order: root first, then mounts as defined in the spec\")\n+ f.Var(&b.ioFDs, \"io-fds\", \"list of FDs to connect gofer clients. They must follow this order: root first, then mounts as defined in the spec\")\nf.Var(&b.stdioFDs, \"stdio-fds\", \"list of FDs containing sandbox stdin, stdout, and stderr in that order\")\nf.IntVar(&b.userLogFD, \"user-log-fd\", 0, \"file descriptor to write user logs to. 0 means no logging.\")\nf.IntVar(&b.startSyncFD, \"start-sync-fd\", -1, \"required FD to used to synchronize sandbox startup\")\n" }, { "change_type": "MODIFY", "old_path": "runsc/sandbox/sandbox.go", "new_path": "runsc/sandbox/sandbox.go", "diff": "@@ -151,9 +151,9 @@ type Args struct {\n// UserLog is the filename to send user-visible logs to. It may be empty.\nUserLog string\n- // IOFiles is the list of files that connect to a 9P endpoint for the mounts\n- // points using Gofers. They must be in the same order as mounts appear in\n- // the spec.\n+ // IOFiles is the list of files that connect to a gofer endpoint for the\n+ // mounts points using Gofers. They must be in the same order as mounts\n+ // appear in the spec.\nIOFiles []*os.File\n// MountsFile is a file container mount information from the spec. It's\n" } ]
Go
Apache License 2.0
google/gvisor
Update docs to reference LISAFS instead of 9P. PiperOrigin-RevId: 484293317
259,985
27.10.2022 14:55:21
25,200
a1468b7a6240a1a99d448b557c64a47e49e4f45a
Let caller specify mount flags and the root dentry on CloneMount.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/mount.go", "new_path": "pkg/sentry/vfs/mount.go", "diff": "@@ -371,7 +371,7 @@ func (vfs *VirtualFilesystem) preparePropagationTree(mnt *Mount, vd VirtualDentr\ndentry: vd.dentry,\n}\npeerVd.IncRef()\n- clone := vfs.cloneMount(mnt, mnt.root)\n+ clone := vfs.cloneMount(mnt, mnt.root, nil)\ntree[clone] = peerVd\nnewPeerGroup = append(newPeerGroup, clone)\n}\n@@ -391,8 +391,10 @@ func (vfs *VirtualFilesystem) commitPropagationTree(ctx context.Context, tree ma\nvfs.mounts.seq.BeginWrite()\nfor mnt, vd := range tree {\nvd.dentry.mu.Lock()\n- mntns := vd.mount.ns\n+ // If mnt isn't connected yet, skip connecting during propagation.\n+ if mntns := vd.mount.ns; mntns != nil {\nvfs.connectLocked(mnt, vd, mntns)\n+ }\nvd.dentry.mu.Unlock()\nmnt.DecRef(ctx)\n}\n@@ -503,12 +505,14 @@ func (vfs *VirtualFilesystem) SetMountPropagation(mnt *Mount, propType Propagati\nmnt.propType = propType\n}\n-// CloneMount returns a new mount with the same fs and root. If mnt's\n-// propagation type is shared the new mount is automatically made a peer of mnt.\n-func (vfs *VirtualFilesystem) CloneMount(mnt *Mount) *Mount {\n+// CloneMountAt returns a new mount with the same fs, specified root and\n+// mount options. If mnt's propagation type is shared the new mount is\n+// automatically made a peer of mnt. If mount options are nil, mnt's\n+// options are copied.\n+func (vfs *VirtualFilesystem) CloneMountAt(mnt *Mount, root *Dentry, mopts *MountOptions) *Mount {\nvfs.mountMu.Lock()\ndefer vfs.mountMu.Unlock()\n- clone := vfs.cloneMount(mnt, mnt.root)\n+ clone := vfs.cloneMount(mnt, root, mopts)\nvfs.addPeer(mnt, clone)\nreturn clone\n}\n@@ -518,12 +522,15 @@ func (vfs *VirtualFilesystem) CloneMount(mnt *Mount) *Mount {\n//\n// +checklocks:vfs.mountMu\n// +checklocksalias:mnt.vfs.mountMu=vfs.mountMu\n-func (vfs *VirtualFilesystem) cloneMount(mnt *Mount, root *Dentry) *Mount {\n- opts := MountOptions{\n+func (vfs *VirtualFilesystem) cloneMount(mnt *Mount, root *Dentry, mopts *MountOptions) *Mount {\n+ opts := mopts\n+ if opts == nil {\n+ opts = &MountOptions{\nFlags: mnt.Flags,\nReadOnly: mnt.ReadOnly(),\n}\n- return vfs.NewDisconnectedMount(mnt.fs, root, &opts)\n+ }\n+ return vfs.NewDisconnectedMount(mnt.fs, root, opts)\n}\n// BindAt creates a clone of the source path's parent mount and mounts it at\n@@ -544,7 +551,7 @@ func (vfs *VirtualFilesystem) BindAt(ctx context.Context, creds *auth.Credential\nvfs.mountMu.Lock()\ndefer vfs.mountMu.Unlock()\n- clone := vfs.cloneMount(sourceVd.mount, sourceVd.dentry)\n+ clone := vfs.cloneMount(sourceVd.mount, sourceVd.dentry, nil)\ndefer clone.DecRef(ctx)\ntree := vfs.preparePropagationTree(clone, targetVd)\nif sourceVd.mount.propType == Shared {\n" } ]
Go
Apache License 2.0
google/gvisor
Let caller specify mount flags and the root dentry on CloneMount. PiperOrigin-RevId: 484356760
259,909
28.10.2022 14:57:55
25,200
6b3b5493d0ea8eebcbe707ec1c3aac9374892d7a
Fix ipv6 header view ownership. During ipv6 header processing, the packet can be released and switched to a different fragment, but we still hold the same ipv6 header bytes from the released packet. This causes a use-after-free.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/BUILD", "new_path": "pkg/tcpip/network/ipv6/BUILD", "diff": "@@ -42,6 +42,7 @@ go_test(\n\"//pkg/bufferv2\",\n\"//pkg/refs\",\n\"//pkg/refsvfs2\",\n+ \"//pkg/sync\",\n\"//pkg/tcpip\",\n\"//pkg/tcpip/checker\",\n\"//pkg/tcpip/checksum\",\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/ipv6.go", "new_path": "pkg/tcpip/network/ipv6/ipv6.go", "diff": "@@ -1046,11 +1046,13 @@ func (e *endpoint) HandlePacket(pkt stack.PacketBufferPtr) {\nreturn\n}\n- h, ok := e.protocol.parseAndValidate(pkt)\n+ hView, ok := e.protocol.parseAndValidate(pkt)\nif !ok {\nstats.MalformedPacketsReceived.Increment()\nreturn\n}\n+ defer hView.Release()\n+ h := header.IPv6(hView.AsSlice())\nif !e.nic.IsLoopback() {\nif !e.protocol.options.AllowExternalLoopbackTraffic {\n@@ -1101,11 +1103,13 @@ func (e *endpoint) handleLocalPacket(pkt stack.PacketBufferPtr, canSkipRXChecksu\ndefer pkt.DecRef()\npkt.RXTransportChecksumValidated = canSkipRXChecksum\n- h, ok := e.protocol.parseAndValidate(pkt)\n+ hView, ok := e.protocol.parseAndValidate(pkt)\nif !ok {\nstats.MalformedPacketsReceived.Increment()\nreturn\n}\n+ defer hView.Release()\n+ h := header.IPv6(hView.AsSlice())\ne.handleValidatedPacket(h, pkt, e.nic.Name() /* inNICName */)\n}\n@@ -2537,19 +2541,22 @@ func (p *protocol) forwardPendingMulticastPacket(pkt stack.PacketBufferPtr, inst\nfunc (*protocol) Wait() {}\n// parseAndValidate parses the packet (including its transport layer header) and\n-// returns the parsed IP header.\n+// returns a view containing the parsed IP header. The caller is responsible\n+// for releasing the returned View.\n//\n// Returns true if the IP header was successfully parsed.\n-func (p *protocol) parseAndValidate(pkt stack.PacketBufferPtr) (header.IPv6, bool) {\n+func (p *protocol) parseAndValidate(pkt stack.PacketBufferPtr) (*bufferv2.View, bool) {\ntransProtoNum, hasTransportHdr, ok := p.Parse(pkt)\nif !ok {\nreturn nil, false\n}\n- h := header.IPv6(pkt.NetworkHeader().Slice())\n+ hView := pkt.NetworkHeader().View()\n+ h := header.IPv6(hView.AsSlice())\n// Do not include the link header's size when calculating the size of the IP\n// packet.\nif !h.IsValid(pkt.Size() - len(pkt.LinkHeader().Slice())) {\n+ hView.Release()\nreturn nil, false\n}\n@@ -2557,7 +2564,7 @@ func (p *protocol) parseAndValidate(pkt stack.PacketBufferPtr) (header.IPv6, boo\np.parseTransport(pkt, transProtoNum)\n}\n- return h, true\n+ return hView, true\n}\nfunc (p *protocol) parseTransport(pkt stack.PacketBufferPtr, transProtoNum tcpip.TransportProtocolNumber) {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/ipv6_test.go", "new_path": "pkg/tcpip/network/ipv6/ipv6_test.go", "diff": "@@ -26,6 +26,7 @@ import (\n\"github.com/google/go-cmp/cmp\"\n\"gvisor.dev/gvisor/pkg/bufferv2\"\n+ \"gvisor.dev/gvisor/pkg/sync\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/checker\"\n\"gvisor.dev/gvisor/pkg/tcpip/checksum\"\n@@ -1109,22 +1110,7 @@ type fragmentData struct {\ndata []byte\n}\n-func TestReceiveIPv6Fragments(t *testing.T) {\n- const (\n- udpPayload1Length = 256\n- udpPayload2Length = 128\n- // Used to test cases where the fragment blocks are not a multiple of\n- // the fragment block size of 8 (RFC 8200 section 4.5).\n- udpPayload3Length = 127\n- udpPayload4Length = header.IPv6MaximumPayloadSize - header.UDPMinimumSize\n- udpMaximumSizeMinus15 = header.UDPMaximumSize - 15\n- fragmentExtHdrLen = 8\n- // Note, not all routing extension headers will be 8 bytes but this test\n- // uses 8 byte routing extension headers for most sub tests.\n- routingExtHdrLen = 8\n- )\n-\n- udpGen := func(payload []byte, multiplier uint8, src, dst tcpip.Address) []byte {\n+func udpGen(payload []byte, multiplier uint8, src, dst tcpip.Address) []byte {\npayloadLen := len(payload)\nfor i := 0; i < payloadLen; i++ {\npayload[i] = uint8(i) * multiplier\n@@ -1146,6 +1132,21 @@ func TestReceiveIPv6Fragments(t *testing.T) {\nreturn hdr.View()\n}\n+func TestReceiveIPv6Fragments(t *testing.T) {\n+ const (\n+ udpPayload1Length = 256\n+ udpPayload2Length = 128\n+ // Used to test cases where the fragment blocks are not a multiple of\n+ // the fragment block size of 8 (RFC 8200 section 4.5).\n+ udpPayload3Length = 127\n+ udpPayload4Length = header.IPv6MaximumPayloadSize - header.UDPMinimumSize\n+ udpMaximumSizeMinus15 = header.UDPMaximumSize - 15\n+ fragmentExtHdrLen = 8\n+ // Note, not all routing extension headers will be 8 bytes but this test\n+ // uses 8 byte routing extension headers for most sub tests.\n+ routingExtHdrLen = 8\n+ )\n+\nvar udpPayload1Addr1ToAddr2Buf [udpPayload1Length]byte\nudpPayload1Addr1ToAddr2 := udpPayload1Addr1ToAddr2Buf[:]\nipv6Payload1Addr1ToAddr2 := udpGen(udpPayload1Addr1ToAddr2, 1, addr1, addr2)\n@@ -1936,6 +1937,124 @@ func TestReceiveIPv6Fragments(t *testing.T) {\n}\n}\n+func TestConcurrentFragmentWrites(t *testing.T) {\n+ const udpPayload1Length = 256\n+ const udpPayload2Length = 128\n+ var udpPayload1Addr1ToAddr2Buf [udpPayload1Length]byte\n+ udpPayload1Addr1ToAddr2 := udpPayload1Addr1ToAddr2Buf[:]\n+ ipv6Payload1Addr1ToAddr2 := udpGen(udpPayload1Addr1ToAddr2, 1, addr1, addr2)\n+\n+ var udpPayload2Addr1ToAddr2Buf [udpPayload2Length]byte\n+ udpPayload2Addr1ToAddr2 := udpPayload2Addr1ToAddr2Buf[:]\n+ ipv6Payload2Addr1ToAddr2 := udpGen(udpPayload2Addr1ToAddr2, 2, addr1, addr2)\n+\n+ fragments := []fragmentData{\n+ {\n+ srcAddr: addr1,\n+ dstAddr: addr2,\n+ nextHdr: fragmentExtHdrID,\n+ data: append(\n+ // Fragment extension header.\n+ //\n+ // Fragment offset = 0, More = true, ID = 1\n+ []byte{uint8(header.UDPProtocolNumber), 0, 0, 1, 0, 0, 0, 1},\n+ ipv6Payload1Addr1ToAddr2[:64]...,\n+ ),\n+ },\n+ {\n+ srcAddr: addr1,\n+ dstAddr: addr2,\n+ nextHdr: fragmentExtHdrID,\n+ data: append(\n+ // Fragment extension header.\n+ //\n+ // Fragment offset = 0, More = true, ID = 2\n+ []byte{uint8(header.UDPProtocolNumber), 0, 0, 1, 0, 0, 0, 2},\n+ ipv6Payload2Addr1ToAddr2[:32]...,\n+ ),\n+ },\n+ {\n+ srcAddr: addr1,\n+ dstAddr: addr2,\n+ nextHdr: fragmentExtHdrID,\n+ data: append(\n+ // Fragment extension header.\n+ //\n+ // Fragment offset = 8, More = false, ID = 1\n+ []byte{uint8(header.UDPProtocolNumber), 0, 0, 64, 0, 0, 0, 1},\n+ ipv6Payload1Addr1ToAddr2[64:]...,\n+ ),\n+ },\n+ }\n+\n+ c := newTestContext()\n+ defer c.cleanup()\n+ s := c.s\n+\n+ e := channel.New(0, header.IPv6MinimumMTU, linkAddr1)\n+ defer e.Close()\n+ if err := s.CreateNIC(nicID, e); err != nil {\n+ t.Fatalf(\"CreateNIC(%d, _) = %s\", nicID, err)\n+ }\n+ protocolAddr := tcpip.ProtocolAddress{\n+ Protocol: ProtocolNumber,\n+ AddressWithPrefix: addr2.WithPrefix(),\n+ }\n+ if err := s.AddProtocolAddress(nicID, protocolAddr, stack.AddressProperties{}); err != nil {\n+ t.Fatalf(\"AddProtocolAddress(%d, %+v, {}): %s\", nicID, protocolAddr, err)\n+ }\n+\n+ wq := waiter.Queue{}\n+ we, ch := waiter.NewChannelEntry(waiter.ReadableEvents)\n+ wq.EventRegister(&we)\n+ defer wq.EventUnregister(&we)\n+ defer close(ch)\n+ ep, err := s.NewEndpoint(udp.ProtocolNumber, ProtocolNumber, &wq)\n+ if err != nil {\n+ t.Fatalf(\"NewEndpoint(%d, %d, _): %s\", udp.ProtocolNumber, ProtocolNumber, err)\n+ }\n+ defer ep.Close()\n+\n+ bindAddr := tcpip.FullAddress{Addr: addr2, Port: 80}\n+ if err := ep.Bind(bindAddr); err != nil {\n+ t.Fatalf(\"Bind(%+v): %s\", bindAddr, err)\n+ }\n+\n+ var wg sync.WaitGroup\n+ defer wg.Wait()\n+ for i := 0; i < 3; i++ {\n+ wg.Add(1)\n+ go func() {\n+ defer wg.Done()\n+ for i := 0; i < 10; i++ {\n+ for _, f := range fragments {\n+ hdr := prependable.New(header.IPv6MinimumSize)\n+\n+ // Serialize IPv6 fixed header.\n+ ip := header.IPv6(hdr.Prepend(header.IPv6MinimumSize))\n+ ip.Encode(&header.IPv6Fields{\n+ PayloadLength: uint16(len(f.data)),\n+ // We're lying about transport protocol here so that we can generate\n+ // raw extension headers for the tests.\n+ TransportProtocol: tcpip.TransportProtocolNumber(f.nextHdr),\n+ HopLimit: 255,\n+ SrcAddr: f.srcAddr,\n+ DstAddr: f.dstAddr,\n+ })\n+\n+ buf := bufferv2.MakeWithData(hdr.View())\n+ buf.Append(bufferv2.NewViewWithData(f.data))\n+ pkt := stack.NewPacketBuffer(stack.PacketBufferOptions{\n+ Payload: buf,\n+ })\n+ e.InjectInbound(ProtocolNumber, pkt)\n+ pkt.DecRef()\n+ }\n+ }\n+ }()\n+ }\n+}\n+\nfunc TestInvalidIPv6Fragments(t *testing.T) {\nconst (\naddr1 = tcpip.Address(\"\\x0a\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\")\n" } ]
Go
Apache License 2.0
google/gvisor
Fix ipv6 header view ownership. During ipv6 header processing, the packet can be released and switched to a different fragment, but we still hold the same ipv6 header bytes from the released packet. This causes a use-after-free. PiperOrigin-RevId: 484627475
259,909
31.10.2022 14:51:31
25,200
20ef2127a1028363df8d056a7143c4d263544763
Lock around optional tag generation. Reported-by:
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/mount.go", "new_path": "pkg/sentry/vfs/mount.go", "diff": "@@ -179,6 +179,17 @@ func (mnt *Mount) Options() MountOptions {\n}\n}\n+func (mnt *Mount) generateOptionalTags() string {\n+ mnt.vfs.mountMu.Lock()\n+ defer mnt.vfs.mountMu.Unlock()\n+ // TODO(b/249777195): Support MS_SLAVE and MS_UNBINDABLE propagation types.\n+ var optional string\n+ if mnt.propType == Shared {\n+ optional = fmt.Sprintf(\"shared:%d\", mnt.groupID)\n+ }\n+ return optional\n+}\n+\n// addPeer adds oth to mnt's peer group. Both will have the same groupID\n// and sharedList. vfs.mountMu must be locked.\n//\n@@ -1326,7 +1337,7 @@ func (vfs *VirtualFilesystem) GenerateProcMountInfo(ctx context.Context, taskRoo\nif path == \"\" {\n// Either an error occurred, or path is not reachable\n// from root.\n- break\n+ continue\n}\n// Stat the mount root to get the major/minor device numbers.\npop := &PathOperation{\n@@ -1337,7 +1348,7 @@ func (vfs *VirtualFilesystem) GenerateProcMountInfo(ctx context.Context, taskRoo\nif err != nil {\n// Well that's not good. Ignore this mount.\nctx.Warningf(\"VFS.GenerateProcMountInfo: failed to stat mount root %+v: %v\", mnt.root, err)\n- break\n+ continue\n}\n// Format:\n@@ -1385,9 +1396,7 @@ func (vfs *VirtualFilesystem) GenerateProcMountInfo(ctx context.Context, taskRoo\nfmt.Fprintf(buf, \"%s \", opts)\n// (7) Optional fields: zero or more fields of the form \"tag[:value]\".\n- if mnt.propType == Shared {\n- fmt.Fprintf(buf, \"shared:%d \", mnt.groupID)\n- }\n+ fmt.Fprintf(buf, \"%s \", mnt.generateOptionalTags())\n// (8) Separator: the end of the optional fields is marked by a single hyphen.\nfmt.Fprintf(buf, \"- \")\n" } ]
Go
Apache License 2.0
google/gvisor
Lock around optional tag generation. Reported-by: syzbot+339e76d7c2c84cbd70c9@syzkaller.appspotmail.com PiperOrigin-RevId: 485155018
259,985
31.10.2022 22:32:10
25,200
d4b159ae93b57be0e9f296b8f0030005175de774
iouring: Disallow zero, or less CQ entries than SQ entries Reported-by:
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/iouringfs/iouringfs.go", "new_path": "pkg/sentry/fsimpl/iouringfs/iouringfs.go", "diff": "@@ -92,10 +92,11 @@ func New(ctx context.Context, vfsObj *vfs.VirtualFilesystem, entries uint32, par\n}\nvar numCqEntries uint32\nif params.Flags&linux.IORING_SETUP_CQSIZE != 0 {\n- if params.CqEntries > linux.IORING_MAX_CQ_ENTRIES {\n+ var ok bool\n+ numCqEntries, ok = roundUpPowerOfTwo(params.CqEntries)\n+ if !ok || numCqEntries < numSqEntries || numCqEntries > linux.IORING_SETUP_CQSIZE {\nreturn nil, linuxerr.EINVAL\n}\n- numCqEntries = params.CqEntries\n} else {\nnumCqEntries = 2 * numSqEntries\n}\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/io_uring.cc", "new_path": "test/syscalls/linux/io_uring.cc", "diff": "@@ -52,6 +52,20 @@ TEST(IOUringTest, ParamsNonZeroResv) {\nASSERT_THAT(IOUringSetup(1, &params), SyscallFailsWithErrno(EINVAL));\n}\n+TEST(IOUringTest, ZeroCQEntries) {\n+ IOUringParams params;\n+ params.cq_entries = 0;\n+ params.flags = IORING_SETUP_CQSIZE;\n+ ASSERT_THAT(IOUringSetup(1, &params), SyscallFailsWithErrno(EINVAL));\n+}\n+\n+TEST(IOUringTest, ZeroCQEntriesLessThanSQEntries) {\n+ IOUringParams params;\n+ params.cq_entries = 16;\n+ params.flags = IORING_SETUP_CQSIZE;\n+ ASSERT_THAT(IOUringSetup(32, &params), SyscallFailsWithErrno(EINVAL));\n+}\n+\n// Testing that io_uring_setup(2) fails with EINVAL on unsupported flags.\nTEST(IOUringTest, UnsupportedFlags) {\nif (IsRunningOnGvisor()) {\n" }, { "change_type": "MODIFY", "old_path": "test/util/io_uring_util.h", "new_path": "test/util/io_uring_util.h", "diff": "@@ -34,6 +34,7 @@ namespace testing {\n// io_uring_setup(2) flags.\n#define IORING_SETUP_SQPOLL (1U << 1)\n+#define IORING_SETUP_CQSIZE (1U << 3)\n#define IORING_FEAT_SINGLE_MMAP (1U << 0)\n" } ]
Go
Apache License 2.0
google/gvisor
iouring: Disallow zero, or less CQ entries than SQ entries Reported-by: syzbot+ad039a9d567cc9ba5ea8@syzkaller.appspotmail.com PiperOrigin-RevId: 485230763
259,985
02.11.2022 09:41:49
25,200
254fedb1d69c02162b19c65219243098eeac0b1b
tmpfs: Handle symlink resolution at root Previously we weren't resolving any links when walking a single component path (i.e. the root of the FS was a symlink).
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/tmpfs/filesystem.go", "new_path": "pkg/sentry/fsimpl/tmpfs/filesystem.go", "diff": "@@ -133,6 +133,18 @@ func walkParentDirLocked(ctx context.Context, rp *vfs.ResolvingPath, d *dentry)\n// Preconditions: filesystem.mu must be locked.\nfunc resolveLocked(ctx context.Context, rp *vfs.ResolvingPath) (*dentry, error) {\nd := rp.Start().Impl().(*dentry)\n+\n+ if symlink, ok := d.inode.impl.(*symlink); rp.Done() && ok && rp.ShouldFollowSymlink() {\n+ // Path with a single component. We don't need to step to the next\n+ // component, but still need to resolve any symlinks.\n+ //\n+ // Symlink traversal updates access time.\n+ d.inode.touchAtime(rp.Mount())\n+ if err := rp.HandleSymlink(symlink.target); err != nil {\n+ return nil, err\n+ }\n+ } else {\n+ // Path with multiple components, walk and resolve as required.\nfor !rp.Done() {\nnext, err := stepLocked(ctx, rp, d)\nif err != nil {\n@@ -140,6 +152,8 @@ func resolveLocked(ctx context.Context, rp *vfs.ResolvingPath) (*dentry, error)\n}\nd = next\n}\n+ }\n+\nif rp.MustBeDir() && !d.inode.isDir() {\nreturn nil, linuxerr.ENOTDIR\n}\n" } ]
Go
Apache License 2.0
google/gvisor
tmpfs: Handle symlink resolution at root Previously we weren't resolving any links when walking a single component path (i.e. the root of the FS was a symlink). PiperOrigin-RevId: 485618692
259,975
02.11.2022 16:53:19
25,200
af8fcbe7cdd2af71967d5f06c85f16620af528f3
Add ARM64 image for grpc-build benchmark.
[ { "change_type": "ADD", "old_path": null, "new_path": "images/benchmarks/build-grpc/Dockerfile.aarch64", "diff": "+FROM ubuntu:18.04\n+\n+RUN set -x \\\n+ && apt-get update \\\n+ && apt-get install -y \\\n+ autoconf \\\n+ build-essential \\\n+ clang \\\n+ curl \\\n+ libtool \\\n+ pkg-config \\\n+ git \\\n+ unzip \\\n+ wget \\\n+ && rm -rf /var/lib/apt/lists/*\n+\n+RUN wget https://github.com/bazelbuild/bazel/releases/download/4.2.1/bazel-4.2.1-linux-arm64\n+RUN mv bazel-4.2.1-linux-arm64 /bin/bazel && chmod +x /bin/bazel\n+\n+RUN mkdir grpc && cd grpc \\\n+ && git init && git remote add origin https://github.com/grpc/grpc.git \\\n+ && git fetch --depth 1 origin a672e22bd1e10b3ff2a91aaae5aee3a65cc95bfe && git checkout FETCH_HEAD\n" } ]
Go
Apache License 2.0
google/gvisor
Add ARM64 image for grpc-build benchmark. PiperOrigin-RevId: 485730449
259,992
03.11.2022 13:37:12
25,200
b322d1cc5bde68711e2c8e69fbf0ded7a6a5c898
Fix EPERM with OCI quick start Fixes
[ { "change_type": "MODIFY", "old_path": "g3doc/user_guide/quick_start/oci.md", "new_path": "g3doc/user_guide/quick_start/oci.md", "diff": "@@ -19,8 +19,8 @@ Create a root file system for the container. We will use the Docker\n`hello-world` image as the basis for our container.\n```bash\n-mkdir rootfs\n-docker export $(docker create hello-world) | tar -xf - -C rootfs\n+mkdir --mode=0755 rootfs\n+docker export $(docker create hello-world) | sudo tar -xf - -C rootfs --same-owner --same-permissions\n```\nNext, create an specification file called `config.json` that contains our\n" } ]
Go
Apache License 2.0
google/gvisor
Fix EPERM with OCI quick start Fixes #8106 PiperOrigin-RevId: 485960462
259,853
03.11.2022 13:48:25
25,200
1497cdffce1fb35179c7da064ba654029ce6f859
Add the context.PrepareSleep platform callback. It is called only when a task switches to the interruptible sleep, because it is the only state where the task can sleep for a long time.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/task_block.go", "new_path": "pkg/sentry/kernel/task_block.go", "diff": "@@ -189,6 +189,7 @@ func (t *Task) block(C <-chan struct{}, timerChan <-chan struct{}) error {\n// prepareSleep prepares to sleep.\nfunc (t *Task) prepareSleep() {\nt.assertTaskGoroutine()\n+ t.p.PrepareSleep()\nt.Deactivate()\nt.accountTaskGoroutineEnter(TaskGoroutineBlockedInterruptible)\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/kvm/context.go", "new_path": "pkg/sentry/platform/kvm/context.go", "diff": "@@ -126,3 +126,6 @@ func (c *context) FullStateChanged() {}\n// PullFullState implements platform.Context.PullFullState.\nfunc (c *context) PullFullState(as platform.AddressSpace, ac *arch.Context64) {}\n+\n+// PrepareSleep implements platform.Context.platform.Context.\n+func (*context) PrepareSleep() {}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/platform.go", "new_path": "pkg/sentry/platform/platform.go", "diff": "@@ -244,6 +244,10 @@ type Context interface {\n// Release() releases any resources associated with this context.\nRelease()\n+\n+ // PrepareSleep() is called when the tread switches to the\n+ // interruptible sleep state.\n+ PrepareSleep()\n}\nvar (\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/ptrace/ptrace.go", "new_path": "pkg/sentry/platform/ptrace/ptrace.go", "diff": "@@ -199,6 +199,9 @@ func (c *context) FullStateChanged() {}\n// PullFullState implements platform.Context.PullFullState.\nfunc (c *context) PullFullState(as platform.AddressSpace, ac *arch.Context64) {}\n+// PrepareSleep implements platform.Context.platform.PrepareSleep.\n+func (*context) PrepareSleep() {}\n+\n// PTrace represents a collection of ptrace subprocesses.\ntype PTrace struct {\nplatform.MMapMinAddr\n" } ]
Go
Apache License 2.0
google/gvisor
Add the context.PrepareSleep platform callback. It is called only when a task switches to the interruptible sleep, because it is the only state where the task can sleep for a long time. PiperOrigin-RevId: 485963460
259,992
03.11.2022 16:09:25
25,200
943eb50b0aecb8e0315449a537ce5962bb82a4af
Allow trace tests to run remotely
[ { "change_type": "MODIFY", "old_path": "test/trace/BUILD", "new_path": "test/trace/BUILD", "diff": "@@ -11,9 +11,6 @@ go_test(\n\"//test/trace/workload\",\n],\nlibrary = \":trace\",\n- tags = [\n- \"local\",\n- ],\ndeps = [\n\"//pkg/sentry/seccheck\",\n\"//pkg/sentry/seccheck/points:points_go_proto\",\n" }, { "change_type": "MODIFY", "old_path": "test/trace/trace_test.go", "new_path": "test/trace/trace_test.go", "diff": "@@ -75,8 +75,8 @@ func TestAll(t *testing.T) {\ncutoffTime = time.Now()\ncmd := exec.Command(\nrunsc,\n- \"--debug\", \"--alsologtostderr\", // Debug logging for troubleshooting\n- \"--rootless\", \"--network=none\", // Disable features that we don't care\n+ \"--debug\", \"--strace\", \"--alsologtostderr\", // Debug logging for troubleshooting\n+ \"--rootless\", \"--network=none\", \"--TESTONLY-unsafe-nonroot\", // Disable features that we don't care\n\"--pod-init-config\", cfgFile.Name(),\n\"do\", workload)\nout, err := cmd.CombinedOutput()\n" } ]
Go
Apache License 2.0
google/gvisor
Allow trace tests to run remotely PiperOrigin-RevId: 485999272
259,992
03.11.2022 16:50:16
25,200
22a0b4acb20e40174ce4ff38cb3666a43ae72781
Allow fsgofer to open character files Closes
[ { "change_type": "MODIFY", "old_path": "Makefile", "new_path": "Makefile", "diff": "@@ -276,7 +276,7 @@ docker-tests: load-basic $(RUNTIME_BIN)\noverlay-tests: load-basic $(RUNTIME_BIN)\n@$(call install_runtime,$(RUNTIME),--overlay)\n- @$(call test_runtime,$(RUNTIME),$(INTEGRATION_TARGETS))\n+ @$(call test_runtime,$(RUNTIME),--test_env=TEST_OVERLAY=true $(INTEGRATION_TARGETS))\n.PHONY: overlay-tests\nswgso-tests: load-basic $(RUNTIME_BIN)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/gofer/special_file.go", "new_path": "pkg/sentry/fsimpl/gofer/special_file.go", "diff": "@@ -94,7 +94,7 @@ type specialFileFD struct {\nfunc newSpecialFileFD(h handle, mnt *vfs.Mount, d *dentry, flags uint32) (*specialFileFD, error) {\nftype := d.fileType()\nseekable := ftype == linux.S_IFREG || ftype == linux.S_IFCHR || ftype == linux.S_IFBLK\n- haveQueue := (ftype == linux.S_IFIFO || ftype == linux.S_IFSOCK) && h.fd >= 0\n+ haveQueue := (ftype == linux.S_IFIFO || ftype == linux.S_IFSOCK || ftype == linux.S_IFCHR) && h.fd >= 0\nfd := &specialFileFD{\nhandle: h,\nisRegularFile: ftype == linux.S_IFREG,\n" }, { "change_type": "MODIFY", "old_path": "pkg/test/testutil/testutil.go", "new_path": "pkg/test/testutil/testutil.go", "diff": "@@ -54,6 +54,8 @@ var (\ntotalPartitions = flag.Int(\"total_partitions\", IntFromEnv(\"TOTAL_PARTITIONS\", 1), \"total number of partitions\")\nisRunningWithHostNet = flag.Bool(\"hostnet\", BoolFromEnv(\"HOSTNET\", false), \"whether test is running with hostnet\")\nrunscPath = flag.String(\"runsc\", os.Getenv(\"RUNTIME\"), \"path to runsc binary\")\n+ // Note: flag overlay is already taken by runsc.\n+ isRunningWithOverlay = flag.Bool(\"test-overlay\", BoolFromEnv(\"TEST_OVERLAY\", false), \"whether test is running with --overlay\")\n)\n// StringFromEnv returns the value of the named environment variable, or `def` if unset/empty.\n@@ -119,6 +121,11 @@ func IsRunningWithHostNet() bool {\nreturn *isRunningWithHostNet\n}\n+// IsRunningWithOverlay returns the relevant command line flag.\n+func IsRunningWithOverlay() bool {\n+ return *isRunningWithOverlay\n+}\n+\n// ImageByName mangles the image name used locally. This depends on the image\n// build infrastructure in images/ and tools/vm.\nfunc ImageByName(name string) string {\n" }, { "change_type": "MODIFY", "old_path": "runsc/fsgofer/fsgofer.go", "new_path": "runsc/fsgofer/fsgofer.go", "diff": "@@ -320,7 +320,7 @@ func openAnyFile(pathDebug string, fn func(mode int) (*fd.FD, error)) (*fd.FD, b\nfunc checkSupportedFileType(mode uint32, config *Config) error {\nswitch mode & unix.S_IFMT {\n- case unix.S_IFREG, unix.S_IFDIR, unix.S_IFLNK:\n+ case unix.S_IFREG, unix.S_IFDIR, unix.S_IFLNK, unix.S_IFCHR:\nreturn nil\ncase unix.S_IFSOCK:\n@@ -450,7 +450,7 @@ func (l *localFile) Open(flags p9.OpenFlags) (*fd.FD, p9.QID, uint32, error) {\n// Best effort to donate file to the Sentry (for performance only).\nfd = newFDMaybe(newFile)\n- case unix.S_IFIFO:\n+ case unix.S_IFIFO, unix.S_IFCHR:\n// Character devices and pipes can block indefinitely during reads/writes,\n// which is not allowed for gofer operations. Ensure that it donates an FD\n// back to the caller, so it can wait on the FD when reads/writes return\n" }, { "change_type": "MODIFY", "old_path": "runsc/fsgofer/lisafs.go", "new_path": "runsc/fsgofer/lisafs.go", "diff": "@@ -427,7 +427,7 @@ func (fd *controlFDLisa) Open(flags uint32) (*lisafs.OpenFD, int, error) {\n// Best effort to donate file to the Sentry (for performance only).\nhostOpenFD, _ = unix.Dup(openFD.hostFD)\n- case unix.S_IFIFO:\n+ case unix.S_IFIFO, unix.S_IFCHR:\n// Character devices and pipes can block indefinitely during reads/writes,\n// which is not allowed for gofer operations. Ensure that it donates an FD\n// back to the caller, so it can wait on the FD when reads/writes return\n" }, { "change_type": "MODIFY", "old_path": "test/e2e/integration_test.go", "new_path": "test/e2e/integration_test.go", "diff": "package integration\nimport (\n+ \"bytes\"\n\"context\"\n\"flag\"\n\"fmt\"\n@@ -997,3 +998,51 @@ func TestNonSearchableWorkingDirectory(t *testing.T) {\nt.Errorf(\"ls error message not found, want: %q, got: %q\", wantErrorMsg, got)\n}\n}\n+\n+func TestCharDevice(t *testing.T) {\n+ if testutil.IsRunningWithOverlay() {\n+ t.Skip(\"files are not available outside the sandbox with overlay.\")\n+ }\n+\n+ ctx := context.Background()\n+ d := dockerutil.MakeContainer(ctx, t)\n+ defer d.CleanUp(ctx)\n+\n+ dir, err := os.MkdirTemp(testutil.TmpDir(), \"tmp-mount\")\n+ if err != nil {\n+ t.Fatalf(\"MkdirTemp() failed: %v\", err)\n+ }\n+ defer os.RemoveAll(dir)\n+\n+ opts := dockerutil.RunOpts{\n+ Image: \"basic/alpine\",\n+ Mounts: []mount.Mount{\n+ {\n+ Type: mount.TypeBind,\n+ Source: \"/dev/zero\",\n+ Target: \"/test/zero\",\n+ },\n+ {\n+ Type: mount.TypeBind,\n+ Source: dir,\n+ Target: \"/out\",\n+ },\n+ },\n+ }\n+\n+ const size = 1024 * 1024\n+\n+ // `docker logs` encodes the string, making it hard to compare. Write the\n+ // result to a file that is available to the test.\n+ cmd := fmt.Sprintf(\"head -c %d /test/zero > /out/result\", size)\n+ if _, err := d.Run(ctx, opts, \"sh\", \"-c\", cmd); err != nil {\n+ t.Fatalf(\"docker run failed: %v\", err)\n+ }\n+ got, err := os.ReadFile(filepath.Join(dir, \"result\"))\n+ if err != nil {\n+ t.Fatal(err)\n+ }\n+ if want := [size]byte{}; !bytes.Equal(want[:], got) {\n+ t.Errorf(\"Wrong bytes, want: [all zeros], got: %v\", got)\n+ }\n+}\n" } ]
Go
Apache License 2.0
google/gvisor
Allow fsgofer to open character files Closes #7007 PiperOrigin-RevId: 486008125
259,986
04.11.2022 08:01:51
25,200
b9b96522ef2b1376add5721bb6345042d9e335c5
Increase SO_RCVTIMEO for RecvTimeoutWaitAll syscall test The timeout is currently 200ms and causes occasionally flakes in Fuchsia infra (https://fxbug.dev/112974). Increase it to 1s. Fixes
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_generic_test_cases.cc", "new_path": "test/syscalls/linux/socket_generic_test_cases.cc", "diff": "@@ -823,7 +823,7 @@ TEST_P(AllSocketPairTest, RecvTimeoutWaitAll) {\nauto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\nstruct timeval tv {\n- .tv_sec = 0, .tv_usec = 200000 // 200ms\n+ .tv_sec = 1, .tv_usec = 0\n};\nEXPECT_THAT(setsockopt(sockets->second_fd(), SOL_SOCKET, SO_RCVTIMEO, &tv,\nsizeof(tv)),\n" } ]
Go
Apache License 2.0
google/gvisor
Increase SO_RCVTIMEO for RecvTimeoutWaitAll syscall test The timeout is currently 200ms and causes occasionally flakes in Fuchsia infra (https://fxbug.dev/112974). Increase it to 1s. Fixes #8140 PiperOrigin-RevId: 486141423
259,868
04.11.2022 12:32:56
25,200
5b3d8659a0401bcea0453c17b34db7f1e29d6de6
Use `runc` as default runtime for unsandboxed containers. Without this, attempting to build or test gVisor on machines where the default runtime isn't `runc` may fail, as that runtime may not support what we need.
[ { "change_type": "MODIFY", "old_path": "Makefile", "new_path": "Makefile", "diff": "@@ -385,6 +385,7 @@ run_benchmark = \\\n($(call header,BENCHMARK $(1)); \\\nset -euo pipefail; \\\nexport T=$$(mktemp --tmpdir logs.$(1).XXXXXX); \\\n+ export UNSANDBOXED_RUNTIME; \\\nif test \"$(1)\" = \"runc\"; then $(call sudo,$(BENCHMARKS_TARGETS),-runtime=$(1) $(BENCHMARKS_ARGS)) | tee $$T; fi; \\\nif test \"$(1)\" != \"runc\"; then $(call sudo,$(BENCHMARKS_TARGETS),-runtime=$(1) $(BENCHMARKS_ARGS) $(BENCHMARKS_PROFILE)) | tee $$T; fi; \\\nif test \"$(BENCHMARKS_UPLOAD)\" = \"true\"; then \\\n" }, { "change_type": "MODIFY", "old_path": "pkg/test/dockerutil/container.go", "new_path": "pkg/test/dockerutil/container.go", "diff": "@@ -140,7 +140,11 @@ func MakeContainerWithRuntime(ctx context.Context, logger testutil.Logger, suffi\n//\n// Native containers aren't profiled.\nfunc MakeNativeContainer(ctx context.Context, logger testutil.Logger) *Container {\n- return makeContainer(ctx, logger, \"\" /*runtime*/)\n+ unsandboxedRuntime := \"runc\"\n+ if override, found := os.LookupEnv(\"UNSANDBOXED_RUNTIME\"); found {\n+ unsandboxedRuntime = override\n+ }\n+ return makeContainer(ctx, logger, unsandboxedRuntime)\n}\n// Spawn is analogous to 'docker run -d'.\n" }, { "change_type": "MODIFY", "old_path": "tools/bazel.mk", "new_path": "tools/bazel.mk", "diff": "## DOCKER_NAME - The container name (default: gvisor-bazel-HASH).\n## DOCKER_HOSTNAME - The container name (default: same as DOCKER_NAME).\n## DOCKER_PRIVILEGED - Docker privileged flags (default: --privileged).\n+## UNSANDBOXED_RUNTIME - Name of the Docker runtime to use for the\n+## unsandboxed build container. Defaults to runc.\n## PRE_BAZEL_INIT - If set, run this command with bash outside the Bazel\n## server container.\n## BAZEL_CACHE - The bazel cache directory (default: detected).\n@@ -55,6 +57,7 @@ BUILDER_HOSTNAME := $(BUILDER_NAME)\nDOCKER_NAME := gvisor-bazel-$(HASH)-$(ARCH)\nDOCKER_HOSTNAME := $(DOCKER_NAME)\nDOCKER_PRIVILEGED := --privileged\n+UNSANDBOXED_RUNTIME ?= runc\nBAZEL_CACHE := $(HOME)/.cache/bazel/\nGCLOUD_CONFIG := $(HOME)/.config/gcloud/\nDOCKER_SOCKET := /var/run/docker.sock\n@@ -71,7 +74,7 @@ PRE_BAZEL_INIT ?=\n## STARTUP_OPTIONS - Startup options passed to Bazel.\n##\nSTARTUP_OPTIONS :=\n-BAZEL_OPTIONS :=\n+BAZEL_OPTIONS ?=\nBAZEL := bazel $(STARTUP_OPTIONS)\nBASE_OPTIONS := --color=no --curses=no\nTEST_OPTIONS += $(BASE_OPTIONS) \\\n@@ -89,6 +92,9 @@ DOCKER_RUN_OPTIONS += --rm\nDOCKER_RUN_OPTIONS += --user $(UID):$(GID)\nDOCKER_RUN_OPTIONS += --entrypoint \"\"\nDOCKER_RUN_OPTIONS += --init\n+ifneq (,$(UNSANDBOXED_RUNTIME))\n+DOCKER_RUN_OPTIONS += --runtime=$(UNSANDBOXED_RUNTIME)\n+endif\nDOCKER_RUN_OPTIONS += -v \"$(shell realpath -m $(BAZEL_CACHE)):$(BAZEL_CACHE)\"\nDOCKER_RUN_OPTIONS += -v \"$(shell realpath -m $(GCLOUD_CONFIG)):$(GCLOUD_CONFIG)\"\nDOCKER_RUN_OPTIONS += -v \"/tmp:/tmp\"\n@@ -214,6 +220,7 @@ bazel-image: load-default ## Ensures that the local builder exists.\n@docker rm -f $(BUILDER_NAME) 2>/dev/null || true\n@docker run --user 0:0 --entrypoint \"\" \\\n--name $(BUILDER_NAME) --hostname $(BUILDER_HOSTNAME) \\\n+ $(shell test -n \"$(UNSANDBOXED_RUNTIME)\" && echo \"--runtime=$(UNSANDBOXED_RUNTIME)\") \\\ngvisor.dev/images/default \\\nbash -c \"$(GROUPADD_DOCKER) $(USERADD_DOCKER) if test -e /dev/kvm; then chmod a+rw /dev/kvm; fi\" >&2\n@docker commit $(BUILDER_NAME) gvisor.dev/images/builder >&2\n" } ]
Go
Apache License 2.0
google/gvisor
Use `runc` as default runtime for unsandboxed containers. Without this, attempting to build or test gVisor on machines where the default runtime isn't `runc` may fail, as that runtime may not support what we need. PiperOrigin-RevId: 486205081
259,868
04.11.2022 13:07:25
25,200
8400a3d40d064deeef347cc5df47af9101cdb44a
Label all benchmarks with tag `gvisor_benchmark`. This makes it easy to list all the available benchmark targets with `bazel`.
[ { "change_type": "MODIFY", "old_path": "Makefile", "new_path": "Makefile", "diff": "@@ -347,8 +347,10 @@ containerd-tests: containerd-test-1.6.2\n## Benchmarks.\n##\n## Targets to run benchmarks. See //test/benchmarks for details.\n+## You can list all available benchmarks using:\n+## $ bazel query 'attr(\"tags\", \".*gvisor_benchmark.*\", //test/benchmarks/...)'\n##\n-## common arguments:\n+## Common arguments:\n## BENCHMARKS_PROJECT - BigQuery project to which to send data.\n## BENCHMARKS_DATASET - BigQuery dataset to which to send data.\n## BENCHMARKS_TABLE - BigQuery table to which to send data.\n@@ -361,6 +363,7 @@ containerd-tests: containerd-test-1.6.2\n## BENCHMARKS_FILTER - filter to be applied to the test suite.\n## BENCHMARKS_OPTIONS - options to be passed to the test.\n## BENCHMARKS_PROFILE - profile options to be passed to the test.\n+## Set to the empty string to avoid profiling overhead.\n##\nBENCHMARKS_PROJECT ?= gvisor-benchmarks\nBENCHMARKS_DATASET ?= kokoro\n" }, { "change_type": "MODIFY", "old_path": "test/benchmarks/defs.bzl", "new_path": "test/benchmarks/defs.bzl", "diff": "@@ -9,6 +9,7 @@ def benchmark_test(name, tags = [], **kwargs):\n# Requires docker and runsc to be configured before the test runs.\n\"local\",\n\"manual\",\n+ \"gvisor_benchmark\",\n],\n**kwargs\n)\n" } ]
Go
Apache License 2.0
google/gvisor
Label all benchmarks with tag `gvisor_benchmark`. This makes it easy to list all the available benchmark targets with `bazel`. PiperOrigin-RevId: 486212679
259,868
04.11.2022 13:48:49
25,200
5e2f66189c1031c0f4abc08a462aabe9675a5ebf
Make all network benchmarks use container links. This CL uses container links rather than going over the host network stack. This avoids relying on that network stack, making the benchmarks more reliable, and simplifies benchmark setup code. #codehealth
[ { "change_type": "MODIFY", "old_path": "test/benchmarks/base/base.go", "new_path": "test/benchmarks/base/base.go", "diff": "@@ -17,7 +17,6 @@ package base\nimport (\n\"context\"\n- \"net\"\n\"testing\"\n\"time\"\n@@ -48,15 +47,8 @@ func StartServers(ctx context.Context, b *testing.B, args ServerArgs) []*dockeru\nb.Fatalf(\"failed to spawn node instance: %v\", err)\n}\n- // Get the container IP.\n- servingIP, err := server.FindIP(ctx, false)\n- if err != nil {\n- CleanUpContainers(ctx, servers)\n- b.Fatalf(\"failed to get ip from server: %v\", err)\n- }\n-\n// Wait until the server is up.\n- if err := harness.WaitUntilServing(ctx, args.Machine, servingIP, args.Port); err != nil {\n+ if err := harness.WaitUntilContainerServing(ctx, args.Machine, server, args.Port); err != nil {\nCleanUpContainers(ctx, servers)\nb.Fatalf(\"failed to wait for serving\")\n}\n@@ -74,7 +66,7 @@ func CleanUpContainers(ctx context.Context, containers []*dockerutil.Container)\n}\n// RedisInstance returns a Redis container and its reachable IP.\n-func RedisInstance(ctx context.Context, b *testing.B, machine harness.Machine) (*dockerutil.Container, net.IP) {\n+func RedisInstance(ctx context.Context, b *testing.B, machine harness.Machine) *dockerutil.Container {\nb.Helper()\n// Spawn a redis instance for the app to use.\nredis := machine.GetNativeContainer(ctx, b)\n@@ -89,10 +81,5 @@ func RedisInstance(ctx context.Context, b *testing.B, machine harness.Machine) (\nredis.CleanUp(ctx)\nb.Fatalf(\"failed to start redis server: %v %s\", err, out)\n}\n- redisIP, err := redis.FindIP(ctx, false)\n- if err != nil {\n- redis.CleanUp(ctx)\n- b.Fatalf(\"failed to get IP from redis instance: %v\", err)\n- }\n- return redis, redisIP\n+ return redis\n}\n" }, { "change_type": "MODIFY", "old_path": "test/benchmarks/base/size_test.go", "new_path": "test/benchmarks/base/size_test.go", "diff": "@@ -132,7 +132,7 @@ func BenchmarkSizeNode(b *testing.B) {\n// Make a redis instance for Node to connect.\nctx := context.Background()\n- redis, redisIP := base.RedisInstance(ctx, b, machine)\n+ redis := base.RedisInstance(ctx, b, machine)\ndefer redis.CleanUp(ctx)\n// DropCaches after redis is created.\n@@ -152,7 +152,7 @@ func BenchmarkSizeNode(b *testing.B) {\nWorkDir: \"/usr/src/app\",\nLinks: []string{redis.MakeLink(\"redis\")},\n}\n- nodeCmd := []string{\"node\", \"index.js\", redisIP.String()}\n+ nodeCmd := []string{\"node\", \"index.js\", \"redis\"}\nconst port = 8080\nservers := base.StartServers(ctx, b,\nbase.ServerArgs{\n" }, { "change_type": "MODIFY", "old_path": "test/benchmarks/base/startup_test.go", "new_path": "test/benchmarks/base/startup_test.go", "diff": "@@ -85,7 +85,7 @@ func BenchmarkStartupNode(b *testing.B) {\ndefer machine.CleanUp()\nctx := context.Background()\n- redis, redisIP := base.RedisInstance(ctx, b, machine)\n+ redis := base.RedisInstance(ctx, b, machine)\ndefer redis.CleanUp(ctx)\nrunOpts := dockerutil.RunOpts{\nImage: \"benchmarks/node\",\n@@ -93,7 +93,7 @@ func BenchmarkStartupNode(b *testing.B) {\nLinks: []string{redis.MakeLink(\"redis\")},\n}\n- cmd := []string{\"node\", \"index.js\", redisIP.String()}\n+ cmd := []string{\"node\", \"index.js\", \"redis\"}\nrunServerWorkload(ctx, b,\nbase.ServerArgs{\nMachine: machine,\n@@ -122,15 +122,9 @@ func runServerWorkload(ctx context.Context, b *testing.B, args base.ServerArgs)\nreturn fmt.Errorf(\"failed to spawn node instance: %v\", err)\n}\n- harness.DebugLog(b, \"Finding Container IP\")\n- servingIP, err := server.FindIP(ctx, false)\n- if err != nil {\n- return fmt.Errorf(\"failed to get ip from server: %v\", err)\n- }\n-\n// Wait until the Client sees the server as up.\nharness.DebugLog(b, \"Waiting for container to start.\")\n- if err := harness.WaitUntilServing(ctx, args.Machine, servingIP, args.Port); err != nil {\n+ if err := harness.WaitUntilContainerServing(ctx, args.Machine, server, args.Port); err != nil {\nreturn fmt.Errorf(\"failed to wait for serving: %v\", err)\n}\nreturn nil\n" }, { "change_type": "MODIFY", "old_path": "test/benchmarks/database/redis_test.go", "new_path": "test/benchmarks/database/redis_test.go", "diff": "@@ -81,17 +81,7 @@ func BenchmarkRedis(b *testing.B) {\nb.Fatalf(\"failed to start redis server: %v %s\", err, out)\n}\n- ip, err := serverMachine.IPAddress()\n- if err != nil {\n- b.Fatalf(\"failed to get IP from server: %v\", err)\n- }\n-\n- serverPort, err := server.FindPort(ctx, port)\n- if err != nil {\n- b.Fatalf(\"failed to get IP from server: %v\", err)\n- }\n-\n- if err = harness.WaitUntilServing(ctx, clientMachine, ip, serverPort); err != nil {\n+ if err = harness.WaitUntilContainerServing(ctx, clientMachine, server, port); err != nil {\nb.Fatalf(\"failed to start redis with: %v\", err)\n}\nfor _, operation := range operations {\n@@ -120,7 +110,8 @@ func BenchmarkRedis(b *testing.B) {\nout, err = client.Run(ctx, dockerutil.RunOpts{\nImage: \"benchmarks/redis\",\n- }, redis.MakeCmd(ip, serverPort, b.N /*requests*/)...)\n+ Links: []string{server.MakeLink(\"redis\")},\n+ }, redis.MakeCmd(\"redis\", port, b.N /*requests*/)...)\n}\nif err != nil {\n" }, { "change_type": "MODIFY", "old_path": "test/benchmarks/harness/util.go", "new_path": "test/benchmarks/harness/util.go", "diff": "@@ -17,7 +17,6 @@ package harness\nimport (\n\"context\"\n\"fmt\"\n- \"net\"\n\"strings\"\n\"testing\"\n@@ -29,16 +28,17 @@ import (\n//TODO(gvisor.dev/issue/3535): move to own package or move methods to harness struct.\n-// WaitUntilServing grabs a container from `machine` and waits for a server at\n-// IP:port.\n-func WaitUntilServing(ctx context.Context, machine Machine, server net.IP, port int) error {\n+// WaitUntilContainerServing grabs a container from `machine` and waits for a server on\n+// the given container and port.\n+func WaitUntilContainerServing(ctx context.Context, machine Machine, container *dockerutil.Container, port int) error {\nvar logger testutil.DefaultLogger = \"util\"\nnetcat := machine.GetNativeContainer(ctx, logger)\ndefer netcat.CleanUp(ctx)\n- cmd := fmt.Sprintf(\"while ! wget -q --spider http://%s:%d; do true; done\", server, port)\n+ cmd := fmt.Sprintf(\"while ! wget -q --spider http://%s:%d; do true; done\", \"server\", port)\n_, err := netcat.Run(ctx, dockerutil.RunOpts{\nImage: \"benchmarks/util\",\n+ Links: []string{container.MakeLink(\"server\")},\n}, \"sh\", \"-c\", cmd)\nreturn err\n}\n" }, { "change_type": "MODIFY", "old_path": "test/benchmarks/network/network.go", "new_path": "test/benchmarks/network/network.go", "diff": "@@ -52,26 +52,15 @@ func runStaticServer(b *testing.B, serverOpts dockerutil.RunOpts, serverCmd []st\nb.Fatalf(\"failed to start server: %v\", err)\n}\n- // Get its IP.\n- ip, err := serverMachine.IPAddress()\n- if err != nil {\n- b.Fatalf(\"failed to find server ip: %v\", err)\n- }\n-\n- // Get the published port.\n- servingPort, err := server.FindPort(ctx, port)\n- if err != nil {\n- b.Fatalf(\"failed to find server port %d: %v\", port, err)\n- }\n-\n// Make sure the server is serving.\n- harness.WaitUntilServing(ctx, clientMachine, ip, servingPort)\n+ harness.WaitUntilContainerServing(ctx, clientMachine, server, port)\n// Run the client.\nb.ResetTimer()\nout, err := client.Run(ctx, dockerutil.RunOpts{\nImage: \"benchmarks/hey\",\n- }, hey.MakeCmd(ip, servingPort)...)\n+ Links: []string{server.MakeLink(\"server\")},\n+ }, hey.MakeCmd(\"server\", port)...)\nif err != nil {\nb.Fatalf(\"run failed with: %v\", err)\n}\n" }, { "change_type": "MODIFY", "old_path": "test/benchmarks/network/node_test.go", "new_path": "test/benchmarks/network/node_test.go", "diff": "@@ -102,26 +102,17 @@ func runNode(b *testing.B, hey *tools.Hey) {\n}\ndefer nodeApp.CleanUp(ctx)\n- servingIP, err := serverMachine.IPAddress()\n- if err != nil {\n- b.Fatalf(\"failed to get ip from server: %v\", err)\n- }\n-\n- servingPort, err := nodeApp.FindPort(ctx, port)\n- if err != nil {\n- b.Fatalf(\"failed to port from node instance: %v\", err)\n- }\n-\n// Wait until the Client sees the server as up.\n- harness.WaitUntilServing(ctx, clientMachine, servingIP, servingPort)\n+ harness.WaitUntilContainerServing(ctx, clientMachine, nodeApp, port)\n- heyCmd := hey.MakeCmd(servingIP, servingPort)\n+ heyCmd := hey.MakeCmd(\"node\", port)\n// the client should run on Native.\nb.ResetTimer()\nclient := clientMachine.GetNativeContainer(ctx, b)\nout, err := client.Run(ctx, dockerutil.RunOpts{\nImage: \"benchmarks/hey\",\n+ Links: []string{nodeApp.MakeLink(\"node\")},\n}, heyCmd...)\nif err != nil {\nb.Fatalf(\"hey container failed: %v logs: %s\", err, out)\n" }, { "change_type": "MODIFY", "old_path": "test/benchmarks/network/ruby_test.go", "new_path": "test/benchmarks/network/ruby_test.go", "diff": "@@ -80,10 +80,6 @@ func runRuby(b *testing.B, hey *tools.Hey) {\nif out, err := redis.WaitForOutput(ctx, \"Ready to accept connections\", 3*time.Second); err != nil {\nb.Fatalf(\"failed to start redis server: %v %s\", err, out)\n}\n- redisIP, err := redis.FindIP(ctx, false)\n- if err != nil {\n- b.Fatalf(\"failed to get IP from redis instance: %v\", err)\n- }\n// Ruby runs on port 9292.\nconst port = 9292\n@@ -100,7 +96,7 @@ func runRuby(b *testing.B, hey *tools.Hey) {\n\"WEB_CONCURRENCY=20\",\n\"WEB_MAX_THREADS=20\",\n\"RACK_ENV=production\",\n- fmt.Sprintf(\"HOST=%s\", redisIP),\n+ \"HOST=redis\",\n},\nUser: \"nobody\",\n}, \"sh\", \"-c\", \"/usr/bin/puma\"); err != nil {\n@@ -108,21 +104,11 @@ func runRuby(b *testing.B, hey *tools.Hey) {\n}\ndefer rubyApp.CleanUp(ctx)\n- servingIP, err := serverMachine.IPAddress()\n- if err != nil {\n- b.Fatalf(\"failed to get ip from server: %v\", err)\n- }\n-\n- servingPort, err := rubyApp.FindPort(ctx, port)\n- if err != nil {\n- b.Fatalf(\"failed to port from node instance: %v\", err)\n- }\n-\n// Wait until the Client sees the server as up.\n- if err := harness.WaitUntilServing(ctx, clientMachine, servingIP, servingPort); err != nil {\n+ if err := harness.WaitUntilContainerServing(ctx, clientMachine, rubyApp, port); err != nil {\nb.Fatalf(\"failed to wait until serving: %v\", err)\n}\n- heyCmd := hey.MakeCmd(servingIP, servingPort)\n+ heyCmd := hey.MakeCmd(\"ruby\", port)\n// the client should run on Native.\nb.ResetTimer()\n@@ -130,6 +116,7 @@ func runRuby(b *testing.B, hey *tools.Hey) {\ndefer client.CleanUp(ctx)\nout, err := client.Run(ctx, dockerutil.RunOpts{\nImage: \"benchmarks/hey\",\n+ Links: []string{rubyApp.MakeLink(\"ruby\")},\n}, heyCmd...)\nif err != nil {\nb.Fatalf(\"hey container failed: %v logs: %s\", err, out)\n" }, { "change_type": "MODIFY", "old_path": "test/benchmarks/tools/ab.go", "new_path": "test/benchmarks/tools/ab.go", "diff": "@@ -16,7 +16,6 @@ package tools\nimport (\n\"fmt\"\n- \"net\"\n\"regexp\"\n\"strconv\"\n\"testing\"\n@@ -31,8 +30,8 @@ type ApacheBench struct {\n}\n// MakeCmd makes an ApacheBench command.\n-func (a *ApacheBench) MakeCmd(ip net.IP, port int) []string {\n- path := fmt.Sprintf(\"http://%s:%d/%s\", ip, port, a.Doc)\n+func (a *ApacheBench) MakeCmd(host string, port int) []string {\n+ path := fmt.Sprintf(\"http://%s:%d/%s\", host, port, a.Doc)\n// See apachebench (ab) for flags.\ncmd := fmt.Sprintf(\"ab -n %d -c %d %s\", a.Requests, a.Concurrency, path)\nreturn []string{\"sh\", \"-c\", cmd}\n" }, { "change_type": "MODIFY", "old_path": "test/benchmarks/tools/hey.go", "new_path": "test/benchmarks/tools/hey.go", "diff": "@@ -16,7 +16,6 @@ package tools\nimport (\n\"fmt\"\n- \"net\"\n\"regexp\"\n\"strconv\"\n\"testing\"\n@@ -30,7 +29,7 @@ type Hey struct {\n}\n// MakeCmd returns a 'hey' command.\n-func (h *Hey) MakeCmd(ip net.IP, port int) []string {\n+func (h *Hey) MakeCmd(host string, port int) []string {\nc := h.Concurrency\nif c > h.Requests {\nc = h.Requests\n@@ -39,7 +38,7 @@ func (h *Hey) MakeCmd(ip net.IP, port int) []string {\n\"hey\",\n\"-n\", fmt.Sprintf(\"%d\", h.Requests),\n\"-c\", fmt.Sprintf(\"%d\", c),\n- fmt.Sprintf(\"http://%s:%d/%s\", ip.String(), port, h.Doc),\n+ fmt.Sprintf(\"http://%s:%d/%s\", host, port, h.Doc),\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "test/benchmarks/tools/redis.go", "new_path": "test/benchmarks/tools/redis.go", "diff": "@@ -16,7 +16,6 @@ package tools\nimport (\n\"fmt\"\n- \"net\"\n\"regexp\"\n\"strconv\"\n\"testing\"\n@@ -28,7 +27,7 @@ type Redis struct {\n}\n// MakeCmd returns a redis-benchmark client command.\n-func (r *Redis) MakeCmd(ip net.IP, port, requests int) []string {\n+func (r *Redis) MakeCmd(host string, port, requests int) []string {\n// There is no -t PING_BULK for redis-benchmark, so adjust the command in that case.\n// Note that \"ping\" will run both PING_INLINE and PING_BULK.\nif r.Operation == \"PING_BULK\" {\n@@ -36,7 +35,7 @@ func (r *Redis) MakeCmd(ip net.IP, port, requests int) []string {\n\"redis-benchmark\",\n\"--csv\",\n\"-t\", \"ping\",\n- \"-h\", ip.String(),\n+ \"-h\", host,\n\"-p\", fmt.Sprintf(\"%d\", port),\n\"-n\", fmt.Sprintf(\"%d\", requests),\n}\n@@ -47,7 +46,7 @@ func (r *Redis) MakeCmd(ip net.IP, port, requests int) []string {\n\"redis-benchmark\",\n\"--csv\",\n\"-t\", r.Operation,\n- \"-h\", ip.String(),\n+ \"-h\", host,\n\"-p\", fmt.Sprintf(\"%d\", port),\n\"-n\", fmt.Sprintf(\"%d\", requests),\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Make all network benchmarks use container links. This CL uses container links rather than going over the host network stack. This avoids relying on that network stack, making the benchmarks more reliable, and simplifies benchmark setup code. #codehealth PiperOrigin-RevId: 486221868
259,909
04.11.2022 15:38:35
25,200
1fc476d7feccff981d4c04e23df982149e47f356
Return a new packet from fragment reassembly instead of an old one.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/internal/fragmentation/reassembler.go", "new_path": "pkg/tcpip/network/internal/fragmentation/reassembler.go", "diff": "@@ -167,7 +167,7 @@ func (r *reassembler) process(first, last uint16, more bool, proto uint8, pkt st\nreturn r.holes[i].first < r.holes[j].first\n})\n- resPkt := r.holes[0].pkt.IncRef()\n+ resPkt := r.holes[0].pkt.Clone()\nfor i := 1; i < len(r.holes); i++ {\nstack.MergeFragment(resPkt, r.holes[i].pkt)\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Return a new packet from fragment reassembly instead of an old one. PiperOrigin-RevId: 486246464
259,909
05.11.2022 14:06:55
25,200
7520b7f833a44a986edeb7ba916ff0309a8dcc67
Modify pivot_root to return errors in cases of shared mounts. This is in line with linux as described here
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/mount.go", "new_path": "pkg/sentry/vfs/mount.go", "diff": "@@ -1121,11 +1121,20 @@ retry:\nif rootVd.mount.ns != ns || newRootVd.mount.ns != ns {\nreturn linuxerr.EINVAL\n}\n- // TODO(gvisor.dev/issues/221): Update this function to disallow\n- // pivot_root-ing new_root/put_old mounts with MS_SHARED propagation once it\n- // is implemented in gVisor.\nvfs.mountMu.Lock()\n+ // Either the mount point at new_root, or the parent mount of that mount\n+ // point, has propagation type MS_SHARED.\n+ if newRootParent := newRootVd.mount.parent(); newRootVd.mount.propType == Shared || newRootParent.propType == Shared {\n+ vfs.mountMu.Unlock()\n+ return linuxerr.EINVAL\n+ }\n+ // put_old is a mount point and has the propagation type MS_SHARED.\n+ if putOldVd.mount.root == putOldVd.dentry && putOldVd.mount.propType == Shared {\n+ vfs.mountMu.Unlock()\n+ return linuxerr.EINVAL\n+ }\n+\nif !vfs.mounts.seq.BeginWriteOk(epoch) {\n// Checks above raced with a mount change.\nvfs.mountMu.Unlock()\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/pivot_root.cc", "new_path": "test/syscalls/linux/pivot_root.cc", "diff": "@@ -325,8 +325,8 @@ TEST(PivotRootTest, NewRootNotAMountpoint) {\nSyscallSucceeds());\nconst std::string mountpoint_path =\nabsl::StrCat(\"/\", Basename(mountpoint.path()));\n- auto new_root = ASSERT_NO_ERRNO_AND_VALUE(\n- TempPath::CreateDirIn(mountpoint.path()));\n+ auto new_root =\n+ ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDirIn(mountpoint.path()));\nconst std::string new_root_path =\nabsl::StrCat(mountpoint_path, \"/\", Basename(new_root.path()));\nauto put_old =\n@@ -336,8 +336,9 @@ TEST(PivotRootTest, NewRootNotAMountpoint) {\nconst auto rest = [&] {\nTEST_CHECK_SUCCESS(chroot(root.path().c_str()));\n- TEST_CHECK_ERRNO(syscall(\n- __NR_pivot_root, new_root_path.c_str(), put_old_path.c_str()), EINVAL);\n+ TEST_CHECK_ERRNO(\n+ syscall(__NR_pivot_root, new_root_path.c_str(), put_old_path.c_str()),\n+ EINVAL);\n};\nEXPECT_THAT(InForkedProcess(rest), IsPosixErrorOkAndHolds(0));\n}\n@@ -349,16 +350,13 @@ TEST(PivotRootTest, PutOldNotUnderNewRoot) {\nauto root = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\nEXPECT_THAT(mount(\"\", root.path().c_str(), \"tmpfs\", 0, \"mode=0700\"),\nSyscallSucceeds());\n- auto new_root =\n- ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDirIn(root.path()));\n+ auto new_root = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDirIn(root.path()));\nconst std::string new_root_path =\nabsl::StrCat(\"/\", Basename(new_root.path()));\nEXPECT_THAT(mount(\"\", new_root.path().c_str(), \"tmpfs\", 0, \"mode=0700\"),\nSyscallSucceeds());\n- auto put_old =\n- ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDirIn(root.path()));\n- const std::string put_old_path =\n- absl::StrCat(\"/\", Basename(put_old.path()));\n+ auto put_old = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDirIn(root.path()));\n+ const std::string put_old_path = absl::StrCat(\"/\", Basename(put_old.path()));\nEXPECT_THAT(mount(\"\", put_old.path().c_str(), \"tmpfs\", 0, \"mode=0700\"),\nSyscallSucceeds());\n@@ -388,8 +386,9 @@ TEST(PivotRootTest, CurrentRootNotAMountPoint) {\nconst auto rest = [&] {\nTEST_CHECK_SUCCESS(chroot(root.path().c_str()));\n- TEST_CHECK_ERRNO(syscall(\n- __NR_pivot_root, new_root_path.c_str(), put_old_path.c_str()), EINVAL);\n+ TEST_CHECK_ERRNO(\n+ syscall(__NR_pivot_root, new_root_path.c_str(), put_old_path.c_str()),\n+ EINVAL);\n};\nEXPECT_THAT(InForkedProcess(rest), IsPosixErrorOkAndHolds(0));\n}\n@@ -414,6 +413,94 @@ TEST(PivotRootTest, OnRootFS) {\nEXPECT_THAT(InForkedProcess(rest), IsPosixErrorOkAndHolds(0));\n}\n+TEST(PivotRootTest, OnSharedNewRootParent) {\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_SYS_ADMIN)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_SYS_CHROOT)));\n+\n+ auto root = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n+ EXPECT_THAT(mount(\"\", root.path().c_str(), \"tmpfs\", 0, \"mode=0700\"),\n+ SyscallSucceeds());\n+ auto new_root = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDirIn(root.path()));\n+ EXPECT_THAT(mount(\"\", new_root.path().c_str(), \"tmpfs\", 0, \"mode=0700\"),\n+ SyscallSucceeds());\n+ const std::string new_root_path = JoinPath(\"/\", Basename(new_root.path()));\n+ auto put_old =\n+ ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDirIn(new_root.path()));\n+ const std::string put_old_path =\n+ JoinPath(new_root_path, \"/\", Basename(put_old.path()));\n+\n+ // Fails because parent has propagation type shared.\n+ EXPECT_THAT(mount(nullptr, root.path().c_str(), nullptr, MS_SHARED, nullptr),\n+ SyscallSucceeds());\n+ const auto rest = [&] {\n+ TEST_CHECK_SUCCESS(chroot(root.path().c_str()));\n+ TEST_CHECK_ERRNO(\n+ syscall(__NR_pivot_root, new_root_path.c_str(), put_old_path.c_str()),\n+ EINVAL);\n+ };\n+ EXPECT_THAT(InForkedProcess(rest), IsPosixErrorOkAndHolds(0));\n+}\n+\n+TEST(PivotRootTest, OnSharedNewRoot) {\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_SYS_ADMIN)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_SYS_CHROOT)));\n+\n+ auto root = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n+ EXPECT_THAT(mount(\"\", root.path().c_str(), \"tmpfs\", 0, \"mode=0700\"),\n+ SyscallSucceeds());\n+ auto new_root = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDirIn(root.path()));\n+ EXPECT_THAT(mount(\"\", new_root.path().c_str(), \"tmpfs\", 0, \"mode=0700\"),\n+ SyscallSucceeds());\n+ const std::string new_root_path = JoinPath(\"/\", Basename(new_root.path()));\n+ auto put_old =\n+ ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDirIn(new_root.path()));\n+ const std::string put_old_path =\n+ JoinPath(new_root_path, \"/\", Basename(put_old.path()));\n+\n+ // Fails because new_root has propagation type shared.\n+ EXPECT_THAT(\n+ mount(nullptr, new_root.path().c_str(), nullptr, MS_SHARED, nullptr),\n+ SyscallSucceeds());\n+ const auto rest = [&] {\n+ TEST_CHECK_SUCCESS(chroot(root.path().c_str()));\n+ TEST_CHECK_ERRNO(\n+ syscall(__NR_pivot_root, new_root_path.c_str(), put_old_path.c_str()),\n+ EINVAL);\n+ };\n+ EXPECT_THAT(InForkedProcess(rest), IsPosixErrorOkAndHolds(0));\n+}\n+\n+TEST(PivotRootTest, OnSharedPutOldMountpoint) {\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_SYS_ADMIN)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_SYS_CHROOT)));\n+\n+ auto root = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n+ EXPECT_THAT(mount(\"\", root.path().c_str(), \"tmpfs\", 0, \"mode=0700\"),\n+ SyscallSucceeds());\n+ auto new_root = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDirIn(root.path()));\n+ EXPECT_THAT(mount(\"\", new_root.path().c_str(), \"tmpfs\", 0, \"mode=0700\"),\n+ SyscallSucceeds());\n+ const std::string new_root_path = JoinPath(\"/\", Basename(new_root.path()));\n+ auto put_old =\n+ ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDirIn(new_root.path()));\n+ const std::string put_old_path =\n+ JoinPath(new_root_path, \"/\", Basename(put_old.path()));\n+\n+ // Fails because put_old is a mountpoint and has propagation type shared.\n+ EXPECT_THAT(mount(\"\", put_old.path().c_str(), \"tmpfs\", 0, \"mode=0700\"),\n+ SyscallSucceeds());\n+ EXPECT_THAT(\n+ mount(nullptr, put_old.path().c_str(), nullptr, MS_SHARED, nullptr),\n+ SyscallSucceeds());\n+ const auto rest = [&] {\n+ TEST_CHECK_SUCCESS(chroot(root.path().c_str()));\n+ TEST_CHECK_ERRNO(\n+ syscall(__NR_pivot_root, new_root_path.c_str(), put_old_path.c_str()),\n+ EINVAL);\n+ };\n+ EXPECT_THAT(InForkedProcess(rest), IsPosixErrorOkAndHolds(0));\n+}\n+\n} // namespace\n} // namespace testing\n" } ]
Go
Apache License 2.0
google/gvisor
Modify pivot_root to return errors in cases of shared mounts. This is in line with linux as described here https://man7.org/linux/man-pages/man2/pivot_root.2.html PiperOrigin-RevId: 486388848
259,907
08.11.2022 08:56:13
28,800
7b169a1640dda2b4e5fcdc7f3dd286f4fdfa989f
Exclude failing java runtime tests. I believe these tests rely on some certs which have now expired.
[ { "change_type": "MODIFY", "old_path": "test/runtimes/exclude/java17.csv", "new_path": "test/runtimes/exclude/java17.csv", "diff": "@@ -43,6 +43,8 @@ java/nio/channels/etc/PrintSupportedOptions.java,,\njava/nio/channels/spi/SelectorProvider/inheritedChannel/InheritedChannelTest.java,,Broken test\njava/nio/channels/unixdomain/SocketOptions.java,,\njava/rmi/transport/checkLeaseInfoLeak/CheckLeaseLeak.java,,Broken test\n+java/security/cert/CertPathBuilder/targetConstraints/BuildEEBasicConstraints.java,,Broken test\n+java/security/cert/pkix/policyChanges/TestPolicy.java,,Broken test\njava/util/ResourceBundle/Control/MissingResourceCauseTestRun.java,,Broken test\njava/util/concurrent/locks/Lock/TimedAcquireLeak.java,,\njava/util/logging/LogManager/Configuration/updateConfiguration/SimpleUpdateConfigWithInputStreamTest.java,,Broken test\n" } ]
Go
Apache License 2.0
google/gvisor
Exclude failing java runtime tests. I believe these tests rely on some certs which have now expired. PiperOrigin-RevId: 486964895
259,891
08.11.2022 11:54:48
28,800
aaf5129c05ecdf1d013fbb51fc0edd0c0415ed39
netstack: don't verify IPv4 checksum when offload is enabled There's no reason to check it.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv4/ipv4.go", "new_path": "pkg/tcpip/network/ipv4/ipv4.go", "diff": "@@ -835,7 +835,7 @@ func (e *endpoint) handleLocalPacket(pkt stack.PacketBufferPtr, canSkipRXChecksu\npkt = pkt.CloneToInbound()\ndefer pkt.DecRef()\n- pkt.RXTransportChecksumValidated = canSkipRXChecksum\n+ pkt.RXChecksumValidated = canSkipRXChecksum\nh, ok := e.protocol.parseAndValidate(pkt)\nif !ok {\n@@ -1705,7 +1705,7 @@ func (p *protocol) parseAndValidate(pkt stack.PacketBufferPtr) (header.IPv4, boo\nreturn nil, false\n}\n- if !h.IsChecksumValid() {\n+ if !pkt.RXChecksumValidated && !h.IsChecksumValid() {\nreturn nil, false\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/ipv6.go", "new_path": "pkg/tcpip/network/ipv6/ipv6.go", "diff": "@@ -1101,7 +1101,7 @@ func (e *endpoint) handleLocalPacket(pkt stack.PacketBufferPtr, canSkipRXChecksu\npkt = pkt.CloneToInbound()\ndefer pkt.DecRef()\n- pkt.RXTransportChecksumValidated = canSkipRXChecksum\n+ pkt.RXChecksumValidated = canSkipRXChecksum\nhView, ok := e.protocol.parseAndValidate(pkt)\nif !ok {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/conntrack.go", "new_path": "pkg/tcpip/stack/conntrack.go", "diff": "@@ -530,7 +530,7 @@ func (ct *ConnTrack) getConnAndUpdate(pkt PacketBufferPtr, skipChecksumValidatio\nuint16(pkt.Data().Size()),\ntid.srcAddr,\ntid.dstAddr,\n- pkt.RXTransportChecksumValidated || skipChecksumValidation)\n+ pkt.RXChecksumValidated || skipChecksumValidation)\nif !csumValid || !ok {\nreturn nil\n}\n@@ -542,7 +542,7 @@ func (ct *ConnTrack) getConnAndUpdate(pkt PacketBufferPtr, skipChecksumValidatio\npkt.NetworkProtocolNumber,\ntid.srcAddr,\ntid.dstAddr,\n- pkt.RXTransportChecksumValidated || skipChecksumValidation)\n+ pkt.RXChecksumValidated || skipChecksumValidation)\nif !lengthValid || !csumValid {\nreturn nil\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/nic.go", "new_path": "pkg/tcpip/stack/nic.go", "diff": "@@ -731,7 +731,7 @@ func (n *nic) DeliverNetworkPacket(protocol tcpip.NetworkProtocolNumber, pkt Pac\nreturn\n}\n- pkt.RXTransportChecksumValidated = n.NetworkLinkEndpoint.Capabilities()&CapabilityRXChecksumOffload != 0\n+ pkt.RXChecksumValidated = n.NetworkLinkEndpoint.Capabilities()&CapabilityRXChecksumOffload != 0\nnetworkEndpoint.HandlePacket(pkt)\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/packet_buffer.go", "new_path": "pkg/tcpip/stack/packet_buffer.go", "diff": "@@ -162,9 +162,9 @@ type packetBuffer struct {\n// NICID is the ID of the last interface the network packet was handled at.\nNICID tcpip.NICID\n- // RXTransportChecksumValidated indicates that transport checksum verification\n- // may be safely skipped.\n- RXTransportChecksumValidated bool\n+ // RXChecksumValidated indicates that checksum verification may be\n+ // safely skipped.\n+ RXChecksumValidated bool\n// NetworkPacketInfo holds an incoming packet's network-layer information.\nNetworkPacketInfo NetworkPacketInfo\n@@ -390,7 +390,7 @@ func (pk PacketBufferPtr) Clone() PacketBufferPtr {\nnewPk.TransportProtocolNumber = pk.TransportProtocolNumber\nnewPk.PktType = pk.PktType\nnewPk.NICID = pk.NICID\n- newPk.RXTransportChecksumValidated = pk.RXTransportChecksumValidated\n+ newPk.RXChecksumValidated = pk.RXChecksumValidated\nnewPk.NetworkPacketInfo = pk.NetworkPacketInfo\nnewPk.tuple = pk.tuple\nnewPk.InitRefs()\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/segment.go", "new_path": "pkg/tcpip/transport/tcp/segment.go", "diff": "@@ -101,7 +101,7 @@ func newIncomingSegment(id stack.TransportEndpointID, clock tcpip.Clock, pkt sta\nuint16(pkt.Data().Size()),\nnetHdr.SourceAddress(),\nnetHdr.DestinationAddress(),\n- pkt.RXTransportChecksumValidated)\n+ pkt.RXChecksumValidated)\nif !ok {\nreturn nil, fmt.Errorf(\"header data offset does not respect size constraints: %d < offset < %d, got offset=%d\", header.TCPMinimumSize, len(hdr), hdr.DataOffset())\n}\n@@ -119,7 +119,7 @@ func newIncomingSegment(id stack.TransportEndpointID, clock tcpip.Clock, pkt sta\ns.pkt = pkt.IncRef()\ns.csumValid = csumValid\n- if !s.pkt.RXTransportChecksumValidated {\n+ if !s.pkt.RXChecksumValidated {\ns.csum = csum\n}\nreturn s, nil\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/udp/endpoint.go", "new_path": "pkg/tcpip/transport/udp/endpoint.go", "diff": "@@ -913,7 +913,7 @@ func (e *endpoint) HandlePacket(id stack.TransportEndpointID, pkt stack.PacketBu\npkt.NetworkProtocolNumber,\nnetHdr.SourceAddress(),\nnetHdr.DestinationAddress(),\n- pkt.RXTransportChecksumValidated)\n+ pkt.RXChecksumValidated)\nif !lengthValid {\n// Malformed packet.\ne.stack.Stats().UDP.MalformedPacketsReceived.Increment()\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/udp/protocol.go", "new_path": "pkg/tcpip/transport/udp/protocol.go", "diff": "@@ -87,7 +87,7 @@ func (p *protocol) HandleUnknownDestinationPacket(id stack.TransportEndpointID,\npkt.NetworkProtocolNumber,\nnetHdr.SourceAddress(),\nnetHdr.DestinationAddress(),\n- pkt.RXTransportChecksumValidated)\n+ pkt.RXChecksumValidated)\nif !lengthValid {\np.stack.Stats().UDP.MalformedPacketsReceived.Increment()\nreturn stack.UnknownDestinationPacketMalformed\n" } ]
Go
Apache License 2.0
google/gvisor
netstack: don't verify IPv4 checksum when offload is enabled There's no reason to check it. PiperOrigin-RevId: 487012436
259,977
08.11.2022 13:21:43
28,800
21b9d59950cd78bbed15efa33ad0c425eee08747
Increase timeout when polling for ICMP errors We're seeing occasional flakes in CQ in which the ICMP error isn't received in time. Double the timeout from 1s to 2s.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/udp_socket.cc", "new_path": "test/syscalls/linux/udp_socket.cc", "diff": "@@ -53,6 +53,8 @@ namespace testing {\nnamespace {\n+constexpr size_t kIcmpTimeout = 2000;\n+\n// Fixture for tests parameterized by the address family to use (AF_INET and\n// AF_INET6) when creating sockets.\nclass UdpSocketTest : public ::testing::TestWithParam<int> {\n@@ -395,9 +397,9 @@ TEST_P(UdpSocketTest, ConnectWriteToInvalidPort) {\nSyscallSucceedsWithValue(sizeof(buf)));\n// Poll to make sure we get the ICMP error back.\n- constexpr int kTimeout = 1000;\nstruct pollfd pfd = {sock_.get(), POLLERR, 0};\n- ASSERT_THAT(RetryEINTR(poll)(&pfd, 1, kTimeout), SyscallSucceedsWithValue(1));\n+ ASSERT_THAT(RetryEINTR(poll)(&pfd, 1, kIcmpTimeout),\n+ SyscallSucceedsWithValue(1));\n// Now verify that we got an ICMP error back of ECONNREFUSED.\nint err;\n@@ -799,10 +801,10 @@ TEST_P(UdpSocketTest, ConnectAndSendNoReceiver) {\nEXPECT_THAT(send(sock_.get(), buf, sizeof(buf), 0),\nSyscallSucceedsWithValue(sizeof(buf)));\n- constexpr int kTimeout = 1000;\n// Poll to make sure we get the ICMP error back before issuing more writes.\nstruct pollfd pfd = {sock_.get(), POLLERR, 0};\n- ASSERT_THAT(RetryEINTR(poll)(&pfd, 1, kTimeout), SyscallSucceedsWithValue(1));\n+ ASSERT_THAT(RetryEINTR(poll)(&pfd, 1, kIcmpTimeout),\n+ SyscallSucceedsWithValue(1));\n// Next write should fail with ECONNREFUSED due to the ICMP error generated in\n// response to the previous write.\n@@ -814,7 +816,8 @@ TEST_P(UdpSocketTest, ConnectAndSendNoReceiver) {\nASSERT_THAT(send(sock_.get(), buf, sizeof(buf), 0), SyscallSucceeds());\n// Poll to make sure we get the ICMP error back before issuing more writes.\n- ASSERT_THAT(RetryEINTR(poll)(&pfd, 1, kTimeout), SyscallSucceedsWithValue(1));\n+ ASSERT_THAT(RetryEINTR(poll)(&pfd, 1, kIcmpTimeout),\n+ SyscallSucceedsWithValue(1));\n// Next write should fail with ECONNREFUSED due to the ICMP error generated in\n// response to the previous write.\n" } ]
Go
Apache License 2.0
google/gvisor
Increase timeout when polling for ICMP errors We're seeing occasional flakes in CQ in which the ICMP error isn't received in time. Double the timeout from 1s to 2s. PiperOrigin-RevId: 487035507
259,848
08.11.2022 14:00:59
28,800
a1476ce4f5ee04d40bdff4fad516022862a7d9c5
io_uring_setup: fixing cqentries setup bug. We should compare against maximum number of allowed cq entries instead of comparing against the flag that allows to set that number.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/iouringfs/iouringfs.go", "new_path": "pkg/sentry/fsimpl/iouringfs/iouringfs.go", "diff": "@@ -94,7 +94,7 @@ func New(ctx context.Context, vfsObj *vfs.VirtualFilesystem, entries uint32, par\nif params.Flags&linux.IORING_SETUP_CQSIZE != 0 {\nvar ok bool\nnumCqEntries, ok = roundUpPowerOfTwo(params.CqEntries)\n- if !ok || numCqEntries < numSqEntries || numCqEntries > linux.IORING_SETUP_CQSIZE {\n+ if !ok || numCqEntries < numSqEntries || numCqEntries > linux.IORING_MAX_CQ_ENTRIES {\nreturn nil, linuxerr.EINVAL\n}\n} else {\n" } ]
Go
Apache License 2.0
google/gvisor
io_uring_setup: fixing cqentries setup bug. We should compare against maximum number of allowed cq entries instead of comparing against the flag that allows to set that number. PiperOrigin-RevId: 487045476
259,891
08.11.2022 14:40:40
28,800
70d7f5033f32338d99c94662c398338e375eb0dc
netstack: setup basic structure for GRO
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/BUILD", "new_path": "pkg/tcpip/stack/BUILD", "diff": "@@ -43,6 +43,7 @@ go_library(\nsrcs = [\n\"addressable_endpoint_state.go\",\n\"conntrack.go\",\n+ \"gro.go\",\n\"headertype_string.go\",\n\"hook_string.go\",\n\"icmp_rate_limit.go\",\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/tcpip/stack/gro.go", "diff": "+// Copyright 2022 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package stack\n+\n+import (\n+ \"time\"\n+\n+ \"gvisor.dev/gvisor/pkg/atomicbitops\"\n+)\n+\n+// groDispatcher coalesces incoming TCP4 packets to increase throughput.\n+type groDispatcher struct {\n+ // newInterval notifies about changes to the interval.\n+ newInterval chan struct{}\n+ // intervalNS is the interval in nanoseconds.\n+ intervalNS atomicbitops.Int64\n+ // stop instructs the GRO dispatcher goroutine to stop.\n+ stop chan struct{}\n+}\n+\n+func (gd *groDispatcher) init() {\n+ gd.newInterval = make(chan struct{}, 1)\n+ gd.stop = make(chan struct{})\n+ gd.start(0)\n+}\n+\n+// start spawns a goroutine that flushes the GRO periodically based on the\n+// interval.\n+func (gd *groDispatcher) start(interval time.Duration) {\n+ go func(interval time.Duration) {\n+ var ch <-chan time.Time\n+ if interval == 0 {\n+ // Never run.\n+ ch = make(<-chan time.Time)\n+ } else {\n+ ticker := time.NewTicker(interval)\n+ ch = ticker.C\n+ }\n+ for {\n+ select {\n+ case <-gd.newInterval:\n+ interval = time.Duration(gd.intervalNS.Load()) * time.Nanosecond\n+ if interval == 0 {\n+ // Never run.\n+ ch = make(<-chan time.Time)\n+ } else {\n+ ticker := time.NewTicker(interval)\n+ ch = ticker.C\n+ }\n+ case <-ch:\n+ gd.flush()\n+ case <-gd.stop:\n+ return\n+ }\n+ }\n+ }(interval)\n+}\n+\n+func (gd *groDispatcher) getInterval() time.Duration {\n+ return time.Duration(gd.intervalNS.Load()) * time.Nanosecond\n+}\n+\n+func (gd *groDispatcher) setInterval(interval time.Duration) {\n+ gd.intervalNS.Store(interval.Nanoseconds())\n+ gd.newInterval <- struct{}{}\n+}\n+\n+func (gd *groDispatcher) dispatch(pkt PacketBufferPtr, ep NetworkEndpoint) {\n+ // Just pass up the stack for now.\n+ ep.HandlePacket(pkt)\n+}\n+\n+// flush sends any packets older than interval up the stack.\n+func (gd *groDispatcher) flush() {\n+ // No-op for now.\n+}\n+\n+// close stops the GRO goroutine.\n+func (gd *groDispatcher) close() {\n+ // TODO(b/256037250): DecRef any packets stored in GRO.\n+ gd.stop <- struct{}{}\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/nic.go", "new_path": "pkg/tcpip/stack/nic.go", "diff": "@@ -76,6 +76,8 @@ type nic struct {\npacketEPs map[tcpip.NetworkProtocolNumber]*packetEndpointList\nqDisc QueueingDiscipline\n+\n+ gro groDispatcher\n}\n// makeNICStats initializes the NIC statistics and associates them to the global\n@@ -199,6 +201,7 @@ func newNIC(stack *Stack, id tcpip.NICID, ep LinkEndpoint, opts NICOptions) *nic\n}\n}\n+ nic.gro.init()\nnic.NetworkLinkEndpoint.Attach(nic)\nreturn nic\n@@ -305,6 +308,9 @@ func (n *nic) remove() tcpip.Error {\nep.Close()\n}\n+ // Shutdown GRO.\n+ n.gro.close()\n+\n// drain and drop any packets pending link resolution.\nn.linkResQueue.cancel()\n@@ -733,7 +739,7 @@ func (n *nic) DeliverNetworkPacket(protocol tcpip.NetworkProtocolNumber, pkt Pac\npkt.RXChecksumValidated = n.NetworkLinkEndpoint.Capabilities()&CapabilityRXChecksumOffload != 0\n- networkEndpoint.HandlePacket(pkt)\n+ n.gro.dispatch(pkt, networkEndpoint)\n}\nfunc (n *nic) DeliverLinkPacket(protocol tcpip.NetworkProtocolNumber, pkt PacketBufferPtr, incoming bool) {\n" } ]
Go
Apache License 2.0
google/gvisor
netstack: setup basic structure for GRO PiperOrigin-RevId: 487055867
259,909
08.11.2022 15:14:27
28,800
28bbe008214497e0e3f3c051e9c463bd0d7c8502
Remove internal PoolingEnabled flag. Pooling is known to be safe at this point. Removing the flags will happen later to avoid breakage in experiments still using them.
[ { "change_type": "MODIFY", "old_path": "pkg/bufferv2/chunk.go", "new_path": "pkg/bufferv2/chunk.go", "diff": "@@ -21,12 +21,6 @@ import (\n\"gvisor.dev/gvisor/pkg/sync\"\n)\n-// PoolingEnabled is set to true when pooling is enabled. Added as a\n-// global to allow easy access.\n-//\n-// TODO(b/236996271): Remove once buffer pooling experiment complete.\n-var PoolingEnabled = true\n-\nconst (\n// This is log2(baseChunkSize). This number is used to calculate which pool\n// to use for a payload size by right shifting the payload size by this\n@@ -86,7 +80,7 @@ type chunk struct {\nfunc newChunk(size int) *chunk {\nvar c *chunk\n- if !PoolingEnabled || size > MaxChunkSize {\n+ if size > MaxChunkSize {\nc = &chunk{\ndata: make([]byte, size),\n}\n@@ -102,7 +96,7 @@ func newChunk(size int) *chunk {\n}\nfunc (c *chunk) destroy() {\n- if !PoolingEnabled || len(c.data) > MaxChunkSize {\n+ if len(c.data) > MaxChunkSize {\nc.data = nil\nreturn\n}\n" }, { "change_type": "MODIFY", "old_path": "runsc/boot/BUILD", "new_path": "runsc/boot/BUILD", "diff": "@@ -28,7 +28,6 @@ go_library(\n\"//pkg/abi\",\n\"//pkg/abi/linux\",\n\"//pkg/bpf\",\n- \"//pkg/bufferv2\",\n\"//pkg/cleanup\",\n\"//pkg/context\",\n\"//pkg/control/server\",\n" }, { "change_type": "MODIFY", "old_path": "runsc/boot/loader.go", "new_path": "runsc/boot/loader.go", "diff": "@@ -27,7 +27,6 @@ import (\n\"golang.org/x/sys/unix\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/bpf\"\n- \"gvisor.dev/gvisor/pkg/bufferv2\"\n\"gvisor.dev/gvisor/pkg/context\"\n\"gvisor.dev/gvisor/pkg/coverage\"\n\"gvisor.dev/gvisor/pkg/cpuid\"\n@@ -240,7 +239,6 @@ func New(args Args) (*Loader, error) {\nkernel.FUSEEnabled = args.Conf.FUSE\nkernel.LISAFSEnabled = args.Conf.Lisafs\n- bufferv2.PoolingEnabled = args.Conf.BufferPooling\nvfs2.Override()\n// Make host FDs stable between invocations. Host FDs must map to the exact\n" } ]
Go
Apache License 2.0
google/gvisor
Remove internal PoolingEnabled flag. Pooling is known to be safe at this point. Removing the flags will happen later to avoid breakage in experiments still using them. PiperOrigin-RevId: 487064491
259,891
08.11.2022 16:31:37
28,800
901d9a75d3163f630f1d0c45f9de7aa95f59252f
netstack: add gro_flush_timeout Makes a per-interface file available to configure the GRO timeout, e.g. /sys/class/net/eth0/gro_flush_timeout
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/sys/BUILD", "new_path": "pkg/sentry/fsimpl/sys/BUILD", "diff": "@@ -19,6 +19,7 @@ go_library(\nsrcs = [\n\"dir_refs.go\",\n\"kcov.go\",\n+ \"net.go\",\n\"sys.go\",\n],\nvisibility = [\"//pkg/sentry:internal\"],\n@@ -33,6 +34,7 @@ go_library(\n\"//pkg/refsvfs2\",\n\"//pkg/sentry/arch\",\n\"//pkg/sentry/fsimpl/kernfs\",\n+ \"//pkg/sentry/inet\",\n\"//pkg/sentry/kernel\",\n\"//pkg/sentry/kernel/auth\",\n\"//pkg/sentry/memmap\",\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/fsimpl/sys/net.go", "diff": "+// Copyright 2022 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package sys\n+\n+import (\n+ \"bytes\"\n+ \"fmt\"\n+ \"time\"\n+\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/context\"\n+ \"gvisor.dev/gvisor/pkg/sentry/fsimpl/kernfs\"\n+ \"gvisor.dev/gvisor/pkg/sentry/inet\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n+ \"gvisor.dev/gvisor/pkg/sentry/vfs\"\n+ \"gvisor.dev/gvisor/pkg/usermem\"\n+)\n+\n+// newNetDir returns a directory containing a subdirectory for each network\n+// interface.\n+func (fs *filesystem) newNetDir(ctx context.Context, creds *auth.Credentials, mode linux.FileMode) map[string]kernfs.Inode {\n+ // Get list of interfaces.\n+ stk := inet.StackFromContext(ctx)\n+ if stk == nil {\n+ return map[string]kernfs.Inode{}\n+ }\n+\n+ subDirs := make(map[string]kernfs.Inode)\n+ for idx, iface := range stk.Interfaces() {\n+ subDirs[iface.Name] = fs.newIfaceDir(ctx, creds, mode, idx, stk)\n+ }\n+ return subDirs\n+}\n+\n+// newIfaceDir returns a directory containing per-interface files.\n+func (fs *filesystem) newIfaceDir(ctx context.Context, creds *auth.Credentials, mode linux.FileMode, idx int32, stk inet.Stack) kernfs.Inode {\n+ files := map[string]kernfs.Inode{\n+ \"gro_flush_timeout\": fs.newGROTimeoutFile(ctx, creds, mode, idx, stk),\n+ }\n+ return fs.newDir(ctx, creds, mode, files)\n+}\n+\n+// groTimeoutFile enables the reading and writing of the GRO timeout.\n+//\n+// +stateify savable\n+type groTimeoutFile struct {\n+ implStatFS\n+ kernfs.DynamicBytesFile\n+\n+ idx int32\n+ stk inet.Stack\n+}\n+\n+// newGROTimeoutFile returns a file that can be used to read and set the GRO\n+// timeout.\n+func (fs *filesystem) newGROTimeoutFile(ctx context.Context, creds *auth.Credentials, mode linux.FileMode, idx int32, stk inet.Stack) kernfs.Inode {\n+ file := groTimeoutFile{idx: idx, stk: stk}\n+ file.DynamicBytesFile.Init(ctx, creds, linux.UNNAMED_MAJOR, fs.devMinor, fs.NextIno(), &file, mode)\n+ return &file\n+}\n+\n+// Generate implements vfs.DynamicBytesSource.Generate.\n+func (gf *groTimeoutFile) Generate(ctx context.Context, buf *bytes.Buffer) error {\n+ timeout, err := gf.stk.GROTimeout(gf.idx)\n+ if err != nil {\n+ return err\n+ }\n+ fmt.Fprintf(buf, \"%d\\n\", timeout.Nanoseconds())\n+ return nil\n+}\n+\n+// Write implements vfs.WritableDynamicBytesSource.Write.\n+func (gf *groTimeoutFile) Write(ctx context.Context, _ *vfs.FileDescription, src usermem.IOSequence, offset int64) (int64, error) {\n+ val := []int32{0}\n+ nRead, err := usermem.CopyInt32StringsInVec(ctx, src.IO, src.Addrs, val, src.Opts)\n+ if err != nil {\n+ return 0, err\n+ }\n+ gf.stk.SetGROTimeout(gf.idx, time.Duration(val[0])*time.Nanosecond)\n+ return nRead, nil\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/sys/sys.go", "new_path": "pkg/sentry/fsimpl/sys/sys.go", "diff": "@@ -108,12 +108,14 @@ func (fsType FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.Virt\nclassSub := map[string]kernfs.Inode{\n\"power_supply\": fs.newDir(ctx, creds, defaultSysDirMode, nil),\n+ \"net\": fs.newDir(ctx, creds, defaultSysDirMode, fs.newNetDir(ctx, creds, defaultSysDirMode)),\n}\ndevicesSub := map[string]kernfs.Inode{\n\"system\": fs.newDir(ctx, creds, defaultSysDirMode, map[string]kernfs.Inode{\n\"cpu\": cpuDir(ctx, fs, creds),\n}),\n}\n+\nproductName := \"\"\nif opts.InternalData != nil {\ndata := opts.InternalData.(*InternalData)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/inet/inet.go", "new_path": "pkg/sentry/inet/inet.go", "diff": "package inet\nimport (\n+ \"time\"\n+\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n@@ -108,6 +110,12 @@ type Stack interface {\n// SetPortRange sets the UDP and TCP IPv4 and IPv6 ephemeral port range\n// (inclusive).\nSetPortRange(start uint16, end uint16) error\n+\n+ // GROTimeout returns the GRO timeout.\n+ GROTimeout(NICID int32) (time.Duration, error)\n+\n+ // GROTimeout sets the GRO timeout.\n+ SetGROTimeout(NICID int32, timeout time.Duration) error\n}\n// Interface contains information about a network interface.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/inet/test_stack.go", "new_path": "pkg/sentry/inet/test_stack.go", "diff": "@@ -17,6 +17,7 @@ package inet\nimport (\n\"bytes\"\n\"fmt\"\n+ \"time\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n@@ -184,3 +185,15 @@ func (*TestStack) SetPortRange(start uint16, end uint16) error {\n// No-op.\nreturn nil\n}\n+\n+// GROTimeout implements Stack.\n+func (*TestStack) GROTimeout(NICID int32) (time.Duration, error) {\n+ // No-op.\n+ return 0, nil\n+}\n+\n+// SetGROTimeout implements Stack.\n+func (*TestStack) SetGROTimeout(NICID int32, timeout time.Duration) error {\n+ // No-op.\n+ return nil\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/hostinet/stack.go", "new_path": "pkg/sentry/socket/hostinet/stack.go", "diff": "@@ -24,6 +24,7 @@ import (\n\"strconv\"\n\"strings\"\n\"syscall\"\n+ \"time\"\n\"golang.org/x/sys/unix\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n@@ -515,3 +516,14 @@ func (*Stack) PortRange() (uint16, uint16) {\nfunc (*Stack) SetPortRange(uint16, uint16) error {\nreturn linuxerr.EACCES\n}\n+\n+// GROTimeout implements inet.Stack.GROTimeout.\n+func (s *Stack) GROTimeout(NICID int32) (time.Duration, error) {\n+ return 0, nil\n+}\n+\n+// SetGROTimeout implements inet.Stack.SetGROTimeout.\n+func (s *Stack) SetGROTimeout(NICID int32, timeout time.Duration) error {\n+ // We don't support setting the hostinet GRO timeout.\n+ return linuxerr.EINVAL\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netstack/stack.go", "new_path": "pkg/sentry/socket/netstack/stack.go", "diff": "@@ -16,6 +16,7 @@ package netstack\nimport (\n\"fmt\"\n+ \"time\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/errors/linuxerr\"\n@@ -491,3 +492,14 @@ func (s *Stack) PortRange() (uint16, uint16) {\nfunc (s *Stack) SetPortRange(start uint16, end uint16) error {\nreturn syserr.TranslateNetstackError(s.Stack.SetPortRange(start, end)).ToError()\n}\n+\n+// GROTimeout implements inet.Stack.GROTimeout.\n+func (s *Stack) GROTimeout(NICID int32) (time.Duration, error) {\n+ timeout, err := s.Stack.GROTimeout(NICID)\n+ return timeout, syserr.TranslateNetstackError(err).ToError()\n+}\n+\n+// SetGROTimeout implements inet.Stack.SetGROTimeout.\n+func (s *Stack) SetGROTimeout(NICID int32, timeout time.Duration) error {\n+ return syserr.TranslateNetstackError(s.Stack.SetGROTimeout(NICID, timeout)).ToError()\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/stack.go", "new_path": "pkg/tcpip/stack/stack.go", "diff": "@@ -710,6 +710,33 @@ func (s *Stack) SetPortRange(start uint16, end uint16) tcpip.Error {\nreturn s.PortManager.SetPortRange(start, end)\n}\n+// GROTimeout returns the GRO timeout.\n+func (s *Stack) GROTimeout(NICID int32) (time.Duration, tcpip.Error) {\n+ s.mu.RLock()\n+ defer s.mu.RUnlock()\n+\n+ nic, ok := s.nics[tcpip.NICID(NICID)]\n+ if !ok {\n+ return 0, &tcpip.ErrUnknownNICID{}\n+ }\n+\n+ return nic.gro.getInterval(), nil\n+}\n+\n+// SetGROTimeout sets the GRO timeout.\n+func (s *Stack) SetGROTimeout(NICID int32, timeout time.Duration) tcpip.Error {\n+ s.mu.RLock()\n+ defer s.mu.RUnlock()\n+\n+ nic, ok := s.nics[tcpip.NICID(NICID)]\n+ if !ok {\n+ return &tcpip.ErrUnknownNICID{}\n+ }\n+\n+ nic.gro.setInterval(timeout)\n+ return nil\n+}\n+\n// SetRouteTable assigns the route table to be used by this stack. It\n// specifies which NIC to use for given destination address ranges.\n//\n" } ]
Go
Apache License 2.0
google/gvisor
netstack: add gro_flush_timeout Makes a per-interface file available to configure the GRO timeout, e.g. /sys/class/net/eth0/gro_flush_timeout PiperOrigin-RevId: 487082821
259,891
08.11.2022 16:42:37
28,800
6db3ed9186aa5375b9b53b74af92285774e8833c
fix lint warnings in tcp_benchmark.sh
[ { "change_type": "MODIFY", "old_path": "test/benchmarks/tcp/tcp_benchmark.sh", "new_path": "test/benchmarks/tcp/tcp_benchmark.sh", "diff": "@@ -43,7 +43,7 @@ latency_variation=1 # +/- 1ms is a relatively low amount of jitter.\nloss=0.1 # 0.1% loss is non-zero, but not extremely high.\nduplicate=0.1 # 0.1% means duplicates are 1/10x as frequent as losses.\nduration=30 # 30s is enough time to consistent results (experimentally).\n-helper_dir=$(dirname $0)\n+helper_dir=\"$(dirname \"$0\")\"\nnetstack_opts=\ndisable_linux_gso=\ndisable_linux_gro=\n@@ -51,11 +51,11 @@ num_client_threads=1\n# Check for netem support.\nlsmod_output=$(lsmod | grep sch_netem)\n-if [ \"$?\" != \"0\" ]; then\n+if [[ \"$?\" != \"0\" ]]; then\necho \"warning: sch_netem may not be installed.\" >&2\nfi\n-while [ $# -gt 0 ]; do\n+while [[ $# -gt 0 ]]; do\ncase \"$1\" in\n--client)\nclient=true\n@@ -90,7 +90,7 @@ while [ $# -gt 0 ]; do\n;;\n--mtu)\nshift\n- [ \"$#\" -le 0 ] && echo \"no mtu provided\" && exit 1\n+ [[ \"$#\" -le 0 ]] && echo \"no mtu provided\" && exit 1\nmtu=$1\n;;\n--sack)\n@@ -107,27 +107,27 @@ while [ $# -gt 0 ]; do\n;;\n--duration)\nshift\n- [ \"$#\" -le 0 ] && echo \"no duration provided\" && exit 1\n+ [[ \"$#\" -le 0 ]] && echo \"no duration provided\" && exit 1\nduration=$1\n;;\n--latency)\nshift\n- [ \"$#\" -le 0 ] && echo \"no latency provided\" && exit 1\n+ [[ \"$#\" -le 0 ]] && echo \"no latency provided\" && exit 1\nlatency=$1\n;;\n--latency-variation)\nshift\n- [ \"$#\" -le 0 ] && echo \"no latency variation provided\" && exit 1\n+ [[ \"$#\" -le 0 ]] && echo \"no latency variation provided\" && exit 1\nlatency_variation=$1\n;;\n--loss)\nshift\n- [ \"$#\" -le 0 ] && echo \"no loss probability provided\" && exit 1\n+ [[ \"$#\" -le 0 ]] && echo \"no loss probability provided\" && exit 1\nloss=$1\n;;\n--duplicate)\nshift\n- [ \"$#\" -le 0 ] && echo \"no duplicate provided\" && exit 1\n+ [[ \"$#\" -le 0 ]] && echo \"no duplicate provided\" && exit 1\nduplicate=$1\n;;\n--cpuprofile)\n@@ -172,7 +172,7 @@ while [ $# -gt 0 ]; do\n;;\n--helpers)\nshift\n- [ \"$#\" -le 0 ] && echo \"no helper dir provided\" && exit 1\n+ [[ \"$#\" -le 0 ]] && echo \"no helper dir provided\" && exit 1\nhelper_dir=$1\n;;\n*)\n@@ -206,29 +206,29 @@ while [ $# -gt 0 ]; do\nshift\ndone\n-if [ ${verbose} == \"true\" ]; then\n+if [[ ${verbose} == \"true\" ]]; then\nset -x\nfi\n# Latency needs to be halved, since it's applied on both ways.\n-half_latency=$(echo ${latency}/2 | bc -l | awk '{printf \"%1.2f\", $0}')\n-half_loss=$(echo ${loss}/2 | bc -l | awk '{printf \"%1.6f\", $0}')\n-half_duplicate=$(echo ${duplicate}/2 | bc -l | awk '{printf \"%1.6f\", $0}')\n-helper_dir=${helper_dir#$(pwd)/} # Use relative paths.\n-proxy_binary=${helper_dir}/tcp_proxy\n-nsjoin_binary=${helper_dir}/nsjoin\n-\n-if [ ! -e ${proxy_binary} ]; then\n+half_latency=$(echo \"${latency}\"/2 | bc -l | awk '{printf \"%1.2f\", $0}')\n+half_loss=$(echo \"${loss}\"/2 | bc -l | awk '{printf \"%1.6f\", $0}')\n+half_duplicate=$(echo \"${duplicate}\"/2 | bc -l | awk '{printf \"%1.6f\", $0}')\n+helper_dir=\"${helper_dir#$(pwd)/}\" # Use relative paths.\n+proxy_binary=\"${helper_dir}/tcp_proxy\"\n+nsjoin_binary=\"${helper_dir}/nsjoin\"\n+\n+if [[ ! -e ${proxy_binary} ]]; then\necho \"Could not locate ${proxy_binary}, please make sure you've built the binary\"\nexit 1\nfi\n-if [ ! -e ${nsjoin_binary} ]; then\n+if [[ ! -e ${nsjoin_binary} ]]; then\necho \"Could not locate ${nsjoin_binary}, please make sure you've built the binary\"\nexit 1\nfi\n-if [ $(echo ${latency_variation} | awk '{printf \"%1.2f\", $0}') != \"0.00\" ]; then\n+if [[ \"$(echo \"${latency_variation}\" | awk '{printf \"%1.2f\", $0}')\" != \"0.00\" ]]; then\n# As long as there's some jitter, then we use the paretonormal distribution.\n# This will preserve the minimum RTT, but add a realistic amount of jitter to\n# the connection and cause re-ordering, etc. The regular pareto distribution\n@@ -262,18 +262,18 @@ fi\n# Specify loss and duplicate parameters only if they are non-zero\nloss_opt=\"\"\n-if [ \"$(echo $half_loss | bc -q)\" != \"0\" ]; then\n+if [[ \"$(echo \"$half_loss\" | bc -q)\" != \"0\" ]]; then\nloss_opt=\"loss random ${half_loss}%\"\nfi\nduplicate_opt=\"\"\n-if [ \"$(echo $half_duplicate | bc -q)\" != \"0\" ]; then\n+if [[ \"$(echo \"$half_duplicate\" | bc -q)\" != \"0\" ]]; then\nduplicate_opt=\"duplicate ${half_duplicate}%\"\nfi\nexec unshare -U -m -n -r -f -p --mount-proc /bin/bash << EOF\nset -e -m\n-if [ ${verbose} == \"true\" ]; then\n+if [[ ${verbose} == \"true\" ]]; then\nset -x\nfi\n@@ -352,7 +352,7 @@ fi\n# Add client and server addresses, and bring everything up.\n${nsjoin_binary} /tmp/client.netns ip addr add ${client_addr}/${mask} dev client.0\n${nsjoin_binary} /tmp/server.netns ip addr add ${server_addr}/${mask} dev server.0\n-if [ \"${disable_linux_gso}\" == \"1\" ]; then\n+if [[ \"${disable_linux_gso}\" == \"1\" ]]; then\n${nsjoin_binary} /tmp/client.netns ethtool -K client.0 tso off\n${nsjoin_binary} /tmp/client.netns ethtool -K client.0 gso off\n${nsjoin_binary} /tmp/client.netns ethtool -K client.0 gro off\n@@ -360,7 +360,7 @@ if [ \"${disable_linux_gso}\" == \"1\" ]; then\n${nsjoin_binary} /tmp/server.netns ethtool -K server.0 gso off\n${nsjoin_binary} /tmp/server.netns ethtool -K server.0 gro off\nfi\n-if [ \"${disable_linux_gro}\" == \"1\" ]; then\n+if [[ \"${disable_linux_gro}\" == \"1\" ]]; then\n${nsjoin_binary} /tmp/client.netns ethtool -K client.0 gro off\n${nsjoin_binary} /tmp/server.netns ethtool -K server.0 gro off\nfi\n" } ]
Go
Apache License 2.0
google/gvisor
fix lint warnings in tcp_benchmark.sh PiperOrigin-RevId: 487085546
259,992
08.11.2022 17:10:12
28,800
c57f7a79ebb4b703a90640c05745e936272bcacf
Add trace session option to ignore errors This allows a configuration file with newer trace points and fields to be used with an older runsc without failing (just skips the new trace points and fields). Updates
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/seccheck/BUILD", "new_path": "pkg/sentry/seccheck/BUILD", "diff": "@@ -45,12 +45,14 @@ go_test(\nname = \"seccheck_test\",\nsize = \"small\",\nsrcs = [\n+ \"config_test.go\",\n\"metadata_test.go\",\n\"seccheck_test.go\",\n],\nlibrary = \":seccheck\",\ndeps = [\n\"//pkg/context\",\n+ \"//pkg/fd\",\n\"//pkg/sentry/seccheck/points:points_go_proto\",\n],\n)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/seccheck/config.go", "new_path": "pkg/sentry/seccheck/config.go", "diff": "@@ -39,6 +39,13 @@ type SessionConfig struct {\nName string `json:\"name,omitempty\"`\n// Points is the set of points to enable in this session.\nPoints []PointConfig `json:\"points,omitempty\"`\n+ // IgnoreMissing skips point and optional/context fields not found. This can\n+ // be used to apply a single configuration file with newer points/fields with\n+ // older versions which do not have them yet. Note that it may hide typos in\n+ // the configuration.\n+ //\n+ // This field does NOT apply to sinks.\n+ IgnoreMissing bool `json:\"ignore_missing,omitempty\"`\n// Sinks are the sinks that will process the points enabled above.\nSinks []SinkConfig `json:\"sinks,omitempty\"`\n}\n@@ -93,17 +100,21 @@ func Create(conf *SessionConfig, force bool) error {\nfor _, ptConfig := range conf.Points {\ndesc, err := findPointDesc(ptConfig.Name)\nif err != nil {\n+ if conf.IgnoreMissing {\n+ log.Warningf(\"Skipping point %q: %v\", ptConfig.Name, err)\n+ continue\n+ }\nreturn err\n}\nreq := PointReq{Pt: desc.ID}\n- mask, err := setFields(ptConfig.OptionalFields, desc.OptionalFields)\n+ mask, err := setFields(ptConfig.OptionalFields, desc.OptionalFields, conf.IgnoreMissing)\nif err != nil {\nreturn fmt.Errorf(\"configuring point %q: %w\", ptConfig.Name, err)\n}\nreq.Fields.Local = mask\n- mask, err = setFields(ptConfig.ContextFields, desc.ContextFields)\n+ mask, err = setFields(ptConfig.ContextFields, desc.ContextFields, conf.IgnoreMissing)\nif err != nil {\nreturn fmt.Errorf(\"configuring point %q: %w\", ptConfig.Name, err)\n}\n@@ -212,11 +223,15 @@ func findField(name string, fields []FieldDesc) (FieldDesc, error) {\nreturn FieldDesc{}, fmt.Errorf(\"field %q not found\", name)\n}\n-func setFields(names []string, fields []FieldDesc) (FieldMask, error) {\n+func setFields(names []string, fields []FieldDesc, ignoreMissing bool) (FieldMask, error) {\nfm := FieldMask{}\nfor _, name := range names {\ndesc, err := findField(name, fields)\nif err != nil {\n+ if ignoreMissing {\n+ log.Warningf(\"Skipping field %q: %v\", name, err)\n+ continue\n+ }\nreturn FieldMask{}, err\n}\nfm.Add(desc.ID)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/seccheck/config_test.go", "diff": "+// Copyright 2022 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package seccheck\n+\n+import (\n+ \"strings\"\n+ \"testing\"\n+)\n+\n+func TestLifecycle(t *testing.T) {\n+ for _, tc := range []struct {\n+ name string\n+ conf SessionConfig\n+ }{\n+ {\n+ name: \"all-fields\",\n+ conf: SessionConfig{\n+ Name: \"Default\",\n+ Points: []PointConfig{\n+ {\n+ Name: \"syscall/sysno/0/enter\",\n+ },\n+ {\n+ Name: \"syscall/openat/enter\",\n+ OptionalFields: []string{\"fd_path\"},\n+ },\n+ {\n+ Name: \"syscall/sysno/1/enter\",\n+ ContextFields: []string{\"time\"},\n+ },\n+ {\n+ Name: \"syscall/openat/enter\",\n+ OptionalFields: []string{\"fd_path\"},\n+ ContextFields: []string{\"time\"},\n+ },\n+ },\n+ Sinks: []SinkConfig{\n+ {Name: \"test-sink\"},\n+ },\n+ },\n+ },\n+ {\n+ name: \"no-sink\",\n+ conf: SessionConfig{\n+ Name: \"Default\",\n+ Points: []PointConfig{\n+ {Name: \"syscall/sysno/0/enter\"},\n+ },\n+ },\n+ },\n+ {\n+ name: \"no-points\",\n+ conf: SessionConfig{\n+ Name: \"Default\",\n+ Sinks: []SinkConfig{\n+ {Name: \"test-sink\"},\n+ },\n+ },\n+ },\n+ {\n+ name: \"ignore-errors\",\n+ conf: SessionConfig{\n+ Name: \"Default\",\n+ IgnoreMissing: true,\n+ Points: []PointConfig{\n+ {\n+ Name: \"foobar\",\n+ },\n+ {\n+ Name: \"syscall/sysno/1/enter\",\n+ ContextFields: []string{\"foobar\"},\n+ },\n+ {\n+ Name: \"syscall/openat/enter\",\n+ ContextFields: []string{\"foobar\"},\n+ },\n+ },\n+ },\n+ },\n+ } {\n+ t.Run(tc.name, func(t *testing.T) {\n+ if err := Create(&tc.conf, false); err != nil {\n+ t.Errorf(\"Create(): %v\", err)\n+ }\n+\n+ var got []SessionConfig\n+ List(&got)\n+ if len(got) != 1 {\n+ t.Errorf(\"only one session should exist, got: %d\", len(got))\n+ } else {\n+ if got[0].Name != tc.conf.Name {\n+ t.Errorf(\"wrong name, want: %q, got: %q\", tc.conf.Name, got[0].Name)\n+ }\n+ }\n+\n+ if err := Delete(tc.conf.Name); err != nil {\n+ t.Errorf(\"Delete(%q): %v\", tc.conf.Name, err)\n+ }\n+ })\n+ }\n+}\n+\n+func TestFailure(t *testing.T) {\n+ for _, tc := range []struct {\n+ name string\n+ conf SessionConfig\n+ err string\n+ }{\n+ {\n+ name: \"point\",\n+ err: `point \"foobar\" not found`,\n+ conf: SessionConfig{\n+ Name: \"Default\",\n+ Points: []PointConfig{\n+ {Name: \"foobar\"},\n+ },\n+ },\n+ },\n+ {\n+ name: \"optional-field\",\n+ err: `field \"foobar\" not found`,\n+ conf: SessionConfig{\n+ Name: \"Default\",\n+ Points: []PointConfig{\n+ {\n+ Name: \"syscall/openat/enter\",\n+ OptionalFields: []string{\"foobar\"},\n+ },\n+ },\n+ },\n+ },\n+ {\n+ name: \"context-field\",\n+ err: `field \"foobar\" not found`,\n+ conf: SessionConfig{\n+ Name: \"Default\",\n+ Points: []PointConfig{\n+ {\n+ Name: \"syscall/sysno/1/enter\",\n+ ContextFields: []string{\"foobar\"},\n+ },\n+ },\n+ },\n+ },\n+ {\n+ name: \"sink\",\n+ err: `sink \"foobar\" not found`,\n+ conf: SessionConfig{\n+ Name: \"Default\",\n+ Sinks: []SinkConfig{\n+ {Name: \"foobar\"},\n+ },\n+ },\n+ },\n+ {\n+ name: \"sink-ignore-missing\",\n+ err: `sink \"foobar\" not found`,\n+ conf: SessionConfig{\n+ Name: \"Default\",\n+ IgnoreMissing: true,\n+ Sinks: []SinkConfig{\n+ {Name: \"foobar\"},\n+ },\n+ },\n+ },\n+ } {\n+ t.Run(tc.name, func(t *testing.T) {\n+ err := Create(&tc.conf, false)\n+ if err == nil {\n+ _ = Delete(tc.conf.Name)\n+ t.Fatal(\"Create() should have failed\")\n+ }\n+ if !strings.Contains(err.Error(), tc.err) {\n+ t.Errorf(\"invalid error, want: %q, got: %q\", tc.err, err)\n+ }\n+ })\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/seccheck/seccheck_test.go", "new_path": "pkg/sentry/seccheck/seccheck_test.go", "diff": "@@ -19,15 +19,29 @@ import (\n\"testing\"\n\"gvisor.dev/gvisor/pkg/context\"\n+ \"gvisor.dev/gvisor/pkg/fd\"\npb \"gvisor.dev/gvisor/pkg/sentry/seccheck/points/points_go_proto\"\n)\n+func init() {\n+ RegisterSink(SinkDesc{\n+ Name: \"test-sink\",\n+ New: newTestSink,\n+ })\n+}\n+\ntype testSink struct {\nSinkDefaults\nonClone func(ctx context.Context, fields FieldSet, info *pb.CloneInfo) error\n}\n+var _ Sink = (*testSink)(nil)\n+\n+func newTestSink(_ map[string]any, _ *fd.FD) (Sink, error) {\n+ return &testSink{}, nil\n+}\n+\n// Name implements Sink.Name.\nfunc (c *testSink) Name() string {\nreturn \"test-sink\"\n" } ]
Go
Apache License 2.0
google/gvisor
Add trace session option to ignore errors This allows a configuration file with newer trace points and fields to be used with an older runsc without failing (just skips the new trace points and fields). Updates #4805 PiperOrigin-RevId: 487091892
259,891
08.11.2022 17:34:01
28,800
434cdd398d291646ff7a85bcba20e3304a82b329
netstack: add GRO flag This allows for configuration of the GRO interval without modifying gro_flush_timeout. In some setups, e.g. docker, sysfs is mounted as RO and thus a flag is easier to work with.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/gro.go", "new_path": "pkg/tcpip/stack/gro.go", "diff": "@@ -30,10 +30,11 @@ type groDispatcher struct {\nstop chan struct{}\n}\n-func (gd *groDispatcher) init() {\n+func (gd *groDispatcher) init(interval time.Duration) {\n+ gd.intervalNS.Store(interval.Nanoseconds())\ngd.newInterval = make(chan struct{}, 1)\ngd.stop = make(chan struct{})\n- gd.start(0)\n+ gd.start(interval)\n}\n// start spawns a goroutine that flushes the GRO periodically based on the\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/nic.go", "new_path": "pkg/tcpip/stack/nic.go", "diff": "@@ -201,7 +201,7 @@ func newNIC(stack *Stack, id tcpip.NICID, ep LinkEndpoint, opts NICOptions) *nic\n}\n}\n- nic.gro.init()\n+ nic.gro.init(opts.GROTimeout)\nnic.NetworkLinkEndpoint.Attach(nic)\nreturn nic\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/stack.go", "new_path": "pkg/tcpip/stack/stack.go", "diff": "@@ -837,6 +837,9 @@ type NICOptions struct {\n// QDisc is the queue discipline to use for this NIC.\nQDisc QueueingDiscipline\n+\n+ // GROTimeout specifies the GRO timeout. Zero bypasses GRO.\n+ GROTimeout time.Duration\n}\n// CreateNICWithOptions creates a NIC with the provided id, LinkEndpoint, and\n" }, { "change_type": "MODIFY", "old_path": "runsc/boot/network.go", "new_path": "runsc/boot/network.go", "diff": "@@ -20,6 +20,7 @@ import (\n\"os\"\n\"runtime\"\n\"strings\"\n+ \"time\"\n\"golang.org/x/sys/unix\"\n\"gvisor.dev/gvisor/pkg/hostos\"\n@@ -96,6 +97,7 @@ type FDBasedLink struct {\nRoutes []Route\nGSOMaxSize uint32\nGvisorGSOEnabled bool\n+ GvisorGROTimeout time.Duration\nTXChecksumOffload bool\nRXChecksumOffload bool\nLinkAddress net.HardwareAddr\n@@ -293,6 +295,7 @@ func (n *Network) CreateLinksAndRoutes(args *CreateLinksAndRoutesArgs, _ *struct\nopts := stack.NICOptions{\nName: link.Name,\nQDisc: qDisc,\n+ GROTimeout: link.GvisorGROTimeout,\n}\nif err := n.createNICWithAddrs(nicID, sniffEP, opts, link.Addresses); err != nil {\nreturn err\n" }, { "change_type": "MODIFY", "old_path": "runsc/config/config.go", "new_path": "runsc/config/config.go", "diff": "@@ -19,6 +19,7 @@ package config\nimport (\n\"fmt\"\n+ \"time\"\n\"gvisor.dev/gvisor/pkg/refs\"\n\"gvisor.dev/gvisor/pkg/sentry/watchdog\"\n@@ -104,6 +105,10 @@ type Config struct {\n// retains its old name of \"software\" GSO for API consistency.\nGvisorGSO bool `flag:\"software-gso\"`\n+ // GvisorGROTimeout sets gVisor's generic receive offload timeout. Zero\n+ // bypasses GRO.\n+ GvisorGROTimeout time.Duration `flag:\"gvisor-gro\"`\n+\n// TXChecksumOffload indicates that TX Checksum Offload is enabled.\nTXChecksumOffload bool `flag:\"tx-checksum-offload\"`\n" }, { "change_type": "MODIFY", "old_path": "runsc/config/flags.go", "new_path": "runsc/config/flags.go", "diff": "@@ -96,6 +96,7 @@ func RegisterFlags(flagSet *flag.FlagSet) {\nflagSet.Bool(\"net-raw\", false, \"enable raw sockets. When false, raw sockets are disabled by removing CAP_NET_RAW from containers (`runsc exec` will still be able to utilize raw sockets). Raw sockets allow malicious containers to craft packets and potentially attack the network.\")\nflagSet.Bool(\"gso\", true, \"enable host segmentation offload if it is supported by a network device.\")\nflagSet.Bool(\"software-gso\", true, \"enable gVisor segmentation offload when host offload can't be enabled.\")\n+ flagSet.Duration(\"gvisor-gro\", 0, \"(e.g. \\\"20000ns\\\" or \\\"1ms\\\") sets gVisor's generic receive offload timeout. Zero bypasses GRO.\")\nflagSet.Bool(\"tx-checksum-offload\", false, \"enable TX checksum offload.\")\nflagSet.Bool(\"rx-checksum-offload\", true, \"enable RX checksum offload.\")\nflagSet.Var(queueingDisciplinePtr(QDiscFIFO), \"qdisc\", \"specifies which queueing discipline to apply by default to the non loopback nics used by the sandbox.\")\n" }, { "change_type": "MODIFY", "old_path": "runsc/sandbox/network.go", "new_path": "runsc/sandbox/network.go", "diff": "@@ -300,6 +300,7 @@ func createInterfacesAndRoutesFromNS(conn *urpc.Client, nsPath string, conf *con\nlink.GSOMaxSize = stack.GvisorGSOMaxSize\nlink.GvisorGSOEnabled = true\n}\n+ link.GvisorGROTimeout = conf.GvisorGROTimeout\nargs.FDBasedLinks = append(args.FDBasedLinks, link)\n}\n" } ]
Go
Apache License 2.0
google/gvisor
netstack: add GRO flag This allows for configuration of the GRO interval without modifying gro_flush_timeout. In some setups, e.g. docker, sysfs is mounted as RO and thus a flag is easier to work with. PiperOrigin-RevId: 487096047
259,891
09.11.2022 14:24:06
28,800
935f29ce6e42731d1cc8beaa7257d67debdf6451
netstack: make GRO timeout configurable in tcp_benchmark Also: don't turn of GRO when --disable-linux-gso is set.
[ { "change_type": "MODIFY", "old_path": "test/benchmarks/tcp/tcp_benchmark.sh", "new_path": "test/benchmarks/tcp/tcp_benchmark.sh", "diff": "@@ -47,6 +47,7 @@ helper_dir=\"$(dirname \"$0\")\"\nnetstack_opts=\ndisable_linux_gso=\ndisable_linux_gro=\n+gro=0\nnum_client_threads=1\n# Check for netem support.\n@@ -156,6 +157,11 @@ while [[ $# -gt 0 ]]; do\n--disable-linux-gro)\ndisable_linux_gro=1\n;;\n+ --gro)\n+ shift\n+ [[ \"$#\" -le 0 ]] && echo \"no GRO timeout provided\" && exit 1\n+ gro=$1\n+ ;;\n--ipv6)\nclient_addr=fd::1\nclient_proxy_addr=fd::2\n@@ -176,6 +182,8 @@ while [[ $# -gt 0 ]]; do\nhelper_dir=$1\n;;\n*)\n+ echo \"unknown option: $1\"\n+ echo \"\"\necho \"usage: $0 [options]\"\necho \"options:\"\necho \" --help show this message\"\n@@ -197,6 +205,7 @@ while [[ $# -gt 0 ]]; do\necho \" --num-client-threads number of parallel client threads to run\"\necho \" --disable-linux-gso disable segmentation offload (TSO, GSO, GRO) in the Linux network stack\"\necho \" --disable-linux-gro disable GRO in the Linux network stack\"\n+ echo \" --gro set gVisor GRO timeout\"\necho \" --ipv6 use ipv6 for benchmarks\"\necho \"\"\necho \"The output will of the script will be:\"\n@@ -246,7 +255,7 @@ if ${client}; then\n# and forward traffic using netstack.\nclient_args=\"${proxy_binary} ${netstack_opts} -port ${proxy_port} -client \\\\\n-mtu ${mtu} -iface client.0 -addr ${client_proxy_addr} -mask ${mask} \\\\\n- -forward ${full_server_proxy_addr} -gso=${gso} -swgso=${swgso}\"\n+ -forward ${full_server_proxy_addr} -gso=${gso} -swgso=${swgso} --gro=${gro}\"\nfi\n# Server proxy that will listen on the proxy port and forward to the server's\n@@ -257,7 +266,7 @@ if ${server}; then\n# iperf server using netstack.\nserver_args=\"${proxy_binary} ${netstack_opts} -port ${proxy_port} -server \\\\\n-mtu ${mtu} -iface server.0 -addr ${server_proxy_addr} -mask ${mask} \\\\\n- -forward ${full_server_addr} -gso=${gso} -swgso=${swgso}\"\n+ -forward ${full_server_addr} -gso=${gso} -swgso=${swgso} --gro=${gro}\"\nfi\n# Specify loss and duplicate parameters only if they are non-zero\n@@ -355,10 +364,8 @@ ${nsjoin_binary} /tmp/server.netns ip addr add ${server_addr}/${mask} dev server\nif [[ \"${disable_linux_gso}\" == \"1\" ]]; then\n${nsjoin_binary} /tmp/client.netns ethtool -K client.0 tso off\n${nsjoin_binary} /tmp/client.netns ethtool -K client.0 gso off\n- ${nsjoin_binary} /tmp/client.netns ethtool -K client.0 gro off\n${nsjoin_binary} /tmp/server.netns ethtool -K server.0 tso off\n${nsjoin_binary} /tmp/server.netns ethtool -K server.0 gso off\n- ${nsjoin_binary} /tmp/server.netns ethtool -K server.0 gro off\nfi\nif [[ \"${disable_linux_gro}\" == \"1\" ]]; then\n${nsjoin_binary} /tmp/client.netns ethtool -K client.0 gro off\n" }, { "change_type": "MODIFY", "old_path": "test/benchmarks/tcp/tcp_proxy.go", "new_path": "test/benchmarks/tcp/tcp_proxy.go", "diff": "@@ -63,6 +63,7 @@ var (\ncubic = flag.Bool(\"cubic\", false, \"enable use of CUBIC congestion control for netstack\")\ngso = flag.Int(\"gso\", 0, \"GSO maximum size\")\nswgso = flag.Bool(\"swgso\", false, \"gVisor-level GSO\")\n+ gro = flag.Duration(\"gro\", 0, \"gVisor-level GRO timeout\")\nclientTCPProbeFile = flag.String(\"client_tcp_probe_file\", \"\", \"if specified, installs a tcp probe to dump endpoint state to the specified file.\")\nserverTCPProbeFile = flag.String(\"server_tcp_probe_file\", \"\", \"if specified, installs a tcp probe to dump endpoint state to the specified file.\")\ncpuprofile = flag.String(\"cpuprofile\", \"\", \"write cpu profile to the specified file.\")\n@@ -224,8 +225,9 @@ func newNetstackImpl(mode string) (impl, error) {\nif err != nil {\nreturn nil, fmt.Errorf(\"failed to create FD endpoint: %v\", err)\n}\n+\nqDisc := fifo.New(ep, runtime.GOMAXPROCS(0), 1000)\n- opts := stack.NICOptions{QDisc: qDisc}\n+ opts := stack.NICOptions{QDisc: qDisc, GROTimeout: *gro}\nif err := s.CreateNICWithOptions(nicID, ep, opts); err != nil {\nreturn nil, fmt.Errorf(\"error creating NIC %q: %v\", *iface, err)\n}\n" } ]
Go
Apache License 2.0
google/gvisor
netstack: make GRO timeout configurable in tcp_benchmark Also: don't turn of GRO when --disable-linux-gso is set. PiperOrigin-RevId: 487346882
259,909
09.11.2022 15:54:35
28,800
e038ca2a1cbd8f15fa3fd30e3d8e9875500f390a
Fix ipv4 header ownership.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv4/ipv4.go", "new_path": "pkg/tcpip/network/ipv4/ipv4.go", "diff": "@@ -22,6 +22,7 @@ import (\n\"time\"\n\"gvisor.dev/gvisor/pkg/atomicbitops\"\n+ \"gvisor.dev/gvisor/pkg/bufferv2\"\n\"gvisor.dev/gvisor/pkg/sync\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n@@ -697,7 +698,9 @@ func (e *endpoint) forwardPacketWithRoute(route *stack.Route, pkt stack.PacketBu\n// forwardUnicastPacket attempts to forward a packet to its final destination.\nfunc (e *endpoint) forwardUnicastPacket(pkt stack.PacketBufferPtr) ip.ForwardingError {\n- h := header.IPv4(pkt.NetworkHeader().Slice())\n+ hView := pkt.NetworkHeader().View()\n+ defer hView.Release()\n+ h := header.IPv4(hView.AsSlice())\ndstAddr := h.DestinationAddress()\n@@ -782,11 +785,13 @@ func (e *endpoint) HandlePacket(pkt stack.PacketBufferPtr) {\nreturn\n}\n- h, ok := e.protocol.parseAndValidate(pkt)\n+ hView, ok := e.protocol.parseAndValidate(pkt)\nif !ok {\nstats.MalformedPacketsReceived.Increment()\nreturn\n}\n+ h := header.IPv4(hView.AsSlice())\n+ defer hView.Release()\nif !e.nic.IsLoopback() {\nif !e.protocol.options.AllowExternalLoopbackTraffic {\n@@ -837,11 +842,13 @@ func (e *endpoint) handleLocalPacket(pkt stack.PacketBufferPtr, canSkipRXChecksu\ndefer pkt.DecRef()\npkt.RXChecksumValidated = canSkipRXChecksum\n- h, ok := e.protocol.parseAndValidate(pkt)\n+ hView, ok := e.protocol.parseAndValidate(pkt)\nif !ok {\nstats.MalformedPacketsReceived.Increment()\nreturn\n}\n+ h := header.IPv4(hView.AsSlice())\n+ defer hView.Release()\ne.handleValidatedPacket(h, pkt, e.nic.Name() /* inNICName */)\n}\n@@ -1692,7 +1699,7 @@ func (p *protocol) isSubnetLocalBroadcastAddress(addr tcpip.Address) bool {\n// returns the parsed IP header.\n//\n// Returns true if the IP header was successfully parsed.\n-func (p *protocol) parseAndValidate(pkt stack.PacketBufferPtr) (header.IPv4, bool) {\n+func (p *protocol) parseAndValidate(pkt stack.PacketBufferPtr) (*bufferv2.View, bool) {\ntransProtoNum, hasTransportHdr, ok := p.Parse(pkt)\nif !ok {\nreturn nil, false\n@@ -1713,7 +1720,7 @@ func (p *protocol) parseAndValidate(pkt stack.PacketBufferPtr) (header.IPv4, boo\np.parseTransport(pkt, transProtoNum)\n}\n- return h, true\n+ return pkt.NetworkHeader().View(), true\n}\nfunc (p *protocol) parseTransport(pkt stack.PacketBufferPtr, transProtoNum tcpip.TransportProtocolNumber) {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/ipv6.go", "new_path": "pkg/tcpip/network/ipv6/ipv6.go", "diff": "@@ -2551,12 +2551,10 @@ func (p *protocol) parseAndValidate(pkt stack.PacketBufferPtr) (*bufferv2.View,\nreturn nil, false\n}\n- hView := pkt.NetworkHeader().View()\n- h := header.IPv6(hView.AsSlice())\n+ h := header.IPv6(pkt.NetworkHeader().Slice())\n// Do not include the link header's size when calculating the size of the IP\n// packet.\nif !h.IsValid(pkt.Size() - len(pkt.LinkHeader().Slice())) {\n- hView.Release()\nreturn nil, false\n}\n@@ -2564,7 +2562,7 @@ func (p *protocol) parseAndValidate(pkt stack.PacketBufferPtr) (*bufferv2.View,\np.parseTransport(pkt, transProtoNum)\n}\n- return hView, true\n+ return pkt.NetworkHeader().View(), true\n}\nfunc (p *protocol) parseTransport(pkt stack.PacketBufferPtr, transProtoNum tcpip.TransportProtocolNumber) {\n" } ]
Go
Apache License 2.0
google/gvisor
Fix ipv4 header ownership. PiperOrigin-RevId: 487369872
259,982
09.11.2022 16:11:22
28,800
68c47a2f88945da9eaaaea3aa573c09e013fa522
Fixing checkSentryExec to account for symlinks as the test runs locally. Updates
[ { "change_type": "MODIFY", "old_path": "test/trace/trace_test.go", "new_path": "test/trace/trace_test.go", "diff": "@@ -324,13 +324,15 @@ func checkSentryExec(msg test.Message) error {\nif err := checkContextData(p.ContextData); err != nil {\nreturn err\n}\n- if want := \"/bin/true\"; want != p.BinaryPath {\n+ // As test runs locally the binary path may resolve to a symlink so would not be exactly same\n+ // as the pathname passed.\n+ if want := \"/bin/true\"; !strings.Contains(p.BinaryPath, want) {\nreturn fmt.Errorf(\"wrong BinaryPath, want: %q, got: %q\", want, p.BinaryPath)\n}\nif len(p.Argv) == 0 {\nreturn fmt.Errorf(\"empty Argv\")\n}\n- if p.Argv[0] != p.BinaryPath {\n+ if !strings.Contains(p.BinaryPath, p.Argv[0]) {\nreturn fmt.Errorf(\"wrong Argv[0], want: %q, got: %q\", p.BinaryPath, p.Argv[0])\n}\nif len(p.Env) == 0 {\n" } ]
Go
Apache License 2.0
google/gvisor
Fixing checkSentryExec to account for symlinks as the test runs locally. Updates #4805 PiperOrigin-RevId: 487374028
259,853
09.11.2022 20:38:22
28,800
edc16b49e3b4302620231460f6155c3636ab9e51
Set TSC offset directly. Fixes
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/kvm/BUILD", "new_path": "pkg/sentry/platform/kvm/BUILD", "diff": "@@ -71,6 +71,7 @@ go_library(\n\"kvm_arm64.go\",\n\"kvm_arm64_unsafe.go\",\n\"kvm_const.go\",\n+ \"kvm_const_amd64.go\",\n\"kvm_const_arm64.go\",\n\"machine.go\",\n\"machine_amd64.go\",\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/kvm/kvm_const.go", "new_path": "pkg/sentry/platform/kvm/kvm_const.go", "diff": "@@ -41,6 +41,7 @@ const (\n_KVM_SET_SIGNAL_MASK = 0x4004ae8b\n_KVM_GET_VCPU_EVENTS = 0x8040ae9f\n_KVM_SET_VCPU_EVENTS = 0x4040aea0\n+ _KVM_SET_DEVICE_ATTR = 0x4018aee1\n)\n// KVM exit reasons.\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/platform/kvm/kvm_const_amd64.go", "diff": "+// Copyright 2019 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package kvm\n+\n+// KVM ioctls for amd64.\n+const (\n+ _KVM_VCPU_TSC_CTRL = 0x0\n+ _KVM_VCPU_TSC_OFFSET = 0x0\n+)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/kvm/machine_amd64.go", "new_path": "pkg/sentry/platform/kvm/machine_amd64.go", "diff": "@@ -46,6 +46,15 @@ func (m *machine) initArchState() error {\nreturn errno\n}\n+ // Initialize all vCPUs to minimize kvm ioctl-s allowed by seccomp filters.\n+ m.mu.Lock()\n+ for i := 0; i < m.maxVCPUs; i++ {\n+ m.createVCPU(i)\n+ }\n+ m.mu.Unlock()\n+\n+ c := m.Get()\n+ defer m.Put(c)\n// Enable CPUID faulting, if possible. Note that this also serves as a\n// basic platform sanity tests, since we will enter guest mode for the\n// first time here. The recovery is necessary, since if we fail to read\n@@ -57,15 +66,6 @@ func (m *machine) initArchState() error {\ndebug.SetPanicOnFault(old)\n}()\n- // Initialize all vCPUs to minimize kvm ioctl-s allowed by seccomp filters.\n- m.mu.Lock()\n- for i := 0; i < m.maxVCPUs; i++ {\n- m.createVCPU(i)\n- }\n- m.mu.Unlock()\n-\n- c := m.Get()\n- defer m.Put(c)\nbluepill(c)\nring0.SetCPUIDFaulting(true)\n@@ -201,6 +201,17 @@ func scaledTSC(rawFreq uintptr) int64 {\n// setSystemTime sets the vCPU to the system time.\nfunc (c *vCPU) setSystemTime() error {\n+ // Attempt to set the offset directly. This is supported as of Linux 5.16,\n+ // or commit 828ca89628bfcb1b8f27535025f69dd00eb55207.\n+ if err := c.setTSCOffset(); err == nil {\n+ return err\n+ }\n+\n+ // If tsc scaling is not supported, fallback to legacy mode.\n+ if !c.machine.tscControl {\n+ return c.setSystemTimeLegacy()\n+ }\n+\n// First, scale down the clock frequency to the lowest value allowed by\n// the API itself. How low we can go depends on the underlying\n// hardware, but it is typically ~1/2^48 for Intel, ~1/2^32 for AMD.\n@@ -212,11 +223,6 @@ func (c *vCPU) setSystemTime() error {\n// capabilities as it is emulated in KVM. We don't actually use this\n// capability, but it means that this method should be robust to\n// different hardware configurations.\n-\n- // if tsc scaling is not supported, fallback to legacy mode\n- if !c.machine.tscControl {\n- return c.setSystemTimeLegacy()\n- }\nrawFreq, err := c.getTSCFreq()\nif err != nil {\nreturn c.setSystemTimeLegacy()\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/kvm/machine_amd64_unsafe.go", "new_path": "pkg/sentry/platform/kvm/machine_amd64_unsafe.go", "diff": "@@ -87,6 +87,29 @@ func (c *vCPU) setTSCFreq(freq uintptr) error {\nreturn nil\n}\n+// setTSCOffset sets the TSC offset to zero.\n+func (c *vCPU) setTSCOffset() error {\n+ offset := uint64(0)\n+ da := struct {\n+ flags uint32\n+ group uint32\n+ attr uint64\n+ addr unsafe.Pointer\n+ }{\n+ group: _KVM_VCPU_TSC_CTRL,\n+ attr: _KVM_VCPU_TSC_OFFSET,\n+ addr: unsafe.Pointer(&offset),\n+ }\n+ if _, _, errno := unix.RawSyscall(\n+ unix.SYS_IOCTL,\n+ uintptr(c.fd),\n+ _KVM_SET_DEVICE_ATTR,\n+ uintptr(unsafe.Pointer(&da))); errno != 0 {\n+ return fmt.Errorf(\"error setting tsc offset: %v\", errno)\n+ }\n+ return nil\n+}\n+\n// setTSC sets the TSC value.\nfunc (c *vCPU) setTSC(value uint64) error {\nconst _MSR_IA32_TSC = 0x00000010\n" } ]
Go
Apache License 2.0
google/gvisor
Set TSC offset directly. Fixes #8118 PiperOrigin-RevId: 487422035
259,907
10.11.2022 03:56:38
28,800
93b37dad70ea37c4b873fffa546de286c459df14
Update gofer mount options to only show version for 9P.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/gofer/filesystem.go", "new_path": "pkg/sentry/fsimpl/gofer/filesystem.go", "diff": "@@ -1898,7 +1898,6 @@ func (fs *filesystem) MountOptions() string {\n{moptDfltUID, fs.opts.dfltuid},\n{moptDfltGID, fs.opts.dfltgid},\n{moptMsize, fs.opts.msize},\n- {moptVersion, fs.opts.version},\n}\nswitch fs.opts.interop {\n@@ -1923,7 +1922,11 @@ func (fs *filesystem) MountOptions() string {\noptsKV = append(optsKV, mopt{moptOverlayfsStaleRead, nil})\n}\nif fs.opts.lisaEnabled {\n+ // LISAFS does not have a protocol level version number. Simply add\n+ // `lisafs` in the opts to indicate that we are using LISAFS.\noptsKV = append(optsKV, mopt{moptLisafs, nil})\n+ } else {\n+ optsKV = append(optsKV, mopt{moptVersion, fs.opts.version9P})\n}\nopts := make([]string, 0, len(optsKV))\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/gofer/gofer.go", "new_path": "pkg/sentry/fsimpl/gofer/gofer.go", "diff": "@@ -218,7 +218,7 @@ type filesystemOptions struct {\ndfltuid auth.KUID\ndfltgid auth.KGID\nmsize uint32\n- version string\n+ version9P string\n// If forcePageCache is true, host FDs may not be used for application\n// memory mappings even if available; instead, the client must perform its\n@@ -438,13 +438,6 @@ func (fstype FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.Virt\nfsopts.msize = uint32(msize)\n}\n- // Parse the 9P protocol version.\n- fsopts.version = p9.HighestVersionString()\n- if version, ok := mopts[moptVersion]; ok {\n- delete(mopts, moptVersion)\n- fsopts.version = version\n- }\n-\n// Handle simple flags.\nif _, ok := mopts[moptForcePageCache]; ok {\ndelete(mopts, moptForcePageCache)\n@@ -466,6 +459,14 @@ func (fstype FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.Virt\nreturn nil, nil, linuxerr.EINVAL\n}\n}\n+ if !fsopts.lisaEnabled {\n+ // Parse the 9P protocol version.\n+ fsopts.version9P = p9.HighestVersionString()\n+ if version, ok := mopts[moptVersion]; ok {\n+ delete(mopts, moptVersion)\n+ fsopts.version9P = version\n+ }\n+ }\n// fsopts.regularFilesUseSpecialFileFD can only be enabled by specifying\n// \"cache=none\".\n@@ -673,7 +674,7 @@ func (fs *filesystem) dial(ctx context.Context) error {\n// Perform version negotiation with the server.\nctx.UninterruptibleSleepStart(false)\n- client, err := p9.NewClient(conn, fs.opts.msize, fs.opts.version)\n+ client, err := p9.NewClient(conn, fs.opts.msize, fs.opts.version9P)\nctx.UninterruptibleSleepFinish(false)\nif err != nil {\nconn.Close()\n" } ]
Go
Apache License 2.0
google/gvisor
Update gofer mount options to only show version for 9P. PiperOrigin-RevId: 487493605
259,907
10.11.2022 10:59:50
28,800
ae136df84998ea98f184f9136c71784d37cf4d09
Add nil-check for parent mount in umount(2) while handling mount propagation.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/mount.go", "new_path": "pkg/sentry/vfs/mount.go", "diff": "@@ -654,7 +654,7 @@ func (vfs *VirtualFilesystem) UmountAt(ctx context.Context, creds *auth.Credenti\numountTree := []*Mount{vd.mount}\nparent, mountpoint := vd.mount.parent(), vd.mount.point()\n- if parent.propType == Shared {\n+ if parent != nil && parent.propType == Shared {\nfor peer := parent.sharedList.Front(); peer != nil; peer = peer.sharedEntry.Next() {\nif peer == parent {\ncontinue\n" } ]
Go
Apache License 2.0
google/gvisor
Add nil-check for parent mount in umount(2) while handling mount propagation. PiperOrigin-RevId: 487585583
259,853
11.11.2022 00:33:51
28,800
5a0803c66ec4e080bbd72d1383a1ee5cc2a5d7ff
builtkite: collect runtime logs
[ { "change_type": "MODIFY", "old_path": ".buildkite/hooks/post-command", "new_path": ".buildkite/hooks/post-command", "diff": "@@ -54,8 +54,12 @@ rm -rf \"${profile_output}\"\n# Clean the bazel cache, if there's failure.\nif test \"${BUILDKITE_COMMAND_EXIT_STATUS}\" -ne \"0\"; then\nset -x\n- if [ -d \"/tmp/${BUILDKITE_JOB_ID}/\" ]; then\n- tar -czf \"/tmp/${BUILDKITE_JOB_ID}.tar.gz\" -C /tmp/ \"${BUILDKITE_JOB_ID}\"\n+ # LINT.IfChange\n+ runtime=\"buildkite_runtime_${BUILDKITE_BRANCH}-${BUILDKITE_BUILD_ID}\"\n+ runtime=\"$(echo \"$runtime\" | sed -r 's~[^-_a-z0-9]+~_~g')\"\n+ # LINT.ThenChange(pre-command)\n+ if [ -d \"/tmp/${runtime}/\" ]; then\n+ tar -czf \"/tmp/${BUILDKITE_JOB_ID}.tar.gz\" -C /tmp/ \"${runtime}\"\nbuildkite-agent artifact upload \"/tmp/${BUILDKITE_JOB_ID}.tar.gz\"\nfi\n# Attempt to clear the cache and shut down.\n" }, { "change_type": "MODIFY", "old_path": ".buildkite/hooks/pre-command", "new_path": ".buildkite/hooks/pre-command", "diff": "@@ -35,8 +35,10 @@ export TOTAL_PARTITIONS=${BUILDKITE_PARALLEL_JOB_COUNT:-1}\n# Set the system-wide Docker runtime name after the BuildKite branch name.\n# Remove any slashes and other characters that are not supported in Docker\n# runtime names. The runtime name must be a single valid path component.\n+# LINT.IfChange\nexport RUNTIME=\"buildkite_runtime_${BUILDKITE_BRANCH}-${BUILDKITE_BUILD_ID}\"\nexport RUNTIME=\"$(echo \"$RUNTIME\" | sed -r 's~[^-_a-z0-9]+~_~g')\"\n+# LINT.ThenChange(post-command)\n# If running in a container, set the reload command appropriately.\nif [[ -x /tmp/buildkite-reload-host-docker/reload ]]; then\n" } ]
Go
Apache License 2.0
google/gvisor
builtkite: collect runtime logs PiperOrigin-RevId: 487748622
260,009
11.11.2022 09:17:30
28,800
8756ebc3b406e2f8ea43360902d8a6dfff391236
Netstack: Check address matches the endpoint protocol for IP_DROP_MEMBERSHIP According to syzkaller report, the setsockopt option used was 0x24, which matches with IP_DROP_MEMBERSHIP for which we did not have the equivalent check that we had for IP_ADD_MEMBERSHIP. Reported-by:
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/tests/integration/multicast_broadcast_test.go", "new_path": "pkg/tcpip/tests/integration/multicast_broadcast_test.go", "diff": "@@ -817,11 +817,16 @@ func TestMismatchedMulticastAddressAndProtocol(t *testing.T) {\nInterfaceAddr: utils.Ipv4Addr.Address,\n}\n- // Add membership should succeed when the interface index is specified,\n+ // Add/remove membership should succeed when the interface index is specified,\n// even if a bad interface address is specified.\naddOpt := tcpip.AddMembershipOption(memOpt)\nexpErr := &tcpip.ErrInvalidOptionValue{}\nif err := ep.SetSockOpt(&addOpt); err != expErr {\nt.Fatalf(\"ep.SetSockOpt(&%#v): want %q, got %q\", addOpt, expErr, err)\n}\n+\n+ removeOpt := tcpip.RemoveMembershipOption(memOpt)\n+ if err := ep.SetSockOpt(&removeOpt); err != expErr {\n+ t.Fatalf(\"ep.SetSockOpt(&%#v): want %q, got %q\", addOpt, expErr, err)\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/internal/network/endpoint.go", "new_path": "pkg/tcpip/transport/internal/network/endpoint.go", "diff": "@@ -951,7 +951,7 @@ func (e *Endpoint) SetSockOpt(opt tcpip.SettableSocketOption) tcpip.Error {\ne.multicastMemberships[memToInsert] = struct{}{}\ncase *tcpip.RemoveMembershipOption:\n- if !header.IsV4MulticastAddress(v.MulticastAddr) && !header.IsV6MulticastAddress(v.MulticastAddr) {\n+ if !(header.IsV4MulticastAddress(v.MulticastAddr) && e.netProto == header.IPv4ProtocolNumber) && !(header.IsV6MulticastAddress(v.MulticastAddr) && e.netProto == header.IPv6ProtocolNumber) {\nreturn &tcpip.ErrInvalidOptionValue{}\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Netstack: Check address matches the endpoint protocol for IP_DROP_MEMBERSHIP According to syzkaller report, the setsockopt option used was 0x24, which matches with IP_DROP_MEMBERSHIP for which we did not have the equivalent check that we had for IP_ADD_MEMBERSHIP. Reported-by: syzbot+923097b958e5b74950d1@syzkaller.appspotmail.com PiperOrigin-RevId: 487840922
259,853
11.11.2022 09:36:43
28,800
4b63ff222d437f70369f08e486e59d7dec10b4d4
kvm: handle errors of applyVirtualRegions
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/kvm/machine_amd64.go", "new_path": "pkg/sentry/platform/kvm/machine_amd64.go", "diff": "@@ -445,7 +445,7 @@ func (c *vCPU) SwitchToUser(switchOpts ring0.SwitchOpts, info *linux.SignalInfo)\nfunc (m *machine) mapUpperHalf(pageTable *pagetables.PageTables) {\n// Map all the executable regions so that all the entry functions\n// are mapped in the upper half.\n- applyVirtualRegions(func(vr virtualRegion) {\n+ if err := applyVirtualRegions(func(vr virtualRegion) {\nif excludeVirtualRegion(vr) || vr.filename == \"[vsyscall]\" {\nreturn\n}\n@@ -462,7 +462,9 @@ func (m *machine) mapUpperHalf(pageTable *pagetables.PageTables) {\npagetables.MapOpts{AccessType: hostarch.Execute, Global: true},\nphysical)\n}\n- })\n+ }); err != nil {\n+ panic(fmt.Sprintf(\"error parsing /proc/self/maps: %v\", err))\n+ }\nfor start, end := range m.kernel.EntryRegions() {\nregionLen := end - start\nphysical, length, ok := translateToPhysical(start)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/kvm/machine_arm64.go", "new_path": "pkg/sentry/platform/kvm/machine_arm64.go", "diff": "package kvm\nimport (\n+ \"fmt\"\n\"runtime\"\n\"golang.org/x/sys/unix\"\n@@ -65,7 +66,7 @@ func (m *machine) mapUpperHalf(pageTable *pagetables.PageTables) {\n// physical regions form them.\nfunc archPhysicalRegions(physicalRegions []physicalRegion) []physicalRegion {\nrdRegions := []virtualRegion{}\n- applyVirtualRegions(func(vr virtualRegion) {\n+ if err := applyVirtualRegions(func(vr virtualRegion) {\nif excludeVirtualRegion(vr) {\nreturn // skip region.\n}\n@@ -74,7 +75,9 @@ func archPhysicalRegions(physicalRegions []physicalRegion) []physicalRegion {\nif !vr.accessType.Write && vr.accessType.Read {\nrdRegions = append(rdRegions, vr)\n}\n- })\n+ }); err != nil {\n+ panic(fmt.Sprintf(\"error parsing /proc/self/maps: %v\", err))\n+ }\n// Add an unreachable region.\nrdRegions = append(rdRegions, virtualRegion{\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/kvm/physical_map.go", "new_path": "pkg/sentry/platform/kvm/physical_map.go", "diff": "@@ -60,13 +60,15 @@ func fillAddressSpace() (excludedRegions []region) {\npSize -= reservedMemory\n// Add specifically excluded regions; see excludeVirtualRegion.\n- applyVirtualRegions(func(vr virtualRegion) {\n+ if err := applyVirtualRegions(func(vr virtualRegion) {\nif excludeVirtualRegion(vr) {\nexcludedRegions = append(excludedRegions, vr.region)\nvSize -= vr.length\nlog.Infof(\"excluded: virtual [%x,%x)\", vr.virtual, vr.virtual+vr.length)\n}\n- })\n+ }); err != nil {\n+ panic(fmt.Sprintf(\"error parsing /proc/self/maps: %v\", err))\n+ }\n// Do we need any more work?\nif vSize < pSize {\n" } ]
Go
Apache License 2.0
google/gvisor
kvm: handle errors of applyVirtualRegions PiperOrigin-RevId: 487845220
259,907
14.11.2022 09:55:33
28,800
c97edad873c3edeb16dc68a226007be48b512395
Exclude broken java script DNS runtime tests. These tests fail with runc too. Error: ``` Error: querySrv ENOTFOUND _jabber._tcp.google.com at QueryReqWrap.onresolve [as oncomplete] (node:internal/dns/promises:173:17) { errno: undefined, code: 'ENOTFOUND', syscall: 'querySrv', hostname: '_jabber._tcp.google.com' } ```
[ { "change_type": "MODIFY", "old_path": "test/runtimes/exclude/nodejs16.13.2.csv", "new_path": "test/runtimes/exclude/nodejs16.13.2.csv", "diff": "@@ -2,6 +2,8 @@ test name,bug id,comment\nbenchmark/test-benchmark-napi.js,,Broken test\ninternet/test-dgram-multicast-ssm-multi-process.js,,\ninternet/test-dgram-multicast-ssmv6-multi-process.js,,Broken test\n+internet/test-dns.js,,Broken test\n+internet/test-dns-any.js,,Broken test\nparallel/test-dns-lookupService-promises.js,,Broken test\nparallel/test-http-writable-true-after-close.js,b/171301436,Flaky\nparallel/test-https-selfsigned-no-keycertsign-no-crash.js,,Broken test\n" } ]
Go
Apache License 2.0
google/gvisor
Exclude broken java script DNS runtime tests. These tests fail with runc too. Error: ``` Error: querySrv ENOTFOUND _jabber._tcp.google.com at QueryReqWrap.onresolve [as oncomplete] (node:internal/dns/promises:173:17) { errno: undefined, code: 'ENOTFOUND', syscall: 'querySrv', hostname: '_jabber._tcp.google.com' } ``` PiperOrigin-RevId: 488394772
259,907
14.11.2022 12:05:46
28,800
bd5e1d8f58991203725327c54f40bbf1fad9ab18
Preserve environment when running sudo commands in make_apt.sh. This is so that `DEBIAN_FRONTEND=noninteractive` env var which has been set is in effect while running apt-get commands.
[ { "change_type": "MODIFY", "old_path": "tools/make_apt.sh", "new_path": "tools/make_apt.sh", "diff": "@@ -33,8 +33,8 @@ shift; shift; shift # For \"$@\" below.\nexport DEBIAN_FRONTEND=noninteractive\nfunction apt_install() {\nwhile true; do\n- sudo apt-get update &&\n- sudo apt-get install -y \"$@\" &&\n+ sudo -E apt-get update &&\n+ sudo -E apt-get install -y \"$@\" &&\ntrue\nresult=\"${?}\"\ncase $result in\n" } ]
Go
Apache License 2.0
google/gvisor
Preserve environment when running sudo commands in make_apt.sh. This is so that `DEBIAN_FRONTEND=noninteractive` env var which has been set is in effect while running apt-get commands. PiperOrigin-RevId: 488432544
259,907
14.11.2022 12:46:17
28,800
3eff27293fbada75248111af4bcce75f86b1f6e9
Remove testing for 9P. LISAFS is now default. Updates
[ { "change_type": "MODIFY", "old_path": "test/runner/defs.bzl", "new_path": "test/runner/defs.bzl", "diff": "@@ -69,7 +69,6 @@ def _syscall_test(\nfile_access = \"exclusive\",\noverlay = False,\nadd_host_communication = False,\n- lisafs = True,\nfuse = False,\ncontainer = None,\none_sandbox = True,\n@@ -85,8 +84,6 @@ def _syscall_test(\nname += \"_overlay\"\nif fuse:\nname += \"_fuse\"\n- if not lisafs:\n- name += \"_p9\"\nif network != \"none\":\nname += \"_\" + network + \"net\"\n@@ -139,7 +136,6 @@ def _syscall_test(\n\"--file-access=\" + file_access,\n\"--overlay=\" + str(overlay),\n\"--add-host-communication=\" + str(add_host_communication),\n- \"--lisafs=\" + str(lisafs),\n\"--fuse=\" + str(fuse),\n\"--strace=\" + str(debug),\n\"--debug=\" + str(debug),\n@@ -226,20 +222,6 @@ def syscall_test(\n**kwargs\n)\n- # Generate a P9 variant with the default platform.\n- _syscall_test(\n- test = test,\n- platform = default_platform,\n- use_tmpfs = use_tmpfs,\n- add_host_communication = add_host_communication,\n- tags = platforms[default_platform] + tags,\n- debug = debug,\n- fuse = fuse,\n- container = container,\n- one_sandbox = one_sandbox,\n- lisafs = False,\n- **kwargs\n- )\nif add_overlay:\n_syscall_test(\ntest = test,\n" }, { "change_type": "MODIFY", "old_path": "test/runner/main.go", "new_path": "test/runner/main.go", "diff": "@@ -52,7 +52,6 @@ var (\nfileAccess = flag.String(\"file-access\", \"exclusive\", \"mounts root in exclusive or shared mode\")\noverlay = flag.Bool(\"overlay\", false, \"wrap filesystem mounts with writable tmpfs overlay\")\nfuse = flag.Bool(\"fuse\", false, \"enable FUSE\")\n- lisafs = flag.Bool(\"lisafs\", true, \"enable lisafs protocol if vfs2 is also enabled\")\ncontainer = flag.Bool(\"container\", false, \"run tests in their own namespaces (user ns, network ns, etc), pretending to be root. Implicitly enabled if network=host, or if using network namespaces\")\nsetupContainerPath = flag.String(\"setup-container\", \"\", \"path to setup_container binary (for use with --container)\")\ntrace = flag.Bool(\"trace\", false, \"enables all trace points\")\n@@ -200,7 +199,6 @@ func runRunsc(tc *gtest.TestCase, spec *specs.Spec) error {\n\"-TESTONLY-allow-packet-endpoint-write=true\",\n\"-net-raw=true\",\nfmt.Sprintf(\"-panic-signal=%d\", unix.SIGTERM),\n- fmt.Sprintf(\"-lisafs=%t\", *lisafs),\n\"-watchdog-action=panic\",\n\"-platform\", *platform,\n\"-file-access\", *fileAccess,\n@@ -435,7 +433,6 @@ func runTestCaseRunsc(testBin string, tc *gtest.TestCase, args []string, t *test\nplatformVar = \"TEST_ON_GVISOR\"\nnetworkVar = \"GVISOR_NETWORK\"\nfuseVar = \"FUSE_ENABLED\"\n- lisafsVar = \"LISAFS_ENABLED\"\n)\nenv := append(os.Environ(), platformVar+\"=\"+*platform, networkVar+\"=\"+*network)\nif *platformSupport != \"\" {\n@@ -446,11 +443,6 @@ func runTestCaseRunsc(testBin string, tc *gtest.TestCase, args []string, t *test\n} else {\nenv = append(env, fuseVar+\"=FALSE\")\n}\n- if *lisafs {\n- env = append(env, lisafsVar+\"=TRUE\")\n- } else {\n- env = append(env, lisafsVar+\"=FALSE\")\n- }\n// Remove shard env variables so that the gunit binary does not try to\n// interpret them.\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/connect_external.cc", "new_path": "test/syscalls/linux/connect_external.cc", "diff": "@@ -114,9 +114,6 @@ TEST_P(GoferStreamSeqpacketTest, NonListening) {\n// Bind to a socket, then Listen and Accept.\nTEST_P(GoferStreamSeqpacketTest, BindListenAccept) {\n- // Binding to host socket requires LisaFS.\n- SKIP_IF(IsRunningOnGvisor() && !IsLisafsEnabled());\n-\nstd::string env;\nProtocolSocket proto;\nstd::tie(env, proto) = GetParam();\n" }, { "change_type": "MODIFY", "old_path": "test/util/test_util.cc", "new_path": "test/util/test_util.cc", "diff": "@@ -42,7 +42,6 @@ namespace testing {\nconstexpr char kGvisorNetwork[] = \"GVISOR_NETWORK\";\nconstexpr char kFuseEnabled[] = \"FUSE_ENABLED\";\n-constexpr char kLisafsEnabled[] = \"LISAFS_ENABLED\";\nbool IsRunningOnGvisor() { return GvisorPlatform() != Platform::kNative; }\n@@ -65,11 +64,6 @@ bool IsFUSEEnabled() {\nreturn env && strcmp(env, \"TRUE\") == 0;\n}\n-bool IsLisafsEnabled() {\n- const char* env = getenv(kLisafsEnabled);\n- return env && strncmp(env, \"TRUE\", 4) == 0;\n-}\n-\n// Inline cpuid instruction. Preserve %ebx/%rbx register. In PIC compilations\n// %ebx contains the address of the global offset table. %rbx is occasionally\n// used to address stack variables in presence of dynamic allocas.\n" }, { "change_type": "MODIFY", "old_path": "test/util/test_util.h", "new_path": "test/util/test_util.h", "diff": "@@ -225,7 +225,6 @@ bool IsRunningOnGvisor();\nconst std::string GvisorPlatform();\nbool IsRunningWithHostinet();\nbool IsFUSEEnabled();\n-bool IsLisafsEnabled();\n#ifdef __linux__\nvoid SetupGvisorDeathTest();\n" } ]
Go
Apache License 2.0
google/gvisor
Remove testing for 9P. LISAFS is now default. Updates #7911 PiperOrigin-RevId: 488442569
259,975
14.11.2022 12:53:53
28,800
cf13339a6ebe3854e27b149de40f46987967802f
Fix name in buildkite pipeline.
[ { "change_type": "MODIFY", "old_path": ".buildkite/pipeline.yaml", "new_path": ".buildkite/pipeline.yaml", "diff": "@@ -488,5 +488,5 @@ steps:\nlabel: \":gear: Syscall benchmarks\"\ncommand: make -i benchmark-platforms BENCHMARKS_SUITE=syscall BENCHMARKS_TARGETS=test/benchmarks/base:syscallbench_test\n- <<: *benchmarks\n- label: \":gear: Syscall benchmarks\"\n+ label: \":thread: hackbench benchmarks\"\ncommand: make -i benchmark-platforms BENCHMARKS_SUITE=hackbench BENCHMARKS_TARGETS=test/benchmarks/base:hackbench_test\n" } ]
Go
Apache License 2.0
google/gvisor
Fix name in buildkite pipeline. PiperOrigin-RevId: 488444365
259,992
15.11.2022 11:51:50
28,800
e6f019594e80e0987a12f103a03bca6a4e7138dd
Add read/write syscalls to trace points Closes
[ { "change_type": "MODIFY", "old_path": "examples/seccheck/server.cc", "new_path": "examples/seccheck/server.cc", "diff": "@@ -113,6 +113,7 @@ std::vector<Callback> dispatchers = {\nunpackSyscall<::gvisor::syscall::InotifyAddWatch>,\nunpackSyscall<::gvisor::syscall::InotifyRmWatch>,\nunpackSyscall<::gvisor::syscall::SocketPair>,\n+ unpackSyscall<::gvisor::syscall::Write>,\n};\nvoid unpack(absl::string_view buf) {\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/seccheck/metadata_amd64.go", "new_path": "pkg/sentry/seccheck/metadata_amd64.go", "diff": "@@ -24,6 +24,12 @@ func init() {\nName: \"fd_path\",\n},\n})\n+ addSyscallPoint(1, \"write\", []FieldDesc{\n+ {\n+ ID: FieldSyscallPath,\n+ Name: \"fd_path\",\n+ },\n+ })\naddSyscallPoint(2, \"open\", nil)\naddSyscallPoint(3, \"close\", []FieldDesc{\n{\n@@ -31,6 +37,30 @@ func init() {\nName: \"fd_path\",\n},\n})\n+ addSyscallPoint(17, \"pread64\", []FieldDesc{\n+ {\n+ ID: FieldSyscallPath,\n+ Name: \"fd_path\",\n+ },\n+ })\n+ addSyscallPoint(18, \"pwrite64\", []FieldDesc{\n+ {\n+ ID: FieldSyscallPath,\n+ Name: \"fd_path\",\n+ },\n+ })\n+ addSyscallPoint(19, \"readv\", []FieldDesc{\n+ {\n+ ID: FieldSyscallPath,\n+ Name: \"fd_path\",\n+ },\n+ })\n+ addSyscallPoint(20, \"writev\", []FieldDesc{\n+ {\n+ ID: FieldSyscallPath,\n+ Name: \"fd_path\",\n+ },\n+ })\naddSyscallPoint(41, \"socket\", nil)\naddSyscallPoint(42, \"connect\", []FieldDesc{\n{\n@@ -169,6 +199,30 @@ func init() {\n},\n})\naddSyscallPoint(53, \"socketpair\", nil)\n+ addSyscallPoint(295, \"preadv\", []FieldDesc{\n+ {\n+ ID: FieldSyscallPath,\n+ Name: \"fd_path\",\n+ },\n+ })\n+ addSyscallPoint(296, \"pwritev\", []FieldDesc{\n+ {\n+ ID: FieldSyscallPath,\n+ Name: \"fd_path\",\n+ },\n+ })\n+ addSyscallPoint(327, \"preadv2\", []FieldDesc{\n+ {\n+ ID: FieldSyscallPath,\n+ Name: \"fd_path\",\n+ },\n+ })\n+ addSyscallPoint(328, \"pwritev2\", []FieldDesc{\n+ {\n+ ID: FieldSyscallPath,\n+ Name: \"fd_path\",\n+ },\n+ })\nconst lastSyscallInTable = 441\nfor i := 0; i <= lastSyscallInTable; i++ {\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/seccheck/metadata_arm64.go", "new_path": "pkg/sentry/seccheck/metadata_arm64.go", "diff": "@@ -24,6 +24,48 @@ func init() {\nName: \"fd_path\",\n},\n})\n+ addSyscallPoint(64, \"write\", []FieldDesc{\n+ {\n+ ID: FieldSyscallPath,\n+ Name: \"fd_path\",\n+ },\n+ })\n+ addSyscallPoint(65, \"readv\", []FieldDesc{\n+ {\n+ ID: FieldSyscallPath,\n+ Name: \"fd_path\",\n+ },\n+ })\n+ addSyscallPoint(66, \"writev\", []FieldDesc{\n+ {\n+ ID: FieldSyscallPath,\n+ Name: \"fd_path\",\n+ },\n+ })\n+ addSyscallPoint(67, \"pread64\", []FieldDesc{\n+ {\n+ ID: FieldSyscallPath,\n+ Name: \"fd_path\",\n+ },\n+ })\n+ addSyscallPoint(68, \"pwrite64\", []FieldDesc{\n+ {\n+ ID: FieldSyscallPath,\n+ Name: \"fd_path\",\n+ },\n+ })\n+ addSyscallPoint(69, \"preadv\", []FieldDesc{\n+ {\n+ ID: FieldSyscallPath,\n+ Name: \"fd_path\",\n+ },\n+ })\n+ addSyscallPoint(70, \"pwritev\", []FieldDesc{\n+ {\n+ ID: FieldSyscallPath,\n+ Name: \"fd_path\",\n+ },\n+ })\naddSyscallPoint(57, \"close\", []FieldDesc{\n{\nID: FieldSyscallPath,\n@@ -145,6 +187,18 @@ func init() {\n},\n})\naddSyscallPoint(199, \"socketpair\", nil)\n+ addSyscallPoint(286, \"preadv2\", []FieldDesc{\n+ {\n+ ID: FieldSyscallPath,\n+ Name: \"fd_path\",\n+ },\n+ })\n+ addSyscallPoint(287, \"pwritev2\", []FieldDesc{\n+ {\n+ ID: FieldSyscallPath,\n+ Name: \"fd_path\",\n+ },\n+ })\nconst lastSyscallInTable = 441\nfor i := 0; i <= lastSyscallInTable; i++ {\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/seccheck/points/common.proto", "new_path": "pkg/sentry/seccheck/points/common.proto", "diff": "@@ -131,5 +131,6 @@ enum MessageType {\nMESSAGE_SYSCALL_INOTIFY_ADD_WATCH = 31;\nMESSAGE_SYSCALL_INOTIFY_RM_WATCH = 32;\nMESSAGE_SYSCALL_SOCKETPAIR = 33;\n+ MESSAGE_SYSCALL_WRITE = 34;\n}\n// LINT.ThenChange(../../../../examples/seccheck/server.cc)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/seccheck/points/syscall.proto", "new_path": "pkg/sentry/seccheck/points/syscall.proto", "diff": "@@ -61,6 +61,21 @@ message Read {\nint64 fd = 4;\nstring fd_path = 5;\nuint64 count = 6;\n+ bool has_offset = 7;\n+ int64 offset = 8;\n+ uint32 flags = 9;\n+}\n+\n+message Write {\n+ gvisor.common.ContextData context_data = 1;\n+ Exit exit = 2;\n+ uint64 sysno = 3;\n+ int64 fd = 4;\n+ string fd_path = 5;\n+ uint64 count = 6;\n+ bool has_offset = 7;\n+ int64 offset = 8;\n+ uint32 flags = 9;\n}\nmessage Connect {\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/linux64.go", "new_path": "pkg/sentry/syscalls/linux/linux64.go", "diff": "@@ -53,7 +53,7 @@ var AMD64 = &kernel.SyscallTable{\nAuditNumber: linux.AUDIT_ARCH_X86_64,\nTable: map[uintptr]kernel.Syscall{\n0: syscalls.SupportedPoint(\"read\", Read, PointRead),\n- 1: syscalls.Supported(\"write\", Write),\n+ 1: syscalls.SupportedPoint(\"write\", Write, PointWrite),\n2: syscalls.SupportedPoint(\"open\", Open, PointOpen),\n3: syscalls.SupportedPoint(\"close\", Close, PointClose),\n4: syscalls.Supported(\"stat\", Stat),\n@@ -69,10 +69,10 @@ var AMD64 = &kernel.SyscallTable{\n14: syscalls.Supported(\"rt_sigprocmask\", RtSigprocmask),\n15: syscalls.Supported(\"rt_sigreturn\", RtSigreturn),\n16: syscalls.Supported(\"ioctl\", Ioctl),\n- 17: syscalls.Supported(\"pread64\", Pread64),\n- 18: syscalls.Supported(\"pwrite64\", Pwrite64),\n- 19: syscalls.Supported(\"readv\", Readv),\n- 20: syscalls.Supported(\"writev\", Writev),\n+ 17: syscalls.SupportedPoint(\"pread64\", Pread64, PointPread64),\n+ 18: syscalls.SupportedPoint(\"pwrite64\", Pwrite64, PointPwrite64),\n+ 19: syscalls.SupportedPoint(\"readv\", Readv, PointReadv),\n+ 20: syscalls.SupportedPoint(\"writev\", Writev, PointWritev),\n21: syscalls.Supported(\"access\", Access),\n22: syscalls.SupportedPoint(\"pipe\", Pipe, PointPipe),\n23: syscalls.Supported(\"select\", Select),\n@@ -347,8 +347,8 @@ var AMD64 = &kernel.SyscallTable{\n292: syscalls.SupportedPoint(\"dup3\", Dup3, PointDup3),\n293: syscalls.SupportedPoint(\"pipe2\", Pipe2, PointPipe2),\n294: syscalls.PartiallySupportedPoint(\"inotify_init1\", InotifyInit1, PointInotifyInit1, \"inotify events are only available inside the sandbox.\", nil),\n- 295: syscalls.Supported(\"preadv\", Preadv),\n- 296: syscalls.Supported(\"pwritev\", Pwritev),\n+ 295: syscalls.SupportedPoint(\"preadv\", Preadv, PointPreadv),\n+ 296: syscalls.SupportedPoint(\"pwritev\", Pwritev, PointPwritev),\n297: syscalls.Supported(\"rt_tgsigqueueinfo\", RtTgsigqueueinfo),\n298: syscalls.ErrorWithEvent(\"perf_event_open\", linuxerr.ENODEV, \"No support for perf counters\", nil),\n299: syscalls.Supported(\"recvmmsg\", RecvMMsg),\n@@ -382,8 +382,8 @@ var AMD64 = &kernel.SyscallTable{\n// Syscalls implemented after 325 are \"backports\" from versions\n// of Linux after 4.4.\n326: syscalls.ErrorWithEvent(\"copy_file_range\", linuxerr.ENOSYS, \"\", nil),\n- 327: syscalls.Supported(\"preadv2\", Preadv2),\n- 328: syscalls.Supported(\"pwritev2\", Pwritev2),\n+ 327: syscalls.SupportedPoint(\"preadv2\", Preadv2, PointPreadv2),\n+ 328: syscalls.SupportedPoint(\"pwritev2\", Pwritev2, PointPwritev2),\n329: syscalls.ErrorWithEvent(\"pkey_mprotect\", linuxerr.ENOSYS, \"\", nil),\n330: syscalls.ErrorWithEvent(\"pkey_alloc\", linuxerr.ENOSYS, \"\", nil),\n331: syscalls.ErrorWithEvent(\"pkey_free\", linuxerr.ENOSYS, \"\", nil),\n@@ -495,13 +495,13 @@ var ARM64 = &kernel.SyscallTable{\n61: syscalls.Supported(\"getdents64\", Getdents64),\n62: syscalls.Supported(\"lseek\", Lseek),\n63: syscalls.SupportedPoint(\"read\", Read, PointRead),\n- 64: syscalls.Supported(\"write\", Write),\n- 65: syscalls.Supported(\"readv\", Readv),\n- 66: syscalls.Supported(\"writev\", Writev),\n- 67: syscalls.Supported(\"pread64\", Pread64),\n- 68: syscalls.Supported(\"pwrite64\", Pwrite64),\n- 69: syscalls.Supported(\"preadv\", Preadv),\n- 70: syscalls.Supported(\"pwritev\", Pwritev),\n+ 64: syscalls.SupportedPoint(\"write\", Write, PointWrite),\n+ 65: syscalls.SupportedPoint(\"readv\", Readv, PointReadv),\n+ 66: syscalls.SupportedPoint(\"writev\", Writev, PointWritev),\n+ 67: syscalls.SupportedPoint(\"pread64\", Pread64, PointPread64),\n+ 68: syscalls.SupportedPoint(\"pwrite64\", Pwrite64, PointPwrite64),\n+ 69: syscalls.SupportedPoint(\"preadv\", Preadv, PointPreadv),\n+ 70: syscalls.SupportedPoint(\"pwritev\", Pwritev, PointPwritev),\n71: syscalls.Supported(\"sendfile\", Sendfile),\n72: syscalls.Supported(\"pselect\", Pselect),\n73: syscalls.Supported(\"ppoll\", Ppoll),\n@@ -703,8 +703,8 @@ var ARM64 = &kernel.SyscallTable{\n// Syscalls after 284 are \"backports\" from versions of Linux after 4.4.\n285: syscalls.ErrorWithEvent(\"copy_file_range\", linuxerr.ENOSYS, \"\", nil),\n- 286: syscalls.Supported(\"preadv2\", Preadv2),\n- 287: syscalls.Supported(\"pwritev2\", Pwritev2),\n+ 286: syscalls.SupportedPoint(\"preadv2\", Preadv2, PointPreadv2),\n+ 287: syscalls.SupportedPoint(\"pwritev2\", Pwritev2, PointPwritev2),\n288: syscalls.ErrorWithEvent(\"pkey_mprotect\", linuxerr.ENOSYS, \"\", nil),\n289: syscalls.ErrorWithEvent(\"pkey_alloc\", linuxerr.ENOSYS, \"\", nil),\n290: syscalls.ErrorWithEvent(\"pkey_free\", linuxerr.ENOSYS, \"\", nil),\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/points.go", "new_path": "pkg/sentry/syscalls/linux/points.go", "diff": "@@ -24,6 +24,7 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n\"gvisor.dev/gvisor/pkg/sentry/seccheck\"\npb \"gvisor.dev/gvisor/pkg/sentry/seccheck/points/points_go_proto\"\n+ \"gvisor.dev/gvisor/pkg/usermem\"\n)\nfunc newExitMaybe(info kernel.SyscallInfo) *pb.Exit {\n@@ -58,6 +59,14 @@ func getFilePath(t *kernel.Task, fd int32) string {\nreturn path\n}\n+func getIovecSize(t *kernel.Task, addr hostarch.Addr, iovcnt int) uint64 {\n+ dst, err := t.IovecsIOSequence(addr, iovcnt, usermem.IOOpts{AddressSpaceActive: true})\n+ if err != nil {\n+ return 0\n+ }\n+ return uint64(dst.NumBytes())\n+}\n+\n// PointOpen converts open(2) syscall to proto.\nfunc PointOpen(t *kernel.Task, _ seccheck.FieldSet, cxtData *pb.ContextData, info kernel.SyscallInfo) (proto.Message, pb.MessageType) {\np := &pb.Open{\n@@ -167,6 +176,173 @@ func PointRead(t *kernel.Task, fields seccheck.FieldSet, cxtData *pb.ContextData\nreturn p, pb.MessageType_MESSAGE_SYSCALL_READ\n}\n+// PointPread64 converts pread64(2) syscall to proto.\n+func PointPread64(t *kernel.Task, fields seccheck.FieldSet, cxtData *pb.ContextData, info kernel.SyscallInfo) (proto.Message, pb.MessageType) {\n+ p := &pb.Read{\n+ ContextData: cxtData,\n+ Sysno: uint64(info.Sysno),\n+ Fd: int64(info.Args[0].Int()),\n+ Count: uint64(info.Args[2].SizeT()),\n+ HasOffset: true,\n+ Offset: info.Args[3].Int64(),\n+ }\n+ if fields.Local.Contains(seccheck.FieldSyscallPath) {\n+ p.FdPath = getFilePath(t, int32(p.Fd))\n+ }\n+\n+ p.Exit = newExitMaybe(info)\n+\n+ return p, pb.MessageType_MESSAGE_SYSCALL_READ\n+}\n+\n+// PointReadv converts readv(2) syscall to proto.\n+func PointReadv(t *kernel.Task, fields seccheck.FieldSet, cxtData *pb.ContextData, info kernel.SyscallInfo) (proto.Message, pb.MessageType) {\n+ p := &pb.Read{\n+ ContextData: cxtData,\n+ Sysno: uint64(info.Sysno),\n+ Fd: int64(info.Args[0].Int()),\n+ Count: getIovecSize(t, info.Args[1].Pointer(), int(info.Args[2].Int())),\n+ }\n+ if fields.Local.Contains(seccheck.FieldSyscallPath) {\n+ p.FdPath = getFilePath(t, int32(p.Fd))\n+ }\n+\n+ p.Exit = newExitMaybe(info)\n+\n+ return p, pb.MessageType_MESSAGE_SYSCALL_READ\n+}\n+\n+// PointPreadv converts preadv(2) syscall to proto.\n+func PointPreadv(t *kernel.Task, fields seccheck.FieldSet, cxtData *pb.ContextData, info kernel.SyscallInfo) (proto.Message, pb.MessageType) {\n+ p := &pb.Read{\n+ ContextData: cxtData,\n+ Sysno: uint64(info.Sysno),\n+ Fd: int64(info.Args[0].Int()),\n+ Count: getIovecSize(t, info.Args[1].Pointer(), int(info.Args[2].Int())),\n+ HasOffset: true,\n+ Offset: info.Args[3].Int64(),\n+ }\n+ if fields.Local.Contains(seccheck.FieldSyscallPath) {\n+ p.FdPath = getFilePath(t, int32(p.Fd))\n+ }\n+\n+ p.Exit = newExitMaybe(info)\n+\n+ return p, pb.MessageType_MESSAGE_SYSCALL_READ\n+}\n+\n+// PointPreadv2 converts preadv2(2) syscall to proto.\n+func PointPreadv2(t *kernel.Task, fields seccheck.FieldSet, cxtData *pb.ContextData, info kernel.SyscallInfo) (proto.Message, pb.MessageType) {\n+ p := &pb.Read{\n+ ContextData: cxtData,\n+ Sysno: uint64(info.Sysno),\n+ Fd: int64(info.Args[0].Int()),\n+ Count: getIovecSize(t, info.Args[1].Pointer(), int(info.Args[2].Int())),\n+ HasOffset: true,\n+ Offset: info.Args[3].Int64(),\n+ Flags: info.Args[5].Uint(),\n+ }\n+ if fields.Local.Contains(seccheck.FieldSyscallPath) {\n+ p.FdPath = getFilePath(t, int32(p.Fd))\n+ }\n+\n+ p.Exit = newExitMaybe(info)\n+\n+ return p, pb.MessageType_MESSAGE_SYSCALL_READ\n+}\n+\n+// PointWrite converts write(2) syscall to proto.\n+func PointWrite(t *kernel.Task, fields seccheck.FieldSet, cxtData *pb.ContextData, info kernel.SyscallInfo) (proto.Message, pb.MessageType) {\n+ p := &pb.Write{\n+ ContextData: cxtData,\n+ Sysno: uint64(info.Sysno),\n+ Fd: int64(info.Args[0].Int()),\n+ Count: uint64(info.Args[2].SizeT()),\n+ }\n+ if fields.Local.Contains(seccheck.FieldSyscallPath) {\n+ p.FdPath = getFilePath(t, int32(p.Fd))\n+ }\n+\n+ p.Exit = newExitMaybe(info)\n+\n+ return p, pb.MessageType_MESSAGE_SYSCALL_WRITE\n+}\n+\n+// PointPwrite64 converts pwrite64(2) syscall to proto.\n+func PointPwrite64(t *kernel.Task, fields seccheck.FieldSet, cxtData *pb.ContextData, info kernel.SyscallInfo) (proto.Message, pb.MessageType) {\n+ p := &pb.Write{\n+ ContextData: cxtData,\n+ Sysno: uint64(info.Sysno),\n+ Fd: int64(info.Args[0].Int()),\n+ Count: uint64(info.Args[2].SizeT()),\n+ HasOffset: true,\n+ Offset: info.Args[3].Int64(),\n+ }\n+ if fields.Local.Contains(seccheck.FieldSyscallPath) {\n+ p.FdPath = getFilePath(t, int32(p.Fd))\n+ }\n+\n+ p.Exit = newExitMaybe(info)\n+\n+ return p, pb.MessageType_MESSAGE_SYSCALL_WRITE\n+}\n+\n+// PointWritev converts writev(2) syscall to proto.\n+func PointWritev(t *kernel.Task, fields seccheck.FieldSet, cxtData *pb.ContextData, info kernel.SyscallInfo) (proto.Message, pb.MessageType) {\n+ p := &pb.Write{\n+ ContextData: cxtData,\n+ Sysno: uint64(info.Sysno),\n+ Fd: int64(info.Args[0].Int()),\n+ Count: getIovecSize(t, info.Args[1].Pointer(), int(info.Args[2].Int())),\n+ }\n+ if fields.Local.Contains(seccheck.FieldSyscallPath) {\n+ p.FdPath = getFilePath(t, int32(p.Fd))\n+ }\n+\n+ p.Exit = newExitMaybe(info)\n+\n+ return p, pb.MessageType_MESSAGE_SYSCALL_WRITE\n+}\n+\n+// PointPwritev converts pwritev(2) syscall to proto.\n+func PointPwritev(t *kernel.Task, fields seccheck.FieldSet, cxtData *pb.ContextData, info kernel.SyscallInfo) (proto.Message, pb.MessageType) {\n+ p := &pb.Write{\n+ ContextData: cxtData,\n+ Sysno: uint64(info.Sysno),\n+ Fd: int64(info.Args[0].Int()),\n+ Count: getIovecSize(t, info.Args[1].Pointer(), int(info.Args[2].Int())),\n+ HasOffset: true,\n+ Offset: info.Args[3].Int64(),\n+ }\n+ if fields.Local.Contains(seccheck.FieldSyscallPath) {\n+ p.FdPath = getFilePath(t, int32(p.Fd))\n+ }\n+\n+ p.Exit = newExitMaybe(info)\n+\n+ return p, pb.MessageType_MESSAGE_SYSCALL_WRITE\n+}\n+\n+// PointPwritev2 converts pwritev2(2) syscall to proto.\n+func PointPwritev2(t *kernel.Task, fields seccheck.FieldSet, cxtData *pb.ContextData, info kernel.SyscallInfo) (proto.Message, pb.MessageType) {\n+ p := &pb.Write{\n+ ContextData: cxtData,\n+ Sysno: uint64(info.Sysno),\n+ Fd: int64(info.Args[0].Int()),\n+ Count: getIovecSize(t, info.Args[1].Pointer(), int(info.Args[2].Int())),\n+ HasOffset: true,\n+ Offset: info.Args[3].Int64(),\n+ Flags: info.Args[5].Uint(),\n+ }\n+ if fields.Local.Contains(seccheck.FieldSyscallPath) {\n+ p.FdPath = getFilePath(t, int32(p.Fd))\n+ }\n+\n+ p.Exit = newExitMaybe(info)\n+\n+ return p, pb.MessageType_MESSAGE_SYSCALL_WRITE\n+}\n+\n// PointSocket converts socket(2) syscall to proto.\nfunc PointSocket(_ *kernel.Task, _ seccheck.FieldSet, cxtData *pb.ContextData, info kernel.SyscallInfo) (proto.Message, pb.MessageType) {\np := &pb.Socket{\n" }, { "change_type": "MODIFY", "old_path": "test/trace/trace_test.go", "new_path": "test/trace/trace_test.go", "diff": "@@ -108,6 +108,7 @@ func matchPoints(t *testing.T, msgs []test.Message) {\npb.MessageType_MESSAGE_SYSCALL_RAW: {checker: checkSyscallRaw},\npb.MessageType_MESSAGE_SYSCALL_READ: {checker: checkSyscallRead},\npb.MessageType_MESSAGE_SYSCALL_SOCKET: {checker: checkSyscallSocket},\n+ pb.MessageType_MESSAGE_SYSCALL_WRITE: {checker: checkSyscallWrite},\n// TODO(gvisor.dev/issue/4805): Add validation for these messages.\npb.MessageType_MESSAGE_SYSCALL_ACCEPT: {checker: checkTODO},\n@@ -291,7 +292,44 @@ func checkSyscallRead(msg test.Message) error {\n}\nif p.Fd < 0 {\n// Although negative FD is possible, it doesn't happen in the test.\n- return fmt.Errorf(\"reading negative FD: %d\", p.Fd)\n+ return fmt.Errorf(\"read negative FD: %d\", p.Fd)\n+ }\n+ if p.HasOffset {\n+ // Workload always uses 20 for read offsets (account for partial reads).\n+ if lower, upper := int64(20), int64(120); p.Offset < lower && p.Offset > upper {\n+ return fmt.Errorf(\"invalid offset, want: [%d, %d], got: %d\", lower, upper, p.Offset)\n+ }\n+ } else if p.Offset != 0 {\n+ return fmt.Errorf(\"offset should be 0: %+v\", &p)\n+ }\n+ if p.Flags != 0 && p.Flags != unix.RWF_HIPRI {\n+ return fmt.Errorf(\"invalid flag value, want: 0 || RWF_HIPRI, got: %+x\", p.Flags)\n+ }\n+ return nil\n+}\n+\n+func checkSyscallWrite(msg test.Message) error {\n+ p := pb.Write{}\n+ if err := proto.Unmarshal(msg.Msg, &p); err != nil {\n+ return err\n+ }\n+ if err := checkContextData(p.ContextData); err != nil {\n+ return err\n+ }\n+ if p.Fd < 0 {\n+ // Although negative FD is possible, it doesn't happen in the test.\n+ return fmt.Errorf(\"write negative FD: %d\", p.Fd)\n+ }\n+ if p.HasOffset {\n+ // Workload always uses 10 for write offsets (account for partial writes).\n+ if lower, upper := int64(10), int64(110); p.Offset < lower && p.Offset > upper {\n+ return fmt.Errorf(\"invalid offset, want: [%d, %d], got: %d\", lower, upper, p.Offset)\n+ }\n+ } else if p.Offset != 0 {\n+ return fmt.Errorf(\"offset should be 0: %+v\", &p)\n+ }\n+ if p.Flags != 0 && p.Flags != unix.RWF_HIPRI {\n+ return fmt.Errorf(\"invalid flag value, want: 0 || RWF_HIPRI, got: %+x\", p.Flags)\n}\nreturn nil\n}\n" }, { "change_type": "MODIFY", "old_path": "test/trace/workload/workload.cc", "new_path": "test/trace/workload/workload.cc", "diff": "@@ -115,12 +115,88 @@ void runSocket() {\n}\n}\n+void runReadWrite() {\n+ const std::string path = \"read-write.txt\";\n+ auto fd_or = Open(path, O_RDWR | O_CREAT, 0644);\n+ if (!fd_or.ok()) {\n+ err(1, \"open(O_CREAT): %s\", fd_or.error().ToString().c_str());\n+ }\n+ auto cleaup = absl::MakeCleanup([path] { unlink(path.c_str()); });\n+\n+ auto fd = std::move(fd_or.ValueOrDie());\n+\n+ // Test different flavors of write.\n+ char msg[] = \"hello world\";\n+ if (WriteFd(fd.get(), msg, ABSL_ARRAYSIZE(msg)) < 0) {\n+ err(1, \"write\");\n+ }\n+ if (PwriteFd(fd.get(), msg, ABSL_ARRAYSIZE(msg), 10) < 0) {\n+ err(1, \"pwrite\");\n+ }\n+\n+ struct iovec write_vecs[] = {\n+ {\n+ .iov_base = msg,\n+ .iov_len = ABSL_ARRAYSIZE(msg),\n+ },\n+ {\n+ .iov_base = msg,\n+ .iov_len = ABSL_ARRAYSIZE(msg) / 2,\n+ },\n+ };\n+ if (writev(fd.get(), write_vecs, ABSL_ARRAYSIZE(write_vecs)) < 0) {\n+ err(1, \"writev\");\n+ }\n+ if (pwritev(fd.get(), write_vecs, ABSL_ARRAYSIZE(write_vecs), 10) < 0) {\n+ err(1, \"pwritev\");\n+ }\n+ if (pwritev2(fd.get(), write_vecs, ABSL_ARRAYSIZE(write_vecs), 10,\n+ RWF_HIPRI) < 0) {\n+ err(1, \"pwritev2\");\n+ }\n+\n+ // Rewind the file and test different flavors of read.\n+ if (lseek(fd.get(), 0, SEEK_SET) < 0) {\n+ err(1, \"seek(0)\");\n+ }\n+ char buf[1024];\n+ if (ReadFd(fd.get(), buf, ABSL_ARRAYSIZE(buf)) < 0) {\n+ err(1, \"read\");\n+ }\n+ if (PreadFd(fd.get(), buf, ABSL_ARRAYSIZE(buf), 20) < 0) {\n+ err(1, \"read\");\n+ }\n+\n+ // Reuse same buffer, since it's not using the result anyways.\n+ struct iovec read_vecs[] = {\n+ {\n+ .iov_base = buf,\n+ .iov_len = ABSL_ARRAYSIZE(msg),\n+ },\n+ {\n+ .iov_base = buf,\n+ .iov_len = ABSL_ARRAYSIZE(msg) / 2,\n+ },\n+ };\n+ if (readv(fd.get(), read_vecs, ABSL_ARRAYSIZE(read_vecs)) < 0) {\n+ err(1, \"writev\");\n+ }\n+ if (preadv(fd.get(), read_vecs, ABSL_ARRAYSIZE(read_vecs), 20) < 0) {\n+ err(1, \"pwritev\");\n+ }\n+ if (preadv2(fd.get(), read_vecs, ABSL_ARRAYSIZE(read_vecs), 20, RWF_HIPRI) <\n+ 0) {\n+ err(1, \"pwritev2\");\n+ }\n+}\n+\n} // namespace testing\n} // namespace gvisor\nint main(int argc, char** argv) {\n::gvisor::testing::runForkExecve();\n::gvisor::testing::runSocket();\n+ ::gvisor::testing::runReadWrite();\nreturn 0;\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Add read/write syscalls to trace points Closes #8092 PiperOrigin-RevId: 488719448
259,992
15.11.2022 11:55:37
28,800
258f27eedae2fd7ba7c1b2b0c2d829c4a6fef41e
Add tool to analyze stuck task dumps It creates a histogram of all unique stacks in the dump. Then prints them in order, marking the ones that were stuck.
[ { "change_type": "ADD", "old_path": null, "new_path": "tools/stucktasks/BUILD", "diff": "+load(\"//tools:defs.bzl\", \"go_binary\")\n+\n+package(licenses = [\"notice\"])\n+\n+go_binary(\n+ name = \"stucktasks\",\n+ srcs = [\"stucktasks.go\"],\n+ deps = [\n+ \"//runsc/flag\",\n+ ],\n+)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "tools/stucktasks/stucktasks.go", "diff": "+// Copyright 2022 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+// Package main implements a tool to help troubleshoot watchdog dumps.\n+package main\n+\n+import (\n+ \"bufio\"\n+ \"fmt\"\n+ \"io\"\n+ \"os\"\n+ \"path/filepath\"\n+ \"regexp\"\n+ \"sort\"\n+ \"strconv\"\n+ \"strings\"\n+\n+ \"gvisor.dev/gvisor/runsc/flag\"\n+)\n+\n+var (\n+ flagStacks = flag.String(\"stacks\", \"\", \"path to log file containing stuck task stacks.\")\n+ flagOut = flag.String(\"out\", \"\", \"path to output file (default: STDERR).\")\n+)\n+\n+func main() {\n+ flag.Parse()\n+\n+ // Mandatory fields missing, print usage.\n+ if len(*flagStacks) == 0 {\n+ fmt.Fprintln(os.Stderr, \"Usage:\")\n+ fmt.Fprintf(os.Stderr, \"\\t%s --stacks=<path> [--out=<path>]\\n\", filepath.Base(os.Args[0]))\n+ os.Exit(1)\n+ }\n+\n+ in, err := os.Open(*flagStacks)\n+ if err != nil {\n+ fatal(err)\n+ }\n+ defer in.Close()\n+\n+ var out io.Writer = os.Stdout\n+ if len(*flagOut) > 0 {\n+ f, err := os.Create(*flagOut)\n+ if err != nil {\n+ fatal(err)\n+ }\n+ defer f.Close()\n+ out = f\n+ }\n+\n+ if err := analyze(in, out); err != nil {\n+ fatal(err)\n+ }\n+}\n+\n+func fatal(err error) {\n+ fatalf(\"%v\", err)\n+}\n+\n+func fatalf(format string, args ...any) {\n+ fmt.Fprintf(os.Stderr, format+\"\\n\", args...)\n+ os.Exit(1)\n+}\n+\n+func analyze(in io.Reader, out io.Writer) error {\n+ scanner := bufio.NewScanner(in)\n+ for scanner.Scan() {\n+ line := scanner.Text()\n+ if strings.Contains(line, \"stuck task(s)\") {\n+ return analyzeStuckTasks(scanner, out)\n+ }\n+ if strings.Contains(line, \"Watchdog goroutine is stuck\") {\n+ return analyzeStackDump(scanner, out, nil)\n+ }\n+ // Skip all lines before the watchdog dump.\n+ }\n+ return fmt.Errorf(\"watchdog header not found\")\n+}\n+\n+func analyzeStuckTasks(scanner *bufio.Scanner, out io.Writer) error {\n+ // Look for stuck tasks goroutine. The output has the folowing format:\n+ // Task tid: 123 (goroutine 45), entered RunSys state 3m28.77s ago.\n+ ids := make(map[uint]struct{})\n+ for scanner.Scan() {\n+ line := scanner.Text()\n+ id, err := parseGoroutineID(line)\n+ if err != nil {\n+ // All stuck tasks were collected, the log is followed by the stack dump.\n+ return analyzeStackDump(scanner, out, ids)\n+ }\n+ ids[id] = struct{}{}\n+ }\n+ return fmt.Errorf(\"not able to find stuck task IDs\")\n+}\n+\n+func analyzeStackDump(scanner *bufio.Scanner, out io.Writer, stuckIds map[uint]struct{}) error {\n+ stacks, err := collectStacks(scanner)\n+ if err != nil {\n+ return nil\n+ }\n+\n+ // Create histogram with all unique stacks.\n+ type counter struct {\n+ count int\n+ ids []uint\n+ *stack\n+ }\n+ uniq := make(map[string]*counter)\n+ for _, stack := range stacks {\n+ c := uniq[stack.signature]\n+ if c == nil {\n+ c = &counter{stack: stack}\n+ uniq[stack.signature] = c\n+ }\n+ c.count++\n+ c.ids = append(c.ids, stack.id)\n+ }\n+\n+ // Sort them in reverse order, to print most occurring at the top.\n+ var sorted []*counter\n+ for _, c := range uniq {\n+ sorted = append(sorted, c)\n+ }\n+ sort.Slice(sorted, func(i, j int) bool {\n+ // Reverse sort\n+ return sorted[i].count > sorted[j].count\n+ })\n+\n+ fmt.Fprintf(out, \"Stacks: %d, unique: %d\\n\\n\", len(stacks), len(sorted))\n+ for _, c := range sorted {\n+ fmt.Fprintf(out, \"=== Stack (count: %d) ===\\ngoroutine IDs: %v\\n\", c.count, c.ids)\n+ var stucks []uint\n+ for _, id := range c.ids {\n+ if _, ok := stuckIds[id]; ok {\n+ stucks = append(stucks, id)\n+ }\n+ }\n+ if len(stucks) > 0 {\n+ fmt.Fprintf(out, \"*** Stuck goroutines: %v ***\\n\", stucks)\n+ }\n+ fmt.Fprintln(out)\n+ for _, line := range c.lines {\n+ fmt.Fprintln(out, line)\n+ }\n+ fmt.Fprintln(out)\n+ }\n+\n+ return nil\n+}\n+\n+// collectStacks parses the input to find stack dump. Expected format is:\n+//\n+// goroutine ID [reason, time]:\n+// package.function(args)\n+// GOROOT/path/file.go:line +offset\n+// <blank line between stacks>\n+func collectStacks(scanner *bufio.Scanner) ([]*stack, error) {\n+ var stacks []*stack\n+ var block []string\n+ for scanner.Scan() {\n+ line := scanner.Text()\n+\n+ // Expect the first line of a block to be the goroutine header:\n+ // goroutine 43 [select, 19 minutes]:\n+ if len(block) == 0 {\n+ if _, err := parseGoroutineID(line); err != nil {\n+ // If not the header and no stacks have been found yet, skip the line\n+ // until the start of stack dump is found.\n+ if len(stacks) == 0 {\n+ continue\n+ }\n+ // if stacks has been found, it means we reached the end of the dump and\n+ // more logging lines exist in the file.\n+ break\n+ }\n+ }\n+\n+ // A blank line means that we reached the end of the block\n+ if len(strings.TrimSpace(line)) > 0 {\n+ block = append(block, line)\n+ continue\n+ }\n+ stack, err := parseBlock(block)\n+ if err != nil {\n+ return nil, err\n+ }\n+ stacks = append(stacks, stack)\n+ block = nil\n+ }\n+ return stacks, nil\n+}\n+\n+func parseBlock(block []string) (*stack, error) {\n+ id, err := parseGoroutineID(block[0])\n+ if err != nil {\n+ return nil, err\n+ }\n+\n+ var signature string\n+ for i, line := range block[1:] {\n+ if i%2 == 1 {\n+ signature += line + \"\\n\"\n+ }\n+ }\n+\n+ return &stack{\n+ id: uint(id),\n+ signature: signature,\n+ lines: block[1:],\n+ }, nil\n+}\n+\n+func parseGoroutineID(line string) (uint, error) {\n+ r := regexp.MustCompile(`goroutine (\\d+)`)\n+ matches := r.FindStringSubmatch(line)\n+ if len(matches) != 2 {\n+ return 0, fmt.Errorf(\"invalid goroutine ID line: %q\", line)\n+ }\n+ id, err := strconv.Atoi(matches[1])\n+ if err != nil {\n+ return 0, fmt.Errorf(\"parsing goroutine ID, line: %q: %w\", line, err)\n+ }\n+ return uint(id), nil\n+}\n+\n+type stack struct {\n+ id uint\n+ signature string\n+ lines []string\n+}\n" } ]
Go
Apache License 2.0
google/gvisor
Add tool to analyze stuck task dumps It creates a histogram of all unique stacks in the dump. Then prints them in order, marking the ones that were stuck. PiperOrigin-RevId: 488720415
259,907
15.11.2022 13:13:20
28,800
7c3ff55fab59c13929442089fdcf96cbc98d2bb5
Update fd_table_test to use VFS2. This unit test had been using VFS1. Updates
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/BUILD", "new_path": "pkg/sentry/kernel/BUILD", "diff": "@@ -387,13 +387,12 @@ go_test(\n\"//pkg/hostarch\",\n\"//pkg/sentry/arch\",\n\"//pkg/sentry/contexttest\",\n- \"//pkg/sentry/fs\",\n- \"//pkg/sentry/fs/filetest\",\n\"//pkg/sentry/kernel/sched\",\n\"//pkg/sentry/limits\",\n\"//pkg/sentry/pgalloc\",\n\"//pkg/sentry/time\",\n\"//pkg/sentry/usage\",\n+ \"//pkg/sentry/vfs\",\n\"//pkg/sync\",\n],\n)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/fd_table.go", "new_path": "pkg/sentry/kernel/fd_table.go", "diff": "@@ -381,7 +381,7 @@ func (f *FDTable) NewFDsVFS2(ctx context.Context, minFD int32, files []*vfs.File\nif lim.Cur != limits.Infinity {\nend = int32(lim.Cur)\n}\n- if minFD >= end {\n+ if minFD+int32(len(files)) > end {\nreturn nil, unix.EMFILE\n}\n}\n@@ -539,8 +539,8 @@ func (f *FDTable) SetFlagsForRange(ctx context.Context, startFd int32, endFd int\nfor fd, err := f.fdBitmap.FirstOne(uint32(startFd)); err == nil && fd <= uint32(endFd); fd, err = f.fdBitmap.FirstOne(fd + 1) {\nfdI32 := int32(fd)\n- file, _, _ := f.get(fdI32)\n- f.set(ctx, fdI32, file, flags)\n+ fd, _, _ := f.getVFS2(fdI32)\n+ f.setVFS2(ctx, fdI32, fd, flags)\n}\nreturn nil\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/fd_table_test.go", "new_path": "pkg/sentry/kernel/fd_table_test.go", "diff": "@@ -20,9 +20,8 @@ import (\n\"gvisor.dev/gvisor/pkg/context\"\n\"gvisor.dev/gvisor/pkg/sentry/contexttest\"\n- \"gvisor.dev/gvisor/pkg/sentry/fs\"\n- \"gvisor.dev/gvisor/pkg/sentry/fs/filetest\"\n\"gvisor.dev/gvisor/pkg/sentry/limits\"\n+ \"gvisor.dev/gvisor/pkg/sentry/vfs\"\n\"gvisor.dev/gvisor/pkg/sync\"\n)\n@@ -33,7 +32,26 @@ const (\nmaxFD = 2 * 1024\n)\n-func runTest(t testing.TB, fn func(ctx context.Context, fdTable *FDTable, file *fs.File, limitSet *limits.LimitSet)) {\n+// testFD is a read-only FileDescriptionImpl representing a regular file.\n+type testFD struct {\n+ vfsfd vfs.FileDescription\n+ vfs.FileDescriptionDefaultImpl\n+ vfs.DentryMetadataFileDescriptionImpl\n+ vfs.NoLockFD\n+}\n+\n+// Release implements FileDescriptionImpl.Release.\n+func (fd *testFD) Release(context.Context) {}\n+\n+func newTestFD(ctx context.Context, vfsObj *vfs.VirtualFilesystem) *vfs.FileDescription {\n+ vd := vfsObj.NewAnonVirtualDentry(\"testFD\")\n+ defer vd.DecRef(ctx)\n+ var fd testFD\n+ fd.vfsfd.Init(&fd, 0 /* flags */, vd.Mount(), vd.Dentry(), &vfs.FileDescriptionOptions{})\n+ return &fd.vfsfd\n+}\n+\n+func runTest(t testing.TB, fn func(ctx context.Context, fdTable *FDTable, fd *vfs.FileDescription, limitSet *limits.LimitSet)) {\nt.Helper() // Don't show in stacks.\n// Create the limits and context.\n@@ -41,55 +59,60 @@ func runTest(t testing.TB, fn func(ctx context.Context, fdTable *FDTable, file *\nlimitSet.Set(limits.NumberOfFiles, limits.Limit{maxFD, maxFD}, true)\nctx := contexttest.WithLimitSet(contexttest.Context(t), limitSet)\n- // Create a test file.;\n- file := filetest.NewTestFile(t)\n+ vfsObj := &vfs.VirtualFilesystem{}\n+ if err := vfsObj.Init(ctx); err != nil {\n+ t.Fatalf(\"VFS init: %v\", err)\n+ }\n+\n+ fd := newTestFD(ctx, vfsObj)\n+ defer fd.DecRef(ctx)\n// Create the table.\nfdTable := new(FDTable)\nfdTable.init()\n// Run the test.\n- fn(ctx, fdTable, file, limitSet)\n+ fn(ctx, fdTable, fd, limitSet)\n}\n// TestFDTableMany allocates maxFD FDs, i.e. maxes out the FDTable, until there\n// is no room, then makes sure that NewFDAt works and also that if we remove\n// one and add one that works too.\nfunc TestFDTableMany(t *testing.T) {\n- runTest(t, func(ctx context.Context, fdTable *FDTable, file *fs.File, _ *limits.LimitSet) {\n+ runTest(t, func(ctx context.Context, fdTable *FDTable, fd *vfs.FileDescription, _ *limits.LimitSet) {\nfor i := 0; i < maxFD; i++ {\n- if _, err := fdTable.NewFDs(ctx, 0, []*fs.File{file}, FDFlags{}); err != nil {\n+ if _, err := fdTable.NewFDsVFS2(ctx, 0, []*vfs.FileDescription{fd}, FDFlags{}); err != nil {\nt.Fatalf(\"Allocated %v FDs but wanted to allocate %v\", i, maxFD)\n}\n}\n- if _, err := fdTable.NewFDs(ctx, 0, []*fs.File{file}, FDFlags{}); err == nil {\n+ if _, err := fdTable.NewFDsVFS2(ctx, 0, []*vfs.FileDescription{fd}, FDFlags{}); err == nil {\nt.Fatalf(\"fdTable.NewFDs(0, r) in full map: got nil, wanted error\")\n}\n- if err := fdTable.NewFDAt(ctx, 1, file, FDFlags{}); err != nil {\n+ if err := fdTable.NewFDAtVFS2(ctx, 1, fd, FDFlags{}); err != nil {\nt.Fatalf(\"fdTable.NewFDAt(1, r, FDFlags{}): got %v, wanted nil\", err)\n}\ni := int32(2)\nfdTable.Remove(ctx, i)\n- if fds, err := fdTable.NewFDs(ctx, 0, []*fs.File{file}, FDFlags{}); err != nil || fds[0] != i {\n+ if fds, err := fdTable.NewFDsVFS2(ctx, 0, []*vfs.FileDescription{fd}, FDFlags{}); err != nil || fds[0] != i {\nt.Fatalf(\"Allocated %v FDs but wanted to allocate %v: %v\", i, maxFD, err)\n}\n})\n}\nfunc TestFDTableOverLimit(t *testing.T) {\n- runTest(t, func(ctx context.Context, fdTable *FDTable, file *fs.File, _ *limits.LimitSet) {\n- if _, err := fdTable.NewFDs(ctx, maxFD, []*fs.File{file}, FDFlags{}); err == nil {\n+ runTest(t, func(ctx context.Context, fdTable *FDTable, fd *vfs.FileDescription, _ *limits.LimitSet) {\n+ if _, err := fdTable.NewFDsVFS2(ctx, maxFD, []*vfs.FileDescription{fd}, FDFlags{}); err == nil {\nt.Fatalf(\"fdTable.NewFDs(maxFD, f): got nil, wanted error\")\n}\n- if _, err := fdTable.NewFDs(ctx, maxFD-2, []*fs.File{file, file, file}, FDFlags{}); err == nil {\n+ if _, err := fdTable.NewFDsVFS2(ctx, maxFD-2, []*vfs.FileDescription{fd, fd, fd}, FDFlags{}); err == nil {\nt.Fatalf(\"fdTable.NewFDs(maxFD-2, {f,f,f}): got nil, wanted error\")\n}\n- if fds, err := fdTable.NewFDs(ctx, maxFD-3, []*fs.File{file, file, file}, FDFlags{}); err != nil {\n+ if fds, err := fdTable.NewFDsVFS2(ctx, maxFD-3, []*vfs.FileDescription{fd, fd, fd}, FDFlags{}); err != nil {\nt.Fatalf(\"fdTable.NewFDs(maxFD-3, {f,f,f}): got %v, wanted nil\", err)\n} else {\nfor _, fd := range fds {\n@@ -97,11 +120,11 @@ func TestFDTableOverLimit(t *testing.T) {\n}\n}\n- if fds, err := fdTable.NewFDs(ctx, maxFD-1, []*fs.File{file}, FDFlags{}); err != nil || fds[0] != maxFD-1 {\n+ if fds, err := fdTable.NewFDsVFS2(ctx, maxFD-1, []*vfs.FileDescription{fd}, FDFlags{}); err != nil || fds[0] != maxFD-1 {\nt.Fatalf(\"fdTable.NewFDAt(1, r, FDFlags{}): got %v, wanted nil\", err)\n}\n- if fds, err := fdTable.NewFDs(ctx, 0, []*fs.File{file}, FDFlags{}); err != nil {\n+ if fds, err := fdTable.NewFDsVFS2(ctx, 0, []*vfs.FileDescription{fd}, FDFlags{}); err != nil {\nt.Fatalf(\"Adding an FD to a resized map: got %v, want nil\", err)\n} else if len(fds) != 1 || fds[0] != 0 {\nt.Fatalf(\"Added an FD to a resized map: got %v, want {1}\", fds)\n@@ -113,64 +136,64 @@ func TestFDTableOverLimit(t *testing.T) {\n// GetRefs, and DecRefs work. The ordering is just weird enough that a\n// table-driven approach seemed clumsy.\nfunc TestFDTable(t *testing.T) {\n- runTest(t, func(ctx context.Context, fdTable *FDTable, file *fs.File, limitSet *limits.LimitSet) {\n+ runTest(t, func(ctx context.Context, fdTable *FDTable, fd *vfs.FileDescription, limitSet *limits.LimitSet) {\n// Cap the limit at one.\nlimitSet.Set(limits.NumberOfFiles, limits.Limit{1, maxFD}, true)\n- if _, err := fdTable.NewFDs(ctx, 0, []*fs.File{file}, FDFlags{}); err != nil {\n+ if _, err := fdTable.NewFDsVFS2(ctx, 0, []*vfs.FileDescription{fd}, FDFlags{}); err != nil {\nt.Fatalf(\"Adding an FD to an empty 1-size map: got %v, want nil\", err)\n}\n- if _, err := fdTable.NewFDs(ctx, 0, []*fs.File{file}, FDFlags{}); err == nil {\n+ if _, err := fdTable.NewFDsVFS2(ctx, 0, []*vfs.FileDescription{fd}, FDFlags{}); err == nil {\nt.Fatalf(\"Adding an FD to a filled 1-size map: got nil, wanted an error\")\n}\n// Remove the previous limit.\nlimitSet.Set(limits.NumberOfFiles, limits.Limit{maxFD, maxFD}, true)\n- if fds, err := fdTable.NewFDs(ctx, 0, []*fs.File{file}, FDFlags{}); err != nil {\n+ if fds, err := fdTable.NewFDsVFS2(ctx, 0, []*vfs.FileDescription{fd}, FDFlags{}); err != nil {\nt.Fatalf(\"Adding an FD to a resized map: got %v, want nil\", err)\n} else if len(fds) != 1 || fds[0] != 1 {\nt.Fatalf(\"Added an FD to a resized map: got %v, want {1}\", fds)\n}\n- if err := fdTable.NewFDAt(ctx, 1, file, FDFlags{}); err != nil {\n+ if err := fdTable.NewFDAtVFS2(ctx, 1, fd, FDFlags{}); err != nil {\nt.Fatalf(\"Replacing FD 1 via fdTable.NewFDAt(1, r, FDFlags{}): got %v, wanted nil\", err)\n}\n- if err := fdTable.NewFDAt(ctx, maxFD+1, file, FDFlags{}); err == nil {\n+ if err := fdTable.NewFDAtVFS2(ctx, maxFD+1, fd, FDFlags{}); err == nil {\nt.Fatalf(\"Using an FD that was too large via fdTable.NewFDAt(%v, r, FDFlags{}): got nil, wanted an error\", maxFD+1)\n}\n- if ref, _ := fdTable.Get(1); ref == nil {\n- t.Fatalf(\"fdTable.Get(1): got nil, wanted %v\", file)\n+ if ref, _ := fdTable.GetVFS2(1); ref == nil {\n+ t.Fatalf(\"fdTable.GetVFS2(1): got nil, wanted %v\", fd)\n}\n- if ref, _ := fdTable.Get(2); ref != nil {\n- t.Fatalf(\"fdTable.Get(2): got a %v, wanted nil\", ref)\n+ if ref, _ := fdTable.GetVFS2(2); ref != nil {\n+ t.Fatalf(\"fdTable.GetVFS2(2): got a %v, wanted nil\", ref)\n}\n- ref, _ := fdTable.Remove(ctx, 1)\n+ _, ref := fdTable.Remove(ctx, 1)\nif ref == nil {\nt.Fatalf(\"fdTable.Remove(1) for an existing FD: failed, want success\")\n}\nref.DecRef(ctx)\n- if ref, _ := fdTable.Remove(ctx, 1); ref != nil {\n+ if _, ref := fdTable.Remove(ctx, 1); ref != nil {\nt.Fatalf(\"r.Remove(1) for a removed FD: got success, want failure\")\n}\n})\n}\nfunc TestDescriptorFlags(t *testing.T) {\n- runTest(t, func(ctx context.Context, fdTable *FDTable, file *fs.File, _ *limits.LimitSet) {\n- if err := fdTable.NewFDAt(ctx, 2, file, FDFlags{CloseOnExec: true}); err != nil {\n+ runTest(t, func(ctx context.Context, fdTable *FDTable, fd *vfs.FileDescription, _ *limits.LimitSet) {\n+ if err := fdTable.NewFDAtVFS2(ctx, 2, fd, FDFlags{CloseOnExec: true}); err != nil {\nt.Fatalf(\"fdTable.NewFDAt(2, r, FDFlags{}): got %v, wanted nil\", err)\n}\n- newFile, flags := fdTable.Get(2)\n+ newFile, flags := fdTable.GetVFS2(2)\nif newFile == nil {\n- t.Fatalf(\"fdTable.Get(2): got a %v, wanted nil\", newFile)\n+ t.Fatalf(\"fdTable.GetVFS2(2): got a %v, wanted nil\", newFile)\n}\nif !flags.CloseOnExec {\n@@ -182,15 +205,15 @@ func TestDescriptorFlags(t *testing.T) {\nfunc BenchmarkFDLookupAndDecRef(b *testing.B) {\nb.StopTimer() // Setup.\n- runTest(b, func(ctx context.Context, fdTable *FDTable, file *fs.File, _ *limits.LimitSet) {\n- fds, err := fdTable.NewFDs(ctx, 0, []*fs.File{file, file, file, file, file}, FDFlags{})\n+ runTest(b, func(ctx context.Context, fdTable *FDTable, fd *vfs.FileDescription, _ *limits.LimitSet) {\n+ fds, err := fdTable.NewFDsVFS2(ctx, 0, []*vfs.FileDescription{fd, fd, fd, fd, fd}, FDFlags{})\nif err != nil {\nb.Fatalf(\"fdTable.NewFDs: got %v, wanted nil\", err)\n}\nb.StartTimer() // Benchmark.\nfor i := 0; i < b.N; i++ {\n- tf, _ := fdTable.Get(fds[i%len(fds)])\n+ tf, _ := fdTable.GetVFS2(fds[i%len(fds)])\ntf.DecRef(ctx)\n}\n})\n@@ -199,8 +222,8 @@ func BenchmarkFDLookupAndDecRef(b *testing.B) {\nfunc BenchmarkFDLookupAndDecRefConcurrent(b *testing.B) {\nb.StopTimer() // Setup.\n- runTest(b, func(ctx context.Context, fdTable *FDTable, file *fs.File, _ *limits.LimitSet) {\n- fds, err := fdTable.NewFDs(ctx, 0, []*fs.File{file, file, file, file, file}, FDFlags{})\n+ runTest(b, func(ctx context.Context, fdTable *FDTable, fd *vfs.FileDescription, _ *limits.LimitSet) {\n+ fds, err := fdTable.NewFDsVFS2(ctx, 0, []*vfs.FileDescription{fd, fd, fd, fd, fd}, FDFlags{})\nif err != nil {\nb.Fatalf(\"fdTable.NewFDs: got %v, wanted nil\", err)\n}\n@@ -218,7 +241,7 @@ func BenchmarkFDLookupAndDecRefConcurrent(b *testing.B) {\ngo func() {\ndefer wg.Done()\nfor i := 0; i < each; i++ {\n- tf, _ := fdTable.Get(fds[i%len(fds)])\n+ tf, _ := fdTable.GetVFS2(fds[i%len(fds)])\ntf.DecRef(ctx)\n}\n}()\n@@ -241,10 +264,10 @@ func TestSetFlagsForRange(t *testing.T) {\n}\nfor _, test := range testCases {\n- runTest(t, func(ctx context.Context, fdTable *FDTable, file *fs.File, _ *limits.LimitSet) {\n+ runTest(t, func(ctx context.Context, fdTable *FDTable, fd *vfs.FileDescription, _ *limits.LimitSet) {\nfor i := 0; i < maxFD; i++ {\n- if _, err := fdTable.NewFDs(ctx, 0, []*fs.File{file}, FDFlags{}); err != nil {\n- t.Fatalf(\"testCase: %v\\nfdTable.NewFDs(_, 0, %+v, FDFlags{}): %d, want: nil\", test, []*fs.File{file}, err)\n+ if _, err := fdTable.NewFDsVFS2(ctx, 0, []*vfs.FileDescription{fd}, FDFlags{}); err != nil {\n+ t.Fatalf(\"testCase: %v\\nfdTable.NewFDs(_, 0, %+v, FDFlags{}): %d, want: nil\", test, []*vfs.FileDescription{fd}, err)\n}\n}\n@@ -259,9 +282,9 @@ func TestSetFlagsForRange(t *testing.T) {\ntestRangeFlags := func(start int32, end int32, expected FDFlags) {\nfor i := start; i <= end; i++ {\n- file, flags := fdTable.Get(i)\n+ file, flags := fdTable.GetVFS2(i)\nif file == nil || flags != expected {\n- t.Fatalf(\"testCase: %v\\nfdTable.Get(%d): (%v, %v), wanted (non-nil, %v)\", test, i, file, flags, expected)\n+ t.Fatalf(\"testCase: %v\\nfdTable.GetVFS2(%d): (%v, %v), wanted (non-nil, %v)\", test, i, file, flags, expected)\n}\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/file_description_impl_util_test.go", "new_path": "pkg/sentry/vfs/file_description_impl_util_test.go", "diff": "@@ -76,6 +76,7 @@ func (d *storeData) Write(ctx context.Context, _ *FileDescription, src usermem.I\ntype testFD struct {\nfileDescription\nDynamicBytesFileDescriptionImpl\n+ DentryMetadataFileDescriptionImpl\ndata DynamicBytesSource\n}\n@@ -93,18 +94,6 @@ func newTestFD(ctx context.Context, vfsObj *VirtualFilesystem, statusFlags uint3\nfunc (fd *testFD) Release(context.Context) {\n}\n-// SetStatusFlags implements FileDescriptionImpl.SetStatusFlags.\n-// Stat implements FileDescriptionImpl.Stat.\n-func (fd *testFD) Stat(ctx context.Context, opts StatOptions) (linux.Statx, error) {\n- // Note that Statx.Mask == 0 in the return value.\n- return linux.Statx{}, nil\n-}\n-\n-// SetStat implements FileDescriptionImpl.SetStat.\n-func (fd *testFD) SetStat(ctx context.Context, opts SetStatOptions) error {\n- return linuxerr.EPERM\n-}\n-\nfunc TestGenCountFD(t *testing.T) {\nctx := contexttest.Context(t)\n" } ]
Go
Apache License 2.0
google/gvisor
Update fd_table_test to use VFS2. This unit test had been using VFS1. Updates #1624 PiperOrigin-RevId: 488740255
259,985
15.11.2022 13:48:33
28,800
58c71d54fc063439fe6fdf1125d3b4a46cd31041
Disable S/R while rapidly polling control files in cgroups tests. This resulted in too many S/Rs and prevents tasks from being scheduled and accumulating CPU time.
[ { "change_type": "MODIFY", "old_path": "test/util/cgroup_util.cc", "new_path": "test/util/cgroup_util.cc", "diff": "@@ -102,6 +102,11 @@ PosixError Cgroup::PollControlFileForChangeAfter(\nbody();\n+ // The loop below iterates quickly and results in too many save-restore\n+ // cycles. This can prevent tasks from being scheduled and incurring the\n+ // resource usage this function is often waiting for, resulting in timeouts.\n+ const DisableSave ds;\n+\nwhile (true) {\nASSIGN_OR_RETURN_ERRNO(const int64_t current_value,\nReadIntegerControlFile(name));\n" } ]
Go
Apache License 2.0
google/gvisor
Disable S/R while rapidly polling control files in cgroups tests. This resulted in too many S/Rs and prevents tasks from being scheduled and accumulating CPU time. PiperOrigin-RevId: 488748888
259,992
15.11.2022 14:25:04
28,800
b4e810c944d8c8dc2a55484fb6f82d1ef26cbdb3
Sort syscall trace points
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/seccheck/metadata_amd64.go", "new_path": "pkg/sentry/seccheck/metadata_amd64.go", "diff": "package seccheck\n+// init registers syscall trace points metadata.\n+// Keep them sorted by syscall number.\nfunc init() {\naddSyscallPoint(0, \"read\", []FieldDesc{\n{\n@@ -61,51 +63,62 @@ func init() {\nName: \"fd_path\",\n},\n})\n- addSyscallPoint(41, \"socket\", nil)\n- addSyscallPoint(42, \"connect\", []FieldDesc{\n+ addSyscallPoint(22, \"pipe\", nil)\n+ addSyscallPoint(32, \"dup\", []FieldDesc{\n{\nID: FieldSyscallPath,\nName: \"fd_path\",\n},\n})\n- addSyscallPoint(59, \"execve\", []FieldDesc{\n+ addSyscallPoint(33, \"dup2\", []FieldDesc{\n{\n- ID: FieldSyscallExecveEnvv,\n- Name: \"envv\",\n+ ID: FieldSyscallPath,\n+ Name: \"fd_path\",\n},\n})\n- addSyscallPoint(85, \"creat\", []FieldDesc{\n+ addSyscallPoint(41, \"socket\", nil)\n+ addSyscallPoint(42, \"connect\", []FieldDesc{\n{\nID: FieldSyscallPath,\nName: \"fd_path\",\n},\n})\n- addSyscallPoint(257, \"openat\", []FieldDesc{\n+ addSyscallPoint(43, \"accept\", []FieldDesc{\n{\nID: FieldSyscallPath,\nName: \"fd_path\",\n},\n})\n- addSyscallPoint(322, \"execveat\", []FieldDesc{\n+ addSyscallPoint(49, \"bind\", []FieldDesc{\n{\nID: FieldSyscallPath,\nName: \"fd_path\",\n},\n+ })\n+ addSyscallPoint(53, \"socketpair\", nil)\n+ addSyscallPoint(56, \"clone\", nil)\n+ addSyscallPoint(57, \"fork\", nil)\n+ addSyscallPoint(58, \"vfork\", nil)\n+ addSyscallPoint(59, \"execve\", []FieldDesc{\n{\nID: FieldSyscallExecveEnvv,\nName: \"envv\",\n},\n})\n- addSyscallPoint(80, \"chdir\", nil)\n- addSyscallPoint(81, \"fchdir\", []FieldDesc{\n+ addSyscallPoint(72, \"fcntl\", []FieldDesc{\n{\nID: FieldSyscallPath,\nName: \"fd_path\",\n},\n})\n- addSyscallPoint(22, \"pipe\", nil)\n- addSyscallPoint(293, \"pipe2\", nil)\n- addSyscallPoint(72, \"fcntl\", []FieldDesc{\n+ addSyscallPoint(85, \"creat\", []FieldDesc{\n+ {\n+ ID: FieldSyscallPath,\n+ Name: \"fd_path\",\n+ },\n+ })\n+ addSyscallPoint(80, \"chdir\", nil)\n+ addSyscallPoint(81, \"fchdir\", []FieldDesc{\n{\nID: FieldSyscallPath,\nName: \"fd_path\",\n@@ -117,47 +130,40 @@ func init() {\naddSyscallPoint(117, \"setresuid\", nil)\naddSyscallPoint(119, \"setresgid\", nil)\naddSyscallPoint(161, \"chroot\", nil)\n- addSyscallPoint(302, \"prlimit64\", nil)\n- addSyscallPoint(284, \"eventfd\", nil)\n- addSyscallPoint(290, \"eventfd2\", nil)\n- addSyscallPoint(282, \"signalfd\", []FieldDesc{\n- {\n- ID: FieldSyscallPath,\n- Name: \"fd_path\",\n- },\n- })\n- addSyscallPoint(289, \"signalfd4\", []FieldDesc{\n+ addSyscallPoint(253, \"inotify_init\", nil)\n+ addSyscallPoint(254, \"inotify_add_watch\", []FieldDesc{\n{\nID: FieldSyscallPath,\nName: \"fd_path\",\n},\n})\n- addSyscallPoint(32, \"dup\", []FieldDesc{\n+ addSyscallPoint(255, \"inotify_rm_watch\", []FieldDesc{\n{\nID: FieldSyscallPath,\nName: \"fd_path\",\n},\n})\n- addSyscallPoint(33, \"dup2\", []FieldDesc{\n+ addSyscallPoint(257, \"openat\", []FieldDesc{\n{\nID: FieldSyscallPath,\nName: \"fd_path\",\n},\n})\n- addSyscallPoint(292, \"dup3\", []FieldDesc{\n+ addSyscallPoint(282, \"signalfd\", []FieldDesc{\n{\nID: FieldSyscallPath,\nName: \"fd_path\",\n},\n})\n- addSyscallPoint(56, \"clone\", nil)\n- addSyscallPoint(49, \"bind\", []FieldDesc{\n+ addSyscallPoint(283, \"timerfd_create\", nil)\n+ addSyscallPoint(284, \"eventfd\", nil)\n+ addSyscallPoint(286, \"timerfd_settime\", []FieldDesc{\n{\nID: FieldSyscallPath,\nName: \"fd_path\",\n},\n})\n- addSyscallPoint(43, \"accept\", []FieldDesc{\n+ addSyscallPoint(287, \"timerfd_gettime\", []FieldDesc{\n{\nID: FieldSyscallPath,\nName: \"fd_path\",\n@@ -169,46 +175,42 @@ func init() {\nName: \"fd_path\",\n},\n})\n- addSyscallPoint(57, \"fork\", nil)\n- addSyscallPoint(58, \"vfork\", nil)\n- addSyscallPoint(253, \"inotify_init\", nil)\n- addSyscallPoint(294, \"inotify_init1\", nil)\n- addSyscallPoint(254, \"inotify_add_watch\", []FieldDesc{\n+ addSyscallPoint(289, \"signalfd4\", []FieldDesc{\n{\nID: FieldSyscallPath,\nName: \"fd_path\",\n},\n})\n- addSyscallPoint(255, \"inotify_rm_watch\", []FieldDesc{\n+ addSyscallPoint(290, \"eventfd2\", nil)\n+ addSyscallPoint(292, \"dup3\", []FieldDesc{\n{\nID: FieldSyscallPath,\nName: \"fd_path\",\n},\n})\n- addSyscallPoint(283, \"timerfd_create\", nil)\n- addSyscallPoint(286, \"timerfd_settime\", []FieldDesc{\n+ addSyscallPoint(293, \"pipe2\", nil)\n+ addSyscallPoint(294, \"inotify_init1\", nil)\n+ addSyscallPoint(295, \"preadv\", []FieldDesc{\n{\nID: FieldSyscallPath,\nName: \"fd_path\",\n},\n})\n- addSyscallPoint(287, \"timerfd_gettime\", []FieldDesc{\n+ addSyscallPoint(296, \"pwritev\", []FieldDesc{\n{\nID: FieldSyscallPath,\nName: \"fd_path\",\n},\n})\n- addSyscallPoint(53, \"socketpair\", nil)\n- addSyscallPoint(295, \"preadv\", []FieldDesc{\n+ addSyscallPoint(302, \"prlimit64\", nil)\n+ addSyscallPoint(322, \"execveat\", []FieldDesc{\n{\nID: FieldSyscallPath,\nName: \"fd_path\",\n},\n- })\n- addSyscallPoint(296, \"pwritev\", []FieldDesc{\n{\n- ID: FieldSyscallPath,\n- Name: \"fd_path\",\n+ ID: FieldSyscallExecveEnvv,\n+ Name: \"envv\",\n},\n})\naddSyscallPoint(327, \"preadv2\", []FieldDesc{\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/seccheck/metadata_arm64.go", "new_path": "pkg/sentry/seccheck/metadata_arm64.go", "diff": "package seccheck\n+// init registers syscall trace points metadata.\n+// Keep them sorted by syscall number.\nfunc init() {\n- addSyscallPoint(63, \"read\", []FieldDesc{\n+ addSyscallPoint(19, \"eventfd2\", nil)\n+ addSyscallPoint(23, \"dup\", []FieldDesc{\n{\nID: FieldSyscallPath,\nName: \"fd_path\",\n},\n})\n- addSyscallPoint(64, \"write\", []FieldDesc{\n+ addSyscallPoint(24, \"dup3\", []FieldDesc{\n{\nID: FieldSyscallPath,\nName: \"fd_path\",\n},\n})\n- addSyscallPoint(65, \"readv\", []FieldDesc{\n+ addSyscallPoint(25, \"fcntl\", []FieldDesc{\n{\nID: FieldSyscallPath,\nName: \"fd_path\",\n},\n})\n- addSyscallPoint(66, \"writev\", []FieldDesc{\n+\n+ addSyscallPoint(26, \"inotify_init1\", nil)\n+ addSyscallPoint(27, \"inotify_add_watch\", []FieldDesc{\n{\nID: FieldSyscallPath,\nName: \"fd_path\",\n},\n})\n- addSyscallPoint(67, \"pread64\", []FieldDesc{\n+ addSyscallPoint(28, \"inotify_rm_watch\", []FieldDesc{\n{\nID: FieldSyscallPath,\nName: \"fd_path\",\n},\n})\n- addSyscallPoint(68, \"pwrite64\", []FieldDesc{\n+ addSyscallPoint(49, \"chdir\", nil)\n+ addSyscallPoint(50, \"fchdir\", []FieldDesc{\n{\nID: FieldSyscallPath,\nName: \"fd_path\",\n},\n})\n- addSyscallPoint(69, \"preadv\", []FieldDesc{\n+ addSyscallPoint(51, \"chroot\", nil)\n+ addSyscallPoint(56, \"openat\", []FieldDesc{\n{\nID: FieldSyscallPath,\nName: \"fd_path\",\n},\n})\n- addSyscallPoint(70, \"pwritev\", []FieldDesc{\n+ addSyscallPoint(57, \"close\", []FieldDesc{\n{\nID: FieldSyscallPath,\nName: \"fd_path\",\n},\n})\n- addSyscallPoint(57, \"close\", []FieldDesc{\n+ addSyscallPoint(59, \"pipe2\", nil)\n+ addSyscallPoint(63, \"read\", []FieldDesc{\n{\nID: FieldSyscallPath,\nName: \"fd_path\",\n},\n})\n- addSyscallPoint(198, \"socket\", nil)\n- addSyscallPoint(203, \"connect\", []FieldDesc{\n+ addSyscallPoint(64, \"write\", []FieldDesc{\n{\nID: FieldSyscallPath,\nName: \"fd_path\",\n},\n})\n- addSyscallPoint(221, \"execve\", []FieldDesc{\n+ addSyscallPoint(65, \"readv\", []FieldDesc{\n{\n- ID: FieldSyscallExecveEnvv,\n- Name: \"envv\",\n+ ID: FieldSyscallPath,\n+ Name: \"fd_path\",\n},\n})\n- addSyscallPoint(56, \"openat\", []FieldDesc{\n+ addSyscallPoint(66, \"writev\", []FieldDesc{\n{\nID: FieldSyscallPath,\nName: \"fd_path\",\n},\n})\n- addSyscallPoint(281, \"execveat\", []FieldDesc{\n+ addSyscallPoint(67, \"pread64\", []FieldDesc{\n{\nID: FieldSyscallPath,\nName: \"fd_path\",\n},\n- {\n- ID: FieldSyscallExecveEnvv,\n- Name: \"envv\",\n- },\n})\n- addSyscallPoint(49, \"chdir\", nil)\n- addSyscallPoint(50, \"fchdir\", []FieldDesc{\n+ addSyscallPoint(68, \"pwrite64\", []FieldDesc{\n{\nID: FieldSyscallPath,\nName: \"fd_path\",\n},\n})\n- addSyscallPoint(146, \"setuid\", nil)\n- addSyscallPoint(144, \"setgid\", nil)\n- addSyscallPoint(157, \"setsid\", nil)\n- addSyscallPoint(147, \"setresuid\", nil)\n- addSyscallPoint(149, \"setresgid\", nil)\n- addSyscallPoint(261, \"prlimit64\", nil)\n- addSyscallPoint(51, \"chroot\", nil)\n- addSyscallPoint(23, \"dup\", []FieldDesc{\n+ addSyscallPoint(69, \"preadv\", []FieldDesc{\n{\nID: FieldSyscallPath,\nName: \"fd_path\",\n},\n})\n- addSyscallPoint(24, \"dup3\", []FieldDesc{\n+ addSyscallPoint(70, \"pwritev\", []FieldDesc{\n{\nID: FieldSyscallPath,\nName: \"fd_path\",\n},\n})\n- addSyscallPoint(59, \"pipe2\", nil)\naddSyscallPoint(74, \"signalfd4\", []FieldDesc{\n{\nID: FieldSyscallPath,\nName: \"fd_path\",\n},\n})\n- addSyscallPoint(25, \"fcntl\", []FieldDesc{\n+ addSyscallPoint(85, \"timerfd_create\", nil)\n+ addSyscallPoint(86, \"timerfd_settime\", []FieldDesc{\n{\nID: FieldSyscallPath,\nName: \"fd_path\",\n},\n})\n- addSyscallPoint(19, \"eventfd2\", nil)\n- addSyscallPoint(220, \"clone\", nil)\n- addSyscallPoint(200, \"bind\", []FieldDesc{\n+ addSyscallPoint(87, \"timerfd_gettime\", []FieldDesc{\n{\nID: FieldSyscallPath,\nName: \"fd_path\",\n},\n})\n- addSyscallPoint(202, \"accept\", []FieldDesc{\n+ addSyscallPoint(144, \"setgid\", nil)\n+ addSyscallPoint(146, \"setuid\", nil)\n+ addSyscallPoint(147, \"setresuid\", nil)\n+ addSyscallPoint(149, \"setresgid\", nil)\n+ addSyscallPoint(157, \"setsid\", nil)\n+ addSyscallPoint(198, \"socket\", nil)\n+ addSyscallPoint(199, \"socketpair\", nil)\n+ addSyscallPoint(200, \"bind\", []FieldDesc{\n{\nID: FieldSyscallPath,\nName: \"fd_path\",\n},\n})\n- addSyscallPoint(242, \"accept4\", []FieldDesc{\n+ addSyscallPoint(202, \"accept\", []FieldDesc{\n{\nID: FieldSyscallPath,\nName: \"fd_path\",\n},\n})\n- addSyscallPoint(26, \"inotify_init1\", nil)\n- addSyscallPoint(27, \"inotify_add_watch\", []FieldDesc{\n+ addSyscallPoint(203, \"connect\", []FieldDesc{\n{\nID: FieldSyscallPath,\nName: \"fd_path\",\n},\n})\n- addSyscallPoint(28, \"inotify_rm_watch\", []FieldDesc{\n+ addSyscallPoint(220, \"clone\", nil)\n+ addSyscallPoint(221, \"execve\", []FieldDesc{\n{\n- ID: FieldSyscallPath,\n- Name: \"fd_path\",\n+ ID: FieldSyscallExecveEnvv,\n+ Name: \"envv\",\n},\n})\n- addSyscallPoint(85, \"timerfd_create\", nil)\n- addSyscallPoint(86, \"timerfd_settime\", []FieldDesc{\n+ addSyscallPoint(242, \"accept4\", []FieldDesc{\n{\nID: FieldSyscallPath,\nName: \"fd_path\",\n},\n})\n- addSyscallPoint(87, \"timerfd_gettime\", []FieldDesc{\n+ addSyscallPoint(261, \"prlimit64\", nil)\n+ addSyscallPoint(281, \"execveat\", []FieldDesc{\n{\nID: FieldSyscallPath,\nName: \"fd_path\",\n},\n+ {\n+ ID: FieldSyscallExecveEnvv,\n+ Name: \"envv\",\n+ },\n})\n- addSyscallPoint(199, \"socketpair\", nil)\naddSyscallPoint(286, \"preadv2\", []FieldDesc{\n{\nID: FieldSyscallPath,\n" } ]
Go
Apache License 2.0
google/gvisor
Sort syscall trace points PiperOrigin-RevId: 488758795
259,853
15.11.2022 14:46:27
28,800
374e716c7ce29304b05b59adcb0360b3942bb4c7
AddSeals has to take the write lock to modify seals Reported-by: Reported-by:
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/tmpfs/regular_file.go", "new_path": "pkg/sentry/fsimpl/tmpfs/regular_file.go", "diff": "@@ -778,8 +778,8 @@ func AddSeals(fd *vfs.FileDescription, val uint32) error {\nrf := f.inode().impl.(*regularFile)\nrf.mapsMu.Lock()\ndefer rf.mapsMu.Unlock()\n- rf.dataMu.RLock()\n- defer rf.dataMu.RUnlock()\n+ rf.dataMu.Lock()\n+ defer rf.dataMu.Unlock()\nif rf.seals&linux.F_SEAL_SEAL != 0 {\n// Seal applied which prevents addition of any new seals.\n" } ]
Go
Apache License 2.0
google/gvisor
AddSeals has to take the write lock to modify seals Reported-by: syzbot+355993d42d99b011ea73@syzkaller.appspotmail.com Reported-by: syzbot+f758f7983773e0a60c7b@syzkaller.appspotmail.com PiperOrigin-RevId: 488764524
259,885
15.11.2022 14:58:19
28,800
9f351c68ca1dd8a184c9508d6cd849fd173119f0
Allow SO_BROADCAST through hostinet. Fixes
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/hostinet/socket.go", "new_path": "pkg/sentry/socket/hostinet/socket.go", "diff": "@@ -383,7 +383,7 @@ func (s *socketOpsCommon) GetSockOpt(t *kernel.Task, level int, name int, optVal\n}\ncase linux.SOL_SOCKET:\nswitch name {\n- case linux.SO_ERROR, linux.SO_KEEPALIVE, linux.SO_SNDBUF, linux.SO_RCVBUF, linux.SO_REUSEADDR, linux.SO_TIMESTAMP:\n+ case linux.SO_BROADCAST, linux.SO_ERROR, linux.SO_KEEPALIVE, linux.SO_SNDBUF, linux.SO_RCVBUF, linux.SO_REUSEADDR, linux.SO_TIMESTAMP:\noptlen = sizeofInt32\ncase linux.SO_LINGER:\noptlen = unix.SizeofLinger\n@@ -448,7 +448,7 @@ func (s *socketOpsCommon) SetSockOpt(t *kernel.Task, level int, name int, opt []\n}\ncase linux.SOL_SOCKET:\nswitch name {\n- case linux.SO_SNDBUF, linux.SO_RCVBUF, linux.SO_REUSEADDR, linux.SO_TIMESTAMP:\n+ case linux.SO_BROADCAST, linux.SO_SNDBUF, linux.SO_RCVBUF, linux.SO_REUSEADDR, linux.SO_TIMESTAMP:\noptlen = sizeofInt32\n}\ncase linux.SOL_TCP:\n" }, { "change_type": "MODIFY", "old_path": "runsc/boot/filter/config.go", "new_path": "runsc/boot/filter/config.go", "diff": "@@ -441,6 +441,11 @@ func hostInetFilters() seccomp.SyscallRules {\nseccomp.EqualTo(unix.SOL_IPV6),\nseccomp.EqualTo(linux.IPV6_RECVORIGDSTADDR),\n},\n+ {\n+ seccomp.MatchAny{},\n+ seccomp.EqualTo(unix.SOL_SOCKET),\n+ seccomp.EqualTo(unix.SO_BROADCAST),\n+ },\n{\nseccomp.MatchAny{},\nseccomp.EqualTo(unix.SOL_SOCKET),\n@@ -542,6 +547,13 @@ func hostInetFilters() seccomp.SyscallRules {\nunix.SYS_SENDMSG: {},\nunix.SYS_SENDTO: {},\nunix.SYS_SETSOCKOPT: []seccomp.Rule{\n+ {\n+ seccomp.MatchAny{},\n+ seccomp.EqualTo(unix.SOL_SOCKET),\n+ seccomp.EqualTo(unix.SO_BROADCAST),\n+ seccomp.MatchAny{},\n+ seccomp.EqualTo(4),\n+ },\n{\nseccomp.MatchAny{},\nseccomp.EqualTo(unix.SOL_SOCKET),\n" } ]
Go
Apache License 2.0
google/gvisor
Allow SO_BROADCAST through hostinet. Fixes #8090 PiperOrigin-RevId: 488767693
259,907
16.11.2022 08:23:17
28,800
681c7ddd5a811a5eb687b8f7d646c89cd6b62a8d
Add docker test for external UDS connect. Serves as a regression test for Our unit tests didn't catch the issue because they run runsc with the flag TESTONLY-unsafe-nonroot. Docker tests are more e2e, they run tests in Docker containers. Fixes
[ { "change_type": "MODIFY", "old_path": "Makefile", "new_path": "Makefile", "diff": "@@ -268,9 +268,9 @@ INTEGRATION_TARGETS := //test/image:image_test //test/e2e:integration_test\ndocker-tests: load-basic $(RUNTIME_BIN)\n@$(call install_runtime,$(RUNTIME),) # Clear flags.\n- # Used by TestRlimitNoFile.\n- @$(call install_runtime,$(RUNTIME)-fdlimit,--fdlimit=2000)\n- @$(call install_runtime,$(RUNTIME)-dcache,--fdlimit=2000 --dcache=100)\n+ @$(call install_runtime,$(RUNTIME)-fdlimit,--fdlimit=2000) # Used by TestRlimitNoFile.\n+ @$(call install_runtime,$(RUNTIME)-dcache,--fdlimit=2000 --dcache=100) # Used by TestDentryCacheLimit.\n+ @$(call install_runtime,$(RUNTIME)-host-uds,--host-uds=all) # Used by TestHostSocketConnect.\n@$(call test_runtime,$(RUNTIME),$(INTEGRATION_TARGETS) //test/e2e:integration_runtime_test)\n.PHONY: docker-tests\n" }, { "change_type": "MODIFY", "old_path": "images/basic/integrationtest/Dockerfile", "new_path": "images/basic/integrationtest/Dockerfile", "diff": "@@ -12,3 +12,4 @@ RUN gcc -O2 -o test_rewinddir test_rewinddir.c\nRUN gcc -O2 -o link_test link_test.c\nRUN gcc -O2 -o test_sticky test_sticky.c\nRUN gcc -O2 -o host_fd host_fd.c\n+RUN gcc -O2 -o host_connect host_connect.c\n\\ No newline at end of file\n" }, { "change_type": "ADD", "old_path": null, "new_path": "images/basic/integrationtest/host_connect.c", "diff": "+// Copyright 2022 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+#include <stdio.h>\n+#include <stdlib.h>\n+#include <sys/socket.h>\n+#include <sys/un.h>\n+#include <unistd.h>\n+\n+int main(int argc, char** argv) {\n+ int fd;\n+ struct sockaddr_un addr;\n+ char buff[10];\n+\n+ if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {\n+ perror(\"socket\");\n+ exit(1);\n+ }\n+\n+ memset(&addr, 0, sizeof(addr));\n+ addr.sun_family = AF_UNIX;\n+ strcpy(addr.sun_path, argv[1]);\n+ if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {\n+ perror(\"connect\");\n+ exit(1);\n+ }\n+\n+ strcpy(buff, \"Hello\");\n+ if (send(fd, buff, strlen(buff) + 1, 0) == -1) {\n+ perror(\"send\");\n+ exit(1);\n+ }\n+\n+ close(fd);\n+ exit(0);\n+}\n" }, { "change_type": "MODIFY", "old_path": "test/e2e/BUILD", "new_path": "test/e2e/BUILD", "diff": "@@ -43,6 +43,7 @@ go_test(\n\"//pkg/test/dockerutil\",\n\"//pkg/test/testutil\",\n\"@com_github_docker_docker//api/types/mount:go_default_library\",\n+ \"@org_golang_x_sys//unix:go_default_library\",\n],\n)\n" }, { "change_type": "MODIFY", "old_path": "test/e2e/integration_runtime_test.go", "new_path": "test/e2e/integration_runtime_test.go", "diff": "@@ -25,12 +25,17 @@ import (\n\"context\"\n\"flag\"\n\"io/ioutil\"\n+ \"net\"\n\"os\"\n+ \"path/filepath\"\n+ \"strconv\"\n\"strings\"\n+ \"sync\"\n\"testing\"\n\"time\"\n\"github.com/docker/docker/api/types/mount\"\n+ \"golang.org/x/sys/unix\"\n\"gvisor.dev/gvisor/pkg/test/dockerutil\"\n\"gvisor.dev/gvisor/pkg/test/testutil\"\n)\n@@ -115,3 +120,61 @@ func TestDentryCacheLimit(t *testing.T) {\nt.Fatalf(\"docker failed: %v, %s\", err, got)\n}\n}\n+\n+// NOTE(gvisor.dev/issue/8126): Regression test.\n+func TestHostSocketConnect(t *testing.T) {\n+ ctx := context.Background()\n+ d := dockerutil.MakeContainerWithRuntime(ctx, t, \"-host-uds\")\n+ defer d.CleanUp(ctx)\n+\n+ tmpDir := testutil.TmpDir()\n+ tmpDirFD, err := unix.Open(tmpDir, unix.O_PATH, 0)\n+ if err != nil {\n+ t.Fatalf(\"open error: %v\", err)\n+ }\n+ defer unix.Close(tmpDirFD)\n+ // Use /proc/self/fd to generate path to avoid EINVAL on large path.\n+ l, err := net.Listen(\"unix\", filepath.Join(\"/proc/self/fd\", strconv.Itoa(tmpDirFD), \"test.sock\"))\n+ if err != nil {\n+ t.Fatalf(\"listen error: %v\", err)\n+ }\n+ defer l.Close()\n+\n+ var wg sync.WaitGroup\n+ wg.Add(1)\n+ go func() {\n+ defer wg.Done()\n+ conn, err := l.Accept()\n+ if err != nil {\n+ t.Errorf(\"accept error: %v\", err)\n+ return\n+ }\n+\n+ conn.SetReadDeadline(time.Now().Add(30 * time.Second))\n+ var buf [5]byte\n+ if _, err := conn.Read(buf[:]); err != nil {\n+ t.Errorf(\"read error: %v\", err)\n+ return\n+ }\n+\n+ if want := \"Hello\"; string(buf[:]) != want {\n+ t.Errorf(\"expected %s, got %v\", want, string(buf[:]))\n+ }\n+ }()\n+\n+ opts := dockerutil.RunOpts{\n+ Image: \"basic/integrationtest\",\n+ WorkDir: \"/root\",\n+ Mounts: []mount.Mount{\n+ {\n+ Type: mount.TypeBind,\n+ Source: filepath.Join(tmpDir, \"test.sock\"),\n+ Target: \"/test.sock\",\n+ },\n+ },\n+ }\n+ if _, err := d.Run(ctx, opts, \"./host_connect\", \"/test.sock\"); err != nil {\n+ t.Fatalf(\"docker run failed: %v\", err)\n+ }\n+ wg.Wait()\n+}\n" } ]
Go
Apache License 2.0
google/gvisor
Add docker test for external UDS connect. Serves as a regression test for #8126. Our unit tests didn't catch the issue because they run runsc with the flag -TESTONLY-unsafe-nonroot. Docker tests are more e2e, they run tests in Docker containers. Fixes #8126 PiperOrigin-RevId: 488945922
259,982
16.11.2022 16:47:26
28,800
84548b78935a8ad39e76a219d8be0fd552770180
Adding check to ensure containerIDs are unique in multi-container mode.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/control/lifecycle.go", "new_path": "pkg/sentry/control/lifecycle.go", "diff": "@@ -303,6 +303,11 @@ func (l *Lifecycle) StartContainer(args *StartContainerArgs, _ *uint32) error {\nif l.containerMap == nil {\nl.containerMap = make(map[string]*Container)\n}\n+\n+ if _, ok := l.containerMap[initArgs.ContainerID]; ok {\n+ return fmt.Errorf(\"container id: %v already exists\", initArgs.ContainerID)\n+ }\n+\nl.containerMap[initArgs.ContainerID] = c\nl.mu.Unlock()\n" } ]
Go
Apache License 2.0
google/gvisor
Adding check to ensure containerIDs are unique in multi-container mode. PiperOrigin-RevId: 489073573
259,982
16.11.2022 17:03:32
28,800
dec1aed1435fc0ed8a844d2fd0c0890f1e9315fd
Adding more trace point integration tests for the following syscalls: Chdir Fchdir Setgid Setuid Setsid Setresuid Setresgid Updates
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/seccheck/points/syscall.proto", "new_path": "pkg/sentry/seccheck/points/syscall.proto", "diff": "@@ -121,9 +121,9 @@ message Setresid {\ngvisor.common.ContextData context_data = 1;\nExit exit = 2;\nuint64 sysno = 3;\n- uint32 rgid = 4;\n- uint32 egid = 5;\n- uint32 sgid = 6;\n+ uint32 rid = 4;\n+ uint32 eid = 5;\n+ uint32 sid = 6;\n}\nmessage Setid {\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/points.go", "new_path": "pkg/sentry/syscalls/linux/points.go", "diff": "@@ -512,9 +512,9 @@ func pointSetresidHelper(t *kernel.Task, fields seccheck.FieldSet, cxtData *pb.C\np := &pb.Setresid{\nContextData: cxtData,\nSysno: uint64(info.Sysno),\n- Rgid: info.Args[0].Uint(),\n- Egid: info.Args[1].Uint(),\n- Sgid: info.Args[2].Uint(),\n+ Rid: info.Args[0].Uint(),\n+ Eid: info.Args[1].Uint(),\n+ Sid: info.Args[2].Uint(),\n}\np.Exit = newExitMaybe(info)\n" }, { "change_type": "MODIFY", "old_path": "test/trace/trace_test.go", "new_path": "test/trace/trace_test.go", "diff": "@@ -109,6 +109,9 @@ func matchPoints(t *testing.T, msgs []test.Message) {\npb.MessageType_MESSAGE_SYSCALL_READ: {checker: checkSyscallRead},\npb.MessageType_MESSAGE_SYSCALL_SOCKET: {checker: checkSyscallSocket},\npb.MessageType_MESSAGE_SYSCALL_WRITE: {checker: checkSyscallWrite},\n+ pb.MessageType_MESSAGE_SYSCALL_CHDIR: {checker: checkSyscallChdir},\n+ pb.MessageType_MESSAGE_SYSCALL_SETID: {checker: checkSyscallSetid},\n+ pb.MessageType_MESSAGE_SYSCALL_SETRESID: {checker: checkSyscallSetresid},\n// TODO(gvisor.dev/issue/4805): Add validation for these messages.\npb.MessageType_MESSAGE_SYSCALL_ACCEPT: {checker: checkTODO},\n@@ -479,6 +482,61 @@ func checkSyscallSocket(msg test.Message) error {\nif want := int32(0); want != p.Protocol {\nreturn fmt.Errorf(\"wrong Protocol, want: %v, got: %v\", want, p.Protocol)\n}\n+\n+ return nil\n+}\n+\n+func checkSyscallSetid(msg test.Message) error {\n+ p := pb.Setid{}\n+ if err := proto.Unmarshal(msg.Msg, &p); err != nil {\n+ return err\n+ }\n+ if err := checkContextData(p.ContextData); err != nil {\n+ return err\n+ }\n+ if p.Id != 0 {\n+ return fmt.Errorf(\" invalid id: %d\", p.Id)\n+ }\n+\n+ return nil\n+}\n+\n+func checkSyscallSetresid(msg test.Message) error {\n+ p := pb.Setresid{}\n+ if err := proto.Unmarshal(msg.Msg, &p); err != nil {\n+ return err\n+ }\n+ if err := checkContextData(p.ContextData); err != nil {\n+ return err\n+ }\n+ if p.GetRid() != 0 {\n+ return fmt.Errorf(\" Invalid RID: %d\", p.Rid)\n+ }\n+ if p.GetEid() != 0 {\n+ return fmt.Errorf(\" Invalid EID: %d\", p.Eid)\n+ }\n+ if p.GetSid() != 0 {\n+ return fmt.Errorf(\" Invalid SID: %d\", p.Sid)\n+ }\n+\n+ return nil\n+}\n+\n+func checkSyscallChdir(msg test.Message) error {\n+ p := pb.Chdir{}\n+ if err := proto.Unmarshal(msg.Msg, &p); err != nil {\n+ return err\n+ }\n+ if err := checkContextData(p.ContextData); err != nil {\n+ return err\n+ }\n+ if p.Fd < 3 && p.Fd != unix.AT_FDCWD { // Constant used for all file-related syscalls.\n+ return fmt.Errorf(\"invalid FD: %d\", p.Fd)\n+ }\n+ if want := \"trace_test.abc\"; !strings.Contains(p.Pathname, want) {\n+ return fmt.Errorf(\"wrong Pathname, got: %q, want: %q\", p.Pathname, want)\n+ }\n+\nreturn nil\n}\n" }, { "change_type": "MODIFY", "old_path": "test/trace/workload/workload.cc", "new_path": "test/trace/workload/workload.cc", "diff": "// limitations under the License.\n#include <err.h>\n+#include <fcntl.h>\n#include <sys/socket.h>\n+#include <sys/stat.h>\n#include <sys/types.h>\n#include <sys/un.h>\n+#include <unistd.h>\n+\n+#include <iostream>\n+#include <ostream>\n#include \"absl/cleanup/cleanup.h\"\n#include \"absl/strings/str_cat.h\"\n@@ -39,7 +45,6 @@ void runForkExecve() {\nauto kill_or_error = ForkAndExecveat(root.get(), \"/bin/true\", argv, envv, 0,\nnullptr, &child, &execve_errno);\nASSERT_EQ(0, execve_errno);\n-\n// Don't kill child, just wait for gracefully exit.\nkill_or_error.ValueOrDie().Release();\nRetryEINTR(waitpid)(child, nullptr, 0);\n@@ -190,6 +195,72 @@ void runReadWrite() {\n}\n}\n+void runChdir() {\n+ const auto pathname = \"trace_test.abc\";\n+ static constexpr mode_t kDefaultDirMode = 0755;\n+ int path_or_error = mkdir(pathname, kDefaultDirMode);\n+ if (path_or_error != 0) {\n+ err(1, \"mkdir\");\n+ }\n+ int res = chdir(pathname);\n+ if (res != 0) {\n+ err(1, \"chdir\");\n+ }\n+ rmdir(pathname);\n+}\n+\n+void runFchdir() {\n+ const auto pathname = \"trace_test.abc\";\n+ static constexpr mode_t kDefaultDirMode = 0755;\n+ int path_or_error = mkdir(pathname, kDefaultDirMode);\n+ if (path_or_error != 0) {\n+ err(1, \"mkdir\");\n+ }\n+ int fd = open(pathname, O_DIRECTORY | O_RDONLY);\n+ int res = fchdir(fd);\n+ if (res != 0) {\n+ err(1, \"fchdir\");\n+ }\n+ rmdir(pathname);\n+ close(fd);\n+}\n+\n+void runSetgid() {\n+ auto get = setgid(0);\n+ if (get != 0) {\n+ err(1, \"setgid\");\n+ }\n+}\n+\n+void runSetuid() {\n+ auto get = setuid(0);\n+ if (get != 0) {\n+ err(1, \"setuid\");\n+ }\n+}\n+\n+void runSetsid() {\n+ auto get = setsid();\n+ // Operation is not permitted so we get an error.\n+ if (get != -1) {\n+ err(1, \"setsid\");\n+ }\n+}\n+\n+void runSetresuid() {\n+ auto get = setresuid(0, 0, 0);\n+ if (get != 0) {\n+ err(1, \"setresuid\");\n+ }\n+}\n+\n+void runSetresgid() {\n+ auto get = setresgid(0, 0, 0);\n+ if (get != 0) {\n+ err(1, \"setresgid\");\n+ }\n+}\n+\n} // namespace testing\n} // namespace gvisor\n@@ -197,6 +268,12 @@ int main(int argc, char** argv) {\n::gvisor::testing::runForkExecve();\n::gvisor::testing::runSocket();\n::gvisor::testing::runReadWrite();\n-\n+ ::gvisor::testing::runChdir();\n+ ::gvisor::testing::runFchdir();\n+ ::gvisor::testing::runSetgid();\n+ ::gvisor::testing::runSetuid();\n+ ::gvisor::testing::runSetsid();\n+ ::gvisor::testing::runSetresuid();\n+ ::gvisor::testing::runSetresgid();\nreturn 0;\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Adding more trace point integration tests for the following syscalls: - Chdir - Fchdir - Setgid - Setuid - Setsid - Setresuid - Setresgid Updates #4805 PiperOrigin-RevId: 489076929
259,985
17.11.2022 10:15:15
28,800
f3aaf4326636caf934e811cb7e41e7873fe945b9
io_ring: Handle EOF on IORING_OP_READV EOFs shouldn't be raised as an errno as error translation will fail. Short reads aren't failures on a readv syscall. Reported-by:
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/iouringfs/iouringfs.go", "new_path": "pkg/sentry/fsimpl/iouringfs/iouringfs.go", "diff": "@@ -24,6 +24,7 @@ package iouringfs\nimport (\n\"fmt\"\n+ \"io\"\n\"sync\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n@@ -382,6 +383,11 @@ func (fd *FileDescription) ProcessSubmission(t *kernel.Task, sqe *linux.IOUringS\n// For the NOP operation, we don't do anything special.\ncase linux.IORING_OP_READV:\nretValue, cqeErr = fd.handleReadv(t, sqe, flags)\n+ if cqeErr == io.EOF {\n+ // Don't raise EOF as errno, error translation will fail. Short\n+ // reads aren't failures.\n+ cqeErr = nil\n+ }\ndefault: // Unsupported operation\nretValue = -int32(linuxerr.EINVAL.Errno())\n}\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/io_uring.cc", "new_path": "test/syscalls/linux/io_uring.cc", "diff": "@@ -692,6 +692,58 @@ TEST(IOUringTest, SingleREADVTest) {\nio_uring->store_cq_head(cq_head + 1);\n}\n+// Tests that IORING_OP_READV handles EOF on an empty file correctly.\n+TEST(IOUringTest, ReadvEmptyFile) {\n+ struct io_uring_params params;\n+ std::unique_ptr<IOUring> io_uring =\n+ ASSERT_NO_ERRNO_AND_VALUE(IOUring::InitIOUring(1, params));\n+\n+ uint32_t sq_head = io_uring->load_sq_head();\n+\n+ std::string file_name = NewTempAbsPath();\n+ ASSERT_NO_ERRNO(CreateWithContents(file_name, \"\", 0666));\n+\n+ FileDescriptor filefd = ASSERT_NO_ERRNO_AND_VALUE(Open(file_name, O_RDONLY));\n+ ASSERT_GE(filefd.get(), 0);\n+\n+ unsigned *sq_array = io_uring->get_sq_array();\n+ struct io_uring_sqe *sqe = io_uring->get_sqes();\n+\n+ struct iovec iov;\n+ iov.iov_len = 0;\n+ void *buf;\n+ ASSERT_THAT(posix_memalign(&buf, BLOCK_SZ, BLOCK_SZ), SyscallSucceeds());\n+ iov.iov_base = buf;\n+\n+ sqe->flags = 0;\n+ sqe->fd = filefd.get();\n+ sqe->opcode = IORING_OP_READV;\n+ sqe->addr = reinterpret_cast<uint64_t>(&iov);\n+ sqe->len = 1;\n+ sqe->off = 0;\n+ sqe->user_data = reinterpret_cast<uint64_t>(&iov);\n+ sq_array[0] = 0;\n+\n+ uint32_t sq_tail = io_uring->load_sq_tail();\n+ io_uring->store_sq_tail(sq_tail + 1);\n+\n+ int ret = io_uring->Enter(1, 1, 0, nullptr);\n+ ASSERT_EQ(ret, 1);\n+\n+ struct io_uring_cqe *cqe = io_uring->get_cqes();\n+\n+ sq_head = io_uring->load_sq_head();\n+ ASSERT_EQ(sq_head, 1);\n+\n+ uint32_t cq_tail = io_uring->load_cq_tail();\n+ ASSERT_EQ(cq_tail, 1);\n+\n+ ASSERT_EQ(cqe->res, 0); // 0 length read, EOF.\n+\n+ uint32_t cq_head = io_uring->load_cq_head();\n+ io_uring->store_cq_head(cq_head + 1);\n+}\n+\n// Testing that io_uring_enter(2) successfully handles three READV operations\n// from three different files submitted through a single invocation.\nTEST(IOUringTest, ThreeREADVSingleEnterTest) {\n" } ]
Go
Apache License 2.0
google/gvisor
io_ring: Handle EOF on IORING_OP_READV EOFs shouldn't be raised as an errno as error translation will fail. Short reads aren't failures on a readv syscall. Reported-by: syzbot+37fc0fc0df42740a5cea@syzkaller.appspotmail.com PiperOrigin-RevId: 489242631
259,992
17.11.2022 12:27:22
28,800
5ce359a6ebf838773131e1e81618add32b2adaa1
Add option to list only sandboxes This is required for setting up trace sessions on running sandboxes. Currently, `runsc list` lists all containers and there is no way to find out the sandbox ID for them. Fixes
[ { "change_type": "MODIFY", "old_path": "runsc/cmd/BUILD", "new_path": "runsc/cmd/BUILD", "diff": "@@ -87,6 +87,7 @@ go_test(\n\"exec_test.go\",\n\"gofer_test.go\",\n\"install_test.go\",\n+ \"list_test.go\",\n\"mitigate_test.go\",\n],\ndata = [\n" }, { "change_type": "MODIFY", "old_path": "runsc/cmd/list.go", "new_path": "runsc/cmd/list.go", "diff": "@@ -18,6 +18,7 @@ import (\n\"context\"\n\"encoding/json\"\n\"fmt\"\n+ \"io\"\n\"os\"\n\"text/tabwriter\"\n\"time\"\n@@ -35,6 +36,7 @@ import (\ntype List struct {\nquiet bool\nformat string\n+ sandbox bool\n}\n// Name implements subcommands.command.name.\n@@ -56,6 +58,7 @@ func (*List) Usage() string {\nfunc (l *List) SetFlags(f *flag.FlagSet) {\nf.BoolVar(&l.quiet, \"quiet\", false, \"only list container ids\")\nf.StringVar(&l.format, \"format\", \"text\", \"output format: 'text' (default) or 'json'\")\n+ f.BoolVar(&l.sandbox, \"sandbox\", false, \"limit output to sandboxes only\")\n}\n// Execute implements subcommands.Command.Execute.\n@@ -66,22 +69,42 @@ func (l *List) Execute(_ context.Context, f *flag.FlagSet, args ...any) subcomma\n}\nconf := args[0].(*config.Config)\n- ids, err := container.List(conf.RootDir)\n- if err != nil {\n+\n+ if err := l.execute(conf.RootDir, os.Stdout); err != nil {\nutil.Fatalf(\"%v\", err)\n}\n+ return subcommands.ExitSuccess\n+}\n+\n+func (l *List) execute(rootDir string, out io.Writer) error {\n+ ids, err := container.List(rootDir)\n+ if err != nil {\n+ return err\n+ }\n+\n+ if l.sandbox {\n+ sandboxes := make(map[string]struct{})\n+ for _, id := range ids {\n+ sandboxes[id.SandboxID] = struct{}{}\n+ }\n+ // Reset ids to list only sandboxes.\n+ ids = nil\n+ for id := range sandboxes {\n+ ids = append(ids, container.FullID{SandboxID: id, ContainerID: id})\n+ }\n+ }\nif l.quiet {\nfor _, id := range ids {\n- fmt.Println(id.ContainerID)\n+ fmt.Fprintln(out, id.ContainerID)\n}\n- return subcommands.ExitSuccess\n+ return nil\n}\n// Collect the containers.\nvar containers []*container.Container\nfor _, id := range ids {\n- c, err := container.Load(conf.RootDir, id, container.LoadOpts{Exact: true})\n+ c, err := container.Load(rootDir, id, container.LoadOpts{Exact: true})\nif err != nil {\nlog.Warningf(\"Skipping container %q: %v\", id, err)\ncontinue\n@@ -92,7 +115,7 @@ func (l *List) Execute(_ context.Context, f *flag.FlagSet, args ...any) subcomma\nswitch l.format {\ncase \"text\":\n// Print a nice table.\n- w := tabwriter.NewWriter(os.Stdout, 12, 1, 3, ' ', 0)\n+ w := tabwriter.NewWriter(out, 12, 1, 3, ' ', 0)\nfmt.Fprint(w, \"ID\\tPID\\tSTATUS\\tBUNDLE\\tCREATED\\tOWNER\\n\")\nfor _, c := range containers {\nfmt.Fprintf(w, \"%s\\t%d\\t%s\\t%s\\t%s\\t%s\\n\",\n@@ -110,11 +133,11 @@ func (l *List) Execute(_ context.Context, f *flag.FlagSet, args ...any) subcomma\nfor _, c := range containers {\nstates = append(states, c.State())\n}\n- if err := json.NewEncoder(os.Stdout).Encode(states); err != nil {\n- util.Fatalf(\"marshaling container state: %v\", err)\n+ if err := json.NewEncoder(out).Encode(states); err != nil {\n+ return fmt.Errorf(\"marshaling container state: %w\", err)\n}\ndefault:\n- util.Fatalf(\"unknown list format %q\", l.format)\n+ return fmt.Errorf(\"unknown list format %q\", l.format)\n}\n- return subcommands.ExitSuccess\n+ return nil\n}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "runsc/cmd/list_test.go", "diff": "+// Copyright 2022 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package cmd\n+\n+import (\n+ \"bytes\"\n+ \"os\"\n+ \"strings\"\n+ \"testing\"\n+\n+ \"gvisor.dev/gvisor/pkg/test/testutil\"\n+ \"gvisor.dev/gvisor/runsc/container\"\n+)\n+\n+func TestList(t *testing.T) {\n+ dir, err := os.MkdirTemp(testutil.TmpDir(), \"list\")\n+ if err != nil {\n+ t.Fatal(err)\n+ }\n+ defer os.RemoveAll(dir)\n+\n+ for _, tc := range []struct {\n+ name string\n+ list List\n+ ids []container.FullID\n+ want []string\n+ }{\n+ {\n+ name: \"single\",\n+ list: List{quiet: true},\n+ ids: []container.FullID{\n+ {SandboxID: \"abc\", ContainerID: \"123\"},\n+ },\n+ want: []string{\"123\"},\n+ },\n+ {\n+ name: \"multiple\",\n+ list: List{quiet: true},\n+ ids: []container.FullID{\n+ {SandboxID: \"abc\", ContainerID: \"123\"},\n+ {SandboxID: \"def\", ContainerID: \"123\"},\n+ },\n+ want: []string{\"123\", \"123\"},\n+ },\n+ {\n+ name: \"multicontainer\",\n+ list: List{quiet: true},\n+ ids: []container.FullID{\n+ {SandboxID: \"abc\", ContainerID: \"123\"},\n+ {SandboxID: \"abc\", ContainerID: \"456\"},\n+ },\n+ want: []string{\"123\", \"456\"},\n+ },\n+ {\n+ name: \"multiple-multicontainer\",\n+ list: List{quiet: true},\n+ ids: []container.FullID{\n+ {SandboxID: \"abc\", ContainerID: \"123\"},\n+ {SandboxID: \"abc\", ContainerID: \"456\"},\n+ {SandboxID: \"def\", ContainerID: \"123\"},\n+ {SandboxID: \"def\", ContainerID: \"789\"},\n+ {SandboxID: \"ghi\", ContainerID: \"012\"},\n+ },\n+ want: []string{\"123\", \"456\", \"123\", \"789\", \"012\"},\n+ },\n+ {\n+ name: \"sandbox-single\",\n+ list: List{quiet: true, sandbox: true},\n+ ids: []container.FullID{\n+ {SandboxID: \"abc\", ContainerID: \"123\"},\n+ },\n+ want: []string{\"abc\"},\n+ },\n+ {\n+ name: \"sandbox-multiple\",\n+ list: List{quiet: true, sandbox: true},\n+ ids: []container.FullID{\n+ {SandboxID: \"abc\", ContainerID: \"123\"},\n+ {SandboxID: \"def\", ContainerID: \"123\"},\n+ },\n+ want: []string{\"abc\", \"def\"},\n+ },\n+ {\n+ name: \"sandbox-multicontainer\",\n+ list: List{quiet: true, sandbox: true},\n+ ids: []container.FullID{\n+ {SandboxID: \"abc\", ContainerID: \"123\"},\n+ {SandboxID: \"abc\", ContainerID: \"456\"},\n+ },\n+ want: []string{\"abc\"},\n+ },\n+ {\n+ name: \"sandbox-multiple-multicontainer\",\n+ list: List{quiet: true, sandbox: true},\n+ ids: []container.FullID{\n+ {SandboxID: \"abc\", ContainerID: \"123\"},\n+ {SandboxID: \"abc\", ContainerID: \"456\"},\n+ {SandboxID: \"def\", ContainerID: \"123\"},\n+ {SandboxID: \"def\", ContainerID: \"789\"},\n+ {SandboxID: \"ghi\", ContainerID: \"012\"},\n+ },\n+ want: []string{\"abc\", \"def\", \"ghi\"},\n+ },\n+ } {\n+ t.Run(tc.name, func(t *testing.T) {\n+ for _, id := range tc.ids {\n+ saver := container.StateFile{RootDir: dir, ID: id}\n+ if err := saver.LockForNew(); err != nil {\n+ t.Fatal(err)\n+ }\n+ defer saver.Destroy()\n+ defer saver.UnlockOrDie()\n+\n+ if err := saver.SaveLocked(nil); err != nil {\n+ t.Fatal(err)\n+ }\n+ }\n+\n+ out := &bytes.Buffer{}\n+ if err := tc.list.execute(dir, out); err != nil {\n+ t.Fatal(err)\n+ }\n+\n+ // Handle IDs returned out of order.\n+ got := make(map[string]struct{})\n+ for _, id := range strings.Split(out.String(), \"\\n\") {\n+ got[id] = struct{}{}\n+ }\n+ for _, want := range tc.want {\n+ if _, ok := got[want]; !ok {\n+ t.Errorf(\"container ID not found in result want: %q, got: %q\", want, out)\n+ }\n+ }\n+ })\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "runsc/container/container.go", "new_path": "runsc/container/container.go", "diff": "@@ -218,10 +218,10 @@ func New(conf *config.Config, args Args) (*Container, error) {\n// Lock the container metadata file to prevent concurrent creations of\n// containers with the same id.\n- if err := c.Saver.lockForNew(); err != nil {\n+ if err := c.Saver.LockForNew(); err != nil {\nreturn nil, fmt.Errorf(\"cannot lock container metadata file: %w\", err)\n}\n- defer c.Saver.unlockOrDie()\n+ defer c.Saver.UnlockOrDie()\n// If the metadata annotations indicate that this container should be started\n// in an existing sandbox, we must do so. These are the possible metadata\n@@ -370,7 +370,7 @@ func (c *Container) Start(conf *config.Config) error {\nif err := c.Saver.lock(); err != nil {\nreturn err\n}\n- unlock := cleanup.Make(c.Saver.unlockOrDie)\n+ unlock := cleanup.Make(c.Saver.UnlockOrDie)\ndefer unlock.Clean()\nif err := c.requireStatus(\"start\", Created); err != nil {\n@@ -454,7 +454,7 @@ func (c *Container) Restore(spec *specs.Spec, conf *config.Config, restoreFile s\nif err := c.Saver.lock(); err != nil {\nreturn err\n}\n- defer c.Saver.unlockOrDie()\n+ defer c.Saver.UnlockOrDie()\nif err := c.requireStatus(\"restore\", Created); err != nil {\nreturn err\n@@ -640,7 +640,7 @@ func (c *Container) Pause() error {\nif err := c.Saver.lock(); err != nil {\nreturn err\n}\n- defer c.Saver.unlockOrDie()\n+ defer c.Saver.UnlockOrDie()\nif c.Status != Created && c.Status != Running {\nreturn fmt.Errorf(\"cannot pause container %q in state %v\", c.ID, c.Status)\n@@ -660,7 +660,7 @@ func (c *Container) Resume() error {\nif err := c.Saver.lock(); err != nil {\nreturn err\n}\n- defer c.Saver.unlockOrDie()\n+ defer c.Saver.UnlockOrDie()\nif c.Status != Paused {\nreturn fmt.Errorf(\"cannot resume container %q in state %v\", c.ID, c.Status)\n@@ -702,7 +702,7 @@ func (c *Container) Destroy() error {\nreturn err\n}\ndefer func() {\n- c.Saver.unlockOrDie()\n+ c.Saver.UnlockOrDie()\n_ = c.Saver.close()\n}()\n@@ -724,7 +724,7 @@ func (c *Container) Destroy() error {\nerrs = append(errs, err.Error())\n}\n- if err := c.Saver.destroy(); err != nil {\n+ if err := c.Saver.Destroy(); err != nil {\nerr = fmt.Errorf(\"deleting container state files: %v\", err)\nlog.Warningf(\"%v\", err)\nerrs = append(errs, err.Error())\n@@ -768,7 +768,7 @@ func (c *Container) Destroy() error {\n// Precondition: container must be locked with container.lock().\nfunc (c *Container) saveLocked() error {\nlog.Debugf(\"Save container, cid: %s\", c.ID)\n- if err := c.Saver.saveLocked(c); err != nil {\n+ if err := c.Saver.SaveLocked(c); err != nil {\nreturn fmt.Errorf(\"saving container metadata: %v\", err)\n}\nreturn nil\n" }, { "change_type": "MODIFY", "old_path": "runsc/container/state_file.go", "new_path": "runsc/container/state_file.go", "diff": "@@ -263,20 +263,20 @@ func (s *StateFile) lock() error {\nreturn nil\n}\n-// lockForNew acquires the lock and checks if the state file doesn't exist. This\n+// LockForNew acquires the lock and checks if the state file doesn't exist. This\n// is done to ensure that more than one creation didn't race to create\n// containers with the same ID.\n-func (s *StateFile) lockForNew() error {\n+func (s *StateFile) LockForNew() error {\nif err := s.lock(); err != nil {\nreturn err\n}\n// Checks if the container already exists by looking for the metadata file.\nif _, err := os.Stat(s.statePath()); err == nil {\n- s.unlockOrDie()\n+ s.UnlockOrDie()\nreturn fmt.Errorf(\"container already exists\")\n} else if !os.IsNotExist(err) {\n- s.unlockOrDie()\n+ s.UnlockOrDie()\nreturn fmt.Errorf(\"looking for existing container: %v\", err)\n}\nreturn nil\n@@ -295,7 +295,8 @@ func (s *StateFile) unlock() error {\nreturn nil\n}\n-func (s *StateFile) unlockOrDie() {\n+// UnlockOrDie is the same as unlock() but panics in case of failure.\n+func (s *StateFile) UnlockOrDie() {\nif !s.flock.Locked() {\npanic(\"unlock called without lock held\")\n}\n@@ -304,10 +305,10 @@ func (s *StateFile) unlockOrDie() {\n}\n}\n-// saveLocked saves 'v' to the state file.\n+// SaveLocked saves 'v' to the state file.\n//\n// Preconditions: lock() must been called before.\n-func (s *StateFile) saveLocked(v any) error {\n+func (s *StateFile) SaveLocked(v any) error {\nif !s.flock.Locked() {\npanic(\"saveLocked called without lock held\")\n}\n@@ -326,7 +327,7 @@ func (s *StateFile) load(v any) error {\nif err := s.lock(); err != nil {\nreturn err\n}\n- defer s.unlockOrDie()\n+ defer s.UnlockOrDie()\nmetaBytes, err := ioutil.ReadFile(s.statePath())\nif err != nil {\n@@ -361,10 +362,10 @@ func (s *StateFile) lockPath() string {\nreturn buildPath(s.RootDir, s.ID, \"lock\")\n}\n-// destroy deletes all state created by the stateFile. It may be called with the\n+// Destroy deletes all state created by the stateFile. It may be called with the\n// lock file held. In that case, the lock file must still be unlocked and\n// properly closed after destroy returns.\n-func (s *StateFile) destroy() error {\n+func (s *StateFile) Destroy() error {\nif err := os.Remove(s.statePath()); err != nil && !os.IsNotExist(err) {\nreturn err\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Add option to list only sandboxes This is required for setting up trace sessions on running sandboxes. Currently, `runsc list` lists all containers and there is no way to find out the sandbox ID for them. Fixes #8210 PiperOrigin-RevId: 489278285
259,975
17.11.2022 13:48:19
28,800
106f6ea967467ae195e03979dba4f82c9e3cdf30
Re-enable process_vm_(read|write)v
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/task_usermem.go", "new_path": "pkg/sentry/kernel/task_usermem.go", "diff": "@@ -347,16 +347,28 @@ func (cc *taskCopyContext) CopyScratchBuffer(size int) []byte {\n}\nfunc (cc *taskCopyContext) getMemoryManager() (*mm.MemoryManager, error) {\n- cc.t.mu.Lock()\ntmm := cc.t.MemoryManager()\n- cc.t.mu.Unlock()\n+ if tmm == nil {\n+ return nil, linuxerr.ESRCH\n+ }\nif !tmm.IncUsers() {\nreturn nil, linuxerr.EFAULT\n}\nreturn tmm, nil\n}\n+// WithTaskMutexLocked runs the given function with the task's mutex locked.\n+func (cc *taskCopyContext) WithTaskMutexLocked(fn func() error) error {\n+ cc.t.mu.Lock()\n+ defer cc.t.mu.Unlock()\n+ return fn()\n+}\n+\n// CopyInBytes implements marshal.CopyContext.CopyInBytes.\n+//\n+// Preconditions: Same as usermem.IO.CopyIn, plus:\n+// - The caller must be running on the task goroutine or hold the cc.t.mu\n+// - t's AddressSpace must be active.\nfunc (cc *taskCopyContext) CopyInBytes(addr hostarch.Addr, dst []byte) (int, error) {\ntmm, err := cc.getMemoryManager()\nif err != nil {\n@@ -367,6 +379,10 @@ func (cc *taskCopyContext) CopyInBytes(addr hostarch.Addr, dst []byte) (int, err\n}\n// CopyOutBytes implements marshal.CopyContext.CopyOutBytes.\n+//\n+// Preconditions: Same as usermem.IO.CopyOut, plus:\n+// - The caller must be running on the task goroutine or hold the cc.t.mu\n+// - t's AddressSpace must be active.\nfunc (cc *taskCopyContext) CopyOutBytes(addr hostarch.Addr, src []byte) (int, error) {\ntmm, err := cc.getMemoryManager()\nif err != nil {\n@@ -378,11 +394,19 @@ func (cc *taskCopyContext) CopyOutBytes(addr hostarch.Addr, src []byte) (int, er\n// CopyOutIovecs converts src to an array of struct iovecs and copies it to the\n// memory mapped at addr for Task.\n+//\n+// Preconditions: Same as usermem.IO.CopyOut, plus:\n+// - The caller must be running on the task goroutine or hold the cc.t.mu\n+// - t's AddressSpace must be active.\nfunc (cc *taskCopyContext) CopyOutIovecs(addr hostarch.Addr, src hostarch.AddrRangeSeq) error {\nreturn copyOutIovecs(cc, cc.t, addr, src)\n}\n// CopyInIovecs copies in IoVecs for taskCopyContext.\n+//\n+// Preconditions: Same as usermem.IO.CopyIn, plus:\n+// - The caller must be running on the task goroutine or hold the cc.t.mu\n+// - t's AddressSpace must be active.\nfunc (cc *taskCopyContext) CopyInIovecs(addr hostarch.Addr, numIovecs int) ([]hostarch.AddrRange, error) {\nreturn copyInIovecs(cc, cc.t, addr, numIovecs)\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/linux64.go", "new_path": "pkg/sentry/syscalls/linux/linux64.go", "diff": "@@ -362,8 +362,8 @@ var AMD64 = &kernel.SyscallTable{\n307: syscalls.Supported(\"sendmmsg\", SendMMsg),\n308: syscalls.ErrorWithEvent(\"setns\", linuxerr.EOPNOTSUPP, \"Needs filesystem support\", []string{\"gvisor.dev/issue/140\"}), // TODO(b/29354995)\n309: syscalls.Supported(\"getcpu\", Getcpu),\n- 310: syscalls.ErrorWithEvent(\"process_vm_readv\", linuxerr.ENOSYS, \"\", []string{\"gvisor.dev/issue/158\"}),\n- 311: syscalls.ErrorWithEvent(\"process_vm_writev\", linuxerr.ENOSYS, \"\", []string{\"gvisor.dev/issue/158\"}),\n+ 310: syscalls.Supported(\"process_vm_readv\", ProcessVMReadv),\n+ 311: syscalls.Supported(\"process_vm_writev\", ProcessVMWritev),\n312: syscalls.CapError(\"kcmp\", linux.CAP_SYS_PTRACE, \"\", nil),\n313: syscalls.CapError(\"finit_module\", linux.CAP_SYS_MODULE, \"\", nil),\n314: syscalls.ErrorWithEvent(\"sched_setattr\", linuxerr.ENOSYS, \"gVisor does not implement a scheduler.\", []string{\"gvisor.dev/issue/264\"}), // TODO(b/118902272)\n@@ -685,8 +685,8 @@ var ARM64 = &kernel.SyscallTable{\n267: syscalls.Supported(\"syncfs\", Syncfs),\n268: syscalls.ErrorWithEvent(\"setns\", linuxerr.EOPNOTSUPP, \"Needs filesystem support\", []string{\"gvisor.dev/issue/140\"}), // TODO(b/29354995)\n269: syscalls.Supported(\"sendmmsg\", SendMMsg),\n- 270: syscalls.ErrorWithEvent(\"process_vm_readv\", linuxerr.ENOSYS, \"\", []string{\"gvisor.dev/issue/158\"}),\n- 271: syscalls.ErrorWithEvent(\"process_vm_writev\", linuxerr.ENOSYS, \"\", []string{\"gvisor.dev/issue/158\"}),\n+ 270: syscalls.Supported(\"process_vm_readv\", ProcessVMReadv),\n+ 271: syscalls.Supported(\"process_vm_writev\", ProcessVMWritev),\n272: syscalls.CapError(\"kcmp\", linux.CAP_SYS_PTRACE, \"\", nil),\n273: syscalls.CapError(\"finit_module\", linux.CAP_SYS_MODULE, \"\", nil),\n274: syscalls.ErrorWithEvent(\"sched_setattr\", linuxerr.ENOSYS, \"gVisor does not implement a scheduler.\", []string{\"gvisor.dev/issue/264\"}), // TODO(b/118902272)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/sys_process_vm.go", "new_path": "pkg/sentry/syscalls/linux/sys_process_vm.go", "diff": "@@ -42,16 +42,14 @@ func processVMRW(t *kernel.Task, args arch.SyscallArguments, isWrite bool) (uint\nflags := args[5].Int()\nswitch {\n- case flags != 0:\n+ case flags != 0 ||\n+ liovcnt < 0 ||\n+ riovcnt < 0 ||\n+ liovcnt > linux.UIO_MAXIOV ||\n+ riovcnt > linux.UIO_MAXIOV:\nreturn 0, nil, linuxerr.EINVAL\n- case liovcnt < 0 || liovcnt > linux.UIO_MAXIOV:\n- return 0, nil, linuxerr.EINVAL\n- case riovcnt < 0 || riovcnt > linux.UIO_MAXIOV:\n- return 0, nil, linuxerr.EFAULT\ncase lvec == 0 || rvec == 0:\nreturn 0, nil, linuxerr.EFAULT\n- case riovcnt > linux.UIO_MAXIOV || liovcnt > linux.UIO_MAXIOV:\n- return 0, nil, linuxerr.EINVAL\ncase liovcnt == 0 || riovcnt == 0:\nreturn 0, nil, nil\n}\n@@ -78,13 +76,15 @@ func doProcessVMReadWrite(rProcess, wProcess *kernel.Task, rAddr, wAddr hostarch\nrCtx := rProcess.CopyContext(rProcess, usermem.IOOpts{})\nwCtx := wProcess.CopyContext(wProcess, usermem.IOOpts{})\n+ var wCount int\n+ doProcessVMReadWriteLocked := func() error {\nrIovecs, err := rCtx.CopyInIovecs(rAddr, rIovecCount)\nif err != nil {\n- return 0, nil, err\n+ return err\n}\nwIovecs, err := wCtx.CopyInIovecs(wAddr, wIovecCount)\nif err != nil {\n- return 0, nil, err\n+ return err\n}\nbufSize := 0\n@@ -95,7 +95,6 @@ func doProcessVMReadWrite(rProcess, wProcess *kernel.Task, rAddr, wAddr hostarch\n}\nbuf := rCtx.CopyScratchBuffer(bufSize)\n- wCount := 0\nfor _, rIovec := range rIovecs {\nif len(wIovecs) <= 0 {\nbreak\n@@ -104,13 +103,13 @@ func doProcessVMReadWrite(rProcess, wProcess *kernel.Task, rAddr, wAddr hostarch\nbuf = buf[0:int(rIovec.Length())]\nbytes, err := rCtx.CopyInBytes(rIovec.Start, buf)\nif linuxerr.Equals(linuxerr.EFAULT, err) {\n- return uintptr(wCount), nil, nil\n+ return nil\n}\nif err != nil {\n- return uintptr(wCount), nil, err\n+ return err\n}\nif bytes != int(rIovec.Length()) {\n- return uintptr(wCount), nil, nil\n+ return nil\n}\nstart := 0\nfor bytes > start && 0 < len(wIovecs) {\n@@ -122,22 +121,34 @@ func doProcessVMReadWrite(rProcess, wProcess *kernel.Task, rAddr, wAddr hostarch\nwCount += out\nstart += out\nif linuxerr.Equals(linuxerr.EFAULT, err) {\n- return uintptr(wCount), nil, nil\n+ return nil\n}\nif err != nil {\n- return uintptr(wCount), nil, err\n+ return err\n}\nif out != writeLength {\n- return uintptr(wCount), nil, nil\n+ return nil\n}\nwIovecs[0].Start += hostarch.Addr(out)\nif !wIovecs[0].WellFormed() {\n- return uintptr(wCount), nil, err\n+ return err\n}\nif wIovecs[0].Length() == 0 {\nwIovecs = wIovecs[1:]\n}\n}\n}\n- return uintptr(wCount), nil, nil\n+ return nil\n+ }\n+\n+ err := rCtx.WithTaskMutexLocked(func() error {\n+ if rProcess.ThreadGroup().Leader() != wProcess.ThreadGroup().Leader() {\n+ return wCtx.WithTaskMutexLocked(func() error {\n+ return doProcessVMReadWriteLocked()\n+ })\n+ }\n+ return doProcessVMReadWriteLocked()\n+ })\n+\n+ return uintptr(wCount), nil, err\n}\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/BUILD", "new_path": "test/syscalls/BUILD", "diff": "@@ -1087,7 +1087,5 @@ syscall_test(\nsyscall_test(\nsize = \"small\",\n- # TODO(b/245647342): These tests are flaky on native.\n- allow_native = False,\ntest = \"//test/syscalls/linux:process_vm_read_write\",\n)\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/process_vm_read_write.cc", "new_path": "test/syscalls/linux/process_vm_read_write.cc", "diff": "#include \"absl/strings/str_cat.h\"\n#include \"absl/strings/str_join.h\"\n#include \"test/util/linux_capability_util.h\"\n+#include \"test/util/logging.h\"\n#include \"test/util/multiprocess_util.h\"\n#include \"test/util/posix_error.h\"\n#include \"test/util/test_util.h\"\n@@ -302,7 +303,7 @@ TEST(ProcessVMInvalidTest, ProcessNoExist) {\nSyscallFailsWithErrno(::testing::AnyOf(ESRCH, EFAULT)));\n}\n-TEST(ProcessVMInvalidTest, InvalidLength) {\n+TEST(ProcessVMInvalidTest, GreaterThanIOV_MAX) {\nSKIP_IF(ProcessVMCallsNotSupported());\nstd::string contents = \"3263827\";\nstruct iovec iov;\n@@ -315,35 +316,25 @@ TEST(ProcessVMInvalidTest, InvalidLength) {\nchild_iov.iov_len = contents.size();\npid_t parent = getppid();\n- TEST_CHECK_ERRNO(process_vm_readv(parent, &child_iov, contents.length(),\n- iov_addr, -1, 0),\n- EFAULT);\n- TEST_CHECK_ERRNO(process_vm_writev(parent, &child_iov, contents.length(),\n- iov_addr, -1, 0),\n- EFAULT);\n-\n- TEST_CHECK_ERRNO(process_vm_readv(parent, &child_iov, -1, iov_addr,\n- contents.length(), 0),\n- EINVAL);\n-\n- TEST_CHECK_ERRNO(process_vm_writev(parent, &child_iov, -1, iov_addr,\n- contents.length(), 0),\n- EINVAL);\n- TEST_CHECK_ERRNO(process_vm_readv(parent, &child_iov, contents.length(),\n- iov_addr, IOV_MAX + 1, 0),\n- EFAULT);\n-\n- TEST_CHECK_ERRNO(process_vm_writev(parent, &child_iov, contents.length(),\n- iov_addr, IOV_MAX + 1, 0),\n- EFAULT);\n-\n- TEST_CHECK_ERRNO(process_vm_readv(parent, &child_iov, IOV_MAX + 2, iov_addr,\n- contents.length(), 0),\n- EINVAL);\n-\n- TEST_CHECK_ERRNO(process_vm_writev(parent, &child_iov, IOV_MAX + 8,\n- iov_addr, contents.length(), 0),\n- EINVAL);\n+ TEST_CHECK_MSG(-1 == process_vm_readv(parent, &child_iov, 1, iov_addr,\n+ IOV_MAX + 1, 0) &&\n+ errno == EINVAL,\n+ \"read remote_process_over_IOV_MAX\");\n+\n+ TEST_CHECK_MSG(-1 == process_vm_writev(parent, &child_iov, 1, iov_addr,\n+ IOV_MAX + 3, 0) &&\n+ errno == EINVAL,\n+ \"write remote process over IOV_MAX\");\n+\n+ TEST_CHECK_MSG(-1 == process_vm_readv(parent, &child_iov, IOV_MAX + 2,\n+ iov_addr, 1, 0) &&\n+ errno == EINVAL,\n+ \"read local process over IOV_MAX\");\n+\n+ TEST_CHECK_MSG(-1 == process_vm_writev(parent, &child_iov, IOV_MAX + 8,\n+ iov_addr, 1, 0) &&\n+ errno == EINVAL,\n+ \"write local process over IOV_MAX\");\n};\nEXPECT_THAT(InForkedProcess(fn), IsPosixErrorOkAndHolds(0));\n}\n@@ -398,6 +389,5 @@ TEST(ProcessVMTest, WriteToZombie) {\nSyscallFailsWithErrno(ESRCH));\n}\n} // namespace\n-\n} // namespace testing\n} // namespace gvisor\n" } ]
Go
Apache License 2.0
google/gvisor
Re-enable process_vm_(read|write)v PiperOrigin-RevId: 489298284
259,982
18.11.2022 11:45:57
28,800
536a924f1abc556a6f905855059cca7f7d511be5
Adding more trace point integration tests for the following syscalls: - chroot - dup - dup2 - dup3 - prlimit64 - eventfd - eventfd2 - bind - accept - accept4 Updates
[ { "change_type": "MODIFY", "old_path": "test/trace/trace_test.go", "new_path": "test/trace/trace_test.go", "diff": "@@ -75,7 +75,7 @@ func TestAll(t *testing.T) {\ncutoffTime = time.Now()\ncmd := exec.Command(\nrunsc,\n- \"--debug\", \"--strace\", \"--alsologtostderr\", // Debug logging for troubleshooting\n+ \"--debug\", \"--alsologtostderr\", // Debug logging for troubleshooting\n\"--rootless\", \"--network=none\", \"--TESTONLY-unsafe-nonroot\", // Disable features that we don't care\n\"--pod-init-config\", cfgFile.Name(),\n\"do\", workload)\n@@ -112,14 +112,16 @@ func matchPoints(t *testing.T, msgs []test.Message) {\npb.MessageType_MESSAGE_SYSCALL_CHDIR: {checker: checkSyscallChdir},\npb.MessageType_MESSAGE_SYSCALL_SETID: {checker: checkSyscallSetid},\npb.MessageType_MESSAGE_SYSCALL_SETRESID: {checker: checkSyscallSetresid},\n+ pb.MessageType_MESSAGE_SYSCALL_CHROOT: {checker: checkSyscallChroot},\n+ pb.MessageType_MESSAGE_SYSCALL_DUP: {checker: checkSyscallDup},\n+ pb.MessageType_MESSAGE_SYSCALL_PRLIMIT64: {checker: checkSyscallPrlimit64},\n+ pb.MessageType_MESSAGE_SYSCALL_EVENTFD: {checker: checkSyscallEventfd},\n+ pb.MessageType_MESSAGE_SYSCALL_BIND: {checker: checkSyscallBind},\n+ pb.MessageType_MESSAGE_SYSCALL_ACCEPT: {checker: checkSyscallAccept},\n// TODO(gvisor.dev/issue/4805): Add validation for these messages.\n- pb.MessageType_MESSAGE_SYSCALL_ACCEPT: {checker: checkTODO},\n- pb.MessageType_MESSAGE_SYSCALL_BIND: {checker: checkTODO},\npb.MessageType_MESSAGE_SYSCALL_CLONE: {checker: checkTODO},\n- pb.MessageType_MESSAGE_SYSCALL_DUP: {checker: checkTODO},\npb.MessageType_MESSAGE_SYSCALL_PIPE: {checker: checkTODO},\n- pb.MessageType_MESSAGE_SYSCALL_PRLIMIT64: {checker: checkTODO},\n}\nfor _, msg := range msgs {\nt.Logf(\"Processing message type %v\", msg.MsgType)\n@@ -540,6 +542,117 @@ func checkSyscallChdir(msg test.Message) error {\nreturn nil\n}\n+func checkSyscallDup(msg test.Message) error {\n+ p := pb.Dup{}\n+ if err := proto.Unmarshal(msg.Msg, &p); err != nil {\n+ return err\n+ }\n+ if err := checkContextData(p.ContextData); err != nil {\n+ return err\n+ }\n+ if p.OldFd < 0 {\n+ return fmt.Errorf(\"invalid FD: %d\", p.OldFd)\n+ }\n+ if p.NewFd < 0 {\n+ return fmt.Errorf(\"invalid FD: %d\", p.NewFd)\n+ }\n+ if p.Flags != unix.O_CLOEXEC && p.Flags != 0 {\n+ return fmt.Errorf(\"invalid flag got: %v\", p.Flags)\n+ }\n+\n+ return nil\n+}\n+\n+func checkSyscallPrlimit64(msg test.Message) error {\n+ p := pb.Prlimit{}\n+ if err := proto.Unmarshal(msg.Msg, &p); err != nil {\n+ return err\n+ }\n+ if err := checkContextData(p.ContextData); err != nil {\n+ return err\n+ }\n+ if p.Pid < 0 {\n+ return fmt.Errorf(\"invalid PID: %d\", p.Pid)\n+ }\n+ return nil\n+}\n+\n+func checkSyscallEventfd(msg test.Message) error {\n+ p := pb.Eventfd{}\n+ if err := proto.Unmarshal(msg.Msg, &p); err != nil {\n+ return err\n+ }\n+ if err := checkContextData(p.ContextData); err != nil {\n+ return err\n+ }\n+ if p.Val < 0 {\n+ return fmt.Errorf(\"invalid PID: %d\", p.Val)\n+ }\n+ if p.Flags != unix.EFD_NONBLOCK && p.Flags != 0 {\n+ return fmt.Errorf(\"invalid Flag got: %d, \", p.Flags)\n+ }\n+\n+ return nil\n+}\n+\n+func checkSyscallBind(msg test.Message) error {\n+ p := pb.Bind{}\n+ if err := proto.Unmarshal(msg.Msg, &p); err != nil {\n+ return err\n+ }\n+ if err := checkContextData(p.ContextData); err != nil {\n+ return err\n+ }\n+ if p.Fd < 0 {\n+ return fmt.Errorf(\"invalid FD: %d\", p.Fd)\n+ }\n+ if p.FdPath == \" \" {\n+ return fmt.Errorf(\"invalid Path: %v\", p.FdPath)\n+ }\n+ if len(p.Address) == 0 {\n+ return fmt.Errorf(\"invalid address: %d\", p.Address)\n+ }\n+ return nil\n+}\n+\n+func checkSyscallAccept(msg test.Message) error {\n+ p := pb.Accept{}\n+ if err := proto.Unmarshal(msg.Msg, &p); err != nil {\n+ return err\n+ }\n+ if err := checkContextData(p.ContextData); err != nil {\n+ return err\n+ }\n+ if p.Fd < 0 {\n+ return fmt.Errorf(\"invalid FD: %d\", p.Fd)\n+ }\n+ if p.FdPath == \"\" {\n+ return fmt.Errorf(\"invalid Path: %v\", p.FdPath)\n+ }\n+ if len(p.Address) != 0 {\n+ return fmt.Errorf(\"invalid address: %d, %v\", p.Address, p.Sysno)\n+ }\n+ if p.Flags != 0 && p.Flags != unix.SOCK_CLOEXEC {\n+ return fmt.Errorf(\"invalid flag got: %d\", p.Flags)\n+ }\n+ return nil\n+}\n+\n+func checkSyscallChroot(msg test.Message) error {\n+ p := pb.Chroot{}\n+ if err := proto.Unmarshal(msg.Msg, &p); err != nil {\n+ return err\n+ }\n+ if err := checkContextData(p.ContextData); err != nil {\n+ return err\n+ }\n+ if want := \"trace_test.abc\"; !strings.Contains(p.Pathname, want) {\n+ return fmt.Errorf(\"wrong Pathname, want: %q, got: %q\", want, p.Pathname)\n+ }\n+\n+ return nil\n+}\n+\nfunc checkTODO(_ test.Message) error {\nreturn nil\n}\n" }, { "change_type": "MODIFY", "old_path": "test/trace/workload/BUILD", "new_path": "test/trace/workload/BUILD", "diff": "@@ -10,6 +10,7 @@ cc_binary(\n],\nvisibility = [\"//test/trace:__pkg__\"],\ndeps = [\n+ \"//test/util:eventfd_util\",\n\"//test/util:file_descriptor\",\n\"//test/util:multiprocess_util\",\n\"//test/util:posix_error\",\n" }, { "change_type": "MODIFY", "old_path": "test/trace/workload/workload.cc", "new_path": "test/trace/workload/workload.cc", "diff": "#include <err.h>\n#include <fcntl.h>\n+#include <sys/eventfd.h>\n+#include <sys/resource.h>\n#include <sys/socket.h>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <sys/un.h>\n#include <unistd.h>\n+#include <csignal>\n#include <iostream>\n#include <ostream>\n#include \"absl/cleanup/cleanup.h\"\n#include \"absl/strings/str_cat.h\"\n#include \"absl/time/clock.h\"\n+#include \"test/util/eventfd_util.h\"\n#include \"test/util/file_descriptor.h\"\n#include \"test/util/multiprocess_util.h\"\n#include \"test/util/posix_error.h\"\n@@ -261,6 +265,199 @@ void runSetresgid() {\n}\n}\n+void runChroot() {\n+ const auto pathname = \"trace_test.abc\";\n+ static constexpr mode_t kDefaultDirMode = 0755;\n+ int path_or_error = mkdir(pathname, kDefaultDirMode);\n+ if (path_or_error != 0) {\n+ err(1, \"mkdir\");\n+ }\n+ if (chroot(pathname)) {\n+ err(1, \"chroot\");\n+ }\n+}\n+void runDup() {\n+ const auto pathname = \"trace_test.abc\";\n+ static constexpr mode_t kDefaultDirMode = 0755;\n+ int path_or_error = mkdir(pathname, kDefaultDirMode);\n+ if (path_or_error != 0) {\n+ err(1, \"mkdir\");\n+ }\n+ int fd = open(pathname, O_DIRECTORY | O_RDONLY);\n+ if (fd < 0) {\n+ err(1, \"open\");\n+ }\n+ int res = dup(fd);\n+ if (res < 0) {\n+ err(1, \"dup\");\n+ }\n+ rmdir(pathname);\n+}\n+\n+void runDup2() {\n+ const auto pathname = \"trace_test.abc\";\n+ static constexpr mode_t kDefaultDirMode = 0755;\n+ int path_or_error = mkdir(pathname, kDefaultDirMode);\n+ if (path_or_error != 0) {\n+ err(1, \"mkdir\");\n+ }\n+ int oldfd = open(pathname, O_DIRECTORY | O_RDONLY);\n+ if (oldfd < 0) {\n+ err(1, \"open\");\n+ }\n+ int newfd = open(pathname, O_DIRECTORY | O_RDONLY);\n+ if (newfd < 0) {\n+ err(1, \"open\");\n+ }\n+ int res = dup2(oldfd, newfd);\n+ if (res != newfd) {\n+ err(1, \"dup2\");\n+ }\n+ rmdir(pathname);\n+}\n+\n+void runDup3() {\n+ const auto pathname = \"trace_test.abc\";\n+ static constexpr mode_t kDefaultDirMode = 0755;\n+ int path_or_error = mkdir(pathname, kDefaultDirMode);\n+ if (path_or_error != 0) {\n+ err(1, \"mkdir\");\n+ }\n+ int oldfd = open(pathname, O_DIRECTORY | O_RDONLY);\n+ if (oldfd < 0) {\n+ err(1, \"open\");\n+ }\n+ int newfd = open(pathname, O_DIRECTORY | O_RDONLY);\n+ if (newfd < 0) {\n+ err(1, \"open\");\n+ }\n+ int res = dup3(oldfd, newfd, O_CLOEXEC);\n+ if (res != newfd) {\n+ err(1, \"dup3\");\n+ }\n+ rmdir(pathname);\n+}\n+\n+void runPrlimit64() {\n+ struct rlimit setlim;\n+ setlim.rlim_cur = 0;\n+ setlim.rlim_max = RLIM_INFINITY;\n+ int res = prlimit(0, RLIMIT_DATA, &setlim, nullptr);\n+ if (res != 0) {\n+ err(1, \"prlimit64\");\n+ }\n+}\n+\n+void runEventfd() {\n+ int res = eventfd(0, EFD_NONBLOCK);\n+ if (res < 0) {\n+ err(1, \"eventfd\");\n+ }\n+}\n+\n+void runEventfd2() {\n+ int res = Eventdfd2Setup(0, EFD_NONBLOCK);\n+ if (res < 0) {\n+ err(1, \"eventfd2\");\n+ }\n+}\n+\n+void runBind() {\n+ auto path = absl::StrCat(std::string(\"\\0\", 1), \"trace_test.abc\");\n+\n+ struct sockaddr_un addr;\n+ addr.sun_family = AF_UNIX;\n+ strncpy(addr.sun_path, path.c_str(), path.size() + 1);\n+\n+ int fd = socket(AF_UNIX, SOCK_STREAM, 0);\n+ if (fd < 0) {\n+ err(1, \"socket\");\n+ }\n+ auto sock_closer = absl::MakeCleanup([fd] { close(fd); });\n+\n+ if (bind(fd, reinterpret_cast<struct sockaddr*>(&addr), sizeof(addr))) {\n+ err(1, \"bind\");\n+ }\n+}\n+\n+void runAccept() {\n+ auto path = absl::StrCat(std::string(\"\\0\", 1), \"trace_test.abc\");\n+\n+ struct sockaddr_un addr;\n+ addr.sun_family = AF_UNIX;\n+ strncpy(addr.sun_path, path.c_str(), path.size() + 1);\n+\n+ int server = socket(AF_UNIX, SOCK_STREAM, 0);\n+ if (server < 0) {\n+ err(1, \"socket\");\n+ }\n+ auto sock_closer = absl::MakeCleanup([server] { close(server); });\n+\n+ if (bind(server, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) < 0) {\n+ err(1, \"bind\");\n+ }\n+\n+ if (listen(server, 5) < 0) {\n+ err(1, \"listen\");\n+ }\n+\n+ int client = socket(AF_UNIX, SOCK_STREAM, 0);\n+ if (client < 0) {\n+ err(1, \"socket\");\n+ }\n+ auto client_closer = absl::MakeCleanup([client] { close(client); });\n+\n+ if (connect(client, reinterpret_cast<struct sockaddr*>(&addr), sizeof(addr)) <\n+ 0) {\n+ err(1, \"connect\");\n+ }\n+\n+ int fd = RetryEINTR(accept)(server, nullptr, nullptr);\n+ if (fd < 0) {\n+ err(1, \"accept\");\n+ }\n+ close(fd);\n+}\n+\n+void runAccept4() {\n+ auto path = absl::StrCat(std::string(\"\\0\", 1), \"trace_test.abc\");\n+\n+ struct sockaddr_un addr;\n+ addr.sun_family = AF_UNIX;\n+ strncpy(addr.sun_path, path.c_str(), path.size() + 1);\n+\n+ int server = socket(AF_UNIX, SOCK_STREAM, 0);\n+ if (server < 0) {\n+ err(1, \"socket\");\n+ }\n+ auto sock_closer = absl::MakeCleanup([server] { close(server); });\n+\n+ if (bind(server, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) < 0) {\n+ err(1, \"bind\");\n+ }\n+\n+ if (listen(server, 5) < 0) {\n+ err(1, \"listen\");\n+ }\n+\n+ int client = socket(AF_UNIX, SOCK_STREAM, 0);\n+ if (client < 0) {\n+ err(1, \"socket\");\n+ }\n+ auto client_closer = absl::MakeCleanup([client] { close(client); });\n+\n+ if (connect(client, reinterpret_cast<struct sockaddr*>(&addr), sizeof(addr)) <\n+ 0) {\n+ err(1, \"connect\");\n+ }\n+\n+ int fd = RetryEINTR(accept4)(server, nullptr, nullptr, SOCK_CLOEXEC);\n+ if (fd < 0) {\n+ err(1, \"accept4\");\n+ }\n+ close(fd);\n+}\n+\n} // namespace testing\n} // namespace gvisor\n@@ -275,5 +472,16 @@ int main(int argc, char** argv) {\n::gvisor::testing::runSetsid();\n::gvisor::testing::runSetresuid();\n::gvisor::testing::runSetresgid();\n+ ::gvisor::testing::runDup();\n+ ::gvisor::testing::runDup2();\n+ ::gvisor::testing::runDup3();\n+ ::gvisor::testing::runPrlimit64();\n+ ::gvisor::testing::runEventfd();\n+ ::gvisor::testing::runEventfd2();\n+ ::gvisor::testing::runBind();\n+ ::gvisor::testing::runAccept();\n+ ::gvisor::testing::runAccept4();\n+ // Run chroot at the end since it changes the root for all other tests.\n+ ::gvisor::testing::runChroot();\nreturn 0;\n}\n" }, { "change_type": "MODIFY", "old_path": "test/util/eventfd_util.h", "new_path": "test/util/eventfd_util.h", "diff": "#ifndef GVISOR_TEST_UTIL_EVENTFD_UTIL_H_\n#define GVISOR_TEST_UTIL_EVENTFD_UTIL_H_\n-\n+#include <asm/unistd.h>\n#include <sys/eventfd.h>\n#include <cerrno>\n@@ -37,6 +37,11 @@ inline PosixErrorOr<FileDescriptor> NewEventFD(unsigned int initval = 0,\nreturn FileDescriptor(fd);\n}\n+// This is a wrapper for the eventfd2(2) system call.\n+inline int Eventdfd2Setup(unsigned int initval, int flags) {\n+ return syscall(__NR_eventfd2, initval, flags);\n+}\n+\n} // namespace testing\n} // namespace gvisor\n" } ]
Go
Apache License 2.0
google/gvisor
Adding more trace point integration tests for the following syscalls: - chroot - dup - dup2 - dup3 - prlimit64 - eventfd - eventfd2 - bind - accept - accept4 Updates #4805 PiperOrigin-RevId: 489526376
259,975
18.11.2022 16:08:19
28,800
38a0512f13faa7d013d85c9eb85bdd993b08c28a
Fix circular lock in process_vm_(read|write)v
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/sys_process_vm.go", "new_path": "pkg/sentry/syscalls/linux/sys_process_vm.go", "diff": "@@ -23,6 +23,15 @@ import (\n\"gvisor.dev/gvisor/pkg/usermem\"\n)\n+type vmReadWriteOp int\n+\n+const (\n+ localReader vmReadWriteOp = iota\n+ localWriter\n+ remoteReader\n+ remoteWriter\n+)\n+\n// ProcessVMReadv implements process_vm_readv(2).\nfunc ProcessVMReadv(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {\nreturn processVMRW(t, args, false /*isWrite*/)\n@@ -64,20 +73,30 @@ func processVMRW(t *kernel.Task, args arch.SyscallArguments, isWrite bool) (uint\n}\nremoteProcess := remoteThreadGroup.Leader()\n+ isRemote := localProcess == remoteProcess\n+\n// For the write case, we read from the local process and write to the remote process.\nif isWrite {\n- return doProcessVMReadWrite(localProcess, remoteProcess, lvec, rvec, liovcnt, riovcnt)\n+ op := localReader\n+ if isRemote {\n+ op = remoteReader\n+ }\n+ return doProcessVMReadWrite(localProcess, remoteProcess, lvec, rvec, liovcnt, riovcnt, op)\n}\n// For the read case, we read from the remote process and write to the local process.\n- return doProcessVMReadWrite(remoteProcess, localProcess, rvec, lvec, riovcnt, liovcnt)\n+ op := localWriter\n+ if isRemote {\n+ op = remoteWriter\n+ }\n+ return doProcessVMReadWrite(remoteProcess, localProcess, rvec, lvec, riovcnt, liovcnt, op)\n}\n-func doProcessVMReadWrite(rProcess, wProcess *kernel.Task, rAddr, wAddr hostarch.Addr, rIovecCount, wIovecCount int) (uintptr, *kernel.SyscallControl, error) {\n+func doProcessVMReadWrite(rProcess, wProcess *kernel.Task, rAddr, wAddr hostarch.Addr, rIovecCount, wIovecCount int, op vmReadWriteOp) (uintptr, *kernel.SyscallControl, error) {\nrCtx := rProcess.CopyContext(rProcess, usermem.IOOpts{})\nwCtx := wProcess.CopyContext(wProcess, usermem.IOOpts{})\nvar wCount int\n- doProcessVMReadWriteLocked := func() error {\n+ doProcessVMReadWriteMaybeLocked := func() error {\nrIovecs, err := rCtx.CopyInIovecs(rAddr, rIovecCount)\nif err != nil {\nreturn err\n@@ -141,14 +160,21 @@ func doProcessVMReadWrite(rProcess, wProcess *kernel.Task, rAddr, wAddr hostarch\nreturn nil\n}\n- err := rCtx.WithTaskMutexLocked(func() error {\n- if rProcess.ThreadGroup().Leader() != wProcess.ThreadGroup().Leader() {\n- return wCtx.WithTaskMutexLocked(func() error {\n- return doProcessVMReadWriteLocked()\n- })\n+ var err error\n+\n+ switch op {\n+ case remoteReader:\n+ err = rCtx.WithTaskMutexLocked(doProcessVMReadWriteMaybeLocked)\n+ case remoteWriter:\n+ err = wCtx.WithTaskMutexLocked(doProcessVMReadWriteMaybeLocked)\n+\n+ case localReader, localWriter:\n+ // in the case of local reads/writes, we don't have to lock the task mutex, because we are\n+ // running on the top of the task's goroutine already.\n+ err = doProcessVMReadWriteMaybeLocked()\n+ default:\n+ panic(\"unsupported operation passed\")\n}\n- return doProcessVMReadWriteLocked()\n- })\nreturn uintptr(wCount), nil, err\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Fix circular lock in process_vm_(read|write)v PiperOrigin-RevId: 489582978
259,891
21.11.2022 13:54:57
28,800
9ff1c425909ed1de53cbfd2755e98110001a3ed1
gro: actually decref packets Also improves performance since we're not leaking memory and allocating as much.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/gro.go", "new_path": "pkg/tcpip/stack/gro.go", "diff": "@@ -295,6 +295,7 @@ func (gd *groDispatcher) dispatch(pkt PacketBufferPtr, netProto tcpip.NetworkPro\nif flushGROPkt {\n// Flush the existing GRO packet.\nep.HandlePacket(groPkt.pkt)\n+ groPkt.pkt.DecRef()\nbucket.removeOne(groPkt)\ngroPkt = nil\n} else if groPkt != nil {\n@@ -325,6 +326,7 @@ func (gd *groDispatcher) dispatch(pkt PacketBufferPtr, netProto tcpip.NetworkPro\ncase flush && groPkt != nil:\n// A merge occurred and we need to flush groPkt.\nep.HandlePacket(groPkt.pkt)\n+ groPkt.pkt.DecRef()\nbucket.removeOne(groPkt)\ncase flush && groPkt == nil:\n// No merge occurred and the incoming packet needs to be flushed.\n@@ -333,7 +335,9 @@ func (gd *groDispatcher) dispatch(pkt PacketBufferPtr, netProto tcpip.NetworkPro\n// New flow and we don't need to flush. Insert pkt into GRO.\nif bucket.full() {\n// Head is always the oldest packet\n- ep.HandlePacket(bucket.removeOldest())\n+ oldPkt := bucket.removeOldest()\n+ ep.HandlePacket(oldPkt)\n+ oldPkt.DecRef()\n}\nbucket.insert(pkt.IncRef(), ipHdr, tcpHdr, ep)\n}\n@@ -420,6 +424,7 @@ func (gd *groDispatcher) flush() {\nfor groPkt := bucket.packets.Front(); groPkt != nil; groPkt = groPkt.Next() {\nif groPkt.created.Before(oldTime) {\ngroPkt.ep.HandlePacket(groPkt.pkt)\n+ groPkt.pkt.DecRef()\nbucket.removeOne(groPkt)\n} else {\n// Packets are ordered by age, so we can move\n@@ -438,6 +443,7 @@ func (gd *groDispatcher) flushAll() {\nbucket := &gd.buckets[i]\nfor groPkt := bucket.packets.Front(); groPkt != nil; groPkt = groPkt.Next() {\ngroPkt.ep.HandlePacket(groPkt.pkt)\n+ groPkt.pkt.DecRef()\nbucket.removeOne(groPkt)\n}\n}\n" } ]
Go
Apache License 2.0
google/gvisor
gro: actually decref packets Also improves performance since we're not leaking memory and allocating as much. PiperOrigin-RevId: 490064348
259,891
21.11.2022 16:41:18
28,800
346aa6fef27da0689e84f5f4969328a705c5d56c
gro: change global lock to per-bucket This will reduce contention with multiple TCP flows.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/gro.go", "new_path": "pkg/tcpip/stack/gro.go", "diff": "@@ -50,24 +50,33 @@ const (\n// A groBucket holds packets that are undergoing GRO.\ntype groBucket struct {\n+ // mu protects the fields of a bucket.\n+ mu sync.Mutex\n+\n// count is the number of packets in the bucket.\n+ // +checklocks:mu\ncount int\n// packets is the linked list of packets.\n+ // +checklocks:mu\npackets groPacketList\n// packetsPrealloc and allocIdxs are used to preallocate and reuse\n// groPacket structs and avoid allocation.\n+ // +checklocks:mu\npacketsPrealloc [groBucketSize]groPacket\n+ // +checklocks:mu\nallocIdxs [groBucketSize]int\n}\n+// +checklocks:gb.mu\nfunc (gb *groBucket) full() bool {\nreturn gb.count == groBucketSize\n}\n// insert inserts pkt into the bucket.\n+// +checklocks:gb.mu\nfunc (gb *groBucket) insert(pkt PacketBufferPtr, ipHdr header.IPv4, tcpHdr header.TCP, ep NetworkEndpoint) {\ngroPkt := &gb.packetsPrealloc[gb.allocIdxs[gb.count]]\n*groPkt = groPacket{\n@@ -83,6 +92,7 @@ func (gb *groBucket) insert(pkt PacketBufferPtr, ipHdr header.IPv4, tcpHdr heade\n// removeOldest removes the oldest packet from gb and returns the contained\n// PacketBufferPtr. gb must not be empty.\n+// +checklocks:gb.mu\nfunc (gb *groBucket) removeOldest() PacketBufferPtr {\npkt := gb.packets.Front()\ngb.packets.Remove(pkt)\n@@ -94,6 +104,7 @@ func (gb *groBucket) removeOldest() PacketBufferPtr {\n}\n// removeOne removes a packet from gb. It also resets pkt to its zero value.\n+// +checklocks:gb.mu\nfunc (gb *groBucket) removeOne(pkt *groPacket) {\ngb.packets.Remove(pkt)\ngb.count--\n@@ -101,6 +112,60 @@ func (gb *groBucket) removeOne(pkt *groPacket) {\n*pkt = groPacket{}\n}\n+// findGROPacket returns the groPkt that matches ipHdr and tcpHdr, or nil if\n+// none exists. It also returns whether the groPkt should be flushed based on\n+// differences between the two headers.\n+// +checklocks:gb.mu\n+func (gb *groBucket) findGROPacket(ipHdr header.IPv4, tcpHdr header.TCP) (*groPacket, bool) {\n+ for groPkt := gb.packets.Front(); groPkt != nil; groPkt = groPkt.Next() {\n+ // Do the addresses match?\n+ if ipHdr.SourceAddress() != groPkt.ipHdr.SourceAddress() || ipHdr.DestinationAddress() != groPkt.ipHdr.DestinationAddress() {\n+ continue\n+ }\n+\n+ // Do the ports match?\n+ if tcpHdr.SourcePort() != groPkt.tcpHdr.SourcePort() || tcpHdr.DestinationPort() != groPkt.tcpHdr.DestinationPort() {\n+ continue\n+ }\n+\n+ // We've found a packet of the same flow.\n+\n+ // IP checks.\n+ TOS, _ := ipHdr.TOS()\n+ groTOS, _ := groPkt.ipHdr.TOS()\n+ if ipHdr.TTL() != groPkt.ipHdr.TTL() || TOS != groTOS {\n+ return groPkt, true\n+ }\n+\n+ // TCP checks.\n+ flags := tcpHdr.Flags()\n+ groPktFlags := groPkt.tcpHdr.Flags()\n+ dataOff := tcpHdr.DataOffset()\n+ if flags&header.TCPFlagCwr != 0 || // Is congestion control occurring?\n+ (flags^groPktFlags)&^(header.TCPFlagCwr|header.TCPFlagFin|header.TCPFlagPsh) != 0 || // Do the flags differ besides CRW, FIN, and PSH?\n+ tcpHdr.AckNumber() != groPkt.tcpHdr.AckNumber() || // Do the ACKs match?\n+ dataOff != groPkt.tcpHdr.DataOffset() || // Are the TCP headers the same length?\n+ groPkt.tcpHdr.SequenceNumber()+uint32(groPkt.payloadSize()) != tcpHdr.SequenceNumber() { // Does the incoming packet match the expected sequence number?\n+ return groPkt, true\n+ }\n+ // The options, including timestamps, must be identical.\n+ for i := header.TCPMinimumSize; i < int(dataOff); i++ {\n+ if tcpHdr[i] != groPkt.tcpHdr[i] {\n+ return groPkt, true\n+ }\n+ }\n+\n+ // There's an upper limit on coalesced packet size.\n+ if int(ipHdr.TotalLength())-header.IPv4MinimumSize-int(dataOff)+groPkt.pkt.Data().Size() >= groMaxPacketSize {\n+ return groPkt, true\n+ }\n+\n+ return groPkt, false\n+ }\n+\n+ return nil, false\n+}\n+\n// A groPacket is packet undergoing GRO. It may be several packets coalesced\n// together.\ntype groPacket struct {\n@@ -142,26 +207,22 @@ type groDispatcher struct {\n// stop instructs the GRO dispatcher goroutine to stop.\nstop chan struct{}\n- // mu protects the buckets.\n- // TODO(b/256037250): This should be per-bucket.\n- mu sync.Mutex\n- // +checklocks:mu\nbuckets [groNBuckets]groBucket\n}\nfunc (gd *groDispatcher) init(interval time.Duration) {\n- gd.mu.Lock()\n- defer gd.mu.Unlock()\n-\ngd.intervalNS.Store(interval.Nanoseconds())\ngd.newInterval = make(chan struct{}, 1)\ngd.stop = make(chan struct{})\nfor i := range gd.buckets {\n- for j := range gd.buckets[i].packetsPrealloc {\n- gd.buckets[i].allocIdxs[j] = j\n- gd.buckets[i].packetsPrealloc[j].idx = j\n+ bucket := &gd.buckets[i]\n+ bucket.mu.Lock()\n+ for j := range bucket.packetsPrealloc {\n+ bucket.allocIdxs[j] = j\n+ bucket.packetsPrealloc[j].idx = j\n}\n+ bucket.mu.Unlock()\n}\ngd.start(interval)\n@@ -284,19 +345,21 @@ func (gd *groDispatcher) dispatch(pkt PacketBufferPtr, netProto tcpip.NetworkPro\n}\n// Now we can get the bucket for the packet.\n- gd.mu.Lock()\n- defer gd.mu.Unlock()\n-\nbucket := &gd.buckets[gd.bucketForPacket(ipHdr, tcpHdr)&groNBucketsMask]\n- groPkt, flushGROPkt := findGROPacket(bucket, ipHdr, tcpHdr)\n+ bucket.mu.Lock()\n+ groPkt, flushGROPkt := bucket.findGROPacket(ipHdr, tcpHdr)\n// Flush groPkt or merge the packets.\nflags := tcpHdr.Flags()\nif flushGROPkt {\n- // Flush the existing GRO packet.\n- ep.HandlePacket(groPkt.pkt)\n- groPkt.pkt.DecRef()\n+ // Flush the existing GRO packet. Don't hold bucket.mu while\n+ // processing the packet.\n+ pkt := groPkt.pkt\nbucket.removeOne(groPkt)\n+ bucket.mu.Unlock()\n+ ep.HandlePacket(pkt)\n+ pkt.DecRef()\n+ bucket.mu.Lock()\ngroPkt = nil\n} else if groPkt != nil {\n// Merge pkt in to GRO packet.\n@@ -325,75 +388,32 @@ func (gd *groDispatcher) dispatch(pkt PacketBufferPtr, netProto tcpip.NetworkPro\nswitch {\ncase flush && groPkt != nil:\n// A merge occurred and we need to flush groPkt.\n- ep.HandlePacket(groPkt.pkt)\n- groPkt.pkt.DecRef()\n+ pkt := groPkt.pkt\nbucket.removeOne(groPkt)\n+ bucket.mu.Unlock()\n+ ep.HandlePacket(pkt)\n+ pkt.DecRef()\ncase flush && groPkt == nil:\n// No merge occurred and the incoming packet needs to be flushed.\n+ bucket.mu.Unlock()\nep.HandlePacket(pkt)\ncase !flush && groPkt == nil:\n// New flow and we don't need to flush. Insert pkt into GRO.\nif bucket.full() {\n// Head is always the oldest packet\n- oldPkt := bucket.removeOldest()\n- ep.HandlePacket(oldPkt)\n- oldPkt.DecRef()\n- }\n+ toFlush := bucket.removeOldest()\nbucket.insert(pkt.IncRef(), ipHdr, tcpHdr, ep)\n+ bucket.mu.Unlock()\n+ ep.HandlePacket(toFlush)\n+ toFlush.DecRef()\n+ } else {\n+ bucket.insert(pkt.IncRef(), ipHdr, tcpHdr, ep)\n+ bucket.mu.Unlock()\n}\n+ default:\n+ // A merge occurred and we don't need to flush anything.\n+ bucket.mu.Unlock()\n}\n-\n-// findGROPacket returns the groPkt that matches ipHdr and tcpHdr, or nil if\n-// none exists. It also returns whether the groPkt should be flushed based on\n-// differences between the two headers.\n-func findGROPacket(bucket *groBucket, ipHdr header.IPv4, tcpHdr header.TCP) (*groPacket, bool) {\n- for groPkt := bucket.packets.Front(); groPkt != nil; groPkt = groPkt.Next() {\n- // Do the addresses match?\n- if ipHdr.SourceAddress() != groPkt.ipHdr.SourceAddress() || ipHdr.DestinationAddress() != groPkt.ipHdr.DestinationAddress() {\n- continue\n- }\n-\n- // Do the ports match?\n- if tcpHdr.SourcePort() != groPkt.tcpHdr.SourcePort() || tcpHdr.DestinationPort() != groPkt.tcpHdr.DestinationPort() {\n- continue\n- }\n-\n- // We've found a packet of the same flow.\n-\n- // IP checks.\n- TOS, _ := ipHdr.TOS()\n- groTOS, _ := groPkt.ipHdr.TOS()\n- if ipHdr.TTL() != groPkt.ipHdr.TTL() || TOS != groTOS {\n- return groPkt, true\n- }\n-\n- // TCP checks.\n- flags := tcpHdr.Flags()\n- groPktFlags := groPkt.tcpHdr.Flags()\n- dataOff := tcpHdr.DataOffset()\n- if flags&header.TCPFlagCwr != 0 || // Is congestion control occurring?\n- (flags^groPktFlags)&^(header.TCPFlagCwr|header.TCPFlagFin|header.TCPFlagPsh) != 0 || // Do the flags differ besides CRW, FIN, and PSH?\n- tcpHdr.AckNumber() != groPkt.tcpHdr.AckNumber() || // Do the ACKs match?\n- dataOff != groPkt.tcpHdr.DataOffset() || // Are the TCP headers the same length?\n- groPkt.tcpHdr.SequenceNumber()+uint32(groPkt.payloadSize()) != tcpHdr.SequenceNumber() { // Does the incoming packet match the expected sequence number?\n- return groPkt, true\n- }\n- // The options, including timestamps, must be identical.\n- for i := header.TCPMinimumSize; i < int(dataOff); i++ {\n- if tcpHdr[i] != groPkt.tcpHdr[i] {\n- return groPkt, true\n- }\n- }\n-\n- // There's an upper limit on coalesced packet size.\n- if int(ipHdr.TotalLength())-header.IPv4MinimumSize-int(dataOff)+groPkt.pkt.Data().Size() >= groMaxPacketSize {\n- return groPkt, true\n- }\n-\n- return groPkt, false\n- }\n-\n- return nil, false\n}\nfunc (gd *groDispatcher) bucketForPacket(ipHdr header.IPv4, tcpHdr header.TCP) int {\n@@ -414,17 +434,27 @@ func (gd *groDispatcher) bucketForPacket(ipHdr header.IPv4, tcpHdr header.TCP) i\n// flush sends any packets older than interval up the stack.\nfunc (gd *groDispatcher) flush() {\ninterval := gd.intervalNS.Load()\n- oldTime := time.Now().Add(-time.Duration(interval) * time.Nanosecond)\n+ old := time.Now().Add(-time.Duration(interval) * time.Nanosecond)\n+ gd.flushSince(old)\n+}\n- gd.mu.Lock()\n- defer gd.mu.Unlock()\n+func (gd *groDispatcher) flushSince(old time.Time) {\n+ type pair struct {\n+ pkt PacketBufferPtr\n+ ep NetworkEndpoint\n+ }\nfor i := range gd.buckets {\n+ // Put packets in a slice so we don't have to hold bucket.mu\n+ // when we call HandlePacket.\n+ var pairsBacking [groNBuckets]pair\n+ pairs := pairsBacking[:0]\n+\nbucket := &gd.buckets[i]\n+ bucket.mu.Lock()\nfor groPkt := bucket.packets.Front(); groPkt != nil; groPkt = groPkt.Next() {\n- if groPkt.created.Before(oldTime) {\n- groPkt.ep.HandlePacket(groPkt.pkt)\n- groPkt.pkt.DecRef()\n+ if groPkt.created.Before(old) {\n+ pairs = append(pairs, pair{groPkt.pkt, groPkt.ep})\nbucket.removeOne(groPkt)\n} else {\n// Packets are ordered by age, so we can move\n@@ -432,51 +462,45 @@ func (gd *groDispatcher) flush() {\nbreak\n}\n}\n- }\n-}\n+ bucket.mu.Unlock()\n-func (gd *groDispatcher) flushAll() {\n- gd.mu.Lock()\n- defer gd.mu.Unlock()\n-\n- for i := range gd.buckets {\n- bucket := &gd.buckets[i]\n- for groPkt := bucket.packets.Front(); groPkt != nil; groPkt = groPkt.Next() {\n- groPkt.ep.HandlePacket(groPkt.pkt)\n- groPkt.pkt.DecRef()\n- bucket.removeOne(groPkt)\n+ for _, pair := range pairs {\n+ pair.ep.HandlePacket(pair.pkt)\n+ pair.pkt.DecRef()\n+ }\n}\n}\n+func (gd *groDispatcher) flushAll() {\n+ gd.flushSince(time.Now())\n}\n// close stops the GRO goroutine and releases any held packets.\nfunc (gd *groDispatcher) close() {\ngd.stop <- struct{}{}\n- gd.mu.Lock()\n- defer gd.mu.Unlock()\n-\nfor i := range gd.buckets {\nbucket := &gd.buckets[i]\n+ bucket.mu.Lock()\nfor groPkt := bucket.packets.Front(); groPkt != nil; groPkt = groPkt.Next() {\ngroPkt.pkt.DecRef()\n}\n+ bucket.mu.Unlock()\n}\n}\n// String implements fmt.Stringer.\nfunc (gd *groDispatcher) String() string {\n- gd.mu.Lock()\n- defer gd.mu.Unlock()\n-\nret := \"GRO state: \\n\"\n- for i, bucket := range gd.buckets {\n+ for i := range gd.buckets {\n+ bucket := &gd.buckets[i]\n+ bucket.mu.Lock()\nret += fmt.Sprintf(\"bucket %d: %d packets: \", i, bucket.count)\nfor groPkt := bucket.packets.Front(); groPkt != nil; groPkt = groPkt.Next() {\nret += fmt.Sprintf(\"%s (%d), \", groPkt.created, groPkt.pkt.Data().Size())\n}\nret += \"\\n\"\n+ bucket.mu.Unlock()\n}\nreturn ret\n}\n" } ]
Go
Apache License 2.0
google/gvisor
gro: change global lock to per-bucket This will reduce contention with multiple TCP flows. PiperOrigin-RevId: 490101814