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,881
01.04.2020 09:58:51
25,200
db7917556a7e4bd2cd6d183c68f04a4787dec493
Fix 386 build tags The build tag for 32-bit x86 is 386, not i386. Updates
[ { "change_type": "MODIFY", "old_path": "pkg/cpuid/cpuid_parse_x86_test.go", "new_path": "pkg/cpuid/cpuid_parse_x86_test.go", "diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-// +build i386 amd64\n+// +build 386 amd64\npackage cpuid\n" }, { "change_type": "MODIFY", "old_path": "pkg/cpuid/cpuid_x86.go", "new_path": "pkg/cpuid/cpuid_x86.go", "diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-// +build i386 amd64\n+// +build 386 amd64\npackage cpuid\n" }, { "change_type": "MODIFY", "old_path": "pkg/cpuid/cpuid_x86_test.go", "new_path": "pkg/cpuid/cpuid_x86_test.go", "diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-// +build i386 amd64\n+// +build 386 amd64\npackage cpuid\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/arch/arch_state_x86.go", "new_path": "pkg/sentry/arch/arch_state_x86.go", "diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-// +build amd64 i386\n+// +build amd64 386\npackage arch\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/arch/arch_x86.go", "new_path": "pkg/sentry/arch/arch_x86.go", "diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-// +build amd64 i386\n+// +build amd64 386\npackage arch\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/arch/arch_x86_impl.go", "new_path": "pkg/sentry/arch/arch_x86_impl.go", "diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-// +build amd64 i386\n+// +build amd64 386\npackage arch\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/arch/signal_stack.go", "new_path": "pkg/sentry/arch/signal_stack.go", "diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-// +build i386 amd64 arm64\n+// +build 386 amd64 arm64\npackage arch\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/ring0/pagetables/pagetables_x86.go", "new_path": "pkg/sentry/platform/ring0/pagetables/pagetables_x86.go", "diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-// +build i386 amd64\n+// +build 386 amd64\npackage pagetables\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/ring0/x86.go", "new_path": "pkg/sentry/platform/ring0/x86.go", "diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-// +build i386 amd64\n+// +build 386 amd64\npackage ring0\n" }, { "change_type": "MODIFY", "old_path": "pkg/usermem/usermem_x86.go", "new_path": "pkg/usermem/usermem_x86.go", "diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-// +build amd64 i386\n+// +build amd64 386\npackage usermem\n" } ]
Go
Apache License 2.0
google/gvisor
Fix 386 build tags The build tag for 32-bit x86 is 386, not i386. Updates #2298 PiperOrigin-RevId: 304206373
259,972
01.04.2020 11:25:43
25,200
38f4501c995d7d915bcd168d58655e67e2b34566
Add context.Context argument to XxxWithErrno functions This allows control over the gRPC timeouts as needed.
[ { "change_type": "MODIFY", "old_path": "test/packetimpact/testbench/dut.go", "new_path": "test/packetimpact/testbench/dut.go", "diff": "@@ -143,13 +143,12 @@ func (dut *DUT) protoToSockaddr(sa *pb.Sockaddr) unix.Sockaddr {\n}\n// BindWithErrno calls bind on the DUT.\n-func (dut *DUT) BindWithErrno(fd int32, sa unix.Sockaddr) (int32, error) {\n+func (dut *DUT) BindWithErrno(ctx context.Context, fd int32, sa unix.Sockaddr) (int32, error) {\ndut.t.Helper()\nreq := pb.BindRequest{\nSockfd: fd,\nAddr: dut.sockaddrToProto(sa),\n}\n- ctx := context.Background()\nresp, err := dut.posixServer.Bind(ctx, &req)\nif err != nil {\ndut.t.Fatalf(\"failed to call Bind: %s\", err)\n@@ -158,22 +157,24 @@ func (dut *DUT) BindWithErrno(fd int32, sa unix.Sockaddr) (int32, error) {\n}\n// Bind calls bind on the DUT and causes a fatal test failure if it doesn't\n-// succeed.\n+// succeed. If more control over the timeout or error handling is\n+// needed, use BindWithErrno.\nfunc (dut *DUT) Bind(fd int32, sa unix.Sockaddr) {\ndut.t.Helper()\n- ret, err := dut.BindWithErrno(fd, sa)\n+ ctx, cancel := context.WithTimeout(context.Background(), *rpcTimeout)\n+ defer cancel()\n+ ret, err := dut.BindWithErrno(ctx, fd, sa)\nif ret != 0 {\ndut.t.Fatalf(\"failed to bind socket: %s\", err)\n}\n}\n// GetSockNameWithErrno calls getsockname on the DUT.\n-func (dut *DUT) GetSockNameWithErrno(sockfd int32) (int32, unix.Sockaddr, error) {\n+func (dut *DUT) GetSockNameWithErrno(ctx context.Context, sockfd int32) (int32, unix.Sockaddr, error) {\ndut.t.Helper()\nreq := pb.GetSockNameRequest{\nSockfd: sockfd,\n}\n- ctx := context.Background()\nresp, err := dut.posixServer.GetSockName(ctx, &req)\nif err != nil {\ndut.t.Fatalf(\"failed to call Bind: %s\", err)\n@@ -182,10 +183,13 @@ func (dut *DUT) GetSockNameWithErrno(sockfd int32) (int32, unix.Sockaddr, error)\n}\n// GetSockName calls getsockname on the DUT and causes a fatal test failure if\n-// it doens't succeed.\n+// it doesn't succeed. If more control over the timeout or error handling is\n+// needed, use GetSockNameWithErrno.\nfunc (dut *DUT) GetSockName(sockfd int32) unix.Sockaddr {\ndut.t.Helper()\n- ret, sa, err := dut.GetSockNameWithErrno(sockfd)\n+ ctx, cancel := context.WithTimeout(context.Background(), *rpcTimeout)\n+ defer cancel()\n+ ret, sa, err := dut.GetSockNameWithErrno(ctx, sockfd)\nif ret != 0 {\ndut.t.Fatalf(\"failed to getsockname: %s\", err)\n}\n@@ -193,14 +197,12 @@ func (dut *DUT) GetSockName(sockfd int32) unix.Sockaddr {\n}\n// ListenWithErrno calls listen on the DUT.\n-func (dut *DUT) ListenWithErrno(sockfd, backlog int32) (int32, error) {\n+func (dut *DUT) ListenWithErrno(ctx context.Context, sockfd, backlog int32) (int32, error) {\ndut.t.Helper()\nreq := pb.ListenRequest{\nSockfd: sockfd,\nBacklog: backlog,\n}\n- ctx, cancel := context.WithTimeout(context.Background(), *rpcTimeout)\n- defer cancel()\nresp, err := dut.posixServer.Listen(ctx, &req)\nif err != nil {\ndut.t.Fatalf(\"failed to call Listen: %s\", err)\n@@ -209,23 +211,24 @@ func (dut *DUT) ListenWithErrno(sockfd, backlog int32) (int32, error) {\n}\n// Listen calls listen on the DUT and causes a fatal test failure if it doesn't\n-// succeed.\n+// succeed. If more control over the timeout or error handling is needed, use\n+// ListenWithErrno.\nfunc (dut *DUT) Listen(sockfd, backlog int32) {\ndut.t.Helper()\n- ret, err := dut.ListenWithErrno(sockfd, backlog)\n+ ctx, cancel := context.WithTimeout(context.Background(), *rpcTimeout)\n+ defer cancel()\n+ ret, err := dut.ListenWithErrno(ctx, sockfd, backlog)\nif ret != 0 {\ndut.t.Fatalf(\"failed to listen: %s\", err)\n}\n}\n// AcceptWithErrno calls accept on the DUT.\n-func (dut *DUT) AcceptWithErrno(sockfd int32) (int32, unix.Sockaddr, error) {\n+func (dut *DUT) AcceptWithErrno(ctx context.Context, sockfd int32) (int32, unix.Sockaddr, error) {\ndut.t.Helper()\nreq := pb.AcceptRequest{\nSockfd: sockfd,\n}\n- ctx, cancel := context.WithTimeout(context.Background(), *rpcTimeout)\n- defer cancel()\nresp, err := dut.posixServer.Accept(ctx, &req)\nif err != nil {\ndut.t.Fatalf(\"failed to call Accept: %s\", err)\n@@ -234,18 +237,23 @@ func (dut *DUT) AcceptWithErrno(sockfd int32) (int32, unix.Sockaddr, error) {\n}\n// Accept calls accept on the DUT and causes a fatal test failure if it doesn't\n-// succeed.\n+// succeed. If more control over the timeout or error handling is needed, use\n+// AcceptWithErrno.\nfunc (dut *DUT) Accept(sockfd int32) (int32, unix.Sockaddr) {\ndut.t.Helper()\n- fd, sa, err := dut.AcceptWithErrno(sockfd)\n+ ctx, cancel := context.WithTimeout(context.Background(), *rpcTimeout)\n+ defer cancel()\n+ fd, sa, err := dut.AcceptWithErrno(ctx, sockfd)\nif fd < 0 {\ndut.t.Fatalf(\"failed to accept: %s\", err)\n}\nreturn fd, sa\n}\n-// SetSockOptWithErrno calls setsockopt on the DUT.\n-func (dut *DUT) SetSockOptWithErrno(sockfd, level, optname int32, optval []byte) (int32, error) {\n+// SetSockOptWithErrno calls setsockopt on the DUT. Because endianess and the\n+// width of values might differ between the testbench and DUT architectures,\n+// prefer to use a more specific SetSockOptXxxWithErrno function.\n+func (dut *DUT) SetSockOptWithErrno(ctx context.Context, sockfd, level, optname int32, optval []byte) (int32, error) {\ndut.t.Helper()\nreq := pb.SetSockOptRequest{\nSockfd: sockfd,\n@@ -253,8 +261,6 @@ func (dut *DUT) SetSockOptWithErrno(sockfd, level, optname int32, optval []byte)\nOptname: optname,\nOptval: optval,\n}\n- ctx, cancel := context.WithTimeout(context.Background(), *rpcTimeout)\n- defer cancel()\nresp, err := dut.posixServer.SetSockOpt(ctx, &req)\nif err != nil {\ndut.t.Fatalf(\"failed to call SetSockOpt: %s\", err)\n@@ -263,10 +269,15 @@ func (dut *DUT) SetSockOptWithErrno(sockfd, level, optname int32, optval []byte)\n}\n// SetSockOpt calls setsockopt on the DUT and causes a fatal test failure if it\n-// doesn't succeed.\n+// doesn't succeed. If more control over the timeout or error handling is\n+// needed, use SetSockOptWithErrno. Because endianess and the width of values\n+// might differ between the testbench and DUT architectures, prefer to use a\n+// more specific SetSockOptXxx function.\nfunc (dut *DUT) SetSockOpt(sockfd, level, optname int32, optval []byte) {\ndut.t.Helper()\n- ret, err := dut.SetSockOptWithErrno(sockfd, level, optname, optval)\n+ ctx, cancel := context.WithTimeout(context.Background(), *rpcTimeout)\n+ defer cancel()\n+ ret, err := dut.SetSockOptWithErrno(ctx, sockfd, level, optname, optval)\nif ret != 0 {\ndut.t.Fatalf(\"failed to SetSockOpt: %s\", err)\n}\n@@ -274,7 +285,7 @@ func (dut *DUT) SetSockOpt(sockfd, level, optname int32, optval []byte) {\n// SetSockOptTimevalWithErrno calls setsockopt with the timeval converted to\n// bytes.\n-func (dut *DUT) SetSockOptTimevalWithErrno(sockfd, level, optname int32, tv *unix.Timeval) (int32, error) {\n+func (dut *DUT) SetSockOptTimevalWithErrno(ctx context.Context, sockfd, level, optname int32, tv *unix.Timeval) (int32, error) {\ndut.t.Helper()\ntimeval := pb.Timeval{\nSeconds: int64(tv.Sec),\n@@ -286,8 +297,6 @@ func (dut *DUT) SetSockOptTimevalWithErrno(sockfd, level, optname int32, tv *uni\nOptname: optname,\nTimeval: &timeval,\n}\n- ctx, cancel := context.WithTimeout(context.Background(), *rpcTimeout)\n- defer cancel()\nresp, err := dut.posixServer.SetSockOptTimeval(ctx, &req)\nif err != nil {\ndut.t.Fatalf(\"failed to call SetSockOptTimeval: %s\", err)\n@@ -296,10 +305,13 @@ func (dut *DUT) SetSockOptTimevalWithErrno(sockfd, level, optname int32, tv *uni\n}\n// SetSockOptTimeval calls setsockopt on the DUT and causes a fatal test failure\n-// if it doesn't succeed.\n+// if it doesn't succeed. If more control over the timeout or error handling is\n+// needed, use SetSockOptTimevalWithErrno.\nfunc (dut *DUT) SetSockOptTimeval(sockfd, level, optname int32, tv *unix.Timeval) {\ndut.t.Helper()\n- ret, err := dut.SetSockOptTimevalWithErrno(sockfd, level, optname, tv)\n+ ctx, cancel := context.WithTimeout(context.Background(), *rpcTimeout)\n+ defer cancel()\n+ ret, err := dut.SetSockOptTimevalWithErrno(ctx, sockfd, level, optname, tv)\nif ret != 0 {\ndut.t.Fatalf(\"failed to SetSockOptTimeval: %s\", err)\n}\n@@ -335,13 +347,11 @@ func (dut *DUT) Recv(sockfd, len, flags int32) []byte {\n}\n// CloseWithErrno calls close on the DUT.\n-func (dut *DUT) CloseWithErrno(fd int32) (int32, error) {\n+func (dut *DUT) CloseWithErrno(ctx context.Context, fd int32) (int32, error) {\ndut.t.Helper()\nreq := pb.CloseRequest{\nFd: fd,\n}\n- ctx, cancel := context.WithTimeout(context.Background(), *rpcTimeout)\n- defer cancel()\nresp, err := dut.posixServer.Close(ctx, &req)\nif err != nil {\ndut.t.Fatalf(\"failed to call Close: %s\", err)\n@@ -350,10 +360,13 @@ func (dut *DUT) CloseWithErrno(fd int32) (int32, error) {\n}\n// Close calls close on the DUT and causes a fatal test failure if it doesn't\n-// succeed.\n+// succeed. If more control over the timeout or error handling is needed, use\n+// CloseWithErrno.\nfunc (dut *DUT) Close(fd int32) {\ndut.t.Helper()\n- ret, err := dut.CloseWithErrno(fd)\n+ ctx, cancel := context.WithTimeout(context.Background(), *rpcTimeout)\n+ defer cancel()\n+ ret, err := dut.CloseWithErrno(ctx, fd)\nif ret != 0 {\ndut.t.Fatalf(\"failed to close: %s\", err)\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Add context.Context argument to XxxWithErrno functions This allows control over the gRPC timeouts as needed. PiperOrigin-RevId: 304225713
259,975
01.04.2020 17:39:12
25,200
37025990d6ed1f1160937c640855070d9a559cb0
Add "/snap/bin" to PATH. "gcloud" may be installed as a snap, under "/snap/bin". Make sure this is in our PATH so that we can use gcloud.
[ { "change_type": "MODIFY", "old_path": "scripts/benchmark.sh", "new_path": "scripts/benchmark.sh", "diff": "source $(dirname $0)/common.sh\n+# gcloud may be installed as a \"snap\". If it is, include it in PATH.\n+declare -r snap=\"/snap/bin\"\n+if [[ -d \"-d ${snap}\" ]]; then\n+ export PATH=\"${PATH}:${snap}\"\n+fi\n+\n+# Make sure we can call gcloud and exit if not.\n+which gcloud\n+\n# Exporting for subprocesses as GCP APIs and tools check this environmental\n# variable for authentication.\nexport GOOGLE_APPLICATION_CREDENTIALS=\"${KOKORO_KEYSTORE_DIR}/${GCLOUD_CREDENTIALS}\"\n-which gcloud\n-\ngcloud auth activate-service-account \\\n--key-file \"${GOOGLE_APPLICATION_CREDENTIALS}\"\n" } ]
Go
Apache License 2.0
google/gvisor
Add "/snap/bin" to PATH. "gcloud" may be installed as a snap, under "/snap/bin". Make sure this is in our PATH so that we can use gcloud. PiperOrigin-RevId: 304297180
259,962
02.04.2020 10:39:56
25,200
c6d5742c21c19f9cf8b964b49b8df935c1303417
Fix flaky TCPLinger2TimeoutAfterClose test. The test is flaky in cooperative S/R mode because TCP timers are not restored across a S/R. This can cause the TCPLinger2 timer to not fire. This change disables S/R before setting the TCP_LINGER2 timeout.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_inet_loopback.cc", "new_path": "test/syscalls/linux/socket_inet_loopback.cc", "diff": "@@ -605,6 +605,10 @@ TEST_P(SocketInetLoopbackTest, TCPLinger2TimeoutAfterClose_NoRandomSave) {\n&conn_addrlen),\nSyscallSucceeds());\n+ // Disable cooperative saves after this point as TCP timers are not restored\n+ // across a S/R.\n+ {\n+ DisableSave ds;\nconstexpr int kTCPLingerTimeout = 5;\nEXPECT_THAT(setsockopt(conn_fd.get(), IPPROTO_TCP, TCP_LINGER2,\n&kTCPLingerTimeout, sizeof(kTCPLingerTimeout)),\n@@ -615,6 +619,10 @@ TEST_P(SocketInetLoopbackTest, TCPLinger2TimeoutAfterClose_NoRandomSave) {\nabsl::SleepFor(absl::Seconds(kTCPLingerTimeout + 1));\n+ // ds going out of scope will Re-enable S/R's since at this point the timer\n+ // must have fired and cleaned up the endpoint.\n+ }\n+\n// Now bind and connect a new socket and verify that we can immediately\n// rebind the address bound by the conn_fd as it never entered TIME_WAIT.\nconst FileDescriptor conn_fd2 = ASSERT_NO_ERRNO_AND_VALUE(\n" } ]
Go
Apache License 2.0
google/gvisor
Fix flaky TCPLinger2TimeoutAfterClose test. The test is flaky in cooperative S/R mode because TCP timers are not restored across a S/R. This can cause the TCPLinger2 timer to not fire. This change disables S/R before setting the TCP_LINGER2 timeout. PiperOrigin-RevId: 304430536
259,975
02.04.2020 11:24:04
25,200
035836193e6d9e1fc9cce6a0161cb3907fbc2ef5
Fix typo in benchmarks.sh
[ { "change_type": "MODIFY", "old_path": "scripts/benchmark.sh", "new_path": "scripts/benchmark.sh", "diff": "@@ -18,11 +18,11 @@ source $(dirname $0)/common.sh\n# gcloud may be installed as a \"snap\". If it is, include it in PATH.\ndeclare -r snap=\"/snap/bin\"\n-if [[ -d \"-d ${snap}\" ]]; then\n+if [[ -d \"${snap}\" ]]; then\nexport PATH=\"${PATH}:${snap}\"\nfi\n-# Make sure we can call gcloud and exit if not.\n+# Make sure we can find gcloud and exit if not.\nwhich gcloud\n# Exporting for subprocesses as GCP APIs and tools check this environmental\n" } ]
Go
Apache License 2.0
google/gvisor
Fix typo in benchmarks.sh PiperOrigin-RevId: 304440599
259,885
02.04.2020 11:55:55
25,200
30388ff5919df33e7184719dfc6c0d9cb110b2e2
Rename files in //pkg/sync to better reflect what they contain.
[ { "change_type": "MODIFY", "old_path": "pkg/sync/BUILD", "new_path": "pkg/sync/BUILD", "diff": "@@ -31,13 +31,13 @@ go_library(\nname = \"sync\",\nsrcs = [\n\"aliases.go\",\n- \"downgradable_rwmutex_unsafe.go\",\n\"memmove_unsafe.go\",\n+ \"mutex_unsafe.go\",\n\"norace_unsafe.go\",\n\"race_unsafe.go\",\n+ \"rwmutex_unsafe.go\",\n\"seqcount.go\",\n- \"syncutil.go\",\n- \"tmutex_unsafe.go\",\n+ \"sync.go\",\n],\n)\n@@ -45,9 +45,9 @@ go_test(\nname = \"sync_test\",\nsize = \"small\",\nsrcs = [\n- \"downgradable_rwmutex_test.go\",\n+ \"mutex_test.go\",\n+ \"rwmutex_test.go\",\n\"seqcount_test.go\",\n- \"tmutex_test.go\",\n],\nlibrary = \":sync\",\n)\n" }, { "change_type": "RENAME", "old_path": "pkg/sync/tmutex_test.go", "new_path": "pkg/sync/mutex_test.go", "diff": "" }, { "change_type": "RENAME", "old_path": "pkg/sync/tmutex_unsafe.go", "new_path": "pkg/sync/mutex_unsafe.go", "diff": "" }, { "change_type": "RENAME", "old_path": "pkg/sync/downgradable_rwmutex_test.go", "new_path": "pkg/sync/rwmutex_test.go", "diff": "" }, { "change_type": "RENAME", "old_path": "pkg/sync/downgradable_rwmutex_unsafe.go", "new_path": "pkg/sync/rwmutex_unsafe.go", "diff": "" }, { "change_type": "RENAME", "old_path": "pkg/sync/syncutil.go", "new_path": "pkg/sync/sync.go", "diff": "" } ]
Go
Apache License 2.0
google/gvisor
Rename files in //pkg/sync to better reflect what they contain. PiperOrigin-RevId: 304447031
260,004
02.04.2020 15:58:38
25,200
ecc3d01d181a6ae6d3cc72531542d9ea5fe3e376
Increment NDP message RX stats before validation Tests: ipv6_test.TestHopLimitValidation ipv6_test.TestRouterAdvertValidation
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/icmp.go", "new_path": "pkg/tcpip/network/ipv6/icmp.go", "diff": "@@ -86,25 +86,12 @@ func (e *endpoint) handleICMP(r *stack.Route, netHeader buffer.View, pkt stack.P\nreturn\n}\n+ isNDPValid := func() bool {\n// As per RFC 4861 sections 4.1 - 4.5, 6.1.1, 6.1.2, 7.1.1, 7.1.2 and\n// 8.1, nodes MUST silently drop NDP packets where the Hop Limit field\n// in the IPv6 header is not set to 255, or the ICMPv6 Code field is not\n// set to 0.\n- switch h.Type() {\n- case header.ICMPv6NeighborSolicit,\n- header.ICMPv6NeighborAdvert,\n- header.ICMPv6RouterSolicit,\n- header.ICMPv6RouterAdvert,\n- header.ICMPv6RedirectMsg:\n- if iph.HopLimit() != header.NDPHopLimit {\n- received.Invalid.Increment()\n- return\n- }\n-\n- if h.Code() != 0 {\n- received.Invalid.Increment()\n- return\n- }\n+ return iph.HopLimit() == header.NDPHopLimit && h.Code() == 0\n}\n// TODO(b/112892170): Meaningfully handle all ICMP types.\n@@ -133,7 +120,7 @@ func (e *endpoint) handleICMP(r *stack.Route, netHeader buffer.View, pkt stack.P\ncase header.ICMPv6NeighborSolicit:\nreceived.NeighborSolicit.Increment()\n- if len(v) < header.ICMPv6NeighborSolicitMinimumSize {\n+ if len(v) < header.ICMPv6NeighborSolicitMinimumSize || !isNDPValid() {\nreceived.Invalid.Increment()\nreturn\n}\n@@ -253,7 +240,7 @@ func (e *endpoint) handleICMP(r *stack.Route, netHeader buffer.View, pkt stack.P\ncase header.ICMPv6NeighborAdvert:\nreceived.NeighborAdvert.Increment()\n- if len(v) < header.ICMPv6NeighborAdvertSize {\n+ if len(v) < header.ICMPv6NeighborAdvertSize || !isNDPValid() {\nreceived.Invalid.Increment()\nreturn\n}\n@@ -355,8 +342,20 @@ func (e *endpoint) handleICMP(r *stack.Route, netHeader buffer.View, pkt stack.P\ncase header.ICMPv6RouterSolicit:\nreceived.RouterSolicit.Increment()\n+ if !isNDPValid() {\n+ received.Invalid.Increment()\n+ return\n+ }\ncase header.ICMPv6RouterAdvert:\n+ received.RouterAdvert.Increment()\n+\n+ p := h.NDPPayload()\n+ if len(p) < header.NDPRAMinimumSize || !isNDPValid() {\n+ received.Invalid.Increment()\n+ return\n+ }\n+\nrouterAddr := iph.SourceAddress()\n//\n@@ -370,16 +369,6 @@ func (e *endpoint) handleICMP(r *stack.Route, netHeader buffer.View, pkt stack.P\nreturn\n}\n- p := h.NDPPayload()\n-\n- // Is the NDP payload of sufficient size to hold a Router\n- // Advertisement?\n- if len(p) < header.NDPRAMinimumSize {\n- // ...No, silently drop the packet.\n- received.Invalid.Increment()\n- return\n- }\n-\nra := header.NDPRouterAdvert(p)\nopts := ra.Options()\n@@ -395,8 +384,6 @@ func (e *endpoint) handleICMP(r *stack.Route, netHeader buffer.View, pkt stack.P\n// as RFC 4861 section 6.1.2 is concerned.\n//\n- received.RouterAdvert.Increment()\n-\n// Tell the NIC to handle the RA.\nstack := r.Stack()\nrxNICID := r.NICID()\n@@ -404,6 +391,10 @@ func (e *endpoint) handleICMP(r *stack.Route, netHeader buffer.View, pkt stack.P\ncase header.ICMPv6RedirectMsg:\nreceived.RedirectMsg.Increment()\n+ if !isNDPValid() {\n+ received.Invalid.Increment()\n+ return\n+ }\ndefault:\nreceived.Invalid.Increment()\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/ndp_test.go", "new_path": "pkg/tcpip/network/ipv6/ndp_test.go", "diff": "@@ -381,44 +381,48 @@ func TestHopLimitValidation(t *testing.T) {\npkt.SetType(typ.typ)\npkt.SetChecksum(header.ICMPv6Checksum(pkt, r.LocalAddress, r.RemoteAddress, extraData.ToVectorisedView()))\n+ // Rx count of the NDP message should initially be 0.\n+ if got := typStat.Value(); got != 0 {\n+ t.Errorf(\"got %s = %d, want = 0\", typ.name, got)\n+ }\n+\n// Invalid count should initially be 0.\nif got := invalid.Value(); got != 0 {\n- t.Fatalf(\"got invalid = %d, want = 0\", got)\n+ t.Errorf(\"got invalid = %d, want = 0\", got)\n}\n- // Should not have received any ICMPv6 packets with\n- // type = typ.typ.\n- if got := typStat.Value(); got != 0 {\n- t.Fatalf(\"got %s = %d, want = 0\", typ.name, got)\n+ if t.Failed() {\n+ t.FailNow()\n}\n- // Receive the NDP packet with an invalid hop limit\n- // value.\n+ // Receive the NDP packet with an invalid hop limit.\nhandleIPv6Payload(hdr, header.NDPHopLimit-1, ep, &r)\n+ // Rx count of the NDP packet should have increased.\n+ if got := typStat.Value(); got != 1 {\n+ t.Errorf(\"got %s = %d, want = 1\", typ.name, got)\n+ }\n+\n// Invalid count should have increased.\nif got := invalid.Value(); got != 1 {\n- t.Fatalf(\"got invalid = %d, want = 1\", got)\n+ t.Errorf(\"got invalid = %d, want = 1\", got)\n}\n- // Rx count of NDP packet of type typ.typ should not\n- // have increased.\n- if got := typStat.Value(); got != 0 {\n- t.Fatalf(\"got %s = %d, want = 0\", typ.name, got)\n+ if t.Failed() {\n+ t.FailNow()\n}\n// Receive the NDP packet with a valid hop limit value.\nhandleIPv6Payload(hdr, header.NDPHopLimit, ep, &r)\n- // Rx count of NDP packet of type typ.typ should have\n- // increased.\n- if got := typStat.Value(); got != 1 {\n- t.Fatalf(\"got %s = %d, want = 1\", typ.name, got)\n+ // Rx count of the NDP packet should have increased.\n+ if got := typStat.Value(); got != 2 {\n+ t.Errorf(\"got %s = %d, want = 2\", typ.name, got)\n}\n// Invalid count should not have increased again.\nif got := invalid.Value(); got != 1 {\n- t.Fatalf(\"got invalid = %d, want = 1\", got)\n+ t.Errorf(\"got invalid = %d, want = 1\", got)\n}\n})\n}\n@@ -592,21 +596,18 @@ func TestRouterAdvertValidation(t *testing.T) {\nData: hdr.View().ToVectorisedView(),\n})\n- if test.expectedSuccess {\n- if got := invalid.Value(); got != 0 {\n- t.Fatalf(\"got invalid = %d, want = 0\", got)\n- }\nif got := rxRA.Value(); got != 1 {\nt.Fatalf(\"got rxRA = %d, want = 1\", got)\n}\n+ if test.expectedSuccess {\n+ if got := invalid.Value(); got != 0 {\n+ t.Fatalf(\"got invalid = %d, want = 0\", got)\n+ }\n} else {\nif got := invalid.Value(); got != 1 {\nt.Fatalf(\"got invalid = %d, want = 1\", got)\n}\n- if got := rxRA.Value(); got != 0 {\n- t.Fatalf(\"got rxRA = %d, want = 0\", got)\n- }\n}\n})\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Increment NDP message RX stats before validation Tests: - ipv6_test.TestHopLimitValidation - ipv6_test.TestRouterAdvertValidation PiperOrigin-RevId: 304495723
259,860
02.04.2020 17:06:19
25,200
5b2396d244ed6283d928a72bdd4cc58d78ef3175
Fix typo in TODO comments.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/proc/mounts.go", "new_path": "pkg/sentry/fs/proc/mounts.go", "diff": "@@ -170,7 +170,8 @@ func superBlockOpts(mountPath string, msrc *fs.MountSource) string {\n// NOTE(b/147673608): If the mount is a cgroup, we also need to include\n// the cgroup name in the options. For now we just read that from the\n// path.\n- // TODO(gvisor.dev/issues/190): Once gVisor has full cgroup support, we\n+ //\n+ // TODO(gvisor.dev/issue/190): Once gVisor has full cgroup support, we\n// should get this value from the cgroup itself, and not rely on the\n// path.\nif msrc.FilesystemType == \"cgroup\" {\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/tmpfs/filesystem.go", "new_path": "pkg/sentry/fsimpl/tmpfs/filesystem.go", "diff": "@@ -57,7 +57,7 @@ afterSymlink:\n}\nnext := nextVFSD.Impl().(*dentry)\nif symlink, ok := next.inode.impl.(*symlink); ok && rp.ShouldFollowSymlink() {\n- // TODO(gvisor.dev/issues/1197): Symlink traversals updates\n+ // TODO(gvisor.dev/issue/1197): Symlink traversals updates\n// access time.\nif err := rp.HandleSymlink(symlink.target); err != nil {\nreturn nil, err\n@@ -515,7 +515,7 @@ func (fs *filesystem) RenameAt(ctx context.Context, rp *vfs.ResolvingPath, oldPa\noldParent.inode.decLinksLocked()\nnewParent.inode.incLinksLocked()\n}\n- // TODO(gvisor.dev/issues/1197): Update timestamps and parent directory\n+ // TODO(gvisor.dev/issue/1197): Update timestamps and parent directory\n// sizes.\nvfsObj.CommitRenameReplaceDentry(renamedVFSD, &newParent.vfsd, newName, replacedVFSD)\nreturn nil\n@@ -600,7 +600,7 @@ func (fs *filesystem) StatFSAt(ctx context.Context, rp *vfs.ResolvingPath) (linu\nif err != nil {\nreturn linux.Statfs{}, err\n}\n- // TODO(gvisor.dev/issues/1197): Actually implement statfs.\n+ // TODO(gvisor.dev/issue/1197): Actually implement statfs.\nreturn linux.Statfs{}, syserror.ENOSYS\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/tmpfs/stat_test.go", "new_path": "pkg/sentry/fsimpl/tmpfs/stat_test.go", "diff": "@@ -29,7 +29,7 @@ func TestStatAfterCreate(t *testing.T) {\nmode := linux.FileMode(0644)\n// Run with different file types.\n- // TODO(gvisor.dev/issues/1197): Also test symlinks and sockets.\n+ // TODO(gvisor.dev/issue/1197): Also test symlinks and sockets.\nfor _, typ := range []string{\"file\", \"dir\", \"pipe\"} {\nt.Run(fmt.Sprintf(\"type=%q\", typ), func(t *testing.T) {\nvar (\n@@ -169,7 +169,7 @@ func TestSetStat(t *testing.T) {\nmode := linux.FileMode(0644)\n// Run with different file types.\n- // TODO(gvisor.dev/issues/1197): Also test symlinks and sockets.\n+ // TODO(gvisor.dev/issue/1197): Also test symlinks and sockets.\nfor _, typ := range []string{\"file\", \"dir\", \"pipe\"} {\nt.Run(fmt.Sprintf(\"type=%q\", typ), func(t *testing.T) {\nvar (\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/tmpfs/tmpfs.go", "new_path": "pkg/sentry/fsimpl/tmpfs/tmpfs.go", "diff": "@@ -315,7 +315,7 @@ func (i *inode) statTo(stat *linux.Statx) {\nstat.Atime = linux.NsecToStatxTimestamp(i.atime)\nstat.Ctime = linux.NsecToStatxTimestamp(i.ctime)\nstat.Mtime = linux.NsecToStatxTimestamp(i.mtime)\n- // TODO(gvisor.dev/issues/1197): Device number.\n+ // TODO(gvisor.dev/issue/1197): Device number.\nswitch impl := i.impl.(type) {\ncase *regularFile:\nstat.Mask |= linux.STATX_SIZE | linux.STATX_BLOCKS\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netstack/netstack.go", "new_path": "pkg/sentry/socket/netstack/netstack.go", "diff": "@@ -663,7 +663,7 @@ func (s *SocketOperations) checkFamily(family uint16, exact bool) *syserr.Error\n// This is a hack to work around the fact that both IPv4 and IPv6 ANY are\n// represented by the empty string.\n//\n-// TODO(gvisor.dev/issues/1556): remove this function.\n+// TODO(gvisor.dev/issue/1556): remove this function.\nfunc (s *SocketOperations) mapFamily(addr tcpip.FullAddress, family uint16) tcpip.FullAddress {\nif len(addr.Addr) == 0 && s.family == linux.AF_INET6 && family == linux.AF_INET {\naddr.Addr = \"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xff\\xff\\x00\\x00\\x00\\x00\"\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/mount.go", "new_path": "pkg/sentry/vfs/mount.go", "diff": "@@ -835,7 +835,8 @@ func superBlockOpts(mountPath string, mnt *Mount) string {\n// NOTE(b/147673608): If the mount is a cgroup, we also need to include\n// the cgroup name in the options. For now we just read that from the\n// path.\n- // TODO(gvisor.dev/issues/190): Once gVisor has full cgroup support, we\n+ //\n+ // TODO(gvisor.dev/issue/190): Once gVisor has full cgroup support, we\n// should get this value from the cgroup itself, and not rely on the\n// path.\nif mnt.fs.FilesystemType().Name() == \"cgroup\" {\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_inet_loopback.cc", "new_path": "test/syscalls/linux/socket_inet_loopback.cc", "diff": "@@ -234,7 +234,7 @@ TEST_P(DualStackSocketTest, AddressOperations) {\n}\n}\n-// TODO(gvisor.dev/issues/1556): uncomment V4MappedAny.\n+// TODO(gvisor.dev/issue/1556): uncomment V4MappedAny.\nINSTANTIATE_TEST_SUITE_P(\nAll, DualStackSocketTest,\n::testing::Combine(\n" } ]
Go
Apache License 2.0
google/gvisor
Fix typo in TODO comments. PiperOrigin-RevId: 304508083
259,884
25.03.2020 01:38:37
14,400
3685fa4886d0b01a16a654e600305389f43cd156
Added second blog post on networking.
[ { "change_type": "MODIFY", "old_path": "content/blog/1_security_basics/index.md", "new_path": "content/blog/1_security_basics/index.md", "diff": "@@ -43,11 +43,13 @@ In general, Design Principles outline good engineering practices, but in the cas\nA simplified version of the design is below ([more detailed version](https://gvisor.dev/docs/architecture_guide/))[^2]:\n-____\n+----\n+\n![Figure 1](./figure1.png)\nFigure 1: Simplified design of gVisor.\n-____\n+\n+----\nIn order to discuss design principles, the following components are important to know:\n@@ -86,12 +88,13 @@ The principle of Least-Privilege implies that each software component has only t\nLeast-Privilege is applied throughout gVisor. Each component and more importantly, each interface between the components, is designed so that only the minimum level of permission is required for it to perform its function. Specifically, the closer you are to the untrusted application, the less privilege you have.\n-____\n+----\n![Figure 2](./figure2.png)\nFigure 2: runsc components and their privileges.\n-____\n+\n+----\nThis is evident in how runsc (the drop in gVisor binary for Docker/Kubernetes) constructs the sandbox. The Sentry has the least privilege possible (it can't even open a file!). Gofers are only allowed file access, so even if it were compromised, the host network would be unavailable. Only the runsc binary itself has full access to the host OS, and even runsc's access to the host OS is often limited through capabilities / chroot / namespacing.\n@@ -134,13 +137,13 @@ The Sentry communicates with the Gofer through a local unix domain socket (UDS)\nSo, of the 350 syscalls in the Linux kernel, the Sentry needs to implement only 237 of them to support containers. At most, the Sentry only needs to call 68 of the host Linux syscalls. In other words, with gVisor, applications get the vast majority (and growing) functionality of Linux containers for only 68 possible syscalls to the Host OS. 350 syscalls to 68 is attack surface reduction.\n-____\n+----\n![Figure 3](./figure3.png)\nFigure 3: Reduction of Attack Surface of the Syscall Table. Note that the Senty's Syscall Emulation Layer keeps the Containerized Process from ever calling the Host OS.\n-____\n+---\n## Secure-by-default\n" }, { "change_type": "ADD", "old_path": "content/blog/2_networking_security/figure1.png", "new_path": "content/blog/2_networking_security/figure1.png", "diff": "Binary files /dev/null and b/content/blog/2_networking_security/figure1.png differ\n" }, { "change_type": "ADD", "old_path": null, "new_path": "content/blog/2_networking_security/index.md", "diff": "+---\n+date: 2020-03-24\n+title: \"gVisor Networking Security\"\n+linkTitle: \"gVisor Networking Security\"\n+description: \"\"\n+author: Ian Gudger\n+---\n+\n+In our [first blog post](https://gvisor.dev/blog/2019/11/18/gvisor-security-basics-part-1/), we covered some secure design principles and how they guided the architecture of gVisor as a whole. In this post, we will cover how these principles guided the networking architecture of gVisor, and the tradeoffs involved. In particular, we will cover how these principles culminated in two networking modes, how they work, and the properties of each.\n+\n+## gVisor's security architecture in the context of networking\n+\n+Linux networking is complicated. The TCP protocol is over 40 years old, and has been repeatedly extended over the years to keep up with the rapid pace of network infrastructure improvements, all while maintaining compatibility. On top of that, Linux networking has a fairly large API surface. Linux supports [over 150 options](https://github.com/google/gvisor/blob/960f6a975b7e44c0efe8fd38c66b02017c4fe137/pkg/sentry/strace/socket.go#L476-L644) for the most common socket types alone. In fact, the net subsystem is one of the largest and fastest growing in Linux at approximately 1.1 million lines of code. For comparison, that is several times the size of the entire gVisor codebase.\n+\n+At the same time, networking is increasingly important. The cloud era is arguably about making everything a network service, and in order to make that work, the interconnect performance is critical. Adding networking support to gVisor was difficult, not just due to the inherent complexity, but also because it has the potential to significantly weaken gVisor's security model.\n+\n+As outlined in the previous blog post, gVisor's [secure design principles](https://gvisor.dev/blog/2019/11/18/gvisor-security-basics-part-1/#design-principles) are:\n+\n+1. Defense in Depth: each component of the software stack trusts each other component as little as possible.\n+1. Least Privilege: each software component has only the permissions it needs to function, and no more.\n+1. Attack Surface Reduction: limit the surface area of the host exposed to the sandbox.\n+1. Secure by Default: the default choice for a user should be safe.\n+\n+gVisor manifests these principles as a multi-layered system. An application running in the sandbox interacts with the Sentry, a userspace kernel, which mediates all interactions with the Host OS and beyond. The Sentry is written in pure Go with minimal unsafe code, making it less vulnerable to buffer overflows and related memory bugs that can lead to a variety of compromises including code injection. It emulates Linux using only a minimal and audited set of Host OS syscalls that limit the Host OS's attack surface exposed to the Sentry itself. The syscall restrictions are enforced by running the Sentry with seccomp filters, which enforce that the Sentry can only use the expected set of syscalls. The Sentry runs as an unprivileged user and in namespaces, which, along with the seccomp filters, ensure that the Sentry is run with the Least Privilege required.\n+\n+gVisor's multi-layered design provides Defense in Depth. The Sentry, which does not trust the application because it may attack the Sentry and try to bypass it, is the first layer. The sandbox that the Sentry runs in is the second layer. If the Sentry were compromised, the attacker would still be in a highly restrictive sandbox which they must also break out of in order to compromise the Host OS.\n+\n+To enable networking functionality while preserving gVisor's security properties, we implemented a [userspace network stack](https://github.com/google/gvisor/tree/master/pkg/tcpip) in the Sentry, which we creatively named netstack. Netstack is also written in Go, not only to avoid unsafe code in the network stack itself, but also to avoid a complicated and unsafe Foreign Function Interface. Having its own integrated network stack allows the Sentry to implement networking operations using up to three Host OS syscalls to read and write packets. These syscalls allow a very minimal set of operations which are already allowed (either through the same or a similar syscall). Moreover, because packets typically come from off-host (e.g. the internet), the Host OS's packet processing code has received a lot of scrutiny, hopefully resulting in a high degree of hardening.\n+\n+----\n+\n+![Figure 1](./figure1.png)\n+\n+Figure 1: Netstack and gVisor\n+\n+----\n+\n+## Writing a network stack\n+\n+Netstack was written from scratch specifically for gVisor. There are now other users (e.g. [Fuchsia](https://fuchsia.googlesource.com/fuchsia/+/refs/heads/master/src/connectivity/network/netstack/)), but they came later. As we discussed, a custom network stack has enabled a variety of security-related goals which would not have been possible any other way. This came at a cost though. Network stacks are complex and writing a new one comes with many challenges, mostly related to application compatibility and performance.\n+\n+Compatibility issues typically come in two forms: missing features, and features with behavior that differs from Linux (usually due to bugs). Both of these are inevitable in an implementation of a complex system spanning many quickly evolving and ambiguous standards. However, we have invested heavily in this area, and the vast majority of applications have no issues using netstack. For example, [we now support setting 34 different socket options](https://github.com/google/gvisor/blob/815df2959a76e4a19f5882e40402b9bbca9e70be/pkg/sentry/socket/netstack/netstack.go#L830-L1764) versus [only 7 in our initial git commit](https://github.com/google/gvisor/blob/d02b74a5dcfed4bfc8f2f8e545bca4d2afabb296/pkg/sentry/socket/epsocket/epsocket.go#L445-L702). We are continuing to make good progress in this area.\n+\n+Performance issues typically come from TCP behavior and packet processing speed. To improve our TCP behavior, we are working on implementing the full set of TCP RFCs. There are many RFCs which are significant to performance (e.g. [RACK](https://tools.ietf.org/id/draft-ietf-tcpm-rack-03.html) and [BBR](https://tools.ietf.org/html/draft-cardwell-iccrg-bbr-congestion-control-00)) that we have yet to implement. This mostly affects TCP performance with non-ideal network conditions (e.g. cross continent connections). Faster packet processing mostly improves TCP performance when network conditions are very good (e.g. within a datacenter). Our primary strategy here is to reduce interactions with the Go runtime, specifically the garbage collector (GC) and scheduler. We are currently optimizing buffer management to reduce the amount of garbage, which will lower the GC cost. To reduce scheduler interactions, we are re-architecting the TCP implementation to use fewer goroutines. Performance today is good enough for most applications and we are making steady improvements. For example, since May of 2019, we have improved the netstack runsc [iperf3 download benchmark](https://github.com/google/gvisor/blob/master/benchmarks/suites/network.py) score by roughly 15% and upload score by around 10,000X. Current numbers are about 17 Gbps download and about 8 Gbps upload versus about 42 Gbps and 43 Gbps for native (Linux) respectively.\n+\n+\n+## An alternative\n+\n+We also offer an alternative network mode: passthrough. This name can be misleading as syscalls are never passed through from the app to the Host OS. Instead, the passthrough mode implements networking in gVisor using the Host OS's network stack. (This mode is called [hostinet](https://github.com/google/gvisor/tree/master/pkg/sentry/socket/hostinet) in the codebase.) Passthrough mode can improve performance for some use cases as the Host OS's network stack has had an enormous number of person-years poured into making it highly performant. However, there is a rather large downside to using passthrough mode: it weakens gVisor's security model by increasing the Host OS's Attack Surface. This is because using the Host OS's network stack requires the Sentry to use the Host OS's [Berkeley socket interface](https://en.wikipedia.org/wiki/Berkeley_sockets). The Berkeley socket interface is a much larger API surface than the packet interface that our network stack uses. When passthrough mode is in use, the Sentry is allowed to use [15 additional syscalls](https://github.com/google/gvisor/blob/b1576e533223e98ebe4bd1b82b04e3dcda8c4bf1/runsc/boot/filter/config.go#L312-L517). Further, this set of syscalls includes some that allow the Sentry to create file descriptors, something that [we don't normally allow](https://gvisor.dev/blog/2019/11/18/gvisor-security-basics-part-1/#sentry-host-os-interface) as it opens up classes of file-based attacks.\n+\n+There are some networking features that we can't implement on top of syscalls that we feel are safe (most notably those behind [ioctl](http://man7.org/linux/man-pages/man2/ioctl.2.html)) and therefore are not supported. Because of this, we actually support fewer networking features in passthrough mode than we do in netstack, reducing application compatibility. That's right: using our networking stack provides better overall application compatibility than using our passthrough mode.\n+\n+That said, gVisor with passthrough networking still provides a high level of isolation. Applications cannot specify host syscall arguments directly, and the sentry's seccomp policy restricts its syscall use significantly more than a general purpose seccomp policy.\n+\n+\n+## Secure by Default\n+\n+The goal of the Secure by Default principle is to make it easy to securely sandbox containers. Of course, disabling network access entirely is the most secure option, but that is not practical for most applications. To make gVisor Secure by Default, we have made netstack the default networking mode in gVisor as we believe that it provides significantly better isolation. For this reason we strongly caution users from changing the default unless netstack flat out won't work for them. The passthrough mode option is still provided, but we want users to make an informed decision when selecting it.\n+\n+Another way in which gVisor makes it easy to securely sandbox containers is by allowing applications to run unmodified, with no special configuration needed. In order to do this, gVisor needs to support all of the features and syscalls that applications use. Neither seccomp nor gVisor's passthrough mode can do this as applications commonly use syscalls which are too dangerous to be included in a secure policy. Even if this dream isn't fully realized today, gVisor's architecture with netstack makes this possible.\n+\n+If you haven't already, try running a workload in gVisor with netstack. You can find instructions on how to get started in our [Quick Start](https://gvisor.dev/docs/user_guide/quick_start/docker/). We want to hear about both your successes and any issues you encounter. We welcome your contributions, whether that be verbal feedback or code contributions, via our [Gitter channel](https://gitter.im/gvisor/community), [email list](https://groups.google.com/forum/#!forum/gvisor-users), [issue tracker](https://gvisor.dev/issue/new), and [Github repository](https://github.com/google/gvisor). Feel free to express interest in an [open issue](https://gvisor.dev/issue/), or reach out if you aren't sure where to start.\n" } ]
Go
Apache License 2.0
google/gvisor
Added second blog post on networking.
259,884
02.04.2020 19:24:41
14,400
4421f4ad9a5b97cbfa064bbbe8cb8a49ab915f5f
Capitalize Netstack.
[ { "change_type": "MODIFY", "old_path": "content/blog/2_networking_security/index.md", "new_path": "content/blog/2_networking_security/index.md", "diff": "@@ -25,7 +25,7 @@ gVisor manifests these principles as a multi-layered system. An application runn\ngVisor's multi-layered design provides Defense in Depth. The Sentry, which does not trust the application because it may attack the Sentry and try to bypass it, is the first layer. The sandbox that the Sentry runs in is the second layer. If the Sentry were compromised, the attacker would still be in a highly restrictive sandbox which they must also break out of in order to compromise the Host OS.\n-To enable networking functionality while preserving gVisor's security properties, we implemented a [userspace network stack](https://github.com/google/gvisor/tree/master/pkg/tcpip) in the Sentry, which we creatively named netstack. Netstack is also written in Go, not only to avoid unsafe code in the network stack itself, but also to avoid a complicated and unsafe Foreign Function Interface. Having its own integrated network stack allows the Sentry to implement networking operations using up to three Host OS syscalls to read and write packets. These syscalls allow a very minimal set of operations which are already allowed (either through the same or a similar syscall). Moreover, because packets typically come from off-host (e.g. the internet), the Host OS's packet processing code has received a lot of scrutiny, hopefully resulting in a high degree of hardening.\n+To enable networking functionality while preserving gVisor's security properties, we implemented a [userspace network stack](https://github.com/google/gvisor/tree/master/pkg/tcpip) in the Sentry, which we creatively named Netstack. Netstack is also written in Go, not only to avoid unsafe code in the network stack itself, but also to avoid a complicated and unsafe Foreign Function Interface. Having its own integrated network stack allows the Sentry to implement networking operations using up to three Host OS syscalls to read and write packets. These syscalls allow a very minimal set of operations which are already allowed (either through the same or a similar syscall). Moreover, because packets typically come from off-host (e.g. the internet), the Host OS's packet processing code has received a lot of scrutiny, hopefully resulting in a high degree of hardening.\n----\n@@ -39,24 +39,24 @@ Figure 1: Netstack and gVisor\nNetstack was written from scratch specifically for gVisor. There are now other users (e.g. [Fuchsia](https://fuchsia.googlesource.com/fuchsia/+/refs/heads/master/src/connectivity/network/netstack/)), but they came later. As we discussed, a custom network stack has enabled a variety of security-related goals which would not have been possible any other way. This came at a cost though. Network stacks are complex and writing a new one comes with many challenges, mostly related to application compatibility and performance.\n-Compatibility issues typically come in two forms: missing features, and features with behavior that differs from Linux (usually due to bugs). Both of these are inevitable in an implementation of a complex system spanning many quickly evolving and ambiguous standards. However, we have invested heavily in this area, and the vast majority of applications have no issues using netstack. For example, [we now support setting 34 different socket options](https://github.com/google/gvisor/blob/815df2959a76e4a19f5882e40402b9bbca9e70be/pkg/sentry/socket/netstack/netstack.go#L830-L1764) versus [only 7 in our initial git commit](https://github.com/google/gvisor/blob/d02b74a5dcfed4bfc8f2f8e545bca4d2afabb296/pkg/sentry/socket/epsocket/epsocket.go#L445-L702). We are continuing to make good progress in this area.\n+Compatibility issues typically come in two forms: missing features, and features with behavior that differs from Linux (usually due to bugs). Both of these are inevitable in an implementation of a complex system spanning many quickly evolving and ambiguous standards. However, we have invested heavily in this area, and the vast majority of applications have no issues using Netstack. For example, [we now support setting 34 different socket options](https://github.com/google/gvisor/blob/815df2959a76e4a19f5882e40402b9bbca9e70be/pkg/sentry/socket/netstack/netstack.go#L830-L1764) versus [only 7 in our initial git commit](https://github.com/google/gvisor/blob/d02b74a5dcfed4bfc8f2f8e545bca4d2afabb296/pkg/sentry/socket/epsocket/epsocket.go#L445-L702). We are continuing to make good progress in this area.\n-Performance issues typically come from TCP behavior and packet processing speed. To improve our TCP behavior, we are working on implementing the full set of TCP RFCs. There are many RFCs which are significant to performance (e.g. [RACK](https://tools.ietf.org/id/draft-ietf-tcpm-rack-03.html) and [BBR](https://tools.ietf.org/html/draft-cardwell-iccrg-bbr-congestion-control-00)) that we have yet to implement. This mostly affects TCP performance with non-ideal network conditions (e.g. cross continent connections). Faster packet processing mostly improves TCP performance when network conditions are very good (e.g. within a datacenter). Our primary strategy here is to reduce interactions with the Go runtime, specifically the garbage collector (GC) and scheduler. We are currently optimizing buffer management to reduce the amount of garbage, which will lower the GC cost. To reduce scheduler interactions, we are re-architecting the TCP implementation to use fewer goroutines. Performance today is good enough for most applications and we are making steady improvements. For example, since May of 2019, we have improved the netstack runsc [iperf3 download benchmark](https://github.com/google/gvisor/blob/master/benchmarks/suites/network.py) score by roughly 15% and upload score by around 10,000X. Current numbers are about 17 Gbps download and about 8 Gbps upload versus about 42 Gbps and 43 Gbps for native (Linux) respectively.\n+Performance issues typically come from TCP behavior and packet processing speed. To improve our TCP behavior, we are working on implementing the full set of TCP RFCs. There are many RFCs which are significant to performance (e.g. [RACK](https://tools.ietf.org/id/draft-ietf-tcpm-rack-03.html) and [BBR](https://tools.ietf.org/html/draft-cardwell-iccrg-bbr-congestion-control-00)) that we have yet to implement. This mostly affects TCP performance with non-ideal network conditions (e.g. cross continent connections). Faster packet processing mostly improves TCP performance when network conditions are very good (e.g. within a datacenter). Our primary strategy here is to reduce interactions with the Go runtime, specifically the garbage collector (GC) and scheduler. We are currently optimizing buffer management to reduce the amount of garbage, which will lower the GC cost. To reduce scheduler interactions, we are re-architecting the TCP implementation to use fewer goroutines. Performance today is good enough for most applications and we are making steady improvements. For example, since May of 2019, we have improved the Netstack runsc [iperf3 download benchmark](https://github.com/google/gvisor/blob/master/benchmarks/suites/network.py) score by roughly 15% and upload score by around 10,000X. Current numbers are about 17 Gbps download and about 8 Gbps upload versus about 42 Gbps and 43 Gbps for native (Linux) respectively.\n## An alternative\nWe also offer an alternative network mode: passthrough. This name can be misleading as syscalls are never passed through from the app to the Host OS. Instead, the passthrough mode implements networking in gVisor using the Host OS's network stack. (This mode is called [hostinet](https://github.com/google/gvisor/tree/master/pkg/sentry/socket/hostinet) in the codebase.) Passthrough mode can improve performance for some use cases as the Host OS's network stack has had an enormous number of person-years poured into making it highly performant. However, there is a rather large downside to using passthrough mode: it weakens gVisor's security model by increasing the Host OS's Attack Surface. This is because using the Host OS's network stack requires the Sentry to use the Host OS's [Berkeley socket interface](https://en.wikipedia.org/wiki/Berkeley_sockets). The Berkeley socket interface is a much larger API surface than the packet interface that our network stack uses. When passthrough mode is in use, the Sentry is allowed to use [15 additional syscalls](https://github.com/google/gvisor/blob/b1576e533223e98ebe4bd1b82b04e3dcda8c4bf1/runsc/boot/filter/config.go#L312-L517). Further, this set of syscalls includes some that allow the Sentry to create file descriptors, something that [we don't normally allow](https://gvisor.dev/blog/2019/11/18/gvisor-security-basics-part-1/#sentry-host-os-interface) as it opens up classes of file-based attacks.\n-There are some networking features that we can't implement on top of syscalls that we feel are safe (most notably those behind [ioctl](http://man7.org/linux/man-pages/man2/ioctl.2.html)) and therefore are not supported. Because of this, we actually support fewer networking features in passthrough mode than we do in netstack, reducing application compatibility. That's right: using our networking stack provides better overall application compatibility than using our passthrough mode.\n+There are some networking features that we can't implement on top of syscalls that we feel are safe (most notably those behind [ioctl](http://man7.org/linux/man-pages/man2/ioctl.2.html)) and therefore are not supported. Because of this, we actually support fewer networking features in passthrough mode than we do in Netstack, reducing application compatibility. That's right: using our networking stack provides better overall application compatibility than using our passthrough mode.\nThat said, gVisor with passthrough networking still provides a high level of isolation. Applications cannot specify host syscall arguments directly, and the sentry's seccomp policy restricts its syscall use significantly more than a general purpose seccomp policy.\n## Secure by Default\n-The goal of the Secure by Default principle is to make it easy to securely sandbox containers. Of course, disabling network access entirely is the most secure option, but that is not practical for most applications. To make gVisor Secure by Default, we have made netstack the default networking mode in gVisor as we believe that it provides significantly better isolation. For this reason we strongly caution users from changing the default unless netstack flat out won't work for them. The passthrough mode option is still provided, but we want users to make an informed decision when selecting it.\n+The goal of the Secure by Default principle is to make it easy to securely sandbox containers. Of course, disabling network access entirely is the most secure option, but that is not practical for most applications. To make gVisor Secure by Default, we have made Netstack the default networking mode in gVisor as we believe that it provides significantly better isolation. For this reason we strongly caution users from changing the default unless Netstack flat out won't work for them. The passthrough mode option is still provided, but we want users to make an informed decision when selecting it.\n-Another way in which gVisor makes it easy to securely sandbox containers is by allowing applications to run unmodified, with no special configuration needed. In order to do this, gVisor needs to support all of the features and syscalls that applications use. Neither seccomp nor gVisor's passthrough mode can do this as applications commonly use syscalls which are too dangerous to be included in a secure policy. Even if this dream isn't fully realized today, gVisor's architecture with netstack makes this possible.\n+Another way in which gVisor makes it easy to securely sandbox containers is by allowing applications to run unmodified, with no special configuration needed. In order to do this, gVisor needs to support all of the features and syscalls that applications use. Neither seccomp nor gVisor's passthrough mode can do this as applications commonly use syscalls which are too dangerous to be included in a secure policy. Even if this dream isn't fully realized today, gVisor's architecture with Netstack makes this possible.\n-If you haven't already, try running a workload in gVisor with netstack. You can find instructions on how to get started in our [Quick Start](https://gvisor.dev/docs/user_guide/quick_start/docker/). We want to hear about both your successes and any issues you encounter. We welcome your contributions, whether that be verbal feedback or code contributions, via our [Gitter channel](https://gitter.im/gvisor/community), [email list](https://groups.google.com/forum/#!forum/gvisor-users), [issue tracker](https://gvisor.dev/issue/new), and [Github repository](https://github.com/google/gvisor). Feel free to express interest in an [open issue](https://gvisor.dev/issue/), or reach out if you aren't sure where to start.\n+If you haven't already, try running a workload in gVisor with Netstack. You can find instructions on how to get started in our [Quick Start](https://gvisor.dev/docs/user_guide/quick_start/docker/). We want to hear about both your successes and any issues you encounter. We welcome your contributions, whether that be verbal feedback or code contributions, via our [Gitter channel](https://gitter.im/gvisor/community), [email list](https://groups.google.com/forum/#!forum/gvisor-users), [issue tracker](https://gvisor.dev/issue/new), and [Github repository](https://github.com/google/gvisor). Feel free to express interest in an [open issue](https://gvisor.dev/issue/), or reach out if you aren't sure where to start.\n" } ]
Go
Apache License 2.0
google/gvisor
Capitalize Netstack.
259,884
02.04.2020 19:26:22
14,400
c6be49273b7fccc6ee53ede4ca87af4dac1c2474
Add header for final paragraph
[ { "change_type": "MODIFY", "old_path": "content/blog/2_networking_security/index.md", "new_path": "content/blog/2_networking_security/index.md", "diff": "@@ -59,4 +59,6 @@ The goal of the Secure by Default principle is to make it easy to securely sandb\nAnother way in which gVisor makes it easy to securely sandbox containers is by allowing applications to run unmodified, with no special configuration needed. In order to do this, gVisor needs to support all of the features and syscalls that applications use. Neither seccomp nor gVisor's passthrough mode can do this as applications commonly use syscalls which are too dangerous to be included in a secure policy. Even if this dream isn't fully realized today, gVisor's architecture with Netstack makes this possible.\n+## Give Netstack a Try\n+\nIf you haven't already, try running a workload in gVisor with Netstack. You can find instructions on how to get started in our [Quick Start](https://gvisor.dev/docs/user_guide/quick_start/docker/). We want to hear about both your successes and any issues you encounter. We welcome your contributions, whether that be verbal feedback or code contributions, via our [Gitter channel](https://gitter.im/gvisor/community), [email list](https://groups.google.com/forum/#!forum/gvisor-users), [issue tracker](https://gvisor.dev/issue/new), and [Github repository](https://github.com/google/gvisor). Feel free to express interest in an [open issue](https://gvisor.dev/issue/), or reach out if you aren't sure where to start.\n" } ]
Go
Apache License 2.0
google/gvisor
Add header for final paragraph
260,004
02.04.2020 18:29:09
25,200
4582a2f188953d34591aef1a479d19d9be8f640f
Drop NDP messages with fragment extension header As per RFC 6980 section 5, nodes MUST silently ignore NDP messages if the packet carrying them include an IPv6 Fragmentation Header. Test: ipv6_test.TestNDPValidation
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/header/ipv6_extension_headers.go", "new_path": "pkg/tcpip/header/ipv6_extension_headers.go", "diff": "@@ -62,6 +62,10 @@ const (\n// within an IPv6RoutingExtHdr.\nipv6RoutingExtHdrSegmentsLeftIdx = 1\n+ // IPv6FragmentExtHdrLength is the length of an IPv6 extension header, in\n+ // bytes.\n+ IPv6FragmentExtHdrLength = 8\n+\n// ipv6FragmentExtHdrFragmentOffsetOffset is the offset to the start of the\n// Fragment Offset field within an IPv6FragmentExtHdr.\nipv6FragmentExtHdrFragmentOffsetOffset = 0\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/icmp.go", "new_path": "pkg/tcpip/network/ipv6/icmp.go", "diff": "@@ -62,7 +62,7 @@ func (e *endpoint) handleControl(typ stack.ControlType, extra uint32, pkt stack.\ne.dispatcher.DeliverTransportControlPacket(e.id.LocalAddress, h.DestinationAddress(), ProtocolNumber, p, typ, extra, pkt)\n}\n-func (e *endpoint) handleICMP(r *stack.Route, netHeader buffer.View, pkt stack.PacketBuffer) {\n+func (e *endpoint) handleICMP(r *stack.Route, netHeader buffer.View, pkt stack.PacketBuffer, hasFragmentHeader bool) {\nstats := r.Stats().ICMP\nsent := stats.V6PacketsSent\nreceived := stats.V6PacketsReceived\n@@ -91,7 +91,10 @@ func (e *endpoint) handleICMP(r *stack.Route, netHeader buffer.View, pkt stack.P\n// 8.1, nodes MUST silently drop NDP packets where the Hop Limit field\n// in the IPv6 header is not set to 255, or the ICMPv6 Code field is not\n// set to 0.\n- return iph.HopLimit() == header.NDPHopLimit && h.Code() == 0\n+ //\n+ // As per RFC 6980 section 5, nodes MUST silently drop NDP messages if the\n+ // packet includes a fragmentation header.\n+ return !hasFragmentHeader && iph.HopLimit() == header.NDPHopLimit && h.Code() == 0\n}\n// TODO(b/112892170): Meaningfully handle all ICMP types.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/ipv6.go", "new_path": "pkg/tcpip/network/ipv6/ipv6.go", "diff": "@@ -185,6 +185,7 @@ func (e *endpoint) HandlePacket(r *stack.Route, pkt stack.PacketBuffer) {\npkt.Data.CapLength(int(h.PayloadLength()))\nit := header.MakeIPv6PayloadIterator(header.IPv6ExtensionHeaderIdentifier(h.NextHeader()), pkt.Data)\n+ hasFragmentHeader := false\nfor firstHeader := true; ; firstHeader = false {\nextHdr, done, err := it.Next()\n@@ -257,6 +258,8 @@ func (e *endpoint) HandlePacket(r *stack.Route, pkt stack.PacketBuffer) {\n}\ncase header.IPv6FragmentExtHdr:\n+ hasFragmentHeader = true\n+\nfragmentOffset := extHdr.FragmentOffset()\nmore := extHdr.More()\nif !more && fragmentOffset == 0 {\n@@ -344,7 +347,7 @@ func (e *endpoint) HandlePacket(r *stack.Route, pkt stack.PacketBuffer) {\npkt.Data = extHdr.Buf\nif p := tcpip.TransportProtocolNumber(extHdr.Identifier); p == header.ICMPv6ProtocolNumber {\n- e.handleICMP(r, headerView, pkt)\n+ e.handleICMP(r, headerView, pkt, hasFragmentHeader)\n} else {\nr.Stats().IP.PacketsDelivered.Increment()\n// TODO(b/152019344): Send an ICMPv6 Parameter Problem, Code 1 error\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/ndp_test.go", "new_path": "pkg/tcpip/network/ipv6/ndp_test.go", "diff": "@@ -276,9 +276,7 @@ func TestNeighorAdvertisementWithTargetLinkLayerOption(t *testing.T) {\n}\n}\n-// TestHopLimitValidation is a test that makes sure that NDP packets are only\n-// received if their IP header's hop limit is set to 255.\n-func TestHopLimitValidation(t *testing.T) {\n+func TestNDPValidation(t *testing.T) {\nsetup := func(t *testing.T) (*stack.Stack, stack.NetworkEndpoint, stack.Route) {\nt.Helper()\n@@ -294,12 +292,19 @@ func TestHopLimitValidation(t *testing.T) {\nreturn s, ep, r\n}\n- handleIPv6Payload := func(hdr buffer.Prependable, hopLimit uint8, ep stack.NetworkEndpoint, r *stack.Route) {\n+ handleIPv6Payload := func(hdr buffer.Prependable, hopLimit uint8, atomicFragment bool, ep stack.NetworkEndpoint, r *stack.Route) {\n+ nextHdr := uint8(header.ICMPv6ProtocolNumber)\n+ if atomicFragment {\n+ bytes := hdr.Prepend(header.IPv6FragmentExtHdrLength)\n+ bytes[0] = nextHdr\n+ nextHdr = uint8(header.IPv6FragmentExtHdrIdentifier)\n+ }\n+\npayloadLength := hdr.UsedLength()\nip := header.IPv6(hdr.Prepend(header.IPv6MinimumSize))\nip.Encode(&header.IPv6Fields{\nPayloadLength: uint16(payloadLength),\n- NextHeader: uint8(header.ICMPv6ProtocolNumber),\n+ NextHeader: nextHdr,\nHopLimit: hopLimit,\nSrcAddr: r.LocalAddress,\nDstAddr: r.RemoteAddress,\n@@ -364,8 +369,47 @@ func TestHopLimitValidation(t *testing.T) {\n},\n}\n+ subTests := []struct {\n+ name string\n+ atomicFragment bool\n+ hopLimit uint8\n+ code uint8\n+ valid bool\n+ }{\n+ {\n+ name: \"Valid\",\n+ atomicFragment: false,\n+ hopLimit: header.NDPHopLimit,\n+ code: 0,\n+ valid: true,\n+ },\n+ {\n+ name: \"Fragmented\",\n+ atomicFragment: true,\n+ hopLimit: header.NDPHopLimit,\n+ code: 0,\n+ valid: false,\n+ },\n+ {\n+ name: \"Invalid hop limit\",\n+ atomicFragment: false,\n+ hopLimit: header.NDPHopLimit - 1,\n+ code: 0,\n+ valid: false,\n+ },\n+ {\n+ name: \"Invalid ICMPv6 code\",\n+ atomicFragment: false,\n+ hopLimit: header.NDPHopLimit,\n+ code: 1,\n+ valid: false,\n+ },\n+ }\n+\nfor _, typ := range types {\nt.Run(typ.name, func(t *testing.T) {\n+ for _, test := range subTests {\n+ t.Run(test.name, func(t *testing.T) {\ns, ep, r := setup(t)\ndefer r.Release()\n@@ -374,11 +418,12 @@ func TestHopLimitValidation(t *testing.T) {\ntypStat := typ.statCounter(stats)\nextraDataLen := len(typ.extraData)\n- hdr := buffer.NewPrependable(header.IPv6MinimumSize + typ.size + extraDataLen)\n+ hdr := buffer.NewPrependable(header.IPv6MinimumSize + typ.size + extraDataLen + header.IPv6FragmentExtHdrLength)\nextraData := buffer.View(hdr.Prepend(extraDataLen))\ncopy(extraData, typ.extraData)\npkt := header.ICMPv6(hdr.Prepend(typ.size))\npkt.SetType(typ.typ)\n+ pkt.SetCode(test.code)\npkt.SetChecksum(header.ICMPv6Checksum(pkt, r.LocalAddress, r.RemoteAddress, extraData.ToVectorisedView()))\n// Rx count of the NDP message should initially be 0.\n@@ -395,34 +440,22 @@ func TestHopLimitValidation(t *testing.T) {\nt.FailNow()\n}\n- // Receive the NDP packet with an invalid hop limit.\n- handleIPv6Payload(hdr, header.NDPHopLimit-1, ep, &r)\n+ handleIPv6Payload(hdr, test.hopLimit, test.atomicFragment, ep, &r)\n// Rx count of the NDP packet should have increased.\nif got := typStat.Value(); got != 1 {\nt.Errorf(\"got %s = %d, want = 1\", typ.name, got)\n}\n+ want := uint64(0)\n+ if !test.valid {\n// Invalid count should have increased.\n- if got := invalid.Value(); got != 1 {\n- t.Errorf(\"got invalid = %d, want = 1\", got)\n- }\n-\n- if t.Failed() {\n- t.FailNow()\n+ want = 1\n}\n-\n- // Receive the NDP packet with a valid hop limit value.\n- handleIPv6Payload(hdr, header.NDPHopLimit, ep, &r)\n-\n- // Rx count of the NDP packet should have increased.\n- if got := typStat.Value(); got != 2 {\n- t.Errorf(\"got %s = %d, want = 2\", typ.name, got)\n+ if got := invalid.Value(); got != want {\n+ t.Errorf(\"got invalid = %d, want = %d\", got, want)\n}\n-\n- // Invalid count should not have increased again.\n- if got := invalid.Value(); got != 1 {\n- t.Errorf(\"got invalid = %d, want = 1\", got)\n+ })\n}\n})\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Drop NDP messages with fragment extension header As per RFC 6980 section 5, nodes MUST silently ignore NDP messages if the packet carrying them include an IPv6 Fragmentation Header. Test: ipv6_test.TestNDPValidation PiperOrigin-RevId: 304519379
259,980
02.04.2020 22:01:57
25,200
d151693530db68db43188ce0fbc9f81aa5f27e2e
Avoid sending a partial dirent when the Rreaddir response exceeds message limit.
[ { "change_type": "MODIFY", "old_path": "pkg/p9/messages.go", "new_path": "pkg/p9/messages.go", "diff": "@@ -1926,19 +1926,17 @@ func (r *Rreaddir) decode(b *buffer) {\n// encode implements encoder.encode.\nfunc (r *Rreaddir) encode(b *buffer) {\nentriesBuf := buffer{}\n+ payloadSize := 0\nfor _, d := range r.Entries {\nd.encode(&entriesBuf)\n- if len(entriesBuf.data) >= int(r.Count) {\n+ if len(entriesBuf.data) > int(r.Count) {\nbreak\n}\n+ payloadSize = len(entriesBuf.data)\n}\n- if len(entriesBuf.data) < int(r.Count) {\n- r.Count = uint32(len(entriesBuf.data))\n- r.payload = entriesBuf.data\n- } else {\n- r.payload = entriesBuf.data[:r.Count]\n- }\n- b.Write32(uint32(r.Count))\n+ r.Count = uint32(payloadSize)\n+ r.payload = entriesBuf.data[:payloadSize]\n+ b.Write32(r.Count)\n}\n// Type implements message.Type.\n" }, { "change_type": "MODIFY", "old_path": "pkg/p9/messages_test.go", "new_path": "pkg/p9/messages_test.go", "diff": "@@ -216,7 +216,7 @@ func TestEncodeDecode(t *testing.T) {\n},\n&Rreaddir{\n// Count must be sufficient to encode a dirent.\n- Count: 0x18,\n+ Count: 0x1a,\nEntries: []Dirent{{QID: QID{Type: 2}}},\n},\n&Tfsync{\n" } ]
Go
Apache License 2.0
google/gvisor
Avoid sending a partial dirent when the Rreaddir response exceeds message limit. PiperOrigin-RevId: 304542967
259,858
03.04.2020 13:39:45
25,200
a94309628ebbc2e6c4997890f1b966fa7a16be20
Ensure EOF is handled propertly during splice.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/pipe/pipe.go", "new_path": "pkg/sentry/kernel/pipe/pipe.go", "diff": "@@ -255,7 +255,8 @@ func (p *Pipe) write(ctx context.Context, ops writeOps) (int64, error) {\n// POSIX requires that a write smaller than atomicIOBytes (PIPE_BUF) be\n// atomic, but requires no atomicity for writes larger than this.\nwanted := ops.left()\n- if avail := p.max - p.view.Size(); wanted > avail {\n+ avail := p.max - p.view.Size()\n+ if wanted > avail {\nif wanted <= p.atomicIOBytes {\nreturn 0, syserror.ErrWouldBlock\n}\n@@ -268,8 +269,14 @@ func (p *Pipe) write(ctx context.Context, ops writeOps) (int64, error) {\nreturn done, err\n}\n- if wanted > done {\n- // Partial write due to full pipe.\n+ if done < avail {\n+ // Non-failure, but short write.\n+ return done, nil\n+ }\n+ if done < wanted {\n+ // Partial write due to full pipe. Note that this could also be\n+ // the short write case above, we would expect a second call\n+ // and the write to return zero bytes in this case.\nreturn done, syserror.ErrWouldBlock\n}\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/sendfile.cc", "new_path": "test/syscalls/linux/sendfile.cc", "diff": "@@ -530,6 +530,34 @@ TEST(SendFileTest, SendToSpecialFile) {\nSyscallSucceedsWithValue(kSize & (~7)));\n}\n+TEST(SendFileTest, SendFileToPipe) {\n+ // Create temp file.\n+ constexpr char kData[] = \"<insert-quote-here>\";\n+ constexpr int kDataSize = sizeof(kData) - 1;\n+ const TempPath in_file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith(\n+ GetAbsoluteTestTmpdir(), kData, TempPath::kDefaultFileMode));\n+ const FileDescriptor inf =\n+ ASSERT_NO_ERRNO_AND_VALUE(Open(in_file.path(), O_RDONLY));\n+\n+ // Create a pipe for sending to a pipe.\n+ int fds[2];\n+ ASSERT_THAT(pipe(fds), SyscallSucceeds());\n+ const FileDescriptor rfd(fds[0]);\n+ const FileDescriptor wfd(fds[1]);\n+\n+ // Expect to read up to the given size.\n+ std::vector<char> buf(kDataSize);\n+ ScopedThread t([&]() {\n+ absl::SleepFor(absl::Milliseconds(100));\n+ ASSERT_THAT(read(rfd.get(), buf.data(), buf.size()),\n+ SyscallSucceedsWithValue(kDataSize));\n+ });\n+\n+ // Send with twice the size of the file, which should hit EOF.\n+ EXPECT_THAT(sendfile(wfd.get(), inf.get(), nullptr, kDataSize * 2),\n+ SyscallSucceedsWithValue(kDataSize));\n+}\n+\n} // namespace\n} // namespace testing\n" } ]
Go
Apache License 2.0
google/gvisor
Ensure EOF is handled propertly during splice. PiperOrigin-RevId: 304684417
259,860
04.04.2020 21:01:42
25,200
24bee1c1813a691072cff5bad7a528690a99eb5e
Record VFS2 sockets in global socket map. Updates
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/proc/BUILD", "new_path": "pkg/sentry/fsimpl/proc/BUILD", "diff": "@@ -22,7 +22,6 @@ go_library(\n\"//pkg/log\",\n\"//pkg/refs\",\n\"//pkg/safemem\",\n- \"//pkg/sentry/fs\",\n\"//pkg/sentry/fsbridge\",\n\"//pkg/sentry/fsimpl/kernfs\",\n\"//pkg/sentry/inet\",\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/proc/task_net.go", "new_path": "pkg/sentry/fsimpl/proc/task_net.go", "diff": "@@ -24,7 +24,6 @@ import (\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/context\"\n\"gvisor.dev/gvisor/pkg/log\"\n- \"gvisor.dev/gvisor/pkg/sentry/fs\"\n\"gvisor.dev/gvisor/pkg/sentry/fsimpl/kernfs\"\n\"gvisor.dev/gvisor/pkg/sentry/inet\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n@@ -32,6 +31,7 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/socket\"\n\"gvisor.dev/gvisor/pkg/sentry/socket/unix\"\n\"gvisor.dev/gvisor/pkg/sentry/socket/unix/transport\"\n+ \"gvisor.dev/gvisor/pkg/sentry/vfs\"\n\"gvisor.dev/gvisor/pkg/syserror\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n\"gvisor.dev/gvisor/pkg/usermem\"\n@@ -206,22 +206,21 @@ var _ dynamicInode = (*netUnixData)(nil)\nfunc (n *netUnixData) Generate(ctx context.Context, buf *bytes.Buffer) error {\nbuf.WriteString(\"Num RefCount Protocol Flags Type St Inode Path\\n\")\nfor _, se := range n.kernel.ListSockets() {\n- s := se.Sock.Get()\n- if s == nil {\n- log.Debugf(\"Couldn't resolve weakref %v in socket table, racing with destruction?\", se.Sock)\n+ s := se.SockVFS2\n+ if !s.TryIncRef() {\n+ log.Debugf(\"Couldn't get reference on %v in socket table, racing with destruction?\", s)\ncontinue\n}\n- sfile := s.(*fs.File)\n- if family, _, _ := sfile.FileOperations.(socket.Socket).Type(); family != linux.AF_UNIX {\n+ if family, _, _ := s.Impl().(socket.SocketVFS2).Type(); family != linux.AF_UNIX {\ns.DecRef()\n// Not a unix socket.\ncontinue\n}\n- sops := sfile.FileOperations.(*unix.SocketOperations)\n+ sops := s.Impl().(*unix.SocketVFS2)\naddr, err := sops.Endpoint().GetLocalAddress()\nif err != nil {\n- log.Warningf(\"Failed to retrieve socket name from %+v: %v\", sfile, err)\n+ log.Warningf(\"Failed to retrieve socket name from %+v: %v\", s, err)\naddr.Addr = \"<unknown>\"\n}\n@@ -234,6 +233,15 @@ func (n *netUnixData) Generate(ctx context.Context, buf *bytes.Buffer) error {\n}\n}\n+ // Get inode number.\n+ var ino uint64\n+ stat, statErr := s.Stat(ctx, vfs.StatOptions{Mask: linux.STATX_INO})\n+ if statErr != nil || stat.Mask&linux.STATX_INO == 0 {\n+ log.Warningf(\"Failed to retrieve ino for socket file: %v\", statErr)\n+ } else {\n+ ino = stat.Ino\n+ }\n+\n// In the socket entry below, the value for the 'Num' field requires\n// some consideration. Linux prints the address to the struct\n// unix_sock representing a socket in the kernel, but may redact the\n@@ -252,14 +260,14 @@ func (n *netUnixData) Generate(ctx context.Context, buf *bytes.Buffer) error {\n// the definition of this struct changes over time.\n//\n// For now, we always redact this pointer.\n- fmt.Fprintf(buf, \"%#016p: %08X %08X %08X %04X %02X %5d\",\n+ fmt.Fprintf(buf, \"%#016p: %08X %08X %08X %04X %02X %8d\",\n(*unix.SocketOperations)(nil), // Num, pointer to kernel socket struct.\n- sfile.ReadRefs()-1, // RefCount, don't count our own ref.\n+ s.Refs()-1, // RefCount, don't count our own ref.\n0, // Protocol, always 0 for UDS.\nsockFlags, // Flags.\nsops.Endpoint().Type(), // Type.\nsops.State(), // State.\n- sfile.InodeID(), // Inode.\n+ ino, // Inode.\n)\n// Path\n@@ -341,15 +349,14 @@ func commonGenerateTCP(ctx context.Context, buf *bytes.Buffer, k *kernel.Kernel,\nt := kernel.TaskFromContext(ctx)\nfor _, se := range k.ListSockets() {\n- s := se.Sock.Get()\n- if s == nil {\n- log.Debugf(\"Couldn't resolve weakref with ID %v in socket table, racing with destruction?\", se.ID)\n+ s := se.SockVFS2\n+ if !s.TryIncRef() {\n+ log.Debugf(\"Couldn't get reference on %v in socket table, racing with destruction?\", s)\ncontinue\n}\n- sfile := s.(*fs.File)\n- sops, ok := sfile.FileOperations.(socket.Socket)\n+ sops, ok := s.Impl().(socket.SocketVFS2)\nif !ok {\n- panic(fmt.Sprintf(\"Found non-socket file in socket table: %+v\", sfile))\n+ panic(fmt.Sprintf(\"Found non-socket file in socket table: %+v\", s))\n}\nif fa, stype, _ := sops.Type(); !(family == fa && stype == linux.SOCK_STREAM) {\ns.DecRef()\n@@ -398,14 +405,15 @@ func commonGenerateTCP(ctx context.Context, buf *bytes.Buffer, k *kernel.Kernel,\n// Unimplemented.\nfmt.Fprintf(buf, \"%08X \", 0)\n+ stat, statErr := s.Stat(ctx, vfs.StatOptions{Mask: linux.STATX_UID | linux.STATX_INO})\n+\n// Field: uid.\n- uattr, err := sfile.Dirent.Inode.UnstableAttr(ctx)\n- if err != nil {\n- log.Warningf(\"Failed to retrieve unstable attr for socket file: %v\", err)\n+ if statErr != nil || stat.Mask&linux.STATX_UID == 0 {\n+ log.Warningf(\"Failed to retrieve uid for socket file: %v\", statErr)\nfmt.Fprintf(buf, \"%5d \", 0)\n} else {\ncreds := auth.CredentialsFromContext(ctx)\n- fmt.Fprintf(buf, \"%5d \", uint32(uattr.Owner.UID.In(creds.UserNamespace).OrOverflow()))\n+ fmt.Fprintf(buf, \"%5d \", uint32(auth.KUID(stat.UID).In(creds.UserNamespace).OrOverflow()))\n}\n// Field: timeout; number of unanswered 0-window probes.\n@@ -413,11 +421,16 @@ func commonGenerateTCP(ctx context.Context, buf *bytes.Buffer, k *kernel.Kernel,\nfmt.Fprintf(buf, \"%8d \", 0)\n// Field: inode.\n- fmt.Fprintf(buf, \"%8d \", sfile.InodeID())\n+ if statErr != nil || stat.Mask&linux.STATX_INO == 0 {\n+ log.Warningf(\"Failed to retrieve inode for socket file: %v\", statErr)\n+ fmt.Fprintf(buf, \"%8d \", 0)\n+ } else {\n+ fmt.Fprintf(buf, \"%8d \", stat.Ino)\n+ }\n// Field: refcount. Don't count the ref we obtain while deferencing\n// the weakref to this socket.\n- fmt.Fprintf(buf, \"%d \", sfile.ReadRefs()-1)\n+ fmt.Fprintf(buf, \"%d \", s.Refs()-1)\n// Field: Socket struct address. Redacted due to the same reason as\n// the 'Num' field in /proc/net/unix, see netUnix.ReadSeqFileData.\n@@ -499,15 +512,14 @@ func (d *netUDPData) Generate(ctx context.Context, buf *bytes.Buffer) error {\nt := kernel.TaskFromContext(ctx)\nfor _, se := range d.kernel.ListSockets() {\n- s := se.Sock.Get()\n- if s == nil {\n- log.Debugf(\"Couldn't resolve weakref with ID %v in socket table, racing with destruction?\", se.ID)\n+ s := se.SockVFS2\n+ if !s.TryIncRef() {\n+ log.Debugf(\"Couldn't get reference on %v in socket table, racing with destruction?\", s)\ncontinue\n}\n- sfile := s.(*fs.File)\n- sops, ok := sfile.FileOperations.(socket.Socket)\n+ sops, ok := s.Impl().(socket.SocketVFS2)\nif !ok {\n- panic(fmt.Sprintf(\"Found non-socket file in socket table: %+v\", sfile))\n+ panic(fmt.Sprintf(\"Found non-socket file in socket table: %+v\", s))\n}\nif family, stype, _ := sops.Type(); family != linux.AF_INET || stype != linux.SOCK_DGRAM {\ns.DecRef()\n@@ -551,25 +563,31 @@ func (d *netUDPData) Generate(ctx context.Context, buf *bytes.Buffer) error {\n// Field: retrnsmt. Always 0 for UDP.\nfmt.Fprintf(buf, \"%08X \", 0)\n+ stat, statErr := s.Stat(ctx, vfs.StatOptions{Mask: linux.STATX_UID | linux.STATX_INO})\n+\n// Field: uid.\n- uattr, err := sfile.Dirent.Inode.UnstableAttr(ctx)\n- if err != nil {\n- log.Warningf(\"Failed to retrieve unstable attr for socket file: %v\", err)\n+ if statErr != nil || stat.Mask&linux.STATX_UID == 0 {\n+ log.Warningf(\"Failed to retrieve uid for socket file: %v\", statErr)\nfmt.Fprintf(buf, \"%5d \", 0)\n} else {\ncreds := auth.CredentialsFromContext(ctx)\n- fmt.Fprintf(buf, \"%5d \", uint32(uattr.Owner.UID.In(creds.UserNamespace).OrOverflow()))\n+ fmt.Fprintf(buf, \"%5d \", uint32(auth.KUID(stat.UID).In(creds.UserNamespace).OrOverflow()))\n}\n// Field: timeout. Always 0 for UDP.\nfmt.Fprintf(buf, \"%8d \", 0)\n// Field: inode.\n- fmt.Fprintf(buf, \"%8d \", sfile.InodeID())\n+ if statErr != nil || stat.Mask&linux.STATX_INO == 0 {\n+ log.Warningf(\"Failed to retrieve inode for socket file: %v\", statErr)\n+ fmt.Fprintf(buf, \"%8d \", 0)\n+ } else {\n+ fmt.Fprintf(buf, \"%8d \", stat.Ino)\n+ }\n// Field: ref; reference count on the socket inode. Don't count the ref\n// we obtain while deferencing the weakref to this socket.\n- fmt.Fprintf(buf, \"%d \", sfile.ReadRefs()-1)\n+ fmt.Fprintf(buf, \"%d \", s.Refs()-1)\n// Field: Socket struct address. Redacted due to the same reason as\n// the 'Num' field in /proc/net/unix, see netUnix.ReadSeqFileData.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/kernel.go", "new_path": "pkg/sentry/kernel/kernel.go", "diff": "@@ -1447,6 +1447,7 @@ type SocketEntry struct {\nsocketEntry\nk *Kernel\nSock *refs.WeakRef\n+ SockVFS2 *vfs.FileDescription\nID uint64 // Socket table entry number.\n}\n@@ -1470,7 +1471,30 @@ func (k *Kernel) RecordSocket(sock *fs.File) {\nk.extMu.Unlock()\n}\n+// RecordSocketVFS2 adds a VFS2 socket to the system-wide socket table for\n+// tracking.\n+//\n+// Precondition: Caller must hold a reference to sock.\n+//\n+// Note that the socket table will not hold a reference on the\n+// vfs.FileDescription, because we do not support weak refs on VFS2 files.\n+func (k *Kernel) RecordSocketVFS2(sock *vfs.FileDescription) {\n+ k.extMu.Lock()\n+ id := k.nextSocketEntry\n+ k.nextSocketEntry++\n+ s := &SocketEntry{\n+ k: k,\n+ ID: id,\n+ SockVFS2: sock,\n+ }\n+ k.sockets.PushBack(s)\n+ k.extMu.Unlock()\n+}\n+\n// ListSockets returns a snapshot of all sockets.\n+//\n+// Callers of ListSockets() in VFS2 should use SocketEntry.SockVFS2.TryIncRef()\n+// to get a reference on a socket in the table.\nfunc (k *Kernel) ListSockets() []*SocketEntry {\nk.extMu.Lock()\nvar socks []*SocketEntry\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/socket.go", "new_path": "pkg/sentry/socket/socket.go", "diff": "@@ -269,7 +269,7 @@ func NewVFS2(t *kernel.Task, family int, stype linux.SockType, protocol int) (*v\nreturn nil, err\n}\nif s != nil {\n- // TODO: Add vfs2 sockets to global socket table.\n+ t.Kernel().RecordSocketVFS2(s)\nreturn s, nil\n}\n}\n@@ -291,7 +291,9 @@ func PairVFS2(t *kernel.Task, family int, stype linux.SockType, protocol int) (*\nreturn nil, nil, err\n}\nif s1 != nil && s2 != nil {\n- // TODO: Add vfs2 sockets to global socket table.\n+ k := t.Kernel()\n+ k.RecordSocketVFS2(s1)\n+ k.RecordSocketVFS2(s2)\nreturn s1, s2, nil\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/unix/unix_vfs2.go", "new_path": "pkg/sentry/socket/unix/unix_vfs2.go", "diff": "@@ -141,7 +141,7 @@ func (s *SocketVFS2) Accept(t *kernel.Task, peerRequested bool, flags int, block\nreturn 0, nil, 0, syserr.FromError(e)\n}\n- // TODO: add vfs2 sockets to global table.\n+ t.Kernel().RecordSocketVFS2(ns)\nreturn fd, addr, addrLen, nil\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/file_description.go", "new_path": "pkg/sentry/vfs/file_description.go", "diff": "@@ -182,6 +182,12 @@ func (fd *FileDescription) DecRef() {\n}\n}\n+// Refs returns the current number of references. The returned count\n+// is inherently racy and is unsafe to use without external synchronization.\n+func (fd *FileDescription) Refs() int64 {\n+ return atomic.LoadInt64(&fd.refs)\n+}\n+\n// Mount returns the mount on which fd was opened. It does not take a reference\n// on the returned Mount.\nfunc (fd *FileDescription) Mount() *Mount {\n" } ]
Go
Apache License 2.0
google/gvisor
Record VFS2 sockets in global socket map. Updates #1476, #1478, #1484, #1485. PiperOrigin-RevId: 304845354
259,860
06.04.2020 07:30:20
25,200
00d9776a4bb1cc1d7125af7d3e54a939a4f3847a
Add socket files to tmpfs VFS2. Updates
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/tmpfs/BUILD", "new_path": "pkg/sentry/fsimpl/tmpfs/BUILD", "diff": "@@ -24,6 +24,7 @@ go_library(\n\"filesystem.go\",\n\"named_pipe.go\",\n\"regular_file.go\",\n+ \"socket_file.go\",\n\"symlink.go\",\n\"tmpfs.go\",\n],\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/tmpfs/filesystem.go", "new_path": "pkg/sentry/fsimpl/tmpfs/filesystem.go", "diff": "@@ -261,8 +261,7 @@ func (fs *filesystem) MknodAt(ctx context.Context, rp *vfs.ResolvingPath, opts v\ncase linux.S_IFCHR:\nchildInode = fs.newDeviceFile(rp.Credentials(), opts.Mode, vfs.CharDevice, opts.DevMajor, opts.DevMinor)\ncase linux.S_IFSOCK:\n- // Not yet supported.\n- return syserror.EPERM\n+ childInode = fs.newSocketFile(rp.Credentials(), opts.Mode, opts.Endpoint)\ndefault:\nreturn syserror.EINVAL\n}\n@@ -396,6 +395,8 @@ func (d *dentry) open(ctx context.Context, rp *vfs.ResolvingPath, opts *vfs.Open\nreturn newNamedPipeFD(ctx, impl, rp, &d.vfsd, opts.Flags)\ncase *deviceFile:\nreturn rp.VirtualFilesystem().OpenDeviceSpecialFile(ctx, rp.Mount(), &d.vfsd, impl.kind, impl.major, impl.minor, opts)\n+ case *socketFile:\n+ return nil, syserror.ENXIO\ndefault:\npanic(fmt.Sprintf(\"unknown inode type: %T\", d.inode.impl))\n}\n@@ -679,11 +680,20 @@ func (fs *filesystem) UnlinkAt(ctx context.Context, rp *vfs.ResolvingPath) error\n}\n// BoundEndpointAt implements FilesystemImpl.BoundEndpointAt.\n-//\n-// TODO(gvisor.dev/issue/1476): Implement BoundEndpointAt.\nfunc (fs *filesystem) BoundEndpointAt(ctx context.Context, rp *vfs.ResolvingPath) (transport.BoundEndpoint, error) {\n+ fs.mu.RLock()\n+ defer fs.mu.RUnlock()\n+ d, err := resolveLocked(rp)\n+ if err != nil {\n+ return nil, err\n+ }\n+ switch impl := d.inode.impl.(type) {\n+ case *socketFile:\n+ return impl.ep, nil\n+ default:\nreturn nil, syserror.ECONNREFUSED\n}\n+}\n// ListxattrAt implements vfs.FilesystemImpl.ListxattrAt.\nfunc (fs *filesystem) ListxattrAt(ctx context.Context, rp *vfs.ResolvingPath) ([]string, error) {\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/fsimpl/tmpfs/socket_file.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 tmpfs\n+\n+import (\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n+ \"gvisor.dev/gvisor/pkg/sentry/socket/unix/transport\"\n+)\n+\n+// socketFile is a socket (=S_IFSOCK) tmpfs file.\n+type socketFile struct {\n+ inode inode\n+ ep transport.BoundEndpoint\n+}\n+\n+func (fs *filesystem) newSocketFile(creds *auth.Credentials, mode linux.FileMode, ep transport.BoundEndpoint) *inode {\n+ file := &socketFile{ep: ep}\n+ file.inode.init(file, fs, creds, mode)\n+ file.inode.nlink = 1 // from parent directory\n+ return &file.inode\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/tmpfs/tmpfs.go", "new_path": "pkg/sentry/fsimpl/tmpfs/tmpfs.go", "diff": "@@ -331,7 +331,7 @@ func (i *inode) statTo(stat *linux.Statx) {\ncase *deviceFile:\nstat.RdevMajor = impl.major\nstat.RdevMinor = impl.minor\n- case *directory, *namedPipe:\n+ case *socketFile, *directory, *namedPipe:\n// Nothing to do.\ndefault:\npanic(fmt.Sprintf(\"unknown inode type: %T\", i.impl))\n@@ -479,6 +479,8 @@ func (i *inode) direntType() uint8 {\nreturn linux.DT_DIR\ncase *symlink:\nreturn linux.DT_LNK\n+ case *socketFile:\n+ return linux.DT_SOCK\ncase *deviceFile:\nswitch impl.kind {\ncase vfs.BlockDevice:\n" } ]
Go
Apache License 2.0
google/gvisor
Add socket files to tmpfs VFS2. Updates #1476. PiperOrigin-RevId: 305024274
259,860
06.04.2020 09:50:13
25,200
4baa7e70795edbb350d55a9365807341515d3af4
Bump up acceptable sample count for flaky itimer test. Running the test 1000x almost always produces 1+ test failures where the sample count is slightly more than 60.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/itimer.cc", "new_path": "test/syscalls/linux/itimer.cc", "diff": "@@ -246,7 +246,7 @@ int TestSIGPROFFairness(absl::Duration sleep) {\n// The number of samples on the main thread should be very low as it did\n// nothing.\n- TEST_CHECK(result.main_thread_samples < 60);\n+ TEST_CHECK(result.main_thread_samples < 80);\n// Both workers should get roughly equal number of samples.\nTEST_CHECK(result.worker_samples.size() == 2);\n" } ]
Go
Apache License 2.0
google/gvisor
Bump up acceptable sample count for flaky itimer test. Running the test 1000x almost always produces 1+ test failures where the sample count is slightly more than 60. PiperOrigin-RevId: 305051754
259,885
06.04.2020 16:31:27
25,200
dd98fdd5beb7f02e7c7b3aeb4f07f5d00ffc41e7
Correctly implement magic symlinks in VFS2 procfs. Updates
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsbridge/vfs.go", "new_path": "pkg/sentry/fsbridge/vfs.go", "diff": "@@ -26,22 +26,22 @@ import (\n\"gvisor.dev/gvisor/pkg/usermem\"\n)\n-// fsFile implements File interface over vfs.FileDescription.\n+// VFSFile implements File interface over vfs.FileDescription.\n//\n// +stateify savable\n-type vfsFile struct {\n+type VFSFile struct {\nfile *vfs.FileDescription\n}\n-var _ File = (*vfsFile)(nil)\n+var _ File = (*VFSFile)(nil)\n// NewVFSFile creates a new File over fs.File.\nfunc NewVFSFile(file *vfs.FileDescription) File {\n- return &vfsFile{file: file}\n+ return &VFSFile{file: file}\n}\n// PathnameWithDeleted implements File.\n-func (f *vfsFile) PathnameWithDeleted(ctx context.Context) string {\n+func (f *VFSFile) PathnameWithDeleted(ctx context.Context) string {\nroot := vfs.RootFromContext(ctx)\ndefer root.DecRef()\n@@ -51,7 +51,7 @@ func (f *vfsFile) PathnameWithDeleted(ctx context.Context) string {\n}\n// ReadFull implements File.\n-func (f *vfsFile) ReadFull(ctx context.Context, dst usermem.IOSequence, offset int64) (int64, error) {\n+func (f *VFSFile) ReadFull(ctx context.Context, dst usermem.IOSequence, offset int64) (int64, error) {\nvar total int64\nfor dst.NumBytes() > 0 {\nn, err := f.file.PRead(ctx, dst, offset+total, vfs.ReadOptions{})\n@@ -67,12 +67,12 @@ func (f *vfsFile) ReadFull(ctx context.Context, dst usermem.IOSequence, offset i\n}\n// ConfigureMMap implements File.\n-func (f *vfsFile) ConfigureMMap(ctx context.Context, opts *memmap.MMapOpts) error {\n+func (f *VFSFile) ConfigureMMap(ctx context.Context, opts *memmap.MMapOpts) error {\nreturn f.file.ConfigureMMap(ctx, opts)\n}\n// Type implements File.\n-func (f *vfsFile) Type(ctx context.Context) (linux.FileMode, error) {\n+func (f *VFSFile) Type(ctx context.Context) (linux.FileMode, error) {\nstat, err := f.file.Stat(ctx, vfs.StatOptions{})\nif err != nil {\nreturn 0, err\n@@ -81,15 +81,21 @@ func (f *vfsFile) Type(ctx context.Context) (linux.FileMode, error) {\n}\n// IncRef implements File.\n-func (f *vfsFile) IncRef() {\n+func (f *VFSFile) IncRef() {\nf.file.IncRef()\n}\n// DecRef implements File.\n-func (f *vfsFile) DecRef() {\n+func (f *VFSFile) DecRef() {\nf.file.DecRef()\n}\n+// FileDescription returns the FileDescription represented by f. It does not\n+// take an additional reference on the returned FileDescription.\n+func (f *VFSFile) FileDescription() *vfs.FileDescription {\n+ return f.file\n+}\n+\n// fsLookup implements Lookup interface using fs.File.\n//\n// +stateify savable\n@@ -132,5 +138,5 @@ func (l *vfsLookup) OpenPath(ctx context.Context, pathname string, opts vfs.Open\nif err != nil {\nreturn nil, err\n}\n- return &vfsFile{file: fd}, nil\n+ return &VFSFile{file: fd}, nil\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/kernfs/filesystem.go", "new_path": "pkg/sentry/fsimpl/kernfs/filesystem.go", "diff": "@@ -79,16 +79,22 @@ afterSymlink:\n}\n// Resolve any symlink at current path component.\nif rp.ShouldFollowSymlink() && next.isSymlink() {\n- // TODO: VFS2 needs something extra for /proc/[pid]/fd/ \"magic symlinks\".\n- target, err := next.inode.Readlink(ctx)\n+ targetVD, targetPathname, err := next.inode.Getlink(ctx)\nif err != nil {\nreturn nil, err\n}\n- if err := rp.HandleSymlink(target); err != nil {\n+ if targetVD.Ok() {\n+ err := rp.HandleJump(targetVD)\n+ targetVD.DecRef()\n+ if err != nil {\n+ return nil, err\n+ }\n+ } else {\n+ if err := rp.HandleSymlink(targetPathname); err != nil {\nreturn nil, err\n}\n+ }\ngoto afterSymlink\n-\n}\nrp.Advance()\nreturn &next.vfsd, nil\n@@ -470,20 +476,26 @@ afterTrailingSymlink:\n}\nchildDentry := childVFSD.Impl().(*Dentry)\nchildInode := childDentry.inode\n- if rp.ShouldFollowSymlink() {\n- if childDentry.isSymlink() {\n- target, err := childInode.Readlink(ctx)\n+ if rp.ShouldFollowSymlink() && childDentry.isSymlink() {\n+ targetVD, targetPathname, err := childInode.Getlink(ctx)\nif err != nil {\nreturn nil, err\n}\n- if err := rp.HandleSymlink(target); err != nil {\n+ if targetVD.Ok() {\n+ err := rp.HandleJump(targetVD)\n+ targetVD.DecRef()\n+ if err != nil {\n+ return nil, err\n+ }\n+ } else {\n+ if err := rp.HandleSymlink(targetPathname); err != nil {\nreturn nil, err\n}\n+ }\n// rp.Final() may no longer be true since we now need to resolve the\n// symlink target.\ngoto afterTrailingSymlink\n}\n- }\nif err := childInode.CheckPermissions(ctx, rp.Credentials(), ats); err != nil {\nreturn nil, err\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/kernfs/inode_impl_util.go", "new_path": "pkg/sentry/fsimpl/kernfs/inode_impl_util.go", "diff": "@@ -181,6 +181,11 @@ func (InodeNotSymlink) Readlink(context.Context) (string, error) {\nreturn \"\", syserror.EINVAL\n}\n+// Getlink implements Inode.Getlink.\n+func (InodeNotSymlink) Getlink(context.Context) (vfs.VirtualDentry, string, error) {\n+ return vfs.VirtualDentry{}, \"\", syserror.EINVAL\n+}\n+\n// InodeAttrs partially implements the Inode interface, specifically the\n// inodeMetadata sub interface. InodeAttrs provides functionality related to\n// inode attributes.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/kernfs/kernfs.go", "new_path": "pkg/sentry/fsimpl/kernfs/kernfs.go", "diff": "@@ -414,7 +414,21 @@ type inodeDynamicLookup interface {\n}\ntype inodeSymlink interface {\n- // Readlink resolves the target of a symbolic link. If an inode is not a\n+ // Readlink returns the target of a symbolic link. If an inode is not a\n// symlink, the implementation should return EINVAL.\nReadlink(ctx context.Context) (string, error)\n+\n+ // Getlink returns the target of a symbolic link, as used by path\n+ // resolution:\n+ //\n+ // - If the inode is a \"magic link\" (a link whose target is most accurately\n+ // represented as a VirtualDentry), Getlink returns (ok VirtualDentry, \"\",\n+ // nil). A reference is taken on the returned VirtualDentry.\n+ //\n+ // - If the inode is an ordinary symlink, Getlink returns (zero-value\n+ // VirtualDentry, symlink target, nil).\n+ //\n+ // - If the inode is not a symlink, Getlink returns (zero-value\n+ // VirtualDentry, \"\", EINVAL).\n+ Getlink(ctx context.Context) (vfs.VirtualDentry, string, error)\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/kernfs/symlink.go", "new_path": "pkg/sentry/fsimpl/kernfs/symlink.go", "diff": "@@ -55,6 +55,11 @@ func (s *StaticSymlink) Readlink(_ context.Context) (string, error) {\nreturn s.target, nil\n}\n+// Getlink implements Inode.Getlink.\n+func (s *StaticSymlink) Getlink(_ context.Context) (vfs.VirtualDentry, string, error) {\n+ return vfs.VirtualDentry{}, s.target, nil\n+}\n+\n// SetStat implements Inode.SetStat not allowing inode attributes to be changed.\nfunc (*StaticSymlink) SetStat(context.Context, *vfs.Filesystem, *auth.Credentials, vfs.SetStatOptions) error {\nreturn syserror.EPERM\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/proc/task_fds.go", "new_path": "pkg/sentry/fsimpl/proc/task_fds.go", "diff": "@@ -196,6 +196,12 @@ func (s *fdSymlink) Readlink(ctx context.Context) (string, error) {\nreturn vfsObj.PathnameWithDeleted(ctx, root, s.file.VirtualDentry())\n}\n+func (s *fdSymlink) Getlink(ctx context.Context) (vfs.VirtualDentry, string, error) {\n+ vd := s.file.VirtualDentry()\n+ vd.IncRef()\n+ return vd, \"\", nil\n+}\n+\nfunc (s *fdSymlink) DecRef() {\ns.AtomicRefCount.DecRefWithDestructor(func() {\ns.Destroy()\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/proc/task_files.go", "new_path": "pkg/sentry/fsimpl/proc/task_files.go", "diff": "@@ -610,6 +610,23 @@ func (s *exeSymlink) Readlink(ctx context.Context) (string, error) {\nreturn exec.PathnameWithDeleted(ctx), nil\n}\n+// Getlink implements kernfs.Inode.Getlink.\n+func (s *exeSymlink) Getlink(ctx context.Context) (vfs.VirtualDentry, string, error) {\n+ if !kernel.ContextCanTrace(ctx, s.task, false) {\n+ return vfs.VirtualDentry{}, \"\", syserror.EACCES\n+ }\n+\n+ exec, err := s.executable()\n+ if err != nil {\n+ return vfs.VirtualDentry{}, \"\", err\n+ }\n+ defer exec.DecRef()\n+\n+ vd := exec.(*fsbridge.VFSFile).FileDescription().VirtualDentry()\n+ vd.IncRef()\n+ return vd, \"\", nil\n+}\n+\nfunc (s *exeSymlink) executable() (file fsbridge.File, err error) {\ns.task.WithMuLocked(func(t *kernel.Task) {\nmm := t.MemoryManager()\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/proc/tasks_files.go", "new_path": "pkg/sentry/fsimpl/proc/tasks_files.go", "diff": "@@ -63,6 +63,11 @@ func (s *selfSymlink) Readlink(ctx context.Context) (string, error) {\nreturn strconv.FormatUint(uint64(tgid), 10), nil\n}\n+func (s *selfSymlink) Getlink(ctx context.Context) (vfs.VirtualDentry, string, error) {\n+ target, err := s.Readlink(ctx)\n+ return vfs.VirtualDentry{}, target, err\n+}\n+\n// SetStat implements Inode.SetStat not allowing inode attributes to be changed.\nfunc (*selfSymlink) SetStat(context.Context, *vfs.Filesystem, *auth.Credentials, vfs.SetStatOptions) error {\nreturn syserror.EPERM\n@@ -101,6 +106,11 @@ func (s *threadSelfSymlink) Readlink(ctx context.Context) (string, error) {\nreturn fmt.Sprintf(\"%d/task/%d\", tgid, tid), nil\n}\n+func (s *threadSelfSymlink) Getlink(ctx context.Context) (vfs.VirtualDentry, string, error) {\n+ target, err := s.Readlink(ctx)\n+ return vfs.VirtualDentry{}, target, err\n+}\n+\n// SetStat implements Inode.SetStat not allowing inode attributes to be changed.\nfunc (*threadSelfSymlink) SetStat(context.Context, *vfs.Filesystem, *auth.Credentials, vfs.SetStatOptions) error {\nreturn syserror.EPERM\n" } ]
Go
Apache License 2.0
google/gvisor
Correctly implement magic symlinks in VFS2 procfs. Updates #1195 PiperOrigin-RevId: 305143567
259,972
06.04.2020 17:52:25
25,200
32fc11ee3e39b7ef1152825090112f4b239887c4
Sort posix service functions
[ { "change_type": "MODIFY", "old_path": "test/packetimpact/dut/posix_server.cc", "new_path": "test/packetimpact/dut/posix_server.cc", "diff": "}\nclass PosixImpl final : public posix_server::Posix::Service {\n- ::grpc::Status Socket(grpc_impl::ServerContext *context,\n- const ::posix_server::SocketRequest *request,\n- ::posix_server::SocketResponse *response) override {\n- response->set_fd(\n- socket(request->domain(), request->type(), request->protocol()));\n+ ::grpc::Status Accept(grpc_impl::ServerContext *context,\n+ const ::posix_server::AcceptRequest *request,\n+ ::posix_server::AcceptResponse *response) override {\n+ sockaddr_storage addr;\n+ socklen_t addrlen = sizeof(addr);\n+ response->set_fd(accept(request->sockfd(),\n+ reinterpret_cast<sockaddr *>(&addr), &addrlen));\nresponse->set_errno_(errno);\n- return ::grpc::Status::OK;\n+ return sockaddr_to_proto(addr, addrlen, response->mutable_addr());\n}\n::grpc::Status Bind(grpc_impl::ServerContext *context,\n@@ -119,6 +121,14 @@ class PosixImpl final : public posix_server::Posix::Service {\nreturn ::grpc::Status::OK;\n}\n+ ::grpc::Status Close(grpc_impl::ServerContext *context,\n+ const ::posix_server::CloseRequest *request,\n+ ::posix_server::CloseResponse *response) override {\n+ response->set_ret(close(request->fd()));\n+ response->set_errno_(errno);\n+ return ::grpc::Status::OK;\n+ }\n+\n::grpc::Status GetSockName(\ngrpc_impl::ServerContext *context,\nconst ::posix_server::GetSockNameRequest *request,\n@@ -139,17 +149,6 @@ class PosixImpl final : public posix_server::Posix::Service {\nreturn ::grpc::Status::OK;\n}\n- ::grpc::Status Accept(grpc_impl::ServerContext *context,\n- const ::posix_server::AcceptRequest *request,\n- ::posix_server::AcceptResponse *response) override {\n- sockaddr_storage addr;\n- socklen_t addrlen = sizeof(addr);\n- response->set_fd(accept(request->sockfd(),\n- reinterpret_cast<sockaddr *>(&addr), &addrlen));\n- response->set_errno_(errno);\n- return sockaddr_to_proto(addr, addrlen, response->mutable_addr());\n- }\n-\n::grpc::Status SetSockOpt(\ngrpc_impl::ServerContext *context,\nconst ::posix_server::SetSockOptRequest *request,\n@@ -174,10 +173,11 @@ class PosixImpl final : public posix_server::Posix::Service {\nreturn ::grpc::Status::OK;\n}\n- ::grpc::Status Close(grpc_impl::ServerContext *context,\n- const ::posix_server::CloseRequest *request,\n- ::posix_server::CloseResponse *response) override {\n- response->set_ret(close(request->fd()));\n+ ::grpc::Status Socket(grpc_impl::ServerContext *context,\n+ const ::posix_server::SocketRequest *request,\n+ ::posix_server::SocketResponse *response) override {\n+ response->set_fd(\n+ socket(request->domain(), request->type(), request->protocol()));\nresponse->set_errno_(errno);\nreturn ::grpc::Status::OK;\n}\n" }, { "change_type": "MODIFY", "old_path": "test/packetimpact/proto/posix_server.proto", "new_path": "test/packetimpact/proto/posix_server.proto", "diff": "@@ -16,17 +16,6 @@ syntax = \"proto3\";\npackage posix_server;\n-message SocketRequest {\n- int32 domain = 1;\n- int32 type = 2;\n- int32 protocol = 3;\n-}\n-\n-message SocketResponse {\n- int32 fd = 1;\n- int32 errno_ = 2; // \"errno\" may fail to compile in c++.\n-}\n-\nmessage SockaddrIn {\nint32 family = 1;\nuint32 port = 2;\n@@ -48,6 +37,23 @@ message Sockaddr {\n}\n}\n+message Timeval {\n+ int64 seconds = 1;\n+ int64 microseconds = 2;\n+}\n+\n+// Request and Response pairs for each Posix service RPC call, sorted.\n+\n+message AcceptRequest {\n+ int32 sockfd = 1;\n+}\n+\n+message AcceptResponse {\n+ int32 fd = 1;\n+ int32 errno_ = 2; // \"errno\" may fail to compile in c++.\n+ Sockaddr addr = 3;\n+}\n+\nmessage BindRequest {\nint32 sockfd = 1;\nSockaddr addr = 2;\n@@ -58,6 +64,15 @@ message BindResponse {\nint32 errno_ = 2; // \"errno\" may fail to compile in c++.\n}\n+message CloseRequest {\n+ int32 fd = 1;\n+}\n+\n+message CloseResponse {\n+ int32 ret = 1;\n+ int32 errno_ = 2; // \"errno\" may fail to compile in c++.\n+}\n+\nmessage GetSockNameRequest {\nint32 sockfd = 1;\n}\n@@ -78,16 +93,6 @@ message ListenResponse {\nint32 errno_ = 2; // \"errno\" may fail to compile in c++.\n}\n-message AcceptRequest {\n- int32 sockfd = 1;\n-}\n-\n-message AcceptResponse {\n- int32 fd = 1;\n- int32 errno_ = 2; // \"errno\" may fail to compile in c++.\n- Sockaddr addr = 3;\n-}\n-\nmessage SetSockOptRequest {\nint32 sockfd = 1;\nint32 level = 2;\n@@ -100,11 +105,6 @@ message SetSockOptResponse {\nint32 errno_ = 2; // \"errno\" may fail to compile in c++.\n}\n-message Timeval {\n- int64 seconds = 1;\n- int64 microseconds = 2;\n-}\n-\nmessage SetSockOptTimevalRequest {\nint32 sockfd = 1;\nint32 level = 2;\n@@ -117,12 +117,14 @@ message SetSockOptTimevalResponse {\nint32 errno_ = 2; // \"errno\" may fail to compile in c++.\n}\n-message CloseRequest {\n- int32 fd = 1;\n+message SocketRequest {\n+ int32 domain = 1;\n+ int32 type = 2;\n+ int32 protocol = 3;\n}\n-message CloseResponse {\n- int32 ret = 1;\n+message SocketResponse {\n+ int32 fd = 1;\nint32 errno_ = 2; // \"errno\" may fail to compile in c++.\n}\n@@ -139,16 +141,16 @@ message RecvResponse {\n}\nservice Posix {\n- // Call socket() on the DUT.\n- rpc Socket(SocketRequest) returns (SocketResponse);\n+ // Call accept() on the DUT.\n+ rpc Accept(AcceptRequest) returns (AcceptResponse);\n// Call bind() on the DUT.\nrpc Bind(BindRequest) returns (BindResponse);\n+ // Call close() on the DUT.\n+ rpc Close(CloseRequest) returns (CloseResponse);\n// Call getsockname() on the DUT.\nrpc GetSockName(GetSockNameRequest) returns (GetSockNameResponse);\n// Call listen() on the DUT.\nrpc Listen(ListenRequest) returns (ListenResponse);\n- // Call accept() on the DUT.\n- rpc Accept(AcceptRequest) returns (AcceptResponse);\n// Call setsockopt() on the DUT. You should prefer one of the other\n// SetSockOpt* functions with a more structured optval or else you may get the\n// encoding wrong, such as making a bad assumption about the server's word\n@@ -157,8 +159,8 @@ service Posix {\n// Call setsockopt() on the DUT with a Timeval optval.\nrpc SetSockOptTimeval(SetSockOptTimevalRequest)\nreturns (SetSockOptTimevalResponse);\n- // Call close() on the DUT.\n- rpc Close(CloseRequest) returns (CloseResponse);\n+ // Call socket() on the DUT.\n+ rpc Socket(SocketRequest) returns (SocketResponse);\n// Call recv() on the DUT.\nrpc Recv(RecvRequest) returns (RecvResponse);\n}\n" }, { "change_type": "MODIFY", "old_path": "test/packetimpact/testbench/dut.go", "new_path": "test/packetimpact/testbench/dut.go", "diff": "@@ -65,33 +65,6 @@ func (dut *DUT) TearDown() {\ndut.conn.Close()\n}\n-// SocketWithErrno calls socket on the DUT and returns the fd and errno.\n-func (dut *DUT) SocketWithErrno(domain, typ, proto int32) (int32, error) {\n- dut.t.Helper()\n- req := pb.SocketRequest{\n- Domain: domain,\n- Type: typ,\n- Protocol: proto,\n- }\n- ctx := context.Background()\n- resp, err := dut.posixServer.Socket(ctx, &req)\n- if err != nil {\n- dut.t.Fatalf(\"failed to call Socket: %s\", err)\n- }\n- return resp.GetFd(), syscall.Errno(resp.GetErrno_())\n-}\n-\n-// Socket calls socket on the DUT and returns the file descriptor. If socket\n-// fails on the DUT, the test ends.\n-func (dut *DUT) Socket(domain, typ, proto int32) int32 {\n- dut.t.Helper()\n- fd, err := dut.SocketWithErrno(domain, typ, proto)\n- if fd < 0 {\n- dut.t.Fatalf(\"failed to create socket: %s\", err)\n- }\n- return fd\n-}\n-\nfunc (dut *DUT) sockaddrToProto(sa unix.Sockaddr) *pb.Sockaddr {\ndut.t.Helper()\nswitch s := sa.(type) {\n@@ -142,6 +115,88 @@ func (dut *DUT) protoToSockaddr(sa *pb.Sockaddr) unix.Sockaddr {\nreturn nil\n}\n+// CreateBoundSocket makes a new socket on the DUT, with type typ and protocol\n+// proto, and bound to the IP address addr. Returns the new file descriptor and\n+// the port that was selected on the DUT.\n+func (dut *DUT) CreateBoundSocket(typ, proto int32, addr net.IP) (int32, uint16) {\n+ dut.t.Helper()\n+ var fd int32\n+ if addr.To4() != nil {\n+ fd = dut.Socket(unix.AF_INET, typ, proto)\n+ sa := unix.SockaddrInet4{}\n+ copy(sa.Addr[:], addr.To4())\n+ dut.Bind(fd, &sa)\n+ } else if addr.To16() != nil {\n+ fd = dut.Socket(unix.AF_INET6, typ, proto)\n+ sa := unix.SockaddrInet6{}\n+ copy(sa.Addr[:], addr.To16())\n+ dut.Bind(fd, &sa)\n+ } else {\n+ dut.t.Fatal(\"unknown ip addr type for remoteIP\")\n+ }\n+ sa := dut.GetSockName(fd)\n+ var port int\n+ switch s := sa.(type) {\n+ case *unix.SockaddrInet4:\n+ port = s.Port\n+ case *unix.SockaddrInet6:\n+ port = s.Port\n+ default:\n+ dut.t.Fatalf(\"unknown sockaddr type from getsockname: %t\", sa)\n+ }\n+ return fd, uint16(port)\n+}\n+\n+// CreateListener makes a new TCP connection. If it fails, the test ends.\n+func (dut *DUT) CreateListener(typ, proto, backlog int32) (int32, uint16) {\n+ fd, remotePort := dut.CreateBoundSocket(typ, proto, net.ParseIP(*remoteIPv4))\n+ dut.Listen(fd, backlog)\n+ return fd, remotePort\n+}\n+\n+// All the functions that make gRPC calls to the Posix service are below, sorted\n+// alphabetically.\n+\n+// Accept calls accept on the DUT and causes a fatal test failure if it doesn't\n+// succeed. If more control over the timeout or error handling is needed, use\n+// AcceptWithErrno.\n+func (dut *DUT) Accept(sockfd int32) (int32, unix.Sockaddr) {\n+ dut.t.Helper()\n+ ctx, cancel := context.WithTimeout(context.Background(), *rpcTimeout)\n+ defer cancel()\n+ fd, sa, err := dut.AcceptWithErrno(ctx, sockfd)\n+ if fd < 0 {\n+ dut.t.Fatalf(\"failed to accept: %s\", err)\n+ }\n+ return fd, sa\n+}\n+\n+// AcceptWithErrno calls accept on the DUT.\n+func (dut *DUT) AcceptWithErrno(ctx context.Context, sockfd int32) (int32, unix.Sockaddr, error) {\n+ dut.t.Helper()\n+ req := pb.AcceptRequest{\n+ Sockfd: sockfd,\n+ }\n+ resp, err := dut.posixServer.Accept(ctx, &req)\n+ if err != nil {\n+ dut.t.Fatalf(\"failed to call Accept: %s\", err)\n+ }\n+ return resp.GetFd(), dut.protoToSockaddr(resp.GetAddr()), syscall.Errno(resp.GetErrno_())\n+}\n+\n+// Bind calls bind on the DUT and causes a fatal test failure if it doesn't\n+// succeed. If more control over the timeout or error handling is\n+// needed, use BindWithErrno.\n+func (dut *DUT) Bind(fd int32, sa unix.Sockaddr) {\n+ dut.t.Helper()\n+ ctx, cancel := context.WithTimeout(context.Background(), *rpcTimeout)\n+ defer cancel()\n+ ret, err := dut.BindWithErrno(ctx, fd, sa)\n+ if ret != 0 {\n+ dut.t.Fatalf(\"failed to bind socket: %s\", err)\n+ }\n+}\n+\n// BindWithErrno calls bind on the DUT.\nfunc (dut *DUT) BindWithErrno(ctx context.Context, fd int32, sa unix.Sockaddr) (int32, error) {\ndut.t.Helper()\n@@ -156,30 +211,30 @@ func (dut *DUT) BindWithErrno(ctx context.Context, fd int32, sa unix.Sockaddr) (\nreturn resp.GetRet(), syscall.Errno(resp.GetErrno_())\n}\n-// Bind calls bind on the DUT and causes a fatal test failure if it doesn't\n-// succeed. If more control over the timeout or error handling is\n-// needed, use BindWithErrno.\n-func (dut *DUT) Bind(fd int32, sa unix.Sockaddr) {\n+// Close calls close on the DUT and causes a fatal test failure if it doesn't\n+// succeed. If more control over the timeout or error handling is needed, use\n+// CloseWithErrno.\n+func (dut *DUT) Close(fd int32) {\ndut.t.Helper()\nctx, cancel := context.WithTimeout(context.Background(), *rpcTimeout)\ndefer cancel()\n- ret, err := dut.BindWithErrno(ctx, fd, sa)\n+ ret, err := dut.CloseWithErrno(ctx, fd)\nif ret != 0 {\n- dut.t.Fatalf(\"failed to bind socket: %s\", err)\n+ dut.t.Fatalf(\"failed to close: %s\", err)\n}\n}\n-// GetSockNameWithErrno calls getsockname on the DUT.\n-func (dut *DUT) GetSockNameWithErrno(ctx context.Context, sockfd int32) (int32, unix.Sockaddr, error) {\n+// CloseWithErrno calls close on the DUT.\n+func (dut *DUT) CloseWithErrno(ctx context.Context, fd int32) (int32, error) {\ndut.t.Helper()\n- req := pb.GetSockNameRequest{\n- Sockfd: sockfd,\n+ req := pb.CloseRequest{\n+ Fd: fd,\n}\n- resp, err := dut.posixServer.GetSockName(ctx, &req)\n+ resp, err := dut.posixServer.Close(ctx, &req)\nif err != nil {\n- dut.t.Fatalf(\"failed to call Bind: %s\", err)\n+ dut.t.Fatalf(\"failed to call Close: %s\", err)\n}\n- return resp.GetRet(), dut.protoToSockaddr(resp.GetAddr()), syscall.Errno(resp.GetErrno_())\n+ return resp.GetRet(), syscall.Errno(resp.GetErrno_())\n}\n// GetSockName calls getsockname on the DUT and causes a fatal test failure if\n@@ -196,18 +251,17 @@ func (dut *DUT) GetSockName(sockfd int32) unix.Sockaddr {\nreturn sa\n}\n-// ListenWithErrno calls listen on the DUT.\n-func (dut *DUT) ListenWithErrno(ctx context.Context, sockfd, backlog int32) (int32, error) {\n+// GetSockNameWithErrno calls getsockname on the DUT.\n+func (dut *DUT) GetSockNameWithErrno(ctx context.Context, sockfd int32) (int32, unix.Sockaddr, error) {\ndut.t.Helper()\n- req := pb.ListenRequest{\n+ req := pb.GetSockNameRequest{\nSockfd: sockfd,\n- Backlog: backlog,\n}\n- resp, err := dut.posixServer.Listen(ctx, &req)\n+ resp, err := dut.posixServer.GetSockName(ctx, &req)\nif err != nil {\n- dut.t.Fatalf(\"failed to call Listen: %s\", err)\n+ dut.t.Fatalf(\"failed to call Bind: %s\", err)\n}\n- return resp.GetRet(), syscall.Errno(resp.GetErrno_())\n+ return resp.GetRet(), dut.protoToSockaddr(resp.GetAddr()), syscall.Errno(resp.GetErrno_())\n}\n// Listen calls listen on the DUT and causes a fatal test failure if it doesn't\n@@ -223,31 +277,33 @@ func (dut *DUT) Listen(sockfd, backlog int32) {\n}\n}\n-// AcceptWithErrno calls accept on the DUT.\n-func (dut *DUT) AcceptWithErrno(ctx context.Context, sockfd int32) (int32, unix.Sockaddr, error) {\n+// ListenWithErrno calls listen on the DUT.\n+func (dut *DUT) ListenWithErrno(ctx context.Context, sockfd, backlog int32) (int32, error) {\ndut.t.Helper()\n- req := pb.AcceptRequest{\n+ req := pb.ListenRequest{\nSockfd: sockfd,\n+ Backlog: backlog,\n}\n- resp, err := dut.posixServer.Accept(ctx, &req)\n+ resp, err := dut.posixServer.Listen(ctx, &req)\nif err != nil {\n- dut.t.Fatalf(\"failed to call Accept: %s\", err)\n+ dut.t.Fatalf(\"failed to call Listen: %s\", err)\n}\n- return resp.GetFd(), dut.protoToSockaddr(resp.GetAddr()), syscall.Errno(resp.GetErrno_())\n+ return resp.GetRet(), syscall.Errno(resp.GetErrno_())\n}\n-// Accept calls accept on the DUT and causes a fatal test failure if it doesn't\n-// succeed. If more control over the timeout or error handling is needed, use\n-// AcceptWithErrno.\n-func (dut *DUT) Accept(sockfd int32) (int32, unix.Sockaddr) {\n+// SetSockOpt calls setsockopt on the DUT and causes a fatal test failure if it\n+// doesn't succeed. If more control over the timeout or error handling is\n+// needed, use SetSockOptWithErrno. Because endianess and the width of values\n+// might differ between the testbench and DUT architectures, prefer to use a\n+// more specific SetSockOptXxx function.\n+func (dut *DUT) SetSockOpt(sockfd, level, optname int32, optval []byte) {\ndut.t.Helper()\nctx, cancel := context.WithTimeout(context.Background(), *rpcTimeout)\ndefer cancel()\n- fd, sa, err := dut.AcceptWithErrno(ctx, sockfd)\n- if fd < 0 {\n- dut.t.Fatalf(\"failed to accept: %s\", err)\n+ ret, err := dut.SetSockOptWithErrno(ctx, sockfd, level, optname, optval)\n+ if ret != 0 {\n+ dut.t.Fatalf(\"failed to SetSockOpt: %s\", err)\n}\n- return fd, sa\n}\n// SetSockOptWithErrno calls setsockopt on the DUT. Because endianess and the\n@@ -268,18 +324,16 @@ func (dut *DUT) SetSockOptWithErrno(ctx context.Context, sockfd, level, optname\nreturn resp.GetRet(), syscall.Errno(resp.GetErrno_())\n}\n-// SetSockOpt calls setsockopt on the DUT and causes a fatal test failure if it\n-// doesn't succeed. If more control over the timeout or error handling is\n-// needed, use SetSockOptWithErrno. Because endianess and the width of values\n-// might differ between the testbench and DUT architectures, prefer to use a\n-// more specific SetSockOptXxx function.\n-func (dut *DUT) SetSockOpt(sockfd, level, optname int32, optval []byte) {\n+// SetSockOptTimeval calls setsockopt on the DUT and causes a fatal test failure\n+// if it doesn't succeed. If more control over the timeout or error handling is\n+// needed, use SetSockOptTimevalWithErrno.\n+func (dut *DUT) SetSockOptTimeval(sockfd, level, optname int32, tv *unix.Timeval) {\ndut.t.Helper()\nctx, cancel := context.WithTimeout(context.Background(), *rpcTimeout)\ndefer cancel()\n- ret, err := dut.SetSockOptWithErrno(ctx, sockfd, level, optname, optval)\n+ ret, err := dut.SetSockOptTimevalWithErrno(ctx, sockfd, level, optname, tv)\nif ret != 0 {\n- dut.t.Fatalf(\"failed to SetSockOpt: %s\", err)\n+ dut.t.Fatalf(\"failed to SetSockOptTimeval: %s\", err)\n}\n}\n@@ -304,32 +358,31 @@ func (dut *DUT) SetSockOptTimevalWithErrno(ctx context.Context, sockfd, level, o\nreturn resp.GetRet(), syscall.Errno(resp.GetErrno_())\n}\n-// SetSockOptTimeval calls setsockopt on the DUT and causes a fatal test failure\n-// if it doesn't succeed. If more control over the timeout or error handling is\n-// needed, use SetSockOptTimevalWithErrno.\n-func (dut *DUT) SetSockOptTimeval(sockfd, level, optname int32, tv *unix.Timeval) {\n+// Socket calls socket on the DUT and returns the file descriptor. If socket\n+// fails on the DUT, the test ends.\n+func (dut *DUT) Socket(domain, typ, proto int32) int32 {\ndut.t.Helper()\n- ctx, cancel := context.WithTimeout(context.Background(), *rpcTimeout)\n- defer cancel()\n- ret, err := dut.SetSockOptTimevalWithErrno(ctx, sockfd, level, optname, tv)\n- if ret != 0 {\n- dut.t.Fatalf(\"failed to SetSockOptTimeval: %s\", err)\n+ fd, err := dut.SocketWithErrno(domain, typ, proto)\n+ if fd < 0 {\n+ dut.t.Fatalf(\"failed to create socket: %s\", err)\n}\n+ return fd\n}\n-// RecvWithErrno calls recv on the DUT.\n-func (dut *DUT) RecvWithErrno(ctx context.Context, sockfd, len, flags int32) (int32, []byte, error) {\n+// SocketWithErrno calls socket on the DUT and returns the fd and errno.\n+func (dut *DUT) SocketWithErrno(domain, typ, proto int32) (int32, error) {\ndut.t.Helper()\n- req := pb.RecvRequest{\n- Sockfd: sockfd,\n- Len: len,\n- Flags: flags,\n+ req := pb.SocketRequest{\n+ Domain: domain,\n+ Type: typ,\n+ Protocol: proto,\n}\n- resp, err := dut.posixServer.Recv(ctx, &req)\n+ ctx := context.Background()\n+ resp, err := dut.posixServer.Socket(ctx, &req)\nif err != nil {\n- dut.t.Fatalf(\"failed to call Recv: %s\", err)\n+ dut.t.Fatalf(\"failed to call Socket: %s\", err)\n}\n- return resp.GetRet(), resp.GetBuf(), syscall.Errno(resp.GetErrno_())\n+ return resp.GetFd(), syscall.Errno(resp.GetErrno_())\n}\n// Recv calls recv on the DUT and causes a fatal test failure if it doesn't\n@@ -346,67 +399,17 @@ func (dut *DUT) Recv(sockfd, len, flags int32) []byte {\nreturn buf\n}\n-// CloseWithErrno calls close on the DUT.\n-func (dut *DUT) CloseWithErrno(ctx context.Context, fd int32) (int32, error) {\n+// RecvWithErrno calls recv on the DUT.\n+func (dut *DUT) RecvWithErrno(ctx context.Context, sockfd, len, flags int32) (int32, []byte, error) {\ndut.t.Helper()\n- req := pb.CloseRequest{\n- Fd: fd,\n+ req := pb.RecvRequest{\n+ Sockfd: sockfd,\n+ Len: len,\n+ Flags: flags,\n}\n- resp, err := dut.posixServer.Close(ctx, &req)\n+ resp, err := dut.posixServer.Recv(ctx, &req)\nif err != nil {\n- dut.t.Fatalf(\"failed to call Close: %s\", err)\n- }\n- return resp.GetRet(), syscall.Errno(resp.GetErrno_())\n-}\n-\n-// Close calls close on the DUT and causes a fatal test failure if it doesn't\n-// succeed. If more control over the timeout or error handling is needed, use\n-// CloseWithErrno.\n-func (dut *DUT) Close(fd int32) {\n- dut.t.Helper()\n- ctx, cancel := context.WithTimeout(context.Background(), *rpcTimeout)\n- defer cancel()\n- ret, err := dut.CloseWithErrno(ctx, fd)\n- if ret != 0 {\n- dut.t.Fatalf(\"failed to close: %s\", err)\n- }\n-}\n-\n-// CreateBoundSocket makes a new socket on the DUT, with type typ and protocol\n-// proto, and bound to the IP address addr. Returns the new file descriptor and\n-// the port that was selected on the DUT.\n-func (dut *DUT) CreateBoundSocket(typ, proto int32, addr net.IP) (int32, uint16) {\n- dut.t.Helper()\n- var fd int32\n- if addr.To4() != nil {\n- fd = dut.Socket(unix.AF_INET, typ, proto)\n- sa := unix.SockaddrInet4{}\n- copy(sa.Addr[:], addr.To4())\n- dut.Bind(fd, &sa)\n- } else if addr.To16() != nil {\n- fd = dut.Socket(unix.AF_INET6, typ, proto)\n- sa := unix.SockaddrInet6{}\n- copy(sa.Addr[:], addr.To16())\n- dut.Bind(fd, &sa)\n- } else {\n- dut.t.Fatal(\"unknown ip addr type for remoteIP\")\n- }\n- sa := dut.GetSockName(fd)\n- var port int\n- switch s := sa.(type) {\n- case *unix.SockaddrInet4:\n- port = s.Port\n- case *unix.SockaddrInet6:\n- port = s.Port\n- default:\n- dut.t.Fatalf(\"unknown sockaddr type from getsockname: %t\", sa)\n- }\n- return fd, uint16(port)\n+ dut.t.Fatalf(\"failed to call Recv: %s\", err)\n}\n-\n-// CreateListener makes a new TCP connection. If it fails, the test ends.\n-func (dut *DUT) CreateListener(typ, proto, backlog int32) (int32, uint16) {\n- fd, remotePort := dut.CreateBoundSocket(typ, proto, net.ParseIP(*remoteIPv4))\n- dut.Listen(fd, backlog)\n- return fd, remotePort\n+ return resp.GetRet(), resp.GetBuf(), syscall.Errno(resp.GetErrno_())\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Sort posix service functions PiperOrigin-RevId: 305157179
259,860
06.04.2020 20:07:32
25,200
51e461cf9c49f6ad5a9a68d93c5928647aae11d8
Add concurrency guarantees to p9 extended attribute methods.
[ { "change_type": "MODIFY", "old_path": "pkg/p9/file.go", "new_path": "pkg/p9/file.go", "diff": "@@ -97,12 +97,12 @@ type File interface {\n// free to ignore the hint entirely (i.e. the value returned may be larger\n// than size). All size checking is done independently at the syscall layer.\n//\n- // TODO(b/127675828): Determine concurrency guarantees once implemented.\n+ // On the server, GetXattr has a read concurrency guarantee.\nGetXattr(name string, size uint64) (string, error)\n// SetXattr sets extended attributes on this node.\n//\n- // TODO(b/127675828): Determine concurrency guarantees once implemented.\n+ // On the server, SetXattr has a write concurrency guarantee.\nSetXattr(name, value string, flags uint32) error\n// ListXattr lists the names of the extended attributes on this node.\n@@ -113,12 +113,12 @@ type File interface {\n// free to ignore the hint entirely (i.e. the value returned may be larger\n// than size). All size checking is done independently at the syscall layer.\n//\n- // TODO(b/148303075): Determine concurrency guarantees once implemented.\n+ // On the server, ListXattr has a read concurrency guarantee.\nListXattr(size uint64) (map[string]struct{}, error)\n// RemoveXattr removes extended attributes on this node.\n//\n- // TODO(b/148303075): Determine concurrency guarantees once implemented.\n+ // On the server, RemoveXattr has a write concurrency guarantee.\nRemoveXattr(name string) error\n// Allocate allows the caller to directly manipulate the allocated disk space\n" }, { "change_type": "MODIFY", "old_path": "pkg/p9/handlers.go", "new_path": "pkg/p9/handlers.go", "diff": "@@ -920,8 +920,15 @@ func (t *Tgetxattr) handle(cs *connState) message {\n}\ndefer ref.DecRef()\n- val, err := ref.file.GetXattr(t.Name, t.Size)\n- if err != nil {\n+ var val string\n+ if err := ref.safelyRead(func() (err error) {\n+ // Don't allow getxattr on files that have been deleted.\n+ if ref.isDeleted() {\n+ return syscall.EINVAL\n+ }\n+ val, err = ref.file.GetXattr(t.Name, t.Size)\n+ return err\n+ }); err != nil {\nreturn newErr(err)\n}\nreturn &Rgetxattr{Value: val}\n@@ -935,7 +942,13 @@ func (t *Tsetxattr) handle(cs *connState) message {\n}\ndefer ref.DecRef()\n- if err := ref.file.SetXattr(t.Name, t.Value, t.Flags); err != nil {\n+ if err := ref.safelyWrite(func() error {\n+ // Don't allow setxattr on files that have been deleted.\n+ if ref.isDeleted() {\n+ return syscall.EINVAL\n+ }\n+ return ref.file.SetXattr(t.Name, t.Value, t.Flags)\n+ }); err != nil {\nreturn newErr(err)\n}\nreturn &Rsetxattr{}\n@@ -949,10 +962,18 @@ func (t *Tlistxattr) handle(cs *connState) message {\n}\ndefer ref.DecRef()\n- xattrs, err := ref.file.ListXattr(t.Size)\n- if err != nil {\n+ var xattrs map[string]struct{}\n+ if err := ref.safelyRead(func() (err error) {\n+ // Don't allow listxattr on files that have been deleted.\n+ if ref.isDeleted() {\n+ return syscall.EINVAL\n+ }\n+ xattrs, err = ref.file.ListXattr(t.Size)\n+ return err\n+ }); err != nil {\nreturn newErr(err)\n}\n+\nxattrList := make([]string, 0, len(xattrs))\nfor x := range xattrs {\nxattrList = append(xattrList, x)\n@@ -968,7 +989,13 @@ func (t *Tremovexattr) handle(cs *connState) message {\n}\ndefer ref.DecRef()\n- if err := ref.file.RemoveXattr(t.Name); err != nil {\n+ if err := ref.safelyWrite(func() error {\n+ // Don't allow removexattr on files that have been deleted.\n+ if ref.isDeleted() {\n+ return syscall.EINVAL\n+ }\n+ return ref.file.RemoveXattr(t.Name)\n+ }); err != nil {\nreturn newErr(err)\n}\nreturn &Rremovexattr{}\n" } ]
Go
Apache License 2.0
google/gvisor
Add concurrency guarantees to p9 extended attribute methods. PiperOrigin-RevId: 305171772
259,992
07.04.2020 09:40:38
25,200
94319a8241cb299edc812024d6132b7a3819a4dc
Make gofer.dentry.destroyLocked idempotent gofer operations accumulate dentries touched in a slice to call checkCachingLocked on them when the operation is over. In case the same dentry is touched multiple times during the operation, checkCachingLocked, and consequently destroyLocked, may be called more than once for the same dentry. Updates
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/gofer/BUILD", "new_path": "pkg/sentry/fsimpl/gofer/BUILD", "diff": "-load(\"//tools:defs.bzl\", \"go_library\")\n+load(\"//tools:defs.bzl\", \"go_library\", \"go_test\")\nload(\"//tools/go_generics:defs.bzl\", \"go_template_instance\")\nlicenses([\"notice\"])\n@@ -54,3 +54,13 @@ go_library(\n\"//pkg/usermem\",\n],\n)\n+\n+go_test(\n+ name = \"gofer_test\",\n+ srcs = [\"gofer_test.go\"],\n+ library = \":gofer\",\n+ deps = [\n+ \"//pkg/p9\",\n+ \"//pkg/sentry/contexttest\",\n+ ],\n+)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/gofer/gofer.go", "new_path": "pkg/sentry/fsimpl/gofer/gofer.go", "diff": "@@ -444,7 +444,8 @@ type dentry struct {\n// refs is the reference count. Each dentry holds a reference on its\n// parent, even if disowned. refs is accessed using atomic memory\n- // operations.\n+ // operations. When refs reaches 0, the dentry may be added to the cache or\n+ // destroyed. If refs==-1 the dentry has already been destroyed.\nrefs int64\n// fs is the owning filesystem. fs is immutable.\n@@ -860,7 +861,7 @@ func (d *dentry) IncRef() {\nfunc (d *dentry) TryIncRef() bool {\nfor {\nrefs := atomic.LoadInt64(&d.refs)\n- if refs == 0 {\n+ if refs <= 0 {\nreturn false\n}\nif atomic.CompareAndSwapInt64(&d.refs, refs, refs+1) {\n@@ -883,13 +884,20 @@ func (d *dentry) DecRef() {\n// checkCachingLocked should be called after d's reference count becomes 0 or it\n// becomes disowned.\n//\n+// It may be called on a destroyed dentry. For example,\n+// renameMu[R]UnlockAndCheckCaching may call checkCachingLocked multiple times\n+// for the same dentry when the dentry is visited more than once in the same\n+// operation. One of the calls may destroy the dentry, so subsequent calls will\n+// do nothing.\n+//\n// Preconditions: d.fs.renameMu must be locked for writing.\nfunc (d *dentry) checkCachingLocked() {\n// Dentries with a non-zero reference count must be retained. (The only way\n// to obtain a reference on a dentry with zero references is via path\n// resolution, which requires renameMu, so if d.refs is zero then it will\n// remain zero while we hold renameMu for writing.)\n- if atomic.LoadInt64(&d.refs) != 0 {\n+ refs := atomic.LoadInt64(&d.refs)\n+ if refs > 0 {\nif d.cached {\nd.fs.cachedDentries.Remove(d)\nd.fs.cachedDentriesLen--\n@@ -897,6 +905,10 @@ func (d *dentry) checkCachingLocked() {\n}\nreturn\n}\n+ if refs == -1 {\n+ // Dentry has already been destroyed.\n+ return\n+ }\n// Non-child dentries with zero references are no longer reachable by path\n// resolution and should be dropped immediately.\nif d.vfsd.Parent() == nil || d.vfsd.IsDisowned() {\n@@ -949,9 +961,22 @@ func (d *dentry) checkCachingLocked() {\n}\n}\n+// destroyLocked destroys the dentry. It may flushes dirty pages from cache,\n+// close p9 file and remove reference on parent dentry.\n+//\n// Preconditions: d.fs.renameMu must be locked for writing. d.refs == 0. d is\n// not a child dentry.\nfunc (d *dentry) destroyLocked() {\n+ switch atomic.LoadInt64(&d.refs) {\n+ case 0:\n+ // Mark the dentry destroyed.\n+ atomic.StoreInt64(&d.refs, -1)\n+ case -1:\n+ panic(\"dentry.destroyLocked() called on already destroyed dentry\")\n+ default:\n+ panic(\"dentry.destroyLocked() called with references on the dentry\")\n+ }\n+\nctx := context.Background()\nd.handleMu.Lock()\nif !d.handle.file.isNil() {\n@@ -971,7 +996,10 @@ func (d *dentry) destroyLocked() {\nd.handle.close(ctx)\n}\nd.handleMu.Unlock()\n+ if !d.file.isNil() {\nd.file.close(ctx)\n+ d.file = p9file{}\n+ }\n// Remove d from the set of all dentries.\nd.fs.syncMu.Lock()\ndelete(d.fs.dentries, d)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/fsimpl/gofer/gofer_test.go", "diff": "+// Copyright 2020 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 gofer\n+\n+import (\n+ \"sync/atomic\"\n+ \"testing\"\n+\n+ \"gvisor.dev/gvisor/pkg/p9\"\n+ \"gvisor.dev/gvisor/pkg/sentry/contexttest\"\n+)\n+\n+func TestDestroyIdempotent(t *testing.T) {\n+ fs := filesystem{\n+ dentries: make(map[*dentry]struct{}),\n+ opts: filesystemOptions{\n+ // Test relies on no dentry being held in the cache.\n+ maxCachedDentries: 0,\n+ },\n+ }\n+\n+ ctx := contexttest.Context(t)\n+ attr := &p9.Attr{\n+ Mode: p9.ModeRegular,\n+ }\n+ mask := p9.AttrMask{\n+ Mode: true,\n+ Size: true,\n+ }\n+ parent, err := fs.newDentry(ctx, p9file{}, p9.QID{}, mask, attr)\n+ if err != nil {\n+ t.Fatalf(\"fs.newDentry(): %v\", err)\n+ }\n+\n+ child, err := fs.newDentry(ctx, p9file{}, p9.QID{}, mask, attr)\n+ if err != nil {\n+ t.Fatalf(\"fs.newDentry(): %v\", err)\n+ }\n+ parent.IncRef() // reference held by child on its parent.\n+ parent.vfsd.InsertChild(&child.vfsd, \"child\")\n+\n+ child.checkCachingLocked()\n+ if got := atomic.LoadInt64(&child.refs); got != -1 {\n+ t.Fatalf(\"child.refs=%d, want: -1\", got)\n+ }\n+ // Parent will also be destroyed when child reference is removed.\n+ if got := atomic.LoadInt64(&parent.refs); got != -1 {\n+ t.Fatalf(\"parent.refs=%d, want: -1\", got)\n+ }\n+ child.checkCachingLocked()\n+ child.checkCachingLocked()\n+}\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/open.cc", "new_path": "test/syscalls/linux/open.cc", "diff": "@@ -186,6 +186,28 @@ TEST_F(OpenTest, OpenNoFollowStillFollowsLinksInPath) {\nASSERT_NO_ERRNO_AND_VALUE(Open(path_via_symlink, O_RDONLY | O_NOFOLLOW));\n}\n+// Test that open(2) can follow symlinks that point back to the same tree.\n+// Test sets up files as follows:\n+// root/child/symlink => redirects to ../..\n+// root/child/target => regular file\n+//\n+// open(\"root/child/symlink/root/child/file\")\n+TEST_F(OpenTest, SymlinkRecurse) {\n+ auto root =\n+ ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDirIn(GetAbsoluteTestTmpdir()));\n+ auto child = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDirIn(root.path()));\n+ auto symlink = ASSERT_NO_ERRNO_AND_VALUE(\n+ TempPath::CreateSymlinkTo(child.path(), \"../..\"));\n+ auto target = ASSERT_NO_ERRNO_AND_VALUE(\n+ TempPath::CreateFileWith(child.path(), \"abc\", 0644));\n+ auto path_via_symlink =\n+ JoinPath(symlink.path(), Basename(root.path()), Basename(child.path()),\n+ Basename(target.path()));\n+ const auto contents =\n+ ASSERT_NO_ERRNO_AND_VALUE(GetContents(path_via_symlink));\n+ ASSERT_EQ(contents, \"abc\");\n+}\n+\nTEST_F(OpenTest, Fault) {\nchar* totally_not_null = nullptr;\nASSERT_THAT(open(totally_not_null, O_RDONLY), SyscallFailsWithErrno(EFAULT));\n" } ]
Go
Apache License 2.0
google/gvisor
Make gofer.dentry.destroyLocked idempotent gofer operations accumulate dentries touched in a slice to call checkCachingLocked on them when the operation is over. In case the same dentry is touched multiple times during the operation, checkCachingLocked, and consequently destroyLocked, may be called more than once for the same dentry. Updates #1198 PiperOrigin-RevId: 305276819
259,854
06.04.2020 16:27:38
25,200
dc2f198866c5fd8162a79978eb3633975d3ba11f
Update networking security blog post
[ { "change_type": "MODIFY", "old_path": "content/blog/2_networking_security/index.md", "new_path": "content/blog/2_networking_security/index.md", "diff": "@@ -37,7 +37,7 @@ Figure 1: Netstack and gVisor\n## Writing a network stack\n-Netstack was written from scratch specifically for gVisor. There are now other users (e.g. [Fuchsia](https://fuchsia.googlesource.com/fuchsia/+/refs/heads/master/src/connectivity/network/netstack/)), but they came later. As we discussed, a custom network stack has enabled a variety of security-related goals which would not have been possible any other way. This came at a cost though. Network stacks are complex and writing a new one comes with many challenges, mostly related to application compatibility and performance.\n+Netstack was written from scratch specifically for gVisor. Because Netstack was designed and implemented to be modular, flexible and self-contained, there are now several more projects using Netstack in creative and exciting ways. As we discussed, a custom network stack has enabled a variety of security-related goals which would not have been possible any other way. This came at a cost though. Network stacks are complex and writing a new one comes with many challenges, mostly related to application compatibility and performance.\nCompatibility issues typically come in two forms: missing features, and features with behavior that differs from Linux (usually due to bugs). Both of these are inevitable in an implementation of a complex system spanning many quickly evolving and ambiguous standards. However, we have invested heavily in this area, and the vast majority of applications have no issues using Netstack. For example, [we now support setting 34 different socket options](https://github.com/google/gvisor/blob/815df2959a76e4a19f5882e40402b9bbca9e70be/pkg/sentry/socket/netstack/netstack.go#L830-L1764) versus [only 7 in our initial git commit](https://github.com/google/gvisor/blob/d02b74a5dcfed4bfc8f2f8e545bca4d2afabb296/pkg/sentry/socket/epsocket/epsocket.go#L445-L702). We are continuing to make good progress in this area.\n" } ]
Go
Apache License 2.0
google/gvisor
Update networking security blog post
260,003
07.04.2020 13:27:26
25,200
71770e56629339c9853466e994b78b172bc668a9
mkdir test: Address TODOs and re-enable a test.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/mkdir.cc", "new_path": "test/syscalls/linux/mkdir.cc", "diff": "@@ -36,21 +36,12 @@ class MkdirTest : public ::testing::Test {\n// TearDown unlinks created files.\nvoid TearDown() override {\n- // FIXME(edahlgren): We don't currently implement rmdir.\n- // We do this unconditionally because there's no harm in trying.\n- rmdir(dirname_.c_str());\n+ EXPECT_THAT(rmdir(dirname_.c_str()), SyscallSucceeds());\n}\nstd::string dirname_;\n};\n-TEST_F(MkdirTest, DISABLED_CanCreateReadbleDir) {\n- ASSERT_THAT(mkdir(dirname_.c_str(), 0444), SyscallSucceeds());\n- ASSERT_THAT(\n- open(JoinPath(dirname_, \"anything\").c_str(), O_RDWR | O_CREAT, 0666),\n- SyscallFailsWithErrno(EACCES));\n-}\n-\nTEST_F(MkdirTest, CanCreateWritableDir) {\nASSERT_THAT(mkdir(dirname_.c_str(), 0777), SyscallSucceeds());\nstd::string filename = JoinPath(dirname_, \"anything\");\n@@ -84,10 +75,11 @@ TEST_F(MkdirTest, FailsOnDirWithoutWritePerms) {\nASSERT_NO_ERRNO(SetCapability(CAP_DAC_OVERRIDE, false));\nASSERT_NO_ERRNO(SetCapability(CAP_DAC_READ_SEARCH, false));\n- auto parent = ASSERT_NO_ERRNO_AND_VALUE(\n- TempPath::CreateDirWith(GetAbsoluteTestTmpdir(), 0555));\n- auto dir = JoinPath(parent.path(), \"foo\");\n- ASSERT_THAT(mkdir(dir.c_str(), 0777), SyscallFailsWithErrno(EACCES));\n+ ASSERT_THAT(mkdir(dirname_.c_str(), 0555), SyscallSucceeds());\n+ auto dir = JoinPath(dirname_.c_str(), \"foo\");\n+ EXPECT_THAT(mkdir(dir.c_str(), 0777), SyscallFailsWithErrno(EACCES));\n+ EXPECT_THAT(open(JoinPath(dirname_, \"file\").c_str(), O_RDWR | O_CREAT, 0666),\n+ SyscallFailsWithErrno(EACCES));\n}\n} // namespace\n" } ]
Go
Apache License 2.0
google/gvisor
mkdir test: Address TODOs and re-enable a test. PiperOrigin-RevId: 305328184
260,004
07.04.2020 13:35:58
25,200
6db55a5bd8933b217d285018ed2187812ebae6ef
Require that IPv6 headers be in the first fragment Test: header_test.TestIPv6ExtHdrIter ipv6_test.TestReceiveIPv6Fragments Updates
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/header/ipv6_extension_headers.go", "new_path": "pkg/tcpip/header/ipv6_extension_headers.go", "diff": "@@ -395,18 +395,25 @@ func MakeIPv6PayloadIterator(nextHdrIdentifier IPv6ExtensionHeaderIdentifier, pa\n}\n// AsRawHeader returns the remaining payload of i as a raw header and\n-// completes the iterator.\n+// optionally consumes the iterator.\n//\n-// Calls to Next after calling AsRawHeader on i will indicate that the\n-// iterator is done.\n-func (i *IPv6PayloadIterator) AsRawHeader() IPv6RawPayloadHeader {\n- buf := i.payload\n+// If consume is true, calls to Next after calling AsRawHeader on i will\n+// indicate that the iterator is done.\n+func (i *IPv6PayloadIterator) AsRawHeader(consume bool) IPv6RawPayloadHeader {\nidentifier := i.nextHdrIdentifier\n+ var buf buffer.VectorisedView\n+ if consume {\n+ // Since we consume the iterator, we return the payload as is.\n+ buf = i.payload\n+\n// Mark i as done.\n*i = IPv6PayloadIterator{\nnextHdrIdentifier: IPv6NoNextHeaderIdentifier,\n}\n+ } else {\n+ buf = i.payload.Clone(nil)\n+ }\nreturn IPv6RawPayloadHeader{Identifier: identifier, Buf: buf}\n}\n@@ -424,7 +431,7 @@ func (i *IPv6PayloadIterator) Next() (IPv6PayloadHeader, bool, error) {\n// a fragment extension header as the data following the fragment extension\n// header may not be complete.\nif i.forceRaw {\n- return i.AsRawHeader(), false, nil\n+ return i.AsRawHeader(true /* consume */), false, nil\n}\n// Is the header we are parsing a known extension header?\n@@ -456,10 +463,12 @@ func (i *IPv6PayloadIterator) Next() (IPv6PayloadHeader, bool, error) {\nfragmentExtHdr := IPv6FragmentExtHdr(data)\n- // If the packet is a fragmented packet, do not attempt to parse\n- // anything after the fragment extension header as the data following\n- // the extension header may not be complete.\n- if fragmentExtHdr.More() || fragmentExtHdr.FragmentOffset() != 0 {\n+ // If the packet is not the first fragment, do not attempt to parse anything\n+ // after the fragment extension header as the payload following the fragment\n+ // extension header should not contain any headers; the first fragment must\n+ // hold all the headers up to and including any upper layer headers, as per\n+ // RFC 8200 section 4.5.\n+ if fragmentExtHdr.FragmentOffset() != 0 {\ni.forceRaw = true\n}\n@@ -480,7 +489,7 @@ func (i *IPv6PayloadIterator) Next() (IPv6PayloadHeader, bool, error) {\ndefault:\n// The header we are parsing is not a known extension header. Return the\n// raw payload.\n- return i.AsRawHeader(), false, nil\n+ return i.AsRawHeader(true /* consume */), false, nil\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/header/ipv6_extension_headers_test.go", "new_path": "pkg/tcpip/header/ipv6_extension_headers_test.go", "diff": "@@ -673,19 +673,26 @@ func TestIPv6ExtHdrIter(t *testing.T) {\npayload buffer.VectorisedView\nexpected []IPv6PayloadHeader\n}{\n- // With a non-atomic fragment, the payload after the fragment will not be\n- // parsed because the payload may not be complete.\n+ // With a non-atomic fragment that is not the first fragment, the payload\n+ // after the fragment will not be parsed because the payload is expected to\n+ // only hold upper layer data.\n{\n- name: \"hopbyhop - fragment - routing - upper\",\n+ name: \"hopbyhop - fragment (not first) - routing - upper\",\nfirstNextHdr: IPv6HopByHopOptionsExtHdrIdentifier,\npayload: makeVectorisedViewFromByteBuffers([]byte{\n// Hop By Hop extension header.\nuint8(IPv6FragmentExtHdrIdentifier), 0, 1, 4, 1, 2, 3, 4,\n// Fragment extension header.\n+ //\n+ // More = 1, Fragment Offset = 2117, ID = 2147746305\nuint8(IPv6RoutingExtHdrIdentifier), 0, 68, 9, 128, 4, 2, 1,\n// Routing extension header.\n+ //\n+ // Even though we have a routing ext header here, it should be\n+ // be interpretted as raw bytes as only the first fragment is expected\n+ // to hold headers.\n255, 0, 1, 2, 3, 4, 5, 6,\n// Upper layer data.\n@@ -700,6 +707,34 @@ func TestIPv6ExtHdrIter(t *testing.T) {\n},\n},\n},\n+ {\n+ name: \"hopbyhop - fragment (first) - routing - upper\",\n+ firstNextHdr: IPv6HopByHopOptionsExtHdrIdentifier,\n+ payload: makeVectorisedViewFromByteBuffers([]byte{\n+ // Hop By Hop extension header.\n+ uint8(IPv6FragmentExtHdrIdentifier), 0, 1, 4, 1, 2, 3, 4,\n+\n+ // Fragment extension header.\n+ //\n+ // More = 1, Fragment Offset = 0, ID = 2147746305\n+ uint8(IPv6RoutingExtHdrIdentifier), 0, 0, 1, 128, 4, 2, 1,\n+\n+ // Routing extension header.\n+ 255, 0, 1, 2, 3, 4, 5, 6,\n+\n+ // Upper layer data.\n+ 1, 2, 3, 4,\n+ }),\n+ expected: []IPv6PayloadHeader{\n+ IPv6HopByHopOptionsExtHdr{ipv6OptionsExtHdr: []byte{1, 4, 1, 2, 3, 4}},\n+ IPv6FragmentExtHdr([6]byte{0, 1, 128, 4, 2, 1}),\n+ IPv6RoutingExtHdr([]byte{1, 2, 3, 4, 5, 6}),\n+ IPv6RawPayloadHeader{\n+ Identifier: 255,\n+ Buf: upperLayerData.ToVectorisedView(),\n+ },\n+ },\n+ },\n{\nname: \"fragment - routing - upper (across views)\",\nfirstNextHdr: IPv6FragmentExtHdrIdentifier,\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/ipv6.go", "new_path": "pkg/tcpip/network/ipv6/ipv6.go", "diff": "@@ -270,7 +270,55 @@ func (e *endpoint) HandlePacket(r *stack.Route, pkt stack.PacketBuffer) {\ncontinue\n}\n- rawPayload := it.AsRawHeader()\n+ // Don't consume the iterator if we have the first fragment because we\n+ // will use it to validate that the first fragment holds the upper layer\n+ // header.\n+ rawPayload := it.AsRawHeader(fragmentOffset != 0 /* consume */)\n+\n+ if fragmentOffset == 0 {\n+ // Check that the iterator ends with a raw payload as the first fragment\n+ // should include all headers up to and including any upper layer\n+ // headers, as per RFC 8200 section 4.5; only upper layer data\n+ // (non-headers) should follow the fragment extension header.\n+ var lastHdr header.IPv6PayloadHeader\n+\n+ for {\n+ it, done, err := it.Next()\n+ if err != nil {\n+ r.Stats().IP.MalformedPacketsReceived.Increment()\n+ r.Stats().IP.MalformedPacketsReceived.Increment()\n+ return\n+ }\n+ if done {\n+ break\n+ }\n+\n+ lastHdr = it\n+ }\n+\n+ // If the last header is a raw header, then the last portion of the IPv6\n+ // payload is not a known IPv6 extension header. Note, this does not\n+ // mean that the last portion is an upper layer header or not an\n+ // extension header because:\n+ // 1) we do not yet support all extension headers\n+ // 2) we do not validate the upper layer header before reassembling.\n+ //\n+ // This check makes sure that a known IPv6 extension header is not\n+ // present after the Fragment extension header in a non-initial\n+ // fragment.\n+ //\n+ // TODO(#2196): Support IPv6 Authentication and Encapsulated\n+ // Security Payload extension headers.\n+ // TODO(#2333): Validate that the upper layer header is valid.\n+ switch lastHdr.(type) {\n+ case header.IPv6RawPayloadHeader:\n+ default:\n+ r.Stats().IP.MalformedPacketsReceived.Increment()\n+ r.Stats().IP.MalformedFragmentsReceived.Increment()\n+ return\n+ }\n+ }\n+\nfragmentPayloadLen := rawPayload.Buf.Size()\nif fragmentPayloadLen == 0 {\n// Drop the packet as it's marked as a fragment but has no payload.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/ipv6_test.go", "new_path": "pkg/tcpip/network/ipv6/ipv6_test.go", "diff": "@@ -1014,7 +1014,7 @@ func TestReceiveIPv6Fragments(t *testing.T) {\n),\n},\n},\n- expectedPayloads: [][]byte{udpPayload1},\n+ expectedPayloads: nil,\n},\n{\nname: \"Two fragments with routing header with non-zero segments left across fragments\",\n" } ]
Go
Apache License 2.0
google/gvisor
Require that IPv6 headers be in the first fragment Test: - header_test.TestIPv6ExtHdrIter - ipv6_test.TestReceiveIPv6Fragments Updates #2197, #2333 PiperOrigin-RevId: 305330178
260,003
07.04.2020 14:32:24
25,200
d5ddb5365086b13c0688c40fc74fa4cc4c5528db
Remove out-of-date TODOs. We already have network namespace for netstack.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netstack/provider.go", "new_path": "pkg/sentry/socket/netstack/provider.go", "diff": "@@ -62,10 +62,6 @@ func getTransportProtocol(ctx context.Context, stype linux.SockType, protocol in\n}\ncase linux.SOCK_RAW:\n- // TODO(b/142504697): \"In order to create a raw socket, a\n- // process must have the CAP_NET_RAW capability in the user\n- // namespace that governs its network namespace.\" - raw(7)\n-\n// Raw sockets require CAP_NET_RAW.\ncreds := auth.CredentialsFromContext(ctx)\nif !creds.HasCapability(linux.CAP_NET_RAW) {\n@@ -141,10 +137,6 @@ func (p *provider) Socket(t *kernel.Task, stype linux.SockType, protocol int) (*\n}\nfunc packetSocket(t *kernel.Task, epStack *Stack, stype linux.SockType, protocol int) (*fs.File, *syserr.Error) {\n- // TODO(b/142504697): \"In order to create a packet socket, a process\n- // must have the CAP_NET_RAW capability in the user namespace that\n- // governs its network namespace.\" - packet(7)\n-\n// Packet sockets require CAP_NET_RAW.\ncreds := auth.CredentialsFromContext(t)\nif !creds.HasCapability(linux.CAP_NET_RAW) {\n" } ]
Go
Apache License 2.0
google/gvisor
Remove out-of-date TODOs. We already have network namespace for netstack. PiperOrigin-RevId: 305341954
259,860
07.04.2020 14:47:16
25,200
fc72eb3595a7c4e2fa83caa39a9bb4171875c208
Remove TODOs for local gofer extended attributes.
[ { "change_type": "MODIFY", "old_path": "runsc/fsgofer/fsgofer.go", "new_path": "runsc/fsgofer/fsgofer.go", "diff": "@@ -767,22 +767,18 @@ func (l *localFile) SetAttr(valid p9.SetAttrMask, attr p9.SetAttr) error {\nreturn err\n}\n-// TODO(b/127675828): support getxattr.\nfunc (*localFile) GetXattr(string, uint64) (string, error) {\nreturn \"\", syscall.EOPNOTSUPP\n}\n-// TODO(b/127675828): support setxattr.\nfunc (*localFile) SetXattr(string, string, uint32) error {\nreturn syscall.EOPNOTSUPP\n}\n-// TODO(b/148303075): support listxattr.\nfunc (*localFile) ListXattr(uint64) (map[string]struct{}, error) {\nreturn nil, syscall.EOPNOTSUPP\n}\n-// TODO(b/148303075): support removexattr.\nfunc (*localFile) RemoveXattr(string) error {\nreturn syscall.EOPNOTSUPP\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Remove TODOs for local gofer extended attributes. PiperOrigin-RevId: 305344989
259,860
07.04.2020 16:16:31
25,200
693b6bdda9206a5910c552a3997b2df5480d6947
Correctly distinguish between seekable and non-seekable host fds. Check whether an fd is seekable by calling the seek syscall and examining the return value, instead of checking the file type, which is inaccurate.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/host/host.go", "new_path": "pkg/sentry/fsimpl/host/host.go", "diff": "@@ -74,31 +74,34 @@ func ImportFD(mnt *vfs.Mount, hostFD int, isTTY bool) (*vfs.FileDescription, err\n}\n// Retrieve metadata.\n- var s syscall.Stat_t\n- if err := syscall.Fstat(hostFD, &s); err != nil {\n+ var s unix.Stat_t\n+ if err := unix.Fstat(hostFD, &s); err != nil {\nreturn nil, err\n}\nfileMode := linux.FileMode(s.Mode)\nfileType := fileMode.FileType()\n- // Pipes, character devices, and sockets.\n- isStream := fileType == syscall.S_IFIFO || fileType == syscall.S_IFCHR || fileType == syscall.S_IFSOCK\n+\n+ // Determine if hostFD is seekable. If not, this syscall will return ESPIPE\n+ // (see fs/read_write.c:llseek), e.g. for pipes, sockets, and some character\n+ // devices.\n+ _, err := unix.Seek(hostFD, 0, linux.SEEK_CUR)\n+ seekable := err != syserror.ESPIPE\ni := &inode{\nhostFD: hostFD,\n- isStream: isStream,\n+ seekable: seekable,\nisTTY: isTTY,\ncanMap: canMap(uint32(fileType)),\nino: fs.NextIno(),\nmode: fileMode,\n- // For simplicity, set offset to 0. Technically, we should\n- // only set to 0 on files that are not seekable (sockets, pipes, etc.),\n- // and use the offset from the host fd otherwise.\n+ // For simplicity, set offset to 0. Technically, we should use the existing\n+ // offset on the host if the file is seekable.\noffset: 0,\n}\n- // These files can't be memory mapped, assert this.\n- if i.isStream && i.canMap {\n+ // Non-seekable files can't be memory mapped, assert this.\n+ if !i.seekable && i.canMap {\npanic(\"files that can return EWOULDBLOCK (sockets, pipes, etc.) cannot be memory mapped\")\n}\n@@ -124,12 +127,12 @@ type inode struct {\n// This field is initialized at creation time and is immutable.\nhostFD int\n- // isStream is true if the host fd points to a file representing a stream,\n+ // seekable is false if the host fd points to a file representing a stream,\n// e.g. a socket or a pipe. Such files are not seekable and can return\n// EWOULDBLOCK for I/O operations.\n//\n// This field is initialized at creation time and is immutable.\n- isStream bool\n+ seekable bool\n// isTTY is true if this file represents a TTY.\n//\n@@ -481,8 +484,7 @@ func (f *fileDescription) Release() {\n// PRead implements FileDescriptionImpl.\nfunc (f *fileDescription) PRead(ctx context.Context, dst usermem.IOSequence, offset int64, opts vfs.ReadOptions) (int64, error) {\ni := f.inode\n- // TODO(b/34716638): Some char devices do support offsets, e.g. /dev/null.\n- if i.isStream {\n+ if !i.seekable {\nreturn 0, syserror.ESPIPE\n}\n@@ -492,8 +494,7 @@ func (f *fileDescription) PRead(ctx context.Context, dst usermem.IOSequence, off\n// Read implements FileDescriptionImpl.\nfunc (f *fileDescription) Read(ctx context.Context, dst usermem.IOSequence, opts vfs.ReadOptions) (int64, error) {\ni := f.inode\n- // TODO(b/34716638): Some char devices do support offsets, e.g. /dev/null.\n- if i.isStream {\n+ if !i.seekable {\nn, err := readFromHostFD(ctx, i.hostFD, dst, -1, opts.Flags)\nif isBlockError(err) {\n// If we got any data at all, return it as a \"completed\" partial read\n@@ -538,8 +539,7 @@ func readFromHostFD(ctx context.Context, hostFD int, dst usermem.IOSequence, off\n// PWrite implements FileDescriptionImpl.\nfunc (f *fileDescription) PWrite(ctx context.Context, src usermem.IOSequence, offset int64, opts vfs.WriteOptions) (int64, error) {\ni := f.inode\n- // TODO(b/34716638): Some char devices do support offsets, e.g. /dev/null.\n- if i.isStream {\n+ if !i.seekable {\nreturn 0, syserror.ESPIPE\n}\n@@ -549,8 +549,7 @@ func (f *fileDescription) PWrite(ctx context.Context, src usermem.IOSequence, of\n// Write implements FileDescriptionImpl.\nfunc (f *fileDescription) Write(ctx context.Context, src usermem.IOSequence, opts vfs.WriteOptions) (int64, error) {\ni := f.inode\n- // TODO(b/34716638): Some char devices do support offsets, e.g. /dev/null.\n- if i.isStream {\n+ if !i.seekable {\nn, err := writeToHostFD(ctx, i.hostFD, src, -1, opts.Flags)\nif isBlockError(err) {\nerr = syserror.ErrWouldBlock\n@@ -593,8 +592,7 @@ func writeToHostFD(ctx context.Context, hostFD int, src usermem.IOSequence, offs\n// allow directory fds to be imported at all.\nfunc (f *fileDescription) Seek(_ context.Context, offset int64, whence int32) (int64, error) {\ni := f.inode\n- // TODO(b/34716638): Some char devices do support seeking, e.g. /dev/null.\n- if i.isStream {\n+ if !i.seekable {\nreturn 0, syserror.ESPIPE\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Correctly distinguish between seekable and non-seekable host fds. Check whether an fd is seekable by calling the seek syscall and examining the return value, instead of checking the file type, which is inaccurate. PiperOrigin-RevId: 305361593
259,853
07.04.2020 16:44:43
25,200
acf0259255bae190759e39fbff3bac6c94122734
Don't map the 0 uid into a sandbox user namespace Starting with go1.13, we can specify ambient capabilities when we execute a new process with os/exe.Cmd.
[ { "change_type": "MODIFY", "old_path": "runsc/sandbox/sandbox.go", "new_path": "runsc/sandbox/sandbox.go", "diff": "@@ -588,44 +588,31 @@ func (s *Sandbox) createSandboxProcess(conf *boot.Config, args *Args, startSyncF\nnss = append(nss, specs.LinuxNamespace{Type: specs.UserNamespace})\ncmd.Args = append(cmd.Args, \"--setup-root\")\n+ const nobody = 65534\nif conf.Rootless {\n- log.Infof(\"Rootless mode: sandbox will run as root inside user namespace, mapped to the current user, uid: %d, gid: %d\", os.Getuid(), os.Getgid())\n+ log.Infof(\"Rootless mode: sandbox will run as nobody inside user namespace, mapped to the current user, uid: %d, gid: %d\", os.Getuid(), os.Getgid())\ncmd.SysProcAttr.UidMappings = []syscall.SysProcIDMap{\n{\n- ContainerID: 0,\n+ ContainerID: nobody,\nHostID: os.Getuid(),\nSize: 1,\n},\n}\ncmd.SysProcAttr.GidMappings = []syscall.SysProcIDMap{\n{\n- ContainerID: 0,\n+ ContainerID: nobody,\nHostID: os.Getgid(),\nSize: 1,\n},\n}\n- cmd.SysProcAttr.Credential = &syscall.Credential{Uid: 0, Gid: 0}\n} else {\n// Map nobody in the new namespace to nobody in the parent namespace.\n//\n// A sandbox process will construct an empty\n- // root for itself, so it has to have the CAP_SYS_ADMIN\n- // capability.\n- //\n- // FIXME(b/122554829): The current implementations of\n- // os/exec doesn't allow to set ambient capabilities if\n- // a process is started in a new user namespace. As a\n- // workaround, we start the sandbox process with the 0\n- // UID and then it constructs a chroot and sets UID to\n- // nobody. https://github.com/golang/go/issues/2315\n- const nobody = 65534\n+ // root for itself, so it has to have\n+ // CAP_SYS_ADMIN and CAP_SYS_CHROOT capabilities.\ncmd.SysProcAttr.UidMappings = []syscall.SysProcIDMap{\n- {\n- ContainerID: 0,\n- HostID: nobody - 1,\n- Size: 1,\n- },\n{\nContainerID: nobody,\nHostID: nobody,\n@@ -639,11 +626,11 @@ func (s *Sandbox) createSandboxProcess(conf *boot.Config, args *Args, startSyncF\nSize: 1,\n},\n}\n-\n- // Set credentials to run as user and group nobody.\n- cmd.SysProcAttr.Credential = &syscall.Credential{Uid: 0, Gid: nobody}\n}\n+ // Set credentials to run as user and group nobody.\n+ cmd.SysProcAttr.Credential = &syscall.Credential{Uid: nobody, Gid: nobody}\n+ cmd.SysProcAttr.AmbientCaps = append(cmd.SysProcAttr.AmbientCaps, uintptr(capability.CAP_SYS_ADMIN), uintptr(capability.CAP_SYS_CHROOT))\n} else {\nreturn fmt.Errorf(\"can't run sandbox process as user nobody since we don't have CAP_SETUID or CAP_SETGID\")\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Don't map the 0 uid into a sandbox user namespace Starting with go1.13, we can specify ambient capabilities when we execute a new process with os/exe.Cmd. PiperOrigin-RevId: 305366706
259,992
07.04.2020 18:26:34
25,200
5a1324625f1d0d9ea2d4874f9d6d1008ec12f45e
Make unlink tests pass with goferfs Required directory checks were being skipped when there was no child cached. Now the code always loads the child file before unlinking it. Updates
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/gofer/filesystem.go", "new_path": "pkg/sentry/fsimpl/gofer/filesystem.go", "diff": "@@ -437,14 +437,19 @@ func (fs *filesystem) unlinkAt(ctx context.Context, rp *vfs.ResolvingPath, dir b\nflags := uint32(0)\nif dir {\nif child != nil && !child.isDir() {\n+ vfsObj.AbortDeleteDentry(childVFSD)\nreturn syserror.ENOTDIR\n}\nflags = linux.AT_REMOVEDIR\n} else {\nif child != nil && child.isDir() {\n+ vfsObj.AbortDeleteDentry(childVFSD)\nreturn syserror.EISDIR\n}\nif rp.MustBeDir() {\n+ if childVFSD != nil {\n+ vfsObj.AbortDeleteDentry(childVFSD)\n+ }\nreturn syserror.ENOTDIR\n}\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Make unlink tests pass with goferfs Required directory checks were being skipped when there was no child cached. Now the code always loads the child file before unlinking it. Updates #1198 PiperOrigin-RevId: 305382323
259,884
07.04.2020 18:38:13
25,200
5802051b3d60a802713fabbd805614f22c9291ea
Update TODO to Move TODO to so that proper synchronization of operations is handled when we create the urpc client. Issue Fixes
[ { "change_type": "MODIFY", "old_path": "runsc/container/container.go", "new_path": "runsc/container/container.go", "diff": "@@ -1077,9 +1077,9 @@ func (c *Container) adjustGoferOOMScoreAdj() error {\n// oom_score_adj is set to the lowest oom_score_adj among the containers\n// running in the sandbox.\n//\n-// TODO(gvisor.dev/issue/512): This call could race with other containers being\n+// TODO(gvisor.dev/issue/238): This call could race with other containers being\n// created at the same time and end up setting the wrong oom_score_adj to the\n-// sandbox.\n+// sandbox. Use rpc client to synchronize.\nfunc adjustSandboxOOMScoreAdj(s *sandbox.Sandbox, rootDir string, destroy bool) error {\ncontainers, err := loadSandbox(rootDir, s.ID)\nif err != nil {\n" } ]
Go
Apache License 2.0
google/gvisor
Update TODO to #238 Move TODO to #238 so that proper synchronization of operations is handled when we create the urpc client. Issue #238 Fixes #512 PiperOrigin-RevId: 305383924
259,974
04.03.2020 05:44:46
0
b574c715a799e476ac788e5f5b2c68f1a00b3538
Move pagetables.limitPCID to arch-specific file. X86 provide 12 bits for PCID while arm64 support 8/16 bits ASID.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/ring0/pagetables/BUILD", "new_path": "pkg/sentry/platform/ring0/pagetables/BUILD", "diff": "@@ -81,6 +81,9 @@ go_library(\n\"pagetables_arm64.go\",\n\"pagetables_x86.go\",\n\"pcids.go\",\n+ \"pcids_aarch64.go\",\n+ \"pcids_aarch64.s\",\n+ \"pcids_x86.go\",\n\"walker_amd64.go\",\n\"walker_arm64.go\",\n\"walker_empty.go\",\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/ring0/pagetables/pcids.go", "new_path": "pkg/sentry/platform/ring0/pagetables/pcids.go", "diff": "@@ -18,9 +18,6 @@ import (\n\"gvisor.dev/gvisor/pkg/sync\"\n)\n-// limitPCID is the number of valid PCIDs.\n-const limitPCID = 4096\n-\n// PCIDs is a simple PCID database.\n//\n// This is not protected by locks and is thus suitable for use only with a\n@@ -44,7 +41,7 @@ type PCIDs struct {\n//\n// Nil is returned iff the start and size are out of range.\nfunc NewPCIDs(start, size uint16) *PCIDs {\n- if start+uint16(size) >= limitPCID {\n+ if start+uint16(size) > limitPCID {\nreturn nil // See comment.\n}\np := &PCIDs{\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/platform/ring0/pagetables/pcids_aarch64.go", "diff": "+// Copyright 2020 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+// +build arm64\n+\n+package pagetables\n+\n+// limitPCID is the maximum value of PCIDs.\n+//\n+// In VMSAv8-64, the PCID(ASID) size is an IMPLEMENTATION DEFINED choice\n+// of 8 bits or 16 bits, and ID_AA64MMFR0_EL1.ASIDBits identifies the\n+// supported size. When an implementation supports a 16-bit ASID, TCR_ELx.AS\n+// selects whether the top 8 bits of the ASID are used.\n+var limitPCID uint16\n+\n+// GetASIDBits return the system ASID bits, 8 or 16 bits.\n+func GetASIDBits() uint8\n+\n+func init() {\n+ limitPCID = uint16(1)<<GetASIDBits() - 1\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/platform/ring0/pagetables/pcids_x86.go", "diff": "+// Copyright 2020 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+// +build i386 amd64\n+\n+package pagetables\n+\n+// limitPCID is the maximum value of valid PCIDs.\n+const limitPCID = 4095\n" } ]
Go
Apache License 2.0
google/gvisor
Move pagetables.limitPCID to arch-specific file. X86 provide 12 bits for PCID while arm64 support 8/16 bits ASID. Signed-off-by: Haibo Xu <[email protected]> Change-Id: I0bd9236e44e6b6c4c88eb6e9adc5ac27b918bf6c
259,884
07.04.2020 18:49:52
25,200
56054fc1fb0b92cb985f96467f9059e202d8095c
Add friendlier messages for frequently encountered errors. Issue Issue
[ { "change_type": "MODIFY", "old_path": "runsc/boot/fs.go", "new_path": "runsc/boot/fs.go", "diff": "@@ -824,7 +824,20 @@ func (c *containerMounter) mountSubmount(ctx context.Context, conf *Config, mns\ninode, err := filesystem.Mount(ctx, mountDevice(m), mf, strings.Join(opts, \",\"), nil)\nif err != nil {\n- return fmt.Errorf(\"creating mount with source %q: %v\", m.Source, err)\n+ err := fmt.Errorf(\"creating mount with source %q: %v\", m.Source, err)\n+ // Check to see if this is a common error due to a Linux bug.\n+ // This error is generated here in order to cause it to be\n+ // printed to the user using Docker via 'runsc create' etc. rather\n+ // than simply printed to the logs for the 'runsc boot' command.\n+ //\n+ // We check the error message string rather than type because the\n+ // actual error types (syscall.EIO, syscall.EPIPE) are lost by file system\n+ // implementation (e.g. p9).\n+ // TODO(gvisor.dev/issue/1765): Remove message when bug is resolved.\n+ if strings.Contains(err.Error(), syscall.EIO.Error()) || strings.Contains(err.Error(), syscall.EPIPE.Error()) {\n+ return fmt.Errorf(\"%v: %s\", err, specutils.FaqErrorMsg(\"memlock\", \"you may be encountering a Linux kernel bug\"))\n+ }\n+ return err\n}\n// If there are submounts, we need to overlay the mount on top of a ramfs\n" }, { "change_type": "MODIFY", "old_path": "runsc/sandbox/sandbox.go", "new_path": "runsc/sandbox/sandbox.go", "diff": "@@ -18,10 +18,12 @@ package sandbox\nimport (\n\"context\"\n\"fmt\"\n+ \"io\"\n\"math\"\n\"os\"\n\"os/exec\"\n\"strconv\"\n+ \"strings\"\n\"syscall\"\n\"time\"\n@@ -142,7 +144,19 @@ func New(conf *boot.Config, args *Args) (*Sandbox, error) {\n// Wait until the sandbox has booted.\nb := make([]byte, 1)\nif l, err := clientSyncFile.Read(b); err != nil || l != 1 {\n- return nil, fmt.Errorf(\"waiting for sandbox to start: %v\", err)\n+ err := fmt.Errorf(\"waiting for sandbox to start: %v\", err)\n+ // If the sandbox failed to start, it may be because the binary\n+ // permissions were incorrect. Check the bits and return a more helpful\n+ // error message.\n+ //\n+ // NOTE: The error message is checked because error types are lost over\n+ // rpc calls.\n+ if strings.Contains(err.Error(), io.EOF.Error()) {\n+ if permsErr := checkBinaryPermissions(conf); permsErr != nil {\n+ return nil, fmt.Errorf(\"%v: %v\", err, permsErr)\n+ }\n+ }\n+ return nil, err\n}\nc.Release()\n@@ -706,7 +720,19 @@ func (s *Sandbox) createSandboxProcess(conf *boot.Config, args *Args, startSyncF\nlog.Debugf(\"Starting sandbox: %s %v\", binPath, cmd.Args)\nlog.Debugf(\"SysProcAttr: %+v\", cmd.SysProcAttr)\nif err := specutils.StartInNS(cmd, nss); err != nil {\n- return fmt.Errorf(\"Sandbox: %v\", err)\n+ err := fmt.Errorf(\"starting sandbox: %v\", err)\n+ // If the sandbox failed to start, it may be because the binary\n+ // permissions were incorrect. Check the bits and return a more helpful\n+ // error message.\n+ //\n+ // NOTE: The error message is checked because error types are lost over\n+ // rpc calls.\n+ if strings.Contains(err.Error(), syscall.EACCES.Error()) {\n+ if permsErr := checkBinaryPermissions(conf); permsErr != nil {\n+ return fmt.Errorf(\"%v: %v\", err, permsErr)\n+ }\n+ }\n+ return err\n}\ns.child = true\ns.Pid = cmd.Process.Pid\n@@ -1169,3 +1195,31 @@ func deviceFileForPlatform(name string) (*os.File, error) {\n}\nreturn f, nil\n}\n+\n+// checkBinaryPermissions verifies that the required binary bits are set on\n+// the runsc executable.\n+func checkBinaryPermissions(conf *boot.Config) error {\n+ // All platforms need the other exe bit\n+ neededBits := os.FileMode(0001)\n+ if conf.Platform == platforms.Ptrace {\n+ // Ptrace needs the other read bit\n+ neededBits |= os.FileMode(0004)\n+ }\n+\n+ exePath, err := os.Executable()\n+ if err != nil {\n+ return fmt.Errorf(\"getting exe path: %v\", err)\n+ }\n+\n+ // Check the permissions of the runsc binary and print an error if it\n+ // doesn't match expectations.\n+ info, err := os.Stat(exePath)\n+ if err != nil {\n+ return fmt.Errorf(\"stat file: %v\", err)\n+ }\n+\n+ if info.Mode().Perm()&neededBits != neededBits {\n+ return fmt.Errorf(specutils.FaqErrorMsg(\"runsc-perms\", fmt.Sprintf(\"%s does not have the correct permissions\", exePath)))\n+ }\n+ return nil\n+}\n" }, { "change_type": "MODIFY", "old_path": "runsc/specutils/specutils.go", "new_path": "runsc/specutils/specutils.go", "diff": "@@ -528,3 +528,8 @@ func EnvVar(env []string, name string) (string, bool) {\n}\nreturn \"\", false\n}\n+\n+// FaqErrorMsg returns an error message pointing to the FAQ.\n+func FaqErrorMsg(anchor, msg string) string {\n+ return fmt.Sprintf(\"%s; see https://gvisor.dev/faq#%s for more details\", msg, anchor)\n+}\n" } ]
Go
Apache License 2.0
google/gvisor
Add friendlier messages for frequently encountered errors. Issue #2270 Issue #1765 PiperOrigin-RevId: 305385436
259,853
08.04.2020 00:25:16
25,200
c7d841ac6e0be2aaacd6a3a81786508be797f667
tests: Specify NoRandomSave for PortReuse tests SO_REUSEPORT is not properly restored:
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_inet_loopback.cc", "new_path": "test/syscalls/linux/socket_inet_loopback.cc", "diff": "@@ -1157,7 +1157,7 @@ TEST_P(SocketInetReusePortTest, TcpPortReuseMultiThread_NoRandomSave) {\nEquivalentWithin((kConnectAttempts / kThreadCount), 0.10));\n}\n-TEST_P(SocketInetReusePortTest, UdpPortReuseMultiThread) {\n+TEST_P(SocketInetReusePortTest, UdpPortReuseMultiThread_NoRandomSave) {\nauto const& param = GetParam();\nTestAddress const& listener = param.listener;\n@@ -1270,7 +1270,7 @@ TEST_P(SocketInetReusePortTest, UdpPortReuseMultiThread) {\nEquivalentWithin((kConnectAttempts / kThreadCount), 0.10));\n}\n-TEST_P(SocketInetReusePortTest, UdpPortReuseMultiThreadShort) {\n+TEST_P(SocketInetReusePortTest, UdpPortReuseMultiThreadShort_NoRandomSave) {\nauto const& param = GetParam();\nTestAddress const& listener = param.listener;\n@@ -2146,8 +2146,9 @@ TEST_P(SocketMultiProtocolInetLoopbackTest, V4EphemeralPortReservedReuseAddr) {\n&kSockOptOn, sizeof(kSockOptOn)),\nSyscallSucceeds());\n- ASSERT_THAT(connect(connected_fd.get(),\n- reinterpret_cast<sockaddr*>(&bound_addr), bound_addr_len),\n+ ASSERT_THAT(RetryEINTR(connect)(connected_fd.get(),\n+ reinterpret_cast<sockaddr*>(&bound_addr),\n+ bound_addr_len),\nSyscallSucceeds());\n// Get the ephemeral port.\n" } ]
Go
Apache License 2.0
google/gvisor
tests: Specify NoRandomSave for PortReuse tests SO_REUSEPORT is not properly restored: https://github.com/google/gvisor/issues/873 PiperOrigin-RevId: 305422775
259,972
08.04.2020 06:41:52
25,200
71c7e24e5cb8641f4cb98b5fc848ae2033b29eac
Return all packets when Expect fails.
[ { "change_type": "MODIFY", "old_path": "test/packetimpact/testbench/connections.go", "new_path": "test/packetimpact/testbench/connections.go", "diff": "@@ -21,6 +21,7 @@ import (\n\"fmt\"\n\"math/rand\"\n\"net\"\n+ \"strings\"\n\"testing\"\n\"time\"\n@@ -233,19 +234,23 @@ func (conn *TCPIPv4) RecvFrame(timeout time.Duration) Layers {\n// Expect a packet that matches the provided tcp within the timeout specified.\n// If it doesn't arrive in time, it returns nil.\n-func (conn *TCPIPv4) Expect(tcp TCP, timeout time.Duration) *TCP {\n+func (conn *TCPIPv4) Expect(tcp TCP, timeout time.Duration) (*TCP, error) {\n// We cannot implement this directly using ExpectFrame as we cannot specify\n// the Payload part.\ndeadline := time.Now().Add(timeout)\n+ var allTCP []string\nfor {\n- timeout = time.Until(deadline)\n- if timeout <= 0 {\n- return nil\n+ var gotTCP *TCP\n+ if timeout = time.Until(deadline); timeout > 0 {\n+ gotTCP = conn.Recv(timeout)\n+ }\n+ if gotTCP == nil {\n+ return nil, fmt.Errorf(\"got %d packets:\\n%s\", len(allTCP), strings.Join(allTCP, \"\\n\"))\n}\n- gotTCP := conn.Recv(timeout)\nif tcp.match(gotTCP) {\n- return gotTCP\n+ return gotTCP, nil\n}\n+ allTCP = append(allTCP, gotTCP.String())\n}\n}\n@@ -284,10 +289,11 @@ func (conn *TCPIPv4) Handshake() {\nconn.Send(TCP{Flags: Uint8(header.TCPFlagSyn)})\n// Wait for the SYN-ACK.\n- conn.SynAck = conn.Expect(TCP{Flags: Uint8(header.TCPFlagSyn | header.TCPFlagAck)}, time.Second)\n- if conn.SynAck == nil {\n- conn.t.Fatalf(\"didn't get synack during handshake\")\n+ synAck, err := conn.Expect(TCP{Flags: Uint8(header.TCPFlagSyn | header.TCPFlagAck)}, time.Second)\n+ if synAck == nil {\n+ conn.t.Fatalf(\"didn't get synack during handshake: %s\", err)\n}\n+ conn.SynAck = synAck\n// Send an ACK.\nconn.Send(TCP{Flags: Uint8(header.TCPFlagAck)})\n@@ -427,19 +433,20 @@ func (conn *UDPIPv4) Recv(timeout time.Duration) *UDP {\n// Expect a packet that matches the provided udp within the timeout specified.\n// If it doesn't arrive in time, the test fails.\n-func (conn *UDPIPv4) Expect(udp UDP, timeout time.Duration) *UDP {\n+func (conn *UDPIPv4) Expect(udp UDP, timeout time.Duration) (*UDP, error) {\ndeadline := time.Now().Add(timeout)\n+ var allUDP []string\nfor {\n- timeout = time.Until(deadline)\n- if timeout <= 0 {\n- return nil\n+ var gotUDP *UDP\n+ if timeout = time.Until(deadline); timeout > 0 {\n+ gotUDP = conn.Recv(timeout)\n}\n- gotUDP := conn.Recv(timeout)\nif gotUDP == nil {\n- return nil\n+ return nil, fmt.Errorf(\"got %d packets:\\n%s\", len(allUDP), strings.Join(allUDP, \"\\n\"))\n}\nif udp.match(gotUDP) {\n- return gotUDP\n+ return gotUDP, nil\n}\n+ allUDP = append(allUDP, gotUDP.String())\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "test/packetimpact/tests/fin_wait2_timeout_test.go", "new_path": "test/packetimpact/tests/fin_wait2_timeout_test.go", "diff": "@@ -47,20 +47,20 @@ func TestFinWait2Timeout(t *testing.T) {\n}\ndut.Close(acceptFd)\n- if gotOne := conn.Expect(tb.TCP{Flags: tb.Uint8(header.TCPFlagFin | header.TCPFlagAck)}, time.Second); gotOne == nil {\n- t.Fatal(\"expected a FIN-ACK within 1 second but got none\")\n+ if _, err := conn.Expect(tb.TCP{Flags: tb.Uint8(header.TCPFlagFin | header.TCPFlagAck)}, time.Second); err != nil {\n+ t.Fatalf(\"expected a FIN-ACK within 1 second but got none: %s\", err)\n}\nconn.Send(tb.TCP{Flags: tb.Uint8(header.TCPFlagAck)})\ntime.Sleep(5 * time.Second)\nconn.Send(tb.TCP{Flags: tb.Uint8(header.TCPFlagAck)})\nif tt.linger2 {\n- if gotOne := conn.Expect(tb.TCP{Flags: tb.Uint8(header.TCPFlagRst)}, time.Second); gotOne == nil {\n- t.Fatal(\"expected a RST packet within a second but got none\")\n+ if _, err := conn.Expect(tb.TCP{Flags: tb.Uint8(header.TCPFlagRst)}, time.Second); err != nil {\n+ t.Fatalf(\"expected a RST packet within a second but got none: %s\", err)\n}\n} else {\n- if gotOne := conn.Expect(tb.TCP{Flags: tb.Uint8(header.TCPFlagRst)}, 10*time.Second); gotOne != nil {\n- t.Fatal(\"expected no RST packets within ten seconds but got one\")\n+ if _, err := conn.Expect(tb.TCP{Flags: tb.Uint8(header.TCPFlagRst)}, 10*time.Second); err == nil {\n+ t.Fatalf(\"expected no RST packets within ten seconds but got one: %s\", err)\n}\n}\n})\n" } ]
Go
Apache License 2.0
google/gvisor
Return all packets when Expect fails. PiperOrigin-RevId: 305466309
259,858
25.03.2020 16:57:37
25,200
f888b9ce83c202bb77c1e29c3ee60cc485906536
Fix unused result errors. This fixes a bug in the proc net directory. Updates
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/proc/task_net.go", "new_path": "pkg/sentry/fsimpl/proc/task_net.go", "diff": "@@ -688,9 +688,9 @@ func (d *netSnmpData) Generate(ctx context.Context, buf *bytes.Buffer) error {\nif line.prefix == \"Tcp\" {\ntcp := stat.(*inet.StatSNMPTCP)\n// \"Tcp\" needs special processing because MaxConn is signed. RFC 2012.\n- fmt.Sprintf(\"%s: %s %d %s\\n\", line.prefix, sprintSlice(tcp[:3]), int64(tcp[3]), sprintSlice(tcp[4:]))\n+ fmt.Fprintf(buf, \"%s: %s %d %s\\n\", line.prefix, sprintSlice(tcp[:3]), int64(tcp[3]), sprintSlice(tcp[4:]))\n} else {\n- fmt.Sprintf(\"%s: %s\\n\", line.prefix, sprintSlice(toSlice(stat)))\n+ fmt.Fprintf(buf, \"%s: %s\\n\", line.prefix, sprintSlice(toSlice(stat)))\n}\n}\nreturn nil\n" }, { "change_type": "MODIFY", "old_path": "tools/nogo.json", "new_path": "tools/nogo.json", "diff": "\"/pkg/sentry/platform/safecopy/safecopy_unsafe.go\": \"allowed: special case\",\n\"/pkg/sentry/vfs/mount_unsafe.go\": \"allowed: special case\"\n}\n- },\n- \"unusedresult\": {\n- \"exclude_files\": {\n- \"/pkg/sentry/fsimpl/proc/task_net.go\": \"fix: result of fmt.Sprintf call not used\",\n- \"/pkg/sentry/fsimpl/proc/tasks_net.go\": \"fix: result of fmt.Sprintf call not used\"\n- }\n}\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Fix unused result errors. This fixes a bug in the proc net directory. Updates #2243
259,858
25.03.2020 17:20:16
25,200
867eeb18d8c65019fb755194d5bdf768837f07a8
Remove lostcancel warnings. Updates
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/arp/arp_test.go", "new_path": "pkg/tcpip/network/arp/arp_test.go", "diff": "@@ -138,7 +138,8 @@ func TestDirectRequest(t *testing.T) {\n// Sleep tests are gross, but this will only potentially flake\n// if there's a bug. If there is no bug this will reliably\n// succeed.\n- ctx, _ := context.WithTimeout(context.Background(), 100*time.Millisecond)\n+ ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)\n+ defer cancel()\nif pkt, ok := c.linkEP.ReadContext(ctx); ok {\nt.Errorf(\"stackAddrBad: unexpected packet sent, Proto=%v\", pkt.Proto)\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/ndp_test.go", "new_path": "pkg/tcpip/stack/ndp_test.go", "diff": "@@ -3483,7 +3483,8 @@ func TestRouterSolicitation(t *testing.T) {\ne.Endpoint.LinkEPCapabilities |= stack.CapabilityResolutionRequired\nwaitForPkt := func(timeout time.Duration) {\nt.Helper()\n- ctx, _ := context.WithTimeout(context.Background(), timeout)\n+ ctx, cancel := context.WithTimeout(context.Background(), timeout)\n+ defer cancel()\np, ok := e.ReadContext(ctx)\nif !ok {\nt.Fatal(\"timed out waiting for packet\")\n@@ -3513,7 +3514,8 @@ func TestRouterSolicitation(t *testing.T) {\n}\nwaitForNothing := func(timeout time.Duration) {\nt.Helper()\n- ctx, _ := context.WithTimeout(context.Background(), timeout)\n+ ctx, cancel := context.WithTimeout(context.Background(), timeout)\n+ defer cancel()\nif _, ok := e.ReadContext(ctx); ok {\nt.Fatal(\"unexpectedly got a packet\")\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/testing/context/context.go", "new_path": "pkg/tcpip/transport/tcp/testing/context/context.go", "diff": "@@ -217,7 +217,8 @@ func (c *Context) Stack() *stack.Stack {\nfunc (c *Context) CheckNoPacketTimeout(errMsg string, wait time.Duration) {\nc.t.Helper()\n- ctx, _ := context.WithTimeout(context.Background(), wait)\n+ ctx, cancel := context.WithTimeout(context.Background(), wait)\n+ defer cancel()\nif _, ok := c.linkEP.ReadContext(ctx); ok {\nc.t.Fatal(errMsg)\n}\n@@ -235,7 +236,8 @@ func (c *Context) CheckNoPacket(errMsg string) {\nfunc (c *Context) GetPacket() []byte {\nc.t.Helper()\n- ctx, _ := context.WithTimeout(context.Background(), 2*time.Second)\n+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)\n+ defer cancel()\np, ok := c.linkEP.ReadContext(ctx)\nif !ok {\nc.t.Fatalf(\"Packet wasn't written out\")\n@@ -486,7 +488,8 @@ func (c *Context) CreateV6Endpoint(v6only bool) {\nfunc (c *Context) GetV6Packet() []byte {\nc.t.Helper()\n- ctx, _ := context.WithTimeout(context.Background(), 2*time.Second)\n+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)\n+ defer cancel()\np, ok := c.linkEP.ReadContext(ctx)\nif !ok {\nc.t.Fatalf(\"Packet wasn't written out\")\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/udp/udp_test.go", "new_path": "pkg/tcpip/transport/udp/udp_test.go", "diff": "@@ -358,7 +358,8 @@ func (c *testContext) createEndpointForFlow(flow testFlow) {\nfunc (c *testContext) getPacketAndVerify(flow testFlow, checkers ...checker.NetworkChecker) []byte {\nc.t.Helper()\n- ctx, _ := context.WithTimeout(context.Background(), 2*time.Second)\n+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)\n+ defer cancel()\np, ok := c.linkEP.ReadContext(ctx)\nif !ok {\nc.t.Fatalf(\"Packet wasn't written out\")\n@@ -1563,7 +1564,8 @@ func TestV4UnknownDestination(t *testing.T) {\n}\nc.injectPacket(tc.flow, payload)\nif !tc.icmpRequired {\n- ctx, _ := context.WithTimeout(context.Background(), time.Second)\n+ ctx, cancel := context.WithTimeout(context.Background(), time.Second)\n+ defer cancel()\nif p, ok := c.linkEP.ReadContext(ctx); ok {\nt.Fatalf(\"unexpected packet received: %+v\", p)\n}\n@@ -1571,7 +1573,8 @@ func TestV4UnknownDestination(t *testing.T) {\n}\n// ICMP required.\n- ctx, _ := context.WithTimeout(context.Background(), time.Second)\n+ ctx, cancel := context.WithTimeout(context.Background(), time.Second)\n+ defer cancel()\np, ok := c.linkEP.ReadContext(ctx)\nif !ok {\nt.Fatalf(\"packet wasn't written out\")\n@@ -1639,7 +1642,8 @@ func TestV6UnknownDestination(t *testing.T) {\n}\nc.injectPacket(tc.flow, payload)\nif !tc.icmpRequired {\n- ctx, _ := context.WithTimeout(context.Background(), time.Second)\n+ ctx, cancel := context.WithTimeout(context.Background(), time.Second)\n+ defer cancel()\nif p, ok := c.linkEP.ReadContext(ctx); ok {\nt.Fatalf(\"unexpected packet received: %+v\", p)\n}\n@@ -1647,7 +1651,8 @@ func TestV6UnknownDestination(t *testing.T) {\n}\n// ICMP required.\n- ctx, _ := context.WithTimeout(context.Background(), time.Second)\n+ ctx, cancel := context.WithTimeout(context.Background(), time.Second)\n+ defer cancel()\np, ok := c.linkEP.ReadContext(ctx)\nif !ok {\nt.Fatalf(\"packet wasn't written out\")\n" }, { "change_type": "MODIFY", "old_path": "tools/nogo.json", "new_path": "tools/nogo.json", "diff": "\"/external/\": \"allowed: not subject to unsafe naming rules\"\n}\n},\n- \"lostcancel\": {\n- \"exclude_files\": {\n- \"/pkg/tcpip/network/arp/arp_test.go\": \"fix: the cancel function returned by context.WithTimeout should be called, not discarded, to avoid a context leak\",\n- \"/pkg/tcpip/stack/ndp_test.go\": \"fix: the cancel function returned by context.WithTimeout should be called, not discarded, to avoid a context leak\",\n- \"/pkg/tcpip/transport/udp/udp_test.go\": \"fix: the cancel function returned by context.WithTimeout should be called, not discarded, to avoid a context leak\",\n- \"/pkg/tcpip/transport/tcp/testing/context/context.go\": \"fix: the cancel function returned by context.WithTimeout should be called, not discarded, to avoid a context leak\"\n- }\n- },\n\"nilness\": {\n\"exclude_files\": {\n\"/com_github_vishvananda_netlink/route_linux.go\": \"allowed: false positive\",\n" } ]
Go
Apache License 2.0
google/gvisor
Remove lostcancel warnings. Updates #2243
259,992
08.04.2020 13:33:44
25,200
b30130567d81157e39b692e0116f86015f0bcc71
Enable SubprocessExited and SubprocessZombie for gVisor Updates
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/proc/task.go", "new_path": "pkg/sentry/fs/proc/task.go", "diff": "@@ -57,6 +57,16 @@ func getTaskMM(t *kernel.Task) (*mm.MemoryManager, error) {\nreturn m, nil\n}\n+func checkTaskState(t *kernel.Task) error {\n+ switch t.ExitState() {\n+ case kernel.TaskExitZombie:\n+ return syserror.EACCES\n+ case kernel.TaskExitDead:\n+ return syserror.ESRCH\n+ }\n+ return nil\n+}\n+\n// taskDir represents a task-level directory.\n//\n// +stateify savable\n@@ -254,11 +264,12 @@ func newExe(t *kernel.Task, msrc *fs.MountSource) *fs.Inode {\n}\nfunc (e *exe) executable() (file fsbridge.File, err error) {\n+ if err := checkTaskState(e.t); err != nil {\n+ return nil, err\n+ }\ne.t.WithMuLocked(func(t *kernel.Task) {\nmm := t.MemoryManager()\nif mm == nil {\n- // TODO(b/34851096): Check shouldn't allow Readlink once the\n- // Task is zombied.\nerr = syserror.EACCES\nreturn\n}\n@@ -268,7 +279,7 @@ func (e *exe) executable() (file fsbridge.File, err error) {\n// (with locks held).\nfile = mm.Executable()\nif file == nil {\n- err = syserror.ENOENT\n+ err = syserror.ESRCH\n}\n})\nreturn\n@@ -313,11 +324,22 @@ func newNamespaceSymlink(t *kernel.Task, msrc *fs.MountSource, name string) *fs.\nreturn newProcInode(t, n, msrc, fs.Symlink, t)\n}\n+// Readlink reads the symlink value.\n+func (n *namespaceSymlink) Readlink(ctx context.Context, inode *fs.Inode) (string, error) {\n+ if err := checkTaskState(n.t); err != nil {\n+ return \"\", err\n+ }\n+ return n.Symlink.Readlink(ctx, inode)\n+}\n+\n// Getlink implements fs.InodeOperations.Getlink.\nfunc (n *namespaceSymlink) Getlink(ctx context.Context, inode *fs.Inode) (*fs.Dirent, error) {\nif !kernel.ContextCanTrace(ctx, n.t, false) {\nreturn nil, syserror.EACCES\n}\n+ if err := checkTaskState(n.t); err != nil {\n+ return nil, err\n+ }\n// Create a new regular file to fake the namespace file.\niops := fsutil.NewNoReadWriteFileInode(ctx, fs.RootOwner, fs.FilePermsFromMode(0777), linux.PROC_SUPER_MAGIC)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/proc/task.go", "new_path": "pkg/sentry/fsimpl/proc/task.go", "diff": "@@ -214,22 +214,6 @@ func newIO(t *kernel.Task, isThreadGroup bool) *ioData {\nreturn &ioData{ioUsage: t}\n}\n-func newNamespaceSymlink(task *kernel.Task, ino uint64, ns string) *kernfs.Dentry {\n- // Namespace symlinks should contain the namespace name and the inode number\n- // for the namespace instance, so for example user:[123456]. We currently fake\n- // the inode number by sticking the symlink inode in its place.\n- target := fmt.Sprintf(\"%s:[%d]\", ns, ino)\n-\n- inode := &kernfs.StaticSymlink{}\n- // Note: credentials are overridden by taskOwnedInode.\n- inode.Init(task.Credentials(), ino, target)\n-\n- taskInode := &taskOwnedInode{Inode: inode, owner: task}\n- d := &kernfs.Dentry{}\n- d.Init(taskInode)\n- return d\n-}\n-\n// newCgroupData creates inode that shows cgroup information.\n// From man 7 cgroups: \"For each cgroup hierarchy of which the process is a\n// member, there is one entry containing three colon-separated fields:\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/proc/task_files.go", "new_path": "pkg/sentry/fsimpl/proc/task_files.go", "diff": "@@ -64,6 +64,16 @@ func getMMIncRef(task *kernel.Task) (*mm.MemoryManager, error) {\nreturn m, nil\n}\n+func checkTaskState(t *kernel.Task) error {\n+ switch t.ExitState() {\n+ case kernel.TaskExitZombie:\n+ return syserror.EACCES\n+ case kernel.TaskExitDead:\n+ return syserror.ESRCH\n+ }\n+ return nil\n+}\n+\ntype bufferWriter struct {\nbuf *bytes.Buffer\n}\n@@ -628,11 +638,13 @@ func (s *exeSymlink) Getlink(ctx context.Context) (vfs.VirtualDentry, string, er\n}\nfunc (s *exeSymlink) executable() (file fsbridge.File, err error) {\n+ if err := checkTaskState(s.task); err != nil {\n+ return nil, err\n+ }\n+\ns.task.WithMuLocked(func(t *kernel.Task) {\nmm := t.MemoryManager()\nif mm == nil {\n- // TODO(b/34851096): Check shouldn't allow Readlink once the\n- // Task is zombied.\nerr = syserror.EACCES\nreturn\n}\n@@ -642,7 +654,7 @@ func (s *exeSymlink) executable() (file fsbridge.File, err error) {\n// (with locks held).\nfile = mm.Executable()\nif file == nil {\n- err = syserror.ENOENT\n+ err = syserror.ESRCH\n}\n})\nreturn\n@@ -709,3 +721,41 @@ func (i *mountsData) Generate(ctx context.Context, buf *bytes.Buffer) error {\ni.task.Kernel().VFS().GenerateProcMounts(ctx, rootDir, buf)\nreturn nil\n}\n+\n+type namespaceSymlink struct {\n+ kernfs.StaticSymlink\n+\n+ task *kernel.Task\n+}\n+\n+func newNamespaceSymlink(task *kernel.Task, ino uint64, ns string) *kernfs.Dentry {\n+ // Namespace symlinks should contain the namespace name and the inode number\n+ // for the namespace instance, so for example user:[123456]. We currently fake\n+ // the inode number by sticking the symlink inode in its place.\n+ target := fmt.Sprintf(\"%s:[%d]\", ns, ino)\n+\n+ inode := &namespaceSymlink{task: task}\n+ // Note: credentials are overridden by taskOwnedInode.\n+ inode.Init(task.Credentials(), ino, target)\n+\n+ taskInode := &taskOwnedInode{Inode: inode, owner: task}\n+ d := &kernfs.Dentry{}\n+ d.Init(taskInode)\n+ return d\n+}\n+\n+// Readlink implements Inode.\n+func (s *namespaceSymlink) Readlink(ctx context.Context) (string, error) {\n+ if err := checkTaskState(s.task); err != nil {\n+ return \"\", err\n+ }\n+ return s.StaticSymlink.Readlink(ctx)\n+}\n+\n+// Getlink implements Inode.Getlink.\n+func (s *namespaceSymlink) Getlink(ctx context.Context) (vfs.VirtualDentry, string, error) {\n+ if err := checkTaskState(s.task); err != nil {\n+ return vfs.VirtualDentry{}, \"\", err\n+ }\n+ return s.StaticSymlink.Getlink(ctx)\n+}\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/proc.cc", "new_path": "test/syscalls/linux/proc.cc", "diff": "@@ -1326,8 +1326,6 @@ TEST(ProcPidSymlink, SubprocessRunning) {\nSyscallSucceedsWithValue(sizeof(buf)));\n}\n-// FIXME(gvisor.dev/issue/164): Inconsistent behavior between gVisor and linux\n-// on proc files.\nTEST(ProcPidSymlink, SubprocessZombied) {\nASSERT_NO_ERRNO(SetCapability(CAP_DAC_OVERRIDE, false));\nASSERT_NO_ERRNO(SetCapability(CAP_DAC_READ_SEARCH, false));\n@@ -1337,7 +1335,7 @@ TEST(ProcPidSymlink, SubprocessZombied) {\nint want = EACCES;\nif (!IsRunningOnGvisor()) {\nauto version = ASSERT_NO_ERRNO_AND_VALUE(GetKernelVersion());\n- if (version.major == 4 && version.minor > 3) {\n+ if (version.major > 4 || (version.major == 4 && version.minor > 3)) {\nwant = ENOENT;\n}\n}\n@@ -1350,30 +1348,25 @@ TEST(ProcPidSymlink, SubprocessZombied) {\nSyscallFailsWithErrno(want));\n}\n- // FIXME(gvisor.dev/issue/164): Inconsistent behavior between gVisor and linux\n- // on proc files.\n+ // FIXME(gvisor.dev/issue/164): Inconsistent behavior between linux on proc\n+ // files.\n//\n// ~4.3: Syscall fails with EACCES.\n- // 4.17 & gVisor: Syscall succeeds and returns 1.\n+ // 4.17: Syscall succeeds and returns 1.\n//\n- // EXPECT_THAT(ReadlinkWhileZombied(\"ns/pid\", buf, sizeof(buf)),\n- // SyscallFailsWithErrno(EACCES));\n+ if (!IsRunningOnGvisor()) {\n+ return;\n+ }\n- // FIXME(gvisor.dev/issue/164): Inconsistent behavior between gVisor and linux\n- // on proc files.\n- //\n- // ~4.3: Syscall fails with EACCES.\n- // 4.17 & gVisor: Syscall succeeds and returns 1.\n- //\n- // EXPECT_THAT(ReadlinkWhileZombied(\"ns/user\", buf, sizeof(buf)),\n- // SyscallFailsWithErrno(EACCES));\n+ EXPECT_THAT(ReadlinkWhileZombied(\"ns/pid\", buf, sizeof(buf)),\n+ SyscallFailsWithErrno(want));\n+\n+ EXPECT_THAT(ReadlinkWhileZombied(\"ns/user\", buf, sizeof(buf)),\n+ SyscallFailsWithErrno(want));\n}\n// Test whether /proc/PID/ symlinks can be read for an exited process.\nTEST(ProcPidSymlink, SubprocessExited) {\n- // FIXME(gvisor.dev/issue/164): These all succeed on gVisor.\n- SKIP_IF(IsRunningOnGvisor());\n-\nchar buf[1];\nEXPECT_THAT(ReadlinkWhileExited(\"exe\", buf, sizeof(buf)),\n" } ]
Go
Apache License 2.0
google/gvisor
Enable SubprocessExited and SubprocessZombie for gVisor Updates #164 PiperOrigin-RevId: 305544029
260,003
08.04.2020 13:46:51
25,200
2907e6da5e9fc7eeda51644db7bec4d15691b384
file test: Remove FIXME about FIFO. It is already tested in mknod test.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/file_base.h", "new_path": "test/syscalls/linux/file_base.h", "diff": "@@ -52,17 +52,6 @@ class FileTest : public ::testing::Test {\ntest_file_fd_ = ASSERT_NO_ERRNO_AND_VALUE(\nOpen(test_file_name_, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR));\n- // FIXME(edahlgren): enable when mknod syscall is supported.\n- // test_fifo_name_ = NewTempAbsPath();\n- // ASSERT_THAT(mknod(test_fifo_name_.c_str()), S_IFIFO|0644, 0,\n- // SyscallSucceeds());\n- // ASSERT_THAT(test_fifo_[1] = open(test_fifo_name_.c_str(),\n- // O_WRONLY),\n- // SyscallSucceeds());\n- // ASSERT_THAT(test_fifo_[0] = open(test_fifo_name_.c_str(),\n- // O_RDONLY),\n- // SyscallSucceeds());\n-\nASSERT_THAT(pipe(test_pipe_), SyscallSucceeds());\nASSERT_THAT(fcntl(test_pipe_[0], F_SETFL, O_NONBLOCK), SyscallSucceeds());\n}\n@@ -96,18 +85,11 @@ class FileTest : public ::testing::Test {\nCloseFile();\nUnlinkFile();\nClosePipes();\n-\n- // FIXME(edahlgren): enable when mknod syscall is supported.\n- // close(test_fifo_[0]);\n- // close(test_fifo_[1]);\n- // unlink(test_fifo_name_.c_str());\n}\nstd::string test_file_name_;\n- std::string test_fifo_name_;\nFileDescriptor test_file_fd_;\n- int test_fifo_[2];\nint test_pipe_[2];\n};\n" } ]
Go
Apache License 2.0
google/gvisor
file test: Remove FIXME about FIFO. It is already tested in mknod test. PiperOrigin-RevId: 305546584
259,860
08.04.2020 14:38:09
25,200
357f136e42de81b033b65b7f39a4a555275a17e3
Handle utimes correctly for shared gofer filesystems. Determine system time from within the sentry rather than relying on the remote filesystem to prevent inconsistencies. Resolve related TODOs; the time discrepancies in question don't exist anymore.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/gofer/util.go", "new_path": "pkg/sentry/fs/gofer/util.go", "diff": "@@ -20,17 +20,29 @@ import (\n\"gvisor.dev/gvisor/pkg/context\"\n\"gvisor.dev/gvisor/pkg/p9\"\n\"gvisor.dev/gvisor/pkg/sentry/fs\"\n+ ktime \"gvisor.dev/gvisor/pkg/sentry/kernel/time\"\n)\nfunc utimes(ctx context.Context, file contextFile, ts fs.TimeSpec) error {\nif ts.ATimeOmit && ts.MTimeOmit {\nreturn nil\n}\n+\n+ // Replace requests to use the \"system time\" with the current time to\n+ // ensure that timestamps remain consistent with the remote\n+ // filesystem.\n+ now := ktime.NowFromContext(ctx)\n+ if ts.ATimeSetSystemTime {\n+ ts.ATime = now\n+ }\n+ if ts.MTimeSetSystemTime {\n+ ts.MTime = now\n+ }\nmask := p9.SetAttrMask{\nATime: !ts.ATimeOmit,\n- ATimeNotSystemTime: !ts.ATimeSetSystemTime,\n+ ATimeNotSystemTime: true,\nMTime: !ts.MTimeOmit,\n- MTimeNotSystemTime: !ts.MTimeSetSystemTime,\n+ MTimeNotSystemTime: true,\n}\nas, ans := ts.ATime.Unix()\nms, mns := ts.MTime.Unix()\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/utimes.cc", "new_path": "test/syscalls/linux/utimes.cc", "diff": "@@ -34,17 +34,10 @@ namespace testing {\nnamespace {\n-// TODO(b/36516566): utimes(nullptr) does not pick the \"now\" time in the\n-// application's time domain, so when asserting that times are within a window,\n-// we expand the window to allow for differences between the time domains.\n-constexpr absl::Duration kClockSlack = absl::Milliseconds(100);\n-\n// TimeBoxed runs fn, setting before and after to (coarse realtime) times\n// guaranteed* to come before and after fn started and completed, respectively.\n//\n// fn may be called more than once if the clock is adjusted.\n-//\n-// * See the comment on kClockSlack. gVisor breaks this guarantee.\nvoid TimeBoxed(absl::Time* before, absl::Time* after,\nstd::function<void()> const& fn) {\ndo {\n@@ -69,12 +62,6 @@ void TimeBoxed(absl::Time* before, absl::Time* after,\n// which could lead to test failures, but that is very unlikely to happen.\ncontinue;\n}\n-\n- if (IsRunningOnGvisor()) {\n- // See comment on kClockSlack.\n- *before -= kClockSlack;\n- *after += kClockSlack;\n- }\n} while (*after < *before);\n}\n@@ -235,11 +222,8 @@ void TestUtimensat(int dirFd, std::string const& path) {\nEXPECT_GE(mtime3, before);\nEXPECT_LE(mtime3, after);\n- if (!IsRunningOnGvisor()) {\n- // FIXME(b/36516566): Gofers set atime and mtime to different \"now\" times.\nEXPECT_EQ(atime3, mtime3);\n}\n-}\nTEST(UtimensatTest, OnAbsPath) {\nauto f = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());\n" } ]
Go
Apache License 2.0
google/gvisor
Handle utimes correctly for shared gofer filesystems. Determine system time from within the sentry rather than relying on the remote filesystem to prevent inconsistencies. Resolve related TODOs; the time discrepancies in question don't exist anymore. PiperOrigin-RevId: 305557099
259,860
08.04.2020 17:32:57
25,200
981a587476e11e49cf49edb31705d8727b0db556
Remove InodeOperations FIXMEs that will be obsoleted by VFS2.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/gofer/inode.go", "new_path": "pkg/sentry/fs/gofer/inode.go", "diff": "@@ -710,13 +710,10 @@ func init() {\n}\n// AddLink implements InodeOperations.AddLink, but is currently a noop.\n-// FIXME(b/63117438): Remove this from InodeOperations altogether.\nfunc (*inodeOperations) AddLink() {}\n// DropLink implements InodeOperations.DropLink, but is currently a noop.\n-// FIXME(b/63117438): Remove this from InodeOperations altogether.\nfunc (*inodeOperations) DropLink() {}\n// NotifyStatusChange implements fs.InodeOperations.NotifyStatusChange.\n-// FIXME(b/63117438): Remove this from InodeOperations altogether.\nfunc (i *inodeOperations) NotifyStatusChange(ctx context.Context) {}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/host/inode.go", "new_path": "pkg/sentry/fs/host/inode.go", "diff": "@@ -397,15 +397,12 @@ func (i *inodeOperations) StatFS(context.Context) (fs.Info, error) {\n}\n// AddLink implements fs.InodeOperations.AddLink.\n-// FIXME(b/63117438): Remove this from InodeOperations altogether.\nfunc (i *inodeOperations) AddLink() {}\n// DropLink implements fs.InodeOperations.DropLink.\n-// FIXME(b/63117438): Remove this from InodeOperations altogether.\nfunc (i *inodeOperations) DropLink() {}\n// NotifyStatusChange implements fs.InodeOperations.NotifyStatusChange.\n-// FIXME(b/63117438): Remove this from InodeOperations altogether.\nfunc (i *inodeOperations) NotifyStatusChange(ctx context.Context) {}\n// readdirAll returns all of the directory entries in i.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/inode.go", "new_path": "pkg/sentry/fs/inode.go", "diff": "@@ -397,8 +397,6 @@ func (i *Inode) Getlink(ctx context.Context) (*Dirent, error) {\n// AddLink calls i.InodeOperations.AddLink.\nfunc (i *Inode) AddLink() {\nif i.overlay != nil {\n- // FIXME(b/63117438): Remove this from InodeOperations altogether.\n- //\n// This interface is only used by ramfs to update metadata of\n// children. These filesystems should _never_ have overlay\n// Inodes cached as children. So explicitly disallow this\n" } ]
Go
Apache License 2.0
google/gvisor
Remove InodeOperations FIXMEs that will be obsoleted by VFS2. PiperOrigin-RevId: 305588941
259,885
08.04.2020 18:40:46
25,200
0f75f7273d8c4ace73d93b6b00f81d53a5cf76ea
Don't call platform.AddressSpace.MapFile with no permissions.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/mm/address_space.go", "new_path": "pkg/sentry/mm/address_space.go", "diff": "@@ -201,9 +201,11 @@ func (mm *MemoryManager) mapASLocked(pseg pmaIterator, ar usermem.AddrRange, pre\nif pma.needCOW {\nperms.Write = false\n}\n+ if perms.Any() { // MapFile precondition\nif err := mm.as.MapFile(pmaMapAR.Start, pma.file, pseg.fileRangeOf(pmaMapAR), perms, precommit); err != nil {\nreturn err\n}\n+ }\npseg = pseg.NextSegment()\n}\nreturn nil\n" } ]
Go
Apache License 2.0
google/gvisor
Don't call platform.AddressSpace.MapFile with no permissions. PiperOrigin-RevId: 305598136
259,885
08.04.2020 19:40:15
25,200
7297fd7238e17803e073fb5a5ef85edf992bdf6b
Bump proc_test's kRSSTolerance to 10MB.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/proc.cc", "new_path": "test/syscalls/linux/proc.cc", "diff": "@@ -994,7 +994,7 @@ constexpr uint64_t kMappingSize = 100 << 20;\n// Tolerance on RSS comparisons to account for background thread mappings,\n// reclaimed pages, newly faulted pages, etc.\n-constexpr uint64_t kRSSTolerance = 5 << 20;\n+constexpr uint64_t kRSSTolerance = 10 << 20;\n// Capture RSS before and after an anonymous mapping with passed prot.\nvoid MapPopulateRSS(int prot, uint64_t* before, uint64_t* after) {\n" } ]
Go
Apache License 2.0
google/gvisor
Bump proc_test's kRSSTolerance to 10MB. PiperOrigin-RevId: 305604557
259,853
08.04.2020 23:02:09
25,200
a10389e783aab5f530641394ef44c8a1dede9372
splice: cap splice calls to MAX_RW_COUNT The Linux does the same. Reported-by:
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/sys_splice.go", "new_path": "pkg/sentry/syscalls/linux/sys_splice.go", "diff": "@@ -29,6 +29,10 @@ func doSplice(t *kernel.Task, outFile, inFile *fs.File, opts fs.SpliceOpts, nonB\nreturn 0, syserror.EINVAL\n}\n+ if opts.Length > int64(kernel.MAX_RW_COUNT) {\n+ opts.Length = int64(kernel.MAX_RW_COUNT)\n+ }\n+\nvar (\ntotal int64\nn int64\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/BUILD", "new_path": "test/syscalls/linux/BUILD", "diff": "@@ -2026,6 +2026,8 @@ cc_binary(\n\"//test/util:file_descriptor\",\n\"@com_google_absl//absl/strings\",\ngtest,\n+ \":ip_socket_test_util\",\n+ \":unix_domain_socket_test_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/sendfile_socket.cc", "new_path": "test/syscalls/linux/sendfile_socket.cc", "diff": "#include \"gtest/gtest.h\"\n#include \"absl/strings/string_view.h\"\n+#include \"test/syscalls/linux/ip_socket_test_util.h\"\n#include \"test/syscalls/linux/socket_test_util.h\"\n#include \"test/util/file_descriptor.h\"\n#include \"test/util/temp_path.h\"\n@@ -35,61 +36,39 @@ namespace {\nclass SendFileTest : public ::testing::TestWithParam<int> {\nprotected:\n- PosixErrorOr<std::tuple<int, int>> Sockets() {\n+ PosixErrorOr<std::unique_ptr<SocketPair>> Sockets(int type) {\n// Bind a server socket.\nint family = GetParam();\n- struct sockaddr server_addr = {};\nswitch (family) {\ncase AF_INET: {\n- struct sockaddr_in* server_addr_in =\n- reinterpret_cast<struct sockaddr_in*>(&server_addr);\n- server_addr_in->sin_family = family;\n- server_addr_in->sin_addr.s_addr = INADDR_ANY;\n- break;\n+ if (type == SOCK_STREAM) {\n+ return SocketPairKind{\n+ \"TCP\", AF_INET, type, 0,\n+ TCPAcceptBindSocketPairCreator(AF_INET, type, 0, false)}\n+ .Create();\n+ } else {\n+ return SocketPairKind{\n+ \"UDP\", AF_INET, type, 0,\n+ UDPBidirectionalBindSocketPairCreator(AF_INET, type, 0, false)}\n+ .Create();\n+ }\n}\ncase AF_UNIX: {\n- struct sockaddr_un* server_addr_un =\n- reinterpret_cast<struct sockaddr_un*>(&server_addr);\n- server_addr_un->sun_family = family;\n- server_addr_un->sun_path[0] = '\\0';\n- break;\n+ if (type == SOCK_STREAM) {\n+ return SocketPairKind{\n+ \"UNIX\", AF_UNIX, type, 0,\n+ FilesystemAcceptBindSocketPairCreator(AF_UNIX, type, 0)}\n+ .Create();\n+ } else {\n+ return SocketPairKind{\n+ \"UNIX\", AF_UNIX, type, 0,\n+ FilesystemBidirectionalBindSocketPairCreator(AF_UNIX, type, 0)}\n+ .Create();\n+ }\n}\ndefault:\nreturn PosixError(EINVAL);\n}\n- int server = socket(family, SOCK_STREAM, 0);\n- if (bind(server, &server_addr, sizeof(server_addr)) < 0) {\n- return PosixError(errno);\n- }\n- if (listen(server, 1) < 0) {\n- close(server);\n- return PosixError(errno);\n- }\n-\n- // Fetch the address; both are anonymous.\n- socklen_t length = sizeof(server_addr);\n- if (getsockname(server, &server_addr, &length) < 0) {\n- close(server);\n- return PosixError(errno);\n- }\n-\n- // Connect the client.\n- int client = socket(family, SOCK_STREAM, 0);\n- if (connect(client, &server_addr, length) < 0) {\n- close(server);\n- close(client);\n- return PosixError(errno);\n- }\n-\n- // Accept on the server.\n- int server_client = accept(server, nullptr, 0);\n- if (server_client < 0) {\n- close(server);\n- close(client);\n- return PosixError(errno);\n- }\n- close(server);\n- return std::make_tuple(client, server_client);\n}\n};\n@@ -106,9 +85,7 @@ TEST_P(SendFileTest, SendMultiple) {\nconst TempPath out_file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());\n// Create sockets.\n- std::tuple<int, int> fds = ASSERT_NO_ERRNO_AND_VALUE(Sockets());\n- const FileDescriptor server(std::get<0>(fds));\n- FileDescriptor client(std::get<1>(fds)); // non-const, reset is used.\n+ auto socks = ASSERT_NO_ERRNO_AND_VALUE(Sockets(SOCK_STREAM));\n// Thread that reads data from socket and dumps to a file.\nScopedThread th([&] {\n@@ -118,7 +95,7 @@ TEST_P(SendFileTest, SendMultiple) {\n// Read until socket is closed.\nchar buf[10240];\nfor (int cnt = 0;; cnt++) {\n- int r = RetryEINTR(read)(server.get(), buf, sizeof(buf));\n+ int r = RetryEINTR(read)(socks->first_fd(), buf, sizeof(buf));\n// We cannot afford to save on every read() call.\nif (cnt % 1000 == 0) {\nASSERT_THAT(r, SyscallSucceeds());\n@@ -152,7 +129,7 @@ TEST_P(SendFileTest, SendMultiple) {\n<< \", remain=\" << remain << std::endl;\n// Send data and verify that sendfile returns the correct value.\n- int res = sendfile(client.get(), inf.get(), nullptr, remain);\n+ int res = sendfile(socks->second_fd(), inf.get(), nullptr, remain);\n// We cannot afford to save on every sendfile() call.\nif (cnt % 120 == 0) {\nMaybeSave();\n@@ -169,7 +146,7 @@ TEST_P(SendFileTest, SendMultiple) {\n}\n// Close socket to stop thread.\n- client.reset();\n+ close(socks->release_second_fd());\nth.Join();\n// Verify that the output file has the correct data.\n@@ -183,9 +160,7 @@ TEST_P(SendFileTest, SendMultiple) {\nTEST_P(SendFileTest, Shutdown) {\n// Create a socket.\n- std::tuple<int, int> fds = ASSERT_NO_ERRNO_AND_VALUE(Sockets());\n- const FileDescriptor client(std::get<0>(fds));\n- FileDescriptor server(std::get<1>(fds)); // non-const, reset below.\n+ auto socks = ASSERT_NO_ERRNO_AND_VALUE(Sockets(SOCK_STREAM));\n// If this is a TCP socket, then turn off linger.\nif (GetParam() == AF_INET) {\n@@ -193,7 +168,7 @@ TEST_P(SendFileTest, Shutdown) {\nsl.l_onoff = 1;\nsl.l_linger = 0;\nASSERT_THAT(\n- setsockopt(server.get(), SOL_SOCKET, SO_LINGER, &sl, sizeof(sl)),\n+ setsockopt(socks->first_fd(), SOL_SOCKET, SO_LINGER, &sl, sizeof(sl)),\nSyscallSucceeds());\n}\n@@ -212,12 +187,12 @@ TEST_P(SendFileTest, Shutdown) {\nScopedThread t([&]() {\nsize_t done = 0;\nwhile (done < data.size()) {\n- int n = RetryEINTR(read)(server.get(), data.data(), data.size());\n+ int n = RetryEINTR(read)(socks->first_fd(), data.data(), data.size());\nASSERT_THAT(n, SyscallSucceeds());\ndone += n;\n}\n// Close the server side socket.\n- server.reset();\n+ close(socks->release_first_fd());\n});\n// Continuously stream from the file to the socket. Note we do not assert\n@@ -225,7 +200,7 @@ TEST_P(SendFileTest, Shutdown) {\n// data is written. Eventually, we should get a connection reset error.\nwhile (1) {\noff_t offset = 0; // Always read from the start.\n- int n = sendfile(client.get(), inf.get(), &offset, data.size());\n+ int n = sendfile(socks->second_fd(), inf.get(), &offset, data.size());\nEXPECT_THAT(n, AnyOf(SyscallFailsWithErrno(ECONNRESET),\nSyscallFailsWithErrno(EPIPE), SyscallSucceeds()));\nif (n <= 0) {\n@@ -234,6 +209,20 @@ TEST_P(SendFileTest, Shutdown) {\n}\n}\n+TEST_P(SendFileTest, SendpageFromEmptyFileToUDP) {\n+ auto socks = ASSERT_NO_ERRNO_AND_VALUE(Sockets(SOCK_DGRAM));\n+\n+ TempPath file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());\n+ const FileDescriptor fd =\n+ ASSERT_NO_ERRNO_AND_VALUE(Open(file.path(), O_RDWR));\n+\n+ // The value to the count argument has to be so that it is impossible to\n+ // allocate a buffer of this size. In Linux, sendfile transfer at most\n+ // 0x7ffff000 (MAX_RW_COUNT) bytes.\n+ EXPECT_THAT(sendfile(socks->first_fd(), fd.get(), 0x0, 0x8000000000004),\n+ SyscallSucceedsWithValue(0));\n+}\n+\nINSTANTIATE_TEST_SUITE_P(AddressFamily, SendFileTest,\n::testing::Values(AF_UNIX, AF_INET));\n" } ]
Go
Apache License 2.0
google/gvisor
splice: cap splice calls to MAX_RW_COUNT The Linux does the same. Reported-by: [email protected] PiperOrigin-RevId: 305625439
259,853
09.04.2020 01:11:20
25,200
1ebfdcc86c1b066a044a64e1f34b679f327a1f36
kokoro: fix handling of apt-get errors When a command is called as if expression, its error code can be get only in this if block. For example, the next script prints 0: if ( false ); then true fi echo $?
[ { "change_type": "MODIFY", "old_path": "scripts/common.sh", "new_path": "scripts/common.sh", "diff": "@@ -89,12 +89,20 @@ function install_runsc() {\n# be correct, otherwise this may result in a loop that spins until time out.\nfunction apt_install() {\nwhile true; do\n- if (sudo apt-get update && sudo apt-get install -y \"$@\"); then\n+ sudo apt-get update &&\n+ sudo apt-get install -y \"$@\" &&\n+ true\n+ result=\"${?}\"\n+ case $result in\n+ 0)\nbreak\n- fi\n- result=$?\n- if [[ $result -ne 100 ]]; then\n- return $result\n- fi\n+ ;;\n+ 100)\n+ # 100 is the error code that apt-get returns.\n+ ;;\n+ *)\n+ exit $result\n+ ;;\n+ esac\ndone\n}\n" } ]
Go
Apache License 2.0
google/gvisor
kokoro: fix handling of apt-get errors When a command is called as if expression, its error code can be get only in this if block. For example, the next script prints 0: if ( false ); then true fi echo $? PiperOrigin-RevId: 305638629
259,860
09.04.2020 11:15:42
25,200
2b4687a46bffc0999f1d5730397c13daba6ae4a9
Handle os.LinkError in p9/handlers.go.
[ { "change_type": "MODIFY", "old_path": "pkg/p9/handlers.go", "new_path": "pkg/p9/handlers.go", "diff": "@@ -48,6 +48,8 @@ func ExtractErrno(err error) syscall.Errno {\nreturn ExtractErrno(e.Err)\ncase *os.SyscallError:\nreturn ExtractErrno(e.Err)\n+ case *os.LinkError:\n+ return ExtractErrno(e.Err)\n}\n// Default case.\n" } ]
Go
Apache License 2.0
google/gvisor
Handle os.LinkError in p9/handlers.go. PiperOrigin-RevId: 305721329
260,003
09.04.2020 13:33:18
25,200
64c2b490671852aaa024a4bb4757eef309fadf18
Dedup netlink utility functions in tests.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/BUILD", "new_path": "test/syscalls/linux/BUILD", "diff": "@@ -138,7 +138,6 @@ cc_library(\nhdrs = [\"socket_netlink_route_util.h\"],\ndeps = [\n\":socket_netlink_util\",\n- \"@com_google_absl//absl/types:optional\",\n],\n)\n@@ -2804,13 +2803,13 @@ cc_binary(\nsrcs = [\"socket_netlink_route.cc\"],\nlinkstatic = 1,\ndeps = [\n+ \":socket_netlink_route_util\",\n\":socket_netlink_util\",\n\":socket_test_util\",\n\"//test/util:capability_util\",\n\"//test/util:cleanup\",\n\"//test/util:file_descriptor\",\n\"@com_google_absl//absl/strings:str_format\",\n- \"@com_google_absl//absl/types:optional\",\ngtest,\n\"//test/util:test_main\",\n\"//test/util:test_util\",\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_netlink_route.cc", "new_path": "test/syscalls/linux/socket_netlink_route.cc", "diff": "#include \"gtest/gtest.h\"\n#include \"absl/strings/str_format.h\"\n-#include \"absl/types/optional.h\"\n+#include \"test/syscalls/linux/socket_netlink_route_util.h\"\n#include \"test/syscalls/linux/socket_netlink_util.h\"\n#include \"test/syscalls/linux/socket_test_util.h\"\n#include \"test/util/capability_util.h\"\n@@ -118,24 +118,6 @@ void CheckGetLinkResponse(const struct nlmsghdr* hdr, int seq, int port) {\n// TODO(mpratt): Check ifinfomsg contents and following attrs.\n}\n-PosixError DumpLinks(\n- const FileDescriptor& fd, uint32_t seq,\n- const std::function<void(const struct nlmsghdr* hdr)>& fn) {\n- struct request {\n- struct nlmsghdr hdr;\n- struct ifinfomsg ifm;\n- };\n-\n- struct request req = {};\n- req.hdr.nlmsg_len = sizeof(req);\n- req.hdr.nlmsg_type = RTM_GETLINK;\n- req.hdr.nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP;\n- req.hdr.nlmsg_seq = seq;\n- req.ifm.ifi_family = AF_UNSPEC;\n-\n- return NetlinkRequestResponse(fd, &req, sizeof(req), fn, false);\n-}\n-\nTEST(NetlinkRouteTest, GetLinkDump) {\nFileDescriptor fd =\nASSERT_NO_ERRNO_AND_VALUE(NetlinkBoundSocket(NETLINK_ROUTE));\n@@ -161,37 +143,6 @@ TEST(NetlinkRouteTest, GetLinkDump) {\nEXPECT_TRUE(loopbackFound);\n}\n-struct Link {\n- int index;\n- std::string name;\n-};\n-\n-PosixErrorOr<absl::optional<Link>> FindLoopbackLink() {\n- ASSIGN_OR_RETURN_ERRNO(FileDescriptor fd, NetlinkBoundSocket(NETLINK_ROUTE));\n-\n- absl::optional<Link> link;\n- RETURN_IF_ERRNO(DumpLinks(fd, kSeq, [&](const struct nlmsghdr* hdr) {\n- if (hdr->nlmsg_type != RTM_NEWLINK ||\n- hdr->nlmsg_len < NLMSG_SPACE(sizeof(struct ifinfomsg))) {\n- return;\n- }\n- const struct ifinfomsg* msg =\n- reinterpret_cast<const struct ifinfomsg*>(NLMSG_DATA(hdr));\n- if (msg->ifi_type == ARPHRD_LOOPBACK) {\n- const auto* rta = FindRtAttr(hdr, msg, IFLA_IFNAME);\n- if (rta == nullptr) {\n- // Ignore links that do not have a name.\n- return;\n- }\n-\n- link = Link();\n- link->index = msg->ifi_index;\n- link->name = std::string(reinterpret_cast<const char*>(RTA_DATA(rta)));\n- }\n- }));\n- return link;\n-}\n-\n// CheckLinkMsg checks a netlink message against an expected link.\nvoid CheckLinkMsg(const struct nlmsghdr* hdr, const Link& link) {\nASSERT_THAT(hdr->nlmsg_type, Eq(RTM_NEWLINK));\n@@ -209,9 +160,7 @@ void CheckLinkMsg(const struct nlmsghdr* hdr, const Link& link) {\n}\nTEST(NetlinkRouteTest, GetLinkByIndex) {\n- absl::optional<Link> loopback_link =\n- ASSERT_NO_ERRNO_AND_VALUE(FindLoopbackLink());\n- ASSERT_TRUE(loopback_link.has_value());\n+ Link loopback_link = ASSERT_NO_ERRNO_AND_VALUE(LoopbackLink());\nFileDescriptor fd =\nASSERT_NO_ERRNO_AND_VALUE(NetlinkBoundSocket(NETLINK_ROUTE));\n@@ -227,13 +176,13 @@ TEST(NetlinkRouteTest, GetLinkByIndex) {\nreq.hdr.nlmsg_flags = NLM_F_REQUEST;\nreq.hdr.nlmsg_seq = kSeq;\nreq.ifm.ifi_family = AF_UNSPEC;\n- req.ifm.ifi_index = loopback_link->index;\n+ req.ifm.ifi_index = loopback_link.index;\nbool found = false;\nASSERT_NO_ERRNO(NetlinkRequestResponse(\nfd, &req, sizeof(req),\n[&](const struct nlmsghdr* hdr) {\n- CheckLinkMsg(hdr, *loopback_link);\n+ CheckLinkMsg(hdr, loopback_link);\nfound = true;\n},\nfalse));\n@@ -241,9 +190,7 @@ TEST(NetlinkRouteTest, GetLinkByIndex) {\n}\nTEST(NetlinkRouteTest, GetLinkByName) {\n- absl::optional<Link> loopback_link =\n- ASSERT_NO_ERRNO_AND_VALUE(FindLoopbackLink());\n- ASSERT_TRUE(loopback_link.has_value());\n+ Link loopback_link = ASSERT_NO_ERRNO_AND_VALUE(LoopbackLink());\nFileDescriptor fd =\nASSERT_NO_ERRNO_AND_VALUE(NetlinkBoundSocket(NETLINK_ROUTE));\n@@ -262,8 +209,8 @@ TEST(NetlinkRouteTest, GetLinkByName) {\nreq.hdr.nlmsg_seq = kSeq;\nreq.ifm.ifi_family = AF_UNSPEC;\nreq.rtattr.rta_type = IFLA_IFNAME;\n- req.rtattr.rta_len = RTA_LENGTH(loopback_link->name.size() + 1);\n- strncpy(req.ifname, loopback_link->name.c_str(), sizeof(req.ifname));\n+ req.rtattr.rta_len = RTA_LENGTH(loopback_link.name.size() + 1);\n+ strncpy(req.ifname, loopback_link.name.c_str(), sizeof(req.ifname));\nreq.hdr.nlmsg_len =\nNLMSG_LENGTH(sizeof(req.ifm)) + NLMSG_ALIGN(req.rtattr.rta_len);\n@@ -271,7 +218,7 @@ TEST(NetlinkRouteTest, GetLinkByName) {\nASSERT_NO_ERRNO(NetlinkRequestResponse(\nfd, &req, sizeof(req),\n[&](const struct nlmsghdr* hdr) {\n- CheckLinkMsg(hdr, *loopback_link);\n+ CheckLinkMsg(hdr, loopback_link);\nfound = true;\n},\nfalse));\n@@ -523,9 +470,7 @@ TEST(NetlinkRouteTest, LookupAll) {\nTEST(NetlinkRouteTest, AddAddr) {\nSKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_ADMIN)));\n- absl::optional<Link> loopback_link =\n- ASSERT_NO_ERRNO_AND_VALUE(FindLoopbackLink());\n- ASSERT_TRUE(loopback_link.has_value());\n+ Link loopback_link = ASSERT_NO_ERRNO_AND_VALUE(LoopbackLink());\nFileDescriptor fd =\nASSERT_NO_ERRNO_AND_VALUE(NetlinkBoundSocket(NETLINK_ROUTE));\n@@ -545,7 +490,7 @@ TEST(NetlinkRouteTest, AddAddr) {\nreq.ifa.ifa_prefixlen = 24;\nreq.ifa.ifa_flags = 0;\nreq.ifa.ifa_scope = 0;\n- req.ifa.ifa_index = loopback_link->index;\n+ req.ifa.ifa_index = loopback_link.index;\nreq.rtattr.rta_type = IFA_LOCAL;\nreq.rtattr.rta_len = RTA_LENGTH(sizeof(req.addr));\ninet_pton(AF_INET, \"10.0.0.1\", &req.addr);\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_netlink_route_util.cc", "new_path": "test/syscalls/linux/socket_netlink_route_util.cc", "diff": "#include <linux/netlink.h>\n#include <linux/rtnetlink.h>\n-#include \"absl/types/optional.h\"\n#include \"test/syscalls/linux/socket_netlink_util.h\"\nnamespace gvisor {\n@@ -73,14 +72,14 @@ PosixErrorOr<std::vector<Link>> DumpLinks() {\nreturn links;\n}\n-PosixErrorOr<absl::optional<Link>> FindLoopbackLink() {\n+PosixErrorOr<Link> LoopbackLink() {\nASSIGN_OR_RETURN_ERRNO(auto links, DumpLinks());\nfor (const auto& link : links) {\nif (link.type == ARPHRD_LOOPBACK) {\n- return absl::optional<Link>(link);\n+ return link;\n}\n}\n- return absl::optional<Link>();\n+ return PosixError(ENOENT, \"loopback link not found\");\n}\nPosixError LinkAddLocalAddr(int index, int family, int prefixlen,\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_netlink_route_util.h", "new_path": "test/syscalls/linux/socket_netlink_route_util.h", "diff": "#include <vector>\n-#include \"absl/types/optional.h\"\n#include \"test/syscalls/linux/socket_netlink_util.h\"\nnamespace gvisor {\n@@ -37,7 +36,8 @@ PosixError DumpLinks(const FileDescriptor& fd, uint32_t seq,\nPosixErrorOr<std::vector<Link>> DumpLinks();\n-PosixErrorOr<absl::optional<Link>> FindLoopbackLink();\n+// Returns the loopback link on the system. ENOENT if not found.\n+PosixErrorOr<Link> LoopbackLink();\n// LinkAddLocalAddr sets IFA_LOCAL attribute on the interface.\nPosixError LinkAddLocalAddr(int index, int family, int prefixlen,\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/tuntap.cc", "new_path": "test/syscalls/linux/tuntap.cc", "diff": "@@ -56,14 +56,14 @@ PosixErrorOr<std::set<std::string>> DumpLinkNames() {\nreturn names;\n}\n-PosixErrorOr<absl::optional<Link>> GetLinkByName(const std::string& name) {\n+PosixErrorOr<Link> GetLinkByName(const std::string& name) {\nASSIGN_OR_RETURN_ERRNO(auto links, DumpLinks());\nfor (const auto& link : links) {\nif (link.name == name) {\n- return absl::optional<Link>(link);\n+ return link;\n}\n}\n- return absl::optional<Link>();\n+ return PosixError(ENOENT, \"interface not found\");\n}\nstruct pihdr {\n@@ -268,24 +268,21 @@ PosixErrorOr<FileDescriptor> OpenAndAttachTap(\nreturn PosixError(errno);\n}\n- ASSIGN_OR_RETURN_ERRNO(absl::optional<Link> link, GetLinkByName(dev_name));\n- if (!link.has_value()) {\n- return PosixError(ENOENT, \"no link\");\n- }\n+ ASSIGN_OR_RETURN_ERRNO(auto link, GetLinkByName(dev_name));\n// Interface setup.\nstruct in_addr addr;\ninet_pton(AF_INET, dev_ipv4_addr.c_str(), &addr);\n- EXPECT_NO_ERRNO(LinkAddLocalAddr(link->index, AF_INET, /*prefixlen=*/24,\n- &addr, sizeof(addr)));\n+ EXPECT_NO_ERRNO(LinkAddLocalAddr(link.index, AF_INET, /*prefixlen=*/24, &addr,\n+ sizeof(addr)));\nif (!IsRunningOnGvisor()) {\n// FIXME(b/110961832): gVisor doesn't support setting MAC address on\n// interfaces yet.\n- RETURN_IF_ERRNO(LinkSetMacAddr(link->index, kMacA, sizeof(kMacA)));\n+ RETURN_IF_ERRNO(LinkSetMacAddr(link.index, kMacA, sizeof(kMacA)));\n// FIXME(b/110961832): gVisor always creates enabled/up'd interfaces.\n- RETURN_IF_ERRNO(LinkChangeFlags(link->index, IFF_UP, IFF_UP));\n+ RETURN_IF_ERRNO(LinkChangeFlags(link.index, IFF_UP, IFF_UP));\n}\nreturn fd;\n" } ]
Go
Apache License 2.0
google/gvisor
Dedup netlink utility functions in tests. PiperOrigin-RevId: 305749697
260,003
09.04.2020 16:21:02
25,200
ace90f823cf33d1c1180dcd0d2061c702270a0d6
Make some functions in IfAddrHelper const.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/ip_socket_test_util.cc", "new_path": "test/syscalls/linux/ip_socket_test_util.cc", "diff": "@@ -177,17 +177,17 @@ SocketKind IPv6TCPUnboundSocket(int type) {\nPosixError IfAddrHelper::Load() {\nRelease();\nRETURN_ERROR_IF_SYSCALL_FAIL(getifaddrs(&ifaddr_));\n- return PosixError(0);\n+ return NoError();\n}\nvoid IfAddrHelper::Release() {\nif (ifaddr_) {\nfreeifaddrs(ifaddr_);\n- }\nifaddr_ = nullptr;\n}\n+}\n-std::vector<std::string> IfAddrHelper::InterfaceList(int family) {\n+std::vector<std::string> IfAddrHelper::InterfaceList(int family) const {\nstd::vector<std::string> names;\nfor (auto ifa = ifaddr_; ifa != NULL; ifa = ifa->ifa_next) {\nif (ifa->ifa_addr == NULL || ifa->ifa_addr->sa_family != family) {\n@@ -198,7 +198,7 @@ std::vector<std::string> IfAddrHelper::InterfaceList(int family) {\nreturn names;\n}\n-sockaddr* IfAddrHelper::GetAddr(int family, std::string name) {\n+const sockaddr* IfAddrHelper::GetAddr(int family, std::string name) const {\nfor (auto ifa = ifaddr_; ifa != NULL; ifa = ifa->ifa_next) {\nif (ifa->ifa_addr == NULL || ifa->ifa_addr->sa_family != family) {\ncontinue;\n@@ -210,7 +210,7 @@ sockaddr* IfAddrHelper::GetAddr(int family, std::string name) {\nreturn nullptr;\n}\n-PosixErrorOr<int> IfAddrHelper::GetIndex(std::string name) {\n+PosixErrorOr<int> IfAddrHelper::GetIndex(std::string name) const {\nreturn InterfaceIndex(name);\n}\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/ip_socket_test_util.h", "new_path": "test/syscalls/linux/ip_socket_test_util.h", "diff": "@@ -110,10 +110,10 @@ class IfAddrHelper {\nPosixError Load();\nvoid Release();\n- std::vector<std::string> InterfaceList(int family);\n+ std::vector<std::string> InterfaceList(int family) const;\n- struct sockaddr* GetAddr(int family, std::string name);\n- PosixErrorOr<int> GetIndex(std::string name);\n+ const sockaddr* GetAddr(int family, std::string name) const;\n+ PosixErrorOr<int> GetIndex(std::string name) const;\nprivate:\nstruct ifaddrs* ifaddr_;\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_ipv4_udp_unbound_external_networking.cc", "new_path": "test/syscalls/linux/socket_ipv4_udp_unbound_external_networking.cc", "diff": "@@ -45,37 +45,31 @@ void IPv4UDPUnboundExternalNetworkingSocketTest::SetUp() {\ngot_if_infos_ = false;\n// Get interface list.\n- std::vector<std::string> if_names;\nASSERT_NO_ERRNO(if_helper_.Load());\n- if_names = if_helper_.InterfaceList(AF_INET);\n+ std::vector<std::string> if_names = if_helper_.InterfaceList(AF_INET);\nif (if_names.size() != 2) {\nreturn;\n}\n// Figure out which interface is where.\n- int lo = 0, eth = 1;\n- if (if_names[lo] != \"lo\") {\n- lo = 1;\n- eth = 0;\n- }\n-\n- if (if_names[lo] != \"lo\") {\n- return;\n- }\n-\n- lo_if_idx_ = ASSERT_NO_ERRNO_AND_VALUE(if_helper_.GetIndex(if_names[lo]));\n- lo_if_addr_ = if_helper_.GetAddr(AF_INET, if_names[lo]);\n- if (lo_if_addr_ == nullptr) {\n+ std::string lo = if_names[0];\n+ std::string eth = if_names[1];\n+ if (lo != \"lo\") std::swap(lo, eth);\n+ if (lo != \"lo\") return;\n+\n+ lo_if_idx_ = ASSERT_NO_ERRNO_AND_VALUE(if_helper_.GetIndex(lo));\n+ auto lo_if_addr = if_helper_.GetAddr(AF_INET, lo);\n+ if (lo_if_addr == nullptr) {\nreturn;\n}\n- lo_if_sin_addr_ = reinterpret_cast<sockaddr_in*>(lo_if_addr_)->sin_addr;\n+ lo_if_addr_ = *reinterpret_cast<const sockaddr_in*>(lo_if_addr);\n- eth_if_idx_ = ASSERT_NO_ERRNO_AND_VALUE(if_helper_.GetIndex(if_names[eth]));\n- eth_if_addr_ = if_helper_.GetAddr(AF_INET, if_names[eth]);\n- if (eth_if_addr_ == nullptr) {\n+ eth_if_idx_ = ASSERT_NO_ERRNO_AND_VALUE(if_helper_.GetIndex(eth));\n+ auto eth_if_addr = if_helper_.GetAddr(AF_INET, eth);\n+ if (eth_if_addr == nullptr) {\nreturn;\n}\n- eth_if_sin_addr_ = reinterpret_cast<sockaddr_in*>(eth_if_addr_)->sin_addr;\n+ eth_if_addr_ = *reinterpret_cast<const sockaddr_in*>(eth_if_addr);\ngot_if_infos_ = true;\n}\n@@ -242,7 +236,7 @@ TEST_P(IPv4UDPUnboundExternalNetworkingSocketTest,\n// Bind the non-receiving socket to the unicast ethernet address.\nauto norecv_addr = rcv1_addr;\nreinterpret_cast<sockaddr_in*>(&norecv_addr.addr)->sin_addr =\n- eth_if_sin_addr_;\n+ eth_if_addr_.sin_addr;\nASSERT_THAT(bind(norcv->get(), reinterpret_cast<sockaddr*>(&norecv_addr.addr),\nnorecv_addr.addr_len),\nSyscallSucceedsWithValue(0));\n@@ -1028,7 +1022,7 @@ TEST_P(IPv4UDPUnboundExternalNetworkingSocketTest,\nauto sender = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());\nip_mreqn iface = {};\niface.imr_ifindex = lo_if_idx_;\n- iface.imr_address = eth_if_sin_addr_;\n+ iface.imr_address = eth_if_addr_.sin_addr;\nASSERT_THAT(setsockopt(sender->get(), IPPROTO_IP, IP_MULTICAST_IF, &iface,\nsizeof(iface)),\nSyscallSucceeds());\n@@ -1058,7 +1052,7 @@ TEST_P(IPv4UDPUnboundExternalNetworkingSocketTest,\nSKIP_IF(IsRunningOnGvisor());\n// Verify the received source address.\n- EXPECT_EQ(eth_if_sin_addr_.s_addr, src_addr_in->sin_addr.s_addr);\n+ EXPECT_EQ(eth_if_addr_.sin_addr.s_addr, src_addr_in->sin_addr.s_addr);\n}\n// Check that when we are bound to one interface we can set IP_MULTICAST_IF to\n@@ -1075,7 +1069,8 @@ TEST_P(IPv4UDPUnboundExternalNetworkingSocketTest,\n// Create sender and bind to eth interface.\nauto sender = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());\n- ASSERT_THAT(bind(sender->get(), eth_if_addr_, sizeof(sockaddr_in)),\n+ ASSERT_THAT(bind(sender->get(), reinterpret_cast<sockaddr*>(&eth_if_addr_),\n+ sizeof(eth_if_addr_)),\nSyscallSucceeds());\n// Run through all possible combinations of index and address for\n@@ -1085,9 +1080,9 @@ TEST_P(IPv4UDPUnboundExternalNetworkingSocketTest,\nstruct in_addr imr_address;\n} test_data[] = {\n{lo_if_idx_, {}},\n- {0, lo_if_sin_addr_},\n- {lo_if_idx_, lo_if_sin_addr_},\n- {lo_if_idx_, eth_if_sin_addr_},\n+ {0, lo_if_addr_.sin_addr},\n+ {lo_if_idx_, lo_if_addr_.sin_addr},\n+ {lo_if_idx_, eth_if_addr_.sin_addr},\n};\nfor (auto t : test_data) {\nip_mreqn iface = {};\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_ipv4_udp_unbound_external_networking.h", "new_path": "test/syscalls/linux/socket_ipv4_udp_unbound_external_networking.h", "diff": "@@ -36,10 +36,8 @@ class IPv4UDPUnboundExternalNetworkingSocketTest : public SimpleSocketTest {\n// Interface infos.\nint lo_if_idx_;\nint eth_if_idx_;\n- sockaddr* lo_if_addr_;\n- sockaddr* eth_if_addr_;\n- in_addr lo_if_sin_addr_;\n- in_addr eth_if_sin_addr_;\n+ sockaddr_in lo_if_addr_;\n+ sockaddr_in eth_if_addr_;\n};\n} // namespace testing\n" } ]
Go
Apache License 2.0
google/gvisor
Make some functions in IfAddrHelper const. PiperOrigin-RevId: 305782490
259,992
09.04.2020 16:40:12
25,200
9f87502b4619b60779ce19c41ea0e6bd6582e8e4
Remove TODOs from Async IO Block and drain requests in io_destroy(2). Note the reason to create read-only mapping.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/mm/aio_context.go", "new_path": "pkg/sentry/mm/aio_context.go", "diff": "@@ -59,25 +59,27 @@ func (a *aioManager) newAIOContext(events uint32, id uint64) bool {\n}\na.contexts[id] = &AIOContext{\n- done: make(chan struct{}, 1),\n+ requestReady: make(chan struct{}, 1),\nmaxOutstanding: events,\n}\nreturn true\n}\n-// destroyAIOContext destroys an asynchronous I/O context.\n+// destroyAIOContext destroys an asynchronous I/O context. It doesn't wait for\n+// for pending requests to complete. Returns the destroyed AIOContext so it can\n+// be drained.\n//\n-// False is returned if the context does not exist.\n-func (a *aioManager) destroyAIOContext(id uint64) bool {\n+// Nil is returned if the context does not exist.\n+func (a *aioManager) destroyAIOContext(id uint64) *AIOContext {\na.mu.Lock()\ndefer a.mu.Unlock()\nctx, ok := a.contexts[id]\nif !ok {\n- return false\n+ return nil\n}\ndelete(a.contexts, id)\nctx.destroy()\n- return true\n+ return ctx\n}\n// lookupAIOContext looks up the given context.\n@@ -102,8 +104,8 @@ type ioResult struct {\n//\n// +stateify savable\ntype AIOContext struct {\n- // done is the notification channel used for all requests.\n- done chan struct{} `state:\"nosave\"`\n+ // requestReady is the notification channel used for all requests.\n+ requestReady chan struct{} `state:\"nosave\"`\n// mu protects below.\nmu sync.Mutex `state:\"nosave\"`\n@@ -129,8 +131,14 @@ func (ctx *AIOContext) destroy() {\nctx.mu.Lock()\ndefer ctx.mu.Unlock()\nctx.dead = true\n- if ctx.outstanding == 0 {\n- close(ctx.done)\n+ ctx.checkForDone()\n+}\n+\n+// Preconditions: ctx.mu must be held by caller.\n+func (ctx *AIOContext) checkForDone() {\n+ if ctx.dead && ctx.outstanding == 0 {\n+ close(ctx.requestReady)\n+ ctx.requestReady = nil\n}\n}\n@@ -154,11 +162,12 @@ func (ctx *AIOContext) PopRequest() (interface{}, bool) {\n// Is there anything ready?\nif e := ctx.results.Front(); e != nil {\n- ctx.results.Remove(e)\n- ctx.outstanding--\n- if ctx.outstanding == 0 && ctx.dead {\n- close(ctx.done)\n+ if ctx.outstanding == 0 {\n+ panic(\"AIOContext outstanding is going negative\")\n}\n+ ctx.outstanding--\n+ ctx.results.Remove(e)\n+ ctx.checkForDone()\nreturn e.data, true\n}\nreturn nil, false\n@@ -172,26 +181,58 @@ func (ctx *AIOContext) FinishRequest(data interface{}) {\n// Push to the list and notify opportunistically. The channel notify\n// here is guaranteed to be safe because outstanding must be non-zero.\n- // The done channel is only closed when outstanding reaches zero.\n+ // The requestReady channel is only closed when outstanding reaches zero.\nctx.results.PushBack(&ioResult{data: data})\nselect {\n- case ctx.done <- struct{}{}:\n+ case ctx.requestReady <- struct{}{}:\ndefault:\n}\n}\n// WaitChannel returns a channel that is notified when an AIO request is\n-// completed.\n-//\n-// The boolean return value indicates whether or not the context is active.\n-func (ctx *AIOContext) WaitChannel() (chan struct{}, bool) {\n+// completed. Returns nil if the context is destroyed and there are no more\n+// outstanding requests.\n+func (ctx *AIOContext) WaitChannel() chan struct{} {\nctx.mu.Lock()\ndefer ctx.mu.Unlock()\n- if ctx.outstanding == 0 && ctx.dead {\n- return nil, false\n+ return ctx.requestReady\n+}\n+\n+// Dead returns true if the context has been destroyed.\n+func (ctx *AIOContext) Dead() bool {\n+ ctx.mu.Lock()\n+ defer ctx.mu.Unlock()\n+ return ctx.dead\n}\n- return ctx.done, true\n+\n+// CancelPendingRequest forgets about a request that hasn't yet completed.\n+func (ctx *AIOContext) CancelPendingRequest() {\n+ ctx.mu.Lock()\n+ defer ctx.mu.Unlock()\n+\n+ if ctx.outstanding == 0 {\n+ panic(\"AIOContext outstanding is going negative\")\n+ }\n+ ctx.outstanding--\n+ ctx.checkForDone()\n+}\n+\n+// Drain drops all completed requests. Pending requests remain untouched.\n+func (ctx *AIOContext) Drain() {\n+ ctx.mu.Lock()\n+ defer ctx.mu.Unlock()\n+\n+ if ctx.outstanding == 0 {\n+ return\n+ }\n+ size := uint32(ctx.results.Len())\n+ if ctx.outstanding < size {\n+ panic(\"AIOContext outstanding is going negative\")\n+ }\n+ ctx.outstanding -= size\n+ ctx.results.Reset()\n+ ctx.checkForDone()\n}\n// aioMappable implements memmap.MappingIdentity and memmap.Mappable for AIO\n@@ -332,9 +373,9 @@ func (mm *MemoryManager) NewAIOContext(ctx context.Context, events uint32) (uint\nLength: aioRingBufferSize,\nMappingIdentity: m,\nMappable: m,\n- // TODO(fvoznika): Linux does \"do_mmap_pgoff(..., PROT_READ |\n- // PROT_WRITE, ...)\" in fs/aio.c:aio_setup_ring(); why do we make this\n- // mapping read-only?\n+ // Linux uses \"do_mmap_pgoff(..., PROT_READ | PROT_WRITE, ...)\" in\n+ // fs/aio.c:aio_setup_ring(). Since we don't implement AIO_RING_MAGIC,\n+ // user mode should not write to this page.\nPerms: usermem.Read,\nMaxPerms: usermem.Read,\n})\n@@ -349,11 +390,11 @@ func (mm *MemoryManager) NewAIOContext(ctx context.Context, events uint32) (uint\nreturn id, nil\n}\n-// DestroyAIOContext destroys an asynchronous I/O context. It returns false if\n-// the context does not exist.\n-func (mm *MemoryManager) DestroyAIOContext(ctx context.Context, id uint64) bool {\n+// DestroyAIOContext destroys an asynchronous I/O context. It returns the\n+// destroyed context. nil if the context does not exist.\n+func (mm *MemoryManager) DestroyAIOContext(ctx context.Context, id uint64) *AIOContext {\nif _, ok := mm.LookupAIOContext(ctx, id); !ok {\n- return false\n+ return nil\n}\n// Only unmaps after it assured that the address is a valid aio context to\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/mm/aio_context_state.go", "new_path": "pkg/sentry/mm/aio_context_state.go", "diff": "@@ -16,5 +16,5 @@ package mm\n// afterLoad is invoked by stateify.\nfunc (a *AIOContext) afterLoad() {\n- a.done = make(chan struct{}, 1)\n+ a.requestReady = make(chan struct{}, 1)\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/sys_aio.go", "new_path": "pkg/sentry/syscalls/linux/sys_aio.go", "diff": "@@ -114,15 +114,29 @@ func IoSetup(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sysca\nfunc IoDestroy(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {\nid := args[0].Uint64()\n- // Destroy the given context.\n- if !t.MemoryManager().DestroyAIOContext(t, id) {\n+ ctx := t.MemoryManager().DestroyAIOContext(t, id)\n+ if ctx == nil {\n// Does not exist.\nreturn 0, nil, syserror.EINVAL\n}\n- // FIXME(fvoznika): Linux blocks until all AIO to the destroyed context is\n- // done.\n+\n+ // Drain completed requests amd wait for pending requests until there are no\n+ // more.\n+ for {\n+ ctx.Drain()\n+\n+ ch := ctx.WaitChannel()\n+ if ch == nil {\n+ // No more requests, we're done.\nreturn 0, nil, nil\n}\n+ // The task cannot be interrupted during the wait. Equivalent to\n+ // TASK_UNINTERRUPTIBLE in Linux.\n+ t.UninterruptibleSleepStart(true /* deactivate */)\n+ <-ch\n+ t.UninterruptibleSleepFinish(true /* activate */)\n+ }\n+}\n// IoGetevents implements linux syscall io_getevents(2).\nfunc IoGetevents(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {\n@@ -200,13 +214,13 @@ func IoGetevents(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.S\nfunc waitForRequest(ctx *mm.AIOContext, t *kernel.Task, haveDeadline bool, deadline ktime.Time) (interface{}, error) {\nfor {\nif v, ok := ctx.PopRequest(); ok {\n- // Request was readly available. Just return it.\n+ // Request was readily available. Just return it.\nreturn v, nil\n}\n// Need to wait for request completion.\n- done, active := ctx.WaitChannel()\n- if !active {\n+ done := ctx.WaitChannel()\n+ if done == nil {\n// Context has been destroyed.\nreturn nil, syserror.EINVAL\n}\n@@ -248,6 +262,10 @@ func memoryFor(t *kernel.Task, cb *ioCallback) (usermem.IOSequence, error) {\n}\nfunc performCallback(t *kernel.Task, file *fs.File, cbAddr usermem.Addr, cb *ioCallback, ioseq usermem.IOSequence, ctx *mm.AIOContext, eventFile *fs.File) {\n+ if ctx.Dead() {\n+ ctx.CancelPendingRequest()\n+ return\n+ }\nev := &ioEvent{\nData: cb.Data,\nObj: uint64(cbAddr),\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/aio.cc", "new_path": "test/syscalls/linux/aio.cc", "diff": "@@ -89,6 +89,7 @@ class AIOTest : public FileTest {\nFileTest::TearDown();\nif (ctx_ != 0) {\nASSERT_THAT(DestroyContext(), SyscallSucceeds());\n+ ctx_ = 0;\n}\n}\n@@ -188,16 +189,21 @@ TEST_F(AIOTest, BadWrite) {\n}\nTEST_F(AIOTest, ExitWithPendingIo) {\n- // Setup a context that is 5 entries deep.\n- ASSERT_THAT(SetupContext(5), SyscallSucceeds());\n+ // Setup a context that is 100 entries deep.\n+ ASSERT_THAT(SetupContext(100), SyscallSucceeds());\nstruct iocb cb = CreateCallback();\nstruct iocb* cbs[] = {&cb};\n// Submit a request but don't complete it to make it pending.\n+ for (int i = 0; i < 100; ++i) {\nEXPECT_THAT(Submit(1, cbs), SyscallSucceeds());\n}\n+ ASSERT_THAT(DestroyContext(), SyscallSucceeds());\n+ ctx_ = 0;\n+}\n+\nint Submitter(void* arg) {\nauto test = reinterpret_cast<AIOTest*>(arg);\n" } ]
Go
Apache License 2.0
google/gvisor
Remove TODOs from Async IO Block and drain requests in io_destroy(2). Note the reason to create read-only mapping. PiperOrigin-RevId: 305786312
259,992
09.04.2020 17:19:08
25,200
2a28e3e9c3463cf68cfa639425cfdcc298ad357a
Don't unconditionally set --panic-signal Closes
[ { "change_type": "MODIFY", "old_path": "runsc/sandbox/sandbox.go", "new_path": "runsc/sandbox/sandbox.go", "diff": "@@ -402,8 +402,6 @@ func (s *Sandbox) createSandboxProcess(conf *boot.Config, args *Args, startSyncF\nnextFD++\n}\n- cmd.Args = append(cmd.Args, \"--panic-signal=\"+strconv.Itoa(int(syscall.SIGTERM)))\n-\n// Add the \"boot\" command to the args.\n//\n// All flags after this must be for the boot command\n" } ]
Go
Apache License 2.0
google/gvisor
Don't unconditionally set --panic-signal Closes #2393 PiperOrigin-RevId: 305793027
259,885
09.04.2020 17:29:43
25,200
257225c34b81ff0d0b5ce8ae333f5905f9e86cce
Downgrade VFS1-specific FIXME to a NOTE.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/dirent.go", "new_path": "pkg/sentry/fs/dirent.go", "diff": "@@ -312,9 +312,9 @@ func (d *Dirent) SyncAll(ctx context.Context) {\n// There is nothing to sync for a read-only filesystem.\nif !d.Inode.MountSource.Flags.ReadOnly {\n- // FIXME(b/34856369): This should be a mount traversal, not a\n- // Dirent traversal, because some Inodes that need to be synced\n- // may no longer be reachable by name (after sys_unlink).\n+ // NOTE(b/34856369): This should be a mount traversal, not a Dirent\n+ // traversal, because some Inodes that need to be synced may no longer\n+ // be reachable by name (after sys_unlink).\n//\n// Write out metadata, dirty page cached pages, and sync disk/remote\n// caches.\n" } ]
Go
Apache License 2.0
google/gvisor
Downgrade VFS1-specific FIXME to a NOTE. PiperOrigin-RevId: 305794509
260,003
09.04.2020 17:59:30
25,200
c9195349c9ac24ccb538e92b308225dfa4184c42
Replace type assertion with TaskFromContext. This should fix panic at aio callback.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netstack/netstack.go", "new_path": "pkg/sentry/socket/netstack/netstack.go", "diff": "@@ -535,7 +535,7 @@ func (s *SocketOperations) Write(ctx context.Context, _ *fs.File, src usermem.IO\n}\nif resCh != nil {\n- t := ctx.(*kernel.Task)\n+ t := kernel.TaskFromContext(ctx)\nif err := t.Block(resCh); err != nil {\nreturn 0, syserr.FromError(err).ToError()\n}\n@@ -608,7 +608,7 @@ func (s *SocketOperations) ReadFrom(ctx context.Context, _ *fs.File, r io.Reader\n}\nif resCh != nil {\n- t := ctx.(*kernel.Task)\n+ t := kernel.TaskFromContext(ctx)\nif err := t.Block(resCh); err != nil {\nreturn 0, syserr.FromError(err).ToError()\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Replace type assertion with TaskFromContext. This should fix panic at aio callback. PiperOrigin-RevId: 305798549
259,974
17.03.2020 06:59:54
0
35e6b6bf1aeb909a12fb80cc99d5695408a9eaa5
Enable syscall fork_test on arm64.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/fork.cc", "new_path": "test/syscalls/linux/fork.cc", "diff": "@@ -431,7 +431,6 @@ TEST(CloneTest, NewUserNamespacePermitsAllOtherNamespaces) {\n<< \"status = \" << status;\n}\n-#ifdef __x86_64__\n// Clone with CLONE_SETTLS and a non-canonical TLS address is rejected.\nTEST(CloneTest, NonCanonicalTLS) {\nconstexpr uintptr_t kNonCanonical = 1ull << 48;\n@@ -440,11 +439,25 @@ TEST(CloneTest, NonCanonicalTLS) {\n// on this.\nchar stack;\n+ // The raw system call interface on x86-64 is:\n+ // long clone(unsigned long flags, void *stack,\n+ // int *parent_tid, int *child_tid,\n+ // unsigned long tls);\n+ //\n+ // While on arm64, the order of the last two arguments is reversed:\n+ // long clone(unsigned long flags, void *stack,\n+ // int *parent_tid, unsigned long tls,\n+ // int *child_tid);\n+#if defined(__x86_64__)\nEXPECT_THAT(syscall(__NR_clone, SIGCHLD | CLONE_SETTLS, &stack, nullptr,\nnullptr, kNonCanonical),\nSyscallFailsWithErrno(EPERM));\n-}\n+#elif defined(__aarch64__)\n+ EXPECT_THAT(syscall(__NR_clone, SIGCHLD | CLONE_SETTLS, &stack, nullptr,\n+ kNonCanonical, nullptr),\n+ SyscallFailsWithErrno(EPERM));\n#endif\n+}\n} // namespace\n} // namespace testing\n" } ]
Go
Apache License 2.0
google/gvisor
Enable syscall fork_test on arm64. Signed-off-by: Haibo Xu <[email protected]> Change-Id: I033692bcf4f8139df29e369a12b150d10fccbe32
259,974
11.03.2020 03:21:34
0
7aa5caae71c29b0be9047a7c156a9daaa435ebb8
Enable syscall ptrace test on arm64.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/arch/arch.go", "new_path": "pkg/sentry/arch/arch.go", "diff": "@@ -88,6 +88,9 @@ type Context interface {\n// SyscallNo returns the syscall number.\nSyscallNo() uintptr\n+ // SyscallSaveOrig save orignal register value.\n+ SyscallSaveOrig()\n+\n// SyscallArgs returns the syscall arguments in an array.\nSyscallArgs() SyscallArguments\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/arch/syscalls_amd64.go", "new_path": "pkg/sentry/arch/syscalls_amd64.go", "diff": "@@ -18,6 +18,13 @@ package arch\nconst restartSyscallNr = uintptr(219)\n+// SyscallSaveOrig save the value of the register which is clobbered in\n+// syscall handler(doSyscall()).\n+//\n+// Noop on x86.\n+func (c *context64) SyscallSaveOrig() {\n+}\n+\n// SyscallNo returns the syscall number according to the 64-bit convention.\nfunc (c *context64) SyscallNo() uintptr {\nreturn uintptr(c.Regs.Orig_rax)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/arch/syscalls_arm64.go", "new_path": "pkg/sentry/arch/syscalls_arm64.go", "diff": "@@ -18,6 +18,17 @@ package arch\nconst restartSyscallNr = uintptr(128)\n+// SyscallSaveOrig save the value of the register R0 which is clobbered in\n+// syscall handler(doSyscall()).\n+//\n+// In linux, at the entry of the syscall handler(el0_svc_common()), value of R0\n+// is saved to the pt_regs.orig_x0 in kernel code. But currently, the orig_x0\n+// was not accessible to the user space application, so we have to do the same\n+// operation in the sentry code to save the R0 value into the App context.\n+func (c *context64) SyscallSaveOrig() {\n+ c.OrigR0 = c.Regs.Regs[0]\n+}\n+\n// SyscallNo returns the syscall number according to the 64-bit convention.\nfunc (c *context64) SyscallNo() uintptr {\nreturn uintptr(c.Regs.Regs[8])\n@@ -40,7 +51,7 @@ func (c *context64) SyscallNo() uintptr {\n// R30: the link register.\nfunc (c *context64) SyscallArgs() SyscallArguments {\nreturn SyscallArguments{\n- SyscallArgument{Value: uintptr(c.Regs.Regs[0])},\n+ SyscallArgument{Value: uintptr(c.OrigR0)},\nSyscallArgument{Value: uintptr(c.Regs.Regs[1])},\nSyscallArgument{Value: uintptr(c.Regs.Regs[2])},\nSyscallArgument{Value: uintptr(c.Regs.Regs[3])},\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/task_syscall.go", "new_path": "pkg/sentry/kernel/task_syscall.go", "diff": "@@ -194,6 +194,19 @@ func (t *Task) executeSyscall(sysno uintptr, args arch.SyscallArguments) (rval u\n//\n// The syscall path is very hot; avoid defer.\nfunc (t *Task) doSyscall() taskRunState {\n+ // Save value of the register which is clobbered in the following\n+ // t.Arch().SetReturn(-ENOSYS) operation. This is dedicated to arm64.\n+ //\n+ // On x86, register rax was shared by syscall number and return\n+ // value, and at the entry of the syscall handler, the rax was\n+ // saved to regs.orig_rax which was exposed to user space.\n+ // But on arm64, syscall number was passed through X8, and the X0\n+ // was shared by the first syscall argument and return value. The\n+ // X0 was saved to regs.orig_x0 which was not exposed to user space.\n+ // So we have to do the same operation here to save the X0 value\n+ // into the task context.\n+ t.Arch().SyscallSaveOrig()\n+\nsysno := t.Arch().SyscallNo()\nargs := t.Arch().SyscallArgs()\n@@ -269,6 +282,7 @@ func (*runSyscallAfterSyscallEnterStop) execute(t *Task) taskRunState {\nreturn (*runSyscallExit)(nil)\n}\nargs := t.Arch().SyscallArgs()\n+\nreturn t.doSyscallInvoke(sysno, args)\n}\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/ptrace.cc", "new_path": "test/syscalls/linux/ptrace.cc", "diff": "@@ -400,9 +400,11 @@ TEST(PtraceTest, GetRegSet) {\n// Read exactly the full register set.\nEXPECT_EQ(iov.iov_len, sizeof(regs));\n-#ifdef __x86_64__\n+#if defined(__x86_64__)\n// Child called kill(2), with SIGSTOP as arg 2.\nEXPECT_EQ(regs.rsi, SIGSTOP);\n+#elif defined(__aarch64__)\n+ EXPECT_EQ(regs.regs[1], SIGSTOP);\n#endif\n// Suppress SIGSTOP and resume the child.\n@@ -752,15 +754,23 @@ TEST(PtraceTest,\nSyscallSucceeds());\nEXPECT_TRUE(siginfo.si_code == SIGTRAP || siginfo.si_code == (SIGTRAP | 0x80))\n<< \"si_code = \" << siginfo.si_code;\n-#ifdef __x86_64__\n+\n{\nstruct user_regs_struct regs = {};\n- ASSERT_THAT(ptrace(PTRACE_GETREGS, child_pid, 0, &regs), SyscallSucceeds());\n+ struct iovec iov;\n+ iov.iov_base = &regs;\n+ iov.iov_len = sizeof(regs);\n+ EXPECT_THAT(ptrace(PTRACE_GETREGSET, child_pid, NT_PRSTATUS, &iov),\n+ SyscallSucceeds());\n+#if defined(__x86_64__)\nEXPECT_TRUE(regs.orig_rax == SYS_vfork || regs.orig_rax == SYS_clone)\n<< \"orig_rax = \" << regs.orig_rax;\nEXPECT_EQ(grandchild_pid, regs.rax);\n- }\n+#elif defined(__aarch64__)\n+ EXPECT_TRUE(regs.regs[8] == SYS_clone) << \"regs[8] = \" << regs.regs[8];\n+ EXPECT_EQ(grandchild_pid, regs.regs[0]);\n#endif // defined(__x86_64__)\n+ }\n// After this point, the child will be making wait4 syscalls that will be\n// interrupted by saving, so saving is not permitted. Note that this is\n@@ -805,14 +815,21 @@ TEST(PtraceTest,\nSyscallSucceedsWithValue(child_pid));\nEXPECT_TRUE(WIFSTOPPED(status) && WSTOPSIG(status) == (SIGTRAP | 0x80))\n<< \" status \" << status;\n-#ifdef __x86_64__\n{\nstruct user_regs_struct regs = {};\n- ASSERT_THAT(ptrace(PTRACE_GETREGS, child_pid, 0, &regs), SyscallSucceeds());\n+ struct iovec iov;\n+ iov.iov_base = &regs;\n+ iov.iov_len = sizeof(regs);\n+ EXPECT_THAT(ptrace(PTRACE_GETREGSET, child_pid, NT_PRSTATUS, &iov),\n+ SyscallSucceeds());\n+#if defined(__x86_64__)\nEXPECT_EQ(SYS_wait4, regs.orig_rax);\nEXPECT_EQ(grandchild_pid, regs.rax);\n- }\n+#elif defined(__aarch64__)\n+ EXPECT_EQ(SYS_wait4, regs.regs[8]);\n+ EXPECT_EQ(grandchild_pid, regs.regs[0]);\n#endif // defined(__x86_64__)\n+ }\n// Detach from the child and wait for it to exit.\nASSERT_THAT(ptrace(PTRACE_DETACH, child_pid, 0, 0), SyscallSucceeds());\n" } ]
Go
Apache License 2.0
google/gvisor
Enable syscall ptrace test on arm64. Signed-off-by: Haibo Xu <[email protected]> Change-Id: I5bb8fa7d580d173b1438d6465e1adb442216c8fa
259,853
10.04.2020 07:13:16
25,200
935007937cee1e2867cc4fc5c00b7f370864e241
test: remove 1s delay after non-blocking socket pair accept It was added in cl/201419897 to deflake socket_ip_tcp_loopback_non_blocking_test_gvisor. It seems we don't need this hack, because the origin issue isn't reproducible without this hack.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_test_util.cc", "new_path": "test/syscalls/linux/socket_test_util.cc", "diff": "@@ -364,11 +364,6 @@ CreateTCPConnectAcceptSocketPair(int bound, int connected, int type,\n}\nMaybeSave(); // Successful accept.\n- // FIXME(b/110484944)\n- if (connect_result == -1) {\n- absl::SleepFor(absl::Seconds(1));\n- }\n-\nT extra_addr = {};\nLocalhostAddr(&extra_addr, dual_stack);\nreturn absl::make_unique<AddrFDSocketPair>(connected, accepted, bind_addr,\n" } ]
Go
Apache License 2.0
google/gvisor
test: remove 1s delay after non-blocking socket pair accept It was added in cl/201419897 to deflake socket_ip_tcp_loopback_non_blocking_test_gvisor. It seems we don't need this hack, because the origin issue isn't reproducible without this hack. PiperOrigin-RevId: 305871748
259,972
10.04.2020 08:20:56
25,200
12b00c815638a28943c23d3be6ef09b955c6149e
Test that RST is sent after ABORT in ESTABLISHED TCP state.
[ { "change_type": "MODIFY", "old_path": "test/packetimpact/tests/BUILD", "new_path": "test/packetimpact/tests/BUILD", "diff": "@@ -40,6 +40,18 @@ packetimpact_go_test(\n],\n)\n+packetimpact_go_test(\n+ name = \"tcp_noaccept_close_rst\",\n+ srcs = [\"tcp_noaccept_close_rst_test.go\"],\n+ # TODO(b/153380909): Fix netstack then remove the line below.\n+ netstack = False,\n+ deps = [\n+ \"//pkg/tcpip/header\",\n+ \"//test/packetimpact/testbench\",\n+ \"@org_golang_x_sys//unix:go_default_library\",\n+ ],\n+)\n+\nsh_binary(\nname = \"test_runner\",\nsrcs = [\"test_runner.sh\"],\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test/packetimpact/tests/tcp_noaccept_close_rst_test.go", "diff": "+// Copyright 2020 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 tcp_noaccept_close_rst_test\n+\n+import (\n+ \"testing\"\n+ \"time\"\n+\n+ \"golang.org/x/sys/unix\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/header\"\n+ tb \"gvisor.dev/gvisor/test/packetimpact/testbench\"\n+)\n+\n+func TestTcpNoAcceptCloseReset(t *testing.T) {\n+ dut := tb.NewDUT(t)\n+ defer dut.TearDown()\n+ listenFd, remotePort := dut.CreateListener(unix.SOCK_STREAM, unix.IPPROTO_TCP, 1)\n+ conn := tb.NewTCPIPv4(t, tb.TCP{DstPort: &remotePort}, tb.TCP{SrcPort: &remotePort})\n+ conn.Handshake()\n+ defer conn.Close()\n+ dut.Close(listenFd)\n+ if _, err := conn.Expect(tb.TCP{Flags: tb.Uint8(header.TCPFlagRst | header.TCPFlagAck)}, 1*time.Second); err != nil {\n+ t.Fatalf(\"expected a RST-ACK packet but got none: %s\", err)\n+ }\n+}\n" } ]
Go
Apache License 2.0
google/gvisor
Test that RST is sent after ABORT in ESTABLISHED TCP state. PiperOrigin-RevId: 305879441
259,992
10.04.2020 11:17:59
25,200
1798d6cbee3360b09d3736069e15fd746e863bd2
Remove TODO from kernel.Stracer The dependency strace=>kernel grew over time. strace also depends on task's FD table and FSContext. It could be fixed with some interfaces the other way, but then we're trading an interface for another, and kernel.Stracer is likely cleaner. Closes
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/syscalls.go", "new_path": "pkg/sentry/kernel/syscalls.go", "diff": "@@ -209,9 +209,6 @@ type Stracer interface {\n// SyscallEnter is called on syscall entry.\n//\n// The returned private data is passed to SyscallExit.\n- //\n- // TODO(gvisor.dev/issue/155): remove kernel imports from the strace\n- // package so that the type can be used directly.\nSyscallEnter(t *Task, sysno uintptr, args arch.SyscallArguments, flags uint32) interface{}\n// SyscallExit is called on syscall exit.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/strace/strace.go", "new_path": "pkg/sentry/strace/strace.go", "diff": "@@ -778,9 +778,6 @@ func (s SyscallMap) Name(sysno uintptr) string {\n//\n// N.B. This is not in an init function because we can't be sure all syscall\n// tables are registered with the kernel when init runs.\n-//\n-// TODO(gvisor.dev/issue/155): remove kernel package dependencies from this\n-// package and have the kernel package self-initialize all syscall tables.\nfunc Initialize() {\nfor _, table := range kernel.SyscallTables() {\n// Is this known?\n" } ]
Go
Apache License 2.0
google/gvisor
Remove TODO from kernel.Stracer The dependency strace=>kernel grew over time. strace also depends on task's FD table and FSContext. It could be fixed with some interfaces the other way, but then we're trading an interface for another, and kernel.Stracer is likely cleaner. Closes #155 PiperOrigin-RevId: 305909678
259,860
10.04.2020 11:35:38
25,200
8bb8027d55d59c9c08e4b7896cf688c0225a1244
Return EIO from p9 if sending/receiving fails. Continues the modifications in cl/272963663. This prevents non-syscall errors from being propogated to kernel/task_syscall.go:ExtractErrno(), which causes a sentry panic.
[ { "change_type": "MODIFY", "old_path": "pkg/p9/client.go", "new_path": "pkg/p9/client.go", "diff": "@@ -174,7 +174,7 @@ func NewClient(socket *unet.Socket, messageSize uint32, version string) (*Client\n// our sendRecv function to use that functionality. Otherwise,\n// we stick to sendRecvLegacy.\nrversion := Rversion{}\n- err := c.sendRecvLegacy(&Tversion{\n+ _, err := c.sendRecvLegacy(&Tversion{\nVersion: versionString(requested),\nMSize: messageSize,\n}, &rversion)\n@@ -219,11 +219,11 @@ func NewClient(socket *unet.Socket, messageSize uint32, version string) (*Client\nc.sendRecv = c.sendRecvChannel\n} else {\n// Channel setup failed; fallback.\n- c.sendRecv = c.sendRecvLegacy\n+ c.sendRecv = c.sendRecvLegacySyscallErr\n}\n} else {\n// No channels available: use the legacy mechanism.\n- c.sendRecv = c.sendRecvLegacy\n+ c.sendRecv = c.sendRecvLegacySyscallErr\n}\n// Ensure that the socket and channels are closed when the socket is shut\n@@ -305,7 +305,7 @@ func (c *Client) openChannel(id int) error {\n)\n// Open the data channel.\n- if err := c.sendRecvLegacy(&Tchannel{\n+ if _, err := c.sendRecvLegacy(&Tchannel{\nID: uint32(id),\nControl: 0,\n}, &rchannel0); err != nil {\n@@ -319,7 +319,7 @@ func (c *Client) openChannel(id int) error {\ndefer rchannel0.FilePayload().Close()\n// Open the channel for file descriptors.\n- if err := c.sendRecvLegacy(&Tchannel{\n+ if _, err := c.sendRecvLegacy(&Tchannel{\nID: uint32(id),\nControl: 1,\n}, &rchannel1); err != nil {\n@@ -431,13 +431,28 @@ func (c *Client) waitAndRecv(done chan error) error {\n}\n}\n+// sendRecvLegacySyscallErr is a wrapper for sendRecvLegacy that converts all\n+// non-syscall errors to EIO.\n+func (c *Client) sendRecvLegacySyscallErr(t message, r message) error {\n+ received, err := c.sendRecvLegacy(t, r)\n+ if !received {\n+ log.Warningf(\"p9.Client.sendRecvChannel: %v\", err)\n+ return syscall.EIO\n+ }\n+ return err\n+}\n+\n// sendRecvLegacy performs a roundtrip message exchange.\n//\n+// sendRecvLegacy returns true if a message was received. This allows us to\n+// differentiate between failed receives and successful receives where the\n+// response was an error message.\n+//\n// This is called by internal functions.\n-func (c *Client) sendRecvLegacy(t message, r message) error {\n+func (c *Client) sendRecvLegacy(t message, r message) (bool, error) {\ntag, ok := c.tagPool.Get()\nif !ok {\n- return ErrOutOfTags\n+ return false, ErrOutOfTags\n}\ndefer c.tagPool.Put(tag)\n@@ -457,12 +472,12 @@ func (c *Client) sendRecvLegacy(t message, r message) error {\nerr := send(c.socket, Tag(tag), t)\nc.sendMu.Unlock()\nif err != nil {\n- return err\n+ return false, err\n}\n// Co-ordinate with other receivers.\nif err := c.waitAndRecv(resp.done); err != nil {\n- return err\n+ return false, err\n}\n// Is it an error message?\n@@ -470,14 +485,14 @@ func (c *Client) sendRecvLegacy(t message, r message) error {\n// For convenience, we transform these directly\n// into errors. Handlers need not handle this case.\nif rlerr, ok := resp.r.(*Rlerror); ok {\n- return syscall.Errno(rlerr.Error)\n+ return true, syscall.Errno(rlerr.Error)\n}\n// At this point, we know it matches.\n//\n// Per recv call above, we will only allow a type\n// match (and give our r) or an instance of Rlerror.\n- return nil\n+ return true, nil\n}\n// sendRecvChannel uses channels to send a message.\n@@ -486,7 +501,7 @@ func (c *Client) sendRecvChannel(t message, r message) error {\nc.channelsMu.Lock()\nif len(c.availableChannels) == 0 {\nc.channelsMu.Unlock()\n- return c.sendRecvLegacy(t, r)\n+ return c.sendRecvLegacySyscallErr(t, r)\n}\nidx := len(c.availableChannels) - 1\nch := c.availableChannels[idx]\n@@ -526,7 +541,11 @@ func (c *Client) sendRecvChannel(t message, r message) error {\n}\n// Parse the server's response.\n- _, retErr := ch.recv(r, rsz)\n+ resp, retErr := ch.recv(r, rsz)\n+ if resp == nil {\n+ log.Warningf(\"p9.Client.sendRecvChannel: p9.channel.recv: %v\", retErr)\n+ retErr = syscall.EIO\n+ }\n// Release the channel.\nc.channelsMu.Lock()\n" }, { "change_type": "MODIFY", "old_path": "pkg/p9/client_test.go", "new_path": "pkg/p9/client_test.go", "diff": "@@ -96,7 +96,12 @@ func benchmarkSendRecv(b *testing.B, fn func(c *Client) func(message, message) e\n}\nfunc BenchmarkSendRecvLegacy(b *testing.B) {\n- benchmarkSendRecv(b, func(c *Client) func(message, message) error { return c.sendRecvLegacy })\n+ benchmarkSendRecv(b, func(c *Client) func(message, message) error {\n+ return func(t message, r message) error {\n+ _, err := c.sendRecvLegacy(t, r)\n+ return err\n+ }\n+ })\n}\nfunc BenchmarkSendRecvChannel(b *testing.B) {\n" }, { "change_type": "MODIFY", "old_path": "pkg/p9/transport_flipcall.go", "new_path": "pkg/p9/transport_flipcall.go", "diff": "@@ -236,7 +236,7 @@ func (ch *channel) recv(r message, rsz uint32) (message, error) {\n// Convert errors appropriately; see above.\nif rlerr, ok := r.(*Rlerror); ok {\n- return nil, syscall.Errno(rlerr.Error)\n+ return r, syscall.Errno(rlerr.Error)\n}\nreturn r, nil\n" } ]
Go
Apache License 2.0
google/gvisor
Return EIO from p9 if sending/receiving fails. Continues the modifications in cl/272963663. This prevents non-syscall errors from being propogated to kernel/task_syscall.go:ExtractErrno(), which causes a sentry panic. PiperOrigin-RevId: 305913127
259,992
10.04.2020 15:46:16
25,200
96f914295920404e7c5c97553771e09b31f6900a
Use O_CLOEXEC when dup'ing FDs The sentry doesn't allow execve, but it's a good defense in-depth measure.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/gofer/inode.go", "new_path": "pkg/sentry/fs/gofer/inode.go", "diff": "@@ -273,7 +273,7 @@ func (i *inodeFileState) recreateReadHandles(ctx context.Context, writer *handle\n// operations on the old will see the new data. Then, make the new handle take\n// ownereship of the old FD and mark the old readHandle to not close the FD\n// when done.\n- if err := syscall.Dup3(h.Host.FD(), i.readHandles.Host.FD(), 0); err != nil {\n+ if err := syscall.Dup3(h.Host.FD(), i.readHandles.Host.FD(), syscall.O_CLOEXEC); err != nil {\nreturn err\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/gofer/gofer.go", "new_path": "pkg/sentry/fsimpl/gofer/gofer.go", "diff": "@@ -1089,7 +1089,7 @@ func (d *dentry) ensureSharedHandle(ctx context.Context, read, write, trunc bool\n// description, but this doesn't matter since they refer to the\n// same file (unless d.fs.opts.overlayfsStaleRead is true,\n// which we handle separately).\n- if err := syscall.Dup3(int(h.fd), int(d.handle.fd), 0); err != nil {\n+ if err := syscall.Dup3(int(h.fd), int(d.handle.fd), syscall.O_CLOEXEC); err != nil {\nd.handleMu.Unlock()\nctx.Warningf(\"gofer.dentry.ensureSharedHandle: failed to dup fd %d to fd %d: %v\", h.fd, d.handle.fd, err)\nh.close(ctx)\n" }, { "change_type": "MODIFY", "old_path": "runsc/boot/filter/config.go", "new_path": "runsc/boot/filter/config.go", "diff": "@@ -44,7 +44,7 @@ var allowedSyscalls = seccomp.SyscallRules{\n{\nseccomp.AllowAny{},\nseccomp.AllowAny{},\n- seccomp.AllowValue(0),\n+ seccomp.AllowValue(syscall.O_CLOEXEC),\n},\n},\nsyscall.SYS_EPOLL_CREATE1: {},\n" }, { "change_type": "MODIFY", "old_path": "runsc/main.go", "new_path": "runsc/main.go", "diff": "@@ -291,7 +291,7 @@ func main() {\n// want with them. Since Docker and Containerd both eat boot's stderr, we\n// dup our stderr to the provided log FD so that panics will appear in the\n// logs, rather than just disappear.\n- if err := syscall.Dup3(fd, int(os.Stderr.Fd()), 0); err != nil {\n+ if err := syscall.Dup3(fd, int(os.Stderr.Fd()), syscall.O_CLOEXEC); err != nil {\ncmd.Fatalf(\"error dup'ing fd %d to stderr: %v\", fd, err)\n}\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Use O_CLOEXEC when dup'ing FDs The sentry doesn't allow execve, but it's a good defense in-depth measure. PiperOrigin-RevId: 305958737
259,884
10.04.2020 20:31:07
25,200
daf3322498b698518a3c8545ad05f790deb3848c
Add logging message for noNewPrivileges OCI option. noNewPrivileges is ignored if set to false since gVisor assumes that PR_SET_NO_NEW_PRIVS is always enabled.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/task_identity.go", "new_path": "pkg/sentry/kernel/task_identity.go", "diff": "@@ -455,7 +455,7 @@ func (t *Task) SetKeepCaps(k bool) {\nt.creds.Store(creds)\n}\n-// updateCredsForExec updates t.creds to reflect an execve().\n+// updateCredsForExecLocked updates t.creds to reflect an execve().\n//\n// NOTE(b/30815691): We currently do not implement privileged executables\n// (set-user/group-ID bits and file capabilities). This allows us to make a lot\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/sys_prctl.go", "new_path": "pkg/sentry/syscalls/linux/sys_prctl.go", "diff": "@@ -161,8 +161,8 @@ func Prctl(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Syscall\nif args[1].Int() != 1 || args[2].Int() != 0 || args[3].Int() != 0 || args[4].Int() != 0 {\nreturn 0, nil, syserror.EINVAL\n}\n- // no_new_privs is assumed to always be set. See\n- // kernel.Task.updateCredsForExec.\n+ // PR_SET_NO_NEW_PRIVS is assumed to always be set.\n+ // See kernel.Task.updateCredsForExecLocked.\nreturn 0, nil, nil\ncase linux.PR_GET_NO_NEW_PRIVS:\n" }, { "change_type": "MODIFY", "old_path": "runsc/specutils/specutils.go", "new_path": "runsc/specutils/specutils.go", "diff": "@@ -92,6 +92,12 @@ func ValidateSpec(spec *specs.Spec) error {\nlog.Warningf(\"AppArmor profile %q is being ignored\", spec.Process.ApparmorProfile)\n}\n+ // PR_SET_NO_NEW_PRIVS is assumed to always be set.\n+ // See kernel.Task.updateCredsForExecLocked.\n+ if !spec.Process.NoNewPrivileges {\n+ log.Warningf(\"noNewPrivileges ignored. PR_SET_NO_NEW_PRIVS is assumed to always be set.\")\n+ }\n+\n// TODO(gvisor.dev/issue/510): Apply seccomp to application inside sandbox.\nif spec.Linux != nil && spec.Linux.Seccomp != nil {\nlog.Warningf(\"Seccomp spec is being ignored\")\n" } ]
Go
Apache License 2.0
google/gvisor
Add logging message for noNewPrivileges OCI option. noNewPrivileges is ignored if set to false since gVisor assumes that PR_SET_NO_NEW_PRIVS is always enabled. PiperOrigin-RevId: 305991947
259,972
11.04.2020 06:45:15
25,200
20203494680f869669ab5318b36e9470ad4b3e7b
Improve error messages when parsing headers. Tested: Looked at output of failing tests.
[ { "change_type": "MODIFY", "old_path": "test/packetimpact/testbench/connections.go", "new_path": "test/packetimpact/testbench/connections.go", "diff": "@@ -213,7 +213,7 @@ func (conn *TCPIPv4) RecvFrame(timeout time.Duration) Layers {\n}\nlayers, err := ParseEther(b)\nif err != nil {\n- conn.t.Logf(\"can't parse frame: %s\", err)\n+ conn.t.Logf(\"debug: can't parse frame, ignoring: %s\", err)\ncontinue // Ignore packets that can't be parsed.\n}\nif !conn.incoming.match(layers) {\n" }, { "change_type": "MODIFY", "old_path": "test/packetimpact/testbench/layers.go", "new_path": "test/packetimpact/testbench/layers.go", "diff": "@@ -153,7 +153,7 @@ func (l *Ether) toBytes() ([]byte, error) {\nfields.Type = header.IPv4ProtocolNumber\ndefault:\n// TODO(b/150301488): Support more protocols, like IPv6.\n- return nil, fmt.Errorf(\"can't deduce the ethernet header's next protocol: %d\", n)\n+ return nil, fmt.Errorf(\"ethernet header's next layer is unrecognized: %#v\", n)\n}\n}\nh.Encode(fields)\n@@ -191,7 +191,7 @@ func ParseEther(b []byte) (Layers, error) {\nreturn append(layers, moreLayers...), nil\ndefault:\n// TODO(b/150301488): Support more protocols, like IPv6.\n- return nil, fmt.Errorf(\"can't deduce the ethernet header's next protocol: %#v\", b)\n+ return nil, fmt.Errorf(\"ethernet header's type field is unrecognized: %#04x\", h.Type())\n}\n}\n@@ -274,7 +274,7 @@ func (l *IPv4) toBytes() ([]byte, error) {\nfields.Protocol = uint8(header.UDPProtocolNumber)\ndefault:\n// TODO(b/150301488): Support more protocols as needed.\n- return nil, fmt.Errorf(\"can't deduce the ip header's next protocol: %#v\", n)\n+ return nil, fmt.Errorf(\"ipv4 header's next layer is unrecognized: %#v\", n)\n}\n}\nif l.SrcAddr != nil {\n@@ -344,7 +344,7 @@ func ParseIPv4(b []byte) (Layers, error) {\n}\nreturn append(layers, moreLayers...), nil\n}\n- return nil, fmt.Errorf(\"can't deduce the ethernet header's next protocol: %d\", h.Protocol())\n+ return nil, fmt.Errorf(\"ipv4 header's protocol field is unrecognized: %#02x\", h.Protocol())\n}\nfunc (l *IPv4) match(other Layer) bool {\n" } ]
Go
Apache License 2.0
google/gvisor
Improve error messages when parsing headers. Tested: Looked at output of failing tests. PiperOrigin-RevId: 306031407
259,972
12.04.2020 18:32:18
25,200
ef0b5584e5389cc392e03d20976a15974f277251
Refactor parser to use a for loop instead of recursion. This makes the code shorter and less repetitive. TESTED: All unit tests still pass.
[ { "change_type": "MODIFY", "old_path": "test/packetimpact/testbench/connections.go", "new_path": "test/packetimpact/testbench/connections.go", "diff": "@@ -211,11 +211,7 @@ func (conn *TCPIPv4) RecvFrame(timeout time.Duration) Layers {\nif b == nil {\nbreak\n}\n- layers, err := ParseEther(b)\n- if err != nil {\n- conn.t.Logf(\"debug: can't parse frame, ignoring: %s\", err)\n- continue // Ignore packets that can't be parsed.\n- }\n+ layers := Parse(ParseEther, b)\nif !conn.incoming.match(layers) {\ncontinue // Ignore packets that don't match the expected incoming.\n}\n@@ -418,11 +414,7 @@ func (conn *UDPIPv4) Recv(timeout time.Duration) *UDP {\nif b == nil {\nbreak\n}\n- layers, err := ParseEther(b)\n- if err != nil {\n- conn.t.Logf(\"can't parse frame: %s\", err)\n- continue // Ignore packets that can't be parsed.\n- }\n+ layers := Parse(ParseEther, b)\nif !conn.incoming.match(layers) {\ncontinue // Ignore packets that don't match the expected incoming.\n}\n" }, { "change_type": "MODIFY", "old_path": "test/packetimpact/testbench/layers.go", "new_path": "test/packetimpact/testbench/layers.go", "diff": "@@ -172,27 +172,46 @@ func NetworkProtocolNumber(v tcpip.NetworkProtocolNumber) *tcpip.NetworkProtocol\nreturn &v\n}\n+// LayerParser parses the input bytes and returns a Layer along with the next\n+// LayerParser to run. If there is no more parsing to do, the returned\n+// LayerParser is nil.\n+type LayerParser func([]byte) (Layer, LayerParser)\n+\n+// Parse parses bytes starting with the first LayerParser and using successive\n+// LayerParsers until all the bytes are parsed.\n+func Parse(parser LayerParser, b []byte) Layers {\n+ var layers Layers\n+ for {\n+ var layer Layer\n+ layer, parser = parser(b)\n+ layers = append(layers, layer)\n+ if parser == nil {\n+ break\n+ }\n+ b = b[layer.length():]\n+ }\n+ layers.linkLayers()\n+ return layers\n+}\n+\n// ParseEther parses the bytes assuming that they start with an ethernet header\n// and continues parsing further encapsulations.\n-func ParseEther(b []byte) (Layers, error) {\n+func ParseEther(b []byte) (Layer, LayerParser) {\nh := header.Ethernet(b)\nether := Ether{\nSrcAddr: LinkAddress(h.SourceAddress()),\nDstAddr: LinkAddress(h.DestinationAddress()),\nType: NetworkProtocolNumber(h.Type()),\n}\n- layers := Layers{&ether}\n+ var nextParser LayerParser\nswitch h.Type() {\ncase header.IPv4ProtocolNumber:\n- moreLayers, err := ParseIPv4(b[ether.length():])\n- if err != nil {\n- return nil, err\n- }\n- return append(layers, moreLayers...), nil\n+ nextParser = ParseIPv4\ndefault:\n- // TODO(b/150301488): Support more protocols, like IPv6.\n- return nil, fmt.Errorf(\"ethernet header's type field is unrecognized: %#04x\", h.Type())\n+ // Assume that the rest is a payload.\n+ nextParser = ParsePayload\n}\n+ return &ether, nextParser\n}\nfunc (l *Ether) match(other Layer) bool {\n@@ -313,7 +332,7 @@ func Address(v tcpip.Address) *tcpip.Address {\n// ParseIPv4 parses the bytes assuming that they start with an ipv4 header and\n// continues parsing further encapsulations.\n-func ParseIPv4(b []byte) (Layers, error) {\n+func ParseIPv4(b []byte) (Layer, LayerParser) {\nh := header.IPv4(b)\ntos, _ := h.TOS()\nipv4 := IPv4{\n@@ -329,22 +348,17 @@ func ParseIPv4(b []byte) (Layers, error) {\nSrcAddr: Address(h.SourceAddress()),\nDstAddr: Address(h.DestinationAddress()),\n}\n- layers := Layers{&ipv4}\n+ var nextParser LayerParser\nswitch h.TransportProtocol() {\ncase header.TCPProtocolNumber:\n- moreLayers, err := ParseTCP(b[ipv4.length():])\n- if err != nil {\n- return nil, err\n- }\n- return append(layers, moreLayers...), nil\n+ nextParser = ParseTCP\ncase header.UDPProtocolNumber:\n- moreLayers, err := ParseUDP(b[ipv4.length():])\n- if err != nil {\n- return nil, err\n- }\n- return append(layers, moreLayers...), nil\n+ nextParser = ParseUDP\n+ default:\n+ // Assume that the rest is a payload.\n+ nextParser = ParsePayload\n}\n- return nil, fmt.Errorf(\"ipv4 header's protocol field is unrecognized: %#02x\", h.Protocol())\n+ return &ipv4, nextParser\n}\nfunc (l *IPv4) match(other Layer) bool {\n@@ -470,7 +484,7 @@ func Uint32(v uint32) *uint32 {\n// ParseTCP parses the bytes assuming that they start with a tcp header and\n// continues parsing further encapsulations.\n-func ParseTCP(b []byte) (Layers, error) {\n+func ParseTCP(b []byte) (Layer, LayerParser) {\nh := header.TCP(b)\ntcp := TCP{\nSrcPort: Uint16(h.SourcePort()),\n@@ -483,12 +497,7 @@ func ParseTCP(b []byte) (Layers, error) {\nChecksum: Uint16(h.Checksum()),\nUrgentPointer: Uint16(h.UrgentPointer()),\n}\n- layers := Layers{&tcp}\n- moreLayers, err := ParsePayload(b[tcp.length():])\n- if err != nil {\n- return nil, err\n- }\n- return append(layers, moreLayers...), nil\n+ return &tcp, ParsePayload\n}\nfunc (l *TCP) match(other Layer) bool {\n@@ -557,8 +566,8 @@ func setUDPChecksum(h *header.UDP, udp *UDP) error {\n}\n// ParseUDP parses the bytes assuming that they start with a udp header and\n-// continues parsing further encapsulations.\n-func ParseUDP(b []byte) (Layers, error) {\n+// returns the parsed layer and the next parser to use.\n+func ParseUDP(b []byte) (Layer, LayerParser) {\nh := header.UDP(b)\nudp := UDP{\nSrcPort: Uint16(h.SourcePort()),\n@@ -566,12 +575,7 @@ func ParseUDP(b []byte) (Layers, error) {\nLength: Uint16(h.Length()),\nChecksum: Uint16(h.Checksum()),\n}\n- layers := Layers{&udp}\n- moreLayers, err := ParsePayload(b[udp.length():])\n- if err != nil {\n- return nil, err\n- }\n- return append(layers, moreLayers...), nil\n+ return &udp, ParsePayload\n}\nfunc (l *UDP) match(other Layer) bool {\n@@ -603,11 +607,11 @@ func (l *Payload) String() string {\n// ParsePayload parses the bytes assuming that they start with a payload and\n// continue to the end. There can be no further encapsulations.\n-func ParsePayload(b []byte) (Layers, error) {\n+func ParsePayload(b []byte) (Layer, LayerParser) {\npayload := Payload{\nBytes: b,\n}\n- return Layers{&payload}, nil\n+ return &payload, nil\n}\nfunc (l *Payload) toBytes() ([]byte, error) {\n@@ -625,15 +629,24 @@ func (l *Payload) length() int {\n// Layers is an array of Layer and supports similar functions to Layer.\ntype Layers []Layer\n-func (ls *Layers) toBytes() ([]byte, error) {\n+// linkLayers sets the linked-list ponters in ls.\n+func (ls *Layers) linkLayers() {\nfor i, l := range *ls {\nif i > 0 {\nl.setPrev((*ls)[i-1])\n+ } else {\n+ l.setPrev(nil)\n}\nif i+1 < len(*ls) {\nl.setNext((*ls)[i+1])\n+ } else {\n+ l.setNext(nil)\n}\n}\n+}\n+\n+func (ls *Layers) toBytes() ([]byte, error) {\n+ ls.linkLayers()\noutBytes := []byte{}\nfor _, l := range *ls {\nlayerBytes, err := l.toBytes()\n" } ]
Go
Apache License 2.0
google/gvisor
Refactor parser to use a for loop instead of recursion. This makes the code shorter and less repetitive. TESTED: All unit tests still pass. PiperOrigin-RevId: 306161475
259,885
13.04.2020 10:51:08
25,200
445c366581637b64336a18d69519faee5a444f5d
Fix VFS2 getdents()/getdents64() alignment.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/vfs2/getdents.go", "new_path": "pkg/sentry/syscalls/linux/vfs2/getdents.go", "diff": "@@ -97,6 +97,7 @@ func (cb *getdentsCallback) Handle(dirent vfs.Dirent) error {\n// char d_name[]; /* Filename (null-terminated) */\n// };\nsize := 8 + 8 + 2 + 1 + 1 + len(dirent.Name)\n+ size = (size + 7) &^ 7 // round up to multiple of 8\nif size > cb.remaining {\nreturn syserror.EINVAL\n}\n@@ -106,7 +107,12 @@ func (cb *getdentsCallback) Handle(dirent vfs.Dirent) error {\nusermem.ByteOrder.PutUint16(buf[16:18], uint16(size))\nbuf[18] = dirent.Type\ncopy(buf[19:], dirent.Name)\n- buf[size-1] = 0 // NUL terminator\n+ // Zero out all remaining bytes in buf, including the NUL terminator\n+ // after dirent.Name.\n+ bufTail := buf[19+len(dirent.Name):]\n+ for i := range bufTail {\n+ bufTail[i] = 0\n+ }\n} else {\n// struct linux_dirent {\n// unsigned long d_ino; /* Inode number */\n@@ -125,6 +131,7 @@ func (cb *getdentsCallback) Handle(dirent vfs.Dirent) error {\npanic(fmt.Sprintf(\"unsupported sizeof(unsigned long): %d\", cb.t.Arch().Width()))\n}\nsize := 8 + 8 + 2 + 1 + 1 + 1 + len(dirent.Name)\n+ size = (size + 7) &^ 7 // round up to multiple of sizeof(long)\nif size > cb.remaining {\nreturn syserror.EINVAL\n}\n@@ -133,9 +140,14 @@ func (cb *getdentsCallback) Handle(dirent vfs.Dirent) error {\nusermem.ByteOrder.PutUint64(buf[8:16], uint64(dirent.NextOff))\nusermem.ByteOrder.PutUint16(buf[16:18], uint16(size))\ncopy(buf[18:], dirent.Name)\n- buf[size-3] = 0 // NUL terminator\n- buf[size-2] = 0 // zero padding byte\n- buf[size-1] = dirent.Type\n+ // Zero out all remaining bytes in buf, including the NUL terminator\n+ // after dirent.Name and the zero padding byte between the name and\n+ // dirent type.\n+ bufTail := buf[18+len(dirent.Name):]\n+ for i := range bufTail {\n+ bufTail[i] = 0\n+ }\n+ bufTail[2] = dirent.Type\n}\nn, err := cb.t.CopyOutBytes(cb.addr, buf)\nif err != nil {\n" } ]
Go
Apache License 2.0
google/gvisor
Fix VFS2 getdents()/getdents64() alignment. PiperOrigin-RevId: 306263615
259,945
13.04.2020 11:01:02
25,200
6a4d17a31dc209afbbca66e871a7c6dc299c167b
Remove obsolete TODOs for b/38173783 The comments in the ticket indicate that this behavior is fine and that the ticket should be closed, so we shouldn't need pointers to the ticket.
[ { "change_type": "MODIFY", "old_path": "pkg/context/context.go", "new_path": "pkg/context/context.go", "diff": "@@ -127,10 +127,6 @@ func (logContext) Value(key interface{}) interface{} {\nvar bgContext = &logContext{Logger: log.Log()}\n// Background returns an empty context using the default logger.\n-//\n-// Users should be wary of using a Background context. Please tag any use with\n-// FIXME(b/38173783) and a note to remove this use.\n-//\n// Generally, one should use the Task as their context when available, or avoid\n// having to use a context in places where a Task is unavailable.\n//\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/arch/stack.go", "new_path": "pkg/sentry/arch/stack.go", "diff": "@@ -97,7 +97,6 @@ func (s *Stack) Push(vals ...interface{}) (usermem.Addr, error) {\nif c < 0 {\nreturn 0, fmt.Errorf(\"bad binary.Size for %T\", v)\n}\n- // TODO(b/38173783): Use a real context.Context.\nn, err := usermem.CopyObjectOut(context.Background(), s.IO, s.Bottom-usermem.Addr(c), norm, usermem.IOOpts{})\nif err != nil || c != n {\nreturn 0, err\n@@ -121,11 +120,9 @@ func (s *Stack) Pop(vals ...interface{}) (usermem.Addr, error) {\nvar err error\nif isVaddr {\nvalue := s.Arch.Native(uintptr(0))\n- // TODO(b/38173783): Use a real context.Context.\nn, err = usermem.CopyObjectIn(context.Background(), s.IO, s.Bottom, value, usermem.IOOpts{})\n*vaddr = usermem.Addr(s.Arch.Value(value))\n} else {\n- // TODO(b/38173783): Use a real context.Context.\nn, err = usermem.CopyObjectIn(context.Background(), s.IO, s.Bottom, v, usermem.IOOpts{})\n}\nif err != nil {\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/gofer/file_state.go", "new_path": "pkg/sentry/fs/gofer/file_state.go", "diff": "@@ -34,7 +34,6 @@ func (f *fileOperations) afterLoad() {\nflags := f.flags\nflags.Truncate = false\n- // TODO(b/38173783): Context is not plumbed to save/restore.\nf.handles, err = f.inodeOperations.fileState.getHandles(context.Background(), flags, f.inodeOperations.cachingInodeOps)\nif err != nil {\nreturn fmt.Errorf(\"failed to re-open handle: %v\", err)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/gofer/handles.go", "new_path": "pkg/sentry/fs/gofer/handles.go", "diff": "@@ -57,7 +57,6 @@ func (h *handles) DecRef() {\n}\n}\n}\n- // FIXME(b/38173783): Context is not plumbed here.\nif err := h.File.close(context.Background()); err != nil {\nlog.Warningf(\"error closing p9 file: %v\", err)\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/gofer/inode_state.go", "new_path": "pkg/sentry/fs/gofer/inode_state.go", "diff": "@@ -123,7 +123,6 @@ func (i *inodeFileState) afterLoad() {\n// beforeSave.\nreturn fmt.Errorf(\"failed to find path for inode number %d. Device %s contains %s\", i.sattr.InodeID, i.s.connID, fs.InodeMappings(i.s.inodeMappings))\n}\n- // TODO(b/38173783): Context is not plumbed to save/restore.\nctx := &dummyClockContext{context.Background()}\n_, i.file, err = i.s.attach.walk(ctx, splitAbsolutePath(name))\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/gofer/session_state.go", "new_path": "pkg/sentry/fs/gofer/session_state.go", "diff": "@@ -104,7 +104,6 @@ func (s *session) afterLoad() {\n// If private unix sockets are enabled, create and fill the session's endpoint\n// maps.\nif opts.privateunixsocket {\n- // TODO(b/38173783): Context is not plumbed to save/restore.\nctx := &dummyClockContext{context.Background()}\nif err = s.restoreEndpointMaps(ctx); err != nil {\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/inode.go", "new_path": "pkg/sentry/fs/inode.go", "diff": "@@ -102,7 +102,6 @@ func (i *Inode) DecRef() {\n// destroy releases the Inode and releases the msrc reference taken.\nfunc (i *Inode) destroy() {\n- // FIXME(b/38173783): Context is not plumbed here.\nctx := context.Background()\nif err := i.WriteOut(ctx); err != nil {\n// FIXME(b/65209558): Mark as warning again once noatime is\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/shm/shm.go", "new_path": "pkg/sentry/kernel/shm/shm.go", "diff": "@@ -461,7 +461,7 @@ func (s *Shm) AddMapping(ctx context.Context, _ memmap.MappingSpace, _ usermem.A\nfunc (s *Shm) RemoveMapping(ctx context.Context, _ memmap.MappingSpace, _ usermem.AddrRange, _ uint64, _ bool) {\ns.mu.Lock()\ndefer s.mu.Unlock()\n- // TODO(b/38173783): RemoveMapping may be called during task exit, when ctx\n+ // RemoveMapping may be called during task exit, when ctx\n// is context.Background. Gracefully handle missing clocks. Failing to\n// update the detach time in these cases is ok, since no one can observe the\n// omission.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/task_context.go", "new_path": "pkg/sentry/kernel/task_context.go", "diff": "@@ -58,7 +58,6 @@ func (tc *TaskContext) release() {\n// Nil out pointers so that if the task is saved after release, it doesn't\n// follow the pointers to possibly now-invalid objects.\nif tc.MemoryManager != nil {\n- // TODO(b/38173783)\ntc.MemoryManager.DecUsers(context.Background())\ntc.MemoryManager = nil\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/task_signals.go", "new_path": "pkg/sentry/kernel/task_signals.go", "diff": "@@ -513,8 +513,6 @@ func (t *Task) canReceiveSignalLocked(sig linux.Signal) bool {\nif t.stop != nil {\nreturn false\n}\n- // - TODO(b/38173783): No special case for when t is also the sending task,\n- // because the identity of the sender is unknown.\n// - Do not choose tasks that have already been interrupted, as they may be\n// busy handling another signal.\nif len(t.interruptChan) != 0 {\n" }, { "change_type": "MODIFY", "old_path": "pkg/usermem/usermem.go", "new_path": "pkg/usermem/usermem.go", "diff": "@@ -29,9 +29,6 @@ import (\n)\n// IO provides access to the contents of a virtual memory space.\n-//\n-// FIXME(b/38173783): Implementations of IO cannot expect ctx to contain any\n-// meaningful data.\ntype IO interface {\n// CopyOut copies len(src) bytes from src to the memory mapped at addr. It\n// returns the number of bytes copied. If the number of bytes copied is <\n" } ]
Go
Apache License 2.0
google/gvisor
Remove obsolete TODOs for b/38173783 The comments in the ticket indicate that this behavior is fine and that the ticket should be closed, so we shouldn't need pointers to the ticket. PiperOrigin-RevId: 306266071
259,858
13.04.2020 12:47:32
25,200
aa75a3da5188d8f62d00fc6590708ca4886526b4
Fix build.sh and VM targets.
[ { "change_type": "MODIFY", "old_path": "benchmarks/runner/__init__.py", "new_path": "benchmarks/runner/__init__.py", "diff": "@@ -19,6 +19,7 @@ import logging\nimport pkgutil\nimport pydoc\nimport re\n+import subprocess\nimport sys\nimport types\nfrom typing import List\n@@ -125,9 +126,8 @@ def run_gcp(ctx, image_file: str, zone_file: str, internal: bool,\n\"\"\"Runs all benchmarks on GCP instances.\"\"\"\n# Resolve all files.\n- image = open(image_file).read().rstrip()\n- zone = open(zone_file).read().rstrip()\n-\n+ image = subprocess.check_output([image_file]).rstrip()\n+ zone = subprocess.check_output([zone_file]).rstrip()\nkey_file = harness.make_key()\nproducer = gcloud_producer.GCloudProducer(\n" }, { "change_type": "MODIFY", "old_path": "benchmarks/runner/commands.py", "new_path": "benchmarks/runner/commands.py", "diff": "@@ -101,15 +101,15 @@ class GCPCommand(RunCommand):\nimage_file = click.core.Option(\n(\"--image_file\",),\n- help=\"The file containing the image for VMs.\",\n+ help=\"The binary that emits the GCP image.\",\ndefault=os.path.join(\n- os.path.dirname(__file__), \"../../tools/images/ubuntu1604.txt\"),\n+ os.path.dirname(__file__), \"../../tools/images/ubuntu1604\"),\n)\nzone_file = click.core.Option(\n(\"--zone_file\",),\n- help=\"The file containing the GCP zone.\",\n+ help=\"The binary that emits the GCP zone.\",\ndefault=os.path.join(\n- os.path.dirname(__file__), \"../../tools/images/zone.txt\"),\n+ os.path.dirname(__file__), \"../../tools/images/zone\"),\n)\ninternal = click.core.Option(\n(\"--internal/--no-internal\",),\n" }, { "change_type": "DELETE", "old_path": "tools/image_build.sh", "new_path": null, "diff": "-#!/bin/bash\n-\n-# 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-# This script is responsible for building a new GCP image that: 1) has nested\n-# virtualization enabled, and 2) has been completely set up with the\n-# image_setup.sh script. This script should be idempotent, as we memoize the\n-# setup script with a hash and check for that name.\n-#\n-# The GCP project name should be defined via a gcloud config.\n-\n-set -xeo pipefail\n-\n-# Parameters.\n-declare -r ZONE=${ZONE:-us-central1-f}\n-declare -r USERNAME=${USERNAME:-test}\n-declare -r IMAGE_PROJECT=${IMAGE_PROJECT:-ubuntu-os-cloud}\n-declare -r IMAGE_FAMILY=${IMAGE_FAMILY:-ubuntu-1604-lts}\n-\n-# Random names.\n-declare -r DISK_NAME=$(mktemp -u disk-XXXXXX | tr A-Z a-z)\n-declare -r SNAPSHOT_NAME=$(mktemp -u snapshot-XXXXXX | tr A-Z a-z)\n-declare -r INSTANCE_NAME=$(mktemp -u build-XXXXXX | tr A-Z a-z)\n-\n-# Hashes inputs.\n-declare -r SETUP_BLOB=$(echo ${ZONE} ${USERNAME} ${IMAGE_PROJECT} ${IMAGE_FAMILY} && sha256sum \"$@\")\n-declare -r SETUP_HASH=$(echo ${SETUP_BLOB} | sha256sum - | cut -d' ' -f1 | cut -c 1-16)\n-declare -r IMAGE_NAME=${IMAGE_NAME:-image-}${SETUP_HASH}\n-\n-# Does the image already exist? Skip the build.\n-declare -r existing=$(gcloud compute images list --filter=\"name=(${IMAGE_NAME})\" --format=\"value(name)\")\n-if ! [[ -z \"${existing}\" ]]; then\n- echo \"${existing}\"\n- exit 0\n-fi\n-\n-# Set the zone for all actions.\n-gcloud config set compute/zone \"${ZONE}\"\n-\n-# Start a unique instance. Note that this instance will have a unique persistent\n-# disk as it's boot disk with the same name as the instance.\n-gcloud compute instances create \\\n- --quiet \\\n- --image-project \"${IMAGE_PROJECT}\" \\\n- --image-family \"${IMAGE_FAMILY}\" \\\n- --boot-disk-size \"200GB\" \\\n- \"${INSTANCE_NAME}\"\n-function cleanup {\n- gcloud compute instances delete --quiet \"${INSTANCE_NAME}\"\n-}\n-trap cleanup EXIT\n-\n-# Wait for the instance to become available.\n-declare attempts=0\n-while [[ \"${attempts}\" -lt 30 ]]; do\n- attempts=$((${attempts}+1))\n- if gcloud compute ssh \"${USERNAME}\"@\"${INSTANCE_NAME}\" -- true; then\n- break\n- fi\n-done\n-if [[ \"${attempts}\" -ge 30 ]]; then\n- echo \"too many attempts: failed\"\n- exit 1\n-fi\n-\n-# Run the install scripts provided.\n-for arg; do\n- gcloud compute ssh \"${USERNAME}\"@\"${INSTANCE_NAME}\" -- sudo bash - <\"${arg}\"\n-done\n-\n-# Stop the instance; required before creating an image.\n-gcloud compute instances stop --quiet \"${INSTANCE_NAME}\"\n-\n-# Create a snapshot of the instance disk.\n-gcloud compute disks snapshot \\\n- --quiet \\\n- --zone=\"${ZONE}\" \\\n- --snapshot-names=\"${SNAPSHOT_NAME}\" \\\n- \"${INSTANCE_NAME}\"\n-\n-# Create the disk image.\n-gcloud compute images create \\\n- --quiet \\\n- --source-snapshot=\"${SNAPSHOT_NAME}\" \\\n- --licenses=\"https://www.googleapis.com/compute/v1/projects/vm-options/global/licenses/enable-vmx\" \\\n- \"${IMAGE_NAME}\"\n" }, { "change_type": "MODIFY", "old_path": "tools/images/BUILD", "new_path": "tools/images/BUILD", "diff": "@@ -6,14 +6,9 @@ package(\nlicenses = [\"notice\"],\n)\n-genrule(\n+sh_binary(\nname = \"zone\",\n- outs = [\"zone.txt\"],\n- cmd = \"gcloud config get-value compute/zone > \\\"$@\\\"\",\n- tags = [\n- \"local\",\n- \"manual\",\n- ],\n+ srcs = [\"zone.sh\"],\n)\nsh_binary(\n" }, { "change_type": "ADD", "old_path": null, "new_path": "tools/images/README.md", "diff": "+# Images\n+\n+All commands in this directory require the `gcloud` project to be set.\n+\n+For example: `gcloud config set project gvisor-kokoro-testing`.\n+\n+Images can be generated by using the `vm_image` rule. This rule will generate a\n+binary target that builds an image in an idempotent way, and can be referenced\n+from other rules.\n+\n+For example:\n+\n+```\n+vm_image(\n+ name = \"ubuntu\",\n+ project = \"ubuntu-1604-lts\",\n+ family = \"ubuntu-os-cloud\",\n+ scripts = [\n+ \"script.sh\",\n+ \"other.sh\",\n+ ],\n+)\n+```\n+\n+These images can be built manually by executing the target. The output on\n+`stdout` will be the image id (in the current project).\n+\n+Images are always named per the hash of all the hermetic input scripts. This\n+allows images to be memoized quickly and easily.\n+\n+The `vm_test` rule can be used to execute a command remotely. This is still\n+under development however, and will likely change over time.\n+\n+For example:\n+\n+```\n+vm_test(\n+ name = \"mycommand\",\n+ image = \":ubuntu\",\n+ targets = [\":test\"],\n+)\n+```\n" }, { "change_type": "MODIFY", "old_path": "tools/images/build.sh", "new_path": "tools/images/build.sh", "diff": "# image_setup.sh script. This script should be idempotent, as we memoize the\n# setup script with a hash and check for that name.\n-set -xeou pipefail\n+set -eou pipefail\n# Parameters.\ndeclare -r USERNAME=${USERNAME:-test}\n@@ -34,10 +34,10 @@ declare -r INSTANCE_NAME=$(mktemp -u build-XXXXXX | tr A-Z a-z)\n# Hash inputs in order to memoize the produced image.\ndeclare -r SETUP_HASH=$( (echo ${USERNAME} ${IMAGE_PROJECT} ${IMAGE_FAMILY} && cat \"$@\") | sha256sum - | cut -d' ' -f1 | cut -c 1-16)\n-declare -r IMAGE_NAME=${IMAGE_FAMILY:-image-}${SETUP_HASH}\n+declare -r IMAGE_NAME=${IMAGE_FAMILY:-image}-${SETUP_HASH}\n# Does the image already exist? Skip the build.\n-declare -r existing=$(gcloud compute images list --filter=\"name=(${IMAGE_NAME})\" --format=\"value(name)\")\n+declare -r existing=$(set -x; gcloud compute images list --filter=\"name=(${IMAGE_NAME})\" --format=\"value(name)\")\nif ! [[ -z \"${existing}\" ]]; then\necho \"${existing}\"\nexit 0\n@@ -48,28 +48,30 @@ export PATH=${PATH:-/bin:/usr/bin:/usr/local/bin}\n# Start a unique instance. Note that this instance will have a unique persistent\n# disk as it's boot disk with the same name as the instance.\n-gcloud compute instances create \\\n+(set -x; gcloud compute instances create \\\n--quiet \\\n--image-project \"${IMAGE_PROJECT}\" \\\n--image-family \"${IMAGE_FAMILY}\" \\\n--boot-disk-size \"200GB\" \\\n--zone \"${ZONE}\" \\\n- \"${INSTANCE_NAME}\" >/dev/null\n+ \"${INSTANCE_NAME}\" >/dev/null)\nfunction cleanup {\n- gcloud compute instances delete --quiet --zone \"${ZONE}\" \"${INSTANCE_NAME}\"\n+ (set -x; gcloud compute instances delete --quiet --zone \"${ZONE}\" \"${INSTANCE_NAME}\")\n}\ntrap cleanup EXIT\n# Wait for the instance to become available (up to 5 minutes).\n+echo -n \"Waiting for ${INSTANCE_NAME}\"\ndeclare timeout=300\ndeclare success=0\ndeclare internal=\"\"\ndeclare -r start=$(date +%s)\ndeclare -r end=$((${start}+${timeout}))\nwhile [[ \"$(date +%s)\" -lt \"${end}\" ]] && [[ \"${success}\" -lt 3 ]]; do\n- if gcloud compute ssh --zone \"${internal}\" \"${ZONE}\" \"${USERNAME}\"@\"${INSTANCE_NAME}\" -- env - true 2>/dev/null; then\n+ echo -n \".\"\n+ if gcloud compute ssh --zone \"${ZONE}\" \"${USERNAME}\"@\"${INSTANCE_NAME}\" -- env - true 2>/dev/null; then\nsuccess=$((${success}+1))\n- elif gcloud compute ssh --zone --internal-ip \"${ZONE}\" \"${USERNAME}\"@\"${INSTANCE_NAME}\" -- env - true 2>/dev/null; then\n+ elif gcloud compute ssh --internal-ip --zone \"${ZONE}\" \"${USERNAME}\"@\"${INSTANCE_NAME}\" -- env - true 2>/dev/null; then\nsuccess=$((${success}+1))\ninternal=\"--internal-ip\"\nfi\n@@ -78,29 +80,34 @@ done\nif [[ \"${success}\" -eq \"0\" ]]; then\necho \"connect timed out after ${timeout} seconds.\"\nexit 1\n+else\n+ echo \"done.\"\nfi\n# Run the install scripts provided.\nfor arg; do\n- gcloud compute ssh --zone \"${internal}\" \"${ZONE}\" \"${USERNAME}\"@\"${INSTANCE_NAME}\" -- sudo bash - <\"${arg}\" >/dev/null\n+ (set -x; gcloud compute ssh ${internal} \\\n+ --zone \"${ZONE}\" \\\n+ \"${USERNAME}\"@\"${INSTANCE_NAME}\" -- \\\n+ sudo bash - <\"${arg}\" >/dev/null)\ndone\n# Stop the instance; required before creating an image.\n-gcloud compute instances stop --quiet --zone \"${ZONE}\" \"${INSTANCE_NAME}\" >/dev/null\n+(set -x; gcloud compute instances stop --quiet --zone \"${ZONE}\" \"${INSTANCE_NAME}\" >/dev/null)\n# Create a snapshot of the instance disk.\n-gcloud compute disks snapshot \\\n+(set -x; gcloud compute disks snapshot \\\n--quiet \\\n--zone \"${ZONE}\" \\\n--snapshot-names=\"${SNAPSHOT_NAME}\" \\\n- \"${INSTANCE_NAME}\" >/dev/null\n+ \"${INSTANCE_NAME}\" >/dev/null)\n# Create the disk image.\n-gcloud compute images create \\\n+(set -x; gcloud compute images create \\\n--quiet \\\n--source-snapshot=\"${SNAPSHOT_NAME}\" \\\n--licenses=\"https://www.googleapis.com/compute/v1/projects/vm-options/global/licenses/enable-vmx\" \\\n- \"${IMAGE_NAME}\" >/dev/null\n+ \"${IMAGE_NAME}\" >/dev/null)\n# Finish up.\necho \"${IMAGE_NAME}\"\n" }, { "change_type": "MODIFY", "old_path": "tools/images/defs.bzl", "new_path": "tools/images/defs.bzl", "diff": "-\"\"\"Image configuration.\n-\n-Images can be generated by using the vm_image rule. For example,\n-\n- vm_image(\n- name = \"ubuntu\",\n- project = \"...\",\n- family = \"...\",\n- scripts = [\n- \"script.sh\",\n- \"other.sh\",\n- ],\n- )\n-\n-This will always create an vm_image in the current default gcloud project. The\n-rule has a text file as its output containing the image name. This will enforce\n-serialization for all dependent rules.\n-\n-Images are always named per the hash of all the hermetic input scripts. This\n-allows images to be memoized quickly and easily.\n-\n-The vm_test rule can be used to execute a command remotely. For example,\n-\n- vm_test(\n- name = \"mycommand\",\n- image = \":myimage\",\n- targets = [\":test\"],\n- )\n-\"\"\"\n+\"\"\"Image configuration. See README.md.\"\"\"\nload(\"//tools:defs.bzl\", \"default_installer\")\n-def _vm_image_impl(ctx):\n+# vm_image_builder is a rule that will construct a shell script that actually\n+# generates a given VM image. Note that this does not _run_ the shell script\n+# (although it can be run manually). It will be run manually during generation\n+# of the vm_image target itself. This level of indirection is used so that the\n+# build system itself only runs the builder once when multiple targets depend\n+# on it, avoiding a set of races and conflicts.\n+def _vm_image_builder_impl(ctx):\n+ # Generate a binary that actually builds the image.\n+ builder = ctx.actions.declare_file(ctx.label.name)\nscript_paths = []\nfor script in ctx.files.scripts:\nscript_paths.append(script.short_path)\n+ builder_content = \"\\n\".join([\n+ \"#!/bin/bash\",\n+ \"export ZONE=$(%s)\" % ctx.files.zone[0].short_path,\n+ \"export USERNAME=%s\" % ctx.attr.username,\n+ \"export IMAGE_PROJECT=%s\" % ctx.attr.project,\n+ \"export IMAGE_FAMILY=%s\" % ctx.attr.family,\n+ \"%s %s\" % (ctx.files._builder[0].short_path, \" \".join(script_paths)),\n+ \"\",\n+ ])\n+ ctx.actions.write(builder, builder_content, is_executable = True)\n- resolved_inputs, argv, runfiles_manifests = ctx.resolve_command(\n- command = \"USERNAME=%s ZONE=$(cat %s) IMAGE_PROJECT=%s IMAGE_FAMILY=%s %s %s > %s\" %\n- (\n- ctx.attr.username,\n- ctx.files.zone[0].path,\n- ctx.attr.project,\n- ctx.attr.family,\n- ctx.executable.builder.path,\n- \" \".join(script_paths),\n- ctx.outputs.out.path,\n- ),\n- tools = [ctx.attr.builder] + ctx.attr.scripts,\n- )\n-\n- ctx.actions.run_shell(\n- tools = resolved_inputs,\n- outputs = [ctx.outputs.out],\n- progress_message = \"Building image...\",\n- execution_requirements = {\"local\": \"true\"},\n- command = argv,\n- input_manifests = runfiles_manifests,\n- )\n+ # Note that the scripts should only be files, and should not include any\n+ # indirect transitive dependencies. The build script wouldn't work.\nreturn [DefaultInfo(\n- files = depset([ctx.outputs.out]),\n- runfiles = ctx.runfiles(files = [ctx.outputs.out]),\n+ executable = builder,\n+ runfiles = ctx.runfiles(\n+ files = ctx.files.scripts + ctx.files._builder + ctx.files.zone,\n+ ),\n)]\n-_vm_image = rule(\n+vm_image_builder = rule(\nattrs = {\n- \"builder\": attr.label(\n+ \"_builder\": attr.label(\nexecutable = True,\ndefault = \"//tools/images:builder\",\ncfg = \"host\",\n),\n\"username\": attr.string(default = \"$(whoami)\"),\n\"zone\": attr.label(\n+ executable = True,\ndefault = \"//tools/images:zone\",\ncfg = \"host\",\n),\n@@ -78,20 +51,55 @@ _vm_image = rule(\n\"project\": attr.string(mandatory = True),\n\"scripts\": attr.label_list(allow_files = True),\n},\n- outputs = {\n- \"out\": \"%{name}.txt\",\n+ executable = True,\n+ implementation = _vm_image_builder_impl,\n+)\n+\n+# See vm_image_builder above.\n+def _vm_image_impl(ctx):\n+ # Run the builder to generate our output.\n+ echo = ctx.actions.declare_file(ctx.label.name)\n+ resolved_inputs, argv, runfiles_manifests = ctx.resolve_command(\n+ command = \"echo -ne \\\"#!/bin/bash\\\\necho $(%s)\\\\n\\\" > %s && chmod 0755 %s\" % (\n+ ctx.files.builder[0].path,\n+ echo.path,\n+ echo.path,\n+ ),\n+ tools = [ctx.attr.builder],\n+ )\n+ ctx.actions.run_shell(\n+ tools = resolved_inputs,\n+ outputs = [echo],\n+ progress_message = \"Building image...\",\n+ execution_requirements = {\"local\": \"true\"},\n+ command = argv,\n+ input_manifests = runfiles_manifests,\n+ )\n+\n+ # Return just the echo command. All of the builder runfiles have been\n+ # resolved and consumed in the generation of the trivial echo script.\n+ return [DefaultInfo(executable = echo)]\n+\n+_vm_image = rule(\n+ attrs = {\n+ \"builder\": attr.label(\n+ executable = True,\n+ cfg = \"host\",\n+ ),\n},\n+ executable = True,\nimplementation = _vm_image_impl,\n)\n-def vm_image(**kwargs):\n- _vm_image(\n- tags = [\n- \"local\",\n- \"manual\",\n- ],\n+def vm_image(name, **kwargs):\n+ vm_image_builder(\n+ name = name + \"_builder\",\n**kwargs\n)\n+ _vm_image(\n+ name = name,\n+ builder = \":\" + name + \"_builder\",\n+ )\ndef _vm_test_impl(ctx):\nrunner = ctx.actions.declare_file(\"%s-executer\" % ctx.label.name)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "tools/images/zone.sh", "diff": "+#!/bin/bash\n+\n+# Copyright 2020 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+exec gcloud config get-value compute/zone\n" } ]
Go
Apache License 2.0
google/gvisor
Fix build.sh and VM targets. PiperOrigin-RevId: 306289643
259,885
14.04.2020 13:36:36
25,200
52b4b19249adfeba65fe6f0ef27111f2ed887888
Pass O_LARGEFILE in syscalls/linux/vfs2.openat. Needed for PipeTest_Flags: files opened by open() and openat() get O_LARGEFILE (on architectures with 64-bit off_t), but not FDs created by other syscalls such as pipe(). Updates
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/vfs2/filesystem.go", "new_path": "pkg/sentry/syscalls/linux/vfs2/filesystem.go", "diff": "@@ -172,7 +172,7 @@ func openat(t *kernel.Task, dirfd int32, pathAddr usermem.Addr, flags uint32, mo\ndefer tpop.Release()\nfile, err := t.Kernel().VFS().OpenAt(t, t.Credentials(), &tpop.pop, &vfs.OpenOptions{\n- Flags: flags,\n+ Flags: flags | linux.O_LARGEFILE,\nMode: linux.FileMode(mode & (0777 | linux.S_ISUID | linux.S_ISGID | linux.S_ISVTX) &^ t.FSContext().Umask()),\n})\nif err != nil {\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/file_description.go", "new_path": "pkg/sentry/vfs/file_description.go", "diff": "@@ -122,7 +122,7 @@ func (fd *FileDescription) Init(impl FileDescriptionImpl, statusFlags uint32, mn\n}\nfd.refs = 1\n- fd.statusFlags = statusFlags | linux.O_LARGEFILE\n+ fd.statusFlags = statusFlags\nfd.vd = VirtualDentry{\nmount: mnt,\ndentry: d,\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/vfs.go", "new_path": "pkg/sentry/vfs/vfs.go", "diff": "@@ -383,14 +383,11 @@ func (vfs *VirtualFilesystem) BoundEndpointAt(ctx context.Context, creds *auth.C\nfunc (vfs *VirtualFilesystem) OpenAt(ctx context.Context, creds *auth.Credentials, pop *PathOperation, opts *OpenOptions) (*FileDescription, error) {\n// Remove:\n//\n- // - O_LARGEFILE, which we always report in FileDescription status flags\n- // since only 64-bit architectures are supported at this time.\n- //\n// - O_CLOEXEC, which affects file descriptors and therefore must be\n// handled outside of VFS.\n//\n// - Unknown flags.\n- opts.Flags &= linux.O_ACCMODE | linux.O_CREAT | linux.O_EXCL | linux.O_NOCTTY | linux.O_TRUNC | linux.O_APPEND | linux.O_NONBLOCK | linux.O_DSYNC | linux.O_ASYNC | linux.O_DIRECT | linux.O_DIRECTORY | linux.O_NOFOLLOW | linux.O_NOATIME | linux.O_SYNC | linux.O_PATH | linux.O_TMPFILE\n+ opts.Flags &= linux.O_ACCMODE | linux.O_CREAT | linux.O_EXCL | linux.O_NOCTTY | linux.O_TRUNC | linux.O_APPEND | linux.O_NONBLOCK | linux.O_DSYNC | linux.O_ASYNC | linux.O_DIRECT | linux.O_LARGEFILE | linux.O_DIRECTORY | linux.O_NOFOLLOW | linux.O_NOATIME | linux.O_SYNC | linux.O_PATH | linux.O_TMPFILE\n// Linux's __O_SYNC (which we call linux.O_SYNC) implies O_DSYNC.\nif opts.Flags&linux.O_SYNC != 0 {\nopts.Flags |= linux.O_DSYNC\n" } ]
Go
Apache License 2.0
google/gvisor
Pass O_LARGEFILE in syscalls/linux/vfs2.openat. Needed for PipeTest_Flags: files opened by open() and openat() get O_LARGEFILE (on architectures with 64-bit off_t), but not FDs created by other syscalls such as pipe(). Updates #1035 PiperOrigin-RevId: 306504788
260,023
15.04.2020 01:10:38
25,200
9c918340e4e6126cca1dfedbf28fec8c8f836e1a
Reset pending connections on listener close Attempt to redeliver TCP segments that are enqueued into a closing TCP endpoint. This was being done for Established endpoints but not for those that are listening or performing connection handshake. Fixes
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/accept.go", "new_path": "pkg/tcpip/transport/tcp/accept.go", "diff": "@@ -330,6 +330,9 @@ func (l *listenContext) createEndpointAndPerformHandshake(s *segment, opts *head\nif l.listenEP != nil {\nl.removePendingEndpoint(ep)\n}\n+\n+ ep.drainClosingSegmentQueue()\n+\nreturn nil, err\n}\nep.isConnectNotified = true\n@@ -378,7 +381,7 @@ func (e *endpoint) deliverAccepted(n *endpoint) {\nfor {\nif e.acceptedChan == nil {\ne.acceptMu.Unlock()\n- n.Close()\n+ n.notifyProtocolGoroutine(notifyReset)\nreturn\n}\nselect {\n@@ -656,6 +659,8 @@ func (e *endpoint) protocolListenLoop(rcvWnd seqnum.Size) *tcpip.Error {\n}\ne.mu.Unlock()\n+ e.drainClosingSegmentQueue()\n+\n// Notify waiters that the endpoint is shutdown.\ne.waiterQueue.Notify(waiter.EventIn | waiter.EventOut | waiter.EventHUp | waiter.EventErr)\n}()\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/connect.go", "new_path": "pkg/tcpip/transport/tcp/connect.go", "diff": "@@ -1062,6 +1062,20 @@ func (e *endpoint) tryDeliverSegmentFromClosedEndpoint(s *segment) {\n}\n}\n+// Drain segment queue from the endpoint and try to re-match the segment to a\n+// different endpoint. This is used when the current endpoint is transitioned to\n+// StateClose and has been unregistered from the transport demuxer.\n+func (e *endpoint) drainClosingSegmentQueue() {\n+ for {\n+ s := e.segmentQueue.dequeue()\n+ if s == nil {\n+ break\n+ }\n+\n+ e.tryDeliverSegmentFromClosedEndpoint(s)\n+ }\n+}\n+\nfunc (e *endpoint) handleReset(s *segment) (ok bool, err *tcpip.Error) {\nif e.rcv.acceptable(s.sequenceNumber, 0) {\n// RFC 793, page 37 states that \"in all states\n@@ -1315,6 +1329,9 @@ func (e *endpoint) protocolMainLoop(handshake bool, wakerInitDone chan<- struct{\n}\ne.mu.Unlock()\n+\n+ e.drainClosingSegmentQueue()\n+\n// When the protocol loop exits we should wake up our waiters.\ne.waiterQueue.Notify(waiter.EventHUp | waiter.EventErr | waiter.EventIn | waiter.EventOut)\n}\n@@ -1565,19 +1582,6 @@ loop:\n// Lock released below.\nepilogue()\n- // epilogue removes the endpoint from the transport-demuxer and\n- // unlocks e.mu. Now that no new segments can get enqueued to this\n- // endpoint, try to re-match the segment to a different endpoint\n- // as the current endpoint is closed.\n- for {\n- s := e.segmentQueue.dequeue()\n- if s == nil {\n- break\n- }\n-\n- e.tryDeliverSegmentFromClosedEndpoint(s)\n- }\n-\n// A new SYN was received during TIME_WAIT and we need to abort\n// the timewait and redirect the segment to the listener queue\nif reuseTW != nil {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/endpoint.go", "new_path": "pkg/tcpip/transport/tcp/endpoint.go", "diff": "@@ -980,25 +980,22 @@ func (e *endpoint) closeNoShutdownLocked() {\n// Mark endpoint as closed.\ne.closed = true\n+\n+ switch e.EndpointState() {\n+ case StateClose, StateError:\n+ return\n+ }\n+\n// Either perform the local cleanup or kick the worker to make sure it\n// knows it needs to cleanup.\n- switch e.EndpointState() {\n- // Sockets in StateSynRecv state(passive connections) are closed when\n- // the handshake fails or if the listening socket is closed while\n- // handshake was in progress. In such cases the handshake goroutine\n- // is already gone by the time Close is called and we need to cleanup\n- // here.\n- case StateInitial, StateBound, StateSynRecv:\n- e.cleanupLocked()\n- e.setEndpointState(StateClose)\n- case StateError, StateClose:\n- // do nothing.\n- default:\n+ if e.workerRunning {\ne.workerCleanup = true\ntcpip.AddDanglingEndpoint(e)\n// Worker will remove the dangling endpoint when the endpoint\n// goroutine terminates.\ne.notifyProtocolGoroutine(notifyClose)\n+ } else {\n+ e.transitionToStateCloseLocked()\n}\n}\n@@ -1010,13 +1007,18 @@ func (e *endpoint) closePendingAcceptableConnectionsLocked() {\ne.acceptMu.Unlock()\nreturn\n}\n-\nclose(e.acceptedChan)\n+ ch := e.acceptedChan\ne.acceptedChan = nil\ne.acceptCond.Broadcast()\ne.acceptMu.Unlock()\n- // Wait for all pending endpoints to close.\n+ // Reset all connections that are waiting to be accepted.\n+ for n := range ch {\n+ n.notifyProtocolGoroutine(notifyReset)\n+ }\n+ // Wait for reset of all endpoints that are still waiting to be delivered to\n+ // the now closed acceptedChan.\ne.pendingAccepted.Wait()\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/tcp_test.go", "new_path": "pkg/tcpip/transport/tcp/tcp_test.go", "diff": "@@ -1068,6 +1068,43 @@ func TestListenShutdown(t *testing.T) {\nc.CheckNoPacket(\"Packet received when listening socket was shutdown\")\n}\n+// TestListenCloseWhileConnect tests for the listening endpoint to\n+// drain the accept-queue when closed. This should reset all of the\n+// pending connections that are waiting to be accepted.\n+func TestListenCloseWhileConnect(t *testing.T) {\n+ c := context.New(t, defaultMTU)\n+ defer c.Cleanup()\n+\n+ c.Create(-1 /* epRcvBuf */)\n+\n+ if err := c.EP.Bind(tcpip.FullAddress{Port: context.StackPort}); err != nil {\n+ t.Fatal(\"Bind failed:\", err)\n+ }\n+\n+ if err := c.EP.Listen(1 /* backlog */); err != nil {\n+ t.Fatal(\"Listen failed:\", err)\n+ }\n+\n+ waitEntry, notifyCh := waiter.NewChannelEntry(nil)\n+ c.WQ.EventRegister(&waitEntry, waiter.EventIn)\n+ defer c.WQ.EventUnregister(&waitEntry)\n+\n+ executeHandshake(t, c, context.TestPort, false /* synCookiesInUse */)\n+ // Wait for the new endpoint created because of handshake to be delivered\n+ // to the listening endpoint's accept queue.\n+ <-notifyCh\n+\n+ // Close the listening endpoint.\n+ c.EP.Close()\n+\n+ // Expect the listening endpoint to reset the connection.\n+ checker.IPv4(t, c.GetPacket(),\n+ checker.TCP(\n+ checker.DstPort(context.TestPort),\n+ checker.TCPFlags(header.TCPFlagAck|header.TCPFlagRst),\n+ ))\n+}\n+\nfunc TestTOSV4(t *testing.T) {\nc := context.New(t, defaultMTU)\ndefer c.Cleanup()\n" }, { "change_type": "MODIFY", "old_path": "test/packetimpact/tests/BUILD", "new_path": "test/packetimpact/tests/BUILD", "diff": "@@ -43,8 +43,6 @@ packetimpact_go_test(\npacketimpact_go_test(\nname = \"tcp_noaccept_close_rst\",\nsrcs = [\"tcp_noaccept_close_rst_test.go\"],\n- # TODO(b/153380909): Fix netstack then remove the line below.\n- netstack = False,\ndeps = [\n\"//pkg/tcpip/header\",\n\"//test/packetimpact/testbench\",\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_inet_loopback.cc", "new_path": "test/syscalls/linux/socket_inet_loopback.cc", "diff": "@@ -365,6 +365,68 @@ TEST_P(SocketInetLoopbackTest, TCPListenClose) {\n}\n}\n+TEST_P(SocketInetLoopbackTest, TCPListenCloseWhileConnect) {\n+ auto const& param = GetParam();\n+\n+ TestAddress const& listener = param.listener;\n+ TestAddress const& connector = param.connector;\n+\n+ constexpr int kBacklog = 2;\n+ constexpr int kClients = kBacklog + 1;\n+\n+ // Create the listening socket.\n+ FileDescriptor listen_fd = ASSERT_NO_ERRNO_AND_VALUE(\n+ Socket(listener.family(), SOCK_STREAM, IPPROTO_TCP));\n+ sockaddr_storage listen_addr = listener.addr;\n+ ASSERT_THAT(bind(listen_fd.get(), reinterpret_cast<sockaddr*>(&listen_addr),\n+ listener.addr_len),\n+ SyscallSucceeds());\n+ ASSERT_THAT(listen(listen_fd.get(), kBacklog), SyscallSucceeds());\n+\n+ // Get the port bound by the listening socket.\n+ socklen_t addrlen = listener.addr_len;\n+ ASSERT_THAT(getsockname(listen_fd.get(),\n+ reinterpret_cast<sockaddr*>(&listen_addr), &addrlen),\n+ SyscallSucceeds());\n+ uint16_t const port =\n+ ASSERT_NO_ERRNO_AND_VALUE(AddrPort(listener.family(), listen_addr));\n+\n+ sockaddr_storage conn_addr = connector.addr;\n+ ASSERT_NO_ERRNO(SetAddrPort(connector.family(), &conn_addr, port));\n+ std::vector<FileDescriptor> clients;\n+ for (int i = 0; i < kClients; i++) {\n+ FileDescriptor client = ASSERT_NO_ERRNO_AND_VALUE(\n+ Socket(connector.family(), SOCK_STREAM | SOCK_NONBLOCK, IPPROTO_TCP));\n+ int ret = connect(client.get(), reinterpret_cast<sockaddr*>(&conn_addr),\n+ connector.addr_len);\n+ if (ret != 0) {\n+ EXPECT_THAT(ret, SyscallFailsWithErrno(EINPROGRESS));\n+ clients.push_back(std::move(client));\n+ }\n+ }\n+ // Close the listening socket.\n+ listen_fd.reset();\n+\n+ for (auto& client : clients) {\n+ const int kTimeout = 10000;\n+ struct pollfd pfd = {\n+ .fd = client.get(),\n+ .events = POLLIN,\n+ };\n+ // When the listening socket is closed, then we expect the remote to reset\n+ // the connection.\n+ ASSERT_THAT(poll(&pfd, 1, kTimeout), SyscallSucceedsWithValue(1));\n+ ASSERT_EQ(pfd.revents, POLLIN | POLLHUP | POLLERR);\n+ char c;\n+ // Subsequent read can fail with:\n+ // ECONNRESET: If the client connection was established and was reset by the\n+ // remote. ECONNREFUSED: If the client connection failed to be established.\n+ ASSERT_THAT(read(client.get(), &c, sizeof(c)),\n+ AnyOf(SyscallFailsWithErrno(ECONNRESET),\n+ SyscallFailsWithErrno(ECONNREFUSED)));\n+ }\n+}\n+\nTEST_P(SocketInetLoopbackTest, TCPbacklog) {\nauto const& param = GetParam();\n" } ]
Go
Apache License 2.0
google/gvisor
Reset pending connections on listener close Attempt to redeliver TCP segments that are enqueued into a closing TCP endpoint. This was being done for Established endpoints but not for those that are listening or performing connection handshake. Fixes #2417 PiperOrigin-RevId: 306598155
260,003
15.04.2020 14:30:20
25,200
ea5b8e9633cd2731bb5656dea523beaf3d643472
Use if_nametoindex to get interface index. Removed the TODO to use netlink.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/ip_socket_test_util.cc", "new_path": "test/syscalls/linux/ip_socket_test_util.cc", "diff": "#include <net/if.h>\n#include <netinet/in.h>\n-#include <sys/ioctl.h>\n#include <sys/socket.h>\n#include <cstring>\n@@ -35,12 +34,11 @@ uint16_t PortFromInetSockaddr(const struct sockaddr* addr) {\n}\nPosixErrorOr<int> InterfaceIndex(std::string name) {\n- // TODO(igudger): Consider using netlink.\n- ifreq req = {};\n- memcpy(req.ifr_name, name.c_str(), name.size());\n- ASSIGN_OR_RETURN_ERRNO(auto sock, Socket(AF_INET, SOCK_DGRAM, 0));\n- RETURN_ERROR_IF_SYSCALL_FAIL(ioctl(sock.get(), SIOCGIFINDEX, &req));\n- return req.ifr_ifindex;\n+ int index = if_nametoindex(name.c_str());\n+ if (index) {\n+ return index;\n+ }\n+ return PosixError(errno);\n}\nnamespace {\n" } ]
Go
Apache License 2.0
google/gvisor
Use if_nametoindex to get interface index. Removed the TODO to use netlink. PiperOrigin-RevId: 306721468
259,972
15.04.2020 14:57:56
25,200
3d3bf9603d9a933b4bf19c38190c583894b75d66
Use hex.Dump for Layer.String() of byte slices.
[ { "change_type": "MODIFY", "old_path": "test/packetimpact/testbench/layers.go", "new_path": "test/packetimpact/testbench/layers.go", "diff": "package testbench\nimport (\n+ \"encoding/hex\"\n\"fmt\"\n\"reflect\"\n\"strings\"\n@@ -133,7 +134,12 @@ func stringLayer(l Layer) string {\nif v.IsNil() {\ncontinue\n}\n- ret = append(ret, fmt.Sprintf(\"%s:%v\", t.Name, reflect.Indirect(v)))\n+ v = reflect.Indirect(v)\n+ if v.Kind() == reflect.Slice && v.Type().Elem().Kind() == reflect.Uint8 {\n+ ret = append(ret, fmt.Sprintf(\"%s:\\n%v\", t.Name, hex.Dump(v.Bytes())))\n+ } else {\n+ ret = append(ret, fmt.Sprintf(\"%s:%v\", t.Name, v))\n+ }\n}\nreturn fmt.Sprintf(\"&%s{%s}\", t, strings.Join(ret, \" \"))\n}\n" }, { "change_type": "MODIFY", "old_path": "test/packetimpact/testbench/layers_test.go", "new_path": "test/packetimpact/testbench/layers_test.go", "diff": "package testbench\n-import \"testing\"\n+import (\n+ \"testing\"\n-import \"gvisor.dev/gvisor/pkg/tcpip\"\n+ \"gvisor.dev/gvisor/pkg/tcpip\"\n+)\nfunc TestLayerMatch(t *testing.T) {\nvar nilPayload *Payload\n@@ -134,6 +136,16 @@ func TestLayerStringFormat(t *testing.T) {\n\"Type:4\" +\n\"}\",\n},\n+ {\n+ name: \"Payload\",\n+ l: &Payload{\n+ Bytes: []byte(\"Hooray for packetimpact.\"),\n+ },\n+ want: \"&testbench.Payload{Bytes:\\n\" +\n+ \"00000000 48 6f 6f 72 61 79 20 66 6f 72 20 70 61 63 6b 65 |Hooray for packe|\\n\" +\n+ \"00000010 74 69 6d 70 61 63 74 2e |timpact.|\\n\" +\n+ \"}\",\n+ },\n} {\nt.Run(tt.name, func(t *testing.T) {\nif got := tt.l.String(); got != tt.want {\n" } ]
Go
Apache License 2.0
google/gvisor
Use hex.Dump for Layer.String() of byte slices. PiperOrigin-RevId: 306726587
259,972
15.04.2020 19:36:03
25,200
09c7e3f6e497f4ae267772e7357763ac7c18659f
Add tests for segments outside the receive window. The tests are based on RFC 793 page 69. Updates
[ { "change_type": "MODIFY", "old_path": "test/packetimpact/testbench/connections.go", "new_path": "test/packetimpact/testbench/connections.go", "diff": "@@ -577,13 +577,27 @@ func (conn *TCPIPv4) Expect(tcp TCP, timeout time.Duration) (*TCP, error) {\nreturn gotTCP, err\n}\n-// RemoteSeqNum returns the next expected sequence number from the DUT.\n-func (conn *TCPIPv4) RemoteSeqNum() *seqnum.Value {\n+func (conn *TCPIPv4) state() *tcpState {\nstate, ok := conn.layerStates[len(conn.layerStates)-1].(*tcpState)\nif !ok {\nconn.t.Fatalf(\"expected final state of %v to be tcpState\", conn.layerStates)\n}\n- return state.remoteSeqNum\n+ return state\n+}\n+\n+// RemoteSeqNum returns the next expected sequence number from the DUT.\n+func (conn *TCPIPv4) RemoteSeqNum() *seqnum.Value {\n+ return conn.state().remoteSeqNum\n+}\n+\n+// LocalSeqNum returns the next expected sequence number from the DUT.\n+func (conn *TCPIPv4) LocalSeqNum() *seqnum.Value {\n+ return conn.state().localSeqNum\n+}\n+\n+// SynAck returns the SynAck that was part of the handshake.\n+func (conn *TCPIPv4) SynAck() *TCP {\n+ return conn.state().synAck\n}\n// Drain drains the sniffer's receive buffer by receiving packets until there's\n" }, { "change_type": "MODIFY", "old_path": "test/packetimpact/tests/BUILD", "new_path": "test/packetimpact/tests/BUILD", "diff": "@@ -40,6 +40,19 @@ packetimpact_go_test(\n],\n)\n+packetimpact_go_test(\n+ name = \"tcp_outside_the_window\",\n+ srcs = [\"tcp_outside_the_window_test.go\"],\n+ # TODO(eyalsoha): Fix #1607 then remove the line below.\n+ netstack = False,\n+ deps = [\n+ \"//pkg/tcpip/header\",\n+ \"//pkg/tcpip/seqnum\",\n+ \"//test/packetimpact/testbench\",\n+ \"@org_golang_x_sys//unix:go_default_library\",\n+ ],\n+)\n+\npacketimpact_go_test(\nname = \"tcp_noaccept_close_rst\",\nsrcs = [\"tcp_noaccept_close_rst_test.go\"],\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test/packetimpact/tests/tcp_outside_the_window_test.go", "diff": "+// Copyright 2020 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 tcp_outside_the_window_test\n+\n+import (\n+ \"fmt\"\n+ \"testing\"\n+ \"time\"\n+\n+ \"golang.org/x/sys/unix\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/header\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/seqnum\"\n+ tb \"gvisor.dev/gvisor/test/packetimpact/testbench\"\n+)\n+\n+// TestTCPOutsideTheWindows tests the behavior of the DUT when packets arrive\n+// that are inside or outside the TCP window. Packets that are outside the\n+// window should force an extra ACK, as described in RFC793 page 69:\n+// https://tools.ietf.org/html/rfc793#page-69\n+func TestTCPOutsideTheWindow(t *testing.T) {\n+ for _, tt := range []struct {\n+ description string\n+ tcpFlags uint8\n+ payload []tb.Layer\n+ seqNumOffset seqnum.Size\n+ expectACK bool\n+ }{\n+ {\"SYN\", header.TCPFlagSyn, nil, 0, true},\n+ {\"SYNACK\", header.TCPFlagSyn | header.TCPFlagAck, nil, 0, true},\n+ {\"ACK\", header.TCPFlagAck, nil, 0, false},\n+ {\"FIN\", header.TCPFlagFin, nil, 0, false},\n+ {\"Data\", header.TCPFlagAck, []tb.Layer{&tb.Payload{Bytes: []byte(\"abc123\")}}, 0, true},\n+\n+ {\"SYN\", header.TCPFlagSyn, nil, 1, true},\n+ {\"SYNACK\", header.TCPFlagSyn | header.TCPFlagAck, nil, 1, true},\n+ {\"ACK\", header.TCPFlagAck, nil, 1, true},\n+ {\"FIN\", header.TCPFlagFin, nil, 1, false},\n+ {\"Data\", header.TCPFlagAck, []tb.Layer{&tb.Payload{Bytes: []byte(\"abc123\")}}, 1, true},\n+\n+ {\"SYN\", header.TCPFlagSyn, nil, 2, true},\n+ {\"SYNACK\", header.TCPFlagSyn | header.TCPFlagAck, nil, 2, true},\n+ {\"ACK\", header.TCPFlagAck, nil, 2, true},\n+ {\"FIN\", header.TCPFlagFin, nil, 2, false},\n+ {\"Data\", header.TCPFlagAck, []tb.Layer{&tb.Payload{Bytes: []byte(\"abc123\")}}, 2, true},\n+ } {\n+ t.Run(fmt.Sprintf(\"%s%d\", tt.description, tt.seqNumOffset), func(t *testing.T) {\n+ dut := tb.NewDUT(t)\n+ defer dut.TearDown()\n+ listenFD, remotePort := dut.CreateListener(unix.SOCK_STREAM, unix.IPPROTO_TCP, 1)\n+ defer dut.Close(listenFD)\n+ conn := tb.NewTCPIPv4(t, tb.TCP{DstPort: &remotePort}, tb.TCP{SrcPort: &remotePort})\n+ defer conn.Close()\n+ conn.Handshake()\n+ acceptFD, _ := dut.Accept(listenFD)\n+ defer dut.Close(acceptFD)\n+\n+ windowSize := seqnum.Size(*conn.SynAck().WindowSize) + tt.seqNumOffset\n+ conn.Drain()\n+ // Ignore whatever incrementing that this out-of-order packet might cause\n+ // to the AckNum.\n+ localSeqNum := tb.Uint32(uint32(*conn.LocalSeqNum()))\n+ conn.Send(tb.TCP{\n+ Flags: tb.Uint8(tt.tcpFlags),\n+ SeqNum: tb.Uint32(uint32(conn.LocalSeqNum().Add(windowSize))),\n+ }, tt.payload...)\n+ timeout := 3 * time.Second\n+ gotACK, err := conn.Expect(tb.TCP{Flags: tb.Uint8(header.TCPFlagAck), AckNum: localSeqNum}, timeout)\n+ if tt.expectACK && err != nil {\n+ t.Fatalf(\"expected an ACK packet within %s but got none: %s\", timeout, err)\n+ }\n+ if !tt.expectACK && gotACK != nil {\n+ t.Fatalf(\"expected no ACK packet within %s but got one: %s\", timeout, gotACK)\n+ }\n+ })\n+ }\n+}\n" } ]
Go
Apache License 2.0
google/gvisor
Add tests for segments outside the receive window. The tests are based on RFC 793 page 69. Updates #1607 PiperOrigin-RevId: 306768847
259,992
16.04.2020 11:48:14
25,200
28399818fc1e5d294cc93ddd4a1ac7e31c375fbf
Make ExtractErrno a function
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/task_run.go", "new_path": "pkg/sentry/kernel/task_run.go", "diff": "@@ -353,7 +353,7 @@ func (app *runApp) execute(t *Task) taskRunState {\ndefault:\n// What happened? Can't continue.\nt.Warningf(\"Unexpected SwitchToApp error: %v\", err)\n- t.PrepareExit(ExitStatus{Code: t.ExtractErrno(err, -1)})\n+ t.PrepareExit(ExitStatus{Code: ExtractErrno(err, -1)})\nreturn (*runExit)(nil)\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/task_signals.go", "new_path": "pkg/sentry/kernel/task_signals.go", "diff": "@@ -174,7 +174,7 @@ func (t *Task) deliverSignal(info *arch.SignalInfo, act arch.SignalAct) taskRunS\nfallthrough\ncase (sre == ERESTARTSYS && !act.IsRestart()):\nt.Debugf(\"Not restarting syscall %d after errno %d: interrupted by signal %d\", t.Arch().SyscallNo(), sre, info.Signo)\n- t.Arch().SetReturn(uintptr(-t.ExtractErrno(syserror.EINTR, -1)))\n+ t.Arch().SetReturn(uintptr(-ExtractErrno(syserror.EINTR, -1)))\ndefault:\nt.Debugf(\"Restarting syscall %d after errno %d: interrupted by signal %d\", t.Arch().SyscallNo(), sre, info.Signo)\nt.Arch().RestartSyscall()\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/task_syscall.go", "new_path": "pkg/sentry/kernel/task_syscall.go", "diff": "@@ -312,7 +312,7 @@ func (t *Task) doSyscallInvoke(sysno uintptr, args arch.SyscallArguments) taskRu\nreturn ctrl.next\n}\n} else if err != nil {\n- t.Arch().SetReturn(uintptr(-t.ExtractErrno(err, int(sysno))))\n+ t.Arch().SetReturn(uintptr(-ExtractErrno(err, int(sysno))))\nt.haveSyscallReturn = true\n} else {\nt.Arch().SetReturn(rval)\n@@ -431,7 +431,7 @@ func (t *Task) doVsyscallInvoke(sysno uintptr, args arch.SyscallArguments, calle\n// A return is not emulated in this case.\nreturn (*runApp)(nil)\n}\n- t.Arch().SetReturn(uintptr(-t.ExtractErrno(err, int(sysno))))\n+ t.Arch().SetReturn(uintptr(-ExtractErrno(err, int(sysno))))\n}\nt.Arch().SetIP(t.Arch().Value(caller))\nt.Arch().SetStack(t.Arch().Stack() + uintptr(t.Arch().Width()))\n@@ -441,7 +441,7 @@ func (t *Task) doVsyscallInvoke(sysno uintptr, args arch.SyscallArguments, calle\n// ExtractErrno extracts an integer error number from the error.\n// The syscall number is purely for context in the error case. Use -1 if\n// syscall number is unknown.\n-func (t *Task) ExtractErrno(err error, sysno int) int {\n+func ExtractErrno(err error, sysno int) int {\nswitch err := err.(type) {\ncase nil:\nreturn 0\n@@ -455,11 +455,11 @@ func (t *Task) ExtractErrno(err error, sysno int) int {\n// handled (and the SIGBUS is delivered).\nreturn int(syscall.EFAULT)\ncase *os.PathError:\n- return t.ExtractErrno(err.Err, sysno)\n+ return ExtractErrno(err.Err, sysno)\ncase *os.LinkError:\n- return t.ExtractErrno(err.Err, sysno)\n+ return ExtractErrno(err.Err, sysno)\ncase *os.SyscallError:\n- return t.ExtractErrno(err.Err, sysno)\n+ return ExtractErrno(err.Err, sysno)\ndefault:\nif errno, ok := syserror.TranslateError(err); ok {\nreturn int(errno)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/strace/strace.go", "new_path": "pkg/sentry/strace/strace.go", "diff": "@@ -719,7 +719,7 @@ func (s SyscallMap) SyscallEnter(t *kernel.Task, sysno uintptr, args arch.Syscal\n// SyscallExit implements kernel.Stracer.SyscallExit. It logs the syscall\n// exit trace.\nfunc (s SyscallMap) SyscallExit(context interface{}, t *kernel.Task, sysno, rval uintptr, err error) {\n- errno := t.ExtractErrno(err, int(sysno))\n+ errno := kernel.ExtractErrno(err, int(sysno))\nc := context.(*syscallContext)\nelapsed := time.Since(c.start)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/sys_aio.go", "new_path": "pkg/sentry/syscalls/linux/sys_aio.go", "diff": "@@ -290,7 +290,7 @@ func performCallback(t *kernel.Task, file *fs.File, cbAddr usermem.Addr, cb *ioC\n// Update the result.\nif err != nil {\nerr = handleIOError(t, ev.Result != 0 /* partial */, err, nil /* never interrupted */, \"aio\", file)\n- ev.Result = -int64(t.ExtractErrno(err, 0))\n+ ev.Result = -int64(kernel.ExtractErrno(err, 0))\n}\nfile.DecRef()\n" } ]
Go
Apache License 2.0
google/gvisor
Make ExtractErrno a function PiperOrigin-RevId: 306891171
259,992
16.04.2020 13:15:47
25,200
5a8ee1beee364559bac37376949de1ea01d00ae2
Preserve log FD after execve
[ { "change_type": "MODIFY", "old_path": "runsc/main.go", "new_path": "runsc/main.go", "diff": "@@ -291,7 +291,7 @@ func main() {\n// want with them. Since Docker and Containerd both eat boot's stderr, we\n// dup our stderr to the provided log FD so that panics will appear in the\n// logs, rather than just disappear.\n- if err := syscall.Dup3(fd, int(os.Stderr.Fd()), syscall.O_CLOEXEC); err != nil {\n+ if err := syscall.Dup3(fd, int(os.Stderr.Fd()), 0); err != nil {\ncmd.Fatalf(\"error dup'ing fd %d to stderr: %v\", fd, err)\n}\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Preserve log FD after execve PiperOrigin-RevId: 306908296
259,972
16.04.2020 15:14:44
25,200
75e864fc7529bf71484ecabbb2ce2264e96399cf
Use multierr in packetimpact Connection.Close()
[ { "change_type": "MODIFY", "old_path": "WORKSPACE", "new_path": "WORKSPACE", "diff": "@@ -400,6 +400,20 @@ go_repository(\nversion = \"v0.20.0\",\n)\n+go_repository(\n+ name = \"org_uber_go_atomic\",\n+ importpath = \"go.uber.org/atomic\",\n+ version = \"v1.6.0\",\n+ sum = \"h1:Ezj3JGmsOnG1MoRWQkPBsKLe9DwWD9QeXzTRzzldNVk=\",\n+)\n+\n+go_repository(\n+ name = \"org_uber_go_multierr\",\n+ importpath = \"go.uber.org/multierr\",\n+ version = \"v1.5.0\",\n+ sum = \"h1:KCa4XfM8CWFCpxXRGok+Q0SS/0XBhMDbHHGABQLvD2A=\",\n+)\n+\n# BigQuery Dependencies for Benchmarks\ngo_repository(\nname = \"com_google_cloud_go\",\n" }, { "change_type": "MODIFY", "old_path": "test/packetimpact/testbench/BUILD", "new_path": "test/packetimpact/testbench/BUILD", "diff": "@@ -28,6 +28,7 @@ go_library(\n\"@org_golang_google_grpc//:go_default_library\",\n\"@org_golang_google_grpc//keepalive:go_default_library\",\n\"@org_golang_x_sys//unix:go_default_library\",\n+ \"@org_uber_go_multierr//:go_default_library\",\n],\n)\n" }, { "change_type": "MODIFY", "old_path": "test/packetimpact/testbench/connections.go", "new_path": "test/packetimpact/testbench/connections.go", "diff": "@@ -26,6 +26,7 @@ import (\n\"time\"\n\"github.com/mohae/deepcopy\"\n+ \"go.uber.org/multierr\"\n\"golang.org/x/sys/unix\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n@@ -382,16 +383,14 @@ func (conn *Connection) match(override, received Layers) bool {\n// Close frees associated resources held by the Connection.\nfunc (conn *Connection) Close() {\n- if err := conn.sniffer.close(); err != nil {\n- conn.t.Fatal(err)\n- }\n- if err := conn.injector.close(); err != nil {\n- conn.t.Fatal(err)\n- }\n+ errs := multierr.Combine(conn.sniffer.close(), conn.injector.close())\nfor _, s := range conn.layerStates {\nif err := s.close(); err != nil {\n- conn.t.Fatalf(\"unable to close %+v: %s\", s, err)\n+ errs = multierr.Append(errs, fmt.Errorf(\"unable to close %+v: %s\", s, err))\n+ }\n}\n+ if errs != nil {\n+ conn.t.Fatalf(\"unable to close %+v: %s\", conn, errs)\n}\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Use multierr in packetimpact Connection.Close() PiperOrigin-RevId: 306930652
260,004
16.04.2020 17:26:12
25,200
b33c3bb4a73974bbae4274da5100a3cd3f5deef8
Return detailed errors when iterating NDP options Test: header_test.TestNDPOptionsIterCheck
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/header/BUILD", "new_path": "pkg/tcpip/header/BUILD", "diff": "@@ -21,6 +21,7 @@ go_library(\n\"ndp_options.go\",\n\"ndp_router_advert.go\",\n\"ndp_router_solicit.go\",\n+ \"ndpoptionidentifier_string.go\",\n\"tcp.go\",\n\"udp.go\",\n],\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/header/ndp_options.go", "new_path": "pkg/tcpip/header/ndp_options.go", "diff": "package header\nimport (\n+ \"bytes\"\n\"encoding/binary\"\n\"errors\"\n\"fmt\"\n+ \"io\"\n\"math\"\n\"time\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n)\n+// NDPOptionIdentifier is an NDP option type identifier.\n+type NDPOptionIdentifier uint8\n+\nconst (\n// NDPSourceLinkLayerAddressOptionType is the type of the Source Link Layer\n// Address option, as per RFC 4861 section 4.6.1.\n- NDPSourceLinkLayerAddressOptionType = 1\n+ NDPSourceLinkLayerAddressOptionType NDPOptionIdentifier = 1\n// NDPTargetLinkLayerAddressOptionType is the type of the Target Link Layer\n// Address option, as per RFC 4861 section 4.6.1.\n- NDPTargetLinkLayerAddressOptionType = 2\n+ NDPTargetLinkLayerAddressOptionType NDPOptionIdentifier = 2\n+\n+ // NDPPrefixInformationType is the type of the Prefix Information\n+ // option, as per RFC 4861 section 4.6.2.\n+ NDPPrefixInformationType NDPOptionIdentifier = 3\n+ // NDPRecursiveDNSServerOptionType is the type of the Recursive DNS\n+ // Server option, as per RFC 8106 section 5.1.\n+ NDPRecursiveDNSServerOptionType NDPOptionIdentifier = 25\n+)\n+\n+const (\n// NDPLinkLayerAddressSize is the size of a Source or Target Link Layer\n// Address option for an Ethernet address.\nNDPLinkLayerAddressSize = 8\n- // NDPPrefixInformationType is the type of the Prefix Information\n- // option, as per RFC 4861 section 4.6.2.\n- NDPPrefixInformationType = 3\n-\n// ndpPrefixInformationLength is the expected length, in bytes, of the\n// body of an NDP Prefix Information option, as per RFC 4861 section\n// 4.6.2 which specifies that the Length field is 4. Given this, the\n@@ -91,10 +102,6 @@ const (\n// within an NDPPrefixInformation.\nndpPrefixInformationPrefixOffset = 14\n- // NDPRecursiveDNSServerOptionType is the type of the Recursive DNS\n- // Server option, as per RFC 8106 section 5.1.\n- NDPRecursiveDNSServerOptionType = 25\n-\n// ndpRecursiveDNSServerLifetimeOffset is the start of the 4-byte\n// Lifetime field within an NDPRecursiveDNSServer.\nndpRecursiveDNSServerLifetimeOffset = 2\n@@ -103,10 +110,10 @@ const (\n// for IPv6 Recursive DNS Servers within an NDPRecursiveDNSServer.\nndpRecursiveDNSServerAddressesOffset = 6\n- // minNDPRecursiveDNSServerLength is the minimum NDP Recursive DNS\n- // Server option's length field value when it contains at least one\n- // IPv6 address.\n- minNDPRecursiveDNSServerLength = 3\n+ // minNDPRecursiveDNSServerLength is the minimum NDP Recursive DNS Server\n+ // option's body size when it contains at least one IPv6 address, as per\n+ // RFC 8106 section 5.3.1.\n+ minNDPRecursiveDNSServerBodySize = 22\n// lengthByteUnits is the multiplier factor for the Length field of an\n// NDP option. That is, the length field for NDP options is in units of\n@@ -132,16 +139,13 @@ var (\n// few NDPOption then modify the backing NDPOptions so long as the\n// NDPOptionIterator obtained before modification is no longer used.\ntype NDPOptionIterator struct {\n- // The NDPOptions this NDPOptionIterator is iterating over.\n- opts NDPOptions\n+ opts *bytes.Buffer\n}\n// Potential errors when iterating over an NDPOptions.\nvar (\n- ErrNDPOptBufExhausted = errors.New(\"Buffer unexpectedly exhausted\")\n- ErrNDPOptZeroLength = errors.New(\"NDP option has zero-valued Length field\")\nErrNDPOptMalformedBody = errors.New(\"NDP option has a malformed body\")\n- ErrNDPInvalidLength = errors.New(\"NDP option's Length value is invalid as per relevant RFC\")\n+ ErrNDPOptMalformedHeader = errors.New(\"NDP option has a malformed header\")\n)\n// Next returns the next element in the backing NDPOptions, or true if we are\n@@ -152,48 +156,50 @@ var (\nfunc (i *NDPOptionIterator) Next() (NDPOption, bool, error) {\nfor {\n// Do we still have elements to look at?\n- if len(i.opts) == 0 {\n+ if i.opts.Len() == 0 {\nreturn nil, true, nil\n}\n- // Do we have enough bytes for an NDP option that has a Length\n- // field of at least 1? Note, 0 in the Length field is invalid.\n- if len(i.opts) < lengthByteUnits {\n- return nil, true, ErrNDPOptBufExhausted\n+ // Get the Type field.\n+ temp, err := i.opts.ReadByte()\n+ if err != nil {\n+ if err != io.EOF {\n+ // ReadByte should only ever return nil or io.EOF.\n+ panic(fmt.Sprintf(\"unexpected error when reading the option's Type field: %s\", err))\n}\n- // Get the Type field.\n- t := i.opts[0]\n+ // We use io.ErrUnexpectedEOF as exhausting the buffer is unexpected once\n+ // we start parsing an option; we expect the buffer to contain enough\n+ // bytes for the whole option.\n+ return nil, true, fmt.Errorf(\"unexpectedly exhausted buffer when reading the option's Type field: %w\", io.ErrUnexpectedEOF)\n+ }\n+ kind := NDPOptionIdentifier(temp)\n// Get the Length field.\n- l := i.opts[1]\n-\n- // This would indicate an erroneous NDP option as the Length\n- // field should never be 0.\n- if l == 0 {\n- return nil, true, ErrNDPOptZeroLength\n+ length, err := i.opts.ReadByte()\n+ if err != nil {\n+ if err != io.EOF {\n+ panic(fmt.Sprintf(\"unexpected error when reading the option's Length field for %s: %s\", kind, err))\n}\n- // How many bytes are in the option body?\n- numBytes := int(l) * lengthByteUnits\n- numBodyBytes := numBytes - 2\n-\n- potentialBody := i.opts[2:]\n-\n- // This would indicate an erroenous NDPOptions buffer as we ran\n- // out of the buffer in the middle of an NDP option.\n- if left := len(potentialBody); left < numBodyBytes {\n- return nil, true, ErrNDPOptBufExhausted\n+ return nil, true, fmt.Errorf(\"unexpectedly exhausted buffer when reading the option's Length field for %s: %w\", kind, io.ErrUnexpectedEOF)\n}\n- // Get only the options body, leaving the rest of the options\n- // buffer alone.\n- body := potentialBody[:numBodyBytes]\n+ // This would indicate an erroneous NDP option as the Length field should\n+ // never be 0.\n+ if length == 0 {\n+ return nil, true, fmt.Errorf(\"zero valued Length field for %s: %w\", kind, ErrNDPOptMalformedHeader)\n+ }\n- // Update opts with the remaining options body.\n- i.opts = i.opts[numBytes:]\n+ // Get the body.\n+ numBytes := int(length) * lengthByteUnits\n+ numBodyBytes := numBytes - 2\n+ body := i.opts.Next(numBodyBytes)\n+ if len(body) < numBodyBytes {\n+ return nil, true, fmt.Errorf(\"unexpectedly exhausted buffer when reading the option's Body for %s: %w\", kind, io.ErrUnexpectedEOF)\n+ }\n- switch t {\n+ switch kind {\ncase NDPSourceLinkLayerAddressOptionType:\nreturn NDPSourceLinkLayerAddressOption(body), false, nil\n@@ -205,22 +211,15 @@ func (i *NDPOptionIterator) Next() (NDPOption, bool, error) {\n// body is ndpPrefixInformationLength, as per RFC 4861\n// section 4.6.2.\nif numBodyBytes != ndpPrefixInformationLength {\n- return nil, true, ErrNDPOptMalformedBody\n+ return nil, true, fmt.Errorf(\"got %d bytes for NDP Prefix Information option's body, expected %d bytes: %w\", numBodyBytes, ndpPrefixInformationLength, ErrNDPOptMalformedBody)\n}\nreturn NDPPrefixInformation(body), false, nil\ncase NDPRecursiveDNSServerOptionType:\n- // RFC 8106 section 5.3.1 outlines that the RDNSS option\n- // must have a minimum length of 3 so it contains at\n- // least one IPv6 address.\n- if l < minNDPRecursiveDNSServerLength {\n- return nil, true, ErrNDPInvalidLength\n- }\n-\nopt := NDPRecursiveDNSServer(body)\n- if len(opt.Addresses()) == 0 {\n- return nil, true, ErrNDPOptMalformedBody\n+ if err := opt.checkAddresses(); err != nil {\n+ return nil, true, err\n}\nreturn opt, false, nil\n@@ -247,10 +246,16 @@ type NDPOptions []byte\n//\n// See NDPOptionIterator for more information.\nfunc (b NDPOptions) Iter(check bool) (NDPOptionIterator, error) {\n- it := NDPOptionIterator{opts: b}\n+ it := NDPOptionIterator{\n+ opts: bytes.NewBuffer(b),\n+ }\nif check {\n- for it2 := it; true; {\n+ it2 := NDPOptionIterator{\n+ opts: bytes.NewBuffer(b),\n+ }\n+\n+ for {\nif _, done, err := it2.Next(); err != nil || done {\nreturn it, err\n}\n@@ -278,7 +283,7 @@ func (b NDPOptions) Serialize(s NDPOptionsSerializer) int {\ncontinue\n}\n- b[0] = o.Type()\n+ b[0] = byte(o.Type())\n// We know this safe because paddedLength would have returned\n// 0 if o had an invalid length (> 255 * lengthByteUnits).\n@@ -304,7 +309,7 @@ type NDPOption interface {\nfmt.Stringer\n// Type returns the type of the receiver.\n- Type() uint8\n+ Type() NDPOptionIdentifier\n// Length returns the length of the body of the receiver, in bytes.\nLength() int\n@@ -386,7 +391,7 @@ func (b NDPOptionsSerializer) Length() int {\ntype NDPSourceLinkLayerAddressOption tcpip.LinkAddress\n// Type implements NDPOption.Type.\n-func (o NDPSourceLinkLayerAddressOption) Type() uint8 {\n+func (o NDPSourceLinkLayerAddressOption) Type() NDPOptionIdentifier {\nreturn NDPSourceLinkLayerAddressOptionType\n}\n@@ -426,7 +431,7 @@ func (o NDPSourceLinkLayerAddressOption) EthernetAddress() tcpip.LinkAddress {\ntype NDPTargetLinkLayerAddressOption tcpip.LinkAddress\n// Type implements NDPOption.Type.\n-func (o NDPTargetLinkLayerAddressOption) Type() uint8 {\n+func (o NDPTargetLinkLayerAddressOption) Type() NDPOptionIdentifier {\nreturn NDPTargetLinkLayerAddressOptionType\n}\n@@ -466,7 +471,7 @@ func (o NDPTargetLinkLayerAddressOption) EthernetAddress() tcpip.LinkAddress {\ntype NDPPrefixInformation []byte\n// Type implements NDPOption.Type.\n-func (o NDPPrefixInformation) Type() uint8 {\n+func (o NDPPrefixInformation) Type() NDPOptionIdentifier {\nreturn NDPPrefixInformationType\n}\n@@ -590,7 +595,7 @@ type NDPRecursiveDNSServer []byte\n// Type returns the type of an NDP Recursive DNS Server option.\n//\n// Type implements NDPOption.Type.\n-func (NDPRecursiveDNSServer) Type() uint8 {\n+func (NDPRecursiveDNSServer) Type() NDPOptionIdentifier {\nreturn NDPRecursiveDNSServerOptionType\n}\n@@ -613,7 +618,12 @@ func (o NDPRecursiveDNSServer) serializeInto(b []byte) int {\n// String implements fmt.Stringer.String.\nfunc (o NDPRecursiveDNSServer) String() string {\n- return fmt.Sprintf(\"%T(%s valid for %s)\", o, o.Addresses(), o.Lifetime())\n+ lt := o.Lifetime()\n+ addrs, err := o.Addresses()\n+ if err != nil {\n+ return fmt.Sprintf(\"%T([] valid for %s; err = %s)\", o, lt, err)\n+ }\n+ return fmt.Sprintf(\"%T(%s valid for %s)\", o, addrs, lt)\n}\n// Lifetime returns the length of time that the DNS server addresses\n@@ -632,29 +642,45 @@ func (o NDPRecursiveDNSServer) Lifetime() time.Duration {\n// Addresses returns the recursive DNS server IPv6 addresses that may be\n// used for name resolution.\n//\n-// Note, some of the addresses returned MAY be link-local addresses.\n+// Note, the addresses MAY be link-local addresses.\n+func (o NDPRecursiveDNSServer) Addresses() ([]tcpip.Address, error) {\n+ var addrs []tcpip.Address\n+ return addrs, o.iterAddresses(func(addr tcpip.Address) { addrs = append(addrs, addr) })\n+}\n+\n+// checkAddresses iterates over the addresses in an NDP Recursive DNS Server\n+// option and returns any error it encounters.\n+func (o NDPRecursiveDNSServer) checkAddresses() error {\n+ return o.iterAddresses(nil)\n+}\n+\n+// iterAddresses iterates over the addresses in an NDP Recursive DNS Server\n+// option and calls a function with each valid unicast IPv6 address.\n//\n-// Addresses may panic if o does not hold valid IPv6 addresses.\n-func (o NDPRecursiveDNSServer) Addresses() []tcpip.Address {\n- l := len(o)\n- if l < ndpRecursiveDNSServerAddressesOffset {\n- return nil\n+// Note, the addresses MAY be link-local addresses.\n+func (o NDPRecursiveDNSServer) iterAddresses(fn func(tcpip.Address)) error {\n+ if l := len(o); l < minNDPRecursiveDNSServerBodySize {\n+ return fmt.Errorf(\"got %d bytes for NDP Recursive DNS Server option's body, expected at least %d bytes: %w\", l, minNDPRecursiveDNSServerBodySize, io.ErrUnexpectedEOF)\n}\n- l -= ndpRecursiveDNSServerAddressesOffset\n+ o = o[ndpRecursiveDNSServerAddressesOffset:]\n+ l := len(o)\nif l%IPv6AddressSize != 0 {\n- return nil\n+ return fmt.Errorf(\"NDP Recursive DNS Server option's body ends in the middle of an IPv6 address (addresses body size = %d bytes): %w\", l, ErrNDPOptMalformedBody)\n}\n- buf := o[ndpRecursiveDNSServerAddressesOffset:]\n- var addrs []tcpip.Address\n- for len(buf) > 0 {\n- addr := tcpip.Address(buf[:IPv6AddressSize])\n+ for i := 0; len(o) != 0; i++ {\n+ addr := tcpip.Address(o[:IPv6AddressSize])\nif !IsV6UnicastAddress(addr) {\n- return nil\n+ return fmt.Errorf(\"%d-th address (%s) in NDP Recursive DNS Server option is not a valid unicast IPv6 address: %w\", i, addr, ErrNDPOptMalformedBody)\n+ }\n+\n+ if fn != nil {\n+ fn(addr)\n}\n- addrs = append(addrs, addr)\n- buf = buf[IPv6AddressSize:]\n+\n+ o = o[IPv6AddressSize:]\n}\n- return addrs\n+\n+ return nil\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/header/ndp_test.go", "new_path": "pkg/tcpip/header/ndp_test.go", "diff": "@@ -16,6 +16,8 @@ package header\nimport (\n\"bytes\"\n+ \"errors\"\n+ \"io\"\n\"testing\"\n\"time\"\n@@ -543,8 +545,12 @@ func TestNDPRecursiveDNSServerOptionSerialize(t *testing.T) {\nwant := []tcpip.Address{\n\"\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c\\x0d\\x0e\\x0f\",\n}\n- if got := opt.Addresses(); !cmp.Equal(got, want) {\n- t.Errorf(\"got Addresses = %v, want = %v\", got, want)\n+ addrs, err := opt.Addresses()\n+ if err != nil {\n+ t.Errorf(\"opt.Addresses() = %s\", err)\n+ }\n+ if diff := cmp.Diff(addrs, want); diff != \"\" {\n+ t.Errorf(\"mismatched addresses (-want +got):\\n%s\", diff)\n}\n// Iterator should not return anything else.\n@@ -638,8 +644,12 @@ func TestNDPRecursiveDNSServerOption(t *testing.T) {\nif got := opt.Lifetime(); got != test.lifetime {\nt.Errorf(\"got Lifetime = %d, want = %d\", got, test.lifetime)\n}\n- if got := opt.Addresses(); !cmp.Equal(got, test.addrs) {\n- t.Errorf(\"got Addresses = %v, want = %v\", got, test.addrs)\n+ addrs, err := opt.Addresses()\n+ if err != nil {\n+ t.Errorf(\"opt.Addresses() = %s\", err)\n+ }\n+ if diff := cmp.Diff(addrs, test.addrs); diff != \"\" {\n+ t.Errorf(\"mismatched addresses (-want +got):\\n%s\", diff)\n}\n// Iterator should not return anything else.\n@@ -663,36 +673,36 @@ func TestNDPOptionsIterCheck(t *testing.T) {\ntests := []struct {\nname string\nbuf []byte\n- expected error\n+ expectedErr error\n}{\n{\n- \"ZeroLengthField\",\n- []byte{0, 0, 0, 0, 0, 0, 0, 0},\n- ErrNDPOptZeroLength,\n+ name: \"ZeroLengthField\",\n+ buf: []byte{0, 0, 0, 0, 0, 0, 0, 0},\n+ expectedErr: ErrNDPOptMalformedHeader,\n},\n{\n- \"ValidSourceLinkLayerAddressOption\",\n- []byte{1, 1, 1, 2, 3, 4, 5, 6},\n- nil,\n+ name: \"ValidSourceLinkLayerAddressOption\",\n+ buf: []byte{1, 1, 1, 2, 3, 4, 5, 6},\n+ expectedErr: nil,\n},\n{\n- \"TooSmallSourceLinkLayerAddressOption\",\n- []byte{1, 1, 1, 2, 3, 4, 5},\n- ErrNDPOptBufExhausted,\n+ name: \"TooSmallSourceLinkLayerAddressOption\",\n+ buf: []byte{1, 1, 1, 2, 3, 4, 5},\n+ expectedErr: io.ErrUnexpectedEOF,\n},\n{\n- \"ValidTargetLinkLayerAddressOption\",\n- []byte{2, 1, 1, 2, 3, 4, 5, 6},\n- nil,\n+ name: \"ValidTargetLinkLayerAddressOption\",\n+ buf: []byte{2, 1, 1, 2, 3, 4, 5, 6},\n+ expectedErr: nil,\n},\n{\n- \"TooSmallTargetLinkLayerAddressOption\",\n- []byte{2, 1, 1, 2, 3, 4, 5},\n- ErrNDPOptBufExhausted,\n+ name: \"TooSmallTargetLinkLayerAddressOption\",\n+ buf: []byte{2, 1, 1, 2, 3, 4, 5},\n+ expectedErr: io.ErrUnexpectedEOF,\n},\n{\n- \"ValidPrefixInformation\",\n- []byte{\n+ name: \"ValidPrefixInformation\",\n+ buf: []byte{\n3, 4, 43, 64,\n1, 2, 3, 4,\n5, 6, 7, 8,\n@@ -702,11 +712,11 @@ func TestNDPOptionsIterCheck(t *testing.T) {\n17, 18, 19, 20,\n21, 22, 23, 24,\n},\n- nil,\n+ expectedErr: nil,\n},\n{\n- \"TooSmallPrefixInformation\",\n- []byte{\n+ name: \"TooSmallPrefixInformation\",\n+ buf: []byte{\n3, 4, 43, 64,\n1, 2, 3, 4,\n5, 6, 7, 8,\n@@ -716,11 +726,11 @@ func TestNDPOptionsIterCheck(t *testing.T) {\n17, 18, 19, 20,\n21, 22, 23,\n},\n- ErrNDPOptBufExhausted,\n+ expectedErr: io.ErrUnexpectedEOF,\n},\n{\n- \"InvalidPrefixInformationLength\",\n- []byte{\n+ name: \"InvalidPrefixInformationLength\",\n+ buf: []byte{\n3, 3, 43, 64,\n1, 2, 3, 4,\n5, 6, 7, 8,\n@@ -728,11 +738,11 @@ func TestNDPOptionsIterCheck(t *testing.T) {\n9, 10, 11, 12,\n13, 14, 15, 16,\n},\n- ErrNDPOptMalformedBody,\n+ expectedErr: ErrNDPOptMalformedBody,\n},\n{\n- \"ValidSourceAndTargetLinkLayerAddressWithPrefixInformation\",\n- []byte{\n+ name: \"ValidSourceAndTargetLinkLayerAddressWithPrefixInformation\",\n+ buf: []byte{\n// Source Link-Layer Address.\n1, 1, 1, 2, 3, 4, 5, 6,\n@@ -749,11 +759,11 @@ func TestNDPOptionsIterCheck(t *testing.T) {\n17, 18, 19, 20,\n21, 22, 23, 24,\n},\n- nil,\n+ expectedErr: nil,\n},\n{\n- \"ValidSourceAndTargetLinkLayerAddressWithPrefixInformationWithUnrecognized\",\n- []byte{\n+ name: \"ValidSourceAndTargetLinkLayerAddressWithPrefixInformationWithUnrecognized\",\n+ buf: []byte{\n// Source Link-Layer Address.\n1, 1, 1, 2, 3, 4, 5, 6,\n@@ -775,52 +785,52 @@ func TestNDPOptionsIterCheck(t *testing.T) {\n17, 18, 19, 20,\n21, 22, 23, 24,\n},\n- nil,\n+ expectedErr: nil,\n},\n{\n- \"InvalidRecursiveDNSServerCutsOffAddress\",\n- []byte{\n+ name: \"InvalidRecursiveDNSServerCutsOffAddress\",\n+ buf: []byte{\n25, 4, 0, 0,\n0, 0, 0, 0,\n0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,\n0, 1, 2, 3, 4, 5, 6, 7,\n},\n- ErrNDPOptMalformedBody,\n+ expectedErr: ErrNDPOptMalformedBody,\n},\n{\n- \"InvalidRecursiveDNSServerInvalidLengthField\",\n- []byte{\n+ name: \"InvalidRecursiveDNSServerInvalidLengthField\",\n+ buf: []byte{\n25, 2, 0, 0,\n0, 0, 0, 0,\n0, 1, 2, 3, 4, 5, 6, 7, 8,\n},\n- ErrNDPInvalidLength,\n+ expectedErr: io.ErrUnexpectedEOF,\n},\n{\n- \"RecursiveDNSServerTooSmall\",\n- []byte{\n+ name: \"RecursiveDNSServerTooSmall\",\n+ buf: []byte{\n25, 1, 0, 0,\n0, 0, 0,\n},\n- ErrNDPOptBufExhausted,\n+ expectedErr: io.ErrUnexpectedEOF,\n},\n{\n- \"RecursiveDNSServerMulticast\",\n- []byte{\n+ name: \"RecursiveDNSServerMulticast\",\n+ buf: []byte{\n25, 3, 0, 0,\n0, 0, 0, 0,\n255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,\n},\n- ErrNDPOptMalformedBody,\n+ expectedErr: ErrNDPOptMalformedBody,\n},\n{\n- \"RecursiveDNSServerUnspecified\",\n- []byte{\n+ name: \"RecursiveDNSServerUnspecified\",\n+ buf: []byte{\n25, 3, 0, 0,\n0, 0, 0, 0,\n0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n},\n- ErrNDPOptMalformedBody,\n+ expectedErr: ErrNDPOptMalformedBody,\n},\n}\n@@ -828,8 +838,8 @@ func TestNDPOptionsIterCheck(t *testing.T) {\nt.Run(test.name, func(t *testing.T) {\nopts := NDPOptions(test.buf)\n- if _, err := opts.Iter(true); err != test.expected {\n- t.Fatalf(\"got Iter(true) = (_, %v), want = (_, %v)\", err, test.expected)\n+ if _, err := opts.Iter(true); !errors.Is(err, test.expectedErr) {\n+ t.Fatalf(\"got Iter(true) = (_, %v), want = (_, %v)\", err, test.expectedErr)\n}\n// test.buf may be malformed but we chose not to check\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/tcpip/header/ndpoptionidentifier_string.go", "diff": "+// Copyright 2020 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+// Code generated by \"stringer -type NDPOptionIdentifier .\"; DO NOT EDIT.\n+\n+package header\n+\n+import \"strconv\"\n+\n+func _() {\n+ // An \"invalid array index\" compiler error signifies that the constant values have changed.\n+ // Re-run the stringer command to generate them again.\n+ var x [1]struct{}\n+ _ = x[NDPSourceLinkLayerAddressOptionType-1]\n+ _ = x[NDPTargetLinkLayerAddressOptionType-2]\n+ _ = x[NDPPrefixInformationType-3]\n+ _ = x[NDPRecursiveDNSServerOptionType-25]\n+}\n+\n+const (\n+ _NDPOptionIdentifier_name_0 = \"NDPSourceLinkLayerAddressOptionTypeNDPTargetLinkLayerAddressOptionTypeNDPPrefixInformationType\"\n+ _NDPOptionIdentifier_name_1 = \"NDPRecursiveDNSServerOptionType\"\n+)\n+\n+var (\n+ _NDPOptionIdentifier_index_0 = [...]uint8{0, 35, 70, 94}\n+)\n+\n+func (i NDPOptionIdentifier) String() string {\n+ switch {\n+ case 1 <= i && i <= 3:\n+ i -= 1\n+ return _NDPOptionIdentifier_name_0[_NDPOptionIdentifier_index_0[i]:_NDPOptionIdentifier_index_0[i+1]]\n+ case i == 25:\n+ return _NDPOptionIdentifier_name_1\n+ default:\n+ return \"NDPOptionIdentifier(\" + strconv.FormatInt(int64(i), 10) + \")\"\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/ndp.go", "new_path": "pkg/tcpip/stack/ndp.go", "diff": "@@ -711,7 +711,8 @@ func (ndp *ndpState) handleRA(ip tcpip.Address, ra header.NDPRouterAdvert) {\ncontinue\n}\n- ndp.nic.stack.ndpDisp.OnRecursiveDNSServerOption(ndp.nic.ID(), opt.Addresses(), opt.Lifetime())\n+ addrs, _ := opt.Addresses()\n+ ndp.nic.stack.ndpDisp.OnRecursiveDNSServerOption(ndp.nic.ID(), addrs, opt.Lifetime())\ncase header.NDPPrefixInformation:\nprefix := opt.Subnet()\n" } ]
Go
Apache License 2.0
google/gvisor
Return detailed errors when iterating NDP options Test: header_test.TestNDPOptionsIterCheck PiperOrigin-RevId: 306953867
260,023
16.04.2020 17:57:06
25,200
3b05f576d73be644daa17203d9ed64481c45b4a8
Reset pending connections on listener shutdown. When the listening socket is read shutdown, we need to reset all pending and incoming connections. Ensure that the endpoint is not cleaned up from the demuxer and subsequent bind to same port does not go through.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/accept.go", "new_path": "pkg/tcpip/transport/tcp/accept.go", "diff": "@@ -26,7 +26,6 @@ import (\n\"gvisor.dev/gvisor/pkg/sleep\"\n\"gvisor.dev/gvisor/pkg/sync\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n- \"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n\"gvisor.dev/gvisor/pkg/tcpip/seqnum\"\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n@@ -433,19 +432,16 @@ func (e *endpoint) acceptQueueIsFull() bool {\n// handleListenSegment is called when a listening endpoint receives a segment\n// and needs to handle it.\nfunc (e *endpoint) handleListenSegment(ctx *listenContext, s *segment) {\n- if s.flagsAreSet(header.TCPFlagSyn | header.TCPFlagAck) {\n+ e.rcvListMu.Lock()\n+ rcvClosed := e.rcvClosed\n+ e.rcvListMu.Unlock()\n+ if rcvClosed || s.flagsAreSet(header.TCPFlagSyn|header.TCPFlagAck) {\n+ // If the endpoint is shutdown, reply with reset.\n+ //\n// RFC 793 section 3.4 page 35 (figure 12) outlines that a RST\n// must be sent in response to a SYN-ACK while in the listen\n// state to prevent completing a handshake from an old SYN.\n- e.sendTCP(&s.route, tcpFields{\n- id: s.id,\n- ttl: e.ttl,\n- tos: e.sendTOS,\n- flags: header.TCPFlagRst,\n- seq: s.ackNumber,\n- ack: 0,\n- rcvWnd: 0,\n- }, buffer.VectorisedView{}, nil)\n+ replyWithReset(s, e.sendTOS, e.ttl)\nreturn\n}\n@@ -534,7 +530,7 @@ func (e *endpoint) handleListenSegment(ctx *listenContext, s *segment) {\n// The only time we should reach here when a connection\n// was opened and closed really quickly and a delayed\n// ACK was received from the sender.\n- replyWithReset(s)\n+ replyWithReset(s, e.sendTOS, e.ttl)\nreturn\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/connect.go", "new_path": "pkg/tcpip/transport/tcp/connect.go", "diff": "@@ -1053,10 +1053,15 @@ func (e *endpoint) tryDeliverSegmentFromClosedEndpoint(s *segment) {\nep = e.stack.FindTransportEndpoint(header.IPv4ProtocolNumber, e.TransProto, e.ID, &s.route)\n}\nif ep == nil {\n- replyWithReset(s)\n+ replyWithReset(s, stack.DefaultTOS, s.route.DefaultTTL())\ns.decRef()\nreturn\n}\n+\n+ if e == ep {\n+ panic(\"current endpoint not removed from demuxer, enqueing segments to itself\")\n+ }\n+\nif ep.(*endpoint).enqueueSegment(s) {\nep.(*endpoint).newSegmentWaker.Assert()\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/endpoint.go", "new_path": "pkg/tcpip/transport/tcp/endpoint.go", "diff": "@@ -2101,7 +2101,7 @@ func (e *endpoint) shutdownLocked(flags tcpip.ShutdownFlags) *tcpip.Error {\nswitch {\ncase e.EndpointState().connected():\n// Close for read.\n- if (e.shutdownFlags & tcpip.ShutdownRead) != 0 {\n+ if e.shutdownFlags&tcpip.ShutdownRead != 0 {\n// Mark read side as closed.\ne.rcvListMu.Lock()\ne.rcvClosed = true\n@@ -2110,7 +2110,7 @@ func (e *endpoint) shutdownLocked(flags tcpip.ShutdownFlags) *tcpip.Error {\n// If we're fully closed and we have unread data we need to abort\n// the connection with a RST.\n- if (e.shutdownFlags&tcpip.ShutdownWrite) != 0 && rcvBufUsed > 0 {\n+ if e.shutdownFlags&tcpip.ShutdownWrite != 0 && rcvBufUsed > 0 {\ne.resetConnectionLocked(tcpip.ErrConnectionAborted)\n// Wake up worker to terminate loop.\ne.notifyProtocolGoroutine(notifyTickleWorker)\n@@ -2119,7 +2119,7 @@ func (e *endpoint) shutdownLocked(flags tcpip.ShutdownFlags) *tcpip.Error {\n}\n// Close for write.\n- if (e.shutdownFlags & tcpip.ShutdownWrite) != 0 {\n+ if e.shutdownFlags&tcpip.ShutdownWrite != 0 {\ne.sndBufMu.Lock()\nif e.sndClosed {\n// Already closed.\n@@ -2142,12 +2142,23 @@ func (e *endpoint) shutdownLocked(flags tcpip.ShutdownFlags) *tcpip.Error {\nreturn nil\ncase e.EndpointState() == StateListen:\n- // Tell protocolListenLoop to stop.\n- if flags&tcpip.ShutdownRead != 0 {\n- e.notifyProtocolGoroutine(notifyClose)\n+ if e.shutdownFlags&tcpip.ShutdownRead != 0 {\n+ // Reset all connections from the accept queue and keep the\n+ // worker running so that it can continue handling incoming\n+ // segments by replying with RST.\n+ //\n+ // By not removing this endpoint from the demuxer mapping, we\n+ // ensure that any other bind to the same port fails, as on Linux.\n+ // TODO(gvisor.dev/issue/2468): We need to enable applications to\n+ // start listening on this endpoint again similar to Linux.\n+ e.rcvListMu.Lock()\n+ e.rcvClosed = true\n+ e.rcvListMu.Unlock()\n+ e.closePendingAcceptableConnectionsLocked()\n+ // Notify waiters that the endpoint is shutdown.\n+ e.waiterQueue.Notify(waiter.EventIn | waiter.EventOut | waiter.EventHUp | waiter.EventErr)\n}\nreturn nil\n-\ndefault:\nreturn tcpip.ErrNotConnected\n}\n@@ -2251,8 +2262,11 @@ func (e *endpoint) Accept() (tcpip.Endpoint, *waiter.Queue, *tcpip.Error) {\ne.LockUser()\ndefer e.UnlockUser()\n+ e.rcvListMu.Lock()\n+ rcvClosed := e.rcvClosed\n+ e.rcvListMu.Unlock()\n// Endpoint must be in listen state before it can accept connections.\n- if e.EndpointState() != StateListen {\n+ if rcvClosed || e.EndpointState() != StateListen {\nreturn nil, nil, tcpip.ErrInvalidEndpointState\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/forwarder.go", "new_path": "pkg/tcpip/transport/tcp/forwarder.go", "diff": "@@ -130,7 +130,7 @@ func (r *ForwarderRequest) Complete(sendReset bool) {\n// If the caller requested, send a reset.\nif sendReset {\n- replyWithReset(r.segment)\n+ replyWithReset(r.segment, stack.DefaultTOS, r.segment.route.DefaultTTL())\n}\n// Release all resources.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/protocol.go", "new_path": "pkg/tcpip/transport/tcp/protocol.go", "diff": "@@ -223,12 +223,12 @@ func (*protocol) HandleUnknownDestinationPacket(r *stack.Route, id stack.Transpo\nreturn true\n}\n- replyWithReset(s)\n+ replyWithReset(s, stack.DefaultTOS, s.route.DefaultTTL())\nreturn true\n}\n// replyWithReset replies to the given segment with a reset segment.\n-func replyWithReset(s *segment) {\n+func replyWithReset(s *segment, tos, ttl uint8) {\n// Get the seqnum from the packet if the ack flag is set.\nseq := seqnum.Value(0)\nack := seqnum.Value(0)\n@@ -252,8 +252,8 @@ func replyWithReset(s *segment) {\n}\nsendTCP(&s.route, tcpFields{\nid: s.id,\n- ttl: s.route.DefaultTTL(),\n- tos: stack.DefaultTOS,\n+ ttl: ttl,\n+ tos: tos,\nflags: flags,\nseq: seq,\nack: ack,\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/tcp_test.go", "new_path": "pkg/tcpip/transport/tcp/tcp_test.go", "diff": "@@ -1034,8 +1034,8 @@ func TestSendRstOnListenerRxAckV6(t *testing.T) {\nchecker.SeqNum(200)))\n}\n-// TestListenShutdown tests for the listening endpoint not processing\n-// any receive when it is on read shutdown.\n+// TestListenShutdown tests for the listening endpoint replying with RST\n+// on read shutdown.\nfunc TestListenShutdown(t *testing.T) {\nc := context.New(t, defaultMTU)\ndefer c.Cleanup()\n@@ -1046,7 +1046,7 @@ func TestListenShutdown(t *testing.T) {\nt.Fatal(\"Bind failed:\", err)\n}\n- if err := c.EP.Listen(10 /* backlog */); err != nil {\n+ if err := c.EP.Listen(1 /* backlog */); err != nil {\nt.Fatal(\"Listen failed:\", err)\n}\n@@ -1054,9 +1054,6 @@ func TestListenShutdown(t *testing.T) {\nt.Fatal(\"Shutdown failed:\", err)\n}\n- // Wait for the endpoint state to be propagated.\n- time.Sleep(10 * time.Millisecond)\n-\nc.SendPacket(nil, &context.Headers{\nSrcPort: context.TestPort,\nDstPort: context.StackPort,\n@@ -1065,7 +1062,12 @@ func TestListenShutdown(t *testing.T) {\nAckNum: 200,\n})\n- c.CheckNoPacket(\"Packet received when listening socket was shutdown\")\n+ // Expect the listening endpoint to reset the connection.\n+ checker.IPv4(t, c.GetPacket(),\n+ checker.TCP(\n+ checker.DstPort(context.TestPort),\n+ checker.TCPFlags(header.TCPFlagAck|header.TCPFlagRst),\n+ ))\n}\n// TestListenCloseWhileConnect tests for the listening endpoint to\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_inet_loopback.cc", "new_path": "test/syscalls/linux/socket_inet_loopback.cc", "diff": "@@ -319,6 +319,75 @@ TEST_P(SocketInetLoopbackTest, TCPListenUnbound) {\ntcpSimpleConnectTest(listener, connector, false);\n}\n+TEST_P(SocketInetLoopbackTest, TCPListenShutdown) {\n+ auto const& param = GetParam();\n+\n+ TestAddress const& listener = param.listener;\n+ TestAddress const& connector = param.connector;\n+\n+ constexpr int kBacklog = 2;\n+ constexpr int kFDs = kBacklog + 1;\n+\n+ // Create the listening socket.\n+ FileDescriptor listen_fd = ASSERT_NO_ERRNO_AND_VALUE(\n+ Socket(listener.family(), SOCK_STREAM, IPPROTO_TCP));\n+ sockaddr_storage listen_addr = listener.addr;\n+ ASSERT_THAT(bind(listen_fd.get(), reinterpret_cast<sockaddr*>(&listen_addr),\n+ listener.addr_len),\n+ SyscallSucceeds());\n+ ASSERT_THAT(listen(listen_fd.get(), kBacklog), SyscallSucceeds());\n+\n+ // Get the port bound by the listening socket.\n+ socklen_t addrlen = listener.addr_len;\n+ ASSERT_THAT(getsockname(listen_fd.get(),\n+ reinterpret_cast<sockaddr*>(&listen_addr), &addrlen),\n+ SyscallSucceeds());\n+ uint16_t const port =\n+ ASSERT_NO_ERRNO_AND_VALUE(AddrPort(listener.family(), listen_addr));\n+\n+ sockaddr_storage conn_addr = connector.addr;\n+ ASSERT_NO_ERRNO(SetAddrPort(connector.family(), &conn_addr, port));\n+\n+ // Shutdown the write of the listener, expect to not have any effect.\n+ ASSERT_THAT(shutdown(listen_fd.get(), SHUT_WR), SyscallSucceeds());\n+\n+ for (int i = 0; i < kFDs; i++) {\n+ auto client = ASSERT_NO_ERRNO_AND_VALUE(\n+ Socket(connector.family(), SOCK_STREAM, IPPROTO_TCP));\n+ ASSERT_THAT(connect(client.get(), reinterpret_cast<sockaddr*>(&conn_addr),\n+ connector.addr_len),\n+ SyscallSucceeds());\n+ ASSERT_THAT(accept(listen_fd.get(), nullptr, nullptr), SyscallSucceeds());\n+ }\n+\n+ // Shutdown the read of the listener, expect to fail subsequent\n+ // server accepts, binds and client connects.\n+ ASSERT_THAT(shutdown(listen_fd.get(), SHUT_RD), SyscallSucceeds());\n+\n+ ASSERT_THAT(accept(listen_fd.get(), nullptr, nullptr),\n+ SyscallFailsWithErrno(EINVAL));\n+\n+ // Check that shutdown did not release the port.\n+ FileDescriptor new_listen_fd = ASSERT_NO_ERRNO_AND_VALUE(\n+ Socket(listener.family(), SOCK_STREAM, IPPROTO_TCP));\n+ ASSERT_THAT(\n+ bind(new_listen_fd.get(), reinterpret_cast<sockaddr*>(&listen_addr),\n+ listener.addr_len),\n+ SyscallFailsWithErrno(EADDRINUSE));\n+\n+ // Check that subsequent connection attempts receive a RST.\n+ auto client = ASSERT_NO_ERRNO_AND_VALUE(\n+ Socket(connector.family(), SOCK_STREAM, IPPROTO_TCP));\n+\n+ for (int i = 0; i < kFDs; i++) {\n+ auto client = ASSERT_NO_ERRNO_AND_VALUE(\n+ Socket(connector.family(), SOCK_STREAM, IPPROTO_TCP));\n+ ASSERT_THAT(connect(client.get(), reinterpret_cast<sockaddr*>(&conn_addr),\n+ connector.addr_len),\n+ SyscallFailsWithErrno(ECONNREFUSED));\n+ }\n+}\n+\nTEST_P(SocketInetLoopbackTest, TCPListenClose) {\nauto const& param = GetParam();\n@@ -365,9 +434,8 @@ TEST_P(SocketInetLoopbackTest, TCPListenClose) {\n}\n}\n-TEST_P(SocketInetLoopbackTest, TCPListenCloseWhileConnect) {\n- auto const& param = GetParam();\n-\n+void TestListenWhileConnect(const TestParam& param,\n+ void (*stopListen)(FileDescriptor&)) {\nTestAddress const& listener = param.listener;\nTestAddress const& connector = param.connector;\n@@ -404,8 +472,8 @@ TEST_P(SocketInetLoopbackTest, TCPListenCloseWhileConnect) {\nclients.push_back(std::move(client));\n}\n}\n- // Close the listening socket.\n- listen_fd.reset();\n+\n+ stopListen(listen_fd);\nfor (auto& client : clients) {\nconst int kTimeout = 10000;\n@@ -420,13 +488,26 @@ TEST_P(SocketInetLoopbackTest, TCPListenCloseWhileConnect) {\nchar c;\n// Subsequent read can fail with:\n// ECONNRESET: If the client connection was established and was reset by the\n- // remote. ECONNREFUSED: If the client connection failed to be established.\n+ // remote.\n+ // ECONNREFUSED: If the client connection failed to be established.\nASSERT_THAT(read(client.get(), &c, sizeof(c)),\nAnyOf(SyscallFailsWithErrno(ECONNRESET),\nSyscallFailsWithErrno(ECONNREFUSED)));\n}\n}\n+TEST_P(SocketInetLoopbackTest, TCPListenCloseWhileConnect) {\n+ TestListenWhileConnect(GetParam(), [](FileDescriptor& f) {\n+ ASSERT_THAT(close(f.release()), SyscallSucceeds());\n+ });\n+}\n+\n+TEST_P(SocketInetLoopbackTest, TCPListenShutdownWhileConnect) {\n+ TestListenWhileConnect(GetParam(), [](FileDescriptor& f) {\n+ ASSERT_THAT(shutdown(f.get(), SHUT_RD), SyscallSucceeds());\n+ });\n+}\n+\nTEST_P(SocketInetLoopbackTest, TCPbacklog) {\nauto const& param = GetParam();\n@@ -1134,6 +1215,7 @@ TEST_P(SocketInetReusePortTest, TcpPortReuseMultiThread_NoRandomSave) {\nif (connects_received >= kConnectAttempts) {\n// Another thread have shutdown our read side causing the\n// accept to fail.\n+ ASSERT_EQ(errno, EINVAL);\nbreak;\n}\nASSERT_NO_ERRNO(fd);\n" } ]
Go
Apache License 2.0
google/gvisor
Reset pending connections on listener shutdown. When the listening socket is read shutdown, we need to reset all pending and incoming connections. Ensure that the endpoint is not cleaned up from the demuxer and subsequent bind to same port does not go through. PiperOrigin-RevId: 306958038
260,004
16.04.2020 18:32:15
25,200
f367cf8e67818b0ca3be6fb15b8be481635c2575
Drop invalid NDP NA messages Better validate NDP NAs options before updating the link address cache. Test: stack_test.TestNeighorAdvertisementWithTargetLinkLayerOption
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/icmp.go", "new_path": "pkg/tcpip/network/ipv6/icmp.go", "diff": "@@ -301,40 +301,38 @@ func (e *endpoint) handleICMP(r *stack.Route, netHeader buffer.View, pkt stack.P\ntargetAddr := na.TargetAddress()\nstack := r.Stack()\n- rxNICID := r.NICID()\n- if isTentative, err := stack.IsAddrTentative(rxNICID, targetAddr); err != nil {\n- // We will only get an error if rxNICID is unrecognized,\n- // which should not happen. For now short-circuit this\n- // packet.\n+ if isTentative, err := stack.IsAddrTentative(e.nicID, targetAddr); err != nil {\n+ // We will only get an error if the NIC is unrecognized, which should not\n+ // happen. For now short-circuit this packet.\n//\n// TODO(b/141002840): Handle this better?\nreturn\n} else if isTentative {\n- // We just got an NA from a node that owns an address we\n- // are performing DAD on, implying the address is not\n- // unique. In this case we let the stack know so it can\n- // handle such a scenario and do nothing furthur with\n+ // We just got an NA from a node that owns an address we are performing\n+ // DAD on, implying the address is not unique. In this case we let the\n+ // stack know so it can handle such a scenario and do nothing furthur with\n// the NDP NA.\n- stack.DupTentativeAddrDetected(rxNICID, targetAddr)\n+ stack.DupTentativeAddrDetected(e.nicID, targetAddr)\nreturn\n}\n- // At this point we know that the targetAddress is not tentative\n- // on rxNICID. However, targetAddr may still be assigned to\n- // rxNICID but not tentative (it could be permanent). Such a\n- // scenario is beyond the scope of RFC 4862. As such, we simply\n- // ignore such a scenario for now and proceed as normal.\n+ // At this point we know that the target address is not tentative on the\n+ // NIC. However, the target address may still be assigned to the NIC but not\n+ // tentative (it could be permanent). Such a scenario is beyond the scope of\n+ // RFC 4862. As such, we simply ignore such a scenario for now and proceed\n+ // as normal.\n//\n+ // TODO(b/143147598): Handle the scenario described above. Also inform the\n+ // netstack integration that a duplicate address was detected outside of\n+ // DAD.\n+\n// If the NA message has the target link layer option, update the link\n// address cache with the link address for the target of the message.\n//\n- // TODO(b/143147598): Handle the scenario described above. Also\n- // inform the netstack integration that a duplicate address was\n- // detected outside of DAD.\n- //\n// TODO(b/148429853): Properly process the NA message and do Neighbor\n// Unreachability Detection.\n+ var targetLinkAddr tcpip.LinkAddress\nfor {\nopt, done, err := it.Next()\nif err != nil {\n@@ -347,8 +345,20 @@ func (e *endpoint) handleICMP(r *stack.Route, netHeader buffer.View, pkt stack.P\nswitch opt := opt.(type) {\ncase header.NDPTargetLinkLayerAddressOption:\n- e.linkAddrCache.AddLinkAddress(e.nicID, targetAddr, opt.EthernetAddress())\n+ // No RFCs define what to do when an NA message has multiple Target\n+ // Link-Layer Address options. Since no interface can have multiple\n+ // link-layer addresses, we consider such messages invalid.\n+ if len(targetLinkAddr) != 0 {\n+ received.Invalid.Increment()\n+ return\n+ }\n+\n+ targetLinkAddr = opt.EthernetAddress()\n+ }\n}\n+\n+ if len(targetLinkAddr) != 0 {\n+ e.linkAddrCache.AddLinkAddress(e.nicID, targetAddr, targetLinkAddr)\n}\ncase header.ICMPv6EchoRequest:\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/ndp_test.go", "new_path": "pkg/tcpip/network/ipv6/ndp_test.go", "diff": "@@ -449,6 +449,13 @@ func TestNeighorAdvertisementWithTargetLinkLayerOption(t *testing.T) {\nname: \"Invalid Length\",\noptsBuf: []byte{2, 2, 2, 3, 4, 5, 6, 7},\n},\n+ {\n+ name: \"Multiple\",\n+ optsBuf: []byte{\n+ 2, 1, 2, 3, 4, 5, 6, 7,\n+ 2, 1, 2, 3, 4, 5, 6, 8,\n+ },\n+ },\n}\nfor _, test := range tests {\n" } ]
Go
Apache License 2.0
google/gvisor
Drop invalid NDP NA messages Better validate NDP NAs options before updating the link address cache. Test: stack_test.TestNeighorAdvertisementWithTargetLinkLayerOption PiperOrigin-RevId: 306962924
259,885
16.04.2020 19:26:02
25,200
f03996c5e9803934226e4b3a10827501cb936ab9
Implement pipe(2) and pipe2(2) for VFS2. Updates
[ { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/fsimpl/pipefs/BUILD", "diff": "+load(\"//tools:defs.bzl\", \"go_library\")\n+\n+licenses([\"notice\"])\n+\n+go_library(\n+ name = \"pipefs\",\n+ srcs = [\"pipefs.go\"],\n+ visibility = [\"//pkg/sentry:internal\"],\n+ deps = [\n+ \"//pkg/abi/linux\",\n+ \"//pkg/context\",\n+ \"//pkg/sentry/fsimpl/kernfs\",\n+ \"//pkg/sentry/kernel/auth\",\n+ \"//pkg/sentry/kernel/pipe\",\n+ \"//pkg/sentry/kernel/time\",\n+ \"//pkg/sentry/vfs\",\n+ \"//pkg/syserror\",\n+ \"//pkg/usermem\",\n+ ],\n+)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/fsimpl/pipefs/pipefs.go", "diff": "+// Copyright 2020 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 pipefs provides the filesystem implementation backing\n+// Kernel.PipeMount.\n+package pipefs\n+\n+import (\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/kernel/auth\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel/pipe\"\n+ ktime \"gvisor.dev/gvisor/pkg/sentry/kernel/time\"\n+ \"gvisor.dev/gvisor/pkg/sentry/vfs\"\n+ \"gvisor.dev/gvisor/pkg/syserror\"\n+ \"gvisor.dev/gvisor/pkg/usermem\"\n+)\n+\n+type filesystemType struct{}\n+\n+// Name implements vfs.FilesystemType.Name.\n+func (filesystemType) Name() string {\n+ return \"pipefs\"\n+}\n+\n+// GetFilesystem implements vfs.FilesystemType.GetFilesystem.\n+func (filesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.VirtualFilesystem, creds *auth.Credentials, source string, opts vfs.GetFilesystemOptions) (*vfs.Filesystem, *vfs.Dentry, error) {\n+ panic(\"pipefs.filesystemType.GetFilesystem should never be called\")\n+}\n+\n+// filesystem implements vfs.FilesystemImpl.\n+type filesystem struct {\n+ kernfs.Filesystem\n+\n+ // TODO(gvisor.dev/issue/1193):\n+ //\n+ // - kernfs does not provide a way to implement statfs, from which we\n+ // should indicate PIPEFS_MAGIC.\n+ //\n+ // - kernfs does not provide a way to override names for\n+ // vfs.FilesystemImpl.PrependPath(); pipefs inodes should use synthetic\n+ // name fmt.Sprintf(\"pipe:[%d]\", inode.ino).\n+}\n+\n+// NewFilesystem sets up and returns a new vfs.Filesystem implemented by\n+// pipefs.\n+func NewFilesystem(vfsObj *vfs.VirtualFilesystem) *vfs.Filesystem {\n+ fs := &filesystem{}\n+ fs.Init(vfsObj, filesystemType{})\n+ return fs.VFSFilesystem()\n+}\n+\n+// inode implements kernfs.Inode.\n+type inode struct {\n+ kernfs.InodeNotDirectory\n+ kernfs.InodeNotSymlink\n+ kernfs.InodeNoopRefCount\n+\n+ pipe *pipe.VFSPipe\n+\n+ ino uint64\n+ uid auth.KUID\n+ gid auth.KGID\n+ // We use the creation timestamp for all of atime, mtime, and ctime.\n+ ctime ktime.Time\n+}\n+\n+func newInode(ctx context.Context, fs *kernfs.Filesystem) *inode {\n+ creds := auth.CredentialsFromContext(ctx)\n+ return &inode{\n+ pipe: pipe.NewVFSPipe(false /* isNamed */, pipe.DefaultPipeSize, usermem.PageSize),\n+ ino: fs.NextIno(),\n+ uid: creds.EffectiveKUID,\n+ gid: creds.EffectiveKGID,\n+ ctime: ktime.NowFromContext(ctx),\n+ }\n+}\n+\n+const pipeMode = 0600 | linux.S_IFIFO\n+\n+// CheckPermissions implements kernfs.Inode.CheckPermissions.\n+func (i *inode) CheckPermissions(ctx context.Context, creds *auth.Credentials, ats vfs.AccessTypes) error {\n+ return vfs.GenericCheckPermissions(creds, ats, pipeMode, i.uid, i.gid)\n+}\n+\n+// Mode implements kernfs.Inode.Mode.\n+func (i *inode) Mode() linux.FileMode {\n+ return pipeMode\n+}\n+\n+// Stat implements kernfs.Inode.Stat.\n+func (i *inode) Stat(vfsfs *vfs.Filesystem, opts vfs.StatOptions) (linux.Statx, error) {\n+ ts := linux.NsecToStatxTimestamp(i.ctime.Nanoseconds())\n+ return linux.Statx{\n+ Mask: linux.STATX_TYPE | linux.STATX_MODE | linux.STATX_NLINK | linux.STATX_UID | linux.STATX_GID | linux.STATX_ATIME | linux.STATX_MTIME | linux.STATX_CTIME | linux.STATX_INO | linux.STATX_SIZE | linux.STATX_BLOCKS,\n+ Blksize: usermem.PageSize,\n+ Nlink: 1,\n+ UID: uint32(i.uid),\n+ GID: uint32(i.gid),\n+ Mode: pipeMode,\n+ Ino: i.ino,\n+ Size: 0,\n+ Blocks: 0,\n+ Atime: ts,\n+ Ctime: ts,\n+ Mtime: ts,\n+ // TODO(gvisor.dev/issue/1197): Device number.\n+ }, nil\n+}\n+\n+// SetStat implements kernfs.Inode.SetStat.\n+func (i *inode) SetStat(ctx context.Context, vfsfs *vfs.Filesystem, creds *auth.Credentials, opts vfs.SetStatOptions) error {\n+ if opts.Stat.Mask == 0 {\n+ return nil\n+ }\n+ return syserror.EPERM\n+}\n+\n+// Open implements kernfs.Inode.Open.\n+func (i *inode) Open(rp *vfs.ResolvingPath, vfsd *vfs.Dentry, opts vfs.OpenOptions) (*vfs.FileDescription, error) {\n+ // FIXME(b/38173783): kernfs does not plumb Context here.\n+ return i.pipe.Open(context.Background(), rp.Mount(), vfsd, opts.Flags)\n+}\n+\n+// NewConnectedPipeFDs returns a pair of FileDescriptions representing the read\n+// and write ends of a newly-created pipe, as for pipe(2) and pipe2(2).\n+//\n+// Preconditions: mnt.Filesystem() must have been returned by NewFilesystem().\n+func NewConnectedPipeFDs(ctx context.Context, mnt *vfs.Mount, flags uint32) (*vfs.FileDescription, *vfs.FileDescription) {\n+ fs := mnt.Filesystem().Impl().(*kernfs.Filesystem)\n+ inode := newInode(ctx, fs)\n+ var d kernfs.Dentry\n+ d.Init(inode)\n+ defer d.DecRef()\n+ return inode.pipe.ReaderWriterPair(mnt, d.VFSDentry(), flags)\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/tmpfs/filesystem.go", "new_path": "pkg/sentry/fsimpl/tmpfs/filesystem.go", "diff": "@@ -392,7 +392,7 @@ func (d *dentry) open(ctx context.Context, rp *vfs.ResolvingPath, opts *vfs.Open\n// Can't open symlinks without O_PATH (which is unimplemented).\nreturn nil, syserror.ELOOP\ncase *namedPipe:\n- return newNamedPipeFD(ctx, impl, rp, &d.vfsd, opts.Flags)\n+ return impl.pipe.Open(ctx, rp.Mount(), &d.vfsd, opts.Flags)\ncase *deviceFile:\nreturn rp.VirtualFilesystem().OpenDeviceSpecialFile(ctx, rp.Mount(), &d.vfsd, impl.kind, impl.major, impl.minor, opts)\ncase *socketFile:\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/tmpfs/named_pipe.go", "new_path": "pkg/sentry/fsimpl/tmpfs/named_pipe.go", "diff": "@@ -16,10 +16,8 @@ package tmpfs\nimport (\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n- \"gvisor.dev/gvisor/pkg/context\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/pipe\"\n- \"gvisor.dev/gvisor/pkg/sentry/vfs\"\n\"gvisor.dev/gvisor/pkg/usermem\"\n)\n@@ -33,27 +31,8 @@ type namedPipe struct {\n// * fs.mu must be locked.\n// * rp.Mount().CheckBeginWrite() has been called successfully.\nfunc (fs *filesystem) newNamedPipe(creds *auth.Credentials, mode linux.FileMode) *inode {\n- file := &namedPipe{pipe: pipe.NewVFSPipe(pipe.DefaultPipeSize, usermem.PageSize)}\n+ file := &namedPipe{pipe: pipe.NewVFSPipe(true /* isNamed */, pipe.DefaultPipeSize, usermem.PageSize)}\nfile.inode.init(file, fs, creds, linux.S_IFIFO|mode)\nfile.inode.nlink = 1 // Only the parent has a link.\nreturn &file.inode\n}\n-\n-// namedPipeFD implements vfs.FileDescriptionImpl. Methods are implemented\n-// entirely via struct embedding.\n-type namedPipeFD struct {\n- fileDescription\n-\n- *pipe.VFSPipeFD\n-}\n-\n-func newNamedPipeFD(ctx context.Context, np *namedPipe, rp *vfs.ResolvingPath, vfsd *vfs.Dentry, flags uint32) (*vfs.FileDescription, error) {\n- var err error\n- var fd namedPipeFD\n- fd.VFSPipeFD, err = np.pipe.NewVFSPipeFD(ctx, vfsd, &fd.vfsfd, flags)\n- if err != nil {\n- return nil, err\n- }\n- fd.vfsfd.Init(&fd, flags, rp.Mount(), vfsd, &vfs.FileDescriptionOptions{})\n- return &fd.vfsfd, nil\n-}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/tmpfs/tmpfs.go", "new_path": "pkg/sentry/fsimpl/tmpfs/tmpfs.go", "diff": "@@ -357,6 +357,7 @@ func (i *inode) setStat(ctx context.Context, creds *auth.Credentials, stat *linu\nreturn err\n}\ni.mu.Lock()\n+ defer i.mu.Unlock()\nvar (\nneedsMtimeBump bool\nneedsCtimeBump bool\n@@ -427,7 +428,6 @@ func (i *inode) setStat(ctx context.Context, creds *auth.Credentials, stat *linu\natomic.StoreInt64(&i.ctime, now)\n}\n- i.mu.Unlock()\nreturn nil\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/BUILD", "new_path": "pkg/sentry/kernel/BUILD", "diff": "@@ -170,6 +170,7 @@ go_library(\n\"//pkg/sentry/fs/timerfd\",\n\"//pkg/sentry/fsbridge\",\n\"//pkg/sentry/fsimpl/kernfs\",\n+ \"//pkg/sentry/fsimpl/pipefs\",\n\"//pkg/sentry/fsimpl/sockfs\",\n\"//pkg/sentry/hostcpu\",\n\"//pkg/sentry/inet\",\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/kernel.go", "new_path": "pkg/sentry/kernel/kernel.go", "diff": "@@ -50,6 +50,7 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/fs\"\n\"gvisor.dev/gvisor/pkg/sentry/fs/timerfd\"\n\"gvisor.dev/gvisor/pkg/sentry/fsbridge\"\n+ \"gvisor.dev/gvisor/pkg/sentry/fsimpl/pipefs\"\n\"gvisor.dev/gvisor/pkg/sentry/fsimpl/sockfs\"\n\"gvisor.dev/gvisor/pkg/sentry/hostcpu\"\n\"gvisor.dev/gvisor/pkg/sentry/inet\"\n@@ -254,6 +255,10 @@ type Kernel struct {\n// VFS keeps the filesystem state used across the kernel.\nvfs vfs.VirtualFilesystem\n+ // pipeMount is the Mount used for pipes created by the pipe() and pipe2()\n+ // syscalls (as opposed to named pipes created by mknod()).\n+ pipeMount *vfs.Mount\n+\n// If set to true, report address space activation waits as if the task is in\n// external wait so that the watchdog doesn't report the task stuck.\nSleepForAddressSpaceActivation bool\n@@ -354,19 +359,29 @@ func (k *Kernel) Init(args InitKernelArgs) error {\nk.monotonicClock = &timekeeperClock{tk: args.Timekeeper, c: sentrytime.Monotonic}\nk.futexes = futex.NewManager()\nk.netlinkPorts = port.New()\n+\nif VFS2Enabled {\nif err := k.vfs.Init(); err != nil {\nreturn fmt.Errorf(\"failed to initialize VFS: %v\", err)\n}\n- fs := sockfs.NewFilesystem(&k.vfs)\n- // NewDisconnectedMount will take an additional reference on fs.\n- defer fs.DecRef()\n- sm, err := k.vfs.NewDisconnectedMount(fs, nil, &vfs.MountOptions{})\n+\n+ pipeFilesystem := pipefs.NewFilesystem(&k.vfs)\n+ defer pipeFilesystem.DecRef()\n+ pipeMount, err := k.vfs.NewDisconnectedMount(pipeFilesystem, nil, &vfs.MountOptions{})\n+ if err != nil {\n+ return fmt.Errorf(\"failed to create pipefs mount: %v\", err)\n+ }\n+ k.pipeMount = pipeMount\n+\n+ socketFilesystem := sockfs.NewFilesystem(&k.vfs)\n+ defer socketFilesystem.DecRef()\n+ socketMount, err := k.vfs.NewDisconnectedMount(socketFilesystem, nil, &vfs.MountOptions{})\nif err != nil {\nreturn fmt.Errorf(\"failed to initialize socket mount: %v\", err)\n}\n- k.socketMount = sm\n+ k.socketMount = socketMount\n}\n+\nreturn nil\n}\n@@ -1613,3 +1628,8 @@ func (k *Kernel) EmitUnimplementedEvent(ctx context.Context) {\nfunc (k *Kernel) VFS() *vfs.VirtualFilesystem {\nreturn &k.vfs\n}\n+\n+// PipeMount returns the pipefs mount.\n+func (k *Kernel) PipeMount() *vfs.Mount {\n+ return k.pipeMount\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/pipe/vfs.go", "new_path": "pkg/sentry/kernel/pipe/vfs.go", "diff": "@@ -49,38 +49,42 @@ type VFSPipe struct {\n}\n// NewVFSPipe returns an initialized VFSPipe.\n-func NewVFSPipe(sizeBytes, atomicIOBytes int64) *VFSPipe {\n+func NewVFSPipe(isNamed bool, sizeBytes, atomicIOBytes int64) *VFSPipe {\nvar vp VFSPipe\n- initPipe(&vp.pipe, true /* isNamed */, sizeBytes, atomicIOBytes)\n+ initPipe(&vp.pipe, isNamed, sizeBytes, atomicIOBytes)\nreturn &vp\n}\n-// NewVFSPipeFD opens a named pipe. Named pipes have special blocking semantics\n-// during open:\n+// ReaderWriterPair returns read-only and write-only FDs for vp.\n//\n-// \"Normally, opening the FIFO blocks until the other end is opened also. A\n-// process can open a FIFO in nonblocking mode. In this case, opening for\n-// read-only will succeed even if no-one has opened on the write side yet,\n-// opening for write-only will fail with ENXIO (no such device or address)\n-// unless the other end has already been opened. Under Linux, opening a FIFO\n-// for read and write will succeed both in blocking and nonblocking mode. POSIX\n-// leaves this behavior undefined. This can be used to open a FIFO for writing\n-// while there are no readers available.\" - fifo(7)\n-func (vp *VFSPipe) NewVFSPipeFD(ctx context.Context, vfsd *vfs.Dentry, vfsfd *vfs.FileDescription, flags uint32) (*VFSPipeFD, error) {\n+// Preconditions: statusFlags should not contain an open access mode.\n+func (vp *VFSPipe) ReaderWriterPair(mnt *vfs.Mount, vfsd *vfs.Dentry, statusFlags uint32) (*vfs.FileDescription, *vfs.FileDescription) {\n+ return vp.newFD(mnt, vfsd, linux.O_RDONLY|statusFlags), vp.newFD(mnt, vfsd, linux.O_WRONLY|statusFlags)\n+}\n+\n+// Open opens the pipe represented by vp.\n+func (vp *VFSPipe) Open(ctx context.Context, mnt *vfs.Mount, vfsd *vfs.Dentry, statusFlags uint32) (*vfs.FileDescription, error) {\nvp.mu.Lock()\ndefer vp.mu.Unlock()\n- readable := vfs.MayReadFileWithOpenFlags(flags)\n- writable := vfs.MayWriteFileWithOpenFlags(flags)\n+ readable := vfs.MayReadFileWithOpenFlags(statusFlags)\n+ writable := vfs.MayWriteFileWithOpenFlags(statusFlags)\nif !readable && !writable {\nreturn nil, syserror.EINVAL\n}\n- vfd, err := vp.open(vfsd, vfsfd, flags)\n- if err != nil {\n- return nil, err\n- }\n+ fd := vp.newFD(mnt, vfsd, statusFlags)\n+ // Named pipes have special blocking semantics during open:\n+ //\n+ // \"Normally, opening the FIFO blocks until the other end is opened also. A\n+ // process can open a FIFO in nonblocking mode. In this case, opening for\n+ // read-only will succeed even if no-one has opened on the write side yet,\n+ // opening for write-only will fail with ENXIO (no such device or address)\n+ // unless the other end has already been opened. Under Linux, opening a\n+ // FIFO for read and write will succeed both in blocking and nonblocking\n+ // mode. POSIX leaves this behavior undefined. This can be used to open a\n+ // FIFO for writing while there are no readers available.\" - fifo(7)\nswitch {\ncase readable && writable:\n// Pipes opened for read-write always succeed without blocking.\n@@ -89,23 +93,26 @@ func (vp *VFSPipe) NewVFSPipeFD(ctx context.Context, vfsd *vfs.Dentry, vfsfd *vf\ncase readable:\nnewHandleLocked(&vp.rWakeup)\n- // If this pipe is being opened as nonblocking and there's no\n+ // If this pipe is being opened as blocking and there's no\n// writer, we have to wait for a writer to open the other end.\n- if flags&linux.O_NONBLOCK == 0 && !vp.pipe.HasWriters() && !waitFor(&vp.mu, &vp.wWakeup, ctx) {\n+ if vp.pipe.isNamed && statusFlags&linux.O_NONBLOCK == 0 && !vp.pipe.HasWriters() && !waitFor(&vp.mu, &vp.wWakeup, ctx) {\n+ fd.DecRef()\nreturn nil, syserror.EINTR\n}\ncase writable:\nnewHandleLocked(&vp.wWakeup)\n- if !vp.pipe.HasReaders() {\n- // Nonblocking, write-only opens fail with ENXIO when\n- // the read side isn't open yet.\n- if flags&linux.O_NONBLOCK != 0 {\n+ if vp.pipe.isNamed && !vp.pipe.HasReaders() {\n+ // Non-blocking, write-only opens fail with ENXIO when the read\n+ // side isn't open yet.\n+ if statusFlags&linux.O_NONBLOCK != 0 {\n+ fd.DecRef()\nreturn nil, syserror.ENXIO\n}\n// Wait for a reader to open the other end.\nif !waitFor(&vp.mu, &vp.rWakeup, ctx) {\n+ fd.DecRef()\nreturn nil, syserror.EINTR\n}\n}\n@@ -114,96 +121,93 @@ func (vp *VFSPipe) NewVFSPipeFD(ctx context.Context, vfsd *vfs.Dentry, vfsfd *vf\npanic(\"invalid pipe flags: must be readable, writable, or both\")\n}\n- return vfd, nil\n+ return fd, nil\n}\n// Preconditions: vp.mu must be held.\n-func (vp *VFSPipe) open(vfsd *vfs.Dentry, vfsfd *vfs.FileDescription, flags uint32) (*VFSPipeFD, error) {\n- var fd VFSPipeFD\n- fd.flags = flags\n- fd.readable = vfs.MayReadFileWithOpenFlags(flags)\n- fd.writable = vfs.MayWriteFileWithOpenFlags(flags)\n- fd.vfsfd = vfsfd\n- fd.pipe = &vp.pipe\n+func (vp *VFSPipe) newFD(mnt *vfs.Mount, vfsd *vfs.Dentry, statusFlags uint32) *vfs.FileDescription {\n+ fd := &VFSPipeFD{\n+ pipe: &vp.pipe,\n+ }\n+ fd.vfsfd.Init(fd, statusFlags, mnt, vfsd, &vfs.FileDescriptionOptions{\n+ DenyPRead: true,\n+ DenyPWrite: true,\n+ UseDentryMetadata: true,\n+ })\nswitch {\n- case fd.readable && fd.writable:\n+ case fd.vfsfd.IsReadable() && fd.vfsfd.IsWritable():\nvp.pipe.rOpen()\nvp.pipe.wOpen()\n- case fd.readable:\n+ case fd.vfsfd.IsReadable():\nvp.pipe.rOpen()\n- case fd.writable:\n+ case fd.vfsfd.IsWritable():\nvp.pipe.wOpen()\ndefault:\npanic(\"invalid pipe flags: must be readable, writable, or both\")\n}\n- return &fd, nil\n+ return &fd.vfsfd\n}\n-// VFSPipeFD implements a subset of vfs.FileDescriptionImpl for pipes. It is\n-// expected that filesystesm will use this in a struct implementing\n-// vfs.FileDescriptionImpl.\n+// VFSPipeFD implements vfs.FileDescriptionImpl for pipes.\ntype VFSPipeFD struct {\n+ vfsfd vfs.FileDescription\n+ vfs.FileDescriptionDefaultImpl\n+ vfs.DentryMetadataFileDescriptionImpl\n+\npipe *Pipe\n- flags uint32\n- readable bool\n- writable bool\n- vfsfd *vfs.FileDescription\n}\n// Release implements vfs.FileDescriptionImpl.Release.\nfunc (fd *VFSPipeFD) Release() {\nvar event waiter.EventMask\n- if fd.readable {\n+ if fd.vfsfd.IsReadable() {\nfd.pipe.rClose()\n- event |= waiter.EventIn\n+ event |= waiter.EventOut\n}\n- if fd.writable {\n+ if fd.vfsfd.IsWritable() {\nfd.pipe.wClose()\n- event |= waiter.EventOut\n+ event |= waiter.EventIn | waiter.EventHUp\n}\nif event == 0 {\npanic(\"invalid pipe flags: must be readable, writable, or both\")\n}\n- if fd.writable {\n- fd.vfsfd.VirtualDentry().Mount().EndWrite()\n+ fd.pipe.Notify(event)\n}\n- fd.pipe.Notify(event)\n+// Readiness implements waiter.Waitable.Readiness.\n+func (fd *VFSPipeFD) Readiness(mask waiter.EventMask) waiter.EventMask {\n+ switch {\n+ case fd.vfsfd.IsReadable() && fd.vfsfd.IsWritable():\n+ return fd.pipe.rwReadiness()\n+ case fd.vfsfd.IsReadable():\n+ return fd.pipe.rReadiness()\n+ case fd.vfsfd.IsWritable():\n+ return fd.pipe.wReadiness()\n+ default:\n+ panic(\"pipe FD is neither readable nor writable\")\n+ }\n}\n-// OnClose implements vfs.FileDescriptionImpl.OnClose.\n-func (fd *VFSPipeFD) OnClose(_ context.Context) error {\n- return nil\n+// EventRegister implements waiter.Waitable.EventRegister.\n+func (fd *VFSPipeFD) EventRegister(e *waiter.Entry, mask waiter.EventMask) {\n+ fd.pipe.EventRegister(e, mask)\n}\n-// PRead implements vfs.FileDescriptionImpl.PRead.\n-func (fd *VFSPipeFD) PRead(_ context.Context, _ usermem.IOSequence, _ int64, _ vfs.ReadOptions) (int64, error) {\n- return 0, syserror.ESPIPE\n+// EventUnregister implements waiter.Waitable.EventUnregister.\n+func (fd *VFSPipeFD) EventUnregister(e *waiter.Entry) {\n+ fd.pipe.EventUnregister(e)\n}\n// Read implements vfs.FileDescriptionImpl.Read.\nfunc (fd *VFSPipeFD) Read(ctx context.Context, dst usermem.IOSequence, _ vfs.ReadOptions) (int64, error) {\n- if !fd.readable {\n- return 0, syserror.EINVAL\n- }\n-\nreturn fd.pipe.Read(ctx, dst)\n}\n-// PWrite implements vfs.FileDescriptionImpl.PWrite.\n-func (fd *VFSPipeFD) PWrite(_ context.Context, _ usermem.IOSequence, _ int64, _ vfs.WriteOptions) (int64, error) {\n- return 0, syserror.ESPIPE\n-}\n-\n// Write implements vfs.FileDescriptionImpl.Write.\nfunc (fd *VFSPipeFD) Write(ctx context.Context, src usermem.IOSequence, _ vfs.WriteOptions) (int64, error) {\n- if !fd.writable {\n- return 0, syserror.EINVAL\n- }\n-\nreturn fd.pipe.Write(ctx, src)\n}\n@@ -211,3 +215,17 @@ func (fd *VFSPipeFD) Write(ctx context.Context, src usermem.IOSequence, _ vfs.Wr\nfunc (fd *VFSPipeFD) Ioctl(ctx context.Context, uio usermem.IO, args arch.SyscallArguments) (uintptr, error) {\nreturn fd.pipe.Ioctl(ctx, uio, args)\n}\n+\n+// PipeSize implements fcntl(F_GETPIPE_SZ).\n+func (fd *VFSPipeFD) PipeSize() int64 {\n+ // Inline Pipe.FifoSize() rather than calling it with nil Context and\n+ // fs.File and ignoring the returned error (which is always nil).\n+ fd.pipe.mu.Lock()\n+ defer fd.pipe.mu.Unlock()\n+ return fd.pipe.max\n+}\n+\n+// SetPipeSize implements fcntl(F_SETPIPE_SZ).\n+func (fd *VFSPipeFD) SetPipeSize(size int64) (int64, error) {\n+ return fd.pipe.SetFifoSize(size)\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/sys_pipe.go", "new_path": "pkg/sentry/syscalls/linux/sys_pipe.go", "diff": "@@ -24,6 +24,8 @@ import (\n\"gvisor.dev/gvisor/pkg/usermem\"\n)\n+// LINT.IfChange\n+\n// pipe2 implements the actual system call with flags.\nfunc pipe2(t *kernel.Task, addr usermem.Addr, flags uint) (uintptr, error) {\nif flags&^(linux.O_NONBLOCK|linux.O_CLOEXEC) != 0 {\n@@ -45,10 +47,12 @@ func pipe2(t *kernel.Task, addr usermem.Addr, flags uint) (uintptr, error) {\n}\nif _, err := t.CopyOut(addr, fds); err != nil {\n- // The files are not closed in this case, the exact semantics\n- // of this error case are not well defined, but they could have\n- // already been observed by user space.\n- return 0, syserror.EFAULT\n+ for _, fd := range fds {\n+ if file, _ := t.FDTable().Remove(fd); file != nil {\n+ file.DecRef()\n+ }\n+ }\n+ return 0, err\n}\nreturn 0, nil\n}\n@@ -69,3 +73,5 @@ func Pipe2(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Syscall\nn, err := pipe2(t, addr, flags)\nreturn n, nil, err\n}\n+\n+// LINT.ThenChange(vfs2/pipe.go)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/vfs2/BUILD", "new_path": "pkg/sentry/syscalls/linux/vfs2/BUILD", "diff": "@@ -18,6 +18,7 @@ go_library(\n\"linux64_override_arm64.go\",\n\"mmap.go\",\n\"path.go\",\n+ \"pipe.go\",\n\"poll.go\",\n\"read_write.go\",\n\"setstat.go\",\n@@ -39,8 +40,10 @@ go_library(\n\"//pkg/gohacks\",\n\"//pkg/sentry/arch\",\n\"//pkg/sentry/fsbridge\",\n+ \"//pkg/sentry/fsimpl/pipefs\",\n\"//pkg/sentry/kernel\",\n\"//pkg/sentry/kernel/auth\",\n+ \"//pkg/sentry/kernel/pipe\",\n\"//pkg/sentry/kernel/time\",\n\"//pkg/sentry/limits\",\n\"//pkg/sentry/loader\",\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/vfs2/fd.go", "new_path": "pkg/sentry/syscalls/linux/vfs2/fd.go", "diff": "@@ -18,6 +18,7 @@ import (\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/sentry/arch\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel/pipe\"\nslinux \"gvisor.dev/gvisor/pkg/sentry/syscalls/linux\"\n\"gvisor.dev/gvisor/pkg/syserror\"\n)\n@@ -140,6 +141,22 @@ func Fcntl(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Syscall\nreturn uintptr(file.StatusFlags()), nil, nil\ncase linux.F_SETFL:\nreturn 0, nil, file.SetStatusFlags(t, t.Credentials(), args[2].Uint())\n+ case linux.F_SETPIPE_SZ:\n+ pipefile, ok := file.Impl().(*pipe.VFSPipeFD)\n+ if !ok {\n+ return 0, nil, syserror.EBADF\n+ }\n+ n, err := pipefile.SetPipeSize(int64(args[2].Int()))\n+ if err != nil {\n+ return 0, nil, err\n+ }\n+ return uintptr(n), nil, nil\n+ case linux.F_GETPIPE_SZ:\n+ pipefile, ok := file.Impl().(*pipe.VFSPipeFD)\n+ if !ok {\n+ return 0, nil, syserror.EBADF\n+ }\n+ return uintptr(pipefile.PipeSize()), nil, nil\ndefault:\n// TODO(gvisor.dev/issue/1623): Everything else is not yet supported.\nreturn 0, nil, syserror.EINVAL\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/vfs2/linux64_override_amd64.go", "new_path": "pkg/sentry/syscalls/linux/vfs2/linux64_override_amd64.go", "diff": "@@ -39,7 +39,7 @@ func Override(table map[uintptr]kernel.Syscall) {\ntable[19] = syscalls.Supported(\"readv\", Readv)\ntable[20] = syscalls.Supported(\"writev\", Writev)\ntable[21] = syscalls.Supported(\"access\", Access)\n- delete(table, 22) // pipe\n+ table[22] = syscalls.Supported(\"pipe\", Pipe)\ntable[23] = syscalls.Supported(\"select\", Select)\ntable[32] = syscalls.Supported(\"dup\", Dup)\ntable[33] = syscalls.Supported(\"dup2\", Dup2)\n@@ -151,7 +151,7 @@ func Override(table map[uintptr]kernel.Syscall) {\ndelete(table, 290) // eventfd2\ntable[291] = syscalls.Supported(\"epoll_create1\", EpollCreate1)\ntable[292] = syscalls.Supported(\"dup3\", Dup3)\n- delete(table, 293) // pipe2\n+ table[293] = syscalls.Supported(\"pipe2\", Pipe2)\ndelete(table, 294) // inotify_init1\ntable[295] = syscalls.Supported(\"preadv\", Preadv)\ntable[296] = syscalls.Supported(\"pwritev\", Pwritev)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/syscalls/linux/vfs2/pipe.go", "diff": "+// Copyright 2020 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 vfs2\n+\n+import (\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/sentry/arch\"\n+ \"gvisor.dev/gvisor/pkg/sentry/fsimpl/pipefs\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel\"\n+ \"gvisor.dev/gvisor/pkg/sentry/vfs\"\n+ \"gvisor.dev/gvisor/pkg/syserror\"\n+ \"gvisor.dev/gvisor/pkg/usermem\"\n+)\n+\n+// Pipe implements Linux syscall pipe(2).\n+func Pipe(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {\n+ addr := args[0].Pointer()\n+ return 0, nil, pipe2(t, addr, 0)\n+}\n+\n+// Pipe2 implements Linux syscall pipe2(2).\n+func Pipe2(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {\n+ addr := args[0].Pointer()\n+ flags := args[1].Int()\n+ return 0, nil, pipe2(t, addr, flags)\n+}\n+\n+func pipe2(t *kernel.Task, addr usermem.Addr, flags int32) error {\n+ if flags&^(linux.O_NONBLOCK|linux.O_CLOEXEC) != 0 {\n+ return syserror.EINVAL\n+ }\n+ r, w := pipefs.NewConnectedPipeFDs(t, t.Kernel().PipeMount(), uint32(flags&linux.O_NONBLOCK))\n+ defer r.DecRef()\n+ defer w.DecRef()\n+\n+ fds, err := t.NewFDsVFS2(0, []*vfs.FileDescription{r, w}, kernel.FDFlags{\n+ CloseOnExec: flags&linux.O_CLOEXEC != 0,\n+ })\n+ if err != nil {\n+ return err\n+ }\n+ if _, err := t.CopyOut(addr, fds); err != nil {\n+ for _, fd := range fds {\n+ if _, file := t.FDTable().Remove(fd); file != nil {\n+ file.DecRef()\n+ }\n+ }\n+ return err\n+ }\n+ return nil\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/vfs2/read_write.go", "new_path": "pkg/sentry/syscalls/linux/vfs2/read_write.go", "diff": "@@ -103,7 +103,7 @@ func read(t *kernel.Task, file *vfs.FileDescription, dst usermem.IOSequence, opt\n// Issue the request and break out if it completes with anything other than\n// \"would block\".\n- n, err := file.Read(t, dst, opts)\n+ n, err = file.Read(t, dst, opts)\ntotal += n\nif err != syserror.ErrWouldBlock {\nbreak\n@@ -248,7 +248,7 @@ func pread(t *kernel.Task, file *vfs.FileDescription, dst usermem.IOSequence, of\n// Issue the request and break out if it completes with anything other than\n// \"would block\".\n- n, err := file.PRead(t, dst, offset+total, opts)\n+ n, err = file.PRead(t, dst, offset+total, opts)\ntotal += n\nif err != syserror.ErrWouldBlock {\nbreak\n@@ -335,7 +335,7 @@ func write(t *kernel.Task, file *vfs.FileDescription, src usermem.IOSequence, op\n// Issue the request and break out if it completes with anything other than\n// \"would block\".\n- n, err := file.Write(t, src, opts)\n+ n, err = file.Write(t, src, opts)\ntotal += n\nif err != syserror.ErrWouldBlock {\nbreak\n@@ -480,7 +480,7 @@ func pwrite(t *kernel.Task, file *vfs.FileDescription, src usermem.IOSequence, o\n// Issue the request and break out if it completes with anything other than\n// \"would block\".\n- n, err := file.PWrite(t, src, offset+total, opts)\n+ n, err = file.PWrite(t, src, offset+total, opts)\ntotal += n\nif err != syserror.ErrWouldBlock {\nbreak\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/vfs.go", "new_path": "pkg/sentry/vfs/vfs.go", "diff": "@@ -335,7 +335,7 @@ func (vfs *VirtualFilesystem) MknodAt(ctx context.Context, creds *auth.Credentia\nrp := vfs.getResolvingPath(creds, pop)\nfor {\nerr := rp.mount.fs.impl.MknodAt(ctx, rp, *opts)\n- if err != nil {\n+ if err == nil {\nvfs.putResolvingPath(rp)\nreturn nil\n}\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/pipe.cc", "new_path": "test/syscalls/linux/pipe.cc", "diff": "@@ -265,6 +265,8 @@ TEST_P(PipeTest, OffsetCalls) {\nSyscallFailsWithErrno(ESPIPE));\nstruct iovec iov;\n+ iov.iov_base = &buf;\n+ iov.iov_len = sizeof(buf);\nEXPECT_THAT(preadv(wfd_.get(), &iov, 1, 0), SyscallFailsWithErrno(ESPIPE));\nEXPECT_THAT(pwritev(rfd_.get(), &iov, 1, 0), SyscallFailsWithErrno(ESPIPE));\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Implement pipe(2) and pipe2(2) for VFS2. Updates #1035 PiperOrigin-RevId: 306968644
260,003
17.04.2020 10:33:54
25,200
4a818d64378f16f3738ba51c7804cff90f753b1d
proc net test: Annotate disable-save test with NoRandomSave.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/proc_net.cc", "new_path": "test/syscalls/linux/proc_net.cc", "diff": "@@ -353,7 +353,7 @@ TEST(ProcNetSnmp, UdpNoPorts_NoRandomSave) {\nEXPECT_EQ(oldNoPorts, newNoPorts - 1);\n}\n-TEST(ProcNetSnmp, UdpIn) {\n+TEST(ProcNetSnmp, UdpIn_NoRandomSave) {\n// TODO(gvisor.dev/issue/866): epsocket metrics are not savable.\nconst DisableSave ds;\n" } ]
Go
Apache License 2.0
google/gvisor
proc net test: Annotate disable-save test with NoRandomSave. PiperOrigin-RevId: 307069884
259,975
17.04.2020 10:38:04
25,200
12bde95635ac266aab8087b4705372bb177638f3
Get /bin/true to run on VFS2 Included: loader_test.go RunTest and TestStartSignal VFS2 container_test.go TestAppExitStatus on VFS2 experimental flag added to runsc to turn on VFS2 Note: shared mounts are not yet supported.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/syscalls.go", "new_path": "pkg/sentry/kernel/syscalls.go", "diff": "@@ -326,6 +326,13 @@ func RegisterSyscallTable(s *SyscallTable) {\nallSyscallTables = append(allSyscallTables, s)\n}\n+// FlushSyscallTablesTestOnly flushes the syscall tables for tests. Used for\n+// parameterized VFSv2 tests.\n+// TODO(gvisor.dv/issue/1624): Remove when VFS1 is no longer supported.\n+func FlushSyscallTablesTestOnly() {\n+ allSyscallTables = nil\n+}\n+\n// Lookup returns the syscall implementation, if one exists.\nfunc (s *SyscallTable) Lookup(sysno uintptr) SyscallFn {\nif sysno < uintptr(len(s.lookup)) {\n" }, { "change_type": "MODIFY", "old_path": "runsc/boot/BUILD", "new_path": "runsc/boot/BUILD", "diff": "@@ -21,6 +21,7 @@ go_library(\n\"network.go\",\n\"strace.go\",\n\"user.go\",\n+ \"vfs.go\",\n],\nvisibility = [\n\"//runsc:__subpackages__\",\n@@ -33,6 +34,7 @@ go_library(\n\"//pkg/control/server\",\n\"//pkg/cpuid\",\n\"//pkg/eventchannel\",\n+ \"//pkg/fspath\",\n\"//pkg/log\",\n\"//pkg/memutil\",\n\"//pkg/rand\",\n@@ -40,6 +42,7 @@ go_library(\n\"//pkg/sentry/arch\",\n\"//pkg/sentry/arch:registers_go_proto\",\n\"//pkg/sentry/control\",\n+ \"//pkg/sentry/devices/memdev\",\n\"//pkg/sentry/fs\",\n\"//pkg/sentry/fs/dev\",\n\"//pkg/sentry/fs/gofer\",\n@@ -49,6 +52,12 @@ go_library(\n\"//pkg/sentry/fs/sys\",\n\"//pkg/sentry/fs/tmpfs\",\n\"//pkg/sentry/fs/tty\",\n+ \"//pkg/sentry/fsimpl/devtmpfs\",\n+ \"//pkg/sentry/fsimpl/gofer\",\n+ \"//pkg/sentry/fsimpl/host\",\n+ \"//pkg/sentry/fsimpl/proc\",\n+ \"//pkg/sentry/fsimpl/sys\",\n+ \"//pkg/sentry/fsimpl/tmpfs\",\n\"//pkg/sentry/inet\",\n\"//pkg/sentry/kernel\",\n\"//pkg/sentry/kernel:uncaught_signal_go_proto\",\n@@ -71,6 +80,7 @@ go_library(\n\"//pkg/sentry/time\",\n\"//pkg/sentry/unimpl:unimplemented_syscall_go_proto\",\n\"//pkg/sentry/usage\",\n+ \"//pkg/sentry/vfs\",\n\"//pkg/sentry/watchdog\",\n\"//pkg/sync\",\n\"//pkg/syserror\",\n@@ -114,6 +124,7 @@ go_test(\n\"//pkg/p9\",\n\"//pkg/sentry/contexttest\",\n\"//pkg/sentry/fs\",\n+ \"//pkg/sentry/kernel\",\n\"//pkg/sentry/kernel/auth\",\n\"//pkg/sync\",\n\"//pkg/unet\",\n" }, { "change_type": "MODIFY", "old_path": "runsc/boot/config.go", "new_path": "runsc/boot/config.go", "diff": "@@ -305,5 +305,10 @@ func (c *Config) ToFlags() []string {\nif len(c.TestOnlyTestNameEnv) != 0 {\nf = append(f, \"--TESTONLY-test-name-env=\"+c.TestOnlyTestNameEnv)\n}\n+\n+ if c.VFS2 {\n+ f = append(f, \"--vfs2=true\")\n+ }\n+\nreturn f\n}\n" }, { "change_type": "MODIFY", "old_path": "runsc/boot/fds.go", "new_path": "runsc/boot/fds.go", "diff": "@@ -20,6 +20,7 @@ import (\n\"gvisor.dev/gvisor/pkg/context\"\n\"gvisor.dev/gvisor/pkg/sentry/fs\"\n\"gvisor.dev/gvisor/pkg/sentry/fs/host\"\n+ vfshost \"gvisor.dev/gvisor/pkg/sentry/fsimpl/host\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n)\n@@ -31,6 +32,10 @@ func createFDTable(ctx context.Context, console bool, stdioFDs []int) (*kernel.F\nreturn nil, fmt.Errorf(\"stdioFDs should contain exactly 3 FDs (stdin, stdout, and stderr), but %d FDs received\", len(stdioFDs))\n}\n+ if kernel.VFS2Enabled {\n+ return createFDTableVFS2(ctx, console, stdioFDs)\n+ }\n+\nk := kernel.KernelFromContext(ctx)\nfdTable := k.NewFDTable()\ndefer fdTable.DecRef()\n@@ -78,3 +83,31 @@ func createFDTable(ctx context.Context, console bool, stdioFDs []int) (*kernel.F\nfdTable.IncRef()\nreturn fdTable, nil\n}\n+\n+func createFDTableVFS2(ctx context.Context, console bool, stdioFDs []int) (*kernel.FDTable, error) {\n+ k := kernel.KernelFromContext(ctx)\n+ fdTable := k.NewFDTable()\n+ defer fdTable.DecRef()\n+\n+ hostMount, err := vfshost.NewMount(k.VFS())\n+ if err != nil {\n+ return nil, fmt.Errorf(\"creating host mount: %w\", err)\n+ }\n+\n+ for appFD, hostFD := range stdioFDs {\n+ // TODO(gvisor.dev/issue/1482): Add TTY support.\n+ appFile, err := vfshost.ImportFD(hostMount, hostFD, false)\n+ if err != nil {\n+ return nil, err\n+ }\n+\n+ if err := fdTable.NewFDAtVFS2(ctx, int32(appFD), appFile, kernel.FDFlags{}); err != nil {\n+ appFile.DecRef()\n+ return nil, err\n+ }\n+ appFile.DecRef()\n+ }\n+\n+ fdTable.IncRef()\n+ return fdTable, nil\n+}\n" }, { "change_type": "MODIFY", "old_path": "runsc/boot/fs.go", "new_path": "runsc/boot/fs.go", "diff": "@@ -278,6 +278,9 @@ func subtargets(root string, mnts []specs.Mount) []string {\n}\nfunc setupContainerFS(ctx context.Context, conf *Config, mntr *containerMounter, procArgs *kernel.CreateProcessArgs) error {\n+ if conf.VFS2 {\n+ return setupContainerVFS2(ctx, conf, mntr, procArgs)\n+ }\nmns, err := mntr.setupFS(conf, procArgs)\nif err != nil {\nreturn err\n@@ -573,6 +576,9 @@ func newContainerMounter(spec *specs.Spec, goferFDs []int, k *kernel.Kernel, hin\n// should be mounted (e.g. a volume shared between containers). It must be\n// called for the root container only.\nfunc (c *containerMounter) processHints(conf *Config) error {\n+ if conf.VFS2 {\n+ return nil\n+ }\nctx := c.k.SupervisorContext()\nfor _, hint := range c.hints.mounts {\n// TODO(b/142076984): Only support tmpfs for now. Bind mounts require a\n@@ -781,9 +787,6 @@ func (c *containerMounter) getMountNameAndOptions(conf *Config, m specs.Mount) (\nuseOverlay = conf.Overlay && !mountFlags(m.Options).ReadOnly\ndefault:\n- // TODO(nlacasse): Support all the mount types and make this a fatal error.\n- // Most applications will \"just work\" without them, so this is a warning\n- // for now.\nlog.Warningf(\"ignoring unknown filesystem type %q\", m.Type)\n}\nreturn fsName, opts, useOverlay, nil\n" }, { "change_type": "MODIFY", "old_path": "runsc/boot/loader.go", "new_path": "runsc/boot/loader.go", "diff": "@@ -26,7 +26,6 @@ import (\nspecs \"github.com/opencontainers/runtime-spec/specs-go\"\n\"golang.org/x/sys/unix\"\n- \"gvisor.dev/gvisor/pkg/abi\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/cpuid\"\n\"gvisor.dev/gvisor/pkg/log\"\n@@ -73,6 +72,8 @@ import (\n_ \"gvisor.dev/gvisor/pkg/sentry/socket/unix\"\n)\n+var syscallTable *kernel.SyscallTable\n+\n// Loader keeps state needed to start the kernel and run the container..\ntype Loader struct {\n// k is the kernel.\n@@ -195,13 +196,14 @@ func New(args Args) (*Loader, error) {\nreturn nil, fmt.Errorf(\"setting up memory usage: %v\", err)\n}\n- if args.Conf.VFS2 {\n- st, ok := kernel.LookupSyscallTable(abi.Linux, arch.Host)\n- if ok {\n- vfs2.Override(st.Table)\n- }\n+ // Patch the syscall table.\n+ kernel.VFS2Enabled = args.Conf.VFS2\n+ if kernel.VFS2Enabled {\n+ vfs2.Override(syscallTable.Table)\n}\n+ kernel.RegisterSyscallTable(syscallTable)\n+\n// Create kernel and platform.\np, err := createPlatform(args.Conf, args.Device)\nif err != nil {\n@@ -392,11 +394,16 @@ func newProcess(id string, spec *specs.Spec, creds *auth.Credentials, k *kernel.\nreturn kernel.CreateProcessArgs{}, fmt.Errorf(\"creating limits: %v\", err)\n}\n+ wd := spec.Process.Cwd\n+ if wd == \"\" {\n+ wd = \"/\"\n+ }\n+\n// Create the process arguments.\nprocArgs := kernel.CreateProcessArgs{\nArgv: spec.Process.Args,\nEnvv: spec.Process.Env,\n- WorkingDirectory: spec.Process.Cwd, // Defaults to '/' if empty.\n+ WorkingDirectory: wd,\nCredentials: creds,\nUmask: 0022,\nLimits: ls,\n@@ -541,7 +548,15 @@ func (l *Loader) run() error {\n}\n// Add the HOME enviroment variable if it is not already set.\n- envv, err := maybeAddExecUserHome(ctx, l.rootProcArgs.MountNamespace, l.rootProcArgs.Credentials.RealKUID, l.rootProcArgs.Envv)\n+ var envv []string\n+ if kernel.VFS2Enabled {\n+ envv, err = maybeAddExecUserHomeVFS2(ctx, l.rootProcArgs.MountNamespaceVFS2,\n+ l.rootProcArgs.Credentials.RealKUID, l.rootProcArgs.Envv)\n+\n+ } else {\n+ envv, err = maybeAddExecUserHome(ctx, l.rootProcArgs.MountNamespace,\n+ l.rootProcArgs.Credentials.RealKUID, l.rootProcArgs.Envv)\n+ }\nif err != nil {\nreturn err\n}\n" }, { "change_type": "MODIFY", "old_path": "runsc/boot/loader_amd64.go", "new_path": "runsc/boot/loader_amd64.go", "diff": "package boot\nimport (\n- \"gvisor.dev/gvisor/pkg/sentry/kernel\"\n\"gvisor.dev/gvisor/pkg/sentry/syscalls/linux\"\n)\nfunc init() {\n- // Register the global syscall table.\n- kernel.RegisterSyscallTable(linux.AMD64)\n+ // Set the global syscall table.\n+ syscallTable = linux.AMD64\n}\n" }, { "change_type": "MODIFY", "old_path": "runsc/boot/loader_arm64.go", "new_path": "runsc/boot/loader_arm64.go", "diff": "package boot\nimport (\n- \"gvisor.dev/gvisor/pkg/sentry/kernel\"\n\"gvisor.dev/gvisor/pkg/sentry/syscalls/linux\"\n)\nfunc init() {\n- // Register the global syscall table.\n- kernel.RegisterSyscallTable(linux.ARM64)\n+ // Set the global syscall table.\n+ syscallTable = linux.ARM64\n}\n" }, { "change_type": "MODIFY", "old_path": "runsc/boot/loader_test.go", "new_path": "runsc/boot/loader_test.go", "diff": "@@ -30,6 +30,7 @@ import (\n\"gvisor.dev/gvisor/pkg/p9\"\n\"gvisor.dev/gvisor/pkg/sentry/contexttest\"\n\"gvisor.dev/gvisor/pkg/sentry/fs\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel\"\n\"gvisor.dev/gvisor/pkg/sync\"\n\"gvisor.dev/gvisor/pkg/unet\"\n\"gvisor.dev/gvisor/runsc/fsgofer\"\n@@ -66,6 +67,11 @@ func testSpec() *specs.Spec {\n}\n}\n+func resetSyscallTable() {\n+ kernel.VFS2Enabled = false\n+ kernel.FlushSyscallTablesTestOnly()\n+}\n+\n// startGofer starts a new gofer routine serving 'root' path. It returns the\n// sandbox side of the connection, and a function that when called will stop the\n// gofer.\n@@ -101,7 +107,7 @@ func startGofer(root string) (int, func(), error) {\nreturn sandboxEnd, cleanup, nil\n}\n-func createLoader() (*Loader, func(), error) {\n+func createLoader(vfsEnabled bool) (*Loader, func(), error) {\nfd, err := server.CreateSocket(ControlSocketAddr(fmt.Sprintf(\"%010d\", rand.Int())[:10]))\nif err != nil {\nreturn nil, nil, err\n@@ -109,6 +115,8 @@ func createLoader() (*Loader, func(), error) {\nconf := testConfig()\nspec := testSpec()\n+ conf.VFS2 = vfsEnabled\n+\nsandEnd, cleanup, err := startGofer(spec.Root.Path)\nif err != nil {\nreturn nil, nil, err\n@@ -142,10 +150,22 @@ func createLoader() (*Loader, func(), error) {\n// TestRun runs a simple application in a sandbox and checks that it succeeds.\nfunc TestRun(t *testing.T) {\n- l, cleanup, err := createLoader()\n+ defer resetSyscallTable()\n+ doRun(t, false)\n+}\n+\n+// TestRunVFS2 runs TestRun in VFSv2.\n+func TestRunVFS2(t *testing.T) {\n+ defer resetSyscallTable()\n+ doRun(t, true)\n+}\n+\n+func doRun(t *testing.T, vfsEnabled bool) {\n+ l, cleanup, err := createLoader(vfsEnabled)\nif err != nil {\nt.Fatalf(\"error creating loader: %v\", err)\n}\n+\ndefer l.Destroy()\ndefer cleanup()\n@@ -179,7 +199,18 @@ func TestRun(t *testing.T) {\n// TestStartSignal tests that the controller Start message will cause\n// WaitForStartSignal to return.\nfunc TestStartSignal(t *testing.T) {\n- l, cleanup, err := createLoader()\n+ defer resetSyscallTable()\n+ doStartSignal(t, false)\n+}\n+\n+// TestStartSignalVFS2 does TestStartSignal with VFS2.\n+func TestStartSignalVFS2(t *testing.T) {\n+ defer resetSyscallTable()\n+ doStartSignal(t, true)\n+}\n+\n+func doStartSignal(t *testing.T, vfsEnabled bool) {\n+ l, cleanup, err := createLoader(vfsEnabled)\nif err != nil {\nt.Fatalf(\"error creating loader: %v\", err)\n}\n" }, { "change_type": "MODIFY", "old_path": "runsc/boot/user.go", "new_path": "runsc/boot/user.go", "diff": "@@ -23,8 +23,10 @@ import (\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/context\"\n+ \"gvisor.dev/gvisor/pkg/fspath\"\n\"gvisor.dev/gvisor/pkg/sentry/fs\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n+ \"gvisor.dev/gvisor/pkg/sentry/vfs\"\n\"gvisor.dev/gvisor/pkg/usermem\"\n)\n@@ -84,6 +86,48 @@ func getExecUserHome(ctx context.Context, rootMns *fs.MountNamespace, uid auth.K\nFile: f,\n}\n+ return findHomeInPasswd(uint32(uid), r, defaultHome)\n+}\n+\n+type fileReaderVFS2 struct {\n+ ctx context.Context\n+ fd *vfs.FileDescription\n+}\n+\n+func (r *fileReaderVFS2) Read(buf []byte) (int, error) {\n+ n, err := r.fd.Read(r.ctx, usermem.BytesIOSequence(buf), vfs.ReadOptions{})\n+ return int(n), err\n+}\n+\n+func getExecUserHomeVFS2(ctx context.Context, mns *vfs.MountNamespace, uid auth.KUID) (string, error) {\n+ const defaultHome = \"/\"\n+\n+ root := mns.Root()\n+ defer root.DecRef()\n+\n+ creds := auth.CredentialsFromContext(ctx)\n+\n+ target := &vfs.PathOperation{\n+ Root: root,\n+ Start: root,\n+ Path: fspath.Parse(\"/etc/passwd\"),\n+ }\n+\n+ opts := &vfs.OpenOptions{\n+ Flags: linux.O_RDONLY,\n+ }\n+\n+ fd, err := root.Mount().Filesystem().VirtualFilesystem().OpenAt(ctx, creds, target, opts)\n+ if err != nil {\n+ return defaultHome, nil\n+ }\n+ defer fd.DecRef()\n+\n+ r := &fileReaderVFS2{\n+ ctx: ctx,\n+ fd: fd,\n+ }\n+\nhomeDir, err := findHomeInPasswd(uint32(uid), r, defaultHome)\nif err != nil {\nreturn \"\", err\n@@ -111,6 +155,26 @@ func maybeAddExecUserHome(ctx context.Context, mns *fs.MountNamespace, uid auth.\nif err != nil {\nreturn nil, fmt.Errorf(\"error reading exec user: %v\", err)\n}\n+\n+ return append(envv, \"HOME=\"+homeDir), nil\n+}\n+\n+func maybeAddExecUserHomeVFS2(ctx context.Context, vmns *vfs.MountNamespace, uid auth.KUID, envv []string) ([]string, error) {\n+ // Check if the envv already contains HOME.\n+ for _, env := range envv {\n+ if strings.HasPrefix(env, \"HOME=\") {\n+ // We have it. Return the original slice unmodified.\n+ return envv, nil\n+ }\n+ }\n+\n+ // Read /etc/passwd for the user's HOME directory and set the HOME\n+ // environment variable as required by POSIX if it is not overridden by\n+ // the user.\n+ homeDir, err := getExecUserHomeVFS2(ctx, vmns, uid)\n+ if err != nil {\n+ return nil, fmt.Errorf(\"error reading exec user: %v\", err)\n+ }\nreturn append(envv, \"HOME=\"+homeDir), nil\n}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "runsc/boot/vfs.go", "diff": "+// Copyright 2018 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 boot\n+\n+import (\n+ \"fmt\"\n+ \"path\"\n+ \"strconv\"\n+ \"strings\"\n+\n+ specs \"github.com/opencontainers/runtime-spec/specs-go\"\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/fspath\"\n+ \"gvisor.dev/gvisor/pkg/sentry/devices/memdev\"\n+ \"gvisor.dev/gvisor/pkg/sentry/fs\"\n+ devtmpfsimpl \"gvisor.dev/gvisor/pkg/sentry/fsimpl/devtmpfs\"\n+ goferimpl \"gvisor.dev/gvisor/pkg/sentry/fsimpl/gofer\"\n+ procimpl \"gvisor.dev/gvisor/pkg/sentry/fsimpl/proc\"\n+ sysimpl \"gvisor.dev/gvisor/pkg/sentry/fsimpl/sys\"\n+ tmpfsimpl \"gvisor.dev/gvisor/pkg/sentry/fsimpl/tmpfs\"\n+ \"gvisor.dev/gvisor/pkg/syserror\"\n+\n+ \"gvisor.dev/gvisor/pkg/context\"\n+ \"gvisor.dev/gvisor/pkg/log\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n+ \"gvisor.dev/gvisor/pkg/sentry/vfs\"\n+)\n+\n+func registerFilesystems(ctx context.Context, vfsObj *vfs.VirtualFilesystem, creds *auth.Credentials) error {\n+\n+ vfsObj.MustRegisterFilesystemType(rootFsName, &goferimpl.FilesystemType{}, &vfs.RegisterFilesystemTypeOptions{\n+ AllowUserList: true,\n+ })\n+\n+ vfsObj.MustRegisterFilesystemType(bind, &goferimpl.FilesystemType{}, &vfs.RegisterFilesystemTypeOptions{\n+ AllowUserList: true,\n+ })\n+\n+ vfsObj.MustRegisterFilesystemType(devpts, &devtmpfsimpl.FilesystemType{}, &vfs.RegisterFilesystemTypeOptions{\n+ AllowUserMount: true,\n+ AllowUserList: true,\n+ })\n+\n+ vfsObj.MustRegisterFilesystemType(devtmpfs, &devtmpfsimpl.FilesystemType{}, &vfs.RegisterFilesystemTypeOptions{\n+ AllowUserMount: true,\n+ AllowUserList: true,\n+ })\n+ vfsObj.MustRegisterFilesystemType(proc, &procimpl.FilesystemType{}, &vfs.RegisterFilesystemTypeOptions{\n+ AllowUserMount: true,\n+ AllowUserList: true,\n+ })\n+ vfsObj.MustRegisterFilesystemType(sysfs, &sysimpl.FilesystemType{}, &vfs.RegisterFilesystemTypeOptions{\n+ AllowUserMount: true,\n+ AllowUserList: true,\n+ })\n+ vfsObj.MustRegisterFilesystemType(tmpfs, &tmpfsimpl.FilesystemType{}, &vfs.RegisterFilesystemTypeOptions{\n+ AllowUserMount: true,\n+ AllowUserList: true,\n+ })\n+ vfsObj.MustRegisterFilesystemType(nonefs, &sysimpl.FilesystemType{}, &vfs.RegisterFilesystemTypeOptions{\n+ AllowUserMount: true,\n+ AllowUserList: true,\n+ })\n+\n+ // Setup files in devtmpfs.\n+ if err := memdev.Register(vfsObj); err != nil {\n+ return fmt.Errorf(\"registering memdev: %w\", err)\n+ }\n+ a, err := devtmpfsimpl.NewAccessor(ctx, vfsObj, creds, devtmpfsimpl.Name)\n+ if err != nil {\n+ return fmt.Errorf(\"creating devtmpfs accessor: %w\", err)\n+ }\n+ defer a.Release()\n+\n+ if err := a.UserspaceInit(ctx); err != nil {\n+ return fmt.Errorf(\"initializing userspace: %w\", err)\n+ }\n+ if err := memdev.CreateDevtmpfsFiles(ctx, a); err != nil {\n+ return fmt.Errorf(\"creating devtmpfs files: %w\", err)\n+ }\n+ return nil\n+}\n+\n+func setupContainerVFS2(ctx context.Context, conf *Config, mntr *containerMounter, procArgs *kernel.CreateProcessArgs) error {\n+ if err := mntr.k.VFS().Init(); err != nil {\n+ return fmt.Errorf(\"failed to initialize VFS: %w\", err)\n+ }\n+ mns, err := mntr.setupVFS2(ctx, conf, procArgs)\n+ if err != nil {\n+ return fmt.Errorf(\"failed to setupFS: %w\", err)\n+ }\n+ procArgs.MountNamespaceVFS2 = mns\n+ return setExecutablePathVFS2(ctx, procArgs)\n+}\n+\n+func setExecutablePathVFS2(ctx context.Context, procArgs *kernel.CreateProcessArgs) error {\n+\n+ exe := procArgs.Argv[0]\n+\n+ // Absolute paths can be used directly.\n+ if path.IsAbs(exe) {\n+ procArgs.Filename = exe\n+ return nil\n+ }\n+\n+ // Paths with '/' in them should be joined to the working directory, or\n+ // to the root if working directory is not set.\n+ if strings.IndexByte(exe, '/') > 0 {\n+\n+ if !path.IsAbs(procArgs.WorkingDirectory) {\n+ return fmt.Errorf(\"working directory %q must be absolute\", procArgs.WorkingDirectory)\n+ }\n+\n+ procArgs.Filename = path.Join(procArgs.WorkingDirectory, exe)\n+ return nil\n+ }\n+\n+ // Paths with a '/' are relative to the CWD.\n+ if strings.IndexByte(exe, '/') > 0 {\n+ procArgs.Filename = path.Join(procArgs.WorkingDirectory, exe)\n+ return nil\n+ }\n+\n+ // Otherwise, We must lookup the name in the paths, starting from the\n+ // root directory.\n+ root := procArgs.MountNamespaceVFS2.Root()\n+ defer root.DecRef()\n+\n+ paths := fs.GetPath(procArgs.Envv)\n+ creds := procArgs.Credentials\n+\n+ for _, p := range paths {\n+\n+ binPath := path.Join(p, exe)\n+\n+ pop := &vfs.PathOperation{\n+ Root: root,\n+ Start: root,\n+ Path: fspath.Parse(binPath),\n+ FollowFinalSymlink: true,\n+ }\n+\n+ opts := &vfs.OpenOptions{\n+ FileExec: true,\n+ Flags: linux.O_RDONLY,\n+ }\n+\n+ dentry, err := root.Mount().Filesystem().VirtualFilesystem().OpenAt(ctx, creds, pop, opts)\n+ if err == syserror.ENOENT || err == syserror.EACCES {\n+ // Didn't find it here.\n+ continue\n+ }\n+ if err != nil {\n+ return err\n+ }\n+ dentry.DecRef()\n+\n+ procArgs.Filename = binPath\n+ return nil\n+ }\n+\n+ return fmt.Errorf(\"executable %q not found in $PATH=%q\", exe, strings.Join(paths, \":\"))\n+}\n+\n+func (c *containerMounter) setupVFS2(ctx context.Context, conf *Config, procArgs *kernel.CreateProcessArgs) (*vfs.MountNamespace, error) {\n+ log.Infof(\"Configuring container's file system with VFS2\")\n+\n+ // Create context with root credentials to mount the filesystem (the current\n+ // user may not be privileged enough).\n+ rootProcArgs := *procArgs\n+ rootProcArgs.WorkingDirectory = \"/\"\n+ rootProcArgs.Credentials = auth.NewRootCredentials(procArgs.Credentials.UserNamespace)\n+ rootProcArgs.Umask = 0022\n+ rootProcArgs.MaxSymlinkTraversals = linux.MaxSymlinkTraversals\n+ rootCtx := procArgs.NewContext(c.k)\n+\n+ creds := procArgs.Credentials\n+ if err := registerFilesystems(rootCtx, c.k.VFS(), creds); err != nil {\n+ return nil, fmt.Errorf(\"register filesystems: %w\", err)\n+ }\n+\n+ fd := c.fds.remove()\n+\n+ opts := strings.Join(p9MountOptionsVFS2(fd, conf.FileAccess), \",\")\n+\n+ log.Infof(\"Mounting root over 9P, ioFD: %d\", fd)\n+ mns, err := c.k.VFS().NewMountNamespace(ctx, creds, \"\", rootFsName, &vfs.GetFilesystemOptions{Data: opts})\n+ if err != nil {\n+ return nil, fmt.Errorf(\"setting up mountnamespace: %w\", err)\n+ }\n+\n+ rootProcArgs.MountNamespaceVFS2 = mns\n+\n+ // Mount submounts.\n+ if err := c.mountSubmountsVFS2(rootCtx, conf, mns, creds); err != nil {\n+ return nil, fmt.Errorf(\"mounting submounts vfs2: %w\", err)\n+ }\n+\n+ return mns, nil\n+}\n+\n+func (c *containerMounter) mountSubmountsVFS2(ctx context.Context, conf *Config, mns *vfs.MountNamespace, creds *auth.Credentials) error {\n+\n+ for _, submount := range c.mounts {\n+ log.Debugf(\"Mounting %q to %q, type: %s, options: %s\", submount.Source, submount.Destination, submount.Type, submount.Options)\n+ if err := c.mountSubmountVFS2(ctx, conf, mns, creds, &submount); err != nil {\n+ return err\n+ }\n+ }\n+\n+ // TODO(gvisor.dev/issue/1487): implement mountTmp from fs.go.\n+\n+ return c.checkDispenser()\n+}\n+\n+// TODO(gvisor.dev/issue/1487): Implement submount options similar to the VFS1 version.\n+func (c *containerMounter) mountSubmountVFS2(ctx context.Context, conf *Config, mns *vfs.MountNamespace, creds *auth.Credentials, submount *specs.Mount) error {\n+ root := mns.Root()\n+ defer root.DecRef()\n+ target := &vfs.PathOperation{\n+ Root: root,\n+ Start: root,\n+ Path: fspath.Parse(submount.Destination),\n+ }\n+\n+ _, options, useOverlay, err := c.getMountNameAndOptionsVFS2(conf, *submount)\n+ if err != nil {\n+ return fmt.Errorf(\"mountOptions failed: %w\", err)\n+ }\n+\n+ opts := &vfs.MountOptions{\n+ GetFilesystemOptions: vfs.GetFilesystemOptions{\n+ Data: strings.Join(options, \",\"),\n+ },\n+ InternalMount: true,\n+ }\n+\n+ // All writes go to upper, be paranoid and make lower readonly.\n+ opts.ReadOnly = useOverlay\n+\n+ if err := c.k.VFS().MountAt(ctx, creds, \"\", target, submount.Type, opts); err != nil {\n+ return fmt.Errorf(\"failed to mount %q (type: %s): %w, opts: %v\", submount.Destination, submount.Type, err, opts)\n+ }\n+ log.Infof(\"Mounted %q to %q type: %s, internal-options: %q\", submount.Source, submount.Destination, submount.Type, opts)\n+ return nil\n+}\n+\n+// getMountNameAndOptionsVFS2 retrieves the fsName, opts, and useOverlay values\n+// used for mounts.\n+func (c *containerMounter) getMountNameAndOptionsVFS2(conf *Config, m specs.Mount) (string, []string, bool, error) {\n+ var (\n+ fsName string\n+ opts []string\n+ useOverlay bool\n+ )\n+\n+ switch m.Type {\n+ case devpts, devtmpfs, proc, sysfs:\n+ fsName = m.Type\n+ case nonefs:\n+ fsName = sysfs\n+ case tmpfs:\n+ fsName = m.Type\n+\n+ var err error\n+ opts, err = parseAndFilterOptions(m.Options, tmpfsAllowedOptions...)\n+ if err != nil {\n+ return \"\", nil, false, err\n+ }\n+\n+ case bind:\n+ fd := c.fds.remove()\n+ fsName = \"9p\"\n+ opts = p9MountOptionsVFS2(fd, c.getMountAccessType(m))\n+ // If configured, add overlay to all writable mounts.\n+ useOverlay = conf.Overlay && !mountFlags(m.Options).ReadOnly\n+\n+ default:\n+ log.Warningf(\"ignoring unknown filesystem type %q\", m.Type)\n+ }\n+ return fsName, opts, useOverlay, nil\n+}\n+\n+// p9MountOptions creates a slice of options for a p9 mount.\n+// TODO(gvisor.dev/issue/1200): Remove this version in favor of the one in\n+// fs.go when privateunixsocket lands.\n+func p9MountOptionsVFS2(fd int, fa FileAccessType) []string {\n+ opts := []string{\n+ \"trans=fd\",\n+ \"rfdno=\" + strconv.Itoa(fd),\n+ \"wfdno=\" + strconv.Itoa(fd),\n+ }\n+ if fa == FileAccessShared {\n+ opts = append(opts, \"cache=remote_revalidating\")\n+ }\n+ return opts\n+}\n" }, { "change_type": "MODIFY", "old_path": "runsc/container/container_test.go", "new_path": "runsc/container/container_test.go", "diff": "@@ -521,9 +521,21 @@ func TestExePath(t *testing.T) {\n// Test the we can retrieve the application exit status from the container.\nfunc TestAppExitStatus(t *testing.T) {\n+ conf := testutil.TestConfig()\n+ conf.VFS2 = false\n+ doAppExitStatus(t, conf)\n+}\n+\n+// This is TestAppExitStatus for VFSv2.\n+func TestAppExitStatusVFS2(t *testing.T) {\n+ conf := testutil.TestConfig()\n+ conf.VFS2 = true\n+ doAppExitStatus(t, conf)\n+}\n+\n+func doAppExitStatus(t *testing.T, conf *boot.Config) {\n// First container will succeed.\nsuccSpec := testutil.NewSpecWithArgs(\"true\")\n- conf := testutil.TestConfig()\nrootDir, bundleDir, err := testutil.SetupContainer(succSpec, conf)\nif err != nil {\nt.Fatalf(\"error setting up container: %v\", err)\n" }, { "change_type": "MODIFY", "old_path": "runsc/main.go", "new_path": "runsc/main.go", "diff": "@@ -84,6 +84,7 @@ var (\nrootless = flag.Bool(\"rootless\", false, \"it allows the sandbox to be started with a user that is not root. Sandbox and Gofer processes may run with same privileges as current user.\")\nreferenceLeakMode = flag.String(\"ref-leak-mode\", \"disabled\", \"sets reference leak check mode: disabled (default), log-names, log-traces.\")\ncpuNumFromQuota = flag.Bool(\"cpu-num-from-quota\", false, \"set cpu number to cpu quota (least integer greater or equal to quota value, but not less than 2)\")\n+ vfs2Enabled = flag.Bool(\"vfs2\", false, \"TEST ONLY; use while VFSv2 is landing. This uses the new experimental VFS layer.\")\n// Test flags, not to be used outside tests, ever.\ntestOnlyAllowRunAsCurrentUserWithoutChroot = flag.Bool(\"TESTONLY-unsafe-nonroot\", false, \"TEST ONLY; do not ever use! This skips many security measures that isolate the host from the sandbox.\")\n@@ -230,6 +231,7 @@ func main() {\nReferenceLeakMode: refsLeakMode,\nOverlayfsStaleRead: *overlayfsStaleRead,\nCPUNumFromQuota: *cpuNumFromQuota,\n+ VFS2: *vfs2Enabled,\nTestOnlyAllowRunAsCurrentUserWithoutChroot: *testOnlyAllowRunAsCurrentUserWithoutChroot,\nTestOnlyTestNameEnv: *testOnlyTestNameEnv,\n@@ -313,6 +315,7 @@ func main() {\nlog.Infof(\"\\t\\tFileAccess: %v, overlay: %t\", conf.FileAccess, conf.Overlay)\nlog.Infof(\"\\t\\tNetwork: %v, logging: %t\", conf.Network, conf.LogPackets)\nlog.Infof(\"\\t\\tStrace: %t, max size: %d, syscalls: %s\", conf.Strace, conf.StraceLogSize, conf.StraceSyscalls)\n+ log.Infof(\"\\t\\tVFS2 enabled: %v\", conf.VFS2)\nlog.Infof(\"***************************\")\nif *testOnlyAllowRunAsCurrentUserWithoutChroot {\n" } ]
Go
Apache License 2.0
google/gvisor
Get /bin/true to run on VFS2 Included: - loader_test.go RunTest and TestStartSignal VFS2 - container_test.go TestAppExitStatus on VFS2 - experimental flag added to runsc to turn on VFS2 Note: shared mounts are not yet supported. PiperOrigin-RevId: 307070753
259,992
17.04.2020 13:27:35
25,200
a80cd4302337f1c3a807e127f5a6edc2f014f431
Add test name to boot and gofer log files This is to make easier to find corresponding logs in case test fails.
[ { "change_type": "MODIFY", "old_path": "runsc/cmd/capability_test.go", "new_path": "runsc/cmd/capability_test.go", "diff": "@@ -85,7 +85,7 @@ func TestCapabilities(t *testing.T) {\nInheritable: caps,\n}\n- conf := testutil.TestConfig()\n+ conf := testutil.TestConfig(t)\n// Use --network=host to make sandbox use spec's capabilities.\nconf.Network = boot.NetworkHost\n" }, { "change_type": "MODIFY", "old_path": "runsc/container/console_test.go", "new_path": "runsc/container/console_test.go", "diff": "@@ -118,7 +118,7 @@ func receiveConsolePTY(srv *unet.ServerSocket) (*os.File, error) {\n// Test that an pty FD is sent over the console socket if one is provided.\nfunc TestConsoleSocket(t *testing.T) {\n- for _, conf := range configs(all...) {\n+ for _, conf := range configs(t, all...) {\nt.Logf(\"Running test with conf: %+v\", conf)\nspec := testutil.NewSpecWithArgs(\"true\")\nrootDir, bundleDir, err := testutil.SetupContainer(spec, conf)\n@@ -163,7 +163,7 @@ func TestConsoleSocket(t *testing.T) {\n// Test that job control signals work on a console created with \"exec -ti\".\nfunc TestJobControlSignalExec(t *testing.T) {\nspec := testutil.NewSpecWithArgs(\"/bin/sleep\", \"10000\")\n- conf := testutil.TestConfig()\n+ conf := testutil.TestConfig(t)\nrootDir, bundleDir, err := testutil.SetupContainer(spec, conf)\nif err != nil {\n@@ -286,7 +286,7 @@ func TestJobControlSignalExec(t *testing.T) {\n// Test that job control signals work on a console created with \"run -ti\".\nfunc TestJobControlSignalRootContainer(t *testing.T) {\n- conf := testutil.TestConfig()\n+ conf := testutil.TestConfig(t)\n// Don't let bash execute from profile or rc files, otherwise our PID\n// counts get messed up.\nspec := testutil.NewSpecWithArgs(\"/bin/bash\", \"--noprofile\", \"--norc\")\n" }, { "change_type": "MODIFY", "old_path": "runsc/container/container_test.go", "new_path": "runsc/container/container_test.go", "diff": "@@ -251,12 +251,12 @@ var noOverlay = []configOption{kvm, nonExclusiveFS}\nvar all = append(noOverlay, overlay)\n// configs generates different configurations to run tests.\n-func configs(opts ...configOption) []*boot.Config {\n+func configs(t *testing.T, opts ...configOption) []*boot.Config {\n// Always load the default config.\n- cs := []*boot.Config{testutil.TestConfig()}\n+ cs := []*boot.Config{testutil.TestConfig(t)}\nfor _, o := range opts {\n- c := testutil.TestConfig()\n+ c := testutil.TestConfig(t)\nswitch o {\ncase overlay:\nc.Overlay = true\n@@ -285,7 +285,7 @@ func TestLifecycle(t *testing.T) {\nchildReaper.Start()\ndefer childReaper.Stop()\n- for _, conf := range configs(all...) {\n+ for _, conf := range configs(t, all...) {\nt.Logf(\"Running test with conf: %+v\", conf)\n// The container will just sleep for a long time. We will kill it before\n// it finishes sleeping.\n@@ -457,7 +457,7 @@ func TestExePath(t *testing.T) {\nt.Fatal(err)\n}\n- for _, conf := range configs(overlay) {\n+ for _, conf := range configs(t, overlay) {\nt.Logf(\"Running test with conf: %+v\", conf)\nfor _, test := range []struct {\npath string\n@@ -521,21 +521,19 @@ func TestExePath(t *testing.T) {\n// Test the we can retrieve the application exit status from the container.\nfunc TestAppExitStatus(t *testing.T) {\n- conf := testutil.TestConfig()\n- conf.VFS2 = false\n- doAppExitStatus(t, conf)\n+ doAppExitStatus(t, false)\n}\n// This is TestAppExitStatus for VFSv2.\nfunc TestAppExitStatusVFS2(t *testing.T) {\n- conf := testutil.TestConfig()\n- conf.VFS2 = true\n- doAppExitStatus(t, conf)\n+ doAppExitStatus(t, true)\n}\n-func doAppExitStatus(t *testing.T, conf *boot.Config) {\n+func doAppExitStatus(t *testing.T, vfs2 bool) {\n// First container will succeed.\nsuccSpec := testutil.NewSpecWithArgs(\"true\")\n+ conf := testutil.TestConfig(t)\n+ conf.VFS2 = vfs2\nrootDir, bundleDir, err := testutil.SetupContainer(succSpec, conf)\nif err != nil {\nt.Fatalf(\"error setting up container: %v\", err)\n@@ -585,7 +583,7 @@ func doAppExitStatus(t *testing.T, conf *boot.Config) {\n// TestExec verifies that a container can exec a new program.\nfunc TestExec(t *testing.T) {\n- for _, conf := range configs(overlay) {\n+ for _, conf := range configs(t, overlay) {\nt.Logf(\"Running test with conf: %+v\", conf)\nconst uid = 343\n@@ -679,7 +677,7 @@ func TestExec(t *testing.T) {\n// TestKillPid verifies that we can signal individual exec'd processes.\nfunc TestKillPid(t *testing.T) {\n- for _, conf := range configs(overlay) {\n+ for _, conf := range configs(t, overlay) {\nt.Logf(\"Running test with conf: %+v\", conf)\napp, err := testutil.FindFile(\"runsc/container/test_app/test_app\")\n@@ -755,7 +753,7 @@ func TestKillPid(t *testing.T) {\n// be the next consecutive number after the last number from the checkpointed container.\nfunc TestCheckpointRestore(t *testing.T) {\n// Skip overlay because test requires writing to host file.\n- for _, conf := range configs(noOverlay...) {\n+ for _, conf := range configs(t, noOverlay...) {\nt.Logf(\"Running test with conf: %+v\", conf)\ndir, err := ioutil.TempDir(testutil.TmpDir(), \"checkpoint-test\")\n@@ -916,7 +914,7 @@ func TestCheckpointRestore(t *testing.T) {\n// with filesystem Unix Domain Socket use.\nfunc TestUnixDomainSockets(t *testing.T) {\n// Skip overlay because test requires writing to host file.\n- for _, conf := range configs(noOverlay...) {\n+ for _, conf := range configs(t, noOverlay...) {\nt.Logf(\"Running test with conf: %+v\", conf)\n// UDS path is limited to 108 chars for compatibility with older systems.\n@@ -1054,7 +1052,7 @@ func TestUnixDomainSockets(t *testing.T) {\n// recreated. Then it resumes the container, verify that the file gets created\n// again.\nfunc TestPauseResume(t *testing.T) {\n- for _, conf := range configs(noOverlay...) {\n+ for _, conf := range configs(t, noOverlay...) {\nt.Run(fmt.Sprintf(\"conf: %+v\", conf), func(t *testing.T) {\nt.Logf(\"Running test with conf: %+v\", conf)\n@@ -1135,7 +1133,7 @@ func TestPauseResume(t *testing.T) {\n// occurs given the correct state.\nfunc TestPauseResumeStatus(t *testing.T) {\nspec := testutil.NewSpecWithArgs(\"sleep\", \"20\")\n- conf := testutil.TestConfig()\n+ conf := testutil.TestConfig(t)\nrootDir, bundleDir, err := testutil.SetupContainer(spec, conf)\nif err != nil {\nt.Fatalf(\"error setting up container: %v\", err)\n@@ -1201,7 +1199,7 @@ func TestCapabilities(t *testing.T) {\nuid := auth.KUID(os.Getuid() + 1)\ngid := auth.KGID(os.Getgid() + 1)\n- for _, conf := range configs(all...) {\n+ for _, conf := range configs(t, all...) {\nt.Logf(\"Running test with conf: %+v\", conf)\nspec := testutil.NewSpecWithArgs(\"sleep\", \"100\")\n@@ -1290,7 +1288,7 @@ func TestCapabilities(t *testing.T) {\n// TestRunNonRoot checks that sandbox can be configured when running as\n// non-privileged user.\nfunc TestRunNonRoot(t *testing.T) {\n- for _, conf := range configs(noOverlay...) {\n+ for _, conf := range configs(t, noOverlay...) {\nt.Logf(\"Running test with conf: %+v\", conf)\nspec := testutil.NewSpecWithArgs(\"/bin/true\")\n@@ -1334,7 +1332,7 @@ func TestRunNonRoot(t *testing.T) {\n// TestMountNewDir checks that runsc will create destination directory if it\n// doesn't exit.\nfunc TestMountNewDir(t *testing.T) {\n- for _, conf := range configs(overlay) {\n+ for _, conf := range configs(t, overlay) {\nt.Logf(\"Running test with conf: %+v\", conf)\nroot, err := ioutil.TempDir(testutil.TmpDir(), \"root\")\n@@ -1363,7 +1361,7 @@ func TestMountNewDir(t *testing.T) {\n}\nfunc TestReadonlyRoot(t *testing.T) {\n- for _, conf := range configs(overlay) {\n+ for _, conf := range configs(t, overlay) {\nt.Logf(\"Running test with conf: %+v\", conf)\nspec := testutil.NewSpecWithArgs(\"/bin/touch\", \"/foo\")\n@@ -1401,7 +1399,7 @@ func TestReadonlyRoot(t *testing.T) {\n}\nfunc TestUIDMap(t *testing.T) {\n- for _, conf := range configs(noOverlay...) {\n+ for _, conf := range configs(t, noOverlay...) {\nt.Logf(\"Running test with conf: %+v\", conf)\ntestDir, err := ioutil.TempDir(testutil.TmpDir(), \"test-mount\")\nif err != nil {\n@@ -1482,7 +1480,7 @@ func TestUIDMap(t *testing.T) {\n}\nfunc TestReadonlyMount(t *testing.T) {\n- for _, conf := range configs(overlay) {\n+ for _, conf := range configs(t, overlay) {\nt.Logf(\"Running test with conf: %+v\", conf)\ndir, err := ioutil.TempDir(testutil.TmpDir(), \"ro-mount\")\n@@ -1539,7 +1537,7 @@ func TestAbbreviatedIDs(t *testing.T) {\n}\ndefer os.RemoveAll(rootDir)\n- conf := testutil.TestConfig()\n+ conf := testutil.TestConfig(t)\nconf.RootDir = rootDir\ncids := []string{\n@@ -1597,7 +1595,7 @@ func TestAbbreviatedIDs(t *testing.T) {\nfunc TestGoferExits(t *testing.T) {\nspec := testutil.NewSpecWithArgs(\"/bin/sleep\", \"10000\")\n- conf := testutil.TestConfig()\n+ conf := testutil.TestConfig(t)\nrootDir, bundleDir, err := testutil.SetupContainer(spec, conf)\nif err != nil {\nt.Fatalf(\"error setting up container: %v\", err)\n@@ -1666,7 +1664,7 @@ func TestRootNotMount(t *testing.T) {\nspec.Root.Readonly = true\nspec.Mounts = nil\n- conf := testutil.TestConfig()\n+ conf := testutil.TestConfig(t)\nif err := run(spec, conf); err != nil {\nt.Fatalf(\"error running sandbox: %v\", err)\n}\n@@ -1680,7 +1678,7 @@ func TestUserLog(t *testing.T) {\n// sched_rr_get_interval = 148 - not implemented in gvisor.\nspec := testutil.NewSpecWithArgs(app, \"syscall\", \"--syscall=148\")\n- conf := testutil.TestConfig()\n+ conf := testutil.TestConfig(t)\nrootDir, bundleDir, err := testutil.SetupContainer(spec, conf)\nif err != nil {\nt.Fatalf(\"error setting up container: %v\", err)\n@@ -1720,7 +1718,7 @@ func TestUserLog(t *testing.T) {\n}\nfunc TestWaitOnExitedSandbox(t *testing.T) {\n- for _, conf := range configs(all...) {\n+ for _, conf := range configs(t, all...) {\nt.Logf(\"Running test with conf: %+v\", conf)\n// Run a shell that sleeps for 1 second and then exits with a\n@@ -1775,7 +1773,7 @@ func TestWaitOnExitedSandbox(t *testing.T) {\nfunc TestDestroyNotStarted(t *testing.T) {\nspec := testutil.NewSpecWithArgs(\"/bin/sleep\", \"100\")\n- conf := testutil.TestConfig()\n+ conf := testutil.TestConfig(t)\nrootDir, bundleDir, err := testutil.SetupContainer(spec, conf)\nif err != nil {\nt.Fatalf(\"error setting up container: %v\", err)\n@@ -1802,7 +1800,7 @@ func TestDestroyNotStarted(t *testing.T) {\nfunc TestDestroyStarting(t *testing.T) {\nfor i := 0; i < 10; i++ {\nspec := testutil.NewSpecWithArgs(\"/bin/sleep\", \"100\")\n- conf := testutil.TestConfig()\n+ conf := testutil.TestConfig(t)\nrootDir, bundleDir, err := testutil.SetupContainer(spec, conf)\nif err != nil {\nt.Fatalf(\"error setting up container: %v\", err)\n@@ -1847,7 +1845,7 @@ func TestDestroyStarting(t *testing.T) {\n}\nfunc TestCreateWorkingDir(t *testing.T) {\n- for _, conf := range configs(overlay) {\n+ for _, conf := range configs(t, overlay) {\nt.Logf(\"Running test with conf: %+v\", conf)\ntmpDir, err := ioutil.TempDir(testutil.TmpDir(), \"cwd-create\")\n@@ -1920,7 +1918,7 @@ func TestMountPropagation(t *testing.T) {\n},\n}\n- conf := testutil.TestConfig()\n+ conf := testutil.TestConfig(t)\nrootDir, bundleDir, err := testutil.SetupContainer(spec, conf)\nif err != nil {\nt.Fatalf(\"error setting up container: %v\", err)\n@@ -1971,7 +1969,7 @@ func TestMountPropagation(t *testing.T) {\n}\nfunc TestMountSymlink(t *testing.T) {\n- for _, conf := range configs(overlay) {\n+ for _, conf := range configs(t, overlay) {\nt.Logf(\"Running test with conf: %+v\", conf)\ndir, err := ioutil.TempDir(testutil.TmpDir(), \"mount-symlink\")\n@@ -2051,7 +2049,7 @@ func TestNetRaw(t *testing.T) {\n}\nfor _, enableRaw := range []bool{true, false} {\n- conf := testutil.TestConfig()\n+ conf := testutil.TestConfig(t)\nconf.EnableRaw = enableRaw\ntest := \"--enabled\"\n@@ -2068,7 +2066,7 @@ func TestNetRaw(t *testing.T) {\n// TestOverlayfsStaleRead most basic test that '--overlayfs-stale-read' works.\nfunc TestOverlayfsStaleRead(t *testing.T) {\n- conf := testutil.TestConfig()\n+ conf := testutil.TestConfig(t)\nconf.OverlayfsStaleRead = true\nin, err := ioutil.TempFile(testutil.TmpDir(), \"stale-read.in\")\n@@ -2132,7 +2130,7 @@ func TestTTYField(t *testing.T) {\nfor _, test := range testCases {\nt.Run(test.name, func(t *testing.T) {\n- conf := testutil.TestConfig()\n+ conf := testutil.TestConfig(t)\n// We will run /bin/sleep, possibly with an open TTY.\ncmd := []string{\"/bin/sleep\", \"10000\"}\n" }, { "change_type": "MODIFY", "old_path": "runsc/container/multi_container_test.go", "new_path": "runsc/container/multi_container_test.go", "diff": "@@ -135,7 +135,7 @@ func createSharedMount(mount specs.Mount, name string, pod ...*specs.Spec) {\n// TestMultiContainerSanity checks that it is possible to run 2 dead-simple\n// containers in the same sandbox.\nfunc TestMultiContainerSanity(t *testing.T) {\n- for _, conf := range configs(all...) {\n+ for _, conf := range configs(t, all...) {\nt.Logf(\"Running test with conf: %+v\", conf)\nrootDir, err := testutil.SetupRootDir()\n@@ -173,7 +173,7 @@ func TestMultiContainerSanity(t *testing.T) {\n// TestMultiPIDNS checks that it is possible to run 2 dead-simple\n// containers in the same sandbox with different pidns.\nfunc TestMultiPIDNS(t *testing.T) {\n- for _, conf := range configs(all...) {\n+ for _, conf := range configs(t, all...) {\nt.Logf(\"Running test with conf: %+v\", conf)\nrootDir, err := testutil.SetupRootDir()\n@@ -218,7 +218,7 @@ func TestMultiPIDNS(t *testing.T) {\n// TestMultiPIDNSPath checks the pidns path.\nfunc TestMultiPIDNSPath(t *testing.T) {\n- for _, conf := range configs(all...) {\n+ for _, conf := range configs(t, all...) {\nt.Logf(\"Running test with conf: %+v\", conf)\nrootDir, err := testutil.SetupRootDir()\n@@ -289,7 +289,7 @@ func TestMultiContainerWait(t *testing.T) {\n}\ndefer os.RemoveAll(rootDir)\n- conf := testutil.TestConfig()\n+ conf := testutil.TestConfig(t)\nconf.RootDir = rootDir\n// The first container should run the entire duration of the test.\n@@ -367,7 +367,7 @@ func TestExecWait(t *testing.T) {\n}\ndefer os.RemoveAll(rootDir)\n- conf := testutil.TestConfig()\n+ conf := testutil.TestConfig(t)\nconf.RootDir = rootDir\n// The first container should run the entire duration of the test.\n@@ -463,7 +463,7 @@ func TestMultiContainerMount(t *testing.T) {\n}\ndefer os.RemoveAll(rootDir)\n- conf := testutil.TestConfig()\n+ conf := testutil.TestConfig(t)\nconf.RootDir = rootDir\ncontainers, cleanup, err := startContainers(conf, sps, ids)\n@@ -484,7 +484,7 @@ func TestMultiContainerMount(t *testing.T) {\n// TestMultiContainerSignal checks that it is possible to signal individual\n// containers without killing the entire sandbox.\nfunc TestMultiContainerSignal(t *testing.T) {\n- for _, conf := range configs(all...) {\n+ for _, conf := range configs(t, all...) {\nt.Logf(\"Running test with conf: %+v\", conf)\nrootDir, err := testutil.SetupRootDir()\n@@ -585,7 +585,7 @@ func TestMultiContainerDestroy(t *testing.T) {\nt.Fatal(\"error finding test_app:\", err)\n}\n- for _, conf := range configs(all...) {\n+ for _, conf := range configs(t, all...) {\nt.Logf(\"Running test with conf: %+v\", conf)\nrootDir, err := testutil.SetupRootDir()\n@@ -653,7 +653,7 @@ func TestMultiContainerProcesses(t *testing.T) {\n}\ndefer os.RemoveAll(rootDir)\n- conf := testutil.TestConfig()\n+ conf := testutil.TestConfig(t)\nconf.RootDir = rootDir\n// Note: use curly braces to keep 'sh' process around. Otherwise, shell\n@@ -712,7 +712,7 @@ func TestMultiContainerKillAll(t *testing.T) {\n}\ndefer os.RemoveAll(rootDir)\n- conf := testutil.TestConfig()\n+ conf := testutil.TestConfig(t)\nconf.RootDir = rootDir\nfor _, tc := range []struct {\n@@ -804,7 +804,7 @@ func TestMultiContainerDestroyNotStarted(t *testing.T) {\n[]string{\"/bin/sleep\", \"100\"},\n[]string{\"/bin/sleep\", \"100\"})\n- conf := testutil.TestConfig()\n+ conf := testutil.TestConfig(t)\nrootDir, rootBundleDir, err := testutil.SetupContainer(specs[0], conf)\nif err != nil {\nt.Fatalf(\"error setting up container: %v\", err)\n@@ -858,7 +858,7 @@ func TestMultiContainerDestroyStarting(t *testing.T) {\n}\nspecs, ids := createSpecs(cmds...)\n- conf := testutil.TestConfig()\n+ conf := testutil.TestConfig(t)\nrootDir, rootBundleDir, err := testutil.SetupContainer(specs[0], conf)\nif err != nil {\nt.Fatalf(\"error setting up container: %v\", err)\n@@ -943,7 +943,7 @@ func TestMultiContainerDifferentFilesystems(t *testing.T) {\n}\ndefer os.RemoveAll(rootDir)\n- conf := testutil.TestConfig()\n+ conf := testutil.TestConfig(t)\nconf.RootDir = rootDir\n// Make sure overlay is enabled, and none of the root filesystems are\n@@ -1006,7 +1006,7 @@ func TestMultiContainerContainerDestroyStress(t *testing.T) {\nchildrenSpecs := allSpecs[1:]\nchildrenIDs := allIDs[1:]\n- conf := testutil.TestConfig()\n+ conf := testutil.TestConfig(t)\nrootDir, bundleDir, err := testutil.SetupContainer(rootSpec, conf)\nif err != nil {\nt.Fatalf(\"error setting up container: %v\", err)\n@@ -1080,7 +1080,7 @@ func TestMultiContainerContainerDestroyStress(t *testing.T) {\n// Test that pod shared mounts are properly mounted in 2 containers and that\n// changes from one container is reflected in the other.\nfunc TestMultiContainerSharedMount(t *testing.T) {\n- for _, conf := range configs(all...) {\n+ for _, conf := range configs(t, all...) {\nt.Logf(\"Running test with conf: %+v\", conf)\nrootDir, err := testutil.SetupRootDir()\n@@ -1195,7 +1195,7 @@ func TestMultiContainerSharedMount(t *testing.T) {\n// Test that pod mounts are mounted as readonly when requested.\nfunc TestMultiContainerSharedMountReadonly(t *testing.T) {\n- for _, conf := range configs(all...) {\n+ for _, conf := range configs(t, all...) {\nt.Logf(\"Running test with conf: %+v\", conf)\nrootDir, err := testutil.SetupRootDir()\n@@ -1262,7 +1262,7 @@ func TestMultiContainerSharedMountReadonly(t *testing.T) {\n// Test that shared pod mounts continue to work after container is restarted.\nfunc TestMultiContainerSharedMountRestart(t *testing.T) {\n- for _, conf := range configs(all...) {\n+ for _, conf := range configs(t, all...) {\nt.Logf(\"Running test with conf: %+v\", conf)\nrootDir, err := testutil.SetupRootDir()\n@@ -1381,7 +1381,7 @@ func TestMultiContainerSharedMountUnsupportedOptions(t *testing.T) {\n}\ndefer os.RemoveAll(rootDir)\n- conf := testutil.TestConfig()\n+ conf := testutil.TestConfig(t)\nconf.RootDir = rootDir\n// Setup the containers.\n@@ -1463,7 +1463,7 @@ func TestMultiContainerMultiRootCanHandleFDs(t *testing.T) {\n}\ndefer os.RemoveAll(rootDir)\n- conf := testutil.TestConfig()\n+ conf := testutil.TestConfig(t)\nconf.RootDir = rootDir\n// Create the specs.\n@@ -1500,7 +1500,7 @@ func TestMultiContainerGoferKilled(t *testing.T) {\n}\ndefer os.RemoveAll(rootDir)\n- conf := testutil.TestConfig()\n+ conf := testutil.TestConfig(t)\nconf.RootDir = rootDir\nsleep := []string{\"sleep\", \"100\"}\n@@ -1587,7 +1587,7 @@ func TestMultiContainerLoadSandbox(t *testing.T) {\n}\ndefer os.RemoveAll(rootDir)\n- conf := testutil.TestConfig()\n+ conf := testutil.TestConfig(t)\nconf.RootDir = rootDir\n// Create containers for the sandbox.\n@@ -1687,7 +1687,7 @@ func TestMultiContainerRunNonRoot(t *testing.T) {\n}\ndefer os.RemoveAll(rootDir)\n- conf := testutil.TestConfig()\n+ conf := testutil.TestConfig(t)\nconf.RootDir = rootDir\npod, cleanup, err := startContainers(conf, podSpecs, ids)\n" }, { "change_type": "MODIFY", "old_path": "runsc/container/shared_volume_test.go", "new_path": "runsc/container/shared_volume_test.go", "diff": "@@ -31,7 +31,7 @@ import (\n// TestSharedVolume checks that modifications to a volume mount are propagated\n// into and out of the sandbox.\nfunc TestSharedVolume(t *testing.T) {\n- conf := testutil.TestConfig()\n+ conf := testutil.TestConfig(t)\nconf.FileAccess = boot.FileAccessShared\nt.Logf(\"Running test with conf: %+v\", conf)\n@@ -190,7 +190,7 @@ func checkFile(c *Container, filename string, want []byte) error {\n// TestSharedVolumeFile tests that changes to file content outside the sandbox\n// is reflected inside.\nfunc TestSharedVolumeFile(t *testing.T) {\n- conf := testutil.TestConfig()\n+ conf := testutil.TestConfig(t)\nconf.FileAccess = boot.FileAccessShared\nt.Logf(\"Running test with conf: %+v\", conf)\n" }, { "change_type": "MODIFY", "old_path": "runsc/main.go", "new_path": "runsc/main.go", "diff": "@@ -296,9 +296,7 @@ func main() {\nif err := syscall.Dup3(fd, int(os.Stderr.Fd()), 0); err != nil {\ncmd.Fatalf(\"error dup'ing fd %d to stderr: %v\", fd, err)\n}\n- }\n-\n- if *alsoLogToStderr {\n+ } else if *alsoLogToStderr {\ne = &log.MultiEmitter{e, newEmitter(*debugLogFormat, os.Stderr)}\n}\n" }, { "change_type": "MODIFY", "old_path": "runsc/testutil/testutil.go", "new_path": "runsc/testutil/testutil.go", "diff": "@@ -31,11 +31,13 @@ import (\n\"os\"\n\"os/exec\"\n\"os/signal\"\n+ \"path\"\n\"path/filepath\"\n\"strconv\"\n\"strings\"\n\"sync/atomic\"\n\"syscall\"\n+ \"testing\"\n\"time\"\n\"github.com/cenkalti/backoff\"\n@@ -81,17 +83,16 @@ func ConfigureExePath() error {\n// TestConfig returns the default configuration to use in tests. Note that\n// 'RootDir' must be set by caller if required.\n-func TestConfig() *boot.Config {\n+func TestConfig(t *testing.T) *boot.Config {\nlogDir := \"\"\nif dir, ok := os.LookupEnv(\"TEST_UNDECLARED_OUTPUTS_DIR\"); ok {\nlogDir = dir + \"/\"\n}\nreturn &boot.Config{\nDebug: true,\n- DebugLog: logDir,\n+ DebugLog: path.Join(logDir, \"runsc.log.\"+t.Name()+\".%TIMESTAMP%.%COMMAND%\"),\nLogFormat: \"text\",\nDebugLogFormat: \"text\",\n- AlsoLogToStderr: true,\nLogPackets: true,\nNetwork: boot.NetworkNone,\nStrace: true,\n" }, { "change_type": "MODIFY", "old_path": "test/root/oom_score_adj_test.go", "new_path": "test/root/oom_score_adj_test.go", "diff": "@@ -46,7 +46,7 @@ func TestOOMScoreAdjSingle(t *testing.T) {\n}\ndefer os.RemoveAll(rootDir)\n- conf := testutil.TestConfig()\n+ conf := testutil.TestConfig(t)\nconf.RootDir = rootDir\nppid, err := specutils.GetParentPid(os.Getpid())\n@@ -137,7 +137,7 @@ func TestOOMScoreAdjMulti(t *testing.T) {\n}\ndefer os.RemoveAll(rootDir)\n- conf := testutil.TestConfig()\n+ conf := testutil.TestConfig(t)\nconf.RootDir = rootDir\nppid, err := specutils.GetParentPid(os.Getpid())\n" } ]
Go
Apache License 2.0
google/gvisor
Add test name to boot and gofer log files This is to make easier to find corresponding logs in case test fails. PiperOrigin-RevId: 307104283
259,858
17.04.2020 22:18:36
25,200
9a233c94f1bd54c7c3c11f7166a09e2eacd179c5
Fix watchdog skipStack: the meaning was reversed.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/watchdog/watchdog.go", "new_path": "pkg/sentry/watchdog/watchdog.go", "diff": "@@ -319,8 +319,8 @@ func (w *Watchdog) report(offenders map[*kernel.Task]*offender, newTaskFound boo\n// Dump stack only if a new task is detected or if it sometime has\n// passed since the last time a stack dump was generated.\n- skipStack := newTaskFound || time.Since(w.lastStackDump) >= stackDumpSameTaskPeriod\n- w.doAction(w.TaskTimeoutAction, skipStack, &buf)\n+ showStack := newTaskFound || time.Since(w.lastStackDump) >= stackDumpSameTaskPeriod\n+ w.doAction(w.TaskTimeoutAction, showStack, &buf)\n}\nfunc (w *Watchdog) reportStuckWatchdog() {\n@@ -329,16 +329,15 @@ func (w *Watchdog) reportStuckWatchdog() {\nw.doAction(w.TaskTimeoutAction, false, &buf)\n}\n-// doAction will take the given action. If the action is LogWarnind and\n-// skipStack is true, then the stack printing will be skipped.\n-func (w *Watchdog) doAction(action Action, skipStack bool, msg *bytes.Buffer) {\n+// doAction will take the given action. If the action is LogWarning and\n+// showStack is false, then the stack printing will be skipped.\n+func (w *Watchdog) doAction(action Action, showStack bool, msg *bytes.Buffer) {\nswitch action {\ncase LogWarning:\n- if skipStack {\n+ if !showStack {\nmsg.WriteString(\"\\n...[stack dump skipped]...\")\nlog.Warningf(msg.String())\nreturn\n-\n}\nlog.TracebackAll(msg.String())\nw.lastStackDump = time.Now()\n" } ]
Go
Apache License 2.0
google/gvisor
Fix watchdog skipStack: the meaning was reversed. PiperOrigin-RevId: 307166317
259,972
19.04.2020 20:47:55
25,200
08b2fd9bc2a963ea15821b782cf6d80c15dbdf42
Convert tcp_user_timeout test from packetdrill to packetimpact.
[ { "change_type": "MODIFY", "old_path": "test/packetdrill/BUILD", "new_path": "test/packetdrill/BUILD", "diff": "-load(\"defs.bzl\", \"packetdrill_linux_test\", \"packetdrill_netstack_test\", \"packetdrill_test\")\n+load(\"defs.bzl\", \"packetdrill_test\")\npackage(licenses = [\"notice\"])\n@@ -17,16 +17,6 @@ packetdrill_test(\nscripts = [\"fin_wait2_timeout.pkt\"],\n)\n-packetdrill_linux_test(\n- name = \"tcp_user_timeout_test_linux_test\",\n- scripts = [\"linux/tcp_user_timeout.pkt\"],\n-)\n-\n-packetdrill_netstack_test(\n- name = \"tcp_user_timeout_test_netstack_test\",\n- scripts = [\"netstack/tcp_user_timeout.pkt\"],\n-)\n-\npacketdrill_test(\nname = \"listen_close_before_handshake_complete_test\",\nscripts = [\"listen_close_before_handshake_complete.pkt\"],\n" }, { "change_type": "DELETE", "old_path": "test/packetdrill/linux/tcp_user_timeout.pkt", "new_path": null, "diff": "-// Test that a socket w/ TCP_USER_TIMEOUT set aborts the connection\n-// if there is pending unacked data after the user specified timeout.\n-\n-0 socket(..., SOCK_STREAM, IPPROTO_TCP) = 3\n-+0 bind(3, ..., ...) = 0\n-\n-+0 listen(3, 1) = 0\n-\n-// Establish a connection without timestamps.\n-+0 < S 0:0(0) win 32792 <mss 1460,sackOK,nop,nop,nop,wscale 7>\n-+0 > S. 0:0(0) ack 1 <...>\n-+0.1 < . 1:1(0) ack 1 win 32792\n-\n-+0.100 accept(3, ..., ...) = 4\n-\n-// Okay, we received nothing, and decide to close this idle socket.\n-// We set TCP_USER_TIMEOUT to 3 seconds because really it is not worth\n-// trying hard to cleanly close this flow, at the price of keeping\n-// a TCP structure in kernel for about 1 minute!\n-+2 setsockopt(4, SOL_TCP, TCP_USER_TIMEOUT, [3000], 4) = 0\n-\n-// The write/ack is required mainly for netstack as netstack does\n-// not update its RTO during the handshake.\n-+0 write(4, ..., 100) = 100\n-+0 > P. 1:101(100) ack 1 <...>\n-+0 < . 1:1(0) ack 101 win 32792\n-\n-+0 close(4) = 0\n-\n-+0 > F. 101:101(0) ack 1 <...>\n-+.3~+.400 > F. 101:101(0) ack 1 <...>\n-+.3~+.400 > F. 101:101(0) ack 1 <...>\n-+.6~+.800 > F. 101:101(0) ack 1 <...>\n-+1.2~+1.300 > F. 101:101(0) ack 1 <...>\n-\n-// We finally receive something from the peer, but it is way too late\n-// Our socket vanished because TCP_USER_TIMEOUT was really small.\n-+.1 < . 1:2(1) ack 102 win 32792\n-+0 > R 102:102(0) win 0\n" }, { "change_type": "DELETE", "old_path": "test/packetdrill/netstack/tcp_user_timeout.pkt", "new_path": null, "diff": "-// Test that a socket w/ TCP_USER_TIMEOUT set aborts the connection\n-// if there is pending unacked data after the user specified timeout.\n-\n-0 socket(..., SOCK_STREAM, IPPROTO_TCP) = 3\n-+0 bind(3, ..., ...) = 0\n-\n-+0 listen(3, 1) = 0\n-\n-// Establish a connection without timestamps.\n-+0 < S 0:0(0) win 32792 <mss 1460,sackOK,nop,nop,nop,wscale 7>\n-+0 > S. 0:0(0) ack 1 <...>\n-+0.1 < . 1:1(0) ack 1 win 32792\n-\n-+0.100 accept(3, ..., ...) = 4\n-\n-// Okay, we received nothing, and decide to close this idle socket.\n-// We set TCP_USER_TIMEOUT to 3 seconds because really it is not worth\n-// trying hard to cleanly close this flow, at the price of keeping\n-// a TCP structure in kernel for about 1 minute!\n-+2 setsockopt(4, SOL_TCP, TCP_USER_TIMEOUT, [3000], 4) = 0\n-\n-// The write/ack is required mainly for netstack as netstack does\n-// not update its RTO during the handshake.\n-+0 write(4, ..., 100) = 100\n-+0 > P. 1:101(100) ack 1 <...>\n-+0 < . 1:1(0) ack 101 win 32792\n-\n-+0 close(4) = 0\n-\n-+0 > F. 101:101(0) ack 1 <...>\n-+.2~+.300 > F. 101:101(0) ack 1 <...>\n-+.4~+.500 > F. 101:101(0) ack 1 <...>\n-+.8~+.900 > F. 101:101(0) ack 1 <...>\n-\n-// We finally receive something from the peer, but it is way too late\n-// Our socket vanished because TCP_USER_TIMEOUT was really small.\n-+1.61 < . 1:2(1) ack 102 win 32792\n-+0 > R 102:102(0) win 0\n" }, { "change_type": "MODIFY", "old_path": "test/packetimpact/tests/BUILD", "new_path": "test/packetimpact/tests/BUILD", "diff": "@@ -88,6 +88,16 @@ packetimpact_go_test(\n],\n)\n+packetimpact_go_test(\n+ name = \"tcp_user_timeout\",\n+ srcs = [\"tcp_user_timeout_test.go\"],\n+ deps = [\n+ \"//pkg/tcpip/header\",\n+ \"//test/packetimpact/testbench\",\n+ \"@org_golang_x_sys//unix:go_default_library\",\n+ ],\n+)\n+\nsh_binary(\nname = \"test_runner\",\nsrcs = [\"test_runner.sh\"],\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test/packetimpact/tests/tcp_user_timeout_test.go", "diff": "+// Copyright 2020 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 tcp_user_timeout_test\n+\n+import (\n+ \"fmt\"\n+ \"testing\"\n+ \"time\"\n+\n+ \"golang.org/x/sys/unix\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/header\"\n+ tb \"gvisor.dev/gvisor/test/packetimpact/testbench\"\n+)\n+\n+func sendPayload(conn *tb.TCPIPv4, dut *tb.DUT, fd int32) error {\n+ sampleData := make([]byte, 100)\n+ for i := range sampleData {\n+ sampleData[i] = uint8(i)\n+ }\n+ conn.Drain()\n+ dut.Send(fd, sampleData, 0)\n+ if _, err := conn.ExpectData(&tb.TCP{Flags: tb.Uint8(header.TCPFlagAck | header.TCPFlagPsh)}, &tb.Payload{Bytes: sampleData}, time.Second); err != nil {\n+ return fmt.Errorf(\"expected data but got none: %w\", err)\n+ }\n+ return nil\n+}\n+\n+func sendFIN(conn *tb.TCPIPv4, dut *tb.DUT, fd int32) error {\n+ dut.Close(fd)\n+ return nil\n+}\n+\n+func TestTCPUserTimeout(t *testing.T) {\n+ for _, tt := range []struct {\n+ description string\n+ userTimeout time.Duration\n+ sendDelay time.Duration\n+ }{\n+ {\"NoUserTimeout\", 0, 3 * time.Second},\n+ {\"ACKBeforeUserTimeout\", 5 * time.Second, 4 * time.Second},\n+ {\"ACKAfterUserTimeout\", 5 * time.Second, 7 * time.Second},\n+ } {\n+ for _, ttf := range []struct {\n+ description string\n+ f func(conn *tb.TCPIPv4, dut *tb.DUT, fd int32) error\n+ }{\n+ {\"AfterPayload\", sendPayload},\n+ {\"AfterFIN\", sendFIN},\n+ } {\n+ t.Run(tt.description+ttf.description, func(t *testing.T) {\n+ // Create a socket, listen, TCP handshake, and accept.\n+ dut := tb.NewDUT(t)\n+ defer dut.TearDown()\n+ listenFD, remotePort := dut.CreateListener(unix.SOCK_STREAM, unix.IPPROTO_TCP, 1)\n+ defer dut.Close(listenFD)\n+ conn := tb.NewTCPIPv4(t, tb.TCP{DstPort: &remotePort}, tb.TCP{SrcPort: &remotePort})\n+ defer conn.Close()\n+ conn.Handshake()\n+ acceptFD, _ := dut.Accept(listenFD)\n+\n+ if tt.userTimeout != 0 {\n+ dut.SetSockOptInt(acceptFD, unix.SOL_TCP, unix.TCP_USER_TIMEOUT, int32(tt.userTimeout.Milliseconds()))\n+ }\n+\n+ if err := ttf.f(&conn, &dut, acceptFD); err != nil {\n+ t.Fatal(err)\n+ }\n+\n+ time.Sleep(tt.sendDelay)\n+ conn.Drain()\n+ conn.Send(tb.TCP{Flags: tb.Uint8(header.TCPFlagAck)})\n+\n+ // If TCP_USER_TIMEOUT was set and the above delay was longer than the\n+ // TCP_USER_TIMEOUT then the DUT should send a RST in response to the\n+ // testbench's packet.\n+ expectRST := tt.userTimeout != 0 && tt.sendDelay > tt.userTimeout\n+ expectTimeout := 5 * time.Second\n+ got, err := conn.Expect(tb.TCP{Flags: tb.Uint8(header.TCPFlagRst)}, expectTimeout)\n+ if expectRST && err != nil {\n+ t.Errorf(\"expected RST packet within %s but got none: %s\", expectTimeout, err)\n+ }\n+ if !expectRST && got != nil {\n+ t.Errorf(\"expected no RST packet within %s but got one: %s\", expectTimeout, got)\n+ }\n+ })\n+ }\n+ }\n+}\n" } ]
Go
Apache License 2.0
google/gvisor
Convert tcp_user_timeout test from packetdrill to packetimpact. PiperOrigin-RevId: 307328289
259,972
19.04.2020 22:14:53
25,200
db2a60be67f0e869a58eb12d253a0d7fe13ebfa3
Don't accept segments outside the receive window Fixed to match RFC 793 page 69. Fixes
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/seqnum/seqnum.go", "new_path": "pkg/tcpip/seqnum/seqnum.go", "diff": "@@ -46,11 +46,6 @@ func (v Value) InWindow(first Value, size Size) bool {\nreturn v.InRange(first, first.Add(size))\n}\n-// Overlap checks if the window [a,a+b) overlaps with the window [x, x+y).\n-func Overlap(a Value, b Size, x Value, y Size) bool {\n- return a.LessThan(x.Add(y)) && x.LessThan(a.Add(b))\n-}\n-\n// Add calculates the sequence number following the [v, v+s) window.\nfunc (v Value) Add(s Size) Value {\nreturn v + Value(s)\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/BUILD", "new_path": "pkg/tcpip/transport/tcp/BUILD", "diff": "@@ -109,3 +109,13 @@ go_test(\n\"//runsc/testutil\",\n],\n)\n+\n+go_test(\n+ name = \"rcv_test\",\n+ size = \"small\",\n+ srcs = [\"rcv_test.go\"],\n+ deps = [\n+ \":tcp\",\n+ \"//pkg/tcpip/seqnum\",\n+ ],\n+)\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/accept.go", "new_path": "pkg/tcpip/transport/tcp/accept.go", "diff": "@@ -101,7 +101,7 @@ type listenContext struct {\n// v6Only is true if listenEP is a dual stack socket and has the\n// IPV6_V6ONLY option set.\n- v6only bool\n+ v6Only bool\n// netProto indicates the network protocol(IPv4/v6) for the listening\n// endpoint.\n@@ -126,12 +126,12 @@ func timeStamp() uint32 {\n}\n// newListenContext creates a new listen context.\n-func newListenContext(stk *stack.Stack, listenEP *endpoint, rcvWnd seqnum.Size, v6only bool, netProto tcpip.NetworkProtocolNumber) *listenContext {\n+func newListenContext(stk *stack.Stack, listenEP *endpoint, rcvWnd seqnum.Size, v6Only bool, netProto tcpip.NetworkProtocolNumber) *listenContext {\nl := &listenContext{\nstack: stk,\nrcvWnd: rcvWnd,\nhasher: sha1.New(),\n- v6only: v6only,\n+ v6Only: v6Only,\nnetProto: netProto,\nlistenEP: listenEP,\npendingEndpoints: make(map[stack.TransportEndpointID]*endpoint),\n@@ -207,7 +207,7 @@ func (l *listenContext) createConnectingEndpoint(s *segment, iss seqnum.Value, i\nnetProto = s.route.NetProto\n}\nn := newEndpoint(l.stack, netProto, queue)\n- n.v6only = l.v6only\n+ n.v6only = l.v6Only\nn.ID = s.id\nn.boundNICID = s.route.NICID()\nn.route = s.route.Clone()\n@@ -293,7 +293,7 @@ func (l *listenContext) createEndpointAndPerformHandshake(s *segment, opts *head\n}\n// Perform the 3-way handshake.\n- h := newPassiveHandshake(ep, seqnum.Size(ep.initialReceiveWindow()), isn, irs, opts, deferAccept)\n+ h := newPassiveHandshake(ep, ep.rcv.rcvWnd, isn, irs, opts, deferAccept)\nif err := h.execute(); err != nil {\nep.mu.Unlock()\nep.Close()\n@@ -613,8 +613,8 @@ func (e *endpoint) handleListenSegment(ctx *listenContext, s *segment) {\n// its own goroutine and is responsible for handling connection requests.\nfunc (e *endpoint) protocolListenLoop(rcvWnd seqnum.Size) *tcpip.Error {\ne.mu.Lock()\n- v6only := e.v6only\n- ctx := newListenContext(e.stack, e, rcvWnd, v6only, e.NetProto)\n+ v6Only := e.v6only\n+ ctx := newListenContext(e.stack, e, rcvWnd, v6Only, e.NetProto)\ndefer func() {\n// Mark endpoint as closed. This will prevent goroutines running\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/connect.go", "new_path": "pkg/tcpip/transport/tcp/connect.go", "diff": "@@ -105,24 +105,11 @@ type handshake struct {\n}\nfunc newHandshake(ep *endpoint, rcvWnd seqnum.Size) handshake {\n- rcvWndScale := ep.rcvWndScaleForHandshake()\n-\n- // Round-down the rcvWnd to a multiple of wndScale. This ensures that the\n- // window offered in SYN won't be reduced due to the loss of precision if\n- // window scaling is enabled after the handshake.\n- rcvWnd = (rcvWnd >> uint8(rcvWndScale)) << uint8(rcvWndScale)\n-\n- // Ensure we can always accept at least 1 byte if the scale specified\n- // was too high for the provided rcvWnd.\n- if rcvWnd == 0 {\n- rcvWnd = 1\n- }\n-\nh := handshake{\nep: ep,\nactive: true,\nrcvWnd: rcvWnd,\n- rcvWndScale: int(rcvWndScale),\n+ rcvWndScale: ep.rcvWndScaleForHandshake(),\n}\nh.resetState()\nreturn h\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/endpoint.go", "new_path": "pkg/tcpip/transport/tcp/endpoint.go", "diff": "@@ -1062,6 +1062,19 @@ func (e *endpoint) initialReceiveWindow() int {\nif rcvWnd > routeWnd {\nrcvWnd = routeWnd\n}\n+ rcvWndScale := e.rcvWndScaleForHandshake()\n+\n+ // Round-down the rcvWnd to a multiple of wndScale. This ensures that the\n+ // window offered in SYN won't be reduced due to the loss of precision if\n+ // window scaling is enabled after the handshake.\n+ rcvWnd = (rcvWnd >> uint8(rcvWndScale)) << uint8(rcvWndScale)\n+\n+ // Ensure we can always accept at least 1 byte if the scale specified\n+ // was too high for the provided rcvWnd.\n+ if rcvWnd == 0 {\n+ rcvWnd = 1\n+ }\n+\nreturn rcvWnd\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/rcv.go", "new_path": "pkg/tcpip/transport/tcp/rcv.go", "diff": "@@ -70,13 +70,24 @@ func newReceiver(ep *endpoint, irs seqnum.Value, rcvWnd seqnum.Size, rcvWndScale\n// acceptable checks if the segment sequence number range is acceptable\n// according to the table on page 26 of RFC 793.\nfunc (r *receiver) acceptable(segSeq seqnum.Value, segLen seqnum.Size) bool {\n- rcvWnd := r.rcvNxt.Size(r.rcvAcc)\n- if rcvWnd == 0 {\n- return segLen == 0 && segSeq == r.rcvNxt\n+ return Acceptable(segSeq, segLen, r.rcvNxt, r.rcvAcc)\n}\n- return segSeq.InWindow(r.rcvNxt, rcvWnd) ||\n- seqnum.Overlap(r.rcvNxt, rcvWnd, segSeq, segLen)\n+// Acceptable checks if a segment that starts at segSeq and has length segLen is\n+// \"acceptable\" for arriving in a receive window that starts at rcvNxt and ends\n+// before rcvAcc, according to the table on page 26 and 69 of RFC 793.\n+func Acceptable(segSeq seqnum.Value, segLen seqnum.Size, rcvNxt, rcvAcc seqnum.Value) bool {\n+ if rcvNxt == rcvAcc {\n+ return segLen == 0 && segSeq == rcvNxt\n+ }\n+ if segLen == 0 {\n+ // rcvWnd is incremented by 1 because that is Linux's behavior despite the\n+ // RFC.\n+ return segSeq.InRange(rcvNxt, rcvAcc.Add(1))\n+ }\n+ // Page 70 of RFC 793 allows packets that can be made \"acceptable\" by trimming\n+ // the payload, so we'll accept any payload that overlaps the receieve window.\n+ return rcvNxt.LessThan(segSeq.Add(segLen)) && segSeq.LessThan(rcvAcc)\n}\n// getSendParams returns the parameters needed by the sender when building\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/tcpip/transport/tcp/rcv_test.go", "diff": "+// Copyright 2020 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 rcv_test\n+\n+import (\n+ \"testing\"\n+\n+ \"gvisor.dev/gvisor/pkg/tcpip/seqnum\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/transport/tcp\"\n+)\n+\n+func TestAcceptable(t *testing.T) {\n+ for _, tt := range []struct {\n+ segSeq seqnum.Value\n+ segLen seqnum.Size\n+ rcvNxt, rcvAcc seqnum.Value\n+ want bool\n+ }{\n+ // The segment is smaller than the window.\n+ {105, 2, 100, 104, false},\n+ {105, 2, 101, 105, false},\n+ {105, 2, 102, 106, true},\n+ {105, 2, 103, 107, true},\n+ {105, 2, 104, 108, true},\n+ {105, 2, 105, 109, true},\n+ {105, 2, 106, 110, true},\n+ {105, 2, 107, 111, false},\n+\n+ // The segment is larger than the window.\n+ {105, 4, 103, 105, false},\n+ {105, 4, 104, 106, true},\n+ {105, 4, 105, 107, true},\n+ {105, 4, 106, 108, true},\n+ {105, 4, 107, 109, true},\n+ {105, 4, 108, 110, true},\n+ {105, 4, 109, 111, false},\n+ {105, 4, 110, 112, false},\n+\n+ // The segment has no width.\n+ {105, 0, 100, 102, false},\n+ {105, 0, 101, 103, false},\n+ {105, 0, 102, 104, false},\n+ {105, 0, 103, 105, true},\n+ {105, 0, 104, 106, true},\n+ {105, 0, 105, 107, true},\n+ {105, 0, 106, 108, false},\n+ {105, 0, 107, 109, false},\n+\n+ // The receive window has no width.\n+ {105, 2, 103, 103, false},\n+ {105, 2, 104, 104, false},\n+ {105, 2, 105, 105, false},\n+ {105, 2, 106, 106, false},\n+ {105, 2, 107, 107, false},\n+ {105, 2, 108, 108, false},\n+ {105, 2, 109, 109, false},\n+ } {\n+ if got := tcp.Acceptable(tt.segSeq, tt.segLen, tt.rcvNxt, tt.rcvAcc); got != tt.want {\n+ t.Errorf(\"tcp.Acceptable(%d, %d, %d, %d) = %t, want %t\", tt.segSeq, tt.segLen, tt.rcvNxt, tt.rcvAcc, got, tt.want)\n+ }\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcpconntrack/BUILD", "new_path": "pkg/tcpip/transport/tcpconntrack/BUILD", "diff": "@@ -9,6 +9,7 @@ go_library(\ndeps = [\n\"//pkg/tcpip/header\",\n\"//pkg/tcpip/seqnum\",\n+ \"//pkg/tcpip/transport/tcp\",\n],\n)\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcpconntrack/tcp_conntrack.go", "new_path": "pkg/tcpip/transport/tcpconntrack/tcp_conntrack.go", "diff": "@@ -20,6 +20,7 @@ package tcpconntrack\nimport (\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n\"gvisor.dev/gvisor/pkg/tcpip/seqnum\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/transport/tcp\"\n)\n// Result is returned when the state of a TCB is updated in response to an\n@@ -311,17 +312,7 @@ type stream struct {\n// the window is zero, if it's a packet with no payload and sequence number\n// equal to una.\nfunc (s *stream) acceptable(segSeq seqnum.Value, segLen seqnum.Size) bool {\n- wnd := s.una.Size(s.end)\n- if wnd == 0 {\n- return segLen == 0 && segSeq == s.una\n- }\n-\n- // Make sure [segSeq, seqSeq+segLen) is non-empty.\n- if segLen == 0 {\n- segLen = 1\n- }\n-\n- return seqnum.Overlap(s.una, wnd, segSeq, segLen)\n+ return tcp.Acceptable(segSeq, segLen, s.una, s.end)\n}\n// closed determines if the stream has already been closed. This happens when\n" }, { "change_type": "MODIFY", "old_path": "test/packetimpact/tests/BUILD", "new_path": "test/packetimpact/tests/BUILD", "diff": "@@ -43,8 +43,6 @@ packetimpact_go_test(\npacketimpact_go_test(\nname = \"tcp_outside_the_window\",\nsrcs = [\"tcp_outside_the_window_test.go\"],\n- # TODO(eyalsoha): Fix #1607 then remove the line below.\n- netstack = False,\ndeps = [\n\"//pkg/tcpip/header\",\n\"//pkg/tcpip/seqnum\",\n" } ]
Go
Apache License 2.0
google/gvisor
Don't accept segments outside the receive window Fixed to match RFC 793 page 69. Fixes #1607 PiperOrigin-RevId: 307334892
259,860
20.04.2020 08:50:27
25,200
1a940f2b6c834693d9f85e3b648a3be3d986129d
Resolve issue with file mode for host fds. Instead of plumbing error through kernfs.Inode.Mode, panic if err != nil. The errors that can result from an fstat syscall all indicate that something is fundamentally wrong, and panicking should be acceptable.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/host/host.go", "new_path": "pkg/sentry/fsimpl/host/host.go", "diff": "@@ -94,7 +94,6 @@ func ImportFD(mnt *vfs.Mount, hostFD int, isTTY bool) (*vfs.FileDescription, err\nisTTY: isTTY,\ncanMap: canMap(uint32(fileType)),\nino: fs.NextIno(),\n- mode: fileMode,\n// For simplicity, set offset to 0. Technically, we should use the existing\n// offset on the host if the file is seekable.\noffset: 0,\n@@ -149,20 +148,6 @@ type inode struct {\n// This field is initialized at creation time and is immutable.\nino uint64\n- // modeMu protects mode.\n- modeMu sync.Mutex\n-\n- // mode is a cached version of the file mode on the host. Note that it may\n- // become out of date if the mode is changed on the host, e.g. with chmod.\n- //\n- // Generally, it is better to retrieve the mode from the host through an\n- // fstat syscall. We only use this value in inode.Mode(), which cannot\n- // return an error, if the syscall to host fails.\n- //\n- // FIXME(b/152294168): Plumb error into Inode.Mode() return value so we\n- // can get rid of this.\n- mode linux.FileMode\n-\n// offsetMu protects offset.\noffsetMu sync.Mutex\n@@ -195,10 +180,11 @@ func (i *inode) CheckPermissions(ctx context.Context, creds *auth.Credentials, a\n// Mode implements kernfs.Inode.\nfunc (i *inode) Mode() linux.FileMode {\nmode, _, _, err := i.getPermissions()\n+ // Retrieving the mode from the host fd using fstat(2) should not fail.\n+ // If the syscall does not succeed, something is fundamentally wrong.\nif err != nil {\n- return i.mode\n+ panic(fmt.Sprintf(\"failed to retrieve mode from host fd %d: %v\", i.hostFD, err))\n}\n-\nreturn linux.FileMode(mode)\n}\n@@ -208,11 +194,6 @@ func (i *inode) getPermissions() (linux.FileMode, auth.KUID, auth.KGID, error) {\nif err := syscall.Fstat(i.hostFD, &s); err != nil {\nreturn 0, 0, 0, err\n}\n-\n- // Update cached mode.\n- i.modeMu.Lock()\n- i.mode = linux.FileMode(s.Mode)\n- i.modeMu.Unlock()\nreturn linux.FileMode(s.Mode), auth.KUID(s.Uid), auth.KGID(s.Gid), nil\n}\n@@ -292,12 +273,6 @@ func (i *inode) Stat(_ *vfs.Filesystem, opts vfs.StatOptions) (linux.Statx, erro\nls.Ino = i.ino\n}\n- // Update cached mode.\n- if (mask&linux.STATX_TYPE != 0) && (mask&linux.STATX_MODE != 0) {\n- i.modeMu.Lock()\n- i.mode = linux.FileMode(s.Mode)\n- i.modeMu.Unlock()\n- }\nreturn ls, nil\n}\n@@ -364,9 +339,6 @@ func (i *inode) SetStat(ctx context.Context, fs *vfs.Filesystem, creds *auth.Cre\nif err := syscall.Fchmod(i.hostFD, uint32(s.Mode)); err != nil {\nreturn err\n}\n- i.modeMu.Lock()\n- i.mode = linux.FileMode(s.Mode)\n- i.modeMu.Unlock()\n}\nif m&linux.STATX_SIZE != 0 {\nif err := syscall.Ftruncate(i.hostFD, int64(s.Size)); err != nil {\n" } ]
Go
Apache License 2.0
google/gvisor
Resolve issue with file mode for host fds. Instead of plumbing error through kernfs.Inode.Mode, panic if err != nil. The errors that can result from an fstat syscall all indicate that something is fundamentally wrong, and panicking should be acceptable. PiperOrigin-RevId: 307406847
259,885
20.04.2020 10:09:23
25,200
e72ce8cce46ed48af306df50d252853c8790924d
Change lingering uses of "memfs" in fsimpl/tmpfs to "tmpfs".
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/tmpfs/benchmark_test.go", "new_path": "pkg/sentry/fsimpl/tmpfs/benchmark_test.go", "diff": "@@ -168,7 +168,7 @@ func BenchmarkVFS1TmpfsStat(b *testing.B) {\n}\n}\n-func BenchmarkVFS2MemfsStat(b *testing.B) {\n+func BenchmarkVFS2TmpfsStat(b *testing.B) {\nfor _, depth := range depths {\nb.Run(fmt.Sprintf(\"%d\", depth), func(b *testing.B) {\nctx := contexttest.Context(b)\n@@ -362,7 +362,7 @@ func BenchmarkVFS1TmpfsMountStat(b *testing.B) {\n}\n}\n-func BenchmarkVFS2MemfsMountStat(b *testing.B) {\n+func BenchmarkVFS2TmpfsMountStat(b *testing.B) {\nfor _, depth := range depths {\nb.Run(fmt.Sprintf(\"%d\", depth), func(b *testing.B) {\nctx := contexttest.Context(b)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/tmpfs/filesystem.go", "new_path": "pkg/sentry/fsimpl/tmpfs/filesystem.go", "diff": "@@ -148,7 +148,7 @@ func (fs *filesystem) doCreateAt(rp *vfs.ResolvingPath, dir bool, create func(pa\nif !dir && rp.MustBeDir() {\nreturn syserror.ENOENT\n}\n- // In memfs, the only way to cause a dentry to be disowned is by removing\n+ // In tmpfs, the only way to cause a dentry to be disowned is by removing\n// it from the filesystem, so this check is equivalent to checking if\n// parent has been removed.\nif parent.vfsd.IsDisowned() {\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/tmpfs/tmpfs.go", "new_path": "pkg/sentry/fsimpl/tmpfs/tmpfs.go", "diff": "@@ -247,7 +247,7 @@ func (i *inode) incLinksLocked() {\npanic(\"tmpfs.inode.incLinksLocked() called with no existing links\")\n}\nif i.nlink == maxLinks {\n- panic(\"memfs.inode.incLinksLocked() called with maximum link count\")\n+ panic(\"tmpfs.inode.incLinksLocked() called with maximum link count\")\n}\natomic.AddUint32(&i.nlink, 1)\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Change lingering uses of "memfs" in fsimpl/tmpfs to "tmpfs". PiperOrigin-RevId: 307422746
259,858
20.04.2020 11:08:01
25,200
9ba3086d9dfc7e9a4a957446f443786b179cd84e
Move runtime_tests.sh to align with other scripts.
[ { "change_type": "MODIFY", "old_path": "kokoro/runtime_tests/go1.12.cfg", "new_path": "kokoro/runtime_tests/go1.12.cfg", "diff": "-build_file: \"github/github/kokoro/runtime_tests/runtime_tests.sh\"\n+build_file: \"github/github/scripts/runtime_tests.sh\"\nenv_vars {\nkey: \"RUNTIME_TEST_NAME\"\n" }, { "change_type": "MODIFY", "old_path": "kokoro/runtime_tests/java11.cfg", "new_path": "kokoro/runtime_tests/java11.cfg", "diff": "-build_file: \"github/github/kokoro/runtime_tests/runtime_tests.sh\"\n+build_file: \"github/github/scripts/runtime_tests.sh\"\nenv_vars {\nkey: \"RUNTIME_TEST_NAME\"\n" }, { "change_type": "MODIFY", "old_path": "kokoro/runtime_tests/nodejs12.4.0.cfg", "new_path": "kokoro/runtime_tests/nodejs12.4.0.cfg", "diff": "-build_file: \"github/github/kokoro/runtime_tests/runtime_tests.sh\"\n+build_file: \"github/github/scripts/runtime_tests.sh\"\nenv_vars {\nkey: \"RUNTIME_TEST_NAME\"\n" }, { "change_type": "MODIFY", "old_path": "kokoro/runtime_tests/php7.3.6.cfg", "new_path": "kokoro/runtime_tests/php7.3.6.cfg", "diff": "-build_file: \"github/github/kokoro/runtime_tests/runtime_tests.sh\"\n+build_file: \"github/github/scripts/runtime_tests.sh\"\nenv_vars {\nkey: \"RUNTIME_TEST_NAME\"\n" }, { "change_type": "MODIFY", "old_path": "kokoro/runtime_tests/python3.7.3.cfg", "new_path": "kokoro/runtime_tests/python3.7.3.cfg", "diff": "-build_file: \"github/github/kokoro/runtime_tests/runtime_tests.sh\"\n+build_file: \"github/github/scripts/runtime_tests.sh\"\nenv_vars {\nkey: \"RUNTIME_TEST_NAME\"\n" }, { "change_type": "ADD", "old_path": null, "new_path": "scripts/runtime_tests.sh", "diff": "+#!/bin/bash\n+\n+# 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+source $(dirname $0)/common.sh\n+\n+# Check that a runtime is provided.\n+if [ ! -v RUNTIME_TEST_NAME ]; then\n+ echo \"Must set $RUNTIME_TEST_NAME\" >&2\n+ exit 1\n+fi\n+\n+install_runsc_for_test runtimes\n+test_runsc \"//test/runtimes:${RUNTIME_TEST_NAME}_test\"\n" } ]
Go
Apache License 2.0
google/gvisor
Move runtime_tests.sh to align with other scripts. PiperOrigin-RevId: 307435879
260,003
20.04.2020 12:57:18
25,200
470633d7e916e7956f4ebd75559f92cf12067cbf
Fix release.sh. git commands need to be run in git repo.
[ { "change_type": "MODIFY", "old_path": "scripts/release.sh", "new_path": "scripts/release.sh", "diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\n-source $(dirname $0)/common.sh\n+cd $(dirname $0)/..\n+source scripts/common.sh\n# Tag a release only if provided.\nif ! [[ -v KOKORO_RELEASE_COMMIT ]]; then\n" } ]
Go
Apache License 2.0
google/gvisor
Fix release.sh. git commands need to be run in git repo. PiperOrigin-RevId: 307458938
259,943
21.04.2020 09:34:42
25,200
7c0f3bc8576addbec001095d754a756691d26df3
Sentry metrics updates. Sentry metrics with nanoseconds units are labeled as such, and non-cumulative sentry metrics are supported.
[ { "change_type": "MODIFY", "old_path": "pkg/metric/metric.go", "new_path": "pkg/metric/metric.go", "diff": "@@ -39,16 +39,11 @@ var (\n// Uint64Metric encapsulates a uint64 that represents some kind of metric to be\n// monitored.\n//\n-// All metrics must be cumulative, meaning that their values will only increase\n-// over time.\n-//\n// Metrics are not saved across save/restore and thus reset to zero on restore.\n//\n-// TODO(b/67298402): Support non-cumulative metrics.\n// TODO(b/67298427): Support metric fields.\ntype Uint64Metric struct {\n- // value is the actual value of the metric. It must be accessed\n- // atomically.\n+ // value is the actual value of the metric. It must be accessed atomically.\nvalue uint64\n}\n@@ -110,13 +105,10 @@ type customUint64Metric struct {\n// Register must only be called at init and will return and error if called\n// after Initialized.\n//\n-// All metrics must be cumulative, meaning that the return values of value must\n-// only increase over time.\n-//\n// Preconditions:\n// * name must be globally unique.\n// * Initialize/Disable have not been called.\n-func RegisterCustomUint64Metric(name string, sync bool, description string, value func() uint64) error {\n+func RegisterCustomUint64Metric(name string, cumulative, sync bool, units pb.MetricMetadata_Units, description string, value func() uint64) error {\nif initialized {\nreturn ErrInitializationDone\n}\n@@ -129,9 +121,10 @@ func RegisterCustomUint64Metric(name string, sync bool, description string, valu\nmetadata: &pb.MetricMetadata{\nName: name,\nDescription: description,\n- Cumulative: true,\n+ Cumulative: cumulative,\nSync: sync,\n- Type: pb.MetricMetadata_UINT64,\n+ Type: pb.MetricMetadata_TYPE_UINT64,\n+ Units: units,\n},\nvalue: value,\n}\n@@ -140,24 +133,32 @@ func RegisterCustomUint64Metric(name string, sync bool, description string, valu\n// MustRegisterCustomUint64Metric calls RegisterCustomUint64Metric and panics\n// if it returns an error.\n-func MustRegisterCustomUint64Metric(name string, sync bool, description string, value func() uint64) {\n- if err := RegisterCustomUint64Metric(name, sync, description, value); err != nil {\n+func MustRegisterCustomUint64Metric(name string, cumulative, sync bool, description string, value func() uint64) {\n+ if err := RegisterCustomUint64Metric(name, cumulative, sync, pb.MetricMetadata_UNITS_NONE, description, value); err != nil {\npanic(fmt.Sprintf(\"Unable to register metric %q: %v\", name, err))\n}\n}\n-// NewUint64Metric creates and registers a new metric with the given name.\n+// NewUint64Metric creates and registers a new cumulative metric with the given name.\n//\n// Metrics must be statically defined (i.e., at init).\n-func NewUint64Metric(name string, sync bool, description string) (*Uint64Metric, error) {\n+func NewUint64Metric(name string, sync bool, units pb.MetricMetadata_Units, description string) (*Uint64Metric, error) {\nvar m Uint64Metric\n- return &m, RegisterCustomUint64Metric(name, sync, description, m.Value)\n+ return &m, RegisterCustomUint64Metric(name, true /* cumulative */, sync, units, description, m.Value)\n}\n-// MustCreateNewUint64Metric calls NewUint64Metric and panics if it returns an\n-// error.\n+// MustCreateNewUint64Metric calls NewUint64Metric and panics if it returns an error.\nfunc MustCreateNewUint64Metric(name string, sync bool, description string) *Uint64Metric {\n- m, err := NewUint64Metric(name, sync, description)\n+ m, err := NewUint64Metric(name, sync, pb.MetricMetadata_UNITS_NONE, description)\n+ if err != nil {\n+ panic(fmt.Sprintf(\"Unable to create metric %q: %v\", name, err))\n+ }\n+ return m\n+}\n+\n+// MustCreateNewUint64NanosecondsMetric calls NewUint64Metric and panics if it returns an error.\n+func MustCreateNewUint64NanosecondsMetric(name string, sync bool, description string) *Uint64Metric {\n+ m, err := NewUint64Metric(name, sync, pb.MetricMetadata_UNITS_NANOSECONDS, description)\nif err != nil {\npanic(fmt.Sprintf(\"Unable to create metric %q: %v\", name, err))\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/metric/metric.proto", "new_path": "pkg/metric/metric.proto", "diff": "@@ -36,10 +36,18 @@ message MetricMetadata {\n// the monitoring system.\nbool sync = 4;\n- enum Type { UINT64 = 0; }\n+ enum Type { TYPE_UINT64 = 0; }\n// type is the type of the metric value.\nType type = 5;\n+\n+ enum Units {\n+ UNITS_NONE = 0;\n+ UNITS_NANOSECONDS = 1;\n+ }\n+\n+ // units is the units of the metric value.\n+ Units units = 6;\n}\n// MetricRegistration contains the metadata for all metrics that will be in\n" }, { "change_type": "MODIFY", "old_path": "pkg/metric/metric_test.go", "new_path": "pkg/metric/metric_test.go", "diff": "@@ -66,12 +66,12 @@ const (\nfunc TestInitialize(t *testing.T) {\ndefer reset()\n- _, err := NewUint64Metric(\"/foo\", false, fooDescription)\n+ _, err := NewUint64Metric(\"/foo\", false, pb.MetricMetadata_UNITS_NONE, fooDescription)\nif err != nil {\nt.Fatalf(\"NewUint64Metric got err %v want nil\", err)\n}\n- _, err = NewUint64Metric(\"/bar\", true, barDescription)\n+ _, err = NewUint64Metric(\"/bar\", true, pb.MetricMetadata_UNITS_NANOSECONDS, barDescription)\nif err != nil {\nt.Fatalf(\"NewUint64Metric got err %v want nil\", err)\n}\n@@ -94,8 +94,8 @@ func TestInitialize(t *testing.T) {\nfoundFoo := false\nfoundBar := false\nfor _, m := range mr.Metrics {\n- if m.Type != pb.MetricMetadata_UINT64 {\n- t.Errorf(\"Metadata %+v Type got %v want %v\", m, m.Type, pb.MetricMetadata_UINT64)\n+ if m.Type != pb.MetricMetadata_TYPE_UINT64 {\n+ t.Errorf(\"Metadata %+v Type got %v want %v\", m, m.Type, pb.MetricMetadata_TYPE_UINT64)\n}\nif !m.Cumulative {\nt.Errorf(\"Metadata %+v Cumulative got false want true\", m)\n@@ -110,6 +110,9 @@ func TestInitialize(t *testing.T) {\nif m.Sync {\nt.Errorf(\"/foo %+v Sync got true want false\", m)\n}\n+ if m.Units != pb.MetricMetadata_UNITS_NONE {\n+ t.Errorf(\"/foo %+v Units got %v want %v\", m, m.Units, pb.MetricMetadata_UNITS_NONE)\n+ }\ncase \"/bar\":\nfoundBar = true\nif m.Description != barDescription {\n@@ -118,6 +121,9 @@ func TestInitialize(t *testing.T) {\nif !m.Sync {\nt.Errorf(\"/bar %+v Sync got true want false\", m)\n}\n+ if m.Units != pb.MetricMetadata_UNITS_NANOSECONDS {\n+ t.Errorf(\"/bar %+v Units got %v want %v\", m, m.Units, pb.MetricMetadata_UNITS_NANOSECONDS)\n+ }\n}\n}\n@@ -132,12 +138,12 @@ func TestInitialize(t *testing.T) {\nfunc TestDisable(t *testing.T) {\ndefer reset()\n- _, err := NewUint64Metric(\"/foo\", false, fooDescription)\n+ _, err := NewUint64Metric(\"/foo\", false, pb.MetricMetadata_UNITS_NONE, fooDescription)\nif err != nil {\nt.Fatalf(\"NewUint64Metric got err %v want nil\", err)\n}\n- _, err = NewUint64Metric(\"/bar\", true, barDescription)\n+ _, err = NewUint64Metric(\"/bar\", true, pb.MetricMetadata_UNITS_NONE, barDescription)\nif err != nil {\nt.Fatalf(\"NewUint64Metric got err %v want nil\", err)\n}\n@@ -161,12 +167,12 @@ func TestDisable(t *testing.T) {\nfunc TestEmitMetricUpdate(t *testing.T) {\ndefer reset()\n- foo, err := NewUint64Metric(\"/foo\", false, fooDescription)\n+ foo, err := NewUint64Metric(\"/foo\", false, pb.MetricMetadata_UNITS_NONE, fooDescription)\nif err != nil {\nt.Fatalf(\"NewUint64Metric got err %v want nil\", err)\n}\n- _, err = NewUint64Metric(\"/bar\", true, barDescription)\n+ _, err = NewUint64Metric(\"/bar\", true, pb.MetricMetadata_UNITS_NONE, barDescription)\nif err != nil {\nt.Fatalf(\"NewUint64Metric got err %v want nil\", err)\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/file.go", "new_path": "pkg/sentry/fs/file.go", "diff": "@@ -44,7 +44,7 @@ var (\nRecordWaitTime = false\nreads = metric.MustCreateNewUint64Metric(\"/fs/reads\", false /* sync */, \"Number of file reads.\")\n- readWait = metric.MustCreateNewUint64Metric(\"/fs/read_wait\", false /* sync */, \"Time waiting on file reads, in nanoseconds.\")\n+ readWait = metric.MustCreateNewUint64NanosecondsMetric(\"/fs/read_wait\", false /* sync */, \"Time waiting on file reads, in nanoseconds.\")\n)\n// IncrementWait increments the given wait time metric, if enabled.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/gofer/file.go", "new_path": "pkg/sentry/fs/gofer/file.go", "diff": "@@ -37,9 +37,9 @@ var (\nopens9P = metric.MustCreateNewUint64Metric(\"/gofer/opens_9p\", false /* sync */, \"Number of times a 9P file was opened from a gofer.\")\nopensHost = metric.MustCreateNewUint64Metric(\"/gofer/opens_host\", false /* sync */, \"Number of times a host file was opened from a gofer.\")\nreads9P = metric.MustCreateNewUint64Metric(\"/gofer/reads_9p\", false /* sync */, \"Number of 9P file reads from a gofer.\")\n- readWait9P = metric.MustCreateNewUint64Metric(\"/gofer/read_wait_9p\", false /* sync */, \"Time waiting on 9P file reads from a gofer, in nanoseconds.\")\n+ readWait9P = metric.MustCreateNewUint64NanosecondsMetric(\"/gofer/read_wait_9p\", false /* sync */, \"Time waiting on 9P file reads from a gofer, in nanoseconds.\")\nreadsHost = metric.MustCreateNewUint64Metric(\"/gofer/reads_host\", false /* sync */, \"Number of host file reads from a gofer.\")\n- readWaitHost = metric.MustCreateNewUint64Metric(\"/gofer/read_wait_host\", false /* sync */, \"Time waiting on host file reads from a gofer, in nanoseconds.\")\n+ readWaitHost = metric.MustCreateNewUint64NanosecondsMetric(\"/gofer/read_wait_host\", false /* sync */, \"Time waiting on host file reads from a gofer, in nanoseconds.\")\n)\n// fileOperations implements fs.FileOperations for a remote file system.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/tmpfs/inode_file.go", "new_path": "pkg/sentry/fs/tmpfs/inode_file.go", "diff": "@@ -39,7 +39,7 @@ var (\nopensRO = metric.MustCreateNewUint64Metric(\"/in_memory_file/opens_ro\", false /* sync */, \"Number of times an in-memory file was opened in read-only mode.\")\nopensW = metric.MustCreateNewUint64Metric(\"/in_memory_file/opens_w\", false /* sync */, \"Number of times an in-memory file was opened in write mode.\")\nreads = metric.MustCreateNewUint64Metric(\"/in_memory_file/reads\", false /* sync */, \"Number of in-memory file reads.\")\n- readWait = metric.MustCreateNewUint64Metric(\"/in_memory_file/read_wait\", false /* sync */, \"Time waiting on in-memory file reads, in nanoseconds.\")\n+ readWait = metric.MustCreateNewUint64NanosecondsMetric(\"/in_memory_file/read_wait\", false /* sync */, \"Time waiting on in-memory file reads, in nanoseconds.\")\n)\n// fileInodeOperations implements fs.InodeOperations for a regular tmpfs file.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netstack/netstack.go", "new_path": "pkg/sentry/socket/netstack/netstack.go", "diff": "@@ -63,7 +63,13 @@ import (\nfunc mustCreateMetric(name, description string) *tcpip.StatCounter {\nvar cm tcpip.StatCounter\n- metric.MustRegisterCustomUint64Metric(name, false /* sync */, description, cm.Value)\n+ metric.MustRegisterCustomUint64Metric(name, true /* cumulative */, false /* sync */, description, cm.Value)\n+ return &cm\n+}\n+\n+func mustCreateGauge(name, description string) *tcpip.StatCounter {\n+ var cm tcpip.StatCounter\n+ metric.MustRegisterCustomUint64Metric(name, false /* cumulative */, false /* sync */, description, cm.Value)\nreturn &cm\n}\n@@ -151,10 +157,10 @@ var Metrics = tcpip.Stats{\nTCP: tcpip.TCPStats{\nActiveConnectionOpenings: mustCreateMetric(\"/netstack/tcp/active_connection_openings\", \"Number of connections opened successfully via Connect.\"),\nPassiveConnectionOpenings: mustCreateMetric(\"/netstack/tcp/passive_connection_openings\", \"Number of connections opened successfully via Listen.\"),\n- CurrentEstablished: mustCreateMetric(\"/netstack/tcp/current_established\", \"Number of connections in ESTABLISHED state now.\"),\n- CurrentConnected: mustCreateMetric(\"/netstack/tcp/current_open\", \"Number of connections that are in connected state.\"),\n+ CurrentEstablished: mustCreateGauge(\"/netstack/tcp/current_established\", \"Number of connections in ESTABLISHED state now.\"),\n+ CurrentConnected: mustCreateGauge(\"/netstack/tcp/current_open\", \"Number of connections that are in connected state.\"),\nEstablishedResets: mustCreateMetric(\"/netstack/tcp/established_resets\", \"Number of times TCP connections have made a direct transition to the CLOSED state from either the ESTABLISHED state or the CLOSE-WAIT state\"),\n- EstablishedClosed: mustCreateMetric(\"/netstack/tcp/established_closed\", \"number of times established TCP connections made a transition to CLOSED state.\"),\n+ EstablishedClosed: mustCreateMetric(\"/netstack/tcp/established_closed\", \"Number of times established TCP connections made a transition to CLOSED state.\"),\nEstablishedTimedout: mustCreateMetric(\"/netstack/tcp/established_timedout\", \"Number of times an established connection was reset because of keep-alive time out.\"),\nListenOverflowSynDrop: mustCreateMetric(\"/netstack/tcp/listen_overflow_syn_drop\", \"Number of times the listen queue overflowed and a SYN was dropped.\"),\nListenOverflowAckDrop: mustCreateMetric(\"/netstack/tcp/listen_overflow_ack_drop\", \"Number of times the listen queue overflowed and the final ACK in the handshake was dropped.\"),\n" } ]
Go
Apache License 2.0
google/gvisor
Sentry metrics updates. Sentry metrics with nanoseconds units are labeled as such, and non-cumulative sentry metrics are supported. PiperOrigin-RevId: 307621080
259,891
21.04.2020 10:56:04
25,200
639c8dd80870133f61465588e717b725417a0c41
Restore euid upon test finish
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/uidgid.cc", "new_path": "test/syscalls/linux/uidgid.cc", "diff": "@@ -253,12 +253,21 @@ TEST(UidGidRootTest, Setgroups) {\nTEST(UidGidRootTest, Setuid_prlimit) {\nSKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(IsRoot()));\n- // Change our UID.\n- EXPECT_THAT(seteuid(65534), SyscallSucceeds());\n+ // Do seteuid in a separate thread so that after finishing this test, the\n+ // process can still open files the test harness created before starting this\n+ // test. Otherwise, the files are created by root (UID before the test), but\n+ // cannot be opened by the `uid` set below after the test.\n+ ScopedThread([&] {\n+ // Use syscall instead of glibc setuid wrapper because we want this seteuid\n+ // call to only apply to this task. POSIX threads, however, require that all\n+ // threads have the same UIDs, so using the seteuid wrapper sets all\n+ // threads' UID.\n+ EXPECT_THAT(syscall(SYS_setreuid, -1, 65534), SyscallSucceeds());\n// Despite the UID change, we should be able to get our own limits.\nstruct rlimit rl = {};\n- ASSERT_THAT(prlimit(0, RLIMIT_NOFILE, NULL, &rl), SyscallSucceeds());\n+ EXPECT_THAT(prlimit(0, RLIMIT_NOFILE, NULL, &rl), SyscallSucceeds());\n+ });\n}\n} // namespace\n" } ]
Go
Apache License 2.0
google/gvisor
Restore euid upon test finish PiperOrigin-RevId: 307638329
259,881
21.04.2020 15:52:42
14,400
a4711053672ae6732583f4eae54596783ec47547
benchmarks: use absolute bazel target bazel run :benchmarks only works from the benchmarks directory. bazel run //benchmarks works from anywhere in the workspace. Also fix help commands, which should be a multiline code section.
[ { "change_type": "MODIFY", "old_path": "benchmarks/README.md", "new_path": "benchmarks/README.md", "diff": "@@ -10,7 +10,7 @@ The scripts assume the following:\n(controller) and one or more machines on which docker containers will be run\n(environment).\n* The controller machine must have bazel installed along with this source\n- code. You should be able to run a command like `bazel run :benchmarks --\n+ code. You should be able to run a command like `bazel run //benchmarks --\n--list`\n* Environment machines must have docker and the required runtimes installed.\nMore specifically, you should be able to run a command like: `docker run\n@@ -33,7 +33,7 @@ but it does support GCP workflows. To run locally, run the following from the\nbenchmarks directory:\n```bash\n-bazel run --define gcloud=off :benchmarks -- run-local startup\n+bazel run --define gcloud=off //benchmarks -- run-local startup\n...\nmethod,metric,result\n@@ -48,16 +48,20 @@ runtime, runc. Running on another installed runtime, like say runsc, is as\nsimple as:\n```bash\n-bazel run --define gcloud=off :benchmarks -- run-local startup --runtime=runsc\n+bazel run --define gcloud=off //benchmarks -- run-local startup --runtime=runsc\n```\n-There is help: `bash bazel run --define gcloud=off :benchmarks -- --help bazel\n-run --define gcloud=off :benchmarks -- run-local --help`\n+There is help:\n+\n+```bash\n+bazel run --define gcloud=off //benchmarks -- --help\n+bazel run --define gcloud=off //benchmarks -- run-local --help\n+```\nTo list available benchmarks, use the `list` commmand:\n```bash\n-bazel --define gcloud=off run :benchmarks -- list\n+bazel --define gcloud=off run //benchmarks -- list\n...\nBenchmark: sysbench.cpu\n@@ -70,7 +74,7 @@ Metrics: events_per_second\nYou can choose benchmarks by name or regex like:\n```bash\n-bazel run --define gcloud=off :benchmarks -- run-local startup.node\n+bazel run --define gcloud=off //benchmarks -- run-local startup.node\n...\nmetric,result\nstartup_time_ms,1671.7178000000001\n@@ -80,7 +84,7 @@ startup_time_ms,1671.7178000000001\nor\n```bash\n-bazel run --define gcloud=off :benchmarks -- run-local s\n+bazel run --define gcloud=off //benchmarks -- run-local s\n...\nmethod,metric,result\nstartup.empty,startup_time_ms,1792.8292\n@@ -98,13 +102,13 @@ You can run parameterized benchmarks, for example to run with different\nruntimes:\n```bash\n-bazel run --define gcloud=off :benchmarks -- run-local --runtime=runc --runtime=runsc sysbench.cpu\n+bazel run --define gcloud=off //benchmarks -- run-local --runtime=runc --runtime=runsc sysbench.cpu\n```\nOr with different parameters:\n```bash\n-bazel run --define gcloud=off :benchmarks -- run-local --max_prime=10 --max_prime=100 sysbench.cpu\n+bazel run --define gcloud=off //benchmarks -- run-local --max_prime=10 --max_prime=100 sysbench.cpu\n```\n### On Google Compute Engine (GCE)\n@@ -117,7 +121,7 @@ runtime is installed from the workspace. See the files in `tools/installers` for\nsupported install targets.\n```bash\n-bazel run :benchmarks -- run-gcp --installers=head --runtime=runsc sysbench.cpu\n+bazel run //benchmarks -- run-gcp --installers=head --runtime=runsc sysbench.cpu\n```\nWhen running on GCE, the scripts generate a per run SSH key, which is added to\n" } ]
Go
Apache License 2.0
google/gvisor
benchmarks: use absolute bazel target bazel run :benchmarks only works from the benchmarks directory. bazel run //benchmarks works from anywhere in the workspace. Also fix help commands, which should be a multiline code section.
259,858
21.04.2020 13:12:38
25,200
89822a446161f1ccb3b84d53f8528bc8b0a28053
Move to GitHub's new issue templates. This allows us to specify a richer configuration for the issue template, that effectively moves a lot of the "metadata" from the template itself to the main issue page.
[ { "change_type": "ADD", "old_path": null, "new_path": ".github/ISSUE_TEMPLATE/bug_report.md", "diff": "+---\n+name: Bug report\n+about: Create a bug report to help us improve\n+title:\n+labels:\n+ - 'type: bug'\n+assignees: ''\n+---\n+\n+**Description**\n+\n+A clear description of what the bug is. If possible, explicitly indicate the\n+expected behavior vs. the observed behavior.\n+\n+**Steps to reproduce**\n+\n+If available, please include detailed reproduction steps.\n+\n+If the bug requires software that is not publicly available, see if it can be\n+reproduced with software that is publicly available.\n+\n+**Environment**\n+\n+Please include the following details of your environment:\n+\n+* `runsc -v`\n+* `docker version` or `docker info` (if available)\n+* `kubectl version` and `kubectl get nodes` (if using Kubernetes)\n+* `uname -a`\n+* `git describe` (if built from source)\n+* `runsc` debug logs (if available)\n" }, { "change_type": "ADD", "old_path": null, "new_path": ".github/ISSUE_TEMPLATE/config.yml", "diff": "+blank_issues_enabled: false\n+contact_links:\n+ - name: gVisor Documentation (FAQ)\n+ url: https://gvisor.dev/docs/user_guide/faq/\n+ about: Please see our documentation for common questions and answers.\n+ - name: gVisor Documentation (Debugging)\n+ url: https://gvisor.dev/docs/user_guide/debugging/\n+ about: Please see our documentation for debugging tips.\n+ - name: gVisor User Forum\n+ url: https://groups.google.com/g/gvisor-users\n+ about: Please ask and answer questions here.\n+ - name: gVisor Security List\n+ url: https://github.com/google/gvisor/blob/master/SECURITY.md\n+ about: Please report security vulnerabilities using the process described here.\n" }, { "change_type": "ADD", "old_path": null, "new_path": ".github/ISSUE_TEMPLATE/feature_request.md", "diff": "+---\n+name: Feature request\n+about: Suggest an idea or improvement\n+title: ''\n+labels:\n+ - 'type: enhancement'\n+assignees: ''\n+---\n+\n+**Description**\n+\n+A clear description of the feature or enhancement.\n+\n+**Is this feature related to a specific bug?**\n+\n+Please include a bug references if yes.\n+\n+**Do you have a specific solution in mind?**\n+\n+Please include any details about a solution that you have in mind, including any\n+alternatives considered.\n" }, { "change_type": "DELETE", "old_path": ".github/issue_template.md", "new_path": null, "diff": "-Before filling an issue, please consult our FAQ:\n-https://gvisor.dev/docs/user_guide/faq/\n-\n-Also check that the issue hasn't been reported before.\n-\n-If you have a question, please email [email protected] rather than filing a bug.\n-\n-If you believe you've found a security issue, please email [email protected] rather than filing a bug.\n-\n-If this is your first time compiling or running gVisor, please make sure that your system meets the minimum requirements: https://github.com/google/gvisor#requirements\n-\n-For all other issues, please attach debug logs. To get debug logs, follow the\n-instructions here: https://gvisor.dev/docs/user_guide/debugging/\n-\n-Other useful information to include is:\n-\n-* `runsc -v`\n-* `docker version` or `docker info` if more relevant\n-* `uname -a` - `git describe`\n-* Detailed reproduction steps\n" } ]
Go
Apache License 2.0
google/gvisor
Move to GitHub's new issue templates. This allows us to specify a richer configuration for the issue template, that effectively moves a lot of the "metadata" from the template itself to the main issue page. PiperOrigin-RevId: 307666509
259,992
21.04.2020 16:30:26
25,200
37e01fd2ea6a0e67637975863317be9aae1b02f0
Misc VFS2 fixes Fix defer operation ordering in kernfs.Filesystem.AccessAt() Add AT_NULL entry in proc/pid/auvx Fix line padding in /proc/pid/maps Fix linux_dirent serialization for getdents(2) Remove file creation flags from vfs.FileDescription.statusFlags() Updates
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/proc/task.go", "new_path": "pkg/sentry/fs/proc/task.go", "diff": "@@ -74,7 +74,6 @@ type taskDir struct {\nramfs.Dir\nt *kernel.Task\n- pidns *kernel.PIDNamespace\n}\nvar _ fs.InodeOperations = (*taskDir)(nil)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/kernfs/filesystem.go", "new_path": "pkg/sentry/fsimpl/kernfs/filesystem.go", "diff": "@@ -246,8 +246,8 @@ func (fs *Filesystem) Sync(ctx context.Context) error {\n// AccessAt implements vfs.Filesystem.Impl.AccessAt.\nfunc (fs *Filesystem) AccessAt(ctx context.Context, rp *vfs.ResolvingPath, creds *auth.Credentials, ats vfs.AccessTypes) error {\nfs.mu.RLock()\n- defer fs.mu.RUnlock()\ndefer fs.processDeferredDecRefs()\n+ defer fs.mu.RUnlock()\n_, inode, err := fs.walkExistingLocked(ctx, rp)\nif err != nil {\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/proc/task_files.go", "new_path": "pkg/sentry/fsimpl/proc/task_files.go", "diff": "@@ -111,17 +111,18 @@ func (d *auxvData) Generate(ctx context.Context, buf *bytes.Buffer) error {\n}\ndefer m.DecUsers(ctx)\n- // Space for buffer with AT_NULL (0) terminator at the end.\nauxv := m.Auxv()\n+ // Space for buffer with AT_NULL (0) terminator at the end.\nbuf.Grow((len(auxv) + 1) * 16)\nfor _, e := range auxv {\n- var tmp [8]byte\n- usermem.ByteOrder.PutUint64(tmp[:], e.Key)\n- buf.Write(tmp[:])\n-\n- usermem.ByteOrder.PutUint64(tmp[:], uint64(e.Value))\n+ var tmp [16]byte\n+ usermem.ByteOrder.PutUint64(tmp[:8], e.Key)\n+ usermem.ByteOrder.PutUint64(tmp[8:], uint64(e.Value))\nbuf.Write(tmp[:])\n}\n+ var atNull [16]byte\n+ buf.Write(atNull[:])\n+\nreturn nil\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/proc/tasks_sys.go", "new_path": "pkg/sentry/fsimpl/proc/tasks_sys.go", "diff": "@@ -39,7 +39,7 @@ func newSysDir(root *auth.Credentials, inoGen InoGenerator, k *kernel.Kernel) *k\n\"shmmni\": newDentry(root, inoGen.NextIno(), 0444, shmData(linux.SHMMNI)),\n}),\n\"vm\": kernfs.NewStaticDir(root, inoGen.NextIno(), 0555, map[string]*kernfs.Dentry{\n- \"mmap_min_addr\": newDentry(root, inoGen.NextIno(), 0444, &mmapMinAddrData{}),\n+ \"mmap_min_addr\": newDentry(root, inoGen.NextIno(), 0444, &mmapMinAddrData{k: k}),\n\"overcommit_memory\": newDentry(root, inoGen.NextIno(), 0444, newStaticFile(\"0\\n\")),\n}),\n\"net\": newSysNetDir(root, inoGen, k),\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/mm/procfs.go", "new_path": "pkg/sentry/mm/procfs.go", "diff": "@@ -148,7 +148,7 @@ func (mm *MemoryManager) appendVMAMapsEntryLocked(ctx context.Context, vseg vmaI\n// Do not include the guard page: fs/proc/task_mmu.c:show_map_vma() =>\n// stack_guard_page_start().\n- fmt.Fprintf(b, \"%08x-%08x %s%s %08x %02x:%02x %d \",\n+ lineLen, _ := fmt.Fprintf(b, \"%08x-%08x %s%s %08x %02x:%02x %d \",\nvseg.Start(), vseg.End(), vma.realPerms, private, vma.off, devMajor, devMinor, ino)\n// Figure out our filename or hint.\n@@ -165,7 +165,7 @@ func (mm *MemoryManager) appendVMAMapsEntryLocked(ctx context.Context, vseg vmaI\n}\nif s != \"\" {\n// Per linux, we pad until the 74th character.\n- if pad := 73 - b.Len(); pad > 0 {\n+ if pad := 73 - lineLen; pad > 0 {\nb.WriteString(strings.Repeat(\" \", pad))\n}\nb.WriteString(s)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/vfs2/getdents.go", "new_path": "pkg/sentry/syscalls/linux/vfs2/getdents.go", "diff": "@@ -130,7 +130,7 @@ func (cb *getdentsCallback) Handle(dirent vfs.Dirent) error {\nif cb.t.Arch().Width() != 8 {\npanic(fmt.Sprintf(\"unsupported sizeof(unsigned long): %d\", cb.t.Arch().Width()))\n}\n- size := 8 + 8 + 2 + 1 + 1 + 1 + len(dirent.Name)\n+ size := 8 + 8 + 2 + 1 + 1 + len(dirent.Name)\nsize = (size + 7) &^ 7 // round up to multiple of sizeof(long)\nif size > cb.remaining {\nreturn syserror.EINVAL\n@@ -143,11 +143,11 @@ func (cb *getdentsCallback) Handle(dirent vfs.Dirent) error {\n// Zero out all remaining bytes in buf, including the NUL terminator\n// after dirent.Name and the zero padding byte between the name and\n// dirent type.\n- bufTail := buf[18+len(dirent.Name):]\n+ bufTail := buf[18+len(dirent.Name) : size-1]\nfor i := range bufTail {\nbufTail[i] = 0\n}\n- bufTail[2] = dirent.Type\n+ buf[size-1] = dirent.Type\n}\nn, err := cb.t.CopyOutBytes(cb.addr, buf)\nif err != nil {\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/file_description.go", "new_path": "pkg/sentry/vfs/file_description.go", "diff": "@@ -111,10 +111,10 @@ type FileDescriptionOptions struct {\n}\n// Init must be called before first use of fd. If it succeeds, it takes\n-// references on mnt and d. statusFlags is the initial file description status\n-// flags, which is usually the full set of flags passed to open(2).\n-func (fd *FileDescription) Init(impl FileDescriptionImpl, statusFlags uint32, mnt *Mount, d *Dentry, opts *FileDescriptionOptions) error {\n- writable := MayWriteFileWithOpenFlags(statusFlags)\n+// references on mnt and d. flags is the initial file description flags, which\n+// is usually the full set of flags passed to open(2).\n+func (fd *FileDescription) Init(impl FileDescriptionImpl, flags uint32, mnt *Mount, d *Dentry, opts *FileDescriptionOptions) error {\n+ writable := MayWriteFileWithOpenFlags(flags)\nif writable {\nif err := mnt.CheckBeginWrite(); err != nil {\nreturn err\n@@ -122,7 +122,10 @@ func (fd *FileDescription) Init(impl FileDescriptionImpl, statusFlags uint32, mn\n}\nfd.refs = 1\n- fd.statusFlags = statusFlags\n+\n+ // Remove \"file creation flags\" to mirror the behavior from file.f_flags in\n+ // fs/open.c:do_dentry_open\n+ fd.statusFlags = flags &^ (linux.O_CREAT | linux.O_EXCL | linux.O_NOCTTY | linux.O_TRUNC)\nfd.vd = VirtualDentry{\nmount: mnt,\ndentry: d,\n@@ -130,7 +133,7 @@ func (fd *FileDescription) Init(impl FileDescriptionImpl, statusFlags uint32, mn\nmnt.IncRef()\nd.IncRef()\nfd.opts = *opts\n- fd.readable = MayReadFileWithOpenFlags(statusFlags)\n+ fd.readable = MayReadFileWithOpenFlags(flags)\nfd.writable = writable\nfd.impl = impl\nreturn nil\n" } ]
Go
Apache License 2.0
google/gvisor
Misc VFS2 fixes - Fix defer operation ordering in kernfs.Filesystem.AccessAt() - Add AT_NULL entry in proc/pid/auvx - Fix line padding in /proc/pid/maps - Fix linux_dirent serialization for getdents(2) - Remove file creation flags from vfs.FileDescription.statusFlags() Updates #1193, #1035 PiperOrigin-RevId: 307704159
259,860
21.04.2020 17:58:43
25,200
80d0a958199cc6095e2d580e403d50ac1c3b5206
Update gofer.filesystem.BoundEndpointAt() to allow path resolution. Even though BoundEndpointAt is not yet implemented for gofer fs, allow path resolution errors to be returned so that we can jump to tmpfs, where it is implemented. Updates
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/gofer/filesystem.go", "new_path": "pkg/sentry/fsimpl/gofer/filesystem.go", "diff": "@@ -1089,9 +1089,15 @@ func (fs *filesystem) UnlinkAt(ctx context.Context, rp *vfs.ResolvingPath) error\n}\n// BoundEndpointAt implements FilesystemImpl.BoundEndpointAt.\n-//\n-// TODO(gvisor.dev/issue/1476): Implement BoundEndpointAt.\nfunc (fs *filesystem) BoundEndpointAt(ctx context.Context, rp *vfs.ResolvingPath) (transport.BoundEndpoint, error) {\n+ var ds *[]*dentry\n+ fs.renameMu.RLock()\n+ defer fs.renameMuRUnlockAndCheckCaching(&ds)\n+ _, err := fs.resolveLocked(ctx, rp, &ds)\n+ if err != nil {\n+ return nil, err\n+ }\n+ // TODO(gvisor.dev/issue/1476): Implement BoundEndpointAt.\nreturn nil, syserror.ECONNREFUSED\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Update gofer.filesystem.BoundEndpointAt() to allow path resolution. Even though BoundEndpointAt is not yet implemented for gofer fs, allow path resolution errors to be returned so that we can jump to tmpfs, where it is implemented. Updates #1476. PiperOrigin-RevId: 307718335
259,860
21.04.2020 19:01:51
25,200
5e3596a6b8abb4c7ee8253be447b86a7b0fad7ad
Fix set/getsockopt in vfs2 override. Updates
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/vfs2/linux64_override_amd64.go", "new_path": "pkg/sentry/syscalls/linux/vfs2/linux64_override_amd64.go", "diff": "@@ -58,8 +58,8 @@ func Override(table map[uintptr]kernel.Syscall) {\ntable[51] = syscalls.PartiallySupported(\"getsockname\", GetSockName, \"In process of porting socket syscalls to VFS2.\", nil)\ntable[52] = syscalls.PartiallySupported(\"getpeername\", GetPeerName, \"In process of porting socket syscalls to VFS2.\", nil)\ntable[53] = syscalls.PartiallySupported(\"socketpair\", SocketPair, \"In process of porting socket syscalls to VFS2.\", nil)\n- table[54] = syscalls.PartiallySupported(\"getsockopt\", GetSockOpt, \"In process of porting socket syscalls to VFS2.\", nil)\n- table[55] = syscalls.PartiallySupported(\"setsockopt\", SetSockOpt, \"In process of porting socket syscalls to VFS2.\", nil)\n+ table[54] = syscalls.PartiallySupported(\"setsockopt\", SetSockOpt, \"In process of porting socket syscalls to VFS2.\", nil)\n+ table[55] = syscalls.PartiallySupported(\"getsockopt\", GetSockOpt, \"In process of porting socket syscalls to VFS2.\", nil)\ntable[59] = syscalls.Supported(\"execve\", Execve)\ntable[72] = syscalls.Supported(\"fcntl\", Fcntl)\ndelete(table, 73) // flock\n" } ]
Go
Apache License 2.0
google/gvisor
Fix set/getsockopt in vfs2 override. Updates #1476. PiperOrigin-RevId: 307726055
259,972
22.04.2020 07:27:34
25,200
6d23673e10bca2fb573809ff78506fc0566817dd
Add comments about deepcopy in Layer.incoming()
[ { "change_type": "MODIFY", "old_path": "test/packetimpact/testbench/connections.go", "new_path": "test/packetimpact/testbench/connections.go", "diff": "@@ -72,7 +72,8 @@ type layerState interface {\n// incoming creates an expected Layer for comparing against a received Layer.\n// Because the expectation can depend on values in the received Layer, it is\n// an input to incoming. For example, the ACK number needs to be checked in a\n- // TCP packet but only if the ACK flag is set in the received packet.\n+ // TCP packet but only if the ACK flag is set in the received packet. The\n+ // calles takes ownership of the returned Layer.\nincoming(received Layer) Layer\n// sent updates the layerState based on the Layer that was sent. The input is\n@@ -124,6 +125,7 @@ func (s *etherState) outgoing() Layer {\nreturn &s.out\n}\n+// incoming implements layerState.incoming.\nfunc (s *etherState) incoming(Layer) Layer {\nreturn deepcopy.Copy(&s.in).(Layer)\n}\n@@ -168,6 +170,7 @@ func (s *ipv4State) outgoing() Layer {\nreturn &s.out\n}\n+// incoming implements layerState.incoming.\nfunc (s *ipv4State) incoming(Layer) Layer {\nreturn deepcopy.Copy(&s.in).(Layer)\n}\n@@ -234,6 +237,7 @@ func (s *tcpState) outgoing() Layer {\nreturn &newOutgoing\n}\n+// incoming implements layerState.incoming.\nfunc (s *tcpState) incoming(received Layer) Layer {\ntcpReceived, ok := received.(*TCP)\nif !ok {\n@@ -328,6 +332,7 @@ func (s *udpState) outgoing() Layer {\nreturn &s.out\n}\n+// incoming implements layerState.incoming.\nfunc (s *udpState) incoming(Layer) Layer {\nreturn deepcopy.Copy(&s.in).(Layer)\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Add comments about deepcopy in Layer.incoming() PiperOrigin-RevId: 307812340
259,858
22.04.2020 12:11:38
25,200
c31641150d9ee0e4b9c7cf1210c4e89a030a6bd7
Add GitHub pull request template. This just provides some sane reminders and ticks a box on the GitHub UI. This change also cleans up the issue template, as there is already an automatic link to the repository's security disclosure policy.
[ { "change_type": "MODIFY", "old_path": ".github/ISSUE_TEMPLATE/config.yml", "new_path": ".github/ISSUE_TEMPLATE/config.yml", "diff": "@@ -8,7 +8,4 @@ contact_links:\nabout: Please see our documentation for debugging tips.\n- name: gVisor User Forum\nurl: https://groups.google.com/g/gvisor-users\n- about: Please ask and answer questions here.\n- - name: gVisor Security List\n- url: https://github.com/google/gvisor/blob/master/SECURITY.md\n- about: Please report security vulnerabilities using the process described here.\n+ about: Ask and answer general questions here.\n" }, { "change_type": "ADD", "old_path": null, "new_path": ".github/pull_request_template.md", "diff": "+* [ ] Have you followed the guidelines in [CONTRIBUTING.md](../blob/master/CONTRIBUTING.md)?\n+* [ ] Have you formatted and linted your code?\n+* [ ] Have you added relevant tests?\n+* [ ] Have you added appropriate Fixes & Updates references?\n+* [ ] If yes, please erase all these lines!\n" } ]
Go
Apache License 2.0
google/gvisor
Add GitHub pull request template. This just provides some sane reminders and ticks a box on the GitHub UI. This change also cleans up the issue template, as there is already an automatic link to the repository's security disclosure policy. PiperOrigin-RevId: 307868833
259,853
22.04.2020 14:15:33
25,200
37f863f62813f76b05979494c1bc2fe102629321
tcp: handle listen after shutdown properly Right now, sentry panics in this case: panic: close of nil channel goroutine 67 [running]: pkg/tcpip/transport/tcp/tcp.(*endpoint).listen(0xc0000ce000, 0x9, 0x0) pkg/tcpip/transport/tcp/endpoint.go:2208 +0x170 pkg/tcpip/transport/tcp/tcp.(*endpoint).Listen(0xc0000ce000, 0x9, 0xc0003a1ad0) pkg/tcpip/transport/tcp/endpoint.go:2179 +0x50 Fixes
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/endpoint.go", "new_path": "pkg/tcpip/transport/tcp/endpoint.go", "diff": "@@ -2158,8 +2158,6 @@ func (e *endpoint) shutdownLocked(flags tcpip.ShutdownFlags) *tcpip.Error {\n//\n// By not removing this endpoint from the demuxer mapping, we\n// ensure that any other bind to the same port fails, as on Linux.\n- // TODO(gvisor.dev/issue/2468): We need to enable applications to\n- // start listening on this endpoint again similar to Linux.\ne.rcvListMu.Lock()\ne.rcvClosed = true\ne.rcvListMu.Unlock()\n@@ -2188,15 +2186,19 @@ func (e *endpoint) listen(backlog int) *tcpip.Error {\ne.LockUser()\ndefer e.UnlockUser()\n- // Allow the backlog to be adjusted if the endpoint is not shutting down.\n- // When the endpoint shuts down, it sets workerCleanup to true, and from\n- // that point onward, acceptedChan is the responsibility of the cleanup()\n- // method (and should not be touched anywhere else, including here).\n- if e.EndpointState() == StateListen && !e.workerCleanup {\n- // Adjust the size of the channel iff we can fix existing\n- // pending connections into the new one.\n+ if e.EndpointState() == StateListen && !e.closed {\ne.acceptMu.Lock()\ndefer e.acceptMu.Unlock()\n+ if e.acceptedChan == nil {\n+ // listen is called after shutdown.\n+ e.acceptedChan = make(chan *endpoint, backlog)\n+ e.shutdownFlags = 0\n+ e.rcvListMu.Lock()\n+ e.rcvClosed = false\n+ e.rcvListMu.Unlock()\n+ } else {\n+ // Adjust the size of the channel iff we can fix\n+ // existing pending connections into the new one.\nif len(e.acceptedChan) > backlog {\nreturn tcpip.ErrInvalidEndpointState\n}\n@@ -2209,6 +2211,7 @@ func (e *endpoint) listen(backlog int) *tcpip.Error {\nfor ep := range origChan {\ne.acceptedChan <- ep\n}\n+ }\n// Notify any blocked goroutines that they can attempt to\n// deliver endpoints again.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/endpoint_state.go", "new_path": "pkg/tcpip/transport/tcp/endpoint_state.go", "diff": "@@ -247,6 +247,11 @@ func (e *endpoint) Resume(s *stack.Stack) {\nif err := e.Listen(backlog); err != nil {\npanic(\"endpoint listening failed: \" + err.String())\n}\n+ e.LockUser()\n+ if e.shutdownFlags != 0 {\n+ e.shutdownLocked(e.shutdownFlags)\n+ }\n+ e.UnlockUser()\nlistenLoading.Done()\ntcpip.AsyncLoading.Done()\n}()\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_inet_loopback.cc", "new_path": "test/syscalls/linux/socket_inet_loopback.cc", "diff": "@@ -319,6 +319,49 @@ TEST_P(SocketInetLoopbackTest, TCPListenUnbound) {\ntcpSimpleConnectTest(listener, connector, false);\n}\n+TEST_P(SocketInetLoopbackTest, TCPListenShutdownListen) {\n+ const auto& param = GetParam();\n+\n+ const TestAddress& listener = param.listener;\n+ const TestAddress& connector = param.connector;\n+\n+ constexpr int kBacklog = 5;\n+\n+ // Create the listening socket.\n+ FileDescriptor listen_fd = ASSERT_NO_ERRNO_AND_VALUE(\n+ Socket(listener.family(), SOCK_STREAM, IPPROTO_TCP));\n+ sockaddr_storage listen_addr = listener.addr;\n+ ASSERT_THAT(bind(listen_fd.get(), reinterpret_cast<sockaddr*>(&listen_addr),\n+ listener.addr_len),\n+ SyscallSucceeds());\n+\n+ ASSERT_THAT(listen(listen_fd.get(), kBacklog), SyscallSucceeds());\n+ ASSERT_THAT(shutdown(listen_fd.get(), SHUT_RD), SyscallSucceeds());\n+ ASSERT_THAT(listen(listen_fd.get(), kBacklog), SyscallSucceeds());\n+\n+ // Get the port bound by the listening socket.\n+ socklen_t addrlen = listener.addr_len;\n+ ASSERT_THAT(getsockname(listen_fd.get(),\n+ reinterpret_cast<sockaddr*>(&listen_addr), &addrlen),\n+ SyscallSucceeds());\n+ const uint16_t port =\n+ ASSERT_NO_ERRNO_AND_VALUE(AddrPort(listener.family(), listen_addr));\n+\n+ sockaddr_storage conn_addr = connector.addr;\n+ ASSERT_NO_ERRNO(SetAddrPort(connector.family(), &conn_addr, port));\n+\n+ for (int i = 0; i < kBacklog; i++) {\n+ auto client = ASSERT_NO_ERRNO_AND_VALUE(\n+ Socket(connector.family(), SOCK_STREAM, IPPROTO_TCP));\n+ ASSERT_THAT(connect(client.get(), reinterpret_cast<sockaddr*>(&conn_addr),\n+ connector.addr_len),\n+ SyscallSucceeds());\n+ }\n+ for (int i = 0; i < kBacklog; i++) {\n+ ASSERT_THAT(accept(listen_fd.get(), nullptr, nullptr), SyscallSucceeds());\n+ }\n+}\n+\nTEST_P(SocketInetLoopbackTest, TCPListenShutdown) {\nauto const& param = GetParam();\n" } ]
Go
Apache License 2.0
google/gvisor
tcp: handle listen after shutdown properly Right now, sentry panics in this case: panic: close of nil channel goroutine 67 [running]: pkg/tcpip/transport/tcp/tcp.(*endpoint).listen(0xc0000ce000, 0x9, 0x0) pkg/tcpip/transport/tcp/endpoint.go:2208 +0x170 pkg/tcpip/transport/tcp/tcp.(*endpoint).Listen(0xc0000ce000, 0x9, 0xc0003a1ad0) pkg/tcpip/transport/tcp/endpoint.go:2179 +0x50 Fixes #2468 PiperOrigin-RevId: 307896725
259,853
22.04.2020 17:48:59
25,200
0c586946ea26610b87c4ff7bda783a5a9ca11ec0
Specify a memory file in platform.New().
[ { "change_type": "MODIFY", "old_path": "pkg/abi/linux/BUILD", "new_path": "pkg/abi/linux/BUILD", "diff": "@@ -10,6 +10,7 @@ go_library(\nname = \"linux\",\nsrcs = [\n\"aio.go\",\n+ \"arch_amd64.go\",\n\"audit.go\",\n\"bpf.go\",\n\"capability.go\",\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/abi/linux/arch_amd64.go", "diff": "+// Copyright 2020 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+// +build amd64\n+\n+package linux\n+\n+// Start and end addresses of the vsyscall page.\n+const (\n+ VSyscallStartAddr uint64 = 0xffffffffff600000\n+ VSyscallEndAddr uint64 = 0xffffffffff601000\n+)\n" }, { "change_type": "MODIFY", "old_path": "pkg/abi/linux/seccomp.go", "new_path": "pkg/abi/linux/seccomp.go", "diff": "@@ -63,3 +63,10 @@ func (a BPFAction) String() string {\nfunc (a BPFAction) Data() uint16 {\nreturn uint16(a & SECCOMP_RET_DATA)\n}\n+\n+// SockFprog is sock_fprog taken from <linux/filter.h>.\n+type SockFprog struct {\n+ Len uint16\n+ pad [6]byte\n+ Filter *BPFInstruction\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/flipcall/packet_window_allocator.go", "new_path": "pkg/flipcall/packet_window_allocator.go", "diff": "@@ -134,7 +134,7 @@ func (pwa *PacketWindowAllocator) Allocate(size int) (PacketWindowDescriptor, er\nstart := pwa.nextAlloc\npwa.nextAlloc = end\nreturn PacketWindowDescriptor{\n- FD: pwa.fd,\n+ FD: pwa.FD(),\nOffset: start,\nLength: size,\n}, nil\n@@ -158,7 +158,7 @@ func (pwa *PacketWindowAllocator) ensureFileSize(min int64) error {\n}\nnewSize = newNewSize\n}\n- if err := syscall.Ftruncate(pwa.fd, newSize); err != nil {\n+ if err := syscall.Ftruncate(pwa.FD(), newSize); err != nil {\nreturn fmt.Errorf(\"ftruncate failed: %v\", err)\n}\npwa.fileSize = newSize\n" }, { "change_type": "MODIFY", "old_path": "pkg/seccomp/seccomp_unsafe.go", "new_path": "pkg/seccomp/seccomp_unsafe.go", "diff": "@@ -21,13 +21,6 @@ import (\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n)\n-// sockFprog is sock_fprog taken from <linux/filter.h>.\n-type sockFprog struct {\n- Len uint16\n- pad [6]byte\n- Filter *linux.BPFInstruction\n-}\n-\n// SetFilter installs the given BPF program.\n//\n// This is safe to call from an afterFork context.\n@@ -39,7 +32,7 @@ func SetFilter(instrs []linux.BPFInstruction) syscall.Errno {\nreturn errno\n}\n- sockProg := sockFprog{\n+ sockProg := linux.SockFprog{\nLen: uint16(len(instrs)),\nFilter: (*linux.BPFInstruction)(unsafe.Pointer(&instrs[0])),\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/task_run.go", "new_path": "pkg/sentry/kernel/task_run.go", "diff": "@@ -96,6 +96,7 @@ func (t *Task) run(threadID uintptr) {\nt.tg.liveGoroutines.Done()\nt.tg.pidns.owner.liveGoroutines.Done()\nt.tg.pidns.owner.runningGoroutines.Done()\n+ t.p.Release()\n// Keep argument alive because stack trace for dead variables may not be correct.\nruntime.KeepAlive(threadID)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/kvm/context.go", "new_path": "pkg/sentry/platform/kvm/context.go", "diff": "@@ -85,3 +85,6 @@ func (c *context) Switch(as platform.AddressSpace, ac arch.Context, _ int32) (*a\nfunc (c *context) Interrupt() {\nc.interrupt.NotifyInterrupt()\n}\n+\n+// Release implements platform.Context.Release().\n+func (c *context) Release() {}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/kvm/kvm.go", "new_path": "pkg/sentry/platform/kvm/kvm.go", "diff": "@@ -191,6 +191,11 @@ func (*constructor) OpenDevice() (*os.File, error) {\nreturn OpenDevice()\n}\n+// Flags implements platform.Constructor.Flags().\n+func (*constructor) Requirements() platform.Requirements {\n+ return platform.Requirements{}\n+}\n+\nfunc init() {\nplatform.Register(\"kvm\", &constructor{})\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/platform.go", "new_path": "pkg/sentry/platform/platform.go", "diff": "@@ -148,6 +148,9 @@ type Context interface {\n// Interrupt interrupts a concurrent call to Switch(), causing it to return\n// ErrContextInterrupt.\nInterrupt()\n+\n+ // Release() releases any resources associated with this context.\n+ Release()\n}\nvar (\n@@ -353,10 +356,28 @@ func (fr FileRange) String() string {\nreturn fmt.Sprintf(\"[%#x, %#x)\", fr.Start, fr.End)\n}\n+// Requirements is used to specify platform specific requirements.\n+type Requirements struct {\n+ // RequiresCurrentPIDNS indicates that the sandbox has to be started in the\n+ // current pid namespace.\n+ RequiresCurrentPIDNS bool\n+ // RequiresCapSysPtrace indicates that the sandbox has to be started with\n+ // the CAP_SYS_PTRACE capability.\n+ RequiresCapSysPtrace bool\n+}\n+\n// Constructor represents a platform type.\ntype Constructor interface {\n+ // New returns a new platform instance.\n+ //\n+ // Arguments:\n+ //\n+ // * deviceFile - the device file (e.g. /dev/kvm for the KVM platform).\nNew(deviceFile *os.File) (Platform, error)\nOpenDevice() (*os.File, error)\n+\n+ // Requirements returns platform specific requirements.\n+ Requirements() Requirements\n}\n// platforms contains all available platform types.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/ptrace/ptrace.go", "new_path": "pkg/sentry/platform/ptrace/ptrace.go", "diff": "@@ -177,6 +177,9 @@ func (c *context) Interrupt() {\nc.interrupt.NotifyInterrupt()\n}\n+// Release implements platform.Context.Release().\n+func (c *context) Release() {}\n+\n// PTrace represents a collection of ptrace subprocesses.\ntype PTrace struct {\nplatform.MMapMinAddr\n@@ -248,6 +251,16 @@ func (*constructor) OpenDevice() (*os.File, error) {\nreturn nil, nil\n}\n+// Flags implements platform.Constructor.Flags().\n+func (*constructor) Requirements() platform.Requirements {\n+ // TODO(b/75837838): Also set a new PID namespace so that we limit\n+ // access to other host processes.\n+ return platform.Requirements{\n+ RequiresCapSysPtrace: true,\n+ RequiresCurrentPIDNS: true,\n+ }\n+}\n+\nfunc init() {\nplatform.Register(\"ptrace\", &constructor{})\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/ptrace/subprocess.go", "new_path": "pkg/sentry/platform/ptrace/subprocess.go", "diff": "@@ -332,7 +332,7 @@ func (t *thread) unexpectedStubExit() {\nmsg, err := t.getEventMessage()\nstatus := syscall.WaitStatus(msg)\nif status.Signaled() && status.Signal() == syscall.SIGKILL {\n- // SIGKILL can be only sent by an user or OOM-killer. In both\n+ // SIGKILL can be only sent by a user or OOM-killer. In both\n// these cases, we don't need to panic. There is no reasons to\n// think that something wrong in gVisor.\nlog.Warningf(\"The ptrace stub process %v has been killed by SIGKILL.\", t.tgid)\n" }, { "change_type": "MODIFY", "old_path": "runsc/cmd/BUILD", "new_path": "runsc/cmd/BUILD", "diff": "@@ -44,13 +44,13 @@ go_library(\n\"//pkg/sentry/control\",\n\"//pkg/sentry/kernel\",\n\"//pkg/sentry/kernel/auth\",\n+ \"//pkg/sentry/platform\",\n\"//pkg/state\",\n\"//pkg/state/statefile\",\n\"//pkg/sync\",\n\"//pkg/unet\",\n\"//pkg/urpc\",\n\"//runsc/boot\",\n- \"//runsc/boot/platforms\",\n\"//runsc/console\",\n\"//runsc/container\",\n\"//runsc/flag\",\n" }, { "change_type": "MODIFY", "old_path": "runsc/cmd/boot.go", "new_path": "runsc/cmd/boot.go", "diff": "@@ -25,8 +25,8 @@ import (\nspecs \"github.com/opencontainers/runtime-spec/specs-go\"\n\"golang.org/x/sys/unix\"\n\"gvisor.dev/gvisor/pkg/log\"\n+ \"gvisor.dev/gvisor/pkg/sentry/platform\"\n\"gvisor.dev/gvisor/runsc/boot\"\n- \"gvisor.dev/gvisor/runsc/boot/platforms\"\n\"gvisor.dev/gvisor/runsc/flag\"\n\"gvisor.dev/gvisor/runsc/specutils\"\n)\n@@ -183,7 +183,12 @@ func (b *Boot) Execute(_ context.Context, f *flag.FlagSet, args ...interface{})\nif caps == nil {\ncaps = &specs.LinuxCapabilities{}\n}\n- if conf.Platform == platforms.Ptrace {\n+\n+ gPlatform, err := platform.Lookup(conf.Platform)\n+ if err != nil {\n+ Fatalf(\"loading platform: %v\", err)\n+ }\n+ if gPlatform.Requirements().RequiresCapSysPtrace {\n// Ptrace platform requires extra capabilities.\nconst c = \"CAP_SYS_PTRACE\"\ncaps.Bounding = append(caps.Bounding, c)\n" }, { "change_type": "MODIFY", "old_path": "runsc/sandbox/sandbox.go", "new_path": "runsc/sandbox/sandbox.go", "diff": "@@ -446,9 +446,13 @@ func (s *Sandbox) createSandboxProcess(conf *boot.Config, args *Args, startSyncF\nnextFD++\n}\n- // If the platform needs a device FD we must pass it in.\n- if deviceFile, err := deviceFileForPlatform(conf.Platform); err != nil {\n+ gPlatform, err := platform.Lookup(conf.Platform)\n+ if err != nil {\nreturn err\n+ }\n+\n+ if deviceFile, err := gPlatform.OpenDevice(); err != nil {\n+ return fmt.Errorf(\"opening device file for platform %q: %v\", gPlatform, err)\n} else if deviceFile != nil {\ndefer deviceFile.Close()\ncmd.ExtraFiles = append(cmd.ExtraFiles, deviceFile)\n@@ -539,7 +543,7 @@ func (s *Sandbox) createSandboxProcess(conf *boot.Config, args *Args, startSyncF\n{Type: specs.UTSNamespace},\n}\n- if conf.Platform == platforms.Ptrace {\n+ if gPlatform.Requirements().RequiresCurrentPIDNS {\n// TODO(b/75837838): Also set a new PID namespace so that we limit\n// access to other host processes.\nlog.Infof(\"Sandbox will be started in the current PID namespace\")\n" }, { "change_type": "MODIFY", "old_path": "tools/nogo/config.go", "new_path": "tools/nogo/config.go", "diff": "@@ -103,6 +103,9 @@ var analyzerConfig = map[*analysis.Analyzer]matcher{\n\"pkg/sentry/platform/ring0/pagetables/allocator_unsafe.go\", // Special case.\n\"pkg/sentry/platform/safecopy/safecopy_unsafe.go\", // Special case.\n\"pkg/sentry/vfs/mount_unsafe.go\", // Special case.\n+ \"pkg/sentry/platform/systrap/stub_unsafe.go\", // Special case.\n+ \"pkg/sentry/platform/systrap/switchto_google_unsafe.go\", // Special case.\n+ \"pkg/sentry/platform/systrap/sysmsg_thread_unsafe.go\", // Special case.\n),\n),\nunusedresult.Analyzer: alwaysMatches(),\n" } ]
Go
Apache License 2.0
google/gvisor
Specify a memory file in platform.New(). PiperOrigin-RevId: 307941984
259,972
23.04.2020 08:34:42
25,200
a2925a079fa04ff4c891016a0eea1818bdb2cf4b
Run failing packetimpact test and expect failure. This will make it easier to notice if a code change causes an existing test to pass.
[ { "change_type": "MODIFY", "old_path": "test/packetimpact/tests/defs.bzl", "new_path": "test/packetimpact/tests/defs.bzl", "diff": "@@ -59,7 +59,11 @@ _packetimpact_test = rule(\nPACKETIMPACT_TAGS = [\"local\", \"manual\"]\n-def packetimpact_linux_test(name, testbench_binary, **kwargs):\n+def packetimpact_linux_test(\n+ name,\n+ testbench_binary,\n+ expect_failure = False,\n+ **kwargs):\n\"\"\"Add a packetimpact test on linux.\nArgs:\n@@ -67,28 +71,37 @@ def packetimpact_linux_test(name, testbench_binary, **kwargs):\ntestbench_binary: the testbench binary\n**kwargs: all the other args, forwarded to _packetimpact_test\n\"\"\"\n+ expect_failure_flag = [\"--expect_failure\"] if expect_failure else []\n_packetimpact_test(\nname = name + \"_linux_test\",\ntestbench_binary = testbench_binary,\n- flags = [\"--dut_platform\", \"linux\"],\n+ flags = [\"--dut_platform\", \"linux\"] + expect_failure_flag,\ntags = PACKETIMPACT_TAGS + [\"packetimpact\"],\n**kwargs\n)\n-def packetimpact_netstack_test(name, testbench_binary, **kwargs):\n+def packetimpact_netstack_test(\n+ name,\n+ testbench_binary,\n+ expect_failure = False,\n+ **kwargs):\n\"\"\"Add a packetimpact test on netstack.\nArgs:\nname: name of the test\ntestbench_binary: the testbench binary\n+ expect_failure: the test must fail\n**kwargs: all the other args, forwarded to _packetimpact_test\n\"\"\"\n+ expect_failure_flag = []\n+ if expect_failure:\n+ expect_failure_flag = [\"--expect_failure\"]\n_packetimpact_test(\nname = name + \"_netstack_test\",\ntestbench_binary = testbench_binary,\n# This is the default runtime unless\n# \"--test_arg=--runtime=OTHER_RUNTIME\" is used to override the value.\n- flags = [\"--dut_platform\", \"netstack\", \"--runtime=runsc-d\"],\n+ flags = [\"--dut_platform\", \"netstack\", \"--runtime=runsc-d\"] + expect_failure_flag,\ntags = PACKETIMPACT_TAGS + [\"packetimpact\"],\n**kwargs\n)\n@@ -112,7 +125,13 @@ def packetimpact_go_test(name, size = \"small\", pure = True, linux = True, netsta\ntags = PACKETIMPACT_TAGS,\n**kwargs\n)\n- if linux:\n- packetimpact_linux_test(name = name, testbench_binary = testbench_binary)\n- if netstack:\n- packetimpact_netstack_test(name = name, testbench_binary = testbench_binary)\n+ packetimpact_linux_test(\n+ name = name,\n+ expect_failure = not linux,\n+ testbench_binary = testbench_binary,\n+ )\n+ packetimpact_netstack_test(\n+ name = name,\n+ expect_failure = not netstack,\n+ testbench_binary = testbench_binary,\n+ )\n" }, { "change_type": "MODIFY", "old_path": "test/packetimpact/tests/test_runner.sh", "new_path": "test/packetimpact/tests/test_runner.sh", "diff": "@@ -29,7 +29,7 @@ function failure() {\n}\ntrap 'failure ${LINENO} \"$BASH_COMMAND\"' ERR\n-declare -r LONGOPTS=\"dut_platform:,posix_server_binary:,testbench_binary:,runtime:,tshark,extra_test_arg:\"\n+declare -r LONGOPTS=\"dut_platform:,posix_server_binary:,testbench_binary:,runtime:,tshark,extra_test_arg:,expect_failure\"\n# Don't use declare below so that the error from getopt will end the script.\nPARSED=$(getopt --options \"\" --longoptions=$LONGOPTS --name \"$0\" -- \"$@\")\n@@ -68,6 +68,10 @@ while true; do\nEXTRA_TEST_ARGS+=\"$2\"\nshift 2\n;;\n+ --expect_failure)\n+ declare -r EXPECT_FAILURE=\"1\"\n+ shift 1\n+ ;;\n--)\nshift\nbreak\n@@ -263,6 +267,15 @@ docker exec -t \"${TESTBENCH}\" \\\n--local_ipv4=${TEST_NET_PREFIX}${TESTBENCH_NET_SUFFIX} \\\n--remote_mac=${REMOTE_MAC} \\\n--local_mac=${LOCAL_MAC} \\\n- --device=${TEST_DEVICE}\"\n-\n+ --device=${TEST_DEVICE}\" && true\n+declare -r TEST_RESULT=\"${?}\"\n+if [[ -z \"${EXPECT_FAILURE-}\" && \"${TEST_RESULT}\" != 0 ]]; then\n+ echo 'FAIL: This test was expected to pass.'\n+ exit ${TEST_RESULT}\n+fi\n+if [[ ! -z \"${EXPECT_FAILURE-}\" && \"${TEST_RESULT}\" == 0 ]]; then\n+ echo 'FAIL: This test was expected to fail but passed. Enable the test and' \\\n+ 'mark the corresponding bug as fixed.'\n+ exit 1\n+fi\necho PASS: No errors.\n" } ]
Go
Apache License 2.0
google/gvisor
Run failing packetimpact test and expect failure. This will make it easier to notice if a code change causes an existing test to pass. PiperOrigin-RevId: 308057978
259,992
23.04.2020 10:19:23
25,200
7d1b7daf7e89c99899fc46187bcb1f3a3bcab7fb
Disable nogo because it breaks Go 1.13 Even though the default build option is to use 1.14, we want to be want to keep the ability to target different Go versions for testing and in case the new release has bugs.
[ { "change_type": "MODIFY", "old_path": "tools/defs.bzl", "new_path": "tools/defs.bzl", "diff": "@@ -92,7 +92,7 @@ def go_imports(name, src, out):\ncmd = (\"$(location @org_golang_x_tools//cmd/goimports:goimports) $(SRCS) > $@\"),\n)\n-def go_library(name, srcs, deps = [], imports = [], stateify = True, marshal = False, marshal_debug = False, nogo = True, **kwargs):\n+def go_library(name, srcs, deps = [], imports = [], stateify = True, marshal = False, marshal_debug = False, nogo = False, **kwargs):\n\"\"\"Wraps the standard go_library and does stateification and marshalling.\nThe recommended way is to use this rule with mostly identical configuration as the native\n" } ]
Go
Apache License 2.0
google/gvisor
Disable nogo because it breaks Go 1.13 Even though the default build option is to use 1.14, we want to be want to keep the ability to target different Go versions for testing and in case the new release has bugs. PiperOrigin-RevId: 308078876
259,885
23.04.2020 11:06:59
25,200
e0c67014cb2200ad58cd28b12fddb3f55652a21b
Factor fsimpl/gofer.host{Preadv,Pwritev} out of fsimpl/gofer. Also fix returning EOF when 0 bytes are read.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/gofer/BUILD", "new_path": "pkg/sentry/fsimpl/gofer/BUILD", "diff": "@@ -35,7 +35,6 @@ go_library(\n\"fstree.go\",\n\"gofer.go\",\n\"handle.go\",\n- \"handle_unsafe.go\",\n\"p9file.go\",\n\"pagemath.go\",\n\"regular_file.go\",\n@@ -53,6 +52,7 @@ go_library(\n\"//pkg/p9\",\n\"//pkg/safemem\",\n\"//pkg/sentry/fs/fsutil\",\n+ \"//pkg/sentry/hostfd\",\n\"//pkg/sentry/kernel/auth\",\n\"//pkg/sentry/kernel/time\",\n\"//pkg/sentry/memmap\",\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/gofer/handle.go", "new_path": "pkg/sentry/fsimpl/gofer/handle.go", "diff": "@@ -20,6 +20,7 @@ import (\n\"gvisor.dev/gvisor/pkg/context\"\n\"gvisor.dev/gvisor/pkg/p9\"\n\"gvisor.dev/gvisor/pkg/safemem\"\n+ \"gvisor.dev/gvisor/pkg/sentry/hostfd\"\n)\n// handle represents a remote \"open file descriptor\", consisting of an opened\n@@ -77,7 +78,7 @@ func (h *handle) readToBlocksAt(ctx context.Context, dsts safemem.BlockSeq, offs\n}\nif h.fd >= 0 {\nctx.UninterruptibleSleepStart(false)\n- n, err := hostPreadv(h.fd, dsts, int64(offset))\n+ n, err := hostfd.Preadv2(h.fd, dsts, int64(offset), 0 /* flags */)\nctx.UninterruptibleSleepFinish(false)\nreturn n, err\n}\n@@ -103,7 +104,7 @@ func (h *handle) writeFromBlocksAt(ctx context.Context, srcs safemem.BlockSeq, o\n}\nif h.fd >= 0 {\nctx.UninterruptibleSleepStart(false)\n- n, err := hostPwritev(h.fd, srcs, int64(offset))\n+ n, err := hostfd.Pwritev2(h.fd, srcs, int64(offset), 0 /* flags */)\nctx.UninterruptibleSleepFinish(false)\nreturn n, err\n}\n" }, { "change_type": "DELETE", "old_path": "pkg/sentry/fsimpl/gofer/handle_unsafe.go", "new_path": null, "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 gofer\n-\n-import (\n- \"syscall\"\n- \"unsafe\"\n-\n- \"gvisor.dev/gvisor/pkg/safemem\"\n-)\n-\n-// Preconditions: !dsts.IsEmpty().\n-func hostPreadv(fd int32, dsts safemem.BlockSeq, off int64) (uint64, error) {\n- // No buffering is necessary regardless of safecopy; host syscalls will\n- // return EFAULT if appropriate, instead of raising SIGBUS.\n- if dsts.NumBlocks() == 1 {\n- // Use pread() instead of preadv() to avoid iovec allocation and\n- // copying.\n- dst := dsts.Head()\n- n, _, e := syscall.Syscall6(syscall.SYS_PREAD64, uintptr(fd), dst.Addr(), uintptr(dst.Len()), uintptr(off), 0, 0)\n- if e != 0 {\n- return 0, e\n- }\n- return uint64(n), nil\n- }\n- iovs := safemem.IovecsFromBlockSeq(dsts)\n- n, _, e := syscall.Syscall6(syscall.SYS_PREADV, uintptr(fd), uintptr((unsafe.Pointer)(&iovs[0])), uintptr(len(iovs)), uintptr(off), 0, 0)\n- if e != 0 {\n- return 0, e\n- }\n- return uint64(n), nil\n-}\n-\n-// Preconditions: !srcs.IsEmpty().\n-func hostPwritev(fd int32, srcs safemem.BlockSeq, off int64) (uint64, error) {\n- // No buffering is necessary regardless of safecopy; host syscalls will\n- // return EFAULT if appropriate, instead of raising SIGBUS.\n- if srcs.NumBlocks() == 1 {\n- // Use pwrite() instead of pwritev() to avoid iovec allocation and\n- // copying.\n- src := srcs.Head()\n- n, _, e := syscall.Syscall6(syscall.SYS_PWRITE64, uintptr(fd), src.Addr(), uintptr(src.Len()), uintptr(off), 0, 0)\n- if e != 0 {\n- return 0, e\n- }\n- return uint64(n), nil\n- }\n- iovs := safemem.IovecsFromBlockSeq(srcs)\n- n, _, e := syscall.Syscall6(syscall.SYS_PWRITEV, uintptr(fd), uintptr((unsafe.Pointer)(&iovs[0])), uintptr(len(iovs)), uintptr(off), 0, 0)\n- if e != 0 {\n- return 0, e\n- }\n- return uint64(n), nil\n-}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/host/BUILD", "new_path": "pkg/sentry/fsimpl/host/BUILD", "diff": "@@ -15,12 +15,11 @@ go_library(\ndeps = [\n\"//pkg/abi/linux\",\n\"//pkg/context\",\n- \"//pkg/fd\",\n\"//pkg/log\",\n\"//pkg/refs\",\n- \"//pkg/safemem\",\n\"//pkg/sentry/arch\",\n\"//pkg/sentry/fsimpl/kernfs\",\n+ \"//pkg/sentry/hostfd\",\n\"//pkg/sentry/kernel\",\n\"//pkg/sentry/kernel/auth\",\n\"//pkg/sentry/memmap\",\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/host/host.go", "new_path": "pkg/sentry/fsimpl/host/host.go", "diff": "@@ -25,11 +25,10 @@ import (\n\"golang.org/x/sys/unix\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/context\"\n- \"gvisor.dev/gvisor/pkg/fd\"\n\"gvisor.dev/gvisor/pkg/log\"\n\"gvisor.dev/gvisor/pkg/refs\"\n- \"gvisor.dev/gvisor/pkg/safemem\"\n\"gvisor.dev/gvisor/pkg/sentry/fsimpl/kernfs\"\n+ \"gvisor.dev/gvisor/pkg/sentry/hostfd\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n\"gvisor.dev/gvisor/pkg/sentry/memmap\"\n\"gvisor.dev/gvisor/pkg/sentry/vfs\"\n@@ -492,19 +491,9 @@ func readFromHostFD(ctx context.Context, hostFD int, dst usermem.IOSequence, off\nif flags != 0 {\nreturn 0, syserror.EOPNOTSUPP\n}\n-\n- var reader safemem.Reader\n- if offset == -1 {\n- reader = safemem.FromIOReader{fd.NewReadWriter(hostFD)}\n- } else {\n- reader = safemem.FromVecReaderFunc{\n- func(srcs [][]byte) (int64, error) {\n- n, err := unix.Preadv(hostFD, srcs, offset)\n- return int64(n), err\n- },\n- }\n- }\n+ reader := hostfd.GetReadWriterAt(int32(hostFD), offset, flags)\nn, err := dst.CopyOutFrom(ctx, reader)\n+ hostfd.PutReadWriterAt(reader)\nreturn int64(n), err\n}\n@@ -542,19 +531,9 @@ func writeToHostFD(ctx context.Context, hostFD int, src usermem.IOSequence, offs\nif flags != 0 {\nreturn 0, syserror.EOPNOTSUPP\n}\n-\n- var writer safemem.Writer\n- if offset == -1 {\n- writer = safemem.FromIOWriter{fd.NewReadWriter(hostFD)}\n- } else {\n- writer = safemem.FromVecWriterFunc{\n- func(srcs [][]byte) (int64, error) {\n- n, err := unix.Pwritev(hostFD, srcs, offset)\n- return int64(n), err\n- },\n- }\n- }\n+ writer := hostfd.GetReadWriterAt(int32(hostFD), offset, flags)\nn, err := src.CopyInTo(ctx, writer)\n+ hostfd.PutReadWriterAt(writer)\nreturn int64(n), err\n}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/hostfd/BUILD", "diff": "+load(\"//tools:defs.bzl\", \"go_library\")\n+\n+licenses([\"notice\"])\n+\n+go_library(\n+ name = \"hostfd\",\n+ srcs = [\n+ \"hostfd.go\",\n+ \"hostfd_unsafe.go\",\n+ ],\n+ visibility = [\"//pkg/sentry:internal\"],\n+ deps = [\n+ \"//pkg/safemem\",\n+ \"//pkg/sync\",\n+ \"@org_golang_x_sys//unix:go_default_library\",\n+ ],\n+)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/hostfd/hostfd.go", "diff": "+// Copyright 2020 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 hostfd provides efficient I/O with host file descriptors.\n+package hostfd\n+\n+import (\n+ \"gvisor.dev/gvisor/pkg/safemem\"\n+ \"gvisor.dev/gvisor/pkg/sync\"\n+)\n+\n+// ReadWriterAt implements safemem.Reader and safemem.Writer by reading from\n+// and writing to a host file descriptor respectively. ReadWriterAts should be\n+// obtained by calling GetReadWriterAt.\n+//\n+// Clients should usually prefer to use Preadv2 and Pwritev2 directly.\n+type ReadWriterAt struct {\n+ fd int32\n+ offset int64\n+ flags uint32\n+}\n+\n+var rwpool = sync.Pool{\n+ New: func() interface{} {\n+ return &ReadWriterAt{}\n+ },\n+}\n+\n+// GetReadWriterAt returns a ReadWriterAt that reads from / writes to the given\n+// host file descriptor, starting at the given offset and using the given\n+// preadv2(2)/pwritev2(2) flags. If offset is -1, the host file descriptor's\n+// offset is used instead. Users are responsible for ensuring that fd remains\n+// valid for the lifetime of the returned ReadWriterAt, and must call\n+// PutReadWriterAt when it is no longer needed.\n+func GetReadWriterAt(fd int32, offset int64, flags uint32) *ReadWriterAt {\n+ rw := rwpool.Get().(*ReadWriterAt)\n+ *rw = ReadWriterAt{\n+ fd: fd,\n+ offset: offset,\n+ flags: flags,\n+ }\n+ return rw\n+}\n+\n+// PutReadWriterAt releases a ReadWriterAt returned by a previous call to\n+// GetReadWriterAt that is no longer in use.\n+func PutReadWriterAt(rw *ReadWriterAt) {\n+ rwpool.Put(rw)\n+}\n+\n+// ReadToBlocks implements safemem.Reader.ReadToBlocks.\n+func (rw *ReadWriterAt) ReadToBlocks(dsts safemem.BlockSeq) (uint64, error) {\n+ if dsts.IsEmpty() {\n+ return 0, nil\n+ }\n+ n, err := Preadv2(rw.fd, dsts, rw.offset, rw.flags)\n+ if rw.offset >= 0 {\n+ rw.offset += int64(n)\n+ }\n+ return n, err\n+}\n+\n+// WriteFromBlocks implements safemem.Writer.WriteFromBlocks.\n+func (rw *ReadWriterAt) WriteFromBlocks(srcs safemem.BlockSeq) (uint64, error) {\n+ if srcs.IsEmpty() {\n+ return 0, nil\n+ }\n+ n, err := Pwritev2(rw.fd, srcs, rw.offset, rw.flags)\n+ if rw.offset >= 0 {\n+ rw.offset += int64(n)\n+ }\n+ return n, err\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/hostfd/hostfd_unsafe.go", "diff": "+// Copyright 2020 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 hostfd\n+\n+import (\n+ \"io\"\n+ \"syscall\"\n+ \"unsafe\"\n+\n+ \"golang.org/x/sys/unix\"\n+ \"gvisor.dev/gvisor/pkg/safemem\"\n+)\n+\n+// Preadv2 reads up to dsts.NumBytes() bytes from host file descriptor fd into\n+// dsts. offset and flags are interpreted as for preadv2(2).\n+//\n+// Preconditions: !dsts.IsEmpty().\n+func Preadv2(fd int32, dsts safemem.BlockSeq, offset int64, flags uint32) (uint64, error) {\n+ // No buffering is necessary regardless of safecopy; host syscalls will\n+ // return EFAULT if appropriate, instead of raising SIGBUS.\n+ var (\n+ n uintptr\n+ e syscall.Errno\n+ )\n+ // Avoid preadv2(2) if possible, since it's relatively new and thus least\n+ // likely to be supported by the host kernel.\n+ if flags == 0 {\n+ if dsts.NumBlocks() == 1 {\n+ // Use read() or pread() to avoid iovec allocation and copying.\n+ dst := dsts.Head()\n+ if offset == -1 {\n+ n, _, e = syscall.Syscall(unix.SYS_READ, uintptr(fd), dst.Addr(), uintptr(dst.Len()))\n+ } else {\n+ n, _, e = syscall.Syscall6(unix.SYS_PREAD64, uintptr(fd), dst.Addr(), uintptr(dst.Len()), uintptr(offset), 0 /* pos_h */, 0 /* unused */)\n+ }\n+ } else {\n+ iovs := safemem.IovecsFromBlockSeq(dsts)\n+ if offset == -1 {\n+ n, _, e = syscall.Syscall(unix.SYS_READV, uintptr(fd), uintptr((unsafe.Pointer)(&iovs[0])), uintptr(len(iovs)))\n+ } else {\n+ n, _, e = syscall.Syscall6(unix.SYS_PREADV, uintptr(fd), uintptr((unsafe.Pointer)(&iovs[0])), uintptr(len(iovs)), uintptr(offset), 0 /* pos_h */, 0 /* unused */)\n+ }\n+ }\n+ } else {\n+ iovs := safemem.IovecsFromBlockSeq(dsts)\n+ n, _, e = syscall.Syscall6(unix.SYS_PREADV2, uintptr(fd), uintptr((unsafe.Pointer)(&iovs[0])), uintptr(len(iovs)), uintptr(offset), 0 /* pos_h */, uintptr(flags))\n+ }\n+ if e != 0 {\n+ return 0, e\n+ }\n+ if n == 0 {\n+ return 0, io.EOF\n+ }\n+ return uint64(n), nil\n+}\n+\n+// Pwritev2 writes up to srcs.NumBytes() from srcs into host file descriptor\n+// fd. offset and flags are interpreted as for pwritev2(2).\n+//\n+// Preconditions: !srcs.IsEmpty().\n+func Pwritev2(fd int32, srcs safemem.BlockSeq, offset int64, flags uint32) (uint64, error) {\n+ // No buffering is necessary regardless of safecopy; host syscalls will\n+ // return EFAULT if appropriate, instead of raising SIGBUS.\n+ var (\n+ n uintptr\n+ e syscall.Errno\n+ )\n+ // Avoid pwritev2(2) if possible, since it's relatively new and thus least\n+ // likely to be supported by the host kernel.\n+ if flags == 0 {\n+ if srcs.NumBlocks() == 1 {\n+ // Use write() or pwrite() to avoid iovec allocation and copying.\n+ src := srcs.Head()\n+ if offset == -1 {\n+ n, _, e = syscall.Syscall(unix.SYS_WRITE, uintptr(fd), src.Addr(), uintptr(src.Len()))\n+ } else {\n+ n, _, e = syscall.Syscall6(unix.SYS_PWRITE64, uintptr(fd), src.Addr(), uintptr(src.Len()), uintptr(offset), 0 /* pos_h */, 0 /* unused */)\n+ }\n+ } else {\n+ iovs := safemem.IovecsFromBlockSeq(srcs)\n+ if offset == -1 {\n+ n, _, e = syscall.Syscall(unix.SYS_WRITEV, uintptr(fd), uintptr((unsafe.Pointer)(&iovs[0])), uintptr(len(iovs)))\n+ } else {\n+ n, _, e = syscall.Syscall6(unix.SYS_PWRITEV, uintptr(fd), uintptr((unsafe.Pointer)(&iovs[0])), uintptr(len(iovs)), uintptr(offset), 0 /* pos_h */, 0 /* unused */)\n+ }\n+ }\n+ } else {\n+ iovs := safemem.IovecsFromBlockSeq(srcs)\n+ n, _, e = syscall.Syscall6(unix.SYS_PWRITEV2, uintptr(fd), uintptr((unsafe.Pointer)(&iovs[0])), uintptr(len(iovs)), uintptr(offset), 0 /* pos_h */, uintptr(flags))\n+ }\n+ if e != 0 {\n+ return 0, e\n+ }\n+ return uint64(n), nil\n+}\n" } ]
Go
Apache License 2.0
google/gvisor
Factor fsimpl/gofer.host{Preadv,Pwritev} out of fsimpl/gofer. Also fix returning EOF when 0 bytes are read. PiperOrigin-RevId: 308089875