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,853 | 14.12.2018 16:23:03 | 28,800 | 3cf84e3bef865214fcf2b080a05065f0a9e976ec | Mark sync.Mutex in TTYFileOperations as nosave | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/host/tty.go",
"new_path": "pkg/sentry/fs/host/tty.go",
"diff": "@@ -35,7 +35,7 @@ type TTYFileOperations struct {\nfileOperations\n// mu protects the fields below.\n- mu sync.Mutex\n+ mu sync.Mutex `state:\"nosave\"`\n// FGProcessGroup is the foreground process group this TTY. Will be\n// nil if not set or if this file has been released.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Mark sync.Mutex in TTYFileOperations as nosave
PiperOrigin-RevId: 225621767
Change-Id: Ie3a42cdf0b0de22a020ff43e307bf86409cff329 |
259,858 | 14.12.2018 18:03:43 | 28,800 | 5d8cf31346376eb7c6a93bad3eab7666f145fa0e | Move fdnotifier package to reduce internal confusion. | [
{
"change_type": "RENAME",
"old_path": "pkg/waiter/fdnotifier/BUILD",
"new_path": "pkg/fdnotifier/BUILD",
"diff": "@@ -8,7 +8,7 @@ go_library(\n\"fdnotifier.go\",\n\"poll_unsafe.go\",\n],\n- importpath = \"gvisor.googlesource.com/gvisor/pkg/waiter/fdnotifier\",\n+ importpath = \"gvisor.googlesource.com/gvisor/pkg/fdnotifier\",\nvisibility = [\"//:sandbox\"],\ndeps = [\"//pkg/waiter\"],\n)\n"
},
{
"change_type": "RENAME",
"old_path": "pkg/waiter/fdnotifier/fdnotifier.go",
"new_path": "pkg/fdnotifier/fdnotifier.go",
"diff": ""
},
{
"change_type": "RENAME",
"old_path": "pkg/waiter/fdnotifier/poll_unsafe.go",
"new_path": "pkg/fdnotifier/poll_unsafe.go",
"diff": ""
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/fdpipe/BUILD",
"new_path": "pkg/sentry/fs/fdpipe/BUILD",
"diff": "@@ -14,6 +14,7 @@ go_library(\nvisibility = [\"//pkg/sentry:internal\"],\ndeps = [\n\"//pkg/fd\",\n+ \"//pkg/fdnotifier\",\n\"//pkg/log\",\n\"//pkg/secio\",\n\"//pkg/sentry/context\",\n@@ -23,7 +24,6 @@ go_library(\n\"//pkg/sentry/usermem\",\n\"//pkg/syserror\",\n\"//pkg/waiter\",\n- \"//pkg/waiter/fdnotifier\",\n],\n)\n@@ -37,12 +37,12 @@ go_test(\nembed = [\":fdpipe\"],\ndeps = [\n\"//pkg/fd\",\n+ \"//pkg/fdnotifier\",\n\"//pkg/sentry/context\",\n\"//pkg/sentry/context/contexttest\",\n\"//pkg/sentry/fs\",\n\"//pkg/sentry/usermem\",\n\"//pkg/syserror\",\n- \"//pkg/waiter/fdnotifier\",\n\"@com_github_google_uuid//:go_default_library\",\n],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/fdpipe/pipe.go",
"new_path": "pkg/sentry/fs/fdpipe/pipe.go",
"diff": "@@ -21,6 +21,7 @@ import (\n\"syscall\"\n\"gvisor.googlesource.com/gvisor/pkg/fd\"\n+ \"gvisor.googlesource.com/gvisor/pkg/fdnotifier\"\n\"gvisor.googlesource.com/gvisor/pkg/log\"\n\"gvisor.googlesource.com/gvisor/pkg/secio\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/context\"\n@@ -30,7 +31,6 @@ import (\n\"gvisor.googlesource.com/gvisor/pkg/sentry/usermem\"\n\"gvisor.googlesource.com/gvisor/pkg/syserror\"\n\"gvisor.googlesource.com/gvisor/pkg/waiter\"\n- \"gvisor.googlesource.com/gvisor/pkg/waiter/fdnotifier\"\n)\n// pipeOperations are the fs.FileOperations of a host pipe.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/fdpipe/pipe_test.go",
"new_path": "pkg/sentry/fs/fdpipe/pipe_test.go",
"diff": "@@ -22,11 +22,11 @@ import (\n\"testing\"\n\"gvisor.googlesource.com/gvisor/pkg/fd\"\n+ \"gvisor.googlesource.com/gvisor/pkg/fdnotifier\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/context/contexttest\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/fs\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/usermem\"\n\"gvisor.googlesource.com/gvisor/pkg/syserror\"\n- \"gvisor.googlesource.com/gvisor/pkg/waiter/fdnotifier\"\n)\nfunc singlePipeFD() (int, error) {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/host/BUILD",
"new_path": "pkg/sentry/fs/host/BUILD",
"diff": "@@ -27,6 +27,7 @@ go_library(\ndeps = [\n\"//pkg/abi/linux\",\n\"//pkg/fd\",\n+ \"//pkg/fdnotifier\",\n\"//pkg/log\",\n\"//pkg/refs\",\n\"//pkg/secio\",\n@@ -51,7 +52,6 @@ go_library(\n\"//pkg/tcpip\",\n\"//pkg/unet\",\n\"//pkg/waiter\",\n- \"//pkg/waiter/fdnotifier\",\n],\n)\n@@ -68,6 +68,7 @@ go_test(\nembed = [\":host\"],\ndeps = [\n\"//pkg/fd\",\n+ \"//pkg/fdnotifier\",\n\"//pkg/sentry/context\",\n\"//pkg/sentry/context/contexttest\",\n\"//pkg/sentry/fs\",\n@@ -78,6 +79,5 @@ go_test(\n\"//pkg/syserr\",\n\"//pkg/tcpip\",\n\"//pkg/waiter\",\n- \"//pkg/waiter/fdnotifier\",\n],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/host/descriptor.go",
"new_path": "pkg/sentry/fs/host/descriptor.go",
"diff": "@@ -19,9 +19,9 @@ import (\n\"path\"\n\"syscall\"\n+ \"gvisor.googlesource.com/gvisor/pkg/fdnotifier\"\n\"gvisor.googlesource.com/gvisor/pkg/log\"\n\"gvisor.googlesource.com/gvisor/pkg/waiter\"\n- \"gvisor.googlesource.com/gvisor/pkg/waiter/fdnotifier\"\n)\n// descriptor wraps a host fd.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/host/descriptor_test.go",
"new_path": "pkg/sentry/fs/host/descriptor_test.go",
"diff": "@@ -20,8 +20,8 @@ import (\n\"syscall\"\n\"testing\"\n+ \"gvisor.googlesource.com/gvisor/pkg/fdnotifier\"\n\"gvisor.googlesource.com/gvisor/pkg/waiter\"\n- \"gvisor.googlesource.com/gvisor/pkg/waiter/fdnotifier\"\n)\nfunc TestDescriptorRelease(t *testing.T) {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/host/file.go",
"new_path": "pkg/sentry/fs/host/file.go",
"diff": "@@ -19,6 +19,7 @@ import (\n\"syscall\"\n\"gvisor.googlesource.com/gvisor/pkg/fd\"\n+ \"gvisor.googlesource.com/gvisor/pkg/fdnotifier\"\n\"gvisor.googlesource.com/gvisor/pkg/log\"\n\"gvisor.googlesource.com/gvisor/pkg/secio\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/context\"\n@@ -29,7 +30,6 @@ import (\n\"gvisor.googlesource.com/gvisor/pkg/sentry/usermem\"\n\"gvisor.googlesource.com/gvisor/pkg/syserror\"\n\"gvisor.googlesource.com/gvisor/pkg/waiter\"\n- \"gvisor.googlesource.com/gvisor/pkg/waiter/fdnotifier\"\n)\n// fileOperations implements fs.FileOperations for a host file descriptor.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/host/socket.go",
"new_path": "pkg/sentry/fs/host/socket.go",
"diff": "@@ -19,6 +19,7 @@ import (\n\"syscall\"\n\"gvisor.googlesource.com/gvisor/pkg/fd\"\n+ \"gvisor.googlesource.com/gvisor/pkg/fdnotifier\"\n\"gvisor.googlesource.com/gvisor/pkg/log\"\n\"gvisor.googlesource.com/gvisor/pkg/refs\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/context\"\n@@ -32,7 +33,6 @@ import (\n\"gvisor.googlesource.com/gvisor/pkg/tcpip\"\n\"gvisor.googlesource.com/gvisor/pkg/unet\"\n\"gvisor.googlesource.com/gvisor/pkg/waiter\"\n- \"gvisor.googlesource.com/gvisor/pkg/waiter/fdnotifier\"\n)\n// maxSendBufferSize is the maximum host send buffer size allowed for endpoint.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/host/socket_test.go",
"new_path": "pkg/sentry/fs/host/socket_test.go",
"diff": "@@ -20,6 +20,7 @@ import (\n\"testing\"\n\"gvisor.googlesource.com/gvisor/pkg/fd\"\n+ \"gvisor.googlesource.com/gvisor/pkg/fdnotifier\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/context/contexttest\"\nktime \"gvisor.googlesource.com/gvisor/pkg/sentry/kernel/time\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/socket\"\n@@ -28,7 +29,6 @@ import (\n\"gvisor.googlesource.com/gvisor/pkg/syserr\"\n\"gvisor.googlesource.com/gvisor/pkg/tcpip\"\n\"gvisor.googlesource.com/gvisor/pkg/waiter\"\n- \"gvisor.googlesource.com/gvisor/pkg/waiter/fdnotifier\"\n)\nvar (\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/eventfd/BUILD",
"new_path": "pkg/sentry/kernel/eventfd/BUILD",
"diff": "@@ -9,6 +9,7 @@ go_library(\nvisibility = [\"//pkg/sentry:internal\"],\ndeps = [\n\"//pkg/abi/linux\",\n+ \"//pkg/fdnotifier\",\n\"//pkg/sentry/context\",\n\"//pkg/sentry/fs\",\n\"//pkg/sentry/fs/anon\",\n@@ -16,7 +17,6 @@ go_library(\n\"//pkg/sentry/usermem\",\n\"//pkg/syserror\",\n\"//pkg/waiter\",\n- \"//pkg/waiter/fdnotifier\",\n],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/eventfd/eventfd.go",
"new_path": "pkg/sentry/kernel/eventfd/eventfd.go",
"diff": "@@ -22,6 +22,7 @@ import (\n\"syscall\"\n\"gvisor.googlesource.com/gvisor/pkg/abi/linux\"\n+ \"gvisor.googlesource.com/gvisor/pkg/fdnotifier\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/context\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/fs\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/fs/anon\"\n@@ -29,7 +30,6 @@ import (\n\"gvisor.googlesource.com/gvisor/pkg/sentry/usermem\"\n\"gvisor.googlesource.com/gvisor/pkg/syserror\"\n\"gvisor.googlesource.com/gvisor/pkg/waiter\"\n- \"gvisor.googlesource.com/gvisor/pkg/waiter/fdnotifier\"\n)\n// EventOperations represents an event with the semantics of Linux's file-based event\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/hostinet/BUILD",
"new_path": "pkg/sentry/socket/hostinet/BUILD",
"diff": "@@ -17,6 +17,7 @@ go_library(\ndeps = [\n\"//pkg/abi/linux\",\n\"//pkg/binary\",\n+ \"//pkg/fdnotifier\",\n\"//pkg/log\",\n\"//pkg/sentry/arch\",\n\"//pkg/sentry/context\",\n@@ -34,6 +35,5 @@ go_library(\n\"//pkg/syserr\",\n\"//pkg/syserror\",\n\"//pkg/waiter\",\n- \"//pkg/waiter/fdnotifier\",\n],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/hostinet/socket.go",
"new_path": "pkg/sentry/socket/hostinet/socket.go",
"diff": "@@ -19,6 +19,7 @@ import (\n\"syscall\"\n\"gvisor.googlesource.com/gvisor/pkg/abi/linux\"\n+ \"gvisor.googlesource.com/gvisor/pkg/fdnotifier\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/context\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/fs\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/fs/fsutil\"\n@@ -32,7 +33,6 @@ import (\n\"gvisor.googlesource.com/gvisor/pkg/syserr\"\n\"gvisor.googlesource.com/gvisor/pkg/syserror\"\n\"gvisor.googlesource.com/gvisor/pkg/waiter\"\n- \"gvisor.googlesource.com/gvisor/pkg/waiter/fdnotifier\"\n)\nconst (\n"
}
] | Go | Apache License 2.0 | google/gvisor | Move fdnotifier package to reduce internal confusion.
PiperOrigin-RevId: 225632398
Change-Id: I909e7e2925aa369adc28e844c284d9a6108e85ce |
259,854 | 14.12.2018 22:10:19 | 28,800 | f74eed464b55d9640432432cd96d811578e9081e | Add blocking recv tests | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/BUILD",
"new_path": "test/syscalls/BUILD",
"diff": "@@ -356,6 +356,10 @@ syscall_test(test = \"//test/syscalls/linux:socket_netdevice_test\")\nsyscall_test(test = \"//test/syscalls/linux:socket_netlink_route_test\")\n+syscall_test(test = \"//test/syscalls/linux:socket_blocking_local_test\")\n+\n+syscall_test(test = \"//test/syscalls/linux:socket_blocking_ip_test\")\n+\nsyscall_test(test = \"//test/syscalls/linux:socket_non_stream_blocking_local_test\")\nsyscall_test(test = \"//test/syscalls/linux:socket_non_stream_blocking_udp_test\")\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/BUILD",
"new_path": "test/syscalls/linux/BUILD",
"diff": "@@ -2148,6 +2148,27 @@ cc_library(\nalwayslink = 1,\n)\n+cc_library(\n+ name = \"socket_blocking_test_cases\",\n+ testonly = 1,\n+ srcs = [\n+ \"socket_blocking.cc\",\n+ ],\n+ hdrs = [\n+ \"socket_blocking.h\",\n+ ],\n+ deps = [\n+ \":socket_test_util\",\n+ \":unix_domain_socket_test_util\",\n+ \"//test/util:test_util\",\n+ \"//test/util:thread_util\",\n+ \"//test/util:timer_util\",\n+ \"@com_google_absl//absl/time\",\n+ \"@com_google_googletest//:gtest\",\n+ ],\n+ alwayslink = 1,\n+)\n+\ncc_library(\nname = \"socket_unix_test_cases\",\ntestonly = 1,\n@@ -2207,6 +2228,27 @@ cc_library(\nalwayslink = 1,\n)\n+cc_library(\n+ name = \"socket_non_stream_blocking_test_cases\",\n+ testonly = 1,\n+ srcs = [\n+ \"socket_non_stream_blocking.cc\",\n+ ],\n+ hdrs = [\n+ \"socket_non_stream_blocking.h\",\n+ ],\n+ deps = [\n+ \":socket_test_util\",\n+ \":unix_domain_socket_test_util\",\n+ \"//test/util:test_util\",\n+ \"//test/util:thread_util\",\n+ \"//test/util:timer_util\",\n+ \"@com_google_absl//absl/time\",\n+ \"@com_google_googletest//:gtest\",\n+ ],\n+ alwayslink = 1,\n+)\n+\ncc_binary(\nname = \"socket_stream_local_test\",\ntestonly = 1,\n@@ -2346,25 +2388,38 @@ cc_binary(\n],\n)\n-cc_library(\n- name = \"socket_non_stream_blocking_test_cases\",\n+cc_binary(\n+ name = \"socket_blocking_local_test\",\ntestonly = 1,\nsrcs = [\n- \"socket_non_stream_blocking.cc\",\n- ],\n- hdrs = [\n- \"socket_non_stream_blocking.h\",\n+ \"socket_unix_blocking_local.cc\",\n],\n+ linkstatic = 1,\ndeps = [\n+ \":socket_blocking_test_cases\",\n\":socket_test_util\",\n\":unix_domain_socket_test_util\",\n+ \"//test/util:test_main\",\n+ \"//test/util:test_util\",\n+ \"@com_google_googletest//:gtest\",\n+ ],\n+)\n+\n+cc_binary(\n+ name = \"socket_blocking_ip_test\",\n+ testonly = 1,\n+ srcs = [\n+ \"socket_ip_loopback_blocking.cc\",\n+ ],\n+ linkstatic = 1,\n+ deps = [\n+ \":ip_socket_test_util\",\n+ \":socket_blocking_test_cases\",\n+ \":socket_test_util\",\n+ \"//test/util:test_main\",\n\"//test/util:test_util\",\n- \"//test/util:thread_util\",\n- \"//test/util:timer_util\",\n- \"@com_google_absl//absl/time\",\n\"@com_google_googletest//:gtest\",\n],\n- alwayslink = 1,\n)\ncc_binary(\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/syscalls/linux/socket_blocking.cc",
"diff": "+// Copyright 2018 Google LLC\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+#include \"test/syscalls/linux/socket_blocking.h\"\n+\n+#include <sys/socket.h>\n+#include <sys/types.h>\n+#include <sys/un.h>\n+#include <cstdio>\n+\n+#include \"gtest/gtest.h\"\n+#include \"gtest/gtest.h\"\n+#include \"absl/time/clock.h\"\n+#include \"absl/time/time.h\"\n+#include \"test/syscalls/linux/socket_test_util.h\"\n+#include \"test/syscalls/linux/unix_domain_socket_test_util.h\"\n+#include \"test/util/test_util.h\"\n+#include \"test/util/thread_util.h\"\n+#include \"test/util/timer_util.h\"\n+\n+namespace gvisor {\n+namespace testing {\n+\n+TEST_P(BlockingSocketPairTest, RecvBlocks) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ char sent_data[100];\n+ RandomizeBuffer(sent_data, sizeof(sent_data));\n+\n+ constexpr auto kDuration = absl::Milliseconds(200);\n+ auto before = Now(CLOCK_MONOTONIC);\n+\n+ const ScopedThread t([&]() {\n+ absl::SleepFor(kDuration);\n+ ASSERT_THAT(write(sockets->first_fd(), sent_data, sizeof(sent_data)),\n+ SyscallSucceedsWithValue(sizeof(sent_data)));\n+ });\n+\n+ char received_data[sizeof(sent_data)] = {};\n+ ASSERT_THAT(RetryEINTR(recv)(sockets->second_fd(), received_data,\n+ sizeof(received_data), 0),\n+ SyscallSucceedsWithValue(sizeof(received_data)));\n+\n+ auto after = Now(CLOCK_MONOTONIC);\n+ EXPECT_GE(after - before, kDuration);\n+}\n+\n+} // namespace testing\n+} // namespace gvisor\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/syscalls/linux/socket_blocking.h",
"diff": "+// Copyright 2018 Google LLC\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+#ifndef GVISOR_TEST_SYSCALLS_LINUX_SOCKET_BLOCKING_H_\n+#define GVISOR_TEST_SYSCALLS_LINUX_SOCKET_BLOCKING_H_\n+\n+#include \"test/syscalls/linux/socket_test_util.h\"\n+\n+namespace gvisor {\n+namespace testing {\n+\n+// Test fixture for tests that apply to pairs of blocking connected sockets.\n+using BlockingSocketPairTest = SocketPairTest;\n+\n+} // namespace testing\n+} // namespace gvisor\n+\n+#endif // GVISOR_TEST_SYSCALLS_LINUX_SOCKET_BLOCKING_H_\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/syscalls/linux/socket_ip_loopback_blocking.cc",
"diff": "+// Copyright 2018 Google LLC\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+#include <netinet/tcp.h>\n+#include <vector>\n+\n+#include \"test/syscalls/linux/ip_socket_test_util.h\"\n+#include \"test/syscalls/linux/socket_blocking.h\"\n+#include \"test/syscalls/linux/socket_test_util.h\"\n+#include \"test/util/test_util.h\"\n+\n+namespace gvisor {\n+namespace testing {\n+\n+std::vector<SocketPairKind> GetSocketPairs() {\n+ return VecCat<SocketPairKind>(\n+ ApplyVec<SocketPairKind>(\n+ IPv6UDPBidirectionalBindSocketPair,\n+ AllBitwiseCombinations(List<int>{0, SOCK_CLOEXEC})),\n+ ApplyVec<SocketPairKind>(\n+ IPv4UDPBidirectionalBindSocketPair,\n+ AllBitwiseCombinations(List<int>{0, SOCK_CLOEXEC})),\n+ ApplyVecToVec<SocketPairKind>(\n+ std::vector<Middleware>{\n+ NoOp, SetSockOpt(IPPROTO_TCP, TCP_NODELAY, &kSockOptOn)},\n+ VecCat<SocketPairKind>(\n+ ApplyVec<SocketPairKind>(\n+ IPv6TCPAcceptBindSocketPair,\n+ AllBitwiseCombinations(List<int>{0, SOCK_CLOEXEC})),\n+ ApplyVec<SocketPairKind>(\n+ IPv4TCPAcceptBindSocketPair,\n+ AllBitwiseCombinations(List<int>{0, SOCK_CLOEXEC})))));\n+}\n+\n+INSTANTIATE_TEST_CASE_P(\n+ AllUnixDomainSockets, BlockingSocketPairTest,\n+ ::testing::ValuesIn(IncludeReversals(GetSocketPairs())));\n+\n+} // namespace testing\n+} // namespace gvisor\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/syscalls/linux/socket_unix_blocking_local.cc",
"diff": "+// Copyright 2018 Google LLC\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+#include \"test/syscalls/linux/socket_blocking.h\"\n+\n+#include <vector>\n+\n+#include \"test/syscalls/linux/socket_test_util.h\"\n+#include \"test/syscalls/linux/unix_domain_socket_test_util.h\"\n+#include \"test/util/test_util.h\"\n+\n+namespace gvisor {\n+namespace testing {\n+\n+std::vector<SocketPairKind> GetSocketPairs() {\n+ return VecCat<SocketPairKind>(\n+ ApplyVec<SocketPairKind>(\n+ UnixDomainSocketPair,\n+ AllBitwiseCombinations(\n+ List<int>{SOCK_STREAM, SOCK_SEQPACKET, SOCK_DGRAM},\n+ List<int>{0, SOCK_CLOEXEC})),\n+ ApplyVec<SocketPairKind>(\n+ FilesystemBoundUnixDomainSocketPair,\n+ AllBitwiseCombinations(\n+ // FIXME: Add SOCK_DGRAM once blocking is fixed.\n+ List<int>{SOCK_STREAM, SOCK_SEQPACKET},\n+ List<int>{0, SOCK_CLOEXEC})),\n+ ApplyVec<SocketPairKind>(\n+ AbstractBoundUnixDomainSocketPair,\n+ AllBitwiseCombinations(\n+ // FIXME: Add SOCK_DGRAM once blocking is fixed.\n+ List<int>{SOCK_STREAM, SOCK_SEQPACKET},\n+ List<int>{0, SOCK_CLOEXEC})));\n+}\n+\n+INSTANTIATE_TEST_CASE_P(\n+ AllUnixDomainSockets, BlockingSocketPairTest,\n+ ::testing::ValuesIn(IncludeReversals(GetSocketPairs())));\n+\n+} // namespace testing\n+} // namespace gvisor\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add blocking recv tests
PiperOrigin-RevId: 225646045
Change-Id: Ic712ebc627587ef4a9486f0b39fe8c96100f10ff |
260,006 | 16.12.2018 23:04:56 | 28,800 | e491ebbacf548a2a2f818f1093b09d6f1c13e7e0 | Allow sending of multicast and IPv6 link-local packets w/o route.
Same as with broadcast packets, sending of a multicast packet shouldn't require
accessing the route table. The same applies to IPv6 link-local addresses, which
aren't routable at all (they don't belong to any subnet by definition). | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/header/ipv6.go",
"new_path": "pkg/tcpip/header/ipv6.go",
"diff": "@@ -77,6 +77,9 @@ const (\n// IPv6MinimumMTU is the minimum MTU required by IPv6, per RFC 2460,\n// section 5.\nIPv6MinimumMTU = 1280\n+\n+ // IPv6Any is the non-routable IPv6 \"any\" meta address.\n+ IPv6Any tcpip.Address = \"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\"\n)\n// PayloadLength returns the value of the \"payload length\" field of the ipv6\n@@ -234,3 +237,12 @@ func LinkLocalAddr(linkAddr tcpip.LinkAddress) tcpip.Address {\n}\nreturn tcpip.Address(lladdrb[:])\n}\n+\n+// IsV6LinkLocalAddress determines if the provided address is an IPv6\n+// link-local address (fe80::/10).\n+func IsV6LinkLocalAddress(addr tcpip.Address) bool {\n+ if len(addr) != IPv6AddressSize {\n+ return false\n+ }\n+ return addr[0] == 0xfe && (addr[1]&0xc0) == 0x80\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/stack.go",
"new_path": "pkg/tcpip/stack/stack.go",
"diff": "@@ -729,8 +729,11 @@ func (s *Stack) FindRoute(id tcpip.NICID, localAddr, remoteAddr tcpip.Address, n\ns.mu.RLock()\ndefer s.mu.RUnlock()\n- // We don't require a route in the table to send a broadcast out on a NIC.\n- if id != 0 && remoteAddr == header.IPv4Broadcast {\n+ // We don't require a route in the table to send a broadcast, multicast or\n+ // IPv6 link-local packet out on a NIC.\n+ isBroadcast := remoteAddr == header.IPv4Broadcast\n+ isMulticast := header.IsV4MulticastAddress(remoteAddr) || header.IsV6MulticastAddress(remoteAddr)\n+ if id != 0 && (isBroadcast || isMulticast || header.IsV6LinkLocalAddress(remoteAddr)) {\nif nic, ok := s.nics[id]; ok {\nif ref := s.getRefEP(nic, localAddr, netProto); ref != nil {\nreturn makeRoute(netProto, ref.ep.ID().LocalAddress, remoteAddr, nic.linkEP.LinkAddress(), ref), nil\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/stack_test.go",
"new_path": "pkg/tcpip/stack/stack_test.go",
"diff": "@@ -680,6 +680,92 @@ func TestBroadcastNeedsNoRoute(t *testing.T) {\n}\n}\n+func TestMulticastOrIPv6LinkLocalNeedsNoRoute(t *testing.T) {\n+ for _, tc := range []struct {\n+ name string\n+ routeNeeded bool\n+ address tcpip.Address\n+ }{\n+ // IPv4 multicast address range: 224.0.0.0 - 239.255.255.255\n+ // <=> 0xe0.0x00.0x00.0x00 - 0xef.0xff.0xff.0xff\n+ {\"IPv4 Multicast 1\", false, \"\\xe0\\x00\\x00\\x00\"},\n+ {\"IPv4 Multicast 2\", false, \"\\xef\\xff\\xff\\xff\"},\n+ {\"IPv4 Unicast 1\", true, \"\\xdf\\xff\\xff\\xff\"},\n+ {\"IPv4 Unicast 2\", true, \"\\xf0\\x00\\x00\\x00\"},\n+ {\"IPv4 Unicast 3\", true, \"\\x00\\x00\\x00\\x00\"},\n+\n+ // IPv6 multicast address is 0xff[8] + flags[4] + scope[4] + groupId[112]\n+ {\"IPv6 Multicast 1\", false, \"\\xff\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\"},\n+ {\"IPv6 Multicast 2\", false, \"\\xff\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\"},\n+ {\"IPv6 Multicast 3\", false, \"\\xff\\x0f\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\"},\n+\n+ // IPv6 link-local address starts with fe80::/10.\n+ {\"IPv6 Unicast Link-Local 1\", false, \"\\xfe\\x80\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\"},\n+ {\"IPv6 Unicast Link-Local 2\", false, \"\\xfe\\x80\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\"},\n+ {\"IPv6 Unicast Link-Local 3\", false, \"\\xfe\\x80\\xff\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xff\"},\n+ {\"IPv6 Unicast Link-Local 4\", false, \"\\xfe\\xbf\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\"},\n+ {\"IPv6 Unicast Link-Local 5\", false, \"\\xfe\\xbf\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\"},\n+\n+ // IPv6 addresses that are neither multicast nor link-local.\n+ {\"IPv6 Unicast Not Link-Local 1\", true, \"\\xf0\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\"},\n+ {\"IPv6 Unicast Not Link-Local 2\", true, \"\\xf0\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\"},\n+ {\"IPv6 Unicast Not Link-local 3\", true, \"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\"},\n+ {\"IPv6 Unicast Not Link-Local 4\", true, \"\\xfe\\xc0\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\"},\n+ {\"IPv6 Unicast Not Link-Local 5\", true, \"\\xfe\\xdf\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\"},\n+ {\"IPv6 Unicast Not Link-Local 6\", true, \"\\xfd\\x80\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\"},\n+ {\"IPv6 Unicast Not Link-Local 7\", true, \"\\xf0\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\"},\n+ } {\n+ t.Run(tc.name, func(t *testing.T) {\n+ s := stack.New([]string{\"fakeNet\"}, nil, stack.Options{})\n+\n+ id, _ := channel.New(10, defaultMTU, \"\")\n+ if err := s.CreateNIC(1, id); err != nil {\n+ t.Fatalf(\"CreateNIC failed: %v\", err)\n+ }\n+\n+ s.SetRouteTable([]tcpip.Route{})\n+\n+ var anyAddr tcpip.Address\n+ if len(tc.address) == header.IPv4AddressSize {\n+ anyAddr = header.IPv4Any\n+ } else {\n+ anyAddr = header.IPv6Any\n+ }\n+\n+ // If there is no endpoint, it won't work.\n+ if _, err := s.FindRoute(1, anyAddr, tc.address, fakeNetNumber); err != tcpip.ErrNoRoute {\n+ t.Fatalf(\"got FindRoute(1, %v, %v, %v) = %v, want = %v\", anyAddr, tc.address, fakeNetNumber, err, tcpip.ErrNoRoute)\n+ }\n+\n+ if err := s.AddAddress(1, fakeNetNumber, anyAddr); err != nil {\n+ t.Fatalf(\"AddAddress(%v, %v) failed: %v\", fakeNetNumber, anyAddr, err)\n+ }\n+\n+ r, err := s.FindRoute(1, anyAddr, tc.address, fakeNetNumber)\n+ if tc.routeNeeded {\n+ // Route table is empty but we need a route, this should cause an error.\n+ if err != tcpip.ErrNoRoute {\n+ t.Fatalf(\"got FindRoute(1, %v, %v, %v) = %v, want = %v\", anyAddr, tc.address, fakeNetNumber, err, tcpip.ErrNoRoute)\n+ }\n+ } else {\n+ if err != nil {\n+ t.Fatalf(\"FindRoute(1, %v, %v, %v) failed: %v\", anyAddr, tc.address, fakeNetNumber, err)\n+ }\n+ if r.LocalAddress != anyAddr {\n+ t.Errorf(\"Bad local address: got %v, want = %v\", r.LocalAddress, anyAddr)\n+ }\n+ if r.RemoteAddress != tc.address {\n+ t.Errorf(\"Bad remote address: got %v, want = %v\", r.RemoteAddress, tc.address)\n+ }\n+ }\n+ // If the NIC doesn't exist, it won't work.\n+ if _, err := s.FindRoute(2, anyAddr, tc.address, fakeNetNumber); err != tcpip.ErrNoRoute {\n+ t.Fatalf(\"got FindRoute(2, %v, %v, %v) = %v want = %v\", anyAddr, tc.address, fakeNetNumber, err, tcpip.ErrNoRoute)\n+ }\n+ })\n+ }\n+}\n+\n// Set the subnet, then check that packet is delivered.\nfunc TestSubnetAcceptsMatchingPacket(t *testing.T) {\ns := stack.New([]string{\"fakeNet\"}, nil, stack.Options{})\n"
}
] | Go | Apache License 2.0 | google/gvisor | Allow sending of multicast and IPv6 link-local packets w/o route.
Same as with broadcast packets, sending of a multicast packet shouldn't require
accessing the route table. The same applies to IPv6 link-local addresses, which
aren't routable at all (they don't belong to any subnet by definition).
PiperOrigin-RevId: 225775870
Change-Id: Ic53e6560c125a83be2be9c3d112e66b36e8dfe7b |
259,985 | 17.12.2018 14:11:10 | 28,800 | e9c4f69f36308b370579c954badc7ad90146d6e7 | Enable recently-fixed test case for shm_test. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/shm.cc",
"new_path": "test/syscalls/linux/shm.cc",
"diff": "@@ -427,6 +427,13 @@ TEST(ShmTest, RequestingDuplicateCreationFails) {\nPosixErrorIs(EEXIST, _));\n}\n+TEST(ShmTest, NonExistentSegmentsAreNotFound) {\n+ const TempPath keyfile = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());\n+ const key_t key = ftok(keyfile.path().c_str(), 1);\n+ // Do not request creation.\n+ EXPECT_THAT(Shmget(key, kAllocSize, 0777), PosixErrorIs(ENOENT, _));\n+}\n+\nTEST(ShmTest, SegmentsSizeFixedOnCreation) {\nconst TempPath keyfile = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());\nconst key_t key = ftok(keyfile.path().c_str(), 1);\n"
}
] | Go | Apache License 2.0 | google/gvisor | Enable recently-fixed test case for shm_test.
PiperOrigin-RevId: 225887356
Change-Id: Iee000dcfc9e0168c2566edf41c66108be9b68cd6 |
259,881 | 17.12.2018 17:34:09 | 28,800 | b62591e6a813ec19a1fd74943584c4fead81f670 | Expose internal testing flag
Never to used outside of runsc tests! | [
{
"change_type": "MODIFY",
"old_path": "runsc/boot/config.go",
"new_path": "runsc/boot/config.go",
"diff": "@@ -218,7 +218,7 @@ type Config struct {\n// ToFlags returns a slice of flags that correspond to the given Config.\nfunc (c *Config) ToFlags() []string {\n- return []string{\n+ f := []string{\n\"--root=\" + c.RootDir,\n\"--debug=\" + strconv.FormatBool(c.Debug),\n\"--log=\" + c.LogFilename,\n@@ -237,4 +237,9 @@ func (c *Config) ToFlags() []string {\n\"--panic-signal=\" + strconv.Itoa(c.PanicSignal),\n\"--trace-signal=\" + strconv.Itoa(c.TraceSignal),\n}\n+ if c.TestOnlyAllowRunAsCurrentUserWithoutChroot {\n+ // Only include if set since it is never to be used by users.\n+ f = append(f, \"-TESTONLY-unsafe-nonroot=true\")\n+ }\n+ return f\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/main.go",
"new_path": "runsc/main.go",
"diff": "@@ -64,6 +64,8 @@ var (\nwatchdogAction = flag.String(\"watchdog-action\", \"log\", \"sets what action the watchdog takes when triggered: log (default), panic.\")\npanicSignal = flag.Int(\"panic-signal\", -1, \"register signal handling that panics. Usually set to SIGUSR2(12) to troubleshoot hangs. -1 disables it. This takes precendence over -trace-signal.\")\ntraceSignal = flag.Int(\"trace-signal\", -1, \"register signal handling that logs a traceback of all goroutines. Usually set to SIGUSR2(12) to troubleshoot hangs. -1 disables it.\")\n+\n+ testOnlyAllowRunAsCurrentUserWithoutChroot = 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)\n// gitRevision is set during linking.\n@@ -146,6 +148,7 @@ func main() {\nWatchdogAction: wa,\nPanicSignal: *panicSignal,\nTraceSignal: *traceSignal,\n+ TestOnlyAllowRunAsCurrentUserWithoutChroot: *testOnlyAllowRunAsCurrentUserWithoutChroot,\n}\nif len(*straceSyscalls) != 0 {\nconf.StraceSyscalls = strings.Split(*straceSyscalls, \",\")\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/test/testutil/BUILD",
"new_path": "runsc/test/testutil/BUILD",
"diff": "@@ -11,10 +11,7 @@ go_library(\n\"testutil_race.go\",\n],\nimportpath = \"gvisor.googlesource.com/gvisor/runsc/test/testutil\",\n- visibility = [\n- \"//runsc:__subpackages__\",\n- \"//test:__subpackages__\",\n- ],\n+ visibility = [\"//:sandbox\"],\ndeps = [\n\"//runsc/boot\",\n\"//runsc/specutils\",\n"
}
] | Go | Apache License 2.0 | google/gvisor | Expose internal testing flag
Never to used outside of runsc tests!
PiperOrigin-RevId: 225919013
Change-Id: Ib3b14aa2a2564b5246fb3f8933d95e01027ed186 |
259,885 | 18.12.2018 07:22:44 | 28,800 | e7b47844d969673cec06ea745d577155131ecf3b | Correctly handle filenames containing spaces in ParseProcMapsLine. | [
{
"change_type": "MODIFY",
"old_path": "test/util/BUILD",
"new_path": "test/util/BUILD",
"diff": "@@ -46,6 +46,16 @@ cc_library(\n],\n)\n+cc_test(\n+ name = \"proc_util_test\",\n+ size = \"small\",\n+ srcs = [\"proc_util_test.cc\"],\n+ deps = [\n+ \":proc_util\",\n+ \":test_util\",\n+ ],\n+)\n+\ncc_library(\nname = \"cleanup\",\ntestonly = 1,\n"
},
{
"change_type": "MODIFY",
"old_path": "test/util/proc_util.cc",
"new_path": "test/util/proc_util.cc",
"diff": "#include <algorithm>\n#include <vector>\n+#include \"absl/strings/ascii.h\"\n#include \"absl/strings/str_cat.h\"\n#include \"absl/strings/str_split.h\"\n#include \"absl/strings/string_view.h\"\n@@ -29,10 +30,15 @@ namespace testing {\n// Parses a single line from /proc/<xxx>/maps.\nPosixErrorOr<ProcMapsEntry> ParseProcMapsLine(absl::string_view line) {\nProcMapsEntry map_entry = {};\n- std::vector<std::string> parts = absl::StrSplit(line, ' ', absl::SkipEmpty());\n- // A size of 5 means there is no file name specified.\n- if (parts.size() != 5 && parts.size() != 6) {\n+ // Limit splitting to 6 parts so that if there is a file path and it contains\n+ // spaces, the file path is not split.\n+ std::vector<std::string> parts =\n+ absl::StrSplit(line, absl::MaxSplits(' ', 5), absl::SkipEmpty());\n+\n+ // parts.size() should be 6 if there is a file name specified, and 5\n+ // otherwise.\n+ if (parts.size() < 5) {\nreturn PosixError(EINVAL, absl::StrCat(\"Invalid line: \", line));\n}\n@@ -67,8 +73,9 @@ PosixErrorOr<ProcMapsEntry> ParseProcMapsLine(absl::string_view line) {\nASSIGN_OR_RETURN_ERRNO(map_entry.inode, Atoi<int64_t>(parts[4]));\nif (parts.size() == 6) {\n- // A filename is present.\n- map_entry.filename = parts[5];\n+ // A filename is present. However, absl::StrSplit retained the whitespace\n+ // between the inode number and the filename.\n+ map_entry.filename = std::string(absl::StripLeadingAsciiWhitespace(parts[5]));\n}\nreturn map_entry;\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/util/proc_util_test.cc",
"diff": "+// Copyright 2018 Google LLC\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+#include \"test/util/proc_util.h\"\n+\n+#include \"gmock/gmock.h\"\n+#include \"gtest/gtest.h\"\n+#include \"test/util/test_util.h\"\n+\n+using ::testing::IsEmpty;\n+\n+namespace gvisor {\n+namespace testing {\n+\n+namespace {\n+\n+TEST(ParseProcMapsLineTest, WithoutFilename) {\n+ auto entry = ASSERT_NO_ERRNO_AND_VALUE(\n+ ParseProcMapsLine(\"2ab4f00b7000-2ab4f00b9000 r-xp 00000000 00:00 0 \"));\n+ EXPECT_EQ(entry.start, 0x2ab4f00b7000);\n+ EXPECT_EQ(entry.end, 0x2ab4f00b9000);\n+ EXPECT_TRUE(entry.readable);\n+ EXPECT_FALSE(entry.writable);\n+ EXPECT_TRUE(entry.executable);\n+ EXPECT_TRUE(entry.priv);\n+ EXPECT_EQ(entry.offset, 0);\n+ EXPECT_EQ(entry.major, 0);\n+ EXPECT_EQ(entry.minor, 0);\n+ EXPECT_EQ(entry.inode, 0);\n+ EXPECT_THAT(entry.filename, IsEmpty());\n+}\n+\n+TEST(ParseProcMapsLineTest, WithFilename) {\n+ auto entry = ASSERT_NO_ERRNO_AND_VALUE(\n+ ParseProcMapsLine(\"00407000-00408000 rw-p 00006000 00:0e 10 \"\n+ \" /bin/cat\"));\n+ EXPECT_EQ(entry.start, 0x407000);\n+ EXPECT_EQ(entry.end, 0x408000);\n+ EXPECT_TRUE(entry.readable);\n+ EXPECT_TRUE(entry.writable);\n+ EXPECT_FALSE(entry.executable);\n+ EXPECT_TRUE(entry.priv);\n+ EXPECT_EQ(entry.offset, 0x6000);\n+ EXPECT_EQ(entry.major, 0);\n+ EXPECT_EQ(entry.minor, 0x0e);\n+ EXPECT_EQ(entry.inode, 10);\n+ EXPECT_EQ(entry.filename, \"/bin/cat\");\n+}\n+\n+TEST(ParseProcMapsLineTest, WithFilenameContainingSpaces) {\n+ auto entry = ASSERT_NO_ERRNO_AND_VALUE(\n+ ParseProcMapsLine(\"7f26b3b12000-7f26b3b13000 rw-s 00000000 00:05 1432484 \"\n+ \" /dev/zero (deleted)\"));\n+ EXPECT_EQ(entry.start, 0x7f26b3b12000);\n+ EXPECT_EQ(entry.end, 0x7f26b3b13000);\n+ EXPECT_TRUE(entry.readable);\n+ EXPECT_TRUE(entry.writable);\n+ EXPECT_FALSE(entry.executable);\n+ EXPECT_FALSE(entry.priv);\n+ EXPECT_EQ(entry.offset, 0);\n+ EXPECT_EQ(entry.major, 0);\n+ EXPECT_EQ(entry.minor, 0x05);\n+ EXPECT_EQ(entry.inode, 1432484);\n+ EXPECT_EQ(entry.filename, \"/dev/zero (deleted)\");\n+}\n+\n+} // namespace\n+\n+} // namespace testing\n+} // namespace gvisor\n"
}
] | Go | Apache License 2.0 | google/gvisor | Correctly handle filenames containing spaces in ParseProcMapsLine.
PiperOrigin-RevId: 225992500
Change-Id: Icc8b1675f1cb625fc5e8ef7389beb42fa7bfaa13 |
259,992 | 18.12.2018 10:27:16 | 28,800 | 03226cd95055aee73d4e4dfcb4954490b4fd8a2d | Add BPFAction type with Stringer | [
{
"change_type": "MODIFY",
"old_path": "pkg/abi/linux/seccomp.go",
"new_path": "pkg/abi/linux/seccomp.go",
"diff": "package linux\n+import \"fmt\"\n+\n// Seccomp constants taken from <linux/seccomp.h>.\nconst (\nSECCOMP_MODE_NONE = 0\nSECCOMP_MODE_FILTER = 2\n- SECCOMP_RET_KILL_PROCESS = 0x80000000\n- SECCOMP_RET_KILL_THREAD = 0x00000000\n- SECCOMP_RET_TRAP = 0x00030000\n- SECCOMP_RET_ERRNO = 0x00050000\n- SECCOMP_RET_TRACE = 0x7ff00000\n- SECCOMP_RET_ALLOW = 0x7fff0000\n-\n+ SECCOMP_RET_ACTION_FULL = 0xffff0000\nSECCOMP_RET_ACTION = 0x7fff0000\nSECCOMP_RET_DATA = 0x0000ffff\n@@ -33,3 +29,37 @@ const (\nSECCOMP_FILTER_FLAG_TSYNC = 1\nSECCOMP_GET_ACTION_AVAIL = 2\n)\n+\n+type BPFAction uint32\n+\n+const (\n+ SECCOMP_RET_KILL_PROCESS BPFAction = 0x80000000\n+ SECCOMP_RET_KILL_THREAD = 0x00000000\n+ SECCOMP_RET_TRAP = 0x00030000\n+ SECCOMP_RET_ERRNO = 0x00050000\n+ SECCOMP_RET_TRACE = 0x7ff00000\n+ SECCOMP_RET_ALLOW = 0x7fff0000\n+)\n+\n+func (a BPFAction) String() string {\n+ switch a & SECCOMP_RET_ACTION_FULL {\n+ case SECCOMP_RET_KILL_PROCESS:\n+ return \"kill process\"\n+ case SECCOMP_RET_KILL_THREAD:\n+ return \"kill thread\"\n+ case SECCOMP_RET_TRAP:\n+ return fmt.Sprintf(\"trap (%d)\", a.Data())\n+ case SECCOMP_RET_ERRNO:\n+ return fmt.Sprintf(\"errno (%d)\", a.Data())\n+ case SECCOMP_RET_TRACE:\n+ return fmt.Sprintf(\"trace (%d)\", a.Data())\n+ case SECCOMP_RET_ALLOW:\n+ return \"allow\"\n+ }\n+ return fmt.Sprintf(\"invalid action: %#x\", a)\n+}\n+\n+// Data returns the SECCOMP_RET_DATA portion of the action.\n+func (a BPFAction) Data() uint16 {\n+ return uint16(a & SECCOMP_RET_DATA)\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/seccomp/seccomp.go",
"new_path": "pkg/seccomp/seccomp.go",
"diff": "@@ -33,16 +33,6 @@ const (\ndefaultLabel = \"default_action\"\n)\n-func actionName(a uint32) string {\n- switch a {\n- case linux.SECCOMP_RET_KILL_PROCESS:\n- return \"kill process\"\n- case linux.SECCOMP_RET_TRAP:\n- return \"trap\"\n- }\n- panic(fmt.Sprintf(\"invalid action: %d\", a))\n-}\n-\n// Install generates BPF code based on the set of syscalls provided. It only\n// allows syscalls that conform to the specification. Syscalls that violate the\n// specification will trigger RET_KILL_PROCESS, except for the cases below.\n@@ -67,12 +57,12 @@ func Install(rules SyscallRules) error {\n// Uncomment to get stack trace when there is a violation.\n// defaultAction = uint32(linux.SECCOMP_RET_TRAP)\n- log.Infof(\"Installing seccomp filters for %d syscalls (action=%s)\", len(rules), actionName(defaultAction))\n+ log.Infof(\"Installing seccomp filters for %d syscalls (action=%v)\", len(rules), defaultAction)\ninstrs, err := BuildProgram([]RuleSet{\nRuleSet{\nRules: rules,\n- Action: uint32(linux.SECCOMP_RET_ALLOW),\n+ Action: linux.SECCOMP_RET_ALLOW,\n},\n}, defaultAction)\nif log.IsLogging(log.Debug) {\n@@ -95,21 +85,21 @@ func Install(rules SyscallRules) error {\nreturn nil\n}\n-func defaultAction() (uint32, error) {\n+func defaultAction() (linux.BPFAction, error) {\navailable, err := isKillProcessAvailable()\nif err != nil {\nreturn 0, err\n}\nif available {\n- return uint32(linux.SECCOMP_RET_KILL_PROCESS), nil\n+ return linux.SECCOMP_RET_KILL_PROCESS, nil\n}\n- return uint32(linux.SECCOMP_RET_TRAP), nil\n+ return linux.SECCOMP_RET_TRAP, nil\n}\n// RuleSet is a set of rules and associated action.\ntype RuleSet struct {\nRules SyscallRules\n- Action uint32\n+ Action linux.BPFAction\n// Vsyscall indicates that a check is made for a function being called\n// from kernel mappings. This is where the vsyscall page is located\n@@ -127,7 +117,7 @@ var SyscallName = func(sysno uintptr) string {\n// BuildProgram builds a BPF program from the given map of actions to matching\n// SyscallRules. The single generated program covers all provided RuleSets.\n-func BuildProgram(rules []RuleSet, defaultAction uint32) ([]linux.BPFInstruction, error) {\n+func BuildProgram(rules []RuleSet, defaultAction linux.BPFAction) ([]linux.BPFInstruction, error) {\nprogram := bpf.NewProgramBuilder()\n// Be paranoid and check that syscall is done in the expected architecture.\n@@ -147,7 +137,7 @@ func BuildProgram(rules []RuleSet, defaultAction uint32) ([]linux.BPFInstruction\nif err := program.AddLabel(defaultLabel); err != nil {\nreturn nil, err\n}\n- program.AddStmt(bpf.Ret|bpf.K, defaultAction)\n+ program.AddStmt(bpf.Ret|bpf.K, uint32(defaultAction))\nreturn program.Instructions()\n}\n@@ -217,7 +207,7 @@ func checkArgsLabel(sysno uintptr) string {\n// not insert a jump to the default action at the end and it is the\n// responsibility of the caller to insert an appropriate jump after calling\n// this function.\n-func addSyscallArgsCheck(p *bpf.ProgramBuilder, rules []Rule, action uint32, ruleSetIdx int, sysno uintptr) error {\n+func addSyscallArgsCheck(p *bpf.ProgramBuilder, rules []Rule, action linux.BPFAction, ruleSetIdx int, sysno uintptr) error {\nfor ruleidx, rule := range rules {\nlabelled := false\nfor i, arg := range rule {\n@@ -240,7 +230,7 @@ func addSyscallArgsCheck(p *bpf.ProgramBuilder, rules []Rule, action uint32, rul\n}\n// Matched, emit the given action.\n- p.AddStmt(bpf.Ret|bpf.K, action)\n+ p.AddStmt(bpf.Ret|bpf.K, uint32(action))\n// Label the end of the rule if necessary. This is added for\n// the jumps above when the argument check fails.\n@@ -319,7 +309,7 @@ func buildBSTProgram(n *node, rules []RuleSet, program *bpf.ProgramBuilder) erro\n// Emit matchers.\nif len(rs.Rules[sysno]) == 0 {\n// This is a blanket action.\n- program.AddStmt(bpf.Ret|bpf.K, rs.Action)\n+ program.AddStmt(bpf.Ret|bpf.K, uint32(rs.Action))\nemitted = true\n} else {\n// Add an argument check for these particular\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/seccomp/seccomp_test.go",
"new_path": "pkg/seccomp/seccomp_test.go",
"diff": "@@ -72,12 +72,12 @@ func TestBasic(t *testing.T) {\ndata seccompData\n// want is the expected return value of the BPF program.\n- want uint32\n+ want linux.BPFAction\n}\nfor _, test := range []struct {\nruleSets []RuleSet\n- defaultAction uint32\n+ defaultAction linux.BPFAction\nspecs []spec\n}{\n{\n@@ -357,7 +357,7 @@ func TestBasic(t *testing.T) {\nt.Errorf(\"%s: bpf.Exec() got error: %v\", spec.desc, err)\ncontinue\n}\n- if got != spec.want {\n+ if got != uint32(spec.want) {\nt.Errorf(\"%s: bpd.Exec() = %d, want: %d\", spec.desc, got, spec.want)\n}\n}\n@@ -380,9 +380,9 @@ func TestRandom(t *testing.T) {\ninstrs, err := BuildProgram([]RuleSet{\nRuleSet{\nRules: syscallRules,\n- Action: uint32(linux.SECCOMP_RET_ALLOW),\n+ Action: linux.SECCOMP_RET_ALLOW,\n},\n- }, uint32(linux.SECCOMP_RET_TRAP))\n+ }, linux.SECCOMP_RET_TRAP)\nif err != nil {\nt.Fatalf(\"buildProgram() got error: %v\", err)\n}\n@@ -397,11 +397,11 @@ func TestRandom(t *testing.T) {\nt.Errorf(\"bpf.Exec() got error: %v, for syscall %d\", err, i)\ncontinue\n}\n- want := uint32(linux.SECCOMP_RET_TRAP)\n+ want := linux.SECCOMP_RET_TRAP\nif _, ok := syscallRules[uintptr(i)]; ok {\nwant = linux.SECCOMP_RET_ALLOW\n}\n- if got != want {\n+ if got != uint32(want) {\nt.Errorf(\"bpf.Exec() = %d, want: %d, for syscall %d\", got, want, i)\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/seccomp.go",
"new_path": "pkg/sentry/kernel/seccomp.go",
"diff": "@@ -27,24 +27,6 @@ import (\nconst maxSyscallFilterInstructions = 1 << 15\n-type seccompResult int\n-\n-const (\n- // seccompResultDeny indicates that a syscall should not be executed.\n- seccompResultDeny seccompResult = iota\n-\n- // seccompResultAllow indicates that a syscall should be executed.\n- seccompResultAllow\n-\n- // seccompResultKill indicates that the task should be killed immediately,\n- // with the exit status indicating that the task was killed by SIGSYS.\n- seccompResultKill\n-\n- // seccompResultTrace indicates that a ptracer was successfully notified as\n- // a result of a SECCOMP_RET_TRACE.\n- seccompResultTrace\n-)\n-\n// seccompData is equivalent to struct seccomp_data, which contains the data\n// passed to seccomp-bpf filters.\ntype seccompData struct {\n@@ -83,48 +65,47 @@ func seccompSiginfo(t *Task, errno, sysno int32, ip usermem.Addr) *arch.SignalIn\n// in because vsyscalls do not use the values in t.Arch().)\n//\n// Preconditions: The caller must be running on the task goroutine.\n-func (t *Task) checkSeccompSyscall(sysno int32, args arch.SyscallArguments, ip usermem.Addr) seccompResult {\n- result := t.evaluateSyscallFilters(sysno, args, ip)\n- switch result & linux.SECCOMP_RET_ACTION {\n+func (t *Task) checkSeccompSyscall(sysno int32, args arch.SyscallArguments, ip usermem.Addr) linux.BPFAction {\n+ result := linux.BPFAction(t.evaluateSyscallFilters(sysno, args, ip))\n+ action := result & linux.SECCOMP_RET_ACTION\n+ switch action {\ncase linux.SECCOMP_RET_TRAP:\n// \"Results in the kernel sending a SIGSYS signal to the triggering\n// task without executing the system call. ... The SECCOMP_RET_DATA\n// portion of the return value will be passed as si_errno.\" -\n// Documentation/prctl/seccomp_filter.txt\n- t.SendSignal(seccompSiginfo(t, int32(result&linux.SECCOMP_RET_DATA), sysno, ip))\n- return seccompResultDeny\n+ t.SendSignal(seccompSiginfo(t, int32(result.Data()), sysno, ip))\ncase linux.SECCOMP_RET_ERRNO:\n// \"Results in the lower 16-bits of the return value being passed to\n// userland as the errno without executing the system call.\"\n- t.Arch().SetReturn(-uintptr(result & linux.SECCOMP_RET_DATA))\n- return seccompResultDeny\n+ t.Arch().SetReturn(-uintptr(result.Data()))\ncase linux.SECCOMP_RET_TRACE:\n// \"When returned, this value will cause the kernel to attempt to\n// notify a ptrace()-based tracer prior to executing the system call.\n// If there is no tracer present, -ENOSYS is returned to userland and\n// the system call is not executed.\"\n- if t.ptraceSeccomp(uint16(result & linux.SECCOMP_RET_DATA)) {\n- return seccompResultTrace\n- }\n+ if !t.ptraceSeccomp(result.Data()) {\n// This useless-looking temporary is needed because Go.\ntmp := uintptr(syscall.ENOSYS)\nt.Arch().SetReturn(-tmp)\n- return seccompResultDeny\n+ return linux.SECCOMP_RET_ERRNO\n+ }\ncase linux.SECCOMP_RET_ALLOW:\n// \"Results in the system call being executed.\"\n- return seccompResultAllow\ncase linux.SECCOMP_RET_KILL_THREAD:\n// \"Results in the task exiting immediately without executing the\n// system call. The exit status of the task will be SIGSYS, not\n// SIGKILL.\"\n- fallthrough\n- default: // consistent with Linux\n- return seccompResultKill\n+\n+ default:\n+ // consistent with Linux\n+ return linux.SECCOMP_RET_KILL_THREAD\n}\n+ return action\n}\nfunc (t *Task) evaluateSyscallFilters(sysno int32, args arch.SyscallArguments, ip usermem.Addr) uint32 {\n@@ -155,7 +136,7 @@ func (t *Task) evaluateSyscallFilters(sysno int32, args arch.SyscallArguments, i\nthisRet, err := bpf.Exec(f.([]bpf.Program)[i], input)\nif err != nil {\nt.Debugf(\"seccomp-bpf filter %d returned error: %v\", i, err)\n- thisRet = linux.SECCOMP_RET_KILL_THREAD\n+ thisRet = uint32(linux.SECCOMP_RET_KILL_THREAD)\n}\n// \"If multiple filters exist, the return value for the evaluation of a\n// given system call will always use the highest precedent value.\" -\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/task_syscall.go",
"new_path": "pkg/sentry/kernel/task_syscall.go",
"diff": "@@ -199,16 +199,16 @@ func (t *Task) doSyscall() taskRunState {\n// is rare), not needed for correctness.\nif t.syscallFilters.Load() != nil {\nswitch r := t.checkSeccompSyscall(int32(sysno), args, usermem.Addr(t.Arch().IP())); r {\n- case seccompResultDeny:\n+ case linux.SECCOMP_RET_ERRNO, linux.SECCOMP_RET_TRAP:\nt.Debugf(\"Syscall %d: denied by seccomp\", sysno)\nreturn (*runSyscallExit)(nil)\n- case seccompResultAllow:\n+ case linux.SECCOMP_RET_ALLOW:\n// ok\n- case seccompResultKill:\n+ case linux.SECCOMP_RET_KILL_THREAD:\nt.Debugf(\"Syscall %d: killed by seccomp\", sysno)\nt.PrepareExit(ExitStatus{Signo: int(linux.SIGSYS)})\nreturn (*runExit)(nil)\n- case seccompResultTrace:\n+ case linux.SECCOMP_RET_TRACE:\nt.Debugf(\"Syscall %d: stopping for PTRACE_EVENT_SECCOMP\", sysno)\nreturn (*runSyscallAfterPtraceEventSeccomp)(nil)\ndefault:\n@@ -345,14 +345,18 @@ func (t *Task) doVsyscall(addr usermem.Addr, sysno uintptr) taskRunState {\nargs := t.Arch().SyscallArgs()\nif t.syscallFilters.Load() != nil {\nswitch r := t.checkSeccompSyscall(int32(sysno), args, addr); r {\n- case seccompResultDeny:\n+ case linux.SECCOMP_RET_ERRNO, linux.SECCOMP_RET_TRAP:\nt.Debugf(\"vsyscall %d, caller %x: denied by seccomp\", sysno, t.Arch().Value(caller))\nreturn (*runApp)(nil)\n- case seccompResultAllow:\n+ case linux.SECCOMP_RET_ALLOW:\n// ok\n- case seccompResultTrace:\n+ case linux.SECCOMP_RET_TRACE:\nt.Debugf(\"vsyscall %d, caller %x: stopping for PTRACE_EVENT_SECCOMP\", sysno, t.Arch().Value(caller))\nreturn &runVsyscallAfterPtraceEventSeccomp{addr, sysno, caller}\n+ case linux.SECCOMP_RET_KILL_THREAD:\n+ t.Debugf(\"vsyscall %d: killed by seccomp\", sysno)\n+ t.PrepareExit(ExitStatus{Signo: int(linux.SIGSYS)})\n+ return (*runExit)(nil)\ndefault:\npanic(fmt.Sprintf(\"Unknown seccomp result %d\", r))\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/ptrace/subprocess_linux.go",
"new_path": "pkg/sentry/platform/ptrace/subprocess_linux.go",
"diff": "@@ -38,7 +38,7 @@ const syscallEvent syscall.Signal = 0x80\n// Precondition: the runtime OS thread must be locked.\nfunc probeSeccomp() bool {\n// Create a completely new, destroyable process.\n- t, err := attachedThread(0, uint32(linux.SECCOMP_RET_ERRNO))\n+ t, err := attachedThread(0, linux.SECCOMP_RET_ERRNO)\nif err != nil {\npanic(fmt.Sprintf(\"seccomp probe failed: %v\", err))\n}\n@@ -112,14 +112,14 @@ func createStub() (*thread, error) {\n// ptrace emulation check. This simplifies using SYSEMU, since seccomp\n// will never run for emulation. Seccomp will only run for injected\n// system calls, and thus we can use RET_KILL as our violation action.\n- var defaultAction uint32\n+ var defaultAction linux.BPFAction\nif probeSeccomp() {\nlog.Infof(\"Latest seccomp behavior found (kernel >= 4.8 likely)\")\n- defaultAction = uint32(linux.SECCOMP_RET_KILL_THREAD)\n+ defaultAction = linux.SECCOMP_RET_KILL_THREAD\n} else {\n// We must rely on SYSEMU behavior; tracing with SYSEMU is broken.\nlog.Infof(\"Legacy seccomp behavior found (kernel < 4.8 likely)\")\n- defaultAction = uint32(linux.SECCOMP_RET_ALLOW)\n+ defaultAction = linux.SECCOMP_RET_ALLOW\n}\n// When creating the new child process, we specify SIGKILL as the\n@@ -135,7 +135,7 @@ func createStub() (*thread, error) {\n// attachedThread returns a new attached thread.\n//\n// Precondition: the runtime OS thread must be locked.\n-func attachedThread(flags uintptr, defaultAction uint32) (*thread, error) {\n+func attachedThread(flags uintptr, defaultAction linux.BPFAction) (*thread, error) {\n// Create a BPF program that allows only the system calls needed by the\n// stub and all its children. This is used to create child stubs\n// (below), so we must include the ability to fork, but otherwise lock\n@@ -148,11 +148,11 @@ func attachedThread(flags uintptr, defaultAction uint32) (*thread, error) {\nsyscall.SYS_TIME: {},\n309: {}, // SYS_GETCPU.\n},\n- Action: uint32(linux.SECCOMP_RET_TRAP),\n+ Action: linux.SECCOMP_RET_TRAP,\nVsyscall: true,\n},\n}\n- if defaultAction != uint32(linux.SECCOMP_RET_ALLOW) {\n+ if defaultAction != linux.SECCOMP_RET_ALLOW {\nrules = append(rules, seccomp.RuleSet{\nRules: seccomp.SyscallRules{\nsyscall.SYS_CLONE: []seccomp.Rule{\n@@ -191,7 +191,7 @@ func attachedThread(flags uintptr, defaultAction uint32) (*thread, error) {\nsyscall.SYS_MMAP: {},\nsyscall.SYS_MUNMAP: {},\n},\n- Action: uint32(linux.SECCOMP_RET_ALLOW),\n+ Action: linux.SECCOMP_RET_ALLOW,\n})\n}\ninstrs, err := seccomp.BuildProgram(rules, defaultAction)\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/seccomp.cc",
"new_path": "test/syscalls/linux/seccomp.cc",
"diff": "@@ -215,6 +215,25 @@ TEST(SeccompTest, SeccompAppliesToVsyscall) {\n<< \"status \" << status;\n}\n+TEST(SeccompTest, RetKillVsyscallCausesDeathBySIGSYS) {\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(IsVsyscallEnabled()));\n+\n+ pid_t const pid = fork();\n+ if (pid == 0) {\n+ // Register a signal handler for SIGSYS that we don't expect to be invoked.\n+ RegisterSignalHandler(\n+ SIGSYS, +[](int, siginfo_t*, void*) { _exit(1); });\n+ ApplySeccompFilter(SYS_time, SECCOMP_RET_KILL);\n+ vsyscall_time(nullptr); // Should result in death.\n+ TEST_CHECK_MSG(false, \"Survived invocation of test syscall\");\n+ }\n+ ASSERT_THAT(pid, SyscallSucceeds());\n+ int status;\n+ ASSERT_THAT(waitpid(pid, &status, 0), SyscallSucceedsWithValue(pid));\n+ EXPECT_TRUE(WIFSIGNALED(status) && WTERMSIG(status) == SIGSYS)\n+ << \"status \" << status;\n+}\n+\nTEST(SeccompTest, RetTraceWithoutPtracerReturnsENOSYS) {\npid_t const pid = fork();\nif (pid == 0) {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add BPFAction type with Stringer
PiperOrigin-RevId: 226018694
Change-Id: I98965e26fe565f37e98e5df5f997363ab273c91b |
259,885 | 18.12.2018 11:51:22 | 28,800 | 3b3f02627870a06de4e1fc3178d5bd23f627a97a | Truncate ar before calling mm.breakCopyOnWriteLocked().
... as required by the latter's precondition. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/mm/pma.go",
"new_path": "pkg/sentry/mm/pma.go",
"diff": "@@ -138,6 +138,10 @@ func (mm *MemoryManager) getPMAsLocked(ctx context.Context, vseg vmaIterator, ar\nvar cowerr error\nif opts.breakCOW {\n+ if pend.Start() < ar.End {\n+ // Adjust ar to reflect missing pmas.\n+ ar.End = pend.Start()\n+ }\nvar invalidated bool\npend, invalidated, cowerr = mm.breakCopyOnWriteLocked(pstart, ar)\nif pend.Start() <= ar.Start {\n@@ -189,6 +193,10 @@ func (mm *MemoryManager) getVecPMAsLocked(ctx context.Context, ars usermem.AddrR\nif !pstart.Ok() {\npstart = mm.findOrSeekPrevUpperBoundPMA(ar.Start, pend)\n}\n+ if pend.Start() < ar.End {\n+ // Adjust ar to reflect missing pmas.\n+ ar.End = pend.Start()\n+ }\npend, _, cowerr = mm.breakCopyOnWriteLocked(pstart, ar)\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Truncate ar before calling mm.breakCopyOnWriteLocked().
... as required by the latter's precondition.
PiperOrigin-RevId: 226033824
Change-Id: I6bc46d0e100c61cc58cb5fc69e70c4ca905cd92d |
259,885 | 18.12.2018 12:15:22 | 28,800 | 0759f3afee5b02d1f43b54f90111086cdc78338e | Allow PosixErrorOr<T> to be implicitly constructible from copyable T. | [
{
"change_type": "MODIFY",
"old_path": "test/util/posix_error.h",
"new_path": "test/util/posix_error.h",
"diff": "@@ -74,9 +74,9 @@ class ABSL_MUST_USE_RESULT PosixError {\ntemplate <typename T>\nclass ABSL_MUST_USE_RESULT PosixErrorOr {\npublic:\n- PosixErrorOr(const PosixError& error); // NOLINT\n- explicit PosixErrorOr(const T& value);\n- PosixErrorOr(T&& value); // NOLINT\n+ PosixErrorOr(const PosixError& error);\n+ PosixErrorOr(const T& value);\n+ PosixErrorOr(T&& value);\nPosixErrorOr(PosixErrorOr&& other) = default;\nPosixErrorOr& operator=(PosixErrorOr&& other) = default;\n"
}
] | Go | Apache License 2.0 | google/gvisor | Allow PosixErrorOr<T> to be implicitly constructible from copyable T.
PiperOrigin-RevId: 226037787
Change-Id: I5fb5f55f68b67dd86bbff46349b46e3e8e6b9d1b |
259,885 | 18.12.2018 13:49:22 | 28,800 | 898838e34d1b0c76405f3e7f7f5fa7f1a444da0e | Fix mremap expansion with mm.checkInvariants = true.
Also remove useless RSS changes in mm.movePMAsLocked(). | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/mm/pma.go",
"new_path": "pkg/sentry/mm/pma.go",
"diff": "@@ -679,7 +679,7 @@ func Unpin(prs []PinnedRange) {\n// movePMAsLocked moves all pmas in oldAR to newAR.\n//\n// Preconditions: mm.activeMu must be locked for writing. oldAR.Length() != 0.\n-// oldAR.Length() == newAR.Length(). !oldAR.Overlaps(newAR).\n+// oldAR.Length() <= newAR.Length(). !oldAR.Overlaps(newAR).\n// mm.pmas.IsEmptyRange(newAR). oldAR and newAR must be page-aligned.\nfunc (mm *MemoryManager) movePMAsLocked(oldAR, newAR usermem.AddrRange) {\nif checkInvariants {\n@@ -689,8 +689,8 @@ func (mm *MemoryManager) movePMAsLocked(oldAR, newAR usermem.AddrRange) {\nif !newAR.WellFormed() || newAR.Length() <= 0 || !newAR.IsPageAligned() {\npanic(fmt.Sprintf(\"invalid newAR: %v\", newAR))\n}\n- if oldAR.Length() != newAR.Length() {\n- panic(fmt.Sprintf(\"old and new address ranges have different lengths: %v, %v\", oldAR, newAR))\n+ if oldAR.Length() > newAR.Length() {\n+ panic(fmt.Sprintf(\"old address range %v may contain pmas that will not fit in new address range %v\", oldAR, newAR))\n}\nif oldAR.Overlaps(newAR) {\npanic(fmt.Sprintf(\"old and new address ranges overlap: %v, %v\", oldAR, newAR))\n@@ -710,8 +710,9 @@ func (mm *MemoryManager) movePMAsLocked(oldAR, newAR usermem.AddrRange) {\noldAR: pseg.Range(),\npma: pseg.Value(),\n})\n- mm.removeRSSLocked(pseg.Range())\npseg = mm.pmas.Remove(pseg).NextSegment()\n+ // No RSS change is needed since we're re-inserting the same pmas\n+ // below.\n}\noff := newAR.Start - oldAR.Start\n@@ -719,7 +720,6 @@ func (mm *MemoryManager) movePMAsLocked(oldAR, newAR usermem.AddrRange) {\nfor i := range movedPMAs {\nmpma := &movedPMAs[i]\npmaNewAR := usermem.AddrRange{mpma.oldAR.Start + off, mpma.oldAR.End + off}\n- mm.addRSSLocked(pmaNewAR)\npgap = mm.pmas.Insert(pgap, pmaNewAR, mpma.pma).NextGap()\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix mremap expansion with mm.checkInvariants = true.
Also remove useless RSS changes in mm.movePMAsLocked().
PiperOrigin-RevId: 226052996
Change-Id: If59fd259b93238fb2f15c1c8ebfeda14cb590a87 |
259,975 | 19.12.2018 13:14:53 | 28,800 | ff7178a4d10f9f1fb34e54fed5ef27cfbff5d6f9 | Implement pwritev2.
Implement pwritev2 and associated unit tests.
Clean up preadv2 unit tests.
Tag RWF_ flags in both preadv2 and pwritev2 with associated bug tickets. | [
{
"change_type": "MODIFY",
"old_path": "pkg/abi/linux/file.go",
"new_path": "pkg/abi/linux/file.go",
"diff": "@@ -152,9 +152,10 @@ const (\n// Values for preadv2/pwritev2.\nconst (\n- RWF_HIPRI = 0x0001\n- RWF_DSYNC = 0X0002\n- RWF_SYNC = 0x0004\n+ RWF_HIPRI = 0x00000001\n+ RWF_DSYNC = 0x00000002\n+ RWF_SYNC = 0x00000004\n+ RWF_VALID = RWF_HIPRI | RWF_DSYNC | RWF_SYNC\n)\n// Stat represents struct stat.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/linux64.go",
"new_path": "pkg/sentry/syscalls/linux/linux64.go",
"diff": "@@ -377,7 +377,7 @@ var AMD64 = &kernel.SyscallTable{\n// Syscalls after 325 are \"backports\" from versions of Linux after 4.4.\n// 326: CopyFileRange,\n327: Preadv2,\n- // 328: Pwritev2, // Pwritev2, TODO\n+ 328: Pwritev2,\n},\nEmulate: map[usermem.Addr]uintptr{\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/sys_read.go",
"new_path": "pkg/sentry/syscalls/linux/sys_read.go",
"diff": "@@ -188,14 +188,20 @@ func Preadv(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Syscal\n}\n// Preadv2 implements linux syscall preadv2(2).\n+// TODO: Implement RWF_HIPRI functionality.\nfunc Preadv2(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {\n+ // While the syscall is\n+ // preadv2(int fd, struct iovec* iov, int iov_cnt, off_t offset, int flags)\n+ // the linux internal call\n+ // (https://elixir.bootlin.com/linux/v4.18/source/fs/read_write.c#L1248)\n+ // splits the offset argument into a high/low value for compatibility with\n+ // 32-bit architectures. The flags argument is the 5th argument.\n+\nfd := kdefs.FD(args[0].Int())\naddr := args[1].Pointer()\niovcnt := int(args[2].Int())\noffset := args[3].Int64()\n- flags := int(args[4].Int())\n-\n- validFlags := linux.RWF_HIPRI\n+ flags := int(args[5].Int())\nfile := t.FDMap().GetFile(fd)\nif file == nil {\n@@ -219,14 +225,8 @@ func Preadv2(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sysca\n}\n// Check flags field.\n- if flags != 0 {\n- if flags&^validFlags != 0 {\n- return 0, nil, syserror.EINVAL\n- }\n- // RWF_HIPRI must be called on a file with O_DIRECT flag set.\n- if flags&linux.RWF_HIPRI != 0 && !file.Flags().Direct {\n- return 0, nil, syserror.EINVAL\n- }\n+ if flags&^linux.RWF_VALID != 0 {\n+ return 0, nil, syserror.EOPNOTSUPP\n}\n// Read the iovecs that specify the destination of the read.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/sys_write.go",
"new_path": "pkg/sentry/syscalls/linux/sys_write.go",
"diff": "@@ -187,6 +187,72 @@ func Pwritev(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sysca\nreturn uintptr(n), nil, handleIOError(t, n != 0, err, kernel.ERESTARTSYS, \"pwritev\", file)\n}\n+// Pwritev2 implements linux syscall pwritev2(2).\n+// TODO: Implement RWF_HIPRI functionality.\n+// TODO: Implement O_SYNC and D_SYNC functionality.\n+func Pwritev2(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {\n+ // While the syscall is\n+ // pwritev2(int fd, struct iovec* iov, int iov_cnt, off_t offset, int flags)\n+ // the linux internal call\n+ // (https://elixir.bootlin.com/linux/v4.18/source/fs/read_write.c#L1354)\n+ // splits the offset argument into a high/low value for compatibility with\n+ // 32-bit architectures. The flags argument is the 5th argument.\n+\n+ fd := kdefs.FD(args[0].Int())\n+ addr := args[1].Pointer()\n+ iovcnt := int(args[2].Int())\n+ offset := args[3].Int64()\n+ flags := int(args[5].Int())\n+\n+ if int(args[4].Int())&0x4 == 1 {\n+ return 0, nil, syserror.EACCES\n+ }\n+\n+ file := t.FDMap().GetFile(fd)\n+ if file == nil {\n+ return 0, nil, syserror.EBADF\n+ }\n+ defer file.DecRef()\n+\n+ // Check that the offset is legitimate.\n+ if offset < -1 {\n+ return 0, nil, syserror.EINVAL\n+ }\n+\n+ // Is writing at an offset supported?\n+ if offset > -1 && !file.Flags().Pwrite {\n+ return 0, nil, syserror.ESPIPE\n+ }\n+\n+ if flags&^linux.RWF_VALID != 0 {\n+ return uintptr(flags), nil, syserror.EOPNOTSUPP\n+ }\n+\n+ // Check that the file is writeable.\n+ if !file.Flags().Write {\n+ return 0, nil, syserror.EBADF\n+ }\n+\n+ // Read the iovecs that specify the source of the write.\n+ src, err := t.IovecsIOSequence(addr, iovcnt, usermem.IOOpts{\n+ AddressSpaceActive: true,\n+ })\n+ if err != nil {\n+ return 0, nil, err\n+ }\n+\n+ // If pwritev2 is called with an offset of -1, writev is called.\n+ if offset == -1 {\n+ n, err := writev(t, file, src)\n+ t.IOUsage().AccountWriteSyscall(n)\n+ return uintptr(n), nil, handleIOError(t, n != 0, err, kernel.ERESTARTSYS, \"pwritev2\", file)\n+ }\n+\n+ n, err := pwritev(t, file, src, offset)\n+ t.IOUsage().AccountWriteSyscall(n)\n+ return uintptr(n), nil, handleIOError(t, n != 0, err, kernel.ERESTARTSYS, \"pwritev2\", file)\n+}\n+\nfunc writev(t *kernel.Task, f *fs.File, src usermem.IOSequence) (int64, error) {\nn, err := f.Writev(t, src)\nif err != syserror.ErrWouldBlock || f.Flags().NonBlocking {\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/BUILD",
"new_path": "test/syscalls/BUILD",
"diff": "@@ -219,6 +219,8 @@ syscall_test(\ntest = \"//test/syscalls/linux:pty_test\",\n)\n+syscall_test(test = \"//test/syscalls/linux:pwritev2_test\")\n+\nsyscall_test(test = \"//test/syscalls/linux:pwrite64_test\")\nsyscall_test(test = \"//test/syscalls/linux:read_test\")\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/BUILD",
"new_path": "test/syscalls/linux/BUILD",
"diff": "@@ -1338,18 +1338,18 @@ cc_binary(\nname = \"preadv2_test\",\ntestonly = 1,\nsrcs = [\n+ \"file_base.h\",\n\"preadv2.cc\",\n- \"readv_common.cc\",\n- \"readv_common.h\",\n],\nlinkstatic = 1,\ndeps = [\n- \":file_base\",\n\"//test/util:file_descriptor\",\n- \"//test/util:memory_util\",\n+ \"//test/util:posix_error\",\n\"//test/util:temp_path\",\n\"//test/util:test_main\",\n\"//test/util:test_util\",\n+ \"@com_google_absl//absl/memory\",\n+ \"@com_google_absl//absl/strings\",\n\"@com_google_googletest//:gtest\",\n],\n)\n@@ -1452,6 +1452,25 @@ cc_binary(\n],\n)\n+cc_binary(\n+ name = \"pwritev2_test\",\n+ testonly = 1,\n+ srcs = [\n+ \"pwritev2.cc\",\n+ ],\n+ linkstatic = 1,\n+ deps = [\n+ \":file_base\",\n+ \"//test/util:file_descriptor\",\n+ \"//test/util:posix_error\",\n+ \"//test/util:temp_path\",\n+ \"//test/util:test_main\",\n+ \"//test/util:test_util\",\n+ \"@com_google_absl//absl/strings\",\n+ \"@com_google_googletest//:gtest\",\n+ ],\n+)\n+\ncc_binary(\nname = \"read_test\",\ntestonly = 1,\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/preadv2.cc",
"new_path": "test/syscalls/linux/preadv2.cc",
"diff": "// limitations under the License.\n#include <fcntl.h>\n-#include <stdlib.h>\n#include <sys/syscall.h>\n#include <sys/types.h>\n#include <sys/uio.h>\n-#include <sys/wait.h>\n-#include <unistd.h>\n-#include <atomic>\n#include <string>\n#include <vector>\n#include \"gtest/gtest.h\"\n#include \"gtest/gtest.h\"\n+#include \"absl/memory/memory.h\"\n#include \"test/syscalls/linux/file_base.h\"\n-#include \"test/syscalls/linux/readv_common.h\"\n#include \"test/util/file_descriptor.h\"\n-#include \"test/util/memory_util.h\"\n#include \"test/util/temp_path.h\"\n#include \"test/util/test_util.h\"\n@@ -60,11 +55,17 @@ std::string SetContent() {\nreturn content;\n}\n+ssize_t preadv2(unsigned long fd, const struct iovec* iov, unsigned long iovcnt,\n+ off_t offset, unsigned long flags) {\n+ // syscall on preadv2 does some weird things (see man syscall and search\n+ // preadv2), so we insert a 0 to word align the flags argument on native.\n+ return syscall(SYS_preadv2, fd, iov, iovcnt, offset, 0, flags);\n+}\n+\n// This test is the base case where we call preadv (no offset, no flags).\nTEST(Preadv2Test, TestBaseCall) {\n- if (!IsRunningOnGvisor()) {\n- SKIP_BEFORE_KERNEL(/*major_version=*/4, /*minor_version=*/6);\n- }\n+ SKIP_IF(preadv2(-1, nullptr, 0, 0, 0) < 0 && errno == ENOSYS);\n+\nstd::string content = SetContent();\nconst TempPath file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith(\n@@ -73,12 +74,13 @@ TEST(Preadv2Test, TestBaseCall) {\nASSERT_NO_ERRNO_AND_VALUE(Open(file.path(), O_RDONLY));\nstd::vector<char> buf(kBufSize);\n- struct iovec iov;\n- iov.iov_base = buf.data();\n- iov.iov_len = buf.size();\n+ struct iovec iov[2];\n+ iov[0].iov_base = buf.data();\n+ iov[0].iov_len = buf.size() / 2;\n+ iov[1].iov_base = static_cast<char*>(iov[0].iov_base) + (content.size() / 2);\n+ iov[1].iov_len = content.size() / 2;\n- EXPECT_THAT(syscall(SYS_preadv2, fd.get(), &iov, /*iov_cnt*/ 1,\n- /*offset=*/0, /*flags=*/0),\n+ EXPECT_THAT(preadv2(fd.get(), iov, /*iovcnt*/ 2, /*offset=*/0, /*flags=*/0),\nSyscallSucceedsWithValue(kBufSize));\nEXPECT_EQ(content, std::string(buf.data(), buf.size()));\n@@ -86,9 +88,8 @@ TEST(Preadv2Test, TestBaseCall) {\n// This test is where we call preadv with an offset and no flags.\nTEST(Preadv2Test, TestValidPositiveOffset) {\n- if (!IsRunningOnGvisor()) {\n- SKIP_BEFORE_KERNEL(/*major_version=*/4, /*minor_version=*/6);\n- }\n+ SKIP_IF(preadv2(-1, nullptr, 0, 0, 0) < 0 && errno == ENOSYS);\n+\nstd::string content = SetContent();\nconst std::string prefix = \"0\";\n@@ -102,10 +103,12 @@ TEST(Preadv2Test, TestValidPositiveOffset) {\niov.iov_base = buf.data();\niov.iov_len = buf.size();\n- EXPECT_THAT(syscall(SYS_preadv2, fd.get(), &iov, /*iov_cnt=*/1,\n- /*offset=*/prefix.size(), /*flags=*/0),\n+ EXPECT_THAT(preadv2(fd.get(), &iov, /*iovcnt=*/1, /*offset=*/prefix.size(),\n+ /*flags=*/0),\nSyscallSucceedsWithValue(kBufSize));\n+ EXPECT_THAT(lseek(fd.get(), 0, SEEK_CUR), SyscallSucceedsWithValue(0));\n+\nEXPECT_EQ(content, std::string(buf.data(), buf.size()));\n}\n@@ -113,9 +116,8 @@ TEST(Preadv2Test, TestValidPositiveOffset) {\n// read should use the file offset, so the test increments it by one prior to\n// calling preadv2.\nTEST(Preadv2Test, TestNegativeOneOffset) {\n- if (!IsRunningOnGvisor()) {\n- SKIP_BEFORE_KERNEL(/*major_version=*/4, /*minor_version=*/6);\n- }\n+ SKIP_IF(preadv2(-1, nullptr, 0, 0, 0) < 0 && errno == ENOSYS);\n+\nstd::string content = SetContent();\nconst std::string prefix = \"231\";\n@@ -123,6 +125,7 @@ TEST(Preadv2Test, TestNegativeOneOffset) {\nGetAbsoluteTestTmpdir(), prefix + content, TempPath::kDefaultFileMode));\nconst FileDescriptor fd =\nASSERT_NO_ERRNO_AND_VALUE(Open(file.path(), O_RDONLY));\n+\nASSERT_THAT(lseek(fd.get(), prefix.size(), SEEK_SET),\nSyscallSucceedsWithValue(prefix.size()));\n@@ -131,79 +134,111 @@ TEST(Preadv2Test, TestNegativeOneOffset) {\niov.iov_base = buf.data();\niov.iov_len = buf.size();\n- EXPECT_THAT(syscall(SYS_preadv2, fd.get(), &iov, /*iov_cnt=*/1,\n- /*offset=*/static_cast<off_t>(-1), /*flags=*/0),\n+ EXPECT_THAT(preadv2(fd.get(), &iov, /*iovcnt=*/1, /*offset=*/-1, /*flags=*/0),\nSyscallSucceedsWithValue(kBufSize));\n+ EXPECT_THAT(lseek(fd.get(), 0, SEEK_CUR),\n+ SyscallSucceedsWithValue(prefix.size() + buf.size()));\n+\nEXPECT_EQ(content, std::string(buf.data(), buf.size()));\n}\n+// preadv2 requires if the RWF_HIPRI flag is passed, the fd must be opened with\n+// O_DIRECT. This test implements a correct call with the RWF_HIPRI flag.\n+TEST(Preadv2Test, TestCallWithRWF_HIPRI) {\n+ SKIP_IF(preadv2(-1, nullptr, 0, 0, 0) < 0 && errno == ENOSYS);\n+\n+ std::string content = SetContent();\n+\n+ const TempPath file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith(\n+ GetAbsoluteTestTmpdir(), content, TempPath::kDefaultFileMode));\n+ const FileDescriptor fd =\n+ ASSERT_NO_ERRNO_AND_VALUE(Open(file.path(), O_RDONLY));\n+\n+ EXPECT_THAT(fsync(fd.get()), SyscallSucceeds());\n+\n+ std::vector<char> buf(kBufSize, '0');\n+ struct iovec iov;\n+ iov.iov_base = buf.data();\n+ iov.iov_len = buf.size();\n+\n+ EXPECT_THAT(\n+ preadv2(fd.get(), &iov, /*iovcnt=*/1, /*offset=*/0, /*flags=*/RWF_HIPRI),\n+ SyscallSucceedsWithValue(kBufSize));\n+\n+ EXPECT_THAT(lseek(fd.get(), 0, SEEK_CUR), SyscallSucceedsWithValue(0));\n+\n+ EXPECT_EQ(content, std::string(buf.data(), buf.size()));\n+}\n// This test calls preadv2 with an invalid flag.\nTEST(Preadv2Test, TestInvalidFlag) {\n- if (!IsRunningOnGvisor()) {\n- SKIP_BEFORE_KERNEL(/*major_version=*/4, /*minor_version=*/6);\n- }\n+ SKIP_IF(preadv2(-1, nullptr, 0, 0, 0) < 0 && errno == ENOSYS);\nconst TempPath file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith(\nGetAbsoluteTestTmpdir(), \"\", TempPath::kDefaultFileMode));\nconst FileDescriptor fd =\nASSERT_NO_ERRNO_AND_VALUE(Open(file.path(), O_RDONLY | O_DIRECT));\n+ std::vector<char> buf(kBufSize, '0');\nstruct iovec iov;\n+ iov.iov_base = buf.data();\n+ iov.iov_len = buf.size();\n- EXPECT_THAT(syscall(SYS_preadv2, fd.get(), &iov, /*iov_cnt=*/1,\n- /*offset=*/0, /*flags=*/RWF_HIPRI << 1),\n- SyscallFailsWithErrno(EINVAL));\n+ EXPECT_THAT(preadv2(fd.get(), &iov, /*iovcnt=*/1,\n+ /*offset=*/0, /*flags=*/0xF0),\n+ SyscallFailsWithErrno(EOPNOTSUPP));\n}\n// This test calls preadv2 with an invalid offset.\nTEST(Preadv2Test, TestInvalidOffset) {\n- if (!IsRunningOnGvisor()) {\n- SKIP_BEFORE_KERNEL(/*major_version=*/4, /*minor_version=*/6);\n- }\n+ SKIP_IF(preadv2(-1, nullptr, 0, 0, 0) < 0 && errno == ENOSYS);\nconst TempPath file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith(\nGetAbsoluteTestTmpdir(), \"\", TempPath::kDefaultFileMode));\nconst FileDescriptor fd =\nASSERT_NO_ERRNO_AND_VALUE(Open(file.path(), O_RDONLY | O_DIRECT));\n- struct iovec iov;\n- EXPECT_THAT(syscall(SYS_preadv2, fd.get(), &iov, /*iov_cnt=*/1,\n- /*offset=*/static_cast<off_t>(-8), /*flags=*/RWF_HIPRI),\n+ auto iov = absl::make_unique<struct iovec[]>(1);\n+ iov[0].iov_base = nullptr;\n+ iov[0].iov_len = 0;\n+\n+ EXPECT_THAT(preadv2(fd.get(), iov.get(), /*iovcnt=*/1, /*offset=*/-8,\n+ /*flags=*/RWF_HIPRI),\nSyscallFailsWithErrno(EINVAL));\n}\n// This test calls preadv with a file set O_WRONLY.\nTEST(Preadv2Test, TestUnreadableFile) {\n- if (!IsRunningOnGvisor()) {\n- SKIP_BEFORE_KERNEL(/*major_version=*/4, /*minor_version=*/6);\n- }\n+ SKIP_IF(preadv2(-1, nullptr, 0, 0, 0) < 0 && errno == ENOSYS);\nconst TempPath file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith(\nGetAbsoluteTestTmpdir(), \"\", TempPath::kDefaultFileMode));\nconst FileDescriptor fd =\nASSERT_NO_ERRNO_AND_VALUE(Open(file.path(), O_WRONLY));\n- struct iovec iov;\n- EXPECT_THAT(syscall(SYS_preadv2, fd.get(), &iov, /*iov_cnt=*/1,\n+ auto iov = absl::make_unique<struct iovec[]>(1);\n+ iov[0].iov_base = nullptr;\n+ iov[0].iov_len = 0;\n+\n+ EXPECT_THAT(preadv2(fd.get(), iov.get(), /*iovcnt=*/1,\n/*offset=*/0, /*flags=*/0),\nSyscallFailsWithErrno(EBADF));\n}\n// Calling preadv2 with a non-negative offset calls preadv. Calling preadv with\n// an unseekable file is not allowed. A pipe is used for an unseekable file.\n-TEST(Preadv2Test, TestUnseekableFile) {\n- if (!IsRunningOnGvisor()) {\n- SKIP_BEFORE_KERNEL(/*major_version=*/4, /*minor_version=*/6);\n- }\n+TEST(Preadv2Test, TestUnseekableFileInvalid) {\n+ SKIP_IF(preadv2(-1, nullptr, 0, 0, 0) < 0 && errno == ENOSYS);\nint pipe_fds[2];\nASSERT_THAT(pipe(pipe_fds), SyscallSucceeds());\n- struct iovec iov;\n+ auto iov = absl::make_unique<struct iovec[]>(1);\n+ iov[0].iov_base = nullptr;\n+ iov[0].iov_len = 0;\n- EXPECT_THAT(syscall(SYS_preadv2, pipe_fds[0], &iov, /*iov_cnt=*/1,\n+ EXPECT_THAT(preadv2(pipe_fds[0], iov.get(), /*iovcnt=*/1,\n/*offset=*/2, /*flags=*/0),\nSyscallFailsWithErrno(ESPIPE));\n@@ -211,6 +246,33 @@ TEST(Preadv2Test, TestUnseekableFile) {\nEXPECT_THAT(close(pipe_fds[1]), SyscallSucceeds());\n}\n+TEST(Preadv2Test, TestUnseekableFileValid) {\n+ SKIP_IF(preadv2(-1, nullptr, 0, 0, 0) < 0 && errno == ENOSYS);\n+\n+ int pipe_fds[2];\n+\n+ ASSERT_THAT(pipe(pipe_fds), SyscallSucceeds());\n+\n+ std::vector<char> content(32, 'X');\n+\n+ EXPECT_THAT(write(pipe_fds[1], content.data(), content.size()),\n+ SyscallSucceedsWithValue(content.size()));\n+\n+ std::vector<char> buf(content.size());\n+ auto iov = absl::make_unique<struct iovec[]>(1);\n+ iov[0].iov_base = buf.data();\n+ iov[0].iov_len = buf.size();\n+\n+ EXPECT_THAT(preadv2(pipe_fds[0], iov.get(), /*iovcnt=*/1,\n+ /*offset=*/static_cast<off_t>(-1), /*flags=*/0),\n+ SyscallSucceedsWithValue(buf.size()));\n+\n+ EXPECT_EQ(content, buf);\n+\n+ EXPECT_THAT(close(pipe_fds[0]), SyscallSucceeds());\n+ EXPECT_THAT(close(pipe_fds[1]), SyscallSucceeds());\n+}\n+\n} // namespace\n} // namespace testing\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/syscalls/linux/pwritev2.cc",
"diff": "+// Copyright 2018 Google LLC\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+#include <fcntl.h>\n+#include <sys/syscall.h>\n+#include <sys/types.h>\n+#include <sys/uio.h>\n+\n+#include <string>\n+#include <vector>\n+\n+#include \"gtest/gtest.h\"\n+#include \"gtest/gtest.h\"\n+#include \"test/syscalls/linux/file_base.h\"\n+#include \"test/util/file_descriptor.h\"\n+#include \"test/util/temp_path.h\"\n+#include \"test/util/test_util.h\"\n+\n+namespace gvisor {\n+namespace testing {\n+\n+namespace {\n+\n+#ifndef SYS_pwritev2\n+#if defined(__x86_64__)\n+#define SYS_pwritev2 328\n+#else\n+#error \"Unknown architecture\"\n+#endif\n+#endif // SYS_pwrite2\n+\n+#ifndef RWF_HIPRI\n+#define RWF_HIPRI 0x1\n+#endif // RWF_HIPRI\n+\n+#ifndef RWF_DSYNC\n+#define RWF_DSYNC 0x2\n+#endif // RWF_DSYNC\n+\n+#ifndef RWF_SYNC\n+#define RWF_SYNC 0x4\n+#endif // RWF_SYNC\n+\n+constexpr int kBufSize = 1024;\n+\n+void SetContent(std::vector<char>& content) {\n+ for (uint i = 0; i < content.size(); i++) {\n+ content[i] = static_cast<char>((i % 10) + '0');\n+ }\n+}\n+\n+ssize_t pwritev2(unsigned long fd, const struct iovec* iov,\n+ unsigned long iovcnt, off_t offset, unsigned long flags) {\n+ // syscall on pwritev2 does some weird things (see man syscall and search\n+ // pwritev2), so we insert a 0 to word align the flags argument on native.\n+ return syscall(SYS_pwritev2, fd, iov, iovcnt, offset, 0, flags);\n+}\n+\n+// This test is the base case where we call pwritev (no offset, no flags).\n+TEST(Writev2Test, TestBaseCall) {\n+ SKIP_IF(pwritev2(-1, nullptr, 0, 0, 0) < 0 && errno == ENOSYS);\n+\n+ const TempPath file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith(\n+ GetAbsoluteTestTmpdir(), \"\", TempPath::kDefaultFileMode));\n+ const FileDescriptor fd =\n+ ASSERT_NO_ERRNO_AND_VALUE(Open(file.path(), O_RDWR));\n+\n+ std::vector<char> content(kBufSize);\n+ SetContent(content);\n+ struct iovec iov[2];\n+ iov[0].iov_base = content.data();\n+ iov[0].iov_len = content.size() / 2;\n+ iov[1].iov_base = static_cast<char*>(iov[0].iov_base) + (content.size() / 2);\n+ iov[1].iov_len = content.size() / 2;\n+\n+ ASSERT_THAT(pwritev2(fd.get(), iov, /*iovcnt=*/2,\n+ /*offset=*/0, /*flags=*/0),\n+ SyscallSucceedsWithValue(kBufSize));\n+\n+ std::vector<char> buf(kBufSize);\n+ EXPECT_THAT(read(fd.get(), buf.data(), kBufSize),\n+ SyscallSucceedsWithValue(kBufSize));\n+\n+ EXPECT_EQ(content, buf);\n+}\n+\n+// This test is where we call pwritev2 with a positive offset and no flags.\n+TEST(Pwritev2Test, TestValidPositiveOffset) {\n+ SKIP_IF(pwritev2(-1, nullptr, 0, 0, 0) < 0 && errno == ENOSYS);\n+\n+ std::string prefix(kBufSize, '0');\n+\n+ const TempPath file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith(\n+ GetAbsoluteTestTmpdir(), prefix, TempPath::kDefaultFileMode));\n+ const FileDescriptor fd =\n+ ASSERT_NO_ERRNO_AND_VALUE(Open(file.path(), O_RDWR));\n+\n+ std::vector<char> content(kBufSize);\n+ SetContent(content);\n+ struct iovec iov;\n+ iov.iov_base = content.data();\n+ iov.iov_len = content.size();\n+\n+ ASSERT_THAT(pwritev2(fd.get(), &iov, /*iovcnt=*/1,\n+ /*offset=*/prefix.size(), /*flags=*/0),\n+ SyscallSucceedsWithValue(content.size()));\n+\n+ std::vector<char> buf(prefix.size() + content.size());\n+ EXPECT_THAT(read(fd.get(), buf.data(), buf.size()),\n+ SyscallSucceedsWithValue(buf.size()));\n+\n+ std::vector<char> want(prefix.begin(), prefix.end());\n+ want.insert(want.end(), content.begin(), content.end());\n+ EXPECT_EQ(want, buf);\n+}\n+\n+// This test is the base case where we call writev by using -1 as the offset.\n+// The write should use the file offset, so the test increments the file offset\n+// prior to call pwritev2.\n+TEST(Pwritev2Test, TestNegativeOneOffset) {\n+ SKIP_IF(pwritev2(-1, nullptr, 0, 0, 0) < 0 && errno == ENOSYS);\n+\n+ const std::string prefix = \"00\";\n+ const TempPath file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith(\n+ GetAbsoluteTestTmpdir(), prefix.data(), TempPath::kDefaultFileMode));\n+ const FileDescriptor fd =\n+ ASSERT_NO_ERRNO_AND_VALUE(Open(file.path(), O_RDWR));\n+ ASSERT_THAT(lseek(fd.get(), prefix.size(), SEEK_SET),\n+ SyscallSucceedsWithValue(prefix.size()));\n+\n+ std::vector<char> content(kBufSize);\n+ SetContent(content);\n+ struct iovec iov;\n+ iov.iov_base = content.data();\n+ iov.iov_len = content.size();\n+\n+ ASSERT_THAT(pwritev2(fd.get(), &iov, /*iovcnt*/ 1,\n+ /*offset=*/static_cast<off_t>(-1), /*flags=*/0),\n+ SyscallSucceedsWithValue(content.size()));\n+\n+ ASSERT_THAT(lseek(fd.get(), 0, SEEK_CUR),\n+ SyscallSucceedsWithValue(prefix.size() + content.size()));\n+\n+ std::vector<char> buf(prefix.size() + content.size());\n+ EXPECT_THAT(pread(fd.get(), buf.data(), buf.size(), /*offset=*/0),\n+ SyscallSucceedsWithValue(buf.size()));\n+\n+ std::vector<char> want(prefix.begin(), prefix.end());\n+ want.insert(want.end(), content.begin(), content.end());\n+ EXPECT_EQ(want, buf);\n+}\n+\n+// pwritev2 requires if the RWF_HIPRI flag is passed, the fd must be opened with\n+// O_DIRECT. This test implements a correct call with the RWF_HIPRI flag.\n+TEST(Pwritev2Test, TestCallWithRWF_HIPRI) {\n+ SKIP_IF(pwritev2(-1, nullptr, 0, 0, 0) < 0 && errno == ENOSYS);\n+\n+ const TempPath file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith(\n+ GetAbsoluteTestTmpdir(), \"\", TempPath::kDefaultFileMode));\n+ const FileDescriptor fd =\n+ ASSERT_NO_ERRNO_AND_VALUE(Open(file.path(), O_RDWR));\n+\n+ std::vector<char> content(kBufSize);\n+ SetContent(content);\n+ struct iovec iov;\n+ iov.iov_base = content.data();\n+ iov.iov_len = content.size();\n+\n+ EXPECT_THAT(pwritev2(fd.get(), &iov, /*iovcnt=*/1,\n+ /*offset=*/0, /*flags=*/RWF_HIPRI),\n+ SyscallSucceedsWithValue(kBufSize));\n+\n+ std::vector<char> buf(content.size());\n+ EXPECT_THAT(read(fd.get(), buf.data(), buf.size()),\n+ SyscallSucceedsWithValue(buf.size()));\n+\n+ EXPECT_EQ(buf, content);\n+}\n+\n+// This test checks that pwritev2 can be called with valid flags\n+TEST(Pwritev2Test, TestCallWithValidFlags) {\n+ SKIP_IF(pwritev2(-1, nullptr, 0, 0, 0) < 0 && errno == ENOSYS);\n+\n+ const TempPath file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith(\n+ GetAbsoluteTestTmpdir(), \"\", TempPath::kDefaultFileMode));\n+ const FileDescriptor fd =\n+ ASSERT_NO_ERRNO_AND_VALUE(Open(file.path(), O_RDWR));\n+\n+ std::vector<char> content(kBufSize, '0');\n+ struct iovec iov;\n+ iov.iov_base = content.data();\n+ iov.iov_len = content.size();\n+\n+ EXPECT_THAT(pwritev2(fd.get(), &iov, /*iovcnt=*/1,\n+ /*offset=*/0, /*flags=*/RWF_DSYNC),\n+ SyscallSucceedsWithValue(kBufSize));\n+\n+ std::vector<char> buf(content.size());\n+ EXPECT_THAT(read(fd.get(), buf.data(), buf.size()),\n+ SyscallSucceedsWithValue(buf.size()));\n+\n+ EXPECT_EQ(buf, content);\n+\n+ SetContent(content);\n+\n+ EXPECT_THAT(pwritev2(fd.get(), &iov, /*iovcnt=*/1,\n+ /*offset=*/0, /*flags=*/0x4),\n+ SyscallSucceedsWithValue(kBufSize));\n+\n+ ASSERT_THAT(lseek(fd.get(), 0, SEEK_CUR),\n+ SyscallSucceedsWithValue(content.size()));\n+\n+ EXPECT_THAT(pread(fd.get(), buf.data(), buf.size(), /*offset=*/0),\n+ SyscallSucceedsWithValue(buf.size()));\n+\n+ EXPECT_EQ(buf, content);\n+}\n+\n+// This test calls pwritev2 with a bad file descriptor.\n+TEST(Writev2Test, TestBadFile) {\n+ SKIP_IF(pwritev2(-1, nullptr, 0, 0, 0) < 0 && errno == ENOSYS);\n+ ASSERT_THAT(pwritev2(/*fd=*/-1, /*iov=*/nullptr, /*iovcnt=*/0,\n+ /*offset=*/0, /*flags=*/0),\n+ SyscallFailsWithErrno(EBADF));\n+}\n+\n+// This test calls pwrite2 with an invalid offset.\n+TEST(Pwritev2Test, TestInvalidOffset) {\n+ SKIP_IF(pwritev2(-1, nullptr, 0, 0, 0) < 0 && errno == ENOSYS);\n+\n+ const TempPath file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith(\n+ GetAbsoluteTestTmpdir(), \"\", TempPath::kDefaultFileMode));\n+ const FileDescriptor fd =\n+ ASSERT_NO_ERRNO_AND_VALUE(Open(file.path(), O_RDWR));\n+\n+ struct iovec iov;\n+ iov.iov_base = nullptr;\n+\n+ EXPECT_THAT(pwritev2(fd.get(), &iov, /*iovcnt=*/1,\n+ /*offset=*/static_cast<off_t>(-8), /*flags=*/0),\n+ SyscallFailsWithErrno(EINVAL));\n+}\n+\n+TEST(Pwritev2Test, TestUnseekableFileValid) {\n+ SKIP_IF(pwritev2(-1, nullptr, 0, 0, 0) < 0 && errno == ENOSYS);\n+\n+ int pipe_fds[2];\n+\n+ ASSERT_THAT(pipe(pipe_fds), SyscallSucceeds());\n+\n+ std::vector<char> content(32, '0');\n+ SetContent(content);\n+ struct iovec iov;\n+ iov.iov_base = content.data();\n+ iov.iov_len = content.size();\n+\n+ EXPECT_THAT(pwritev2(pipe_fds[1], &iov, /*iovcnt=*/1,\n+ /*offset=*/static_cast<off_t>(-1), /*flags=*/0),\n+ SyscallSucceedsWithValue(content.size()));\n+\n+ std::vector<char> buf(content.size());\n+ EXPECT_THAT(read(pipe_fds[0], buf.data(), buf.size()),\n+ SyscallSucceedsWithValue(buf.size()));\n+\n+ EXPECT_EQ(content, buf);\n+\n+ EXPECT_THAT(close(pipe_fds[0]), SyscallSucceeds());\n+ EXPECT_THAT(close(pipe_fds[1]), SyscallSucceeds());\n+}\n+\n+// Calling pwritev2 with a non-negative offset calls pwritev. Calling pwritev\n+// with an unseekable file is not allowed. A pipe is used for an unseekable\n+// file.\n+TEST(Pwritev2Test, TestUnseekableFileInValid) {\n+ SKIP_IF(pwritev2(-1, nullptr, 0, 0, 0) < 0 && errno == ENOSYS);\n+\n+ int pipe_fds[2];\n+ struct iovec iov;\n+ iov.iov_base = nullptr;\n+\n+ ASSERT_THAT(pipe(pipe_fds), SyscallSucceeds());\n+\n+ EXPECT_THAT(pwritev2(pipe_fds[1], &iov, /*iovcnt=*/1,\n+ /*offset=*/2, /*flags=*/0),\n+ SyscallFailsWithErrno(ESPIPE));\n+\n+ EXPECT_THAT(close(pipe_fds[0]), SyscallSucceeds());\n+ EXPECT_THAT(close(pipe_fds[1]), SyscallSucceeds());\n+}\n+\n+TEST(Pwritev2Test, TestReadOnlyFile) {\n+ SKIP_IF(pwritev2(-1, nullptr, 0, 0, 0) < 0 && errno == ENOSYS);\n+\n+ const TempPath file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith(\n+ GetAbsoluteTestTmpdir(), \"\", TempPath::kDefaultFileMode));\n+ const FileDescriptor fd =\n+ ASSERT_NO_ERRNO_AND_VALUE(Open(file.path(), O_RDONLY));\n+\n+ struct iovec iov;\n+ iov.iov_base = nullptr;\n+\n+ EXPECT_THAT(pwritev2(fd.get(), &iov, /*iovcnt=*/1,\n+ /*offset=*/0, /*flags=*/0),\n+ SyscallFailsWithErrno(EBADF));\n+}\n+\n+// This test calls pwritev2 with an invalid flag.\n+TEST(Pwritev2Test, TestInvalidFlag) {\n+ SKIP_IF(pwritev2(-1, nullptr, 0, 0, 0) < 0 && errno == ENOSYS);\n+\n+ const TempPath file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith(\n+ GetAbsoluteTestTmpdir(), \"\", TempPath::kDefaultFileMode));\n+ const FileDescriptor fd =\n+ ASSERT_NO_ERRNO_AND_VALUE(Open(file.path(), O_RDWR | O_DIRECT));\n+\n+ struct iovec iov;\n+ iov.iov_base = nullptr;\n+\n+ EXPECT_THAT(pwritev2(fd.get(), &iov, /*iovcnt=*/1,\n+ /*offset=*/0, /*flags=*/0xF0),\n+ SyscallFailsWithErrno(EOPNOTSUPP));\n+}\n+\n+} // namespace\n+} // namespace testing\n+} // namespace gvisor\n"
},
{
"change_type": "MODIFY",
"old_path": "test/util/test_util.h",
"new_path": "test/util/test_util.h",
"diff": "@@ -217,13 +217,6 @@ void TestInit(int* argc, char*** argv);\n} \\\n} while (0)\n-#define SKIP_BEFORE_KERNEL(maj, min) \\\n- do { \\\n- auto version = ASSERT_NO_ERRNO_AND_VALUE(GetKernelVersion()); \\\n- SKIP_IF(version.major < (maj) || \\\n- (version.major == (maj) && version.minor < (min))); \\\n- } while (0)\n-\nenum class Platform {\nkNative,\nkKVM,\n"
}
] | Go | Apache License 2.0 | google/gvisor | Implement pwritev2.
Implement pwritev2 and associated unit tests.
Clean up preadv2 unit tests.
Tag RWF_ flags in both preadv2 and pwritev2 with associated bug tickets.
PiperOrigin-RevId: 226222119
Change-Id: Ieb22672418812894ba114bbc88e67f1dd50de620 |
259,948 | 20.12.2018 09:51:26 | 28,800 | 25d62850ce8a420600194009a7257148c43cc5f8 | test: deflake socket_inet_loopback. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_inet_loopback.cc",
"new_path": "test/syscalls/linux/socket_inet_loopback.cc",
"diff": "@@ -185,6 +185,11 @@ TEST_P(SocketInetLoopbackTest, TCP) {\nSyscallSucceeds());\n// Accept the connection.\n+ //\n+ // We have to assign a name to the accepted socket, as unamed temporary\n+ // objects are destructed upon full evaluation of the expression it is in,\n+ // potentially causing the connecting socket to fail to shutdown properly.\n+ auto accepted =\nASSERT_NO_ERRNO_AND_VALUE(Accept(listen_fd.get(), nullptr, nullptr));\nASSERT_THAT(shutdown(listen_fd.get(), SHUT_RDWR), SyscallSucceeds());\n"
}
] | Go | Apache License 2.0 | google/gvisor | test: deflake socket_inet_loopback.
PiperOrigin-RevId: 226350590
Change-Id: Idff080705f644f8f78ce92b53c77eecc37e002e7 |
259,885 | 20.12.2018 13:27:25 | 28,800 | 194ef586fcb1bec049ee8777c2e5f70997de7a87 | Rename limits.MemoryPagesLocked to limits.MemoryLocked.
"RLIMIT_MEMLOCK: This is the maximum number of bytes of memory that may
be locked into RAM." - getrlimit(2) | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/limits/limits.go",
"new_path": "pkg/sentry/limits/limits.go",
"diff": "@@ -33,7 +33,7 @@ const (\nRss\nProcessCount\nNumberOfFiles\n- MemoryPagesLocked\n+ MemoryLocked\nAS\nLocks\nSignalsPending\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/limits/linux.go",
"new_path": "pkg/sentry/limits/linux.go",
"diff": "@@ -30,7 +30,7 @@ var FromLinuxResource = map[int]LimitType{\nlinux.RLIMIT_RSS: Rss,\nlinux.RLIMIT_NPROC: ProcessCount,\nlinux.RLIMIT_NOFILE: NumberOfFiles,\n- linux.RLIMIT_MEMLOCK: MemoryPagesLocked,\n+ linux.RLIMIT_MEMLOCK: MemoryLocked,\nlinux.RLIMIT_AS: AS,\nlinux.RLIMIT_LOCKS: Locks,\nlinux.RLIMIT_SIGPENDING: SignalsPending,\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/limits.go",
"new_path": "runsc/boot/limits.go",
"diff": "@@ -29,7 +29,7 @@ var fromLinuxResource = map[string]limits.LimitType{\n\"RLIMIT_DATA\": limits.Data,\n\"RLIMIT_FSIZE\": limits.FileSize,\n\"RLIMIT_LOCKS\": limits.Locks,\n- \"RLIMIT_MEMLOCK\": limits.MemoryPagesLocked,\n+ \"RLIMIT_MEMLOCK\": limits.MemoryLocked,\n\"RLIMIT_MSGQUEUE\": limits.MessageQueueBytes,\n\"RLIMIT_NICE\": limits.Nice,\n\"RLIMIT_NOFILE\": limits.NumberOfFiles,\n@@ -55,7 +55,7 @@ func createLimitSet(spec *specs.Spec) (*limits.LimitSet, error) {\nls.SetUnchecked(limits.Data, limits.Limit{Cur: limits.Infinity, Max: limits.Infinity})\nls.SetUnchecked(limits.FileSize, limits.Limit{Cur: limits.Infinity, Max: limits.Infinity})\nls.SetUnchecked(limits.Locks, limits.Limit{Cur: limits.Infinity, Max: limits.Infinity})\n- ls.SetUnchecked(limits.MemoryPagesLocked, limits.Limit{Cur: 65536, Max: 65536})\n+ ls.SetUnchecked(limits.MemoryLocked, limits.Limit{Cur: 65536, Max: 65536})\nls.SetUnchecked(limits.MessageQueueBytes, limits.Limit{Cur: 819200, Max: 819200})\nls.SetUnchecked(limits.Nice, limits.Limit{Cur: 0, Max: 0})\nls.SetUnchecked(limits.NumberOfFiles, limits.Limit{Cur: 1048576, Max: 1048576})\n"
}
] | Go | Apache License 2.0 | google/gvisor | Rename limits.MemoryPagesLocked to limits.MemoryLocked.
"RLIMIT_MEMLOCK: This is the maximum number of bytes of memory that may
be locked into RAM." - getrlimit(2)
PiperOrigin-RevId: 226384346
Change-Id: Iefac4a1bb69f7714dc813b5b871226a8344dc800 |
259,854 | 20.12.2018 13:47:46 | 28,800 | f6274804e14ece853c952cb71fde73dfb06b733a | Make read and write respect SO_RCVTIMEO and SO_SNDTIMEO | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/sys_read.go",
"new_path": "pkg/sentry/syscalls/linux/sys_read.go",
"diff": "package linux\nimport (\n+ \"time\"\n+\n\"gvisor.googlesource.com/gvisor/pkg/abi/linux\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/arch\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/fs\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/kernel\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/kernel/kdefs\"\n+ ktime \"gvisor.googlesource.com/gvisor/pkg/sentry/kernel/time\"\n+ \"gvisor.googlesource.com/gvisor/pkg/sentry/socket\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/usermem\"\n\"gvisor.googlesource.com/gvisor/pkg/syserror\"\n\"gvisor.googlesource.com/gvisor/pkg/waiter\"\n@@ -259,6 +263,20 @@ func readv(t *kernel.Task, f *fs.File, dst usermem.IOSequence) (int64, error) {\nreturn n, err\n}\n+ // Sockets support read timeouts.\n+ var haveDeadline bool\n+ var deadline ktime.Time\n+ if s, ok := f.FileOperations.(socket.Socket); ok {\n+ dl := s.RecvTimeout()\n+ if dl < 0 && err == syserror.ErrWouldBlock {\n+ return n, err\n+ }\n+ if dl > 0 {\n+ deadline = t.Kernel().MonotonicClock().Now().Add(time.Duration(dl) * time.Nanosecond)\n+ haveDeadline = true\n+ }\n+ }\n+\n// Register for notifications.\nw, ch := waiter.NewChannelEntry(nil)\nf.EventRegister(&w, EventMaskRead)\n@@ -277,7 +295,10 @@ func readv(t *kernel.Task, f *fs.File, dst usermem.IOSequence) (int64, error) {\n}\n// Wait for a notification that we should retry.\n- if err = t.Block(ch); err != nil {\n+ if err = t.BlockWithDeadline(ch, haveDeadline, deadline); err != nil {\n+ if err == syserror.ETIMEDOUT {\n+ err = syserror.ErrWouldBlock\n+ }\nbreak\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/sys_write.go",
"new_path": "pkg/sentry/syscalls/linux/sys_write.go",
"diff": "package linux\nimport (\n+ \"time\"\n+\n\"gvisor.googlesource.com/gvisor/pkg/abi/linux\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/arch\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/fs\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/kernel\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/kernel/kdefs\"\n+ ktime \"gvisor.googlesource.com/gvisor/pkg/sentry/kernel/time\"\n+ \"gvisor.googlesource.com/gvisor/pkg/sentry/socket\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/usermem\"\n\"gvisor.googlesource.com/gvisor/pkg/syserror\"\n\"gvisor.googlesource.com/gvisor/pkg/waiter\"\n@@ -263,6 +267,20 @@ func writev(t *kernel.Task, f *fs.File, src usermem.IOSequence) (int64, error) {\nreturn n, err\n}\n+ // Sockets support write timeouts.\n+ var haveDeadline bool\n+ var deadline ktime.Time\n+ if s, ok := f.FileOperations.(socket.Socket); ok {\n+ dl := s.SendTimeout()\n+ if dl < 0 && err == syserror.ErrWouldBlock {\n+ return n, err\n+ }\n+ if dl > 0 {\n+ deadline = t.Kernel().MonotonicClock().Now().Add(time.Duration(dl) * time.Nanosecond)\n+ haveDeadline = true\n+ }\n+ }\n+\n// Register for notifications.\nw, ch := waiter.NewChannelEntry(nil)\nf.EventRegister(&w, EventMaskWrite)\n@@ -281,7 +299,10 @@ func writev(t *kernel.Task, f *fs.File, src usermem.IOSequence) (int64, error) {\n}\n// Wait for a notification that we should retry.\n- if err = t.Block(ch); err != nil {\n+ if err = t.BlockWithDeadline(ch, haveDeadline, deadline); err != nil {\n+ if err == syserror.ETIMEDOUT {\n+ err = syserror.ErrWouldBlock\n+ }\nbreak\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_generic.cc",
"new_path": "test/syscalls/linux/socket_generic.cc",
"diff": "@@ -280,7 +280,22 @@ TEST_P(AllSocketPairTest, SndBufSucceeds) {\nEXPECT_GT(size, 0);\n}\n-TEST_P(AllSocketPairTest, RecvTimeoutSucceeds) {\n+TEST_P(AllSocketPairTest, RecvTimeoutReadSucceeds) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ struct timeval tv {\n+ .tv_sec = 0, .tv_usec = 10\n+ };\n+ EXPECT_THAT(\n+ setsockopt(sockets->first_fd(), SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)),\n+ SyscallSucceeds());\n+\n+ char buf[20] = {};\n+ EXPECT_THAT(RetryEINTR(read)(sockets->first_fd(), buf, sizeof(buf)),\n+ SyscallFailsWithErrno(EAGAIN));\n+}\n+\n+TEST_P(AllSocketPairTest, RecvTimeoutRecvSucceeds) {\nauto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\nstruct timeval tv {\n@@ -295,7 +310,7 @@ TEST_P(AllSocketPairTest, RecvTimeoutSucceeds) {\nSyscallFailsWithErrno(EAGAIN));\n}\n-TEST_P(AllSocketPairTest, RecvTimeoutOneSecondSucceeds) {\n+TEST_P(AllSocketPairTest, RecvTimeoutRecvOneSecondSucceeds) {\nauto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\nstruct timeval tv {\n@@ -310,7 +325,7 @@ TEST_P(AllSocketPairTest, RecvTimeoutOneSecondSucceeds) {\nSyscallFailsWithErrno(EAGAIN));\n}\n-TEST_P(AllSocketPairTest, RecvmsgTimeoutSucceeds) {\n+TEST_P(AllSocketPairTest, RecvTimeoutRecvmsgSucceeds) {\nauto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\nstruct timeval tv {\n@@ -332,6 +347,21 @@ TEST_P(AllSocketPairTest, RecvmsgTimeoutSucceeds) {\nSyscallFailsWithErrno(EAGAIN));\n}\n+TEST_P(AllSocketPairTest, SendTimeoutAllowsWrite) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ struct timeval tv {\n+ .tv_sec = 0, .tv_usec = 10\n+ };\n+ EXPECT_THAT(\n+ setsockopt(sockets->first_fd(), SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)),\n+ SyscallSucceeds());\n+\n+ char buf[20] = {};\n+ ASSERT_THAT(RetryEINTR(write)(sockets->first_fd(), buf, sizeof(buf)),\n+ SyscallSucceedsWithValue(sizeof(buf)));\n+}\n+\nTEST_P(AllSocketPairTest, SendTimeoutAllowsSend) {\nauto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n@@ -347,7 +377,7 @@ TEST_P(AllSocketPairTest, SendTimeoutAllowsSend) {\nSyscallSucceedsWithValue(sizeof(buf)));\n}\n-TEST_P(AllSocketPairTest, SendmsgTimeoutAllowsSend) {\n+TEST_P(AllSocketPairTest, SendTimeoutAllowsSendmsg) {\nauto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\nstruct timeval tv {\n@@ -389,7 +419,7 @@ TEST_P(AllSocketPairTest, SoRcvTimeoIsSetLargerArg) {\nSyscallSucceeds());\n}\n-TEST_P(AllSocketPairTest, RecvmsgTimeoutOneSecondSucceeds) {\n+TEST_P(AllSocketPairTest, RecvTimeoutRecvmsgOneSecondSucceeds) {\nauto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\nstruct timeval tv {\n@@ -455,7 +485,22 @@ TEST_P(AllSocketPairTest, SendTimeoutUsecNeg) {\nSyscallFailsWithErrno(EDOM));\n}\n-TEST_P(AllSocketPairTest, RecvTimeoutNegSec) {\n+TEST_P(AllSocketPairTest, RecvTimeoutNegSecRead) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ struct timeval tv {\n+ .tv_sec = -1, .tv_usec = 0\n+ };\n+ EXPECT_THAT(\n+ setsockopt(sockets->first_fd(), SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)),\n+ SyscallSucceeds());\n+\n+ char buf[20] = {};\n+ EXPECT_THAT(RetryEINTR(read)(sockets->first_fd(), buf, sizeof(buf)),\n+ SyscallFailsWithErrno(EAGAIN));\n+}\n+\n+TEST_P(AllSocketPairTest, RecvTimeoutNegSecRecv) {\nauto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\nstruct timeval tv {\n@@ -470,7 +515,7 @@ TEST_P(AllSocketPairTest, RecvTimeoutNegSec) {\nSyscallFailsWithErrno(EAGAIN));\n}\n-TEST_P(AllSocketPairTest, RecvmsgTimeoutNegSec) {\n+TEST_P(AllSocketPairTest, RecvTimeoutNegSecRecvmsg) {\nauto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\nstruct timeval tv {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Make read and write respect SO_RCVTIMEO and SO_SNDTIMEO
PiperOrigin-RevId: 226387521
Change-Id: I0579ab262320fde6c72d2994dd38437f01a99ea5 |
259,881 | 21.12.2018 10:47:41 | 28,800 | 5c7f70a07d8f4b08db3446e0cf75ad43bb2c1953 | Update rules_go, gazelle, and Go | [
{
"change_type": "MODIFY",
"old_path": "WORKSPACE",
"new_path": "WORKSPACE",
"diff": "load(\"@bazel_tools//tools/build_defs/repo:http.bzl\", \"http_archive\")\nhttp_archive(\nname = \"io_bazel_rules_go\",\n- url = \"https://github.com/bazelbuild/rules_go/releases/download/0.16.4/rules_go-0.16.4.tar.gz\",\n- sha256 = \"62ec3496a00445889a843062de9930c228b770218c735eca89c67949cd967c3f\",\n+ url = \"https://github.com/bazelbuild/rules_go/releases/download/0.16.5/rules_go-0.16.5.tar.gz\",\n+ sha256 = \"7be7dc01f1e0afdba6c8eb2b43d2fa01c743be1b9273ab1eaf6c233df078d705\",\n)\nhttp_archive(\nname = \"bazel_gazelle\",\n- url = \"https://github.com/bazelbuild/bazel-gazelle/releases/download/0.15.0/bazel-gazelle-0.15.0.tar.gz\",\n- sha256 = \"6e875ab4b6bf64a38c352887760f21203ab054676d9c1b274963907e0768740d\",\n+ url = \"https://github.com/bazelbuild/bazel-gazelle/releases/download/0.16.0/bazel-gazelle-0.16.0.tar.gz\",\n+ sha256 = \"7949fc6cc17b5b191103e97481cf8889217263acf52e00b560683413af204fcb\",\n)\nload(\"@io_bazel_rules_go//go:def.bzl\", \"go_rules_dependencies\", \"go_register_toolchains\")\ngo_rules_dependencies()\n-go_register_toolchains(go_version=\"1.11.3\")\n+go_register_toolchains(go_version=\"1.11.4\")\nload(\"@bazel_gazelle//:deps.bzl\", \"gazelle_dependencies\", \"go_repository\")\ngazelle_dependencies()\n"
}
] | Go | Apache License 2.0 | google/gvisor | Update rules_go, gazelle, and Go
PiperOrigin-RevId: 226511383
Change-Id: I3a42572d44582d5713841799ec1fd9695d050938 |
259,992 | 21.12.2018 11:52:39 | 28,800 | 1679ef31ef15344eba218a5251fa1fb1438b4cb7 | inotify notifies watchers when control events bit are set
The code that matches the event being published with events watchers
was wronly matching all watchers in case any of the control event bits
were set.
Issue | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/inotify_watch.go",
"new_path": "pkg/sentry/fs/inotify_watch.go",
"diff": "@@ -76,15 +76,17 @@ func isRenameEvent(eventMask uint32) bool {\n// Notify queues a new event on this watch.\nfunc (w *Watch) Notify(name string, events uint32, cookie uint32) {\n- unmaskableBits := ^uint32(0) &^ linux.IN_ALL_EVENTS\n- effectiveMask := unmaskableBits | atomic.LoadUint32(&w.mask)\n- matchedEvents := effectiveMask & events\n-\n- if matchedEvents == 0 {\n+ mask := atomic.LoadUint32(&w.mask)\n+ if mask&events == 0 {\n// We weren't watching for this event.\nreturn\n}\n+ // Event mask should include bits matched from the watch plus all control\n+ // event bits.\n+ unmaskableBits := ^uint32(0) &^ linux.IN_ALL_EVENTS\n+ effectiveMask := unmaskableBits | mask\n+ matchedEvents := effectiveMask & events\nw.owner.queueEvent(newEvent(w.wd, name, matchedEvents, cookie))\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/strace/linux64.go",
"new_path": "pkg/sentry/strace/linux64.go",
"diff": "@@ -271,7 +271,7 @@ var linuxAMD64 = SyscallMap{\n251: makeSyscallInfo(\"ioprio_set\", Hex, Hex, Hex),\n252: makeSyscallInfo(\"ioprio_get\", Hex, Hex),\n253: makeSyscallInfo(\"inotify_init\"),\n- 254: makeSyscallInfo(\"inotify_add_watch\", Hex, Hex, Hex),\n+ 254: makeSyscallInfo(\"inotify_add_watch\", Hex, Path, Hex),\n255: makeSyscallInfo(\"inotify_rm_watch\", Hex, Hex),\n256: makeSyscallInfo(\"migrate_pages\", Hex, Hex, Hex, Hex),\n257: makeSyscallInfo(\"openat\", Hex, Path, OpenFlags, Mode),\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/inotify.cc",
"new_path": "test/syscalls/linux/inotify.cc",
"diff": "@@ -1484,6 +1484,34 @@ TEST(Inotify, MaskAddMergesWithExistingEventMask) {\nASSERT_THAT(events, Are({Event(IN_CLOSE_WRITE, wd)}));\n}\n+// Test that control events bits are not considered when checking event mask.\n+TEST(Inotify, ControlEvents) {\n+ const TempPath dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n+ const FileDescriptor fd =\n+ ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));\n+\n+ const int wd = ASSERT_NO_ERRNO_AND_VALUE(\n+ InotifyAddWatch(fd.get(), dir.path(), IN_ACCESS));\n+\n+ // Check that events in the mask are dispatched and that control bits are\n+ // part of the event mask.\n+ std::vector<std::string> files =\n+ ASSERT_NO_ERRNO_AND_VALUE(ListDir(dir.path(), false));\n+ ASSERT_EQ(files.size(), 2);\n+\n+ const std::vector<Event> events1 =\n+ ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));\n+ ASSERT_THAT(events1, Are({Event(IN_ACCESS | IN_ISDIR, wd)}));\n+\n+ // Check that events not in the mask are discarded.\n+ const FileDescriptor dir_fd =\n+ ASSERT_NO_ERRNO_AND_VALUE(Open(dir.path(), O_RDONLY | O_DIRECTORY));\n+\n+ const std::vector<Event> events2 =\n+ ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));\n+ ASSERT_THAT(events2, Are({}));\n+}\n+\n} // namespace\n} // namespace testing\n} // namespace gvisor\n"
}
] | Go | Apache License 2.0 | google/gvisor | inotify notifies watchers when control events bit are set
The code that matches the event being published with events watchers
was wronly matching all watchers in case any of the control event bits
were set.
Issue #121
PiperOrigin-RevId: 226521230
Change-Id: Ie2c42bc4366faaf59fbf80a74e9297499bd93f9e |
259,881 | 21.12.2018 12:14:17 | 28,800 | 0e9b32485670bb321b9b2eee3f1860e0db43d377 | Fix test util tests
We actually need to include test main! | [
{
"change_type": "MODIFY",
"old_path": "test/util/BUILD",
"new_path": "test/util/BUILD",
"diff": "@@ -52,7 +52,9 @@ cc_test(\nsrcs = [\"proc_util_test.cc\"],\ndeps = [\n\":proc_util\",\n+ \":test_main\",\n\":test_util\",\n+ \"@com_google_googletest//:gtest\",\n],\n)\n@@ -84,7 +86,9 @@ cc_test(\n\":fs_util\",\n\":posix_error\",\n\":temp_path\",\n+ \":test_main\",\n\":test_util\",\n+ \"@com_google_googletest//:gtest\",\n],\n)\n@@ -161,7 +165,11 @@ cc_test(\nname = \"posix_error_test\",\nsize = \"small\",\nsrcs = [\"posix_error_test.cc\"],\n- deps = [\":posix_error\"],\n+ deps = [\n+ \":posix_error\",\n+ \":test_main\",\n+ \"@com_google_googletest//:gtest\",\n+ ],\n)\ncc_library(\n@@ -238,7 +246,11 @@ cc_test(\nname = \"test_util_test\",\nsize = \"small\",\nsrcs = [\"test_util_test.cc\"],\n- deps = [\":test_util\"],\n+ deps = [\n+ \":test_main\",\n+ \":test_util\",\n+ \"@com_google_googletest//:gtest\",\n+ ],\n)\ncc_library(\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix test util tests
We actually need to include test main!
PiperOrigin-RevId: 226524447
Change-Id: I9d9e631611183c7c1fbae1c20a222c9aeef269b2 |
259,854 | 21.12.2018 13:12:32 | 28,800 | b515556519a44d4b6a23590e236bb4f30726b5bf | Implement SO_KEEPALIVE, TCP_KEEPIDLE, and TCP_KEEPINTVL.
Within gVisor, plumb new socket options to netstack.
Within netstack, fix GetSockOpt and SetSockOpt return value logic. | [
{
"change_type": "MODIFY",
"old_path": "pkg/abi/linux/tcp.go",
"new_path": "pkg/abi/linux/tcp.go",
"diff": "@@ -52,3 +52,9 @@ const (\nTCP_ZEROCOPY_RECEIVE = 35\nTCP_INQ = 36\n)\n+\n+// Socket constants from include/net/tcp.h.\n+const (\n+ MAX_TCP_KEEPIDLE = 32767\n+ MAX_TCP_KEEPINTVL = 32767\n+)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/epsocket/epsocket.go",
"new_path": "pkg/sentry/socket/epsocket/epsocket.go",
"diff": "@@ -636,7 +636,13 @@ func getSockOptSocket(t *kernel.Task, s socket.Socket, ep commonEndpoint, family\nif outLen < sizeOfInt32 {\nreturn nil, syserr.ErrInvalidArgument\n}\n- return int32(0), nil\n+\n+ var v tcpip.KeepaliveEnabledOption\n+ if err := ep.GetSockOpt(&v); err != nil {\n+ return nil, syserr.TranslateNetstackError(err)\n+ }\n+\n+ return int32(v), nil\ncase linux.SO_LINGER:\nif outLen < syscall.SizeofLinger {\n@@ -720,6 +726,30 @@ func getSockOptTCP(t *kernel.Task, ep commonEndpoint, name, outLen int) (interfa\nreturn int32(v), nil\n+ case linux.TCP_KEEPIDLE:\n+ if outLen < sizeOfInt32 {\n+ return nil, syserr.ErrInvalidArgument\n+ }\n+\n+ var v tcpip.KeepaliveIdleOption\n+ if err := ep.GetSockOpt(&v); err != nil {\n+ return nil, syserr.TranslateNetstackError(err)\n+ }\n+\n+ return int32(time.Duration(v) / time.Second), nil\n+\n+ case linux.TCP_KEEPINTVL:\n+ if outLen < sizeOfInt32 {\n+ return nil, syserr.ErrInvalidArgument\n+ }\n+\n+ var v tcpip.KeepaliveIntervalOption\n+ if err := ep.GetSockOpt(&v); err != nil {\n+ return nil, syserr.TranslateNetstackError(err)\n+ }\n+\n+ return int32(time.Duration(v) / time.Second), nil\n+\ncase linux.TCP_INFO:\nvar v tcpip.TCPInfoOption\nif err := ep.GetSockOpt(&v); err != nil {\n@@ -843,6 +873,14 @@ func setSockOptSocket(t *kernel.Task, s socket.Socket, ep commonEndpoint, name i\nv := usermem.ByteOrder.Uint32(optVal)\nreturn syserr.TranslateNetstackError(ep.SetSockOpt(tcpip.PasscredOption(v)))\n+ case linux.SO_KEEPALIVE:\n+ if len(optVal) < sizeOfInt32 {\n+ return syserr.ErrInvalidArgument\n+ }\n+\n+ v := usermem.ByteOrder.Uint32(optVal)\n+ return syserr.TranslateNetstackError(ep.SetSockOpt(tcpip.KeepaliveEnabledOption(v)))\n+\ncase linux.SO_SNDTIMEO:\nif len(optVal) < linux.SizeOfTimeval {\nreturn syserr.ErrInvalidArgument\n@@ -916,6 +954,28 @@ func setSockOptTCP(t *kernel.Task, ep commonEndpoint, name int, optVal []byte) *\nv := usermem.ByteOrder.Uint32(optVal)\nreturn syserr.TranslateNetstackError(ep.SetSockOpt(tcpip.QuickAckOption(v)))\n+ case linux.TCP_KEEPIDLE:\n+ if len(optVal) < sizeOfInt32 {\n+ return syserr.ErrInvalidArgument\n+ }\n+\n+ v := usermem.ByteOrder.Uint32(optVal)\n+ if v < 1 || v > linux.MAX_TCP_KEEPIDLE {\n+ return syserr.ErrInvalidArgument\n+ }\n+ return syserr.TranslateNetstackError(ep.SetSockOpt(tcpip.KeepaliveIdleOption(time.Second * time.Duration(v))))\n+\n+ case linux.TCP_KEEPINTVL:\n+ if len(optVal) < sizeOfInt32 {\n+ return syserr.ErrInvalidArgument\n+ }\n+\n+ v := usermem.ByteOrder.Uint32(optVal)\n+ if v < 1 || v > linux.MAX_TCP_KEEPINTVL {\n+ return syserr.ErrInvalidArgument\n+ }\n+ return syserr.TranslateNetstackError(ep.SetSockOpt(tcpip.KeepaliveIntervalOption(time.Second * time.Duration(v))))\n+\ncase linux.TCP_REPAIR_OPTIONS:\nt.Kernel().EmitUnimplementedEvent(t)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/unix/transport/unix.go",
"new_path": "pkg/sentry/socket/unix/transport/unix.go",
"diff": "@@ -837,6 +837,7 @@ func (e *baseEndpoint) GetSockOpt(opt interface{}) *tcpip.Error {\nswitch o := opt.(type) {\ncase tcpip.ErrorOption:\nreturn nil\n+\ncase *tcpip.SendQueueSizeOption:\ne.Lock()\nif !e.Connected() {\n@@ -850,6 +851,7 @@ func (e *baseEndpoint) GetSockOpt(opt interface{}) *tcpip.Error {\n}\n*o = qs\nreturn nil\n+\ncase *tcpip.ReceiveQueueSizeOption:\ne.Lock()\nif !e.Connected() {\n@@ -863,6 +865,7 @@ func (e *baseEndpoint) GetSockOpt(opt interface{}) *tcpip.Error {\n}\n*o = qs\nreturn nil\n+\ncase *tcpip.PasscredOption:\nif e.Passcred() {\n*o = tcpip.PasscredOption(1)\n@@ -870,6 +873,7 @@ func (e *baseEndpoint) GetSockOpt(opt interface{}) *tcpip.Error {\n*o = tcpip.PasscredOption(0)\n}\nreturn nil\n+\ncase *tcpip.SendBufferSizeOption:\ne.Lock()\nif !e.Connected() {\n@@ -883,6 +887,7 @@ func (e *baseEndpoint) GetSockOpt(opt interface{}) *tcpip.Error {\n}\n*o = qs\nreturn nil\n+\ncase *tcpip.ReceiveBufferSizeOption:\ne.Lock()\nif e.receiver == nil {\n@@ -896,9 +901,15 @@ func (e *baseEndpoint) GetSockOpt(opt interface{}) *tcpip.Error {\n}\n*o = qs\nreturn nil\n- }\n+\n+ case *tcpip.KeepaliveEnabledOption:\n+ *o = 0\n+ return nil\n+\n+ default:\nreturn tcpip.ErrUnknownProtocolOption\n}\n+}\n// Shutdown closes the read and/or write end of the endpoint connection to its\n// peer.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/ping/endpoint.go",
"new_path": "pkg/tcpip/transport/ping/endpoint.go",
"diff": "@@ -358,10 +358,16 @@ func (e *endpoint) GetSockOpt(opt interface{}) *tcpip.Error {\n*o = 1\n}\ne.rcvMu.Unlock()\n- }\n+ return nil\n+ case *tcpip.KeepaliveEnabledOption:\n+ *o = 0\n+ return nil\n+\n+ default:\nreturn tcpip.ErrUnknownProtocolOption\n}\n+}\nfunc sendPing4(r *stack.Route, ident uint16, data buffer.View) *tcpip.Error {\nif len(data) < header.ICMPv4EchoMinimumSize {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/endpoint.go",
"new_path": "pkg/tcpip/transport/tcp/endpoint.go",
"diff": "@@ -662,7 +662,6 @@ func (e *endpoint) SetSockOpt(opt interface{}) *tcpip.Error {\n} else {\natomic.StoreUint32(&e.delay, 1)\n}\n-\nreturn nil\ncase tcpip.CorkOption:\n@@ -674,7 +673,6 @@ func (e *endpoint) SetSockOpt(opt interface{}) *tcpip.Error {\n} else {\natomic.StoreUint32(&e.cork, 1)\n}\n-\nreturn nil\ncase tcpip.ReuseAddressOption:\n@@ -689,7 +687,6 @@ func (e *endpoint) SetSockOpt(opt interface{}) *tcpip.Error {\n} else {\natomic.StoreUint32(&e.slowAck, 0)\n}\n-\nreturn nil\ncase tcpip.ReceiveBufferSizeOption:\n@@ -754,7 +751,6 @@ func (e *endpoint) SetSockOpt(opt interface{}) *tcpip.Error {\ne.sndBufMu.Lock()\ne.sndBufSize = size\ne.sndBufMu.Unlock()\n-\nreturn nil\ncase tcpip.V6OnlyOption:\n@@ -772,35 +768,40 @@ func (e *endpoint) SetSockOpt(opt interface{}) *tcpip.Error {\n}\ne.v6only = v != 0\n+ return nil\ncase tcpip.KeepaliveEnabledOption:\ne.keepalive.Lock()\ne.keepalive.enabled = v != 0\ne.keepalive.Unlock()\ne.notifyProtocolGoroutine(notifyKeepaliveChanged)\n+ return nil\ncase tcpip.KeepaliveIdleOption:\ne.keepalive.Lock()\ne.keepalive.idle = time.Duration(v)\ne.keepalive.Unlock()\ne.notifyProtocolGoroutine(notifyKeepaliveChanged)\n+ return nil\ncase tcpip.KeepaliveIntervalOption:\ne.keepalive.Lock()\ne.keepalive.interval = time.Duration(v)\ne.keepalive.Unlock()\ne.notifyProtocolGoroutine(notifyKeepaliveChanged)\n+ return nil\ncase tcpip.KeepaliveCountOption:\ne.keepalive.Lock()\ne.keepalive.count = int(v)\ne.keepalive.Unlock()\ne.notifyProtocolGoroutine(notifyKeepaliveChanged)\n+ return nil\n- }\n-\n+ default:\nreturn nil\n}\n+}\n// readyReceiveSize returns the number of bytes ready to be received.\nfunc (e *endpoint) readyReceiveSize() (int, *tcpip.Error) {\n@@ -908,7 +909,6 @@ func (e *endpoint) GetSockOpt(opt interface{}) *tcpip.Error {\no.RTTVar = snd.rtt.rttvar\nsnd.rtt.Unlock()\n}\n-\nreturn nil\ncase *tcpip.KeepaliveEnabledOption:\n@@ -920,26 +920,30 @@ func (e *endpoint) GetSockOpt(opt interface{}) *tcpip.Error {\nif v {\n*o = 1\n}\n+ return nil\ncase *tcpip.KeepaliveIdleOption:\ne.keepalive.Lock()\n*o = tcpip.KeepaliveIdleOption(e.keepalive.idle)\ne.keepalive.Unlock()\n+ return nil\ncase *tcpip.KeepaliveIntervalOption:\ne.keepalive.Lock()\n*o = tcpip.KeepaliveIntervalOption(e.keepalive.interval)\ne.keepalive.Unlock()\n+ return nil\ncase *tcpip.KeepaliveCountOption:\ne.keepalive.Lock()\n*o = tcpip.KeepaliveCountOption(e.keepalive.count)\ne.keepalive.Unlock()\n+ return nil\n- }\n-\n+ default:\nreturn tcpip.ErrUnknownProtocolOption\n}\n+}\nfunc (e *endpoint) checkV4Mapped(addr *tcpip.FullAddress) (tcpip.NetworkProtocolNumber, *tcpip.Error) {\nnetProto := e.netProto\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/udp/endpoint.go",
"new_path": "pkg/tcpip/transport/udp/endpoint.go",
"diff": "@@ -505,16 +505,22 @@ func (e *endpoint) GetSockOpt(opt interface{}) *tcpip.Error {\n*o = 1\n}\ne.rcvMu.Unlock()\n+ return nil\ncase *tcpip.MulticastTTLOption:\ne.mu.Lock()\n*o = tcpip.MulticastTTLOption(e.multicastTTL)\ne.mu.Unlock()\nreturn nil\n- }\n+ case *tcpip.KeepaliveEnabledOption:\n+ *o = 0\n+ return nil\n+\n+ default:\nreturn tcpip.ErrUnknownProtocolOption\n}\n+}\n// sendUDP sends a UDP segment via the provided network endpoint and under the\n// provided identity.\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_ip_tcp_generic.cc",
"new_path": "test/syscalls/linux/socket_ip_tcp_generic.cc",
"diff": "@@ -296,7 +296,7 @@ TEST_P(TCPSocketPairTest, TCPCorkDefault) {\ngetsockopt(sockets->first_fd(), IPPROTO_TCP, TCP_CORK, &get, &get_len),\nSyscallSucceedsWithValue(0));\nEXPECT_EQ(get_len, sizeof(get));\n- EXPECT_EQ(get, 0);\n+ EXPECT_EQ(get, kSockOptOff);\n}\nTEST_P(TCPSocketPairTest, SetTCPCork) {\n@@ -388,5 +388,139 @@ TEST_P(TCPSocketPairTest, SetTCPQuickAck) {\nEXPECT_EQ(get, kSockOptOn);\n}\n+TEST_P(TCPSocketPairTest, SoKeepaliveDefault) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ int get = -1;\n+ socklen_t get_len = sizeof(get);\n+ EXPECT_THAT(\n+ getsockopt(sockets->first_fd(), SOL_SOCKET, SO_KEEPALIVE, &get, &get_len),\n+ SyscallSucceedsWithValue(0));\n+ EXPECT_EQ(get_len, sizeof(get));\n+ EXPECT_EQ(get, kSockOptOff);\n+}\n+\n+TEST_P(TCPSocketPairTest, SetSoKeepalive) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ ASSERT_THAT(setsockopt(sockets->first_fd(), SOL_SOCKET, SO_KEEPALIVE,\n+ &kSockOptOn, sizeof(kSockOptOn)),\n+ SyscallSucceeds());\n+\n+ int get = -1;\n+ socklen_t get_len = sizeof(get);\n+ EXPECT_THAT(\n+ getsockopt(sockets->first_fd(), SOL_SOCKET, SO_KEEPALIVE, &get, &get_len),\n+ SyscallSucceedsWithValue(0));\n+ EXPECT_EQ(get_len, sizeof(get));\n+ EXPECT_EQ(get, kSockOptOn);\n+\n+ ASSERT_THAT(setsockopt(sockets->first_fd(), SOL_SOCKET, SO_KEEPALIVE,\n+ &kSockOptOff, sizeof(kSockOptOff)),\n+ SyscallSucceeds());\n+\n+ EXPECT_THAT(\n+ getsockopt(sockets->first_fd(), SOL_SOCKET, SO_KEEPALIVE, &get, &get_len),\n+ SyscallSucceedsWithValue(0));\n+ EXPECT_EQ(get_len, sizeof(get));\n+ EXPECT_EQ(get, kSockOptOff);\n+}\n+\n+TEST_P(TCPSocketPairTest, TCPKeepidleDefault) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ int get = -1;\n+ socklen_t get_len = sizeof(get);\n+ EXPECT_THAT(getsockopt(sockets->first_fd(), IPPROTO_TCP, TCP_KEEPIDLE, &get,\n+ &get_len),\n+ SyscallSucceedsWithValue(0));\n+ EXPECT_EQ(get_len, sizeof(get));\n+ EXPECT_EQ(get, 2 * 60 * 60); // 2 hours.\n+}\n+\n+TEST_P(TCPSocketPairTest, TCPKeepintvlDefault) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ int get = -1;\n+ socklen_t get_len = sizeof(get);\n+ EXPECT_THAT(getsockopt(sockets->first_fd(), IPPROTO_TCP, TCP_KEEPINTVL, &get,\n+ &get_len),\n+ SyscallSucceedsWithValue(0));\n+ EXPECT_EQ(get_len, sizeof(get));\n+ EXPECT_EQ(get, 75); // 75 seconds.\n+}\n+\n+TEST_P(TCPSocketPairTest, SetTCPKeepidleZero) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ constexpr int kZero = 0;\n+ EXPECT_THAT(setsockopt(sockets->first_fd(), IPPROTO_TCP, TCP_KEEPIDLE, &kZero,\n+ sizeof(kZero)),\n+ SyscallFailsWithErrno(EINVAL));\n+}\n+\n+TEST_P(TCPSocketPairTest, SetTCPKeepintvlZero) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ constexpr int kZero = 0;\n+ EXPECT_THAT(setsockopt(sockets->first_fd(), IPPROTO_TCP, TCP_KEEPINTVL,\n+ &kZero, sizeof(kZero)),\n+ SyscallFailsWithErrno(EINVAL));\n+}\n+\n+// Copied from include/net/tcp.h.\n+constexpr int MAX_TCP_KEEPIDLE = 32767;\n+constexpr int MAX_TCP_KEEPINTVL = 32767;\n+\n+TEST_P(TCPSocketPairTest, SetTCPKeepidleAboveMax) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ constexpr int kAboveMax = MAX_TCP_KEEPIDLE + 1;\n+ EXPECT_THAT(setsockopt(sockets->first_fd(), IPPROTO_TCP, TCP_KEEPIDLE,\n+ &kAboveMax, sizeof(kAboveMax)),\n+ SyscallFailsWithErrno(EINVAL));\n+}\n+\n+TEST_P(TCPSocketPairTest, SetTCPKeepintvlAboveMax) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ constexpr int kAboveMax = MAX_TCP_KEEPINTVL + 1;\n+ EXPECT_THAT(setsockopt(sockets->first_fd(), IPPROTO_TCP, TCP_KEEPINTVL,\n+ &kAboveMax, sizeof(kAboveMax)),\n+ SyscallFailsWithErrno(EINVAL));\n+}\n+\n+TEST_P(TCPSocketPairTest, SetTCPKeepidleToMax) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ EXPECT_THAT(setsockopt(sockets->first_fd(), IPPROTO_TCP, TCP_KEEPIDLE,\n+ &MAX_TCP_KEEPIDLE, sizeof(MAX_TCP_KEEPIDLE)),\n+ SyscallSucceedsWithValue(0));\n+\n+ int get = -1;\n+ socklen_t get_len = sizeof(get);\n+ EXPECT_THAT(getsockopt(sockets->first_fd(), IPPROTO_TCP, TCP_KEEPIDLE, &get,\n+ &get_len),\n+ SyscallSucceedsWithValue(0));\n+ EXPECT_EQ(get_len, sizeof(get));\n+ EXPECT_EQ(get, MAX_TCP_KEEPIDLE);\n+}\n+\n+TEST_P(TCPSocketPairTest, SetTCPKeepintvlToMax) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ EXPECT_THAT(setsockopt(sockets->first_fd(), IPPROTO_TCP, TCP_KEEPINTVL,\n+ &MAX_TCP_KEEPINTVL, sizeof(MAX_TCP_KEEPINTVL)),\n+ SyscallSucceedsWithValue(0));\n+\n+ int get = -1;\n+ socklen_t get_len = sizeof(get);\n+ EXPECT_THAT(getsockopt(sockets->first_fd(), IPPROTO_TCP, TCP_KEEPINTVL, &get,\n+ &get_len),\n+ SyscallSucceedsWithValue(0));\n+ EXPECT_EQ(get_len, sizeof(get));\n+ EXPECT_EQ(get, MAX_TCP_KEEPINTVL);\n+}\n+\n} // namespace testing\n} // namespace gvisor\n"
}
] | Go | Apache License 2.0 | google/gvisor | Implement SO_KEEPALIVE, TCP_KEEPIDLE, and TCP_KEEPINTVL.
Within gVisor, plumb new socket options to netstack.
Within netstack, fix GetSockOpt and SetSockOpt return value logic.
PiperOrigin-RevId: 226532229
Change-Id: If40734e119eed633335f40b4c26facbebc791c74 |
259,853 | 21.12.2018 15:39:04 | 28,800 | 89b18f7108e2c3a04169e0b79b615429fbb08a99 | Remove gunit_no_heapcheck from deps
heapcheck works fine now. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/BUILD",
"new_path": "test/syscalls/linux/BUILD",
"diff": "@@ -254,14 +254,15 @@ cc_binary(\n],\nlinkstatic = 1,\ndeps = [\n+ # The heap check doesn't handle mremap properly.\n+ \"@com_google_googletest//:gtest\",\n+ \"@com_google_absl//absl/strings\",\n\"//test/util:cleanup\",\n\"//test/util:file_descriptor\",\n\"//test/util:posix_error\",\n\"//test/util:temp_path\",\n\"//test/util:test_main\",\n\"//test/util:test_util\",\n- \"@com_google_absl//absl/strings\",\n- \"@com_google_googletest//:gtest\",\n],\n)\n@@ -1081,6 +1082,9 @@ cc_binary(\nsrcs = [\"mremap.cc\"],\nlinkstatic = 1,\ndeps = [\n+ # The heap check fails due to MremapDeathTest\n+ \"@com_google_googletest//:gtest\",\n+ \"@com_google_absl//absl/strings\",\n\"//test/util:file_descriptor\",\n\"//test/util:logging\",\n\"//test/util:memory_util\",\n@@ -1089,8 +1093,6 @@ cc_binary(\n\"//test/util:temp_path\",\n\"//test/util:test_main\",\n\"//test/util:test_util\",\n- \"@com_google_absl//absl/strings\",\n- \"@com_google_googletest//:gtest\",\n],\n)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Remove gunit_no_heapcheck from deps
heapcheck works fine now.
PiperOrigin-RevId: 226552252
Change-Id: Ifcf17a377b3d6512a576f54462dd81c1d4c7b17c |
259,854 | 21.12.2018 19:45:43 | 28,800 | 0df0df35fc4aa4d69dc01f7c7e2d9e0530a34db7 | Stub out SO_OOBINLINE.
We don't explicitly support out-of-band data and treat it like normal in-band
data. This is equilivent to SO_OOBINLINE being enabled, so always report that
it is enabled. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/epsocket/epsocket.go",
"new_path": "pkg/sentry/socket/epsocket/epsocket.go",
"diff": "@@ -678,6 +678,18 @@ func getSockOptSocket(t *kernel.Task, s socket.Socket, ep commonEndpoint, family\nreturn int32(v), nil\n+ case linux.SO_OOBINLINE:\n+ if outLen < sizeOfInt32 {\n+ return nil, syserr.ErrInvalidArgument\n+ }\n+\n+ var v tcpip.OutOfBandInlineOption\n+ if err := ep.GetSockOpt(&v); err != nil {\n+ return nil, syserr.TranslateNetstackError(err)\n+ }\n+\n+ return int32(v), nil\n+\ndefault:\nsocket.GetSockOptEmitUnimplementedEvent(t, name)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/tcpip.go",
"new_path": "pkg/tcpip/tcpip.go",
"diff": "@@ -497,6 +497,10 @@ type AddMembershipOption MembershipOption\n// the given interface address.\ntype RemoveMembershipOption MembershipOption\n+// OutOfBandInlineOption is used by SetSockOpt/GetSockOpt to specify whether\n+// TCP out-of-band data is delivered along with the normal in-band data.\n+type OutOfBandInlineOption int\n+\n// Route is a row in the routing table. It specifies through which NIC (and\n// gateway) sets of packets should be routed. A row is considered viable if the\n// masked target address matches the destination adddress in the row.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/endpoint.go",
"new_path": "pkg/tcpip/transport/tcp/endpoint.go",
"diff": "@@ -940,6 +940,11 @@ func (e *endpoint) GetSockOpt(opt interface{}) *tcpip.Error {\ne.keepalive.Unlock()\nreturn nil\n+ case *tcpip.OutOfBandInlineOption:\n+ // We don't currently support disabling this option.\n+ *o = 1\n+ return nil\n+\ndefault:\nreturn tcpip.ErrUnknownProtocolOption\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_ip_tcp_generic.cc",
"new_path": "test/syscalls/linux/socket_ip_tcp_generic.cc",
"diff": "@@ -522,5 +522,21 @@ TEST_P(TCPSocketPairTest, SetTCPKeepintvlToMax) {\nEXPECT_EQ(get, MAX_TCP_KEEPINTVL);\n}\n+TEST_P(TCPSocketPairTest, SetOOBInline) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ EXPECT_THAT(setsockopt(sockets->first_fd(), SOL_SOCKET, SO_OOBINLINE,\n+ &kSockOptOn, sizeof(kSockOptOn)),\n+ SyscallSucceeds());\n+\n+ int get = -1;\n+ socklen_t get_len = sizeof(get);\n+ EXPECT_THAT(\n+ getsockopt(sockets->first_fd(), SOL_SOCKET, SO_OOBINLINE, &get, &get_len),\n+ SyscallSucceedsWithValue(0));\n+ EXPECT_EQ(get_len, sizeof(get));\n+ EXPECT_EQ(get, kSockOptOn);\n+}\n+\n} // namespace testing\n} // namespace gvisor\n"
}
] | Go | Apache License 2.0 | google/gvisor | Stub out SO_OOBINLINE.
We don't explicitly support out-of-band data and treat it like normal in-band
data. This is equilivent to SO_OOBINLINE being enabled, so always report that
it is enabled.
PiperOrigin-RevId: 226572742
Change-Id: I4c30ccb83265e76c30dea631cbf86822e6ee1c1b |
260,013 | 26.12.2018 11:24:29 | 28,800 | bfa2f314ca05854b0d08aa2f5c2b93b16542d95f | Add EventChannel messages for uncaught signals. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/BUILD",
"new_path": "pkg/sentry/kernel/BUILD",
"diff": "+load(\"@io_bazel_rules_go//proto:def.bzl\", \"go_proto_library\")\n+\npackage(licenses = [\"notice\"]) # Apache 2.0\nload(\"//tools/go_generics:defs.bzl\", \"go_template_instance\")\n@@ -62,6 +64,21 @@ go_template_instance(\n},\n)\n+proto_library(\n+ name = \"uncaught_signal_proto\",\n+ srcs = [\"uncaught_signal.proto\"],\n+ visibility = [\"//visibility:public\"],\n+ deps = [\"//pkg/sentry/arch:registers_proto\"],\n+)\n+\n+go_proto_library(\n+ name = \"uncaught_signal_go_proto\",\n+ importpath = \"gvisor.googlesource.com/gvisor/pkg/sentry/kernel/uncaught_signal_go_proto\",\n+ proto = \":uncaught_signal_proto\",\n+ visibility = [\"//visibility:public\"],\n+ deps = [\"//pkg/sentry/arch:registers_go_proto\"],\n+)\n+\ngo_library(\nname = \"kernel\",\nsrcs = [\n@@ -122,6 +139,7 @@ go_library(\n],\nvisibility = [\"//:sandbox\"],\ndeps = [\n+ \":uncaught_signal_go_proto\",\n\"//pkg/abi\",\n\"//pkg/abi/linux\",\n\"//pkg/amutex\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/task_signals.go",
"new_path": "pkg/sentry/kernel/task_signals.go",
"diff": "@@ -22,8 +22,10 @@ import (\n\"time\"\n\"gvisor.googlesource.com/gvisor/pkg/abi/linux\"\n+ \"gvisor.googlesource.com/gvisor/pkg/eventchannel\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/arch\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/kernel/auth\"\n+ ucspb \"gvisor.googlesource.com/gvisor/pkg/sentry/kernel/uncaught_signal_go_proto\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/usermem\"\n\"gvisor.googlesource.com/gvisor/pkg/syserror\"\n)\n@@ -184,6 +186,23 @@ func (t *Task) deliverSignal(info *arch.SignalInfo, act arch.SignalAct) taskRunS\ncase SignalActionTerm, SignalActionCore:\n// \"Default action is to terminate the process.\" - signal(7)\nt.Debugf(\"Signal %d: terminating thread group\", info.Signo)\n+\n+ // Emit an event channel messages related to this uncaught signal.\n+ ucs := &ucspb.UncaughtSignal{\n+ Tid: int32(t.Kernel().TaskSet().Root.IDOfTask(t)),\n+ Pid: int32(t.Kernel().TaskSet().Root.IDOfThreadGroup(t.ThreadGroup())),\n+ Registers: t.Arch().StateData().Proto(),\n+ SignalNumber: info.Signo,\n+ }\n+\n+ // Attach an fault address if appropriate.\n+ switch linux.Signal(info.Signo) {\n+ case linux.SIGSEGV, linux.SIGFPE, linux.SIGILL, linux.SIGTRAP, linux.SIGBUS:\n+ ucs.FaultAddr = info.Addr()\n+ }\n+\n+ eventchannel.Emit(ucs)\n+\nt.PrepareGroupExit(ExitStatus{Signo: int(info.Signo)})\nreturn (*runExit)(nil)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/kernel/uncaught_signal.proto",
"diff": "+// Copyright 2018 Google LLC\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+syntax = \"proto3\";\n+\n+package gvisor;\n+\n+import \"pkg/sentry/arch/registers.proto\";\n+\n+message UncaughtSignal {\n+ // Thread ID.\n+ int32 tid = 1;\n+\n+ // Process ID.\n+ int32 pid = 2;\n+\n+ // Registers at the time of the fault or signal.\n+ Registers registers = 3;\n+\n+ // Signal number.\n+ int32 signal_number = 4;\n+\n+ // The memory location which caused the fault (set if applicable, 0\n+ // otherwise). This will be set for SIGILL, SIGFPE, SIGSEGV, and SIGBUS.\n+ uint64 fault_addr = 5;\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add EventChannel messages for uncaught signals.
PiperOrigin-RevId: 226936778
Change-Id: I2a6dda157c55d39d81e1b543ab11a58a0bfe5c05 |
259,854 | 26.12.2018 23:51:00 | 28,800 | bce2f9751f415da869d04ccb53833b024373666d | Plumb IP_MULTICAST_TTL to netstack. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/epsocket/epsocket.go",
"new_path": "pkg/sentry/socket/epsocket/epsocket.go",
"diff": "@@ -531,8 +531,10 @@ func GetSockOpt(t *kernel.Task, s socket.Socket, ep commonEndpoint, family int,\ncase linux.SOL_IPV6:\nreturn getSockOptIPv6(t, ep, name, outLen)\n- case linux.SOL_IP,\n- linux.SOL_UDP,\n+ case linux.SOL_IP:\n+ return getSockOptIP(t, ep, name, outLen)\n+\n+ case linux.SOL_UDP,\nlinux.SOL_ICMPV6,\nlinux.SOL_RAW,\nlinux.SOL_PACKET:\n@@ -787,7 +789,7 @@ func getSockOptTCP(t *kernel.Task, ep commonEndpoint, name, outLen int) (interfa\nt.Kernel().EmitUnimplementedEvent(t)\ndefault:\n- emitUmplementedEventTCP(t, name)\n+ emitUnimplementedEventTCP(t, name)\n}\nreturn nil, syserr.ErrProtocolNotAvailable\n}\n@@ -811,7 +813,28 @@ func getSockOptIPv6(t *kernel.Task, ep commonEndpoint, name, outLen int) (interf\nt.Kernel().EmitUnimplementedEvent(t)\ndefault:\n- emitUmplementedEventIPv6(t, name)\n+ emitUnimplementedEventIPv6(t, name)\n+ }\n+ return nil, syserr.ErrProtocolNotAvailable\n+}\n+\n+// getSockOptIP implements GetSockOpt when level is SOL_IP.\n+func getSockOptIP(t *kernel.Task, ep commonEndpoint, name, outLen int) (interface{}, *syserr.Error) {\n+ switch name {\n+ case linux.IP_MULTICAST_TTL:\n+ if outLen < sizeOfInt32 {\n+ return nil, syserr.ErrInvalidArgument\n+ }\n+\n+ var v tcpip.MulticastTTLOption\n+ if err := ep.GetSockOpt(&v); err != nil {\n+ return nil, syserr.TranslateNetstackError(err)\n+ }\n+\n+ return int32(v), nil\n+\n+ default:\n+ emitUnimplementedEventIP(t, name)\n}\nreturn nil, syserr.ErrProtocolNotAvailable\n}\n@@ -992,7 +1015,7 @@ func setSockOptTCP(t *kernel.Task, ep commonEndpoint, name int, optVal []byte) *\nt.Kernel().EmitUnimplementedEvent(t)\ndefault:\n- emitUmplementedEventTCP(t, name)\n+ emitUnimplementedEventTCP(t, name)\n}\n// Default to the old behavior; hand off to network stack.\n@@ -1028,7 +1051,7 @@ func setSockOptIPv6(t *kernel.Task, ep commonEndpoint, name int, optVal []byte)\nt.Kernel().EmitUnimplementedEvent(t)\ndefault:\n- emitUmplementedEventIPv6(t, name)\n+ emitUnimplementedEventIPv6(t, name)\n}\n// Default to the old behavior; hand off to network stack.\n@@ -1038,6 +1061,21 @@ func setSockOptIPv6(t *kernel.Task, ep commonEndpoint, name int, optVal []byte)\n// setSockOptIP implements SetSockOpt when level is SOL_IP.\nfunc setSockOptIP(t *kernel.Task, ep commonEndpoint, name int, optVal []byte) *syserr.Error {\nswitch name {\n+ case linux.IP_MULTICAST_TTL:\n+ if len(optVal) < sizeOfInt32 {\n+ return syserr.ErrInvalidArgument\n+ }\n+\n+ v := int32(usermem.ByteOrder.Uint32(optVal))\n+ if v == -1 {\n+ // Linux translates -1 to 1.\n+ v = 1\n+ }\n+ if v < 0 || v > 255 {\n+ return syserr.ErrInvalidArgument\n+ }\n+ return syserr.TranslateNetstackError(ep.SetSockOpt(tcpip.MulticastTTLOption(v)))\n+\ncase linux.IP_ADD_MEMBERSHIP, linux.MCAST_JOIN_GROUP, linux.IP_MULTICAST_IF:\n// FIXME: Disallow IP-level multicast group options by\n// default. These will need to be supported by appropriately plumbing\n@@ -1060,7 +1098,6 @@ func setSockOptIP(t *kernel.Task, ep commonEndpoint, name int, optVal []byte) *s\nlinux.IP_MTU_DISCOVER,\nlinux.IP_MULTICAST_ALL,\nlinux.IP_MULTICAST_LOOP,\n- linux.IP_MULTICAST_TTL,\nlinux.IP_NODEFRAG,\nlinux.IP_OPTIONS,\nlinux.IP_PASSSEC,\n@@ -1092,10 +1129,10 @@ func setSockOptIP(t *kernel.Task, ep commonEndpoint, name int, optVal []byte) *s\nreturn syserr.TranslateNetstackError(ep.SetSockOpt(struct{}{}))\n}\n-// emitUmplementedEventTCP emits unimplemented event if name is valid. This\n+// emitUnimplementedEventTCP emits unimplemented event if name is valid. This\n// function contains names that are common between Get and SetSockOpt when\n// level is SOL_TCP.\n-func emitUmplementedEventTCP(t *kernel.Task, name int) {\n+func emitUnimplementedEventTCP(t *kernel.Task, name int) {\nswitch name {\ncase linux.TCP_CONGESTION,\nlinux.TCP_CORK,\n@@ -1129,10 +1166,10 @@ func emitUmplementedEventTCP(t *kernel.Task, name int) {\n}\n}\n-// emitUmplementedEventIPv6 emits unimplemented event if name is valid. It\n+// emitUnimplementedEventIPv6 emits unimplemented event if name is valid. It\n// contains names that are common between Get and SetSockOpt when level is\n// SOL_IPV6.\n-func emitUmplementedEventIPv6(t *kernel.Task, name int) {\n+func emitUnimplementedEventIPv6(t *kernel.Task, name int) {\nswitch name {\ncase linux.IPV6_2292DSTOPTS,\nlinux.IPV6_2292HOPLIMIT,\n@@ -1179,6 +1216,60 @@ func emitUmplementedEventIPv6(t *kernel.Task, name int) {\n}\n}\n+// emitUnimplementedEventIP emits unimplemented event if name is valid. It\n+// contains names that are common between Get and SetSockOpt when level is\n+// SOL_IP.\n+func emitUnimplementedEventIP(t *kernel.Task, name int) {\n+ switch name {\n+ case linux.IP_TOS,\n+ linux.IP_TTL,\n+ linux.IP_HDRINCL,\n+ linux.IP_OPTIONS,\n+ linux.IP_ROUTER_ALERT,\n+ linux.IP_RECVOPTS,\n+ linux.IP_RETOPTS,\n+ linux.IP_PKTINFO,\n+ linux.IP_PKTOPTIONS,\n+ linux.IP_MTU_DISCOVER,\n+ linux.IP_RECVERR,\n+ linux.IP_RECVTTL,\n+ linux.IP_RECVTOS,\n+ linux.IP_MTU,\n+ linux.IP_FREEBIND,\n+ linux.IP_IPSEC_POLICY,\n+ linux.IP_XFRM_POLICY,\n+ linux.IP_PASSSEC,\n+ linux.IP_TRANSPARENT,\n+ linux.IP_ORIGDSTADDR,\n+ linux.IP_MINTTL,\n+ linux.IP_NODEFRAG,\n+ linux.IP_CHECKSUM,\n+ linux.IP_BIND_ADDRESS_NO_PORT,\n+ linux.IP_RECVFRAGSIZE,\n+ linux.IP_MULTICAST_IF,\n+ linux.IP_MULTICAST_TTL,\n+ linux.IP_MULTICAST_LOOP,\n+ linux.IP_ADD_MEMBERSHIP,\n+ linux.IP_DROP_MEMBERSHIP,\n+ linux.IP_UNBLOCK_SOURCE,\n+ linux.IP_BLOCK_SOURCE,\n+ linux.IP_ADD_SOURCE_MEMBERSHIP,\n+ linux.IP_DROP_SOURCE_MEMBERSHIP,\n+ linux.IP_MSFILTER,\n+ linux.MCAST_JOIN_GROUP,\n+ linux.MCAST_BLOCK_SOURCE,\n+ linux.MCAST_UNBLOCK_SOURCE,\n+ linux.MCAST_LEAVE_GROUP,\n+ linux.MCAST_JOIN_SOURCE_GROUP,\n+ linux.MCAST_LEAVE_SOURCE_GROUP,\n+ linux.MCAST_MSFILTER,\n+ linux.IP_MULTICAST_ALL,\n+ linux.IP_UNICAST_IF:\n+\n+ t.Kernel().EmitUnimplementedEvent(t)\n+ }\n+}\n+\n// isLinkLocal determines if the given IPv6 address is link-local. This is the\n// case when it has the fe80::/10 prefix. This check is used to determine when\n// the NICID is relevant for a given IPv6 address.\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/BUILD",
"new_path": "test/syscalls/linux/BUILD",
"diff": "@@ -1875,6 +1875,24 @@ cc_library(\nalwayslink = 1,\n)\n+cc_library(\n+ name = \"socket_ip_udp_test_cases\",\n+ testonly = 1,\n+ srcs = [\n+ \"socket_ip_udp_generic.cc\",\n+ ],\n+ hdrs = [\n+ \"socket_ip_udp_generic.h\",\n+ ],\n+ deps = [\n+ \":ip_socket_test_util\",\n+ \":socket_test_util\",\n+ \"//test/util:test_util\",\n+ \"@com_google_googletest//:gtest\",\n+ ],\n+ alwayslink = 1,\n+)\n+\ncc_binary(\nname = \"socket_abstract_test\",\ntestonly = 1,\n@@ -2044,6 +2062,7 @@ cc_binary(\ndeps = [\n\":ip_socket_test_util\",\n\":socket_generic_test_cases\",\n+ \":socket_ip_udp_test_cases\",\n\":socket_non_stream_test_cases\",\n\":socket_test_util\",\n\"//test/util:test_main\",\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/syscalls/linux/socket_ip_udp_generic.cc",
"diff": "+// Copyright 2018 Google LLC\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+#include \"test/syscalls/linux/socket_ip_udp_generic.h\"\n+\n+#include <netinet/in.h>\n+#include <netinet/tcp.h>\n+#include <stdio.h>\n+#include <sys/ioctl.h>\n+#include <sys/poll.h>\n+#include <sys/socket.h>\n+#include <sys/types.h>\n+#include <sys/un.h>\n+\n+#include \"gtest/gtest.h\"\n+#include \"gtest/gtest.h\"\n+#include \"test/syscalls/linux/socket_test_util.h\"\n+#include \"test/util/test_util.h\"\n+\n+namespace gvisor {\n+namespace testing {\n+\n+TEST_P(UDPSocketPairTest, MulticastTTLDefault) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ int get = -1;\n+ socklen_t get_len = sizeof(get);\n+ EXPECT_THAT(getsockopt(sockets->first_fd(), IPPROTO_IP, IP_MULTICAST_TTL,\n+ &get, &get_len),\n+ SyscallSucceedsWithValue(0));\n+ EXPECT_EQ(get_len, sizeof(get));\n+ EXPECT_EQ(get, 1);\n+}\n+\n+TEST_P(UDPSocketPairTest, SetUDPMulticastTTLMin) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ constexpr int kMin = 0;\n+ EXPECT_THAT(setsockopt(sockets->first_fd(), IPPROTO_IP, IP_MULTICAST_TTL,\n+ &kMin, sizeof(kMin)),\n+ SyscallSucceeds());\n+\n+ int get = -1;\n+ socklen_t get_len = sizeof(get);\n+ EXPECT_THAT(getsockopt(sockets->first_fd(), IPPROTO_IP, IP_MULTICAST_TTL,\n+ &get, &get_len),\n+ SyscallSucceedsWithValue(0));\n+ EXPECT_EQ(get_len, sizeof(get));\n+ EXPECT_EQ(get, kMin);\n+}\n+\n+TEST_P(UDPSocketPairTest, SetUDPMulticastTTLMax) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ constexpr int kMax = 255;\n+ EXPECT_THAT(setsockopt(sockets->first_fd(), IPPROTO_IP, IP_MULTICAST_TTL,\n+ &kMax, sizeof(kMax)),\n+ SyscallSucceeds());\n+\n+ int get = -1;\n+ socklen_t get_len = sizeof(get);\n+ EXPECT_THAT(getsockopt(sockets->first_fd(), IPPROTO_IP, IP_MULTICAST_TTL,\n+ &get, &get_len),\n+ SyscallSucceedsWithValue(0));\n+ EXPECT_EQ(get_len, sizeof(get));\n+ EXPECT_EQ(get, kMax);\n+}\n+\n+TEST_P(UDPSocketPairTest, SetUDPMulticastTTLNegativeOne) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ constexpr int kArbitrary = 6;\n+ EXPECT_THAT(setsockopt(sockets->first_fd(), IPPROTO_IP, IP_MULTICAST_TTL,\n+ &kArbitrary, sizeof(kArbitrary)),\n+ SyscallSucceeds());\n+\n+ constexpr int kNegOne = -1;\n+ EXPECT_THAT(setsockopt(sockets->first_fd(), IPPROTO_IP, IP_MULTICAST_TTL,\n+ &kNegOne, sizeof(kNegOne)),\n+ SyscallSucceeds());\n+\n+ int get = -1;\n+ socklen_t get_len = sizeof(get);\n+ EXPECT_THAT(getsockopt(sockets->first_fd(), IPPROTO_IP, IP_MULTICAST_TTL,\n+ &get, &get_len),\n+ SyscallSucceedsWithValue(0));\n+ EXPECT_EQ(get_len, sizeof(get));\n+ EXPECT_EQ(get, 1);\n+}\n+\n+TEST_P(UDPSocketPairTest, SetUDPMulticastTTLBelowMin) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ constexpr int kBelowMin = -2;\n+ EXPECT_THAT(setsockopt(sockets->first_fd(), IPPROTO_IP, IP_MULTICAST_TTL,\n+ &kBelowMin, sizeof(kBelowMin)),\n+ SyscallFailsWithErrno(EINVAL));\n+}\n+\n+TEST_P(UDPSocketPairTest, SetUDPMulticastTTLAboveMax) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ constexpr int kAboveMax = 256;\n+ EXPECT_THAT(setsockopt(sockets->first_fd(), IPPROTO_IP, IP_MULTICAST_TTL,\n+ &kAboveMax, sizeof(kAboveMax)),\n+ SyscallFailsWithErrno(EINVAL));\n+}\n+\n+} // namespace testing\n+} // namespace gvisor\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/syscalls/linux/socket_ip_udp_generic.h",
"diff": "+// Copyright 2018 Google LLC\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+#ifndef GVISOR_TEST_SYSCALLS_LINUX_SOCKET_IP_UDP_GENERIC_H_\n+#define GVISOR_TEST_SYSCALLS_LINUX_SOCKET_IP_UDP_GENERIC_H_\n+\n+#include \"test/syscalls/linux/socket_test_util.h\"\n+\n+namespace gvisor {\n+namespace testing {\n+\n+// Test fixture for tests that apply to pairs of connected UDP sockets.\n+using UDPSocketPairTest = SocketPairTest;\n+\n+} // namespace testing\n+} // namespace gvisor\n+\n+#endif // GVISOR_TEST_SYSCALLS_LINUX_SOCKET_IP_UDP_GENERIC_H_\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_ip_udp_loopback.cc",
"new_path": "test/syscalls/linux/socket_ip_udp_loopback.cc",
"diff": "#include \"test/syscalls/linux/ip_socket_test_util.h\"\n#include \"test/syscalls/linux/socket_generic.h\"\n+#include \"test/syscalls/linux/socket_ip_udp_generic.h\"\n#include \"test/syscalls/linux/socket_non_stream.h\"\n#include \"test/syscalls/linux/socket_test_util.h\"\n#include \"test/util/test_util.h\"\n@@ -44,5 +45,9 @@ INSTANTIATE_TEST_CASE_P(\nAllUnixDomainSockets, NonStreamSocketPairTest,\n::testing::ValuesIn(IncludeReversals(GetSocketPairs())));\n+INSTANTIATE_TEST_CASE_P(\n+ UDPSockets, UDPSocketPairTest,\n+ ::testing::ValuesIn(IncludeReversals(GetSocketPairs())));\n+\n} // namespace testing\n} // namespace gvisor\n"
}
] | Go | Apache License 2.0 | google/gvisor | Plumb IP_MULTICAST_TTL to netstack.
PiperOrigin-RevId: 226993086
Change-Id: I71757f231436538081d494da32ca69f709bc71c7 |
259,992 | 28.12.2018 13:47:19 | 28,800 | a891afad6d7e3b09bafdccb4cc4b9fc4e577620e | Simplify synchronization between runsc and sandbox process
Make 'runsc create' join cgroup before creating sandbox process.
This removes the need to synchronize platform creation and ensure
that sandbox process is charged to the right cgroup from the start. | [
{
"change_type": "MODIFY",
"old_path": "runsc/boot/controller.go",
"new_path": "runsc/boot/controller.go",
"diff": "@@ -81,9 +81,6 @@ const (\n// and return its ExitStatus.\nContainerWait = \"containerManager.Wait\"\n- // ContainerWaitForLoader blocks until the container's loader has been created.\n- ContainerWaitForLoader = \"containerManager.WaitForLoader\"\n-\n// ContainerWaitPID is used to wait on a process with a certain PID in\n// the sandbox and return its ExitStatus.\nContainerWaitPID = \"containerManager.WaitPID\"\n@@ -115,8 +112,9 @@ type controller struct {\nmanager *containerManager\n}\n-// newController creates a new controller and starts it listening.\n-func newController(fd int, k *kernel.Kernel, w *watchdog.Watchdog) (*controller, error) {\n+// newController creates a new controller. The caller must call\n+// controller.srv.StartServing() to start the controller.\n+func newController(fd int, l *Loader) (*controller, error) {\nsrv, err := server.CreateFromFD(fd)\nif err != nil {\nreturn nil, err\n@@ -125,11 +123,11 @@ func newController(fd int, k *kernel.Kernel, w *watchdog.Watchdog) (*controller,\nmanager := &containerManager{\nstartChan: make(chan struct{}),\nstartResultChan: make(chan error),\n- loaderCreatedChan: make(chan struct{}),\n+ l: l,\n}\nsrv.Register(manager)\n- if eps, ok := k.NetworkStack().(*epsocket.Stack); ok {\n+ if eps, ok := l.k.NetworkStack().(*epsocket.Stack); ok {\nnet := &Network{\nStack: eps.Stack,\n}\n@@ -138,10 +136,6 @@ func newController(fd int, k *kernel.Kernel, w *watchdog.Watchdog) (*controller,\nsrv.Register(&debug{})\n- if err := srv.StartServing(); err != nil {\n- return nil, err\n- }\n-\nreturn &controller{\nsrv: srv,\nmanager: manager,\n@@ -161,11 +155,6 @@ type containerManager struct {\n// l is the loader that creates containers and sandboxes.\nl *Loader\n-\n- // loaderCreatedChan is used to signal when the loader has been created.\n- // After a loader is created, a notify method is called that writes to\n- // this channel.\n- loaderCreatedChan chan struct{}\n}\n// StartRoot will start the root container process.\n@@ -291,13 +280,6 @@ func (cm *containerManager) Pause(_, _ *struct{}) error {\nreturn nil\n}\n-// WaitForLoader blocks until the container's loader has been created.\n-func (cm *containerManager) WaitForLoader(_, _ *struct{}) error {\n- log.Debugf(\"containerManager.WaitForLoader\")\n- <-cm.loaderCreatedChan\n- return nil\n-}\n-\n// RestoreOpts contains options related to restoring a container's file system.\ntype RestoreOpts struct {\n// FilePayload contains the state file to be restored, followed by the\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/loader.go",
"new_path": "runsc/boot/loader.go",
"diff": "@@ -277,20 +277,6 @@ func New(args Args) (*Loader, error) {\n// Create a watchdog.\nwatchdog := watchdog.New(k, watchdog.DefaultTimeout, args.Conf.WatchdogAction)\n- // Create the control server using the provided FD.\n- //\n- // This must be done *after* we have initialized the kernel since the\n- // controller is used to configure the kernel's network stack.\n- //\n- // This should also be *before* we create the process, since a\n- // misconfigured process will cause an error, and we want the control\n- // server up before that so that we don't time out trying to connect to\n- // it.\n- ctrl, err := newController(args.ControllerFD, k, watchdog)\n- if err != nil {\n- return nil, fmt.Errorf(\"error creating control server: %v\", err)\n- }\n-\nprocArgs, err := newProcess(args.ID, args.Spec, creds, k)\nif err != nil {\nreturn nil, fmt.Errorf(\"failed to create init process for root container: %v\", err)\n@@ -303,7 +289,6 @@ func New(args Args) (*Loader, error) {\neid := execID{cid: args.ID}\nl := &Loader{\nk: k,\n- ctrl: ctrl,\nconf: args.Conf,\nconsole: args.Console,\nwatchdog: watchdog,\n@@ -348,7 +333,22 @@ func New(args Args) (*Loader, error) {\n}\n})\n- ctrl.manager.l = l\n+ // Create the control server using the provided FD.\n+ //\n+ // This must be done *after* we have initialized the kernel since the\n+ // controller is used to configure the kernel's network stack.\n+ ctrl, err := newController(args.ControllerFD, l)\n+ if err != nil {\n+ return nil, fmt.Errorf(\"creating control server: %v\", err)\n+ }\n+ l.ctrl = ctrl\n+\n+ // Only start serving after Loader is set to controller and controller is set\n+ // to Loader, because they are both used in the urpc methods.\n+ if err := ctrl.srv.StartServing(); err != nil {\n+ return nil, fmt.Errorf(\"starting control server: %v\", err)\n+ }\n+\nreturn l, nil\n}\n@@ -745,12 +745,6 @@ func (l *Loader) WaitForStartSignal() {\n<-l.ctrl.manager.startChan\n}\n-// NotifyLoaderCreated sends a signal to the container manager that this\n-// loader has been created.\n-func (l *Loader) NotifyLoaderCreated() {\n- l.ctrl.manager.loaderCreatedChan <- struct{}{}\n-}\n-\n// WaitExit waits for the root container to exit, and returns its exit status.\nfunc (l *Loader) WaitExit() kernel.ExitStatus {\n// Wait for container.\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/cgroup/cgroup.go",
"new_path": "runsc/cgroup/cgroup.go",
"diff": "@@ -241,6 +241,11 @@ func (c *Cgroup) Uninstall() error {\nreturn nil\n}\n+// Join adds the current process to the all controllers.\n+func (c *Cgroup) Join() error {\n+ return c.Add(0)\n+}\n+\n// Add adds given process to all controllers.\nfunc (c *Cgroup) Add(pid int) error {\nfor key := range controllers {\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/cmd/boot.go",
"new_path": "runsc/cmd/boot.go",
"diff": "@@ -159,14 +159,6 @@ func (b *Boot) Execute(_ context.Context, f *flag.FlagSet, args ...interface{})\npanic(\"setCapsAndCallSelf must never return success\")\n}\n- // Wait until this process has been moved into cgroups.\n- startSyncFile := os.NewFile(uintptr(b.startSyncFD), \"start-sync file\")\n- defer startSyncFile.Close()\n- buf := make([]byte, 1)\n- if r, err := startSyncFile.Read(buf); err != nil || r != 1 {\n- Fatalf(\"Unable to read from the start-sync descriptor: %v\", err)\n- }\n-\n// Create the loader.\nbootArgs := boot.Args{\nID: f.Arg(0),\n@@ -186,21 +178,20 @@ func (b *Boot) Execute(_ context.Context, f *flag.FlagSet, args ...interface{})\nFatalf(\"error creating loader: %v\", err)\n}\n- // Fatalf exits the process and doesn't run defers. 'l' must be destroyed\n- // explicitly!\n+ // Fatalf exits the process and doesn't run defers.\n+ // 'l' must be destroyed explicitly after this point!\n- // Notify the parent process the controller has been created.\n+ // Notify the parent process the sandbox has booted (and that the controller\n+ // is up).\n+ startSyncFile := os.NewFile(uintptr(b.startSyncFD), \"start-sync file\")\n+ buf := make([]byte, 1)\nif w, err := startSyncFile.Write(buf); err != nil || w != 1 {\nl.Destroy()\nFatalf(\"Unable to write into the start-sync descriptor: %v\", err)\n}\n- // startSyncFile is closed here to be sure that starting with this point\n- // the runsc process will not write anything into it.\n+ // Closes startSyncFile because 'l.Run()' only returns when the sandbox exits.\nstartSyncFile.Close()\n- // Notify other processes the loader has been created.\n- l.NotifyLoaderCreated()\n-\n// Wait for the start signal from runsc.\nl.WaitForStartSignal()\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/sandbox/sandbox.go",
"new_path": "runsc/sandbox/sandbox.go",
"diff": "@@ -65,7 +65,8 @@ type Sandbox struct {\n}\n// Create creates the sandbox process. The caller must call Destroy() on the\n-// sandbox.\n+// sandbox. If spec specified a cgroup, the current process will have joined\n+// the cgroup upon return.\nfunc Create(id string, spec *specs.Spec, conf *boot.Config, bundleDir, consoleSocket, userLog string, ioFiles []*os.File) (*Sandbox, error) {\ns := &Sandbox{ID: id}\n// The Cleanup object cleans up partially created sandboxes when an error occurs.\n@@ -78,55 +79,41 @@ func Create(id string, spec *specs.Spec, conf *boot.Config, bundleDir, consoleSo\n// If there is cgroup config, install it before creating sandbox process.\nif err := s.Cgroup.Install(spec.Linux.Resources); err != nil {\n- return nil, fmt.Errorf(\"error configuring cgroup: %v\", err)\n+ return nil, fmt.Errorf(\"configuring cgroup: %v\", err)\n+ }\n+\n+ // Make this process join the cgroup to ensure the sandbox (and all its\n+ // children processes) are part of the cgroup from the start. Don't bother\n+ // moving out because the caller is about to exit anyways.\n+ if err := cg.Join(); err != nil {\n+ return nil, fmt.Errorf(\"joining cgroup: %v\", err)\n}\n}\n- // Create a socket pair to synchronize runsc and sandbox processes.\n- // It is used for the following:\n- // * to notify the sandbox process when it has been moved into cgroups.\n- // * to wait for the controller socket.\n- fds, err := syscall.Socketpair(syscall.AF_UNIX, syscall.SOCK_SEQPACKET, 0)\n- if err != nil {\n- return nil, fmt.Errorf(\"error creating a start-sync socket pair %q: %v\", s.ID, err)\n+ // Create pipe to synchronize when sandbox process has been booted.\n+ fds := make([]int, 2)\n+ if err := syscall.Pipe(fds); err != nil {\n+ return nil, fmt.Errorf(\"creating pipe for sandbox %q: %v\", s.ID, err)\n}\n- startSyncFile := os.NewFile(uintptr(fds[0]), \"start-sync socket\")\n- defer startSyncFile.Close()\n+ clientSyncFile := os.NewFile(uintptr(fds[0]), \"client sandbox sync\")\n+ defer clientSyncFile.Close()\n- sandboxSyncFile := os.NewFile(uintptr(fds[1]), \"sandbox start-sync socket\")\n+ sandboxSyncFile := os.NewFile(uintptr(fds[1]), \"sandbox sync\")\n// Create the sandbox process.\n- err = s.createSandboxProcess(spec, conf, bundleDir, consoleSocket, userLog, ioFiles, sandboxSyncFile)\n- // sandboxSyncFile has to be closed to be able to detect\n- // when the sandbox process exits unexpectedly.\n+ err := s.createSandboxProcess(spec, conf, bundleDir, consoleSocket, userLog, ioFiles, sandboxSyncFile)\n+ // sandboxSyncFile has to be closed to be able to detect when the sandbox\n+ // process exits unexpectedly.\nsandboxSyncFile.Close()\nif err != nil {\nreturn nil, err\n}\n- if s.Cgroup != nil {\n- if err := s.Cgroup.Add(s.Pid); err != nil {\n- return nil, fmt.Errorf(\"error adding sandbox to cgroup: %v\", err)\n- }\n- }\n-\n+ // Wait until the sandbox has booted.\nb := make([]byte, 1)\n- // Notify the sandbox process it has been moved into cgroups.\n- if l, err := startSyncFile.Write(b); err != nil || l != 1 {\n- return nil, fmt.Errorf(\"error writing into the start-sync descriptor: %v\", err)\n- }\n- // Wait until the sandbox process has initialized the controller socket.\n- if l, err := startSyncFile.Read(b); err != nil || l != 1 {\n+ if l, err := clientSyncFile.Read(b); err != nil || l != 1 {\nreturn nil, fmt.Errorf(\"error reading from the start-sync descriptor: %v\", err)\n}\n- // startSyncFile is closed here to be sure that starting with this point\n- // the sandbox process will not write anything into it.\n- startSyncFile.Close()\n-\n- // Wait for the control server to come up.\n- if err := s.waitForCreated(); err != nil {\n- return nil, err\n- }\nc.Release()\nreturn s, nil\n@@ -612,23 +599,6 @@ func (s *Sandbox) createSandboxProcess(spec *specs.Spec, conf *boot.Config, bund\nreturn nil\n}\n-// waitForCreated waits for the sandbox subprocess control server to be\n-// running and for the loader to have been created, at which point the sandbox\n-// is in Created state.\n-func (s *Sandbox) waitForCreated() error {\n- log.Debugf(\"Waiting for sandbox %q creation\", s.ID)\n- conn, err := s.sandboxConnect()\n- if err != nil {\n- return err\n- }\n- defer conn.Close()\n-\n- if err := conn.Call(boot.ContainerWaitForLoader, nil, nil); err != nil {\n- return fmt.Errorf(\"err waiting on loader on sandbox %q, err: %v\", s.ID, err)\n- }\n- return nil\n-}\n-\n// Wait waits for the containerized process to exit, and returns its WaitStatus.\nfunc (s *Sandbox) Wait(cid string) (syscall.WaitStatus, error) {\nlog.Debugf(\"Waiting for container %q in sandbox %q\", cid, s.ID)\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/test/root/cgroup_test.go",
"new_path": "runsc/test/root/cgroup_test.go",
"diff": "@@ -18,6 +18,7 @@ import (\n\"io/ioutil\"\n\"os\"\n\"path/filepath\"\n+ \"strconv\"\n\"strings\"\n\"testing\"\n@@ -123,6 +124,8 @@ func TestCgroup(t *testing.T) {\nt.Fatalf(\"Docker.ID() failed: %v\", err)\n}\nt.Logf(\"cgroup ID: %s\", gid)\n+\n+ // Check list of attributes defined above.\nfor _, attr := range attrs {\npath := filepath.Join(\"/sys/fs/cgroup\", attr.ctrl, \"docker\", gid, attr.file)\nout, err := ioutil.ReadFile(path)\n@@ -137,4 +140,33 @@ func TestCgroup(t *testing.T) {\nt.Errorf(\"arg: %q, cgroup attribute %s/%s, got: %q, want: %q\", attr.arg, attr.ctrl, attr.file, got, attr.want)\n}\n}\n+\n+ // Check that sandbox is inside cgroup.\n+ controllers := []string{\n+ \"blkio\",\n+ \"cpu\",\n+ \"cpuset\",\n+ \"memory\",\n+ \"net_cls\",\n+ \"net_prio\",\n+ \"devices\",\n+ \"freezer\",\n+ \"perf_event\",\n+ \"pids\",\n+ \"systemd\",\n+ }\n+ pid, err := d.SandboxPid()\n+ if err != nil {\n+ t.Fatalf(\"SandboxPid: %v\", err)\n+ }\n+ for _, ctrl := range controllers {\n+ path := filepath.Join(\"/sys/fs/cgroup\", ctrl, \"docker\", gid, \"cgroup.procs\")\n+ out, err := ioutil.ReadFile(path)\n+ if err != nil {\n+ t.Fatalf(\"failed to read %q: %v\", path, err)\n+ }\n+ if got := string(out); !strings.Contains(got, strconv.Itoa(pid)) {\n+ t.Errorf(\"cgroup control %s processes, got: %q, want: %q\", ctrl, got, pid)\n+ }\n+ }\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Simplify synchronization between runsc and sandbox process
Make 'runsc create' join cgroup before creating sandbox process.
This removes the need to synchronize platform creation and ensure
that sandbox process is charged to the right cgroup from the start.
PiperOrigin-RevId: 227166451
Change-Id: Ieb4b18e6ca0daf7b331dc897699ca419bc5ee3a2 |
259,992 | 02.01.2019 11:38:51 | 28,800 | 8e586db16274c2563fb13c95bafa9e20ea3d73ce | Add /proc/net/psched content
FIO reads this file and expects it to be well formed. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/proc/net.go",
"new_path": "pkg/sentry/fs/proc/net.go",
"diff": "@@ -16,6 +16,7 @@ package proc\nimport (\n\"fmt\"\n+ \"time\"\n\"gvisor.googlesource.com/gvisor/pkg/abi/linux\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/context\"\n@@ -42,7 +43,12 @@ func (p *proc) newNetDir(ctx context.Context, msrc *fs.MountSource) *fs.Inode {\nd.AddChild(ctx, \"netstat\", p.newStubProcFSFile(ctx, msrc, []byte(\"TcpExt: SyncookiesSent SyncookiesRecv SyncookiesFailed EmbryonicRsts PruneCalled RcvPruned OfoPruned OutOfWindowIcmps LockDroppedIcmps ArpFilter TW TWRecycled TWKilled PAWSPassive PAWSActive PAWSEstab DelayedACKs DelayedACKLocked DelayedACKLost ListenOverflows ListenDrops TCPPrequeued TCPDirectCopyFromBacklog TCPDirectCopyFromPrequeue TCPPrequeueDropped TCPHPHits TCPHPHitsToUser TCPPureAcks TCPHPAcks TCPRenoRecovery TCPSackRecovery TCPSACKReneging TCPFACKReorder TCPSACKReorder TCPRenoReorder TCPTSReorder TCPFullUndo TCPPartialUndo TCPDSACKUndo TCPLossUndo TCPLostRetransmit TCPRenoFailures TCPSackFailures TCPLossFailures TCPFastRetrans TCPForwardRetrans TCPSlowStartRetrans TCPTimeouts TCPLossProbes TCPLossProbeRecovery TCPRenoRecoveryFail TCPSackRecoveryFail TCPSchedulerFailed TCPRcvCollapsed TCPDSACKOldSent TCPDSACKOfoSent TCPDSACKRecv TCPDSACKOfoRecv TCPAbortOnData TCPAbortOnClose TCPAbortOnMemory TCPAbortOnTimeout TCPAbortOnLinger TCPAbortFailed TCPMemoryPressures TCPSACKDiscard TCPDSACKIgnoredOld TCPDSACKIgnoredNoUndo TCPSpuriousRTOs TCPMD5NotFound TCPMD5Unexpected TCPMD5Failure TCPSackShifted TCPSackMerged TCPSackShiftFallback TCPBacklogDrop TCPMinTTLDrop TCPDeferAcceptDrop IPReversePathFilter TCPTimeWaitOverflow TCPReqQFullDoCookies TCPReqQFullDrop TCPRetransFail TCPRcvCoalesce TCPOFOQueue TCPOFODrop TCPOFOMerge TCPChallengeACK TCPSYNChallenge TCPFastOpenActive TCPFastOpenActiveFail TCPFastOpenPassive TCPFastOpenPassiveFail TCPFastOpenListenOverflow TCPFastOpenCookieReqd TCPSpuriousRtxHostQueues BusyPollRxPackets TCPAutoCorking TCPFromZeroWindowAdv TCPToZeroWindowAdv TCPWantZeroWindowAdv TCPSynRetrans TCPOrigDataSent TCPHystartTrainDetect TCPHystartTrainCwnd TCPHystartDelayDetect TCPHystartDelayCwnd TCPACKSkippedSynRecv TCPACKSkippedPAWS TCPACKSkippedSeq TCPACKSkippedFinWait2 TCPACKSkippedTimeWait TCPACKSkippedChallenge TCPWinProbe TCPKeepAlive TCPMTUPFail TCPMTUPSuccess\")))\nd.AddChild(ctx, \"packet\", p.newStubProcFSFile(ctx, msrc, []byte(\"sk RefCnt Type Proto Iface R Rmem User Inode\")))\nd.AddChild(ctx, \"protocols\", p.newStubProcFSFile(ctx, msrc, []byte(\"protocol size sockets memory press maxhdr slab module cl co di ac io in de sh ss gs se re sp bi br ha uh gp em\")))\n- d.AddChild(ctx, \"psched\", p.newStubProcFSFile(ctx, msrc, []byte(\"\")))\n+\n+ // Linux sets these values to: nsec per usec, psched tick in ns, 1000000,\n+ // high res timer ticks per sec (ClockGetres returns 1ns resolution).\n+ psched := fmt.Sprintf(\"%08x %08x %08x %08x\\n\", uint64(time.Microsecond/time.Nanosecond), 64, 1000000, uint64(time.Second/time.Nanosecond))\n+ d.AddChild(ctx, \"psched\", p.newStubProcFSFile(ctx, msrc, []byte(psched)))\n+\nd.AddChild(ctx, \"ptype\", p.newStubProcFSFile(ctx, msrc, []byte(\"Type Device Function\")))\nd.AddChild(ctx, \"route\", p.newStubProcFSFile(ctx, msrc, []byte(\"Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT\")))\nd.AddChild(ctx, \"tcp\", p.newStubProcFSFile(ctx, msrc, []byte(\" sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode\")))\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add /proc/net/psched content
FIO reads this file and expects it to be well formed.
PiperOrigin-RevId: 227554483
Change-Id: Ia48ae2377626dd6a2daf17b5b4f5119f90ece55b |
260,013 | 03.01.2019 13:22:12 | 28,800 | d89836fe51eeef4920439d6d2433f2ee6f37aec9 | Add test for reopening socketpair end via procfs. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_unix.cc",
"new_path": "test/syscalls/linux/socket_unix.cc",
"diff": "#include \"test/syscalls/linux/socket_unix.h\"\n+#include <errno.h>\n#include <net/if.h>\n#include <stdio.h>\n#include <sys/ioctl.h>\n@@ -1175,6 +1176,17 @@ TEST_P(UnixSocketPairTest, SocketShutdown) {\nEXPECT_EQ(data, absl::string_view(buf, 3));\n}\n+// TODO: We should be returning ENXIO and NOT EIO.\n+TEST_P(UnixSocketPairTest, DISABLED_SocketReopenFromProcfs) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ // Opening a socket pair via /proc/self/fd/X is a ENXIO.\n+ for (const int fd : {sockets->first_fd(), sockets->second_fd()}) {\n+ ASSERT_THAT(Open(absl::StrCat(\"/proc/self/fd/\", fd), O_WRONLY),\n+ PosixErrorIs(ENXIO, ::testing::_));\n+ }\n+}\n+\n} // namespace\n} // namespace testing\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add test for reopening socketpair end via procfs.
PiperOrigin-RevId: 227738801
Change-Id: Ic0c5d10c3b1f21b3f85ff9a661a55db77fab77b0 |
259,854 | 03.01.2019 13:52:30 | 28,800 | b709997d78a9504d1d9a14eb2dffae327cd69238 | Rename linux.Errno.Error to linux.Errno.String.
Using linux.Errno as an error doesn't work very well as none of the sentry code
expects error to contain a linux.Errno.
This moves using syserr.Error.ToLinux as an error in a syscall handler from a
runtime error to a compile error. | [
{
"change_type": "MODIFY",
"old_path": "pkg/abi/linux/errors.go",
"new_path": "pkg/abi/linux/errors.go",
"diff": "@@ -25,8 +25,8 @@ func (e *Errno) Number() int {\nreturn e.number\n}\n-// Error implements error.Error.\n-func (e *Errno) Error() string {\n+// String implements fmt.Stringer.String.\n+func (e *Errno) String() string {\nreturn e.name\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Rename linux.Errno.Error to linux.Errno.String.
Using linux.Errno as an error doesn't work very well as none of the sentry code
expects error to contain a linux.Errno.
This moves using syserr.Error.ToLinux as an error in a syscall handler from a
runtime error to a compile error.
PiperOrigin-RevId: 227744312
Change-Id: Iea63108a5b198296c908614e09c01733dd684da0 |
259,992 | 03.01.2019 14:09:47 | 28,800 | d033a76fa6e215cb302e5383dbd7b0120de4395d | Apply chroot for --network=host too | [
{
"change_type": "MODIFY",
"old_path": "runsc/sandbox/sandbox.go",
"new_path": "runsc/sandbox/sandbox.go",
"diff": "@@ -529,11 +529,13 @@ func (s *Sandbox) createSandboxProcess(spec *specs.Spec, conf *boot.Config, bund\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+ }\n// If we have CAP_SYS_ADMIN, we can create an empty chroot and\n// bind-mount the executable inside it.\nif conf.TestOnlyAllowRunAsCurrentUserWithoutChroot {\nlog.Warningf(\"Running sandbox in test mode without chroot. This is only safe in tests!\")\n+\n} else if specutils.HasCapabilities(capability.CAP_SYS_ADMIN, capability.CAP_SYS_CHROOT) {\nlog.Infof(\"Sandbox will be started in minimal chroot\")\nchroot, err := setUpChroot()\n@@ -545,10 +547,10 @@ func (s *Sandbox) createSandboxProcess(spec *specs.Spec, conf *boot.Config, bund\ncmd.Dir = \"/\"\ncmd.Args[0] = \"/runsc\"\ncmd.Path = \"/runsc\"\n+\n} else {\nreturn fmt.Errorf(\"can't run sandbox process in minimal chroot since we don't have CAP_SYS_ADMIN and CAP_SYS_CHROOT\")\n}\n- }\nif s.Cgroup != nil {\ncpuNum, err := s.Cgroup.NumCPU()\n"
}
] | Go | Apache License 2.0 | google/gvisor | Apply chroot for --network=host too
PiperOrigin-RevId: 227747566
Change-Id: Ide9df4ac1391adcd1c56e08d6570e0d149d85bc4 |
259,854 | 03.01.2019 15:09:31 | 28,800 | 4a4cc7dc3794535f3d65736cde4293ecf0e565e0 | Allow creating syserr.Errors at runtime.
Not allowing this was an oversight. | [
{
"change_type": "MODIFY",
"old_path": "pkg/syserr/syserr.go",
"new_path": "pkg/syserr/syserr.go",
"diff": "@@ -68,8 +68,21 @@ func New(message string, linuxTranslation *linux.Errno) *Error {\nreturn err\n}\n+// NewDynamic creates a new error with a dynamic error message and an errno\n+// translation.\n+//\n+// NewDynamic should only be used sparingly and not be used for static error\n+// messages. Errors with static error messages should be declared with New as\n+// global variables.\n+func NewDynamic(message string, linuxTranslation *linux.Errno) *Error {\n+ return &Error{message: message, errno: linuxTranslation}\n+}\n+\n// NewWithoutTranslation creates a new Error. If translation is attempted on\n// the error, translation will fail.\n+//\n+// NewWithoutTranslation may be called at any time, but static errors should\n+// be declared as global variables and dynamic errors should be used sparingly.\nfunc NewWithoutTranslation(message string) *Error {\nreturn &Error{message: message, noTranslation: true}\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Allow creating syserr.Errors at runtime.
Not allowing this was an oversight.
PiperOrigin-RevId: 227757813
Change-Id: I845800ab69028b7320afca36d832c477ff17c5ce |
259,885 | 07.01.2019 15:04:00 | 28,800 | e44cb43b9c2292239c33fb77ddd6510ef52e1a7a | Default syscall_test shard_count to 5. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/build_defs.bzl",
"new_path": "test/syscalls/build_defs.bzl",
"diff": "# syscall_test is a macro that will create targets to run the given test target\n# on the host (native) and runsc.\n-def syscall_test(test, shard_count = 1, size = \"small\"):\n+def syscall_test(test, shard_count = 5, size = \"small\"):\n_syscall_test(test, shard_count, size, \"native\")\n_syscall_test(test, shard_count, size, \"kvm\")\n_syscall_test(test, shard_count, size, \"ptrace\")\n"
}
] | Go | Apache License 2.0 | google/gvisor | Default syscall_test shard_count to 5.
PiperOrigin-RevId: 228243120
Change-Id: I2726d580f4f9fad0ecc6a912e0e576ed9e08ce72 |
259,885 | 07.01.2019 15:39:14 | 28,800 | dc4849e49c354ee43256a4a117a217f86767a059 | Add usermem support for arm64 platform. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/usermem/BUILD",
"new_path": "pkg/sentry/usermem/BUILD",
"diff": "@@ -24,6 +24,7 @@ go_library(\n\"bytes_io.go\",\n\"bytes_io_unsafe.go\",\n\"usermem.go\",\n+ \"usermem_arm64.go\",\n\"usermem_x86.go\",\n],\nimportpath = \"gvisor.googlesource.com/gvisor/pkg/sentry/usermem\",\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/usermem/usermem_arm64.go",
"diff": "+// Copyright 2019 Google LLC\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 usermem\n+\n+import (\n+ \"encoding/binary\"\n+ \"syscall\"\n+)\n+\n+const (\n+ // PageSize is the system page size.\n+ // arm64 support 4K/16K/64K page size,\n+ // which can be get by syscall.Getpagesize().\n+ // Currently, only 4K page size is supported.\n+ PageSize = 1 << PageShift\n+\n+ // HugePageSize is the system huge page size.\n+ HugePageSize = 1 << HugePageShift\n+\n+ // PageShift is the binary log of the system page size.\n+ PageShift = 12\n+\n+ // HugePageShift is the binary log of the system huge page size.\n+ // Should be calculated by \"PageShift + (PageShift - 3)\"\n+ // when multiple page size support is ready.\n+ HugePageShift = 21\n+)\n+\n+var (\n+ // ByteOrder is the native byte order (little endian).\n+ ByteOrder = binary.LittleEndian\n+)\n+\n+func init() {\n+ // Make sure the page size is 4K on arm64 platform.\n+ if size := syscall.Getpagesize(); size != PageSize {\n+ panic(\"Only 4K page size is supported on arm64!\")\n+ }\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add usermem support for arm64 platform.
Signed-off-by: Haibo Xu <[email protected]>
PiperOrigin-RevId: 228249611
Change-Id: I1046e70bec4274f18b9948eefd6b0d546e4c48bb |
259,992 | 07.01.2019 23:01:10 | 28,800 | 5ce542ecc749cb9a1e8d216c7181aeaebfbc3110 | Undo changes in case of failure to create file/dir/symlink
File/dir/symlink creation is multi-step and may leave state behind in
case of failure in one of the steps. Added best effort attempt to
clean up. | [
{
"change_type": "MODIFY",
"old_path": "runsc/fsgofer/BUILD",
"new_path": "runsc/fsgofer/BUILD",
"diff": "@@ -18,6 +18,7 @@ go_library(\n\"//pkg/log\",\n\"//pkg/p9\",\n\"//pkg/syserr\",\n+ \"//runsc/specutils\",\n\"@org_golang_x_sys//unix:go_default_library\",\n],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/fsgofer/fsgofer.go",
"new_path": "runsc/fsgofer/fsgofer.go",
"diff": "@@ -35,6 +35,7 @@ import (\n\"gvisor.googlesource.com/gvisor/pkg/fd\"\n\"gvisor.googlesource.com/gvisor/pkg/log\"\n\"gvisor.googlesource.com/gvisor/pkg/p9\"\n+ \"gvisor.googlesource.com/gvisor/runsc/specutils\"\n)\nconst (\n@@ -379,19 +380,20 @@ func (l *localFile) Create(name string, mode p9.OpenFlags, perm p9.FileMode, uid\nif err != nil {\nreturn nil, nil, p9.QID{}, 0, extractErrno(err)\n}\n- if err := fchown(fd, uid, gid); err != nil {\n+ cu := specutils.MakeCleanup(func() {\nsyscall.Close(fd)\n- if e := syscall.Unlinkat(l.controlFD(), name); e != nil {\n- log.Warningf(\"error unlinking file %q after failed chown: %v\", name, e)\n+ // Best effort attempt to remove the file in case of failure.\n+ if err := syscall.Unlinkat(l.controlFD(), name); err != nil {\n+ log.Warningf(\"error unlinking file %q after failure: %v\", path.Join(l.hostPath, name), err)\n}\n+ })\n+ defer cu.Clean()\n+\n+ if err := fchown(fd, uid, gid); err != nil {\nreturn nil, nil, p9.QID{}, 0, extractErrno(err)\n}\nstat, err := stat(fd)\nif err != nil {\n- syscall.Close(fd)\n- if e := syscall.Unlinkat(l.controlFD(), name); e != nil {\n- log.Warningf(\"error unlinking file %q after failed stat: %v\", name, e)\n- }\nreturn nil, nil, p9.QID{}, 0, extractErrno(err)\n}\n@@ -404,6 +406,8 @@ func (l *localFile) Create(name string, mode p9.OpenFlags, perm p9.FileMode, uid\nopenedFile: f,\nmode: mode,\n}\n+\n+ cu.Release()\nreturn newFDMaybe(c.openedFile), c, l.attachPoint.makeQID(stat), 0, nil\n}\n@@ -420,6 +424,13 @@ func (l *localFile) Mkdir(name string, perm p9.FileMode, uid p9.UID, gid p9.GID)\nif err := syscall.Mkdirat(l.controlFD(), name, uint32(perm.Permissions())); err != nil {\nreturn p9.QID{}, extractErrno(err)\n}\n+ cu := specutils.MakeCleanup(func() {\n+ // Best effort attempt to remove the dir in case of failure.\n+ if err := unix.Unlinkat(l.controlFD(), name, unix.AT_REMOVEDIR); err != nil {\n+ log.Warningf(\"error unlinking dir %q after failure: %v\", path.Join(l.hostPath, name), err)\n+ }\n+ })\n+ defer cu.Clean()\n// Open directory to change ownership and stat it.\nflags := syscall.O_DIRECTORY | syscall.O_RDONLY | openFlags\n@@ -436,6 +447,8 @@ func (l *localFile) Mkdir(name string, perm p9.FileMode, uid p9.UID, gid p9.GID)\nif err != nil {\nreturn p9.QID{}, extractErrno(err)\n}\n+\n+ cu.Release()\nreturn l.attachPoint.makeQID(stat), nil\n}\n@@ -759,6 +772,13 @@ func (l *localFile) Symlink(target, newName string, uid p9.UID, gid p9.GID) (p9.\nif err := unix.Symlinkat(target, l.controlFD(), newName); err != nil {\nreturn p9.QID{}, extractErrno(err)\n}\n+ cu := specutils.MakeCleanup(func() {\n+ // Best effort attempt to remove the symlink in case of failure.\n+ if err := syscall.Unlinkat(l.controlFD(), newName); err != nil {\n+ log.Warningf(\"error unlinking file %q after failure: %v\", path.Join(l.hostPath, newName), err)\n+ }\n+ })\n+ defer cu.Clean()\n// Open symlink to change ownership and stat it.\nfd, err := syscall.Openat(l.controlFD(), newName, unix.O_PATH|openFlags, 0)\n@@ -774,6 +794,8 @@ func (l *localFile) Symlink(target, newName string, uid p9.UID, gid p9.GID) (p9.\nif err != nil {\nreturn p9.QID{}, extractErrno(err)\n}\n+\n+ cu.Release()\nreturn l.attachPoint.makeQID(stat), nil\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Undo changes in case of failure to create file/dir/symlink
File/dir/symlink creation is multi-step and may leave state behind in
case of failure in one of the steps. Added best effort attempt to
clean up.
PiperOrigin-RevId: 228286612
Change-Id: Ib03c27cd3d3e4f44d0352edc6ee212a53412d7f1 |
259,942 | 08.01.2019 12:34:08 | 28,800 | 3f45878b7323697c82e06649144e2a4f39018a12 | Implement Stringer for tcpip.StatCounter
This enables formatting tcpip.Stats readably with %+v. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/tcpip.go",
"new_path": "pkg/tcpip/tcpip.go",
"diff": "@@ -568,6 +568,10 @@ func (s *StatCounter) IncrementBy(v uint64) {\natomic.AddUint64(&s.count, v)\n}\n+func (s *StatCounter) String() string {\n+ return strconv.FormatUint(s.Value(), 10)\n+}\n+\n// IPStats collects IP-specific stats (both v4 and v6).\ntype IPStats struct {\n// PacketsReceived is the total number of IP packets received from the link\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/tcpip_test.go",
"new_path": "pkg/tcpip/tcpip_test.go",
"diff": "package tcpip\nimport (\n+ \"fmt\"\n\"net\"\n+ \"strings\"\n\"testing\"\n)\n@@ -193,3 +195,23 @@ func TestAddressString(t *testing.T) {\n}\n}\n}\n+\n+func TestStatsString(t *testing.T) {\n+ got := fmt.Sprintf(\"%+v\", Stats{}.FillIn())\n+\n+ matchers := []string{\n+ // Print root-level stats correctly.\n+ \"UnknownProtocolRcvdPackets:0\",\n+ // Print protocol-specific stats correctly.\n+ \"TCP:{ActiveConnectionOpenings:0\",\n+ }\n+\n+ for _, m := range matchers {\n+ if !strings.Contains(got, m) {\n+ t.Errorf(\"string.Contains(got, %q) = false\", m)\n+ }\n+ }\n+ if t.Failed() {\n+ t.Logf(`got = fmt.Sprintf(\"%%+v\", Stats{}.FillIn()) = %q`, got)\n+ }\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Implement Stringer for tcpip.StatCounter
This enables formatting tcpip.Stats readably with %+v.
PiperOrigin-RevId: 228379088
Change-Id: I6a9876454a22f151ee752cf94589b4188729458f |
259,885 | 08.01.2019 12:51:04 | 28,800 | f95b94fbe3e557b16ed2b78c87e8936c0aeab6c5 | Grant no initial capabilities to non-root UIDs.
See modified comment in auth.NewUserCredentials(); compare to the
behavior of setresuid(2) as implemented by
//pkg/sentry/kernel/task_identity.go:kernel.Task.setKUIDsUncheckedLocked(). | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/auth/credentials.go",
"new_path": "pkg/sentry/kernel/auth/credentials.go",
"diff": "@@ -119,19 +119,24 @@ func NewUserCredentials(kuid KUID, kgid KGID, extraKGIDs []KGID, capabilities *T\n// Set additional GIDs.\ncreds.ExtraKGIDs = append(creds.ExtraKGIDs, extraKGIDs...)\n- // Set capabilities. If capabilities aren't specified, we default to\n- // all capabilities.\n+ // Set capabilities.\nif capabilities != nil {\ncreds.PermittedCaps = capabilities.PermittedCaps\ncreds.EffectiveCaps = capabilities.EffectiveCaps\ncreds.BoundingCaps = capabilities.BoundingCaps\ncreds.InheritableCaps = capabilities.InheritableCaps\n- // // TODO: Support ambient capabilities.\n+ // TODO: Support ambient capabilities.\n} else {\n- // If no capabilities are specified, grant the same capabilities\n- // that NewRootCredentials does.\n+ // If no capabilities are specified, grant capabilities consistent with\n+ // setresuid + setresgid from NewRootCredentials to the given uid and\n+ // gid.\n+ if kuid == RootKUID {\ncreds.PermittedCaps = AllCapabilities\ncreds.EffectiveCaps = AllCapabilities\n+ } else {\n+ creds.PermittedCaps = 0\n+ creds.EffectiveCaps = 0\n+ }\ncreds.BoundingCaps = AllCapabilities\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Grant no initial capabilities to non-root UIDs.
See modified comment in auth.NewUserCredentials(); compare to the
behavior of setresuid(2) as implemented by
//pkg/sentry/kernel/task_identity.go:kernel.Task.setKUIDsUncheckedLocked().
PiperOrigin-RevId: 228381765
Change-Id: I45238777c8f63fcf41b99fce3969caaf682fe408 |
260,013 | 08.01.2019 12:56:59 | 28,800 | 3676b7ff1ca07e9fec1e380a0c2068390ce5d8de | Improve loader related error messages returned to users. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/BUILD",
"new_path": "pkg/sentry/kernel/BUILD",
"diff": "@@ -184,6 +184,7 @@ go_library(\n\"//pkg/state\",\n\"//pkg/state/statefile\",\n\"//pkg/sync\",\n+ \"//pkg/syserr\",\n\"//pkg/syserror\",\n\"//pkg/tcpip\",\n\"//pkg/tcpip/stack\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/kernel.go",
"new_path": "pkg/sentry/kernel/kernel.go",
"diff": "package kernel\nimport (\n+ \"errors\"\n\"fmt\"\n\"io\"\n\"path/filepath\"\n@@ -658,9 +659,9 @@ func (k *Kernel) CreateProcess(args CreateProcessArgs) (*ThreadGroup, ThreadID,\n// Create a fresh task context.\nremainingTraversals = uint(args.MaxSymlinkTraversals)\n- tc, err := k.LoadTaskImage(ctx, k.mounts, root, wd, &remainingTraversals, args.Filename, args.Argv, args.Envv, k.featureSet)\n- if err != nil {\n- return nil, 0, err\n+ tc, se := k.LoadTaskImage(ctx, k.mounts, root, wd, &remainingTraversals, args.Filename, args.Argv, args.Envv, k.featureSet)\n+ if se != nil {\n+ return nil, 0, errors.New(se.String())\n}\n// Take a reference on the FDMap, which will be transferred to\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/task_context.go",
"new_path": "pkg/sentry/kernel/task_context.go",
"diff": "package kernel\nimport (\n- \"errors\"\n\"fmt\"\n+ \"gvisor.googlesource.com/gvisor/pkg/abi/linux\"\n\"gvisor.googlesource.com/gvisor/pkg/cpuid\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/arch\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/context\"\n@@ -26,10 +26,10 @@ import (\n\"gvisor.googlesource.com/gvisor/pkg/sentry/loader\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/mm\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/usermem\"\n+ \"gvisor.googlesource.com/gvisor/pkg/syserr\"\n)\n-// ErrNoSyscalls is returned if there is no syscall table.\n-var ErrNoSyscalls = errors.New(\"no syscall table found\")\n+var errNoSyscalls = syserr.New(\"no syscall table found\", linux.ENOEXEC)\n// Auxmap contains miscellaneous data for the task.\ntype Auxmap map[string]interface{}\n@@ -142,7 +142,7 @@ func (t *Task) Stack() *arch.Stack {\n// * argv: Binary argv\n// * envv: Binary envv\n// * fs: Binary FeatureSet\n-func (k *Kernel) LoadTaskImage(ctx context.Context, mounts *fs.MountNamespace, root, wd *fs.Dirent, maxTraversals *uint, filename string, argv, envv []string, fs *cpuid.FeatureSet) (*TaskContext, error) {\n+func (k *Kernel) LoadTaskImage(ctx context.Context, mounts *fs.MountNamespace, root, wd *fs.Dirent, maxTraversals *uint, filename string, argv, envv []string, fs *cpuid.FeatureSet) (*TaskContext, *syserr.Error) {\n// Prepare a new user address space to load into.\nm := mm.NewMemoryManager(k)\ndefer m.DecUsers(ctx)\n@@ -155,8 +155,9 @@ func (k *Kernel) LoadTaskImage(ctx context.Context, mounts *fs.MountNamespace, r\n// Lookup our new syscall table.\nst, ok := LookupSyscallTable(os, ac.Arch())\nif !ok {\n- // No syscall table found. Yikes.\n- return nil, ErrNoSyscalls\n+ // No syscall table found. This means that the ELF binary does not match\n+ // the architecture.\n+ return nil, errNoSyscalls\n}\nif !m.IncUsers() {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/loader/BUILD",
"new_path": "pkg/sentry/loader/BUILD",
"diff": "@@ -44,6 +44,7 @@ go_library(\n\"//pkg/sentry/uniqueid\",\n\"//pkg/sentry/usage\",\n\"//pkg/sentry/usermem\",\n+ \"//pkg/syserr\",\n\"//pkg/syserror\",\n\"//pkg/waiter\",\n],\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/loader/loader.go",
"new_path": "pkg/sentry/loader/loader.go",
"diff": "@@ -17,6 +17,7 @@ package loader\nimport (\n\"bytes\"\n+ \"fmt\"\n\"io\"\n\"path\"\n@@ -30,6 +31,7 @@ import (\n\"gvisor.googlesource.com/gvisor/pkg/sentry/kernel/auth\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/mm\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/usermem\"\n+ \"gvisor.googlesource.com/gvisor/pkg/syserr\"\n\"gvisor.googlesource.com/gvisor/pkg/syserror\"\n)\n@@ -196,20 +198,18 @@ func loadPath(ctx context.Context, m *mm.MemoryManager, mounts *fs.MountNamespac\n// Preconditions:\n// * The Task MemoryManager is empty.\n// * Load is called on the Task goroutine.\n-func Load(ctx context.Context, m *mm.MemoryManager, mounts *fs.MountNamespace, root, wd *fs.Dirent, maxTraversals *uint, fs *cpuid.FeatureSet, filename string, argv, envv []string, extraAuxv []arch.AuxEntry, vdso *VDSO) (abi.OS, arch.Context, string, error) {\n+func Load(ctx context.Context, m *mm.MemoryManager, mounts *fs.MountNamespace, root, wd *fs.Dirent, maxTraversals *uint, fs *cpuid.FeatureSet, filename string, argv, envv []string, extraAuxv []arch.AuxEntry, vdso *VDSO) (abi.OS, arch.Context, string, *syserr.Error) {\n// Load the binary itself.\nloaded, ac, d, argv, err := loadPath(ctx, m, mounts, root, wd, maxTraversals, fs, filename, argv)\nif err != nil {\n- ctx.Infof(\"Failed to load %s: %v\", filename, err)\n- return 0, nil, \"\", err\n+ return 0, nil, \"\", syserr.NewDynamic(fmt.Sprintf(\"Failed to load %s: %v\", filename, err), syserr.FromError(err).ToLinux())\n}\ndefer d.DecRef()\n// Load the VDSO.\nvdsoAddr, err := loadVDSO(ctx, m, vdso, loaded)\nif err != nil {\n- ctx.Infof(\"Error loading VDSO: %v\", err)\n- return 0, nil, \"\", err\n+ return 0, nil, \"\", syserr.NewDynamic(fmt.Sprintf(\"Error loading VDSO: %v\", err), syserr.FromError(err).ToLinux())\n}\n// Setup the heap. brk starts at the next page after the end of the\n@@ -217,35 +217,30 @@ func Load(ctx context.Context, m *mm.MemoryManager, mounts *fs.MountNamespace, r\n// loaded.end is available for its use.\ne, ok := loaded.end.RoundUp()\nif !ok {\n- ctx.Warningf(\"brk overflows: %#x\", loaded.end)\n- return 0, nil, \"\", syserror.ENOEXEC\n+ return 0, nil, \"\", syserr.NewDynamic(fmt.Sprintf(\"brk overflows: %#x\", loaded.end), linux.ENOEXEC)\n}\nm.BrkSetup(ctx, e)\n// Allocate our stack.\nstack, err := allocStack(ctx, m, ac)\nif err != nil {\n- ctx.Infof(\"Failed to allocate stack: %v\", err)\n- return 0, nil, \"\", err\n+ return 0, nil, \"\", syserr.NewDynamic(fmt.Sprintf(\"Failed to allocate stack: %v\", err), syserr.FromError(err).ToLinux())\n}\n// Push the original filename to the stack, for AT_EXECFN.\nexecfn, err := stack.Push(filename)\nif err != nil {\n- ctx.Infof(\"Failed to push exec filename: %v\", err)\n- return 0, nil, \"\", err\n+ return 0, nil, \"\", syserr.NewDynamic(fmt.Sprintf(\"Failed to push exec filename: %v\", err), syserr.FromError(err).ToLinux())\n}\n// Push 16 random bytes on the stack which AT_RANDOM will point to.\nvar b [16]byte\nif _, err := rand.Read(b[:]); err != nil {\n- ctx.Infof(\"Failed to read random bytes: %v\", err)\n- return 0, nil, \"\", err\n+ return 0, nil, \"\", syserr.NewDynamic(fmt.Sprintf(\"Failed to read random bytes: %v\", err), syserr.FromError(err).ToLinux())\n}\nrandom, err := stack.Push(b)\nif err != nil {\n- ctx.Infof(\"Failed to push random bytes: %v\", err)\n- return 0, nil, \"\", err\n+ return 0, nil, \"\", syserr.NewDynamic(fmt.Sprintf(\"Failed to push random bytes: %v\", err), syserr.FromError(err).ToLinux())\n}\nc := auth.CredentialsFromContext(ctx)\n@@ -266,8 +261,7 @@ func Load(ctx context.Context, m *mm.MemoryManager, mounts *fs.MountNamespace, r\nsl, err := stack.Load(argv, envv, auxv)\nif err != nil {\n- ctx.Infof(\"Failed to load stack: %v\", err)\n- return 0, nil, \"\", err\n+ return 0, nil, \"\", syserr.NewDynamic(fmt.Sprintf(\"Failed to load stack: %v\", err), syserr.FromError(err).ToLinux())\n}\nm.SetArgvStart(sl.ArgvStart)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/sys_thread.go",
"new_path": "pkg/sentry/syscalls/linux/sys_thread.go",
"diff": "@@ -104,9 +104,9 @@ func Execve(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Syscal\n// Load the new TaskContext.\nmaxTraversals := uint(linux.MaxSymlinkTraversals)\n- tc, err := t.Kernel().LoadTaskImage(t, t.MountNamespace(), root, wd, &maxTraversals, filename, argv, envv, t.Arch().FeatureSet())\n- if err != nil {\n- return 0, nil, err\n+ tc, se := t.Kernel().LoadTaskImage(t, t.MountNamespace(), root, wd, &maxTraversals, filename, argv, envv, t.Arch().FeatureSet())\n+ if se != nil {\n+ return 0, nil, se.ToError()\n}\nctrl, err := t.Execve(tc)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Improve loader related error messages returned to users.
PiperOrigin-RevId: 228382827
Change-Id: Ica1d30e0df826bdd77f180a5092b2b735ea5c804 |
260,013 | 08.01.2019 14:45:17 | 28,800 | bc19103d589352d7a31f088585d68ef224eaed4c | Enable proc/self/fd test on linux and disable only on gvisor. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_unix.cc",
"new_path": "test/syscalls/linux/socket_unix.cc",
"diff": "@@ -1176,8 +1176,9 @@ TEST_P(UnixSocketPairTest, SocketShutdown) {\nEXPECT_EQ(data, absl::string_view(buf, 3));\n}\n+TEST_P(UnixSocketPairTest, SocketReopenFromProcfs) {\n// TODO: We should be returning ENXIO and NOT EIO.\n-TEST_P(UnixSocketPairTest, DISABLED_SocketReopenFromProcfs) {\n+ SKIP_IF(IsRunningOnGvisor());\nauto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n// Opening a socket pair via /proc/self/fd/X is a ENXIO.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Enable proc/self/fd test on linux and disable only on gvisor.
PiperOrigin-RevId: 228403149
Change-Id: Iab212e49d9eb27d785bddc9fd447835ce8c485ae |
260,013 | 08.01.2019 17:12:14 | 28,800 | dd761c170cc2d44eee20757a6088f80a9322342c | Allow MSG_OOB and MSG_DONTROUTE to be no-ops on recvmsg(2). | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/sys_socket.go",
"new_path": "pkg/sentry/syscalls/linux/sys_socket.go",
"diff": "@@ -63,6 +63,10 @@ var messageHeader64Len = uint64(binary.Size(MessageHeader64{}))\n// multipleMessageHeader64Len is the length of a multipeMessageHeader64 struct.\nvar multipleMessageHeader64Len = uint64(binary.Size(multipleMessageHeader64{}))\n+// baseRecvFlags are the flags that are accepted across recvmsg(2),\n+// recvmmsg(2), and recvfrom(2).\n+const baseRecvFlags = linux.MSG_OOB | linux.MSG_DONTROUTE | linux.MSG_DONTWAIT | linux.MSG_NOSIGNAL | linux.MSG_WAITALL | linux.MSG_TRUNC | linux.MSG_CTRUNC\n+\n// MessageHeader64 is the 64-bit representation of the msghdr struct used in\n// the recvmsg and sendmsg syscalls.\ntype MessageHeader64 struct {\n@@ -602,7 +606,7 @@ func RecvMsg(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sysca\n}\n// Reject flags that we don't handle yet.\n- if flags & ^(linux.MSG_DONTWAIT|linux.MSG_NOSIGNAL|linux.MSG_PEEK|linux.MSG_TRUNC|linux.MSG_CTRUNC|linux.MSG_CMSG_CLOEXEC|linux.MSG_ERRQUEUE|linux.MSG_WAITALL) != 0 {\n+ if flags & ^(baseRecvFlags|linux.MSG_PEEK|linux.MSG_CMSG_CLOEXEC|linux.MSG_ERRQUEUE) != 0 {\nreturn 0, nil, syscall.EINVAL\n}\n@@ -637,7 +641,7 @@ func RecvMMsg(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sysc\n}\n// Reject flags that we don't handle yet.\n- if flags & ^(linux.MSG_DONTWAIT|linux.MSG_NOSIGNAL|linux.MSG_TRUNC|linux.MSG_CTRUNC|linux.MSG_CMSG_CLOEXEC|linux.MSG_ERRQUEUE|linux.MSG_WAITALL) != 0 {\n+ if flags & ^(baseRecvFlags|linux.MSG_CMSG_CLOEXEC|linux.MSG_ERRQUEUE) != 0 {\nreturn 0, nil, syscall.EINVAL\n}\n@@ -794,7 +798,7 @@ func recvFrom(t *kernel.Task, fd kdefs.FD, bufPtr usermem.Addr, bufLen uint64, f\n}\n// Reject flags that we don't handle yet.\n- if flags & ^(linux.MSG_DONTWAIT|linux.MSG_NOSIGNAL|linux.MSG_PEEK|linux.MSG_TRUNC|linux.MSG_CTRUNC|linux.MSG_CONFIRM|linux.MSG_WAITALL) != 0 {\n+ if flags & ^(baseRecvFlags|linux.MSG_PEEK|linux.MSG_CONFIRM) != 0 {\nreturn 0, syscall.EINVAL\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Allow MSG_OOB and MSG_DONTROUTE to be no-ops on recvmsg(2).
PiperOrigin-RevId: 228428223
Change-Id: I433ba5ffc15ea4c2706ec944901b8269b1f364f8 |
259,992 | 09.01.2019 09:17:04 | 28,800 | 0d7023d581612e1670ef36490a827e46968d6d08 | Restore to original cgroup after sandbox and gofer processes are created
The original code assumed that it was safe to join and not restore cgroup,
but Container.Run will not exit after calling start, making cgroup cleanup
fail because there were still processes inside the cgroup. | [
{
"change_type": "MODIFY",
"old_path": "runsc/cgroup/cgroup.go",
"new_path": "runsc/cgroup/cgroup.go",
"diff": "package cgroup\nimport (\n+ \"bufio\"\n\"context\"\n\"fmt\"\n\"io/ioutil\"\n@@ -168,12 +169,12 @@ type Cgroup struct {\n}\n// New creates a new Cgroup instance if the spec includes a cgroup path.\n-// Otherwise it returns nil and false.\n-func New(spec *specs.Spec) (*Cgroup, bool) {\n+// Returns nil otherwise.\n+func New(spec *specs.Spec) *Cgroup {\nif spec.Linux == nil || spec.Linux.CgroupsPath == \"\" {\n- return nil, false\n+ return nil\n}\n- return &Cgroup{Name: spec.Linux.CgroupsPath}, true\n+ return &Cgroup{Name: spec.Linux.CgroupsPath}\n}\n// Install creates and configures cgroups according to 'res'. If cgroup path\n@@ -241,19 +242,57 @@ func (c *Cgroup) Uninstall() error {\nreturn nil\n}\n-// Join adds the current process to the all controllers.\n-func (c *Cgroup) Join() error {\n- return c.Add(0)\n+// Join adds the current process to the all controllers. Returns function that\n+// restores cgroup to the original state.\n+func (c *Cgroup) Join() (func(), error) {\n+ // First save the current state so it can be restored.\n+ undo := func() {}\n+ f, err := os.Open(\"/proc/self/cgroup\")\n+ if err != nil {\n+ return undo, err\n+ }\n+ defer f.Close()\n+\n+ var undoPaths []string\n+ scanner := bufio.NewScanner(f)\n+ for scanner.Scan() {\n+ // Format: ID:controller1,controller2:path\n+ // Example: 2:cpu,cpuacct:/user.slice\n+ tokens := strings.Split(scanner.Text(), \":\")\n+ if len(tokens) != 3 {\n+ return undo, fmt.Errorf(\"formatting cgroups file, line: %q\", scanner.Text())\n+ }\n+ for _, ctrlr := range strings.Split(tokens[1], \",\") {\n+ // Skip controllers we don't handle.\n+ if _, ok := controllers[ctrlr]; ok {\n+ undoPaths = append(undoPaths, filepath.Join(cgroupRoot, ctrlr, tokens[2]))\n+ break\n+ }\n+ }\n+ }\n+ if err := scanner.Err(); err != nil {\n+ return undo, err\n}\n-// Add adds given process to all controllers.\n-func (c *Cgroup) Add(pid int) error {\n+ // Replace empty undo with the real thing before changes are made to cgroups.\n+ undo = func() {\n+ for _, path := range undoPaths {\n+ log.Debugf(\"Restoring cgroup %q\", path)\n+ if err := setValue(path, \"cgroup.procs\", \"0\"); err != nil {\n+ log.Warningf(\"Error restoring cgroup %q: %v\", path, err)\n+ }\n+ }\n+ }\n+\n+ // Now join the cgroups.\nfor key := range controllers {\n- if err := setValue(c.makePath(key), \"cgroup.procs\", strconv.Itoa(pid)); err != nil {\n- return err\n+ path := c.makePath(key)\n+ log.Debugf(\"Joining cgroup %q\", path)\n+ if err := setValue(path, \"cgroup.procs\", \"0\"); err != nil {\n+ return undo, err\n}\n}\n- return nil\n+ return undo, nil\n}\n// NumCPU returns the number of CPUs configured in 'cpuset/cpuset.cpus'.\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/container/BUILD",
"new_path": "runsc/container/BUILD",
"diff": "@@ -19,6 +19,7 @@ go_library(\n\"//pkg/log\",\n\"//pkg/sentry/control\",\n\"//runsc/boot\",\n+ \"//runsc/cgroup\",\n\"//runsc/sandbox\",\n\"//runsc/specutils\",\n\"@com_github_cenkalti_backoff//:go_default_library\",\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/container/container.go",
"new_path": "runsc/container/container.go",
"diff": "@@ -36,6 +36,7 @@ import (\n\"gvisor.googlesource.com/gvisor/pkg/log\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/control\"\n\"gvisor.googlesource.com/gvisor/runsc/boot\"\n+ \"gvisor.googlesource.com/gvisor/runsc/cgroup\"\n\"gvisor.googlesource.com/gvisor/runsc/sandbox\"\n\"gvisor.googlesource.com/gvisor/runsc/specutils\"\n)\n@@ -286,18 +287,26 @@ func Create(id string, spec *specs.Spec, conf *boot.Config, bundleDir, consoleSo\nreturn nil, fmt.Errorf(\"writing clean spec: %v\", err)\n}\n+ // Create and join cgroup before processes are created to ensure they are\n+ // part of the cgroup from the start (and all tneir children processes).\n+ cg := cgroup.New(spec)\n+ if cg != nil {\n+ // If there is cgroup config, install it before creating sandbox process.\n+ if err := cg.Install(spec.Linux.Resources); err != nil {\n+ return nil, fmt.Errorf(\"configuring cgroup: %v\", err)\n+ }\n+ }\n+ if err := runInCgroup(cg, func() error {\nioFiles, err := c.createGoferProcess(spec, conf, bundleDir)\nif err != nil {\n- return nil, err\n+ return err\n}\n// Start a new sandbox for this container. Any errors after this point\n// must destroy the container.\n- c.Sandbox, err = sandbox.Create(id, spec, conf, bundleDir, consoleSocket, userLog, ioFiles)\n- if err != nil {\n- return nil, err\n- }\n- if err := c.Sandbox.AddGoferToCgroup(c.GoferPid); err != nil {\n+ c.Sandbox, err = sandbox.New(id, spec, conf, bundleDir, consoleSocket, userLog, ioFiles, cg)\n+ return err\n+ }); err != nil {\nreturn nil, err\n}\n} else {\n@@ -381,15 +390,16 @@ func (c *Container) Start(conf *boot.Config) error {\nreturn fmt.Errorf(\"writing clean spec: %v\", err)\n}\n+ // Join cgroup to strt gofer process to ensure it's part of the cgroup from\n+ // the start (and all tneir children processes).\n+ if err := runInCgroup(c.Sandbox.Cgroup, func() error {\n// Create the gofer process.\nioFiles, err := c.createGoferProcess(c.Spec, conf, c.BundleDir)\nif err != nil {\nreturn err\n}\n- if err := c.Sandbox.StartContainer(c.Spec, conf, c.ID, ioFiles); err != nil {\n- return err\n- }\n- if err := c.Sandbox.AddGoferToCgroup(c.GoferPid); err != nil {\n+ return c.Sandbox.StartContainer(c.Spec, conf, c.ID, ioFiles)\n+ }); err != nil {\nreturn err\n}\n}\n@@ -883,3 +893,17 @@ func lockContainerMetadata(containerRootDir string) (func() error, error) {\n}\nreturn l.Unlock, nil\n}\n+\n+// runInCgroup executes fn inside the specified cgroup. If cg is nil, execute\n+// it in the current context.\n+func runInCgroup(cg *cgroup.Cgroup, fn func() error) error {\n+ if cg == nil {\n+ return fn()\n+ }\n+ restore, err := cg.Join()\n+ defer restore()\n+ if err != nil {\n+ return err\n+ }\n+ return fn()\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/sandbox/sandbox.go",
"new_path": "runsc/sandbox/sandbox.go",
"diff": "@@ -64,32 +64,15 @@ type Sandbox struct {\nCgroup *cgroup.Cgroup `json:\"cgroup\"`\n}\n-// Create creates the sandbox process. The caller must call Destroy() on the\n-// sandbox. If spec specified a cgroup, the current process will have joined\n-// the cgroup upon return.\n-func Create(id string, spec *specs.Spec, conf *boot.Config, bundleDir, consoleSocket, userLog string, ioFiles []*os.File) (*Sandbox, error) {\n- s := &Sandbox{ID: id}\n- // The Cleanup object cleans up partially created sandboxes when an error occurs.\n- // Any errors occurring during cleanup itself are ignored.\n+// New creates the sandbox process. The caller must call Destroy() on the\n+// sandbox.\n+func New(id string, spec *specs.Spec, conf *boot.Config, bundleDir, consoleSocket, userLog string, ioFiles []*os.File, cg *cgroup.Cgroup) (*Sandbox, error) {\n+ s := &Sandbox{ID: id, Cgroup: cg}\n+ // The Cleanup object cleans up partially created sandboxes when an error\n+ // occurs. Any errors occurring during cleanup itself are ignored.\nc := specutils.MakeCleanup(func() { _ = s.destroy() })\ndefer c.Clean()\n- if cg, ok := cgroup.New(spec); ok {\n- s.Cgroup = cg\n-\n- // If there is cgroup config, install it before creating sandbox process.\n- if err := s.Cgroup.Install(spec.Linux.Resources); err != nil {\n- return nil, fmt.Errorf(\"configuring cgroup: %v\", err)\n- }\n-\n- // Make this process join the cgroup to ensure the sandbox (and all its\n- // children processes) are part of the cgroup from the start. Don't bother\n- // moving out because the caller is about to exit anyways.\n- if err := cg.Join(); err != nil {\n- return nil, fmt.Errorf(\"joining cgroup: %v\", err)\n- }\n- }\n-\n// Create pipe to synchronize when sandbox process has been booted.\nfds := make([]int, 2)\nif err := syscall.Pipe(fds); err != nil {\n@@ -871,14 +854,6 @@ func (s *Sandbox) waitForStopped() error {\nreturn backoff.Retry(op, b)\n}\n-// AddGoferToCgroup adds the gofer process to the sandbox's cgroup.\n-func (s *Sandbox) AddGoferToCgroup(pid int) error {\n- if s.Cgroup != nil {\n- return s.Cgroup.Add(pid)\n- }\n- return nil\n-}\n-\n// deviceFileForPlatform opens the device file for the given platform. If the\n// platform does not need a device file, then nil is returned.\nfunc deviceFileForPlatform(p boot.PlatformType) (*os.File, error) {\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/specutils/specutils.go",
"new_path": "runsc/specutils/specutils.go",
"diff": "@@ -471,7 +471,6 @@ func ContainsStr(strs []string, str string) bool {\n// return f\ntype Cleanup struct {\nclean func()\n- released bool\n}\n// MakeCleanup creates a new Cleanup object.\n@@ -481,13 +480,14 @@ func MakeCleanup(f func()) Cleanup {\n// Clean calls the cleanup function.\nfunc (c *Cleanup) Clean() {\n- if !c.released {\n+ if c.clean != nil {\nc.clean()\n+ c.clean = nil\n}\n}\n// Release releases the cleanup from its duties, i.e. cleanup function is not\n// called after this point.\nfunc (c *Cleanup) Release() {\n- c.released = true\n+ c.clean = nil\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Restore to original cgroup after sandbox and gofer processes are created
The original code assumed that it was safe to join and not restore cgroup,
but Container.Run will not exit after calling start, making cgroup cleanup
fail because there were still processes inside the cgroup.
PiperOrigin-RevId: 228529199
Change-Id: I12a48d9adab4bbb02f20d71ec99598c336cbfe51 |
259,853 | 09.01.2019 13:13:04 | 28,800 | 252e57992d0a5872bb0f1f41c38c004662a729de | Allow to specify a custom path to runsc for syscall-test-runner | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/BUILD",
"new_path": "test/syscalls/BUILD",
"diff": "@@ -535,8 +535,6 @@ go_binary(\n],\ndeps = [\n\"//pkg/log\",\n- \"//runsc/boot\",\n- \"//runsc/container\",\n\"//runsc/specutils\",\n\"//runsc/test/testutil\",\n\"//test/syscalls/gtest\",\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/syscall_test_runner.go",
"new_path": "test/syscalls/syscall_test_runner.go",
"diff": "@@ -31,8 +31,6 @@ import (\n\"golang.org/x/sys/unix\"\n\"gvisor.googlesource.com/gvisor/pkg/log\"\n- \"gvisor.googlesource.com/gvisor/runsc/boot\"\n- \"gvisor.googlesource.com/gvisor/runsc/container\"\n\"gvisor.googlesource.com/gvisor/runsc/specutils\"\n\"gvisor.googlesource.com/gvisor/runsc/test/testutil\"\n\"gvisor.googlesource.com/gvisor/test/syscalls/gtest\"\n@@ -47,6 +45,7 @@ var (\nstrace = flag.Bool(\"strace\", false, \"enable strace logs\")\nplatform = flag.String(\"platform\", \"ptrace\", \"platform to run on\")\nparallel = flag.Bool(\"parallel\", false, \"run tests in parallel\")\n+ runscPath = flag.String(\"runsc\", \"\", \"path to runsc binary\")\n)\n// runTestCaseNative runs the test case directly on the host machine.\n@@ -101,16 +100,6 @@ func runTestCaseRunsc(testBin string, tc gtest.TestCase, t *testing.T) {\n}\ndefer os.RemoveAll(rootDir)\n- conf := testutil.TestConfig()\n- conf.RootDir = rootDir\n- conf.Debug = *debug\n- conf.Strace = *strace\n- p, err := boot.MakePlatformType(*platform)\n- if err != nil {\n- t.Fatalf(\"error getting platform %q: %v\", *platform, err)\n- }\n- conf.Platform = p\n-\n// Run a new container with the test executable and filter for the\n// given test suite and name.\nspec := testutil.NewSpecWithArgs(testBin, gtest.FilterTestFlag+\"=\"+tc.FullName())\n@@ -154,12 +143,43 @@ func runTestCaseRunsc(testBin string, tc gtest.TestCase, t *testing.T) {\nid := testutil.UniqueContainerID()\nlog.Infof(\"Running test %q in container %q\", tc.FullName(), id)\nspecutils.LogSpec(spec)\n- ws, err := container.Run(id, spec, conf, bundleDir, \"\", \"\", \"\")\n- if err != nil {\n- t.Fatalf(\"container.Run failed: %v\", err)\n+\n+ args := []string{\n+ \"-platform\", *platform,\n+ \"-root\", rootDir,\n+ \"--network=none\",\n+ \"-log-format=text\",\n+ \"-TESTONLY-unsafe-nonroot=true\",\n}\n- if got := ws.ExitStatus(); got != 0 {\n- t.Errorf(\"test %q exited with status %d, want 0\", tc.FullName(), ws.ExitStatus())\n+ if *debug {\n+ args = append(args, \"-debug\", \"-log-packets=true\")\n+ }\n+ if *strace {\n+ args = append(args, \"-strace\")\n+ }\n+ // Current process doesn't have CAP_SYS_ADMIN, create user namespace and run\n+ // as root inside that namespace to get it.\n+ args = append(args, \"run\", \"--bundle\", bundleDir, id)\n+ cmd := exec.Command(*runscPath, args...)\n+ cmd.SysProcAttr = &syscall.SysProcAttr{\n+ Cloneflags: syscall.CLONE_NEWUSER | syscall.CLONE_NEWNS,\n+ // Set current user/group as root inside the namespace.\n+ UidMappings: []syscall.SysProcIDMap{\n+ {ContainerID: 0, HostID: os.Getuid(), Size: 1},\n+ },\n+ GidMappings: []syscall.SysProcIDMap{\n+ {ContainerID: 0, HostID: os.Getgid(), Size: 1},\n+ },\n+ GidMappingsEnableSetgroups: false,\n+ Credential: &syscall.Credential{\n+ Uid: 0,\n+ Gid: 0,\n+ },\n+ }\n+ cmd.Stdout = os.Stdout\n+ cmd.Stderr = os.Stderr\n+ if err = cmd.Run(); err != nil {\n+ t.Errorf(\"test %q exited with status %v, want 0\", tc.FullName(), err)\n}\n}\n@@ -201,13 +221,11 @@ func main() {\nlog.SetLevel(log.Debug)\n}\n- if *platform != \"native\" {\n+ if *platform != \"native\" && *runscPath == \"\" {\nif err := testutil.ConfigureExePath(); err != nil {\npanic(err.Error())\n}\n- // The native tests don't expect to be running as root, but\n- // runsc requires it.\n- testutil.RunAsRoot()\n+ *runscPath = specutils.ExePath\n}\n// Make sure stdout and stderr are opened with O_APPEND, otherwise logs\n"
}
] | Go | Apache License 2.0 | google/gvisor | Allow to specify a custom path to runsc for syscall-test-runner
PiperOrigin-RevId: 228574092
Change-Id: Id93abcca1ce964eb595907df9355702d469bc33b |
259,885 | 09.01.2019 17:53:31 | 28,800 | 9270d940eb1a6e31587c34f4644189f3b2c002e1 | Minor memevent fixes.
Call MemoryEvents.done.Add(1) outside of MemoryEvents.run() so that if
MemoryEvents.Stop() => MemoryEvents.done.Wait() is called before the
goroutine starts running, it still waits for the goroutine to stop.
Use defer to call MemoryEvents.done.Done() in MemoryEvents.run() so that it's
called even if the goroutine panics. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/memevent/memory_events.go",
"new_path": "pkg/sentry/kernel/memevent/memory_events.go",
"diff": "@@ -69,11 +69,12 @@ func (m *MemoryEvents) Start() {\nif m.period == 0 {\nreturn\n}\n+ m.done.Add(1)\ngo m.run() // S/R-SAFE: doesn't interact with saved state.\n}\nfunc (m *MemoryEvents) run() {\n- m.done.Add(1)\n+ defer m.done.Done()\n// Emit the first event immediately on startup.\ntotalTicks.Increment()\n@@ -85,7 +86,6 @@ func (m *MemoryEvents) run() {\nfor {\nselect {\ncase <-m.stop:\n- m.done.Done()\nreturn\ncase <-ticker.C:\ntotalTicks.Increment()\n"
}
] | Go | Apache License 2.0 | google/gvisor | Minor memevent fixes.
- Call MemoryEvents.done.Add(1) outside of MemoryEvents.run() so that if
MemoryEvents.Stop() => MemoryEvents.done.Wait() is called before the
goroutine starts running, it still waits for the goroutine to stop.
- Use defer to call MemoryEvents.done.Done() in MemoryEvents.run() so that it's
called even if the goroutine panics.
PiperOrigin-RevId: 228623307
Change-Id: I1b0459e7999606c1a1a271b16092b1ca87005015 |
259,975 | 10.01.2019 09:43:43 | 28,800 | 7f8de3bf92decbd745a4bc4e8aebf1ba1159ed4b | Fixing select call to not enforce RLIMIT_NOFILE.
Removing check to RLIMIT_NOFILE in select call.
Adding unit test to select suite to document behavior.
Moving setrlimit class from mlock to a util file for reuse.
Fixing flaky test based on comments from Jamie. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/sys_poll.go",
"new_path": "pkg/sentry/syscalls/linux/sys_poll.go",
"diff": "@@ -82,7 +82,7 @@ func doPoll(t *kernel.Task, pfdAddr usermem.Addr, nfds uint, timeout time.Durati\n}\nfunc doSelect(t *kernel.Task, nfds int, readFDs, writeFDs, exceptFDs usermem.Addr, timeout time.Duration) (uintptr, error) {\n- if nfds < 0 || uint64(nfds) > t.ThreadGroup().Limits().GetCapped(limits.NumberOfFiles, fileCap) {\n+ if nfds < 0 || nfds > fileCap {\nreturn 0, syserror.EINVAL\n}\n@@ -90,6 +90,7 @@ func doSelect(t *kernel.Task, nfds int, readFDs, writeFDs, exceptFDs usermem.Add\n//\n// N.B. This only works on little-endian architectures.\nbyteCount := (nfds + 7) / 8\n+\nbitsInLastPartialByte := uint(nfds % 8)\nr := make([]byte, byteCount)\nw := make([]byte, byteCount)\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/BUILD",
"new_path": "test/syscalls/linux/BUILD",
"diff": "@@ -1033,6 +1033,7 @@ cc_binary(\n\"//test/util:cleanup\",\n\"//test/util:memory_util\",\n\"//test/util:multiprocess_util\",\n+ \"//test/util:rlimit_util\",\n\"//test/util:test_main\",\n\"//test/util:test_util\",\n\"@com_google_googletest//:gtest\",\n@@ -1650,6 +1651,11 @@ cc_binary(\nlinkstatic = 1,\ndeps = [\n\":base_poll_test\",\n+ \"//test/util:file_descriptor\",\n+ \"//test/util:multiprocess_util\",\n+ \"//test/util:posix_error\",\n+ \"//test/util:rlimit_util\",\n+ \"//test/util:temp_path\",\n\"//test/util:test_main\",\n\"//test/util:test_util\",\n\"@com_google_absl//absl/time\",\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/mlock.cc",
"new_path": "test/syscalls/linux/mlock.cc",
"diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-#include <errno.h>\n-#include <string.h>\n#include <sys/mman.h>\n#include <sys/resource.h>\n#include <sys/syscall.h>\n#include <unistd.h>\n+#include <cerrno>\n+#include <cstring>\n#include \"gmock/gmock.h\"\n#include \"test/util/capability_util.h\"\n#include \"test/util/cleanup.h\"\n#include \"test/util/memory_util.h\"\n#include \"test/util/multiprocess_util.h\"\n+#include \"test/util/rlimit_util.h\"\n#include \"test/util/test_util.h\"\nusing ::testing::_;\n@@ -58,20 +59,6 @@ bool IsPageMlocked(uintptr_t addr) {\nreturn true;\n}\n-PosixErrorOr<Cleanup> ScopedSetSoftRlimit(int resource, rlim_t newval) {\n- struct rlimit old_rlim;\n- if (getrlimit(resource, &old_rlim) != 0) {\n- return PosixError(errno, \"getrlimit failed\");\n- }\n- struct rlimit new_rlim = old_rlim;\n- new_rlim.rlim_cur = newval;\n- if (setrlimit(resource, &new_rlim) != 0) {\n- return PosixError(errno, \"setrlimit failed\");\n- }\n- return Cleanup([resource, old_rlim] {\n- TEST_PCHECK(setrlimit(resource, &old_rlim) == 0);\n- });\n-}\nTEST(MlockTest, Basic) {\nSKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(CanMlock()));\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/select.cc",
"new_path": "test/syscalls/linux/select.cc",
"diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-#include <limits.h>\n-#include <signal.h>\n+#include <fcntl.h>\n+#include <sys/resource.h>\n#include <sys/select.h>\n+#include <sys/time.h>\n+#include <climits>\n+#include <csignal>\n+#include <cstdio>\n#include \"gtest/gtest.h\"\n#include \"gtest/gtest.h\"\n#include \"absl/time/time.h\"\n#include \"test/syscalls/linux/base_poll_test.h\"\n+#include \"test/util/file_descriptor.h\"\n+#include \"test/util/multiprocess_util.h\"\n+#include \"test/util/posix_error.h\"\n+#include \"test/util/rlimit_util.h\"\n+#include \"test/util/temp_path.h\"\n#include \"test/util/test_util.h\"\nnamespace gvisor {\n@@ -57,15 +66,27 @@ TEST_F(SelectTest, NegativeNfds) {\n}\nTEST_F(SelectTest, ClosedFds) {\n+ auto temp_file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());\n+ FileDescriptor fd =\n+ ASSERT_NO_ERRNO_AND_VALUE(Open(temp_file.path(), O_RDONLY));\n+\n+ // We can't rely on a file descriptor being closed in a multi threaded\n+ // application so fork to get a clean process.\n+ EXPECT_THAT(InForkedProcess([&] {\n+ int fd_num = fd.get();\n+ fd.reset();\n+\nfd_set read_set;\nFD_ZERO(&read_set);\n- int fd;\n- ASSERT_THAT(fd = dup(1), SyscallSucceeds());\n- ASSERT_THAT(close(fd), SyscallSucceeds());\n- FD_SET(fd, &read_set);\n- struct timeval timeout = absl::ToTimeval(absl::Milliseconds(10));\n- EXPECT_THAT(select(fd + 1, &read_set, nullptr, nullptr, &timeout),\n- SyscallFailsWithErrno(EBADF));\n+ FD_SET(fd_num, &read_set);\n+\n+ struct timeval timeout =\n+ absl::ToTimeval(absl::Milliseconds(10));\n+ TEST_PCHECK(select(fd_num + 1, &read_set, nullptr, nullptr,\n+ &timeout) != 0);\n+ TEST_PCHECK(errno == EBADF);\n+ }),\n+ IsPosixErrorOkAndHolds(0));\n}\nTEST_F(SelectTest, ZeroTimeout) {\n@@ -123,6 +144,25 @@ TEST_F(SelectTest, IgnoreBitsAboveNfds) {\nSyscallSucceedsWithValue(0));\n}\n+// This test illustrates Linux's behavior of 'select' calls passing after\n+// setrlimit RLIMIT_NOFILE is called. In particular, versions of sshd rely on\n+// this behavior.\n+TEST_F(SelectTest, SetrlimitCallNOFILE) {\n+ fd_set read_set;\n+ FD_ZERO(&read_set);\n+ timeval timeout = {};\n+ const FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(\n+ Open(NewTempAbsPath(), O_RDONLY | O_CREAT, S_IRUSR));\n+\n+ Cleanup reset_rlimit =\n+ ASSERT_NO_ERRNO_AND_VALUE(ScopedSetSoftRlimit(RLIMIT_NOFILE, 0));\n+\n+ FD_SET(fd.get(), &read_set);\n+ // this call with zero timeout should return immediately\n+ EXPECT_THAT(select(fd.get() + 1, &read_set, nullptr, nullptr, &timeout),\n+ SyscallSucceeds());\n+}\n+\n} // namespace\n} // namespace testing\n} // namespace gvisor\n"
},
{
"change_type": "MODIFY",
"old_path": "test/util/BUILD",
"new_path": "test/util/BUILD",
"diff": "@@ -272,3 +272,16 @@ cc_library(\n\"@com_google_googletest//:gtest\",\n],\n)\n+\n+cc_library(\n+ name = \"rlimit_util\",\n+ testonly = 1,\n+ srcs = [\"rlimit_util.cc\"],\n+ hdrs = [\"rlimit_util.h\"],\n+ deps = [\n+ \":cleanup\",\n+ \":logging\",\n+ \":posix_error\",\n+ \":test_util\",\n+ ],\n+)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/util/rlimit_util.cc",
"diff": "+// Copyright 2019 Google LLC\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+#include \"test/util/rlimit_util.h\"\n+\n+#include <sys/resource.h>\n+#include <cerrno>\n+\n+#include \"test/util/cleanup.h\"\n+#include \"test/util/logging.h\"\n+#include \"test/util/posix_error.h\"\n+#include \"test/util/test_util.h\"\n+\n+namespace gvisor {\n+namespace testing {\n+\n+PosixErrorOr<Cleanup> ScopedSetSoftRlimit(int resource, rlim_t newval) {\n+ struct rlimit old_rlim;\n+ if (getrlimit(resource, &old_rlim) != 0) {\n+ return PosixError(errno, \"getrlimit failed\");\n+ }\n+ struct rlimit new_rlim = old_rlim;\n+ new_rlim.rlim_cur = newval;\n+ if (setrlimit(resource, &new_rlim) != 0) {\n+ return PosixError(errno, \"setrlimit failed\");\n+ }\n+ return Cleanup([resource, old_rlim] {\n+ TEST_PCHECK(setrlimit(resource, &old_rlim) == 0);\n+ });\n+}\n+\n+} // namespace testing\n+} // namespace gvisor\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/util/rlimit_util.h",
"diff": "+// Copyright 2019 Google LLC\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+#ifndef GVISOR_TEST_UTIL_RLIMIT_UTIL_H_\n+#define GVISOR_TEST_UTIL_RLIMIT_UTIL_H_\n+\n+#include <sys/resource.h>\n+#include <sys/time.h>\n+\n+#include \"test/util/cleanup.h\"\n+#include \"test/util/posix_error.h\"\n+#include \"test/util/test_util.h\"\n+\n+namespace gvisor {\n+namespace testing {\n+\n+PosixErrorOr<Cleanup> ScopedSetSoftRlimit(int resource, rlim_t newval);\n+\n+} // namespace testing\n+} // namespace gvisor\n+#endif // GVISOR_TEST_UTIL_RLIMIT_UTIL_H_\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fixing select call to not enforce RLIMIT_NOFILE.
Removing check to RLIMIT_NOFILE in select call.
Adding unit test to select suite to document behavior.
Moving setrlimit class from mlock to a util file for reuse.
Fixing flaky test based on comments from Jamie.
PiperOrigin-RevId: 228726131
Change-Id: Ie9dbe970bbf835ba2cca6e17eec7c2ee6fadf459 |
259,881 | 10.01.2019 17:15:33 | 28,800 | bde588ff05cad3591025a1e313eebe61cd82e421 | Define name earlier | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/build_defs.bzl",
"new_path": "test/syscalls/build_defs.bzl",
"diff": "@@ -13,6 +13,8 @@ def _syscall_test(test, shard_count, size, platform):\n# Prepend \"runsc\" to non-native platform names.\nfull_platform = platform if platform == \"native\" else \"runsc_\" + platform\n+ name = test_name + \"_\" + full_platform\n+\n# Add the full_platform in a tag to make it easier to run all the tests on\n# a specific platform.\ntags = [full_platform]\n@@ -28,7 +30,7 @@ def _syscall_test(test, shard_count, size, platform):\nsh_test(\nsrcs = [\"syscall_test_runner.sh\"],\n- name = test_name + \"_\" + full_platform,\n+ name = name,\ndata = [\n\":syscall_test_runner\",\ntest,\n"
}
] | Go | Apache License 2.0 | google/gvisor | Define name earlier
PiperOrigin-RevId: 228805981
Change-Id: I4f4c4a5d8de325dff38f6dfb92108fc848d823fd |
259,853 | 11.01.2019 10:31:21 | 28,800 | f8c8f241540fa79b47090ce4808c2c0cfbe44a12 | runsc: Collect zombies of sandbox and gofer processes
And we need to wait a gofer process before cgroup.Uninstall,
because it is running in the sandbox cgroups. | [
{
"change_type": "MODIFY",
"old_path": "runsc/container/container.go",
"new_path": "runsc/container/container.go",
"diff": "@@ -119,6 +119,12 @@ type Container struct {\n// be 0 if the gofer has been killed.\nGoferPid int `json:\"goferPid\"`\n+ // goferIsChild is set if a gofer process is a child of the current process.\n+ //\n+ // This field isn't saved to json, because only a creator of a gofer\n+ // process will have it as a child process.\n+ goferIsChild bool\n+\n// Sandbox is the sandbox this container is running in. It's set when the\n// container is created and reset when the sandbox is destroyed.\nSandbox *sandbox.Sandbox `json:\"sandbox\"`\n@@ -708,11 +714,14 @@ func (c *Container) save() error {\n// root containers), and waits for the container or sandbox and the gofer\n// to stop. If any of them doesn't stop before timeout, an error is returned.\nfunc (c *Container) stop() error {\n+ var cgroup *cgroup.Cgroup\n+\nif c.Sandbox != nil {\nlog.Debugf(\"Destroying container %q\", c.ID)\nif err := c.Sandbox.DestroyContainer(c.ID); err != nil {\nreturn fmt.Errorf(\"error destroying container %q: %v\", c.ID, err)\n}\n+ cgroup = c.Sandbox.Cgroup\n// Only set sandbox to nil after it has been told to destroy the container.\nc.Sandbox = nil\n}\n@@ -725,7 +734,18 @@ func (c *Container) stop() error {\nlog.Warningf(\"Error sending signal %d to gofer %d: %v\", syscall.SIGKILL, c.GoferPid, err)\n}\n}\n- return c.waitForStopped()\n+\n+ if err := c.waitForStopped(); err != nil {\n+ return err\n+ }\n+\n+ // Gofer is running in cgroups, so Cgroup.Uninstall has to be called after it.\n+ if cgroup != nil {\n+ if err := cgroup.Uninstall(); err != nil {\n+ return err\n+ }\n+ }\n+ return nil\n}\nfunc (c *Container) waitForStopped() error {\n@@ -738,12 +758,24 @@ func (c *Container) waitForStopped() error {\nreturn fmt.Errorf(\"container is still running\")\n}\n}\n- if c.GoferPid != 0 {\n- if err := syscall.Kill(c.GoferPid, 0); err == nil {\n+ if c.GoferPid == 0 {\n+ return nil\n+ }\n+ if c.goferIsChild {\n+ // The gofer process is a child of the current process,\n+ // so we can wait it and collect its zombie.\n+ wpid, err := syscall.Wait4(int(c.GoferPid), nil, syscall.WNOHANG, nil)\n+ if err != nil {\n+ return fmt.Errorf(\"error waiting the gofer process: %v\", err)\n+ }\n+ if wpid == 0 {\nreturn fmt.Errorf(\"gofer is still running\")\n}\n- c.GoferPid = 0\n+\n+ } else if err := syscall.Kill(c.GoferPid, 0); err == nil {\n+ return fmt.Errorf(\"gofer is still running\")\n}\n+ c.GoferPid = 0\nreturn nil\n}\nreturn backoff.Retry(op, b)\n@@ -816,6 +848,7 @@ func (c *Container) createGoferProcess(spec *specs.Spec, conf *boot.Config, bund\n}\nlog.Infof(\"Gofer started, PID: %d\", cmd.Process.Pid)\nc.GoferPid = cmd.Process.Pid\n+ c.goferIsChild = true\nreturn sandEnds, nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/container/container_test.go",
"new_path": "runsc/container/container_test.go",
"diff": "@@ -39,9 +39,6 @@ import (\n\"gvisor.googlesource.com/gvisor/runsc/test/testutil\"\n)\n-// childReaper reaps child processes.\n-var childReaper *testutil.Reaper\n-\n// waitForProcessList waits for the given process list to show up in the container.\nfunc waitForProcessList(cont *Container, want []*control.Process) error {\ncb := func() error {\n@@ -75,6 +72,18 @@ func waitForProcessCount(cont *Container, want int) error {\nreturn testutil.Poll(cb, 30*time.Second)\n}\n+func blockUntilWaitable(pid int) error {\n+ _, _, err := testutil.RetryEintr(func() (uintptr, uintptr, error) {\n+ var err error\n+ _, _, err1 := syscall.Syscall6(syscall.SYS_WAITID, 1, uintptr(pid), 0, syscall.WEXITED|syscall.WNOWAIT, 0, 0)\n+ if err1 != 0 {\n+ err = err1\n+ }\n+ return 0, 0, err\n+ })\n+ return err\n+}\n+\n// procListsEqual is used to check whether 2 Process lists are equal for all\n// implemented fields.\nfunc procListsEqual(got, want []*control.Process) bool {\n@@ -256,6 +265,11 @@ func configs(opts ...configOption) []*boot.Config {\n// It verifies after each step that the container can be loaded from disk, and\n// has the correct status.\nfunc TestLifecycle(t *testing.T) {\n+ // Start the child reaper.\n+ childReaper := &testutil.Reaper{}\n+ childReaper.Start()\n+ defer childReaper.Stop()\n+\nfor _, conf := range configs(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@@ -1505,10 +1519,7 @@ func TestGoferExits(t *testing.T) {\nt.Fatalf(\"error killing sandbox process: %v\", err)\n}\n- _, _, err = testutil.RetryEintr(func() (uintptr, uintptr, error) {\n- cpid, err := syscall.Wait4(c.GoferPid, nil, 0, nil)\n- return uintptr(cpid), 0, err\n- })\n+ err = blockUntilWaitable(c.GoferPid)\nif err != nil && err != syscall.ECHILD {\nt.Errorf(\"error waiting for gofer to exit: %v\", err)\n}\n@@ -1576,10 +1587,6 @@ func TestUserLog(t *testing.T) {\n}\nfunc TestWaitOnExitedSandbox(t *testing.T) {\n- // Disable the childReaper for this test.\n- childReaper.Stop()\n- defer childReaper.Start()\n-\nfor _, conf := range configs(all...) {\nt.Logf(\"Running test with conf: %+v\", conf)\n@@ -1712,10 +1719,5 @@ func TestMain(m *testing.M) {\n}\ntestutil.RunAsRoot()\n- // Start the child reaper.\n- childReaper = &testutil.Reaper{}\n- childReaper.Start()\n- defer childReaper.Stop()\n-\nos.Exit(m.Run())\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/container/multi_container_test.go",
"new_path": "runsc/container/multi_container_test.go",
"diff": "@@ -359,7 +359,7 @@ func TestMultiContainerSignal(t *testing.T) {\ncpid, err := syscall.Wait4(goferPid, nil, 0, nil)\nreturn uintptr(cpid), 0, err\n})\n- if err != nil && err != syscall.ECHILD {\n+ if err != syscall.ECHILD {\nt.Errorf(\"error waiting for gofer to exit: %v\", err)\n}\n// Make sure process 1 is still running.\n@@ -379,18 +379,12 @@ func TestMultiContainerSignal(t *testing.T) {\n}\n// Ensure that container's gofer and sandbox process are no more.\n- _, _, err = testutil.RetryEintr(func() (uintptr, uintptr, error) {\n- cpid, err := syscall.Wait4(containers[0].GoferPid, nil, 0, nil)\n- return uintptr(cpid), 0, err\n- })\n+ err = blockUntilWaitable(containers[0].GoferPid)\nif err != nil && err != syscall.ECHILD {\nt.Errorf(\"error waiting for gofer to exit: %v\", err)\n}\n- _, _, err = testutil.RetryEintr(func() (uintptr, uintptr, error) {\n- cpid, err := syscall.Wait4(containers[0].Sandbox.Pid, nil, 0, nil)\n- return uintptr(cpid), 0, err\n- })\n+ err = blockUntilWaitable(containers[0].Sandbox.Pid)\nif err != nil && err != syscall.ECHILD {\nt.Errorf(\"error waiting for sandbox to exit: %v\", err)\n}\n@@ -399,6 +393,10 @@ func TestMultiContainerSignal(t *testing.T) {\nif err := containers[0].SignalContainer(syscall.SIGKILL, false); err == nil {\nt.Errorf(\"sandbox %q shouldn't exist, but we were able to signal it\", containers[0].Sandbox.ID)\n}\n+\n+ if err := containers[0].Destroy(); err != nil {\n+ t.Errorf(\"failed to destroy container: %v\", err)\n+ }\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/sandbox/sandbox.go",
"new_path": "runsc/sandbox/sandbox.go",
"diff": "@@ -62,6 +62,12 @@ type Sandbox struct {\n// Cgroup has the cgroup configuration for the sandbox.\nCgroup *cgroup.Cgroup `json:\"cgroup\"`\n+\n+ // child is set if a sandbox process is a child of the current process.\n+ //\n+ // This field isn't saved to json, because only a creator of sandbox\n+ // will have it as a child process.\n+ child bool\n}\n// New creates the sandbox process. The caller must call Destroy() on the\n@@ -70,7 +76,10 @@ func New(id string, spec *specs.Spec, conf *boot.Config, bundleDir, consoleSocke\ns := &Sandbox{ID: id, Cgroup: cg}\n// The Cleanup object cleans up partially created sandboxes when an error\n// occurs. Any errors occurring during cleanup itself are ignored.\n- c := specutils.MakeCleanup(func() { _ = s.destroy() })\n+ c := specutils.MakeCleanup(func() {\n+ err := s.destroy()\n+ log.Warningf(\"error destroying sandbox: %v\", err)\n+ })\ndefer c.Clean()\n// Create pipe to synchronize when sandbox process has been booted.\n@@ -578,6 +587,7 @@ func (s *Sandbox) createSandboxProcess(spec *specs.Spec, conf *boot.Config, bund\nif err := specutils.StartInNS(cmd, nss); err != nil {\nreturn err\n}\n+ s.child = true\ns.Pid = cmd.Process.Pid\nlog.Infof(\"Sandbox started, PID: %d\", s.Pid)\n@@ -666,11 +676,6 @@ func (s *Sandbox) destroy() error {\n}\n}\n- if s.Cgroup != nil {\n- if err := s.Cgroup.Uninstall(); err != nil {\n- return err\n- }\n- }\nif s.Chroot != \"\" {\nif err := tearDownChroot(s.Chroot); err != nil {\nreturn err\n@@ -846,7 +851,18 @@ func (s *Sandbox) waitForStopped() error {\ndefer cancel()\nb := backoff.WithContext(backoff.NewConstantBackOff(100*time.Millisecond), ctx)\nop := func() error {\n- if s.IsRunning() {\n+ if s.child && s.Pid != 0 {\n+ // The sandbox process is a child of the current process,\n+ // so we can wait it and collect its zombie.\n+ wpid, err := syscall.Wait4(int(s.Pid), nil, syscall.WNOHANG, nil)\n+ if err != nil {\n+ return fmt.Errorf(\"error waiting the sandbox process: %v\", err)\n+ }\n+ if wpid == 0 {\n+ return fmt.Errorf(\"sandbox is still running\")\n+ }\n+ s.Pid = 0\n+ } else if s.IsRunning() {\nreturn fmt.Errorf(\"sandbox is still running\")\n}\nreturn nil\n"
}
] | Go | Apache License 2.0 | google/gvisor | runsc: Collect zombies of sandbox and gofer processes
And we need to wait a gofer process before cgroup.Uninstall,
because it is running in the sandbox cgroups.
PiperOrigin-RevId: 228904020
Change-Id: Iaf8826d5b9626db32d4057a1c505a8d7daaeb8f9 |
259,885 | 11.01.2019 14:47:14 | 28,800 | 290bcb6de9c4aeff65bbfa06b8addecdbc51ca88 | Require CAP_SYS_CHROOT in ChrootTest.ProcMountsMountinfoNoEscape. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/chroot.cc",
"new_path": "test/syscalls/linux/chroot.cc",
"diff": "@@ -280,6 +280,7 @@ TEST(ChrootTest, ProcMemSelfMapsNoEscapeProcOpen) {\n// /proc/self/mountinfo.\nTEST(ChrootTest, ProcMountsMountinfoNoEscape) {\nSKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_SYS_ADMIN)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_SYS_CHROOT)));\n// We are going to create some mounts and then chroot. In order to be able to\n// unmount the mounts after the test run, we must chdir to the root and use\n"
}
] | Go | Apache License 2.0 | google/gvisor | Require CAP_SYS_CHROOT in ChrootTest.ProcMountsMountinfoNoEscape.
PiperOrigin-RevId: 228949227
Change-Id: I8f47bcd56aab706081218ec7498af8049ccd6d63 |
259,885 | 11.01.2019 14:47:45 | 28,800 | bf65e06c5f00eb41e40dfbb07dda31c6b7ae443e | Clean up some uses of fork() in tests.
Fix a few cases where async-signal-unsafe code is executed in a forked
process pre-execve.
Ensure that the return value of fork() is always checked. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/BUILD",
"new_path": "test/syscalls/linux/BUILD",
"diff": "@@ -1460,7 +1460,6 @@ cc_binary(\n\"//test/util:logging\",\n\"//test/util:multiprocess_util\",\n\"//test/util:signal_util\",\n- \"//test/util:test_main\",\n\"//test/util:test_util\",\n\"//test/util:thread_util\",\n\"@com_google_absl//absl/time\",\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/concurrency.cc",
"new_path": "test/syscalls/linux/concurrency.cc",
"diff": "@@ -72,8 +72,7 @@ TEST(ConcurrencyTest, MultiProcessMultithreaded) {\n}\n});\n- pid_t child_pid;\n- ASSERT_THAT(child_pid = fork(), SyscallSucceeds());\n+ pid_t child_pid = fork();\nif (child_pid == 0) {\n// Busy wait without making any blocking syscalls.\nauto end = absl::Now() + absl::Seconds(5);\n@@ -81,6 +80,7 @@ TEST(ConcurrencyTest, MultiProcessMultithreaded) {\n}\n_exit(0);\n}\n+ ASSERT_THAT(child_pid, SyscallSucceeds());\nabsl::SleepFor(absl::Seconds(1));\n@@ -99,13 +99,13 @@ TEST(ConcurrencyTest, MultiProcessMultithreaded) {\n// never yields.\nTEST(ConcurrencyTest, MultiProcessConcurrency) {\n- pid_t child_pid;\n- ASSERT_THAT(child_pid = fork(), SyscallSucceeds());\n+ pid_t child_pid = fork();\nif (child_pid == 0) {\nwhile (true) {\n}\n__builtin_unreachable();\n}\n+ ASSERT_THAT(child_pid, SyscallSucceeds());\nabsl::SleepFor(absl::Seconds(5));\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/kill.cc",
"new_path": "test/syscalls/linux/kill.cc",
"diff": "@@ -70,7 +70,7 @@ TEST(KillTest, CanKillAllPIDs) {\nsa.sa_sigaction = SigHandler;\nsigfillset(&sa.sa_mask);\nsa.sa_flags = SA_SIGINFO;\n- auto cleanup = ASSERT_NO_ERRNO_AND_VALUE(ScopedSigaction(SIGWINCH, sa));\n+ auto cleanup = ScopedSigaction(SIGWINCH, sa).ValueOrDie();\n// Indicate to the parent that we're ready.\nwrite_fd.reset();\n@@ -81,7 +81,7 @@ TEST(KillTest, CanKillAllPIDs) {\n}\n}\n- EXPECT_THAT(pid, SyscallSucceeds());\n+ ASSERT_THAT(pid, SyscallSucceeds());\nwrite_fd.reset();\n@@ -111,7 +111,7 @@ TEST(KillTest, CannotKillInvalidPID) {\n_exit(0);\n}\n- EXPECT_THAT(fake_pid, SyscallSucceeds());\n+ ASSERT_THAT(fake_pid, SyscallSucceeds());\nint status;\nASSERT_THAT(RetryEINTR(waitpid)(fake_pid, &status, 0),\n@@ -134,7 +134,7 @@ TEST(KillTest, CanKillRemoteProcess) {\n}\n}\n- EXPECT_THAT(pid, SyscallSucceeds());\n+ ASSERT_THAT(pid, SyscallSucceeds());\nEXPECT_THAT(kill(pid, SIGKILL), SyscallSucceeds());\n@@ -182,7 +182,7 @@ TEST(KillTest, SetPgid) {\n}\n}\n- EXPECT_THAT(pid, SyscallSucceeds());\n+ ASSERT_THAT(pid, SyscallSucceeds());\n// Set the child's group and exit.\nASSERT_THAT(setpgid(pid, pid), SyscallSucceeds());\n@@ -208,7 +208,7 @@ TEST(KillTest, ProcessGroups) {\npause();\n}\n}\n- EXPECT_THAT(child, SyscallSucceeds());\n+ ASSERT_THAT(child, SyscallSucceeds());\npid_t other_child = fork();\nif (other_child == 0) {\n@@ -216,6 +216,7 @@ TEST(KillTest, ProcessGroups) {\npause();\n}\n}\n+ ASSERT_THAT(other_child, SyscallSucceeds());\n// Ensure the kill does not succeed without the new group.\nEXPECT_THAT(kill(-child, SIGKILL), SyscallFailsWithErrno(ESRCH));\n@@ -298,7 +299,7 @@ TEST(KillTest, ChildDropsPrivsCannotKill) {\n_exit(0);\n}\n- EXPECT_THAT(pid, SyscallSucceeds());\n+ ASSERT_THAT(pid, SyscallSucceeds());\nint status;\nEXPECT_THAT(RetryEINTR(waitpid)(pid, &status, 0),\n@@ -316,7 +317,7 @@ TEST(KillTest, CanSIGCONTSameSession) {\n_exit(0);\n}\n- EXPECT_THAT(stopped_child, SyscallSucceeds());\n+ ASSERT_THAT(stopped_child, SyscallSucceeds());\n// Put the child in its own process group. The child and parent process\n// groups also share a session.\n@@ -359,7 +360,7 @@ TEST(KillTest, CanSIGCONTSameSession) {\n_exit(0);\n}\n- EXPECT_THAT(stopped_child, SyscallSucceeds());\n+ ASSERT_THAT(stopped_child, SyscallSucceeds());\n// Make sure child exited normally.\nEXPECT_THAT(RetryEINTR(waitpid)(stopped_child, &status, 0),\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/ptrace.cc",
"new_path": "test/syscalls/linux/ptrace.cc",
"diff": "#include \"test/util/test_util.h\"\n#include \"test/util/thread_util.h\"\n+DEFINE_bool(ptrace_test_execve_child, false,\n+ \"If true, run the \"\n+ \"PtraceExecveTest_Execve_GetRegs_PeekUser_SIGKILL_TraceClone_\"\n+ \"TraceExit child workload.\");\n+\nnamespace gvisor {\nnamespace testing {\n@@ -457,26 +462,18 @@ class PtraceExecveTest : public ::testing::TestWithParam<bool> {\n};\nTEST_P(PtraceExecveTest, Execve_GetRegs_PeekUser_SIGKILL_TraceClone_TraceExit) {\n+ ExecveArray const owned_child_argv = {\"/proc/self/exe\",\n+ \"--ptrace_test_execve_child\"};\n+ char* const* const child_argv = owned_child_argv.get();\n+\npid_t const child_pid = fork();\nif (child_pid == 0) {\n- // In child process.\n-\n- // Enable tracing, then raise SIGSTOP and expect our parent to suppress it.\n- TEST_PCHECK(ptrace(PTRACE_TRACEME, 0, 0, 0) == 0);\n- MaybeSave();\n- RaiseSignal(SIGSTOP);\n- MaybeSave();\n-\n- // Call execve in a non-leader thread.\n- ExecveArray const owned_child_argv = {\"/proc/self/exe\"};\n- char* const* const child_argv = owned_child_argv.get();\n- ScopedThread t([&] {\n+ // In child process. The test relies on calling execve() in a non-leader\n+ // thread; pthread_create() isn't async-signal-safe, so the safest way to\n+ // do this is to execve() first, then enable tracing and run the expected\n+ // child process behavior in the new subprocess.\nexecve(child_argv[0], child_argv, /* envp = */ nullptr);\n- TEST_CHECK_MSG(false, \"Survived execve? (thread)\");\n- });\n- t.Join();\n- TEST_CHECK_MSG(false, \"Survived execve? (main)\");\n- _exit(1);\n+ TEST_PCHECK_MSG(false, \"Survived execve to test child\");\n}\n// In parent process.\nASSERT_THAT(child_pid, SyscallSucceeds());\n@@ -595,6 +592,28 @@ TEST_P(PtraceExecveTest, Execve_GetRegs_PeekUser_SIGKILL_TraceClone_TraceExit) {\n<< \" status \" << status;\n}\n+[[noreturn]] void RunExecveChild() {\n+ // Enable tracing, then raise SIGSTOP and expect our parent to suppress it.\n+ TEST_PCHECK(ptrace(PTRACE_TRACEME, 0, 0, 0) == 0);\n+ MaybeSave();\n+ RaiseSignal(SIGSTOP);\n+ MaybeSave();\n+\n+ // Call execve() in a non-leader thread. As long as execve() succeeds, what\n+ // exactly we execve() shouldn't really matter, since the tracer should kill\n+ // us after execve() completes.\n+ ScopedThread t([&] {\n+ ExecveArray const owned_child_argv = {\"/proc/self/exe\",\n+ \"--this_flag_shouldnt_exist\"};\n+ char* const* const child_argv = owned_child_argv.get();\n+ execve(child_argv[0], child_argv, /* envp = */ nullptr);\n+ TEST_PCHECK_MSG(false, \"Survived execve? (thread)\");\n+ });\n+ t.Join();\n+ TEST_CHECK_MSG(false, \"Survived execve? (main)\");\n+ _exit(1);\n+}\n+\nINSTANTIATE_TEST_CASE_P(TraceExec, PtraceExecveTest, ::testing::Bool());\n// This test has expectations on when syscall-enter/exit-stops occur that are\n@@ -946,3 +965,13 @@ TEST(PtraceTest, ERESTART_NoRandomSave) {\n} // namespace testing\n} // namespace gvisor\n+\n+int main(int argc, char** argv) {\n+ gvisor::testing::TestInit(&argc, &argv);\n+\n+ if (FLAGS_ptrace_test_execve_child) {\n+ gvisor::testing::RunExecveChild();\n+ }\n+\n+ return RUN_ALL_TESTS();\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/sync_file_range.cc",
"new_path": "test/syscalls/linux/sync_file_range.cc",
"diff": "@@ -70,6 +70,7 @@ TEST(SyncFileRangeTest, CannotSyncFileRangeOnUnopenedFd) {\nTEST_PCHECK(errno == EBADF);\n_exit(0);\n}\n+ ASSERT_THAT(pid, SyscallSucceeds());\nint status = 0;\nASSERT_THAT(waitpid(pid, &status, 0), SyscallSucceedsWithValue(pid));\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/timers.cc",
"new_path": "test/syscalls/linux/timers.cc",
"diff": "@@ -92,6 +92,7 @@ TEST(TimerTest, ProcessKilledOnCPUSoftLimit) {\nfor (;;) {\n}\n}\n+ ASSERT_THAT(pid, SyscallSucceeds());\nauto c = Cleanup([pid] {\nint status;\nEXPECT_THAT(waitpid(pid, &status, 0), SyscallSucceedsWithValue(pid));\n@@ -150,6 +151,7 @@ TEST(TimerTest, ProcessPingedRepeatedlyAfterCPUSoftLimit) {\nfor (;;) {\n}\n}\n+ ASSERT_THAT(pid, SyscallSucceeds());\nauto c = Cleanup([pid] {\nint status;\nEXPECT_THAT(waitpid(pid, &status, 0), SyscallSucceedsWithValue(pid));\n@@ -195,6 +197,7 @@ TEST(TimerTest, ProcessKilledOnCPUHardLimit) {\nfor (;;) {\n}\n}\n+ ASSERT_THAT(pid, SyscallSucceeds());\nauto c = Cleanup([pid] {\nint status;\nEXPECT_THAT(waitpid(pid, &status, 0), SyscallSucceedsWithValue(pid));\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/wait.cc",
"new_path": "test/syscalls/linux/wait.cc",
"diff": "@@ -547,6 +547,7 @@ TEST_P(WaitSpecificChildTest, AfterChildExecve) {\nconst_cast<char**>(child_argv));\n_exit(errno);\n}\n+ ASSERT_THAT(child, SyscallSucceeds());\nEXPECT_NO_ERRNO(WaitFor(child, 0));\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Clean up some uses of fork() in tests.
- Fix a few cases where async-signal-unsafe code is executed in a forked
process pre-execve.
- Ensure that the return value of fork() is always checked.
PiperOrigin-RevId: 228949310
Change-Id: I3096cb7d7394b8d9ab81b0e0245f2060713ef589 |
259,854 | 14.01.2019 13:06:16 | 28,800 | 003eedea1c66d3ff07b28accb46bbe9abfa8c89c | Deflake RecvLessThanBufferWaitAll. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_stream_blocking.cc",
"new_path": "test/syscalls/linux/socket_stream_blocking.cc",
"diff": "@@ -98,7 +98,10 @@ TEST_P(BlockingStreamSocketPairTest, RecvLessThanBuffer) {\nSyscallSucceedsWithValue(sizeof(sent_data)));\n}\n-TEST_P(BlockingStreamSocketPairTest, RecvLessThanBufferWaitAll) {\n+// Test that MSG_WAITALL causes recv to block until all requested data is\n+// received. Random save can interrupt blocking and cause received data to be\n+// returned, even if the amount received is less than the full requested amount.\n+TEST_P(BlockingStreamSocketPairTest, RecvLessThanBufferWaitAll_NoRandomSave) {\nauto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\nchar sent_data[100];\n@@ -112,6 +115,10 @@ TEST_P(BlockingStreamSocketPairTest, RecvLessThanBufferWaitAll) {\nconst ScopedThread t([&]() {\nabsl::SleepFor(kDuration);\n+\n+ // Don't let saving after the write interrupt the blocking recv.\n+ const DisableSave ds;\n+\nASSERT_THAT(write(sockets->first_fd(), sent_data, sizeof(sent_data)),\nSyscallSucceedsWithValue(sizeof(sent_data)));\n});\n"
}
] | Go | Apache License 2.0 | google/gvisor | Deflake RecvLessThanBufferWaitAll.
PiperOrigin-RevId: 229238781
Change-Id: Ib5a1e46293583efcb09e255fcd400c3fcc53ef1b |
259,948 | 14.01.2019 13:32:31 | 28,800 | 7182b9cf52087bc354104ad2a23fcf4c468ab20e | netstack: release port inline for listening sockets only. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/endpoint.go",
"new_path": "pkg/tcpip/transport/tcp/endpoint.go",
"diff": "@@ -410,18 +410,18 @@ func (e *endpoint) Close() {\ne.mu.Lock()\n- // We always release ports inline so that they are immediately available\n- // for reuse after Close() is called. If also registered, it means this\n- // is a listening socket, so we must unregister as well otherwise the\n- // next user would fail in Listen() when trying to register.\n- if e.isPortReserved {\n- e.stack.ReleasePort(e.effectiveNetProtos, ProtocolNumber, e.id.LocalAddress, e.id.LocalPort)\n- e.isPortReserved = false\n-\n+ // For listening sockets, we always release ports inline so that they\n+ // are immediately available for reuse after Close() is called. If also\n+ // registered, we unregister as well otherwise the next user would fail\n+ // in Listen() when trying to register.\n+ if e.state == stateListen && e.isPortReserved {\nif e.isRegistered {\ne.stack.UnregisterTransportEndpoint(e.boundNICID, e.effectiveNetProtos, ProtocolNumber, e.id, e)\ne.isRegistered = false\n}\n+\n+ e.stack.ReleasePort(e.effectiveNetProtos, ProtocolNumber, e.id.LocalAddress, e.id.LocalPort)\n+ e.isPortReserved = false\n}\n// Either perform the local cleanup or kick the worker to make sure it\n@@ -457,6 +457,12 @@ func (e *endpoint) cleanupLocked() {\nif e.isRegistered {\ne.stack.UnregisterTransportEndpoint(e.boundNICID, e.effectiveNetProtos, ProtocolNumber, e.id, e)\n+ e.isRegistered = false\n+ }\n+\n+ if e.isPortReserved {\n+ e.stack.ReleasePort(e.effectiveNetProtos, ProtocolNumber, e.id.LocalAddress, e.id.LocalPort)\n+ e.isPortReserved = false\n}\ne.route.Release()\n"
}
] | Go | Apache License 2.0 | google/gvisor | netstack: release port inline for listening sockets only.
PiperOrigin-RevId: 229243918
Change-Id: Ie14ef34e66ae851ed080f57b7d26a369a66f7664 |
259,853 | 14.01.2019 14:07:05 | 28,800 | a46b6d453d198b96949342a81750114bfa5a5429 | runsc: set up a minimal chroot from the sandbox process
In this case, new mounts are not created in the host mount namspaces, so
tearDownChroot isn't needed, because chroot will be destroyed with a
sandbox mount namespace.
In additional, pivot_root can't be called instead of chroot. | [
{
"change_type": "MODIFY",
"old_path": "runsc/cmd/BUILD",
"new_path": "runsc/cmd/BUILD",
"diff": "@@ -8,6 +8,7 @@ go_library(\n\"boot.go\",\n\"capability.go\",\n\"checkpoint.go\",\n+ \"chroot.go\",\n\"cmd.go\",\n\"create.go\",\n\"debug.go\",\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/cmd/boot.go",
"new_path": "runsc/cmd/boot.go",
"diff": "@@ -60,6 +60,9 @@ type Boot struct {\n// to the process.\napplyCaps bool\n+ // setUpChroot is set to true if the sandbox is started in an empty root.\n+ setUpRoot bool\n+\n// cpuNum number of CPUs to create inside the sandbox.\ncpuNum int\n@@ -99,6 +102,7 @@ func (b *Boot) SetFlags(f *flag.FlagSet) {\nf.Var(&b.stdioFDs, \"stdio-fds\", \"list of FDs containing sandbox stdin, stdout, and stderr in that order\")\nf.BoolVar(&b.console, \"console\", false, \"set to true if the sandbox should allow terminal ioctl(2) syscalls\")\nf.BoolVar(&b.applyCaps, \"apply-caps\", false, \"if true, apply capabilities defined in the spec to the process\")\n+ f.BoolVar(&b.setUpRoot, \"setup-root\", false, \"if true, set up an empty root for the process\")\nf.IntVar(&b.cpuNum, \"cpu-num\", 0, \"number of CPUs to create inside the sandbox\")\nf.Uint64Var(&b.totalMem, \"total-memory\", 0, \"sets the initial amount of total memory to report back to the container\")\nf.IntVar(&b.userLogFD, \"user-log-fd\", 0, \"file descriptor to write user logs to. 0 means no logging.\")\n@@ -116,6 +120,31 @@ func (b *Boot) Execute(_ context.Context, f *flag.FlagSet, args ...interface{})\n// Ensure that if there is a panic, all goroutine stacks are printed.\ndebug.SetTraceback(\"all\")\n+ if b.setUpRoot {\n+ if err := setUpChroot(); err != nil {\n+ Fatalf(\"error setting up chroot: %v\", err)\n+ }\n+\n+ specutils.ExePath = \"/runsc\"\n+ if !b.applyCaps {\n+ // Remove --setup-root arg to call myself.\n+ var args []string\n+ for _, arg := range os.Args {\n+ if !strings.Contains(arg, \"setup-root\") {\n+ args = append(args, arg)\n+ }\n+ }\n+ // Note that we've already read the spec from the spec FD, and\n+ // we will read it again after the exec call. This works\n+ // because the ReadSpecFromFile function seeks to the beginning\n+ // of the file before reading.\n+ if err := callSelfAsNobody(args); err != nil {\n+ Fatalf(\"%v\", err)\n+ }\n+ panic(\"callSelfAsNobody must never return success\")\n+ }\n+ }\n+\n// Get the spec from the specFD.\nspecFile := os.NewFile(uintptr(b.specFD), \"spec file\")\ndefer specFile.Close()\n@@ -144,7 +173,7 @@ func (b *Boot) Execute(_ context.Context, f *flag.FlagSet, args ...interface{})\n// Remove --apply-caps arg to call myself.\nvar args []string\nfor _, arg := range os.Args {\n- if !strings.Contains(arg, \"apply-caps\") {\n+ if !strings.Contains(arg, \"setup-root\") && !strings.Contains(arg, \"apply-caps\") {\nargs = append(args, arg)\n}\n}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "runsc/cmd/chroot.go",
"diff": "+// Copyright 2019 Google LLC\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package cmd\n+\n+import (\n+ \"fmt\"\n+ \"os\"\n+ \"path/filepath\"\n+ \"syscall\"\n+\n+ \"gvisor.googlesource.com/gvisor/pkg/log\"\n+ \"gvisor.googlesource.com/gvisor/runsc/specutils\"\n+)\n+\n+// chrootBinPath is the location inside the chroot where the runsc binary will\n+// be mounted.\n+const chrootBinPath = \"/runsc\"\n+\n+// mountInChroot creates the destination mount point in the given chroot and\n+// mounts the source.\n+func mountInChroot(chroot, src, dst, typ string, flags uint32) error {\n+ chrootDst := filepath.Join(chroot, dst)\n+ log.Infof(\"Mounting %q at %q\", src, chrootDst)\n+\n+ if err := specutils.Mount(src, chrootDst, typ, flags); err != nil {\n+ return fmt.Errorf(\"error mounting %q at %q: %v\", src, chrootDst, err)\n+ }\n+ return nil\n+}\n+\n+// setUpChroot creates an empty directory with runsc mounted at /runsc and proc\n+// mounted at /proc.\n+func setUpChroot() error {\n+ // We are a new mount namespace, so we can use /tmp as a directory to\n+ // construct a new root.\n+ chroot := os.TempDir()\n+\n+ log.Infof(\"Setting up sandbox chroot in %q\", chroot)\n+\n+ // Convert all shared mounts into slave to be sure that nothing will be\n+ // propagated outside of our namespace.\n+ if err := syscall.Mount(\"\", \"/\", \"\", syscall.MS_SLAVE|syscall.MS_REC, \"\"); err != nil {\n+ return fmt.Errorf(\"error converting mounts: %v\", err)\n+ }\n+\n+ if err := syscall.Mount(\"runsc-root\", chroot, \"tmpfs\", syscall.MS_NOSUID|syscall.MS_NODEV|syscall.MS_NOEXEC, \"\"); err != nil {\n+ return fmt.Errorf(\"error mounting tmpfs in choot: %v\", err)\n+ }\n+\n+ if err := mountInChroot(chroot, \"/proc\", \"/proc\", \"bind\", syscall.MS_BIND|syscall.MS_RDONLY|syscall.MS_REC); err != nil {\n+ return fmt.Errorf(\"error mounting proc in chroot: %v\", err)\n+ }\n+\n+ if err := mountInChroot(chroot, specutils.ExePath, chrootBinPath, \"bind\", syscall.MS_BIND|syscall.MS_RDONLY); err != nil {\n+ return fmt.Errorf(\"error mounting runsc in chroot: %v\", err)\n+ }\n+\n+ if err := os.Chdir(chroot); err != nil {\n+ return fmt.Errorf(\"error changing working directory: %v\", err)\n+ }\n+\n+ if err := syscall.Mount(\"\", chroot, \"\", syscall.MS_REMOUNT|syscall.MS_RDONLY|syscall.MS_BIND, \"\"); err != nil {\n+ return fmt.Errorf(\"error remounting chroot in read-only: %v\", err)\n+ }\n+ // pivot_root(new_root, put_old) moves the root filesystem (old_root)\n+ // of the calling process to the directory put_old and makes new_root\n+ // the new root filesystem of the calling process.\n+ //\n+ // pivot_root(\".\", \".\") makes a mount of the working directory the new\n+ // root filesystem, so it will be moved in \"/\" and then the old_root\n+ // will be moved to \"/\" too. The parent mount of the old_root will be\n+ // new_root, so after umounting the old_root, we will see only\n+ // the new_root in \"/\".\n+ if err := syscall.PivotRoot(\".\", \".\"); err != nil {\n+ return fmt.Errorf(\"error changing root filesystem: %v\", err)\n+ }\n+\n+ if err := syscall.Unmount(\".\", syscall.MNT_DETACH); err != nil {\n+ return fmt.Errorf(\"error umounting the old root file system: %v\", err)\n+ }\n+\n+ return nil\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/cmd/cmd.go",
"new_path": "runsc/cmd/cmd.go",
"diff": "@@ -86,6 +86,28 @@ func setCapsAndCallSelf(args []string, caps *specs.LinuxCapabilities) error {\n}\nlog.Infof(\"Execve %q again, bye!\", binPath)\n- syscall.Exec(binPath, args, []string{})\n- panic(\"unreachable\")\n+ err = syscall.Exec(binPath, args, []string{})\n+ return fmt.Errorf(\"error executing %s: %v\", binPath, err)\n+}\n+\n+// callSelfAsNobody sets UID and GID to nobody and then execve's itself again.\n+func callSelfAsNobody(args []string) error {\n+ // Keep thread locked while user/group are changed.\n+ runtime.LockOSThread()\n+ defer runtime.UnlockOSThread()\n+\n+ const nobody = 65534\n+\n+ if _, _, err := syscall.RawSyscall(syscall.SYS_SETGID, uintptr(nobody), 0, 0); err != 0 {\n+ return fmt.Errorf(\"error setting uid: %v\", err)\n+ }\n+ if _, _, err := syscall.RawSyscall(syscall.SYS_SETUID, uintptr(nobody), 0, 0); err != 0 {\n+ return fmt.Errorf(\"error setting gid: %v\", err)\n+ }\n+\n+ binPath := \"/runsc\"\n+\n+ log.Infof(\"Execve %q again, bye!\", binPath)\n+ err := syscall.Exec(binPath, args, []string{})\n+ return fmt.Errorf(\"error executing %s: %v\", binPath, err)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/sandbox/BUILD",
"new_path": "runsc/sandbox/BUILD",
"diff": "@@ -5,7 +5,6 @@ package(licenses = [\"notice\"]) # Apache 2.0\ngo_library(\nname = \"sandbox\",\nsrcs = [\n- \"chroot.go\",\n\"network.go\",\n\"sandbox.go\",\n],\n"
},
{
"change_type": "DELETE",
"old_path": "runsc/sandbox/chroot.go",
"new_path": null,
"diff": "-// Copyright 2018 Google LLC\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 sandbox\n-\n-import (\n- \"fmt\"\n- \"io/ioutil\"\n- \"os\"\n- \"path/filepath\"\n- \"syscall\"\n-\n- \"gvisor.googlesource.com/gvisor/pkg/log\"\n- \"gvisor.googlesource.com/gvisor/runsc/specutils\"\n-)\n-\n-// chrootBinPath is the location inside the chroot where the runsc binary will\n-// be mounted.\n-const chrootBinPath = \"/runsc\"\n-\n-// mountInChroot creates the destination mount point in the given chroot and\n-// mounts the source.\n-func mountInChroot(chroot, src, dst, typ string, flags uint32) error {\n- chrootDst := filepath.Join(chroot, dst)\n- log.Infof(\"Mounting %q at %q\", src, chrootDst)\n-\n- if err := specutils.Mount(src, chrootDst, typ, flags); err != nil {\n- return fmt.Errorf(\"error mounting %q at %q: %v\", src, chrootDst, err)\n- }\n- return nil\n-}\n-\n-// setUpChroot creates an empty directory with runsc mounted at /runsc and proc\n-// mounted at /proc.\n-func setUpChroot() (string, error) {\n- // Create the chroot directory and make it accessible to all users.\n- chroot, err := ioutil.TempDir(\"\", \"runsc-sandbox-chroot-\")\n- if err != nil {\n- return \"\", fmt.Errorf(\"TempDir() failed: %v\", err)\n- }\n- if err := os.Chmod(chroot, 0777); err != nil {\n- return \"\", fmt.Errorf(\"Chmod(%q) failed: %v\", chroot, err)\n- }\n- log.Infof(\"Setting up sandbox chroot in %q\", chroot)\n-\n- // Mount /proc.\n- if err := mountInChroot(chroot, \"proc\", \"/proc\", \"proc\", syscall.MS_NOSUID|syscall.MS_NODEV|syscall.MS_NOEXEC); err != nil {\n- return \"\", fmt.Errorf(\"error mounting proc in chroot: %v\", err)\n- }\n-\n- // Mount runsc at /runsc in the chroot.\n- binPath, err := specutils.BinPath()\n- if err != nil {\n- return \"\", err\n- }\n- if err := mountInChroot(chroot, binPath, chrootBinPath, \"bind\", syscall.MS_BIND|syscall.MS_RDONLY); err != nil {\n- return \"\", fmt.Errorf(\"error mounting runsc in chroot: %v\", err)\n- }\n-\n- return chroot, nil\n-}\n-\n-// tearDownChroot unmounts /proc and /runsc from the chroot before deleting the\n-// directory.\n-func tearDownChroot(chroot string) error {\n- log.Debugf(\"Removing chroot mounts %q\", chroot)\n-\n- // Unmount /proc.\n- proc := filepath.Join(chroot, \"proc\")\n- if err := syscall.Unmount(proc, 0); err != nil {\n- return fmt.Errorf(\"error unmounting %q: %v\", proc, err)\n- }\n-\n- // Unmount /runsc.\n- exe := filepath.Join(chroot, chrootBinPath)\n- if err := syscall.Unmount(exe, 0); err != nil {\n- return fmt.Errorf(\"error unmounting %q: %v\", exe, err)\n- }\n-\n- // Remove chroot directory.\n- if err := os.RemoveAll(chroot); err != nil {\n- return fmt.Errorf(\"error removing %q: %v\", chroot, err)\n- }\n-\n- return nil\n-}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/sandbox/sandbox.go",
"new_path": "runsc/sandbox/sandbox.go",
"diff": "@@ -56,10 +56,6 @@ type Sandbox struct {\n// is not running.\nPid int `json:\"pid\"`\n- // Chroot is the path to the chroot directory that the sandbox process\n- // is running in.\n- Chroot string `json:\"chroot\"`\n-\n// Cgroup has the cgroup configuration for the sandbox.\nCgroup *cgroup.Cgroup `json:\"cgroup\"`\n@@ -491,6 +487,17 @@ func (s *Sandbox) createSandboxProcess(spec *specs.Spec, conf *boot.Config, bund\n// rules.\ncmd.Args = append(cmd.Args, \"--apply-caps=true\")\n+ // If we have CAP_SYS_ADMIN, we can create an empty chroot and\n+ // bind-mount the executable inside it.\n+ if conf.TestOnlyAllowRunAsCurrentUserWithoutChroot {\n+ log.Warningf(\"Running sandbox in test mode without chroot. This is only safe in tests!\")\n+\n+ } else if specutils.HasCapabilities(capability.CAP_SYS_ADMIN) {\n+ log.Infof(\"Sandbox will be started in minimal chroot\")\n+ cmd.Args = append(cmd.Args, \"--setup-root\")\n+ } else {\n+ return fmt.Errorf(\"can't run sandbox process in minimal chroot since we don't have CAP_SYS_ADMIN\")\n+ }\n} else {\nlog.Infof(\"Sandbox will be started in new user namespace\")\nnss = append(nss, specs.LinuxNamespace{Type: specs.UserNamespace})\n@@ -499,50 +506,53 @@ func (s *Sandbox) createSandboxProcess(spec *specs.Spec, conf *boot.Config, bund\n// as user nobody.\nif conf.TestOnlyAllowRunAsCurrentUserWithoutChroot {\nlog.Warningf(\"Running sandbox in test mode as current user (uid=%d gid=%d). This is only safe in tests!\", os.Getuid(), os.Getgid())\n+ log.Warningf(\"Running sandbox in test mode without chroot. This is only safe in tests!\")\n} else if specutils.HasCapabilities(capability.CAP_SETUID, capability.CAP_SETGID) {\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: 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\nconst nobody = 65534\n- cmd.SysProcAttr.UidMappings = []syscall.SysProcIDMap{{\n+ cmd.SysProcAttr.UidMappings = []syscall.SysProcIDMap{\n+ {\n+ ContainerID: int(0),\n+ HostID: int(nobody - 1),\n+ Size: int(1),\n+ },\n+ {\nContainerID: int(nobody),\nHostID: int(nobody),\nSize: int(1),\n- }}\n- cmd.SysProcAttr.GidMappings = []syscall.SysProcIDMap{{\n+ },\n+ }\n+ cmd.SysProcAttr.GidMappings = []syscall.SysProcIDMap{\n+ {\nContainerID: int(nobody),\nHostID: int(nobody),\nSize: int(1),\n- }}\n+ },\n+ }\n// Set credentials to run as user and group nobody.\ncmd.SysProcAttr.Credential = &syscall.Credential{\n- Uid: nobody,\n+ Uid: 0,\nGid: nobody,\n}\n+ cmd.Args = append(cmd.Args, \"--setup-root\")\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}\n- // If we have CAP_SYS_ADMIN, we can create an empty chroot and\n- // bind-mount the executable inside it.\n- if conf.TestOnlyAllowRunAsCurrentUserWithoutChroot {\n- log.Warningf(\"Running sandbox in test mode without chroot. This is only safe in tests!\")\n-\n- } else if specutils.HasCapabilities(capability.CAP_SYS_ADMIN, capability.CAP_SYS_CHROOT) {\n- log.Infof(\"Sandbox will be started in minimal chroot\")\n- chroot, err := setUpChroot()\n- if err != nil {\n- return fmt.Errorf(\"error setting up chroot: %v\", err)\n- }\n- s.Chroot = chroot // Remember path so it can cleaned up.\n- cmd.SysProcAttr.Chroot = chroot\n- cmd.Dir = \"/\"\n- cmd.Args[0] = \"/runsc\"\n- cmd.Path = \"/runsc\"\n-\n- } else {\n- return fmt.Errorf(\"can't run sandbox process in minimal chroot since we don't have CAP_SYS_ADMIN and CAP_SYS_CHROOT\")\n- }\n+ cmd.Args[0] = \"runsc-sandbox\"\nif s.Cgroup != nil {\ncpuNum, err := s.Cgroup.NumCPU()\n@@ -676,12 +686,6 @@ func (s *Sandbox) destroy() error {\n}\n}\n- if s.Chroot != \"\" {\n- if err := tearDownChroot(s.Chroot); err != nil {\n- return err\n- }\n- }\n-\nreturn nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/test/root/chroot_test.go",
"new_path": "runsc/test/root/chroot_test.go",
"diff": "@@ -52,12 +52,13 @@ func TestChroot(t *testing.T) {\n}\n// Check that sandbox is chroot'ed.\n- chroot, err := filepath.EvalSymlinks(filepath.Join(\"/proc\", strconv.Itoa(pid), \"root\"))\n+ procRoot := filepath.Join(\"/proc\", strconv.Itoa(pid), \"root\")\n+ chroot, err := filepath.EvalSymlinks(procRoot)\nif err != nil {\nt.Fatalf(\"error resolving /proc/<pid>/root symlink: %v\", err)\n}\n- if want := \"/tmp/runsc-sandbox-chroot-\"; !strings.HasPrefix(chroot, want) {\n- t.Errorf(\"sandbox is not chroot'd, it should be inside: %q, got: %q\", want, chroot)\n+ if chroot != \"/\" {\n+ t.Errorf(\"sandbox is not chroot'd, it should be inside: /, got: %q\", chroot)\n}\npath, err := filepath.EvalSymlinks(filepath.Join(\"/proc\", strconv.Itoa(pid), \"cwd\"))\n@@ -68,12 +69,12 @@ func TestChroot(t *testing.T) {\nt.Errorf(\"sandbox current dir is wrong, want: %q, got: %q\", chroot, path)\n}\n- fi, err := ioutil.ReadDir(chroot)\n+ fi, err := ioutil.ReadDir(procRoot)\nif err != nil {\nt.Fatalf(\"error listing %q: %v\", chroot, err)\n}\nif want, got := 2, len(fi); want != got {\n- t.Fatalf(\"chroot dir got %d entries, want %d\", want, got)\n+ t.Fatalf(\"chroot dir got %d entries, want %d\", got, want)\n}\n// chroot dir is prepared by runsc and should contains only the executable\n@@ -85,11 +86,6 @@ func TestChroot(t *testing.T) {\n}\nd.CleanUp()\n-\n- // Check that chroot directory was cleaned up.\n- if _, err := os.Stat(chroot); err == nil || !os.IsNotExist(err) {\n- t.Errorf(\"chroot directory %q was not deleted: %v\", chroot, err)\n- }\n}\nfunc TestChrootGofer(t *testing.T) {\n"
}
] | Go | Apache License 2.0 | google/gvisor | runsc: set up a minimal chroot from the sandbox process
In this case, new mounts are not created in the host mount namspaces, so
tearDownChroot isn't needed, because chroot will be destroyed with a
sandbox mount namespace.
In additional, pivot_root can't be called instead of chroot.
PiperOrigin-RevId: 229250871
Change-Id: I765bdb587d0b8287a6a8efda8747639d37c7e7b6 |
259,853 | 14.01.2019 16:11:13 | 28,800 | 343ebe9789087b099ea7feae19879f5c24e59bf1 | Fix a few compilation warnings
test/syscalls/linux/wait.cc:626:8: warning: lambda capture 'this' is not
used
302
[this, stack] { ASSERT_THAT(FreeStack(stack), SyscallSucceeds()); });
303
^~~~~
test/syscalls/linux/priority.cc:195:17: warning: lambda capture
'kParentPriority' is not required to be captured for this use
273
ScopedThread([kParentPriority, kChildPriority]() {
274
^~~~~~~~~~~~~~~~ | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/priority.cc",
"new_path": "test/syscalls/linux/priority.cc",
"diff": "@@ -192,7 +192,7 @@ TEST(GetpriorityTest, CloneMaintainsPriority) {\nASSERT_THAT(setpriority(PRIO_PROCESS, getpid(), kParentPriority),\nSyscallSucceeds());\n- ScopedThread([kParentPriority, kChildPriority]() {\n+ ScopedThread th([]() {\n// Check that priority equals that of parent thread\npid_t my_tid;\nEXPECT_THAT(my_tid = syscall(__NR_gettid), SyscallSucceeds());\n@@ -203,6 +203,7 @@ TEST(GetpriorityTest, CloneMaintainsPriority) {\nEXPECT_THAT(setpriority(PRIO_PROCESS, my_tid, kChildPriority),\nSyscallSucceeds());\n});\n+ th.Join();\n// Check that parent's priority reemained the same even though\n// the child's priority was altered\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/wait.cc",
"new_path": "test/syscalls/linux/wait.cc",
"diff": "@@ -201,8 +201,8 @@ TEST_P(WaitAnyChildTest, MultipleFork) {\nTEST_P(WaitAnyChildTest, CloneSIGCHLD) {\nuintptr_t stack;\nASSERT_THAT(stack = AllocStack(), SyscallSucceeds());\n- auto free = Cleanup(\n- [this, stack] { ASSERT_THAT(FreeStack(stack), SyscallSucceeds()); });\n+ auto free =\n+ Cleanup([stack] { ASSERT_THAT(FreeStack(stack), SyscallSucceeds()); });\nint child;\nASSERT_THAT(child = CloneAndExit(0, stack, SIGCHLD), SyscallSucceeds());\n@@ -217,8 +217,8 @@ TEST_P(WaitAnyChildTest, ForkAndClone) {\nuintptr_t stack;\nASSERT_THAT(stack = AllocStack(), SyscallSucceeds());\n- auto free = Cleanup(\n- [this, stack] { ASSERT_THAT(FreeStack(stack), SyscallSucceeds()); });\n+ auto free =\n+ Cleanup([stack] { ASSERT_THAT(FreeStack(stack), SyscallSucceeds()); });\nint thread;\n// Send SIGCHLD for normal wait semantics.\n@@ -438,8 +438,8 @@ TEST_P(WaitSpecificChildTest, AfterExit) {\nTEST_P(WaitSpecificChildTest, CloneSIGCHLD) {\nuintptr_t stack;\nASSERT_THAT(stack = AllocStack(), SyscallSucceeds());\n- auto free = Cleanup(\n- [this, stack] { ASSERT_THAT(FreeStack(stack), SyscallSucceeds()); });\n+ auto free =\n+ Cleanup([stack] { ASSERT_THAT(FreeStack(stack), SyscallSucceeds()); });\nint child;\nASSERT_THAT(child = CloneAndExit(0, stack, SIGCHLD), SyscallSucceeds());\n@@ -453,8 +453,8 @@ TEST_P(WaitSpecificChildTest, CloneSIGCHLD) {\nTEST_P(WaitSpecificChildTest, CloneNoSIGCHLD) {\nuintptr_t stack;\nASSERT_THAT(stack = AllocStack(), SyscallSucceeds());\n- auto free = Cleanup(\n- [this, stack] { ASSERT_THAT(FreeStack(stack), SyscallSucceeds()); });\n+ auto free =\n+ Cleanup([stack] { ASSERT_THAT(FreeStack(stack), SyscallSucceeds()); });\nint child;\nASSERT_THAT(child = CloneAndExit(0, stack, 0), SyscallSucceeds());\n@@ -469,8 +469,8 @@ TEST_P(WaitSpecificChildTest, CloneNoSIGCHLD) {\nTEST_P(WaitSpecificChildTest, CloneAfterExit) {\nuintptr_t stack;\nASSERT_THAT(stack = AllocStack(), SyscallSucceeds());\n- auto free = Cleanup(\n- [this, stack] { ASSERT_THAT(FreeStack(stack), SyscallSucceeds()); });\n+ auto free =\n+ Cleanup([stack] { ASSERT_THAT(FreeStack(stack), SyscallSucceeds()); });\nint child;\n// Send SIGCHLD for normal wait semantics.\n@@ -485,8 +485,8 @@ TEST_P(WaitSpecificChildTest, CloneAfterExit) {\nTEST_P(WaitSpecificChildTest, CloneThread) {\nuintptr_t stack;\nASSERT_THAT(stack = AllocStack(), SyscallSucceeds());\n- auto free = Cleanup(\n- [this, stack] { ASSERT_THAT(FreeStack(stack), SyscallSucceeds()); });\n+ auto free =\n+ Cleanup([stack] { ASSERT_THAT(FreeStack(stack), SyscallSucceeds()); });\nint child;\nASSERT_THAT(child = CloneAndExit(15, stack, CLONE_THREAD), SyscallSucceeds());\n@@ -521,8 +521,8 @@ TEST_P(WaitSpecificChildTest, AfterChildExecve) {\nuintptr_t stack;\nASSERT_THAT(stack = AllocStack(), SyscallSucceeds());\n- auto free = Cleanup(\n- [this, stack] { ASSERT_THAT(FreeStack(stack), SyscallSucceeds()); });\n+ auto free =\n+ Cleanup([stack] { ASSERT_THAT(FreeStack(stack), SyscallSucceeds()); });\npid_t const child = fork();\nif (child == 0) {\n@@ -622,8 +622,8 @@ TEST(WaitTest, SignalExit) {\nTEST(WaitTest, CloneWCLONE) {\nuintptr_t stack;\nASSERT_THAT(stack = AllocStack(), SyscallSucceeds());\n- auto free = Cleanup(\n- [this, stack] { ASSERT_THAT(FreeStack(stack), SyscallSucceeds()); });\n+ auto free =\n+ Cleanup([stack] { ASSERT_THAT(FreeStack(stack), SyscallSucceeds()); });\nint child;\nASSERT_THAT(child = CloneAndExit(0, stack, 0), SyscallSucceeds());\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix a few compilation warnings
test/syscalls/linux/wait.cc:626:8: warning: lambda capture 'this' is not
used
302
[this, stack] { ASSERT_THAT(FreeStack(stack), SyscallSucceeds()); });
303
^~~~~
test/syscalls/linux/priority.cc:195:17: warning: lambda capture
'kParentPriority' is not required to be captured for this use
273
ScopedThread([kParentPriority, kChildPriority]() {
274
^~~~~~~~~~~~~~~~
PiperOrigin-RevId: 229275900
Change-Id: I6f0c88efc7891c6c729378a2fa70f70b1b9046a7 |
259,944 | 15.01.2019 04:54:36 | 28,800 | c120d7ee2d46a93551075667a01a15bdec8ec1a9 | Use cni v0.7.0.
Use cni v0.7.0 in the integration test. | [
{
"change_type": "MODIFY",
"old_path": "test/e2e/containerd-install.sh",
"new_path": "test/e2e/containerd-install.sh",
"diff": "wget -q --https-only \\\nhttps://github.com/containerd/containerd/releases/download/v${CONTAINERD_VERSION}/containerd-${CONTAINERD_VERSION}.linux-amd64.tar.gz \\\n- https://github.com/containernetworking/plugins/releases/download/v0.6.0/cni-plugins-amd64-v0.6.0.tgz\n+ https://github.com/containernetworking/plugins/releases/download/v0.7.0/cni-plugins-amd64-v0.7.0.tgz\nsudo mkdir -p /etc/containerd /etc/cni/net.d /opt/cni/bin\n-sudo tar -xvf cni-plugins-amd64-v0.6.0.tgz -C /opt/cni/bin/\n+sudo tar -xvf cni-plugins-amd64-v0.7.0.tgz -C /opt/cni/bin/\nsudo tar -xvf containerd-${CONTAINERD_VERSION}.linux-amd64.tar.gz -C /\ncat <<EOF | sudo tee /etc/cni/net.d/10-bridge.conf\n"
}
] | Go | Apache License 2.0 | google/gvisor | Use cni v0.7.0. (#11)
Use cni v0.7.0 in the integration test.
Signed-off-by: Lantao Liu <[email protected]> |
259,944 | 15.01.2019 04:55:38 | 28,800 | f39907aa5d3d1b4ffb2dc0bb08954da1dea6f0b8 | Port containerd fix
Adds a timeout and cancel to shim fifo open | [
{
"change_type": "MODIFY",
"old_path": "pkg/proc/exec.go",
"new_path": "pkg/proc/exec.go",
"diff": "@@ -191,6 +191,12 @@ func (e *execProcess) start(ctx context.Context) (err error) {\ne.stdin = sc\n}\nvar copyWaitGroup sync.WaitGroup\n+ ctx, cancel := context.WithTimeout(ctx, 30*time.Second)\n+ defer func() {\n+ if err != nil {\n+ cancel()\n+ }\n+ }()\nif socket != nil {\nconsole, err := socket.ReceiveMaster()\nif err != nil {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/proc/init.go",
"new_path": "pkg/proc/init.go",
"diff": "@@ -106,11 +106,8 @@ func New(id string, runtime *runsc.Runsc, stdio proc.Stdio) *Init {\n}\n// Create the process with the provided config\n-func (p *Init) Create(ctx context.Context, r *CreateConfig) error {\n- var (\n- err error\n- socket *runc.Socket\n- )\n+func (p *Init) Create(ctx context.Context, r *CreateConfig) (err error) {\n+ var socket *runc.Socket\nif r.Terminal {\nif socket, err = runc.NewTempConsoleSocket(); err != nil {\nreturn errors.Wrap(err, \"failed to create OCI runtime console socket\")\n@@ -149,6 +146,12 @@ func (p *Init) Create(ctx context.Context, r *CreateConfig) error {\np.closers = append(p.closers, sc)\n}\nvar copyWaitGroup sync.WaitGroup\n+ ctx, cancel := context.WithTimeout(ctx, 30*time.Second)\n+ defer func() {\n+ if err != nil {\n+ cancel()\n+ }\n+ }()\nif socket != nil {\nconsole, err := socket.ReceiveMaster()\nif err != nil {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Port containerd fix https://github.com/containerd/containerd/pull/2877. (#12)
Adds a timeout and cancel to shim fifo open
Signed-off-by: Lantao Liu <[email protected]> |
259,872 | 15.01.2019 11:14:59 | 28,800 | 6c117a01e97b5604dc474cf02269cf03fc797af8 | Set end of subslice as begin of next subslice
syscall test split testcase via shard count, reset
high bound as begin of next subslice, cause the slice
is half-open range. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/syscall_test_runner.go",
"new_path": "test/syscalls/syscall_test_runner.go",
"diff": "@@ -271,7 +271,8 @@ func main() {\n// Calculate subslice of tests to run.\nshardSize := int(math.Ceil(float64(len(testCases)) / float64(total)))\nbegin := index * shardSize\n- end := ((index + 1) * shardSize) - 1\n+ // Set end as begin of next subslice.\n+ end := ((index + 1) * shardSize)\nif begin > len(testCases) {\n// Nothing to run.\nreturn\n"
}
] | Go | Apache License 2.0 | google/gvisor | Set end of subslice as begin of next subslice
syscall test split testcase via shard count, reset
high bound as begin of next subslice, cause the slice
is half-open range.
Change-Id: I1954f57c93cbfd9be518153315da305a2de377a0
PiperOrigin-RevId: 229405199 |
259,992 | 15.01.2019 14:12:19 | 28,800 | 92cf3764e032740f0c84a1b242c54b99f45a6bf0 | Create working directory if it doesn't yet exist | [
{
"change_type": "MODIFY",
"old_path": "runsc/container/container_test.go",
"new_path": "runsc/container/container_test.go",
"diff": "@@ -1699,6 +1699,27 @@ func TestDestroyStarting(t *testing.T) {\n}\n}\n+func TestCreateWorkingDir(t *testing.T) {\n+ for _, conf := range configs(overlay) {\n+ t.Logf(\"Running test with conf: %+v\", conf)\n+\n+ tmpDir, err := ioutil.TempDir(testutil.TmpDir(), \"cwd-create\")\n+ if err != nil {\n+ t.Fatalf(\"ioutil.TempDir() failed: %v\", err)\n+ }\n+ dir := path.Join(tmpDir, \"new/working/dir\")\n+\n+ // touch will fail if the directory doesn't exist.\n+ spec := testutil.NewSpecWithArgs(\"/bin/touch\", path.Join(dir, \"file\"))\n+ spec.Process.Cwd = dir\n+ spec.Root.Readonly = true\n+\n+ if err := run(spec, conf); err != nil {\n+ t.Fatalf(\"Error running container: %v\", err)\n+ }\n+ }\n+}\n+\n// executeSync synchronously executes a new process.\nfunc (cont *Container) executeSync(args *control.ExecArgs) (syscall.WaitStatus, error) {\npid, err := cont.Execute(args)\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/container/fs.go",
"new_path": "runsc/container/fs.go",
"diff": "@@ -87,7 +87,7 @@ func setupFS(spec *specs.Spec, conf *boot.Config, bundleDir string) ([]specs.Mou\n// container.\ndst, err := resolveSymlinks(spec.Root.Path, m.Destination)\nif err != nil {\n- return nil, fmt.Errorf(\"failed to resolve symlinks: %v\", err)\n+ return nil, fmt.Errorf(\"resolving symlinks to %q: %v\", m.Destination, err)\n}\nflags := optionsToFlags(m.Options)\n@@ -113,6 +113,16 @@ func setupFS(spec *specs.Spec, conf *boot.Config, bundleDir string) ([]specs.Mou\nrv = append(rv, cpy)\n}\n+ if spec.Process.Cwd != \"\" {\n+ dst, err := resolveSymlinks(spec.Root.Path, spec.Process.Cwd)\n+ if err != nil {\n+ return nil, fmt.Errorf(\"resolving symlinks to %q: %v\", spec.Process.Cwd, err)\n+ }\n+ if err := os.MkdirAll(dst, 0755); err != nil {\n+ return nil, err\n+ }\n+ }\n+\n// If root is read only, check if it needs to be remounted as readonly.\nif spec.Root.Readonly {\nisMountPoint, readonly, err := mountInfo(spec.Root.Path)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Create working directory if it doesn't yet exist
PiperOrigin-RevId: 229438125
Change-Id: I58eb0d10178d1adfc709d7b859189d1acbcb2f22 |
259,985 | 18.01.2019 10:01:08 | 28,800 | 8d7c10e90840cfecf53089e7cc3507cac2804fd1 | Display /proc/net entries for all network configurations.
Most of the entries are stubbed out at the moment, but even those were
only displayed if IPv6 support was enabled. The entries should be
displayed with IPv4-support only, and with only loopback devices. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/proc/net.go",
"new_path": "pkg/sentry/fs/proc/net.go",
"diff": "@@ -29,17 +29,16 @@ import (\n// newNet creates a new proc net entry.\nfunc (p *proc) newNetDir(ctx context.Context, msrc *fs.MountSource) *fs.Inode {\nvar contents map[string]*fs.Inode\n- if s := p.k.NetworkStack(); s != nil && s.SupportsIPv6() {\n+ if s := p.k.NetworkStack(); s != nil {\ncontents = map[string]*fs.Inode{\n\"dev\": seqfile.NewSeqFileInode(ctx, &netDev{s: s}, msrc),\n- \"if_inet6\": seqfile.NewSeqFileInode(ctx, &ifinet6{s: s}, msrc),\n// The following files are simple stubs until they are\n// implemented in netstack, if the file contains a\n// header the stub is just the header otherwise it is\n// an empty file.\n\"arp\": newStaticProcInode(ctx, msrc, []byte(\"IP address HW type Flags HW address Mask Device\")),\n- \"ipv6_route\": newStaticProcInode(ctx, msrc, []byte(\"\")),\n+\n\"netlink\": newStaticProcInode(ctx, msrc, []byte(\"sk Eth Pid Groups Rmem Wmem Dump Locks Drops Inode\")),\n\"netstat\": newStaticProcInode(ctx, msrc, []byte(\"TcpExt: SyncookiesSent SyncookiesRecv SyncookiesFailed EmbryonicRsts PruneCalled RcvPruned OfoPruned OutOfWindowIcmps LockDroppedIcmps ArpFilter TW TWRecycled TWKilled PAWSPassive PAWSActive PAWSEstab DelayedACKs DelayedACKLocked DelayedACKLost ListenOverflows ListenDrops TCPPrequeued TCPDirectCopyFromBacklog TCPDirectCopyFromPrequeue TCPPrequeueDropped TCPHPHits TCPHPHitsToUser TCPPureAcks TCPHPAcks TCPRenoRecovery TCPSackRecovery TCPSACKReneging TCPFACKReorder TCPSACKReorder TCPRenoReorder TCPTSReorder TCPFullUndo TCPPartialUndo TCPDSACKUndo TCPLossUndo TCPLostRetransmit TCPRenoFailures TCPSackFailures TCPLossFailures TCPFastRetrans TCPForwardRetrans TCPSlowStartRetrans TCPTimeouts TCPLossProbes TCPLossProbeRecovery TCPRenoRecoveryFail TCPSackRecoveryFail TCPSchedulerFailed TCPRcvCollapsed TCPDSACKOldSent TCPDSACKOfoSent TCPDSACKRecv TCPDSACKOfoRecv TCPAbortOnData TCPAbortOnClose TCPAbortOnMemory TCPAbortOnTimeout TCPAbortOnLinger TCPAbortFailed TCPMemoryPressures TCPSACKDiscard TCPDSACKIgnoredOld TCPDSACKIgnoredNoUndo TCPSpuriousRTOs TCPMD5NotFound TCPMD5Unexpected TCPMD5Failure TCPSackShifted TCPSackMerged TCPSackShiftFallback TCPBacklogDrop TCPMinTTLDrop TCPDeferAcceptDrop IPReversePathFilter TCPTimeWaitOverflow TCPReqQFullDoCookies TCPReqQFullDrop TCPRetransFail TCPRcvCoalesce TCPOFOQueue TCPOFODrop TCPOFOMerge TCPChallengeACK TCPSYNChallenge TCPFastOpenActive TCPFastOpenActiveFail TCPFastOpenPassive TCPFastOpenPassiveFail TCPFastOpenListenOverflow TCPFastOpenCookieReqd TCPSpuriousRtxHostQueues BusyPollRxPackets TCPAutoCorking TCPFromZeroWindowAdv TCPToZeroWindowAdv TCPWantZeroWindowAdv TCPSynRetrans TCPOrigDataSent TCPHystartTrainDetect TCPHystartTrainCwnd TCPHystartDelayDetect TCPHystartDelayCwnd TCPACKSkippedSynRecv TCPACKSkippedPAWS TCPACKSkippedSeq TCPACKSkippedFinWait2 TCPACKSkippedTimeWait TCPACKSkippedChallenge TCPWinProbe TCPKeepAlive TCPMTUPFail TCPMTUPSuccess\")),\n\"packet\": newStaticProcInode(ctx, msrc, []byte(\"sk RefCnt Type Proto Iface R Rmem User Inode\")),\n@@ -51,9 +50,15 @@ func (p *proc) newNetDir(ctx context.Context, msrc *fs.MountSource) *fs.Inode {\n\"ptype\": newStaticProcInode(ctx, msrc, []byte(\"Type Device Function\")),\n\"route\": newStaticProcInode(ctx, msrc, []byte(\"Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT\")),\n\"tcp\": newStaticProcInode(ctx, msrc, []byte(\" sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode\")),\n- \"tcp6\": newStaticProcInode(ctx, msrc, []byte(\" sl local_address remote_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode\")),\n+\n\"udp\": newStaticProcInode(ctx, msrc, []byte(\" sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode ref pointer drops\")),\n- \"udp6\": newStaticProcInode(ctx, msrc, []byte(\" sl local_address remote_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode\")),\n+ }\n+\n+ if s.SupportsIPv6() {\n+ contents[\"if_inet6\"] = seqfile.NewSeqFileInode(ctx, &ifinet6{s: s}, msrc)\n+ contents[\"ipv6_route\"] = newStaticProcInode(ctx, msrc, []byte(\"\"))\n+ contents[\"tcp6\"] = newStaticProcInode(ctx, msrc, []byte(\" sl local_address remote_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode\"))\n+ contents[\"udp6\"] = newStaticProcInode(ctx, msrc, []byte(\" sl local_address remote_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode\"))\n}\n}\nd := ramfs.NewDir(ctx, contents, fs.RootOwner, fs.FilePermsFromMode(0555))\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/proc/proc.go",
"new_path": "pkg/sentry/fs/proc/proc.go",
"diff": "@@ -83,9 +83,9 @@ func New(ctx context.Context, msrc *fs.MountSource) (*fs.Inode, error) {\n// If we're using rpcinet we will let it manage /proc/net.\nif _, ok := p.k.NetworkStack().(*rpcinet.Stack); ok {\n- contents[\"net\"] = newRPCInetProcNet(ctx, msrc)\n+ p.AddChild(ctx, \"net\", newRPCInetProcNet(ctx, msrc))\n} else {\n- contents[\"net\"] = p.newNetDir(ctx, msrc)\n+ p.AddChild(ctx, \"net\", p.newNetDir(ctx, msrc))\n}\nreturn newProcInode(p, msrc, fs.SpecialDirectory, nil), nil\n"
}
] | Go | Apache License 2.0 | google/gvisor | Display /proc/net entries for all network configurations.
Most of the entries are stubbed out at the moment, but even those were
only displayed if IPv6 support was enabled. The entries should be
displayed with IPv4-support only, and with only loopback devices.
PiperOrigin-RevId: 229946441
Change-Id: I18afaa3af386322787f91bf9d168ab66c01d5a4c |
259,853 | 18.01.2019 12:16:24 | 28,800 | c063a1350f4ac6249fb26e6125c9cc99db14263b | runsc: create a new proc mount if the sandbox process is running in a new pidns | [
{
"change_type": "MODIFY",
"old_path": "runsc/cmd/boot.go",
"new_path": "runsc/cmd/boot.go",
"diff": "@@ -75,6 +75,9 @@ type Boot struct {\n// startSyncFD is the file descriptor to synchronize runsc and sandbox.\nstartSyncFD int\n+\n+ // pidns is set if the sanadbox is in its own pid namespace.\n+ pidns bool\n}\n// Name implements subcommands.Command.Name.\n@@ -103,6 +106,7 @@ func (b *Boot) SetFlags(f *flag.FlagSet) {\nf.BoolVar(&b.console, \"console\", false, \"set to true if the sandbox should allow terminal ioctl(2) syscalls\")\nf.BoolVar(&b.applyCaps, \"apply-caps\", false, \"if true, apply capabilities defined in the spec to the process\")\nf.BoolVar(&b.setUpRoot, \"setup-root\", false, \"if true, set up an empty root for the process\")\n+ f.BoolVar(&b.pidns, \"pidns\", false, \"if true, the sandbox is in its own PID namespace\")\nf.IntVar(&b.cpuNum, \"cpu-num\", 0, \"number of CPUs to create inside the sandbox\")\nf.Uint64Var(&b.totalMem, \"total-memory\", 0, \"sets the initial amount of total memory to report back to the container\")\nf.IntVar(&b.userLogFD, \"user-log-fd\", 0, \"file descriptor to write user logs to. 0 means no logging.\")\n@@ -121,7 +125,7 @@ func (b *Boot) Execute(_ context.Context, f *flag.FlagSet, args ...interface{})\ndebug.SetTraceback(\"all\")\nif b.setUpRoot {\n- if err := setUpChroot(); err != nil {\n+ if err := setUpChroot(b.pidns); err != nil {\nFatalf(\"error setting up chroot: %v\", err)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/cmd/chroot.go",
"new_path": "runsc/cmd/chroot.go",
"diff": "@@ -42,7 +42,7 @@ func mountInChroot(chroot, src, dst, typ string, flags uint32) error {\n// setUpChroot creates an empty directory with runsc mounted at /runsc and proc\n// mounted at /proc.\n-func setUpChroot() error {\n+func setUpChroot(pidns bool) error {\n// We are a new mount namespace, so we can use /tmp as a directory to\n// construct a new root.\nchroot := os.TempDir()\n@@ -59,9 +59,16 @@ func setUpChroot() error {\nreturn fmt.Errorf(\"error mounting tmpfs in choot: %v\", err)\n}\n+ if pidns {\n+ flags := uint32(syscall.MS_NOSUID | syscall.MS_NODEV | syscall.MS_NOEXEC | syscall.MS_RDONLY)\n+ if err := mountInChroot(chroot, \"proc\", \"/proc\", \"proc\", flags); err != nil {\n+ return fmt.Errorf(\"error mounting proc in chroot: %v\", err)\n+ }\n+ } else {\nif err := mountInChroot(chroot, \"/proc\", \"/proc\", \"bind\", syscall.MS_BIND|syscall.MS_RDONLY|syscall.MS_REC); err != nil {\nreturn fmt.Errorf(\"error mounting proc in chroot: %v\", err)\n}\n+ }\nif err := mountInChroot(chroot, specutils.ExePath, chrootBinPath, \"bind\", syscall.MS_BIND|syscall.MS_RDONLY); err != nil {\nreturn fmt.Errorf(\"error mounting runsc in chroot: %v\", err)\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/sandbox/sandbox.go",
"new_path": "runsc/sandbox/sandbox.go",
"diff": "@@ -458,6 +458,7 @@ func (s *Sandbox) createSandboxProcess(spec *specs.Spec, conf *boot.Config, bund\n} else {\nlog.Infof(\"Sandbox will be started in a new PID namespace\")\nnss = append(nss, specs.LinuxNamespace{Type: specs.PIDNamespace})\n+ cmd.Args = append(cmd.Args, \"--pidns=true\")\n}\n// Joins the network namespace if network is enabled. the sandbox talks\n"
}
] | Go | Apache License 2.0 | google/gvisor | runsc: create a new proc mount if the sandbox process is running in a new pidns
PiperOrigin-RevId: 229971902
Change-Id: Ief4fac731e839ef092175908de9375d725eaa3aa |
259,853 | 18.01.2019 16:07:28 | 28,800 | c0a981629cf44688687548490c5e665d851afe06 | Start a sandbox process in a new userns only if CAP_SETUID is set
In addition, it fixes a race condition in TestMultiContainerGoferStop.
There are two scripts copy the same set of files into the same directory
and sometime one of this command fails with EXIST. | [
{
"change_type": "MODIFY",
"old_path": "runsc/container/multi_container_test.go",
"new_path": "runsc/container/multi_container_test.go",
"diff": "@@ -739,11 +739,6 @@ func TestMultiContainerGoferStop(t *testing.T) {\nt.Fatal(\"error finding test_app:\", err)\n}\n- dir, err := ioutil.TempDir(testutil.TmpDir(), \"gofer-stop-test\")\n- if err != nil {\n- t.Fatal(\"ioutil.TempDir failed:\", err)\n- }\n-\n// Setup containers. Root container just reaps children, while the others\n// perform some IOs. Children are executed in 3 batches of 10. Within the\n// batch there is overlap between containers starting and being destroyed. In\n@@ -751,6 +746,12 @@ func TestMultiContainerGoferStop(t *testing.T) {\ncmds := [][]string{{app, \"reaper\"}}\nconst batchSize = 10\nfor i := 0; i < 3*batchSize; i++ {\n+ dir, err := ioutil.TempDir(testutil.TmpDir(), \"gofer-stop-test\")\n+ if err != nil {\n+ t.Fatal(\"ioutil.TempDir failed:\", err)\n+ }\n+ defer os.RemoveAll(dir)\n+\ncmd := \"find /bin -type f | head | xargs -I SRC cp SRC \" + dir\ncmds = append(cmds, []string{\"sh\", \"-c\", cmd})\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/sandbox/sandbox.go",
"new_path": "runsc/sandbox/sandbox.go",
"diff": "@@ -500,15 +500,15 @@ func (s *Sandbox) createSandboxProcess(spec *specs.Spec, conf *boot.Config, bund\nreturn fmt.Errorf(\"can't run sandbox process in minimal chroot since we don't have CAP_SYS_ADMIN\")\n}\n} else {\n- log.Infof(\"Sandbox will be started in new user namespace\")\n- nss = append(nss, specs.LinuxNamespace{Type: specs.UserNamespace})\n-\n// If we have CAP_SETUID and CAP_SETGID, then we can also run\n// as user nobody.\nif conf.TestOnlyAllowRunAsCurrentUserWithoutChroot {\nlog.Warningf(\"Running sandbox in test mode as current user (uid=%d gid=%d). This is only safe in tests!\", os.Getuid(), os.Getgid())\nlog.Warningf(\"Running sandbox in test mode without chroot. This is only safe in tests!\")\n} else if specutils.HasCapabilities(capability.CAP_SETUID, capability.CAP_SETGID) {\n+ log.Infof(\"Sandbox will be started in new user namespace\")\n+ nss = append(nss, specs.LinuxNamespace{Type: specs.UserNamespace})\n+\n// Map nobody in the new namespace to nobody in the parent namespace.\n//\n// A sandbox process will construct an empty\n"
}
] | Go | Apache License 2.0 | google/gvisor | Start a sandbox process in a new userns only if CAP_SETUID is set
In addition, it fixes a race condition in TestMultiContainerGoferStop.
There are two scripts copy the same set of files into the same directory
and sometime one of this command fails with EXIST.
PiperOrigin-RevId: 230011247
Change-Id: I9289f72e65dc407cdcd0e6cd632a509e01f43e9c |
259,853 | 22.01.2019 16:45:45 | 28,800 | 5f08f8fd8162fa2fc2ca7b862263081d8d07b206 | Don't bind-mount runsc into a sandbox mntns | [
{
"change_type": "MODIFY",
"old_path": "runsc/cmd/boot.go",
"new_path": "runsc/cmd/boot.go",
"diff": "@@ -129,7 +129,6 @@ func (b *Boot) Execute(_ context.Context, f *flag.FlagSet, args ...interface{})\nFatalf(\"error setting up chroot: %v\", err)\n}\n- specutils.ExePath = \"/runsc\"\nif !b.applyCaps {\n// Remove --setup-root arg to call myself.\nvar args []string\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/cmd/chroot.go",
"new_path": "runsc/cmd/chroot.go",
"diff": "@@ -24,10 +24,6 @@ import (\n\"gvisor.googlesource.com/gvisor/runsc/specutils\"\n)\n-// chrootBinPath is the location inside the chroot where the runsc binary will\n-// be mounted.\n-const chrootBinPath = \"/runsc\"\n-\n// mountInChroot creates the destination mount point in the given chroot and\n// mounts the source.\nfunc mountInChroot(chroot, src, dst, typ string, flags uint32) error {\n@@ -70,10 +66,6 @@ func setUpChroot(pidns bool) error {\n}\n}\n- if err := mountInChroot(chroot, specutils.ExePath, chrootBinPath, \"bind\", syscall.MS_BIND|syscall.MS_RDONLY); err != nil {\n- return fmt.Errorf(\"error mounting runsc in chroot: %v\", err)\n- }\n-\nif err := os.Chdir(chroot); err != nil {\nreturn fmt.Errorf(\"error changing working directory: %v\", err)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/cmd/cmd.go",
"new_path": "runsc/cmd/cmd.go",
"diff": "@@ -80,13 +80,10 @@ func setCapsAndCallSelf(args []string, caps *specs.LinuxCapabilities) error {\nif err := applyCaps(caps); err != nil {\nreturn fmt.Errorf(\"applyCaps() failed: %v\", err)\n}\n- binPath, err := specutils.BinPath()\n- if err != nil {\n- return err\n- }\n+ binPath := specutils.ExePath\nlog.Infof(\"Execve %q again, bye!\", binPath)\n- err = syscall.Exec(binPath, args, []string{})\n+ err := syscall.Exec(binPath, args, []string{})\nreturn fmt.Errorf(\"error executing %s: %v\", binPath, err)\n}\n@@ -105,7 +102,7 @@ func callSelfAsNobody(args []string) error {\nreturn fmt.Errorf(\"error setting gid: %v\", err)\n}\n- binPath := \"/runsc\"\n+ binPath := specutils.ExePath\nlog.Infof(\"Execve %q again, bye!\", binPath)\nerr := syscall.Exec(binPath, args, []string{})\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/cmd/exec.go",
"new_path": "runsc/cmd/exec.go",
"diff": "@@ -186,10 +186,7 @@ func (ex *Exec) Execute(_ context.Context, f *flag.FlagSet, args ...interface{})\n}\nfunc (ex *Exec) execAndWait(waitStatus *syscall.WaitStatus) subcommands.ExitStatus {\n- binPath, err := specutils.BinPath()\n- if err != nil {\n- Fatalf(\"getting bin path: %v\", err)\n- }\n+ binPath := specutils.ExePath\nvar args []string\n// The command needs to write a pid file so that execAndWait can tell\n@@ -219,6 +216,7 @@ func (ex *Exec) execAndWait(waitStatus *syscall.WaitStatus) subcommands.ExitStat\n}\ncmd := exec.Command(binPath, args...)\n+ cmd.Args[0] = \"runsc-exec\"\n// Exec stdio defaults to current process stdio.\ncmd.Stdin = os.Stdin\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/container/container.go",
"new_path": "runsc/container/container.go",
"diff": "@@ -818,12 +818,10 @@ func (c *Container) createGoferProcess(spec *specs.Spec, conf *boot.Config, bund\nargs = append(args, fmt.Sprintf(\"--io-fds=%d\", nextFD))\n}\n- binPath, err := specutils.BinPath()\n- if err != nil {\n- return nil, err\n- }\n+ binPath := specutils.ExePath\ncmd := exec.Command(binPath, args...)\ncmd.ExtraFiles = goferEnds\n+ cmd.Args[0] = \"runsc-gofer\"\n// Enter new namespaces to isolate from the rest of the system. Don't unshare\n// cgroup because gofer is added to a cgroup in the caller's namespace.\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/sandbox/sandbox.go",
"new_path": "runsc/sandbox/sandbox.go",
"diff": "@@ -292,10 +292,7 @@ func (s *Sandbox) createSandboxProcess(spec *specs.Spec, conf *boot.Config, bund\n// starts at 3 because 0, 1, and 2 are taken by stdin/out/err.\nnextFD := 3\n- binPath, err := specutils.BinPath()\n- if err != nil {\n- return err\n- }\n+ binPath := specutils.ExePath\ncmd := exec.Command(binPath, conf.ToFlags()...)\ncmd.SysProcAttr = &syscall.SysProcAttr{}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/specutils/specutils.go",
"new_path": "runsc/specutils/specutils.go",
"diff": "@@ -315,16 +315,6 @@ func IsSupportedDevMount(m specs.Mount) bool {\nreturn true\n}\n-// BinPath returns the real path to self, resolving symbolink links. This is done\n-// to make the process name appears as 'runsc', instead of 'exe'.\n-func BinPath() (string, error) {\n- binPath, err := filepath.EvalSymlinks(ExePath)\n- if err != nil {\n- return \"\", fmt.Errorf(`error resolving %q symlink: %v`, ExePath, err)\n- }\n- return binPath, nil\n-}\n-\nconst (\n// ContainerdContainerTypeAnnotation is the OCI annotation set by\n// containerd to indicate whether the container to create should have\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/test/root/chroot_test.go",
"new_path": "runsc/test/root/chroot_test.go",
"diff": "@@ -26,8 +26,6 @@ import (\n\"os\"\n\"os/exec\"\n\"path/filepath\"\n- \"reflect\"\n- \"sort\"\n\"strconv\"\n\"strings\"\n\"testing\"\n@@ -73,16 +71,13 @@ func TestChroot(t *testing.T) {\nif err != nil {\nt.Fatalf(\"error listing %q: %v\", chroot, err)\n}\n- if want, got := 2, len(fi); want != got {\n+ if want, got := 1, len(fi); want != got {\nt.Fatalf(\"chroot dir got %d entries, want %d\", got, want)\n}\n- // chroot dir is prepared by runsc and should contains only the executable\n- // and /proc.\n- files := []string{fi[0].Name(), fi[1].Name()}\n- sort.Strings(files)\n- if want := []string{\"proc\", \"runsc\"}; !reflect.DeepEqual(files, want) {\n- t.Errorf(\"chroot got children %v, want %v\", files, want)\n+ // chroot dir is prepared by runsc and should contains only /proc.\n+ if fi[0].Name() != \"proc\" {\n+ t.Errorf(\"chroot got children %v, want %v\", fi[0].Name(), \"proc\")\n}\nd.CleanUp()\n"
}
] | Go | Apache License 2.0 | google/gvisor | Don't bind-mount runsc into a sandbox mntns
PiperOrigin-RevId: 230437407
Change-Id: Id9d8ceeb018aad2fe317407c78c6ee0f4b47aa2b |
259,853 | 23.01.2019 17:07:38 | 28,800 | af89fb49af1c9112753c718eb8538bcd9d2a6c6c | socket_netlink_route: ignore negative port ID values
netlink_autobind() sets a port id to a process ID, if this address is
available. Otherwise, it will set a port id to a random negative value. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_netlink_route.cc",
"new_path": "test/syscalls/linux/socket_netlink_route.cc",
"diff": "#include <linux/rtnetlink.h>\n#include <sys/socket.h>\n#include <sys/types.h>\n+#include <unistd.h>\n#include <vector>\n#include \"gtest/gtest.h\"\n@@ -100,12 +101,13 @@ TEST(NetlinkRouteTest, ConnectBinds) {\n&addrlen),\nSyscallSucceeds());\nEXPECT_EQ(addrlen, sizeof(addr));\n- // This is the only netlink socket in the process, so it should get the PID as\n- // the port id.\n- //\n- // N.B. Another process could theoretically have explicitly reserved our pid\n- // as a port ID, but that is very unlikely.\n+\n+ // Each test is running in a pid namespace, so another process can explicitly\n+ // reserve our pid as a port ID. In this case, a negative portid value will be\n+ // set.\n+ if (static_cast<pid_t>(addr.nl_pid) > 0) {\nEXPECT_EQ(addr.nl_pid, getpid());\n+ }\nmemset(&addr, 0, sizeof(addr));\naddr.nl_family = AF_NETLINK;\n"
}
] | Go | Apache License 2.0 | google/gvisor | socket_netlink_route: ignore negative port ID values
netlink_autobind() sets a port id to a process ID, if this address is
available. Otherwise, it will set a port id to a random negative value.
PiperOrigin-RevId: 230631956
Change-Id: I11692e4fe9421e77d9406627b4e7772e4d9b105a |
259,881 | 23.01.2019 18:23:39 | 28,800 | 74f5100a92854bb244f560847cd8f459a8a06688 | Fix cases of missing braces on if | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_inet_loopback.cc",
"new_path": "test/syscalls/linux/socket_inet_loopback.cc",
"diff": "@@ -261,7 +261,9 @@ TEST_P(SocketInetReusePortTest, TcpPortReuseMultiThread) {\nASSERT_THAT(listen(fd, 40), SyscallSucceeds());\n// On the first bind we need to determine which port was bound.\n- if (i != 0) continue;\n+ if (i != 0) {\n+ continue;\n+ }\n// Get the port bound by the listening socket.\nsocklen_t addrlen = listener.addr_len;\n@@ -363,7 +365,9 @@ TEST_P(SocketInetReusePortTest, UdpPortReuseMultiThread) {\nSyscallSucceeds());\n// On the first bind we need to determine which port was bound.\n- if (i != 0) continue;\n+ if (i != 0) {\n+ continue;\n+ }\n// Get the port bound by the listening socket.\nsocklen_t addrlen = listener.addr_len;\n@@ -1087,13 +1091,14 @@ TEST_P(SocketMultiProtocolInetLoopbackTest, PortReuseTwoSockets) {\n// Verify that two sockets can be bound to the same port only if\n// SO_REUSEPORT is set for both of them.\n- if (!portreuse1 || !portreuse2)\n+ if (!portreuse1 || !portreuse2) {\nASSERT_THAT(ret, SyscallFailsWithErrno(EADDRINUSE));\n- else\n+ } else {\nASSERT_THAT(ret, SyscallSucceeds());\n}\n}\n}\n+}\nINSTANTIATE_TEST_CASE_P(AllFamlies, SocketMultiProtocolInetLoopbackTest,\n::testing::Values(ProtocolTestParam{\"TCP\", SOCK_STREAM},\n"
},
{
"change_type": "MODIFY",
"old_path": "test/util/fs_util.cc",
"new_path": "test/util/fs_util.cc",
"diff": "@@ -550,25 +550,35 @@ std::pair<absl::string_view, absl::string_view> SplitPath(\nstd::string::size_type pos = path.find_last_of('/');\n// Handle the case with no '/' in 'path'.\n- if (pos == absl::string_view::npos)\n+ if (pos == absl::string_view::npos) {\nreturn std::make_pair(path.substr(0, 0), path);\n+ }\n// Handle the case with a single leading '/' in 'path'.\n- if (pos == 0)\n+ if (pos == 0) {\nreturn std::make_pair(path.substr(0, 1), absl::ClippedSubstr(path, 1));\n+ }\nreturn std::make_pair(path.substr(0, pos),\nabsl::ClippedSubstr(path, pos + 1));\n}\nstd::string JoinPath(absl::string_view path1, absl::string_view path2) {\n- if (path1.empty()) return std::string(path2);\n- if (path2.empty()) return std::string(path1);\n+ if (path1.empty()) {\n+ return std::string(path2);\n+ }\n+ if (path2.empty()) {\n+ return std::string(path1);\n+ }\n+\nif (path1.back() == '/') {\n- if (path2.front() == '/')\n+ if (path2.front() == '/') {\nreturn absl::StrCat(path1, absl::ClippedSubstr(path2, 1));\n+ }\n} else {\n- if (path2.front() != '/') return absl::StrCat(path1, \"/\", path2);\n+ if (path2.front() != '/') {\n+ return absl::StrCat(path1, \"/\", path2);\n+ }\n}\nreturn absl::StrCat(path1, path2);\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/util/posix_error.h",
"new_path": "test/util/posix_error.h",
"diff": "@@ -426,7 +426,9 @@ IsPosixErrorOkAndHolds(InnerMatcher&& inner_matcher) {\n#define RETURN_IF_ERRNO(s) \\\ndo { \\\n- if (!s.ok()) return s; \\\n+ if (!s.ok()) { \\\n+ return s; \\\n+ } \\\n} while (false);\n#define ASSERT_NO_ERRNO_AND_VALUE(expr) \\\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix cases of missing braces on if
PiperOrigin-RevId: 230641540
Change-Id: Icccc3cdeec191138940f0ecea0a29798359d2b1f |
259,992 | 24.01.2019 14:19:07 | 28,800 | 01679f3b5ab957c274690a62f0fce5d332ee94af | Increase gofer coverage in tests
Lots of tests use /tmp for the tests. Force /tmp to be
mounted over fsgofer instead of tmpfs. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/BUILD",
"new_path": "test/syscalls/BUILD",
"diff": "@@ -42,6 +42,7 @@ syscall_test(test = \"//test/syscalls/linux:chmod_test\")\nsyscall_test(\nsize = \"medium\",\ntest = \"//test/syscalls/linux:chown_test\",\n+ use_tmpfs = True, # chwon tests require gofer to be running as root.\n)\nsyscall_test(test = \"//test/syscalls/linux:chroot_test\")\n@@ -137,7 +138,10 @@ syscall_test(\nsyscall_test(test = \"//test/syscalls/linux:kill_test\")\n-syscall_test(test = \"//test/syscalls/linux:link_test\")\n+syscall_test(\n+ test = \"//test/syscalls/linux:link_test\",\n+ use_tmpfs = True, # gofer needs CAP_DAC_READ_SEARCH to use AT_EMPTY_PATH with linkat(2)\n+)\nsyscall_test(test = \"//test/syscalls/linux:lseek_test\")\n@@ -151,7 +155,10 @@ syscall_test(test = \"//test/syscalls/linux:mincore_test\")\nsyscall_test(test = \"//test/syscalls/linux:mkdir_test\")\n-syscall_test(test = \"//test/syscalls/linux:mknod_test\")\n+syscall_test(\n+ test = \"//test/syscalls/linux:mknod_test\",\n+ use_tmpfs = True, # mknod is not supported over gofer.\n+)\nsyscall_test(\nsize = \"medium\",\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/build_defs.bzl",
"new_path": "test/syscalls/build_defs.bzl",
"diff": "# syscall_test is a macro that will create targets to run the given test target\n# on the host (native) and runsc.\n-def syscall_test(test, shard_count = 5, size = \"small\"):\n- _syscall_test(test, shard_count, size, \"native\")\n- _syscall_test(test, shard_count, size, \"kvm\")\n- _syscall_test(test, shard_count, size, \"ptrace\")\n+def syscall_test(test, shard_count = 5, size = \"small\", use_tmpfs = False):\n+ _syscall_test(test, shard_count, size, \"native\", False)\n+ _syscall_test(test, shard_count, size, \"kvm\", use_tmpfs)\n+ _syscall_test(test, shard_count, size, \"ptrace\", use_tmpfs)\n-def _syscall_test(test, shard_count, size, platform):\n+def _syscall_test(test, shard_count, size, platform, use_tmpfs):\ntest_name = test.split(\":\")[1]\n# Prepend \"runsc\" to non-native platform names.\n@@ -39,6 +39,7 @@ def _syscall_test(test, shard_count, size, platform):\n# Arguments are passed directly to syscall_test_runner binary.\n\"--test-name=\" + test_name,\n\"--platform=\" + platform,\n+ \"--use-tmpfs=\" + str(use_tmpfs),\n\"--debug=false\",\n\"--strace=false\",\n\"--parallel=true\",\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/inotify.cc",
"new_path": "test/syscalls/linux/inotify.cc",
"diff": "@@ -1222,7 +1222,8 @@ TEST(Inotify, LinkGeneratesAttribAndCreateEvents) {\nconst int rc = link(file1.path().c_str(), link1.path().c_str());\n// link(2) is only supported on tmpfs in the sandbox.\n- SKIP_IF(IsRunningOnGvisor() && rc != 0 && errno == EPERM);\n+ SKIP_IF(IsRunningOnGvisor() && rc != 0 &&\n+ (errno == EPERM || errno == ENOENT));\nASSERT_THAT(rc, SyscallSucceeds());\nconst std::vector<Event> events =\n@@ -1238,7 +1239,8 @@ TEST(Inotify, HardlinksReuseSameWatch) {\nTempPath link1(root.path() + \"/link1\");\nconst int rc = link(file1.path().c_str(), link1.path().c_str());\n// link(2) is only supported on tmpfs in the sandbox.\n- SKIP_IF(IsRunningOnGvisor() && rc != 0 && errno == EPERM);\n+ SKIP_IF(IsRunningOnGvisor() && rc != 0 &&\n+ (errno == EPERM || errno == ENOENT));\nASSERT_THAT(rc, SyscallSucceeds());\nconst FileDescriptor fd =\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/syscall_test_runner.go",
"new_path": "test/syscalls/syscall_test_runner.go",
"diff": "@@ -45,6 +45,7 @@ var (\ndebug = flag.Bool(\"debug\", false, \"enable debug logs\")\nstrace = flag.Bool(\"strace\", false, \"enable strace logs\")\nplatform = flag.String(\"platform\", \"ptrace\", \"platform to run on\")\n+ useTmpfs = flag.Bool(\"use-tmpfs\", false, \"mounts tmpfs for /tmp\")\nparallel = flag.Bool(\"parallel\", false, \"run tests in parallel\")\nrunscPath = flag.String(\"runsc\", \"\", \"path to runsc binary\")\n)\n@@ -109,11 +110,15 @@ func runTestCaseRunsc(testBin string, tc gtest.TestCase, t *testing.T) {\n// write to the rootfs, and expect EACCES, not EROFS.\nspec.Root.Readonly = false\n- // Forces '/tmp' to be mounted as tmpfs, otherwise test that rely on features\n- // available in gVisor's tmpfs and not gofers, may fail.\n+ // Test spec comes with pre-defined mounts that we don't want. Reset it.\n+ spec.Mounts = nil\n+ if *useTmpfs {\n+ // Forces '/tmp' to be mounted as tmpfs, otherwise test that rely on\n+ // features available in gVisor's tmpfs and not gofers, may fail.\nspec.Mounts = []specs.Mount{\n{Destination: \"/tmp\", Type: \"tmpfs\"},\n}\n+ }\n// Set environment variable that indicates we are\n// running in gVisor and with the given platform.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Increase gofer coverage in tests
Lots of tests use /tmp for the tests. Force /tmp to be
mounted over fsgofer instead of tmpfs.
PiperOrigin-RevId: 230788985
Change-Id: Id6597ed88133232d15e808c48126bf77cb32673e |
259,858 | 24.01.2019 17:01:20 | 28,800 | b5088ba59c4b6e6fe19a38e15a5472d36f80b397 | cleanup: extract the kernel from context | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ashmem/BUILD",
"new_path": "pkg/sentry/fs/ashmem/BUILD",
"diff": "@@ -21,7 +21,6 @@ go_library(\n\"//pkg/sentry/fs\",\n\"//pkg/sentry/fs/fsutil\",\n\"//pkg/sentry/fs/tmpfs\",\n- \"//pkg/sentry/kernel\",\n\"//pkg/sentry/kernel/time\",\n\"//pkg/sentry/memmap\",\n\"//pkg/sentry/platform\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ashmem/area.go",
"new_path": "pkg/sentry/fs/ashmem/area.go",
"diff": "@@ -23,7 +23,6 @@ import (\n\"gvisor.googlesource.com/gvisor/pkg/sentry/fs\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/fs/fsutil\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/fs/tmpfs\"\n- \"gvisor.googlesource.com/gvisor/pkg/sentry/kernel\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/memmap\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/usage\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/usermem\"\n@@ -114,11 +113,7 @@ func (a *Area) ConfigureMMap(ctx context.Context, file *fs.File, opts *memmap.MM\nopts.MaxPerms = opts.MaxPerms.Intersect(a.perms)\nif a.tmpfsFile == nil {\n- k := kernel.KernelFromContext(ctx)\n- if k == nil {\n- return syserror.ENOMEM\n- }\n- tmpfsInodeOps := tmpfs.NewInMemoryFile(ctx, usage.Tmpfs, fs.UnstableAttr{}, k)\n+ tmpfsInodeOps := tmpfs.NewInMemoryFile(ctx, usage.Tmpfs, fs.UnstableAttr{})\ntmpfsInode := fs.NewInode(tmpfsInodeOps, fs.NewPseudoMountSource(), fs.StableAttr{})\ndirent := fs.NewDirent(tmpfsInode, namePrefix+\"/\"+a.name)\ntmpfsFile, err := tmpfsInode.GetFile(ctx, dirent, fs.FileFlags{Read: true, Write: true})\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/dev/BUILD",
"new_path": "pkg/sentry/fs/dev/BUILD",
"diff": "@@ -25,7 +25,6 @@ go_library(\n\"//pkg/sentry/fs/fsutil\",\n\"//pkg/sentry/fs/ramfs\",\n\"//pkg/sentry/fs/tmpfs\",\n- \"//pkg/sentry/kernel\",\n\"//pkg/sentry/memmap\",\n\"//pkg/sentry/mm\",\n\"//pkg/sentry/platform\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/dev/dev.go",
"new_path": "pkg/sentry/fs/dev/dev.go",
"diff": "@@ -24,7 +24,6 @@ import (\n\"gvisor.googlesource.com/gvisor/pkg/sentry/fs/binder\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/fs/ramfs\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/fs/tmpfs\"\n- \"gvisor.googlesource.com/gvisor/pkg/sentry/kernel\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/usermem\"\n)\n@@ -77,7 +76,7 @@ func New(ctx context.Context, msrc *fs.MountSource, binderEnabled bool, ashmemEn\n\"random\": newCharacterDevice(newRandomDevice(ctx, fs.RootOwner, 0444), msrc),\n\"urandom\": newCharacterDevice(newRandomDevice(ctx, fs.RootOwner, 0444), msrc),\n- \"shm\": tmpfs.NewDir(ctx, nil, fs.RootOwner, fs.FilePermsFromMode(0777), msrc, kernel.KernelFromContext(ctx)),\n+ \"shm\": tmpfs.NewDir(ctx, nil, fs.RootOwner, fs.FilePermsFromMode(0777), msrc),\n// A devpts is typically mounted at /dev/pts to provide\n// pseudoterminal support. Place an empty directory there for\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/tmpfs/BUILD",
"new_path": "pkg/sentry/fs/tmpfs/BUILD",
"diff": "@@ -42,7 +42,6 @@ go_test(\ndeps = [\n\"//pkg/sentry/context\",\n\"//pkg/sentry/fs\",\n- \"//pkg/sentry/kernel\",\n\"//pkg/sentry/kernel/contexttest\",\n\"//pkg/sentry/usage\",\n\"//pkg/sentry/usermem\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/tmpfs/file_test.go",
"new_path": "pkg/sentry/fs/tmpfs/file_test.go",
"diff": "@@ -20,7 +20,6 @@ import (\n\"gvisor.googlesource.com/gvisor/pkg/sentry/context\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/fs\"\n- \"gvisor.googlesource.com/gvisor/pkg/sentry/kernel\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/kernel/contexttest\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/usage\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/usermem\"\n@@ -28,7 +27,7 @@ import (\nfunc newFileInode(ctx context.Context) *fs.Inode {\nm := fs.NewCachingMountSource(&Filesystem{}, fs.MountSourceFlags{})\n- iops := NewInMemoryFile(ctx, usage.Tmpfs, fs.WithCurrentTime(ctx, fs.UnstableAttr{}), kernel.KernelFromContext(ctx))\n+ iops := NewInMemoryFile(ctx, usage.Tmpfs, fs.WithCurrentTime(ctx, fs.UnstableAttr{}))\nreturn fs.NewInode(iops, m, fs.StableAttr{\nDeviceID: tmpfsDevice.DeviceID(),\nInodeID: tmpfsDevice.NextIno(),\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/tmpfs/fs.go",
"new_path": "pkg/sentry/fs/tmpfs/fs.go",
"diff": "@@ -21,7 +21,6 @@ import (\n\"gvisor.googlesource.com/gvisor/pkg/abi/linux\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/context\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/fs\"\n- \"gvisor.googlesource.com/gvisor/pkg/sentry/kernel\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/kernel/auth\"\n)\n@@ -133,5 +132,5 @@ func (f *Filesystem) Mount(ctx context.Context, device string, flags fs.MountSou\nmsrc := fs.NewCachingMountSource(f, flags)\n// Construct the tmpfs root.\n- return NewDir(ctx, nil, owner, perms, msrc, kernel.KernelFromContext(ctx)), nil\n+ return NewDir(ctx, nil, owner, perms, msrc), nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/tmpfs/inode_file.go",
"new_path": "pkg/sentry/fs/tmpfs/inode_file.go",
"diff": "@@ -89,10 +89,10 @@ type fileInodeOperations struct {\nvar _ fs.InodeOperations = (*fileInodeOperations)(nil)\n// NewInMemoryFile returns a new file backed by p.Memory().\n-func NewInMemoryFile(ctx context.Context, usage usage.MemoryKind, uattr fs.UnstableAttr, k *kernel.Kernel) fs.InodeOperations {\n+func NewInMemoryFile(ctx context.Context, usage usage.MemoryKind, uattr fs.UnstableAttr) fs.InodeOperations {\nreturn &fileInodeOperations{\nattr: uattr,\n- kernel: k,\n+ kernel: kernel.KernelFromContext(ctx),\nmemUsage: usage,\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/tmpfs/tmpfs.go",
"new_path": "pkg/sentry/fs/tmpfs/tmpfs.go",
"diff": "@@ -81,10 +81,10 @@ type Dir struct {\nvar _ fs.InodeOperations = (*Dir)(nil)\n// NewDir returns a new directory.\n-func NewDir(ctx context.Context, contents map[string]*fs.Inode, owner fs.FileOwner, perms fs.FilePermissions, msrc *fs.MountSource, kernel *kernel.Kernel) *fs.Inode {\n+func NewDir(ctx context.Context, contents map[string]*fs.Inode, owner fs.FileOwner, perms fs.FilePermissions, msrc *fs.MountSource) *fs.Inode {\nd := &Dir{\nramfsDir: ramfs.NewDir(ctx, contents, owner, perms),\n- kernel: kernel,\n+ kernel: kernel.KernelFromContext(ctx),\n}\n// Manually set the CreateOps.\n@@ -208,7 +208,7 @@ func (d *Dir) SetTimestamps(ctx context.Context, i *fs.Inode, ts fs.TimeSpec) er\nfunc (d *Dir) newCreateOps() *ramfs.CreateOps {\nreturn &ramfs.CreateOps{\nNewDir: func(ctx context.Context, dir *fs.Inode, perms fs.FilePermissions) (*fs.Inode, error) {\n- return NewDir(ctx, nil, fs.FileOwnerFromContext(ctx), perms, dir.MountSource, d.kernel), nil\n+ return NewDir(ctx, nil, fs.FileOwnerFromContext(ctx), perms, dir.MountSource), nil\n},\nNewFile: func(ctx context.Context, dir *fs.Inode, perms fs.FilePermissions) (*fs.Inode, error) {\nuattr := fs.WithCurrentTime(ctx, fs.UnstableAttr{\n@@ -217,7 +217,7 @@ func (d *Dir) newCreateOps() *ramfs.CreateOps {\n// Always start unlinked.\nLinks: 0,\n})\n- iops := NewInMemoryFile(ctx, usage.Tmpfs, uattr, d.kernel)\n+ iops := NewInMemoryFile(ctx, usage.Tmpfs, uattr)\nreturn fs.NewInode(iops, dir.MountSource, fs.StableAttr{\nDeviceID: tmpfsDevice.DeviceID(),\nInodeID: tmpfsDevice.NextIno(),\n"
}
] | Go | Apache License 2.0 | google/gvisor | cleanup: extract the kernel from context
Change-Id: I94704a90beebb53164325e0cce1fcb9a0b97d65c
PiperOrigin-RevId: 230817308 |
259,992 | 24.01.2019 22:41:28 | 28,800 | cc995207531965b70bc1b812a70b91f242a92086 | Add runsc logs to test results | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/syscall_test_runner.go",
"new_path": "test/syscalls/syscall_test_runner.go",
"diff": "@@ -168,6 +168,10 @@ func runTestCaseRunsc(testBin string, tc gtest.TestCase, t *testing.T) {\nif *strace {\nargs = append(args, \"-strace\")\n}\n+ if outDir, ok := syscall.Getenv(\"TEST_UNDECLARED_OUTPUTS_DIR\"); ok {\n+ args = append(args, \"-debug-log\", outDir+\"/\")\n+ }\n+\n// Current process doesn't have CAP_SYS_ADMIN, create user namespace and run\n// as root inside that namespace to get it.\nargs = append(args, \"run\", \"--bundle\", bundleDir, id)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add runsc logs to test results
PiperOrigin-RevId: 230850177
Change-Id: I34eb24e8ff8dd9ce3e7f5eb2dc2ee58eeac49f07 |
259,992 | 25.01.2019 14:38:10 | 28,800 | c28f886c0bb0ff996e07fc133e0ebe1d842b496a | Execute statically linked binary
Mounting lib and lib64 are not necessary anymore and simplifies the test. | [
{
"change_type": "MODIFY",
"old_path": "runsc/container/BUILD",
"new_path": "runsc/container/BUILD",
"diff": "@@ -65,7 +65,9 @@ go_test(\ngo_binary(\nname = \"test_app\",\n+ testonly = 1,\nsrcs = [\"test_app.go\"],\n+ pure = \"on\",\ndeps = [\n\"//runsc/test/testutil\",\n\"@com_github_google_subcommands//:go_default_library\",\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/container/container_test.go",
"new_path": "runsc/container/container_test.go",
"diff": "@@ -1526,19 +1526,30 @@ func TestGoferExits(t *testing.T) {\n}\nfunc TestRootNotMount(t *testing.T) {\n- spec := testutil.NewSpecWithArgs(\"/bin/true\")\n+ if testutil.RaceEnabled {\n+ // Requires statically linked binary, since it's mapping the root to a\n+ // random dir, libs cannot be located.\n+ t.Skip(\"race makes test_app not statically linked\")\n+ }\n- root, err := ioutil.TempDir(testutil.TmpDir(), \"root\")\n+ appSym, err := testutil.FindFile(\"runsc/container/test_app\")\n+ if err != nil {\n+ t.Fatal(\"error finding test_app:\", err)\n+ }\n+ app, err := filepath.EvalSymlinks(appSym)\nif err != nil {\n- t.Fatalf(\"failure to create tmp dir: %v\", err)\n+ t.Fatalf(\"error resolving %q symlink: %v\", appSym, err)\n}\n+ log.Infof(\"App path %q is a symlink to %q\", appSym, app)\n+\n+ root := filepath.Dir(app)\n+ exe := \"/\" + filepath.Base(app)\n+ log.Infof(\"Executing %q in %q\", exe, root)\n+\n+ spec := testutil.NewSpecWithArgs(exe, \"help\")\nspec.Root.Path = root\nspec.Root.Readonly = true\n- spec.Mounts = []specs.Mount{\n- {Destination: \"/bin\", Source: \"/bin\", Type: \"bind\", Options: []string{\"ro\"}},\n- {Destination: \"/lib\", Source: \"/lib\", Type: \"bind\", Options: []string{\"ro\"}},\n- {Destination: \"/lib64\", Source: \"/lib64\", Type: \"bind\", Options: []string{\"ro\"}},\n- }\n+ spec.Mounts = nil\nconf := testutil.TestConfig()\nif err := run(spec, conf); err != nil {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Execute statically linked binary
Mounting lib and lib64 are not necessary anymore and simplifies the test.
PiperOrigin-RevId: 230971195
Change-Id: Ib91a3ffcec4b322cd3687c337eedbde9641685ed |
259,885 | 25.01.2019 22:37:41 | 28,800 | a8b8e13154fe39396b9139e8409cb822bbe0a68a | Deflake socket_stream_blocking tests. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_stream_blocking.cc",
"new_path": "test/syscalls/linux/socket_stream_blocking.cc",
"diff": "@@ -62,12 +62,14 @@ TEST_P(BlockingStreamSocketPairTest, BlockPartialWriteClosed) {\n});\n// Leave time for write to become blocked.\n- absl::SleepFor(absl::Seconds(1.0));\n+ absl::SleepFor(absl::Seconds(1));\nASSERT_THAT(close(sockets->release_second_fd()), SyscallSucceeds());\n}\n-TEST_P(BlockingStreamSocketPairTest, SendMsgTooLarge) {\n+// Random save may interrupt the call to sendmsg() in SendLargeSendMsg(),\n+// causing the write to be incomplete and the test to hang.\n+TEST_P(BlockingStreamSocketPairTest, SendMsgTooLarge_NoRandomSave) {\nauto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\nint sndbuf;\n@@ -142,11 +144,15 @@ TEST_P(BlockingStreamSocketPairTest, SendTimeout) {\nsetsockopt(sockets->first_fd(), SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)),\nSyscallSucceeds());\n- char buf[100] = {};\n+ std::vector<char> buf(kPageSize);\n+ // We don't know how much data the socketpair will buffer, so we may do an\n+ // arbitrarily large number of writes; saving after each write causes this\n+ // test's time to explode.\n+ const DisableSave ds;\nfor (;;) {\nint ret;\nASSERT_THAT(\n- ret = RetryEINTR(send)(sockets->first_fd(), buf, sizeof(buf), 0),\n+ ret = RetryEINTR(send)(sockets->first_fd(), buf.data(), buf.size(), 0),\n::testing::AnyOf(SyscallSucceeds(), SyscallFailsWithErrno(EAGAIN)));\nif (ret == -1) {\nbreak;\n"
}
] | Go | Apache License 2.0 | google/gvisor | Deflake socket_stream_blocking tests.
PiperOrigin-RevId: 231020482
Change-Id: Idd9168678b18d03aac473adcc40902e27e06d0a1 |
259,885 | 28.01.2019 10:59:01 | 28,800 | 1cedccf8e9b63757c182477f803afcb27bd9e17e | Drop the one-page limit for /proc/[pid]/{cmdline,environ}.
It never actually should have applied to environ (the relevant change in
Linux 4.2 is "proc: fix PAGE_SIZE limit of
/proc/$PID/cmdline"), and we claim to be Linux 4.4 now anyway. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/proc/exec_args.go",
"new_path": "pkg/sentry/fs/proc/exec_args.go",
"diff": "@@ -101,12 +101,6 @@ func (f *execArgFile) Read(ctx context.Context, _ *fs.File, dst usermem.IOSequen\nreturn 0, syserror.EINVAL\n}\n- // N.B. Linux 4.2 eliminates the arbitrary one page limit.\n- if offset > usermem.PageSize {\n- return 0, io.EOF\n- }\n- dst = dst.TakeFirst64(usermem.PageSize - offset)\n-\nm, err := getTaskMM(f.t)\nif err != nil {\nreturn 0, err\n"
}
] | Go | Apache License 2.0 | google/gvisor | Drop the one-page limit for /proc/[pid]/{cmdline,environ}.
It never actually should have applied to environ (the relevant change in
Linux 4.2 is c2c0bb44620d "proc: fix PAGE_SIZE limit of
/proc/$PID/cmdline"), and we claim to be Linux 4.4 now anyway.
PiperOrigin-RevId: 231250661
Change-Id: I37f9c4280a533d1bcb3eebb7803373ac3c7b9f15 |
259,948 | 28.01.2019 11:57:45 | 28,800 | 196e9f9d82287e30380414f9a47a12c3cda56e41 | Convert outdated TODO to NOTE. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/sigprocmask.cc",
"new_path": "test/syscalls/linux/sigprocmask.cc",
"diff": "@@ -232,7 +232,7 @@ TEST_F(SigProcMaskTest, SignalHandler) {\nEXPECT_THAT(raw_sigprocmask(SIG_UNBLOCK, &mask, nullptr), SyscallSucceeds());\n// Check that the unblocked kTestSignal1 has been delivered.\n- // TODO: gvisor currently drops masked signals on the floor.\n+ // Note: gvisor currently drops masked signals on the floor.\nif (!IsRunningOnGvisor()) {\nEXPECT_EQ(2, signal_count[kTestSignal1]);\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Convert outdated TODO to NOTE.
PiperOrigin-RevId: 231263193
Change-Id: Ib732c9639462f7994d473050495d88c2855434af |
259,885 | 28.01.2019 13:02:04 | 28,800 | 9114471a5a5428bd8858d291811249314473d12d | Remove obsolete gVisor-specific test condition. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/sigprocmask.cc",
"new_path": "test/syscalls/linux/sigprocmask.cc",
"diff": "@@ -232,10 +232,7 @@ TEST_F(SigProcMaskTest, SignalHandler) {\nEXPECT_THAT(raw_sigprocmask(SIG_UNBLOCK, &mask, nullptr), SyscallSucceeds());\n// Check that the unblocked kTestSignal1 has been delivered.\n- // Note: gvisor currently drops masked signals on the floor.\n- if (!IsRunningOnGvisor()) {\nEXPECT_EQ(2, signal_count[kTestSignal1]);\n- }\nEXPECT_EQ(2, signal_count[kTestSignal2]);\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Remove obsolete gVisor-specific test condition.
PiperOrigin-RevId: 231274510
Change-Id: I8f65157dbe18dae1c6235147fc4d27e0c844c833 |
259,948 | 28.01.2019 15:33:09 | 28,800 | ae6e37df2abe450b30aba0908c212e9a1f81b84a | Convert TODO into FIXME. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/proc/task.go",
"new_path": "pkg/sentry/fs/proc/task.go",
"diff": "@@ -76,9 +76,7 @@ func newTaskDir(t *kernel.Task, msrc *fs.MountSource, pidns *kernel.PIDNamespace\n\"fd\": newFdDir(t, msrc),\n\"fdinfo\": newFdInfoDir(t, msrc),\n\"gid_map\": newGIDMap(t, msrc),\n- // TODO: This is incorrect for /proc/[pid]/task/[tid]/io, i.e. if\n- // showSubtasks is false:\n- // https://elixir.bootlin.com/linux/v4.4/source/fs/proc/base.c#L3154\n+ // FIXME: create the correct io file for threads.\n\"io\": newIO(t, msrc),\n\"maps\": newMaps(t, msrc),\n\"mountinfo\": seqfile.NewSeqFileInode(t, &mountInfoFile{t: t}, msrc),\n"
}
] | Go | Apache License 2.0 | google/gvisor | Convert TODO into FIXME.
PiperOrigin-RevId: 231301228
Change-Id: I3e18f3a12a35fb89a22a8c981188268d5887dc61 |
259,962 | 29.01.2019 01:37:54 | 28,800 | 24cb2c0a7256cdb515c2fc2cfc90d130e2a405ef | Use recvmmsg() instead of readv() to read packets from NIC.
This should reduce the number of syscalls required to process packets
significantly and improve throughputs. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/fdbased/BUILD",
"new_path": "pkg/tcpip/link/fdbased/BUILD",
"diff": "@@ -27,6 +27,7 @@ go_test(\n\"//pkg/tcpip\",\n\"//pkg/tcpip/buffer\",\n\"//pkg/tcpip/header\",\n+ \"//pkg/tcpip/link/rawfile\",\n\"//pkg/tcpip/stack\",\n],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/fdbased/endpoint.go",
"new_path": "pkg/tcpip/link/fdbased/endpoint.go",
"diff": "package fdbased\nimport (\n+ \"fmt\"\n\"syscall\"\n\"gvisor.googlesource.com/gvisor/pkg/tcpip\"\n@@ -33,9 +34,19 @@ import (\n\"gvisor.googlesource.com/gvisor/pkg/tcpip/stack\"\n)\n+const (\n+ // MaxMsgsPerRecv is the maximum number of packets we want to retrieve\n+ // in a single RecvMMsg call.\n+ MaxMsgsPerRecv = 8\n+)\n+\n// BufConfig defines the shape of the vectorised view used to read packets from the NIC.\nvar BufConfig = []int{128, 256, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768}\n+// linkDispatcher reads packets from the link FD and dispatches them to the\n+// NetworkDispatcher.\n+type linkDispatcher func() (bool, *tcpip.Error)\n+\ntype endpoint struct {\n// fd is the file descriptor used to send and receive packets.\nfd int\n@@ -57,14 +68,25 @@ type endpoint struct {\n// its end of the communication pipe.\nclosed func(*tcpip.Error)\n- iovecs []syscall.Iovec\n- views []buffer.View\n+ views [][]buffer.View\n+ iovecs [][]syscall.Iovec\n+ msgHdrs []rawfile.MMsgHdr\n+ inboundDispatcher linkDispatcher\ndispatcher stack.NetworkDispatcher\n// handleLocal indicates whether packets destined to itself should be\n// handled by the netstack internally (true) or be forwarded to the FD\n// endpoint (false).\nhandleLocal bool\n+\n+ // useRecvMMsg enables use of recvmmsg() syscall instead of readv() to\n+ // read inbound packets. This reduces # of syscalls needed to process\n+ // packets.\n+ //\n+ // NOTE: recvmmsg() is only supported for sockets, so if the underlying\n+ // FD is not a socket then the code will still fall back to the readv()\n+ // path.\n+ useRecvMMsg bool\n}\n// Options specify the details about the fd-based endpoint to be created.\n@@ -78,6 +100,7 @@ type Options struct {\nSaveRestore bool\nDisconnectOk bool\nHandleLocal bool\n+ UseRecvMMsg bool\n}\n// New creates a new fd-based endpoint.\n@@ -85,7 +108,10 @@ type Options struct {\n// Makes fd non-blocking, but does not take ownership of fd, which must remain\n// open for the lifetime of the returned endpoint.\nfunc New(opts *Options) tcpip.LinkEndpointID {\n- syscall.SetNonblock(opts.FD, true)\n+ if err := syscall.SetNonblock(opts.FD, true); err != nil {\n+ // TODO : replace panic with an error return.\n+ panic(fmt.Sprintf(\"syscall.SetNonblock(%v) failed: %v\", opts.FD, err))\n+ }\ncaps := stack.LinkEndpointCapabilities(0)\nif opts.ChecksumOffload {\n@@ -113,13 +139,44 @@ func New(opts *Options) tcpip.LinkEndpointID {\nclosed: opts.ClosedFunc,\naddr: opts.Address,\nhdrSize: hdrSize,\n- views: make([]buffer.View, len(BufConfig)),\n- iovecs: make([]syscall.Iovec, len(BufConfig)),\nhandleLocal: opts.HandleLocal,\n+ useRecvMMsg: opts.UseRecvMMsg,\n+ }\n+ // For non-socket FDs we read one packet a time (e.g. TAP devices)\n+ msgsPerRecv := 1\n+ e.inboundDispatcher = e.dispatch\n+ // If the provided FD is a socket then we optimize packet reads by\n+ // using recvmmsg() instead of read() to read packets in a batch.\n+ if isSocketFD(opts.FD) && e.useRecvMMsg {\n+ e.inboundDispatcher = e.recvMMsgDispatch\n+ msgsPerRecv = MaxMsgsPerRecv\n+ }\n+\n+ e.views = make([][]buffer.View, msgsPerRecv)\n+ for i, _ := range e.views {\n+ e.views[i] = make([]buffer.View, len(BufConfig))\n+ }\n+ e.iovecs = make([][]syscall.Iovec, msgsPerRecv)\n+ for i, _ := range e.iovecs {\n+ e.iovecs[i] = make([]syscall.Iovec, len(BufConfig))\n+ }\n+ e.msgHdrs = make([]rawfile.MMsgHdr, msgsPerRecv)\n+ for i, _ := range e.msgHdrs {\n+ e.msgHdrs[i].Msg.Iov = &e.iovecs[i][0]\n+ e.msgHdrs[i].Msg.Iovlen = uint64(len(BufConfig))\n}\nreturn stack.RegisterLinkEndpoint(e)\n}\n+func isSocketFD(fd int) bool {\n+ var stat syscall.Stat_t\n+ if err := syscall.Fstat(fd, &stat); err != nil {\n+ // TODO : replace panic with an error return.\n+ panic(fmt.Sprintf(\"syscall.Fstat(%v,...) failed: %v\", fd, err))\n+ }\n+ return (stat.Mode & syscall.S_IFSOCK) == syscall.S_IFSOCK\n+}\n+\n// Attach launches the goroutine that reads packets from the file descriptor and\n// dispatches them via the provided dispatcher.\nfunc (e *endpoint) Attach(dispatcher stack.NetworkDispatcher) {\n@@ -191,12 +248,12 @@ func (e *endpoint) WritePacket(r *stack.Route, hdr buffer.Prependable, payload b\nreturn rawfile.NonBlockingWrite2(e.fd, hdr.View(), payload.ToView())\n}\n-func (e *endpoint) capViews(n int, buffers []int) int {\n+func (e *endpoint) capViews(k, n int, buffers []int) int {\nc := 0\nfor i, s := range buffers {\nc += s\nif c >= n {\n- e.views[i].CapLength(s - (c - n))\n+ e.views[k][i].CapLength(s - (c - n))\nreturn i + 1\n}\n}\n@@ -204,24 +261,26 @@ func (e *endpoint) capViews(n int, buffers []int) int {\n}\nfunc (e *endpoint) allocateViews(bufConfig []int) {\n- for i, v := range e.views {\n- if v != nil {\n+ for k := 0; k < len(e.views); k++ {\n+ for i := 0; i < len(bufConfig); i++ {\n+ if e.views[k][i] != nil {\nbreak\n}\nb := buffer.NewView(bufConfig[i])\n- e.views[i] = b\n- e.iovecs[i] = syscall.Iovec{\n+ e.views[k][i] = b\n+ e.iovecs[k][i] = syscall.Iovec{\nBase: &b[0],\nLen: uint64(len(b)),\n}\n}\n}\n+}\n// dispatch reads one packet from the file descriptor and dispatches it.\n-func (e *endpoint) dispatch(largeV buffer.View) (bool, *tcpip.Error) {\n+func (e *endpoint) dispatch() (bool, *tcpip.Error) {\ne.allocateViews(BufConfig)\n- n, err := rawfile.BlockingReadv(e.fd, e.iovecs)\n+ n, err := rawfile.BlockingReadv(e.fd, e.iovecs[0])\nif err != nil {\nreturn false, err\n}\n@@ -235,14 +294,14 @@ func (e *endpoint) dispatch(largeV buffer.View) (bool, *tcpip.Error) {\nremote, local tcpip.LinkAddress\n)\nif e.hdrSize > 0 {\n- eth := header.Ethernet(e.views[0])\n+ eth := header.Ethernet(e.views[0][0])\np = eth.Type()\nremote = eth.SourceAddress()\nlocal = eth.DestinationAddress()\n} else {\n// We don't get any indication of what the packet is, so try to guess\n// if it's an IPv4 or IPv6 packet.\n- switch header.IPVersion(e.views[0]) {\n+ switch header.IPVersion(e.views[0][0]) {\ncase header.IPv4Version:\np = header.IPv4ProtocolNumber\ncase header.IPv6Version:\n@@ -252,15 +311,71 @@ func (e *endpoint) dispatch(largeV buffer.View) (bool, *tcpip.Error) {\n}\n}\n- used := e.capViews(n, BufConfig)\n- vv := buffer.NewVectorisedView(n, e.views[:used])\n+ used := e.capViews(0, n, BufConfig)\n+ vv := buffer.NewVectorisedView(n, e.views[0][:used])\nvv.TrimFront(e.hdrSize)\ne.dispatcher.DeliverNetworkPacket(e, remote, local, p, vv)\n// Prepare e.views for another packet: release used views.\nfor i := 0; i < used; i++ {\n- e.views[i] = nil\n+ e.views[0][i] = nil\n+ }\n+\n+ return true, nil\n+}\n+\n+// recvMMsgDispatch reads more than one packet at a time from the file\n+// descriptor and dispatches it.\n+func (e *endpoint) recvMMsgDispatch() (bool, *tcpip.Error) {\n+ e.allocateViews(BufConfig)\n+\n+ nMsgs, err := rawfile.BlockingRecvMMsg(e.fd, e.msgHdrs)\n+ if err != nil {\n+ return false, err\n+ }\n+ // Process each of received packets.\n+ for k := 0; k < nMsgs; k++ {\n+ n := e.msgHdrs[k].Len\n+ if n <= uint32(e.hdrSize) {\n+ return false, nil\n+ }\n+\n+ var (\n+ p tcpip.NetworkProtocolNumber\n+ remote, local tcpip.LinkAddress\n+ )\n+ if e.hdrSize > 0 {\n+ eth := header.Ethernet(e.views[k][0])\n+ p = eth.Type()\n+ remote = eth.SourceAddress()\n+ local = eth.DestinationAddress()\n+ } else {\n+ // We don't get any indication of what the packet is, so try to guess\n+ // if it's an IPv4 or IPv6 packet.\n+ switch header.IPVersion(e.views[k][0]) {\n+ case header.IPv4Version:\n+ p = header.IPv4ProtocolNumber\n+ case header.IPv6Version:\n+ p = header.IPv6ProtocolNumber\n+ default:\n+ return true, nil\n+ }\n+ }\n+\n+ used := e.capViews(k, int(n), BufConfig)\n+ vv := buffer.NewVectorisedView(int(n), e.views[k][:used])\n+ vv.TrimFront(e.hdrSize)\n+ e.dispatcher.DeliverNetworkPacket(e, remote, local, p, vv)\n+\n+ // Prepare e.views for another packet: release used views.\n+ for i := 0; i < used; i++ {\n+ e.views[k][i] = nil\n+ }\n+ }\n+\n+ for k := 0; k < nMsgs; k++ {\n+ e.msgHdrs[k].Len = 0\n}\nreturn true, nil\n@@ -269,9 +384,8 @@ func (e *endpoint) dispatch(largeV buffer.View) (bool, *tcpip.Error) {\n// dispatchLoop reads packets from the file descriptor in a loop and dispatches\n// them to the network stack.\nfunc (e *endpoint) dispatchLoop() *tcpip.Error {\n- v := buffer.NewView(header.MaxIPPacketSize)\nfor {\n- cont, err := e.dispatch(v)\n+ cont, err := e.inboundDispatcher()\nif err != nil || !cont {\nif e.closed != nil {\ne.closed(err)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/fdbased/endpoint_test.go",
"new_path": "pkg/tcpip/link/fdbased/endpoint_test.go",
"diff": "@@ -28,6 +28,7 @@ import (\n\"gvisor.googlesource.com/gvisor/pkg/tcpip\"\n\"gvisor.googlesource.com/gvisor/pkg/tcpip/buffer\"\n\"gvisor.googlesource.com/gvisor/pkg/tcpip/header\"\n+ \"gvisor.googlesource.com/gvisor/pkg/tcpip/link/rawfile\"\n\"gvisor.googlesource.com/gvisor/pkg/tcpip/stack\"\n)\n@@ -309,9 +310,22 @@ func TestBufConfigFirst(t *testing.T) {\nfunc build(bufConfig []int) *endpoint {\ne := &endpoint{\n- views: make([]buffer.View, len(bufConfig)),\n- iovecs: make([]syscall.Iovec, len(bufConfig)),\n+ views: make([][]buffer.View, MaxMsgsPerRecv),\n+ iovecs: make([][]syscall.Iovec, MaxMsgsPerRecv),\n+ msgHdrs: make([]rawfile.MMsgHdr, MaxMsgsPerRecv),\n}\n+\n+ for i, _ := range e.views {\n+ e.views[i] = make([]buffer.View, len(bufConfig))\n+ }\n+ for i := range e.iovecs {\n+ e.iovecs[i] = make([]syscall.Iovec, len(bufConfig))\n+ }\n+ for k, msgHdr := range e.msgHdrs {\n+ msgHdr.Msg.Iov = &e.iovecs[k][0]\n+ msgHdr.Msg.Iovlen = uint64(len(bufConfig))\n+ }\n+\ne.allocateViews(bufConfig)\nreturn e\n}\n@@ -356,12 +370,12 @@ var capLengthTestCases = []struct {\nfunc TestCapLength(t *testing.T) {\nfor _, c := range capLengthTestCases {\ne := build(c.config)\n- used := e.capViews(c.n, c.config)\n+ used := e.capViews(0, c.n, c.config)\nif used != c.wantUsed {\nt.Errorf(\"Test \\\"%s\\\" failed when calling capViews(%d, %v). Got %d. Want %d\", c.comment, c.n, c.config, used, c.wantUsed)\n}\n- lengths := make([]int, len(e.views))\n- for i, v := range e.views {\n+ lengths := make([]int, len(e.views[0]))\n+ for i, v := range e.views[0] {\nlengths[i] = len(v)\n}\nif !reflect.DeepEqual(lengths, c.wantLengths) {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/rawfile/rawfile_unsafe.go",
"new_path": "pkg/tcpip/link/rawfile/rawfile_unsafe.go",
"diff": "@@ -124,7 +124,7 @@ func BlockingRead(fd int, b []byte) (int, *tcpip.Error) {\n// BlockingReadv reads from a file descriptor that is set up as non-blocking and\n// stores the data in a list of iovecs buffers. If no data is available, it will\n-// block in a poll() syscall until the file descirptor becomes readable.\n+// block in a poll() syscall until the file descriptor becomes readable.\nfunc BlockingReadv(fd int, iovecs []syscall.Iovec) (int, *tcpip.Error) {\nfor {\nn, _, e := syscall.RawSyscall(syscall.SYS_READV, uintptr(fd), uintptr(unsafe.Pointer(&iovecs[0])), uintptr(len(iovecs)))\n@@ -143,3 +143,32 @@ func BlockingReadv(fd int, iovecs []syscall.Iovec) (int, *tcpip.Error) {\n}\n}\n}\n+\n+// MMsgHdr represents the mmsg_hdr structure required by recvmmsg() on linux.\n+type MMsgHdr struct {\n+ Msg syscall.Msghdr\n+ Len uint32\n+ _ [4]byte\n+}\n+\n+// BlockingRecvMMsg reads from a file descriptor that is set up as non-blocking\n+// and stores the received messages in a slice of MMsgHdr structures. If no data\n+// is available, it will block in a poll() syscall until the file descriptor\n+// becomes readable.\n+func BlockingRecvMMsg(fd int, msgHdrs []MMsgHdr) (int, *tcpip.Error) {\n+ for {\n+ n, _, e := syscall.RawSyscall6(syscall.SYS_RECVMMSG, uintptr(fd), uintptr(unsafe.Pointer(&msgHdrs[0])), uintptr(len(msgHdrs)), syscall.MSG_DONTWAIT, 0, 0)\n+ if e == 0 {\n+ return int(n), nil\n+ }\n+\n+ event := pollEvent{\n+ fd: int32(fd),\n+ events: 1, // POLLIN\n+ }\n+\n+ if _, e := blockingPoll(&event, 1, -1); e != 0 && e != syscall.EINTR {\n+ return 0, TranslateErrno(e)\n+ }\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/filter/config.go",
"new_path": "runsc/boot/filter/config.go",
"diff": "@@ -211,23 +211,25 @@ var allowedSyscalls = seccomp.SyscallRules{\nsyscall.SYS_PREAD64: {},\nsyscall.SYS_PWRITE64: {},\nsyscall.SYS_READ: {},\n- syscall.SYS_READV: []seccomp.Rule{\n+ syscall.SYS_RECVMSG: []seccomp.Rule{\n{\nseccomp.AllowAny{},\nseccomp.AllowAny{},\n- seccomp.AllowValue(len(fdbased.BufConfig)),\n- },\n+ seccomp.AllowValue(syscall.MSG_DONTWAIT | syscall.MSG_TRUNC),\n},\n- syscall.SYS_RECVMSG: []seccomp.Rule{\n{\nseccomp.AllowAny{},\nseccomp.AllowAny{},\n- seccomp.AllowValue(syscall.MSG_DONTWAIT | syscall.MSG_TRUNC),\n+ seccomp.AllowValue(syscall.MSG_DONTWAIT | syscall.MSG_TRUNC | syscall.MSG_PEEK),\n+ },\n},\n+ syscall.SYS_RECVMMSG: []seccomp.Rule{\n{\nseccomp.AllowAny{},\nseccomp.AllowAny{},\n- seccomp.AllowValue(syscall.MSG_DONTWAIT | syscall.MSG_TRUNC | syscall.MSG_PEEK),\n+ seccomp.AllowValue(fdbased.MaxMsgsPerRecv),\n+ seccomp.AllowValue(syscall.MSG_DONTWAIT),\n+ seccomp.AllowValue(0),\n},\n},\nsyscall.SYS_RESTART_SYSCALL: {},\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/network.go",
"new_path": "runsc/boot/network.go",
"diff": "@@ -140,6 +140,7 @@ func (n *Network) CreateLinksAndRoutes(args *CreateLinksAndRoutesArgs, _ *struct\nEthernetHeader: true,\nHandleLocal: true,\nAddress: mac,\n+ UseRecvMMsg: true,\n})\nlog.Infof(\"Enabling interface %q with id %d on addresses %+v (%v)\", link.Name, nicID, link.Addresses, mac)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Use recvmmsg() instead of readv() to read packets from NIC.
This should reduce the number of syscalls required to process packets
significantly and improve throughputs.
PiperOrigin-RevId: 231366886
Change-Id: I8b38077262bf9c53176bc4a94b530188d3d7c0ca |
259,885 | 29.01.2019 08:00:33 | 28,800 | 57c202ead2d937e40c5d10da409504ac474165d1 | Refactor out NewEventFD to a test utility. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/BUILD",
"new_path": "test/syscalls/linux/BUILD",
"diff": "@@ -481,6 +481,7 @@ cc_binary(\nsrcs = [\"dup.cc\"],\nlinkstatic = 1,\ndeps = [\n+ \"//test/util:eventfd_util\",\n\"//test/util:file_descriptor\",\n\"//test/util:posix_error\",\n\"//test/util:temp_path\",\n@@ -497,6 +498,7 @@ cc_binary(\nlinkstatic = 1,\ndeps = [\n\"//test/util:epoll_util\",\n+ \"//test/util:eventfd_util\",\n\"//test/util:file_descriptor\",\n\"//test/util:posix_error\",\n\"//test/util:test_main\",\n@@ -511,6 +513,8 @@ cc_binary(\nsrcs = [\"eventfd.cc\"],\nlinkstatic = 1,\ndeps = [\n+ \"//test/util:epoll_util\",\n+ \"//test/util:eventfd_util\",\n\"//test/util:test_main\",\n\"//test/util:test_util\",\n\"//test/util:thread_util\",\n@@ -686,6 +690,7 @@ cc_binary(\ndeps = [\n\":socket_test_util\",\n\"//test/util:cleanup\",\n+ \"//test/util:eventfd_util\",\n\"//test/util:multiprocess_util\",\n\"//test/util:posix_error\",\n\"//test/util:temp_path\",\n@@ -817,6 +822,7 @@ cc_binary(\nsrcs = [\"getdents.cc\"],\nlinkstatic = 1,\ndeps = [\n+ \"//test/util:eventfd_util\",\n\"//test/util:file_descriptor\",\n\"//test/util:fs_util\",\n\"//test/util:posix_error\",\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/chmod.cc",
"new_path": "test/syscalls/linux/chmod.cc",
"diff": "// limitations under the License.\n#include <fcntl.h>\n-#include <sys/eventfd.h>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <unistd.h>\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/dup.cc",
"new_path": "test/syscalls/linux/dup.cc",
"diff": "// limitations under the License.\n#include <fcntl.h>\n-#include <sys/eventfd.h>\n#include <unistd.h>\n#include \"gtest/gtest.h\"\n+#include \"test/util/eventfd_util.h\"\n#include \"test/util/file_descriptor.h\"\n#include \"test/util/posix_error.h\"\n#include \"test/util/temp_path.h\"\n@@ -63,20 +63,14 @@ TEST(DupTest, Dup) {\n}\nTEST(DupTest, DupClearsCloExec) {\n- FileDescriptor nfd;\n-\n// Open an eventfd file descriptor with FD_CLOEXEC descriptor flag set.\n- int event_fd = 0;\n- ASSERT_THAT(event_fd = eventfd(0, EFD_CLOEXEC), SyscallSucceeds());\n- FileDescriptor event_fd_closer(event_fd);\n-\n- EXPECT_THAT(fcntl(event_fd_closer.get(), F_GETFD),\n- SyscallSucceedsWithValue(FD_CLOEXEC));\n+ FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(NewEventFD(0, EFD_CLOEXEC));\n+ EXPECT_THAT(fcntl(fd.get(), F_GETFD), SyscallSucceedsWithValue(FD_CLOEXEC));\n// Duplicate the descriptor. Ensure that it doesn't have FD_CLOEXEC set.\n- nfd = ASSERT_NO_ERRNO_AND_VALUE(event_fd_closer.Dup());\n- ASSERT_NE(event_fd_closer.get(), nfd.get());\n- CheckSameFile(event_fd_closer, nfd);\n+ FileDescriptor nfd = ASSERT_NO_ERRNO_AND_VALUE(fd.Dup());\n+ ASSERT_NE(fd.get(), nfd.get());\n+ CheckSameFile(fd, nfd);\nEXPECT_THAT(fcntl(nfd.get(), F_GETFD), SyscallSucceedsWithValue(0));\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/epoll.cc",
"new_path": "test/syscalls/linux/epoll.cc",
"diff": "#include \"gtest/gtest.h\"\n#include \"test/util/epoll_util.h\"\n+#include \"test/util/eventfd_util.h\"\n#include \"test/util/file_descriptor.h\"\n#include \"test/util/posix_error.h\"\n#include \"test/util/test_util.h\"\n@@ -38,16 +39,6 @@ namespace {\nconstexpr int kFDsPerEpoll = 3;\nconstexpr uint64_t kMagicConstant = 0x0102030405060708;\n-// Returns a new eventfd.\n-PosixErrorOr<FileDescriptor> NewEventFD() {\n- int fd = eventfd(/* initval = */ 0, /* flags = */ 0);\n- MaybeSave();\n- if (fd < 0) {\n- return PosixError(errno, \"eventfd\");\n- }\n- return FileDescriptor(fd);\n-}\n-\nuint64_t ms_elapsed(const struct timespec* begin, const struct timespec* end) {\nreturn (end->tv_sec - begin->tv_sec) * 1000 +\n(end->tv_nsec - begin->tv_nsec) / 1000000;\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/eventfd.cc",
"new_path": "test/syscalls/linux/eventfd.cc",
"diff": "#include <stdlib.h>\n#include <string.h>\n#include <sys/epoll.h>\n-#include <sys/eventfd.h>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <unistd.h>\n#include \"gtest/gtest.h\"\n+#include \"test/util/epoll_util.h\"\n+#include \"test/util/eventfd_util.h\"\n#include \"test/util/test_util.h\"\n#include \"test/util/thread_util.h\"\n@@ -33,21 +34,20 @@ namespace testing {\nnamespace {\nTEST(EventfdTest, Nonblock) {\n- int efd;\n- ASSERT_THAT(efd = eventfd(0, EFD_NONBLOCK | EFD_SEMAPHORE),\n- SyscallSucceeds());\n+ FileDescriptor efd =\n+ ASSERT_NO_ERRNO_AND_VALUE(NewEventFD(0, EFD_NONBLOCK | EFD_SEMAPHORE));\nuint64_t l;\n- ASSERT_THAT(read(efd, &l, sizeof(l)), SyscallFailsWithErrno(EAGAIN));\n+ ASSERT_THAT(read(efd.get(), &l, sizeof(l)), SyscallFailsWithErrno(EAGAIN));\nl = 1;\n- ASSERT_THAT(write(efd, &l, sizeof(l)), SyscallSucceeds());\n+ ASSERT_THAT(write(efd.get(), &l, sizeof(l)), SyscallSucceeds());\nl = 0;\n- ASSERT_THAT(read(efd, &l, sizeof(l)), SyscallSucceeds());\n+ ASSERT_THAT(read(efd.get(), &l, sizeof(l)), SyscallSucceeds());\nEXPECT_EQ(l, 1);\n- ASSERT_THAT(read(efd, &l, sizeof(l)), SyscallFailsWithErrno(EAGAIN));\n+ ASSERT_THAT(read(efd.get(), &l, sizeof(l)), SyscallFailsWithErrno(EAGAIN));\n}\nvoid* read_three_times(void* arg) {\n@@ -60,8 +60,8 @@ void* read_three_times(void* arg) {\n}\nTEST(EventfdTest, BlockingWrite) {\n- int efd;\n- ASSERT_THAT(efd = eventfd(0, EFD_SEMAPHORE), SyscallSucceeds());\n+ FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(NewEventFD(0, EFD_SEMAPHORE));\n+ int efd = fd.get();\npthread_t p;\nASSERT_THAT(pthread_create(&p, nullptr, read_three_times,\n@@ -82,58 +82,53 @@ TEST(EventfdTest, BlockingWrite) {\n}\nTEST(EventfdTest, SmallWrite) {\n- int efd;\n- ASSERT_THAT(efd = eventfd(0, EFD_NONBLOCK | EFD_SEMAPHORE),\n- SyscallSucceeds());\n+ FileDescriptor efd =\n+ ASSERT_NO_ERRNO_AND_VALUE(NewEventFD(0, EFD_NONBLOCK | EFD_SEMAPHORE));\nuint64_t l = 16;\n- ASSERT_THAT(write(efd, &l, 4), SyscallFailsWithErrno(EINVAL));\n+ ASSERT_THAT(write(efd.get(), &l, 4), SyscallFailsWithErrno(EINVAL));\n}\nTEST(EventfdTest, SmallRead) {\n- int efd;\n- ASSERT_THAT(efd = eventfd(0, EFD_NONBLOCK | EFD_SEMAPHORE),\n- SyscallSucceeds());\n+ FileDescriptor efd =\n+ ASSERT_NO_ERRNO_AND_VALUE(NewEventFD(0, EFD_NONBLOCK | EFD_SEMAPHORE));\nuint64_t l = 1;\n- ASSERT_THAT(write(efd, &l, sizeof(l)), SyscallSucceeds());\n+ ASSERT_THAT(write(efd.get(), &l, sizeof(l)), SyscallSucceeds());\nl = 0;\n- ASSERT_THAT(read(efd, &l, 4), SyscallFailsWithErrno(EINVAL));\n+ ASSERT_THAT(read(efd.get(), &l, 4), SyscallFailsWithErrno(EINVAL));\n}\nTEST(EventfdTest, BigWrite) {\n- int efd;\n- ASSERT_THAT(efd = eventfd(0, EFD_NONBLOCK | EFD_SEMAPHORE),\n- SyscallSucceeds());\n+ FileDescriptor efd =\n+ ASSERT_NO_ERRNO_AND_VALUE(NewEventFD(0, EFD_NONBLOCK | EFD_SEMAPHORE));\nuint64_t big[16];\nbig[0] = 16;\n- ASSERT_THAT(write(efd, big, sizeof(big)), SyscallSucceeds());\n+ ASSERT_THAT(write(efd.get(), big, sizeof(big)), SyscallSucceeds());\n}\nTEST(EventfdTest, BigRead) {\n- int efd;\n- ASSERT_THAT(efd = eventfd(0, EFD_NONBLOCK | EFD_SEMAPHORE),\n- SyscallSucceeds());\n+ FileDescriptor efd =\n+ ASSERT_NO_ERRNO_AND_VALUE(NewEventFD(0, EFD_NONBLOCK | EFD_SEMAPHORE));\nuint64_t l = 1;\n- ASSERT_THAT(write(efd, &l, sizeof(l)), SyscallSucceeds());\n+ ASSERT_THAT(write(efd.get(), &l, sizeof(l)), SyscallSucceeds());\nuint64_t big[16];\n- ASSERT_THAT(read(efd, big, sizeof(big)), SyscallSucceeds());\n+ ASSERT_THAT(read(efd.get(), big, sizeof(big)), SyscallSucceeds());\nEXPECT_EQ(big[0], 1);\n}\nTEST(EventfdTest, BigWriteBigRead) {\n- int efd;\n- ASSERT_THAT(efd = eventfd(0, EFD_NONBLOCK | EFD_SEMAPHORE),\n- SyscallSucceeds());\n+ FileDescriptor efd =\n+ ASSERT_NO_ERRNO_AND_VALUE(NewEventFD(0, EFD_NONBLOCK | EFD_SEMAPHORE));\nuint64_t l[16];\nl[0] = 16;\n- ASSERT_THAT(write(efd, l, sizeof(l)), SyscallSucceeds());\n- ASSERT_THAT(read(efd, l, sizeof(l)), SyscallSucceeds());\n+ ASSERT_THAT(write(efd.get(), l, sizeof(l)), SyscallSucceeds());\n+ ASSERT_THAT(read(efd.get(), l, sizeof(l)), SyscallSucceeds());\nEXPECT_EQ(l[0], 1);\n}\n@@ -142,44 +137,39 @@ TEST(EventfdTest, NotifyNonZero_NoRandomSave) {\n// Waits will time out at 10 seconds.\nconstexpr int kEpollTimeoutMs = 10000;\n// Create an eventfd descriptor.\n- int efd;\n- ASSERT_THAT(efd = eventfd(7, EFD_SEMAPHORE | EFD_NONBLOCK),\n- SyscallSucceeds());\n+ FileDescriptor efd =\n+ ASSERT_NO_ERRNO_AND_VALUE(NewEventFD(7, EFD_NONBLOCK | EFD_SEMAPHORE));\n// Create an epoll fd to listen to efd.\n- int epollfd;\n- ASSERT_THAT(epollfd = epoll_create1(0), SyscallSucceeds());\n+ FileDescriptor epollfd = ASSERT_NO_ERRNO_AND_VALUE(NewEpollFD());\n// Add efd to epoll.\n- struct epoll_event add_ev;\n- add_ev.events = EPOLLIN | EPOLLET;\n- add_ev.data.fd = efd;\n- ASSERT_THAT(epoll_ctl(epollfd, EPOLL_CTL_ADD, efd, &add_ev),\n- SyscallSucceeds());\n+ ASSERT_NO_ERRNO(\n+ RegisterEpollFD(epollfd.get(), efd.get(), EPOLLIN | EPOLLET, efd.get()));\n// Use epoll to get a value from efd.\nstruct epoll_event out_ev;\n- int wait_out = epoll_wait(epollfd, &out_ev, 1, kEpollTimeoutMs);\n+ int wait_out = epoll_wait(epollfd.get(), &out_ev, 1, kEpollTimeoutMs);\nEXPECT_EQ(wait_out, 1);\n- EXPECT_EQ(efd, out_ev.data.fd);\n+ EXPECT_EQ(efd.get(), out_ev.data.fd);\nuint64_t val = 0;\n- ASSERT_THAT(read(efd, &val, sizeof(val)), SyscallSucceeds());\n+ ASSERT_THAT(read(efd.get(), &val, sizeof(val)), SyscallSucceeds());\nEXPECT_EQ(val, 1);\n// Start a thread that, after this thread blocks on epoll_wait, will write to\n// efd. This is racy -- it's possible that this write will happen after\n// epoll_wait times out.\n- ScopedThread t([efd] {\n+ ScopedThread t([&efd] {\nsleep(5);\nuint64_t val = 1;\n- write(efd, &val, sizeof(val));\n+ write(efd.get(), &val, sizeof(val));\n});\n// epoll_wait should return once the thread writes.\n- wait_out = epoll_wait(epollfd, &out_ev, 1, kEpollTimeoutMs);\n+ wait_out = epoll_wait(epollfd.get(), &out_ev, 1, kEpollTimeoutMs);\nEXPECT_EQ(wait_out, 1);\n- EXPECT_EQ(efd, out_ev.data.fd);\n+ EXPECT_EQ(efd.get(), out_ev.data.fd);\nval = 0;\n- ASSERT_THAT(read(efd, &val, sizeof(val)), SyscallSucceeds());\n+ ASSERT_THAT(read(efd.get(), &val, sizeof(val)), SyscallSucceeds());\nEXPECT_EQ(val, 1);\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/fallocate.cc",
"new_path": "test/syscalls/linux/fallocate.cc",
"diff": "// limitations under the License.\n#include <fcntl.h>\n-#include <sys/eventfd.h>\n#include <unistd.h>\n#include \"gtest/gtest.h\"\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/fcntl.cc",
"new_path": "test/syscalls/linux/fcntl.cc",
"diff": "#include <fcntl.h>\n#include <signal.h>\n-#include <sys/eventfd.h>\n#include <syscall.h>\n#include <unistd.h>\n#include \"absl/time/time.h\"\n#include \"test/syscalls/linux/socket_test_util.h\"\n#include \"test/util/cleanup.h\"\n+#include \"test/util/eventfd_util.h\"\n#include \"test/util/multiprocess_util.h\"\n#include \"test/util/posix_error.h\"\n#include \"test/util/temp_path.h\"\n@@ -112,17 +112,9 @@ PosixErrorOr<Cleanup> SubprocessLock(std::string const& path, bool for_write,\nreturn std::move(cleanup);\n}\n-PosixErrorOr<FileDescriptor> Eventfd(int count, int flags) {\n- int efd = eventfd(count, flags);\n- if (efd < 0) {\n- return PosixError(errno, \"Eventfd\");\n- }\n- return FileDescriptor(efd);\n-}\n-\nTEST(FcntlTest, SetCloExec) {\n// Open an eventfd file descriptor with FD_CLOEXEC descriptor flag not set.\n- FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(Eventfd(0, 0));\n+ FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(NewEventFD(0, 0));\nASSERT_THAT(fcntl(fd.get(), F_GETFD), SyscallSucceedsWithValue(0));\n// Set the FD_CLOEXEC flag.\n@@ -132,7 +124,7 @@ TEST(FcntlTest, SetCloExec) {\nTEST(FcntlTest, ClearCloExec) {\n// Open an eventfd file descriptor with FD_CLOEXEC descriptor flag set.\n- FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(Eventfd(0, EFD_CLOEXEC));\n+ FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(NewEventFD(0, EFD_CLOEXEC));\nASSERT_THAT(fcntl(fd.get(), F_GETFD), SyscallSucceedsWithValue(FD_CLOEXEC));\n// Clear the FD_CLOEXEC flag.\n@@ -142,7 +134,7 @@ TEST(FcntlTest, ClearCloExec) {\nTEST(FcntlTest, IndependentDescriptorFlags) {\n// Open an eventfd file descriptor with FD_CLOEXEC descriptor flag not set.\n- FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(Eventfd(0, 0));\n+ FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(NewEventFD(0, 0));\nASSERT_THAT(fcntl(fd.get(), F_GETFD), SyscallSucceedsWithValue(0));\n// Duplicate the descriptor. Ensure that it also doesn't have FD_CLOEXEC.\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/getdents.cc",
"new_path": "test/syscalls/linux/getdents.cc",
"diff": "#include <stdint.h>\n#include <stdio.h>\n#include <string.h>\n-#include <sys/eventfd.h>\n#include <sys/mman.h>\n#include <sys/types.h>\n#include <syscall.h>\n#include <unistd.h>\n#include <map>\n#include <string>\n+#include <unordered_map>\n#include <unordered_set>\n#include <utility>\n#include \"gtest/gtest.h\"\n#include \"absl/strings/numbers.h\"\n#include \"absl/strings/str_cat.h\"\n+#include \"test/util/eventfd_util.h\"\n#include \"test/util/file_descriptor.h\"\n#include \"test/util/fs_util.h\"\n#include \"test/util/posix_error.h\"\n@@ -368,16 +369,11 @@ TYPED_TEST(GetdentsTest, PartialBuffer) {\n// getdents iterates correctly despite mutation of /proc/self/fd.\nTYPED_TEST(GetdentsTest, ProcSelfFd) {\nconstexpr size_t kNfds = 10;\n- std::unordered_set<int> fds;\n- std::vector<FileDescriptor> fd_closers;\n- fd_closers.reserve(fds.size());\n- for (int fd : fds) {\n- fd_closers.emplace_back(fd);\n- }\n+ std::unordered_map<int, FileDescriptor> fds;\n+ fds.reserve(kNfds);\nfor (size_t i = 0; i < kNfds; i++) {\n- int fd;\n- ASSERT_THAT(fd = eventfd(0, 0), SyscallSucceeds());\n- fds.insert(fd);\n+ FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(NewEventFD());\n+ fds.emplace(fd.get(), std::move(fd));\n}\nconst FileDescriptor proc_self_fd =\n@@ -401,11 +397,7 @@ TYPED_TEST(GetdentsTest, ProcSelfFd) {\nif (!absl::SimpleAtoi(d->d_name, &dfd)) continue;\nEXPECT_TRUE(prev_fds.insert(dfd).second)\n<< \"Repeated observation of /proc/self/fd/\" << dfd;\n- auto it = fds.find(dfd);\n- if (it != fds.end()) {\n- fds.erase(it);\n- EXPECT_THAT(close(dfd), SyscallSucceeds());\n- }\n+ fds.erase(dfd);\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/util/BUILD",
"new_path": "test/util/BUILD",
"diff": "@@ -18,6 +18,17 @@ cc_library(\n],\n)\n+cc_library(\n+ name = \"eventfd_util\",\n+ testonly = 1,\n+ hdrs = [\"eventfd_util.h\"],\n+ deps = [\n+ \":file_descriptor\",\n+ \":posix_error\",\n+ \":save_util\",\n+ ],\n+)\n+\ncc_library(\nname = \"file_descriptor\",\ntestonly = 1,\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/util/eventfd_util.h",
"diff": "+// Copyright 2019 Google LLC\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+#ifndef GVISOR_TEST_UTIL_EVENTFD_UTIL_H_\n+#define GVISOR_TEST_UTIL_EVENTFD_UTIL_H_\n+\n+#include <sys/eventfd.h>\n+\n+#include <cerrno>\n+\n+#include \"test/util/file_descriptor.h\"\n+#include \"test/util/posix_error.h\"\n+#include \"test/util/save_util.h\"\n+\n+namespace gvisor {\n+namespace testing {\n+\n+// Returns a new eventfd with the given initial value and flags.\n+inline PosixErrorOr<FileDescriptor> NewEventFD(unsigned int initval = 0,\n+ int flags = 0) {\n+ int fd = eventfd(initval, flags);\n+ MaybeSave();\n+ if (fd < 0) {\n+ return PosixError(errno, \"eventfd\");\n+ }\n+ return FileDescriptor(fd);\n+}\n+\n+} // namespace testing\n+} // namespace gvisor\n+\n+#endif // GVISOR_TEST_UTIL_EVENTFD_UTIL_H_\n"
}
] | Go | Apache License 2.0 | google/gvisor | Refactor out NewEventFD to a test utility.
PiperOrigin-RevId: 231404512
Change-Id: I31efcc23a0c4a48ef6fbba3ca07415d79290f55c |
259,885 | 29.01.2019 09:05:51 | 28,800 | 3c5f8dfd4b0a7157343bacb62620e4f11612c3b7 | Don't assume that stdout is always writable in PollTest.Nfds.
stdout can be (and, in automated testing, often is) a host pipe or
similar resource shared between multiple parallel tests, such that it
can become transiently full during testing. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/BUILD",
"new_path": "test/syscalls/linux/BUILD",
"diff": "@@ -1246,6 +1246,7 @@ cc_binary(\nlinkstatic = 1,\ndeps = [\n\":base_poll_test\",\n+ \"//test/util:eventfd_util\",\n\"//test/util:file_descriptor\",\n\"//test/util:logging\",\n\"//test/util:test_main\",\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/poll.cc",
"new_path": "test/syscalls/linux/poll.cc",
"diff": "#include \"absl/time/clock.h\"\n#include \"absl/time/time.h\"\n#include \"test/syscalls/linux/base_poll_test.h\"\n+#include \"test/util/eventfd_util.h\"\n#include \"test/util/file_descriptor.h\"\n#include \"test/util/logging.h\"\n#include \"test/util/test_util.h\"\n@@ -256,12 +257,14 @@ TEST_F(PollTest, Nfds) {\nTEST_PCHECK(getrlimit(RLIMIT_NOFILE, &rlim) == 0);\nrlim_t max_fds = rlim.rlim_cur;\n+ // Create an eventfd. Since its value is initially zero, it is writable.\n+ FileDescriptor efd = ASSERT_NO_ERRNO_AND_VALUE(NewEventFD());\n+\n// Create the biggest possible pollfd array such that each element is valid.\n- //\n- // Each entry in the 'fds' array refers to stdout (fd=1) and polls for\n+ // Each entry in the 'fds' array refers to the eventfd and polls for\n// \"writable\" events (events=POLLOUT). This essentially guarantees that the\n// poll() is a no-op and allows negative testing of the 'nfds' parameter.\n- std::vector<struct pollfd> fds(max_fds, {.fd = 1, .events = POLLOUT});\n+ std::vector<struct pollfd> fds(max_fds, {.fd = efd.get(), .events = POLLOUT});\n// Verify that 'nfds' up to RLIMIT_NOFILE are allowed.\nEXPECT_THAT(RetryEINTR(poll)(fds.data(), 1, 1), SyscallSucceedsWithValue(1));\n"
}
] | Go | Apache License 2.0 | google/gvisor | Don't assume that stdout is always writable in PollTest.Nfds.
stdout can be (and, in automated testing, often is) a host pipe or
similar resource shared between multiple parallel tests, such that it
can become transiently full during testing.
PiperOrigin-RevId: 231413569
Change-Id: Id14991b5f71e53c894695899e65e1be4dd228cc6 |
259,854 | 29.01.2019 16:22:34 | 28,800 | ff1c3bb0b577a4ea55a64de39415a8d31142b741 | Fix NIC endpoint forwarding.
Also adds a test for regular NIC forwarding. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/BUILD",
"new_path": "pkg/tcpip/stack/BUILD",
"diff": "@@ -43,6 +43,7 @@ go_test(\n\"//pkg/tcpip/buffer\",\n\"//pkg/tcpip/header\",\n\"//pkg/tcpip/link/channel\",\n+ \"//pkg/tcpip/link/loopback\",\n\"//pkg/waiter\",\n],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/nic.go",
"new_path": "pkg/tcpip/stack/nic.go",
"diff": "@@ -428,6 +428,8 @@ func (n *NIC) DeliverNetworkPacket(linkEP LinkEndpoint, remote, _ tcpip.LinkAddr\nref, ok := n.endpoints[NetworkEndpointID{dst}]\nn.mu.RUnlock()\nif ok && ref.tryIncRef() {\n+ r.RemoteAddress = src\n+ // TODO: Update the source NIC as well.\nref.ep.HandlePacket(&r, vv)\nref.decRef()\n} else {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/stack_test.go",
"new_path": "pkg/tcpip/stack/stack_test.go",
"diff": "@@ -1039,6 +1039,45 @@ func TestGetMainNICAddressAddRemove(t *testing.T) {\n}\n}\n+func TestNICForwarding(t *testing.T) {\n+ // Create a stack with the fake network protocol, two NICs, each with\n+ // an address.\n+ s := stack.New([]string{\"fakeNet\"}, nil, stack.Options{})\n+ s.SetForwarding(true)\n+\n+ id1, linkEP1 := channel.New(10, defaultMTU, \"\")\n+ if err := s.CreateNIC(1, id1); err != nil {\n+ t.Fatalf(\"CreateNIC #1 failed: %v\", err)\n+ }\n+ if err := s.AddAddress(1, fakeNetNumber, \"\\x01\"); err != nil {\n+ t.Fatalf(\"AddAddress #1 failed: %v\", err)\n+ }\n+\n+ id2, linkEP2 := channel.New(10, defaultMTU, \"\")\n+ if err := s.CreateNIC(2, id2); err != nil {\n+ t.Fatalf(\"CreateNIC #2 failed: %v\", err)\n+ }\n+ if err := s.AddAddress(2, fakeNetNumber, \"\\x02\"); err != nil {\n+ t.Fatalf(\"AddAddress #2 failed: %v\", err)\n+ }\n+\n+ // Route all packets to address 3 to NIC 2.\n+ s.SetRouteTable([]tcpip.Route{\n+ {\"\\x03\", \"\\xff\", \"\\x00\", 2},\n+ })\n+\n+ // Send a packet to address 3.\n+ buf := buffer.NewView(30)\n+ buf[0] = 3\n+ linkEP1.Inject(fakeNetNumber, buf.ToVectorisedView())\n+\n+ select {\n+ case <-linkEP2.C:\n+ default:\n+ t.Fatal(\"Packet not forwarded\")\n+ }\n+}\n+\nfunc init() {\nstack.RegisterNetworkProtocolFactory(\"fakeNet\", func() stack.NetworkProtocol {\nreturn &fakeNetworkProtocol{}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/transport_test.go",
"new_path": "pkg/tcpip/stack/transport_test.go",
"diff": "@@ -20,6 +20,7 @@ import (\n\"gvisor.googlesource.com/gvisor/pkg/tcpip\"\n\"gvisor.googlesource.com/gvisor/pkg/tcpip/buffer\"\n\"gvisor.googlesource.com/gvisor/pkg/tcpip/link/channel\"\n+ \"gvisor.googlesource.com/gvisor/pkg/tcpip/link/loopback\"\n\"gvisor.googlesource.com/gvisor/pkg/tcpip/stack\"\n\"gvisor.googlesource.com/gvisor/pkg/waiter\"\n)\n@@ -42,6 +43,9 @@ type fakeTransportEndpoint struct {\nproto *fakeTransportProtocol\npeerAddr tcpip.Address\nroute stack.Route\n+\n+ // acceptQueue is non-nil iff bound.\n+ acceptQueue []fakeTransportEndpoint\n}\nfunc newFakeTransportEndpoint(stack *stack.Stack, proto *fakeTransportProtocol, netProto tcpip.NetworkProtocolNumber) tcpip.Endpoint {\n@@ -132,11 +136,27 @@ func (*fakeTransportEndpoint) Listen(int) *tcpip.Error {\nreturn nil\n}\n-func (*fakeTransportEndpoint) Accept() (tcpip.Endpoint, *waiter.Queue, *tcpip.Error) {\n+func (f *fakeTransportEndpoint) Accept() (tcpip.Endpoint, *waiter.Queue, *tcpip.Error) {\n+ if len(f.acceptQueue) == 0 {\nreturn nil, nil, nil\n}\n+ a := f.acceptQueue[0]\n+ f.acceptQueue = f.acceptQueue[1:]\n+ return &a, nil, nil\n+}\n-func (*fakeTransportEndpoint) Bind(_ tcpip.FullAddress, commit func() *tcpip.Error) *tcpip.Error {\n+func (f *fakeTransportEndpoint) Bind(a tcpip.FullAddress, commit func() *tcpip.Error) *tcpip.Error {\n+ if err := f.stack.RegisterTransportEndpoint(\n+ a.NIC,\n+ []tcpip.NetworkProtocolNumber{fakeNetNumber},\n+ fakeTransNumber,\n+ stack.TransportEndpointID{LocalAddress: a.Addr},\n+ f,\n+ false,\n+ ); err != nil {\n+ return err\n+ }\n+ f.acceptQueue = []fakeTransportEndpoint{}\nreturn commit()\n}\n@@ -148,9 +168,19 @@ func (*fakeTransportEndpoint) GetRemoteAddress() (tcpip.FullAddress, *tcpip.Erro\nreturn tcpip.FullAddress{}, nil\n}\n-func (f *fakeTransportEndpoint) HandlePacket(*stack.Route, stack.TransportEndpointID, buffer.VectorisedView) {\n+func (f *fakeTransportEndpoint) HandlePacket(r *stack.Route, id stack.TransportEndpointID, _ buffer.VectorisedView) {\n// Increment the number of received packets.\nf.proto.packetCount++\n+ if f.acceptQueue != nil {\n+ f.acceptQueue = append(f.acceptQueue, fakeTransportEndpoint{\n+ id: id,\n+ stack: f.stack,\n+ netProto: f.netProto,\n+ proto: f.proto,\n+ peerAddr: r.RemoteAddress,\n+ route: r.Clone(),\n+ })\n+ }\n}\nfunc (f *fakeTransportEndpoint) HandleControlPacket(stack.TransportEndpointID, stack.ControlType, uint32, buffer.VectorisedView) {\n@@ -415,6 +445,76 @@ func TestTransportOptions(t *testing.T) {\n}\n}\n+func TestTransportForwarding(t *testing.T) {\n+ s := stack.New([]string{\"fakeNet\"}, []string{\"fakeTrans\"}, stack.Options{})\n+ s.SetForwarding(true)\n+\n+ // TODO: Change this to a channel NIC.\n+ id1 := loopback.New()\n+ if err := s.CreateNIC(1, id1); err != nil {\n+ t.Fatalf(\"CreateNIC #1 failed: %v\", err)\n+ }\n+ if err := s.AddAddress(1, fakeNetNumber, \"\\x01\"); err != nil {\n+ t.Fatalf(\"AddAddress #1 failed: %v\", err)\n+ }\n+\n+ id2, linkEP2 := channel.New(10, defaultMTU, \"\")\n+ if err := s.CreateNIC(2, id2); err != nil {\n+ t.Fatalf(\"CreateNIC #2 failed: %v\", err)\n+ }\n+ if err := s.AddAddress(2, fakeNetNumber, \"\\x02\"); err != nil {\n+ t.Fatalf(\"AddAddress #2 failed: %v\", err)\n+ }\n+\n+ // Route all packets to address 3 to NIC 2 and all packets to address\n+ // 1 to NIC 1.\n+ s.SetRouteTable([]tcpip.Route{\n+ {\"\\x03\", \"\\xff\", \"\\x00\", 2},\n+ {\"\\x01\", \"\\xff\", \"\\x00\", 1},\n+ })\n+\n+ wq := waiter.Queue{}\n+ ep, err := s.NewEndpoint(fakeTransNumber, fakeNetNumber, &wq)\n+ if err != nil {\n+ t.Fatalf(\"NewEndpoint failed: %v\", err)\n+ }\n+\n+ if err := ep.Bind(tcpip.FullAddress{Addr: \"\\x01\", NIC: 1}, func() *tcpip.Error { return nil }); err != nil {\n+ t.Fatalf(\"Bind failed: %v\", err)\n+ }\n+\n+ // Send a packet to address 1 from address 3.\n+ req := buffer.NewView(30)\n+ req[0] = 1\n+ req[1] = 3\n+ req[2] = byte(fakeTransNumber)\n+ linkEP2.Inject(fakeNetNumber, req.ToVectorisedView())\n+\n+ aep, _, err := ep.Accept()\n+ if err != nil || aep == nil {\n+ t.Fatalf(\"Accept failed: %v, %v\", aep, err)\n+ }\n+\n+ resp := buffer.NewView(30)\n+ if _, _, err := aep.Write(tcpip.SlicePayload(resp), tcpip.WriteOptions{}); err != nil {\n+ t.Fatalf(\"Write failed: %v\", err)\n+ }\n+\n+ var p channel.PacketInfo\n+ select {\n+ case p = <-linkEP2.C:\n+ default:\n+ t.Fatal(\"Response packet not forwarded\")\n+ }\n+\n+ if dst := p.Header[0]; dst != 3 {\n+ t.Errorf(\"Response packet has incorrect destination addresss: got = %d, want = 3\", dst)\n+ }\n+ if src := p.Header[1]; src != 1 {\n+ t.Errorf(\"Response packet has incorrect source addresss: got = %d, want = 3\", src)\n+ }\n+}\n+\nfunc init() {\nstack.RegisterTransportProtocolFactory(\"fakeTrans\", func() stack.TransportProtocol {\nreturn &fakeTransportProtocol{}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix NIC endpoint forwarding.
Also adds a test for regular NIC forwarding.
PiperOrigin-RevId: 231495279
Change-Id: Ic7edec249568e9ad0280cea77eac14478c9073e1 |
259,853 | 29.01.2019 17:14:26 | 28,800 | dd577f5410a90d31a927b7b0fd6c4bb32b34b9f9 | runsc: reap a sandbox process only in sandbox.Wait() | [
{
"change_type": "MODIFY",
"old_path": "runsc/boot/controller.go",
"new_path": "runsc/boot/controller.go",
"diff": "@@ -235,7 +235,7 @@ func (cm *containerManager) Start(args *StartArgs, _ *struct{}) error {\nerr := cm.l.startContainer(cm.l.k, args.Spec, args.Conf, args.CID, args.FilePayload.Files)\nif err != nil {\n- log.Debugf(\"containerManager.Start failed %q: %+v\", args.CID, args)\n+ log.Debugf(\"containerManager.Start failed %q: %+v: %v\", args.CID, args, err)\nreturn err\n}\nlog.Debugf(\"Container %q started\", args.CID)\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/sandbox/sandbox.go",
"new_path": "runsc/sandbox/sandbox.go",
"diff": "@@ -21,6 +21,7 @@ import (\n\"os\"\n\"os/exec\"\n\"strconv\"\n+ \"sync\"\n\"syscall\"\n\"time\"\n@@ -64,6 +65,12 @@ type Sandbox struct {\n// This field isn't saved to json, because only a creator of sandbox\n// will have it as a child process.\nchild bool\n+\n+ // status is an exit status of a sandbox process.\n+ status syscall.WaitStatus\n+\n+ // statusMu protects status.\n+ statusMu sync.Mutex\n}\n// New creates the sandbox process. The caller must call Destroy() on the\n@@ -628,18 +635,13 @@ func (s *Sandbox) Wait(cid string) (syscall.WaitStatus, error) {\n// Wait RPC. The best we can do is ask Linux what the sandbox exit\n// status was, since in most cases that will be the same as the\n// container exit status.\n- p, err := os.FindProcess(s.Pid)\n- if err != nil {\n- // \"On Unix systems, FindProcess always succeeds and returns a\n- // Process for the given pid, regardless of whether the process\n- // exists.\"\n- return ws, fmt.Errorf(\"Find process %d: %v\", s.Pid, err)\n+ if err := s.waitForStopped(); err != nil {\n+ return ws, err\n}\n- ps, err := p.Wait()\n- if err != nil {\n- return ws, fmt.Errorf(\"sandbox no longer running, tried to get exit status, but Wait failed: %v\", err)\n+ if !s.child {\n+ return ws, fmt.Errorf(\"sandbox no longer running and its exit status is unavailable\")\n}\n- return ps.Sys().(syscall.WaitStatus), nil\n+ return s.status, nil\n}\n// WaitPID waits for process 'pid' in the container's sandbox and returns its\n@@ -853,10 +855,15 @@ func (s *Sandbox) waitForStopped() error {\ndefer cancel()\nb := backoff.WithContext(backoff.NewConstantBackOff(100*time.Millisecond), ctx)\nop := func() error {\n- if s.child && s.Pid != 0 {\n+ if s.child {\n+ s.statusMu.Lock()\n+ defer s.statusMu.Unlock()\n+ if s.Pid == 0 {\n+ return nil\n+ }\n// The sandbox process is a child of the current process,\n// so we can wait it and collect its zombie.\n- wpid, err := syscall.Wait4(int(s.Pid), nil, syscall.WNOHANG, nil)\n+ wpid, err := syscall.Wait4(int(s.Pid), &s.status, syscall.WNOHANG, nil)\nif err != nil {\nreturn fmt.Errorf(\"error waiting the sandbox process: %v\", err)\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | runsc: reap a sandbox process only in sandbox.Wait()
PiperOrigin-RevId: 231504064
Change-Id: I585b769aef04a3ad7e7936027958910a6eed9c8d |
259,974 | 30.01.2019 11:48:02 | 28,800 | cedff8d3aef3bc2055b1a7c3ad47a4c8297367ea | Add muldiv/rd_tsc support for arm64 platform. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/time/BUILD",
"new_path": "pkg/sentry/time/BUILD",
"diff": "load(\"//tools/go_stateify:defs.bzl\", \"go_library\", \"go_test\")\n-package(licenses = [\"notice\"]) # Apache 2.0\n+package(licenses = [\"notice\"]) # Apache 2.0, portions BSD\nload(\"//tools/go_generics:defs.bzl\", \"go_template_instance\")\n@@ -18,15 +18,18 @@ go_template_instance(\ngo_library(\nname = \"time\",\nsrcs = [\n+ \"arith_arm64.go\",\n\"calibrated_clock.go\",\n\"clock_id.go\",\n\"clocks.go\",\n\"muldiv_amd64.s\",\n+ \"muldiv_arm64.s\",\n\"parameters.go\",\n\"sampler.go\",\n\"sampler_unsafe.go\",\n\"seqatomic_parameters.go\",\n\"tsc_amd64.s\",\n+ \"tsc_arm64.s\",\n],\nimportpath = \"gvisor.googlesource.com/gvisor/pkg/sentry/time\",\nvisibility = [\"//pkg/sentry:internal\"],\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/time/LICENSE",
"diff": "+Copyright (c) 2009 The Go Authors. All rights reserved.\n+\n+Redistribution and use in source and binary forms, with or without\n+modification, are permitted provided that the following conditions are\n+met:\n+\n+ * Redistributions of source code must retain the above copyright\n+notice, this list of conditions and the following disclaimer.\n+ * Redistributions in binary form must reproduce the above\n+copyright notice, this list of conditions and the following disclaimer\n+in the documentation and/or other materials provided with the\n+distribution.\n+ * Neither the name of Google Inc. nor the names of its\n+contributors may be used to endorse or promote products derived from\n+this software without specific prior written permission.\n+\n+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n+\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/time/arith_arm64.go",
"diff": "+// Copyright 2009 The Go Authors. All rights reserved.\n+// Use of this source code is governed by a BSD-style\n+// license that can be found in the LICENSE file.\n+\n+// This file provides a generic Go implementation of uint128 divided by uint64.\n+\n+// The code is derived from Go's generic math/big.divWW_g\n+// (src/math/big/arith.go), but is only used on ARM64.\n+\n+package time\n+\n+import \"math/bits\"\n+\n+type word uint\n+\n+const (\n+ _W = bits.UintSize // word size in bits\n+ _W2 = _W / 2 // half word size in bits\n+ _B2 = 1 << _W2 // half digit base\n+ _M2 = _B2 - 1 // half digit mask\n+)\n+\n+// nlz returns the number of leading zeros in x.\n+// Wraps bits.LeadingZeros call for convenience.\n+func nlz(x word) uint {\n+ return uint(bits.LeadingZeros(uint(x)))\n+}\n+\n+// q = (u1<<_W + u0 - r)/y\n+// Adapted from Warren, Hacker's Delight, p. 152.\n+func divWW(u1, u0, v word) (q, r word) {\n+ if u1 >= v {\n+ return 1<<_W - 1, 1<<_W - 1\n+ }\n+\n+ s := nlz(v)\n+ v <<= s\n+\n+ vn1 := v >> _W2\n+ vn0 := v & _M2\n+ un32 := u1<<s | u0>>(_W-s)\n+ un10 := u0 << s\n+ un1 := un10 >> _W2\n+ un0 := un10 & _M2\n+ q1 := un32 / vn1\n+ rhat := un32 - q1*vn1\n+\n+ for q1 >= _B2 || q1*vn0 > _B2*rhat+un1 {\n+ q1--\n+ rhat += vn1\n+\n+ if rhat >= _B2 {\n+ break\n+ }\n+ }\n+\n+ un21 := un32*_B2 + un1 - q1*v\n+ q0 := un21 / vn1\n+ rhat = un21 - q0*vn1\n+\n+ for q0 >= _B2 || q0*vn0 > _B2*rhat+un0 {\n+ q0--\n+ rhat += vn1\n+ if rhat >= _B2 {\n+ break\n+ }\n+ }\n+\n+ return q1*_B2 + q0, (un21*_B2 + un0 - q0*v) >> s\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add muldiv/rd_tsc support for arm64 platform.
Signed-off-by: Haibo Xu <[email protected]>
Change-Id: If35459be78e023346a140184401172f8e023c7f9
PiperOrigin-RevId: 231638020 |
259,853 | 31.01.2019 10:33:09 | 28,800 | 7e8a56087bfb4ab89e058cd9f9d2459a06275559 | runsc: check whether a container is deleted or not before setupContainerFS | [
{
"change_type": "MODIFY",
"old_path": "runsc/boot/loader.go",
"new_path": "runsc/boot/loader.go",
"diff": "@@ -430,6 +430,15 @@ func (l *Loader) run() error {\n}\n}\n+ l.mu.Lock()\n+ defer l.mu.Unlock()\n+\n+ eid := execID{cid: l.sandboxID}\n+ ep, ok := l.processes[eid]\n+ if !ok {\n+ return fmt.Errorf(\"trying to start deleted container %q\", l.sandboxID)\n+ }\n+\n// Finally done with all configuration. Setup filters before user code\n// is loaded.\nif l.conf.DisableSeccomp {\n@@ -478,14 +487,6 @@ func (l *Loader) run() error {\nl.rootProcArgs.FDMap.DecRef()\n}\n- l.mu.Lock()\n- defer l.mu.Unlock()\n-\n- eid := execID{cid: l.sandboxID}\n- ep := l.processes[eid]\n- if ep == nil {\n- return fmt.Errorf(\"trying to start deleted container %q\", l.sandboxID)\n- }\nep.tg = l.k.GlobalInit()\nif l.console {\nttyFile := l.rootProcArgs.FDMap.GetFile(0)\n@@ -524,6 +525,14 @@ func (l *Loader) startContainer(k *kernel.Kernel, spec *specs.Spec, conf *Config\nreturn fmt.Errorf(\"creating capabilities: %v\", err)\n}\n+ l.mu.Lock()\n+ defer l.mu.Unlock()\n+\n+ eid := execID{cid: cid}\n+ if _, ok := l.processes[eid]; !ok {\n+ return fmt.Errorf(\"trying to start a deleted container %q\", cid)\n+ }\n+\n// Convert the spec's additional GIDs to KGIDs.\nextraKGIDs := make([]auth.KGID, 0, len(spec.Process.User.AdditionalGids))\nfor _, GID := range spec.Process.User.AdditionalGids {\n@@ -586,14 +595,6 @@ func (l *Loader) startContainer(k *kernel.Kernel, spec *specs.Spec, conf *Config\nreturn fmt.Errorf(\"setting executable path for %+v: %v\", procArgs, err)\n}\n- l.mu.Lock()\n- defer l.mu.Unlock()\n-\n- eid := execID{cid: cid}\n- if _, ok := l.processes[eid]; !ok {\n- return fmt.Errorf(\"trying to start a deleted container %q\", cid)\n- }\n-\ntg, _, err := l.k.CreateProcess(procArgs)\nif err != nil {\nreturn fmt.Errorf(\"creating process: %v\", err)\n"
}
] | Go | Apache License 2.0 | google/gvisor | runsc: check whether a container is deleted or not before setupContainerFS
PiperOrigin-RevId: 231811387
Change-Id: Ib143fb9a4d0fa1f105d1a3a3bd533dfc44e792af |
259,992 | 31.01.2019 11:29:55 | 28,800 | f1c1ee8a8ea6c0035aa799af3d7f5733fa2275d0 | Don't mask out sticky bit to/from gofer
RELNOTES: sticky bit propagates to gofers now. | [
{
"change_type": "MODIFY",
"old_path": "pkg/p9/buffer.go",
"new_path": "pkg/p9/buffer.go",
"diff": "@@ -144,7 +144,7 @@ func (b *buffer) ReadGID() GID {\n// ReadPermissions reads a file mode value and applies the mask for permissions.\nfunc (b *buffer) ReadPermissions() FileMode {\n- return b.ReadFileMode() & PermissionsMask\n+ return b.ReadFileMode() & permissionsMask\n}\n// ReadFileMode reads a file mode value.\n@@ -230,7 +230,7 @@ func (b *buffer) WriteGID(gid GID) {\n// WritePermissions applies a permissions mask and writes the FileMode.\nfunc (b *buffer) WritePermissions(perm FileMode) {\n- b.WriteFileMode(perm & PermissionsMask)\n+ b.WriteFileMode(perm & permissionsMask)\n}\n// WriteFileMode writes a FileMode.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/p9/p9.go",
"new_path": "pkg/p9/p9.go",
"diff": "@@ -130,8 +130,12 @@ const (\n// Exec is a mode bit indicating exec permission.\nExec FileMode = 01\n- // PermissionsMask is the mask to apply to FileModes for permissions.\n- PermissionsMask FileMode = 0777\n+ // AllPermissions is a mask with rwx bits set for user, group and others.\n+ AllPermissions FileMode = 0777\n+\n+ // permissionsMask is the mask to apply to FileModes for permissions. It\n+ // includes rwx bits for user, group and others, and sticky bit (01000).\n+ permissionsMask FileMode = 01777\n)\n// QIDType is the most significant byte of the FileMode word, to be used as the\n@@ -157,7 +161,7 @@ func (m FileMode) FileType() FileMode {\n// Permissions returns just the permission bits of the mode.\nfunc (m FileMode) Permissions() FileMode {\n- return m & PermissionsMask\n+ return m & permissionsMask\n}\n// Writable returns the mode with write bits added.\n@@ -987,7 +991,7 @@ func (s *SetAttr) Encode(b *buffer) {\n// Apply applies this to the given Attr.\nfunc (a *Attr) Apply(mask SetAttrMask, attr SetAttr) {\nif mask.Permissions {\n- a.Mode = a.Mode&^PermissionsMask | (attr.Permissions & PermissionsMask)\n+ a.Mode = a.Mode&^permissionsMask | (attr.Permissions & permissionsMask)\n}\nif mask.UID {\na.UID = attr.UID\n"
}
] | Go | Apache License 2.0 | google/gvisor | Don't mask out sticky bit to/from gofer
RELNOTES: sticky bit propagates to gofers now.
PiperOrigin-RevId: 231822453
Change-Id: I73426170b9457350480a3b144a2baf937e7cb477 |
259,992 | 31.01.2019 12:53:00 | 28,800 | a497f5ed5f97e4ad49ed60dd46f0146ae45eefd6 | Invalidate COW mappings when file is truncated
This changed required making fsutil.HostMappable use
a backing file to ensure the correct FD would be used
for read/write operations.
RELNOTES: relnotes is needed for the parent CL. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/fsutil/BUILD",
"new_path": "pkg/sentry/fs/fsutil/BUILD",
"diff": "@@ -71,7 +71,6 @@ go_library(\n\"host_file_mapper_state.go\",\n\"host_file_mapper_unsafe.go\",\n\"host_mappable.go\",\n- \"host_mappable_state.go\",\n\"inode.go\",\n\"inode_cached.go\",\n],\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/fsutil/host_mappable.go",
"new_path": "pkg/sentry/fs/fsutil/host_mappable.go",
"diff": "package fsutil\nimport (\n+ \"math\"\n\"sync\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/context\"\n+ \"gvisor.googlesource.com/gvisor/pkg/sentry/fs\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/memmap\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/platform\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/safemem\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/usermem\"\n)\n-// HostMappable implements memmap.Mappable and platform.File over an arbitrary\n-// host file descriptor.\n+// HostMappable implements memmap.Mappable and platform.File over a\n+// CachedFileObject.\n+//\n+// Lock order (compare the lock order model in mm/mm.go):\n+// truncateMu (\"fs locks\")\n+// mu (\"memmap.Mappable locks not taken by Translate\")\n+// (\"platform.File locks\")\n+// backingFile (\"CachedFileObject locks\")\n//\n// +stateify savable\ntype HostMappable struct {\nhostFileMapper *HostFileMapper\n- mu sync.Mutex `state:\"nosave\"`\n+ backingFile CachedFileObject\n- // fd is the file descriptor to the host. Protected by mu.\n- fd int `state:\"nosave\"`\n+ mu sync.Mutex `state:\"nosave\"`\n// mappings tracks mappings of the cached file object into\n// memmap.MappingSpaces so it can invalidated upon save. Protected by mu.\nmappings memmap.MappingSet\n+\n+ // truncateMu protects writes and truncations. See Truncate() for details.\n+ truncateMu sync.RWMutex `state:\"nosave\"`\n}\n// NewHostMappable creates a new mappable that maps directly to host FD.\n-func NewHostMappable() *HostMappable {\n+func NewHostMappable(backingFile CachedFileObject) *HostMappable {\nreturn &HostMappable{\nhostFileMapper: NewHostFileMapper(),\n- fd: -1,\n- }\n-}\n-\n-func (h *HostMappable) getFD() int {\n- h.mu.Lock()\n- defer h.mu.Unlock()\n- if h.fd < 0 {\n- panic(\"HostMappable FD isn't set\")\n+ backingFile: backingFile,\n}\n- return h.fd\n-}\n-\n-// UpdateFD sets the host FD iff FD hasn't been set before or if there are\n-// no mappings.\n-func (h *HostMappable) UpdateFD(fd int) {\n- h.mu.Lock()\n- defer h.mu.Unlock()\n- h.fd = fd\n}\n// AddMapping implements memmap.Mappable.AddMapping.\n@@ -115,12 +108,12 @@ func (h *HostMappable) InvalidateUnsavable(ctx context.Context) error {\n// MapInto implements platform.File.MapInto.\nfunc (h *HostMappable) MapInto(as platform.AddressSpace, addr usermem.Addr, fr platform.FileRange, at usermem.AccessType, precommit bool) error {\n- return as.MapFile(addr, h.getFD(), fr, at, precommit)\n+ return as.MapFile(addr, h.backingFile.FD(), fr, at, precommit)\n}\n// MapInternal implements platform.File.MapInternal.\nfunc (h *HostMappable) MapInternal(fr platform.FileRange, at usermem.AccessType) (safemem.BlockSeq, error) {\n- return h.hostFileMapper.MapInternal(fr, h.getFD(), at.Write)\n+ return h.hostFileMapper.MapInternal(fr, h.backingFile.FD(), at.Write)\n}\n// IncRef implements platform.File.IncRef.\n@@ -134,3 +127,62 @@ func (h *HostMappable) DecRef(fr platform.FileRange) {\nmr := memmap.MappableRange{Start: fr.Start, End: fr.End}\nh.hostFileMapper.DecRefOn(mr)\n}\n+\n+// Truncate truncates the file, invalidating any mapping that may have been\n+// removed after the size change.\n+//\n+// Truncation and writes are synchronized to prevent races where writes make the\n+// file grow between truncation and invalidation below:\n+// T1: Calls SetMaskedAttributes and stalls\n+// T2: Appends to file causing it to grow\n+// T2: Writes to mapped pages and COW happens\n+// T1: Continues and wronly invalidates the page mapped in step above.\n+func (h *HostMappable) Truncate(ctx context.Context, newSize int64) error {\n+ h.truncateMu.Lock()\n+ defer h.truncateMu.Unlock()\n+\n+ mask := fs.AttrMask{Size: true}\n+ attr := fs.UnstableAttr{Size: newSize}\n+ if err := h.backingFile.SetMaskedAttributes(ctx, mask, attr); err != nil {\n+ return err\n+ }\n+\n+ // Invalidate COW mappings that may exist beyond the new size in case the file\n+ // is being shrunk. Other mappinsg don't need to be invalidated because\n+ // translate will just return identical mappings after invalidation anyway,\n+ // and SIGBUS will be raised and handled when the mappings are touched.\n+ //\n+ // Compare Linux's mm/truncate.c:truncate_setsize() =>\n+ // truncate_pagecache() =>\n+ // mm/memory.c:unmap_mapping_range(evencows=1).\n+ h.mu.Lock()\n+ defer h.mu.Unlock()\n+ mr := memmap.MappableRange{\n+ Start: fs.OffsetPageEnd(newSize),\n+ End: fs.OffsetPageEnd(math.MaxInt64),\n+ }\n+ h.mappings.Invalidate(mr, memmap.InvalidateOpts{InvalidatePrivate: true})\n+\n+ return nil\n+}\n+\n+// Write writes to the file backing this mappable.\n+func (h *HostMappable) Write(ctx context.Context, src usermem.IOSequence, offset int64) (int64, error) {\n+ h.truncateMu.RLock()\n+ n, err := src.CopyInTo(ctx, &writer{ctx: ctx, hostMappable: h, off: offset})\n+ h.truncateMu.RUnlock()\n+ return n, err\n+}\n+\n+type writer struct {\n+ ctx context.Context\n+ hostMappable *HostMappable\n+ off int64\n+}\n+\n+// WriteFromBlocks implements safemem.Writer.WriteFromBlocks.\n+func (w *writer) WriteFromBlocks(src safemem.BlockSeq) (uint64, error) {\n+ n, err := w.hostMappable.backingFile.WriteFromBlocksAt(w.ctx, src, uint64(w.off))\n+ w.off += int64(n)\n+ return n, err\n+}\n"
},
{
"change_type": "DELETE",
"old_path": "pkg/sentry/fs/fsutil/host_mappable_state.go",
"new_path": null,
"diff": "-// Copyright 2019 Google LLC\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 fsutil\n-\n-// afterLoad is invoked by stateify.\n-func (h *HostMappable) afterLoad() {\n- h.mu.Lock()\n- defer h.mu.Unlock()\n- h.fd = -1\n-}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/gofer/file.go",
"new_path": "pkg/sentry/fs/gofer/file.go",
"diff": "@@ -215,6 +215,9 @@ func (f *fileOperations) Write(ctx context.Context, file *fs.File, src usermem.I\n}\nreturn n, err\n}\n+ if f.inodeOperations.fileState.hostMappable != nil {\n+ return f.inodeOperations.fileState.hostMappable.Write(ctx, src, offset)\n+ }\nreturn src.CopyInTo(ctx, f.handles.readWriterAt(ctx, offset))\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/gofer/inode.go",
"new_path": "pkg/sentry/fs/gofer/inode.go",
"diff": "@@ -170,9 +170,6 @@ func (i *inodeFileState) setHandlesForCachedIO(flags fs.FileFlags, h *handles) {\ni.writebackRW = true\n}\n}\n- if i.hostMappable != nil {\n- i.hostMappable.UpdateFD(i.fdLocked())\n- }\n}\n// getCachedHandles returns any cached handles which would accelerate\n@@ -520,6 +517,9 @@ func (i *inodeOperations) Truncate(ctx context.Context, inode *fs.Inode, length\nif i.session().cachePolicy.useCachingInodeOps(inode) {\nreturn i.cachingInodeOps.Truncate(ctx, inode, length)\n}\n+ if i.session().cachePolicy == cacheRemoteRevalidating {\n+ return i.fileState.hostMappable.Truncate(ctx, length)\n+ }\nreturn i.fileState.file.setAttr(ctx, p9.SetAttrMask{Size: true}, p9.SetAttr{Size: uint64(length)})\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/gofer/session.go",
"new_path": "pkg/sentry/fs/gofer/session.go",
"diff": "@@ -197,17 +197,14 @@ func newInodeOperations(ctx context.Context, s *session, file contextFile, qid p\n}\n}\n- var hm *fsutil.HostMappable\n- if s.cachePolicy == cacheRemoteRevalidating && fs.IsFile(sattr) {\n- hm = fsutil.NewHostMappable()\n- }\n-\nfileState := &inodeFileState{\ns: s,\nfile: file,\nsattr: sattr,\nkey: deviceKey,\n- hostMappable: hm,\n+ }\n+ if s.cachePolicy == cacheRemoteRevalidating && fs.IsFile(sattr) {\n+ fileState.hostMappable = fsutil.NewHostMappable(fileState)\n}\nuattr := unstable(ctx, valid, attr, s.mounter, s.client)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Invalidate COW mappings when file is truncated
This changed required making fsutil.HostMappable use
a backing file to ensure the correct FD would be used
for read/write operations.
RELNOTES: relnotes is needed for the parent CL.
PiperOrigin-RevId: 231836164
Change-Id: I8ae9639715529874ea7d80a65e2c711a5b4ce254 |
259,992 | 31.01.2019 14:36:52 | 28,800 | aec5b67c8116035fca8b8c560debe66b04b788a7 | Add syscall test dimension for --file_access=shared | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/build_defs.bzl",
"new_path": "test/syscalls/build_defs.bzl",
"diff": "@@ -6,18 +6,22 @@ def syscall_test(test, shard_count = 5, size = \"small\", use_tmpfs = False):\n_syscall_test(test, shard_count, size, \"native\", False)\n_syscall_test(test, shard_count, size, \"kvm\", use_tmpfs)\n_syscall_test(test, shard_count, size, \"ptrace\", use_tmpfs)\n+ if not use_tmpfs:\n+ _syscall_test(test, shard_count, size, \"ptrace\", use_tmpfs, \"shared\")\n-def _syscall_test(test, shard_count, size, platform, use_tmpfs):\n+def _syscall_test(test, shard_count, size, platform, use_tmpfs, file_access = \"exclusive\"):\ntest_name = test.split(\":\")[1]\n# Prepend \"runsc\" to non-native platform names.\nfull_platform = platform if platform == \"native\" else \"runsc_\" + platform\nname = test_name + \"_\" + full_platform\n+ if file_access == \"shared\":\n+ name += \"_shared\"\n- # Add the full_platform in a tag to make it easier to run all the tests on\n- # a specific platform.\n- tags = [full_platform]\n+ # Add the full_platform and file access in a tag to make it easier to run\n+ # all the tests on a specific flavor. Use --test_tag_filters=ptrace,file_shared.\n+ tags = [full_platform, \"file_\" + file_access]\n# Add tag to prevent the tests from running in a Bazel sandbox.\n# TODO: Make the tests run without this tag.\n@@ -40,8 +44,7 @@ def _syscall_test(test, shard_count, size, platform, use_tmpfs):\n\"--test-name=\" + test_name,\n\"--platform=\" + platform,\n\"--use-tmpfs=\" + str(use_tmpfs),\n- \"--debug=false\",\n- \"--strace=false\",\n+ \"--file-access=\" + file_access,\n\"--parallel=true\",\n],\nsize = size,\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/syscall_test_runner.go",
"new_path": "test/syscalls/syscall_test_runner.go",
"diff": "@@ -46,6 +46,7 @@ var (\nstrace = flag.Bool(\"strace\", false, \"enable strace logs\")\nplatform = flag.String(\"platform\", \"ptrace\", \"platform to run on\")\nuseTmpfs = flag.Bool(\"use-tmpfs\", false, \"mounts tmpfs for /tmp\")\n+ fileAccess = flag.String(\"file-access\", \"exclusive\", \"mounts root in exclusive or shared mode\")\nparallel = flag.Bool(\"parallel\", false, \"run tests in parallel\")\nrunscPath = flag.String(\"runsc\", \"\", \"path to runsc binary\")\n)\n@@ -158,6 +159,7 @@ func runTestCaseRunsc(testBin string, tc gtest.TestCase, t *testing.T) {\nargs := []string{\n\"-platform\", *platform,\n\"-root\", rootDir,\n+ \"-file-access\", *fileAccess,\n\"--network=none\",\n\"-log-format=text\",\n\"-TESTONLY-unsafe-nonroot=true\",\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add syscall test dimension for --file_access=shared
PiperOrigin-RevId: 231856279
Change-Id: I175db87374890a62a3a3c2ddef727668ff854ce4 |
259,853 | 31.01.2019 15:17:50 | 28,800 | 4e695adcd0c739101c3d50431ca18b1b911c9238 | gvisor/gofer: Use pivot_root instead of chroot | [
{
"change_type": "MODIFY",
"old_path": "runsc/cmd/chroot.go",
"new_path": "runsc/cmd/chroot.go",
"diff": "@@ -36,6 +36,29 @@ func mountInChroot(chroot, src, dst, typ string, flags uint32) error {\nreturn nil\n}\n+func pivotRoot(root string) error {\n+ if err := os.Chdir(root); err != nil {\n+ return fmt.Errorf(\"error changing working directory: %v\", err)\n+ }\n+ // pivot_root(new_root, put_old) moves the root filesystem (old_root)\n+ // of the calling process to the directory put_old and makes new_root\n+ // the new root filesystem of the calling process.\n+ //\n+ // pivot_root(\".\", \".\") makes a mount of the working directory the new\n+ // root filesystem, so it will be moved in \"/\" and then the old_root\n+ // will be moved to \"/\" too. The parent mount of the old_root will be\n+ // new_root, so after umounting the old_root, we will see only\n+ // the new_root in \"/\".\n+ if err := syscall.PivotRoot(\".\", \".\"); err != nil {\n+ return fmt.Errorf(\"error changing root filesystem: %v\", err)\n+ }\n+\n+ if err := syscall.Unmount(\".\", syscall.MNT_DETACH); err != nil {\n+ return fmt.Errorf(\"error umounting the old root file system: %v\", err)\n+ }\n+ return nil\n+}\n+\n// setUpChroot creates an empty directory with runsc mounted at /runsc and proc\n// mounted at /proc.\nfunc setUpChroot(pidns bool) error {\n@@ -66,29 +89,9 @@ func setUpChroot(pidns bool) error {\n}\n}\n- if err := os.Chdir(chroot); err != nil {\n- return fmt.Errorf(\"error changing working directory: %v\", err)\n- }\n-\nif err := syscall.Mount(\"\", chroot, \"\", syscall.MS_REMOUNT|syscall.MS_RDONLY|syscall.MS_BIND, \"\"); err != nil {\nreturn fmt.Errorf(\"error remounting chroot in read-only: %v\", err)\n}\n- // pivot_root(new_root, put_old) moves the root filesystem (old_root)\n- // of the calling process to the directory put_old and makes new_root\n- // the new root filesystem of the calling process.\n- //\n- // pivot_root(\".\", \".\") makes a mount of the working directory the new\n- // root filesystem, so it will be moved in \"/\" and then the old_root\n- // will be moved to \"/\" too. The parent mount of the old_root will be\n- // new_root, so after umounting the old_root, we will see only\n- // the new_root in \"/\".\n- if err := syscall.PivotRoot(\".\", \".\"); err != nil {\n- return fmt.Errorf(\"error changing root filesystem: %v\", err)\n- }\n- if err := syscall.Unmount(\".\", syscall.MNT_DETACH); err != nil {\n- return fmt.Errorf(\"error umounting the old root file system: %v\", err)\n- }\n-\n- return nil\n+ return pivotRoot(chroot)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/cmd/gofer.go",
"new_path": "runsc/cmd/gofer.go",
"diff": "@@ -26,6 +26,7 @@ import (\n\"gvisor.googlesource.com/gvisor/pkg/log\"\n\"gvisor.googlesource.com/gvisor/pkg/p9\"\n\"gvisor.googlesource.com/gvisor/pkg/unet\"\n+ \"gvisor.googlesource.com/gvisor/runsc/boot\"\n\"gvisor.googlesource.com/gvisor/runsc/fsgofer\"\n\"gvisor.googlesource.com/gvisor/runsc/fsgofer/filter\"\n\"gvisor.googlesource.com/gvisor/runsc/specutils\"\n@@ -54,8 +55,10 @@ type Gofer struct {\nbundleDir string\nioFDs intFlags\napplyCaps bool\n+ setUpRoot bool\npanicOnWrite bool\n+ specFD int\n}\n// Name implements subcommands.Command.\n@@ -79,43 +82,83 @@ func (g *Gofer) SetFlags(f *flag.FlagSet) {\nf.Var(&g.ioFDs, \"io-fds\", \"list of FDs to connect 9P servers. They must follow this order: root first, then mounts as defined in the spec\")\nf.BoolVar(&g.applyCaps, \"apply-caps\", true, \"if true, apply capabilities to restrict what the Gofer process can do\")\nf.BoolVar(&g.panicOnWrite, \"panic-on-write\", false, \"if true, panics on attempts to write to RO mounts. RW mounts are unnaffected\")\n+ f.BoolVar(&g.setUpRoot, \"setup-root\", true, \"if true, set up an empty root for the process\")\n+ f.IntVar(&g.specFD, \"spec-fd\", -1, \"required fd with the container spec\")\n}\n// Execute implements subcommands.Command.\nfunc (g *Gofer) Execute(_ context.Context, f *flag.FlagSet, args ...interface{}) subcommands.ExitStatus {\n- if g.bundleDir == \"\" || len(g.ioFDs) < 1 {\n+ if g.bundleDir == \"\" || len(g.ioFDs) < 1 || g.specFD < 0 {\nf.Usage()\nreturn subcommands.ExitUsageError\n}\n+ specFile := os.NewFile(uintptr(g.specFD), \"spec file\")\n+ defer specFile.Close()\n+ spec, err := specutils.ReadSpecFromFile(g.bundleDir, specFile)\n+ if err != nil {\n+ Fatalf(\"reading spec: %v\", err)\n+ }\n+\n+ // Find what path is going to be served by this gofer.\n+ root := spec.Root.Path\n+\n+ conf := args[0].(*boot.Config)\n+\n+ if g.setUpRoot && !conf.TestOnlyAllowRunAsCurrentUserWithoutChroot {\n+ // Convert all shared mounts into slave to be sure that nothing will be\n+ // propagated outside of our namespace.\n+ if err := syscall.Mount(\"\", \"/\", \"\", syscall.MS_SLAVE|syscall.MS_REC, \"\"); err != nil {\n+ Fatalf(\"error converting mounts: %v\", err)\n+ }\n+\n+ // FIXME: runsc can't be re-executed without\n+ // /proc, so we create a tmpfs mount, mount ./proc and ./root\n+ // there, then move this mount to the root and after\n+ // setCapsAndCallSelf, runsc will chroot into /root.\n+ //\n+ // We need a directory to construct a new root and we know that\n+ // runsc can't start without /proc, so we can use it for this.\n+ flags := uintptr(syscall.MS_NOSUID | syscall.MS_NODEV | syscall.MS_NOEXEC)\n+ if err := syscall.Mount(\"runsc-root\", \"/proc\", \"tmpfs\", flags, \"\"); err != nil {\n+ Fatalf(\"error mounting tmpfs: %v\", err)\n+ }\n+ os.Mkdir(\"/proc/proc\", 0755)\n+ os.Mkdir(\"/proc/root\", 0755)\n+ if err := syscall.Mount(\"runsc-proc\", \"/proc/proc\", \"proc\", flags|syscall.MS_RDONLY, \"\"); err != nil {\n+ Fatalf(\"error mounting proc: %v\", err)\n+ }\n+ if err := syscall.Mount(root, \"/proc/root\", \"\", syscall.MS_BIND|syscall.MS_REC, \"\"); err != nil {\n+ Fatalf(\"error mounting root: %v\", err)\n+ }\n+ if err := pivotRoot(\"/proc\"); err != nil {\n+ Fatalf(\"faild to change the root file system: %v\", err)\n+ }\n+ if err := os.Chdir(\"/\"); err != nil {\n+ Fatalf(\"failed to change working directory\")\n+ }\n+ }\n+\nif g.applyCaps {\n// Disable caps when calling myself again.\n// Note: minimal argument handling for the default case to keep it simple.\nargs := os.Args\n- args = append(args, \"--apply-caps=false\")\n+ args = append(args, \"--apply-caps=false\", \"--setup-root=false\")\nif err := setCapsAndCallSelf(args, goferCaps); err != nil {\nFatalf(\"Unable to apply caps: %v\", err)\n}\npanic(\"unreachable\")\n}\n- specFile, err := specutils.OpenCleanSpec(g.bundleDir)\n- if err != nil {\n- Fatalf(\"opening spec: %v\", err)\n- }\n- spec, err := specutils.ReadSpecFromFile(g.bundleDir, specFile)\n- specFile.Close()\n- if err != nil {\n- Fatalf(\"reading spec: %v\", err)\n- }\nspecutils.LogSpec(spec)\n// fsgofer should run with a umask of 0, because we want to preserve file\n// modes exactly as sent by the sandbox, which will have applied its own umask.\nsyscall.Umask(0)\n- // Find what path is going to be served by this gofer.\n- root := spec.Root.Path\n+ if !conf.TestOnlyAllowRunAsCurrentUserWithoutChroot {\n+ root = \"/root\"\n+ }\nif err := syscall.Chroot(root); err != nil {\nFatalf(\"failed to chroot to %q: %v\", root, err)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/container/container.go",
"new_path": "runsc/container/container.go",
"diff": "@@ -787,11 +787,50 @@ func (c *Container) waitForStopped() error {\nfunc (c *Container) createGoferProcess(spec *specs.Spec, conf *boot.Config, bundleDir string) ([]*os.File, error) {\n// Start with the general config flags.\nargs := conf.ToFlags()\n+\n+ var goferEnds []*os.File\n+\n+ // nextFD is the next available file descriptor for the gofer process.\n+ // It starts at 3 because 0-2 are used by stdin/stdout/stderr.\n+ nextFD := 3\n+\n+ if conf.LogFilename != \"\" {\n+ logFile, err := os.OpenFile(conf.LogFilename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)\n+ if err != nil {\n+ return nil, fmt.Errorf(\"opening log file %q: %v\", conf.LogFilename, err)\n+ }\n+ defer logFile.Close()\n+ goferEnds = append(goferEnds, logFile)\n+ args = append(args, \"--log-fd=\"+strconv.Itoa(nextFD))\n+ nextFD++\n+ }\n+\n+ if conf.DebugLog != \"\" {\n+ debugLogFile, err := specutils.DebugLogFile(conf.DebugLog, \"gofer\")\n+ if err != nil {\n+ return nil, fmt.Errorf(\"opening debug log file in %q: %v\", conf.DebugLog, err)\n+ }\n+ defer debugLogFile.Close()\n+ goferEnds = append(goferEnds, debugLogFile)\n+ args = append(args, \"--debug-log-fd=\"+strconv.Itoa(nextFD))\n+ nextFD++\n+ }\n+\nargs = append(args, \"gofer\", \"--bundle\", bundleDir)\nif conf.Overlay {\nargs = append(args, \"--panic-on-write=true\")\n}\n+ // Open the spec file to donate to the sandbox.\n+ specFile, err := specutils.OpenCleanSpec(bundleDir)\n+ if err != nil {\n+ return nil, fmt.Errorf(\"opening spec file: %v\", err)\n+ }\n+ defer specFile.Close()\n+ goferEnds = append(goferEnds, specFile)\n+ args = append(args, \"--spec-fd=\"+strconv.Itoa(nextFD))\n+ nextFD++\n+\n// Add root mount and then add any other additional mounts.\nmountCount := 1\n@@ -802,12 +841,8 @@ func (c *Container) createGoferProcess(spec *specs.Spec, conf *boot.Config, bund\n}\n}\nsandEnds := make([]*os.File, 0, mountCount)\n- goferEnds := make([]*os.File, 0, mountCount)\n- // nextFD is the next available file descriptor for the gofer process.\n- // It starts at 3 because 0-2 are used by stdin/stdout/stderr.\n- nextFD := 3\n- for ; nextFD-3 < mountCount; nextFD++ {\n+ for i := 0; i < mountCount; i++ {\nfds, err := syscall.Socketpair(syscall.AF_UNIX, syscall.SOCK_STREAM|syscall.SOCK_CLOEXEC, 0)\nif err != nil {\nreturn nil, err\n@@ -819,6 +854,7 @@ func (c *Container) createGoferProcess(spec *specs.Spec, conf *boot.Config, bund\ngoferEnds = append(goferEnds, goferEnd)\nargs = append(args, fmt.Sprintf(\"--io-fds=%d\", nextFD))\n+ nextFD++\n}\nbinPath := specutils.ExePath\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/main.go",
"new_path": "runsc/main.go",
"diff": "@@ -179,8 +179,8 @@ func main() {\n// Quick sanity check to make sure no other commands get passed\n// a log fd (they should use log dir instead).\n- if subcommand != \"boot\" {\n- cmd.Fatalf(\"flag --debug-log-fd should only be passed to 'boot' command, but was passed to %q\", subcommand)\n+ if subcommand != \"boot\" && subcommand != \"gofer\" {\n+ cmd.Fatalf(\"flag --debug-log-fd should only be passed to 'boot' and 'gofer' command, but was passed to %q\", subcommand)\n}\n// If we are the boot process, then we own our stdio FDs and\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/test/root/chroot_test.go",
"new_path": "runsc/test/root/chroot_test.go",
"diff": "@@ -118,10 +118,7 @@ func TestChrootGofer(t *testing.T) {\n// This where the root directory is mapped on the host and that's where the\n// gofer must have chroot'd to.\n- root, err := d.RootDirInHost()\n- if err != nil {\n- t.Fatalf(\"Docker.RootDirInHost(): %v\", err)\n- }\n+ root := \"/root\"\nfor _, child := range children {\nchildPID, err := strconv.Atoi(child)\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/test/testutil/docker.go",
"new_path": "runsc/test/testutil/docker.go",
"diff": "@@ -297,15 +297,6 @@ func (d *Docker) SandboxPid() (int, error) {\nreturn pid, nil\n}\n-// RootDirInHost returns where the root directory is mapped on the host.\n-func (d *Docker) RootDirInHost() (string, error) {\n- out, err := do(\"inspect\", \"-f={{.GraphDriver.Data.MergedDir}}\", d.Name)\n- if err != nil {\n- return \"\", fmt.Errorf(\"error retrieving pid: %v\", err)\n- }\n- return strings.TrimSuffix(string(out), \"\\n\"), nil\n-}\n-\n// ID returns the container ID.\nfunc (d *Docker) ID() (string, error) {\nout, err := do(\"inspect\", \"-f={{.Id}}\", d.Name)\n"
}
] | Go | Apache License 2.0 | google/gvisor | gvisor/gofer: Use pivot_root instead of chroot
PiperOrigin-RevId: 231864273
Change-Id: I8545b72b615f5c2945df374b801b80be64ec3e13 |
259,853 | 01.02.2019 18:12:12 | 28,800 | 4f5fd311dca3eccd7a3bc8aaf19ed11d6755ee0a | gvisor/test: Remove gtest shard env variables | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/syscall_test_runner.go",
"new_path": "test/syscalls/syscall_test_runner.go",
"diff": "@@ -83,7 +83,7 @@ func runTestCaseNative(testBin string, tc gtest.TestCase, t *testing.T) {\n// Remove shard env variables so that the gunit binary does not try to\n// intepret them.\n- env = filterEnv(env, []string{\"TEST_SHARD_INDEX\", \"TEST_TOTAL_SHARDS\"})\n+ env = filterEnv(env, []string{\"TEST_SHARD_INDEX\", \"TEST_TOTAL_SHARDS\", \"GTEST_SHARD_INDEX\", \"GTEST_TOTAL_SHARDS\"})\ncmd := exec.Command(testBin, gtest.FilterTestFlag+\"=\"+tc.FullName())\ncmd.Env = env\n@@ -133,7 +133,7 @@ func runTestCaseRunsc(testBin string, tc gtest.TestCase, t *testing.T) {\n// Remove shard env variables so that the gunit binary does not try to\n// intepret them.\n- env = filterEnv(env, []string{\"TEST_SHARD_INDEX\", \"TEST_TOTAL_SHARDS\"})\n+ env = filterEnv(env, []string{\"TEST_SHARD_INDEX\", \"TEST_TOTAL_SHARDS\", \"GTEST_SHARD_INDEX\", \"GTEST_TOTAL_SHARDS\"})\n// Set TEST_TMPDIR to /tmp, as some of the syscall tests require it to\n// be backed by tmpfs.\n"
}
] | Go | Apache License 2.0 | google/gvisor | gvisor/test: Remove gtest shard env variables
PiperOrigin-RevId: 232071420
Change-Id: I5aa57f3dc4aac637d6f467445b4b3110fc08ac80 |
259,891 | 04.02.2019 16:34:37 | 28,800 | 3eae03fe4f2813dc56d6e33cd7feb7760fccfb25 | Deflake unlink test.
Multiple tests were creating the same directory before removing it, making it
possible for concurrent tests to fail because the directory already exists. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/unlink.cc",
"new_path": "test/syscalls/linux/unlink.cc",
"diff": "@@ -47,19 +47,20 @@ TEST(UnlinkTest, DirNotEmpty) {\n}\nTEST(UnlinkTest, Rmdir) {\n- std::string path = JoinPath(GetAbsoluteTestTmpdir(), \"NewDir\");\n- ASSERT_THAT(mkdir(path.c_str(), 0755), SyscallSucceeds());\n- EXPECT_THAT(rmdir(path.c_str()), SyscallSucceeds());\n+ auto dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n+ EXPECT_THAT(rmdir(dir.path().c_str()), SyscallSucceeds());\n}\nTEST(UnlinkTest, AtDir) {\nint dirfd;\n- EXPECT_THAT(dirfd = open(GetAbsoluteTestTmpdir().c_str(), O_DIRECTORY, 0),\n- SyscallSucceeds());\n+ auto tmpdir = GetAbsoluteTestTmpdir();\n+ EXPECT_THAT(dirfd = open(tmpdir.c_str(), O_DIRECTORY, 0), SyscallSucceeds());\n- std::string path = JoinPath(GetAbsoluteTestTmpdir(), \"NewDir\");\n- EXPECT_THAT(mkdir(path.c_str(), 0755), SyscallSucceeds());\n- EXPECT_THAT(unlinkat(dirfd, \"NewDir\", AT_REMOVEDIR), SyscallSucceeds());\n+ auto dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDirIn(tmpdir));\n+ auto dir_relpath =\n+ ASSERT_NO_ERRNO_AND_VALUE(GetRelativePath(tmpdir, dir.path()));\n+ EXPECT_THAT(unlinkat(dirfd, dir_relpath.c_str(), AT_REMOVEDIR),\n+ SyscallSucceeds());\nASSERT_THAT(close(dirfd), SyscallSucceeds());\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Deflake unlink test.
Multiple tests were creating the same directory before removing it, making it
possible for concurrent tests to fail because the directory already exists.
PiperOrigin-RevId: 232389814
Change-Id: I35d409fff4b3fd864b30fee742cb587b14975c23 |
259,975 | 05.02.2019 10:00:22 | 28,800 | 0cf7fc4e115c2dcc40901c44b238ab36b5d966fc | Change /proc/PID/cmdline to read environment vector.
Change proc to return envp on overwrite of argv with limitations from
upstream.
Add unit tests
Change layout of argv/envp on the stack so that end of argv is contiguous with
beginning of envp. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/arch/stack.go",
"new_path": "pkg/sentry/arch/stack.go",
"diff": "@@ -170,6 +170,24 @@ func (s *Stack) Load(args []string, env []string, aux Auxv) (StackLayout, error)\n// Make sure we start with a 16-byte alignment.\ns.Align(16)\n+ // Push the environment vector so the end of the argument vector is adjacent to\n+ // the beginning of the environment vector.\n+ // While the System V abi for x86_64 does not specify an ordering to the\n+ // Information Block (the block holding the arg, env, and aux vectors),\n+ // support features like setproctitle(3) naturally expect these segments\n+ // to be in this order. See: https://www.uclibc.org/docs/psABI-x86_64.pdf\n+ // page 29.\n+ l.EnvvEnd = s.Bottom\n+ envAddrs := make([]usermem.Addr, len(env))\n+ for i := len(env) - 1; i >= 0; i-- {\n+ addr, err := s.Push(env[i])\n+ if err != nil {\n+ return StackLayout{}, err\n+ }\n+ envAddrs[i] = addr\n+ }\n+ l.EnvvStart = s.Bottom\n+\n// Push our strings.\nl.ArgvEnd = s.Bottom\nargAddrs := make([]usermem.Addr, len(args))\n@@ -182,18 +200,6 @@ func (s *Stack) Load(args []string, env []string, aux Auxv) (StackLayout, error)\n}\nl.ArgvStart = s.Bottom\n- // Push our environment.\n- l.EnvvEnd = s.Bottom\n- envAddrs := make([]usermem.Addr, len(env))\n- for i := len(env) - 1; i >= 0; i-- {\n- addr, err := s.Push(env[i])\n- if err != nil {\n- return StackLayout{}, err\n- }\n- envAddrs[i] = addr\n- }\n- l.EnvvStart = s.Bottom\n-\n// We need to align the arguments appropriately.\n//\n// We must finish on a 16-byte alignment, but we'll play it\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/proc/exec_args.go",
"new_path": "pkg/sentry/fs/proc/exec_args.go",
"diff": "package proc\nimport (\n+ \"bytes\"\n\"fmt\"\n\"io\"\n@@ -139,20 +140,62 @@ func (f *execArgFile) Read(ctx context.Context, _ *fs.File, dst usermem.IOSequen\n// N.B. Technically this should be usermem.IOOpts.IgnorePermissions = true\n// until Linux 4.9 (272ddc8b3735 \"proc: don't use FOLL_FORCE for reading\n// cmdline and environment\").\n- copyN, copyErr := m.CopyIn(ctx, start, buf, usermem.IOOpts{})\n+ copyN, err := m.CopyIn(ctx, start, buf, usermem.IOOpts{})\nif copyN == 0 {\n// Nothing to copy.\n- return 0, copyErr\n+ return 0, err\n+ }\n+ buf = buf[:copyN]\n+\n+ // On Linux, if the NUL byte at the end of the argument vector has been\n+ // overwritten, it continues reading the environment vector as part of\n+ // the argument vector.\n+\n+ if f.arg == cmdlineExecArg && buf[copyN-1] != 0 {\n+ // Linux will limit the return up to and including the first null character in argv\n+\n+ copyN = bytes.IndexByte(buf, 0)\n+ if copyN == -1 {\n+ copyN = len(buf)\n}\n+ // If we found a NUL character in argv, return upto and including that character.\n+ if copyN < len(buf) {\nbuf = buf[:copyN]\n+ } else { // Otherwise return into envp.\n+ lengthEnvv := int(m.EnvvEnd() - m.EnvvStart())\n+\n+ // Upstream limits the returned amount to one page of slop.\n+ // https://elixir.bootlin.com/linux/v4.20/source/fs/proc/base.c#L208\n+ // we'll return one page total between argv and envp because of the\n+ // above page restrictions.\n+ if lengthEnvv > usermem.PageSize-len(buf) {\n+ lengthEnvv = usermem.PageSize - len(buf)\n+ }\n+ // Make a new buffer to fit the whole thing\n+ tmp := make([]byte, length+lengthEnvv)\n+ copyNE, err := m.CopyIn(ctx, m.EnvvStart(), tmp[copyN:], usermem.IOOpts{})\n+ if err != nil {\n+ return 0, err\n+ }\n+\n+ // Linux will return envp up to and including the first NUL character, so find it.\n+ for i, c := range tmp[copyN:] {\n+ if c == 0 {\n+ copyNE = i\n+ break\n+ }\n+ }\n- // TODO: On Linux, if the NUL byte at the end of the\n- // argument vector has been overwritten, it continues reading the\n- // environment vector as part of the argument vector.\n+ copy(tmp, buf)\n+ buf = tmp[:copyN+copyNE]\n+\n+ }\n+\n+ }\nn, dstErr := dst.CopyOut(ctx, buf)\nif dstErr != nil {\nreturn int64(n), dstErr\n}\n- return int64(n), copyErr\n+ return int64(n), err\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/util/multiprocess_util.h",
"new_path": "test/util/multiprocess_util.h",
"diff": "@@ -74,6 +74,7 @@ class ExecveArray {\nExecveArray& operator=(ExecveArray&&) = delete;\nchar* const* get() const { return ptrs_.data(); }\n+ size_t get_size() { return str_.size(); }\nprivate:\nstd::vector<char> str_;\n"
}
] | Go | Apache License 2.0 | google/gvisor | Change /proc/PID/cmdline to read environment vector.
- Change proc to return envp on overwrite of argv with limitations from
upstream.
- Add unit tests
- Change layout of argv/envp on the stack so that end of argv is contiguous with
beginning of envp.
PiperOrigin-RevId: 232506107
Change-Id: I993880499ab2c1220f6dc456a922235c49304dec |
259,992 | 07.02.2019 11:40:45 | 28,800 | 9ef3427ac14a84002497f3c8bac346486cb36f2b | Implement semctl(2) SETALL and GETALL | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/semaphore/semaphore.go",
"new_path": "pkg/sentry/kernel/semaphore/semaphore.go",
"diff": "package semaphore\nimport (\n+ \"fmt\"\n\"sync\"\n\"gvisor.googlesource.com/gvisor/pkg/abi/linux\"\n@@ -75,6 +76,9 @@ type Set struct {\nperms fs.FilePermissions\nopTime ktime.Time\nchangeTime ktime.Time\n+\n+ // sems holds all semaphores in the set. The slice itself is immutable after\n+ // it's been set, however each 'sem' object in the slice requires 'mu' lock.\nsems []sem\n// dead is set to true when the set is removed and can't be reached anymore.\n@@ -136,7 +140,7 @@ func (r *Registry) FindOrCreate(ctx context.Context, key, nsems int32, mode linu\n}\n// Validate parameters.\n- if nsems > int32(set.size()) {\n+ if nsems > int32(set.Size()) {\nreturn nil, syserror.EINVAL\n}\nif create && exclusive {\n@@ -244,19 +248,20 @@ func (r *Registry) findByKey(key int32) *Set {\nfunc (r *Registry) totalSems() int {\ntotalSems := 0\nfor _, v := range r.semaphores {\n- totalSems += v.size()\n+ totalSems += v.Size()\n}\nreturn totalSems\n}\nfunc (s *Set) findSem(num int32) *sem {\n- if num < 0 || int(num) >= s.size() {\n+ if num < 0 || int(num) >= s.Size() {\nreturn nil\n}\nreturn &s.sems[num]\n}\n-func (s *Set) size() int {\n+// Size returns the number of semaphores in the set. Size is immutable.\n+func (s *Set) Size() int {\nreturn len(s.sems)\n}\n@@ -303,6 +308,39 @@ func (s *Set) SetVal(ctx context.Context, num int32, val int16, creds *auth.Cred\nreturn nil\n}\n+// SetValAll overrides all semaphores values, waking up waiters as needed.\n+//\n+// 'len(vals)' must be equal to 's.Size()'.\n+func (s *Set) SetValAll(ctx context.Context, vals []uint16, creds *auth.Credentials) error {\n+ if len(vals) != s.Size() {\n+ panic(fmt.Sprintf(\"vals length (%d) different that Set.Size() (%d)\", len(vals), s.Size()))\n+ }\n+\n+ for _, val := range vals {\n+ if val < 0 || val > valueMax {\n+ return syserror.ERANGE\n+ }\n+ }\n+\n+ s.mu.Lock()\n+ defer s.mu.Unlock()\n+\n+ // \"The calling process must have alter permission on the semaphore set.\"\n+ if !s.checkPerms(creds, fs.PermMask{Write: true}) {\n+ return syserror.EACCES\n+ }\n+\n+ for i, val := range vals {\n+ sem := &s.sems[i]\n+\n+ // TODO: Clear undo entries in all processes\n+ sem.value = int16(val)\n+ sem.wakeWaiters()\n+ }\n+ s.changeTime = ktime.NowFromContext(ctx)\n+ return nil\n+}\n+\n// GetVal returns a semaphore value.\nfunc (s *Set) GetVal(num int32, creds *auth.Credentials) (int16, error) {\ns.mu.Lock()\n@@ -320,6 +358,23 @@ func (s *Set) GetVal(num int32, creds *auth.Credentials) (int16, error) {\nreturn sem.value, nil\n}\n+// GetValAll returns value for all semaphores.\n+func (s *Set) GetValAll(creds *auth.Credentials) ([]uint16, error) {\n+ s.mu.Lock()\n+ defer s.mu.Unlock()\n+\n+ // \"The calling process must have read permission on the semaphore set.\"\n+ if !s.checkPerms(creds, fs.PermMask{Read: true}) {\n+ return nil, syserror.EACCES\n+ }\n+\n+ vals := make([]uint16, s.Size())\n+ for i, sem := range s.sems {\n+ vals[i] = uint16(sem.value)\n+ }\n+ return vals, nil\n+}\n+\n// ExecuteOps attempts to execute a list of operations to the set. It only\n// succeeds when all operations can be applied. No changes are made if it fails.\n//\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/sys_sem.go",
"new_path": "pkg/sentry/syscalls/linux/sys_sem.go",
"diff": "@@ -22,6 +22,7 @@ import (\n\"gvisor.googlesource.com/gvisor/pkg/sentry/fs\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/kernel\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/kernel/auth\"\n+ \"gvisor.googlesource.com/gvisor/pkg/sentry/usermem\"\n\"gvisor.googlesource.com/gvisor/pkg/syserror\"\n)\n@@ -97,10 +98,18 @@ func Semctl(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Syscal\n}\nreturn 0, nil, setVal(t, id, num, int16(val))\n+ case linux.SETALL:\n+ array := args[3].Pointer()\n+ return 0, nil, setValAll(t, id, array)\n+\ncase linux.GETVAL:\nv, err := getVal(t, id, num)\nreturn uintptr(v), nil, err\n+ case linux.GETALL:\n+ array := args[3].Pointer()\n+ return 0, nil, getValAll(t, id, array)\n+\ncase linux.IPC_RMID:\nreturn 0, nil, remove(t, id)\n@@ -155,6 +164,20 @@ func setVal(t *kernel.Task, id int32, num int32, val int16) error {\nreturn set.SetVal(t, num, val, creds)\n}\n+func setValAll(t *kernel.Task, id int32, array usermem.Addr) error {\n+ r := t.IPCNamespace().SemaphoreRegistry()\n+ set := r.FindByID(id)\n+ if set == nil {\n+ return syserror.EINVAL\n+ }\n+ vals := make([]uint16, set.Size())\n+ if _, err := t.CopyIn(array, vals); err != nil {\n+ return err\n+ }\n+ creds := auth.CredentialsFromContext(t)\n+ return set.SetValAll(t, vals, creds)\n+}\n+\nfunc getVal(t *kernel.Task, id int32, num int32) (int16, error) {\nr := t.IPCNamespace().SemaphoreRegistry()\nset := r.FindByID(id)\n@@ -164,3 +187,18 @@ func getVal(t *kernel.Task, id int32, num int32) (int16, error) {\ncreds := auth.CredentialsFromContext(t)\nreturn set.GetVal(num, creds)\n}\n+\n+func getValAll(t *kernel.Task, id int32, array usermem.Addr) error {\n+ r := t.IPCNamespace().SemaphoreRegistry()\n+ set := r.FindByID(id)\n+ if set == nil {\n+ return syserror.EINVAL\n+ }\n+ creds := auth.CredentialsFromContext(t)\n+ vals, err := set.GetValAll(creds)\n+ if err != nil {\n+ return err\n+ }\n+ _, err = t.CopyOut(array, vals)\n+ return err\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/semaphore.cc",
"new_path": "test/syscalls/linux/semaphore.cc",
"diff": "@@ -223,7 +223,7 @@ TEST(SemaphoreTest, SemOpRemoveWithWaiter_NoRandomSave) {\n});\n// This must happen before IPC_RMID runs above. Otherwise it fails with EINVAL\n- // instead because the semaphire has already been removed.\n+ // instead because the semaphore has already been removed.\nstruct sembuf buf = {};\nbuf.sem_op = -1;\nASSERT_THAT(RetryEINTR(semop)(sem.get(), &buf, 1),\n@@ -408,6 +408,29 @@ TEST(SemaphoreTest, SemCtlVal) {\nthZero.Join();\n}\n+TEST(SemaphoreTest, SemCtlValAll) {\n+ AutoSem sem(semget(IPC_PRIVATE, 3, 0600 | IPC_CREAT));\n+ ASSERT_THAT(sem.get(), SyscallSucceeds());\n+\n+ // Semaphores must start with 0.\n+ uint16_t get[3] = {10, 10, 10};\n+ EXPECT_THAT(semctl(sem.get(), 1, GETALL, get), SyscallSucceedsWithValue(0));\n+ for (auto v : get) {\n+ EXPECT_EQ(v, 0);\n+ }\n+\n+ // SetAll and check that they were set.\n+ uint16_t vals[3] = {0, 10, 20};\n+ EXPECT_THAT(semctl(sem.get(), 1, SETALL, vals), SyscallSucceedsWithValue(0));\n+ EXPECT_THAT(semctl(sem.get(), 1, GETALL, get), SyscallSucceedsWithValue(0));\n+ for (size_t i = 0; i < ABSL_ARRAYSIZE(vals); ++i) {\n+ EXPECT_EQ(get[i], vals[i]);\n+ }\n+\n+ EXPECT_THAT(semctl(sem.get(), 1, SETALL, nullptr),\n+ SyscallFailsWithErrno(EFAULT));\n+}\n+\nTEST(SemaphoreTest, SemIpcSet) {\n// Drop CAP_IPC_OWNER which allows us to bypass semaphore permissions.\nASSERT_NO_ERRNO(SetCapability(CAP_IPC_OWNER, false));\n"
}
] | Go | Apache License 2.0 | google/gvisor | Implement semctl(2) SETALL and GETALL
PiperOrigin-RevId: 232914984
Change-Id: Id2643d7ad8e986ca9be76d860788a71db2674cda |
259,985 | 07.02.2019 14:43:18 | 28,800 | 2ba74f84be8b9d3d588fb834414d151607799fd3 | Implement /proc/net/unix. | [
{
"change_type": "MODIFY",
"old_path": "pkg/abi/linux/socket.go",
"new_path": "pkg/abi/linux/socket.go",
"diff": "@@ -191,6 +191,15 @@ const (\nSO_TXTIME = 61\n)\n+// enum socket_state, from uapi/linux/net.h.\n+const (\n+ SS_FREE = 0 // Not allocated.\n+ SS_UNCONNECTED = 1 // Unconnected to any socket.\n+ SS_CONNECTING = 2 // In process of connecting.\n+ SS_CONNECTED = 3 // Connected to socket.\n+ SS_DISCONNECTING = 4 // In process of disconnecting.\n+)\n+\n// SockAddrMax is the maximum size of a struct sockaddr, from\n// uapi/linux/socket.h.\nconst SockAddrMax = 128\n@@ -343,3 +352,10 @@ const SizeOfControlMessageRight = 4\n// SCM_MAX_FD is the maximum number of FDs accepted in a single sendmsg call.\n// From net/scm.h.\nconst SCM_MAX_FD = 253\n+\n+// SO_ACCEPTCON is defined as __SO_ACCEPTCON in\n+// include/uapi/linux/net.h, which represents a listening socket\n+// state. Note that this is distinct from SO_ACCEPTCONN, which is a\n+// socket option for querying whether a socket is in a listening\n+// state.\n+const SO_ACCEPTCON = 1 << 16\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/proc/BUILD",
"new_path": "pkg/sentry/fs/proc/BUILD",
"diff": "@@ -30,6 +30,7 @@ go_library(\nvisibility = [\"//pkg/sentry:internal\"],\ndeps = [\n\"//pkg/abi/linux\",\n+ \"//pkg/log\",\n\"//pkg/sentry/context\",\n\"//pkg/sentry/fs\",\n\"//pkg/sentry/fs/fsutil\",\n@@ -43,6 +44,8 @@ go_library(\n\"//pkg/sentry/kernel/time\",\n\"//pkg/sentry/mm\",\n\"//pkg/sentry/socket/rpcinet\",\n+ \"//pkg/sentry/socket/unix\",\n+ \"//pkg/sentry/socket/unix/transport\",\n\"//pkg/sentry/usage\",\n\"//pkg/sentry/usermem\",\n\"//pkg/syserror\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/proc/net.go",
"new_path": "pkg/sentry/fs/proc/net.go",
"diff": "package proc\nimport (\n+ \"bytes\"\n\"fmt\"\n\"time\"\n\"gvisor.googlesource.com/gvisor/pkg/abi/linux\"\n+ \"gvisor.googlesource.com/gvisor/pkg/log\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/context\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/fs\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/fs/proc/seqfile\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/fs/ramfs\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/inet\"\n+ \"gvisor.googlesource.com/gvisor/pkg/sentry/kernel\"\n+ \"gvisor.googlesource.com/gvisor/pkg/sentry/socket/unix\"\n+ \"gvisor.googlesource.com/gvisor/pkg/sentry/socket/unix/transport\"\n)\n// newNet creates a new proc net entry.\n-func (p *proc) newNetDir(ctx context.Context, msrc *fs.MountSource) *fs.Inode {\n+func (p *proc) newNetDir(ctx context.Context, k *kernel.Kernel, msrc *fs.MountSource) *fs.Inode {\nvar contents map[string]*fs.Inode\nif s := p.k.NetworkStack(); s != nil {\ncontents = map[string]*fs.Inode{\n@@ -52,6 +57,8 @@ func (p *proc) newNetDir(ctx context.Context, msrc *fs.MountSource) *fs.Inode {\n\"tcp\": newStaticProcInode(ctx, msrc, []byte(\" sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode\")),\n\"udp\": newStaticProcInode(ctx, msrc, []byte(\" sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode ref pointer drops\")),\n+\n+ \"unix\": seqfile.NewSeqFileInode(ctx, &netUnix{k: k}, msrc),\n}\nif s.SupportsIPv6() {\n@@ -182,3 +189,120 @@ func (n *netDev) ReadSeqFileData(ctx context.Context, h seqfile.SeqHandle) ([]se\nreturn data, 0\n}\n+\n+// netUnix implements seqfile.SeqSource for /proc/net/unix.\n+//\n+// +stateify savable\n+type netUnix struct {\n+ k *kernel.Kernel\n+}\n+\n+// NeedsUpdate implements seqfile.SeqSource.NeedsUpdate.\n+func (*netUnix) NeedsUpdate(generation int64) bool {\n+ return true\n+}\n+\n+// ReadSeqFileData implements seqfile.SeqSource.ReadSeqFileData.\n+func (n *netUnix) ReadSeqFileData(ctx context.Context, h seqfile.SeqHandle) ([]seqfile.SeqData, int64) {\n+ if h != nil {\n+ return []seqfile.SeqData{}, 0\n+ }\n+\n+ var buf bytes.Buffer\n+ // Header\n+ fmt.Fprintf(&buf, \"Num RefCount Protocol Flags Type St Inode Path\\n\")\n+\n+ // Entries\n+ for _, sref := range n.k.ListSockets(linux.AF_UNIX) {\n+ s := sref.Get()\n+ if s == nil {\n+ log.Debugf(\"Couldn't resolve weakref %v in socket table, racing with destruction?\", sref)\n+ continue\n+ }\n+ sfile := s.(*fs.File)\n+ sops, ok := sfile.FileOperations.(*unix.SocketOperations)\n+ if !ok {\n+ panic(fmt.Sprintf(\"Found non-unix socket file in unix socket table: %+v\", sfile))\n+ }\n+\n+ addr, err := sops.Endpoint().GetLocalAddress()\n+ if err != nil {\n+ log.Warningf(\"Failed to retrieve socket name from %+v: %v\", sfile, err)\n+ addr.Addr = \"<unknown>\"\n+ }\n+\n+ sockFlags := 0\n+ if ce, ok := sops.Endpoint().(transport.ConnectingEndpoint); ok {\n+ if ce.Listening() {\n+ // For unix domain sockets, linux reports a single flag\n+ // value if the socket is listening, of __SO_ACCEPTCON.\n+ sockFlags = linux.SO_ACCEPTCON\n+ }\n+ }\n+\n+ var sockState int\n+ switch sops.Endpoint().Type() {\n+ case linux.SOCK_DGRAM:\n+ sockState = linux.SS_CONNECTING\n+ // Unlike Linux, we don't have unbound connection-less sockets,\n+ // so no SS_DISCONNECTING.\n+\n+ case linux.SOCK_SEQPACKET:\n+ fallthrough\n+ case linux.SOCK_STREAM:\n+ // Connectioned.\n+ if sops.Endpoint().(transport.ConnectingEndpoint).Connected() {\n+ sockState = linux.SS_CONNECTED\n+ } else {\n+ sockState = linux.SS_UNCONNECTED\n+ }\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+ // value for unprivileged users depending on the kptr_restrict\n+ // sysctl.\n+ //\n+ // One use for this field is to allow a privileged user to\n+ // introspect into the kernel memory to determine information about\n+ // a socket not available through procfs, such as the socket's peer.\n+ //\n+ // On gvisor, returning a pointer to our internal structures would\n+ // be pointless, as it wouldn't match the memory layout for struct\n+ // unix_sock, making introspection difficult. We could populate a\n+ // struct unix_sock with the appropriate data, but even that\n+ // requires consideration for which kernel version to emulate, as\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+ (*unix.SocketOperations)(nil), // Num, pointer to kernel socket struct.\n+ sfile.ReadRefs()-1, // RefCount, don't count our own ref.\n+ 0, // Protocol, always 0 for UDS.\n+ sockFlags, // Flags.\n+ sops.Endpoint().Type(), // Type.\n+ sockState, // State.\n+ sfile.InodeID(), // Inode.\n+ )\n+\n+ // Path\n+ if len(addr.Addr) != 0 {\n+ if addr.Addr[0] == 0 {\n+ // Abstract path.\n+ fmt.Fprintf(&buf, \" @%s\", string(addr.Addr[1:]))\n+ } else {\n+ fmt.Fprintf(&buf, \" %s\", string(addr.Addr))\n+ }\n+ }\n+ fmt.Fprintf(&buf, \"\\n\")\n+\n+ sfile.DecRef()\n+ }\n+\n+ data := []seqfile.SeqData{{\n+ Buf: buf.Bytes(),\n+ Handle: (*netUnix)(nil),\n+ }}\n+ return data, 0\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/proc/proc.go",
"new_path": "pkg/sentry/fs/proc/proc.go",
"diff": "@@ -85,7 +85,7 @@ func New(ctx context.Context, msrc *fs.MountSource) (*fs.Inode, error) {\nif _, ok := p.k.NetworkStack().(*rpcinet.Stack); ok {\np.AddChild(ctx, \"net\", newRPCInetProcNet(ctx, msrc))\n} else {\n- p.AddChild(ctx, \"net\", p.newNetDir(ctx, msrc))\n+ p.AddChild(ctx, \"net\", p.newNetDir(ctx, k, msrc))\n}\nreturn newProcInode(p, msrc, fs.SpecialDirectory, nil), nil\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/kernel.go",
"new_path": "pkg/sentry/kernel/kernel.go",
"diff": "@@ -43,6 +43,7 @@ import (\n\"gvisor.googlesource.com/gvisor/pkg/cpuid\"\n\"gvisor.googlesource.com/gvisor/pkg/eventchannel\"\n\"gvisor.googlesource.com/gvisor/pkg/log\"\n+ \"gvisor.googlesource.com/gvisor/pkg/refs\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/arch\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/context\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/fs\"\n@@ -164,7 +165,7 @@ type Kernel struct {\n// nextInotifyCookie is a monotonically increasing counter used for\n// generating unique inotify event cookies.\n//\n- // nextInotifyCookie is mutable, and is accesed using atomic memory\n+ // nextInotifyCookie is mutable, and is accessed using atomic memory\n// operations.\nnextInotifyCookie uint32\n@@ -177,6 +178,10 @@ type Kernel struct {\n// danglingEndpoints is used to save / restore tcpip.DanglingEndpoints.\ndanglingEndpoints struct{} `state:\".([]tcpip.Endpoint)\"`\n+\n+ // socketTable is used to track all sockets on the system. Protected by\n+ // extMu.\n+ socketTable map[int]map[*refs.WeakRef]struct{}\n}\n// InitKernelArgs holds arguments to Init.\n@@ -266,6 +271,7 @@ 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+ k.socketTable = make(map[int]map[*refs.WeakRef]struct{})\nreturn nil\n}\n@@ -1051,6 +1057,56 @@ func (k *Kernel) EmitUnimplementedEvent(ctx context.Context) {\n})\n}\n+// socketEntry represents a socket recorded in Kernel.socketTable. It implements\n+// refs.WeakRefUser for sockets stored in the socket table.\n+//\n+// +stateify savable\n+type socketEntry struct {\n+ k *Kernel\n+ sock *refs.WeakRef\n+ family int\n+}\n+\n+// WeakRefGone implements refs.WeakRefUser.WeakRefGone.\n+func (s *socketEntry) WeakRefGone() {\n+ s.k.extMu.Lock()\n+ // k.socketTable is guaranteed to point to a valid socket table for s.family\n+ // at this point, since we made sure of the fact when we created this\n+ // socketEntry, and we never delete socket tables.\n+ delete(s.k.socketTable[s.family], s.sock)\n+ s.k.extMu.Unlock()\n+}\n+\n+// RecordSocket adds a socket to the system-wide socket table for tracking.\n+//\n+// Precondition: Caller must hold a reference to sock.\n+func (k *Kernel) RecordSocket(sock *fs.File, family int) {\n+ k.extMu.Lock()\n+ table, ok := k.socketTable[family]\n+ if !ok {\n+ table = make(map[*refs.WeakRef]struct{})\n+ k.socketTable[family] = table\n+ }\n+ se := socketEntry{k: k, family: family}\n+ se.sock = refs.NewWeakRef(sock, &se)\n+ table[se.sock] = struct{}{}\n+ k.extMu.Unlock()\n+}\n+\n+// ListSockets returns a snapshot of all sockets of a given family.\n+func (k *Kernel) ListSockets(family int) []*refs.WeakRef {\n+ k.extMu.Lock()\n+ socks := []*refs.WeakRef{}\n+ if table, ok := k.socketTable[family]; ok {\n+ socks = make([]*refs.WeakRef, 0, len(table))\n+ for s, _ := range table {\n+ socks = append(socks, s)\n+ }\n+ }\n+ k.extMu.Unlock()\n+ return socks\n+}\n+\ntype supervisorContext struct {\ncontext.NoopSleeper\nlog.Logger\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/socket.go",
"new_path": "pkg/sentry/socket/socket.go",
"diff": "@@ -147,6 +147,7 @@ func New(t *kernel.Task, family int, stype transport.SockType, protocol int) (*f\nreturn nil, err\n}\nif s != nil {\n+ t.Kernel().RecordSocket(s, family)\nreturn s, nil\n}\n}\n@@ -163,12 +164,15 @@ func Pair(t *kernel.Task, family int, stype transport.SockType, protocol int) (*\n}\nfor _, p := range providers {\n- s, t, err := p.Pair(t, stype, protocol)\n+ s1, s2, err := p.Pair(t, stype, protocol)\nif err != nil {\nreturn nil, nil, err\n}\n- if s != nil && t != nil {\n- return s, t, nil\n+ if s1 != nil && s2 != nil {\n+ k := t.Kernel()\n+ k.RecordSocket(s1, family)\n+ k.RecordSocket(s2, family)\n+ return s1, s2, nil\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/unix/unix.go",
"new_path": "pkg/sentry/socket/unix/unix.go",
"diff": "@@ -219,6 +219,8 @@ func (s *SocketOperations) Accept(t *kernel.Task, peerRequested bool, flags int,\nreturn 0, nil, 0, syserr.FromError(e)\n}\n+ t.Kernel().RecordSocket(ns, linux.AF_UNIX)\n+\nreturn fd, addr, addrLen, nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/BUILD",
"new_path": "test/syscalls/BUILD",
"diff": "@@ -534,6 +534,13 @@ syscall_test(\nsyscall_test(test = \"//test/syscalls/linux:write_test\")\n+syscall_test(\n+ test = \"//test/syscalls/linux:proc_net_unix_test\",\n+ # Unix domain socket creation isn't supported on all file systems. The\n+ # sentry-internal tmpfs is known to support it.\n+ use_tmpfs = True,\n+)\n+\ngo_binary(\nname = \"syscall_test_runner\",\nsrcs = [\"syscall_test_runner.go\"],\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/BUILD",
"new_path": "test/syscalls/linux/BUILD",
"diff": "@@ -3102,3 +3102,20 @@ cc_binary(\n\"@com_google_googletest//:gtest\",\n],\n)\n+\n+cc_binary(\n+ name = \"proc_net_unix_test\",\n+ testonly = 1,\n+ srcs = [\"proc_net_unix.cc\"],\n+ linkstatic = 1,\n+ deps = [\n+ \":unix_domain_socket_test_util\",\n+ \"//test/util:file_descriptor\",\n+ \"//test/util:fs_util\",\n+ \"//test/util:test_main\",\n+ \"//test/util:test_util\",\n+ \"@com_google_absl//absl/strings\",\n+ \"@com_google_absl//absl/strings:str_format\",\n+ \"@com_google_googletest//:gtest\",\n+ ],\n+)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/syscalls/linux/proc_net_unix.cc",
"diff": "+// Copyright 2019 Google LLC\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+#include \"gtest/gtest.h\"\n+#include \"gtest/gtest.h\"\n+#include \"absl/strings/numbers.h\"\n+#include \"absl/strings/str_format.h\"\n+#include \"absl/strings/str_join.h\"\n+#include \"absl/strings/str_split.h\"\n+#include \"test/syscalls/linux/unix_domain_socket_test_util.h\"\n+#include \"test/util/file_descriptor.h\"\n+#include \"test/util/fs_util.h\"\n+#include \"test/util/test_util.h\"\n+\n+namespace gvisor {\n+namespace testing {\n+namespace {\n+\n+using absl::StrCat;\n+using absl::StreamFormat;\n+using absl::StrFormat;\n+\n+constexpr char kProcNetUnixHeader[] =\n+ \"Num RefCount Protocol Flags Type St Inode Path\";\n+\n+// UnixEntry represents a single entry from /proc/net/unix.\n+struct UnixEntry {\n+ uintptr_t addr;\n+ uint64_t refs;\n+ uint64_t protocol;\n+ uint64_t flags;\n+ uint64_t type;\n+ uint64_t state;\n+ uint64_t inode;\n+ std::string path;\n+};\n+\n+std::string ExtractPath(const struct sockaddr* addr) {\n+ const char* path =\n+ reinterpret_cast<const struct sockaddr_un*>(addr)->sun_path;\n+ // Note: sockaddr_un.sun_path is an embedded character array of length\n+ // UNIX_PATH_MAX, so we can always safely dereference the first 2 bytes below.\n+ //\n+ // The kernel also enforces that the path is always null terminated.\n+ if (path[0] == 0) {\n+ // Abstract socket paths are null padded to the end of the struct\n+ // sockaddr. However, these null bytes may or may not show up in\n+ // /proc/net/unix depending on the kernel version. Truncate after the first\n+ // null byte (by treating path as a c-std::string).\n+ return StrCat(\"@\", &path[1]);\n+ }\n+ return std::string(path);\n+}\n+\n+// Returns a parsed representation of /proc/net/unix entries.\n+PosixErrorOr<std::vector<UnixEntry>> ProcNetUnixEntries() {\n+ std::string content;\n+ RETURN_IF_ERRNO(GetContents(\"/proc/net/unix\", &content));\n+\n+ bool skipped_header = false;\n+ std::vector<UnixEntry> entries;\n+ std::vector<std::string> lines = absl::StrSplit(content, absl::ByAnyChar(\"\\n\"));\n+ for (std::string line : lines) {\n+ if (!skipped_header) {\n+ EXPECT_EQ(line, kProcNetUnixHeader);\n+ skipped_header = true;\n+ continue;\n+ }\n+ if (line.empty()) {\n+ continue;\n+ }\n+\n+ // Abstract socket paths can have trailing null bytes in them depending on\n+ // the linux version. Strip off everything after a null byte, including the\n+ // null byte.\n+ std::size_t null_pos = line.find('\\0');\n+ if (null_pos != std::string::npos) {\n+ line.erase(null_pos);\n+ }\n+\n+ // Parse a single entry from /proc/net/unix.\n+ //\n+ // Sample file:\n+ //\n+ // clang-format off\n+ //\n+ // Num RefCount Protocol Flags Type St Inode Path\"\n+ // ffffa130e7041c00: 00000002 00000000 00010000 0001 01 1299413685 /tmp/control_server/13293772586877554487\n+ // ffffa14f547dc400: 00000002 00000000 00010000 0001 01 3793 @remote_coredump\n+ //\n+ // clang-format on\n+ //\n+ // Note that from the second entry, the inode number can be padded using\n+ // spaces, so we need to handle it separately during parsing. See\n+ // net/unix/af_unix.c:unix_seq_show() for how these entries are produced. In\n+ // particular, only the inode field is padded with spaces.\n+ UnixEntry entry;\n+\n+ // Process the first 6 fields, up to but not including \"Inode\".\n+ std::vector<std::string> fields = absl::StrSplit(line, absl::MaxSplits(' ', 6));\n+\n+ if (fields.size() < 7) {\n+ return PosixError(EINVAL, StrFormat(\"Invalid entry: '%s'\\n\", line));\n+ }\n+\n+ // AtoiBase can't handle the ':' in the \"Num\" field, so strip it out.\n+ std::vector<std::string> addr = absl::StrSplit(fields[0], ':');\n+ ASSIGN_OR_RETURN_ERRNO(entry.addr, AtoiBase(addr[0], 16));\n+\n+ ASSIGN_OR_RETURN_ERRNO(entry.refs, AtoiBase(fields[1], 16));\n+ ASSIGN_OR_RETURN_ERRNO(entry.protocol, AtoiBase(fields[2], 16));\n+ ASSIGN_OR_RETURN_ERRNO(entry.flags, AtoiBase(fields[3], 16));\n+ ASSIGN_OR_RETURN_ERRNO(entry.type, AtoiBase(fields[4], 16));\n+ ASSIGN_OR_RETURN_ERRNO(entry.state, AtoiBase(fields[5], 16));\n+\n+ absl::string_view rest = absl::StripAsciiWhitespace(fields[6]);\n+ fields = absl::StrSplit(rest, absl::MaxSplits(' ', 1));\n+ if (fields.empty()) {\n+ return PosixError(\n+ EINVAL, StrFormat(\"Invalid entry, missing 'Inode': '%s'\\n\", line));\n+ }\n+ ASSIGN_OR_RETURN_ERRNO(entry.inode, AtoiBase(fields[0], 10));\n+\n+ entry.path = \"\";\n+ if (fields.size() > 1) {\n+ entry.path = fields[1];\n+ }\n+\n+ entries.push_back(entry);\n+ }\n+\n+ return entries;\n+}\n+\n+// Finds the first entry in 'entries' for which 'predicate' returns true.\n+// Returns true on match, and sets 'match' to point to the matching entry.\n+bool FindBy(std::vector<UnixEntry> entries, UnixEntry* match,\n+ std::function<bool(UnixEntry)> predicate) {\n+ for (int i = 0; i < entries.size(); ++i) {\n+ if (predicate(entries[i])) {\n+ *match = entries[i];\n+ return true;\n+ }\n+ }\n+ return false;\n+}\n+\n+bool FindByPath(std::vector<UnixEntry> entries, UnixEntry* match,\n+ const std::string& path) {\n+ return FindBy(entries, match, [path](UnixEntry e) { return e.path == path; });\n+}\n+\n+TEST(ProcNetUnix, Exists) {\n+ const std::string content =\n+ ASSERT_NO_ERRNO_AND_VALUE(GetContents(\"/proc/net/unix\"));\n+ const std::string header_line = StrCat(kProcNetUnixHeader, \"\\n\");\n+ if (IsRunningOnGvisor()) {\n+ // Should be just the header since we don't have any unix domain sockets\n+ // yet.\n+ EXPECT_EQ(content, header_line);\n+ } else {\n+ // However, on a general linux machine, we could have abitrary sockets on\n+ // the system, so just check the header.\n+ EXPECT_THAT(content, ::testing::StartsWith(header_line));\n+ }\n+}\n+\n+TEST(ProcNetUnix, FilesystemBindAcceptConnect) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(\n+ FilesystemBoundUnixDomainSocketPair(SOCK_STREAM).Create());\n+\n+ std::string path1 = ExtractPath(sockets->first_addr());\n+ std::string path2 = ExtractPath(sockets->second_addr());\n+ std::cout << StreamFormat(\"Server socket address: %s\\n\", path1);\n+ std::cout << StreamFormat(\"Client socket address: %s\\n\", path2);\n+\n+ std::vector<UnixEntry> entries =\n+ ASSERT_NO_ERRNO_AND_VALUE(ProcNetUnixEntries());\n+ if (IsRunningOnGvisor()) {\n+ EXPECT_EQ(entries.size(), 2);\n+ }\n+\n+ // The server-side socket's path is listed in the socket entry...\n+ UnixEntry s1;\n+ EXPECT_TRUE(FindByPath(entries, &s1, path1));\n+\n+ // ... but the client-side socket's path is not.\n+ UnixEntry s2;\n+ EXPECT_FALSE(FindByPath(entries, &s2, path2));\n+}\n+\n+TEST(ProcNetUnix, AbstractBindAcceptConnect) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(\n+ AbstractBoundUnixDomainSocketPair(SOCK_STREAM).Create());\n+\n+ std::string path1 = ExtractPath(sockets->first_addr());\n+ std::string path2 = ExtractPath(sockets->second_addr());\n+ std::cout << StreamFormat(\"Server socket address: '%s'\\n\", path1);\n+ std::cout << StreamFormat(\"Client socket address: '%s'\\n\", path2);\n+\n+ std::vector<UnixEntry> entries =\n+ ASSERT_NO_ERRNO_AND_VALUE(ProcNetUnixEntries());\n+ if (IsRunningOnGvisor()) {\n+ EXPECT_EQ(entries.size(), 2);\n+ }\n+\n+ // The server-side socket's path is listed in the socket entry...\n+ UnixEntry s1;\n+ EXPECT_TRUE(FindByPath(entries, &s1, path1));\n+\n+ // ... but the client-side socket's path is not.\n+ UnixEntry s2;\n+ EXPECT_FALSE(FindByPath(entries, &s2, path2));\n+}\n+\n+TEST(ProcNetUnix, SocketPair) {\n+ // Under gvisor, ensure a socketpair() syscall creates exactly 2 new\n+ // entries. We have no way to verify this under Linux, as we have no control\n+ // over socket creation on a general Linux machine.\n+ SKIP_IF(!IsRunningOnGvisor());\n+\n+ std::vector<UnixEntry> entries =\n+ ASSERT_NO_ERRNO_AND_VALUE(ProcNetUnixEntries());\n+ ASSERT_EQ(entries.size(), 0);\n+\n+ auto sockets =\n+ ASSERT_NO_ERRNO_AND_VALUE(UnixDomainSocketPair(SOCK_STREAM).Create());\n+\n+ entries = ASSERT_NO_ERRNO_AND_VALUE(ProcNetUnixEntries());\n+ EXPECT_EQ(entries.size(), 2);\n+}\n+\n+} // namespace\n+} // namespace testing\n+} // namespace gvisor\n"
}
] | Go | Apache License 2.0 | google/gvisor | Implement /proc/net/unix.
PiperOrigin-RevId: 232948478
Change-Id: Ib830121e5e79afaf5d38d17aeef5a1ef97913d23 |
259,853 | 07.02.2019 19:31:50 | 28,800 | fda4d1f4f11201c34bd15d41ba4c94279d135d95 | gvisor/tests: save runsc logs for each container in a separate directory | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/syscall_test_runner.go",
"new_path": "test/syscalls/syscall_test_runner.go",
"diff": "@@ -171,7 +171,13 @@ func runTestCaseRunsc(testBin string, tc gtest.TestCase, t *testing.T) {\nargs = append(args, \"-strace\")\n}\nif outDir, ok := syscall.Getenv(\"TEST_UNDECLARED_OUTPUTS_DIR\"); ok {\n- args = append(args, \"-debug-log\", outDir+\"/\")\n+ debugLogDir, err := ioutil.TempDir(outDir, \"runsc\")\n+ if err != nil {\n+ t.Fatalf(\"could not create temp dir: %v\", err)\n+ }\n+ debugLogDir += \"/\"\n+ log.Infof(\"runsc logs: %s\", debugLogDir)\n+ args = append(args, \"-debug-log\", debugLogDir)\n}\n// Current process doesn't have CAP_SYS_ADMIN, create user namespace and run\n"
}
] | Go | Apache License 2.0 | google/gvisor | gvisor/tests: save runsc logs for each container in a separate directory
PiperOrigin-RevId: 232990964
Change-Id: Icfa426d5e83c7d3e56b0b92e6a9e1229bcb8361b |
259,854 | 07.02.2019 23:14:06 | 28,800 | 80f901b16b8bb8fe397cc44578035173f5155b24 | Plumb IP_ADD_MEMBERSHIP and IP_DROP_MEMBERSHIP to netstack.
Also includes a few fixes for IPv4 multicast support. IPv6 support is coming in
a followup CL. | [
{
"change_type": "MODIFY",
"old_path": "pkg/abi/linux/socket.go",
"new_path": "pkg/abi/linux/socket.go",
"diff": "@@ -204,15 +204,30 @@ const (\n// uapi/linux/socket.h.\nconst SockAddrMax = 128\n-// SockAddrInt is struct sockaddr_in, from uapi/linux/in.h.\n+// InetAddr is struct in_addr, from uapi/linux/in.h.\n+type InetAddr [4]byte\n+\n+// SockAddrInet is struct sockaddr_in, from uapi/linux/in.h.\ntype SockAddrInet struct {\nFamily uint16\nPort uint16\n- Addr [4]byte\n+ Addr InetAddr\nZero [8]uint8 // pad to sizeof(struct sockaddr).\n}\n-// SockAddrInt6 is struct sockaddr_in6, from uapi/linux/in6.h.\n+// InetMulticastRequest is struct ip_mreq, from uapi/linux/in.h.\n+type InetMulticastRequest struct {\n+ MulticastAddr InetAddr\n+ InterfaceAddr InetAddr\n+}\n+\n+// InetMulticastRequestWithNIC is struct ip_mreqn, from uapi/linux/in.h.\n+type InetMulticastRequestWithNIC struct {\n+ InetMulticastRequest\n+ InterfaceIndex int32\n+}\n+\n+// SockAddrInet6 is struct sockaddr_in6, from uapi/linux/in6.h.\ntype SockAddrInet6 struct {\nFamily uint16\nPort uint16\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/epsocket/epsocket.go",
"new_path": "pkg/sentry/socket/epsocket/epsocket.go",
"diff": "@@ -1078,6 +1078,25 @@ func setSockOptIPv6(t *kernel.Task, ep commonEndpoint, name int, optVal []byte)\nreturn syserr.TranslateNetstackError(ep.SetSockOpt(struct{}{}))\n}\n+var (\n+ inetMulticastRequestSize = int(binary.Size(linux.InetMulticastRequest{}))\n+ inetMulticastRequestWithNICSize = int(binary.Size(linux.InetMulticastRequestWithNIC{}))\n+)\n+\n+func copyInMulticastRequest(optVal []byte) (linux.InetMulticastRequestWithNIC, *syserr.Error) {\n+ if len(optVal) < inetMulticastRequestSize {\n+ return linux.InetMulticastRequestWithNIC{}, syserr.ErrInvalidArgument\n+ }\n+\n+ var req linux.InetMulticastRequestWithNIC\n+ if len(optVal) >= inetMulticastRequestWithNICSize {\n+ binary.Unmarshal(optVal[:inetMulticastRequestWithNICSize], usermem.ByteOrder, &req)\n+ } else {\n+ binary.Unmarshal(optVal[:inetMulticastRequestSize], usermem.ByteOrder, &req.InetMulticastRequest)\n+ }\n+ return req, nil\n+}\n+\n// setSockOptIP implements SetSockOpt when level is SOL_IP.\nfunc setSockOptIP(t *kernel.Task, ep commonEndpoint, name int, optVal []byte) *syserr.Error {\nswitch name {\n@@ -1096,7 +1115,31 @@ func setSockOptIP(t *kernel.Task, ep commonEndpoint, name int, optVal []byte) *s\n}\nreturn syserr.TranslateNetstackError(ep.SetSockOpt(tcpip.MulticastTTLOption(v)))\n- case linux.IP_ADD_MEMBERSHIP, linux.MCAST_JOIN_GROUP, linux.IP_MULTICAST_IF:\n+ case linux.IP_ADD_MEMBERSHIP:\n+ req, err := copyInMulticastRequest(optVal)\n+ if err != nil {\n+ return err\n+ }\n+\n+ return syserr.TranslateNetstackError(ep.SetSockOpt(tcpip.AddMembershipOption{\n+ NIC: tcpip.NICID(req.InterfaceIndex),\n+ InterfaceAddr: tcpip.Address(req.InterfaceAddr[:]),\n+ MulticastAddr: tcpip.Address(req.MulticastAddr[:]),\n+ }))\n+\n+ case linux.IP_DROP_MEMBERSHIP:\n+ req, err := copyInMulticastRequest(optVal)\n+ if err != nil {\n+ return err\n+ }\n+\n+ return syserr.TranslateNetstackError(ep.SetSockOpt(tcpip.RemoveMembershipOption{\n+ NIC: tcpip.NICID(req.InterfaceIndex),\n+ InterfaceAddr: tcpip.Address(req.InterfaceAddr[:]),\n+ MulticastAddr: tcpip.Address(req.MulticastAddr[:]),\n+ }))\n+\n+ case linux.MCAST_JOIN_GROUP, linux.IP_MULTICAST_IF:\n// FIXME: Disallow IP-level multicast group options by\n// default. These will need to be supported by appropriately plumbing\n// the level through to the network stack (if at all). However, we\n@@ -1108,7 +1151,6 @@ func setSockOptIP(t *kernel.Task, ep commonEndpoint, name int, optVal []byte) *s\nlinux.IP_BIND_ADDRESS_NO_PORT,\nlinux.IP_BLOCK_SOURCE,\nlinux.IP_CHECKSUM,\n- linux.IP_DROP_MEMBERSHIP,\nlinux.IP_DROP_SOURCE_MEMBERSHIP,\nlinux.IP_FREEBIND,\nlinux.IP_HDRINCL,\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/stack.go",
"new_path": "pkg/tcpip/stack/stack.go",
"diff": "@@ -742,6 +742,9 @@ func (s *Stack) FindRoute(id tcpip.NICID, localAddr, remoteAddr tcpip.Address, n\nreturn Route{}, tcpip.ErrNoRoute\n}\n+ // TODO: Route multicast packets with no specified local\n+ // address or NIC.\n+\nfor i := range s.routeTable {\nif (id != 0 && id != s.routeTable[i].NIC) || (len(remoteAddr) != 0 && !s.routeTable[i].Match(remoteAddr)) {\ncontinue\n@@ -768,6 +771,10 @@ func (s *Stack) FindRoute(id tcpip.NICID, localAddr, remoteAddr tcpip.Address, n\nreturn r, nil\n}\n+ if isMulticast {\n+ return Route{}, tcpip.ErrNetworkUnreachable\n+ }\n+\nreturn Route{}, tcpip.ErrNoRoute\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/udp/endpoint.go",
"new_path": "pkg/tcpip/transport/udp/endpoint.go",
"diff": "@@ -99,6 +99,7 @@ type endpoint struct {\neffectiveNetProtos []tcpip.NetworkProtocolNumber\n}\n+// +stateify savable\ntype multicastMembership struct {\nnicID tcpip.NICID\nmulticastAddr tcpip.Address\n@@ -412,6 +413,8 @@ func (e *endpoint) SetSockOpt(opt interface{}) *tcpip.Error {\nnicID = e.stack.CheckLocalAddress(nicID, e.netProto, v.InterfaceAddr)\n}\nif nicID == 0 {\n+ // TODO: Allow adding memberships without\n+ // specifing an interface.\nreturn tcpip.ErrNoRoute\n}\n@@ -766,9 +769,11 @@ func (e *endpoint) bindLocked(addr tcpip.FullAddress, commit func() *tcpip.Error\n}\n}\n+ nicid := addr.NIC\nif len(addr.Addr) != 0 {\n// A local address was specified, verify that it's valid.\n- if e.stack.CheckLocalAddress(addr.NIC, netProto, addr.Addr) == 0 {\n+ nicid = e.stack.CheckLocalAddress(addr.NIC, netProto, addr.Addr)\n+ if nicid == 0 {\nreturn tcpip.ErrBadLocalAddress\n}\n}\n@@ -777,21 +782,21 @@ func (e *endpoint) bindLocked(addr tcpip.FullAddress, commit func() *tcpip.Error\nLocalPort: addr.Port,\nLocalAddress: addr.Addr,\n}\n- id, err = e.registerWithStack(addr.NIC, netProtos, id)\n+ id, err = e.registerWithStack(nicid, netProtos, id)\nif err != nil {\nreturn err\n}\nif commit != nil {\nif err := commit(); err != nil {\n// Unregister, the commit failed.\n- e.stack.UnregisterTransportEndpoint(addr.NIC, netProtos, ProtocolNumber, id, e)\n+ e.stack.UnregisterTransportEndpoint(nicid, netProtos, ProtocolNumber, id, e)\ne.stack.ReleasePort(netProtos, ProtocolNumber, id.LocalAddress, id.LocalPort)\nreturn err\n}\n}\ne.id = id\n- e.regNICID = addr.NIC\n+ e.regNICID = nicid\ne.effectiveNetProtos = netProtos\n// Mark endpoint as bound.\n@@ -815,7 +820,8 @@ func (e *endpoint) Bind(addr tcpip.FullAddress, commit func() *tcpip.Error) *tcp\nreturn err\n}\n- e.bindNICID = addr.NIC\n+ // Save the effective NICID generated by bindLocked.\n+ e.bindNICID = e.regNICID\nreturn nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/udp/endpoint_state.go",
"new_path": "pkg/tcpip/transport/udp/endpoint_state.go",
"diff": "@@ -103,4 +103,10 @@ func (e *endpoint) afterLoad() {\nif err != nil {\npanic(*err)\n}\n+\n+ for _, m := range e.multicastMemberships {\n+ if err := e.stack.JoinGroup(e.netProto, m.nicID, m.multicastAddr); err != nil {\n+ panic(err)\n+ }\n+ }\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/BUILD",
"new_path": "test/syscalls/BUILD",
"diff": "@@ -361,6 +361,8 @@ syscall_test(\ntest = \"//test/syscalls/linux:socket_ip_udp_loopback_test\",\n)\n+syscall_test(test = \"//test/syscalls/linux:socket_ipv4_udp_unbound_loopback_test\")\n+\nsyscall_test(test = \"//test/syscalls/linux:socket_netdevice_test\")\nsyscall_test(test = \"//test/syscalls/linux:socket_netlink_route_test\")\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/BUILD",
"new_path": "test/syscalls/linux/BUILD",
"diff": "@@ -1931,6 +1931,24 @@ cc_library(\nalwayslink = 1,\n)\n+cc_library(\n+ name = \"socket_ipv4_udp_unbound_test_cases\",\n+ testonly = 1,\n+ srcs = [\n+ \"socket_ipv4_udp_unbound.cc\",\n+ ],\n+ hdrs = [\n+ \"socket_ipv4_udp_unbound.h\",\n+ ],\n+ deps = [\n+ \":ip_socket_test_util\",\n+ \":socket_test_util\",\n+ \"//test/util:test_util\",\n+ \"@com_google_googletest//:gtest\",\n+ ],\n+ alwayslink = 1,\n+)\n+\ncc_binary(\nname = \"socket_abstract_test\",\ntestonly = 1,\n@@ -2124,6 +2142,22 @@ cc_binary(\n],\n)\n+cc_binary(\n+ name = \"socket_ipv4_udp_unbound_loopback_test\",\n+ testonly = 1,\n+ srcs = [\n+ \"socket_ipv4_udp_unbound_loopback.cc\",\n+ ],\n+ linkstatic = 1,\n+ deps = [\n+ \":ip_socket_test_util\",\n+ \":socket_ipv4_udp_unbound_test_cases\",\n+ \":socket_test_util\",\n+ \"//test/util:test_main\",\n+ \"//test/util:test_util\",\n+ ],\n+)\n+\ncc_binary(\nname = \"socket_domain_test\",\ntestonly = 1,\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/ip_socket_test_util.cc",
"new_path": "test/syscalls/linux/ip_socket_test_util.cc",
"diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n+#include <net/if.h>\n+#include <sys/ioctl.h>\n+#include <cstring>\n+\n#include \"test/syscalls/linux/ip_socket_test_util.h\"\nnamespace gvisor {\nnamespace testing {\n+PosixErrorOr<int> InterfaceIndex(std::string name) {\n+ // TODO: 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+}\n+\nnamespace {\nstd::string DescribeSocketType(int type) {\n@@ -28,7 +41,7 @@ std::string DescribeSocketType(int type) {\nSocketPairKind IPv6TCPAcceptBindSocketPair(int type) {\nstd::string description =\n- absl::StrCat(DescribeSocketType(type), \"IPv6 TCP socket\");\n+ absl::StrCat(DescribeSocketType(type), \"connected IPv6 TCP socket\");\nreturn SocketPairKind{\ndescription, TCPAcceptBindSocketPairCreator(AF_INET6, type | SOCK_STREAM,\n0, /* dual_stack = */ false)};\n@@ -36,7 +49,7 @@ SocketPairKind IPv6TCPAcceptBindSocketPair(int type) {\nSocketPairKind IPv4TCPAcceptBindSocketPair(int type) {\nstd::string description =\n- absl::StrCat(DescribeSocketType(type), \"IPv4 TCP socket\");\n+ absl::StrCat(DescribeSocketType(type), \"connected IPv4 TCP socket\");\nreturn SocketPairKind{\ndescription, TCPAcceptBindSocketPairCreator(AF_INET, type | SOCK_STREAM,\n0, /* dual_stack = */ false)};\n@@ -44,7 +57,7 @@ SocketPairKind IPv4TCPAcceptBindSocketPair(int type) {\nSocketPairKind DualStackTCPAcceptBindSocketPair(int type) {\nstd::string description =\n- absl::StrCat(DescribeSocketType(type), \"dual stack TCP socket\");\n+ absl::StrCat(DescribeSocketType(type), \"connected dual stack TCP socket\");\nreturn SocketPairKind{\ndescription, TCPAcceptBindSocketPairCreator(AF_INET6, type | SOCK_STREAM,\n0, /* dual_stack = */ true)};\n@@ -52,7 +65,7 @@ SocketPairKind DualStackTCPAcceptBindSocketPair(int type) {\nSocketPairKind IPv6UDPBidirectionalBindSocketPair(int type) {\nstd::string description =\n- absl::StrCat(DescribeSocketType(type), \"IPv6 UDP socket\");\n+ absl::StrCat(DescribeSocketType(type), \"connected IPv6 UDP socket\");\nreturn SocketPairKind{description, UDPBidirectionalBindSocketPairCreator(\nAF_INET6, type | SOCK_DGRAM, 0,\n/* dual_stack = */ false)};\n@@ -60,7 +73,7 @@ SocketPairKind IPv6UDPBidirectionalBindSocketPair(int type) {\nSocketPairKind IPv4UDPBidirectionalBindSocketPair(int type) {\nstd::string description =\n- absl::StrCat(DescribeSocketType(type), \"IPv4 UDP socket\");\n+ absl::StrCat(DescribeSocketType(type), \"connected IPv4 UDP socket\");\nreturn SocketPairKind{description, UDPBidirectionalBindSocketPairCreator(\nAF_INET, type | SOCK_DGRAM, 0,\n/* dual_stack = */ false)};\n@@ -68,11 +81,19 @@ SocketPairKind IPv4UDPBidirectionalBindSocketPair(int type) {\nSocketPairKind DualStackUDPBidirectionalBindSocketPair(int type) {\nstd::string description =\n- absl::StrCat(DescribeSocketType(type), \"dual stack UDP socket\");\n+ absl::StrCat(DescribeSocketType(type), \"connected dual stack UDP socket\");\nreturn SocketPairKind{description, UDPBidirectionalBindSocketPairCreator(\nAF_INET6, type | SOCK_DGRAM, 0,\n/* dual_stack = */ true)};\n}\n+SocketPairKind IPv4UDPUnboundSocketPair(int type) {\n+ std::string description =\n+ absl::StrCat(DescribeSocketType(type), \"IPv4 UDP socket\");\n+ return SocketPairKind{\n+ description, UDPUnboundSocketPairCreator(AF_INET, type | SOCK_DGRAM, 0,\n+ /* dual_stack = */ false)};\n+}\n+\n} // namespace testing\n} // namespace gvisor\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": "namespace gvisor {\nnamespace testing {\n+// InterfaceIndex returns the index of the named interface.\n+PosixErrorOr<int> InterfaceIndex(std::string name);\n+\n// IPv6TCPAcceptBindSocketPair returns a SocketPairKind that represents\n// SocketPairs created with bind() and accept() syscalls with AF_INET6 and the\n// given type bound to the IPv6 loopback.\n@@ -51,6 +54,10 @@ SocketPairKind IPv4UDPBidirectionalBindSocketPair(int type);\n// AF_INET6 and the given type bound to the IPv4 loopback.\nSocketPairKind DualStackUDPBidirectionalBindSocketPair(int type);\n+// IPv4UDPUnboundSocketPair returns a SocketPairKind that represents\n+// SocketPairs created with AF_INET and the given type.\n+SocketPairKind IPv4UDPUnboundSocketPair(int type);\n+\n} // namespace testing\n} // namespace gvisor\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_ip_udp_generic.cc",
"new_path": "test/syscalls/linux/socket_ip_udp_generic.cc",
"diff": "@@ -117,5 +117,19 @@ TEST_P(UDPSocketPairTest, SetUDPMulticastTTLAboveMax) {\nSyscallFailsWithErrno(EINVAL));\n}\n+TEST_P(UDPSocketPairTest, SetEmptyIPAddMembership) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ struct ip_mreqn req = {};\n+ int ret = setsockopt(sockets->first_fd(), IPPROTO_IP, IP_ADD_MEMBERSHIP, &req,\n+ sizeof(req));\n+ // FIXME: gVisor returns the incorrect errno.\n+ if (IsRunningOnGvisor()) {\n+ EXPECT_THAT(ret, SyscallFails());\n+ } else {\n+ EXPECT_THAT(ret, SyscallFailsWithErrno(EINVAL));\n+ }\n+}\n+\n} // namespace testing\n} // namespace gvisor\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/syscalls/linux/socket_ipv4_udp_unbound.cc",
"diff": "+// Copyright 2019 Google LLC\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+#include \"test/syscalls/linux/socket_ipv4_udp_unbound.h\"\n+\n+#include <arpa/inet.h>\n+#include <sys/ioctl.h>\n+#include <sys/socket.h>\n+#include <sys/un.h>\n+#include <cstdio>\n+\n+#include \"gtest/gtest.h\"\n+#include \"gtest/gtest.h\"\n+#include \"test/syscalls/linux/ip_socket_test_util.h\"\n+#include \"test/syscalls/linux/socket_test_util.h\"\n+#include \"test/util/test_util.h\"\n+\n+namespace gvisor {\n+namespace testing {\n+\n+// Check that packets are not received without a group memebership. Default send\n+// interface configured by bind.\n+TEST_P(IPv4UDPUnboundSocketPairTest, IpMulticastLoopbackNoGroup) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ // Bind the first FD to the loopback. This is an alternative to\n+ // IP_MULTICAST_IF for setting the default send interface.\n+ sockaddr_in senderAddr = {};\n+ senderAddr.sin_family = AF_INET;\n+ senderAddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);\n+ EXPECT_THAT(\n+ bind(sockets->first_fd(), reinterpret_cast<sockaddr*>(&senderAddr),\n+ sizeof(senderAddr)),\n+ SyscallSucceeds());\n+\n+ // Bind the second FD to the v4 any address. If multicast worked like unicast,\n+ // this would ensure that we get the packet.\n+ sockaddr_in receiverAddr = {};\n+ receiverAddr.sin_family = AF_INET;\n+ receiverAddr.sin_addr.s_addr = htonl(INADDR_ANY);\n+ EXPECT_THAT(\n+ bind(sockets->second_fd(), reinterpret_cast<sockaddr*>(&receiverAddr),\n+ sizeof(receiverAddr)),\n+ SyscallSucceeds());\n+ socklen_t receiverAddrLen = sizeof(receiverAddr);\n+ EXPECT_THAT(\n+ getsockname(sockets->second_fd(),\n+ reinterpret_cast<sockaddr*>(&receiverAddr), &receiverAddrLen),\n+ SyscallSucceeds());\n+ EXPECT_EQ(receiverAddrLen, sizeof(receiverAddr));\n+\n+ // Send the multicast packet.\n+ sockaddr_in sendAddr = {};\n+ sendAddr.sin_family = AF_INET;\n+ sendAddr.sin_port = receiverAddr.sin_port;\n+ sendAddr.sin_addr.s_addr = inet_addr(\"224.0.2.1\");\n+ char send_buf[200];\n+ RandomizeBuffer(send_buf, sizeof(send_buf));\n+ EXPECT_THAT(RetryEINTR(sendto)(\n+ sockets->first_fd(), send_buf, sizeof(send_buf), 0,\n+ reinterpret_cast<sockaddr*>(&sendAddr), sizeof(sendAddr)),\n+ SyscallSucceedsWithValue(sizeof(send_buf)));\n+\n+ // Check that we did not receive the multicast packet.\n+ char recv_buf[sizeof(send_buf)] = {};\n+ EXPECT_THAT(RetryEINTR(recv)(sockets->second_fd(), recv_buf, sizeof(recv_buf),\n+ MSG_DONTWAIT),\n+ SyscallFailsWithErrno(EAGAIN));\n+}\n+\n+// Check that not setting a default send interface prevents multicast packets\n+// from being sent. Group membership interface configured by address.\n+TEST_P(IPv4UDPUnboundSocketPairTest, IpMulticastLoopbackAddrNoDefaultSendIf) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ // Bind the second FD to the v4 any address to ensure that we can receive any\n+ // unicast packet.\n+ sockaddr_in receiverAddr = {};\n+ receiverAddr.sin_family = AF_INET;\n+ receiverAddr.sin_addr.s_addr = htonl(INADDR_ANY);\n+ EXPECT_THAT(\n+ bind(sockets->second_fd(), reinterpret_cast<sockaddr*>(&receiverAddr),\n+ sizeof(receiverAddr)),\n+ SyscallSucceeds());\n+ socklen_t receiverAddrLen = sizeof(receiverAddr);\n+ EXPECT_THAT(\n+ getsockname(sockets->second_fd(),\n+ reinterpret_cast<sockaddr*>(&receiverAddr), &receiverAddrLen),\n+ SyscallSucceeds());\n+ EXPECT_EQ(receiverAddrLen, sizeof(receiverAddr));\n+\n+ // Register to receive multicast packets.\n+ ip_mreq group = {};\n+ group.imr_multiaddr.s_addr = inet_addr(\"224.0.2.1\");\n+ group.imr_interface.s_addr = htonl(INADDR_LOOPBACK);\n+ EXPECT_THAT(setsockopt(sockets->second_fd(), IPPROTO_IP, IP_ADD_MEMBERSHIP,\n+ &group, sizeof(group)),\n+ SyscallSucceeds());\n+\n+ // Send a multicast packet.\n+ sockaddr_in sendAddr = {};\n+ sendAddr.sin_family = AF_INET;\n+ sendAddr.sin_port = receiverAddr.sin_port;\n+ sendAddr.sin_addr.s_addr = inet_addr(\"224.0.2.1\");\n+ char send_buf[200];\n+ RandomizeBuffer(send_buf, sizeof(send_buf));\n+ EXPECT_THAT(RetryEINTR(sendto)(\n+ sockets->first_fd(), send_buf, sizeof(send_buf), 0,\n+ reinterpret_cast<sockaddr*>(&sendAddr), sizeof(sendAddr)),\n+ SyscallFailsWithErrno(ENETUNREACH));\n+}\n+\n+// Check that not setting a default send interface prevents multicast packets\n+// from being sent. Group membership interface configured by NIC ID.\n+TEST_P(IPv4UDPUnboundSocketPairTest, IpMulticastLoopbackNicNoDefaultSendIf) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ // Bind the second FD to the v4 any address to ensure that we can receive any\n+ // unicast packet.\n+ sockaddr_in receiverAddr = {};\n+ receiverAddr.sin_family = AF_INET;\n+ receiverAddr.sin_addr.s_addr = htonl(INADDR_ANY);\n+ EXPECT_THAT(\n+ bind(sockets->second_fd(), reinterpret_cast<sockaddr*>(&receiverAddr),\n+ sizeof(receiverAddr)),\n+ SyscallSucceeds());\n+ socklen_t receiverAddrLen = sizeof(receiverAddr);\n+ EXPECT_THAT(\n+ getsockname(sockets->second_fd(),\n+ reinterpret_cast<sockaddr*>(&receiverAddr), &receiverAddrLen),\n+ SyscallSucceeds());\n+ EXPECT_EQ(receiverAddrLen, sizeof(receiverAddr));\n+\n+ // Register to receive multicast packets.\n+ ip_mreqn group = {};\n+ group.imr_multiaddr.s_addr = inet_addr(\"224.0.2.1\");\n+ group.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(InterfaceIndex(\"lo\"));\n+ EXPECT_THAT(setsockopt(sockets->second_fd(), IPPROTO_IP, IP_ADD_MEMBERSHIP,\n+ &group, sizeof(group)),\n+ SyscallSucceeds());\n+\n+ // Send a multicast packet.\n+ sockaddr_in sendAddr = {};\n+ sendAddr.sin_family = AF_INET;\n+ sendAddr.sin_port = receiverAddr.sin_port;\n+ sendAddr.sin_addr.s_addr = inet_addr(\"224.0.2.1\");\n+ char send_buf[200];\n+ RandomizeBuffer(send_buf, sizeof(send_buf));\n+ EXPECT_THAT(RetryEINTR(sendto)(\n+ sockets->first_fd(), send_buf, sizeof(send_buf), 0,\n+ reinterpret_cast<sockaddr*>(&sendAddr), sizeof(sendAddr)),\n+ SyscallFailsWithErrno(ENETUNREACH));\n+}\n+\n+// Check that multicast works when the default send interface is configured by\n+// bind and the group membership is configured by address.\n+TEST_P(IPv4UDPUnboundSocketPairTest, IpMulticastLoopbackAddr) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ // Bind the first FD to the loopback. This is an alternative to\n+ // IP_MULTICAST_IF for setting the default send interface.\n+ sockaddr_in senderAddr = {};\n+ senderAddr.sin_family = AF_INET;\n+ senderAddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);\n+ EXPECT_THAT(\n+ bind(sockets->first_fd(), reinterpret_cast<sockaddr*>(&senderAddr),\n+ sizeof(senderAddr)),\n+ SyscallSucceeds());\n+\n+ // Bind the second FD to the v4 any address to ensure that we can receive the\n+ // multicast packet.\n+ sockaddr_in receiverAddr = {};\n+ receiverAddr.sin_family = AF_INET;\n+ receiverAddr.sin_addr.s_addr = htonl(INADDR_ANY);\n+ EXPECT_THAT(\n+ bind(sockets->second_fd(), reinterpret_cast<sockaddr*>(&receiverAddr),\n+ sizeof(receiverAddr)),\n+ SyscallSucceeds());\n+ socklen_t receiverAddrLen = sizeof(receiverAddr);\n+ EXPECT_THAT(\n+ getsockname(sockets->second_fd(),\n+ reinterpret_cast<sockaddr*>(&receiverAddr), &receiverAddrLen),\n+ SyscallSucceeds());\n+ EXPECT_EQ(receiverAddrLen, sizeof(receiverAddr));\n+\n+ // Register to receive multicast packets.\n+ ip_mreq group = {};\n+ group.imr_multiaddr.s_addr = inet_addr(\"224.0.2.1\");\n+ group.imr_interface.s_addr = htonl(INADDR_LOOPBACK);\n+ EXPECT_THAT(setsockopt(sockets->second_fd(), IPPROTO_IP, IP_ADD_MEMBERSHIP,\n+ &group, sizeof(group)),\n+ SyscallSucceeds());\n+\n+ // Send a multicast packet.\n+ sockaddr_in sendAddr = {};\n+ sendAddr.sin_family = AF_INET;\n+ sendAddr.sin_port = receiverAddr.sin_port;\n+ sendAddr.sin_addr.s_addr = inet_addr(\"224.0.2.1\");\n+ char send_buf[200];\n+ RandomizeBuffer(send_buf, sizeof(send_buf));\n+ EXPECT_THAT(RetryEINTR(sendto)(\n+ sockets->first_fd(), send_buf, sizeof(send_buf), 0,\n+ reinterpret_cast<sockaddr*>(&sendAddr), sizeof(sendAddr)),\n+ SyscallSucceedsWithValue(sizeof(send_buf)));\n+\n+ // Check that we received the multicast packet.\n+ char recv_buf[sizeof(send_buf)] = {};\n+ ASSERT_THAT(\n+ RetryEINTR(recv)(sockets->second_fd(), recv_buf, sizeof(recv_buf), 0),\n+ SyscallSucceedsWithValue(sizeof(recv_buf)));\n+\n+ EXPECT_EQ(0, memcmp(send_buf, recv_buf, sizeof(send_buf)));\n+}\n+\n+// Check that multicast works when the default send interface is confgured by\n+// bind and the group membership is configured by NIC ID.\n+TEST_P(IPv4UDPUnboundSocketPairTest, IpMulticastLoopbackNic) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ // Bind the first FD to the loopback. This is an alternative to\n+ // IP_MULTICAST_IF for setting the default send interface.\n+ sockaddr_in senderAddr = {};\n+ senderAddr.sin_family = AF_INET;\n+ senderAddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);\n+ EXPECT_THAT(\n+ bind(sockets->first_fd(), reinterpret_cast<sockaddr*>(&senderAddr),\n+ sizeof(senderAddr)),\n+ SyscallSucceeds());\n+\n+ // Bind the second FD to the v4 any address to ensure that we can receive the\n+ // multicast packet.\n+ sockaddr_in receiverAddr = {};\n+ receiverAddr.sin_family = AF_INET;\n+ receiverAddr.sin_addr.s_addr = htonl(INADDR_ANY);\n+ EXPECT_THAT(\n+ bind(sockets->second_fd(), reinterpret_cast<sockaddr*>(&receiverAddr),\n+ sizeof(receiverAddr)),\n+ SyscallSucceeds());\n+ socklen_t receiverAddrLen = sizeof(receiverAddr);\n+ EXPECT_THAT(\n+ getsockname(sockets->second_fd(),\n+ reinterpret_cast<sockaddr*>(&receiverAddr), &receiverAddrLen),\n+ SyscallSucceeds());\n+ EXPECT_EQ(receiverAddrLen, sizeof(receiverAddr));\n+\n+ // Register to receive multicast packets.\n+ ip_mreqn group = {};\n+ group.imr_multiaddr.s_addr = inet_addr(\"224.0.2.1\");\n+ group.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(InterfaceIndex(\"lo\"));\n+ EXPECT_THAT(setsockopt(sockets->second_fd(), IPPROTO_IP, IP_ADD_MEMBERSHIP,\n+ &group, sizeof(group)),\n+ SyscallSucceeds());\n+\n+ // Send a multicast packet.\n+ sockaddr_in sendAddr = {};\n+ sendAddr.sin_family = AF_INET;\n+ sendAddr.sin_port = receiverAddr.sin_port;\n+ sendAddr.sin_addr.s_addr = inet_addr(\"224.0.2.1\");\n+ char send_buf[200];\n+ RandomizeBuffer(send_buf, sizeof(send_buf));\n+ EXPECT_THAT(RetryEINTR(sendto)(\n+ sockets->first_fd(), send_buf, sizeof(send_buf), 0,\n+ reinterpret_cast<sockaddr*>(&sendAddr), sizeof(sendAddr)),\n+ SyscallSucceedsWithValue(sizeof(send_buf)));\n+\n+ // Check that we received the multicast packet.\n+ char recv_buf[sizeof(send_buf)] = {};\n+ ASSERT_THAT(\n+ RetryEINTR(recv)(sockets->second_fd(), recv_buf, sizeof(recv_buf), 0),\n+ SyscallSucceedsWithValue(sizeof(recv_buf)));\n+\n+ EXPECT_EQ(0, memcmp(send_buf, recv_buf, sizeof(send_buf)));\n+}\n+\n+// Check that dropping a group membership that does not exist fails.\n+TEST_P(IPv4UDPUnboundSocketPairTest, IpMulticastInvalidDrop) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ // Unregister from a membership that we didn't have.\n+ ip_mreq group = {};\n+ group.imr_multiaddr.s_addr = inet_addr(\"224.0.2.1\");\n+ group.imr_interface.s_addr = htonl(INADDR_LOOPBACK);\n+ EXPECT_THAT(setsockopt(sockets->first_fd(), IPPROTO_IP, IP_DROP_MEMBERSHIP,\n+ &group, sizeof(group)),\n+ SyscallFailsWithErrno(EADDRNOTAVAIL));\n+}\n+\n+// Check that dropping a group membership prevents multicast packets from being\n+// delivered. Default send address configured by bind and group membership\n+// interface configured by address.\n+TEST_P(IPv4UDPUnboundSocketPairTest, IpMulticastDropAddr) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ // Bind the first FD to the loopback. This is an alternative to\n+ // IP_MULTICAST_IF for setting the default send interface.\n+ sockaddr_in senderAddr = {};\n+ senderAddr.sin_family = AF_INET;\n+ senderAddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);\n+ EXPECT_THAT(\n+ bind(sockets->first_fd(), reinterpret_cast<sockaddr*>(&senderAddr),\n+ sizeof(senderAddr)),\n+ SyscallSucceeds());\n+\n+ // Bind the second FD to the v4 any address to ensure that we can receive the\n+ // multicast packet.\n+ sockaddr_in receiverAddr = {};\n+ receiverAddr.sin_family = AF_INET;\n+ receiverAddr.sin_addr.s_addr = htonl(INADDR_ANY);\n+ EXPECT_THAT(\n+ bind(sockets->second_fd(), reinterpret_cast<sockaddr*>(&receiverAddr),\n+ sizeof(receiverAddr)),\n+ SyscallSucceeds());\n+ socklen_t receiverAddrLen = sizeof(receiverAddr);\n+ EXPECT_THAT(\n+ getsockname(sockets->second_fd(),\n+ reinterpret_cast<sockaddr*>(&receiverAddr), &receiverAddrLen),\n+ SyscallSucceeds());\n+ EXPECT_EQ(receiverAddrLen, sizeof(receiverAddr));\n+\n+ // Register and unregister to receive multicast packets.\n+ ip_mreq group = {};\n+ group.imr_multiaddr.s_addr = inet_addr(\"224.0.2.1\");\n+ group.imr_interface.s_addr = htonl(INADDR_LOOPBACK);\n+ EXPECT_THAT(setsockopt(sockets->second_fd(), IPPROTO_IP, IP_ADD_MEMBERSHIP,\n+ &group, sizeof(group)),\n+ SyscallSucceeds());\n+ EXPECT_THAT(setsockopt(sockets->second_fd(), IPPROTO_IP, IP_DROP_MEMBERSHIP,\n+ &group, sizeof(group)),\n+ SyscallSucceeds());\n+\n+ // Send a multicast packet.\n+ sockaddr_in sendAddr = {};\n+ sendAddr.sin_family = AF_INET;\n+ sendAddr.sin_port = receiverAddr.sin_port;\n+ sendAddr.sin_addr.s_addr = inet_addr(\"224.0.2.1\");\n+ char send_buf[200];\n+ RandomizeBuffer(send_buf, sizeof(send_buf));\n+ EXPECT_THAT(RetryEINTR(sendto)(\n+ sockets->first_fd(), send_buf, sizeof(send_buf), 0,\n+ reinterpret_cast<sockaddr*>(&sendAddr), sizeof(sendAddr)),\n+ SyscallSucceedsWithValue(sizeof(send_buf)));\n+\n+ // Check that we did not receive the multicast packet.\n+ char recv_buf[sizeof(send_buf)] = {};\n+ EXPECT_THAT(RetryEINTR(recv)(sockets->second_fd(), recv_buf, sizeof(recv_buf),\n+ MSG_DONTWAIT),\n+ SyscallFailsWithErrno(EAGAIN));\n+}\n+\n+// Check that dropping a group membership prevents multicast packets from being\n+// delivered. Default send address configured by bind and group membership\n+// interface configured by NIC ID.\n+TEST_P(IPv4UDPUnboundSocketPairTest, IpMulticastDropNic) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ // Bind the first FD to the loopback. This is an alternative to\n+ // IP_MULTICAST_IF for setting the default send interface.\n+ sockaddr_in senderAddr = {};\n+ senderAddr.sin_family = AF_INET;\n+ senderAddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);\n+ EXPECT_THAT(\n+ bind(sockets->first_fd(), reinterpret_cast<sockaddr*>(&senderAddr),\n+ sizeof(senderAddr)),\n+ SyscallSucceeds());\n+\n+ // Bind the second FD to the v4 any address to ensure that we can receive the\n+ // multicast packet.\n+ sockaddr_in receiverAddr = {};\n+ receiverAddr.sin_family = AF_INET;\n+ receiverAddr.sin_addr.s_addr = htonl(INADDR_ANY);\n+ EXPECT_THAT(\n+ bind(sockets->second_fd(), reinterpret_cast<sockaddr*>(&receiverAddr),\n+ sizeof(receiverAddr)),\n+ SyscallSucceeds());\n+ socklen_t receiverAddrLen = sizeof(receiverAddr);\n+ EXPECT_THAT(\n+ getsockname(sockets->second_fd(),\n+ reinterpret_cast<sockaddr*>(&receiverAddr), &receiverAddrLen),\n+ SyscallSucceeds());\n+ EXPECT_EQ(receiverAddrLen, sizeof(receiverAddr));\n+\n+ // Register and unregister to receive multicast packets.\n+ ip_mreqn group = {};\n+ group.imr_multiaddr.s_addr = inet_addr(\"224.0.2.1\");\n+ group.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(InterfaceIndex(\"lo\"));\n+ EXPECT_THAT(setsockopt(sockets->second_fd(), IPPROTO_IP, IP_ADD_MEMBERSHIP,\n+ &group, sizeof(group)),\n+ SyscallSucceeds());\n+ EXPECT_THAT(setsockopt(sockets->second_fd(), IPPROTO_IP, IP_DROP_MEMBERSHIP,\n+ &group, sizeof(group)),\n+ SyscallSucceeds());\n+\n+ // Send a multicast packet.\n+ sockaddr_in sendAddr = {};\n+ sendAddr.sin_family = AF_INET;\n+ sendAddr.sin_port = receiverAddr.sin_port;\n+ sendAddr.sin_addr.s_addr = inet_addr(\"224.0.2.1\");\n+ char send_buf[200];\n+ RandomizeBuffer(send_buf, sizeof(send_buf));\n+ EXPECT_THAT(RetryEINTR(sendto)(\n+ sockets->first_fd(), send_buf, sizeof(send_buf), 0,\n+ reinterpret_cast<sockaddr*>(&sendAddr), sizeof(sendAddr)),\n+ SyscallSucceedsWithValue(sizeof(send_buf)));\n+\n+ // Check that we did not receive the multicast packet.\n+ char recv_buf[sizeof(send_buf)] = {};\n+ EXPECT_THAT(RetryEINTR(recv)(sockets->second_fd(), recv_buf, sizeof(recv_buf),\n+ MSG_DONTWAIT),\n+ SyscallFailsWithErrno(EAGAIN));\n+}\n+\n+} // namespace testing\n+} // namespace gvisor\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/syscalls/linux/socket_ipv4_udp_unbound.h",
"diff": "+// Copyright 2019 Google LLC\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+#ifndef GVISOR_TEST_SYSCALLS_LINUX_SOCKET_IPV4_UDP_UNBOUND_H_\n+#define GVISOR_TEST_SYSCALLS_LINUX_SOCKET_IPV4_UDP_UNBOUND_H_\n+\n+#include \"test/syscalls/linux/socket_test_util.h\"\n+\n+namespace gvisor {\n+namespace testing {\n+\n+// Test fixture for tests that apply to pairs of IPv4 UDP sockets.\n+using IPv4UDPUnboundSocketPairTest = SocketPairTest;\n+\n+} // namespace testing\n+} // namespace gvisor\n+\n+#endif // GVISOR_TEST_SYSCALLS_LINUX_SOCKET_IPV4_UDP_UNBOUND_H_\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/syscalls/linux/socket_ipv4_udp_unbound_loopback.cc",
"diff": "+// Copyright 2018 Google LLC\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+#include <vector>\n+\n+#include \"test/syscalls/linux/ip_socket_test_util.h\"\n+#include \"test/syscalls/linux/socket_ipv4_udp_unbound.h\"\n+#include \"test/syscalls/linux/socket_test_util.h\"\n+#include \"test/util/test_util.h\"\n+\n+namespace gvisor {\n+namespace testing {\n+\n+std::vector<SocketPairKind> GetSocketPairs() {\n+ return ApplyVec<SocketPairKind>(\n+ IPv4UDPUnboundSocketPair,\n+ AllBitwiseCombinations(List<int>{0, SOCK_NONBLOCK}));\n+}\n+\n+INSTANTIATE_TEST_CASE_P(IPv4UDPSockets, IPv4UDPUnboundSocketPairTest,\n+ ::testing::ValuesIn(GetSocketPairs()));\n+\n+} // namespace testing\n+} // namespace gvisor\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_test_util.cc",
"new_path": "test/syscalls/linux/socket_test_util.cc",
"diff": "@@ -388,24 +388,33 @@ Creator<SocketPair> TCPAcceptBindSocketPairCreator(int domain, int type,\n};\n}\n+template <typename T>\n+PosixErrorOr<std::unique_ptr<AddrFDSocketPair>> CreateUDPBoundSocketPair(\n+ int sock1, int sock2, int type, bool dual_stack) {\n+ ASSIGN_OR_RETURN_ERRNO(T addr1, BindIP<T>(sock1, dual_stack));\n+ ASSIGN_OR_RETURN_ERRNO(T addr2, BindIP<T>(sock2, dual_stack));\n+\n+ return absl::make_unique<AddrFDSocketPair>(sock1, sock2, addr1, addr2);\n+}\n+\ntemplate <typename T>\nPosixErrorOr<std::unique_ptr<AddrFDSocketPair>>\nCreateUDPBidirectionalBindSocketPair(int sock1, int sock2, int type,\nbool dual_stack) {\n- ASSIGN_OR_RETURN_ERRNO(T addr1, BindIP<T>(sock1, dual_stack));\n- ASSIGN_OR_RETURN_ERRNO(T addr2, BindIP<T>(sock2, dual_stack));\n+ ASSIGN_OR_RETURN_ERRNO(\n+ auto socks, CreateUDPBoundSocketPair<T>(sock1, sock2, type, dual_stack));\n// Connect sock1 to sock2.\n- RETURN_ERROR_IF_SYSCALL_FAIL(connect(\n- sock1, reinterpret_cast<struct sockaddr*>(&addr2), sizeof(addr2)));\n+ RETURN_ERROR_IF_SYSCALL_FAIL(connect(socks->first_fd(), socks->second_addr(),\n+ socks->second_addr_size()));\nMaybeSave(); // Successful connection.\n// Connect sock2 to sock1.\n- RETURN_ERROR_IF_SYSCALL_FAIL(connect(\n- sock2, reinterpret_cast<struct sockaddr*>(&addr1), sizeof(addr1)));\n+ RETURN_ERROR_IF_SYSCALL_FAIL(connect(socks->second_fd(), socks->first_addr(),\n+ socks->first_addr_size()));\nMaybeSave(); // Successful connection.\n- return absl::make_unique<AddrFDSocketPair>(sock1, sock2, addr1, addr2);\n+ return socks;\n}\nCreator<SocketPair> UDPBidirectionalBindSocketPairCreator(int domain, int type,\n@@ -429,6 +438,21 @@ Creator<SocketPair> UDPBidirectionalBindSocketPairCreator(int domain, int type,\n};\n}\n+Creator<SocketPair> UDPUnboundSocketPairCreator(int domain, int type,\n+ int protocol, bool dual_stack) {\n+ return [=]() -> PosixErrorOr<std::unique_ptr<FDSocketPair>> {\n+ int sock1;\n+ RETURN_ERROR_IF_SYSCALL_FAIL(sock1 = socket(domain, type, protocol));\n+ MaybeSave(); // Successful socket creation.\n+\n+ int sock2;\n+ RETURN_ERROR_IF_SYSCALL_FAIL(sock2 = socket(domain, type, protocol));\n+ MaybeSave(); // Successful socket creation.\n+\n+ return absl::make_unique<FDSocketPair>(sock1, sock2);\n+ };\n+}\n+\nSocketPairKind Reversed(SocketPairKind const& base) {\nauto const& creator = base.creator;\nreturn SocketPairKind{\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_test_util.h",
"new_path": "test/syscalls/linux/socket_test_util.h",
"diff": "@@ -273,6 +273,11 @@ Creator<SocketPair> UDPBidirectionalBindSocketPairCreator(int domain, int type,\nint protocol,\nbool dual_stack);\n+// UDPUnboundSocketPairCreator returns a Creator<SocketPair> that obtains file\n+// descriptors by creating UDP sockets.\n+Creator<SocketPair> UDPUnboundSocketPairCreator(int domain, int type,\n+ int protocol, bool dual_stack);\n+\n// A SocketPairKind couples a human-readable description of a socket pair with\n// a function that creates such a socket pair.\nstruct SocketPairKind {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Plumb IP_ADD_MEMBERSHIP and IP_DROP_MEMBERSHIP to netstack.
Also includes a few fixes for IPv4 multicast support. IPv6 support is coming in
a followup CL.
PiperOrigin-RevId: 233008638
Change-Id: If7dae6222fef43fda48033f0292af77832d95e82 |
259,956 | 08.02.2019 10:50:14 | 28,800 | 5079b38a9af1d66ad720005d7487dd711a0cb713 | Keep FilePayloads open on server side until after RPC completed.
Prevents URPC FDs from being closed mid-call, especially if they
are used as raw FDs. | [
{
"change_type": "MODIFY",
"old_path": "pkg/fd/fd.go",
"new_path": "pkg/fd/fd.go",
"diff": "@@ -158,6 +158,9 @@ func New(fd int) *FD {\n// The returned FD is always blocking (Go 1.9+).\nfunc NewFromFile(file *os.File) (*FD, error) {\nfd, err := syscall.Dup(int(file.Fd()))\n+ // Technically, the runtime may call the finalizer on file as soon as\n+ // Fd() returns.\n+ runtime.KeepAlive(file)\nif err != nil {\nreturn &FD{ReadWriter{-1}}, err\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/urpc/BUILD",
"new_path": "pkg/urpc/BUILD",
"diff": "@@ -8,6 +8,7 @@ go_library(\nimportpath = \"gvisor.googlesource.com/gvisor/pkg/urpc\",\nvisibility = [\"//:sandbox\"],\ndeps = [\n+ \"//pkg/fd\",\n\"//pkg/log\",\n\"//pkg/unet\",\n],\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/urpc/urpc.go",
"new_path": "pkg/urpc/urpc.go",
"diff": "@@ -29,6 +29,7 @@ import (\n\"runtime\"\n\"sync\"\n+ \"gvisor.googlesource.com/gvisor/pkg/fd\"\n\"gvisor.googlesource.com/gvisor/pkg/log\"\n\"gvisor.googlesource.com/gvisor/pkg/unet\"\n)\n@@ -71,6 +72,11 @@ type FilePayload struct {\nFiles []*os.File `json:\"-\"`\n}\n+// ReleaseFD releases the indexth FD.\n+func (f *FilePayload) ReleaseFD(index int) (*fd.FD, error) {\n+ return fd.NewFromFile(f.Files[index])\n+}\n+\n// filePayload returns the file. It may be nil.\nfunc (f *FilePayload) filePayload() []*os.File {\nreturn f.Files\n@@ -268,6 +274,12 @@ func (s *Server) handleOne(client *unet.Socket) error {\nreturn err\n}\n+ // Explicitly close all these files after the call.\n+ //\n+ // This is also explicitly a reference to the files after the call,\n+ // which means they are kept open for the duration of the call.\n+ defer closeAll(newFs)\n+\n// Start the request.\nif !s.clientBeginRequest(client) {\n// Client is dead; don't process this call.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Keep FilePayloads open on server side until after RPC completed.
Prevents URPC FDs from being closed mid-call, especially if they
are used as raw FDs.
PiperOrigin-RevId: 233087955
Change-Id: I815a2ff32cc5f03774605aef0b35a32862f8e633 |
259,854 | 08.02.2019 18:22:31 | 28,800 | 85d53d81d9f544277e3e86f83558cbc008ff7adb | Use socket address functions in unbound IPv4 UDP tests.
Also switch to the correct casing style for local address variables. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_inet_loopback.cc",
"new_path": "test/syscalls/linux/socket_inet_loopback.cc",
"diff": "@@ -69,67 +69,6 @@ PosixError SetAddrPort(int family, sockaddr_storage* addr, uint16_t port) {\n}\n}\n-struct TestAddress {\n- std::string description;\n- sockaddr_storage addr;\n- socklen_t addr_len;\n-\n- int family() const { return addr.ss_family; }\n- explicit TestAddress(std::string description = \"\")\n- : description(std::move(description)), addr(), addr_len() {}\n-};\n-\n-TestAddress V4Any() {\n- TestAddress t(\"V4Any\");\n- t.addr.ss_family = AF_INET;\n- t.addr_len = sizeof(sockaddr_in);\n- reinterpret_cast<sockaddr_in*>(&t.addr)->sin_addr.s_addr = htonl(INADDR_ANY);\n- return t;\n-}\n-\n-TestAddress V4Loopback() {\n- TestAddress t(\"V4Loopback\");\n- t.addr.ss_family = AF_INET;\n- t.addr_len = sizeof(sockaddr_in);\n- reinterpret_cast<sockaddr_in*>(&t.addr)->sin_addr.s_addr =\n- htonl(INADDR_LOOPBACK);\n- return t;\n-}\n-\n-TestAddress V4MappedAny() {\n- TestAddress t(\"V4MappedAny\");\n- t.addr.ss_family = AF_INET6;\n- t.addr_len = sizeof(sockaddr_in6);\n- inet_pton(AF_INET6, \"::ffff:0.0.0.0\",\n- reinterpret_cast<sockaddr_in6*>(&t.addr)->sin6_addr.s6_addr);\n- return t;\n-}\n-\n-TestAddress V4MappedLoopback() {\n- TestAddress t(\"V4MappedLoopback\");\n- t.addr.ss_family = AF_INET6;\n- t.addr_len = sizeof(sockaddr_in6);\n- inet_pton(AF_INET6, \"::ffff:127.0.0.1\",\n- reinterpret_cast<sockaddr_in6*>(&t.addr)->sin6_addr.s6_addr);\n- return t;\n-}\n-\n-TestAddress V6Any() {\n- TestAddress t(\"V6Any\");\n- t.addr.ss_family = AF_INET6;\n- t.addr_len = sizeof(sockaddr_in6);\n- reinterpret_cast<sockaddr_in6*>(&t.addr)->sin6_addr = in6addr_any;\n- return t;\n-}\n-\n-TestAddress V6Loopback() {\n- TestAddress t(\"V6Loopback\");\n- t.addr.ss_family = AF_INET6;\n- t.addr_len = sizeof(sockaddr_in6);\n- reinterpret_cast<sockaddr_in6*>(&t.addr)->sin6_addr = in6addr_loopback;\n- return t;\n-}\n-\nstruct TestParam {\nTestAddress listener;\nTestAddress connector;\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_ipv4_udp_unbound.cc",
"new_path": "test/syscalls/linux/socket_ipv4_udp_unbound.cc",
"diff": "namespace gvisor {\nnamespace testing {\n+constexpr char kMulticastAddress[] = \"224.0.2.1\";\n+\n+TestAddress V4Multicast() {\n+ TestAddress t(\"V4Multicast\");\n+ t.addr.ss_family = AF_INET;\n+ t.addr_len = sizeof(sockaddr_in);\n+ reinterpret_cast<sockaddr_in*>(&t.addr)->sin_addr.s_addr =\n+ inet_addr(kMulticastAddress);\n+ return t;\n+}\n+\n// Check that packets are not received without a group memebership. Default send\n// interface configured by bind.\nTEST_P(IPv4UDPUnboundSocketPairTest, IpMulticastLoopbackNoGroup) {\n@@ -36,40 +47,36 @@ TEST_P(IPv4UDPUnboundSocketPairTest, IpMulticastLoopbackNoGroup) {\n// Bind the first FD to the loopback. This is an alternative to\n// IP_MULTICAST_IF for setting the default send interface.\n- sockaddr_in senderAddr = {};\n- senderAddr.sin_family = AF_INET;\n- senderAddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);\n+ auto sender_addr = V4Loopback();\nEXPECT_THAT(\n- bind(sockets->first_fd(), reinterpret_cast<sockaddr*>(&senderAddr),\n- sizeof(senderAddr)),\n+ bind(sockets->first_fd(), reinterpret_cast<sockaddr*>(&sender_addr.addr),\n+ sender_addr.addr_len),\nSyscallSucceeds());\n// Bind the second FD to the v4 any address. If multicast worked like unicast,\n// this would ensure that we get the packet.\n- sockaddr_in receiverAddr = {};\n- receiverAddr.sin_family = AF_INET;\n- receiverAddr.sin_addr.s_addr = htonl(INADDR_ANY);\n- EXPECT_THAT(\n- bind(sockets->second_fd(), reinterpret_cast<sockaddr*>(&receiverAddr),\n- sizeof(receiverAddr)),\n+ auto receiver_addr = V4Any();\n+ EXPECT_THAT(bind(sockets->second_fd(),\n+ reinterpret_cast<sockaddr*>(&receiver_addr.addr),\n+ receiver_addr.addr_len),\nSyscallSucceeds());\n- socklen_t receiverAddrLen = sizeof(receiverAddr);\n- EXPECT_THAT(\n- getsockname(sockets->second_fd(),\n- reinterpret_cast<sockaddr*>(&receiverAddr), &receiverAddrLen),\n+ socklen_t receiver_addr_len = receiver_addr.addr_len;\n+ EXPECT_THAT(getsockname(sockets->second_fd(),\n+ reinterpret_cast<sockaddr*>(&receiver_addr.addr),\n+ &receiver_addr_len),\nSyscallSucceeds());\n- EXPECT_EQ(receiverAddrLen, sizeof(receiverAddr));\n+ EXPECT_EQ(receiver_addr_len, receiver_addr.addr_len);\n// Send the multicast packet.\n- sockaddr_in sendAddr = {};\n- sendAddr.sin_family = AF_INET;\n- sendAddr.sin_port = receiverAddr.sin_port;\n- sendAddr.sin_addr.s_addr = inet_addr(\"224.0.2.1\");\n+ auto send_addr = V4Multicast();\n+ reinterpret_cast<sockaddr_in*>(&send_addr.addr)->sin_port =\n+ reinterpret_cast<sockaddr_in*>(&receiver_addr.addr)->sin_port;\nchar send_buf[200];\nRandomizeBuffer(send_buf, sizeof(send_buf));\n- EXPECT_THAT(RetryEINTR(sendto)(\n- sockets->first_fd(), send_buf, sizeof(send_buf), 0,\n- reinterpret_cast<sockaddr*>(&sendAddr), sizeof(sendAddr)),\n+ EXPECT_THAT(\n+ RetryEINTR(sendto)(sockets->first_fd(), send_buf, sizeof(send_buf), 0,\n+ reinterpret_cast<sockaddr*>(&send_addr.addr),\n+ send_addr.addr_len),\nSyscallSucceedsWithValue(sizeof(send_buf)));\n// Check that we did not receive the multicast packet.\n@@ -86,38 +93,36 @@ TEST_P(IPv4UDPUnboundSocketPairTest, IpMulticastLoopbackAddrNoDefaultSendIf) {\n// Bind the second FD to the v4 any address to ensure that we can receive any\n// unicast packet.\n- sockaddr_in receiverAddr = {};\n- receiverAddr.sin_family = AF_INET;\n- receiverAddr.sin_addr.s_addr = htonl(INADDR_ANY);\n- EXPECT_THAT(\n- bind(sockets->second_fd(), reinterpret_cast<sockaddr*>(&receiverAddr),\n- sizeof(receiverAddr)),\n+ auto receiver_addr = V4Any();\n+ EXPECT_THAT(bind(sockets->second_fd(),\n+ reinterpret_cast<sockaddr*>(&receiver_addr.addr),\n+ receiver_addr.addr_len),\nSyscallSucceeds());\n- socklen_t receiverAddrLen = sizeof(receiverAddr);\n- EXPECT_THAT(\n- getsockname(sockets->second_fd(),\n- reinterpret_cast<sockaddr*>(&receiverAddr), &receiverAddrLen),\n+ socklen_t receiver_addr_len = receiver_addr.addr_len;\n+ EXPECT_THAT(getsockname(sockets->second_fd(),\n+ reinterpret_cast<sockaddr*>(&receiver_addr.addr),\n+ &receiver_addr_len),\nSyscallSucceeds());\n- EXPECT_EQ(receiverAddrLen, sizeof(receiverAddr));\n+ EXPECT_EQ(receiver_addr_len, receiver_addr.addr_len);\n// Register to receive multicast packets.\nip_mreq group = {};\n- group.imr_multiaddr.s_addr = inet_addr(\"224.0.2.1\");\n+ group.imr_multiaddr.s_addr = inet_addr(kMulticastAddress);\ngroup.imr_interface.s_addr = htonl(INADDR_LOOPBACK);\nEXPECT_THAT(setsockopt(sockets->second_fd(), IPPROTO_IP, IP_ADD_MEMBERSHIP,\n&group, sizeof(group)),\nSyscallSucceeds());\n// Send a multicast packet.\n- sockaddr_in sendAddr = {};\n- sendAddr.sin_family = AF_INET;\n- sendAddr.sin_port = receiverAddr.sin_port;\n- sendAddr.sin_addr.s_addr = inet_addr(\"224.0.2.1\");\n+ auto send_addr = V4Multicast();\n+ reinterpret_cast<sockaddr_in*>(&send_addr.addr)->sin_port =\n+ reinterpret_cast<sockaddr_in*>(&receiver_addr.addr)->sin_port;\nchar send_buf[200];\nRandomizeBuffer(send_buf, sizeof(send_buf));\n- EXPECT_THAT(RetryEINTR(sendto)(\n- sockets->first_fd(), send_buf, sizeof(send_buf), 0,\n- reinterpret_cast<sockaddr*>(&sendAddr), sizeof(sendAddr)),\n+ EXPECT_THAT(\n+ RetryEINTR(sendto)(sockets->first_fd(), send_buf, sizeof(send_buf), 0,\n+ reinterpret_cast<sockaddr*>(&send_addr.addr),\n+ send_addr.addr_len),\nSyscallFailsWithErrno(ENETUNREACH));\n}\n@@ -128,38 +133,36 @@ TEST_P(IPv4UDPUnboundSocketPairTest, IpMulticastLoopbackNicNoDefaultSendIf) {\n// Bind the second FD to the v4 any address to ensure that we can receive any\n// unicast packet.\n- sockaddr_in receiverAddr = {};\n- receiverAddr.sin_family = AF_INET;\n- receiverAddr.sin_addr.s_addr = htonl(INADDR_ANY);\n- EXPECT_THAT(\n- bind(sockets->second_fd(), reinterpret_cast<sockaddr*>(&receiverAddr),\n- sizeof(receiverAddr)),\n+ auto receiver_addr = V4Any();\n+ EXPECT_THAT(bind(sockets->second_fd(),\n+ reinterpret_cast<sockaddr*>(&receiver_addr.addr),\n+ receiver_addr.addr_len),\nSyscallSucceeds());\n- socklen_t receiverAddrLen = sizeof(receiverAddr);\n- EXPECT_THAT(\n- getsockname(sockets->second_fd(),\n- reinterpret_cast<sockaddr*>(&receiverAddr), &receiverAddrLen),\n+ socklen_t receiver_addr_len = receiver_addr.addr_len;\n+ EXPECT_THAT(getsockname(sockets->second_fd(),\n+ reinterpret_cast<sockaddr*>(&receiver_addr.addr),\n+ &receiver_addr_len),\nSyscallSucceeds());\n- EXPECT_EQ(receiverAddrLen, sizeof(receiverAddr));\n+ EXPECT_EQ(receiver_addr_len, receiver_addr.addr_len);\n// Register to receive multicast packets.\nip_mreqn group = {};\n- group.imr_multiaddr.s_addr = inet_addr(\"224.0.2.1\");\n+ group.imr_multiaddr.s_addr = inet_addr(kMulticastAddress);\ngroup.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(InterfaceIndex(\"lo\"));\nEXPECT_THAT(setsockopt(sockets->second_fd(), IPPROTO_IP, IP_ADD_MEMBERSHIP,\n&group, sizeof(group)),\nSyscallSucceeds());\n// Send a multicast packet.\n- sockaddr_in sendAddr = {};\n- sendAddr.sin_family = AF_INET;\n- sendAddr.sin_port = receiverAddr.sin_port;\n- sendAddr.sin_addr.s_addr = inet_addr(\"224.0.2.1\");\n+ auto send_addr = V4Multicast();\n+ reinterpret_cast<sockaddr_in*>(&send_addr.addr)->sin_port =\n+ reinterpret_cast<sockaddr_in*>(&receiver_addr.addr)->sin_port;\nchar send_buf[200];\nRandomizeBuffer(send_buf, sizeof(send_buf));\n- EXPECT_THAT(RetryEINTR(sendto)(\n- sockets->first_fd(), send_buf, sizeof(send_buf), 0,\n- reinterpret_cast<sockaddr*>(&sendAddr), sizeof(sendAddr)),\n+ EXPECT_THAT(\n+ RetryEINTR(sendto)(sockets->first_fd(), send_buf, sizeof(send_buf), 0,\n+ reinterpret_cast<sockaddr*>(&send_addr.addr),\n+ send_addr.addr_len),\nSyscallFailsWithErrno(ENETUNREACH));\n}\n@@ -170,48 +173,44 @@ TEST_P(IPv4UDPUnboundSocketPairTest, IpMulticastLoopbackAddr) {\n// Bind the first FD to the loopback. This is an alternative to\n// IP_MULTICAST_IF for setting the default send interface.\n- sockaddr_in senderAddr = {};\n- senderAddr.sin_family = AF_INET;\n- senderAddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);\n+ auto sender_addr = V4Loopback();\nEXPECT_THAT(\n- bind(sockets->first_fd(), reinterpret_cast<sockaddr*>(&senderAddr),\n- sizeof(senderAddr)),\n+ bind(sockets->first_fd(), reinterpret_cast<sockaddr*>(&sender_addr.addr),\n+ sender_addr.addr_len),\nSyscallSucceeds());\n// Bind the second FD to the v4 any address to ensure that we can receive the\n// multicast packet.\n- sockaddr_in receiverAddr = {};\n- receiverAddr.sin_family = AF_INET;\n- receiverAddr.sin_addr.s_addr = htonl(INADDR_ANY);\n- EXPECT_THAT(\n- bind(sockets->second_fd(), reinterpret_cast<sockaddr*>(&receiverAddr),\n- sizeof(receiverAddr)),\n+ auto receiver_addr = V4Any();\n+ EXPECT_THAT(bind(sockets->second_fd(),\n+ reinterpret_cast<sockaddr*>(&receiver_addr.addr),\n+ receiver_addr.addr_len),\nSyscallSucceeds());\n- socklen_t receiverAddrLen = sizeof(receiverAddr);\n- EXPECT_THAT(\n- getsockname(sockets->second_fd(),\n- reinterpret_cast<sockaddr*>(&receiverAddr), &receiverAddrLen),\n+ socklen_t receiver_addr_len = receiver_addr.addr_len;\n+ EXPECT_THAT(getsockname(sockets->second_fd(),\n+ reinterpret_cast<sockaddr*>(&receiver_addr.addr),\n+ &receiver_addr_len),\nSyscallSucceeds());\n- EXPECT_EQ(receiverAddrLen, sizeof(receiverAddr));\n+ EXPECT_EQ(receiver_addr_len, receiver_addr.addr_len);\n// Register to receive multicast packets.\nip_mreq group = {};\n- group.imr_multiaddr.s_addr = inet_addr(\"224.0.2.1\");\n+ group.imr_multiaddr.s_addr = inet_addr(kMulticastAddress);\ngroup.imr_interface.s_addr = htonl(INADDR_LOOPBACK);\nEXPECT_THAT(setsockopt(sockets->second_fd(), IPPROTO_IP, IP_ADD_MEMBERSHIP,\n&group, sizeof(group)),\nSyscallSucceeds());\n// Send a multicast packet.\n- sockaddr_in sendAddr = {};\n- sendAddr.sin_family = AF_INET;\n- sendAddr.sin_port = receiverAddr.sin_port;\n- sendAddr.sin_addr.s_addr = inet_addr(\"224.0.2.1\");\n+ auto send_addr = V4Multicast();\n+ reinterpret_cast<sockaddr_in*>(&send_addr.addr)->sin_port =\n+ reinterpret_cast<sockaddr_in*>(&receiver_addr.addr)->sin_port;\nchar send_buf[200];\nRandomizeBuffer(send_buf, sizeof(send_buf));\n- EXPECT_THAT(RetryEINTR(sendto)(\n- sockets->first_fd(), send_buf, sizeof(send_buf), 0,\n- reinterpret_cast<sockaddr*>(&sendAddr), sizeof(sendAddr)),\n+ EXPECT_THAT(\n+ RetryEINTR(sendto)(sockets->first_fd(), send_buf, sizeof(send_buf), 0,\n+ reinterpret_cast<sockaddr*>(&send_addr.addr),\n+ send_addr.addr_len),\nSyscallSucceedsWithValue(sizeof(send_buf)));\n// Check that we received the multicast packet.\n@@ -230,48 +229,44 @@ TEST_P(IPv4UDPUnboundSocketPairTest, IpMulticastLoopbackNic) {\n// Bind the first FD to the loopback. This is an alternative to\n// IP_MULTICAST_IF for setting the default send interface.\n- sockaddr_in senderAddr = {};\n- senderAddr.sin_family = AF_INET;\n- senderAddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);\n+ auto sender_addr = V4Loopback();\nEXPECT_THAT(\n- bind(sockets->first_fd(), reinterpret_cast<sockaddr*>(&senderAddr),\n- sizeof(senderAddr)),\n+ bind(sockets->first_fd(), reinterpret_cast<sockaddr*>(&sender_addr.addr),\n+ sender_addr.addr_len),\nSyscallSucceeds());\n// Bind the second FD to the v4 any address to ensure that we can receive the\n// multicast packet.\n- sockaddr_in receiverAddr = {};\n- receiverAddr.sin_family = AF_INET;\n- receiverAddr.sin_addr.s_addr = htonl(INADDR_ANY);\n- EXPECT_THAT(\n- bind(sockets->second_fd(), reinterpret_cast<sockaddr*>(&receiverAddr),\n- sizeof(receiverAddr)),\n+ auto receiver_addr = V4Any();\n+ EXPECT_THAT(bind(sockets->second_fd(),\n+ reinterpret_cast<sockaddr*>(&receiver_addr.addr),\n+ receiver_addr.addr_len),\nSyscallSucceeds());\n- socklen_t receiverAddrLen = sizeof(receiverAddr);\n- EXPECT_THAT(\n- getsockname(sockets->second_fd(),\n- reinterpret_cast<sockaddr*>(&receiverAddr), &receiverAddrLen),\n+ socklen_t receiver_addr_len = receiver_addr.addr_len;\n+ EXPECT_THAT(getsockname(sockets->second_fd(),\n+ reinterpret_cast<sockaddr*>(&receiver_addr.addr),\n+ &receiver_addr_len),\nSyscallSucceeds());\n- EXPECT_EQ(receiverAddrLen, sizeof(receiverAddr));\n+ EXPECT_EQ(receiver_addr_len, receiver_addr.addr_len);\n// Register to receive multicast packets.\nip_mreqn group = {};\n- group.imr_multiaddr.s_addr = inet_addr(\"224.0.2.1\");\n+ group.imr_multiaddr.s_addr = inet_addr(kMulticastAddress);\ngroup.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(InterfaceIndex(\"lo\"));\nEXPECT_THAT(setsockopt(sockets->second_fd(), IPPROTO_IP, IP_ADD_MEMBERSHIP,\n&group, sizeof(group)),\nSyscallSucceeds());\n// Send a multicast packet.\n- sockaddr_in sendAddr = {};\n- sendAddr.sin_family = AF_INET;\n- sendAddr.sin_port = receiverAddr.sin_port;\n- sendAddr.sin_addr.s_addr = inet_addr(\"224.0.2.1\");\n+ auto send_addr = V4Multicast();\n+ reinterpret_cast<sockaddr_in*>(&send_addr.addr)->sin_port =\n+ reinterpret_cast<sockaddr_in*>(&receiver_addr.addr)->sin_port;\nchar send_buf[200];\nRandomizeBuffer(send_buf, sizeof(send_buf));\n- EXPECT_THAT(RetryEINTR(sendto)(\n- sockets->first_fd(), send_buf, sizeof(send_buf), 0,\n- reinterpret_cast<sockaddr*>(&sendAddr), sizeof(sendAddr)),\n+ EXPECT_THAT(\n+ RetryEINTR(sendto)(sockets->first_fd(), send_buf, sizeof(send_buf), 0,\n+ reinterpret_cast<sockaddr*>(&send_addr.addr),\n+ send_addr.addr_len),\nSyscallSucceedsWithValue(sizeof(send_buf)));\n// Check that we received the multicast packet.\n@@ -289,7 +284,7 @@ TEST_P(IPv4UDPUnboundSocketPairTest, IpMulticastInvalidDrop) {\n// Unregister from a membership that we didn't have.\nip_mreq group = {};\n- group.imr_multiaddr.s_addr = inet_addr(\"224.0.2.1\");\n+ group.imr_multiaddr.s_addr = inet_addr(kMulticastAddress);\ngroup.imr_interface.s_addr = htonl(INADDR_LOOPBACK);\nEXPECT_THAT(setsockopt(sockets->first_fd(), IPPROTO_IP, IP_DROP_MEMBERSHIP,\n&group, sizeof(group)),\n@@ -304,33 +299,29 @@ TEST_P(IPv4UDPUnboundSocketPairTest, IpMulticastDropAddr) {\n// Bind the first FD to the loopback. This is an alternative to\n// IP_MULTICAST_IF for setting the default send interface.\n- sockaddr_in senderAddr = {};\n- senderAddr.sin_family = AF_INET;\n- senderAddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);\n+ auto sender_addr = V4Loopback();\nEXPECT_THAT(\n- bind(sockets->first_fd(), reinterpret_cast<sockaddr*>(&senderAddr),\n- sizeof(senderAddr)),\n+ bind(sockets->first_fd(), reinterpret_cast<sockaddr*>(&sender_addr.addr),\n+ sender_addr.addr_len),\nSyscallSucceeds());\n// Bind the second FD to the v4 any address to ensure that we can receive the\n// multicast packet.\n- sockaddr_in receiverAddr = {};\n- receiverAddr.sin_family = AF_INET;\n- receiverAddr.sin_addr.s_addr = htonl(INADDR_ANY);\n- EXPECT_THAT(\n- bind(sockets->second_fd(), reinterpret_cast<sockaddr*>(&receiverAddr),\n- sizeof(receiverAddr)),\n+ auto receiver_addr = V4Any();\n+ EXPECT_THAT(bind(sockets->second_fd(),\n+ reinterpret_cast<sockaddr*>(&receiver_addr.addr),\n+ receiver_addr.addr_len),\nSyscallSucceeds());\n- socklen_t receiverAddrLen = sizeof(receiverAddr);\n- EXPECT_THAT(\n- getsockname(sockets->second_fd(),\n- reinterpret_cast<sockaddr*>(&receiverAddr), &receiverAddrLen),\n+ socklen_t receiver_addr_len = receiver_addr.addr_len;\n+ EXPECT_THAT(getsockname(sockets->second_fd(),\n+ reinterpret_cast<sockaddr*>(&receiver_addr.addr),\n+ &receiver_addr_len),\nSyscallSucceeds());\n- EXPECT_EQ(receiverAddrLen, sizeof(receiverAddr));\n+ EXPECT_EQ(receiver_addr_len, receiver_addr.addr_len);\n// Register and unregister to receive multicast packets.\nip_mreq group = {};\n- group.imr_multiaddr.s_addr = inet_addr(\"224.0.2.1\");\n+ group.imr_multiaddr.s_addr = inet_addr(kMulticastAddress);\ngroup.imr_interface.s_addr = htonl(INADDR_LOOPBACK);\nEXPECT_THAT(setsockopt(sockets->second_fd(), IPPROTO_IP, IP_ADD_MEMBERSHIP,\n&group, sizeof(group)),\n@@ -340,15 +331,15 @@ TEST_P(IPv4UDPUnboundSocketPairTest, IpMulticastDropAddr) {\nSyscallSucceeds());\n// Send a multicast packet.\n- sockaddr_in sendAddr = {};\n- sendAddr.sin_family = AF_INET;\n- sendAddr.sin_port = receiverAddr.sin_port;\n- sendAddr.sin_addr.s_addr = inet_addr(\"224.0.2.1\");\n+ auto send_addr = V4Multicast();\n+ reinterpret_cast<sockaddr_in*>(&send_addr.addr)->sin_port =\n+ reinterpret_cast<sockaddr_in*>(&receiver_addr.addr)->sin_port;\nchar send_buf[200];\nRandomizeBuffer(send_buf, sizeof(send_buf));\n- EXPECT_THAT(RetryEINTR(sendto)(\n- sockets->first_fd(), send_buf, sizeof(send_buf), 0,\n- reinterpret_cast<sockaddr*>(&sendAddr), sizeof(sendAddr)),\n+ EXPECT_THAT(\n+ RetryEINTR(sendto)(sockets->first_fd(), send_buf, sizeof(send_buf), 0,\n+ reinterpret_cast<sockaddr*>(&send_addr.addr),\n+ send_addr.addr_len),\nSyscallSucceedsWithValue(sizeof(send_buf)));\n// Check that we did not receive the multicast packet.\n@@ -366,33 +357,29 @@ TEST_P(IPv4UDPUnboundSocketPairTest, IpMulticastDropNic) {\n// Bind the first FD to the loopback. This is an alternative to\n// IP_MULTICAST_IF for setting the default send interface.\n- sockaddr_in senderAddr = {};\n- senderAddr.sin_family = AF_INET;\n- senderAddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);\n+ auto sender_addr = V4Loopback();\nEXPECT_THAT(\n- bind(sockets->first_fd(), reinterpret_cast<sockaddr*>(&senderAddr),\n- sizeof(senderAddr)),\n+ bind(sockets->first_fd(), reinterpret_cast<sockaddr*>(&sender_addr.addr),\n+ sender_addr.addr_len),\nSyscallSucceeds());\n// Bind the second FD to the v4 any address to ensure that we can receive the\n// multicast packet.\n- sockaddr_in receiverAddr = {};\n- receiverAddr.sin_family = AF_INET;\n- receiverAddr.sin_addr.s_addr = htonl(INADDR_ANY);\n- EXPECT_THAT(\n- bind(sockets->second_fd(), reinterpret_cast<sockaddr*>(&receiverAddr),\n- sizeof(receiverAddr)),\n+ auto receiver_addr = V4Any();\n+ EXPECT_THAT(bind(sockets->second_fd(),\n+ reinterpret_cast<sockaddr*>(&receiver_addr.addr),\n+ receiver_addr.addr_len),\nSyscallSucceeds());\n- socklen_t receiverAddrLen = sizeof(receiverAddr);\n- EXPECT_THAT(\n- getsockname(sockets->second_fd(),\n- reinterpret_cast<sockaddr*>(&receiverAddr), &receiverAddrLen),\n+ socklen_t receiver_addr_len = receiver_addr.addr_len;\n+ EXPECT_THAT(getsockname(sockets->second_fd(),\n+ reinterpret_cast<sockaddr*>(&receiver_addr.addr),\n+ &receiver_addr_len),\nSyscallSucceeds());\n- EXPECT_EQ(receiverAddrLen, sizeof(receiverAddr));\n+ EXPECT_EQ(receiver_addr_len, receiver_addr.addr_len);\n// Register and unregister to receive multicast packets.\nip_mreqn group = {};\n- group.imr_multiaddr.s_addr = inet_addr(\"224.0.2.1\");\n+ group.imr_multiaddr.s_addr = inet_addr(kMulticastAddress);\ngroup.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(InterfaceIndex(\"lo\"));\nEXPECT_THAT(setsockopt(sockets->second_fd(), IPPROTO_IP, IP_ADD_MEMBERSHIP,\n&group, sizeof(group)),\n@@ -402,15 +389,15 @@ TEST_P(IPv4UDPUnboundSocketPairTest, IpMulticastDropNic) {\nSyscallSucceeds());\n// Send a multicast packet.\n- sockaddr_in sendAddr = {};\n- sendAddr.sin_family = AF_INET;\n- sendAddr.sin_port = receiverAddr.sin_port;\n- sendAddr.sin_addr.s_addr = inet_addr(\"224.0.2.1\");\n+ auto send_addr = V4Multicast();\n+ reinterpret_cast<sockaddr_in*>(&send_addr.addr)->sin_port =\n+ reinterpret_cast<sockaddr_in*>(&receiver_addr.addr)->sin_port;\nchar send_buf[200];\nRandomizeBuffer(send_buf, sizeof(send_buf));\n- EXPECT_THAT(RetryEINTR(sendto)(\n- sockets->first_fd(), send_buf, sizeof(send_buf), 0,\n- reinterpret_cast<sockaddr*>(&sendAddr), sizeof(sendAddr)),\n+ EXPECT_THAT(\n+ RetryEINTR(sendto)(sockets->first_fd(), send_buf, sizeof(send_buf), 0,\n+ reinterpret_cast<sockaddr*>(&send_addr.addr),\n+ send_addr.addr_len),\nSyscallSucceedsWithValue(sizeof(send_buf)));\n// Check that we did not receive the multicast packet.\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_test_util.cc",
"new_path": "test/syscalls/linux/socket_test_util.cc",
"diff": "@@ -680,5 +680,56 @@ void RecvNoData(int sock) {\nSyscallFailsWithErrno(EAGAIN));\n}\n+TestAddress V4Any() {\n+ TestAddress t(\"V4Any\");\n+ t.addr.ss_family = AF_INET;\n+ t.addr_len = sizeof(sockaddr_in);\n+ reinterpret_cast<sockaddr_in*>(&t.addr)->sin_addr.s_addr = htonl(INADDR_ANY);\n+ return t;\n+}\n+\n+TestAddress V4Loopback() {\n+ TestAddress t(\"V4Loopback\");\n+ t.addr.ss_family = AF_INET;\n+ t.addr_len = sizeof(sockaddr_in);\n+ reinterpret_cast<sockaddr_in*>(&t.addr)->sin_addr.s_addr =\n+ htonl(INADDR_LOOPBACK);\n+ return t;\n+}\n+\n+TestAddress V4MappedAny() {\n+ TestAddress t(\"V4MappedAny\");\n+ t.addr.ss_family = AF_INET6;\n+ t.addr_len = sizeof(sockaddr_in6);\n+ inet_pton(AF_INET6, \"::ffff:0.0.0.0\",\n+ reinterpret_cast<sockaddr_in6*>(&t.addr)->sin6_addr.s6_addr);\n+ return t;\n+}\n+\n+TestAddress V4MappedLoopback() {\n+ TestAddress t(\"V4MappedLoopback\");\n+ t.addr.ss_family = AF_INET6;\n+ t.addr_len = sizeof(sockaddr_in6);\n+ inet_pton(AF_INET6, \"::ffff:127.0.0.1\",\n+ reinterpret_cast<sockaddr_in6*>(&t.addr)->sin6_addr.s6_addr);\n+ return t;\n+}\n+\n+TestAddress V6Any() {\n+ TestAddress t(\"V6Any\");\n+ t.addr.ss_family = AF_INET6;\n+ t.addr_len = sizeof(sockaddr_in6);\n+ reinterpret_cast<sockaddr_in6*>(&t.addr)->sin6_addr = in6addr_any;\n+ return t;\n+}\n+\n+TestAddress V6Loopback() {\n+ TestAddress t(\"V6Loopback\");\n+ t.addr.ss_family = AF_INET6;\n+ t.addr_len = sizeof(sockaddr_in6);\n+ reinterpret_cast<sockaddr_in6*>(&t.addr)->sin6_addr = in6addr_loopback;\n+ return t;\n+}\n+\n} // namespace testing\n} // namespace gvisor\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_test_util.h",
"new_path": "test/syscalls/linux/socket_test_util.h",
"diff": "@@ -449,6 +449,23 @@ void RecvNoData(int sock);\n// sockets.\nusing AllSocketPairTest = SocketPairTest;\n+struct TestAddress {\n+ std::string description;\n+ sockaddr_storage addr;\n+ socklen_t addr_len;\n+\n+ int family() const { return addr.ss_family; }\n+ explicit TestAddress(std::string description = \"\")\n+ : description(std::move(description)), addr(), addr_len() {}\n+};\n+\n+TestAddress V4Any();\n+TestAddress V4Loopback();\n+TestAddress V4MappedAny();\n+TestAddress V4MappedLoopback();\n+TestAddress V6Any();\n+TestAddress V6Loopback();\n+\n} // namespace testing\n} // namespace gvisor\n"
}
] | Go | Apache License 2.0 | google/gvisor | Use socket address functions in unbound IPv4 UDP tests.
Also switch to the correct casing style for local address variables.
PiperOrigin-RevId: 233161128
Change-Id: Ibc4a10a5d3ab04c40907aa885e8237b255c65a79 |
259,853 | 11.02.2019 12:42:20 | 28,800 | ecce96bab56de3aedd7d5cf47a6981f0f56acba1 | gvisor: Run syscall tests in kokoro on the rbe cluster | [
{
"change_type": "MODIFY",
"old_path": ".bazelrc_rbe",
"new_path": ".bazelrc_rbe",
"diff": "@@ -51,10 +51,10 @@ build:remote --action_env=BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1\n# \"extra_toolchains\" to be selected (given constraints defined in\n# \"exec_compatible_with\").\n# More about platforms: https://docs.bazel.build/versions/master/platforms.html\n-build:remote --extra_toolchains=@bazel_toolchains//configs/ubuntu16_04_clang/1.1/bazel_0.20.0/cpp:cc-toolchain-clang-x86_64-default\n-build:remote --extra_execution_platforms=@bazel_toolchains//configs/ubuntu16_04_clang/1.1:rbe_ubuntu1604\n-build:remote --host_platform=@bazel_toolchains//configs/ubuntu16_04_clang/1.1:rbe_ubuntu1604\n-build:remote --platforms=@bazel_toolchains//configs/ubuntu16_04_clang/1.1:rbe_ubuntu1604\n+build:remote --extra_toolchains=//test:cc-toolchain-clang-x86_64-default\n+build:remote --extra_execution_platforms=//test:rbe_ubuntu1604\n+build:remote --host_platform=//test:rbe_ubuntu1604\n+build:remote --platforms=//test:rbe_ubuntu1604\n# Set various strategies so that all actions execute remotely. Mixing remote\n# and local execution will lead to errors unless the toolchain and remote\n"
},
{
"change_type": "MODIFY",
"old_path": "kokoro/presubmit.cfg",
"new_path": "kokoro/presubmit.cfg",
"diff": "@@ -7,5 +7,6 @@ action {\ndefine_artifacts {\nregex: \"**/sponge_log.xml\"\nregex: \"**/sponge_log.log\"\n+ regex: \"**/outputs.zip\"\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "kokoro/run_tests.sh",
"new_path": "kokoro/run_tests.sh",
"diff": "@@ -33,8 +33,6 @@ readonly RUNTIME=\"runsc_test_$((RANDOM))\"\n# Packages that will be built and tested.\nreadonly BUILD_PACKAGES=(\"//...\")\n-# TODO: Include syscall tests in \"test\" directory once all tests\n-# pass on RBE.\nreadonly TEST_PACKAGES=(\"//pkg/...\" \"//runsc/...\" \"//tools/...\")\n#######################\n@@ -174,17 +172,30 @@ run_root_tests() {\nsudo -n -E RUNSC_RUNTIME=\"${RUNTIME}\" RUNSC_EXEC=/tmp/\"${RUNTIME}\"/runsc ${root_test}\n}\n+# Run syscall unit tests.\n+run_syscall_tests() {\n+ cd ${WORKSPACE_DIR}\n+ # TODO: Exclude tests which fail.\n+ bazel \\\n+ \"${BAZEL_RBE_FLAGS[@]}\" \\\n+ test \"${BAZEL_BUILD_RBE_FLAGS[@]}\" \\\n+ `bazel query //test/syscalls/... |\n+ grep runsc_ptrace |\n+ grep -v affinity_test_runsc_ptrace |\n+ grep -v exec_test_runsc_ptrace |\n+ grep -v open_create_test_runsc_ptrace |\n+ grep -v clock_gettime_test_runsc_ptrace`\n+}\n+\n# Find and rename all test xml and log files so that Sponge can pick them up.\n# XML files must be named sponge_log.xml, and log files must be named\n# sponge_log.log. We move all such files into KOKORO_ARTIFACTS_DIR, in a\n# subdirectory named with the test name.\nupload_test_artifacts() {\ncd ${WORKSPACE_DIR}\n- for file in $(find -L \"bazel-testlogs\" -name \"test.xml\" -o -name \"test.log\"); do\n- newpath=${KOKORO_ARTIFACTS_DIR}/$(dirname ${file})\n- extension=\"${file##*.}\"\n- mkdir -p \"${newpath}\" && cp \"${file}\" \"${newpath}/sponge_log.${extension}\"\n- done\n+ find -L \"bazel-testlogs\" -name \"test.xml\" -o -name \"test.log\" -o -name \"outputs.zip\" |\n+ tar --create --files-from - --transform 's/test\\./sponge_log./' |\n+ tar --extract --directory ${KOKORO_ARTIFACTS_DIR}\n}\n# Finish runs at exit, even in the event of an error, and uploads all test\n@@ -214,6 +225,8 @@ main() {\nrun_docker_tests\nrun_root_tests\n+ run_syscall_tests\n+\n# No need to call \"finish\" here, it will happen at exit.\n}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/BUILD",
"diff": "+# gVisor is a general-purpose sandbox.\n+\n+package(licenses = [\"notice\"])\n+\n+exports_files([\"LICENSE\"])\n+\n+# We need to define a bazel platform and toolchain to specify dockerPrivileged\n+# and dockerRunAsRoot options, they are required to run tests on the RBE\n+# cluster in Kokoro.\n+alias(\n+ name = \"rbe_ubuntu1604\",\n+ actual = \":rbe_ubuntu1604_r346485\",\n+)\n+\n+platform(\n+ name = \"rbe_ubuntu1604_r346485\",\n+ constraint_values = [\n+ \"@bazel_tools//platforms:x86_64\",\n+ \"@bazel_tools//platforms:linux\",\n+ \"@bazel_tools//tools/cpp:clang\",\n+ \"@bazel_toolchains//constraints:xenial\",\n+ \"@bazel_toolchains//constraints/sanitizers:support_msan\",\n+ ],\n+ remote_execution_properties = \"\"\"\n+ properties: {\n+ name: \"container-image\"\n+ value:\"docker://gcr.io/cloud-marketplace/google/rbe-ubuntu16-04@sha256:f3120a030a19d67626ababdac79cc787e699a1aa924081431285118f87e7b375\"\n+ }\n+ properties: {\n+ name: \"dockerAddCapabilities\"\n+ value: \"SYS_ADMIN\"\n+ }\n+ properties: {\n+ name: \"dockerPrivileged\"\n+ value: \"true\"\n+ }\n+ properties: {\n+ name: \"dockerRunAsRoot\"\n+ value: \"true\"\n+ }\n+ \"\"\",\n+)\n+\n+toolchain(\n+ name = \"cc-toolchain-clang-x86_64-default\",\n+ exec_compatible_with = [\n+ ],\n+ target_compatible_with = [\n+ ],\n+ toolchain = \"@bazel_toolchains//configs/ubuntu16_04_clang/1.1/bazel_0.20.0/default:cc-compiler-k8\",\n+ toolchain_type = \"@bazel_tools//tools/cpp:toolchain_type\",\n+)\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/BUILD",
"new_path": "test/syscalls/BUILD",
"diff": "@@ -9,7 +9,7 @@ syscall_test(test = \"//test/syscalls/linux:accept_bind_stream_test\")\nsyscall_test(\nsize = \"large\",\n- shard_count = 50,\n+ shard_count = 10,\ntest = \"//test/syscalls/linux:accept_bind_test\",\n)\n@@ -107,7 +107,7 @@ syscall_test(test = \"//test/syscalls/linux:fsync_test\")\nsyscall_test(\nsize = \"medium\",\n- shard_count = 20,\n+ shard_count = 5,\ntest = \"//test/syscalls/linux:futex_test\",\n)\n@@ -162,7 +162,7 @@ syscall_test(\nsyscall_test(\nsize = \"medium\",\n- shard_count = 10,\n+ shard_count = 5,\ntest = \"//test/syscalls/linux:mmap_test\",\n)\n@@ -296,7 +296,7 @@ syscall_test(\nsyscall_test(\nsize = \"large\",\n- shard_count = 50,\n+ shard_count = 10,\ntest = \"//test/syscalls/linux:socket_abstract_test\",\n)\n@@ -307,7 +307,7 @@ syscall_test(\nsyscall_test(\nsize = \"large\",\n- shard_count = 50,\n+ shard_count = 10,\ntest = \"//test/syscalls/linux:socket_domain_test\",\n)\n@@ -318,7 +318,7 @@ syscall_test(\nsyscall_test(\nsize = \"large\",\n- shard_count = 50,\n+ shard_count = 10,\ntest = \"//test/syscalls/linux:socket_filesystem_test\",\n)\n@@ -329,7 +329,7 @@ syscall_test(\nsyscall_test(\nsize = \"large\",\n- shard_count = 50,\n+ shard_count = 10,\ntest = \"//test/syscalls/linux:socket_ip_tcp_generic_loopback_test\",\n)\n@@ -340,13 +340,13 @@ syscall_test(\nsyscall_test(\nsize = \"large\",\n- shard_count = 50,\n+ shard_count = 10,\ntest = \"//test/syscalls/linux:socket_ip_tcp_loopback_test\",\n)\nsyscall_test(\nsize = \"medium\",\n- shard_count = 50,\n+ shard_count = 10,\ntest = \"//test/syscalls/linux:socket_ip_tcp_udp_generic_loopback_test\",\n)\n@@ -357,7 +357,7 @@ syscall_test(\nsyscall_test(\nsize = \"large\",\n- shard_count = 50,\n+ shard_count = 10,\ntest = \"//test/syscalls/linux:socket_ip_udp_loopback_test\",\n)\n@@ -397,7 +397,7 @@ syscall_test(\nsyscall_test(\nsize = \"large\",\n- shard_count = 50,\n+ shard_count = 10,\ntest = \"//test/syscalls/linux:socket_unix_abstract_test\",\n)\n@@ -414,13 +414,13 @@ syscall_test(\nsyscall_test(\nsize = \"large\",\n- shard_count = 50,\n+ shard_count = 10,\ntest = \"//test/syscalls/linux:socket_unix_filesystem_test\",\n)\nsyscall_test(\nsize = \"large\",\n- shard_count = 50,\n+ shard_count = 10,\ntest = \"//test/syscalls/linux:socket_unix_pair_test\",\n)\n@@ -452,13 +452,13 @@ syscall_test(\nsyscall_test(\nsize = \"medium\",\n- shard_count = 50,\n+ shard_count = 10,\ntest = \"//test/syscalls/linux:socket_unix_unbound_seqpacket_test\",\n)\nsyscall_test(\nsize = \"large\",\n- shard_count = 50,\n+ shard_count = 10,\ntest = \"//test/syscalls/linux:socket_unix_unbound_stream_test\",\n)\n@@ -484,7 +484,7 @@ syscall_test(test = \"//test/syscalls/linux:sysret_test\")\nsyscall_test(\nsize = \"medium\",\n- shard_count = 50,\n+ shard_count = 10,\ntest = \"//test/syscalls/linux:tcp_socket_test\",\n)\n@@ -504,7 +504,7 @@ syscall_test(test = \"//test/syscalls/linux:udp_bind_test\")\nsyscall_test(\nsize = \"medium\",\n- shard_count = 50,\n+ shard_count = 10,\ntest = \"//test/syscalls/linux:udp_socket_test\",\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/build_defs.bzl",
"new_path": "test/syscalls/build_defs.bzl",
"diff": "# syscall_test is a macro that will create targets to run the given test target\n# on the host (native) and runsc.\n-def syscall_test(test, shard_count = 5, size = \"small\", use_tmpfs = False):\n+def syscall_test(test, shard_count = 1, size = \"small\", use_tmpfs = False):\n_syscall_test(test, shard_count, size, \"native\", False)\n_syscall_test(test, shard_count, size, \"kvm\", use_tmpfs)\n_syscall_test(test, shard_count, size, \"ptrace\", use_tmpfs)\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/syscall_test_runner.sh",
"new_path": "test/syscalls/syscall_test_runner.sh",
"diff": "# It exists so that we can build the syscall test runner once, and use it for\n# all syscall tests, rather than build it for each test run.\n-set -euf -o pipefail\n+set -euf -x -o pipefail\n+\n+echo -- \"$@\"\n+\n+if [[ -n \"${TEST_UNDECLARED_OUTPUTS_DIR}\" ]]; then\n+ mkdir -p \"${TEST_UNDECLARED_OUTPUTS_DIR}\"\n+ chmod a+rwx \"${TEST_UNDECLARED_OUTPUTS_DIR}\"\n+fi\n# Get location of syscall_test_runner binary.\n-readonly runner=$(find ${TEST_SRCDIR} -name syscall_test_runner)\n+readonly runner=$(find \"${TEST_SRCDIR}\" -name syscall_test_runner)\n# Pass the arguments of this script directly to the runner.\nexec \"${runner}\" \"$@\"\n"
}
] | Go | Apache License 2.0 | google/gvisor | gvisor: Run syscall tests in kokoro on the rbe cluster
PiperOrigin-RevId: 233458853
Change-Id: I92c734b8075aa31e040fe7b4770bcf608e271e7a |
259,853 | 11.02.2019 18:04:29 | 28,800 | 3ff9dc9cc1f69605f9e9e3c028d81957c37349a3 | gvisor: check that ptrace properly handles int3 | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/ptrace.cc",
"new_path": "test/syscalls/linux/ptrace.cc",
"diff": "@@ -809,6 +809,44 @@ TEST(PtraceTest,\n// These tests requires knowledge of architecture-specific syscall convention.\n#ifdef __x86_64__\n+TEST(PtraceTest, Int3) {\n+ switch (GvisorPlatform()) {\n+ case Platform::kKVM:\n+ // TODO: int3 isn't handled properly.\n+ return;\n+ default:\n+ break;\n+ }\n+ pid_t const child_pid = fork();\n+ if (child_pid == 0) {\n+ // In child process.\n+\n+ // Enable tracing.\n+ TEST_PCHECK(ptrace(PTRACE_TRACEME, 0, 0, 0) == 0);\n+\n+ // Interrupt 3 - trap to debugger\n+ asm(\"int3\");\n+\n+ _exit(56);\n+ }\n+ // In parent process.\n+ ASSERT_THAT(child_pid, SyscallSucceeds());\n+\n+ int status;\n+ ASSERT_THAT(waitpid(child_pid, &status, 0),\n+ SyscallSucceedsWithValue(child_pid));\n+ EXPECT_TRUE(WIFSTOPPED(status) && WSTOPSIG(status) == SIGTRAP)\n+ << \" status \" << status;\n+\n+ ASSERT_THAT(ptrace(PTRACE_CONT, child_pid, 0, 0), SyscallSucceeds());\n+\n+ // The child should validate the injected return value and then exit normally.\n+ ASSERT_THAT(waitpid(child_pid, &status, 0),\n+ SyscallSucceedsWithValue(child_pid));\n+ EXPECT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) == 56)\n+ << \" status \" << status;\n+}\n+\nTEST(PtraceTest, Sysemu_PokeUser) {\nconstexpr int kSysemuHelperFirstExitCode = 126;\nconstexpr uint64_t kSysemuInjectedExitGroupReturn = 42;\n"
}
] | Go | Apache License 2.0 | google/gvisor | gvisor: check that ptrace properly handles int3
PiperOrigin-RevId: 233516412
Change-Id: I7a0f1443de7eeebb5d8ad59e4759ca2e036a3c4d |
259,881 | 13.02.2019 11:58:49 | 28,800 | 2c7488454e7fcbf98c00bcdceb70cb8e2fa98c96 | Expose XSAVES in /proc/cpuinfo
Linux started doing this in
("x86/fpu/xstate: Re-enable XSAVES"), which first appeared in 4.8. | [
{
"change_type": "MODIFY",
"old_path": "pkg/cpuid/cpuid.go",
"new_path": "pkg/cpuid/cpuid.go",
"diff": "@@ -361,6 +361,7 @@ var x86FeatureStrings = map[Feature]string{\nX86FeatureXSAVEOPT: \"xsaveopt\",\nX86FeatureXSAVEC: \"xsavec\",\nX86FeatureXGETBV1: \"xgetbv1\",\n+ X86FeatureXSAVES: \"xsaves\",\n// Block 5.\nX86FeatureLAHF64: \"lahf_lm\", // LAHF/SAHF in long mode\n@@ -415,9 +416,6 @@ var x86FeatureParseOnlyStrings = map[Feature]string{\n// Block 3.\nX86FeaturePREFETCHWT1: \"prefetchwt1\",\n-\n- // Block 4.\n- X86FeatureXSAVES: \"xsaves\",\n}\n// Just a way to wrap cpuid function numbers.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/cpuid/cpuid_parse_test.go",
"new_path": "pkg/cpuid/cpuid_parse_test.go",
"diff": "@@ -114,6 +114,11 @@ func TestHostFeatureFlags(t *testing.T) {\n// PKU only exposed in dfb4a70f20c5b3880da56ee4c9484bdb4e8f1e65\n// (4.9).\ncontinue\n+ // Block 4.\n+ case f == X86FeatureXSAVES && (major < 4 || major == 4 && minor < 8):\n+ // XSAVES only exposed in\n+ // b8be15d588060a03569ac85dc4a0247460988f5b (4.8).\n+ continue\n}\nhidden := f.flagString(true) == \"\"\n"
}
] | Go | Apache License 2.0 | google/gvisor | Expose XSAVES in /proc/cpuinfo
Linux started doing this in b8be15d588060a03569ac85dc4a0247460988f5b
("x86/fpu/xstate: Re-enable XSAVES"), which first appeared in 4.8.
PiperOrigin-RevId: 233800931
Change-Id: Icac2c2b03ccf1a91f3070431efb5152ca619fca3 |
259,885 | 13.02.2019 14:24:23 | 28,800 | 0e84ae72e086c77cea066000a898b7bc951ba790 | Improve safecopy sanity checks.
Fix CopyIn/CopyOut/ZeroOut range checks.
Include the faulting signal number in the panic message. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/safecopy/safecopy_unsafe.go",
"new_path": "pkg/sentry/platform/safecopy/safecopy_unsafe.go",
"diff": "@@ -92,14 +92,14 @@ func CopyIn(dst []byte, src unsafe.Pointer) (int, error) {\nreturn len(dst), nil\n}\n- if faultN, srcN := uintptr(fault), uintptr(src); faultN < srcN && faultN >= srcN+toCopy {\n- panic(fmt.Sprintf(\"CopyIn faulted at %#x, which is outside source [%#x, %#x)\", faultN, srcN, srcN+toCopy))\n+ faultN, srcN := uintptr(fault), uintptr(src)\n+ if faultN < srcN || faultN >= srcN+toCopy {\n+ panic(fmt.Sprintf(\"CopyIn raised signal %d at %#x, which is outside source [%#x, %#x)\", sig, faultN, srcN, srcN+toCopy))\n}\n// memcpy might have ended the copy up to maxRegisterSize bytes before\n// fault, if an instruction caused a memory access that straddled two\n// pages, and the second one faulted. Try to copy up to the fault.\n- faultN, srcN := uintptr(fault), uintptr(src)\nvar done int\nif faultN-srcN > maxRegisterSize {\ndone = int(faultN - srcN - maxRegisterSize)\n@@ -126,14 +126,14 @@ func CopyOut(dst unsafe.Pointer, src []byte) (int, error) {\nreturn len(src), nil\n}\n- if faultN, dstN := uintptr(fault), uintptr(dst); faultN < dstN && faultN >= dstN+toCopy {\n- panic(fmt.Sprintf(\"CopyOut faulted at %#x, which is outside destination [%#x, %#x)\", faultN, dstN, dstN+toCopy))\n+ faultN, dstN := uintptr(fault), uintptr(dst)\n+ if faultN < dstN || faultN >= dstN+toCopy {\n+ panic(fmt.Sprintf(\"CopyOut raised signal %d at %#x, which is outside destination [%#x, %#x)\", sig, faultN, dstN, dstN+toCopy))\n}\n// memcpy might have ended the copy up to maxRegisterSize bytes before\n// fault, if an instruction caused a memory access that straddled two\n// pages, and the second one faulted. Try to copy up to the fault.\n- faultN, dstN := uintptr(fault), uintptr(dst)\nvar done int\nif faultN-dstN > maxRegisterSize {\ndone = int(faultN - dstN - maxRegisterSize)\n@@ -173,7 +173,7 @@ func Copy(dst, src unsafe.Pointer, toCopy uintptr) (uintptr, error) {\nfaultAfterDst = faultN - dstN\n}\nif faultAfterSrc >= toCopy && faultAfterDst >= toCopy {\n- panic(fmt.Sprintf(\"Copy faulted at %#x, which is outside source [%#x, %#x) and destination [%#x, %#x)\", faultN, srcN, srcN+toCopy, dstN, dstN+toCopy))\n+ panic(fmt.Sprintf(\"Copy raised signal %d at %#x, which is outside source [%#x, %#x) and destination [%#x, %#x)\", sig, faultN, srcN, srcN+toCopy, dstN, dstN+toCopy))\n}\nfaultedAfter := faultAfterSrc\nif faultedAfter > faultAfterDst {\n@@ -207,14 +207,14 @@ func ZeroOut(dst unsafe.Pointer, toZero uintptr) (uintptr, error) {\nreturn toZero, nil\n}\n- if faultN, dstN := uintptr(fault), uintptr(dst); faultN < dstN && faultN >= dstN+toZero {\n- panic(fmt.Sprintf(\"ZeroOut faulted at %#x, which is outside destination [%#x, %#x)\", faultN, dstN, dstN+toZero))\n+ faultN, dstN := uintptr(fault), uintptr(dst)\n+ if faultN < dstN || faultN >= dstN+toZero {\n+ panic(fmt.Sprintf(\"ZeroOut raised signal %d at %#x, which is outside destination [%#x, %#x)\", sig, faultN, dstN, dstN+toZero))\n}\n// memclr might have ended the write up to maxRegisterSize bytes before\n// fault, if an instruction caused a memory access that straddled two\n// pages, and the second one faulted. Try to write up to the fault.\n- faultN, dstN := uintptr(fault), uintptr(dst)\nvar done uintptr\nif faultN-dstN > maxRegisterSize {\ndone = faultN - dstN - maxRegisterSize\n"
}
] | Go | Apache License 2.0 | google/gvisor | Improve safecopy sanity checks.
- Fix CopyIn/CopyOut/ZeroOut range checks.
- Include the faulting signal number in the panic message.
PiperOrigin-RevId: 233829501
Change-Id: I8959ead12d05dbd4cd63c2b908cddeb2a27eb513 |
259,853 | 13.02.2019 19:37:44 | 28,800 | cbd6b35c56011d6e2d75a68385bdc984fdf35317 | gvisor/kokoro: run apt-get update before apt-get install
We need to update the package lists, otherwise apt-get
install can request an old package which has been
removed from repositories. | [
{
"change_type": "MODIFY",
"old_path": "kokoro/run_tests.sh",
"new_path": "kokoro/run_tests.sh",
"diff": "@@ -99,7 +99,8 @@ install_runtime() {\ninstall_crictl_test_deps() {\n# Install containerd.\n# libseccomp2 needs to be downgraded in order to install libseccomp-dev.\n- sudo -n -E apt-get install -y --force-yes libseccomp2=2.1.1-1ubuntu1~trusty4\n+ sudo -n -E apt-get update\n+ sudo -n -E apt-get install -y --force-yes libseccomp2=2.1.1-1ubuntu1~trusty5\nsudo -n -E apt-get install -y btrfs-tools libseccomp-dev\n# go get will exit with a status of 1 despite succeeding, so ignore errors.\ngo get -d github.com/containerd/containerd || true\n"
}
] | Go | Apache License 2.0 | google/gvisor | gvisor/kokoro: run apt-get update before apt-get install
We need to update the package lists, otherwise apt-get
install can request an old package which has been
removed from repositories.
PiperOrigin-RevId: 233879031
Change-Id: I2e1b3afd9d01008f774f10efd8852fd3f5e1c882 |
259,992 | 15.02.2019 08:22:26 | 28,800 | e34d27e8b6709809582eb0ad43c7232f2d5ab8ad | Redirect FIXME to more appropriate bug | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/epsocket/epsocket.go",
"new_path": "pkg/sentry/socket/epsocket/epsocket.go",
"diff": "@@ -1139,11 +1139,14 @@ func setSockOptIP(t *kernel.Task, ep commonEndpoint, name int, optVal []byte) *s\nMulticastAddr: tcpip.Address(req.MulticastAddr[:]),\n}))\n- case linux.MCAST_JOIN_GROUP, linux.IP_MULTICAST_IF:\n+ case linux.IP_MULTICAST_IF:\n// FIXME: Disallow IP-level multicast group options by\n// default. These will need to be supported by appropriately plumbing\n// the level through to the network stack (if at all). However, we\n// still allow setting TTL, and multicast-enable/disable type options.\n+ fallthrough\n+ case linux.MCAST_JOIN_GROUP:\n+ // FIXME: Implement MCAST_JOIN_GROUP.\nt.Kernel().EmitUnimplementedEvent(t)\nreturn syserr.ErrInvalidArgument\n"
}
] | Go | Apache License 2.0 | google/gvisor | Redirect FIXME to more appropriate bug
PiperOrigin-RevId: 234147487
Change-Id: I779a6012832bb94a6b89f5bcc7d821b40ae969cc |
259,891 | 15.02.2019 11:17:51 | 28,800 | a9cb3dcd9df373fb7a531476bf1da69fc9189e3a | Move SO_TIMESTAMP from different transport endpoints to epsocket.
SO_TIMESTAMP is reimplemented in ping and UDP sockets (and needs to be added for
TCP), but can just be implemented in epsocket for simplicity. This will also
make SIOCGSTAMP easier to implement. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/epsocket/epsocket.go",
"new_path": "pkg/sentry/socket/epsocket/epsocket.go",
"diff": "@@ -150,11 +150,24 @@ type SocketOperations struct {\nEndpoint tcpip.Endpoint\nskType transport.SockType\n- // readMu protects access to readView, control, and sender.\n+ // readMu protects access to the below fields.\nreadMu sync.Mutex `state:\"nosave\"`\n+ // readView contains the remaining payload from the last packet.\nreadView buffer.View\n+ // readCM holds control message information for the last packet read\n+ // from Endpoint.\nreadCM tcpip.ControlMessages\nsender tcpip.FullAddress\n+ // sockOptTimestamp corresponds to SO_TIMESTAMP. When true, timestamps\n+ // of returned messages can be returned via control messages. When\n+ // false, the same timestamp is instead stored and can be read via the\n+ // SIOCGSTAMP ioctl. See socket(7).\n+ sockOptTimestamp bool\n+ // timestampValid indicates whether timestamp has been set.\n+ timestampValid bool\n+ // timestampNS holds the timestamp to use with SIOCGSTAMP. It is only\n+ // valid when timestampValid is true.\n+ timestampNS int64\n}\n// New creates a new endpoint socket.\n@@ -515,6 +528,24 @@ func (s *SocketOperations) Shutdown(t *kernel.Task, how int) *syserr.Error {\n// GetSockOpt implements the linux syscall getsockopt(2) for sockets backed by\n// tcpip.Endpoint.\nfunc (s *SocketOperations) GetSockOpt(t *kernel.Task, level, name, outLen int) (interface{}, *syserr.Error) {\n+ // TODO: Unlike other socket options, SO_TIMESTAMP is\n+ // implemented specifically for epsocket.SocketOperations rather than\n+ // commonEndpoint. commonEndpoint should be extended to support socket\n+ // options where the implementation is not shared, as unix sockets need\n+ // their own support for SO_TIMESTAMP.\n+ if level == linux.SOL_SOCKET && name == linux.SO_TIMESTAMP {\n+ if outLen < sizeOfInt32 {\n+ return nil, syserr.ErrInvalidArgument\n+ }\n+ val := int32(0)\n+ s.readMu.Lock()\n+ defer s.readMu.Unlock()\n+ if s.sockOptTimestamp {\n+ val = 1\n+ }\n+ return val, nil\n+ }\n+\nreturn GetSockOpt(t, s, s.Endpoint, s.family, s.skType, level, name, outLen)\n}\n@@ -680,18 +711,6 @@ func getSockOptSocket(t *kernel.Task, s socket.Socket, ep commonEndpoint, family\nreturn linux.NsecToTimeval(s.RecvTimeout()), nil\n- case linux.SO_TIMESTAMP:\n- if outLen < sizeOfInt32 {\n- return nil, syserr.ErrInvalidArgument\n- }\n-\n- var v tcpip.TimestampOption\n- if err := ep.GetSockOpt(&v); err != nil {\n- return nil, syserr.TranslateNetstackError(err)\n- }\n-\n- return int32(v), nil\n-\ncase linux.SO_OOBINLINE:\nif outLen < sizeOfInt32 {\nreturn nil, syserr.ErrInvalidArgument\n@@ -854,6 +873,21 @@ func getSockOptIP(t *kernel.Task, ep commonEndpoint, name, outLen int) (interfac\n// SetSockOpt implements the linux syscall setsockopt(2) for sockets backed by\n// tcpip.Endpoint.\nfunc (s *SocketOperations) SetSockOpt(t *kernel.Task, level int, name int, optVal []byte) *syserr.Error {\n+ // TODO: Unlike other socket options, SO_TIMESTAMP is\n+ // implemented specifically for epsocket.SocketOperations rather than\n+ // commonEndpoint. commonEndpoint should be extended to support socket\n+ // options where the implementation is not shared, as unix sockets need\n+ // their own support for SO_TIMESTAMP.\n+ if level == linux.SOL_SOCKET && name == linux.SO_TIMESTAMP {\n+ if len(optVal) < sizeOfInt32 {\n+ return syserr.ErrInvalidArgument\n+ }\n+ s.readMu.Lock()\n+ defer s.readMu.Unlock()\n+ s.sockOptTimestamp = usermem.ByteOrder.Uint32(optVal) != 0\n+ return nil\n+ }\n+\nreturn SetSockOpt(t, s, s.Endpoint, level, name, optVal)\n}\n@@ -962,14 +996,6 @@ func setSockOptSocket(t *kernel.Task, s socket.Socket, ep commonEndpoint, name i\ns.SetRecvTimeout(v.ToNsecCapped())\nreturn nil\n- case linux.SO_TIMESTAMP:\n- if len(optVal) < sizeOfInt32 {\n- return syserr.ErrInvalidArgument\n- }\n-\n- v := usermem.ByteOrder.Uint32(optVal)\n- return syserr.TranslateNetstackError(ep.SetSockOpt(tcpip.TimestampOption(v)))\n-\ndefault:\nsocket.SetSockOptEmitUnimplementedEvent(t, name)\n}\n@@ -1436,6 +1462,11 @@ func (s *SocketOperations) coalescingRead(ctx context.Context, dst usermem.IOSeq\n}\n} else {\nn, e = dst.CopyOut(ctx, s.readView)\n+ // Set the control message, even if 0 bytes were read.\n+ if e == nil && s.readCM.HasTimestamp && s.sockOptTimestamp {\n+ s.timestampNS = s.readCM.Timestamp\n+ s.timestampValid = true\n+ }\n}\ncopied += n\ns.readView.TrimFront(n)\n@@ -1499,6 +1530,11 @@ func (s *SocketOperations) nonBlockingRead(ctx context.Context, dst usermem.IOSe\n}\nn, err := dst.CopyOut(ctx, s.readView)\n+ // Set the control message, even if 0 bytes were read.\n+ if err == nil && s.readCM.HasTimestamp && s.sockOptTimestamp {\n+ s.timestampNS = s.readCM.Timestamp\n+ s.timestampValid = true\n+ }\nvar addr interface{}\nvar addrLen uint32\nif isPacket && senderRequested {\n@@ -1508,11 +1544,11 @@ func (s *SocketOperations) nonBlockingRead(ctx context.Context, dst usermem.IOSe\nif peek {\nif l := len(s.readView); trunc && l > n {\n// isPacket must be true.\n- return l, addr, addrLen, socket.ControlMessages{IP: s.readCM}, syserr.FromError(err)\n+ return l, addr, addrLen, socket.ControlMessages{IP: tcpip.ControlMessages{HasTimestamp: s.timestampValid, Timestamp: s.timestampNS}}, syserr.FromError(err)\n}\nif isPacket || err != nil {\n- return int(n), addr, addrLen, socket.ControlMessages{IP: s.readCM}, syserr.FromError(err)\n+ return int(n), addr, addrLen, socket.ControlMessages{IP: tcpip.ControlMessages{HasTimestamp: s.timestampValid, Timestamp: s.timestampNS}}, syserr.FromError(err)\n}\n// We need to peek beyond the first message.\n@@ -1530,7 +1566,7 @@ func (s *SocketOperations) nonBlockingRead(ctx context.Context, dst usermem.IOSe\n// We got some data, so no need to return an error.\nerr = nil\n}\n- return int(n), nil, 0, socket.ControlMessages{IP: s.readCM}, syserr.FromError(err)\n+ return int(n), nil, 0, socket.ControlMessages{IP: tcpip.ControlMessages{HasTimestamp: s.timestampValid, Timestamp: s.timestampNS}}, syserr.FromError(err)\n}\nvar msgLen int\n@@ -1543,10 +1579,10 @@ func (s *SocketOperations) nonBlockingRead(ctx context.Context, dst usermem.IOSe\n}\nif trunc {\n- return msgLen, addr, addrLen, socket.ControlMessages{IP: s.readCM}, syserr.FromError(err)\n+ return msgLen, addr, addrLen, socket.ControlMessages{IP: tcpip.ControlMessages{HasTimestamp: s.timestampValid, Timestamp: s.timestampNS}}, syserr.FromError(err)\n}\n- return int(n), addr, addrLen, socket.ControlMessages{IP: s.readCM}, syserr.FromError(err)\n+ return int(n), addr, addrLen, socket.ControlMessages{IP: tcpip.ControlMessages{HasTimestamp: s.timestampValid, Timestamp: s.timestampNS}}, syserr.FromError(err)\n}\n// RecvMsg implements the linux syscall recvmsg(2) for sockets backed by\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/tcpip.go",
"new_path": "pkg/tcpip/tcpip.go",
"diff": "@@ -298,9 +298,6 @@ type Endpoint interface {\n//\n// This method does not block if there is no data pending. It will also\n// either return an error or data, never both.\n- //\n- // A timestamp (in ns) is optionally returned. A zero value indicates\n- // that no timestamp was available.\nRead(*FullAddress) (buffer.View, ControlMessages, *Error)\n// Write writes data to the endpoint's peer. This method does not block if\n@@ -326,9 +323,6 @@ type Endpoint interface {\n// Peek reads data without consuming it from the endpoint.\n//\n// This method does not block if there is no data pending.\n- //\n- // A timestamp (in ns) is optionally returned. A zero value indicates\n- // that no timestamp was available.\nPeek([][]byte) (uintptr, ControlMessages, *Error)\n// Connect connects the endpoint to its peer. Specifying a NIC is\n@@ -449,10 +443,6 @@ type QuickAckOption int\n// Only supported on Unix sockets.\ntype PasscredOption int\n-// TimestampOption is used by SetSockOpt/GetSockOpt to specify whether\n-// SO_TIMESTAMP socket control messages are enabled.\n-type TimestampOption int\n-\n// TCPInfoOption is used by GetSockOpt to expose TCP statistics.\n//\n// TODO: Add and populate stat fields.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/ping/endpoint.go",
"new_path": "pkg/tcpip/transport/ping/endpoint.go",
"diff": "@@ -32,7 +32,6 @@ type pingPacket struct {\nsenderAddress tcpip.FullAddress\ndata buffer.VectorisedView `state:\".(buffer.VectorisedView)\"`\ntimestamp int64\n- hasTimestamp bool\n// views is used as buffer for data when its length is large\n// enough to store a VectorisedView.\nviews [8]buffer.View `state:\"nosave\"`\n@@ -67,7 +66,6 @@ type endpoint struct {\nrcvBufSizeMax int `state:\".(int)\"`\nrcvBufSize int\nrcvClosed bool\n- rcvTimestamp bool\n// The following fields are protected by the mu mutex.\nmu sync.RWMutex `state:\"nosave\"`\n@@ -140,7 +138,6 @@ func (e *endpoint) Read(addr *tcpip.FullAddress) (buffer.View, tcpip.ControlMess\np := e.rcvList.Front()\ne.rcvList.Remove(p)\ne.rcvBufSize -= p.data.Size()\n- ts := e.rcvTimestamp\ne.rcvMu.Unlock()\n@@ -148,12 +145,7 @@ func (e *endpoint) Read(addr *tcpip.FullAddress) (buffer.View, tcpip.ControlMess\n*addr = p.senderAddress\n}\n- if ts && !p.hasTimestamp {\n- // Linux uses the current time.\n- p.timestamp = e.stack.NowNanoseconds()\n- }\n-\n- return p.data.ToView(), tcpip.ControlMessages{HasTimestamp: ts, Timestamp: p.timestamp}, nil\n+ return p.data.ToView(), tcpip.ControlMessages{HasTimestamp: true, Timestamp: p.timestamp}, nil\n}\n// prepareForWrite prepares the endpoint for sending data. In particular, it\n@@ -313,12 +305,6 @@ func (e *endpoint) Peek([][]byte) (uintptr, tcpip.ControlMessages, *tcpip.Error)\n// SetSockOpt sets a socket option. Currently not supported.\nfunc (e *endpoint) SetSockOpt(opt interface{}) *tcpip.Error {\n- switch v := opt.(type) {\n- case tcpip.TimestampOption:\n- e.rcvMu.Lock()\n- e.rcvTimestamp = v != 0\n- e.rcvMu.Unlock()\n- }\nreturn nil\n}\n@@ -351,15 +337,6 @@ func (e *endpoint) GetSockOpt(opt interface{}) *tcpip.Error {\ne.rcvMu.Unlock()\nreturn nil\n- case *tcpip.TimestampOption:\n- e.rcvMu.Lock()\n- *o = 0\n- if e.rcvTimestamp {\n- *o = 1\n- }\n- e.rcvMu.Unlock()\n- return nil\n-\ncase *tcpip.KeepaliveEnabledOption:\n*o = 0\nreturn nil\n@@ -702,10 +679,7 @@ func (e *endpoint) HandlePacket(r *stack.Route, id stack.TransportEndpointID, vv\ne.rcvList.PushBack(pkt)\ne.rcvBufSize += vv.Size()\n- if e.rcvTimestamp {\npkt.timestamp = e.stack.NowNanoseconds()\n- pkt.hasTimestamp = true\n- }\ne.rcvMu.Unlock()\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/udp/endpoint.go",
"new_path": "pkg/tcpip/transport/udp/endpoint.go",
"diff": "@@ -32,7 +32,6 @@ type udpPacket struct {\nsenderAddress tcpip.FullAddress\ndata buffer.VectorisedView `state:\".(buffer.VectorisedView)\"`\ntimestamp int64\n- hasTimestamp bool\n// views is used as buffer for data when its length is large\n// enough to store a VectorisedView.\nviews [8]buffer.View `state:\"nosave\"`\n@@ -68,7 +67,6 @@ type endpoint struct {\nrcvBufSizeMax int `state:\".(int)\"`\nrcvBufSize int\nrcvClosed bool\n- rcvTimestamp bool\n// The following fields are protected by the mu mutex.\nmu sync.RWMutex `state:\"nosave\"`\n@@ -203,7 +201,6 @@ func (e *endpoint) Read(addr *tcpip.FullAddress) (buffer.View, tcpip.ControlMess\np := e.rcvList.Front()\ne.rcvList.Remove(p)\ne.rcvBufSize -= p.data.Size()\n- ts := e.rcvTimestamp\ne.rcvMu.Unlock()\n@@ -211,12 +208,7 @@ func (e *endpoint) Read(addr *tcpip.FullAddress) (buffer.View, tcpip.ControlMess\n*addr = p.senderAddress\n}\n- if ts && !p.hasTimestamp {\n- // Linux uses the current time.\n- p.timestamp = e.stack.NowNanoseconds()\n- }\n-\n- return p.data.ToView(), tcpip.ControlMessages{HasTimestamp: ts, Timestamp: p.timestamp}, nil\n+ return p.data.ToView(), tcpip.ControlMessages{HasTimestamp: true, Timestamp: p.timestamp}, nil\n}\n// prepareForWrite prepares the endpoint for sending data. In particular, it\n@@ -397,11 +389,6 @@ func (e *endpoint) SetSockOpt(opt interface{}) *tcpip.Error {\ne.v6only = v != 0\n- case tcpip.TimestampOption:\n- e.rcvMu.Lock()\n- e.rcvTimestamp = v != 0\n- e.rcvMu.Unlock()\n-\ncase tcpip.MulticastTTLOption:\ne.mu.Lock()\ne.multicastTTL = uint8(v)\n@@ -508,15 +495,6 @@ func (e *endpoint) GetSockOpt(opt interface{}) *tcpip.Error {\ne.rcvMu.Unlock()\nreturn nil\n- case *tcpip.TimestampOption:\n- e.rcvMu.Lock()\n- *o = 0\n- if e.rcvTimestamp {\n- *o = 1\n- }\n- e.rcvMu.Unlock()\n- return nil\n-\ncase *tcpip.MulticastTTLOption:\ne.mu.Lock()\n*o = tcpip.MulticastTTLOption(e.multicastTTL)\n@@ -909,10 +887,7 @@ func (e *endpoint) HandlePacket(r *stack.Route, id stack.TransportEndpointID, vv\ne.rcvList.PushBack(pkt)\ne.rcvBufSize += vv.Size()\n- if e.rcvTimestamp {\npkt.timestamp = e.stack.NowNanoseconds()\n- pkt.hasTimestamp = true\n- }\ne.rcvMu.Unlock()\n"
}
] | Go | Apache License 2.0 | google/gvisor | Move SO_TIMESTAMP from different transport endpoints to epsocket.
SO_TIMESTAMP is reimplemented in ping and UDP sockets (and needs to be added for
TCP), but can just be implemented in epsocket for simplicity. This will also
make SIOCGSTAMP easier to implement.
PiperOrigin-RevId: 234179300
Change-Id: Ib5ea0b1261dc218c1a8b15a65775de0050fe3230 |
259,854 | 15.02.2019 18:39:10 | 28,800 | c611dbc5a7399922588e3fd99b22bda19f684afe | Implement IP_MULTICAST_IF.
This allows setting a default send interface for IPv4 multicast. IPv6 support
will come later. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/epsocket/epsocket.go",
"new_path": "pkg/sentry/socket/epsocket/epsocket.go",
"diff": "@@ -27,7 +27,6 @@ package epsocket\nimport (\n\"bytes\"\n\"math\"\n- \"strings\"\n\"sync\"\n\"syscall\"\n\"time\"\n@@ -191,6 +190,15 @@ func New(t *kernel.Task, family int, skType transport.SockType, queue *waiter.Qu\nvar sockAddrInetSize = int(binary.Size(linux.SockAddrInet{}))\nvar sockAddrInet6Size = int(binary.Size(linux.SockAddrInet6{}))\n+// bytesToIPAddress converts an IPv4 or IPv6 address from the user to the\n+// netstack representation taking any addresses into account.\n+func bytesToIPAddress(addr []byte) tcpip.Address {\n+ if bytes.Equal(addr, make([]byte, 4)) || bytes.Equal(addr, make([]byte, 16)) {\n+ return \"\"\n+ }\n+ return tcpip.Address(addr)\n+}\n+\n// GetAddress reads an sockaddr struct from the given address and converts it\n// to the FullAddress format. It supports AF_UNIX, AF_INET and AF_INET6\n// addresses.\n@@ -231,12 +239,9 @@ func GetAddress(sfamily int, addr []byte) (tcpip.FullAddress, *syserr.Error) {\nbinary.Unmarshal(addr[:sockAddrInetSize], usermem.ByteOrder, &a)\nout := tcpip.FullAddress{\n- Addr: tcpip.Address(a.Addr[:]),\n+ Addr: bytesToIPAddress(a.Addr[:]),\nPort: ntohs(a.Port),\n}\n- if out.Addr == \"\\x00\\x00\\x00\\x00\" {\n- out.Addr = \"\"\n- }\nreturn out, nil\ncase linux.AF_INET6:\n@@ -247,15 +252,12 @@ func GetAddress(sfamily int, addr []byte) (tcpip.FullAddress, *syserr.Error) {\nbinary.Unmarshal(addr[:sockAddrInet6Size], usermem.ByteOrder, &a)\nout := tcpip.FullAddress{\n- Addr: tcpip.Address(a.Addr[:]),\n+ Addr: bytesToIPAddress(a.Addr[:]),\nPort: ntohs(a.Port),\n}\nif isLinkLocal(out.Addr) {\nout.NIC = tcpip.NICID(a.Scope_id)\n}\n- if out.Addr == tcpip.Address(strings.Repeat(\"\\x00\", 16)) {\n- out.Addr = \"\"\n- }\nreturn out, nil\ndefault:\n@@ -864,6 +866,30 @@ func getSockOptIP(t *kernel.Task, ep commonEndpoint, name, outLen int) (interfac\nreturn int32(v), nil\n+ case linux.IP_MULTICAST_IF:\n+ if outLen < inetMulticastRequestSize {\n+ return nil, syserr.ErrInvalidArgument\n+ }\n+\n+ var v tcpip.MulticastInterfaceOption\n+ if err := ep.GetSockOpt(&v); err != nil {\n+ return nil, syserr.TranslateNetstackError(err)\n+ }\n+\n+ a, _ := ConvertAddress(linux.AF_INET, tcpip.FullAddress{Addr: v.InterfaceAddr})\n+\n+ rv := linux.InetMulticastRequestWithNIC{\n+ linux.InetMulticastRequest{\n+ InterfaceAddr: a.(linux.SockAddrInet).Addr,\n+ },\n+ int32(v.NIC),\n+ }\n+\n+ if outLen >= inetMulticastRequestWithNICSize {\n+ return rv, nil\n+ }\n+ return rv.InetMulticastRequest, nil\n+\ndefault:\nemitUnimplementedEventIP(t, name)\n}\n@@ -1149,6 +1175,8 @@ func setSockOptIP(t *kernel.Task, ep commonEndpoint, name int, optVal []byte) *s\nreturn syserr.TranslateNetstackError(ep.SetSockOpt(tcpip.AddMembershipOption{\nNIC: tcpip.NICID(req.InterfaceIndex),\n+ // TODO: Change AddMembership to use the standard\n+ // any address representation.\nInterfaceAddr: tcpip.Address(req.InterfaceAddr[:]),\nMulticastAddr: tcpip.Address(req.MulticastAddr[:]),\n}))\n@@ -1161,18 +1189,28 @@ func setSockOptIP(t *kernel.Task, ep commonEndpoint, name int, optVal []byte) *s\nreturn syserr.TranslateNetstackError(ep.SetSockOpt(tcpip.RemoveMembershipOption{\nNIC: tcpip.NICID(req.InterfaceIndex),\n+ // TODO: Change DropMembership to use the standard\n+ // any address representation.\nInterfaceAddr: tcpip.Address(req.InterfaceAddr[:]),\nMulticastAddr: tcpip.Address(req.MulticastAddr[:]),\n}))\ncase linux.IP_MULTICAST_IF:\n+ req, err := copyInMulticastRequest(optVal)\n+ if err != nil {\n+ return err\n+ }\n+\n+ return syserr.TranslateNetstackError(ep.SetSockOpt(tcpip.MulticastInterfaceOption{\n+ NIC: tcpip.NICID(req.InterfaceIndex),\n+ InterfaceAddr: bytesToIPAddress(req.InterfaceAddr[:]),\n+ }))\n+\n+ case linux.MCAST_JOIN_GROUP:\n// FIXME: Disallow IP-level multicast group options by\n// default. These will need to be supported by appropriately plumbing\n// the level through to the network stack (if at all). However, we\n// still allow setting TTL, and multicast-enable/disable type options.\n- fallthrough\n- case linux.MCAST_JOIN_GROUP:\n- // FIXME: Implement MCAST_JOIN_GROUP.\nt.Kernel().EmitUnimplementedEvent(t)\nreturn syserr.ErrInvalidArgument\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/stack.go",
"new_path": "pkg/tcpip/stack/stack.go",
"diff": "@@ -565,6 +565,17 @@ func (s *Stack) EnableNIC(id tcpip.NICID) *tcpip.Error {\nreturn nil\n}\n+// CheckNIC checks if a NIC is usable.\n+func (s *Stack) CheckNIC(id tcpip.NICID) bool {\n+ s.mu.RLock()\n+ nic, ok := s.nics[id]\n+ s.mu.RUnlock()\n+ if ok {\n+ return nic.linkEP.IsAttached()\n+ }\n+ return false\n+}\n+\n// NICSubnets returns a map of NICIDs to their associated subnets.\nfunc (s *Stack) NICSubnets() map[tcpip.NICID][]tcpip.Subnet {\ns.mu.RLock()\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/tcpip.go",
"new_path": "pkg/tcpip/tcpip.go",
"diff": "@@ -473,6 +473,13 @@ type KeepaliveCountOption int\n// TTL value for multicast messages. The default is 1.\ntype MulticastTTLOption uint8\n+// MulticastInterfaceOption is used by SetSockOpt/GetSockOpt to specify a\n+// default interface for multicast.\n+type MulticastInterfaceOption struct {\n+ NIC NICID\n+ InterfaceAddr Address\n+}\n+\n// MembershipOption is used by SetSockOpt/GetSockOpt as an argument to\n// AddMembershipOption and RemoveMembershipOption.\ntype MembershipOption struct {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/udp/endpoint.go",
"new_path": "pkg/tcpip/transport/udp/endpoint.go",
"diff": "@@ -79,6 +79,8 @@ type endpoint struct {\ndstPort uint16\nv6only bool\nmulticastTTL uint8\n+ multicastAddr tcpip.Address\n+ multicastNICID tcpip.NICID\nreusePort bool\n// shutdownFlags represent the current shutdown state of the endpoint.\n@@ -251,6 +253,33 @@ func (e *endpoint) prepareForWrite(to *tcpip.FullAddress) (retry bool, err *tcpi\nreturn true, nil\n}\n+// connectRoute establishes a route to the specified interface or the\n+// configured multicast interface if no interface is specified and the\n+// specified address is a multicast address.\n+func (e *endpoint) connectRoute(nicid tcpip.NICID, addr tcpip.FullAddress) (stack.Route, tcpip.NICID, tcpip.NetworkProtocolNumber, *tcpip.Error) {\n+ netProto, err := e.checkV4Mapped(&addr, false)\n+ if err != nil {\n+ return stack.Route{}, 0, 0, err\n+ }\n+\n+ localAddr := e.id.LocalAddress\n+ if header.IsV4MulticastAddress(addr.Addr) || header.IsV6MulticastAddress(addr.Addr) {\n+ if nicid == 0 {\n+ nicid = e.multicastNICID\n+ }\n+ if localAddr == \"\" {\n+ localAddr = e.multicastAddr\n+ }\n+ }\n+\n+ // Find a route to the desired destination.\n+ r, err := e.stack.FindRoute(nicid, localAddr, addr.Addr, netProto)\n+ if err != nil {\n+ return stack.Route{}, 0, 0, err\n+ }\n+ return r, nicid, netProto, nil\n+}\n+\n// Write writes data to the endpoint's peer. This method does not block\n// if the data cannot be written.\nfunc (e *endpoint) Write(p tcpip.Payload, opts tcpip.WriteOptions) (uintptr, <-chan struct{}, *tcpip.Error) {\n@@ -318,15 +347,7 @@ func (e *endpoint) Write(p tcpip.Payload, opts tcpip.WriteOptions) (uintptr, <-c\nnicid = e.bindNICID\n}\n- toCopy := *to\n- to = &toCopy\n- netProto, err := e.checkV4Mapped(to, false)\n- if err != nil {\n- return 0, nil, err\n- }\n-\n- // Find the enpoint.\n- r, err := e.stack.FindRoute(nicid, e.id.LocalAddress, to.Addr, netProto)\n+ r, _, _, err := e.connectRoute(nicid, *to)\nif err != nil {\nreturn 0, nil, err\n}\n@@ -394,6 +415,42 @@ func (e *endpoint) SetSockOpt(opt interface{}) *tcpip.Error {\ne.multicastTTL = uint8(v)\ne.mu.Unlock()\n+ case tcpip.MulticastInterfaceOption:\n+ e.mu.Lock()\n+ defer e.mu.Unlock()\n+\n+ fa := tcpip.FullAddress{Addr: v.InterfaceAddr}\n+ netProto, err := e.checkV4Mapped(&fa, false)\n+ if err != nil {\n+ return err\n+ }\n+ nic := v.NIC\n+ addr := fa.Addr\n+\n+ if nic == 0 && addr == \"\" {\n+ e.multicastAddr = \"\"\n+ e.multicastNICID = 0\n+ break\n+ }\n+\n+ if nic != 0 {\n+ if !e.stack.CheckNIC(nic) {\n+ return tcpip.ErrBadLocalAddress\n+ }\n+ } else {\n+ nic = e.stack.CheckLocalAddress(0, netProto, addr)\n+ if nic == 0 {\n+ return tcpip.ErrBadLocalAddress\n+ }\n+ }\n+\n+ if e.bindNICID != 0 && e.bindNICID != nic {\n+ return tcpip.ErrInvalidEndpointState\n+ }\n+\n+ e.multicastNICID = nic\n+ e.multicastAddr = addr\n+\ncase tcpip.AddMembershipOption:\nnicID := v.NIC\nif v.InterfaceAddr != header.IPv4Any {\n@@ -445,7 +502,6 @@ func (e *endpoint) SetSockOpt(opt interface{}) *tcpip.Error {\ne.mu.Lock()\ne.reusePort = v != 0\ne.mu.Unlock()\n- return nil\n}\nreturn nil\n}\n@@ -501,6 +557,15 @@ func (e *endpoint) GetSockOpt(opt interface{}) *tcpip.Error {\ne.mu.Unlock()\nreturn nil\n+ case *tcpip.MulticastInterfaceOption:\n+ e.mu.Lock()\n+ *o = tcpip.MulticastInterfaceOption{\n+ e.multicastNICID,\n+ e.multicastAddr,\n+ }\n+ e.mu.Unlock()\n+ return nil\n+\ncase *tcpip.ReusePortOption:\ne.mu.RLock()\nv := e.reusePort\n@@ -610,13 +675,7 @@ func (e *endpoint) Connect(addr tcpip.FullAddress) *tcpip.Error {\nreturn tcpip.ErrInvalidEndpointState\n}\n- netProto, err := e.checkV4Mapped(&addr, false)\n- if err != nil {\n- return err\n- }\n-\n- // Find a route to the desired destination.\n- r, err := e.stack.FindRoute(nicid, e.id.LocalAddress, addr.Addr, netProto)\n+ r, nicid, netProto, err := e.connectRoute(nicid, addr)\nif err != nil {\nreturn err\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_ipv4_udp_unbound.cc",
"new_path": "test/syscalls/linux/socket_ipv4_udp_unbound.cc",
"diff": "@@ -278,6 +278,238 @@ TEST_P(IPv4UDPUnboundSocketPairTest, IpMulticastLoopbackNic) {\nEXPECT_EQ(0, memcmp(send_buf, recv_buf, sizeof(send_buf)));\n}\n+// Check that multicast works when the default send interface is confgured by\n+// IP_MULTICAST_IF, the send address is specified in sendto, and the group\n+// membership is configured by address.\n+TEST_P(IPv4UDPUnboundSocketPairTest, IpMulticastLoopbackIfAddr) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ // Set the default send interface.\n+ ip_mreq iface = {};\n+ iface.imr_interface.s_addr = htonl(INADDR_LOOPBACK);\n+ EXPECT_THAT(setsockopt(sockets->first_fd(), IPPROTO_IP, IP_MULTICAST_IF,\n+ &iface, sizeof(iface)),\n+ SyscallSucceeds());\n+\n+ // Bind the second FD to the v4 any address to ensure that we can receive the\n+ // multicast packet.\n+ auto receiver_addr = V4Any();\n+ EXPECT_THAT(bind(sockets->second_fd(),\n+ reinterpret_cast<sockaddr*>(&receiver_addr.addr),\n+ receiver_addr.addr_len),\n+ SyscallSucceeds());\n+ socklen_t receiver_addr_len = receiver_addr.addr_len;\n+ EXPECT_THAT(getsockname(sockets->second_fd(),\n+ reinterpret_cast<sockaddr*>(&receiver_addr.addr),\n+ &receiver_addr_len),\n+ SyscallSucceeds());\n+ EXPECT_EQ(receiver_addr_len, receiver_addr.addr_len);\n+\n+ // Register to receive multicast packets.\n+ ip_mreq group = {};\n+ group.imr_multiaddr.s_addr = inet_addr(kMulticastAddress);\n+ group.imr_interface.s_addr = htonl(INADDR_LOOPBACK);\n+ EXPECT_THAT(setsockopt(sockets->second_fd(), IPPROTO_IP, IP_ADD_MEMBERSHIP,\n+ &group, sizeof(group)),\n+ SyscallSucceeds());\n+\n+ // Send a multicast packet.\n+ auto send_addr = V4Multicast();\n+ reinterpret_cast<sockaddr_in*>(&send_addr.addr)->sin_port =\n+ reinterpret_cast<sockaddr_in*>(&receiver_addr.addr)->sin_port;\n+ char send_buf[200];\n+ RandomizeBuffer(send_buf, sizeof(send_buf));\n+ EXPECT_THAT(\n+ RetryEINTR(sendto)(sockets->first_fd(), send_buf, sizeof(send_buf), 0,\n+ reinterpret_cast<sockaddr*>(&send_addr.addr),\n+ send_addr.addr_len),\n+ SyscallSucceedsWithValue(sizeof(send_buf)));\n+\n+ // Check that we received the multicast packet.\n+ char recv_buf[sizeof(send_buf)] = {};\n+ ASSERT_THAT(\n+ RetryEINTR(recv)(sockets->second_fd(), recv_buf, sizeof(recv_buf), 0),\n+ SyscallSucceedsWithValue(sizeof(recv_buf)));\n+\n+ EXPECT_EQ(0, memcmp(send_buf, recv_buf, sizeof(send_buf)));\n+}\n+\n+// Check that multicast works when the default send interface is confgured by\n+// IP_MULTICAST_IF, the send address is specified in sendto, and the group\n+// membership is configured by NIC ID.\n+TEST_P(IPv4UDPUnboundSocketPairTest, IpMulticastLoopbackIfNic) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ // Set the default send interface.\n+ ip_mreqn iface = {};\n+ iface.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(InterfaceIndex(\"lo\"));\n+ EXPECT_THAT(setsockopt(sockets->first_fd(), IPPROTO_IP, IP_MULTICAST_IF,\n+ &iface, sizeof(iface)),\n+ SyscallSucceeds());\n+\n+ // Bind the second FD to the v4 any address to ensure that we can receive the\n+ // multicast packet.\n+ auto receiver_addr = V4Any();\n+ EXPECT_THAT(bind(sockets->second_fd(),\n+ reinterpret_cast<sockaddr*>(&receiver_addr.addr),\n+ receiver_addr.addr_len),\n+ SyscallSucceeds());\n+ socklen_t receiver_addr_len = receiver_addr.addr_len;\n+ EXPECT_THAT(getsockname(sockets->second_fd(),\n+ reinterpret_cast<sockaddr*>(&receiver_addr.addr),\n+ &receiver_addr_len),\n+ SyscallSucceeds());\n+ EXPECT_EQ(receiver_addr_len, receiver_addr.addr_len);\n+\n+ // Register to receive multicast packets.\n+ ip_mreqn group = {};\n+ group.imr_multiaddr.s_addr = inet_addr(kMulticastAddress);\n+ group.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(InterfaceIndex(\"lo\"));\n+ EXPECT_THAT(setsockopt(sockets->second_fd(), IPPROTO_IP, IP_ADD_MEMBERSHIP,\n+ &group, sizeof(group)),\n+ SyscallSucceeds());\n+\n+ // Send a multicast packet.\n+ auto send_addr = V4Multicast();\n+ reinterpret_cast<sockaddr_in*>(&send_addr.addr)->sin_port =\n+ reinterpret_cast<sockaddr_in*>(&receiver_addr.addr)->sin_port;\n+ char send_buf[200];\n+ RandomizeBuffer(send_buf, sizeof(send_buf));\n+ EXPECT_THAT(\n+ RetryEINTR(sendto)(sockets->first_fd(), send_buf, sizeof(send_buf), 0,\n+ reinterpret_cast<sockaddr*>(&send_addr.addr),\n+ send_addr.addr_len),\n+ SyscallSucceedsWithValue(sizeof(send_buf)));\n+\n+ // Check that we received the multicast packet.\n+ char recv_buf[sizeof(send_buf)] = {};\n+ ASSERT_THAT(\n+ RetryEINTR(recv)(sockets->second_fd(), recv_buf, sizeof(recv_buf), 0),\n+ SyscallSucceedsWithValue(sizeof(recv_buf)));\n+\n+ EXPECT_EQ(0, memcmp(send_buf, recv_buf, sizeof(send_buf)));\n+}\n+\n+// Check that multicast works when the default send interface is confgured by\n+// IP_MULTICAST_IF, the send address is specified in connect, and the group\n+// membership is configured by address.\n+TEST_P(IPv4UDPUnboundSocketPairTest, IpMulticastLoopbackIfAddrConnect) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ // Set the default send interface.\n+ ip_mreq iface = {};\n+ iface.imr_interface.s_addr = htonl(INADDR_LOOPBACK);\n+ EXPECT_THAT(setsockopt(sockets->first_fd(), IPPROTO_IP, IP_MULTICAST_IF,\n+ &iface, sizeof(iface)),\n+ SyscallSucceeds());\n+\n+ // Bind the second FD to the v4 any address to ensure that we can receive the\n+ // multicast packet.\n+ auto receiver_addr = V4Any();\n+ EXPECT_THAT(bind(sockets->second_fd(),\n+ reinterpret_cast<sockaddr*>(&receiver_addr.addr),\n+ receiver_addr.addr_len),\n+ SyscallSucceeds());\n+ socklen_t receiver_addr_len = receiver_addr.addr_len;\n+ EXPECT_THAT(getsockname(sockets->second_fd(),\n+ reinterpret_cast<sockaddr*>(&receiver_addr.addr),\n+ &receiver_addr_len),\n+ SyscallSucceeds());\n+ EXPECT_EQ(receiver_addr_len, receiver_addr.addr_len);\n+\n+ // Register to receive multicast packets.\n+ ip_mreq group = {};\n+ group.imr_multiaddr.s_addr = inet_addr(kMulticastAddress);\n+ group.imr_interface.s_addr = htonl(INADDR_LOOPBACK);\n+ EXPECT_THAT(setsockopt(sockets->second_fd(), IPPROTO_IP, IP_ADD_MEMBERSHIP,\n+ &group, sizeof(group)),\n+ SyscallSucceeds());\n+\n+ // Send a multicast packet.\n+ auto connect_addr = V4Multicast();\n+ reinterpret_cast<sockaddr_in*>(&connect_addr.addr)->sin_port =\n+ reinterpret_cast<sockaddr_in*>(&receiver_addr.addr)->sin_port;\n+ EXPECT_THAT(\n+ RetryEINTR(connect)(sockets->first_fd(),\n+ reinterpret_cast<sockaddr*>(&connect_addr.addr),\n+ connect_addr.addr_len),\n+ SyscallSucceeds());\n+\n+ char send_buf[200];\n+ RandomizeBuffer(send_buf, sizeof(send_buf));\n+ EXPECT_THAT(\n+ RetryEINTR(send)(sockets->first_fd(), send_buf, sizeof(send_buf), 0),\n+ SyscallSucceedsWithValue(sizeof(send_buf)));\n+\n+ // Check that we received the multicast packet.\n+ char recv_buf[sizeof(send_buf)] = {};\n+ ASSERT_THAT(\n+ RetryEINTR(recv)(sockets->second_fd(), recv_buf, sizeof(recv_buf), 0),\n+ SyscallSucceedsWithValue(sizeof(recv_buf)));\n+\n+ EXPECT_EQ(0, memcmp(send_buf, recv_buf, sizeof(send_buf)));\n+}\n+\n+// Check that multicast works when the default send interface is confgured by\n+// IP_MULTICAST_IF, the send address is specified in connect, and the group\n+// membership is configured by NIC ID.\n+TEST_P(IPv4UDPUnboundSocketPairTest, IpMulticastLoopbackIfNicConnect) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ // Set the default send interface.\n+ ip_mreqn iface = {};\n+ iface.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(InterfaceIndex(\"lo\"));\n+ EXPECT_THAT(setsockopt(sockets->first_fd(), IPPROTO_IP, IP_MULTICAST_IF,\n+ &iface, sizeof(iface)),\n+ SyscallSucceeds());\n+\n+ // Bind the second FD to the v4 any address to ensure that we can receive the\n+ // multicast packet.\n+ auto receiver_addr = V4Any();\n+ EXPECT_THAT(bind(sockets->second_fd(),\n+ reinterpret_cast<sockaddr*>(&receiver_addr.addr),\n+ receiver_addr.addr_len),\n+ SyscallSucceeds());\n+ socklen_t receiver_addr_len = receiver_addr.addr_len;\n+ EXPECT_THAT(getsockname(sockets->second_fd(),\n+ reinterpret_cast<sockaddr*>(&receiver_addr.addr),\n+ &receiver_addr_len),\n+ SyscallSucceeds());\n+ EXPECT_EQ(receiver_addr_len, receiver_addr.addr_len);\n+\n+ // Register to receive multicast packets.\n+ ip_mreqn group = {};\n+ group.imr_multiaddr.s_addr = inet_addr(kMulticastAddress);\n+ group.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(InterfaceIndex(\"lo\"));\n+ EXPECT_THAT(setsockopt(sockets->second_fd(), IPPROTO_IP, IP_ADD_MEMBERSHIP,\n+ &group, sizeof(group)),\n+ SyscallSucceeds());\n+\n+ // Send a multicast packet.\n+ auto connect_addr = V4Multicast();\n+ reinterpret_cast<sockaddr_in*>(&connect_addr.addr)->sin_port =\n+ reinterpret_cast<sockaddr_in*>(&receiver_addr.addr)->sin_port;\n+ EXPECT_THAT(\n+ RetryEINTR(connect)(sockets->first_fd(),\n+ reinterpret_cast<sockaddr*>(&connect_addr.addr),\n+ connect_addr.addr_len),\n+ SyscallSucceeds());\n+\n+ char send_buf[200];\n+ RandomizeBuffer(send_buf, sizeof(send_buf));\n+ EXPECT_THAT(\n+ RetryEINTR(send)(sockets->first_fd(), send_buf, sizeof(send_buf), 0),\n+ SyscallSucceedsWithValue(sizeof(send_buf)));\n+\n+ // Check that we received the multicast packet.\n+ char recv_buf[sizeof(send_buf)] = {};\n+ ASSERT_THAT(\n+ RetryEINTR(recv)(sockets->second_fd(), recv_buf, sizeof(recv_buf), 0),\n+ SyscallSucceedsWithValue(sizeof(recv_buf)));\n+\n+ EXPECT_EQ(0, memcmp(send_buf, recv_buf, sizeof(send_buf)));\n+}\n+\n// Check that dropping a group membership that does not exist fails.\nTEST_P(IPv4UDPUnboundSocketPairTest, IpMulticastInvalidDrop) {\nauto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n@@ -407,5 +639,34 @@ TEST_P(IPv4UDPUnboundSocketPairTest, IpMulticastDropNic) {\nSyscallFailsWithErrno(EAGAIN));\n}\n+TEST_P(IPv4UDPUnboundSocketPairTest, IpMulticastIfZero) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ ip_mreqn iface = {};\n+ EXPECT_THAT(setsockopt(sockets->first_fd(), IPPROTO_IP, IP_MULTICAST_IF,\n+ &iface, sizeof(iface)),\n+ SyscallSucceeds());\n+}\n+\n+TEST_P(IPv4UDPUnboundSocketPairTest, IpMulticastIfInvalidNic) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ ip_mreqn iface = {};\n+ iface.imr_ifindex = -1;\n+ EXPECT_THAT(setsockopt(sockets->first_fd(), IPPROTO_IP, IP_MULTICAST_IF,\n+ &iface, sizeof(iface)),\n+ SyscallFailsWithErrno(EADDRNOTAVAIL));\n+}\n+\n+TEST_P(IPv4UDPUnboundSocketPairTest, IpMulticastIfInvalidAddr) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ ip_mreq iface = {};\n+ iface.imr_interface.s_addr = inet_addr(\"255.255.255\");\n+ EXPECT_THAT(setsockopt(sockets->first_fd(), IPPROTO_IP, IP_MULTICAST_IF,\n+ &iface, sizeof(iface)),\n+ SyscallFailsWithErrno(EADDRNOTAVAIL));\n+}\n+\n} // namespace testing\n} // namespace gvisor\n"
}
] | Go | Apache License 2.0 | google/gvisor | Implement IP_MULTICAST_IF.
This allows setting a default send interface for IPv4 multicast. IPv6 support
will come later.
PiperOrigin-RevId: 234251379
Change-Id: I65922341cd8b8880f690fae3eeb7ddfa47c8c173 |
259,885 | 19.02.2019 14:19:07 | 28,800 | bb47d8a545f82849f637c480459109e16be336cf | Fix clone(CLONE_NEWUSER).
Use new user namespace for namespace creation checks.
Ensure userns is never nil since it's used by other namespaces. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/task_clone.go",
"new_path": "pkg/sentry/kernel/task_clone.go",
"diff": "@@ -17,7 +17,6 @@ package kernel\nimport (\n\"gvisor.googlesource.com/gvisor/pkg/abi/linux\"\n\"gvisor.googlesource.com/gvisor/pkg/bpf\"\n- \"gvisor.googlesource.com/gvisor/pkg/sentry/kernel/auth\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/usermem\"\n\"gvisor.googlesource.com/gvisor/pkg/syserror\"\n)\n@@ -166,7 +165,7 @@ func (t *Task) Clone(opts *CloneOptions) (ThreadID, *SyscallControl, error) {\n// privileges over the remaining namespaces created by the call.\" -\n// user_namespaces(7)\ncreds := t.Credentials()\n- var userns *auth.UserNamespace\n+ userns := creds.UserNamespace\nif opts.NewUserNamespace {\nvar err error\n// \"EPERM (since Linux 3.9): CLONE_NEWUSER was specified in flags and\n@@ -182,7 +181,7 @@ func (t *Task) Clone(opts *CloneOptions) (ThreadID, *SyscallControl, error) {\nreturn 0, nil, err\n}\n}\n- if (opts.NewPIDNamespace || opts.NewNetworkNamespace || opts.NewUTSNamespace) && !creds.HasCapability(linux.CAP_SYS_ADMIN) {\n+ if (opts.NewPIDNamespace || opts.NewNetworkNamespace || opts.NewUTSNamespace) && !creds.HasCapabilityIn(linux.CAP_SYS_ADMIN, userns) {\nreturn 0, nil, syserror.EPERM\n}\n@@ -287,7 +286,7 @@ func (t *Task) Clone(opts *CloneOptions) (ThreadID, *SyscallControl, error) {\nnt.SetSignalStack(t.SignalStack())\n}\n- if userns != nil {\n+ if userns != creds.UserNamespace {\nif err := nt.SetUserNamespace(userns); err != nil {\n// This shouldn't be possible: userns was created from nt.creds, so\n// nt should have CAP_SYS_ADMIN in userns.\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/BUILD",
"new_path": "test/syscalls/linux/BUILD",
"diff": "@@ -732,7 +732,9 @@ cc_binary(\nsrcs = [\"fork.cc\"],\nlinkstatic = 1,\ndeps = [\n+ \"//test/util:capability_util\",\n\"//test/util:logging\",\n+ \"//test/util:memory_util\",\n\"//test/util:test_main\",\n\"//test/util:test_util\",\n\"//test/util:thread_util\",\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/fork.cc",
"new_path": "test/syscalls/linux/fork.cc",
"diff": "#include <sys/types.h>\n#include <unistd.h>\n#include <atomic>\n+#include <cstdlib>\n#include \"gtest/gtest.h\"\n#include \"absl/time/clock.h\"\n#include \"absl/time/time.h\"\n+#include \"test/util/capability_util.h\"\n#include \"test/util/logging.h\"\n+#include \"test/util/memory_util.h\"\n#include \"test/util/test_util.h\"\n#include \"test/util/thread_util.h\"\n@@ -393,6 +396,34 @@ TEST_F(ForkTest, Affinity) {\nEXPECT_THAT(Wait(child), SyscallSucceedsWithValue(0));\n}\n+TEST(CloneTest, NewUserNamespacePermitsAllOtherNamespaces) {\n+ // \"If CLONE_NEWUSER is specified along with other CLONE_NEW* flags in a\n+ // single clone(2) or unshare(2) call, the user namespace is guaranteed to be\n+ // created first, giving the child (clone(2)) or caller (unshare(2))\n+ // privileges over the remaining namespaces created by the call. Thus, it is\n+ // possible for an unprivileged caller to specify this combination of flags.\"\n+ // - user_namespaces(7)\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(CanCreateUserNamespace()));\n+ Mapping child_stack = ASSERT_NO_ERRNO_AND_VALUE(\n+ MmapAnon(kPageSize, PROT_READ | PROT_WRITE, MAP_PRIVATE));\n+ int child_pid;\n+ // We only test with CLONE_NEWIPC, CLONE_NEWNET, and CLONE_NEWUTS since these\n+ // namespaces were implemented in Linux before user namespaces.\n+ ASSERT_THAT(\n+ child_pid = clone(\n+ +[](void*) { return 0; },\n+ reinterpret_cast<void*>(child_stack.addr() + kPageSize),\n+ CLONE_NEWUSER | CLONE_NEWIPC | CLONE_NEWNET | CLONE_NEWUTS | SIGCHLD,\n+ /* arg = */ nullptr),\n+ SyscallSucceeds());\n+\n+ int status;\n+ ASSERT_THAT(waitpid(child_pid, &status, 0),\n+ SyscallSucceedsWithValue(child_pid));\n+ EXPECT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) == 0)\n+ << \"status = \" << status;\n+}\n+\n#ifdef __x86_64__\n// Clone with CLONE_SETTLS and a non-canonical TLS address is rejected.\nTEST(CloneTest, NonCanonicalTLS) {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix clone(CLONE_NEWUSER).
- Use new user namespace for namespace creation checks.
- Ensure userns is never nil since it's used by other namespaces.
PiperOrigin-RevId: 234673175
Change-Id: I4b9d9d1e63ce4e24362089793961a996f7540cd9 |
259,885 | 19.02.2019 15:48:39 | 28,800 | bed6f8534b1bedaad031682fe052b5a46d9cb3ee | Set rax to syscall number on SECCOMP_RET_TRAP. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/seccomp.go",
"new_path": "pkg/sentry/kernel/seccomp.go",
"diff": "@@ -75,6 +75,9 @@ func (t *Task) checkSeccompSyscall(sysno int32, args arch.SyscallArguments, ip u\n// portion of the return value will be passed as si_errno.\" -\n// Documentation/prctl/seccomp_filter.txt\nt.SendSignal(seccompSiginfo(t, int32(result.Data()), sysno, ip))\n+ // \"The return value register will contain an arch-dependent value.\" In\n+ // practice, it's ~always the syscall number.\n+ t.Arch().SetReturn(uintptr(sysno))\ncase linux.SECCOMP_RET_ERRNO:\n// \"Results in the lower 16-bits of the return value being passed to\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/seccomp.cc",
"new_path": "test/syscalls/linux/seccomp.cc",
"diff": "#include <sys/prctl.h>\n#include <sys/syscall.h>\n#include <time.h>\n+#include <ucontext.h>\n#include <unistd.h>\n#include <atomic>\n@@ -161,14 +162,19 @@ TEST(SeccompTest, RetTrapCausesSIGSYS) {\npid_t const pid = fork();\nif (pid == 0) {\nconstexpr uint16_t kTrapValue = 0xdead;\n- RegisterSignalHandler(SIGSYS, +[](int signo, siginfo_t* info, void*) {\n+ RegisterSignalHandler(\n+ SIGSYS, +[](int signo, siginfo_t* info, void* ucv) {\n+ ucontext_t* uc = static_cast<ucontext_t*>(ucv);\n// This is a signal handler, so we must stay async-signal-safe.\nTEST_CHECK(info->si_signo == SIGSYS);\nTEST_CHECK(info->si_code == SYS_SECCOMP);\nTEST_CHECK(info->si_errno == kTrapValue);\nTEST_CHECK(info->si_call_addr != nullptr);\nTEST_CHECK(info->si_syscall == kFilteredSyscall);\n+#ifdef __x86_64__\nTEST_CHECK(info->si_arch == AUDIT_ARCH_X86_64);\n+ TEST_CHECK(uc->uc_mcontext.gregs[REG_RAX] == kFilteredSyscall);\n+#endif // defined(__x86_64__)\n_exit(0);\n});\nApplySeccompFilter(kFilteredSyscall, SECCOMP_RET_TRAP | kTrapValue);\n@@ -182,6 +188,8 @@ TEST(SeccompTest, RetTrapCausesSIGSYS) {\n<< \"status \" << status;\n}\n+#ifdef __x86_64__\n+\nconstexpr uint64_t kVsyscallTimeEntry = 0xffffffffff600400;\ntime_t vsyscall_time(time_t* t) {\n@@ -194,7 +202,9 @@ TEST(SeccompTest, SeccompAppliesToVsyscall) {\npid_t const pid = fork();\nif (pid == 0) {\nconstexpr uint16_t kTrapValue = 0xdead;\n- RegisterSignalHandler(SIGSYS, +[](int signo, siginfo_t* info, void*) {\n+ RegisterSignalHandler(\n+ SIGSYS, +[](int signo, siginfo_t* info, void* ucv) {\n+ ucontext_t* uc = static_cast<ucontext_t*>(ucv);\n// This is a signal handler, so we must stay async-signal-safe.\nTEST_CHECK(info->si_signo == SIGSYS);\nTEST_CHECK(info->si_code == SYS_SECCOMP);\n@@ -202,6 +212,7 @@ TEST(SeccompTest, SeccompAppliesToVsyscall) {\nTEST_CHECK(info->si_call_addr != nullptr);\nTEST_CHECK(info->si_syscall == SYS_time);\nTEST_CHECK(info->si_arch == AUDIT_ARCH_X86_64);\n+ TEST_CHECK(uc->uc_mcontext.gregs[REG_RAX] == SYS_time);\n_exit(0);\n});\nApplySeccompFilter(SYS_time, SECCOMP_RET_TRAP | kTrapValue);\n@@ -234,6 +245,8 @@ TEST(SeccompTest, RetKillVsyscallCausesDeathBySIGSYS) {\n<< \"status \" << status;\n}\n+#endif // defined(__x86_64__)\n+\nTEST(SeccompTest, RetTraceWithoutPtracerReturnsENOSYS) {\npid_t const pid = fork();\nif (pid == 0) {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Set rax to syscall number on SECCOMP_RET_TRAP.
PiperOrigin-RevId: 234690475
Change-Id: I1cbfb5aecd4697a4a26ec8524354aa8656cc3ba1 |
259,885 | 19.02.2019 15:52:47 | 28,800 | 2840f7c1b12c88f47f7c3c8df659ca436f5901b6 | Add p9.Sticky. | [
{
"change_type": "MODIFY",
"old_path": "pkg/p9/p9.go",
"new_path": "pkg/p9/p9.go",
"diff": "@@ -139,8 +139,11 @@ const (\n// AllPermissions is a mask with rwx bits set for user, group and others.\nAllPermissions FileMode = 0777\n+ // Sticky is a mode bit indicating sticky directories.\n+ Sticky FileMode = 01000\n+\n// permissionsMask is the mask to apply to FileModes for permissions. It\n- // includes rwx bits for user, group and others, and sticky bit (01000).\n+ // includes rwx bits for user, group and others, and sticky bit.\npermissionsMask FileMode = 01777\n)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add p9.Sticky.
PiperOrigin-RevId: 234691125
Change-Id: I2a588153ded5a4fbed07bc2f0937a43ccfba791b |
259,891 | 19.02.2019 16:40:31 | 28,800 | ec2460b1890aa1dbf8bd84f11dbdb3758e2443b2 | netstack: Add SIOCGSTAMP support.
Ping sometimes uses this instead of SO_TIMESTAMP. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/epsocket/epsocket.go",
"new_path": "pkg/sentry/socket/epsocket/epsocket.go",
"diff": "@@ -157,15 +157,17 @@ type SocketOperations struct {\n// from Endpoint.\nreadCM tcpip.ControlMessages\nsender tcpip.FullAddress\n+\n// sockOptTimestamp corresponds to SO_TIMESTAMP. When true, timestamps\n// of returned messages can be returned via control messages. When\n// false, the same timestamp is instead stored and can be read via the\n- // SIOCGSTAMP ioctl. See socket(7).\n+ // SIOCGSTAMP ioctl. It is protected by readMu. See socket(7).\nsockOptTimestamp bool\n- // timestampValid indicates whether timestamp has been set.\n+ // timestampValid indicates whether timestamp for SIOCGSTAMP has been\n+ // set. It is protected by readMu.\ntimestampValid bool\n- // timestampNS holds the timestamp to use with SIOCGSTAMP. It is only\n- // valid when timestampValid is true.\n+ // timestampNS holds the timestamp to use with SIOCTSTAMP. It is only\n+ // valid when timestampValid is true. It is protected by readMu.\ntimestampNS int64\n}\n@@ -266,7 +268,7 @@ func GetAddress(sfamily int, addr []byte) (tcpip.FullAddress, *syserr.Error) {\n}\nfunc (s *SocketOperations) isPacketBased() bool {\n- return s.skType == linux.SOCK_DGRAM || s.skType == linux.SOCK_SEQPACKET || s.skType == linux.SOCK_RDM\n+ return s.skType == linux.SOCK_DGRAM || s.skType == linux.SOCK_SEQPACKET || s.skType == linux.SOCK_RDM || s.skType == linux.SOCK_RAW\n}\n// fetchReadView updates the readView field of the socket if it's currently\n@@ -1480,6 +1482,8 @@ func (s *SocketOperations) GetPeerName(t *kernel.Task) (interface{}, uint32, *sy\n// coalescingRead is the fast path for non-blocking, non-peek, stream-based\n// case. It coalesces as many packets as possible before returning to the\n// caller.\n+//\n+// Precondition: s.readMu must be locked.\nfunc (s *SocketOperations) coalescingRead(ctx context.Context, dst usermem.IOSequence, discard bool) (int, *syserr.Error) {\nvar err *syserr.Error\nvar copied int\n@@ -1501,9 +1505,8 @@ func (s *SocketOperations) coalescingRead(ctx context.Context, dst usermem.IOSeq\n} else {\nn, e = dst.CopyOut(ctx, s.readView)\n// Set the control message, even if 0 bytes were read.\n- if e == nil && s.readCM.HasTimestamp && s.sockOptTimestamp {\n- s.timestampNS = s.readCM.Timestamp\n- s.timestampValid = true\n+ if e == nil {\n+ s.updateTimestamp()\n}\n}\ncopied += n\n@@ -1569,9 +1572,8 @@ func (s *SocketOperations) nonBlockingRead(ctx context.Context, dst usermem.IOSe\nn, err := dst.CopyOut(ctx, s.readView)\n// Set the control message, even if 0 bytes were read.\n- if err == nil && s.readCM.HasTimestamp && s.sockOptTimestamp {\n- s.timestampNS = s.readCM.Timestamp\n- s.timestampValid = true\n+ if err == nil {\n+ s.updateTimestamp()\n}\nvar addr interface{}\nvar addrLen uint32\n@@ -1582,11 +1584,11 @@ func (s *SocketOperations) nonBlockingRead(ctx context.Context, dst usermem.IOSe\nif peek {\nif l := len(s.readView); trunc && l > n {\n// isPacket must be true.\n- return l, addr, addrLen, socket.ControlMessages{IP: tcpip.ControlMessages{HasTimestamp: s.timestampValid, Timestamp: s.timestampNS}}, syserr.FromError(err)\n+ return l, addr, addrLen, s.controlMessages(), syserr.FromError(err)\n}\nif isPacket || err != nil {\n- return int(n), addr, addrLen, socket.ControlMessages{IP: tcpip.ControlMessages{HasTimestamp: s.timestampValid, Timestamp: s.timestampNS}}, syserr.FromError(err)\n+ return int(n), addr, addrLen, s.controlMessages(), syserr.FromError(err)\n}\n// We need to peek beyond the first message.\n@@ -1604,7 +1606,7 @@ func (s *SocketOperations) nonBlockingRead(ctx context.Context, dst usermem.IOSe\n// We got some data, so no need to return an error.\nerr = nil\n}\n- return int(n), nil, 0, socket.ControlMessages{IP: tcpip.ControlMessages{HasTimestamp: s.timestampValid, Timestamp: s.timestampNS}}, syserr.FromError(err)\n+ return int(n), nil, 0, s.controlMessages(), syserr.FromError(err)\n}\nvar msgLen int\n@@ -1617,10 +1619,26 @@ func (s *SocketOperations) nonBlockingRead(ctx context.Context, dst usermem.IOSe\n}\nif trunc {\n- return msgLen, addr, addrLen, socket.ControlMessages{IP: tcpip.ControlMessages{HasTimestamp: s.timestampValid, Timestamp: s.timestampNS}}, syserr.FromError(err)\n+ return msgLen, addr, addrLen, s.controlMessages(), syserr.FromError(err)\n+ }\n+\n+ return int(n), addr, addrLen, s.controlMessages(), syserr.FromError(err)\n}\n- return int(n), addr, addrLen, socket.ControlMessages{IP: tcpip.ControlMessages{HasTimestamp: s.timestampValid, Timestamp: s.timestampNS}}, syserr.FromError(err)\n+func (s *SocketOperations) controlMessages() socket.ControlMessages {\n+ return socket.ControlMessages{IP: tcpip.ControlMessages{HasTimestamp: s.readCM.HasTimestamp && s.sockOptTimestamp, Timestamp: s.readCM.Timestamp}}\n+}\n+\n+// updateTimestamp sets the timestamp for SIOCGSTAMP. It should be called after\n+// successfully writing packet data out to userspace.\n+//\n+// Precondition: s.readMu must be locked.\n+func (s *SocketOperations) updateTimestamp() {\n+ // Save the SIOCGSTAMP timestamp only if SO_TIMESTAMP is disabled.\n+ if !s.sockOptTimestamp {\n+ s.timestampValid = true\n+ s.timestampNS = s.readCM.Timestamp\n+ }\n}\n// RecvMsg implements the linux syscall recvmsg(2) for sockets backed by\n@@ -1771,6 +1789,23 @@ func (s *SocketOperations) SendMsg(t *kernel.Task, src usermem.IOSequence, to []\n// Ioctl implements fs.FileOperations.Ioctl.\nfunc (s *SocketOperations) Ioctl(ctx context.Context, io usermem.IO, args arch.SyscallArguments) (uintptr, error) {\n+ // SIOCGSTAMP is implemented by epsocket rather than all commonEndpoint\n+ // sockets.\n+ // TODO: Add a commonEndpoint method to support SIOCGSTAMP.\n+ if int(args[1].Int()) == syscall.SIOCGSTAMP {\n+ s.readMu.Lock()\n+ defer s.readMu.Unlock()\n+ if !s.timestampValid {\n+ return 0, syserror.ENOENT\n+ }\n+\n+ tv := linux.NsecToTimeval(s.timestampNS)\n+ _, err := usermem.CopyObjectOut(ctx, io, args[2].Pointer(), &tv, usermem.IOOpts{\n+ AddressSpaceActive: true,\n+ })\n+ return 0, err\n+ }\n+\nreturn Ioctl(ctx, s.Endpoint, io, args)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/BUILD",
"new_path": "test/syscalls/linux/BUILD",
"diff": "@@ -2907,6 +2907,7 @@ cc_binary(\nlinkstatic = 1,\ndeps = [\n\":socket_test_util\",\n+ \":unix_domain_socket_test_util\",\n\"//test/util:test_main\",\n\"//test/util:test_util\",\n\"//test/util:thread_util\",\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/udp_socket.cc",
"new_path": "test/syscalls/linux/udp_socket.cc",
"diff": "#include \"absl/time/clock.h\"\n#include \"absl/time/time.h\"\n#include \"test/syscalls/linux/socket_test_util.h\"\n+#include \"test/syscalls/linux/unix_domain_socket_test_util.h\"\n#include \"test/util/test_util.h\"\n#include \"test/util/thread_util.h\"\n@@ -892,12 +893,21 @@ TEST_P(UdpSocketTest, ErrorQueue) {\nSyscallFailsWithErrno(EAGAIN));\n}\n+TEST_P(UdpSocketTest, SoTimestampOffByDefault) {\n+ int v = -1;\n+ socklen_t optlen = sizeof(v);\n+ ASSERT_THAT(getsockopt(s_, SOL_SOCKET, SO_TIMESTAMP, &v, &optlen),\n+ SyscallSucceeds());\n+ ASSERT_EQ(v, kSockOptOff);\n+ ASSERT_EQ(optlen, sizeof(v));\n+}\n+\nTEST_P(UdpSocketTest, SoTimestamp) {\nASSERT_THAT(bind(s_, addr_[0], addrlen_), SyscallSucceeds());\nASSERT_THAT(connect(t_, addr_[0], addrlen_), SyscallSucceeds());\nint v = 1;\n- EXPECT_THAT(setsockopt(s_, SOL_SOCKET, SO_TIMESTAMP, &v, sizeof(v)),\n+ ASSERT_THAT(setsockopt(s_, SOL_SOCKET, SO_TIMESTAMP, &v, sizeof(v)),\nSyscallSucceeds());\nchar buf[3];\n@@ -926,12 +936,89 @@ TEST_P(UdpSocketTest, SoTimestamp) {\nmemcpy(&tv, CMSG_DATA(cmsg), sizeof(struct timeval));\nASSERT_TRUE(tv.tv_sec != 0 || tv.tv_usec != 0);\n+\n+ // There should be nothing to get via ioctl.\n+ ASSERT_THAT(ioctl(s_, SIOCGSTAMP, &tv), SyscallFailsWithErrno(ENOENT));\n}\nTEST_P(UdpSocketTest, WriteShutdownNotConnected) {\nEXPECT_THAT(shutdown(s_, SHUT_WR), SyscallFailsWithErrno(ENOTCONN));\n}\n+TEST_P(UdpSocketTest, TimestampIoctl) {\n+ ASSERT_THAT(bind(s_, addr_[0], addrlen_), SyscallSucceeds());\n+ ASSERT_THAT(connect(t_, addr_[0], addrlen_), SyscallSucceeds());\n+\n+ char buf[3];\n+ // Send packet from t_ to s_.\n+ ASSERT_THAT(RetryEINTR(write)(t_, buf, sizeof(buf)),\n+ SyscallSucceedsWithValue(sizeof(buf)));\n+\n+ // There should be no control messages.\n+ char recv_buf[sizeof(buf)];\n+ ASSERT_NO_FATAL_FAILURE(RecvNoCmsg(s_, recv_buf, sizeof(recv_buf)));\n+\n+ // A nonzero timeval should be available via ioctl.\n+ struct timeval tv = {};\n+ ASSERT_THAT(ioctl(s_, SIOCGSTAMP, &tv), SyscallSucceeds());\n+ ASSERT_TRUE(tv.tv_sec != 0 || tv.tv_usec != 0);\n+}\n+\n+TEST_P(UdpSocketTest, TimetstampIoctlNothingRead) {\n+ ASSERT_THAT(bind(s_, addr_[0], addrlen_), SyscallSucceeds());\n+ ASSERT_THAT(connect(t_, addr_[0], addrlen_), SyscallSucceeds());\n+\n+ struct timeval tv = {};\n+ ASSERT_THAT(ioctl(s_, SIOCGSTAMP, &tv), SyscallFailsWithErrno(ENOENT));\n+}\n+\n+// Test that the timestamp accessed via SIOCGSTAMP is still accessible after\n+// SO_TIMESTAMP is enabled and used to retrieve a timestamp.\n+TEST_P(UdpSocketTest, TimestampIoctlPersistence) {\n+ ASSERT_THAT(bind(s_, addr_[0], addrlen_), SyscallSucceeds());\n+ ASSERT_THAT(connect(t_, addr_[0], addrlen_), SyscallSucceeds());\n+\n+ char buf[3];\n+ // Send packet from t_ to s_.\n+ ASSERT_THAT(RetryEINTR(write)(t_, buf, sizeof(buf)),\n+ SyscallSucceedsWithValue(sizeof(buf)));\n+ ASSERT_THAT(RetryEINTR(write)(t_, buf, 0), SyscallSucceedsWithValue(0));\n+\n+ // There should be no control messages.\n+ char recv_buf[sizeof(buf)];\n+ ASSERT_NO_FATAL_FAILURE(RecvNoCmsg(s_, recv_buf, sizeof(recv_buf)));\n+\n+ // A nonzero timeval should be available via ioctl.\n+ struct timeval tv = {};\n+ ASSERT_THAT(ioctl(s_, SIOCGSTAMP, &tv), SyscallSucceeds());\n+ ASSERT_TRUE(tv.tv_sec != 0 || tv.tv_usec != 0);\n+\n+ // Enable SO_TIMESTAMP and send a message.\n+ int v = 1;\n+ EXPECT_THAT(setsockopt(s_, SOL_SOCKET, SO_TIMESTAMP, &v, sizeof(v)),\n+ SyscallSucceeds());\n+ ASSERT_THAT(RetryEINTR(write)(t_, buf, 0), SyscallSucceedsWithValue(0));\n+\n+ // There should be a message for SO_TIMESTAMP.\n+ char cmsgbuf[CMSG_SPACE(sizeof(struct timeval))];\n+ msghdr msg = {};\n+ iovec iov = {};\n+ msg.msg_iov = &iov;\n+ msg.msg_iovlen = 1;\n+ msg.msg_control = cmsgbuf;\n+ msg.msg_controllen = sizeof(cmsgbuf);\n+ ASSERT_THAT(RetryEINTR(recvmsg)(s_, &msg, 0), SyscallSucceedsWithValue(0));\n+ struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);\n+ cmsg = CMSG_FIRSTHDR(&msg);\n+ ASSERT_NE(cmsg, nullptr);\n+\n+ // The ioctl should return the exact same values as before.\n+ struct timeval tv2 = {};\n+ ASSERT_THAT(ioctl(s_, SIOCGSTAMP, &tv2), SyscallSucceeds());\n+ ASSERT_EQ(tv.tv_sec, tv2.tv_sec);\n+ ASSERT_EQ(tv.tv_usec, tv2.tv_usec);\n+}\n+\nINSTANTIATE_TEST_CASE_P(AllInetTests, UdpSocketTest,\n::testing::Values(AF_INET, AF_INET6));\n"
}
] | Go | Apache License 2.0 | google/gvisor | netstack: Add SIOCGSTAMP support.
Ping sometimes uses this instead of SO_TIMESTAMP.
PiperOrigin-RevId: 234699590
Change-Id: Ibec9c34fa0d443a931557a2b1b1ecd83effe7765 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.