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,992
22.04.2021 20:04:17
25,200
9e4aa04ad1f6e63f4aa99f516b19e4ff2592918b
Remove side effect from mount tests Dropping CAP_SYS_ADMIN and not restoring it causes other tests to be skipped.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/mount.cc", "new_path": "test/syscalls/linux/mount.cc", "diff": "@@ -67,9 +67,7 @@ TEST(MountTest, MountInvalidTarget) {\nTEST(MountTest, MountPermDenied) {\n// Clear CAP_SYS_ADMIN.\n- if (ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_SYS_ADMIN))) {\n- EXPECT_NO_ERRNO(SetCapability(CAP_SYS_ADMIN, false));\n- }\n+ AutoCapability cap(CAP_SYS_ADMIN, false);\n// Linux expects a valid target before checking capability.\nauto const dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n" }, { "change_type": "MODIFY", "old_path": "test/util/capability_util.h", "new_path": "test/util/capability_util.h", "diff": "@@ -99,14 +99,23 @@ PosixErrorOr<bool> CanCreateUserNamespace();\nclass AutoCapability {\npublic:\nAutoCapability(int cap, bool set) : cap_(cap), set_(set) {\n+ const bool has = EXPECT_NO_ERRNO_AND_VALUE(HaveCapability(cap));\n+ if (set != has) {\nEXPECT_NO_ERRNO(SetCapability(cap_, set_));\n+ applied_ = true;\n+ }\n}\n- ~AutoCapability() { EXPECT_NO_ERRNO(SetCapability(cap_, !set_)); }\n+ ~AutoCapability() {\n+ if (applied_) {\n+ EXPECT_NO_ERRNO(SetCapability(cap_, !set_));\n+ }\n+ }\nprivate:\nint cap_;\nbool set_;\n+ bool applied_ = false;\n};\n} // namespace testing\n" }, { "change_type": "MODIFY", "old_path": "test/util/posix_error.h", "new_path": "test/util/posix_error.h", "diff": "@@ -438,6 +438,13 @@ IsPosixErrorOkAndHolds(InnerMatcher&& inner_matcher) {\nstd::move(_expr_result).ValueOrDie(); \\\n})\n+#define EXPECT_NO_ERRNO_AND_VALUE(expr) \\\n+ ({ \\\n+ auto _expr_result = (expr); \\\n+ EXPECT_NO_ERRNO(_expr_result); \\\n+ std::move(_expr_result).ValueOrDie(); \\\n+ })\n+\n} // namespace testing\n} // namespace gvisor\n" } ]
Go
Apache License 2.0
google/gvisor
Remove side effect from mount tests Dropping CAP_SYS_ADMIN and not restoring it causes other tests to be skipped. PiperOrigin-RevId: 370002644
259,853
23.04.2021 16:43:03
25,200
80cd26c2f43e78d43e2ff769cf0449e67254e673
hostinet: parse the timeval structure from a SO_TIMESTAMP control message
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/hostinet/socket.go", "new_path": "pkg/sentry/socket/hostinet/socket.go", "diff": "@@ -528,7 +528,9 @@ func parseUnixControlMessages(unixControlMessages []unix.SocketControlMessage) s\nswitch unixCmsg.Header.Type {\ncase linux.SO_TIMESTAMP:\ncontrolMessages.IP.HasTimestamp = true\n- binary.Unmarshal(unixCmsg.Data[:linux.SizeOfTimeval], hostarch.ByteOrder, &controlMessages.IP.Timestamp)\n+ ts := linux.Timeval{}\n+ ts.UnmarshalBytes(unixCmsg.Data[:linux.SizeOfTimeval])\n+ controlMessages.IP.Timestamp = ts.ToNsecCapped()\n}\ncase linux.SOL_IP:\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/udp_socket.cc", "new_path": "test/syscalls/linux/udp_socket.cc", "diff": "@@ -1529,10 +1529,6 @@ TEST_P(UdpSocketTest, ErrorQueue) {\n#endif // __linux__\nTEST_P(UdpSocketTest, SoTimestampOffByDefault) {\n- // TODO(gvisor.dev/issue/1202): SO_TIMESTAMP socket option not supported by\n- // hostinet.\n- SKIP_IF(IsRunningWithHostinet());\n-\nint v = -1;\nsocklen_t optlen = sizeof(v);\nASSERT_THAT(getsockopt(bind_.get(), SOL_SOCKET, SO_TIMESTAMP, &v, &optlen),\n@@ -1542,10 +1538,6 @@ TEST_P(UdpSocketTest, SoTimestampOffByDefault) {\n}\nTEST_P(UdpSocketTest, SoTimestamp) {\n- // TODO(gvisor.dev/issue/1202): ioctl() and SO_TIMESTAMP socket option are not\n- // supported by hostinet.\n- SKIP_IF(IsRunningWithHostinet());\n-\nASSERT_NO_ERRNO(BindLoopback());\nASSERT_THAT(connect(sock_.get(), bind_addr_, addrlen_), SyscallSucceeds());\n@@ -1555,8 +1547,8 @@ TEST_P(UdpSocketTest, SoTimestamp) {\nchar buf[3];\n// Send zero length packet from sock to bind_.\n- ASSERT_THAT(RetryEINTR(write)(sock_.get(), buf, 0),\n- SyscallSucceedsWithValue(0));\n+ ASSERT_THAT(RetryEINTR(write)(sock_.get(), buf, sizeof(buf)),\n+ SyscallSucceedsWithValue(sizeof(buf)));\nstruct pollfd pfd = {bind_.get(), POLLIN, 0};\nASSERT_THAT(RetryEINTR(poll)(&pfd, 1, /*timeout=*/1000),\n@@ -1586,10 +1578,14 @@ TEST_P(UdpSocketTest, SoTimestamp) {\nASSERT_TRUE(tv.tv_sec != 0 || tv.tv_usec != 0);\n+ // TODO(gvisor.dev/issue/1202): ioctl(SIOCGSTAMP) is not supported by\n+ // hostinet.\n+ if (!IsRunningWithHostinet()) {\n// There should be nothing to get via ioctl.\nASSERT_THAT(ioctl(bind_.get(), SIOCGSTAMP, &tv),\nSyscallFailsWithErrno(ENOENT));\n}\n+}\nTEST_P(UdpSocketTest, WriteShutdownNotConnected) {\nEXPECT_THAT(shutdown(bind_.get(), SHUT_WR), SyscallFailsWithErrno(ENOTCONN));\n" } ]
Go
Apache License 2.0
google/gvisor
hostinet: parse the timeval structure from a SO_TIMESTAMP control message PiperOrigin-RevId: 370181621
260,001
23.04.2021 23:58:56
25,200
bf64560681182b0024790f683f4c9aea142e70c5
Add verity tests for stat, deleted/renamed file
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/verity_ioctl.cc", "new_path": "test/syscalls/linux/verity_ioctl.cc", "diff": "#include <stdint.h>\n#include <stdlib.h>\n#include <sys/mount.h>\n+#include <sys/stat.h>\n#include <time.h>\n#include <iomanip>\n@@ -272,6 +273,72 @@ TEST_F(IoctlTest, ModifiedDirMerkle) {\nSyscallFailsWithErrno(EIO));\n}\n+TEST_F(IoctlTest, Stat) {\n+ std::string verity_dir =\n+ ASSERT_NO_ERRNO_AND_VALUE(MountVerity(tmpfs_dir_.path(), filename_));\n+\n+ struct stat st;\n+ EXPECT_THAT(stat(JoinPath(verity_dir, filename_).c_str(), &st),\n+ SyscallSucceeds());\n+}\n+\n+TEST_F(IoctlTest, ModifiedStat) {\n+ std::string verity_dir =\n+ ASSERT_NO_ERRNO_AND_VALUE(MountVerity(tmpfs_dir_.path(), filename_));\n+\n+ EXPECT_THAT(chmod(JoinPath(tmpfs_dir_.path(), filename_).c_str(), 0644),\n+ SyscallSucceeds());\n+ struct stat st;\n+ EXPECT_THAT(stat(JoinPath(verity_dir, filename_).c_str(), &st),\n+ SyscallFailsWithErrno(EIO));\n+}\n+\n+TEST_F(IoctlTest, DeleteFile) {\n+ std::string verity_dir =\n+ ASSERT_NO_ERRNO_AND_VALUE(MountVerity(tmpfs_dir_.path(), filename_));\n+\n+ EXPECT_THAT(unlink(JoinPath(tmpfs_dir_.path(), filename_).c_str()),\n+ SyscallSucceeds());\n+ EXPECT_THAT(open(JoinPath(verity_dir, filename_).c_str(), O_RDONLY, 0777),\n+ SyscallFailsWithErrno(EIO));\n+}\n+\n+TEST_F(IoctlTest, DeleteMerkle) {\n+ std::string verity_dir =\n+ ASSERT_NO_ERRNO_AND_VALUE(MountVerity(tmpfs_dir_.path(), filename_));\n+\n+ EXPECT_THAT(\n+ unlink(MerklePath(JoinPath(tmpfs_dir_.path(), filename_)).c_str()),\n+ SyscallSucceeds());\n+ EXPECT_THAT(open(JoinPath(verity_dir, filename_).c_str(), O_RDONLY, 0777),\n+ SyscallFailsWithErrno(EIO));\n+}\n+\n+TEST_F(IoctlTest, RenameFile) {\n+ std::string verity_dir =\n+ ASSERT_NO_ERRNO_AND_VALUE(MountVerity(tmpfs_dir_.path(), filename_));\n+\n+ std::string new_file_name = \"renamed-\" + filename_;\n+ EXPECT_THAT(rename(JoinPath(tmpfs_dir_.path(), filename_).c_str(),\n+ JoinPath(tmpfs_dir_.path(), new_file_name).c_str()),\n+ SyscallSucceeds());\n+ EXPECT_THAT(open(JoinPath(verity_dir, filename_).c_str(), O_RDONLY, 0777),\n+ SyscallFailsWithErrno(EIO));\n+}\n+\n+TEST_F(IoctlTest, RenameMerkle) {\n+ std::string verity_dir =\n+ ASSERT_NO_ERRNO_AND_VALUE(MountVerity(tmpfs_dir_.path(), filename_));\n+\n+ std::string new_file_name = \"renamed-\" + filename_;\n+ EXPECT_THAT(\n+ rename(MerklePath(JoinPath(tmpfs_dir_.path(), filename_)).c_str(),\n+ MerklePath(JoinPath(tmpfs_dir_.path(), new_file_name)).c_str()),\n+ SyscallSucceeds());\n+ EXPECT_THAT(open(JoinPath(verity_dir, filename_).c_str(), O_RDONLY, 0777),\n+ SyscallFailsWithErrno(EIO));\n+}\n+\n} // namespace\n} // namespace testing\n" } ]
Go
Apache License 2.0
google/gvisor
Add verity tests for stat, deleted/renamed file PiperOrigin-RevId: 370219558
259,858
26.04.2021 16:25:26
25,200
36fdc6c9ef565be34f5ab27affed31eb2430e89a
Handle tmpfs with 5 fields in /proc/mounts parsing.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/mount.cc", "new_path": "test/syscalls/linux/mount.cc", "diff": "@@ -45,6 +45,7 @@ namespace testing {\nnamespace {\n+using ::testing::AnyOf;\nusing ::testing::Contains;\nusing ::testing::Pair;\n@@ -360,7 +361,8 @@ TEST(MountTest, MountInfo) {\nif (e.mount_point == dir.path()) {\nEXPECT_EQ(e.fstype, \"tmpfs\");\nauto mopts = ParseMountOptions(e.mount_opts);\n- EXPECT_THAT(mopts, Contains(Pair(\"mode\", \"0123\")));\n+ EXPECT_THAT(mopts, AnyOf(Contains(Pair(\"mode\", \"0123\")),\n+ Contains(Pair(\"mode\", \"123\"))));\n}\n}\n@@ -371,7 +373,8 @@ TEST(MountTest, MountInfo) {\nif (e.mount_point == dir.path()) {\nEXPECT_EQ(e.fstype, \"tmpfs\");\nauto mopts = ParseMountOptions(e.super_opts);\n- EXPECT_THAT(mopts, Contains(Pair(\"mode\", \"0123\")));\n+ EXPECT_THAT(mopts, AnyOf(Contains(Pair(\"mode\", \"0123\")),\n+ Contains(Pair(\"mode\", \"123\"))));\n}\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "test/util/BUILD", "new_path": "test/util/BUILD", "diff": "@@ -149,6 +149,18 @@ cc_library(\n],\n)\n+cc_test(\n+ name = \"mount_util_test\",\n+ size = \"small\",\n+ srcs = [\"mount_util_test.cc\"],\n+ deps = [\n+ \":mount_util\",\n+ \":test_main\",\n+ \":test_util\",\n+ gtest,\n+ ],\n+)\n+\ncc_library(\nname = \"save_util\",\ntestonly = 1,\n" }, { "change_type": "MODIFY", "old_path": "test/util/mount_util.cc", "new_path": "test/util/mount_util.cc", "diff": "@@ -26,9 +26,14 @@ namespace testing {\nPosixErrorOr<std::vector<ProcMountsEntry>> ProcSelfMountsEntries() {\nstd::string content;\nRETURN_IF_ERRNO(GetContents(\"/proc/self/mounts\", &content));\n+ return ProcSelfMountsEntriesFrom(content);\n+}\n+PosixErrorOr<std::vector<ProcMountsEntry>> ProcSelfMountsEntriesFrom(\n+ const std::string& content) {\nstd::vector<ProcMountsEntry> entries;\n- std::vector<std::string> lines = absl::StrSplit(content, '\\n');\n+ std::vector<std::string> lines =\n+ absl::StrSplit(content, absl::ByChar('\\n'), absl::AllowEmpty());\nstd::cerr << \"<contents of /proc/self/mounts>\" << std::endl;\nfor (const std::string& line : lines) {\nstd::cerr << line << std::endl;\n@@ -47,11 +52,11 @@ PosixErrorOr<std::vector<ProcMountsEntry>> ProcSelfMountsEntries() {\nProcMountsEntry entry;\nstd::vector<std::string> fields =\n- absl::StrSplit(line, absl::ByChar(' '), absl::SkipEmpty());\n+ absl::StrSplit(line, absl::ByChar(' '), absl::AllowEmpty());\nif (fields.size() != 6) {\n- return PosixError(EINVAL,\n- absl::StrFormat(\"Not enough tokens, got %d, line: %s\",\n- fields.size(), line));\n+ return PosixError(\n+ EINVAL, absl::StrFormat(\"Not enough tokens, got %d, content: <<%s>>\",\n+ fields.size(), content));\n}\nentry.spec = fields[0];\n@@ -71,9 +76,14 @@ PosixErrorOr<std::vector<ProcMountsEntry>> ProcSelfMountsEntries() {\nPosixErrorOr<std::vector<ProcMountInfoEntry>> ProcSelfMountInfoEntries() {\nstd::string content;\nRETURN_IF_ERRNO(GetContents(\"/proc/self/mountinfo\", &content));\n+ return ProcSelfMountInfoEntriesFrom(content);\n+}\n+PosixErrorOr<std::vector<ProcMountInfoEntry>> ProcSelfMountInfoEntriesFrom(\n+ const std::string& content) {\nstd::vector<ProcMountInfoEntry> entries;\n- std::vector<std::string> lines = absl::StrSplit(content, '\\n');\n+ std::vector<std::string> lines =\n+ absl::StrSplit(content, absl::ByChar('\\n'), absl::AllowEmpty());\nstd::cerr << \"<contents of /proc/self/mountinfo>\" << std::endl;\nfor (const std::string& line : lines) {\nstd::cerr << line << std::endl;\n@@ -92,12 +102,12 @@ PosixErrorOr<std::vector<ProcMountInfoEntry>> ProcSelfMountInfoEntries() {\nProcMountInfoEntry entry;\nstd::vector<std::string> fields =\n- absl::StrSplit(line, absl::ByChar(' '), absl::SkipEmpty());\n+ absl::StrSplit(line, absl::ByChar(' '), absl::AllowEmpty());\nif (fields.size() < 10 || fields.size() > 11) {\nreturn PosixError(\n- EINVAL,\n- absl::StrFormat(\"Unexpected number of tokens, got %d, line: %s\",\n- fields.size(), line));\n+ EINVAL, absl::StrFormat(\n+ \"Unexpected number of tokens, got %d, content: <<%s>>\",\n+ fields.size(), content));\n}\nASSIGN_OR_RETURN_ERRNO(entry.id, Atoi<uint64_t>(fields[0]));\n@@ -142,7 +152,7 @@ absl::flat_hash_map<std::string, std::string> ParseMountOptions(\nstd::string mopts) {\nabsl::flat_hash_map<std::string, std::string> entries;\nconst std::vector<std::string> tokens =\n- absl::StrSplit(mopts, absl::ByChar(','), absl::SkipEmpty());\n+ absl::StrSplit(mopts, absl::ByChar(','), absl::AllowEmpty());\nfor (const auto& token : tokens) {\nstd::vector<std::string> kv =\nabsl::StrSplit(token, absl::MaxSplits('=', 1));\n" }, { "change_type": "MODIFY", "old_path": "test/util/mount_util.h", "new_path": "test/util/mount_util.h", "diff": "@@ -58,6 +58,11 @@ struct ProcMountsEntry {\n// ProcSelfMountsEntries returns a parsed representation of /proc/self/mounts.\nPosixErrorOr<std::vector<ProcMountsEntry>> ProcSelfMountsEntries();\n+// ProcSelfMountsEntries returns a parsed representation of mounts from the\n+// provided content.\n+PosixErrorOr<std::vector<ProcMountsEntry>> ProcSelfMountsEntriesFrom(\n+ const std::string& content);\n+\nstruct ProcMountInfoEntry {\nuint64_t id;\nuint64_t parent_id;\n@@ -76,6 +81,11 @@ struct ProcMountInfoEntry {\n// /proc/self/mountinfo.\nPosixErrorOr<std::vector<ProcMountInfoEntry>> ProcSelfMountInfoEntries();\n+// ProcSelfMountInfoEntriesFrom returns a parsed representation of\n+// mountinfo from the provided content.\n+PosixErrorOr<std::vector<ProcMountInfoEntry>> ProcSelfMountInfoEntriesFrom(\n+ const std::string&);\n+\n// Interprets the input string mopts as a comma separated list of mount\n// options. A mount option can either be just a value, or a key=value pair. For\n// example, the string \"rw,relatime,fd=7\" will be parsed into a map like { \"rw\":\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test/util/mount_util_test.cc", "diff": "+// Copyright 2018 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+#include \"test/util/mount_util.h\"\n+\n+#include \"gmock/gmock.h\"\n+#include \"gtest/gtest.h\"\n+#include \"test/util/test_util.h\"\n+\n+namespace gvisor {\n+namespace testing {\n+\n+namespace {\n+\n+TEST(ParseMounts, Mounts) {\n+ auto entries = ASSERT_NO_ERRNO_AND_VALUE(ProcSelfMountsEntriesFrom(\n+ R\"proc(sysfs /sys sysfs rw,nosuid,nodev,noexec,relatime 0 0\n+proc /proc proc rw,nosuid,nodev,noexec,relatime 0 0\n+ /mnt tmpfs rw,noexec 0 0\n+)proc\"));\n+ EXPECT_EQ(entries.size(), 3);\n+}\n+\n+TEST(ParseMounts, MountInfo) {\n+ auto entries = ASSERT_NO_ERRNO_AND_VALUE(ProcSelfMountInfoEntriesFrom(\n+ R\"proc(22 28 0:20 / /sys rw,relatime shared:7 - sysfs sysfs rw\n+23 28 0:21 / /proc rw,relatime shared:14 - proc proc rw\n+2007 8844 0:278 / /mnt rw,noexec - tmpfs rw,mode=123,uid=268601820,gid=5000\n+)proc\"));\n+ EXPECT_EQ(entries.size(), 3);\n+}\n+\n+} // namespace\n+\n+} // namespace testing\n+} // namespace gvisor\n" } ]
Go
Apache License 2.0
google/gvisor
Handle tmpfs with 5 fields in /proc/mounts parsing. PiperOrigin-RevId: 370565903
259,896
26.04.2021 17:35:16
25,200
5b207fe7834d9c6541bd99bf75e3dfeebce2d9d5
Remove metrics: fallback, vsyscallCount and partialResult The newly added Weirdness metric with fields should be used instead of them. Simple query for weirdness metric:
[ { "change_type": "MODIFY", "old_path": "pkg/metric/metric.go", "new_path": "pkg/metric/metric.go", "diff": "@@ -37,7 +37,7 @@ var (\nErrInitializationDone = errors.New(\"metric cannot be created after initialization is complete\")\n// WeirdnessMetric is a metric with fields created to track the number\n- // of weird occurrences such as clock fallback, partial_result and\n+ // of weird occurrences such as time fallback, partial_result and\n// vsyscall count.\nWeirdnessMetric *Uint64Metric\n)\n@@ -392,9 +392,9 @@ func CreateSentryMetrics() {\nreturn\n}\n- WeirdnessMetric = MustCreateNewUint64Metric(\"/weirdness\", true /* sync */, \"Increment for weird occurrences of problems such as clock fallback, partial result and vsyscalls invoked in the sandbox\",\n+ WeirdnessMetric = MustCreateNewUint64Metric(\"/weirdness\", true /* sync */, \"Increment for weird occurrences of problems such as time fallback, partial result and vsyscalls invoked in the sandbox\",\nField{\nname: \"weirdness_type\",\n- allowedValues: []string{\"fallback\", \"partial_result\", \"vsyscall_count\"},\n+ allowedValues: []string{\"time_fallback\", \"partial_result\", \"vsyscall_count\"},\n})\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/task_syscall.go", "new_path": "pkg/sentry/kernel/task_syscall.go", "diff": "@@ -30,8 +30,6 @@ import (\n\"gvisor.dev/gvisor/pkg/syserror\"\n)\n-var vsyscallCount = metric.MustCreateNewUint64Metric(\"/kernel/vsyscall_count\", false /* sync */, \"Number of times vsyscalls were invoked by the application\")\n-\n// SyscallRestartBlock represents the restart block for a syscall restartable\n// with a custom function. It encapsulates the state required to restart a\n// syscall across a S/R.\n@@ -284,7 +282,6 @@ func (*runSyscallExit) execute(t *Task) taskRunState {\n// indicated by an execution fault at address addr. doVsyscall returns the\n// task's next run state.\nfunc (t *Task) doVsyscall(addr hostarch.Addr, sysno uintptr) taskRunState {\n- vsyscallCount.Increment()\nmetric.WeirdnessMetric.Increment(\"vsyscall_count\")\n// Grab the caller up front, to make sure there's a sensible stack.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/error.go", "new_path": "pkg/sentry/syscalls/linux/error.go", "diff": "@@ -29,7 +29,6 @@ import (\n)\nvar (\n- partialResultMetric = metric.MustCreateNewUint64Metric(\"/syscalls/partial_result\", true /* sync */, \"Whether or not a partial result has occurred for this sandbox.\")\npartialResultOnce sync.Once\n)\n@@ -38,7 +37,6 @@ var (\n// us to pass a function which does not take any arguments, whereas Increment()\n// takes a variadic number of arguments.\nfunc incrementPartialResultMetric() {\n- partialResultMetric.Increment()\nmetric.WeirdnessMetric.Increment(\"partial_result\")\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/time/calibrated_clock.go", "new_path": "pkg/sentry/time/calibrated_clock.go", "diff": "@@ -25,11 +25,6 @@ import (\n\"gvisor.dev/gvisor/pkg/syserror\"\n)\n-// fallbackMetric tracks failed updates. It is not sync, as it is not critical\n-// that all occurrences are captured and CalibratedClock may fallback many\n-// times.\n-var fallbackMetric = metric.MustCreateNewUint64Metric(\"/time/fallback\", false /* sync */, \"Incremented when a clock falls back to system calls due to a failed update\")\n-\n// CalibratedClock implements a clock that tracks a reference clock.\n//\n// Users should call Update at regular intervals of around approxUpdateInterval\n@@ -102,8 +97,7 @@ func (c *CalibratedClock) resetLocked(str string, v ...interface{}) {\nc.Warningf(str+\" Resetting clock; time may jump.\", v...)\nc.ready = false\nc.ref.Reset()\n- fallbackMetric.Increment()\n- metric.WeirdnessMetric.Increment(\"fallback\")\n+ metric.WeirdnessMetric.Increment(\"time_fallback\")\n}\n// updateParams updates the timekeeping parameters based on the passed\n" } ]
Go
Apache License 2.0
google/gvisor
Remove metrics: fallback, vsyscallCount and partialResult The newly added Weirdness metric with fields should be used instead of them. Simple query for weirdness metric: http://shortn/_DGNk0z2Up6 PiperOrigin-RevId: 370578132
259,875
27.04.2021 12:05:30
25,200
9ec49aabd34ecf9eba982439abd2ada4617d576a
Fix SyscallInfo for epoll_pwait in strace.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/strace/linux64_amd64.go", "new_path": "pkg/sentry/strace/linux64_amd64.go", "diff": "@@ -305,7 +305,7 @@ var linuxAMD64 = SyscallMap{\n278: makeSyscallInfo(\"vmsplice\", FD, Hex, Hex, Hex),\n279: makeSyscallInfo(\"move_pages\", Hex, Hex, Hex, Hex, Hex, Hex),\n280: makeSyscallInfo(\"utimensat\", FD, Path, UTimeTimespec, Hex),\n- 281: makeSyscallInfo(\"epoll_pwait\", FD, EpollEvents, Hex, Hex, SigSet, Hex),\n+ 281: makeSyscallInfo(\"epoll_pwait\", FD, EpollEvents, Hex, Hex, SigSet),\n282: makeSyscallInfo(\"signalfd\", Hex, Hex, Hex),\n283: makeSyscallInfo(\"timerfd_create\", Hex, Hex),\n284: makeSyscallInfo(\"eventfd\", Hex),\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/strace/linux64_arm64.go", "new_path": "pkg/sentry/strace/linux64_arm64.go", "diff": "@@ -46,7 +46,7 @@ var linuxARM64 = SyscallMap{\n19: makeSyscallInfo(\"eventfd2\", Hex, Hex),\n20: makeSyscallInfo(\"epoll_create1\", Hex),\n21: makeSyscallInfo(\"epoll_ctl\", FD, EpollCtlOp, FD, EpollEvent),\n- 22: makeSyscallInfo(\"epoll_pwait\", FD, EpollEvents, Hex, Hex, SigSet, Hex),\n+ 22: makeSyscallInfo(\"epoll_pwait\", FD, EpollEvents, Hex, Hex, SigSet),\n23: makeSyscallInfo(\"dup\", FD),\n24: makeSyscallInfo(\"dup3\", FD, FD, Hex),\n25: makeSyscallInfo(\"fcntl\", FD, Hex, Hex),\n" } ]
Go
Apache License 2.0
google/gvisor
Fix SyscallInfo for epoll_pwait in strace. PiperOrigin-RevId: 370733869
259,992
28.04.2021 14:41:59
25,200
704728d38fdb3ceaf8dfbfdba84eee183775b90c
Disable test that is always skipped
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/raw_socket_hdrincl.cc", "new_path": "test/syscalls/linux/raw_socket_hdrincl.cc", "diff": "@@ -177,10 +177,8 @@ TEST_F(RawHDRINCL, ConnectToLoopback) {\nSyscallSucceeds());\n}\n-TEST_F(RawHDRINCL, SendWithoutConnectSucceeds) {\n// FIXME(gvisor.dev/issue/3159): Test currently flaky.\n- SKIP_IF(true);\n-\n+TEST_F(RawHDRINCL, DISABLED_SendWithoutConnectSucceeds) {\nstruct iphdr hdr = LoopbackHeader();\nASSERT_THAT(send(socket_, &hdr, sizeof(hdr), 0),\nSyscallSucceedsWithValue(sizeof(hdr)));\n" } ]
Go
Apache License 2.0
google/gvisor
Disable test that is always skipped PiperOrigin-RevId: 370989166
259,884
28.04.2021 16:18:21
25,200
39fdf0b950e2161247b60d8576151c6015a3b47c
Use containerd v2 config format in docs Fixes
[ { "change_type": "MODIFY", "old_path": "g3doc/user_guide/containerd/configuration.md", "new_path": "g3doc/user_guide/containerd/configuration.md", "diff": "@@ -14,6 +14,7 @@ cat <<EOF | sudo tee /etc/containerd/runsc.toml\noption = \"value\"\n[runsc_config]\nflag = \"value\"\n+EOF\n```\nThe set of options that can be configured can be found in\n@@ -32,10 +33,12 @@ configuration. Here is an example:\n```shell\ncat <<EOF | sudo tee /etc/containerd/config.toml\n-disabled_plugins = [\"restart\"]\n-[plugins.cri.containerd.runtimes.runsc]\n+version = 2\n+[plugins.\"io.containerd.grpc.v1.cri\".containerd.runtimes.runc]\n+ runtime_type = \"io.containerd.runc.v2\"\n+[plugins.\"io.containerd.grpc.v1.cri\".containerd.runtimes.runsc]\nruntime_type = \"io.containerd.runsc.v1\"\n-[plugins.cri.containerd.runtimes.runsc.options]\n+[plugins.\"io.containerd.grpc.v1.cri\".containerd.runtimes.runsc.options]\nTypeUrl = \"io.containerd.runsc.v1.options\"\nConfigPath = \"/etc/containerd/runsc.toml\"\nEOF\n@@ -56,14 +59,16 @@ a containerd configuration file that enables both options:\n```shell\ncat <<EOF | sudo tee /etc/containerd/config.toml\n-disabled_plugins = [\"restart\"]\n+version = 2\n[debug]\nlevel = \"debug\"\n-[plugins.linux]\n+[plugins.\"io.containerd.runtime.v1.linux\"]\nshim_debug = true\n-[plugins.cri.containerd.runtimes.runsc]\n+[plugins.\"io.containerd.grpc.v1.cri\".containerd.runtimes.runc]\n+ runtime_type = \"io.containerd.runc.v2\"\n+[plugins.\"io.containerd.grpc.v1.cri\".containerd.runtimes.runsc]\nruntime_type = \"io.containerd.runsc.v1\"\n-[plugins.cri.containerd.runtimes.runsc.options]\n+[plugins.\"io.containerd.grpc.v1.cri\".containerd.runtimes.runsc.option]\nTypeUrl = \"io.containerd.runsc.v1.options\"\nConfigPath = \"/etc/containerd/runsc.toml\"\nEOF\n@@ -93,4 +98,5 @@ log_level = \"debug\"\n[runsc_config]\ndebug = \"true\"\ndebug-log = \"/var/log/runsc/%ID%/gvisor.%COMMAND%.log\"\n+EOF\n```\n" }, { "change_type": "MODIFY", "old_path": "g3doc/user_guide/containerd/quick_start.md", "new_path": "g3doc/user_guide/containerd/quick_start.md", "diff": "@@ -21,10 +21,12 @@ Update `/etc/containerd/config.toml`. Make sure `containerd-shim-runsc-v1` is in\n```shell\ncat <<EOF | sudo tee /etc/containerd/config.toml\n-disabled_plugins = [\"restart\"]\n-[plugins.linux]\n+version = 2\n+[plugins.\"io.containerd.runtime.v1.linux\"]\nshim_debug = true\n-[plugins.cri.containerd.runtimes.runsc]\n+[plugins.\"io.containerd.grpc.v1.cri\".containerd.runtimes.runc]\n+ runtime_type = \"io.containerd.runc.v2\"\n+[plugins.\"io.containerd.grpc.v1.cri\".containerd.runtimes.runsc]\nruntime_type = \"io.containerd.runsc.v1\"\nEOF\n```\n" } ]
Go
Apache License 2.0
google/gvisor
Use containerd v2 config format in docs Fixes #5170 PiperOrigin-RevId: 371007691
259,992
29.04.2021 11:23:19
25,200
2e442f908142d175e95226e3ad5892902921f8fd
Remove ResolvingPath.Restart
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/resolving_path.go", "new_path": "pkg/sentry/vfs/resolving_path.go", "diff": "@@ -46,11 +46,8 @@ type ResolvingPath struct {\nflags uint16\nmustBeDir bool // final file must be a directory?\n- mustBeDirOrig bool\nsymlinks uint8 // number of symlinks traversed\n- symlinksOrig uint8\ncurPart uint8 // index into parts\n- numOrigParts uint8\ncreds *auth.Credentials\n@@ -60,14 +57,9 @@ type ResolvingPath struct {\nnextStart *Dentry // ref held if not nil\nabsSymlinkTarget fspath.Path\n- // ResolvingPath must track up to two relative paths: the \"current\"\n- // relative path, which is updated whenever a relative symlink is\n- // encountered, and the \"original\" relative path, which is updated from the\n- // current relative path by handleError() when resolution must change\n- // filesystems (due to reaching a mount boundary or absolute symlink) and\n- // overwrites the current relative path when Restart() is called.\n+ // ResolvingPath tracks relative paths, which is updated whenever a relative\n+ // symlink is encountered.\nparts [1 + linux.MaxSymlinkTraversals]fspath.Iterator\n- origParts [1 + linux.MaxSymlinkTraversals]fspath.Iterator\n}\nconst (\n@@ -134,13 +126,10 @@ func (vfs *VirtualFilesystem) getResolvingPath(creds *auth.Credentials, pop *Pat\nrp.flags |= rpflagsFollowFinalSymlink\n}\nrp.mustBeDir = pop.Path.Dir\n- rp.mustBeDirOrig = pop.Path.Dir\nrp.symlinks = 0\nrp.curPart = 0\n- rp.numOrigParts = 1\nrp.creds = creds\nrp.parts[0] = pop.Path.Begin\n- rp.origParts[0] = pop.Path.Begin\nreturn rp\n}\n@@ -265,25 +254,6 @@ func (rp *ResolvingPath) Advance() {\n}\n}\n-// Restart resets the stream of path components represented by rp to its state\n-// on entry to the current FilesystemImpl method.\n-func (rp *ResolvingPath) Restart(ctx context.Context) {\n- rp.pit = rp.origParts[rp.numOrigParts-1]\n- rp.mustBeDir = rp.mustBeDirOrig\n- rp.symlinks = rp.symlinksOrig\n- rp.curPart = rp.numOrigParts - 1\n- copy(rp.parts[:], rp.origParts[:rp.numOrigParts])\n- rp.releaseErrorState(ctx)\n-}\n-\n-func (rp *ResolvingPath) relpathCommit() {\n- rp.mustBeDirOrig = rp.mustBeDir\n- rp.symlinksOrig = rp.symlinks\n- rp.numOrigParts = rp.curPart + 1\n- copy(rp.origParts[:rp.curPart], rp.parts[:])\n- rp.origParts[rp.curPart] = rp.pit\n-}\n-\n// CheckRoot is called before resolving the parent of the Dentry d. If the\n// Dentry is contextually a VFS root, such that path resolution should treat\n// d's parent as itself, CheckRoot returns (true, nil). If the Dentry is the\n@@ -430,11 +400,10 @@ func (rp *ResolvingPath) handleError(ctx context.Context, err error) bool {\nrp.flags |= rpflagsHaveMountRef | rpflagsHaveStartRef\nrp.nextMount = nil\nrp.nextStart = nil\n- // Commit the previous FileystemImpl's progress through the relative\n- // path. (Don't consume the path component that caused us to traverse\n+ // Don't consume the path component that caused us to traverse\n// through the mount root - i.e. the \"..\" - because we still need to\n- // resolve the mount point's parent in the new FilesystemImpl.)\n- rp.relpathCommit()\n+ // resolve the mount point's parent in the new FilesystemImpl.\n+ //\n// Restart path resolution on the new Mount. Don't bother calling\n// rp.releaseErrorState() since we already set nextMount and nextStart\n// to nil above.\n@@ -450,9 +419,6 @@ func (rp *ResolvingPath) handleError(ctx context.Context, err error) bool {\nrp.nextMount = nil\n// Consume the path component that represented the mount point.\nrp.Advance()\n- // Commit the previous FilesystemImpl's progress through the relative\n- // path.\n- rp.relpathCommit()\n// Restart path resolution on the new Mount.\nrp.releaseErrorState(ctx)\nreturn true\n@@ -467,9 +433,6 @@ func (rp *ResolvingPath) handleError(ctx context.Context, err error) bool {\nrp.Advance()\n// Prepend the symlink target to the relative path.\nrp.relpathPrepend(rp.absSymlinkTarget)\n- // Commit the previous FilesystemImpl's progress through the relative\n- // path, including the symlink target we just prepended.\n- rp.relpathCommit()\n// Restart path resolution on the new Mount.\nrp.releaseErrorState(ctx)\nreturn true\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/vfs.go", "new_path": "pkg/sentry/vfs/vfs.go", "diff": "@@ -425,7 +425,6 @@ func (vfs *VirtualFilesystem) OpenAt(ctx context.Context, creds *auth.Credential\nrp := vfs.getResolvingPath(creds, pop)\nif opts.Flags&linux.O_DIRECTORY != 0 {\nrp.mustBeDir = true\n- rp.mustBeDirOrig = true\n}\n// Ignore O_PATH for verity, as verity performs extra operations on the fd for verification.\n// The underlying filesystem that verity wraps opens the fd with O_PATH.\n" } ]
Go
Apache License 2.0
google/gvisor
Remove ResolvingPath.Restart PiperOrigin-RevId: 371163405
260,003
29.04.2021 11:41:12
25,200
a41c5fe217e6c40e563669e0a888b33bc125fa88
netstack: Rename pkt.Data().TrimFront() to DeleteFront(), and ... ... it may now invalidate backing slice references This is currently safe because TrimFront() in VectorisedView only shrinks the view. This may not hold under the a different buffer implementation. Reordering method calls order to allow this.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv4/icmp.go", "new_path": "pkg/tcpip/network/ipv4/icmp.go", "diff": "@@ -163,10 +163,12 @@ func (e *endpoint) handleControl(errInfo stack.TransportError, pkt *stack.Packet\nreturn\n}\n- // Skip the ip header, then deliver the error.\n- pkt.Data().TrimFront(hlen)\n+ // Keep needed information before trimming header.\np := hdr.TransportProtocol()\n- e.dispatcher.DeliverTransportError(srcAddr, hdr.DestinationAddress(), ProtocolNumber, p, errInfo, pkt)\n+ dstAddr := hdr.DestinationAddress()\n+ // Skip the ip header, then deliver the error.\n+ pkt.Data().DeleteFront(hlen)\n+ e.dispatcher.DeliverTransportError(srcAddr, dstAddr, ProtocolNumber, p, errInfo, pkt)\n}\nfunc (e *endpoint) handleICMP(pkt *stack.PacketBuffer) {\n@@ -336,14 +338,16 @@ func (e *endpoint) handleICMP(pkt *stack.PacketBuffer) {\ncase header.ICMPv4DstUnreachable:\nreceived.dstUnreachable.Increment()\n- pkt.Data().TrimFront(header.ICMPv4MinimumSize)\n- switch h.Code() {\n+ mtu := h.MTU()\n+ code := h.Code()\n+ pkt.Data().DeleteFront(header.ICMPv4MinimumSize)\n+ switch code {\ncase header.ICMPv4HostUnreachable:\ne.handleControl(&icmpv4DestinationHostUnreachableSockError{}, pkt)\ncase header.ICMPv4PortUnreachable:\ne.handleControl(&icmpv4DestinationPortUnreachableSockError{}, pkt)\ncase header.ICMPv4FragmentationNeeded:\n- networkMTU, err := calculateNetworkMTU(uint32(h.MTU()), header.IPv4MinimumSize)\n+ networkMTU, err := calculateNetworkMTU(uint32(mtu), header.IPv4MinimumSize)\nif err != nil {\nnetworkMTU = 0\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/icmp.go", "new_path": "pkg/tcpip/network/ipv6/icmp.go", "diff": "@@ -181,10 +181,13 @@ func (e *endpoint) handleControl(transErr stack.TransportError, pkt *stack.Packe\nreturn\n}\n+ // Keep needed information before trimming header.\n+ p := hdr.TransportProtocol()\n+ dstAddr := hdr.DestinationAddress()\n+\n// Skip the IP header, then handle the fragmentation header if there\n// is one.\n- pkt.Data().TrimFront(header.IPv6MinimumSize)\n- p := hdr.TransportProtocol()\n+ pkt.Data().DeleteFront(header.IPv6MinimumSize)\nif p == header.IPv6FragmentHeader {\nf, ok := pkt.Data().PullUp(header.IPv6FragmentHeaderSize)\nif !ok {\n@@ -196,14 +199,14 @@ func (e *endpoint) handleControl(transErr stack.TransportError, pkt *stack.Packe\n// because they don't have the transport headers.\nreturn\n}\n+ p = fragHdr.TransportProtocol()\n// Skip fragmentation header and find out the actual protocol\n// number.\n- pkt.Data().TrimFront(header.IPv6FragmentHeaderSize)\n- p = fragHdr.TransportProtocol()\n+ pkt.Data().DeleteFront(header.IPv6FragmentHeaderSize)\n}\n- e.dispatcher.DeliverTransportError(srcAddr, hdr.DestinationAddress(), ProtocolNumber, p, transErr, pkt)\n+ e.dispatcher.DeliverTransportError(srcAddr, dstAddr, ProtocolNumber, p, transErr, pkt)\n}\n// getLinkAddrOption searches NDP options for a given link address option using\n@@ -327,11 +330,11 @@ func (e *endpoint) handleICMP(pkt *stack.PacketBuffer, hasFragmentHeader bool, r\nreceived.invalid.Increment()\nreturn\n}\n- pkt.Data().TrimFront(header.ICMPv6PacketTooBigMinimumSize)\nnetworkMTU, err := calculateNetworkMTU(header.ICMPv6(hdr).MTU(), header.IPv6MinimumSize)\nif err != nil {\nnetworkMTU = 0\n}\n+ pkt.Data().DeleteFront(header.ICMPv6PacketTooBigMinimumSize)\ne.handleControl(&icmpv6PacketTooBigSockError{mtu: networkMTU}, pkt)\ncase header.ICMPv6DstUnreachable:\n@@ -341,8 +344,9 @@ func (e *endpoint) handleICMP(pkt *stack.PacketBuffer, hasFragmentHeader bool, r\nreceived.invalid.Increment()\nreturn\n}\n- pkt.Data().TrimFront(header.ICMPv6DstUnreachableMinimumSize)\n- switch header.ICMPv6(hdr).Code() {\n+ code := header.ICMPv6(hdr).Code()\n+ pkt.Data().DeleteFront(header.ICMPv6DstUnreachableMinimumSize)\n+ switch code {\ncase header.ICMPv6NetworkUnreachable:\ne.handleControl(&icmpv6DestinationNetworkUnreachableSockError{}, pkt)\ncase header.ICMPv6PortUnreachable:\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/packet_buffer.go", "new_path": "pkg/tcpip/stack/packet_buffer.go", "diff": "@@ -364,9 +364,10 @@ func (d PacketData) PullUp(size int) (buffer.View, bool) {\nreturn d.pk.data.PullUp(size)\n}\n-// TrimFront removes count from the beginning of d. It panics if count >\n-// d.Size().\n-func (d PacketData) TrimFront(count int) {\n+// DeleteFront removes count from the beginning of d. It panics if count >\n+// d.Size(). All backing storage references after the front of the d are\n+// invalidated.\n+func (d PacketData) DeleteFront(count int) {\nd.pk.data.TrimFront(count)\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/packet_buffer_test.go", "new_path": "pkg/tcpip/stack/packet_buffer_test.go", "diff": "@@ -397,11 +397,11 @@ func TestPacketBufferData(t *testing.T) {\n}\n})\n- // TrimFront\n+ // DeleteFront\nfor _, n := range []int{1, len(tc.data)} {\n- t.Run(fmt.Sprintf(\"TrimFront%d\", n), func(t *testing.T) {\n+ t.Run(fmt.Sprintf(\"DeleteFront%d\", n), func(t *testing.T) {\npkt := tc.makePkt(t)\n- pkt.Data().TrimFront(n)\n+ pkt.Data().DeleteFront(n)\ncheckData(t, pkt, []byte(tc.data)[n:])\n})\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/stack_test.go", "new_path": "pkg/tcpip/stack/stack_test.go", "diff": "@@ -138,11 +138,13 @@ func (f *fakeNetworkEndpoint) HandlePacket(pkt *stack.PacketBuffer) {\n// Handle control packets.\nif netHdr[protocolNumberOffset] == uint8(fakeControlProtocol) {\n- nb, ok := pkt.Data().PullUp(fakeNetHeaderLen)\n+ hdr, ok := pkt.Data().PullUp(fakeNetHeaderLen)\nif !ok {\nreturn\n}\n- pkt.Data().TrimFront(fakeNetHeaderLen)\n+ // DeleteFront invalidates slices. Make a copy before trimming.\n+ nb := append([]byte(nil), hdr...)\n+ pkt.Data().DeleteFront(fakeNetHeaderLen)\nf.dispatcher.DeliverTransportError(\ntcpip.Address(nb[srcAddrOffset:srcAddrOffset+1]),\ntcpip.Address(nb[dstAddrOffset:dstAddrOffset+1]),\n" } ]
Go
Apache License 2.0
google/gvisor
netstack: Rename pkt.Data().TrimFront() to DeleteFront(), and ... ... it may now invalidate backing slice references This is currently safe because TrimFront() in VectorisedView only shrinks the view. This may not hold under the a different buffer implementation. Reordering method calls order to allow this. PiperOrigin-RevId: 371167610
260,001
29.04.2021 13:59:39
25,200
669523f7d225006d1fbc7c6a2b347736019908e2
Remove outdated TODOs in verity
[ { "change_type": "MODIFY", "old_path": "pkg/merkletree/merkletree.go", "new_path": "pkg/merkletree/merkletree.go", "diff": "@@ -36,7 +36,6 @@ const (\n)\n// DigestSize returns the size (in bytes) of a digest.\n-// TODO(b/156980949): Allow config SHA384.\nfunc DigestSize(hashAlgorithm int) int {\nswitch hashAlgorithm {\ncase linux.FS_VERITY_HASH_ALG_SHA256:\n@@ -69,7 +68,6 @@ func InitLayout(dataSize int64, hashAlgorithms int, dataAndTreeInSameFile bool)\nblockSize: hostarch.PageSize,\n}\n- // TODO(b/156980949): Allow config SHA384.\nswitch hashAlgorithms {\ncase linux.FS_VERITY_HASH_ALG_SHA256:\nlayout.digestSize = sha256DigestSize\n@@ -429,8 +427,6 @@ func Verify(params *VerifyParams) (int64, error) {\n}\n// If this is the end of file, zero the remaining bytes in buf,\n// otherwise they are still from the previous block.\n- // TODO(b/162908070): Investigate possible issues with zero\n- // padding the data.\nif bytesRead < len(buf) {\nfor j := bytesRead; j < len(buf); j++ {\nbuf[j] = 0\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/verity/filesystem.go", "new_path": "pkg/sentry/fsimpl/verity/filesystem.go", "diff": "@@ -168,10 +168,6 @@ afterSymlink:\n// Preconditions:\n// * fs.renameMu must be locked.\n// * d.dirMu must be locked.\n-//\n-// TODO(b/166474175): Investigate all possible errors returned in this\n-// function, and make sure we differentiate all errors that indicate unexpected\n-// modifications to the file system from the ones that are not harmful.\nfunc (fs *filesystem) verifyChildLocked(ctx context.Context, parent *dentry, child *dentry) (*dentry, error) {\nvfsObj := fs.vfsfs.VirtualFilesystem()\n@@ -287,7 +283,6 @@ func (fs *filesystem) verifyChildLocked(ctx context.Context, parent *dentry, chi\nUID: parentStat.UID,\nGID: parentStat.GID,\nChildren: parent.childrenNames,\n- //TODO(b/156980949): Support passing other hash algorithms.\nHashAlgorithms: fs.alg.toLinuxHashAlg(),\nReadOffset: int64(offset),\nReadSize: int64(merkletree.DigestSize(fs.alg.toLinuxHashAlg())),\n@@ -417,7 +412,6 @@ func (fs *filesystem) verifyStatAndChildrenLocked(ctx context.Context, d *dentry\nUID: stat.UID,\nGID: stat.GID,\nChildren: d.childrenNames,\n- //TODO(b/156980949): Support passing other hash algorithms.\nHashAlgorithms: fs.alg.toLinuxHashAlg(),\nReadOffset: 0,\n// Set read size to 0 so only the metadata is verified.\n@@ -991,8 +985,6 @@ func (fs *filesystem) SetStatAt(ctx context.Context, rp *vfs.ResolvingPath, opts\n}\n// StatAt implements vfs.FilesystemImpl.StatAt.\n-// TODO(b/170157489): Investigate whether stats other than Mode/UID/GID should\n-// be verified.\nfunc (fs *filesystem) StatAt(ctx context.Context, rp *vfs.ResolvingPath, opts vfs.StatOptions) (linux.Statx, error) {\nvar ds *[]*dentry\nfs.renameMu.RLock()\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/verity/verity.go", "new_path": "pkg/sentry/fsimpl/verity/verity.go", "diff": "@@ -840,7 +840,6 @@ func (fd *fileDescription) Release(ctx context.Context) {\n// Stat implements vfs.FileDescriptionImpl.Stat.\nfunc (fd *fileDescription) Stat(ctx context.Context, opts vfs.StatOptions) (linux.Statx, error) {\n- // TODO(b/162788573): Add integrity check for metadata.\nstat, err := fd.lowerFD.Stat(ctx, opts)\nif err != nil {\nreturn linux.Statx{}, err\n@@ -963,7 +962,6 @@ func (fd *fileDescription) generateMerkleLocked(ctx context.Context) ([]byte, ui\nTreeReader: &merkleReader,\nTreeWriter: &merkleWriter,\nChildren: fd.d.childrenNames,\n- //TODO(b/156980949): Support passing other hash algorithms.\nHashAlgorithms: fd.d.fs.alg.toLinuxHashAlg(),\nName: fd.d.name,\nMode: uint32(stat.Mode),\n@@ -1192,8 +1190,6 @@ func (fd *fileDescription) Ioctl(ctx context.Context, uio usermem.IO, args arch.\ncase linux.FS_IOC_GETFLAGS:\nreturn fd.verityFlags(ctx, args[2].Pointer())\ndefault:\n- // TODO(b/169682228): Investigate which ioctl commands should\n- // be allowed.\nreturn 0, syserror.ENOSYS\n}\n}\n@@ -1262,7 +1258,6 @@ func (fd *fileDescription) PRead(ctx context.Context, dst usermem.IOSequence, of\nUID: fd.d.uid,\nGID: fd.d.gid,\nChildren: fd.d.childrenNames,\n- //TODO(b/156980949): Support passing other hash algorithms.\nHashAlgorithms: fd.d.fs.alg.toLinuxHashAlg(),\nReadOffset: offset,\nReadSize: dst.NumBytes(),\n" } ]
Go
Apache License 2.0
google/gvisor
Remove outdated TODOs in verity PiperOrigin-RevId: 371198372
259,875
29.04.2021 15:19:22
25,200
eefa00f4aecc7c72a1866357fbd1bbb58aa6fc5e
Implement epoll_pwait2.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/strace/linux64_amd64.go", "new_path": "pkg/sentry/strace/linux64_amd64.go", "diff": "@@ -371,6 +371,7 @@ var linuxAMD64 = SyscallMap{\n433: makeSyscallInfo(\"fspick\", FD, Path, Hex),\n434: makeSyscallInfo(\"pidfd_open\", Hex, Hex),\n435: makeSyscallInfo(\"clone3\", Hex, Hex),\n+ 441: makeSyscallInfo(\"epoll_pwait2\", FD, EpollEvents, Hex, Timespec, SigSet),\n}\nfunc init() {\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/strace/linux64_arm64.go", "new_path": "pkg/sentry/strace/linux64_arm64.go", "diff": "@@ -312,6 +312,7 @@ var linuxARM64 = SyscallMap{\n433: makeSyscallInfo(\"fspick\", FD, Path, Hex),\n434: makeSyscallInfo(\"pidfd_open\", Hex, Hex),\n435: makeSyscallInfo(\"clone3\", Hex, Hex),\n+ 441: makeSyscallInfo(\"epoll_pwait2\", FD, EpollEvents, Hex, Timespec, SigSet),\n}\nfunc init() {\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/epoll.go", "new_path": "pkg/sentry/syscalls/epoll.go", "diff": "@@ -119,7 +119,7 @@ func RemoveEpoll(t *kernel.Task, epfd int32, fd int32) error {\n}\n// WaitEpoll implements the epoll_wait(2) linux syscall.\n-func WaitEpoll(t *kernel.Task, fd int32, max int, timeout int) ([]linux.EpollEvent, error) {\n+func WaitEpoll(t *kernel.Task, fd int32, max int, timeoutInNanos int64) ([]linux.EpollEvent, error) {\n// Get epoll from the file descriptor.\nepollfile := t.GetFile(fd)\nif epollfile == nil {\n@@ -136,7 +136,7 @@ func WaitEpoll(t *kernel.Task, fd int32, max int, timeout int) ([]linux.EpollEve\n// Try to read events and return right away if we got them or if the\n// caller requested a non-blocking \"wait\".\nr := e.ReadEvents(max)\n- if len(r) != 0 || timeout == 0 {\n+ if len(r) != 0 || timeoutInNanos == 0 {\nreturn r, nil\n}\n@@ -144,8 +144,8 @@ func WaitEpoll(t *kernel.Task, fd int32, max int, timeout int) ([]linux.EpollEve\n// and register with the epoll object for readability events.\nvar haveDeadline bool\nvar deadline ktime.Time\n- if timeout > 0 {\n- timeoutDur := time.Duration(timeout) * time.Millisecond\n+ if timeoutInNanos > 0 {\n+ timeoutDur := time.Duration(timeoutInNanos) * time.Nanosecond\ndeadline = t.Kernel().MonotonicClock().Now().Add(timeoutDur)\nhaveDeadline = true\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/linux64.go", "new_path": "pkg/sentry/syscalls/linux/linux64.go", "diff": "@@ -404,6 +404,7 @@ var AMD64 = &kernel.SyscallTable{\n433: syscalls.ErrorWithEvent(\"fspick\", syserror.ENOSYS, \"\", nil),\n434: syscalls.ErrorWithEvent(\"pidfd_open\", syserror.ENOSYS, \"\", nil),\n435: syscalls.ErrorWithEvent(\"clone3\", syserror.ENOSYS, \"\", nil),\n+ 441: syscalls.Supported(\"epoll_pwait2\", EpollPwait2),\n},\nEmulate: map[hostarch.Addr]uintptr{\n0xffffffffff600000: 96, // vsyscall gettimeofday(2)\n@@ -722,6 +723,7 @@ var ARM64 = &kernel.SyscallTable{\n433: syscalls.ErrorWithEvent(\"fspick\", syserror.ENOSYS, \"\", nil),\n434: syscalls.ErrorWithEvent(\"pidfd_open\", syserror.ENOSYS, \"\", nil),\n435: syscalls.ErrorWithEvent(\"clone3\", syserror.ENOSYS, \"\", nil),\n+ 441: syscalls.Supported(\"epoll_pwait2\", EpollPwait2),\n},\nEmulate: map[hostarch.Addr]uintptr{},\nMissing: func(t *kernel.Task, sysno uintptr, args arch.SyscallArguments) (uintptr, error) {\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/sys_epoll.go", "new_path": "pkg/sentry/syscalls/linux/sys_epoll.go", "diff": "@@ -16,6 +16,7 @@ package linux\nimport (\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/hostarch\"\n\"gvisor.dev/gvisor/pkg/sentry/arch\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/epoll\"\n@@ -104,14 +105,8 @@ func EpollCtl(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sysc\n}\n}\n-// EpollWait implements the epoll_wait(2) linux syscall.\n-func EpollWait(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {\n- epfd := args[0].Int()\n- eventsAddr := args[1].Pointer()\n- maxEvents := int(args[2].Int())\n- timeout := int(args[3].Int())\n-\n- r, err := syscalls.WaitEpoll(t, epfd, maxEvents, timeout)\n+func waitEpoll(t *kernel.Task, fd int32, eventsAddr hostarch.Addr, max int, timeoutInNanos int64) (uintptr, *kernel.SyscallControl, error) {\n+ r, err := syscalls.WaitEpoll(t, fd, max, timeoutInNanos)\nif err != nil {\nreturn 0, nil, syserror.ConvertIntr(err, syserror.EINTR)\n}\n@@ -123,6 +118,17 @@ func EpollWait(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sys\n}\nreturn uintptr(len(r)), nil, nil\n+\n+}\n+\n+// EpollWait implements the epoll_wait(2) linux syscall.\n+func EpollWait(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {\n+ epfd := args[0].Int()\n+ eventsAddr := args[1].Pointer()\n+ maxEvents := int(args[2].Int())\n+ // Convert milliseconds to nanoseconds.\n+ timeoutInNanos := int64(args[3].Int()) * 1000000\n+ return waitEpoll(t, epfd, eventsAddr, maxEvents, timeoutInNanos)\n}\n// EpollPwait implements the epoll_pwait(2) linux syscall.\n@@ -144,4 +150,38 @@ func EpollPwait(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sy\nreturn EpollWait(t, args)\n}\n+// EpollPwait2 implements the epoll_pwait(2) linux syscall.\n+func EpollPwait2(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {\n+ epfd := args[0].Int()\n+ eventsAddr := args[1].Pointer()\n+ maxEvents := int(args[2].Int())\n+ timeoutPtr := args[3].Pointer()\n+ maskAddr := args[4].Pointer()\n+ maskSize := uint(args[5].Uint())\n+ haveTimeout := timeoutPtr != 0\n+\n+ var timeoutInNanos int64 = -1\n+ if haveTimeout {\n+ timeout, err := copyTimespecIn(t, timeoutPtr)\n+ if err != nil {\n+ return 0, nil, err\n+ }\n+ timeoutInNanos = timeout.ToNsec()\n+\n+ }\n+\n+ if maskAddr != 0 {\n+ mask, err := CopyInSigSet(t, maskAddr, maskSize)\n+ if err != nil {\n+ return 0, nil, err\n+ }\n+\n+ oldmask := t.SignalMask()\n+ t.SetSignalMask(mask)\n+ t.SetSavedSignalMask(oldmask)\n+ }\n+\n+ return waitEpoll(t, epfd, eventsAddr, maxEvents, timeoutInNanos)\n+}\n+\n// LINT.ThenChange(vfs2/epoll.go)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/vfs2/epoll.go", "new_path": "pkg/sentry/syscalls/linux/vfs2/epoll.go", "diff": "@@ -19,6 +19,7 @@ import (\n\"time\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/hostarch\"\n\"gvisor.dev/gvisor/pkg/sentry/arch\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\nktime \"gvisor.dev/gvisor/pkg/sentry/kernel/time\"\n@@ -118,13 +119,7 @@ func EpollCtl(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sysc\n}\n}\n-// EpollWait implements Linux syscall epoll_wait(2).\n-func EpollWait(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {\n- epfd := args[0].Int()\n- eventsAddr := args[1].Pointer()\n- maxEvents := int(args[2].Int())\n- timeout := int(args[3].Int())\n-\n+func waitEpoll(t *kernel.Task, epfd int32, eventsAddr hostarch.Addr, maxEvents int, timeoutInNanos int64) (uintptr, *kernel.SyscallControl, error) {\nvar _EP_MAX_EVENTS = math.MaxInt32 / sizeofEpollEvent // Linux: fs/eventpoll.c:EP_MAX_EVENTS\nif maxEvents <= 0 || maxEvents > _EP_MAX_EVENTS {\nreturn 0, nil, syserror.EINVAL\n@@ -158,7 +153,7 @@ func EpollWait(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sys\n}\nreturn 0, nil, err\n}\n- if timeout == 0 {\n+ if timeoutInNanos == 0 {\nreturn 0, nil, nil\n}\n// In the first iteration of this loop, register with the epoll\n@@ -173,8 +168,8 @@ func EpollWait(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sys\ndefer epfile.EventUnregister(&w)\n} else {\n// Set up the timer if a timeout was specified.\n- if timeout > 0 && !haveDeadline {\n- timeoutDur := time.Duration(timeout) * time.Millisecond\n+ if timeoutInNanos > 0 && !haveDeadline {\n+ timeoutDur := time.Duration(timeoutInNanos) * time.Nanosecond\ndeadline = t.Kernel().MonotonicClock().Now().Add(timeoutDur)\nhaveDeadline = true\n}\n@@ -186,6 +181,17 @@ func EpollWait(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sys\n}\n}\n}\n+\n+}\n+\n+// EpollWait implements Linux syscall epoll_wait(2).\n+func EpollWait(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {\n+ epfd := args[0].Int()\n+ eventsAddr := args[1].Pointer()\n+ maxEvents := int(args[2].Int())\n+ timeoutInNanos := int64(args[3].Int()) * 1000000\n+\n+ return waitEpoll(t, epfd, eventsAddr, maxEvents, timeoutInNanos)\n}\n// EpollPwait implements Linux syscall epoll_pwait(2).\n@@ -199,3 +205,29 @@ func EpollPwait(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sy\nreturn EpollWait(t, args)\n}\n+\n+// EpollPwait2 implements Linux syscall epoll_pwait(2).\n+func EpollPwait2(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {\n+ epfd := args[0].Int()\n+ eventsAddr := args[1].Pointer()\n+ maxEvents := int(args[2].Int())\n+ timeoutPtr := args[3].Pointer()\n+ maskAddr := args[4].Pointer()\n+ maskSize := uint(args[5].Uint())\n+ haveTimeout := timeoutPtr != 0\n+\n+ var timeoutInNanos int64 = -1\n+ if haveTimeout {\n+ var timeout linux.Timespec\n+ if _, err := timeout.CopyIn(t, timeoutPtr); err != nil {\n+ return 0, nil, err\n+ }\n+ timeoutInNanos = timeout.ToNsec()\n+ }\n+\n+ if err := setTempSignalSet(t, maskAddr, maskSize); err != nil {\n+ return 0, nil, err\n+ }\n+\n+ return waitEpoll(t, epfd, eventsAddr, maxEvents, timeoutInNanos)\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/vfs2/vfs2.go", "new_path": "pkg/sentry/syscalls/linux/vfs2/vfs2.go", "diff": "@@ -159,6 +159,7 @@ func Override() {\ns.Table[327] = syscalls.Supported(\"preadv2\", Preadv2)\ns.Table[328] = syscalls.Supported(\"pwritev2\", Pwritev2)\ns.Table[332] = syscalls.Supported(\"statx\", Statx)\n+ s.Table[441] = syscalls.Supported(\"epoll_pwait2\", EpollPwait2)\ns.Init()\n// Override ARM64.\n@@ -269,6 +270,7 @@ func Override() {\ns.Table[286] = syscalls.Supported(\"preadv2\", Preadv2)\ns.Table[287] = syscalls.Supported(\"pwritev2\", Pwritev2)\ns.Table[291] = syscalls.Supported(\"statx\", Statx)\n+ s.Table[441] = syscalls.Supported(\"epoll_pwait2\", EpollPwait2)\ns.Init()\n}\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/epoll.cc", "new_path": "test/syscalls/linux/epoll.cc", "diff": "@@ -39,6 +39,15 @@ namespace {\nconstexpr int kFDsPerEpoll = 3;\nconstexpr uint64_t kMagicConstant = 0x0102030405060708;\n+#ifndef SYS_epoll_pwait2\n+#define SYS_epoll_pwait2 441\n+#endif\n+\n+int epoll_pwait2(int fd, struct epoll_event* events, int maxevents,\n+ const struct timespec* timeout, const sigset_t* sigset) {\n+ return syscall(SYS_epoll_pwait2, fd, events, maxevents, timeout, sigset);\n+}\n+\nTEST(EpollTest, AllWritable) {\nauto epollfd = ASSERT_NO_ERRNO_AND_VALUE(NewEpollFD());\nstd::vector<FileDescriptor> eventfds;\n@@ -144,6 +153,50 @@ TEST(EpollTest, Timeout) {\nEXPECT_GT(ms_elapsed(begin, end), kTimeoutMs - 1);\n}\n+TEST(EpollTest, EpollPwait2Timeout) {\n+ auto epollfd = ASSERT_NO_ERRNO_AND_VALUE(NewEpollFD());\n+ // 200 milliseconds.\n+ constexpr int kTimeoutNs = 200000000;\n+ struct timespec timeout;\n+ timeout.tv_sec = 0;\n+ timeout.tv_nsec = 0;\n+ struct timespec begin;\n+ struct timespec end;\n+ struct epoll_event result[kFDsPerEpoll];\n+\n+ std::vector<FileDescriptor> eventfds;\n+ for (int i = 0; i < kFDsPerEpoll; i++) {\n+ eventfds.push_back(ASSERT_NO_ERRNO_AND_VALUE(NewEventFD()));\n+ ASSERT_NO_ERRNO(RegisterEpollFD(epollfd.get(), eventfds[i].get(), EPOLLIN,\n+ kMagicConstant + i));\n+ }\n+\n+ // Pass valid arguments so that the syscall won't be blocked indefinitely\n+ // nor return errno EINVAL.\n+ //\n+ // The syscall returns immediately when timeout is zero,\n+ // even if no events are available.\n+ SKIP_IF(!IsRunningOnGvisor() &&\n+ epoll_pwait2(epollfd.get(), result, kFDsPerEpoll, &timeout, nullptr) <\n+ 0 &&\n+ errno == ENOSYS);\n+\n+ {\n+ const DisableSave ds; // Timing-related.\n+ EXPECT_THAT(clock_gettime(CLOCK_MONOTONIC, &begin), SyscallSucceeds());\n+\n+ timeout.tv_nsec = kTimeoutNs;\n+ ASSERT_THAT(RetryEINTR(epoll_pwait2)(epollfd.get(), result, kFDsPerEpoll,\n+ &timeout, nullptr),\n+ SyscallSucceedsWithValue(0));\n+ EXPECT_THAT(clock_gettime(CLOCK_MONOTONIC, &end), SyscallSucceeds());\n+ }\n+\n+ // Check the lower bound on the timeout. Checking for an upper bound is\n+ // fragile because Linux can overrun the timeout due to scheduling delays.\n+ EXPECT_GT(ns_elapsed(begin, end), kTimeoutNs - 1);\n+}\n+\nvoid* writer(void* arg) {\nint fd = *reinterpret_cast<int*>(arg);\nuint64_t tmp = 1;\n" }, { "change_type": "MODIFY", "old_path": "test/util/test_util.h", "new_path": "test/util/test_util.h", "diff": "@@ -272,10 +272,15 @@ PosixErrorOr<std::vector<OpenFd>> GetOpenFDs();\n// Returns the number of hard links to a path.\nPosixErrorOr<uint64_t> Links(const std::string& path);\n+inline uint64_t ns_elapsed(const struct timespec& begin,\n+ const struct timespec& end) {\n+ return (end.tv_sec - begin.tv_sec) * 1000000000 +\n+ (end.tv_nsec - begin.tv_nsec);\n+}\n+\ninline uint64_t ms_elapsed(const struct timespec& begin,\nconst struct timespec& end) {\n- return (end.tv_sec - begin.tv_sec) * 1000 +\n- (end.tv_nsec - begin.tv_nsec) / 1000000;\n+ return ns_elapsed(begin, end) / 1000000;\n}\nnamespace internal {\n" } ]
Go
Apache License 2.0
google/gvisor
Implement epoll_pwait2. PiperOrigin-RevId: 371216407
259,992
29.04.2021 16:40:57
25,200
c958c5a4f103725ddbb87f6db66cca9beb06cb84
Fix up TODOs in the code
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/forwarding_test.go", "new_path": "pkg/tcpip/stack/forwarding_test.go", "diff": "@@ -101,7 +101,7 @@ func (f *fwdTestNetworkEndpoint) HandlePacket(pkt *PacketBuffer) {\nReserveHeaderBytes: int(r.MaxHeaderLength()),\nData: vv.ToView().ToVectorisedView(),\n})\n- // TODO(b/143425874) Decrease the TTL field in forwarded packets.\n+ // TODO(gvisor.dev/issue/1085) Decrease the TTL field in forwarded packets.\n_ = r.WriteHeaderIncludedPacket(pkt)\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/icmp/endpoint.go", "new_path": "pkg/tcpip/transport/icmp/endpoint.go", "diff": "@@ -747,8 +747,8 @@ func (e *endpoint) HandlePacket(id stack.TransportEndpointID, pkt *stack.PacketB\nswitch e.NetProto {\ncase header.IPv4ProtocolNumber:\nh := header.ICMPv4(pkt.TransportHeader().View())\n- // TODO(b/129292233): Determine if len(h) check is still needed after early\n- // parsing.\n+ // TODO(gvisor.dev/issue/170): Determine if len(h) check is still needed\n+ // after early parsing.\nif len(h) < header.ICMPv4MinimumSize || h.Type() != header.ICMPv4EchoReply {\ne.stack.Stats().DroppedPackets.Increment()\ne.stats.ReceiveErrors.MalformedPacketsReceived.Increment()\n@@ -756,8 +756,8 @@ func (e *endpoint) HandlePacket(id stack.TransportEndpointID, pkt *stack.PacketB\n}\ncase header.IPv6ProtocolNumber:\nh := header.ICMPv6(pkt.TransportHeader().View())\n- // TODO(b/129292233): Determine if len(h) check is still needed after early\n- // parsing.\n+ // TODO(gvisor.dev/issue/170): Determine if len(h) check is still needed\n+ // after early parsing.\nif len(h) < header.ICMPv6MinimumSize || h.Type() != header.ICMPv6EchoReply {\ne.stack.Stats().DroppedPackets.Increment()\ne.stats.ReceiveErrors.MalformedPacketsReceived.Increment()\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/xattr.cc", "new_path": "test/syscalls/linux/xattr.cc", "diff": "@@ -632,7 +632,7 @@ TEST_F(XattrTest, TrustedNamespaceWithCapSysAdmin) {\n// Trusted namespace not supported in VFS1.\nSKIP_IF(IsRunningWithVFS1());\n- // TODO(b/66162845): Only gVisor tmpfs currently supports trusted namespace.\n+ // TODO(b/166162845): Only gVisor tmpfs currently supports trusted namespace.\nSKIP_IF(IsRunningOnGvisor() &&\n!ASSERT_NO_ERRNO_AND_VALUE(IsTmpfs(test_file_name_)));\n" } ]
Go
Apache License 2.0
google/gvisor
Fix up TODOs in the code PiperOrigin-RevId: 371231148
260,001
30.04.2021 13:25:00
25,200
ea89cd38a11fc63b3ff397c9f5901fa541c8acb4
Do not return content if verity translate fails If verification fails for translating mmapped memory, the content should not be returned. This is not an issue for panic mode, but for error mode we should return empty content along with the error.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/verity/verity.go", "new_path": "pkg/sentry/fsimpl/verity/verity.go", "diff": "@@ -1328,7 +1328,7 @@ func (fd *fileDescription) TestPOSIX(ctx context.Context, uid fslock.UniqueID, t\nfunc (fd *fileDescription) Translate(ctx context.Context, required, optional memmap.MappableRange, at hostarch.AccessType) ([]memmap.Translation, error) {\nts, err := fd.lowerMappable.Translate(ctx, required, optional, at)\nif err != nil {\n- return ts, err\n+ return nil, err\n}\n// dataSize is the size of the whole file.\n@@ -1341,17 +1341,17 @@ func (fd *fileDescription) Translate(ctx context.Context, required, optional mem\n// contains the expected xattrs. If the xattr does not exist, it\n// indicates unexpected modifications to the file system.\nif err == syserror.ENODATA {\n- return ts, fd.d.fs.alertIntegrityViolation(fmt.Sprintf(\"Failed to get xattr %s: %v\", merkleSizeXattr, err))\n+ return nil, fd.d.fs.alertIntegrityViolation(fmt.Sprintf(\"Failed to get xattr %s: %v\", merkleSizeXattr, err))\n}\nif err != nil {\n- return ts, err\n+ return nil, err\n}\n// The dataSize xattr should be an integer. If it's not, it indicates\n// unexpected modifications to the file system.\nsize, err := strconv.Atoi(dataSize)\nif err != nil {\n- return ts, fd.d.fs.alertIntegrityViolation(fmt.Sprintf(\"Failed to convert xattr %s to int: %v\", merkleSizeXattr, err))\n+ return nil, fd.d.fs.alertIntegrityViolation(fmt.Sprintf(\"Failed to convert xattr %s to int: %v\", merkleSizeXattr, err))\n}\nmerkleReader := FileReadWriteSeeker{\n@@ -1384,7 +1384,7 @@ func (fd *fileDescription) Translate(ctx context.Context, required, optional mem\nDataAndTreeInSameFile: false,\n})\nif err != nil {\n- return ts, fd.d.fs.alertIntegrityViolation(fmt.Sprintf(\"Verification failed: %v\", err))\n+ return nil, fd.d.fs.alertIntegrityViolation(fmt.Sprintf(\"Verification failed: %v\", err))\n}\n}\nreturn ts, err\n" } ]
Go
Apache License 2.0
google/gvisor
Do not return content if verity translate fails If verification fails for translating mmapped memory, the content should not be returned. This is not an issue for panic mode, but for error mode we should return empty content along with the error. PiperOrigin-RevId: 371393519
260,004
30.04.2021 17:03:25
25,200
eb2b39f70287b2ee54127699fa34a06484aaed8b
Comment ip package in a single place Fixes the below linting error: ``` From Golint: > Package ip has package comment defined in multiple places: > duplicate_address_detection.go > generic_multicast_protocol.go ```
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/internal/ip/generic_multicast_protocol.go", "new_path": "pkg/tcpip/network/internal/ip/generic_multicast_protocol.go", "diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-// Package ip holds IPv4/IPv6 common utilities.\npackage ip\nimport (\n" } ]
Go
Apache License 2.0
google/gvisor
Comment ip package in a single place Fixes the below linting error: ``` From Golint: > Package ip has package comment defined in multiple places: > duplicate_address_detection.go > generic_multicast_protocol.go ``` PiperOrigin-RevId: 371430486
259,891
30.04.2021 17:55:54
25,200
6fb8c01bb488e22c741a307e030b61c512dcd34f
Fix //test/syscalls:tcp_socket_test_native The data written was larger than the write buffer, and nobody was reading the other end.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/BUILD", "new_path": "test/syscalls/linux/BUILD", "diff": "@@ -3710,6 +3710,7 @@ cc_binary(\ndeps = [\n\":socket_test_util\",\n\"//test/util:file_descriptor\",\n+ \"@com_google_absl//absl/strings\",\n\"@com_google_absl//absl/time\",\ngtest,\n\"//test/util:posix_error\",\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/tcp_socket.cc", "new_path": "test/syscalls/linux/tcp_socket.cc", "diff": "#include <vector>\n#include \"gtest/gtest.h\"\n+#include \"absl/strings/str_split.h\"\n#include \"absl/time/clock.h\"\n#include \"absl/time/time.h\"\n#include \"test/syscalls/linux/socket_test_util.h\"\n@@ -1144,6 +1145,17 @@ TEST_P(SimpleTcpSocketTest, SelfConnectSendRecv) {\n}\nTEST_P(SimpleTcpSocketTest, SelfConnectSend) {\n+ // Ensure the write size is not larger than the write buffer.\n+ size_t write_size = 512 << 10; // 512 KiB.\n+ constexpr char kWMem[] = \"/proc/sys/net/ipv4/tcp_wmem\";\n+ std::string wmem = ASSERT_NO_ERRNO_AND_VALUE(GetContents(kWMem));\n+ std::vector<std::string> vals = absl::StrSplit(wmem, absl::ByAnyChar(\"\\t \"));\n+ size_t max_wmem;\n+ ASSERT_TRUE(absl::SimpleAtoi(vals.back(), &max_wmem));\n+ if (write_size > max_wmem) {\n+ write_size = max_wmem;\n+ }\n+\n// Initialize address to the loopback one.\nsockaddr_storage addr =\nASSERT_NO_ERRNO_AND_VALUE(InetLoopbackAddr(GetParam()));\n@@ -1164,7 +1176,7 @@ TEST_P(SimpleTcpSocketTest, SelfConnectSend) {\nASSERT_THAT(RetryEINTR(connect)(s.get(), AsSockAddr(&addr), addrlen),\nSyscallSucceeds());\n- std::vector<char> writebuf(512 << 10); // 512 KiB.\n+ std::vector<char> writebuf(write_size);\n// Try to send the whole thing.\nint n;\n" } ]
Go
Apache License 2.0
google/gvisor
Fix //test/syscalls:tcp_socket_test_native The data written was larger than the write buffer, and nobody was reading the other end. PiperOrigin-RevId: 371436084
259,992
03.05.2021 13:47:45
25,200
1947c873423cabcaf5e67b667542421ade7414ff
Fix deadlock in /proc/[pid]/fd/[num] In order to resolve path names, fsSymlink.Readlink() may need to reenter kernfs. Change the code so that kernfs.Inode.Readlink() is called without locks and document the new contract.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/kernfs/filesystem.go", "new_path": "pkg/sentry/fsimpl/kernfs/filesystem.go", "diff": "@@ -612,16 +612,24 @@ afterTrailingSymlink:\n// ReadlinkAt implements vfs.FilesystemImpl.ReadlinkAt.\nfunc (fs *Filesystem) ReadlinkAt(ctx context.Context, rp *vfs.ResolvingPath) (string, error) {\n- fs.mu.RLock()\ndefer fs.processDeferredDecRefs(ctx)\n- defer fs.mu.RUnlock()\n+\n+ fs.mu.RLock()\nd, err := fs.walkExistingLocked(ctx, rp)\nif err != nil {\n+ fs.mu.RUnlock()\nreturn \"\", err\n}\nif !d.isSymlink() {\n+ fs.mu.RUnlock()\nreturn \"\", syserror.EINVAL\n}\n+\n+ // Inode.Readlink() cannot be called holding fs locks.\n+ d.IncRef()\n+ defer d.DecRef(ctx)\n+ fs.mu.RUnlock()\n+\nreturn d.inode.Readlink(ctx, rp.Mount())\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/kernfs/kernfs.go", "new_path": "pkg/sentry/fsimpl/kernfs/kernfs.go", "diff": "@@ -534,6 +534,9 @@ func (d *Dentry) FSLocalPath() string {\n// - Checking that dentries passed to methods are of the appropriate file type.\n// - Checking permissions.\n//\n+// Inode functions may be called holding filesystem wide locks and are not\n+// allowed to call vfs functions that may reenter, unless otherwise noted.\n+//\n// Specific responsibilities of implementations are documented below.\ntype Inode interface {\n// Methods related to reference counting. A generic implementation is\n@@ -680,6 +683,9 @@ type inodeDirectory interface {\ntype inodeSymlink interface {\n// Readlink returns the target of a symbolic link. If an inode is not a\n// symlink, the implementation should return EINVAL.\n+ //\n+ // Readlink is called with no kernfs locks held, so it may reenter if needed\n+ // to resolve symlink targets.\nReadlink(ctx context.Context, mnt *vfs.Mount) (string, error)\n// Getlink returns the target of a symbolic link, as used by path\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/proc/task_fds.go", "new_path": "pkg/sentry/fsimpl/proc/task_fds.go", "diff": "@@ -221,6 +221,8 @@ func (s *fdSymlink) Readlink(ctx context.Context, _ *vfs.Mount) (string, error)\ndefer file.DecRef(ctx)\nroot := vfs.RootFromContext(ctx)\ndefer root.DecRef(ctx)\n+\n+ // Note: it's safe to reenter kernfs from Readlink if needed to resolve path.\nreturn s.task.Kernel().VFS().PathnameWithDeleted(ctx, root, file.VirtualDentry())\n}\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/proc.cc", "new_path": "test/syscalls/linux/proc.cc", "diff": "@@ -2698,6 +2698,14 @@ TEST(Proc, Statfs) {\nEXPECT_EQ(st.f_namelen, NAME_MAX);\n}\n+// Tests that /proc/[pid]/fd/[num] can resolve to a path inside /proc.\n+TEST(Proc, ResolveSymlinkToProc) {\n+ const auto proc = ASSERT_NO_ERRNO_AND_VALUE(Open(\"/proc/self/cmdline\", 0));\n+ const auto path = JoinPath(\"/proc/self/fd/\", absl::StrCat(proc.get()));\n+ const auto target = ASSERT_NO_ERRNO_AND_VALUE(ReadLink(path));\n+ EXPECT_EQ(target, JoinPath(\"/proc/\", absl::StrCat(getpid()), \"/cmdline\"));\n+}\n+\n} // namespace\n} // namespace testing\n} // namespace gvisor\n" } ]
Go
Apache License 2.0
google/gvisor
Fix deadlock in /proc/[pid]/fd/[num] In order to resolve path names, fsSymlink.Readlink() may need to reenter kernfs. Change the code so that kernfs.Inode.Readlink() is called without locks and document the new contract. PiperOrigin-RevId: 371770222
259,860
03.05.2021 14:20:19
25,200
1d92396aaa958d171ee83933612c8d156f427d4a
Temporarily disable atime/mtime check in utimensat test.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/utimes.cc", "new_path": "test/syscalls/linux/utimes.cc", "diff": "@@ -225,7 +225,8 @@ void TestUtimensat(int dirFd, std::string const& path) {\nEXPECT_GE(mtime3, before);\nEXPECT_LE(mtime3, after);\n- EXPECT_EQ(atime3, mtime3);\n+ // TODO(b/187074006): atime/mtime may differ with local_gofer_uncached.\n+ // EXPECT_EQ(atime3, mtime3);\n}\nTEST(UtimensatTest, OnAbsPath) {\n" } ]
Go
Apache License 2.0
google/gvisor
Temporarily disable atime/mtime check in utimensat test. PiperOrigin-RevId: 371776583
260,003
03.05.2021 16:31:19
25,200
4218ba6fb4282b4466ddda05c2ea1ffec837e079
netstack: Add a test for mixed Push/Consume Not really designed to be used this way, but it works and it's been relied upon. Add a test.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/packet_buffer_test.go", "new_path": "pkg/tcpip/stack/packet_buffer_test.go", "diff": "@@ -112,23 +112,13 @@ func TestPacketHeaderPush(t *testing.T) {\nif got, want := pk.Size(), allHdrSize+len(test.data); got != want {\nt.Errorf(\"After pk.Size() = %d, want %d\", got, want)\n}\n- checkData(t, pk, test.data)\n- checkViewEqual(t, \"After pk.Views()\", concatViews(pk.Views()...),\n- concatViews(test.link, test.network, test.transport, test.data))\n- // Check the after values for each header.\n- checkPacketHeader(t, \"After pk.LinkHeader\", pk.LinkHeader(), test.link)\n- checkPacketHeader(t, \"After pk.NetworkHeader\", pk.NetworkHeader(), test.network)\n- checkPacketHeader(t, \"After pk.TransportHeader\", pk.TransportHeader(), test.transport)\n- // Check the after values for PayloadSince.\n- checkViewEqual(t, \"After PayloadSince(LinkHeader)\",\n- PayloadSince(pk.LinkHeader()),\n- concatViews(test.link, test.network, test.transport, test.data))\n- checkViewEqual(t, \"After PayloadSince(NetworkHeader)\",\n- PayloadSince(pk.NetworkHeader()),\n- concatViews(test.network, test.transport, test.data))\n- checkViewEqual(t, \"After PayloadSince(TransportHeader)\",\n- PayloadSince(pk.TransportHeader()),\n- concatViews(test.transport, test.data))\n+ // Check the after state.\n+ checkPacketContents(t, \"After \", pk, packetContents{\n+ link: test.link,\n+ network: test.network,\n+ transport: test.transport,\n+ data: test.data,\n+ })\n})\n}\n}\n@@ -199,29 +189,13 @@ func TestPacketHeaderConsume(t *testing.T) {\nif got, want := pk.Size(), len(test.data); got != want {\nt.Errorf(\"After pk.Size() = %d, want %d\", got, want)\n}\n- // After state of pk.\n- var (\n- link = test.data[:test.link]\n- network = test.data[test.link:][:test.network]\n- transport = test.data[test.link+test.network:][:test.transport]\n- payload = test.data[allHdrSize:]\n- )\n- checkData(t, pk, payload)\n- checkViewEqual(t, \"After pk.Views()\", concatViews(pk.Views()...), test.data)\n- // Check the after values for each header.\n- checkPacketHeader(t, \"After pk.LinkHeader\", pk.LinkHeader(), link)\n- checkPacketHeader(t, \"After pk.NetworkHeader\", pk.NetworkHeader(), network)\n- checkPacketHeader(t, \"After pk.TransportHeader\", pk.TransportHeader(), transport)\n- // Check the after values for PayloadSince.\n- checkViewEqual(t, \"After PayloadSince(LinkHeader)\",\n- PayloadSince(pk.LinkHeader()),\n- concatViews(link, network, transport, payload))\n- checkViewEqual(t, \"After PayloadSince(NetworkHeader)\",\n- PayloadSince(pk.NetworkHeader()),\n- concatViews(network, transport, payload))\n- checkViewEqual(t, \"After PayloadSince(TransportHeader)\",\n- PayloadSince(pk.TransportHeader()),\n- concatViews(transport, payload))\n+ // Check the after state of pk.\n+ checkPacketContents(t, \"After \", pk, packetContents{\n+ link: test.data[:test.link],\n+ network: test.data[test.link:][:test.network],\n+ transport: test.data[test.link+test.network:][:test.transport],\n+ data: test.data[allHdrSize:],\n+ })\n})\n}\n}\n@@ -252,6 +226,39 @@ func TestPacketHeaderConsumeDataTooShort(t *testing.T) {\n})\n}\n+// This is a very obscure use-case seen in the code that verifies packets\n+// before sending them out. It tries to parse the headers to verify.\n+// PacketHeader was initially not designed to mix Push() and Consume(), but it\n+// works and it's been relied upon. Include a test here.\n+func TestPacketHeaderPushConsumeMixed(t *testing.T) {\n+ link := makeView(10)\n+ network := makeView(20)\n+ data := makeView(30)\n+\n+ initData := append([]byte(nil), network...)\n+ initData = append(initData, data...)\n+ pk := NewPacketBuffer(PacketBufferOptions{\n+ ReserveHeaderBytes: len(link),\n+ Data: buffer.NewViewFromBytes(initData).ToVectorisedView(),\n+ })\n+\n+ // 1. Consume network header\n+ gotNetwork, ok := pk.NetworkHeader().Consume(len(network))\n+ if !ok {\n+ t.Fatalf(\"pk.NetworkHeader().Consume(%d) = _, false; want _, true\", len(network))\n+ }\n+ checkViewEqual(t, \"gotNetwork\", gotNetwork, network)\n+\n+ // 2. Push link header\n+ copy(pk.LinkHeader().Push(len(link)), link)\n+\n+ checkPacketContents(t, \"\" /* prefix */, pk, packetContents{\n+ link: link,\n+ network: network,\n+ data: data,\n+ })\n+}\n+\nfunc TestPacketHeaderPushCalledAtMostOnce(t *testing.T) {\nconst headerSize = 10\n@@ -494,6 +501,37 @@ func TestPacketBufferData(t *testing.T) {\n}\n}\n+type packetContents struct {\n+ link buffer.View\n+ network buffer.View\n+ transport buffer.View\n+ data buffer.View\n+}\n+\n+func checkPacketContents(t *testing.T, prefix string, pk *PacketBuffer, want packetContents) {\n+ t.Helper()\n+ // Headers.\n+ checkPacketHeader(t, prefix+\"pk.LinkHeader\", pk.LinkHeader(), want.link)\n+ checkPacketHeader(t, prefix+\"pk.NetworkHeader\", pk.NetworkHeader(), want.network)\n+ checkPacketHeader(t, prefix+\"pk.TransportHeader\", pk.TransportHeader(), want.transport)\n+ // Data.\n+ checkData(t, pk, want.data)\n+ // Whole packet.\n+ checkViewEqual(t, prefix+\"pk.Views()\",\n+ concatViews(pk.Views()...),\n+ concatViews(want.link, want.network, want.transport, want.data))\n+ // PayloadSince.\n+ checkViewEqual(t, prefix+\"PayloadSince(LinkHeader)\",\n+ PayloadSince(pk.LinkHeader()),\n+ concatViews(want.link, want.network, want.transport, want.data))\n+ checkViewEqual(t, prefix+\"PayloadSince(NetworkHeader)\",\n+ PayloadSince(pk.NetworkHeader()),\n+ concatViews(want.network, want.transport, want.data))\n+ checkViewEqual(t, prefix+\"PayloadSince(TransportHeader)\",\n+ PayloadSince(pk.TransportHeader()),\n+ concatViews(want.transport, want.data))\n+}\n+\nfunc checkInitialPacketBuffer(t *testing.T, pk *PacketBuffer, opts PacketBufferOptions) {\nt.Helper()\nreserved := opts.ReserveHeaderBytes\n@@ -510,19 +548,9 @@ func checkInitialPacketBuffer(t *testing.T, pk *PacketBuffer, opts PacketBufferO\nif got, want := pk.Size(), len(data); got != want {\nt.Errorf(\"Initial pk.Size() = %d, want %d\", got, want)\n}\n- checkData(t, pk, data)\n- checkViewEqual(t, \"Initial pk.Views()\", concatViews(pk.Views()...), data)\n- // Check the initial values for each header.\n- checkPacketHeader(t, \"Initial pk.LinkHeader\", pk.LinkHeader(), nil)\n- checkPacketHeader(t, \"Initial pk.NetworkHeader\", pk.NetworkHeader(), nil)\n- checkPacketHeader(t, \"Initial pk.TransportHeader\", pk.TransportHeader(), nil)\n- // Check the initial valies for PayloadSince.\n- checkViewEqual(t, \"Initial PayloadSince(LinkHeader)\",\n- PayloadSince(pk.LinkHeader()), data)\n- checkViewEqual(t, \"Initial PayloadSince(NetworkHeader)\",\n- PayloadSince(pk.NetworkHeader()), data)\n- checkViewEqual(t, \"Initial PayloadSince(TransportHeader)\",\n- PayloadSince(pk.TransportHeader()), data)\n+ checkPacketContents(t, \"Initial \", pk, packetContents{\n+ data: data,\n+ })\n}\nfunc checkPacketHeader(t *testing.T, name string, h PacketHeader, want []byte) {\n" } ]
Go
Apache License 2.0
google/gvisor
netstack: Add a test for mixed Push/Consume Not really designed to be used this way, but it works and it's been relied upon. Add a test. PiperOrigin-RevId: 371802756
260,004
03.05.2021 16:38:51
25,200
f0b3298db07df63fa74559d5689008f9de9980a9
Convey GSO capabilities through GSOEndpoint ...as all GSO capable endpoints must implement GSOEndpoint.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/link/channel/channel.go", "new_path": "pkg/tcpip/link/channel/channel.go", "diff": "@@ -123,6 +123,9 @@ func (q *queue) RemoveNotify(handle *NotificationHandle) {\nq.notify = notify\n}\n+var _ stack.LinkEndpoint = (*Endpoint)(nil)\n+var _ stack.GSOEndpoint = (*Endpoint)(nil)\n+\n// Endpoint is link layer endpoint that stores outbound packets in a channel\n// and allows injection of inbound packets.\ntype Endpoint struct {\n@@ -130,6 +133,7 @@ type Endpoint struct {\nmtu uint32\nlinkAddr tcpip.LinkAddress\nLinkEPCapabilities stack.LinkEndpointCapabilities\n+ SupportedGSOKind stack.SupportedGSO\n// Outbound packet queue.\nq *queue\n@@ -211,11 +215,16 @@ func (e *Endpoint) Capabilities() stack.LinkEndpointCapabilities {\nreturn e.LinkEPCapabilities\n}\n-// GSOMaxSize returns the maximum GSO packet size.\n+// GSOMaxSize implements stack.GSOEndpoint.\nfunc (*Endpoint) GSOMaxSize() uint32 {\nreturn 1 << 15\n}\n+// SupportedGSO implements stack.GSOEndpoint.\n+func (e *Endpoint) SupportedGSO() stack.SupportedGSO {\n+ return e.SupportedGSOKind\n+}\n+\n// MaxHeaderLength returns the maximum size of the link layer header. Given it\n// doesn't have a header, it just returns 0.\nfunc (*Endpoint) MaxHeaderLength() uint16 {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/link/fdbased/endpoint.go", "new_path": "pkg/tcpip/link/fdbased/endpoint.go", "diff": "@@ -97,6 +97,9 @@ func (p PacketDispatchMode) String() string {\n}\n}\n+var _ stack.LinkEndpoint = (*endpoint)(nil)\n+var _ stack.GSOEndpoint = (*endpoint)(nil)\n+\ntype endpoint struct {\n// fds is the set of file descriptors each identifying one inbound/outbound\n// channel. The endpoint will dispatch from all inbound channels as well as\n@@ -133,6 +136,9 @@ type endpoint struct {\n// wg keeps track of running goroutines.\nwg sync.WaitGroup\n+\n+ // gsoKind is the supported kind of GSO.\n+ gsoKind stack.SupportedGSO\n}\n// Options specify the details about the fd-based endpoint to be created.\n@@ -254,9 +260,9 @@ func New(opts *Options) (stack.LinkEndpoint, error) {\nif isSocket {\nif opts.GSOMaxSize != 0 {\nif opts.SoftwareGSOEnabled {\n- e.caps |= stack.CapabilitySoftwareGSO\n+ e.gsoKind = stack.SWGSOSupported\n} else {\n- e.caps |= stack.CapabilityHardwareGSO\n+ e.gsoKind = stack.HWGSOSupported\n}\ne.gsoMaxSize = opts.GSOMaxSize\n}\n@@ -469,7 +475,7 @@ func (e *endpoint) WritePacket(r stack.RouteInfo, protocol tcpip.NetworkProtocol\nvar builder iovec.Builder\nfd := e.fds[pkt.Hash%uint32(len(e.fds))]\n- if e.Capabilities()&stack.CapabilityHardwareGSO != 0 {\n+ if e.gsoKind == stack.HWGSOSupported {\nvnetHdr := virtioNetHdr{}\nif pkt.GSOOptions.Type != stack.GSONone {\nvnetHdr.hdrLen = uint16(pkt.HeaderSize())\n@@ -510,7 +516,7 @@ func (e *endpoint) sendBatch(batchFD int, batch []*stack.PacketBuffer) (int, tcp\n}\nvar vnetHdrBuf []byte\n- if e.Capabilities()&stack.CapabilityHardwareGSO != 0 {\n+ if e.gsoKind == stack.HWGSOSupported {\nvnetHdr := virtioNetHdr{}\nif pkt.GSOOptions.Type != stack.GSONone {\nvnetHdr.hdrLen = uint16(pkt.HeaderSize())\n@@ -630,11 +636,16 @@ func (e *endpoint) dispatchLoop(inboundDispatcher linkDispatcher) tcpip.Error {\n}\n}\n-// GSOMaxSize returns the maximum GSO packet size.\n+// GSOMaxSize implements stack.GSOEndpoint.\nfunc (e *endpoint) GSOMaxSize() uint32 {\nreturn e.gsoMaxSize\n}\n+// SupportsHWGSO implements stack.GSOEndpoint.\n+func (e *endpoint) SupportedGSO() stack.SupportedGSO {\n+ return e.gsoKind\n+}\n+\n// ARPHardwareType implements stack.LinkEndpoint.ARPHardwareType.\nfunc (e *endpoint) ARPHardwareType() header.ARPHardwareType {\nif e.hdrSize > 0 {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/link/fdbased/packet_dispatchers.go", "new_path": "pkg/tcpip/link/fdbased/packet_dispatchers.go", "diff": "@@ -128,7 +128,7 @@ type readVDispatcher struct {\nfunc newReadVDispatcher(fd int, e *endpoint) (linkDispatcher, error) {\nd := &readVDispatcher{fd: fd, e: e}\n- skipsVnetHdr := d.e.Capabilities()&stack.CapabilityHardwareGSO != 0\n+ skipsVnetHdr := d.e.gsoKind == stack.HWGSOSupported\nd.buf = newIovecBuffer(BufConfig, skipsVnetHdr)\nreturn d, nil\n}\n@@ -212,7 +212,7 @@ func newRecvMMsgDispatcher(fd int, e *endpoint) (linkDispatcher, error) {\nbufs: make([]*iovecBuffer, MaxMsgsPerRecv),\nmsgHdrs: make([]rawfile.MMsgHdr, MaxMsgsPerRecv),\n}\n- skipsVnetHdr := d.e.Capabilities()&stack.CapabilityHardwareGSO != 0\n+ skipsVnetHdr := d.e.gsoKind == stack.HWGSOSupported\nfor i := range d.bufs {\nd.bufs[i] = newIovecBuffer(BufConfig, skipsVnetHdr)\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/link/nested/nested.go", "new_path": "pkg/tcpip/link/nested/nested.go", "diff": "@@ -135,6 +135,14 @@ func (e *Endpoint) GSOMaxSize() uint32 {\nreturn 0\n}\n+// SupportedGSO implements stack.GSOEndpoint.\n+func (e *Endpoint) SupportedGSO() stack.SupportedGSO {\n+ if e, ok := e.child.(stack.GSOEndpoint); ok {\n+ return e.SupportedGSO()\n+ }\n+ return stack.GSONotSupported\n+}\n+\n// ARPHardwareType implements stack.LinkEndpoint.ARPHardwareType\nfunc (e *Endpoint) ARPHardwareType() header.ARPHardwareType {\nreturn e.child.ARPHardwareType()\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/link/qdisc/fifo/endpoint.go", "new_path": "pkg/tcpip/link/qdisc/fifo/endpoint.go", "diff": "@@ -25,6 +25,9 @@ import (\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n)\n+var _ stack.LinkEndpoint = (*endpoint)(nil)\n+var _ stack.GSOEndpoint = (*endpoint)(nil)\n+\n// endpoint represents a LinkEndpoint which implements a FIFO queue for all\n// outgoing packets. endpoint can have 1 or more underlying queueDispatchers.\n// All outgoing packets are consistenly hashed to a single underlying queue\n@@ -141,7 +144,7 @@ func (e *endpoint) LinkAddress() tcpip.LinkAddress {\nreturn e.lower.LinkAddress()\n}\n-// GSOMaxSize returns the maximum GSO packet size.\n+// GSOMaxSize implements stack.GSOEndpoint.\nfunc (e *endpoint) GSOMaxSize() uint32 {\nif gso, ok := e.lower.(stack.GSOEndpoint); ok {\nreturn gso.GSOMaxSize()\n@@ -149,6 +152,14 @@ func (e *endpoint) GSOMaxSize() uint32 {\nreturn 0\n}\n+// SupportedGSO implements stack.GSOEndpoint.\n+func (e *endpoint) SupportedGSO() stack.SupportedGSO {\n+ if gso, ok := e.lower.(stack.GSOEndpoint); ok {\n+ return gso.SupportedGSO()\n+ }\n+ return stack.GSONotSupported\n+}\n+\n// WritePacket implements stack.LinkEndpoint.WritePacket.\n//\n// The packet must have the following fields populated:\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/forwarding_test.go", "new_path": "pkg/tcpip/stack/forwarding_test.go", "diff": "@@ -264,6 +264,8 @@ type fwdTestPacketInfo struct {\nPkt *PacketBuffer\n}\n+var _ LinkEndpoint = (*fwdTestLinkEndpoint)(nil)\n+\ntype fwdTestLinkEndpoint struct {\ndispatcher NetworkDispatcher\nmtu uint32\n@@ -306,11 +308,6 @@ func (e fwdTestLinkEndpoint) Capabilities() LinkEndpointCapabilities {\nreturn caps | CapabilityResolutionRequired\n}\n-// GSOMaxSize returns the maximum GSO packet size.\n-func (*fwdTestLinkEndpoint) GSOMaxSize() uint32 {\n- return 1 << 15\n-}\n-\n// MaxHeaderLength returns the maximum size of the link layer header. Given it\n// doesn't have a header, it just returns 0.\nfunc (*fwdTestLinkEndpoint) MaxHeaderLength() uint16 {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/registration.go", "new_path": "pkg/tcpip/stack/registration.go", "diff": "@@ -756,11 +756,6 @@ const (\nCapabilitySaveRestore\nCapabilityDisconnectOk\nCapabilityLoopback\n- CapabilityHardwareGSO\n-\n- // CapabilitySoftwareGSO indicates the link endpoint supports of sending\n- // multiple packets using a single call (LinkEndpoint.WritePackets).\n- CapabilitySoftwareGSO\n)\n// NetworkLinkEndpoint is a data-link layer that supports sending network\n@@ -1047,10 +1042,29 @@ type GSO struct {\nMaxSize uint32\n}\n+// SupportedGSO returns the type of segmentation offloading supported.\n+type SupportedGSO int\n+\n+const (\n+ // GSONotSupported indicates that segmentation offloading is not supported.\n+ GSONotSupported SupportedGSO = iota\n+\n+ // HWGSOSupported indicates that segmentation offloading may be performed by\n+ // the hardware.\n+ HWGSOSupported\n+\n+ // SWGSOSupported indicates that segmentation offloading may be performed in\n+ // software.\n+ SWGSOSupported\n+)\n+\n// GSOEndpoint provides access to GSO properties.\ntype GSOEndpoint interface {\n// GSOMaxSize returns the maximum GSO packet size.\nGSOMaxSize() uint32\n+\n+ // SupportedGSO returns the supported segmentation offloading.\n+ SupportedGSO() SupportedGSO\n}\n// SoftwareGSOMaxSize is a maximum allowed size of a software GSO segment.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/route.go", "new_path": "pkg/tcpip/stack/route.go", "diff": "@@ -300,12 +300,18 @@ func (r *Route) RequiresTXTransportChecksum() bool {\n// HasSoftwareGSOCapability returns true if the route supports software GSO.\nfunc (r *Route) HasSoftwareGSOCapability() bool {\n- return r.outgoingNIC.LinkEndpoint.Capabilities()&CapabilitySoftwareGSO != 0\n+ if gso, ok := r.outgoingNIC.LinkEndpoint.(GSOEndpoint); ok {\n+ return gso.SupportedGSO() == SWGSOSupported\n+ }\n+ return false\n}\n// HasHardwareGSOCapability returns true if the route supports hardware GSO.\nfunc (r *Route) HasHardwareGSOCapability() bool {\n- return r.outgoingNIC.LinkEndpoint.Capabilities()&CapabilityHardwareGSO != 0\n+ if gso, ok := r.outgoingNIC.LinkEndpoint.(GSOEndpoint); ok {\n+ return gso.SupportedGSO() == HWGSOSupported\n+ }\n+ return false\n}\n// HasSaveRestoreCapability returns true if the route supports save/restore.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/testing/context/context.go", "new_path": "pkg/tcpip/transport/tcp/testing/context/context.go", "diff": "@@ -1214,9 +1214,9 @@ func (c *Context) SACKEnabled() bool {\n// SetGSOEnabled enables or disables generic segmentation offload.\nfunc (c *Context) SetGSOEnabled(enable bool) {\nif enable {\n- c.linkEP.LinkEPCapabilities |= stack.CapabilityHardwareGSO\n+ c.linkEP.SupportedGSOKind = stack.HWGSOSupported\n} else {\n- c.linkEP.LinkEPCapabilities &^= stack.CapabilityHardwareGSO\n+ c.linkEP.SupportedGSOKind = stack.GSONotSupported\n}\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Convey GSO capabilities through GSOEndpoint ...as all GSO capable endpoints must implement GSOEndpoint. PiperOrigin-RevId: 371804175
260,004
03.05.2021 16:44:02
25,200
279f9fcee763a52d210f8269bc4c871b7eee112f
Implement standard clock safely Previously, tcpip.StdClock depended on linking with the unexposed method time.now to implement tcpip.Clock using the time package. This change updates the standard clock to not require manually linking to this unexported method and use publicly documented functions from the time package.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/BUILD", "new_path": "pkg/tcpip/BUILD", "diff": "@@ -22,8 +22,9 @@ go_library(\n\"errors.go\",\n\"sock_err_list.go\",\n\"socketops.go\",\n+ \"stdclock.go\",\n+ \"stdclock_state.go\",\n\"tcpip.go\",\n- \"time_unsafe.go\",\n\"timer.go\",\n],\nvisibility = [\"//visibility:public\"],\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/neighbor_cache_test.go", "new_path": "pkg/tcpip/stack/neighbor_cache_test.go", "diff": "@@ -1556,7 +1556,7 @@ func TestNeighborCacheRetryResolution(t *testing.T) {\nfunc BenchmarkCacheClear(b *testing.B) {\nb.StopTimer()\nconfig := DefaultNUDConfigurations()\n- clock := &tcpip.StdClock{}\n+ clock := tcpip.NewStdClock()\nlinkRes := newTestNeighborResolver(nil, config, clock)\nlinkRes.delay = 0\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/stack.go", "new_path": "pkg/tcpip/stack/stack.go", "diff": "@@ -322,7 +322,7 @@ func (*TransportEndpointInfo) IsEndpointInfo() {}\nfunc New(opts Options) *Stack {\nclock := opts.Clock\nif clock == nil {\n- clock = &tcpip.StdClock{}\n+ clock = tcpip.NewStdClock()\n}\nif opts.UniqueID == nil {\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/tcpip/stdclock_state.go", "diff": "+// Copyright 2021 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package tcpip\n+\n+import \"time\"\n+\n+// afterLoad is invoked by stateify.\n+func (s *stdClock) afterLoad() {\n+ s.baseTime = time.Now()\n+\n+ s.monotonicMU.Lock()\n+ defer s.monotonicMU.Unlock()\n+ s.monotonicOffset = s.maxMonotonic\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/tcpip.go", "new_path": "pkg/tcpip/tcpip.go", "diff": "@@ -73,7 +73,7 @@ type Clock interface {\n// nanoseconds since the Unix epoch.\nNowNanoseconds() int64\n- // NowMonotonic returns a monotonic time value.\n+ // NowMonotonic returns a monotonic time value at nanosecond resolution.\nNowMonotonic() int64\n// AfterFunc waits for the duration to elapse and then calls f in its own\n" }, { "change_type": "DELETE", "old_path": "pkg/tcpip/time_unsafe.go", "new_path": null, "diff": "-// Copyright 2018 The gVisor Authors.\n-//\n-// Licensed under the Apache License, Version 2.0 (the \"License\");\n-// you may not use this file except in compliance with the License.\n-// You may obtain a copy of the License at\n-//\n-// http://www.apache.org/licenses/LICENSE-2.0\n-//\n-// Unless required by applicable law or agreed to in writing, software\n-// distributed under the License is distributed on an \"AS IS\" BASIS,\n-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n-// See the License for the specific language governing permissions and\n-// limitations under the License.\n-\n-// +build go1.9\n-// +build !go1.18\n-\n-// Check go:linkname function signatures when updating Go version.\n-\n-package tcpip\n-\n-import (\n- \"time\" // Used with go:linkname.\n- _ \"unsafe\" // Required for go:linkname.\n-)\n-\n-// StdClock implements Clock with the time package.\n-//\n-// +stateify savable\n-type StdClock struct{}\n-\n-var _ Clock = (*StdClock)(nil)\n-\n-//go:linkname now time.now\n-func now() (sec int64, nsec int32, mono int64)\n-\n-// NowNanoseconds implements Clock.NowNanoseconds.\n-func (*StdClock) NowNanoseconds() int64 {\n- sec, nsec, _ := now()\n- return sec*1e9 + int64(nsec)\n-}\n-\n-// NowMonotonic implements Clock.NowMonotonic.\n-func (*StdClock) NowMonotonic() int64 {\n- _, _, mono := now()\n- return mono\n-}\n-\n-// AfterFunc implements Clock.AfterFunc.\n-func (*StdClock) AfterFunc(d time.Duration, f func()) Timer {\n- return &stdTimer{\n- t: time.AfterFunc(d, f),\n- }\n-}\n-\n-type stdTimer struct {\n- t *time.Timer\n-}\n-\n-var _ Timer = (*stdTimer)(nil)\n-\n-// Stop implements Timer.Stop.\n-func (st *stdTimer) Stop() bool {\n- return st.t.Stop()\n-}\n-\n-// Reset implements Timer.Reset.\n-func (st *stdTimer) Reset(d time.Duration) {\n- st.t.Reset(d)\n-}\n-\n-// NewStdTimer returns a Timer implemented with the time package.\n-func NewStdTimer(t *time.Timer) Timer {\n- return &stdTimer{t: t}\n-}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/timer_test.go", "new_path": "pkg/tcpip/timer_test.go", "diff": "@@ -29,7 +29,7 @@ const (\n)\nfunc TestJobReschedule(t *testing.T) {\n- var clock tcpip.StdClock\n+ clock := tcpip.NewStdClock()\nvar wg sync.WaitGroup\nvar lock sync.Mutex\n@@ -43,7 +43,7 @@ func TestJobReschedule(t *testing.T) {\n// that has an active timer (even if it has been stopped as a stopped\n// timer may be blocked on a lock before it can check if it has been\n// stopped while another goroutine holds the same lock).\n- job := tcpip.NewJob(&clock, &lock, func() {\n+ job := tcpip.NewJob(clock, &lock, func() {\nwg.Done()\n})\njob.Schedule(shortDuration)\n@@ -56,11 +56,11 @@ func TestJobReschedule(t *testing.T) {\nfunc TestJobExecution(t *testing.T) {\nt.Parallel()\n- var clock tcpip.StdClock\n+ clock := tcpip.NewStdClock()\nvar lock sync.Mutex\nch := make(chan struct{})\n- job := tcpip.NewJob(&clock, &lock, func() {\n+ job := tcpip.NewJob(clock, &lock, func() {\nch <- struct{}{}\n})\njob.Schedule(shortDuration)\n@@ -83,11 +83,11 @@ func TestJobExecution(t *testing.T) {\nfunc TestCancellableTimerResetFromLongDuration(t *testing.T) {\nt.Parallel()\n- var clock tcpip.StdClock\n+ clock := tcpip.NewStdClock()\nvar lock sync.Mutex\nch := make(chan struct{})\n- job := tcpip.NewJob(&clock, &lock, func() { ch <- struct{}{} })\n+ job := tcpip.NewJob(clock, &lock, func() { ch <- struct{}{} })\njob.Schedule(middleDuration)\nlock.Lock()\n@@ -114,12 +114,12 @@ func TestCancellableTimerResetFromLongDuration(t *testing.T) {\nfunc TestJobRescheduleFromShortDuration(t *testing.T) {\nt.Parallel()\n- var clock tcpip.StdClock\n+ clock := tcpip.NewStdClock()\nvar lock sync.Mutex\nch := make(chan struct{})\nlock.Lock()\n- job := tcpip.NewJob(&clock, &lock, func() { ch <- struct{}{} })\n+ job := tcpip.NewJob(clock, &lock, func() { ch <- struct{}{} })\njob.Schedule(shortDuration)\njob.Cancel()\nlock.Unlock()\n@@ -151,13 +151,13 @@ func TestJobRescheduleFromShortDuration(t *testing.T) {\nfunc TestJobImmediatelyCancel(t *testing.T) {\nt.Parallel()\n- var clock tcpip.StdClock\n+ clock := tcpip.NewStdClock()\nvar lock sync.Mutex\nch := make(chan struct{})\nfor i := 0; i < 1000; i++ {\nlock.Lock()\n- job := tcpip.NewJob(&clock, &lock, func() { ch <- struct{}{} })\n+ job := tcpip.NewJob(clock, &lock, func() { ch <- struct{}{} })\njob.Schedule(shortDuration)\njob.Cancel()\nlock.Unlock()\n@@ -174,12 +174,12 @@ func TestJobImmediatelyCancel(t *testing.T) {\nfunc TestJobCancelledRescheduleWithoutLock(t *testing.T) {\nt.Parallel()\n- var clock tcpip.StdClock\n+ clock := tcpip.NewStdClock()\nvar lock sync.Mutex\nch := make(chan struct{})\nlock.Lock()\n- job := tcpip.NewJob(&clock, &lock, func() { ch <- struct{}{} })\n+ job := tcpip.NewJob(clock, &lock, func() { ch <- struct{}{} })\njob.Schedule(shortDuration)\njob.Cancel()\nlock.Unlock()\n@@ -206,12 +206,12 @@ func TestJobCancelledRescheduleWithoutLock(t *testing.T) {\nfunc TestManyCancellableTimerResetAfterBlockedOnLock(t *testing.T) {\nt.Parallel()\n- var clock tcpip.StdClock\n+ clock := tcpip.NewStdClock()\nvar lock sync.Mutex\nch := make(chan struct{})\nlock.Lock()\n- job := tcpip.NewJob(&clock, &lock, func() { ch <- struct{}{} })\n+ job := tcpip.NewJob(clock, &lock, func() { ch <- struct{}{} })\njob.Schedule(shortDuration)\nfor i := 0; i < 10; i++ {\n// Sleep until the timer fires and gets blocked trying to take the lock.\n@@ -239,12 +239,12 @@ func TestManyCancellableTimerResetAfterBlockedOnLock(t *testing.T) {\nfunc TestManyJobReschedulesUnderLock(t *testing.T) {\nt.Parallel()\n- var clock tcpip.StdClock\n+ clock := tcpip.NewStdClock()\nvar lock sync.Mutex\nch := make(chan struct{})\nlock.Lock()\n- job := tcpip.NewJob(&clock, &lock, func() { ch <- struct{}{} })\n+ job := tcpip.NewJob(clock, &lock, func() { ch <- struct{}{} })\njob.Schedule(shortDuration)\nfor i := 0; i < 10; i++ {\njob.Cancel()\n" } ]
Go
Apache License 2.0
google/gvisor
Implement standard clock safely Previously, tcpip.StdClock depended on linking with the unexposed method time.now to implement tcpip.Clock using the time package. This change updates the standard clock to not require manually linking to this unexported method and use publicly documented functions from the time package. PiperOrigin-RevId: 371805101
259,860
04.05.2021 11:53:02
25,200
dd3875eabecc479d83cb66828a4163c37458170e
Increase error margin for memory accounting test.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/memory_accounting.cc", "new_path": "test/syscalls/linux/memory_accounting.cc", "diff": "@@ -83,7 +83,7 @@ TEST(MemoryAccounting, AnonAccountingPreservedOnSaveRestore) {\nuint64_t anon_after_alloc = ASSERT_NO_ERRNO_AND_VALUE(AnonUsageFromMeminfo());\nEXPECT_THAT(anon_after_alloc,\n- EquivalentWithin(anon_initial + map_bytes, 0.03));\n+ EquivalentWithin(anon_initial + map_bytes, 0.04));\n// We have many implicit S/R cycles from scraping /proc/meminfo throughout the\n// test, but throw an explicit S/R in here as well.\n@@ -91,7 +91,7 @@ TEST(MemoryAccounting, AnonAccountingPreservedOnSaveRestore) {\n// Usage should remain the same across S/R.\nuint64_t anon_after_sr = ASSERT_NO_ERRNO_AND_VALUE(AnonUsageFromMeminfo());\n- EXPECT_THAT(anon_after_sr, EquivalentWithin(anon_after_alloc, 0.03));\n+ EXPECT_THAT(anon_after_sr, EquivalentWithin(anon_after_alloc, 0.04));\n}\n} // namespace\n" } ]
Go
Apache License 2.0
google/gvisor
Increase error margin for memory accounting test. PiperOrigin-RevId: 371963265
259,860
04.05.2021 15:56:05
25,200
d496c285aacff88bb858e4efd700aa1e0b2ebad1
Add TODOs to old reference counting utility.
[ { "change_type": "MODIFY", "old_path": "pkg/refs/refcounter.go", "new_path": "pkg/refs/refcounter.go", "diff": "@@ -30,6 +30,9 @@ import (\n// RefCounter is the interface to be implemented by objects that are reference\n// counted.\n+//\n+// TODO(gvisor.dev/issue/1624): Get rid of most of this package and replace it\n+// with refsvfs2.\ntype RefCounter interface {\n// IncRef increments the reference counter on the object.\nIncRef()\n@@ -181,6 +184,9 @@ func (w *WeakRef) zap() {\n// AtomicRefCount keeps a reference count using atomic operations and calls the\n// destructor when the count reaches zero.\n//\n+// Do not use AtomicRefCount for new ref-counted objects! It is deprecated in\n+// favor of the refsvfs2 package.\n+//\n// N.B. To allow the zero-object to be initialized, the count is offset by\n// 1, that is, when refCount is n, there are really n+1 references.\n//\n@@ -215,8 +221,8 @@ type AtomicRefCount struct {\n// LeakMode configures the leak checker.\ntype LeakMode uint32\n-// TODO(gvisor.dev/issue/1624): Simplify down to two modes once vfs1 ref\n-// counting is gone.\n+// TODO(gvisor.dev/issue/1624): Simplify down to two modes (on/off) once vfs1\n+// ref counting is gone.\nconst (\n// UninitializedLeakChecking indicates that the leak checker has not yet been initialized.\nUninitializedLeakChecking LeakMode = iota\n" }, { "change_type": "MODIFY", "old_path": "pkg/refsvfs2/BUILD", "new_path": "pkg/refsvfs2/BUILD", "diff": "+# TODO(gvisor.dev/issue/1624): rename this directory/package to \"refs\" once VFS1\n+# is gone and the current refs package can be deleted.\nload(\"//tools:defs.bzl\", \"go_library\")\nload(\"//tools/go_generics:defs.bzl\", \"go_template\")\n" } ]
Go
Apache License 2.0
google/gvisor
Add TODOs to old reference counting utility. PiperOrigin-RevId: 372012795
260,023
04.05.2021 16:40:17
25,200
682415b6d0035a2af0e7981c31b728762e15bf10
Use cmp.Diff for tcpip.Error comparison
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/dual_stack_test.go", "new_path": "pkg/tcpip/transport/tcp/dual_stack_test.go", "diff": "@@ -19,6 +19,7 @@ import (\n\"testing\"\n\"time\"\n+ \"github.com/google/go-cmp/cmp\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/checker\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n@@ -37,8 +38,8 @@ func TestV4MappedConnectOnV6Only(t *testing.T) {\n// Start connection attempt, it must fail.\nerr := c.EP.Connect(tcpip.FullAddress{Addr: context.TestV4MappedAddr, Port: context.TestPort})\n- if _, ok := err.(*tcpip.ErrNoRoute); !ok {\n- t.Fatalf(\"Unexpected return value from Connect: %v\", err)\n+ if d := cmp.Diff(&tcpip.ErrNoRoute{}, err); d != \"\" {\n+ t.Fatalf(\"c.EP.Connect(...) mismatch (-want +got):\\n%s\", d)\n}\n}\n@@ -49,8 +50,8 @@ func testV4Connect(t *testing.T, c *context.Context, checkers ...checker.Network\ndefer c.WQ.EventUnregister(&we)\nerr := c.EP.Connect(tcpip.FullAddress{Addr: context.TestV4MappedAddr, Port: context.TestPort})\n- if _, ok := err.(*tcpip.ErrConnectStarted); !ok {\n- t.Fatalf(\"Unexpected return value from Connect: %v\", err)\n+ if d := cmp.Diff(&tcpip.ErrConnectStarted{}, err); d != \"\" {\n+ t.Fatalf(\"c.EP.Connect(...) mismatch (-want +got):\\n%s\", d)\n}\n// Receive SYN packet.\n@@ -156,8 +157,8 @@ func testV6Connect(t *testing.T, c *context.Context, checkers ...checker.Network\ndefer c.WQ.EventUnregister(&we)\nerr := c.EP.Connect(tcpip.FullAddress{Addr: context.TestV6Addr, Port: context.TestPort})\n- if _, ok := err.(*tcpip.ErrConnectStarted); !ok {\n- t.Fatalf(\"Unexpected return value from Connect: %v\", err)\n+ if d := cmp.Diff(&tcpip.ErrConnectStarted{}, err); d != \"\" {\n+ t.Fatalf(\"Connect(...) mismatch (-want +got):\\n%s\", d)\n}\n// Receive SYN packet.\n@@ -391,7 +392,7 @@ func testV4Accept(t *testing.T, c *context.Context) {\ndefer c.WQ.EventUnregister(&we)\nnep, _, err := c.EP.Accept(nil)\n- if _, ok := err.(*tcpip.ErrWouldBlock); ok {\n+ if cmp.Equal(&tcpip.ErrWouldBlock{}, err) {\n// Wait for connection to be established.\nselect {\ncase <-ch:\n@@ -525,7 +526,7 @@ func TestV6AcceptOnV6(t *testing.T) {\ndefer c.WQ.EventUnregister(&we)\nvar addr tcpip.FullAddress\n_, _, err := c.EP.Accept(&addr)\n- if _, ok := err.(*tcpip.ErrWouldBlock); ok {\n+ if cmp.Equal(&tcpip.ErrWouldBlock{}, err) {\n// Wait for connection to be established.\nselect {\ncase <-ch:\n@@ -611,7 +612,7 @@ func testV4ListenClose(t *testing.T, c *context.Context) {\nc.WQ.EventRegister(&we, waiter.ReadableEvents)\ndefer c.WQ.EventUnregister(&we)\nnep, _, err := c.EP.Accept(nil)\n- if _, ok := err.(*tcpip.ErrWouldBlock); ok {\n+ if cmp.Equal(&tcpip.ErrWouldBlock{}, err) {\n// Wait for connection to be established.\nselect {\ncase <-ch:\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/tcp_test.go", "new_path": "pkg/tcpip/transport/tcp/tcp_test.go", "diff": "@@ -87,7 +87,7 @@ func (e *endpointTester) CheckReadFull(t *testing.T, count int, notifyRead <-cha\n}\nfor w.N != 0 {\n_, err := e.ep.Read(&w, tcpip.ReadOptions{})\n- if _, ok := err.(*tcpip.ErrWouldBlock); ok {\n+ if cmp.Equal(&tcpip.ErrWouldBlock{}, err) {\n// Wait for receive to be notified.\nselect {\ncase <-notifyRead:\n@@ -130,8 +130,8 @@ func TestGiveUpConnect(t *testing.T) {\n{\nerr := ep.Connect(tcpip.FullAddress{Addr: context.TestAddr, Port: context.TestPort})\n- if _, ok := err.(*tcpip.ErrConnectStarted); !ok {\n- t.Fatalf(\"got ep.Connect(...) = %v, want = %s\", err, &tcpip.ErrConnectStarted{})\n+ if d := cmp.Diff(&tcpip.ErrConnectStarted{}, err); d != \"\" {\n+ t.Fatalf(\"ep.Connect(...) mismatch (-want +got):\\n%s\", d)\n}\n}\n@@ -145,8 +145,8 @@ func TestGiveUpConnect(t *testing.T) {\n// and stats updates.\n{\nerr := ep.Connect(tcpip.FullAddress{Addr: context.TestAddr, Port: context.TestPort})\n- if _, ok := err.(*tcpip.ErrAborted); !ok {\n- t.Fatalf(\"got ep.Connect(...) = %v, want = %s\", err, &tcpip.ErrAborted{})\n+ if d := cmp.Diff(&tcpip.ErrAborted{}, err); d != \"\" {\n+ t.Fatalf(\"ep.Connect(...) mismatch (-want +got):\\n%s\", d)\n}\n}\n@@ -202,8 +202,8 @@ func TestActiveFailedConnectionAttemptIncrement(t *testing.T) {\n{\nerr := c.EP.Connect(tcpip.FullAddress{NIC: 2, Addr: context.TestAddr, Port: context.TestPort})\n- if _, ok := err.(*tcpip.ErrNoRoute); !ok {\n- t.Errorf(\"got c.EP.Connect(...) = %v, want = %s\", err, &tcpip.ErrNoRoute{})\n+ if d := cmp.Diff(&tcpip.ErrNoRoute{}, err); d != \"\" {\n+ t.Errorf(\"c.EP.Connect(...) mismatch (-want +got):\\n%s\", d)\n}\n}\n@@ -393,7 +393,7 @@ func TestTCPResetSentForACKWhenNotUsingSynCookies(t *testing.T) {\ndefer wq.EventUnregister(&we)\nc.EP, _, err = ep.Accept(nil)\n- if _, ok := err.(*tcpip.ErrWouldBlock); ok {\n+ if cmp.Equal(&tcpip.ErrWouldBlock{}, err) {\n// Wait for connection to be established.\nselect {\ncase <-ch:\n@@ -936,8 +936,8 @@ func TestUserSuppliedMSSOnConnect(t *testing.T) {\nconnectAddr := tcpip.FullAddress{Addr: ip.connectAddr, Port: context.TestPort}\n{\nerr := c.EP.Connect(connectAddr)\n- if _, ok := err.(*tcpip.ErrConnectStarted); !ok {\n- t.Fatalf(\"Connect(%+v): %s\", connectAddr, err)\n+ if d := cmp.Diff(&tcpip.ErrConnectStarted{}, err); d != \"\" {\n+ t.Fatalf(\"Connect(%+v) mismatch (-want +got):\\n%s\", connectAddr, d)\n}\n}\n@@ -1543,8 +1543,8 @@ func TestConnectBindToDevice(t *testing.T) {\ndefer c.WQ.EventUnregister(&waitEntry)\nerr := c.EP.Connect(tcpip.FullAddress{Addr: context.TestAddr, Port: context.TestPort})\n- if _, ok := err.(*tcpip.ErrConnectStarted); !ok {\n- t.Fatalf(\"unexpected return value from Connect: %s\", err)\n+ if d := cmp.Diff(&tcpip.ErrConnectStarted{}, err); d != \"\" {\n+ t.Fatalf(\"c.EP.Connect(...) mismatch (-want +got):\\n%s\", d)\n}\n// Receive SYN packet.\n@@ -1604,8 +1604,8 @@ func TestSynSent(t *testing.T) {\naddr := tcpip.FullAddress{Addr: context.TestAddr, Port: context.TestPort}\nerr := c.EP.Connect(addr)\n- if _, ok := err.(*tcpip.ErrConnectStarted); !ok {\n- t.Fatalf(\"got Connect(%+v) = %v, want %s\", addr, err, &tcpip.ErrConnectStarted{})\n+ if d := cmp.Diff(err, &tcpip.ErrConnectStarted{}); d != \"\" {\n+ t.Fatalf(\"Connect(...) mismatch (-want +got):\\n%s\", d)\n}\n// Receive SYN packet.\n@@ -2473,7 +2473,7 @@ func TestScaledWindowAccept(t *testing.T) {\ndefer wq.EventUnregister(&we)\nc.EP, _, err = ep.Accept(nil)\n- if _, ok := err.(*tcpip.ErrWouldBlock); ok {\n+ if cmp.Equal(&tcpip.ErrWouldBlock{}, err) {\n// Wait for connection to be established.\nselect {\ncase <-ch:\n@@ -2545,7 +2545,7 @@ func TestNonScaledWindowAccept(t *testing.T) {\ndefer wq.EventUnregister(&we)\nc.EP, _, err = ep.Accept(nil)\n- if _, ok := err.(*tcpip.ErrWouldBlock); ok {\n+ if cmp.Equal(&tcpip.ErrWouldBlock{}, err) {\n// Wait for connection to be established.\nselect {\ncase <-ch:\n@@ -3077,8 +3077,8 @@ func TestSetTTL(t *testing.T) {\n{\nerr := c.EP.Connect(tcpip.FullAddress{Addr: context.TestAddr, Port: context.TestPort})\n- if _, ok := err.(*tcpip.ErrConnectStarted); !ok {\n- t.Fatalf(\"unexpected return value from Connect: %s\", err)\n+ if d := cmp.Diff(&tcpip.ErrConnectStarted{}, err); d != \"\" {\n+ t.Fatalf(\"c.EP.Connect(...) mismatch (-want +got):\\n%s\", d)\n}\n}\n@@ -3137,7 +3137,7 @@ func TestPassiveSendMSSLessThanMTU(t *testing.T) {\ndefer wq.EventUnregister(&we)\nc.EP, _, err = ep.Accept(nil)\n- if _, ok := err.(*tcpip.ErrWouldBlock); ok {\n+ if cmp.Equal(&tcpip.ErrWouldBlock{}, err) {\n// Wait for connection to be established.\nselect {\ncase <-ch:\n@@ -3191,7 +3191,7 @@ func TestSynCookiePassiveSendMSSLessThanMTU(t *testing.T) {\ndefer wq.EventUnregister(&we)\nc.EP, _, err = ep.Accept(nil)\n- if _, ok := err.(*tcpip.ErrWouldBlock); ok {\n+ if cmp.Equal(&tcpip.ErrWouldBlock{}, err) {\n// Wait for connection to be established.\nselect {\ncase <-ch:\n@@ -3266,8 +3266,8 @@ func TestSynOptionsOnActiveConnect(t *testing.T) {\n{\nerr := c.EP.Connect(tcpip.FullAddress{Addr: context.TestAddr, Port: context.TestPort})\n- if _, ok := err.(*tcpip.ErrConnectStarted); !ok {\n- t.Fatalf(\"got c.EP.Connect(...) = %v, want = %s\", err, &tcpip.ErrConnectStarted{})\n+ if d := cmp.Diff(&tcpip.ErrConnectStarted{}, err); d != \"\" {\n+ t.Fatalf(\"c.EP.Connect(...) mismatch (-want +got):\\n%s\", d)\n}\n}\n@@ -3385,8 +3385,8 @@ loop:\ncase <-ch:\n// Expect the state to be StateError and subsequent Reads to fail with HardError.\n_, err := c.EP.Read(ioutil.Discard, tcpip.ReadOptions{})\n- if _, ok := err.(*tcpip.ErrConnectionReset); !ok {\n- t.Fatalf(\"got c.EP.Read() = %v, want = %s\", err, &tcpip.ErrConnectionReset{})\n+ if d := cmp.Diff(&tcpip.ErrConnectionReset{}, err); d != \"\" {\n+ t.Fatalf(\"c.EP.Read() mismatch (-want +got):\\n%s\", d)\n}\nbreak loop\ncase <-time.After(1 * time.Second):\n@@ -3436,8 +3436,8 @@ func TestSendOnResetConnection(t *testing.T) {\nvar r bytes.Reader\nr.Reset(make([]byte, 10))\n_, err := c.EP.Write(&r, tcpip.WriteOptions{})\n- if _, ok := err.(*tcpip.ErrConnectionReset); !ok {\n- t.Fatalf(\"got c.EP.Write(...) = %v, want = %s\", err, &tcpip.ErrConnectionReset{})\n+ if d := cmp.Diff(&tcpip.ErrConnectionReset{}, err); d != \"\" {\n+ t.Fatalf(\"c.EP.Write(...) mismatch (-want +got):\\n%s\", d)\n}\n}\n@@ -4390,8 +4390,8 @@ func TestReadAfterClosedState(t *testing.T) {\nvar buf bytes.Buffer\n{\n_, err := c.EP.Read(&buf, tcpip.ReadOptions{Peek: true})\n- if _, ok := err.(*tcpip.ErrClosedForReceive); !ok {\n- t.Fatalf(\"c.EP.Read(_, {Peek: true}) = %v, %s; want _, %s\", res, err, &tcpip.ErrClosedForReceive{})\n+ if d := cmp.Diff(&tcpip.ErrClosedForReceive{}, err); d != \"\" {\n+ t.Fatalf(\"c.EP.Read(_, {Peek: true}) mismatch (-want +got):\\n%s\", d)\n}\n}\n}\n@@ -4435,8 +4435,8 @@ func TestReusePort(t *testing.T) {\n}\n{\nerr := c.EP.Connect(tcpip.FullAddress{Addr: context.TestAddr, Port: context.TestPort})\n- if _, ok := err.(*tcpip.ErrConnectStarted); !ok {\n- t.Fatalf(\"got c.EP.Connect(...) = %v, want = %s\", err, &tcpip.ErrConnectStarted{})\n+ if d := cmp.Diff(&tcpip.ErrConnectStarted{}, err); d != \"\" {\n+ t.Fatalf(\"c.EP.Connect(...) mismatch (-want +got):\\n%s\", d)\n}\n}\nc.EP.Close()\n@@ -4724,8 +4724,8 @@ func TestSelfConnect(t *testing.T) {\n{\nerr := ep.Connect(tcpip.FullAddress{Addr: context.StackAddr, Port: context.StackPort})\n- if _, ok := err.(*tcpip.ErrConnectStarted); !ok {\n- t.Fatalf(\"got ep.Connect(...) = %v, want = %s\", err, &tcpip.ErrConnectStarted{})\n+ if d := cmp.Diff(&tcpip.ErrConnectStarted{}, err); d != \"\" {\n+ t.Fatalf(\"ep.Connect(...) mismatch (-want +got):\\n%s\", d)\n}\n}\n@@ -5452,7 +5452,7 @@ func TestListenBacklogFull(t *testing.T) {\nfor i := 0; i < listenBacklog; i++ {\n_, _, err = c.EP.Accept(nil)\n- if _, ok := err.(*tcpip.ErrWouldBlock); ok {\n+ if cmp.Equal(&tcpip.ErrWouldBlock{}, err) {\n// Wait for connection to be established.\nselect {\ncase <-ch:\n@@ -5469,7 +5469,7 @@ func TestListenBacklogFull(t *testing.T) {\n// Now verify that there are no more connections that can be accepted.\n_, _, err = c.EP.Accept(nil)\n- if _, ok := err.(*tcpip.ErrWouldBlock); !ok {\n+ if !cmp.Equal(&tcpip.ErrWouldBlock{}, err) {\nselect {\ncase <-ch:\nt.Fatalf(\"unexpected endpoint delivered on Accept: %+v\", c.EP)\n@@ -5481,7 +5481,7 @@ func TestListenBacklogFull(t *testing.T) {\nexecuteHandshake(t, c, context.TestPort+lastPortOffset, false /*synCookieInUse */)\nnewEP, _, err := c.EP.Accept(nil)\n- if _, ok := err.(*tcpip.ErrWouldBlock); ok {\n+ if cmp.Equal(&tcpip.ErrWouldBlock{}, err) {\n// Wait for connection to be established.\nselect {\ncase <-ch:\n@@ -5794,7 +5794,7 @@ func TestListenSynRcvdQueueFull(t *testing.T) {\n// Try to accept the connections in the backlog.\nnewEP, _, err := c.EP.Accept(nil)\n- if _, ok := err.(*tcpip.ErrWouldBlock); ok {\n+ if cmp.Equal(&tcpip.ErrWouldBlock{}, err) {\n// Wait for connection to be established.\nselect {\ncase <-ch:\n@@ -5865,7 +5865,7 @@ func TestListenBacklogFullSynCookieInUse(t *testing.T) {\ndefer c.WQ.EventUnregister(&we)\n_, _, err = c.EP.Accept(nil)\n- if _, ok := err.(*tcpip.ErrWouldBlock); ok {\n+ if cmp.Equal(&tcpip.ErrWouldBlock{}, err) {\n// Wait for connection to be established.\nselect {\ncase <-ch:\n@@ -5881,7 +5881,7 @@ func TestListenBacklogFullSynCookieInUse(t *testing.T) {\n// Now verify that there are no more connections that can be accepted.\n_, _, err = c.EP.Accept(nil)\n- if _, ok := err.(*tcpip.ErrWouldBlock); !ok {\n+ if !cmp.Equal(&tcpip.ErrWouldBlock{}, err) {\nselect {\ncase <-ch:\nt.Fatalf(\"unexpected endpoint delivered on Accept: %+v\", c.EP)\n@@ -6020,7 +6020,7 @@ func TestSynRcvdBadSeqNumber(t *testing.T) {\nt.Fatalf(\"Accept failed: %s\", err)\n}\n- if _, ok := err.(*tcpip.ErrWouldBlock); ok {\n+ if cmp.Equal(&tcpip.ErrWouldBlock{}, err) {\n// Try to accept the connections in the backlog.\nwe, ch := waiter.NewChannelEntry(nil)\nc.WQ.EventRegister(&we, waiter.ReadableEvents)\n@@ -6088,7 +6088,7 @@ func TestPassiveConnectionAttemptIncrement(t *testing.T) {\n// Verify that there is only one acceptable connection at this point.\n_, _, err = c.EP.Accept(nil)\n- if _, ok := err.(*tcpip.ErrWouldBlock); ok {\n+ if cmp.Equal(&tcpip.ErrWouldBlock{}, err) {\n// Wait for connection to be established.\nselect {\ncase <-ch:\n@@ -6158,7 +6158,7 @@ func TestPassiveFailedConnectionAttemptIncrement(t *testing.T) {\n// Now check that there is one acceptable connections.\n_, _, err = c.EP.Accept(nil)\n- if _, ok := err.(*tcpip.ErrWouldBlock); ok {\n+ if cmp.Equal(&tcpip.ErrWouldBlock{}, err) {\n// Wait for connection to be established.\nselect {\ncase <-ch:\n@@ -6210,7 +6210,7 @@ func TestEndpointBindListenAcceptState(t *testing.T) {\ndefer wq.EventUnregister(&we)\naep, _, err := ep.Accept(nil)\n- if _, ok := err.(*tcpip.ErrWouldBlock); ok {\n+ if cmp.Equal(&tcpip.ErrWouldBlock{}, err) {\n// Wait for connection to be established.\nselect {\ncase <-ch:\n@@ -6228,8 +6228,8 @@ func TestEndpointBindListenAcceptState(t *testing.T) {\n}\n{\nerr := aep.Connect(tcpip.FullAddress{Addr: context.TestAddr, Port: context.TestPort})\n- if _, ok := err.(*tcpip.ErrAlreadyConnected); !ok {\n- t.Errorf(\"unexpected error attempting to call connect on an established endpoint, got: %v, want: %s\", err, &tcpip.ErrAlreadyConnected{})\n+ if d := cmp.Diff(&tcpip.ErrAlreadyConnected{}, err); d != \"\" {\n+ t.Errorf(\"Connect(...) mismatch (-want +got):\\n%s\", d)\n}\n}\n// Listening endpoint remains in listen state.\n@@ -6349,7 +6349,7 @@ func TestReceiveBufferAutoTuningApplicationLimited(t *testing.T) {\n// window increases to the full available buffer size.\nfor {\n_, err := c.EP.Read(ioutil.Discard, tcpip.ReadOptions{})\n- if _, ok := err.(*tcpip.ErrWouldBlock); ok {\n+ if cmp.Equal(&tcpip.ErrWouldBlock{}, err) {\nbreak\n}\n}\n@@ -6480,7 +6480,7 @@ func TestReceiveBufferAutoTuning(t *testing.T) {\ntotalCopied := 0\nfor {\nres, err := c.EP.Read(ioutil.Discard, tcpip.ReadOptions{})\n- if _, ok := err.(*tcpip.ErrWouldBlock); ok {\n+ if cmp.Equal(&tcpip.ErrWouldBlock{}, err) {\nbreak\n}\ntotalCopied += res.Count\n@@ -6672,7 +6672,7 @@ func TestTCPTimeWaitRSTIgnored(t *testing.T) {\ndefer wq.EventUnregister(&we)\nc.EP, _, err = ep.Accept(nil)\n- if _, ok := err.(*tcpip.ErrWouldBlock); ok {\n+ if cmp.Equal(&tcpip.ErrWouldBlock{}, err) {\n// Wait for connection to be established.\nselect {\ncase <-ch:\n@@ -6791,7 +6791,7 @@ func TestTCPTimeWaitOutOfOrder(t *testing.T) {\ndefer wq.EventUnregister(&we)\nc.EP, _, err = ep.Accept(nil)\n- if _, ok := err.(*tcpip.ErrWouldBlock); ok {\n+ if cmp.Equal(&tcpip.ErrWouldBlock{}, err) {\n// Wait for connection to be established.\nselect {\ncase <-ch:\n@@ -6898,7 +6898,7 @@ func TestTCPTimeWaitNewSyn(t *testing.T) {\ndefer wq.EventUnregister(&we)\nc.EP, _, err = ep.Accept(nil)\n- if _, ok := err.(*tcpip.ErrWouldBlock); ok {\n+ if cmp.Equal(&tcpip.ErrWouldBlock{}, err) {\n// Wait for connection to be established.\nselect {\ncase <-ch:\n@@ -6988,7 +6988,7 @@ func TestTCPTimeWaitNewSyn(t *testing.T) {\n// Try to accept the connection.\nc.EP, _, err = ep.Accept(nil)\n- if _, ok := err.(*tcpip.ErrWouldBlock); ok {\n+ if cmp.Equal(&tcpip.ErrWouldBlock{}, err) {\n// Wait for connection to be established.\nselect {\ncase <-ch:\n@@ -7062,7 +7062,7 @@ func TestTCPTimeWaitDuplicateFINExtendsTimeWait(t *testing.T) {\ndefer wq.EventUnregister(&we)\nc.EP, _, err = ep.Accept(nil)\n- if _, ok := err.(*tcpip.ErrWouldBlock); ok {\n+ if cmp.Equal(&tcpip.ErrWouldBlock{}, err) {\n// Wait for connection to be established.\nselect {\ncase <-ch:\n@@ -7212,7 +7212,7 @@ func TestTCPCloseWithData(t *testing.T) {\ndefer wq.EventUnregister(&we)\nc.EP, _, err = ep.Accept(nil)\n- if _, ok := err.(*tcpip.ErrWouldBlock); ok {\n+ if cmp.Equal(&tcpip.ErrWouldBlock{}, err) {\n// Wait for connection to be established.\nselect {\ncase <-ch:\n@@ -7643,8 +7643,8 @@ func TestTCPDeferAccept(t *testing.T) {\nirs, iss := executeHandshake(t, c, context.TestPort, false /* synCookiesInUse */)\n_, _, err := c.EP.Accept(nil)\n- if _, ok := err.(*tcpip.ErrWouldBlock); !ok {\n- t.Fatalf(\"got c.EP.Accept(nil) = %v, want: %s\", err, &tcpip.ErrWouldBlock{})\n+ if d := cmp.Diff(&tcpip.ErrWouldBlock{}, err); d != \"\" {\n+ t.Fatalf(\"c.EP.Accept(nil) mismatch (-want +got):\\n%s\", d)\n}\n// Send data. This should result in an acceptable endpoint.\n@@ -7702,8 +7702,8 @@ func TestTCPDeferAcceptTimeout(t *testing.T) {\nirs, iss := executeHandshake(t, c, context.TestPort, false /* synCookiesInUse */)\n_, _, err := c.EP.Accept(nil)\n- if _, ok := err.(*tcpip.ErrWouldBlock); !ok {\n- t.Fatalf(\"got c.EP.Accept(nil) = %v, want: %s\", err, &tcpip.ErrWouldBlock{})\n+ if d := cmp.Diff(&tcpip.ErrWouldBlock{}, err); d != \"\" {\n+ t.Fatalf(\"c.EP.Accept(nil) mismatch (-want +got):\\n%s\", d)\n}\n// Sleep for a little of the tcpDeferAccept timeout.\n" } ]
Go
Apache License 2.0
google/gvisor
Use cmp.Diff for tcpip.Error comparison PiperOrigin-RevId: 372021039
259,891
04.05.2021 16:49:11
25,200
689b369f5788c15f9b018246baa4e318082c0d79
tcp_socket_test: replace tcp_wmem with SO_SNDBUF
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/BUILD", "new_path": "test/syscalls/linux/BUILD", "diff": "@@ -3710,7 +3710,6 @@ cc_binary(\ndeps = [\n\":socket_test_util\",\n\"//test/util:file_descriptor\",\n- \"@com_google_absl//absl/strings\",\n\"@com_google_absl//absl/time\",\ngtest,\n\"//test/util:posix_error\",\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/tcp_socket.cc", "new_path": "test/syscalls/linux/tcp_socket.cc", "diff": "#include <vector>\n#include \"gtest/gtest.h\"\n-#include \"absl/strings/str_split.h\"\n#include \"absl/time/clock.h\"\n#include \"absl/time/time.h\"\n#include \"test/syscalls/linux/socket_test_util.h\"\n@@ -1145,17 +1144,6 @@ TEST_P(SimpleTcpSocketTest, SelfConnectSendRecv) {\n}\nTEST_P(SimpleTcpSocketTest, SelfConnectSend) {\n- // Ensure the write size is not larger than the write buffer.\n- size_t write_size = 512 << 10; // 512 KiB.\n- constexpr char kWMem[] = \"/proc/sys/net/ipv4/tcp_wmem\";\n- std::string wmem = ASSERT_NO_ERRNO_AND_VALUE(GetContents(kWMem));\n- std::vector<std::string> vals = absl::StrSplit(wmem, absl::ByAnyChar(\"\\t \"));\n- size_t max_wmem;\n- ASSERT_TRUE(absl::SimpleAtoi(vals.back(), &max_wmem));\n- if (write_size > max_wmem) {\n- write_size = max_wmem;\n- }\n-\n// Initialize address to the loopback one.\nsockaddr_storage addr =\nASSERT_NO_ERRNO_AND_VALUE(InetLoopbackAddr(GetParam()));\n@@ -1176,6 +1164,12 @@ TEST_P(SimpleTcpSocketTest, SelfConnectSend) {\nASSERT_THAT(RetryEINTR(connect)(s.get(), AsSockAddr(&addr), addrlen),\nSyscallSucceeds());\n+ // Ensure the write buffer is large enough not to block on a single write.\n+ size_t write_size = 512 << 10; // 512 KiB.\n+ EXPECT_THAT(setsockopt(s.get(), SOL_SOCKET, SO_SNDBUF, &write_size,\n+ sizeof(write_size)),\n+ SyscallSucceedsWithValue(0));\n+\nstd::vector<char> writebuf(write_size);\n// Try to send the whole thing.\n" } ]
Go
Apache License 2.0
google/gvisor
tcp_socket_test: replace tcp_wmem with SO_SNDBUF PiperOrigin-RevId: 372022596
259,985
04.05.2021 17:38:00
25,200
5960674c8fe086413c3ef88b29fbb4c6f4c4ca3f
Document how to handle build failures from go-marshal verbosity. With debugging enabled, go-marshal can generate too much output for bazel under default configurations, which can cause builds to fail. The limit defaults to 1 MB.
[ { "change_type": "MODIFY", "old_path": "tools/go_marshal/README.md", "new_path": "tools/go_marshal/README.md", "diff": "@@ -140,3 +140,6 @@ options, depending on how go-marshal is being invoked:\n- Set `debug = True` on the `go_marshal` BUILD rule.\n- Pass `-debug` to the go-marshal tool invocation.\n+\n+If bazel complains about stdout output being too large, set a larger value\n+through `--experimental_ui_max_stdouterr_bytes`, or `-1` for unlimited output.\n" } ]
Go
Apache License 2.0
google/gvisor
Document how to handle build failures from go-marshal verbosity. With debugging enabled, go-marshal can generate too much output for bazel under default configurations, which can cause builds to fail. The limit defaults to 1 MB. PiperOrigin-RevId: 372030402
259,907
05.05.2021 00:00:52
25,200
d924515b0991a3a14e0b0d7d21268eaed6fafb5b
[perf] Fix profiling in benchmarking jobs. Due to the docker daemon is passing the incorrect `--root` flag to runsc. So our profiler is not able to find the container stat files where it expects them to be.
[ { "change_type": "MODIFY", "old_path": "pkg/test/dockerutil/profile.go", "new_path": "pkg/test/dockerutil/profile.go", "diff": "@@ -82,10 +82,15 @@ func (p *profile) createProcess(c *Container) error {\n}\n// The root directory of this container's runtime.\n- root := fmt.Sprintf(\"--root=/var/run/docker/runtime-%s/moby\", c.runtime)\n+ rootDir := fmt.Sprintf(\"/var/run/docker/runtime-%s/moby\", c.runtime)\n+ if _, err := os.Stat(rootDir); os.IsNotExist(err) {\n+ // In docker v20+, due to https://github.com/moby/moby/issues/42345 the\n+ // rootDir seems to always be the following.\n+ rootDir = \"/var/run/docker/runtime-runc/moby\"\n+ }\n- // Format is `runsc --root=rootdir debug --profile-*=file --duration=24h containerID`.\n- args := []string{root, \"debug\"}\n+ // Format is `runsc --root=rootDir debug --profile-*=file --duration=24h containerID`.\n+ args := []string{fmt.Sprintf(\"--root=%s\", rootDir), \"debug\"}\nfor _, profileArg := range p.Types {\noutputPath := filepath.Join(p.BasePath, fmt.Sprintf(\"%s.pprof\", profileArg))\nargs = append(args, fmt.Sprintf(\"--profile-%s=%s\", profileArg, outputPath))\n" } ]
Go
Apache License 2.0
google/gvisor
[perf] Fix profiling in benchmarking jobs. Due to https://github.com/moby/moby/issues/42345, the docker daemon is passing the incorrect `--root` flag to runsc. So our profiler is not able to find the container stat files where it expects them to be. PiperOrigin-RevId: 372067954
259,891
18.03.2021 15:38:13
25,200
4c9340fcbf0cb10c230925e24f082478f7c458a0
Fix alignment issue with 64-bit atomics on 32 bit machines
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/BUILD", "new_path": "pkg/tcpip/BUILD", "diff": "@@ -19,6 +19,8 @@ go_template_instance(\ngo_library(\nname = \"tcpip\",\nsrcs = [\n+ \"aligned.go\",\n+ \"aligned_unsafe.go\",\n\"errors.go\",\n\"sock_err_list.go\",\n\"socketops.go\",\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/tcpip/aligned.go", "diff": "+// Copyright 2021 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+// +build !arm,!386\n+\n+package tcpip\n+\n+import \"sync/atomic\"\n+\n+// AlignedAtomicInt64 is an atomic int64 that is guaranteed to be 64-bit\n+// aligned, even on 32-bit systems. On 64-bit machines, it's just a regular\n+// int64.\n+//\n+// See aligned_unsafe.go in this directory for justification.\n+type AlignedAtomicInt64 struct {\n+ value int64\n+}\n+\n+func (aa *AlignedAtomicInt64) Load() int64 {\n+ return atomic.LoadInt64(&aa.value)\n+}\n+\n+func (aa *AlignedAtomicInt64) Store(v int64) {\n+ atomic.StoreInt64(&aa.value, v)\n+}\n+\n+func (aa *AlignedAtomicInt64) Add(v int64) int64 {\n+ return atomic.AddInt64(&aa.value, v)\n+}\n+\n+// AlignedAtomicUint64 is an atomic uint64 that is guaranteed to be 64-bit\n+// aligned, even on 32-bit systems. On 64-bit machines, it's just a regular\n+// uint64.\n+//\n+// See aligned_unsafe.go in this directory for justification.\n+type AlignedAtomicUint64 struct {\n+ value uint64\n+}\n+\n+func (aa *AlignedAtomicUint64) Load() uint64 {\n+ return atomic.LoadUint64(&aa.value)\n+}\n+\n+func (aa *AlignedAtomicUint64) Store(v uint64) {\n+ atomic.StoreUint64(&aa.value, v)\n+}\n+\n+func (aa *AlignedAtomicUint64) Add(v uint64) uint64 {\n+ return atomic.AddUint64(&aa.value, v)\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/tcpip/aligned_unsafe.go", "diff": "+// Copyright 2021 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+// +build arm 386\n+\n+package tcpip\n+\n+import (\n+ \"sync/atomic\"\n+ \"unsafe\"\n+)\n+\n+// AlignedAtomicInt64 is an atomic int64 that is guaranteed to be 64-bit\n+// aligned, even on 32-bit systems.\n+//\n+// Per https://golang.org/pkg/sync/atomic/#pkg-note-BUG:\n+//\n+// \"On ARM, 386, and 32-bit MIPS, it is the caller's responsibility to arrange\n+// for 64-bit alignment of 64-bit words accessed atomically. The first word in\n+// a variable or in an allocated struct, array, or slice can be relied upon to\n+// be 64-bit aligned.\"\n+type AlignedAtomicInt64 struct {\n+ value [15]byte\n+}\n+\n+func (aa *AlignedAtomicInt64) ptr() *int64 {\n+ return (*int64)(unsafe.Pointer((uintptr(unsafe.Pointer(&aa.value)) + 7) &^ 7))\n+}\n+\n+func (aa *AlignedAtomicInt64) Load() int64 {\n+ return atomic.LoadInt64(aa.ptr())\n+}\n+\n+func (aa *AlignedAtomicInt64) Store(v int64) {\n+ atomic.StoreInt64(aa.ptr(), v)\n+}\n+\n+func (aa *AlignedAtomicInt64) Add(v int64) int64 {\n+ return atomic.AddInt64(aa.ptr(), v)\n+}\n+\n+// AlignedAtomicUint64 is an atomic uint64 that is guaranteed to be 64-bit\n+// aligned, even on 32-bit systems.\n+//\n+// Per https://golang.org/pkg/sync/atomic/#pkg-note-BUG:\n+//\n+// \"On ARM, 386, and 32-bit MIPS, it is the caller's responsibility to arrange\n+// for 64-bit alignment of 64-bit words accessed atomically. The first word in\n+// a variable or in an allocated struct, array, or slice can be relied upon to\n+// be 64-bit aligned.\"\n+type AlignedAtomicUint64 struct {\n+ value [15]byte\n+}\n+\n+func (aa *AlignedAtomicUint64) ptr() *uint64 {\n+ return (*uint64)(unsafe.Pointer((uintptr(unsafe.Pointer(&aa.value)) + 7) &^ 7))\n+}\n+\n+func (aa *AlignedAtomicUint64) Load() uint64 {\n+ return atomic.LoadUint64(aa.ptr())\n+}\n+\n+func (aa *AlignedAtomicUint64) Store(v uint64) {\n+ atomic.StoreUint64(aa.ptr(), v)\n+}\n+\n+func (aa *AlignedAtomicUint64) Add(v uint64) uint64 {\n+ return atomic.AddUint64(aa.ptr(), v)\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/socketops.go", "new_path": "pkg/tcpip/socketops.go", "diff": "@@ -213,7 +213,7 @@ type SocketOptions struct {\ngetSendBufferLimits GetSendBufferLimits `state:\"manual\"`\n// sendBufferSize determines the send buffer size for this socket.\n- sendBufferSize int64\n+ sendBufferSize AlignedAtomicInt64\n// getReceiveBufferLimits provides the handler to get the min, default and\n// max size for receive buffer. It is initialized at the creation time and\n@@ -612,7 +612,7 @@ func (so *SocketOptions) SetBindToDevice(bindToDevice int32) Error {\n// GetSendBufferSize gets value for SO_SNDBUF option.\nfunc (so *SocketOptions) GetSendBufferSize() int64 {\n- return atomic.LoadInt64(&so.sendBufferSize)\n+ return so.sendBufferSize.Load()\n}\n// SetSendBufferSize sets value for SO_SNDBUF option. notify indicates if the\n@@ -621,7 +621,7 @@ func (so *SocketOptions) SetSendBufferSize(sendBufferSize int64, notify bool) {\nv := sendBufferSize\nif !notify {\n- atomic.StoreInt64(&so.sendBufferSize, v)\n+ so.sendBufferSize.Store(v)\nreturn\n}\n@@ -647,7 +647,7 @@ func (so *SocketOptions) SetSendBufferSize(sendBufferSize int64, notify bool) {\n// Notify endpoint about change in buffer size.\nnewSz := so.handler.OnSetSendBufferSize(v)\n- atomic.StoreInt64(&so.sendBufferSize, newSz)\n+ so.sendBufferSize.Store(newSz)\n}\n// GetReceiveBufferSize gets value for SO_RCVBUF option.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/tcpip.go", "new_path": "pkg/tcpip/tcpip.go", "diff": "@@ -1220,7 +1220,7 @@ type NetworkProtocolNumber uint32\n// A StatCounter keeps track of a statistic.\ntype StatCounter struct {\n- count uint64\n+ count AlignedAtomicUint64\n}\n// Increment adds one to the counter.\n@@ -1240,7 +1240,7 @@ func (s *StatCounter) Value(name ...string) uint64 {\n// IncrementBy increments the counter by v.\nfunc (s *StatCounter) IncrementBy(v uint64) {\n- atomic.AddUint64(&s.count, v)\n+ s.count.Add(v)\n}\nfunc (s *StatCounter) String() string {\n" } ]
Go
Apache License 2.0
google/gvisor
Fix alignment issue with 64-bit atomics on 32 bit machines
259,891
19.03.2021 13:44:26
25,200
1e2ba2666135e7f28cb3c4185add5a257ad53637
Moved to atomicbitops and renamed files
[ { "change_type": "MODIFY", "old_path": "pkg/atomicbitops/BUILD", "new_path": "pkg/atomicbitops/BUILD", "diff": "@@ -5,6 +5,8 @@ package(licenses = [\"notice\"])\ngo_library(\nname = \"atomicbitops\",\nsrcs = [\n+ \"aligned_32bit_unsafe.go\",\n+ \"aligned_64bit.go\",\n\"atomicbitops.go\",\n\"atomicbitops_amd64.s\",\n\"atomicbitops_arm64.s\",\n" }, { "change_type": "RENAME", "old_path": "pkg/tcpip/aligned_unsafe.go", "new_path": "pkg/atomicbitops/aligned_32bit_unsafe.go", "diff": "// +build arm 386\n-package tcpip\n+package atomicbitops\nimport (\n\"sync/atomic\"\n" }, { "change_type": "RENAME", "old_path": "pkg/tcpip/aligned.go", "new_path": "pkg/atomicbitops/aligned_64bit.go", "diff": "// +build !arm,!386\n-package tcpip\n+package atomicbitops\nimport \"sync/atomic\"\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/BUILD", "new_path": "pkg/tcpip/BUILD", "diff": "@@ -19,8 +19,6 @@ go_template_instance(\ngo_library(\nname = \"tcpip\",\nsrcs = [\n- \"aligned.go\",\n- \"aligned_unsafe.go\",\n\"errors.go\",\n\"sock_err_list.go\",\n\"socketops.go\",\n@@ -31,6 +29,7 @@ go_library(\n],\nvisibility = [\"//visibility:public\"],\ndeps = [\n+ \"//pkg/atomicbitops\",\n\"//pkg/sync\",\n\"//pkg/tcpip/buffer\",\n\"//pkg/waiter\",\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/socketops.go", "new_path": "pkg/tcpip/socketops.go", "diff": "@@ -18,6 +18,7 @@ import (\n\"math\"\n\"sync/atomic\"\n+ \"gvisor.dev/gvisor/pkg/atomicbitops\"\n\"gvisor.dev/gvisor/pkg/sync\"\n)\n@@ -213,7 +214,7 @@ type SocketOptions struct {\ngetSendBufferLimits GetSendBufferLimits `state:\"manual\"`\n// sendBufferSize determines the send buffer size for this socket.\n- sendBufferSize AlignedAtomicInt64\n+ sendBufferSize atomicbitops.AlignedAtomicInt64\n// getReceiveBufferLimits provides the handler to get the min, default and\n// max size for receive buffer. It is initialized at the creation time and\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/BUILD", "new_path": "pkg/tcpip/stack/BUILD", "diff": "@@ -73,6 +73,7 @@ go_library(\n],\nvisibility = [\"//visibility:public\"],\ndeps = [\n+ \"//pkg/atomicbitops\",\n\"//pkg/ilist\",\n\"//pkg/log\",\n\"//pkg/rand\",\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/stack.go", "new_path": "pkg/tcpip/stack/stack.go", "diff": "@@ -29,6 +29,7 @@ import (\n\"time\"\n\"golang.org/x/time/rate\"\n+ \"gvisor.dev/gvisor/pkg/atomicbitops\"\n\"gvisor.dev/gvisor/pkg/rand\"\n\"gvisor.dev/gvisor/pkg/sync\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n@@ -65,10 +66,10 @@ type ResumableEndpoint interface {\n}\n// uniqueIDGenerator is a default unique ID generator.\n-type uniqueIDGenerator uint64\n+type uniqueIDGenerator atomicbitops.AlignedAtomicUint64\nfunc (u *uniqueIDGenerator) UniqueID() uint64 {\n- return atomic.AddUint64((*uint64)(u), 1)\n+ return ((*atomicbitops.AlignedAtomicUint64)(u)).Add(1)\n}\n// Stack is a networking stack, with all supported protocols, NICs, and route\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/tcpip.go", "new_path": "pkg/tcpip/tcpip.go", "diff": "@@ -40,6 +40,7 @@ import (\n\"sync/atomic\"\n\"time\"\n+ \"gvisor.dev/gvisor/pkg/atomicbitops\"\n\"gvisor.dev/gvisor/pkg/sync\"\n\"gvisor.dev/gvisor/pkg/waiter\"\n)\n@@ -1220,7 +1221,7 @@ type NetworkProtocolNumber uint32\n// A StatCounter keeps track of a statistic.\ntype StatCounter struct {\n- count AlignedAtomicUint64\n+ count atomicbitops.AlignedAtomicUint64\n}\n// Increment adds one to the counter.\n" } ]
Go
Apache License 2.0
google/gvisor
Moved to atomicbitops and renamed files
259,891
05.04.2021 11:54:50
25,200
eded0d28de7f62423e496d89fd2699bb02e2744f
mark types as saveable
[ { "change_type": "MODIFY", "old_path": "pkg/atomicbitops/aligned_32bit_unsafe.go", "new_path": "pkg/atomicbitops/aligned_32bit_unsafe.go", "diff": "@@ -30,6 +30,8 @@ import (\n// for 64-bit alignment of 64-bit words accessed atomically. The first word in\n// a variable or in an allocated struct, array, or slice can be relied upon to\n// be 64-bit aligned.\"\n+//\n+// +stateify savable\ntype AlignedAtomicInt64 struct {\nvalue [15]byte\n}\n@@ -65,6 +67,8 @@ func (aa *AlignedAtomicInt64) Add(v int64) int64 {\n// for 64-bit alignment of 64-bit words accessed atomically. The first word in\n// a variable or in an allocated struct, array, or slice can be relied upon to\n// be 64-bit aligned.\"\n+//\n+// +stateify savable\ntype AlignedAtomicUint64 struct {\nvalue [15]byte\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/atomicbitops/aligned_64bit.go", "new_path": "pkg/atomicbitops/aligned_64bit.go", "diff": "@@ -23,6 +23,8 @@ import \"sync/atomic\"\n// int64.\n//\n// See aligned_unsafe.go in this directory for justification.\n+//\n+// +stateify savable\ntype AlignedAtomicInt64 struct {\nvalue int64\n}\n@@ -47,6 +49,8 @@ func (aa *AlignedAtomicInt64) Add(v int64) int64 {\n// uint64.\n//\n// See aligned_unsafe.go in this directory for justification.\n+//\n+// +stateify savable\ntype AlignedAtomicUint64 struct {\nvalue uint64\n}\n" } ]
Go
Apache License 2.0
google/gvisor
mark types as saveable
259,891
06.05.2021 15:01:09
25,200
66de003e19642b5d6eb6d3f7660ad638271f3477
fix build constraints
[ { "change_type": "MODIFY", "old_path": "pkg/atomicbitops/aligned_64bit.go", "new_path": "pkg/atomicbitops/aligned_64bit.go", "diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-// +build !arm,!386\n+// +build amd64 arm64\npackage atomicbitops\n" }, { "change_type": "MODIFY", "old_path": "tools/bazeldefs/tags.bzl", "new_path": "tools/bazeldefs/tags.bzl", "diff": "@@ -33,6 +33,10 @@ archs = [\n\"_s390x\",\n\"_sparc64\",\n\"_x86\",\n+\n+ # Pseudo-architectures to group by word side.\n+ \"_32bit\",\n+ \"_64bit\",\n]\noses = [\n" } ]
Go
Apache License 2.0
google/gvisor
fix build constraints
259,878
06.05.2021 18:00:49
25,200
339001204000a3060628256cd9131ea2a2d4e08a
Implement /proc/cmdline This change implements /proc/cmdline with a basic faux command line "BOOT_IMAGE=/vmlinuz-[version]-gvisor quiet" so apps that may expect it do not receive errors. Also tests for the existence of /proc/cmdline as part of the system call test suite
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/proc/tasks.go", "new_path": "pkg/sentry/fsimpl/proc/tasks.go", "diff": "@@ -65,6 +65,7 @@ var _ kernfs.Inode = (*tasksInode)(nil)\nfunc (fs *filesystem) newTasksInode(ctx context.Context, k *kernel.Kernel, pidns *kernel.PIDNamespace, fakeCgroupControllers map[string]string) *tasksInode {\nroot := auth.NewRootCredentials(pidns.UserNamespace())\ncontents := map[string]kernfs.Inode{\n+ \"cmdline\": fs.newInode(ctx, root, 0444, &cmdLineData{}),\n\"cpuinfo\": fs.newInode(ctx, root, 0444, newStaticFileSetStat(cpuInfoData(k))),\n\"filesystems\": fs.newInode(ctx, root, 0444, &filesystemsData{}),\n\"loadavg\": fs.newInode(ctx, root, 0444, &loadavgData{}),\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/proc/tasks_files.go", "new_path": "pkg/sentry/fsimpl/proc/tasks_files.go", "diff": "@@ -336,15 +336,6 @@ var _ dynamicInode = (*versionData)(nil)\n// Generate implements vfs.DynamicBytesSource.Generate.\nfunc (*versionData) Generate(ctx context.Context, buf *bytes.Buffer) error {\n- k := kernel.KernelFromContext(ctx)\n- init := k.GlobalInit()\n- if init == nil {\n- // Attempted to read before the init Task is created. This can\n- // only occur during startup, which should never need to read\n- // this file.\n- panic(\"Attempted to read version before initial Task is available\")\n- }\n-\n// /proc/version takes the form:\n//\n// \"SYSNAME version RELEASE (COMPILE_USER@COMPILE_HOST)\n@@ -364,7 +355,7 @@ func (*versionData) Generate(ctx context.Context, buf *bytes.Buffer) error {\n// FIXME(mpratt): Using Version from the init task SyscallTable\n// disregards the different version a task may have (e.g., in a uts\n// namespace).\n- ver := init.Leader().SyscallTable().Version\n+ ver := kernelVersion(ctx)\nfmt.Fprintf(buf, \"%s version %s %s\\n\", ver.Sysname, ver.Release, ver.Version)\nreturn nil\n}\n@@ -400,3 +391,31 @@ func (*cgroupsData) Generate(ctx context.Context, buf *bytes.Buffer) error {\nr.GenerateProcCgroups(buf)\nreturn nil\n}\n+\n+// cmdLineData backs /proc/cmdline.\n+//\n+// +stateify savable\n+type cmdLineData struct {\n+ dynamicBytesFileSetAttr\n+}\n+\n+var _ dynamicInode = (*cmdLineData)(nil)\n+\n+// Generate implements vfs.DynamicByteSource.Generate.\n+func (*cmdLineData) Generate(ctx context.Context, buf *bytes.Buffer) error {\n+ fmt.Fprintf(buf, \"BOOT_IMAGE=/vmlinuz-%s-gvisor quiet\\n\", kernelVersion(ctx).Release)\n+ return nil\n+}\n+\n+// kernelVersion returns the kernel version.\n+func kernelVersion(ctx context.Context) kernel.Version {\n+ k := kernel.KernelFromContext(ctx)\n+ init := k.GlobalInit()\n+ if init == nil {\n+ // Attempted to read before the init Task is created. This can\n+ // only occur during startup, which should never need to read\n+ // this file.\n+ panic(\"Attempted to read version before initial Task is available\")\n+ }\n+ return init.Leader().SyscallTable().Version\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/proc/tasks_test.go", "new_path": "pkg/sentry/fsimpl/proc/tasks_test.go", "diff": "@@ -47,6 +47,7 @@ var (\nvar (\ntasksStaticFiles = map[string]testutil.DirentType{\n+ \"cmdline\": linux.DT_REG,\n\"cpuinfo\": linux.DT_REG,\n\"filesystems\": linux.DT_REG,\n\"loadavg\": linux.DT_REG,\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/proc.cc", "new_path": "test/syscalls/linux/proc.cc", "diff": "@@ -1201,6 +1201,15 @@ TEST(ProcSelfCwd, Absolute) {\nEXPECT_EQ(exe[0], '/');\n}\n+// Sanity check that /proc/cmdline is present.\n+TEST(ProcCmdline, IsPresent) {\n+ SKIP_IF(IsRunningWithVFS1());\n+\n+ std::string proc_cmdline =\n+ ASSERT_NO_ERRNO_AND_VALUE(GetContents(\"/proc/cmdline\"));\n+ ASSERT_FALSE(proc_cmdline.empty());\n+}\n+\n// Sanity check for /proc/cpuinfo fields that must be present.\nTEST(ProcCpuinfo, RequiredFieldsArePresent) {\nstd::string proc_cpuinfo =\n" } ]
Go
Apache License 2.0
google/gvisor
Implement /proc/cmdline This change implements /proc/cmdline with a basic faux command line "BOOT_IMAGE=/vmlinuz-[version]-gvisor quiet" so apps that may expect it do not receive errors. Also tests for the existence of /proc/cmdline as part of the system call test suite PiperOrigin-RevId: 372462070
259,891
07.05.2021 13:51:09
25,200
314a5f8d7e7402e66ba5d22f79fa13143a7b69d0
explicitly 0-index backing array
[ { "change_type": "MODIFY", "old_path": "pkg/atomicbitops/aligned_32bit_unsafe.go", "new_path": "pkg/atomicbitops/aligned_32bit_unsafe.go", "diff": "@@ -40,7 +40,7 @@ func (aa *AlignedAtomicInt64) ptr() *int64 {\n// In the 15-byte aa.value, there are guaranteed to be 8 contiguous\n// bytes with 64-bit alignment. We find an address in this range by\n// adding 7, then clear the 3 least significant bits to get its start.\n- return (*int64)(unsafe.Pointer((uintptr(unsafe.Pointer(&aa.value)) + 7) &^ 7))\n+ return (*int64)(unsafe.Pointer((uintptr(unsafe.Pointer(&aa.value[0])) + 7) &^ 7))\n}\n// Load is analagous to atomic.LoadInt64.\n@@ -77,7 +77,7 @@ func (aa *AlignedAtomicUint64) ptr() *uint64 {\n// In the 15-byte aa.value, there are guaranteed to be 8 contiguous\n// bytes with 64-bit alignment. We find an address in this range by\n// adding 7, then clear the 3 least significant bits to get its start.\n- return (*uint64)(unsafe.Pointer((uintptr(unsafe.Pointer(&aa.value)) + 7) &^ 7))\n+ return (*uint64)(unsafe.Pointer((uintptr(unsafe.Pointer(&aa.value[0])) + 7) &^ 7))\n}\n// Load is analagous to atomic.LoadUint64.\n" } ]
Go
Apache License 2.0
google/gvisor
explicitly 0-index backing array
259,884
10.05.2021 17:27:08
25,200
1699d702cbfcf6f34bd14327b644738f996feb3b
Fix issue reviver Fixes invocation of the Github issue reviver by including the required 'path' command line option. Also updates the issue reviver to add a 'revived' label to revived issues. Issues with a 'revived' label will no longer be marked as stale.
[ { "change_type": "MODIFY", "old_path": ".github/workflows/issue_reviver.yml", "new_path": ".github/workflows/issue_reviver.yml", "diff": "@@ -11,7 +11,7 @@ jobs:\nsteps:\n- uses: actions/checkout@v2\nif: github.repository == 'google/gvisor'\n- - run: make run TARGETS=\"//tools/github\" ARGS=\"revive\"\n+ - run: make run TARGETS=\"//tools/github\" ARGS=\"-path=. revive\"\nif: github.repository == 'google/gvisor'\nenv:\nGITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n" }, { "change_type": "MODIFY", "old_path": ".github/workflows/stale.yml", "new_path": ".github/workflows/stale.yml", "diff": "@@ -14,7 +14,7 @@ jobs:\nrepo-token: ${{ secrets.GITHUB_TOKEN }}\nstale-issue-label: 'stale'\nstale-pr-label: 'stale'\n- exempt-issue-labels: 'exported, type: bug, type: cleanup, type: enhancement, type: process, type: proposal, type: question'\n+ exempt-issue-labels: 'revived, exported, type: bug, type: cleanup, type: enhancement, type: process, type: proposal, type: question'\nexempt-pr-labels: 'ready to pull, exported'\nstale-issue-message: 'This issue is stale because it has been open 90 days with no activity. Remove the stale label or comment or this will be closed in 30 days.'\nstale-pr-message: 'This pull request is stale because it has been open 90 days with no activity. Remove the stale label or comment or this will be closed in 30 days.'\n" }, { "change_type": "MODIFY", "old_path": "tools/github/reviver/github.go", "new_path": "tools/github/reviver/github.go", "diff": "@@ -110,6 +110,11 @@ func (b *GitHubBugger) Activate(todo *Todo) (bool, error) {\nreturn true, fmt.Errorf(\"failed to reactivate issue %d: %v\", id, err)\n}\n+ _, _, err = b.client.Issues.AddLabelsToIssue(ctx, b.owner, b.repo, id, []string{\"revived\"})\n+ if err != nil {\n+ return true, fmt.Errorf(\"failed to set label on issue %d: %v\", id, err)\n+ }\n+\ncmt := &github.IssueComment{\nBody: github.String(comment.String()),\nReactions: &github.Reactions{Confused: github.Int(1)},\n" } ]
Go
Apache License 2.0
google/gvisor
Fix issue reviver Fixes invocation of the Github issue reviver by including the required 'path' command line option. Also updates the issue reviver to add a 'revived' label to revived issues. Issues with a 'revived' label will no longer be marked as stale. PiperOrigin-RevId: 373046772
259,951
11.05.2021 10:23:06
25,200
60bdf7ed31bc32bb8413cfdb67cd906ca3d5955a
Move multicounter testutil functions out of network/ip This is in preparation of having aggregated NIC stats at the stack level. These validation functions will be needed outside of the network layer packages to test aggregated NIC stats.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/arp/BUILD", "new_path": "pkg/tcpip/network/arp/BUILD", "diff": "@@ -47,7 +47,7 @@ go_test(\nlibrary = \":arp\",\ndeps = [\n\"//pkg/tcpip\",\n- \"//pkg/tcpip/network/internal/testutil\",\n\"//pkg/tcpip/stack\",\n+ \"//pkg/tcpip/testutil\",\n],\n)\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/arp/stats_test.go", "new_path": "pkg/tcpip/network/arp/stats_test.go", "diff": "@@ -19,8 +19,8 @@ import (\n\"testing\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n- \"gvisor.dev/gvisor/pkg/tcpip/network/internal/testutil\"\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/testutil\"\n)\nvar _ stack.NetworkInterface = (*testInterface)(nil)\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/internal/testutil/BUILD", "new_path": "pkg/tcpip/network/internal/testutil/BUILD", "diff": "@@ -4,10 +4,7 @@ package(licenses = [\"notice\"])\ngo_library(\nname = \"testutil\",\n- srcs = [\n- \"testutil.go\",\n- \"testutil_unsafe.go\",\n- ],\n+ srcs = [\"testutil.go\"],\nvisibility = [\n\"//pkg/tcpip/network/arp:__pkg__\",\n\"//pkg/tcpip/network/internal/fragmentation:__pkg__\",\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/internal/testutil/testutil.go", "new_path": "pkg/tcpip/network/internal/testutil/testutil.go", "diff": "@@ -19,8 +19,6 @@ package testutil\nimport (\n\"fmt\"\n\"math/rand\"\n- \"reflect\"\n- \"strings\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n@@ -129,69 +127,3 @@ func MakeRandPkt(transportHeaderLength int, extraHeaderReserveLength int, viewSi\n}\nreturn pkt\n}\n-\n-func checkFieldCounts(ref, multi reflect.Value) error {\n- refTypeName := ref.Type().Name()\n- multiTypeName := multi.Type().Name()\n- refNumField := ref.NumField()\n- multiNumField := multi.NumField()\n-\n- if refNumField != multiNumField {\n- return fmt.Errorf(\"type %s has an incorrect number of fields: got = %d, want = %d (same as type %s)\", multiTypeName, multiNumField, refNumField, refTypeName)\n- }\n-\n- return nil\n-}\n-\n-func validateField(ref reflect.Value, refName string, m tcpip.MultiCounterStat, multiName string) error {\n- s, ok := ref.Addr().Interface().(**tcpip.StatCounter)\n- if !ok {\n- return fmt.Errorf(\"expected ref type's to be *StatCounter, but its type is %s\", ref.Type().Elem().Name())\n- }\n-\n- // The field names are expected to match (case insensitive).\n- if !strings.EqualFold(refName, multiName) {\n- return fmt.Errorf(\"wrong field name: got = %s, want = %s\", multiName, refName)\n- }\n-\n- base := (*s).Value()\n- m.Increment()\n- if (*s).Value() != base+1 {\n- return fmt.Errorf(\"updates to the '%s MultiCounterStat' counters are not reflected in the '%s CounterStat'\", multiName, refName)\n- }\n-\n- return nil\n-}\n-\n-// ValidateMultiCounterStats verifies that every counter stored in multi is\n-// correctly tracking its counterpart in the given counters.\n-func ValidateMultiCounterStats(multi reflect.Value, counters []reflect.Value) error {\n- for _, c := range counters {\n- if err := checkFieldCounts(c, multi); err != nil {\n- return err\n- }\n- }\n-\n- for i := 0; i < multi.NumField(); i++ {\n- multiName := multi.Type().Field(i).Name\n- multiUnsafe := unsafeExposeUnexportedFields(multi.Field(i))\n-\n- if m, ok := multiUnsafe.Addr().Interface().(*tcpip.MultiCounterStat); ok {\n- for _, c := range counters {\n- if err := validateField(unsafeExposeUnexportedFields(c.Field(i)), c.Type().Field(i).Name, *m, multiName); err != nil {\n- return err\n- }\n- }\n- } else {\n- var countersNextField []reflect.Value\n- for _, c := range counters {\n- countersNextField = append(countersNextField, c.Field(i))\n- }\n- if err := ValidateMultiCounterStats(multi.Field(i), countersNextField); err != nil {\n- return err\n- }\n- }\n- }\n-\n- return nil\n-}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv4/BUILD", "new_path": "pkg/tcpip/network/ipv4/BUILD", "diff": "@@ -62,7 +62,7 @@ go_test(\nlibrary = \":ipv4\",\ndeps = [\n\"//pkg/tcpip\",\n- \"//pkg/tcpip/network/internal/testutil\",\n\"//pkg/tcpip/stack\",\n+ \"//pkg/tcpip/testutil\",\n],\n)\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv4/stats_test.go", "new_path": "pkg/tcpip/network/ipv4/stats_test.go", "diff": "@@ -19,8 +19,8 @@ import (\n\"testing\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n- \"gvisor.dev/gvisor/pkg/tcpip/network/internal/testutil\"\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/testutil\"\n)\nvar _ stack.NetworkInterface = (*testInterface)(nil)\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/BUILD", "new_path": "pkg/tcpip/network/ipv6/BUILD", "diff": "@@ -45,6 +45,7 @@ go_test(\n\"//pkg/tcpip/link/sniffer\",\n\"//pkg/tcpip/network/internal/testutil\",\n\"//pkg/tcpip/stack\",\n+ \"//pkg/tcpip/testutil\",\n\"//pkg/tcpip/transport/icmp\",\n\"//pkg/tcpip/transport/tcp\",\n\"//pkg/tcpip/transport/udp\",\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/ipv6_test.go", "new_path": "pkg/tcpip/network/ipv6/ipv6_test.go", "diff": "@@ -31,8 +31,9 @@ import (\n\"gvisor.dev/gvisor/pkg/tcpip/faketime\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n\"gvisor.dev/gvisor/pkg/tcpip/link/channel\"\n- \"gvisor.dev/gvisor/pkg/tcpip/network/internal/testutil\"\n+ iptestutil \"gvisor.dev/gvisor/pkg/tcpip/network/internal/testutil\"\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/testutil\"\n\"gvisor.dev/gvisor/pkg/tcpip/transport/icmp\"\n\"gvisor.dev/gvisor/pkg/tcpip/transport/tcp\"\n\"gvisor.dev/gvisor/pkg/tcpip/transport/udp\"\n@@ -2603,7 +2604,7 @@ func TestWriteStats(t *testing.T) {\nt.Run(writer.name, func(t *testing.T) {\nfor _, test := range tests {\nt.Run(test.name, func(t *testing.T) {\n- ep := testutil.NewMockLinkEndpoint(header.IPv6MinimumMTU, &tcpip.ErrInvalidEndpointState{}, test.allowPackets)\n+ ep := iptestutil.NewMockLinkEndpoint(header.IPv6MinimumMTU, &tcpip.ErrInvalidEndpointState{}, test.allowPackets)\nrt := buildRoute(t, ep)\nvar pkts stack.PacketBufferList\nfor i := 0; i < nPackets; i++ {\n@@ -2802,9 +2803,9 @@ func TestFragmentationWritePacket(t *testing.T) {\nfor _, ft := range fragmentationTests {\nt.Run(ft.description, func(t *testing.T) {\n- pkt := testutil.MakeRandPkt(ft.transHdrLen, extraHeaderReserve+header.IPv6MinimumSize, []int{ft.payloadSize}, header.IPv6ProtocolNumber)\n+ pkt := iptestutil.MakeRandPkt(ft.transHdrLen, extraHeaderReserve+header.IPv6MinimumSize, []int{ft.payloadSize}, header.IPv6ProtocolNumber)\nsource := pkt.Clone()\n- ep := testutil.NewMockLinkEndpoint(ft.mtu, nil, math.MaxInt32)\n+ ep := iptestutil.NewMockLinkEndpoint(ft.mtu, nil, math.MaxInt32)\nr := buildRoute(t, ep)\nerr := r.WritePacket(stack.NetworkHeaderParams{\nProtocol: tcp.ProtocolNumber,\n@@ -2858,7 +2859,7 @@ func TestFragmentationWritePackets(t *testing.T) {\ninsertAfter: 1,\n},\n}\n- tinyPacket := testutil.MakeRandPkt(header.TCPMinimumSize, extraHeaderReserve+header.IPv6MinimumSize, []int{1}, header.IPv6ProtocolNumber)\n+ tinyPacket := iptestutil.MakeRandPkt(header.TCPMinimumSize, extraHeaderReserve+header.IPv6MinimumSize, []int{1}, header.IPv6ProtocolNumber)\nfor _, test := range tests {\nt.Run(test.description, func(t *testing.T) {\n@@ -2868,14 +2869,14 @@ func TestFragmentationWritePackets(t *testing.T) {\nfor i := 0; i < test.insertBefore; i++ {\npkts.PushBack(tinyPacket.Clone())\n}\n- pkt := testutil.MakeRandPkt(ft.transHdrLen, extraHeaderReserve+header.IPv6MinimumSize, []int{ft.payloadSize}, header.IPv6ProtocolNumber)\n+ pkt := iptestutil.MakeRandPkt(ft.transHdrLen, extraHeaderReserve+header.IPv6MinimumSize, []int{ft.payloadSize}, header.IPv6ProtocolNumber)\nsource := pkt\npkts.PushBack(pkt.Clone())\nfor i := 0; i < test.insertAfter; i++ {\npkts.PushBack(tinyPacket.Clone())\n}\n- ep := testutil.NewMockLinkEndpoint(ft.mtu, nil, math.MaxInt32)\n+ ep := iptestutil.NewMockLinkEndpoint(ft.mtu, nil, math.MaxInt32)\nr := buildRoute(t, ep)\nwantTotalPackets := len(ft.wantFragments) + test.insertBefore + test.insertAfter\n@@ -2980,8 +2981,8 @@ func TestFragmentationErrors(t *testing.T) {\nfor _, ft := range tests {\nt.Run(ft.description, func(t *testing.T) {\n- pkt := testutil.MakeRandPkt(ft.transHdrLen, extraHeaderReserve+header.IPv6MinimumSize, []int{ft.payloadSize}, header.IPv6ProtocolNumber)\n- ep := testutil.NewMockLinkEndpoint(ft.mtu, ft.mockError, ft.allowPackets)\n+ pkt := iptestutil.MakeRandPkt(ft.transHdrLen, extraHeaderReserve+header.IPv6MinimumSize, []int{ft.payloadSize}, header.IPv6ProtocolNumber)\n+ ep := iptestutil.NewMockLinkEndpoint(ft.mtu, ft.mockError, ft.allowPackets)\nr := buildRoute(t, ep)\nerr := r.WritePacket(stack.NetworkHeaderParams{\nProtocol: tcp.ProtocolNumber,\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/testutil/BUILD", "new_path": "pkg/tcpip/testutil/BUILD", "diff": "@@ -5,7 +5,10 @@ package(licenses = [\"notice\"])\ngo_library(\nname = \"testutil\",\ntestonly = True,\n- srcs = [\"testutil.go\"],\n+ srcs = [\n+ \"testutil.go\",\n+ \"testutil_unsafe.go\",\n+ ],\nvisibility = [\"//visibility:public\"],\ndeps = [\"//pkg/tcpip\"],\n)\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/testutil/testutil.go", "new_path": "pkg/tcpip/testutil/testutil.go", "diff": "@@ -18,6 +18,8 @@ package testutil\nimport (\n\"fmt\"\n\"net\"\n+ \"reflect\"\n+ \"strings\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n)\n@@ -41,3 +43,69 @@ func MustParse6(addr string) tcpip.Address {\n}\nreturn tcpip.Address(ip)\n}\n+\n+func checkFieldCounts(ref, multi reflect.Value) error {\n+ refTypeName := ref.Type().Name()\n+ multiTypeName := multi.Type().Name()\n+ refNumField := ref.NumField()\n+ multiNumField := multi.NumField()\n+\n+ if refNumField != multiNumField {\n+ return fmt.Errorf(\"type %s has an incorrect number of fields: got = %d, want = %d (same as type %s)\", multiTypeName, multiNumField, refNumField, refTypeName)\n+ }\n+\n+ return nil\n+}\n+\n+func validateField(ref reflect.Value, refName string, m tcpip.MultiCounterStat, multiName string) error {\n+ s, ok := ref.Addr().Interface().(**tcpip.StatCounter)\n+ if !ok {\n+ return fmt.Errorf(\"expected ref type's to be *StatCounter, but its type is %s\", ref.Type().Elem().Name())\n+ }\n+\n+ // The field names are expected to match (case insensitive).\n+ if !strings.EqualFold(refName, multiName) {\n+ return fmt.Errorf(\"wrong field name: got = %s, want = %s\", multiName, refName)\n+ }\n+\n+ base := (*s).Value()\n+ m.Increment()\n+ if (*s).Value() != base+1 {\n+ return fmt.Errorf(\"updates to the '%s MultiCounterStat' counters are not reflected in the '%s CounterStat'\", multiName, refName)\n+ }\n+\n+ return nil\n+}\n+\n+// ValidateMultiCounterStats verifies that every counter stored in multi is\n+// correctly tracking its counterpart in the given counters.\n+func ValidateMultiCounterStats(multi reflect.Value, counters []reflect.Value) error {\n+ for _, c := range counters {\n+ if err := checkFieldCounts(c, multi); err != nil {\n+ return err\n+ }\n+ }\n+\n+ for i := 0; i < multi.NumField(); i++ {\n+ multiName := multi.Type().Field(i).Name\n+ multiUnsafe := unsafeExposeUnexportedFields(multi.Field(i))\n+\n+ if m, ok := multiUnsafe.Addr().Interface().(*tcpip.MultiCounterStat); ok {\n+ for _, c := range counters {\n+ if err := validateField(unsafeExposeUnexportedFields(c.Field(i)), c.Type().Field(i).Name, *m, multiName); err != nil {\n+ return err\n+ }\n+ }\n+ } else {\n+ var countersNextField []reflect.Value\n+ for _, c := range counters {\n+ countersNextField = append(countersNextField, c.Field(i))\n+ }\n+ if err := ValidateMultiCounterStats(multi.Field(i), countersNextField); err != nil {\n+ return err\n+ }\n+ }\n+ }\n+\n+ return nil\n+}\n" }, { "change_type": "RENAME", "old_path": "pkg/tcpip/network/internal/testutil/testutil_unsafe.go", "new_path": "pkg/tcpip/testutil/testutil_unsafe.go", "diff": "" } ]
Go
Apache License 2.0
google/gvisor
Move multicounter testutil functions out of network/ip This is in preparation of having aggregated NIC stats at the stack level. These validation functions will be needed outside of the network layer packages to test aggregated NIC stats. PiperOrigin-RevId: 373180565
259,962
11.05.2021 10:26:17
25,200
ebebb3059f7c5dbe42af85715f1c51c23461463b
Change AcquireAssignedAddress to use RLock. This is a hot path for all incoming packets and we don't need an exclusive lock here as we are not modifying any of the fields protected by mu here.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv4/ipv4.go", "new_path": "pkg/tcpip/network/ipv4/ipv4.go", "diff": "@@ -990,8 +990,8 @@ func (e *endpoint) Close() {\n// AddAndAcquirePermanentAddress implements stack.AddressableEndpoint.\nfunc (e *endpoint) AddAndAcquirePermanentAddress(addr tcpip.AddressWithPrefix, peb stack.PrimaryEndpointBehavior, configType stack.AddressConfigType, deprecated bool) (stack.AddressEndpoint, tcpip.Error) {\n- e.mu.Lock()\n- defer e.mu.Unlock()\n+ e.mu.RLock()\n+ defer e.mu.RUnlock()\nep, err := e.mu.addressableEndpointState.AddAndAcquirePermanentAddress(addr, peb, configType, deprecated)\nif err == nil {\n@@ -1002,8 +1002,8 @@ func (e *endpoint) AddAndAcquirePermanentAddress(addr tcpip.AddressWithPrefix, p\n// RemovePermanentAddress implements stack.AddressableEndpoint.\nfunc (e *endpoint) RemovePermanentAddress(addr tcpip.Address) tcpip.Error {\n- e.mu.Lock()\n- defer e.mu.Unlock()\n+ e.mu.RLock()\n+ defer e.mu.RUnlock()\nreturn e.mu.addressableEndpointState.RemovePermanentAddress(addr)\n}\n@@ -1016,8 +1016,8 @@ func (e *endpoint) MainAddress() tcpip.AddressWithPrefix {\n// AcquireAssignedAddress implements stack.AddressableEndpoint.\nfunc (e *endpoint) AcquireAssignedAddress(localAddr tcpip.Address, allowTemp bool, tempPEB stack.PrimaryEndpointBehavior) stack.AddressEndpoint {\n- e.mu.Lock()\n- defer e.mu.Unlock()\n+ e.mu.RLock()\n+ defer e.mu.RUnlock()\nloopback := e.nic.IsLoopback()\nreturn e.mu.addressableEndpointState.AcquireAssignedAddressOrMatching(localAddr, func(addressEndpoint stack.AddressEndpoint) bool {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/ipv6.go", "new_path": "pkg/tcpip/network/ipv6/ipv6.go", "diff": "@@ -1546,8 +1546,8 @@ func (e *endpoint) NetworkProtocolNumber() tcpip.NetworkProtocolNumber {\nfunc (e *endpoint) AddAndAcquirePermanentAddress(addr tcpip.AddressWithPrefix, peb stack.PrimaryEndpointBehavior, configType stack.AddressConfigType, deprecated bool) (stack.AddressEndpoint, tcpip.Error) {\n// TODO(b/169350103): add checks here after making sure we no longer receive\n// an empty address.\n- e.mu.Lock()\n- defer e.mu.Unlock()\n+ e.mu.RLock()\n+ defer e.mu.RUnlock()\nreturn e.addAndAcquirePermanentAddressLocked(addr, peb, configType, deprecated)\n}\n@@ -1588,8 +1588,8 @@ func (e *endpoint) addAndAcquirePermanentAddressLocked(addr tcpip.AddressWithPre\n// RemovePermanentAddress implements stack.AddressableEndpoint.\nfunc (e *endpoint) RemovePermanentAddress(addr tcpip.Address) tcpip.Error {\n- e.mu.Lock()\n- defer e.mu.Unlock()\n+ e.mu.RLock()\n+ defer e.mu.RUnlock()\naddressEndpoint := e.getAddressRLocked(addr)\nif addressEndpoint == nil || !addressEndpoint.GetKind().IsPermanent() {\n@@ -1666,8 +1666,8 @@ func (e *endpoint) MainAddress() tcpip.AddressWithPrefix {\n// AcquireAssignedAddress implements stack.AddressableEndpoint.\nfunc (e *endpoint) AcquireAssignedAddress(localAddr tcpip.Address, allowTemp bool, tempPEB stack.PrimaryEndpointBehavior) stack.AddressEndpoint {\n- e.mu.Lock()\n- defer e.mu.Unlock()\n+ e.mu.RLock()\n+ defer e.mu.RUnlock()\nreturn e.acquireAddressOrCreateTempLocked(localAddr, allowTemp, tempPEB)\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/addressable_endpoint_state.go", "new_path": "pkg/tcpip/stack/addressable_endpoint_state.go", "diff": "@@ -440,9 +440,7 @@ func (a *AddressableEndpointState) acquirePrimaryAddressRLocked(isValid func(*ad\n// Regardless how the address was obtained, it will be acquired before it is\n// returned.\nfunc (a *AddressableEndpointState) AcquireAssignedAddressOrMatching(localAddr tcpip.Address, f func(AddressEndpoint) bool, allowTemp bool, tempPEB PrimaryEndpointBehavior) AddressEndpoint {\n- a.mu.Lock()\n- defer a.mu.Unlock()\n-\n+ lookup := func() *addressState {\nif addrState, ok := a.mu.endpoints[localAddr]; ok {\nif !addrState.IsAssigned(allowTemp) {\nreturn nil\n@@ -462,11 +460,34 @@ func (a *AddressableEndpointState) AcquireAssignedAddressOrMatching(localAddr tc\n}\n}\n}\n+ return nil\n+ }\n+ // Avoid exclusive lock on mu unless we need to add a new address.\n+ a.mu.RLock()\n+ ep := lookup()\n+ a.mu.RUnlock()\n+\n+ if ep != nil {\n+ return ep\n+ }\nif !allowTemp {\nreturn nil\n}\n+ // Acquire state lock in exclusive mode as we need to add a new temporary\n+ // endpoint.\n+ a.mu.Lock()\n+ defer a.mu.Unlock()\n+\n+ // Do the lookup again in case another goroutine added the address in the time\n+ // we released and acquired the lock.\n+ ep = lookup()\n+ if ep != nil {\n+ return ep\n+ }\n+\n+ // Proceed to add a new temporary endpoint.\naddr := localAddr.WithPrefix()\nep, err := a.addAndAcquireAddressLocked(addr, tempPEB, AddressConfigStatic, false /* deprecated */, false /* permanent */)\nif err != nil {\n@@ -475,6 +496,7 @@ func (a *AddressableEndpointState) AcquireAssignedAddressOrMatching(localAddr tc\n// expect no error.\npanic(fmt.Sprintf(\"a.addAndAcquireAddressLocked(%s, %d, %d, false, false): %s\", addr, tempPEB, AddressConfigStatic, err))\n}\n+\n// From https://golang.org/doc/faq#nil_error:\n//\n// Under the covers, interfaces are implemented as two elements, a type T and\n" } ]
Go
Apache License 2.0
google/gvisor
Change AcquireAssignedAddress to use RLock. This is a hot path for all incoming packets and we don't need an exclusive lock here as we are not modifying any of the fields protected by mu here. PiperOrigin-RevId: 373181254
259,975
11.05.2021 17:21:24
25,200
49eb3da98aeb436011ec9d895727b237ec2ea93f
[syserror] Refactor abi/linux.Errno
[ { "change_type": "MODIFY", "old_path": "pkg/abi/linux/BUILD", "new_path": "pkg/abi/linux/BUILD", "diff": "@@ -85,6 +85,8 @@ go_library(\ngo_test(\nname = \"linux_test\",\nsize = \"small\",\n- srcs = [\"netfilter_test.go\"],\n+ srcs = [\n+ \"netfilter_test.go\",\n+ ],\nlibrary = \":linux\",\n)\n" }, { "change_type": "MODIFY", "old_path": "pkg/abi/linux/errors.go", "new_path": "pkg/abi/linux/errors.go", "diff": "package linux\n// Errno represents a Linux errno value.\n-type Errno struct {\n- number int\n- name string\n-}\n-\n-// Number returns the errno number.\n-func (e *Errno) Number() int {\n- return e.number\n-}\n-\n-// String implements fmt.Stringer.String.\n-func (e *Errno) String() string {\n- return e.name\n-}\n+type Errno int\n// Errno values from include/uapi/asm-generic/errno-base.h.\n-var (\n- EPERM = &Errno{1, \"operation not permitted\"}\n- ENOENT = &Errno{2, \"no such file or directory\"}\n- ESRCH = &Errno{3, \"no such process\"}\n- EINTR = &Errno{4, \"interrupted system call\"}\n- EIO = &Errno{5, \"I/O error\"}\n- ENXIO = &Errno{6, \"no such device or address\"}\n- E2BIG = &Errno{7, \"argument list too long\"}\n- ENOEXEC = &Errno{8, \"exec format error\"}\n- EBADF = &Errno{9, \"bad file number\"}\n- ECHILD = &Errno{10, \"no child processes\"}\n- EAGAIN = &Errno{11, \"try again\"}\n- ENOMEM = &Errno{12, \"out of memory\"}\n- EACCES = &Errno{13, \"permission denied\"}\n- EFAULT = &Errno{14, \"bad address\"}\n- ENOTBLK = &Errno{15, \"block device required\"}\n- EBUSY = &Errno{16, \"device or resource busy\"}\n- EEXIST = &Errno{17, \"file exists\"}\n- EXDEV = &Errno{18, \"cross-device link\"}\n- ENODEV = &Errno{19, \"no such device\"}\n- ENOTDIR = &Errno{20, \"not a directory\"}\n- EISDIR = &Errno{21, \"is a directory\"}\n- EINVAL = &Errno{22, \"invalid argument\"}\n- ENFILE = &Errno{23, \"file table overflow\"}\n- EMFILE = &Errno{24, \"too many open files\"}\n- ENOTTY = &Errno{25, \"not a typewriter\"}\n- ETXTBSY = &Errno{26, \"text file busy\"}\n- EFBIG = &Errno{27, \"file too large\"}\n- ENOSPC = &Errno{28, \"no space left on device\"}\n- ESPIPE = &Errno{29, \"illegal seek\"}\n- EROFS = &Errno{30, \"read-only file system\"}\n- EMLINK = &Errno{31, \"too many links\"}\n- EPIPE = &Errno{32, \"broken pipe\"}\n- EDOM = &Errno{33, \"math argument out of domain of func\"}\n- ERANGE = &Errno{34, \"math result not representable\"}\n+const (\n+ NOERRNO = iota\n+ EPERM\n+ ENOENT\n+ ESRCH\n+ EINTR\n+ EIO\n+ ENXIO\n+ E2BIG\n+ ENOEXEC\n+ EBADF\n+ ECHILD // 10\n+ EAGAIN\n+ ENOMEM\n+ EACCES\n+ EFAULT\n+ ENOTBLK\n+ EBUSY\n+ EEXIST\n+ EXDEV\n+ ENODEV\n+ ENOTDIR // 20\n+ EISDIR\n+ EINVAL\n+ ENFILE\n+ EMFILE\n+ ENOTTY\n+ ETXTBSY\n+ EFBIG\n+ ENOSPC\n+ ESPIPE\n+ EROFS // 30\n+ EMLINK\n+ EPIPE\n+ EDOM\n+ ERANGE\n+ // Errno values from include/uapi/asm-generic/errno.h.\n+ EDEADLK\n+ ENAMETOOLONG\n+ ENOLCK\n+ ENOSYS\n+ ENOTEMPTY\n+ ELOOP //40\n+ _ // Skip for EWOULDBLOCK = EAGAIN\n+ ENOMSG //42\n+ EIDRM\n+ ECHRNG\n+ EL2NSYNC\n+ EL3HLT\n+ EL3RST\n+ ELNRNG\n+ EUNATCH\n+ ENOCSI\n+ EL2HLT // 50\n+ EBADE\n+ EBADR\n+ EXFULL\n+ ENOANO\n+ EBADRQC\n+ EBADSLT\n+ _ // Skip for EDEADLOCK = EDEADLK\n+ EBFONT\n+ ENOSTR // 60\n+ ENODATA\n+ ETIME\n+ ENOSR\n+ ENONET\n+ ENOPKG\n+ EREMOTE\n+ ENOLINK\n+ EADV\n+ ESRMNT\n+ ECOMM // 70\n+ EPROTO\n+ EMULTIHOP\n+ EDOTDOT\n+ EBADMSG\n+ EOVERFLOW\n+ ENOTUNIQ\n+ EBADFD\n+ EREMCHG\n+ ELIBACC\n+ ELIBBAD // 80\n+ ELIBSCN\n+ ELIBMAX\n+ ELIBEXEC\n+ EILSEQ\n+ ERESTART\n+ ESTRPIPE\n+ EUSERS\n+ ENOTSOCK\n+ EDESTADDRREQ\n+ EMSGSIZE // 90\n+ EPROTOTYPE\n+ ENOPROTOOPT\n+ EPROTONOSUPPORT\n+ ESOCKTNOSUPPORT\n+ EOPNOTSUPP\n+ EPFNOSUPPORT\n+ EAFNOSUPPORT\n+ EADDRINUSE\n+ EADDRNOTAVAIL\n+ ENETDOWN // 100\n+ ENETUNREACH\n+ ENETRESET\n+ ECONNABORTED\n+ ECONNRESET\n+ ENOBUFS\n+ EISCONN\n+ ENOTCONN\n+ ESHUTDOWN\n+ ETOOMANYREFS\n+ ETIMEDOUT // 110\n+ ECONNREFUSED\n+ EHOSTDOWN\n+ EHOSTUNREACH\n+ EALREADY\n+ EINPROGRESS\n+ ESTALE\n+ EUCLEAN\n+ ENOTNAM\n+ ENAVAIL\n+ EISNAM // 120\n+ EREMOTEIO\n+ EDQUOT\n+ ENOMEDIUM\n+ EMEDIUMTYPE\n+ ECANCELED\n+ ENOKEY\n+ EKEYEXPIRED\n+ EKEYREVOKED\n+ EKEYREJECTED\n+ EOWNERDEAD // 130\n+ ENOTRECOVERABLE\n+ ERFKILL\n+ EHWPOISON\n)\n-// Errno values from include/uapi/asm-generic/errno.h.\n-var (\n- EDEADLK = &Errno{35, \"resource deadlock would occur\"}\n- ENAMETOOLONG = &Errno{36, \"file name too long\"}\n- ENOLCK = &Errno{37, \"no record locks available\"}\n- ENOSYS = &Errno{38, \"invalid system call number\"}\n- ENOTEMPTY = &Errno{39, \"directory not empty\"}\n- ELOOP = &Errno{40, \"too many symbolic links encountered\"}\n- EWOULDBLOCK = &Errno{EAGAIN.number, \"operation would block\"}\n- ENOMSG = &Errno{42, \"no message of desired type\"}\n- EIDRM = &Errno{43, \"identifier removed\"}\n- ECHRNG = &Errno{44, \"channel number out of range\"}\n- EL2NSYNC = &Errno{45, \"level 2 not synchronized\"}\n- EL3HLT = &Errno{46, \"level 3 halted\"}\n- EL3RST = &Errno{47, \"level 3 reset\"}\n- ELNRNG = &Errno{48, \"link number out of range\"}\n- EUNATCH = &Errno{49, \"protocol driver not attached\"}\n- ENOCSI = &Errno{50, \"no CSI structure available\"}\n- EL2HLT = &Errno{51, \"level 2 halted\"}\n- EBADE = &Errno{52, \"invalid exchange\"}\n- EBADR = &Errno{53, \"invalid request descriptor\"}\n- EXFULL = &Errno{54, \"exchange full\"}\n- ENOANO = &Errno{55, \"no anode\"}\n- EBADRQC = &Errno{56, \"invalid request code\"}\n- EBADSLT = &Errno{57, \"invalid slot\"}\n+// errnos derived from other errnos\n+const (\n+ EWOULDBLOCK = EAGAIN\nEDEADLOCK = EDEADLK\n- EBFONT = &Errno{59, \"bad font file format\"}\n- ENOSTR = &Errno{60, \"device not a stream\"}\n- ENODATA = &Errno{61, \"no data available\"}\n- ETIME = &Errno{62, \"timer expired\"}\n- ENOSR = &Errno{63, \"out of streams resources\"}\n- ENONET = &Errno{64, \"machine is not on the network\"}\n- ENOPKG = &Errno{65, \"package not installed\"}\n- EREMOTE = &Errno{66, \"object is remote\"}\n- ENOLINK = &Errno{67, \"link has been severed\"}\n- EADV = &Errno{68, \"advertise error\"}\n- ESRMNT = &Errno{69, \"srmount error\"}\n- ECOMM = &Errno{70, \"communication error on send\"}\n- EPROTO = &Errno{71, \"protocol error\"}\n- EMULTIHOP = &Errno{72, \"multihop attempted\"}\n- EDOTDOT = &Errno{73, \"RFS specific error\"}\n- EBADMSG = &Errno{74, \"not a data message\"}\n- EOVERFLOW = &Errno{75, \"value too large for defined data type\"}\n- ENOTUNIQ = &Errno{76, \"name not unique on network\"}\n- EBADFD = &Errno{77, \"file descriptor in bad state\"}\n- EREMCHG = &Errno{78, \"remote address changed\"}\n- ELIBACC = &Errno{79, \"can not access a needed shared library\"}\n- ELIBBAD = &Errno{80, \"accessing a corrupted shared library\"}\n- ELIBSCN = &Errno{81, \".lib section in a.out corrupted\"}\n- ELIBMAX = &Errno{82, \"attempting to link in too many shared libraries\"}\n- ELIBEXEC = &Errno{83, \"cannot exec a shared library directly\"}\n- EILSEQ = &Errno{84, \"illegal byte sequence\"}\n- ERESTART = &Errno{85, \"interrupted system call should be restarted\"}\n- ESTRPIPE = &Errno{86, \"streams pipe error\"}\n- EUSERS = &Errno{87, \"too many users\"}\n- ENOTSOCK = &Errno{88, \"socket operation on non-socket\"}\n- EDESTADDRREQ = &Errno{89, \"destination address required\"}\n- EMSGSIZE = &Errno{90, \"message too long\"}\n- EPROTOTYPE = &Errno{91, \"protocol wrong type for socket\"}\n- ENOPROTOOPT = &Errno{92, \"protocol not available\"}\n- EPROTONOSUPPORT = &Errno{93, \"protocol not supported\"}\n- ESOCKTNOSUPPORT = &Errno{94, \"socket type not supported\"}\n- EOPNOTSUPP = &Errno{95, \"operation not supported on transport endpoint\"}\n- EPFNOSUPPORT = &Errno{96, \"protocol family not supported\"}\n- EAFNOSUPPORT = &Errno{97, \"address family not supported by protocol\"}\n- EADDRINUSE = &Errno{98, \"address already in use\"}\n- EADDRNOTAVAIL = &Errno{99, \"cannot assign requested address\"}\n- ENETDOWN = &Errno{100, \"network is down\"}\n- ENETUNREACH = &Errno{101, \"network is unreachable\"}\n- ENETRESET = &Errno{102, \"network dropped connection because of reset\"}\n- ECONNABORTED = &Errno{103, \"software caused connection abort\"}\n- ECONNRESET = &Errno{104, \"connection reset by peer\"}\n- ENOBUFS = &Errno{105, \"no buffer space available\"}\n- EISCONN = &Errno{106, \"transport endpoint is already connected\"}\n- ENOTCONN = &Errno{107, \"transport endpoint is not connected\"}\n- ESHUTDOWN = &Errno{108, \"cannot send after transport endpoint shutdown\"}\n- ETOOMANYREFS = &Errno{109, \"too many references: cannot splice\"}\n- ETIMEDOUT = &Errno{110, \"connection timed out\"}\n- ECONNREFUSED = &Errno{111, \"connection refused\"}\n- EHOSTDOWN = &Errno{112, \"host is down\"}\n- EHOSTUNREACH = &Errno{113, \"no route to host\"}\n- EALREADY = &Errno{114, \"operation already in progress\"}\n- EINPROGRESS = &Errno{115, \"operation now in progress\"}\n- ESTALE = &Errno{116, \"stale file handle\"}\n- EUCLEAN = &Errno{117, \"structure needs cleaning\"}\n- ENOTNAM = &Errno{118, \"not a XENIX named type file\"}\n- ENAVAIL = &Errno{119, \"no XENIX semaphores available\"}\n- EISNAM = &Errno{120, \"is a named type file\"}\n- EREMOTEIO = &Errno{121, \"remote I/O error\"}\n- EDQUOT = &Errno{122, \"quota exceeded\"}\n- ENOMEDIUM = &Errno{123, \"no medium found\"}\n- EMEDIUMTYPE = &Errno{124, \"wrong medium type\"}\n- ECANCELED = &Errno{125, \"operation Canceled\"}\n- ENOKEY = &Errno{126, \"required key not available\"}\n- EKEYEXPIRED = &Errno{127, \"key has expired\"}\n- EKEYREVOKED = &Errno{128, \"key has been revoked\"}\n- EKEYREJECTED = &Errno{129, \"key was rejected by service\"}\n- EOWNERDEAD = &Errno{130, \"owner died\"}\n- ENOTRECOVERABLE = &Errno{131, \"state not recoverable\"}\n- ERFKILL = &Errno{132, \"operation not possible due to RF-kill\"}\n- EHWPOISON = &Errno{133, \"memory page has hardware error\"}\n)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netlink/socket.go", "new_path": "pkg/sentry/socket/netlink/socket.go", "diff": "@@ -656,7 +656,7 @@ func dumpErrorMesage(hdr linux.NetlinkMessageHeader, ms *MessageSet, err *syserr\nType: linux.NLMSG_ERROR,\n})\nm.Put(&linux.NetlinkErrorMessage{\n- Error: int32(-err.ToLinux().Number()),\n+ Error: int32(-err.ToLinux()),\nHeader: hdr,\n})\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netstack/netstack.go", "new_path": "pkg/sentry/socket/netstack/netstack.go", "diff": "@@ -851,7 +851,7 @@ func getSockOptSocket(t *kernel.Task, s socket.SocketOps, ep commonEndpoint, fam\nreturn &optP, nil\n}\n- optP := primitive.Int32(syserr.TranslateNetstackError(err).ToLinux().Number())\n+ optP := primitive.Int32(syserr.TranslateNetstackError(err).ToLinux())\nreturn &optP, nil\ncase linux.SO_PEERCRED:\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/socket.go", "new_path": "pkg/sentry/socket/socket.go", "diff": "@@ -80,7 +80,7 @@ func sockErrCmsgToLinux(sockErr *tcpip.SockError) linux.SockErrCMsg {\n}\nee := linux.SockExtendedErr{\n- Errno: uint32(syserr.TranslateNetstackError(sockErr.Err).ToLinux().Number()),\n+ Errno: uint32(syserr.TranslateNetstackError(sockErr.Err).ToLinux()),\nOrigin: errOriginToLinux(sockErr.Cause.Origin()),\nType: sockErr.Cause.Type(),\nCode: sockErr.Cause.Code(),\n" }, { "change_type": "MODIFY", "old_path": "pkg/syserr/netstack.go", "new_path": "pkg/syserr/netstack.go", "diff": "@@ -38,7 +38,7 @@ var (\nErrPortInUse = New((&tcpip.ErrPortInUse{}).String(), linux.EADDRINUSE)\nErrBadLocalAddress = New((&tcpip.ErrBadLocalAddress{}).String(), linux.EADDRNOTAVAIL)\nErrClosedForSend = New((&tcpip.ErrClosedForSend{}).String(), linux.EPIPE)\n- ErrClosedForReceive = New((&tcpip.ErrClosedForReceive{}).String(), nil)\n+ ErrClosedForReceive = New((&tcpip.ErrClosedForReceive{}).String(), linux.NOERRNO)\nErrTimeout = New((&tcpip.ErrTimeout{}).String(), linux.ETIMEDOUT)\nErrAborted = New((&tcpip.ErrAborted{}).String(), linux.EPIPE)\nErrConnectStarted = New((&tcpip.ErrConnectStarted{}).String(), linux.EINPROGRESS)\n" }, { "change_type": "MODIFY", "old_path": "pkg/syserr/syserr.go", "new_path": "pkg/syserr/syserr.go", "diff": "@@ -34,24 +34,19 @@ type Error struct {\n// linux.Errno.\nnoTranslation bool\n- // errno is the linux.Errno this Error should be translated to. nil means\n- // that this Error should be translated to a nil linux.Errno.\n- errno *linux.Errno\n+ // errno is the linux.Errno this Error should be translated to.\n+ errno linux.Errno\n}\n// New creates a new Error and adds a translation for it.\n//\n// New must only be called at init.\n-func New(message string, linuxTranslation *linux.Errno) *Error {\n+func New(message string, linuxTranslation linux.Errno) *Error {\nerr := &Error{message: message, errno: linuxTranslation}\n- if linuxTranslation == nil {\n- return err\n- }\n-\n// TODO(b/34162363): Remove this.\n- errno := linuxTranslation.Number()\n- if errno <= 0 || errno >= len(linuxBackwardsTranslations) {\n+ errno := linuxTranslation\n+ if errno < 0 || int(errno) >= len(linuxBackwardsTranslations) {\npanic(fmt.Sprint(\"invalid errno: \", errno))\n}\n@@ -74,7 +69,7 @@ func New(message string, linuxTranslation *linux.Errno) *Error {\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+func NewDynamic(message string, linuxTranslation linux.Errno) *Error {\nreturn &Error{message: message, errno: linuxTranslation}\n}\n@@ -87,7 +82,7 @@ func NewWithoutTranslation(message string) *Error {\nreturn &Error{message: message, noTranslation: true}\n}\n-func newWithHost(message string, linuxTranslation *linux.Errno, hostErrno unix.Errno) *Error {\n+func newWithHost(message string, linuxTranslation linux.Errno, hostErrno unix.Errno) *Error {\ne := New(message, linuxTranslation)\naddLinuxHostTranslation(hostErrno, e)\nreturn e\n@@ -119,10 +114,10 @@ func (e *Error) ToError() error {\nif e.noTranslation {\npanic(fmt.Sprintf(\"error %q does not support translation\", e.message))\n}\n- if e.errno == nil {\n+ errno := int(e.errno)\n+ if errno == linux.NOERRNO {\nreturn nil\n}\n- errno := e.errno.Number()\nif errno <= 0 || errno >= len(linuxBackwardsTranslations) || !linuxBackwardsTranslations[errno].ok {\npanic(fmt.Sprintf(\"unknown error %q (%d)\", e.message, errno))\n}\n@@ -131,7 +126,7 @@ func (e *Error) ToError() error {\n// ToLinux converts the Error to a Linux ABI error that can be returned to the\n// application.\n-func (e *Error) ToLinux() *linux.Errno {\n+func (e *Error) ToLinux() linux.Errno {\nif e.noTranslation {\npanic(fmt.Sprintf(\"No Linux ABI translation available for %q\", e.message))\n}\n" } ]
Go
Apache License 2.0
google/gvisor
[syserror] Refactor abi/linux.Errno PiperOrigin-RevId: 373265454
259,891
12.05.2021 10:26:21
25,200
d5f69e0decef6f62706fdeef33ba5f1305e2e431
Use an exhaustive list of architectures
[ { "change_type": "MODIFY", "old_path": "pkg/atomicbitops/aligned_64bit.go", "new_path": "pkg/atomicbitops/aligned_64bit.go", "diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-// +build amd64 arm64\n+// +build !arm,!mips,!386\npackage atomicbitops\nimport \"sync/atomic\"\n// AlignedAtomicInt64 is an atomic int64 that is guaranteed to be 64-bit\n-// aligned, even on 32-bit systems. On 64-bit machines, it's just a regular\n+// aligned, even on 32-bit systems. On most architectures, it's just a regular\n// int64.\n//\n// See aligned_unsafe.go in this directory for justification.\n@@ -45,7 +45,7 @@ func (aa *AlignedAtomicInt64) Add(v int64) int64 {\n}\n// AlignedAtomicUint64 is an atomic uint64 that is guaranteed to be 64-bit\n-// aligned, even on 32-bit systems. On 64-bit machines, it's just a regular\n+// aligned, even on 32-bit systems. On most architectures, it's just a regular\n// uint64.\n//\n// See aligned_unsafe.go in this directory for justification.\n" } ]
Go
Apache License 2.0
google/gvisor
Use an exhaustive list of architectures
259,860
12.05.2021 13:21:47
25,200
07e32fa6967370ef29327417fd941c5130335fbc
Document design details for refsvfs2 template.
[ { "change_type": "MODIFY", "old_path": "pkg/refsvfs2/refs_template.go", "new_path": "pkg/refsvfs2/refs_template.go", "diff": "// limitations under the License.\n// Package refs_template defines a template that can be used by reference\n-// counted objects.\n+// counted objects. The template comes with leak checking capabilities.\npackage refs_template\nimport (\n@@ -40,6 +40,14 @@ var obj *T\n// Refs implements refs.RefCounter. It keeps a reference count using atomic\n// operations and calls the destructor when the count reaches zero.\n//\n+// NOTE: Do not introduce additional fields to the Refs struct. It is used by\n+// many filesystem objects, and we want to keep it as small as possible (i.e.,\n+// the same size as using an int64 directly) to avoid taking up extra cache\n+// space. In general, this template should not be extended at the cost of\n+// performance. If it does not offer enough flexibility for a particular object\n+// (example: b/187877947), we should implement the RefCounter/CheckedObject\n+// interfaces manually.\n+//\n// +stateify savable\ntype Refs struct {\n// refCount is composed of two fields:\n" } ]
Go
Apache License 2.0
google/gvisor
Document design details for refsvfs2 template. PiperOrigin-RevId: 373437576
259,905
12.05.2021 22:59:21
-28,800
ddaa36bde5c55067ca866dbfcbd2e560e3bb356d
Fix file descriptor leak in MultiGetAttr We need to make sure that all children are closed before return. But the last child saved in parent isn't closed after we successfully iterate all the files in "names". This patch fixes this issue. Fixes
[ { "change_type": "MODIFY", "old_path": "runsc/fsgofer/fsgofer.go", "new_path": "runsc/fsgofer/fsgofer.go", "diff": "@@ -1247,6 +1247,7 @@ func (l *localFile) MultiGetAttr(names []string) ([]p9.FullStat, error) {\nif parent != l.file.FD() {\n// Parent is no longer needed.\n_ = unix.Close(parent)\n+ parent = -1\n}\nif err != nil {\nif errors.Is(err, unix.ENOENT) {\n@@ -1275,5 +1276,8 @@ func (l *localFile) MultiGetAttr(names []string) ([]p9.FullStat, error) {\n}\nparent = child\n}\n+ if parent != -1 && parent != l.file.FD() {\n+ _ = unix.Close(parent)\n+ }\nreturn stats, nil\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Fix file descriptor leak in MultiGetAttr We need to make sure that all children are closed before return. But the last child saved in parent isn't closed after we successfully iterate all the files in "names". This patch fixes this issue. Fixes #5982 Signed-off-by: Tiwei Bie <[email protected]>
259,884
12.05.2021 18:06:38
25,200
e6a9780f3cca047577db3fe57eeb0d7444030711
Fix TODO comments. Fix TODO comments referring to incorrect issue numbers. Also fix the link in issue reviver comments to include the right url fragment.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/devtmpfs/devtmpfs.go", "new_path": "pkg/sentry/fsimpl/devtmpfs/devtmpfs.go", "diff": "@@ -36,7 +36,7 @@ const Name = \"devtmpfs\"\n//\n// +stateify savable\ntype FilesystemType struct {\n- initOnce sync.Once `state:\"nosave\"` // FIXME(gvisor.dev/issue/1664): not yet supported.\n+ initOnce sync.Once `state:\"nosave\"` // FIXME(gvisor.dev/issue/1663): not yet supported.\ninitErr error\n// fs is the tmpfs filesystem that backs all mounts of this FilesystemType.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netfilter/targets.go", "new_path": "pkg/sentry/socket/netfilter/targets.go", "diff": "@@ -564,7 +564,7 @@ func (*snatTargetMakerV6) unmarshal(buf []byte, filter stack.IPHeaderFilter) (ta\nbuf = buf[linux.SizeOfXTEntryTarget:nfNATMarshalledSize]\nnatRange.UnmarshalUnsafe(buf)\n- // TODO(gvisor.dev/issue/5689): Support port or address ranges.\n+ // TODO(gvisor.dev/issue/5697): Support port or address ranges.\nif natRange.MinAddr != natRange.MaxAddr {\nnflog(\"snatTargetMakerV6: MinAddr and MaxAddr are different\")\nreturn nil, syserr.ErrInvalidArgument\n" }, { "change_type": "MODIFY", "old_path": "tools/github/reviver/github.go", "new_path": "tools/github/reviver/github.go", "diff": "@@ -92,7 +92,7 @@ func (b *GitHubBugger) Activate(todo *Todo) (bool, error) {\nfmt.Fprintln(&comment, \"There are TODOs still referencing this issue:\")\nfor _, l := range todo.Locations {\nfmt.Fprintf(&comment,\n- \"1. [%s:%d](https://github.com/%s/%s/blob/HEAD/%s#%d): %s\\n\",\n+ \"1. [%s:%d](https://github.com/%s/%s/blob/HEAD/%s#L%d): %s\\n\",\nl.File, l.Line, b.owner, b.repo, l.File, l.Line, l.Comment)\n}\nfmt.Fprintf(&comment,\n" } ]
Go
Apache License 2.0
google/gvisor
Fix TODO comments. Fix TODO comments referring to incorrect issue numbers. Also fix the link in issue reviver comments to include the right url fragment. PiperOrigin-RevId: 373491821
260,004
13.05.2021 11:22:25
25,200
baa0888f114c586ea490d49a23c3d828fd739b85
Rename SetForwarding to SetForwardingDefaultAndAllNICs ...to make it clear to callers that all interfaces are updated with the forwarding flag and that future NICs will be created with the new forwarding state.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netstack/stack.go", "new_path": "pkg/sentry/socket/netstack/stack.go", "diff": "@@ -470,11 +470,8 @@ func (s *Stack) Forwarding(protocol tcpip.NetworkProtocolNumber) bool {\n// SetForwarding implements inet.Stack.SetForwarding.\nfunc (s *Stack) SetForwarding(protocol tcpip.NetworkProtocolNumber, enable bool) error {\n- switch protocol {\n- case ipv4.ProtocolNumber, ipv6.ProtocolNumber:\n- s.Stack.SetForwarding(protocol, enable)\n- default:\n- panic(fmt.Sprintf(\"SetForwarding(%v) failed: unsupported protocol\", protocol))\n+ if err := s.Stack.SetForwardingDefaultAndAllNICs(protocol, enable); err != nil {\n+ return fmt.Errorf(\"SetForwardingDefaultAndAllNICs(%d, %t): %s\", protocol, enable, err)\n}\nreturn nil\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ip_test.go", "new_path": "pkg/tcpip/network/ip_test.go", "diff": "@@ -1996,8 +1996,8 @@ func TestJoinLeaveAllRoutersGroup(t *testing.T) {\nt.Fatalf(\"got s.IsInGroup(%d, %s) = true, want = false\", nicID, test.allRoutersAddr)\n}\n- if err := s.SetForwarding(test.netProto, true); err != nil {\n- t.Fatalf(\"s.SetForwarding(%d, true): %s\", test.netProto, err)\n+ if err := s.SetForwardingDefaultAndAllNICs(test.netProto, true); err != nil {\n+ t.Fatalf(\"s.SetForwardingDefaultAndAllNICs(%d, true): %s\", test.netProto, err)\n}\nif got, err := s.IsInGroup(nicID, test.allRoutersAddr); err != nil {\nt.Fatalf(\"s.IsInGroup(%d, %s): %s\", nicID, test.allRoutersAddr, err)\n@@ -2005,8 +2005,8 @@ func TestJoinLeaveAllRoutersGroup(t *testing.T) {\nt.Fatalf(\"got s.IsInGroup(%d, %s) = false, want = true\", nicID, test.allRoutersAddr)\n}\n- if err := s.SetForwarding(test.netProto, false); err != nil {\n- t.Fatalf(\"s.SetForwarding(%d, false): %s\", test.netProto, err)\n+ if err := s.SetForwardingDefaultAndAllNICs(test.netProto, false); err != nil {\n+ t.Fatalf(\"s.SetForwardingDefaultAndAllNICs(%d, false): %s\", test.netProto, err)\n}\nif got, err := s.IsInGroup(nicID, test.allRoutersAddr); err != nil {\nt.Fatalf(\"s.IsInGroup(%d, %s): %s\", nicID, test.allRoutersAddr, err)\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv4/ipv4_test.go", "new_path": "pkg/tcpip/network/ipv4/ipv4_test.go", "diff": "@@ -389,8 +389,8 @@ func TestForwarding(t *testing.T) {\n},\n})\n- if err := s.SetForwarding(header.IPv4ProtocolNumber, true); err != nil {\n- t.Fatalf(\"SetForwarding(%d, true): %s\", header.IPv4ProtocolNumber, err)\n+ if err := s.SetForwardingDefaultAndAllNICs(header.IPv4ProtocolNumber, true); err != nil {\n+ t.Fatalf(\"SetForwardingDefaultAndAllNICs(%d, true): %s\", header.IPv4ProtocolNumber, err)\n}\nipHeaderLength := header.IPv4MinimumSize + len(test.options)\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/icmp_test.go", "new_path": "pkg/tcpip/network/ipv6/icmp_test.go", "diff": "@@ -673,8 +673,9 @@ func TestICMPChecksumValidationSimple(t *testing.T) {\nNetworkProtocols: []stack.NetworkProtocolFactory{NewProtocol},\n})\nif isRouter {\n- // Enabling forwarding makes the stack act as a router.\n- s.SetForwarding(ProtocolNumber, true)\n+ if err := s.SetForwardingDefaultAndAllNICs(ProtocolNumber, true); err != nil {\n+ t.Fatalf(\"SetForwardingDefaultAndAllNICs(%d, true): %s\", ProtocolNumber, err)\n+ }\n}\nif err := s.CreateNIC(nicID, e); err != nil {\nt.Fatalf(\"CreateNIC(_, _) = %s\", err)\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/ipv6_test.go", "new_path": "pkg/tcpip/network/ipv6/ipv6_test.go", "diff": "@@ -3329,8 +3329,8 @@ func TestForwarding(t *testing.T) {\n},\n})\n- if err := s.SetForwarding(ProtocolNumber, true); err != nil {\n- t.Fatalf(\"SetForwarding(%d, true): %s\", ProtocolNumber, err)\n+ if err := s.SetForwardingDefaultAndAllNICs(ProtocolNumber, true); err != nil {\n+ t.Fatalf(\"SetForwardingDefaultAndAllNICs(%d, true): %s\", ProtocolNumber, err)\n}\ntransportProtocol := header.ICMPv6ProtocolNumber\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/ndp_test.go", "new_path": "pkg/tcpip/network/ipv6/ndp_test.go", "diff": "@@ -878,8 +878,9 @@ func TestNDPValidation(t *testing.T) {\ns, ep := setup(t)\nif isRouter {\n- // Enabling forwarding makes the stack act as a router.\n- s.SetForwarding(ProtocolNumber, true)\n+ if err := s.SetForwardingDefaultAndAllNICs(ProtocolNumber, true); err != nil {\n+ t.Fatalf(\"SetForwardingDefaultAndAllNICs(%d, true): %s\", ProtocolNumber, err)\n+ }\n}\nstats := s.Stats().ICMP.V6.PacketsReceived\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/forwarding_test.go", "new_path": "pkg/tcpip/stack/forwarding_test.go", "diff": "@@ -367,8 +367,10 @@ func fwdTestNetFactory(t *testing.T, proto *fwdTestNetworkProtocol) (ep1, ep2 *f\n}},\n})\n- // Enable forwarding.\n- s.SetForwarding(proto.Number(), true)\n+ protoNum := proto.Number()\n+ if err := s.SetForwardingDefaultAndAllNICs(protoNum, true); err != nil {\n+ t.Fatalf(\"SetForwardingDefaultAndAllNICs(%d, true): %s\", protoNum, err)\n+ }\n// NIC 1 has the link address \"a\", and added the network address 1.\nep1 = &fwdTestLinkEndpoint{\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/ndp_test.go", "new_path": "pkg/tcpip/stack/ndp_test.go", "diff": "@@ -1220,8 +1220,8 @@ func TestDynamicConfigurationsDisabled(t *testing.T) {\nNDPDisp: &ndpDisp,\n})},\n})\n- if err := s.SetForwarding(ipv6.ProtocolNumber, forwarding); err != nil {\n- t.Fatalf(\"SetForwarding(%d, %t): %s\", ipv6.ProtocolNumber, forwarding, err)\n+ if err := s.SetForwardingDefaultAndAllNICs(ipv6.ProtocolNumber, forwarding); err != nil {\n+ t.Fatalf(\"SetForwardingDefaultAndAllNICs(%d, %t): %s\", ipv6.ProtocolNumber, forwarding, err)\n}\ne := channel.New(1, 1280, linkAddr1)\n@@ -1424,8 +1424,8 @@ func TestRouterDiscovery(t *testing.T) {\n}\n}\n- if err := s.SetForwarding(ipv6.ProtocolNumber, forwarding); err != nil {\n- t.Fatalf(\"SetForwarding(%d, %t): %s\", ipv6.ProtocolNumber, forwarding, err)\n+ if err := s.SetForwardingDefaultAndAllNICs(ipv6.ProtocolNumber, forwarding); err != nil {\n+ t.Fatalf(\"SetForwardingDefaultAndAllNICs(%d, %t): %s\", ipv6.ProtocolNumber, forwarding, err)\n}\nif err := s.CreateNIC(1, e); err != nil {\n@@ -1626,8 +1626,8 @@ func TestPrefixDiscovery(t *testing.T) {\n}\n}\n- if err := s.SetForwarding(ipv6.ProtocolNumber, forwarding); err != nil {\n- t.Fatalf(\"SetForwarding(%d, %t): %s\", ipv6.ProtocolNumber, forwarding, err)\n+ if err := s.SetForwardingDefaultAndAllNICs(ipv6.ProtocolNumber, forwarding); err != nil {\n+ t.Fatalf(\"SetForwardingDefaultAndAllNICs(%d, %t): %s\", ipv6.ProtocolNumber, forwarding, err)\n}\n// Receive an RA with prefix1 in an NDP Prefix Information option (PI)\n@@ -1893,8 +1893,8 @@ func TestAutoGenAddr(t *testing.T) {\n})},\n})\n- if err := s.SetForwarding(ipv6.ProtocolNumber, forwarding); err != nil {\n- t.Fatalf(\"SetForwarding(%d, %t): %s\", ipv6.ProtocolNumber, forwarding, err)\n+ if err := s.SetForwardingDefaultAndAllNICs(ipv6.ProtocolNumber, forwarding); err != nil {\n+ t.Fatalf(\"SetForwardingDefaultAndAllNICs(%d, %t): %s\", ipv6.ProtocolNumber, forwarding, err)\n}\nif err := s.CreateNIC(1, e); err != nil {\n@@ -4771,8 +4771,8 @@ func TestNoCleanupNDPStateWhenForwardingEnabled(t *testing.T) {\n// or routers, or auto-generated address.\nfor _, forwarding := range [...]bool{true, false} {\nt.Run(fmt.Sprintf(\"Transition forwarding to %t\", forwarding), func(t *testing.T) {\n- if err := s.SetForwarding(ipv6.ProtocolNumber, forwarding); err != nil {\n- t.Fatalf(\"SetForwarding(%d, %t): %s\", ipv6.ProtocolNumber, forwarding, err)\n+ if err := s.SetForwardingDefaultAndAllNICs(ipv6.ProtocolNumber, forwarding); err != nil {\n+ t.Fatalf(\"SetForwardingDefaultAndAllNICs(%d, %t): %s\", ipv6.ProtocolNumber, forwarding, err)\n}\nselect {\ncase e := <-ndpDisp.routerC:\n@@ -5353,8 +5353,8 @@ func TestRouterSolicitation(t *testing.T) {\nname: \"Handle RAs always\",\nhandleRAs: ipv6.HandlingRAsAlwaysEnabled,\nafterFirstRS: func(t *testing.T, s *stack.Stack) {\n- if err := s.SetForwarding(ipv6.ProtocolNumber, true); err != nil {\n- t.Fatalf(\"SetForwarding(%d, true): %s\", ipv6.ProtocolNumber, err)\n+ if err := s.SetForwardingDefaultAndAllNICs(ipv6.ProtocolNumber, true); err != nil {\n+ t.Fatalf(\"SetForwardingDefaultAndAllNICs(%d, true): %s\", ipv6.ProtocolNumber, err)\n}\n},\n},\n@@ -5481,11 +5481,17 @@ func TestStopStartSolicitingRouters(t *testing.T) {\nname: \"Enable and disable forwarding\",\nstartFn: func(t *testing.T, s *stack.Stack) {\nt.Helper()\n- s.SetForwarding(ipv6.ProtocolNumber, false)\n+\n+ if err := s.SetForwardingDefaultAndAllNICs(ipv6.ProtocolNumber, false); err != nil {\n+ t.Fatalf(\"SetForwardingDefaultAndAllNICs(%d, false): %s\", ipv6.ProtocolNumber, err)\n+ }\n},\nstopFn: func(t *testing.T, s *stack.Stack, _ bool) {\nt.Helper()\n- s.SetForwarding(ipv6.ProtocolNumber, true)\n+\n+ if err := s.SetForwardingDefaultAndAllNICs(ipv6.ProtocolNumber, true); err != nil {\n+ t.Fatalf(\"SetForwardingDefaultAndAllNICs(%d, true): %s\", ipv6.ProtocolNumber, err)\n+ }\n},\n},\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/stack.go", "new_path": "pkg/tcpip/stack/stack.go", "diff": "@@ -492,9 +492,9 @@ func (s *Stack) Stats() tcpip.Stats {\nreturn s.stats\n}\n-// SetForwarding enables or disables packet forwarding between NICs for the\n-// passed protocol.\n-func (s *Stack) SetForwarding(protocolNum tcpip.NetworkProtocolNumber, enable bool) tcpip.Error {\n+// SetForwardingDefaultAndAllNICs sets packet forwarding for all NICs for the\n+// passed protocol and sets the default setting for newly created NICs.\n+func (s *Stack) SetForwardingDefaultAndAllNICs(protocolNum tcpip.NetworkProtocolNumber, enable bool) tcpip.Error {\nprotocol, ok := s.networkProtocols[protocolNum]\nif !ok {\nreturn &tcpip.ErrUnknownProtocol{}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/stack_test.go", "new_path": "pkg/tcpip/stack/stack_test.go", "diff": "@@ -4220,8 +4220,8 @@ func TestFindRouteWithForwarding(t *testing.T) {\nt.Fatalf(\"AddAddress(%d, %d, %s): %s\", nicID2, test.netCfg.proto, test.netCfg.nic2Addr, err)\n}\n- if err := s.SetForwarding(test.netCfg.proto, test.forwardingEnabled); err != nil {\n- t.Fatalf(\"SetForwarding(%d, %t): %s\", test.netCfg.proto, test.forwardingEnabled, err)\n+ if err := s.SetForwardingDefaultAndAllNICs(test.netCfg.proto, test.forwardingEnabled); err != nil {\n+ t.Fatalf(\"SetForwardingDefaultAndAllNICs(%d, %t): %s\", test.netCfg.proto, test.forwardingEnabled, err)\n}\ns.SetRouteTable([]tcpip.Route{{Destination: test.netCfg.remoteAddr.WithPrefix().Subnet(), NIC: nicID2}})\n@@ -4275,8 +4275,8 @@ func TestFindRouteWithForwarding(t *testing.T) {\n// Disabling forwarding when the route is dependent on forwarding being\n// enabled should make the route invalid.\n- if err := s.SetForwarding(test.netCfg.proto, false); err != nil {\n- t.Fatalf(\"SetForwarding(%d, false): %s\", test.netCfg.proto, err)\n+ if err := s.SetForwardingDefaultAndAllNICs(test.netCfg.proto, false); err != nil {\n+ t.Fatalf(\"SetForwardingDefaultAndAllNICs(%d, false): %s\", test.netCfg.proto, err)\n}\n{\nerr := send(r, data)\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/tests/integration/forward_test.go", "new_path": "pkg/tcpip/tests/integration/forward_test.go", "diff": "@@ -475,11 +475,11 @@ func TestMulticastForwarding(t *testing.T) {\nt.Fatalf(\"s.AddAddress(%d, %d, %s): %s\", nicID2, ipv6.ProtocolNumber, utils.Ipv6Addr.Address, err)\n}\n- if err := s.SetForwarding(ipv4.ProtocolNumber, true); err != nil {\n- t.Fatalf(\"s.SetForwarding(%d, true): %s\", ipv4.ProtocolNumber, err)\n+ if err := s.SetForwardingDefaultAndAllNICs(ipv4.ProtocolNumber, true); err != nil {\n+ t.Fatalf(\"s.SetForwardingDefaultAndAllNICs(%d, true): %s\", ipv4.ProtocolNumber, err)\n}\n- if err := s.SetForwarding(ipv6.ProtocolNumber, true); err != nil {\n- t.Fatalf(\"s.SetForwarding(%d, true): %s\", ipv6.ProtocolNumber, err)\n+ if err := s.SetForwardingDefaultAndAllNICs(ipv6.ProtocolNumber, true); err != nil {\n+ t.Fatalf(\"s.SetForwardingDefaultAndAllNICs(%d, true): %s\", ipv6.ProtocolNumber, err)\n}\ns.SetRouteTable([]tcpip.Route{\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/tests/integration/loopback_test.go", "new_path": "pkg/tcpip/tests/integration/loopback_test.go", "diff": "@@ -714,11 +714,11 @@ func TestExternalLoopbackTraffic(t *testing.T) {\n}\nif test.forwarding {\n- if err := s.SetForwarding(ipv4.ProtocolNumber, true); err != nil {\n- t.Fatalf(\"SetForwarding(%d, true): %s\", ipv4.ProtocolNumber, err)\n+ if err := s.SetForwardingDefaultAndAllNICs(ipv4.ProtocolNumber, true); err != nil {\n+ t.Fatalf(\"SetForwardingDefaultAndAllNICs(%d, true): %s\", ipv4.ProtocolNumber, err)\n}\n- if err := s.SetForwarding(ipv6.ProtocolNumber, true); err != nil {\n- t.Fatalf(\"SetForwarding(%d, true): %s\", ipv6.ProtocolNumber, err)\n+ if err := s.SetForwardingDefaultAndAllNICs(ipv6.ProtocolNumber, true); err != nil {\n+ t.Fatalf(\"SetForwardingDefaultAndAllNICs(%d, true): %s\", ipv6.ProtocolNumber, err)\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/tests/utils/utils.go", "new_path": "pkg/tcpip/tests/utils/utils.go", "diff": "@@ -224,11 +224,11 @@ func SetupRoutedStacks(t *testing.T, host1Stack, routerStack, host2Stack *stack.\nt.Fatalf(\"host2Stack.CreateNIC(%d, _): %s\", Host2NICID, err)\n}\n- if err := routerStack.SetForwarding(ipv4.ProtocolNumber, true); err != nil {\n- t.Fatalf(\"routerStack.SetForwarding(%d): %s\", ipv4.ProtocolNumber, err)\n+ if err := routerStack.SetForwardingDefaultAndAllNICs(ipv4.ProtocolNumber, true); err != nil {\n+ t.Fatalf(\"routerStack.SetForwardingDefaultAndAllNICs(%d): %s\", ipv4.ProtocolNumber, err)\n}\n- if err := routerStack.SetForwarding(ipv6.ProtocolNumber, true); err != nil {\n- t.Fatalf(\"routerStack.SetForwarding(%d): %s\", ipv6.ProtocolNumber, err)\n+ if err := routerStack.SetForwardingDefaultAndAllNICs(ipv6.ProtocolNumber, true); err != nil {\n+ t.Fatalf(\"routerStack.SetForwardingDefaultAndAllNICs(%d): %s\", ipv6.ProtocolNumber, err)\n}\nif err := host1Stack.AddProtocolAddress(Host1NICID, Host1IPv4Addr); err != nil {\n" } ]
Go
Apache License 2.0
google/gvisor
Rename SetForwarding to SetForwardingDefaultAndAllNICs ...to make it clear to callers that all interfaces are updated with the forwarding flag and that future NICs will be created with the new forwarding state. PiperOrigin-RevId: 373618435
259,992
13.05.2021 14:41:38
25,200
f3478b7516e02ab341324ae1361ea9b019ae4f4e
Fix problem with grouped cgroups cgroup controllers can be grouped together (e.g. cpu,cpuacct) and that was confusing Cgroup.Install() into thinking that a cgroup directory was created by the caller, when it had being created by another controller that is grouped together.
[ { "change_type": "MODIFY", "old_path": "runsc/cgroup/cgroup.go", "new_path": "runsc/cgroup/cgroup.go", "diff": "@@ -342,25 +342,31 @@ func new(pid, cgroupsPath string) (*Cgroup, error) {\n// already exists, it means that the caller has already provided a\n// pre-configured cgroups, and 'res' is ignored.\nfunc (c *Cgroup) Install(res *specs.LinuxResources) error {\n- log.Debugf(\"Creating cgroup %q\", c.Name)\n+ log.Debugf(\"Installing cgroup path %q\", c.Name)\n- // The Cleanup object cleans up partially created cgroups when an error occurs.\n- // Errors occuring during cleanup itself are ignored.\n+ // Clean up partially created cgroups on error. Errors during cleanup itself\n+ // are ignored.\nclean := cleanup.Make(func() { _ = c.Uninstall() })\ndefer clean.Clean()\n- for key, ctrlr := range controllers {\n+ // Controllers can be symlinks to a group of controllers (e.g. cpu,cpuacct).\n+ // So first check what directories need to be created. Otherwise, when\n+ // the directory for one of the controllers in a group is created, it will\n+ // make it seem like the directory already existed and it's not owned by the\n+ // other controllers in the group.\n+ var missing []string\n+ for key := range controllers {\npath := c.MakePath(key)\n- if _, err := os.Stat(path); err == nil {\n- // If cgroup has already been created; it has been setup by caller. Don't\n- // make any changes to configuration, just join when sandbox/gofer starts.\n- log.Debugf(\"Using pre-created cgroup %q\", path)\n- continue\n+ if _, err := os.Stat(path); err != nil {\n+ missing = append(missing, key)\n+ } else {\n+ log.Debugf(\"Using pre-created cgroup %q: %q\", key, path)\n}\n-\n- // Mark that cgroup resources are owned by me.\n- c.Own[key] = true\n-\n+ }\n+ for _, key := range missing {\n+ ctrlr := controllers[key]\n+ path := c.MakePath(key)\n+ log.Debugf(\"Creating cgroup %q: %q\", key, path)\nif err := os.MkdirAll(path, 0755); err != nil {\nif ctrlr.optional() && errors.Is(err, unix.EROFS) {\nif err := ctrlr.skip(res); err != nil {\n@@ -371,6 +377,9 @@ func (c *Cgroup) Install(res *specs.LinuxResources) error {\n}\nreturn err\n}\n+\n+ // Only set controllers that were created by me.\n+ c.Own[key] = true\nif err := ctrlr.set(res, path); err != nil {\nreturn err\n}\n" }, { "change_type": "MODIFY", "old_path": "runsc/cgroup/cgroup_test.go", "new_path": "runsc/cgroup/cgroup_test.go", "diff": "@@ -60,10 +60,10 @@ var dindMountinfo = `\nfunc TestUninstallEnoent(t *testing.T) {\nc := Cgroup{\n- // set a non-existent name\n+ // Use a non-existent name.\nName: \"runsc-test-uninstall-656e6f656e740a\",\n+ Own: make(map[string]bool),\n}\n- c.Own = make(map[string]bool)\nfor key := range controllers {\nc.Own[key] = true\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Fix problem with grouped cgroups cgroup controllers can be grouped together (e.g. cpu,cpuacct) and that was confusing Cgroup.Install() into thinking that a cgroup directory was created by the caller, when it had being created by another controller that is grouped together. PiperOrigin-RevId: 373661336
260,023
13.05.2021 17:15:08
25,200
7ea2dcbaece00b5c7310c74fcf99c1fb32e9ec28
Apply SWS avoidance to ACKs with window updates When recovering from a zero-receive-window situation, and asked to send out an ACK, ensure that we apply SWS avoidance in our window updates. Fixes
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/endpoint.go", "new_path": "pkg/tcpip/transport/tcp/endpoint.go", "diff": "@@ -1601,7 +1601,7 @@ func (e *endpoint) selectWindow() (wnd seqnum.Size) {\n//\n// For large receive buffers, the threshold is aMSS - once reader reads more\n// than aMSS we'll send ACK. For tiny receive buffers, the threshold is half of\n-// receive buffer size. This is chosen arbitrairly.\n+// receive buffer size. This is chosen arbitrarily.\n// crossed will be true if the window size crossed the ACK threshold.\n// above will be true if the new window is >= ACK threshold and false\n// otherwise.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/rcv.go", "new_path": "pkg/tcpip/transport/tcp/rcv.go", "diff": "@@ -148,6 +148,18 @@ func (r *receiver) getSendParams() (RcvNxt seqnum.Value, rcvWnd seqnum.Size) {\n}\nnewWnd = curWnd\n}\n+\n+ // Apply silly-window avoidance when recovering from zero-window situation.\n+ // Keep advertising zero receive window up until the new window reaches a\n+ // threshold.\n+ if r.rcvWnd == 0 && newWnd != 0 {\n+ r.ep.rcvQueueInfo.rcvQueueMu.Lock()\n+ if crossed, above := r.ep.windowCrossedACKThresholdLocked(int(newWnd), int(r.ep.ops.GetReceiveBufferSize())); !crossed && !above {\n+ newWnd = 0\n+ }\n+ r.ep.rcvQueueInfo.rcvQueueMu.Unlock()\n+ }\n+\n// Stash away the non-scaled receive window as we use it for measuring\n// receiver's estimated RTT.\nr.rcvWnd = newWnd\n" }, { "change_type": "MODIFY", "old_path": "test/packetimpact/testbench/testbench.go", "new_path": "test/packetimpact/testbench/testbench.go", "diff": "@@ -57,6 +57,11 @@ type DUTUname struct {\nOperatingSystem string\n}\n+// IsLinux returns true if we are running natively on Linux.\n+func (n *DUTUname) IsLinux() bool {\n+ return Native && n.OperatingSystem == \"GNU/Linux\"\n+}\n+\n// DUTTestNet describes the test network setup on dut and how the testbench\n// should connect with an existing DUT.\ntype DUTTestNet struct {\n" }, { "change_type": "MODIFY", "old_path": "test/packetimpact/tests/tcp_zero_receive_window_test.go", "new_path": "test/packetimpact/tests/tcp_zero_receive_window_test.go", "diff": "@@ -45,10 +45,16 @@ func TestZeroReceiveWindow(t *testing.T) {\ndut.SetSockOptInt(t, acceptFd, unix.IPPROTO_TCP, unix.TCP_NODELAY, 1)\n- samplePayload := &testbench.Payload{Bytes: testbench.GenerateRandomPayload(t, payloadLen)}\n+ fillRecvBuffer(t, &conn, &dut, acceptFd, payloadLen)\n+ })\n+ }\n+}\n+\n+func fillRecvBuffer(t *testing.T, conn *testbench.TCPIPv4, dut *testbench.DUT, acceptFd int32, payloadLen int) {\n// Expect the DUT to eventually advertise zero receive window.\n// The test would timeout otherwise.\nfor readOnce := false; ; {\n+ samplePayload := &testbench.Payload{Bytes: testbench.GenerateRandomPayload(t, payloadLen)}\nconn.Send(t, testbench.TCP{Flags: testbench.TCPFlags(header.TCPFlagAck | header.TCPFlagPsh)}, samplePayload)\ngotTCP, err := conn.Expect(t, testbench.TCP{Flags: testbench.TCPFlags(header.TCPFlagAck)}, time.Second)\nif err != nil {\n@@ -71,8 +77,79 @@ func TestZeroReceiveWindow(t *testing.T) {\nif windowSize == 0 {\nbreak\n}\n+ if payloadLen > int(windowSize) {\n+ payloadLen = int(windowSize)\n+ }\n+ }\n+}\n+\n+func TestZeroToNonZeroWindowUpdate(t *testing.T) {\n+ dut := testbench.NewDUT(t)\n+ listenFd, remotePort := dut.CreateListener(t, unix.SOCK_STREAM, unix.IPPROTO_TCP, 1)\n+ defer dut.Close(t, listenFd)\n+ conn := dut.Net.NewTCPIPv4(t, testbench.TCP{DstPort: &remotePort}, testbench.TCP{SrcPort: &remotePort})\n+ defer conn.Close(t)\n+\n+ conn.Send(t, testbench.TCP{Flags: testbench.TCPFlags(header.TCPFlagSyn)})\n+ synAck, err := conn.Expect(t, testbench.TCP{Flags: testbench.TCPFlags(header.TCPFlagSyn | header.TCPFlagAck)}, time.Second)\n+ if err != nil {\n+ t.Fatalf(\"didn't get synack during handshake: %s\", err)\n+ }\n+ conn.Send(t, testbench.TCP{Flags: testbench.TCPFlags(header.TCPFlagAck)})\n+\n+ acceptFd, _ := dut.Accept(t, listenFd)\n+ defer dut.Close(t, acceptFd)\n+\n+ dut.SetSockOptInt(t, acceptFd, unix.IPPROTO_TCP, unix.TCP_NODELAY, 1)\n+\n+ mss := header.ParseSynOptions(synAck.Options, true).MSS\n+ fillRecvBuffer(t, &conn, &dut, acceptFd, int(mss))\n+\n+ // Read < mss worth of data from the receive buffer and expect the DUT to\n+ // not send a non-zero window update.\n+ payloadLen := mss - 1\n+ if got := dut.Recv(t, acceptFd, int32(payloadLen), 0); len(got) != int(payloadLen) {\n+ t.Fatalf(\"got dut.Recv(t, %d, %d, 0) = %d, want %d\", acceptFd, payloadLen, len(got), payloadLen)\n+ }\n+ // Send a zero-window-probe to force an ACK from the receiver with any\n+ // window updates.\n+ conn.Send(t, testbench.TCP{SeqNum: testbench.Uint32(uint32(*conn.LocalSeqNum(t) - 1)), Flags: testbench.TCPFlags(header.TCPFlagAck)})\n+ gotTCP, err := conn.Expect(t, testbench.TCP{Flags: testbench.TCPFlags(header.TCPFlagAck)}, time.Second)\n+ if err != nil {\n+ t.Fatalf(\"expected packet was not received: %s\", err)\n+ }\n+ if windowSize := *gotTCP.WindowSize; windowSize != 0 {\n+ t.Fatalf(\"got non zero window = %d\", windowSize)\n+ }\n+\n+ // Now, ensure that the DUT eventually sends non-zero window update.\n+ seqNum := testbench.Uint32(uint32(*conn.LocalSeqNum(t) - 1))\n+ ackNum := testbench.Uint32(uint32(*conn.LocalSeqNum(t)))\n+ recvCheckWindowUpdate := func(readLen int) uint16 {\n+ if got := dut.Recv(t, acceptFd, int32(readLen), 0); len(got) != readLen {\n+ t.Fatalf(\"got dut.Recv(t, %d, %d, 0) = %d, want %d\", acceptFd, readLen, len(got), readLen)\n+ }\n+ conn.Send(t, testbench.TCP{SeqNum: seqNum, Flags: testbench.TCPFlags(header.TCPFlagPsh | header.TCPFlagAck)}, &testbench.Payload{Bytes: make([]byte, 1)})\n+ gotTCP, err := conn.Expect(t, testbench.TCP{AckNum: ackNum, Flags: testbench.TCPFlags(header.TCPFlagAck)}, time.Second)\n+ if err != nil {\n+ t.Fatalf(\"expected packet was not received: %s\", err)\n+ }\n+ return *gotTCP.WindowSize\n+ }\n+\n+ if !dut.Uname.IsLinux() {\n+ if win := recvCheckWindowUpdate(1); win == 0 {\n+ t.Fatal(\"expected non-zero window update\")\n+ }\n+ } else {\n+ // Linux stack takes additional socket reads to send out window update,\n+ // its a function of sysctl_tcp_rmem among other things.\n+ // https://github.com/torvalds/linux/blob/7acac4b3196/net/ipv4/tcp_input.c#L687\n+ for {\n+ if win := recvCheckWindowUpdate(int(payloadLen)); win != 0 {\n+ break\n+ }\n}\n- })\n}\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Apply SWS avoidance to ACKs with window updates When recovering from a zero-receive-window situation, and asked to send out an ACK, ensure that we apply SWS avoidance in our window updates. Fixes #5984 PiperOrigin-RevId: 373689578
260,004
13.05.2021 18:52:06
25,200
2b457d9ee9ba50da4a9208d957053fac2c77932d
Check filter table when forwarding IP packets This change updates the forwarding path to perform the forwarding hook with iptables so that the filter table is consulted before a packet is forwarded Updates Test: iptables_test.TestForwardingHook
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/internal/ip/stats.go", "new_path": "pkg/tcpip/network/internal/ip/stats.go", "diff": "@@ -74,6 +74,10 @@ type MultiCounterIPStats struct {\n// layer.\nPacketsReceived tcpip.MultiCounterStat\n+ // ValidPacketsReceived is the number of valid IP packets that reached the IP\n+ // layer.\n+ ValidPacketsReceived tcpip.MultiCounterStat\n+\n// DisabledPacketsReceived is the number of IP packets received from\n// the link layer when the IP layer is disabled.\nDisabledPacketsReceived tcpip.MultiCounterStat\n@@ -114,6 +118,10 @@ type MultiCounterIPStats struct {\n// Input chain.\nIPTablesInputDropped tcpip.MultiCounterStat\n+ // IPTablesForwardDropped is the number of IP packets dropped in the\n+ // Forward chain.\n+ IPTablesForwardDropped tcpip.MultiCounterStat\n+\n// IPTablesOutputDropped is the number of IP packets dropped in the\n// Output chain.\nIPTablesOutputDropped tcpip.MultiCounterStat\n@@ -146,6 +154,7 @@ type MultiCounterIPStats struct {\n// Init sets internal counters to track a and b counters.\nfunc (m *MultiCounterIPStats) Init(a, b *tcpip.IPStats) {\nm.PacketsReceived.Init(a.PacketsReceived, b.PacketsReceived)\n+ m.ValidPacketsReceived.Init(a.ValidPacketsReceived, b.ValidPacketsReceived)\nm.DisabledPacketsReceived.Init(a.DisabledPacketsReceived, b.DisabledPacketsReceived)\nm.InvalidDestinationAddressesReceived.Init(a.InvalidDestinationAddressesReceived, b.InvalidDestinationAddressesReceived)\nm.InvalidSourceAddressesReceived.Init(a.InvalidSourceAddressesReceived, b.InvalidSourceAddressesReceived)\n@@ -156,6 +165,7 @@ func (m *MultiCounterIPStats) Init(a, b *tcpip.IPStats) {\nm.MalformedFragmentsReceived.Init(a.MalformedFragmentsReceived, b.MalformedFragmentsReceived)\nm.IPTablesPreroutingDropped.Init(a.IPTablesPreroutingDropped, b.IPTablesPreroutingDropped)\nm.IPTablesInputDropped.Init(a.IPTablesInputDropped, b.IPTablesInputDropped)\n+ m.IPTablesForwardDropped.Init(a.IPTablesForwardDropped, b.IPTablesForwardDropped)\nm.IPTablesOutputDropped.Init(a.IPTablesOutputDropped, b.IPTablesOutputDropped)\nm.IPTablesPostroutingDropped.Init(a.IPTablesPostroutingDropped, b.IPTablesPostroutingDropped)\nm.OptionTimestampReceived.Init(a.OptionTimestampReceived, b.OptionTimestampReceived)\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv4/ipv4.go", "new_path": "pkg/tcpip/network/ipv4/ipv4.go", "diff": "@@ -668,13 +668,23 @@ func (e *endpoint) forwardPacket(pkt *stack.PacketBuffer) ip.ForwardingError {\n}\n}\n+ stk := e.protocol.stack\n+\n// Check if the destination is owned by the stack.\nif ep := e.protocol.findEndpointWithAddress(dstAddr); ep != nil {\n+ inNicName := stk.FindNICNameFromID(e.nic.ID())\n+ outNicName := stk.FindNICNameFromID(ep.nic.ID())\n+ if ok := stk.IPTables().Check(stack.Forward, pkt, nil, \"\" /* preroutingAddr */, inNicName, outNicName); !ok {\n+ // iptables is telling us to drop the packet.\n+ e.stats.ip.IPTablesForwardDropped.Increment()\n+ return nil\n+ }\n+\nep.handleValidatedPacket(h, pkt)\nreturn nil\n}\n- r, err := e.protocol.stack.FindRoute(0, \"\", dstAddr, ProtocolNumber, false /* multicastLoop */)\n+ r, err := stk.FindRoute(0, \"\", dstAddr, ProtocolNumber, false /* multicastLoop */)\nswitch err.(type) {\ncase nil:\ncase *tcpip.ErrNoRoute, *tcpip.ErrNetworkUnreachable:\n@@ -688,6 +698,14 @@ func (e *endpoint) forwardPacket(pkt *stack.PacketBuffer) ip.ForwardingError {\n}\ndefer r.Release()\n+ inNicName := stk.FindNICNameFromID(e.nic.ID())\n+ outNicName := stk.FindNICNameFromID(r.NICID())\n+ if ok := stk.IPTables().Check(stack.Forward, pkt, nil, \"\" /* preroutingAddr */, inNicName, outNicName); !ok {\n+ // iptables is telling us to drop the packet.\n+ e.stats.ip.IPTablesForwardDropped.Increment()\n+ return nil\n+ }\n+\n// We need to do a deep copy of the IP packet because\n// WriteHeaderIncludedPacket takes ownership of the packet buffer, but we do\n// not own it.\n@@ -803,6 +821,7 @@ func (e *endpoint) handleLocalPacket(pkt *stack.PacketBuffer, canSkipRXChecksum\nfunc (e *endpoint) handleValidatedPacket(h header.IPv4, pkt *stack.PacketBuffer) {\npkt.NICID = e.nic.ID()\nstats := e.stats\n+ stats.ip.ValidPacketsReceived.Increment()\nsrcAddr := h.SourceAddress()\ndstAddr := h.DestinationAddress()\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/ipv6.go", "new_path": "pkg/tcpip/network/ipv6/ipv6.go", "diff": "@@ -941,8 +941,18 @@ func (e *endpoint) forwardPacket(pkt *stack.PacketBuffer) ip.ForwardingError {\nreturn &ip.ErrTTLExceeded{}\n}\n+ stk := e.protocol.stack\n+\n// Check if the destination is owned by the stack.\nif ep := e.protocol.findEndpointWithAddress(dstAddr); ep != nil {\n+ inNicName := stk.FindNICNameFromID(e.nic.ID())\n+ outNicName := stk.FindNICNameFromID(ep.nic.ID())\n+ if ok := stk.IPTables().Check(stack.Forward, pkt, nil, \"\" /* preroutingAddr */, inNicName, outNicName); !ok {\n+ // iptables is telling us to drop the packet.\n+ e.stats.ip.IPTablesForwardDropped.Increment()\n+ return nil\n+ }\n+\nep.handleValidatedPacket(h, pkt)\nreturn nil\n}\n@@ -952,7 +962,7 @@ func (e *endpoint) forwardPacket(pkt *stack.PacketBuffer) ip.ForwardingError {\nreturn &ip.ErrParameterProblem{}\n}\n- r, err := e.protocol.stack.FindRoute(0, \"\", dstAddr, ProtocolNumber, false /* multicastLoop */)\n+ r, err := stk.FindRoute(0, \"\", dstAddr, ProtocolNumber, false /* multicastLoop */)\nswitch err.(type) {\ncase nil:\ncase *tcpip.ErrNoRoute, *tcpip.ErrNetworkUnreachable:\n@@ -965,6 +975,14 @@ func (e *endpoint) forwardPacket(pkt *stack.PacketBuffer) ip.ForwardingError {\n}\ndefer r.Release()\n+ inNicName := stk.FindNICNameFromID(e.nic.ID())\n+ outNicName := stk.FindNICNameFromID(r.NICID())\n+ if ok := stk.IPTables().Check(stack.Forward, pkt, nil, \"\" /* preroutingAddr */, inNicName, outNicName); !ok {\n+ // iptables is telling us to drop the packet.\n+ e.stats.ip.IPTablesForwardDropped.Increment()\n+ return nil\n+ }\n+\n// We need to do a deep copy of the IP packet because\n// WriteHeaderIncludedPacket takes ownership of the packet buffer, but we do\n// not own it.\n@@ -1073,6 +1091,8 @@ func (e *endpoint) handleLocalPacket(pkt *stack.PacketBuffer, canSkipRXChecksum\nfunc (e *endpoint) handleValidatedPacket(h header.IPv6, pkt *stack.PacketBuffer) {\npkt.NICID = e.nic.ID()\nstats := e.stats.ip\n+ stats.ValidPacketsReceived.Increment()\n+\nsrcAddr := h.SourceAddress()\ndstAddr := h.DestinationAddress()\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/iptables.go", "new_path": "pkg/tcpip/stack/iptables.go", "diff": "@@ -177,6 +177,7 @@ func DefaultTables() *IPTables {\npriorities: [NumHooks][]TableID{\nPrerouting: {MangleID, NATID},\nInput: {NATID, FilterID},\n+ Forward: {FilterID},\nOutput: {MangleID, NATID, FilterID},\nPostrouting: {MangleID, NATID},\n},\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/iptables_types.go", "new_path": "pkg/tcpip/stack/iptables_types.go", "diff": "@@ -280,9 +280,18 @@ func (fl IPHeaderFilter) match(pkt *PacketBuffer, hook Hook, inNicName, outNicNa\nreturn matchIfName(inNicName, fl.InputInterface, fl.InputInterfaceInvert)\ncase Output:\nreturn matchIfName(outNicName, fl.OutputInterface, fl.OutputInterfaceInvert)\n- case Forward, Postrouting:\n- // TODO(gvisor.dev/issue/170): Add the check for FORWARD and POSTROUTING\n- // hooks after supported.\n+ case Forward:\n+ if !matchIfName(inNicName, fl.InputInterface, fl.InputInterfaceInvert) {\n+ return false\n+ }\n+\n+ if !matchIfName(outNicName, fl.OutputInterface, fl.OutputInterfaceInvert) {\n+ return false\n+ }\n+\n+ return true\n+ case Postrouting:\n+ // TODO(gvisor.dev/issue/170): Add the check for POSTROUTING.\nreturn true\ndefault:\npanic(fmt.Sprintf(\"unknown hook: %d\", hook))\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/tcpip.go", "new_path": "pkg/tcpip/tcpip.go", "diff": "@@ -1571,6 +1571,10 @@ type IPStats struct {\n// PacketsReceived is the number of IP packets received from the link layer.\nPacketsReceived *StatCounter\n+ // ValidPacketsReceived is the number of valid IP packets that reached the IP\n+ // layer.\n+ ValidPacketsReceived *StatCounter\n+\n// DisabledPacketsReceived is the number of IP packets received from the link\n// layer when the IP layer is disabled.\nDisabledPacketsReceived *StatCounter\n@@ -1610,6 +1614,10 @@ type IPStats struct {\n// chain.\nIPTablesInputDropped *StatCounter\n+ // IPTablesForwardDropped is the number of IP packets dropped in the Forward\n+ // chain.\n+ IPTablesForwardDropped *StatCounter\n+\n// IPTablesOutputDropped is the number of IP packets dropped in the Output\n// chain.\nIPTablesOutputDropped *StatCounter\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/tests/integration/BUILD", "new_path": "pkg/tcpip/tests/integration/BUILD", "diff": "@@ -31,12 +31,14 @@ go_test(\ndeps = [\n\"//pkg/tcpip\",\n\"//pkg/tcpip/buffer\",\n+ \"//pkg/tcpip/checker\",\n\"//pkg/tcpip/header\",\n\"//pkg/tcpip/link/channel\",\n\"//pkg/tcpip/network/ipv4\",\n\"//pkg/tcpip/network/ipv6\",\n\"//pkg/tcpip/stack\",\n\"//pkg/tcpip/tests/utils\",\n+ \"//pkg/tcpip/testutil\",\n\"//pkg/tcpip/transport/udp\",\n],\n)\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/tests/integration/iptables_test.go", "new_path": "pkg/tcpip/tests/integration/iptables_test.go", "diff": "@@ -19,12 +19,14 @@ import (\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/checker\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n\"gvisor.dev/gvisor/pkg/tcpip/link/channel\"\n\"gvisor.dev/gvisor/pkg/tcpip/network/ipv4\"\n\"gvisor.dev/gvisor/pkg/tcpip/network/ipv6\"\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n\"gvisor.dev/gvisor/pkg/tcpip/tests/utils\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/testutil\"\n\"gvisor.dev/gvisor/pkg/tcpip/transport/udp\"\n)\n@@ -645,3 +647,297 @@ func TestIPTableWritePackets(t *testing.T) {\n})\n}\n}\n+\n+const ttl = 64\n+\n+var (\n+ ipv4GlobalMulticastAddr = testutil.MustParse4(\"224.0.1.10\")\n+ ipv6GlobalMulticastAddr = testutil.MustParse6(\"ff0e::a\")\n+)\n+\n+func rxICMPv4EchoReply(e *channel.Endpoint, src, dst tcpip.Address) {\n+ utils.RxICMPv4EchoReply(e, src, dst, ttl)\n+}\n+\n+func rxICMPv6EchoReply(e *channel.Endpoint, src, dst tcpip.Address) {\n+ utils.RxICMPv6EchoReply(e, src, dst, ttl)\n+}\n+\n+func forwardedICMPv4EchoReplyChecker(t *testing.T, b []byte, src, dst tcpip.Address) {\n+ checker.IPv4(t, b,\n+ checker.SrcAddr(src),\n+ checker.DstAddr(dst),\n+ checker.TTL(ttl-1),\n+ checker.ICMPv4(\n+ checker.ICMPv4Type(header.ICMPv4EchoReply)))\n+}\n+\n+func forwardedICMPv6EchoReplyChecker(t *testing.T, b []byte, src, dst tcpip.Address) {\n+ checker.IPv6(t, b,\n+ checker.SrcAddr(src),\n+ checker.DstAddr(dst),\n+ checker.TTL(ttl-1),\n+ checker.ICMPv6(\n+ checker.ICMPv6Type(header.ICMPv6EchoReply)))\n+}\n+\n+func TestForwardingHook(t *testing.T) {\n+ const (\n+ nicID1 = 1\n+ nicID2 = 2\n+\n+ nic1Name = \"nic1\"\n+ nic2Name = \"nic2\"\n+\n+ otherNICName = \"otherNIC\"\n+ )\n+\n+ tests := []struct {\n+ name string\n+ netProto tcpip.NetworkProtocolNumber\n+ local bool\n+ srcAddr, dstAddr tcpip.Address\n+ rx func(*channel.Endpoint, tcpip.Address, tcpip.Address)\n+ checker func(*testing.T, []byte)\n+ }{\n+ {\n+ name: \"IPv4 remote\",\n+ netProto: ipv4.ProtocolNumber,\n+ local: false,\n+ srcAddr: utils.RemoteIPv4Addr,\n+ dstAddr: utils.Ipv4Addr2.AddressWithPrefix.Address,\n+ rx: rxICMPv4EchoReply,\n+ checker: func(t *testing.T, b []byte) {\n+ forwardedICMPv4EchoReplyChecker(t, b, utils.RemoteIPv4Addr, utils.Ipv4Addr2.AddressWithPrefix.Address)\n+ },\n+ },\n+ {\n+ name: \"IPv4 local\",\n+ netProto: ipv4.ProtocolNumber,\n+ local: true,\n+ srcAddr: utils.RemoteIPv4Addr,\n+ dstAddr: utils.Ipv4Addr.Address,\n+ rx: rxICMPv4EchoReply,\n+ },\n+ {\n+ name: \"IPv6 remote\",\n+ netProto: ipv6.ProtocolNumber,\n+ local: false,\n+ srcAddr: utils.RemoteIPv6Addr,\n+ dstAddr: utils.Ipv6Addr2.AddressWithPrefix.Address,\n+ rx: rxICMPv6EchoReply,\n+ checker: func(t *testing.T, b []byte) {\n+ forwardedICMPv6EchoReplyChecker(t, b, utils.RemoteIPv6Addr, utils.Ipv6Addr2.AddressWithPrefix.Address)\n+ },\n+ },\n+ {\n+ name: \"IPv6 local\",\n+ netProto: ipv6.ProtocolNumber,\n+ local: true,\n+ srcAddr: utils.RemoteIPv6Addr,\n+ dstAddr: utils.Ipv6Addr.Address,\n+ rx: rxICMPv6EchoReply,\n+ },\n+ }\n+\n+ setupDropFilter := func(f stack.IPHeaderFilter) func(*testing.T, *stack.Stack, tcpip.NetworkProtocolNumber) {\n+ return func(t *testing.T, s *stack.Stack, netProto tcpip.NetworkProtocolNumber) {\n+ t.Helper()\n+\n+ ipv6 := netProto == ipv6.ProtocolNumber\n+\n+ ipt := s.IPTables()\n+ filter := ipt.GetTable(stack.FilterID, ipv6)\n+ ruleIdx := filter.BuiltinChains[stack.Forward]\n+ filter.Rules[ruleIdx].Filter = f\n+ filter.Rules[ruleIdx].Target = &stack.DropTarget{NetworkProtocol: netProto}\n+ // Make sure the packet is not dropped by the next rule.\n+ filter.Rules[ruleIdx+1].Target = &stack.AcceptTarget{NetworkProtocol: netProto}\n+ if err := ipt.ReplaceTable(stack.FilterID, filter, ipv6); err != nil {\n+ t.Fatalf(\"ipt.RelaceTable(%d, _, %t): %s\", stack.FilterID, ipv6, err)\n+ }\n+ }\n+ }\n+\n+ boolToInt := func(v bool) uint64 {\n+ if v {\n+ return 1\n+ }\n+ return 0\n+ }\n+\n+ subTests := []struct {\n+ name string\n+ setupFilter func(*testing.T, *stack.Stack, tcpip.NetworkProtocolNumber)\n+ expectForward bool\n+ }{\n+ {\n+ name: \"Accept\",\n+ setupFilter: func(*testing.T, *stack.Stack, tcpip.NetworkProtocolNumber) { /* no filter */ },\n+ expectForward: true,\n+ },\n+\n+ {\n+ name: \"Drop\",\n+ setupFilter: setupDropFilter(stack.IPHeaderFilter{}),\n+ expectForward: false,\n+ },\n+ {\n+ name: \"Drop with input NIC filtering\",\n+ setupFilter: setupDropFilter(stack.IPHeaderFilter{InputInterface: nic1Name}),\n+ expectForward: false,\n+ },\n+ {\n+ name: \"Drop with output NIC filtering\",\n+ setupFilter: setupDropFilter(stack.IPHeaderFilter{OutputInterface: nic2Name}),\n+ expectForward: false,\n+ },\n+ {\n+ name: \"Drop with input and output NIC filtering\",\n+ setupFilter: setupDropFilter(stack.IPHeaderFilter{InputInterface: nic1Name, OutputInterface: nic2Name}),\n+ expectForward: false,\n+ },\n+\n+ {\n+ name: \"Drop with other input NIC filtering\",\n+ setupFilter: setupDropFilter(stack.IPHeaderFilter{InputInterface: otherNICName}),\n+ expectForward: true,\n+ },\n+ {\n+ name: \"Drop with other output NIC filtering\",\n+ setupFilter: setupDropFilter(stack.IPHeaderFilter{OutputInterface: otherNICName}),\n+ expectForward: true,\n+ },\n+ {\n+ name: \"Drop with other input and output NIC filtering\",\n+ setupFilter: setupDropFilter(stack.IPHeaderFilter{InputInterface: otherNICName, OutputInterface: nic2Name}),\n+ expectForward: true,\n+ },\n+ {\n+ name: \"Drop with input and other output NIC filtering\",\n+ setupFilter: setupDropFilter(stack.IPHeaderFilter{InputInterface: nic1Name, OutputInterface: otherNICName}),\n+ expectForward: true,\n+ },\n+ {\n+ name: \"Drop with other input and other output NIC filtering\",\n+ setupFilter: setupDropFilter(stack.IPHeaderFilter{InputInterface: otherNICName, OutputInterface: otherNICName}),\n+ expectForward: true,\n+ },\n+\n+ {\n+ name: \"Drop with inverted input NIC filtering\",\n+ setupFilter: setupDropFilter(stack.IPHeaderFilter{InputInterface: nic1Name, InputInterfaceInvert: true}),\n+ expectForward: true,\n+ },\n+ {\n+ name: \"Drop with inverted output NIC filtering\",\n+ setupFilter: setupDropFilter(stack.IPHeaderFilter{OutputInterface: nic2Name, OutputInterfaceInvert: true}),\n+ expectForward: true,\n+ },\n+ }\n+\n+ for _, test := range tests {\n+ t.Run(test.name, func(t *testing.T) {\n+ for _, subTest := range subTests {\n+ t.Run(subTest.name, func(t *testing.T) {\n+ s := stack.New(stack.Options{\n+ NetworkProtocols: []stack.NetworkProtocolFactory{ipv4.NewProtocol, ipv6.NewProtocol},\n+ })\n+\n+ subTest.setupFilter(t, s, test.netProto)\n+\n+ e1 := channel.New(1, header.IPv6MinimumMTU, \"\")\n+ if err := s.CreateNICWithOptions(nicID1, e1, stack.NICOptions{Name: nic1Name}); err != nil {\n+ t.Fatalf(\"s.CreateNICWithOptions(%d, _, _): %s\", nicID1, err)\n+ }\n+\n+ e2 := channel.New(1, header.IPv6MinimumMTU, \"\")\n+ if err := s.CreateNICWithOptions(nicID2, e2, stack.NICOptions{Name: nic2Name}); err != nil {\n+ t.Fatalf(\"s.CreateNICWithOptions(%d, _, _): %s\", nicID2, err)\n+ }\n+\n+ if err := s.AddAddress(nicID2, ipv4.ProtocolNumber, utils.Ipv4Addr.Address); err != nil {\n+ t.Fatalf(\"s.AddAddress(%d, %d, %s): %s\", nicID2, ipv4.ProtocolNumber, utils.Ipv4Addr.Address, err)\n+ }\n+ if err := s.AddAddress(nicID2, ipv6.ProtocolNumber, utils.Ipv6Addr.Address); err != nil {\n+ t.Fatalf(\"s.AddAddress(%d, %d, %s): %s\", nicID2, ipv6.ProtocolNumber, utils.Ipv6Addr.Address, err)\n+ }\n+\n+ if err := s.SetForwardingDefaultAndAllNICs(ipv4.ProtocolNumber, true); err != nil {\n+ t.Fatalf(\"s.SetForwardingDefaultAndAllNICs(%d, true): %s\", ipv4.ProtocolNumber, err)\n+ }\n+ if err := s.SetForwardingDefaultAndAllNICs(ipv6.ProtocolNumber, true); err != nil {\n+ t.Fatalf(\"s.SetForwardingDefaultAndAllNICs(%d, true): %s\", ipv6.ProtocolNumber, err)\n+ }\n+\n+ s.SetRouteTable([]tcpip.Route{\n+ {\n+ Destination: header.IPv4EmptySubnet,\n+ NIC: nicID2,\n+ },\n+ {\n+ Destination: header.IPv6EmptySubnet,\n+ NIC: nicID2,\n+ },\n+ })\n+\n+ test.rx(e1, test.srcAddr, test.dstAddr)\n+\n+ expectTransmitPacket := subTest.expectForward && !test.local\n+\n+ ep1, err := s.GetNetworkEndpoint(nicID1, test.netProto)\n+ if err != nil {\n+ t.Fatalf(\"s.GetNetworkEndpoint(%d, %d): %s\", nicID1, test.netProto, err)\n+ }\n+ ep1Stats := ep1.Stats()\n+ ipEP1Stats, ok := ep1Stats.(stack.IPNetworkEndpointStats)\n+ if !ok {\n+ t.Fatalf(\"got ep1Stats = %T, want = stack.IPNetworkEndpointStats\", ep1Stats)\n+ }\n+ ip1Stats := ipEP1Stats.IPStats()\n+\n+ if got := ip1Stats.PacketsReceived.Value(); got != 1 {\n+ t.Errorf(\"got ip1Stats.PacketsReceived.Value() = %d, want = 1\", got)\n+ }\n+ if got := ip1Stats.ValidPacketsReceived.Value(); got != 1 {\n+ t.Errorf(\"got ip1Stats.ValidPacketsReceived.Value() = %d, want = 1\", got)\n+ }\n+ if got, want := ip1Stats.IPTablesForwardDropped.Value(), boolToInt(!subTest.expectForward); got != want {\n+ t.Errorf(\"got ip1Stats.IPTablesForwardDropped.Value() = %d, want = %d\", got, want)\n+ }\n+ if got := ip1Stats.PacketsSent.Value(); got != 0 {\n+ t.Errorf(\"got ip1Stats.PacketsSent.Value() = %d, want = 0\", got)\n+ }\n+\n+ ep2, err := s.GetNetworkEndpoint(nicID2, test.netProto)\n+ if err != nil {\n+ t.Fatalf(\"s.GetNetworkEndpoint(%d, %d): %s\", nicID2, test.netProto, err)\n+ }\n+ ep2Stats := ep2.Stats()\n+ ipEP2Stats, ok := ep2Stats.(stack.IPNetworkEndpointStats)\n+ if !ok {\n+ t.Fatalf(\"got ep2Stats = %T, want = stack.IPNetworkEndpointStats\", ep2Stats)\n+ }\n+ ip2Stats := ipEP2Stats.IPStats()\n+ if got := ip2Stats.PacketsReceived.Value(); got != 0 {\n+ t.Errorf(\"got ip2Stats.PacketsReceived.Value() = %d, want = 0\", got)\n+ }\n+ if got, want := ip2Stats.ValidPacketsReceived.Value(), boolToInt(subTest.expectForward && test.local); got != want {\n+ t.Errorf(\"got ip2Stats.ValidPacketsReceived.Value() = %d, want = %d\", got, want)\n+ }\n+ if got, want := ip2Stats.PacketsSent.Value(), boolToInt(expectTransmitPacket); got != want {\n+ t.Errorf(\"got ip2Stats.PacketsSent.Value() = %d, want = %d\", got, want)\n+ }\n+\n+ p, ok := e2.Read()\n+ if ok != expectTransmitPacket {\n+ t.Fatalf(\"got e2.Read() = (%#v, %t), want = (_, %t)\", p, ok, expectTransmitPacket)\n+ }\n+ if expectTransmitPacket {\n+ test.checker(t, stack.PayloadSince(p.Pkt.NetworkHeader()))\n+ }\n+ })\n+ }\n+ })\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/tests/utils/utils.go", "new_path": "pkg/tcpip/tests/utils/utils.go", "diff": "@@ -316,13 +316,11 @@ func SetupRoutedStacks(t *testing.T, host1Stack, routerStack, host2Stack *stack.\n})\n}\n-// RxICMPv4EchoRequest constructs and injects an ICMPv4 echo request packet on\n-// the provided endpoint.\n-func RxICMPv4EchoRequest(e *channel.Endpoint, src, dst tcpip.Address, ttl uint8) {\n+func rxICMPv4Echo(e *channel.Endpoint, src, dst tcpip.Address, ttl uint8, ty header.ICMPv4Type) {\ntotalLen := header.IPv4MinimumSize + header.ICMPv4MinimumSize\nhdr := buffer.NewPrependable(totalLen)\npkt := header.ICMPv4(hdr.Prepend(header.ICMPv4MinimumSize))\n- pkt.SetType(header.ICMPv4Echo)\n+ pkt.SetType(ty)\npkt.SetCode(header.ICMPv4UnusedCode)\npkt.SetChecksum(0)\npkt.SetChecksum(^header.Checksum(pkt, 0))\n@@ -341,13 +339,23 @@ func RxICMPv4EchoRequest(e *channel.Endpoint, src, dst tcpip.Address, ttl uint8)\n}))\n}\n-// RxICMPv6EchoRequest constructs and injects an ICMPv6 echo request packet on\n+// RxICMPv4EchoRequest constructs and injects an ICMPv4 echo request packet on\n// the provided endpoint.\n-func RxICMPv6EchoRequest(e *channel.Endpoint, src, dst tcpip.Address, ttl uint8) {\n+func RxICMPv4EchoRequest(e *channel.Endpoint, src, dst tcpip.Address, ttl uint8) {\n+ rxICMPv4Echo(e, src, dst, ttl, header.ICMPv4Echo)\n+}\n+\n+// RxICMPv4EchoReply constructs and injects an ICMPv4 echo reply packet on\n+// the provided endpoint.\n+func RxICMPv4EchoReply(e *channel.Endpoint, src, dst tcpip.Address, ttl uint8) {\n+ rxICMPv4Echo(e, src, dst, ttl, header.ICMPv4EchoReply)\n+}\n+\n+func rxICMPv6Echo(e *channel.Endpoint, src, dst tcpip.Address, ttl uint8, ty header.ICMPv6Type) {\ntotalLen := header.IPv6MinimumSize + header.ICMPv6MinimumSize\nhdr := buffer.NewPrependable(totalLen)\npkt := header.ICMPv6(hdr.Prepend(header.ICMPv6MinimumSize))\n- pkt.SetType(header.ICMPv6EchoRequest)\n+ pkt.SetType(ty)\npkt.SetCode(header.ICMPv6UnusedCode)\npkt.SetChecksum(0)\npkt.SetChecksum(header.ICMPv6Checksum(header.ICMPv6ChecksumParams{\n@@ -368,3 +376,15 @@ func RxICMPv6EchoRequest(e *channel.Endpoint, src, dst tcpip.Address, ttl uint8)\nData: hdr.View().ToVectorisedView(),\n}))\n}\n+\n+// RxICMPv6EchoRequest constructs and injects an ICMPv6 echo request packet on\n+// the provided endpoint.\n+func RxICMPv6EchoRequest(e *channel.Endpoint, src, dst tcpip.Address, ttl uint8) {\n+ rxICMPv6Echo(e, src, dst, ttl, header.ICMPv6EchoRequest)\n+}\n+\n+// RxICMPv6EchoReply constructs and injects an ICMPv6 echo reply packet on\n+// the provided endpoint.\n+func RxICMPv6EchoReply(e *channel.Endpoint, src, dst tcpip.Address, ttl uint8) {\n+ rxICMPv6Echo(e, src, dst, ttl, header.ICMPv6EchoReply)\n+}\n" } ]
Go
Apache License 2.0
google/gvisor
Check filter table when forwarding IP packets This change updates the forwarding path to perform the forwarding hook with iptables so that the filter table is consulted before a packet is forwarded Updates #170. Test: iptables_test.TestForwardingHook PiperOrigin-RevId: 373702359
260,003
14.05.2021 12:47:26
25,200
436148d68a50e086ae7b967d6a190b3137e68ac8
Fix panic on consume in a mixed push/consume case headerOffset() is incorrectly taking account of previous push(), so it thinks there is more data to consume. This change switches to use pk.reserved as pivot point. Reported-by:
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/packet_buffer.go", "new_path": "pkg/tcpip/stack/packet_buffer.go", "diff": "@@ -261,7 +261,7 @@ func (pk *PacketBuffer) consume(typ headerType, size int) (v tcpipbuffer.View, c\nif h.length > 0 {\npanic(fmt.Sprintf(\"consume must not be called twice: type %s\", typ))\n}\n- if pk.headerOffset()+pk.consumed+size > int(pk.buf.Size()) {\n+ if pk.reserved+pk.consumed+size > int(pk.buf.Size()) {\nreturn nil, false\n}\nh.offset = pk.consumed\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/packet_buffer_test.go", "new_path": "pkg/tcpip/stack/packet_buffer_test.go", "diff": "@@ -259,6 +259,37 @@ func TestPacketHeaderPushConsumeMixed(t *testing.T) {\n})\n}\n+func TestPacketHeaderPushConsumeMixedTooLong(t *testing.T) {\n+ link := makeView(10)\n+ network := makeView(20)\n+ data := makeView(30)\n+\n+ initData := concatViews(network, data)\n+ pk := NewPacketBuffer(PacketBufferOptions{\n+ ReserveHeaderBytes: len(link),\n+ Data: buffer.NewViewFromBytes(initData).ToVectorisedView(),\n+ })\n+\n+ // 1. Push link header\n+ copy(pk.LinkHeader().Push(len(link)), link)\n+\n+ checkPacketContents(t, \"\" /* prefix */, pk, packetContents{\n+ link: link,\n+ data: initData,\n+ })\n+\n+ // 2. Consume network header, with a number of bytes too large.\n+ gotNetwork, ok := pk.NetworkHeader().Consume(len(initData) + 1)\n+ if ok {\n+ t.Fatalf(\"pk.NetworkHeader().Consume(%d) = %q, true; want _, false\", len(initData)+1, gotNetwork)\n+ }\n+\n+ checkPacketContents(t, \"\" /* prefix */, pk, packetContents{\n+ link: link,\n+ data: initData,\n+ })\n+}\n+\nfunc TestPacketHeaderPushCalledAtMostOnce(t *testing.T) {\nconst headerSize = 10\n" } ]
Go
Apache License 2.0
google/gvisor
Fix panic on consume in a mixed push/consume case headerOffset() is incorrectly taking account of previous push(), so it thinks there is more data to consume. This change switches to use pk.reserved as pivot point. Reported-by: [email protected] PiperOrigin-RevId: 373846283
260,003
14.05.2021 12:50:19
25,200
2ac6b76884c7a8c8b788b4c376098ea48b9fe610
pkg/buffer: Remove dependency to safemem, code no longer used
[ { "change_type": "MODIFY", "old_path": "pkg/buffer/BUILD", "new_path": "pkg/buffer/BUILD", "diff": "@@ -21,7 +21,6 @@ go_library(\n\"buffer.go\",\n\"buffer_list.go\",\n\"pool.go\",\n- \"safemem.go\",\n\"view.go\",\n\"view_unsafe.go\",\n],\n@@ -29,8 +28,6 @@ go_library(\ndeps = [\n\"//pkg/context\",\n\"//pkg/log\",\n- \"//pkg/safemem\",\n- \"//pkg/usermem\",\n],\n)\n@@ -40,12 +37,10 @@ go_test(\nsrcs = [\n\"buffer_test.go\",\n\"pool_test.go\",\n- \"safemem_test.go\",\n\"view_test.go\",\n],\nlibrary = \":buffer\",\ndeps = [\n- \"//pkg/safemem\",\n\"//pkg/state\",\n],\n)\n" }, { "change_type": "DELETE", "old_path": "pkg/buffer/safemem.go", "new_path": null, "diff": "-// Copyright 2020 The gVisor Authors.\n-//\n-// Licensed under the Apache License, Version 2.0 (the \"License\");\n-// you may not use this file except in compliance with the License.\n-// You may obtain a copy of the License at\n-//\n-// http://www.apache.org/licenses/LICENSE-2.0\n-//\n-// Unless required by applicable law or agreed to in writing, software\n-// distributed under the License is distributed on an \"AS IS\" BASIS,\n-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n-// See the License for the specific language governing permissions and\n-// limitations under the License.\n-\n-package buffer\n-\n-import (\n- \"gvisor.dev/gvisor/pkg/safemem\"\n-)\n-\n-// WriteBlock returns this buffer as a write Block.\n-func (b *buffer) WriteBlock() safemem.Block {\n- return safemem.BlockFromSafeSlice(b.WriteSlice())\n-}\n-\n-// ReadBlock returns this buffer as a read Block.\n-func (b *buffer) ReadBlock() safemem.Block {\n- return safemem.BlockFromSafeSlice(b.ReadSlice())\n-}\n-\n-// WriteFromSafememReader writes up to count bytes from r to v and advances the\n-// write index by the number of bytes written. It calls r.ReadToBlocks() at\n-// most once.\n-func (v *View) WriteFromSafememReader(r safemem.Reader, count uint64) (uint64, error) {\n- if count == 0 {\n- return 0, nil\n- }\n-\n- var (\n- dst safemem.BlockSeq\n- blocks []safemem.Block\n- )\n-\n- // Need at least one buffer.\n- firstBuf := v.data.Back()\n- if firstBuf == nil {\n- firstBuf = v.pool.get()\n- v.data.PushBack(firstBuf)\n- }\n-\n- // Does the last block have sufficient capacity alone?\n- if l := uint64(firstBuf.WriteSize()); l >= count {\n- dst = safemem.BlockSeqOf(firstBuf.WriteBlock().TakeFirst64(count))\n- } else {\n- // Append blocks until sufficient.\n- count -= l\n- blocks = append(blocks, firstBuf.WriteBlock())\n- for count > 0 {\n- emptyBuf := v.pool.get()\n- v.data.PushBack(emptyBuf)\n- block := emptyBuf.WriteBlock().TakeFirst64(count)\n- count -= uint64(block.Len())\n- blocks = append(blocks, block)\n- }\n- dst = safemem.BlockSeqFromSlice(blocks)\n- }\n-\n- // Perform I/O.\n- n, err := r.ReadToBlocks(dst)\n- v.size += int64(n)\n-\n- // Update all indices.\n- for left := n; left > 0; firstBuf = firstBuf.Next() {\n- if l := firstBuf.WriteSize(); left >= uint64(l) {\n- firstBuf.WriteMove(l) // Whole block.\n- left -= uint64(l)\n- } else {\n- firstBuf.WriteMove(int(left)) // Partial block.\n- left = 0\n- }\n- }\n-\n- return n, err\n-}\n-\n-// WriteFromBlocks implements safemem.Writer.WriteFromBlocks. It advances the\n-// write index by the number of bytes written.\n-func (v *View) WriteFromBlocks(srcs safemem.BlockSeq) (uint64, error) {\n- return v.WriteFromSafememReader(&safemem.BlockSeqReader{srcs}, srcs.NumBytes())\n-}\n-\n-// ReadToSafememWriter reads up to count bytes from v to w. It does not advance\n-// the read index. It calls w.WriteFromBlocks() at most once.\n-func (v *View) ReadToSafememWriter(w safemem.Writer, count uint64) (uint64, error) {\n- if count == 0 {\n- return 0, nil\n- }\n-\n- var (\n- src safemem.BlockSeq\n- blocks []safemem.Block\n- )\n-\n- firstBuf := v.data.Front()\n- if firstBuf == nil {\n- return 0, nil // No EOF.\n- }\n-\n- // Is all the data in a single block?\n- if l := uint64(firstBuf.ReadSize()); l >= count {\n- src = safemem.BlockSeqOf(firstBuf.ReadBlock().TakeFirst64(count))\n- } else {\n- // Build a list of all the buffers.\n- count -= l\n- blocks = append(blocks, firstBuf.ReadBlock())\n- for buf := firstBuf.Next(); buf != nil && count > 0; buf = buf.Next() {\n- block := buf.ReadBlock().TakeFirst64(count)\n- count -= uint64(block.Len())\n- blocks = append(blocks, block)\n- }\n- src = safemem.BlockSeqFromSlice(blocks)\n- }\n-\n- // Perform I/O. As documented, we don't advance the read index.\n- return w.WriteFromBlocks(src)\n-}\n-\n-// ReadToBlocks implements safemem.Reader.ReadToBlocks. It does not advance the\n-// read index by the number of bytes read, such that it's only safe to call if\n-// the caller guarantees that ReadToBlocks will only be called once.\n-func (v *View) ReadToBlocks(dsts safemem.BlockSeq) (uint64, error) {\n- return v.ReadToSafememWriter(&safemem.BlockSeqWriter{dsts}, dsts.NumBytes())\n-}\n" }, { "change_type": "DELETE", "old_path": "pkg/buffer/safemem_test.go", "new_path": null, "diff": "-// Copyright 2020 The gVisor Authors.\n-//\n-// Licensed under the Apache License, Version 2.0 (the \"License\");\n-// you may not use this file except in compliance with the License.\n-// You may obtain a copy of the License at\n-//\n-// http://www.apache.org/licenses/LICENSE-2.0\n-//\n-// Unless required by applicable law or agreed to in writing, software\n-// distributed under the License is distributed on an \"AS IS\" BASIS,\n-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n-// See the License for the specific language governing permissions and\n-// limitations under the License.\n-\n-package buffer\n-\n-import (\n- \"bytes\"\n- \"strings\"\n- \"testing\"\n-\n- \"gvisor.dev/gvisor/pkg/safemem\"\n-)\n-\n-func TestSafemem(t *testing.T) {\n- const bufferSize = defaultBufferSize\n-\n- testCases := []struct {\n- name string\n- input string\n- output string\n- readLen int\n- op func(*View)\n- }{\n- // Basic coverage.\n- {\n- name: \"short\",\n- input: \"010\",\n- output: \"010\",\n- },\n- {\n- name: \"long\",\n- input: \"0\" + strings.Repeat(\"1\", bufferSize) + \"0\",\n- output: \"0\" + strings.Repeat(\"1\", bufferSize) + \"0\",\n- },\n- {\n- name: \"short-read\",\n- input: \"0\",\n- readLen: 100, // > size.\n- output: \"0\",\n- },\n- {\n- name: \"zero-read\",\n- input: \"0\",\n- output: \"\",\n- },\n- {\n- name: \"read-empty\",\n- input: \"\",\n- readLen: 1, // > size.\n- output: \"\",\n- },\n-\n- // Ensure offsets work.\n- {\n- name: \"offsets-short\",\n- input: \"012\",\n- output: \"2\",\n- op: func(v *View) {\n- v.TrimFront(2)\n- },\n- },\n- {\n- name: \"offsets-long0\",\n- input: \"0\" + strings.Repeat(\"1\", bufferSize) + \"0\",\n- output: strings.Repeat(\"1\", bufferSize) + \"0\",\n- op: func(v *View) {\n- v.TrimFront(1)\n- },\n- },\n- {\n- name: \"offsets-long1\",\n- input: \"0\" + strings.Repeat(\"1\", bufferSize) + \"0\",\n- output: strings.Repeat(\"1\", bufferSize-1) + \"0\",\n- op: func(v *View) {\n- v.TrimFront(2)\n- },\n- },\n- {\n- name: \"offsets-long2\",\n- input: \"0\" + strings.Repeat(\"1\", bufferSize) + \"0\",\n- output: \"10\",\n- op: func(v *View) {\n- v.TrimFront(bufferSize)\n- },\n- },\n-\n- // Ensure truncation works.\n- {\n- name: \"truncate-short\",\n- input: \"012\",\n- output: \"01\",\n- op: func(v *View) {\n- v.Truncate(2)\n- },\n- },\n- {\n- name: \"truncate-long0\",\n- input: \"0\" + strings.Repeat(\"1\", bufferSize) + \"0\",\n- output: \"0\" + strings.Repeat(\"1\", bufferSize),\n- op: func(v *View) {\n- v.Truncate(bufferSize + 1)\n- },\n- },\n- {\n- name: \"truncate-long1\",\n- input: \"0\" + strings.Repeat(\"1\", bufferSize) + \"0\",\n- output: \"0\" + strings.Repeat(\"1\", bufferSize-1),\n- op: func(v *View) {\n- v.Truncate(bufferSize)\n- },\n- },\n- {\n- name: \"truncate-long2\",\n- input: \"0\" + strings.Repeat(\"1\", bufferSize) + \"0\",\n- output: \"01\",\n- op: func(v *View) {\n- v.Truncate(2)\n- },\n- },\n- }\n-\n- for _, tc := range testCases {\n- t.Run(tc.name, func(t *testing.T) {\n- // Construct the new view.\n- var view View\n- bs := safemem.BlockSeqOf(safemem.BlockFromSafeSlice([]byte(tc.input)))\n- n, err := view.WriteFromBlocks(bs)\n- if err != nil {\n- t.Errorf(\"expected err nil, got %v\", err)\n- }\n- if n != uint64(len(tc.input)) {\n- t.Errorf(\"expected %d bytes, got %d\", len(tc.input), n)\n- }\n-\n- // Run the operation.\n- if tc.op != nil {\n- tc.op(&view)\n- }\n-\n- // Read and validate.\n- readLen := tc.readLen\n- if readLen == 0 {\n- readLen = len(tc.output) // Default.\n- }\n- out := make([]byte, readLen)\n- bs = safemem.BlockSeqOf(safemem.BlockFromSafeSlice(out))\n- n, err = view.ReadToBlocks(bs)\n- if err != nil {\n- t.Errorf(\"expected nil, got %v\", err)\n- }\n- if n != uint64(len(tc.output)) {\n- t.Errorf(\"expected %d bytes, got %d\", len(tc.output), n)\n- }\n-\n- // Ensure the contents are correct.\n- if !bytes.Equal(out[:n], []byte(tc.output[:n])) {\n- t.Errorf(\"contents are wrong: expected %q, got %q\", tc.output, string(out))\n- }\n- })\n- }\n-}\n" } ]
Go
Apache License 2.0
google/gvisor
pkg/buffer: Remove dependency to safemem, code no longer used PiperOrigin-RevId: 373846881
260,001
14.05.2021 13:27:14
25,200
eb7e83f645cc21f3219865d38fa7f8e06852c822
Add verity_mmap tests
[ { "change_type": "MODIFY", "old_path": "test/syscalls/BUILD", "new_path": "test/syscalls/BUILD", "diff": "@@ -312,6 +312,10 @@ syscall_test(\ntest = \"//test/syscalls/linux:mmap_test\",\n)\n+syscall_test(\n+ test = \"//test/syscalls/linux:verity_mmap_test\",\n+)\n+\nsyscall_test(\nadd_overlay = True,\ntest = \"//test/syscalls/linux:mount_test\",\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/BUILD", "new_path": "test/syscalls/linux/BUILD", "diff": "@@ -1024,6 +1024,7 @@ cc_binary(\n\"//test/util:temp_path\",\n\"//test/util:test_main\",\n\"//test/util:test_util\",\n+ \"//test/util:verity_util\",\n],\n)\n@@ -1293,6 +1294,23 @@ cc_binary(\n],\n)\n+cc_binary(\n+ name = \"verity_mmap_test\",\n+ testonly = 1,\n+ srcs = [\"verity_mmap.cc\"],\n+ linkstatic = 1,\n+ deps = [\n+ \"//test/util:capability_util\",\n+ gtest,\n+ \"//test/util:fs_util\",\n+ \"//test/util:memory_util\",\n+ \"//test/util:temp_path\",\n+ \"//test/util:test_main\",\n+ \"//test/util:test_util\",\n+ \"//test/util:verity_util\",\n+ ],\n+)\n+\ncc_binary(\nname = \"mount_test\",\ntestonly = 1,\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/verity_ioctl.cc", "new_path": "test/syscalls/linux/verity_ioctl.cc", "diff": "#include \"test/util/mount_util.h\"\n#include \"test/util/temp_path.h\"\n#include \"test/util/test_util.h\"\n+#include \"test/util/verity_util.h\"\nnamespace gvisor {\nnamespace testing {\nnamespace {\n-#ifndef FS_IOC_ENABLE_VERITY\n-#define FS_IOC_ENABLE_VERITY 1082156677\n-#endif\n-\n-#ifndef FS_IOC_MEASURE_VERITY\n-#define FS_IOC_MEASURE_VERITY 3221513862\n-#endif\n-\n-#ifndef FS_VERITY_FL\n-#define FS_VERITY_FL 1048576\n-#endif\n-\n-#ifndef FS_IOC_GETFLAGS\n-#define FS_IOC_GETFLAGS 2148034049\n-#endif\n-\n-struct fsverity_digest {\n- __u16 digest_algorithm;\n- __u16 digest_size; /* input/output */\n- __u8 digest[];\n-};\n-\n-constexpr int kMaxDigestSize = 64;\n-constexpr int kDefaultDigestSize = 32;\n-constexpr char kContents[] = \"foobarbaz\";\n-constexpr char kMerklePrefix[] = \".merkle.verity.\";\n-constexpr char kMerkleRootPrefix[] = \".merkleroot.verity.\";\n-\nclass IoctlTest : public ::testing::Test {\nprotected:\nvoid SetUp() override {\n@@ -85,80 +58,6 @@ class IoctlTest : public ::testing::Test {\nstd::string filename_;\n};\n-// Provide a function to convert bytes to hex string, since\n-// absl::BytesToHexString does not seem to be compatible with golang\n-// hex.DecodeString used in verity due to zero-padding.\n-std::string BytesToHexString(uint8_t bytes[], int size) {\n- std::stringstream ss;\n- ss << std::hex;\n- for (int i = 0; i < size; ++i) {\n- ss << std::setw(2) << std::setfill('0') << static_cast<int>(bytes[i]);\n- }\n- return ss.str();\n-}\n-\n-std::string MerklePath(absl::string_view path) {\n- return JoinPath(Dirname(path),\n- std::string(kMerklePrefix) + std::string(Basename(path)));\n-}\n-\n-std::string MerkleRootPath(absl::string_view path) {\n- return JoinPath(Dirname(path),\n- std::string(kMerkleRootPrefix) + std::string(Basename(path)));\n-}\n-\n-// Flip a random bit in the file represented by fd.\n-PosixError FlipRandomBit(int fd, int size) {\n- // Generate a random offset in the file.\n- srand(time(nullptr));\n- unsigned int seed = 0;\n- int random_offset = rand_r(&seed) % size;\n-\n- // Read a random byte and flip a bit in it.\n- char buf[1];\n- RETURN_ERROR_IF_SYSCALL_FAIL(PreadFd(fd, buf, 1, random_offset));\n- buf[0] ^= 1;\n- RETURN_ERROR_IF_SYSCALL_FAIL(PwriteFd(fd, buf, 1, random_offset));\n- return NoError();\n-}\n-\n-// Mount a verity on the tmpfs and enable both the file and the direcotry. Then\n-// mount a new verity with measured root hash.\n-PosixErrorOr<std::string> MountVerity(std::string tmpfs_dir,\n- std::string filename) {\n- // Mount a verity fs on the existing tmpfs mount.\n- std::string mount_opts = \"lower_path=\" + tmpfs_dir;\n- ASSIGN_OR_RETURN_ERRNO(TempPath verity_dir, TempPath::CreateDir());\n- RETURN_ERROR_IF_SYSCALL_FAIL(\n- mount(\"\", verity_dir.path().c_str(), \"verity\", 0, mount_opts.c_str()));\n-\n- // Enable both the file and the directory.\n- ASSIGN_OR_RETURN_ERRNO(\n- auto fd, Open(JoinPath(verity_dir.path(), filename), O_RDONLY, 0777));\n- RETURN_ERROR_IF_SYSCALL_FAIL(ioctl(fd.get(), FS_IOC_ENABLE_VERITY));\n- ASSIGN_OR_RETURN_ERRNO(auto dir_fd, Open(verity_dir.path(), O_RDONLY, 0777));\n- RETURN_ERROR_IF_SYSCALL_FAIL(ioctl(dir_fd.get(), FS_IOC_ENABLE_VERITY));\n-\n- // Measure the root hash.\n- uint8_t digest_array[sizeof(struct fsverity_digest) + kMaxDigestSize] = {0};\n- struct fsverity_digest* digest =\n- reinterpret_cast<struct fsverity_digest*>(digest_array);\n- digest->digest_size = kMaxDigestSize;\n- RETURN_ERROR_IF_SYSCALL_FAIL(\n- ioctl(dir_fd.get(), FS_IOC_MEASURE_VERITY, digest));\n-\n- // Mount a verity fs with specified root hash.\n- mount_opts +=\n- \",root_hash=\" + BytesToHexString(digest->digest, digest->digest_size);\n- ASSIGN_OR_RETURN_ERRNO(TempPath verity_with_hash_dir, TempPath::CreateDir());\n- RETURN_ERROR_IF_SYSCALL_FAIL(mount(\"\", verity_with_hash_dir.path().c_str(),\n- \"verity\", 0, mount_opts.c_str()));\n- // Verity directories should not be deleted. Release the TempPath objects to\n- // prevent those directories from being deleted by the destructor.\n- verity_dir.release();\n- return verity_with_hash_dir.release();\n-}\n-\nTEST_F(IoctlTest, Enable) {\n// Mount a verity fs on the existing tmpfs mount.\nstd::string mount_opts = \"lower_path=\" + tmpfs_dir_.path();\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test/syscalls/linux/verity_mmap.cc", "diff": "+// Copyright 2021 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+#include <stdint.h>\n+#include <stdlib.h>\n+#include <sys/mman.h>\n+#include <sys/mount.h>\n+\n+#include <string>\n+\n+#include \"gmock/gmock.h\"\n+#include \"gtest/gtest.h\"\n+#include \"test/util/capability_util.h\"\n+#include \"test/util/fs_util.h\"\n+#include \"test/util/memory_util.h\"\n+#include \"test/util/temp_path.h\"\n+#include \"test/util/test_util.h\"\n+#include \"test/util/verity_util.h\"\n+\n+namespace gvisor {\n+namespace testing {\n+\n+namespace {\n+\n+class MmapTest : public ::testing::Test {\n+ protected:\n+ void SetUp() override {\n+ // Verity is implemented in VFS2.\n+ SKIP_IF(IsRunningWithVFS1());\n+\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_SYS_ADMIN)));\n+ // Mount a tmpfs file system, to be wrapped by a verity fs.\n+ tmpfs_dir_ = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n+ ASSERT_THAT(mount(\"\", tmpfs_dir_.path().c_str(), \"tmpfs\", 0, \"\"),\n+ SyscallSucceeds());\n+\n+ // Create a new file in the tmpfs mount.\n+ file_ = ASSERT_NO_ERRNO_AND_VALUE(\n+ TempPath::CreateFileWith(tmpfs_dir_.path(), kContents, 0777));\n+ filename_ = Basename(file_.path());\n+ }\n+\n+ TempPath tmpfs_dir_;\n+ TempPath file_;\n+ std::string filename_;\n+};\n+\n+TEST_F(MmapTest, MmapRead) {\n+ std::string verity_dir =\n+ ASSERT_NO_ERRNO_AND_VALUE(MountVerity(tmpfs_dir_.path(), filename_));\n+\n+ // Make sure the file can be open and mmapped in the mounted verity fs.\n+ auto const verity_fd = ASSERT_NO_ERRNO_AND_VALUE(\n+ Open(JoinPath(verity_dir, filename_), O_RDONLY, 0777));\n+\n+ Mapping const m =\n+ ASSERT_NO_ERRNO_AND_VALUE(Mmap(nullptr, sizeof(kContents) - 1, PROT_READ,\n+ MAP_SHARED, verity_fd.get(), 0));\n+ EXPECT_THAT(std::string(m.view()), ::testing::StrEq(kContents));\n+}\n+\n+TEST_F(MmapTest, ModifiedBeforeMmap) {\n+ std::string verity_dir =\n+ ASSERT_NO_ERRNO_AND_VALUE(MountVerity(tmpfs_dir_.path(), filename_));\n+\n+ // Modify the file and check verification failure upon mmapping.\n+ auto const fd = ASSERT_NO_ERRNO_AND_VALUE(\n+ Open(JoinPath(tmpfs_dir_.path(), filename_), O_RDWR, 0777));\n+ ASSERT_NO_ERRNO(FlipRandomBit(fd.get(), sizeof(kContents) - 1));\n+\n+ auto const verity_fd = ASSERT_NO_ERRNO_AND_VALUE(\n+ Open(JoinPath(verity_dir, filename_), O_RDONLY, 0777));\n+ Mapping const m =\n+ ASSERT_NO_ERRNO_AND_VALUE(Mmap(nullptr, sizeof(kContents) - 1, PROT_READ,\n+ MAP_SHARED, verity_fd.get(), 0));\n+\n+ // Memory fault is expected when Translate fails.\n+ EXPECT_EXIT(std::string(m.view()), ::testing::KilledBySignal(SIGSEGV), \"\");\n+}\n+\n+TEST_F(MmapTest, ModifiedAfterMmap) {\n+ std::string verity_dir =\n+ ASSERT_NO_ERRNO_AND_VALUE(MountVerity(tmpfs_dir_.path(), filename_));\n+\n+ auto const verity_fd = ASSERT_NO_ERRNO_AND_VALUE(\n+ Open(JoinPath(verity_dir, filename_), O_RDONLY, 0777));\n+ Mapping const m =\n+ ASSERT_NO_ERRNO_AND_VALUE(Mmap(nullptr, sizeof(kContents) - 1, PROT_READ,\n+ MAP_SHARED, verity_fd.get(), 0));\n+\n+ // Modify the file after mapping and check verification failure upon mmapping.\n+ auto const fd = ASSERT_NO_ERRNO_AND_VALUE(\n+ Open(JoinPath(tmpfs_dir_.path(), filename_), O_RDWR, 0777));\n+ ASSERT_NO_ERRNO(FlipRandomBit(fd.get(), sizeof(kContents) - 1));\n+\n+ // Memory fault is expected when Translate fails.\n+ EXPECT_EXIT(std::string(m.view()), ::testing::KilledBySignal(SIGSEGV), \"\");\n+}\n+\n+class MmapParamTest\n+ : public MmapTest,\n+ public ::testing::WithParamInterface<std::tuple<int, int>> {\n+ protected:\n+ int prot() const { return std::get<0>(GetParam()); }\n+ int flags() const { return std::get<1>(GetParam()); }\n+};\n+\n+INSTANTIATE_TEST_SUITE_P(\n+ WriteExecNoneSharedPrivate, MmapParamTest,\n+ ::testing::Combine(::testing::ValuesIn({\n+ PROT_WRITE,\n+ PROT_EXEC,\n+ PROT_NONE,\n+ }),\n+ ::testing::ValuesIn({MAP_SHARED, MAP_PRIVATE})));\n+\n+TEST_P(MmapParamTest, Mmap) {\n+ std::string verity_dir =\n+ ASSERT_NO_ERRNO_AND_VALUE(MountVerity(tmpfs_dir_.path(), filename_));\n+\n+ // Make sure the file can be open and mmapped in the mounted verity fs.\n+ auto const verity_fd = ASSERT_NO_ERRNO_AND_VALUE(\n+ Open(JoinPath(verity_dir, filename_), O_RDONLY, 0777));\n+\n+ if (prot() == PROT_WRITE && flags() == MAP_SHARED) {\n+ // Verity file system is read-only.\n+ EXPECT_THAT(\n+ reinterpret_cast<intptr_t>(mmap(nullptr, sizeof(kContents) - 1, prot(),\n+ flags(), verity_fd.get(), 0)),\n+ SyscallFailsWithErrno(EACCES));\n+ } else {\n+ Mapping const m = ASSERT_NO_ERRNO_AND_VALUE(Mmap(\n+ nullptr, sizeof(kContents) - 1, prot(), flags(), verity_fd.get(), 0));\n+ if (prot() == PROT_NONE) {\n+ // Memory mapped by MAP_NONE cannot be accessed.\n+ EXPECT_EXIT(std::string(m.view()), ::testing::KilledBySignal(SIGSEGV),\n+ \"\");\n+ } else {\n+ EXPECT_THAT(std::string(m.view()), ::testing::StrEq(kContents));\n+ }\n+ }\n+}\n+\n+} // namespace\n+\n+} // namespace testing\n+} // namespace gvisor\n" }, { "change_type": "MODIFY", "old_path": "test/util/BUILD", "new_path": "test/util/BUILD", "diff": "@@ -401,3 +401,16 @@ cc_library(\n\"@com_google_absl//absl/strings\",\n],\n)\n+\n+cc_library(\n+ name = \"verity_util\",\n+ testonly = 1,\n+ srcs = [\"verity_util.cc\"],\n+ hdrs = [\"verity_util.h\"],\n+ deps = [\n+ \":fs_util\",\n+ \":mount_util\",\n+ \":posix_error\",\n+ \":temp_path\",\n+ ],\n+)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test/util/verity_util.cc", "diff": "+// Copyright 2021 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+#include \"test/util/verity_util.h\"\n+\n+#include \"test/util/fs_util.h\"\n+#include \"test/util/mount_util.h\"\n+#include \"test/util/temp_path.h\"\n+\n+namespace gvisor {\n+namespace testing {\n+\n+std::string BytesToHexString(uint8_t bytes[], int size) {\n+ std::stringstream ss;\n+ ss << std::hex;\n+ for (int i = 0; i < size; ++i) {\n+ ss << std::setw(2) << std::setfill('0') << static_cast<int>(bytes[i]);\n+ }\n+ return ss.str();\n+}\n+\n+std::string MerklePath(absl::string_view path) {\n+ return JoinPath(Dirname(path),\n+ std::string(kMerklePrefix) + std::string(Basename(path)));\n+}\n+\n+std::string MerkleRootPath(absl::string_view path) {\n+ return JoinPath(Dirname(path),\n+ std::string(kMerkleRootPrefix) + std::string(Basename(path)));\n+}\n+\n+PosixError FlipRandomBit(int fd, int size) {\n+ // Generate a random offset in the file.\n+ srand(time(nullptr));\n+ unsigned int seed = 0;\n+ int random_offset = rand_r(&seed) % size;\n+\n+ // Read a random byte and flip a bit in it.\n+ char buf[1];\n+ RETURN_ERROR_IF_SYSCALL_FAIL(PreadFd(fd, buf, 1, random_offset));\n+ buf[0] ^= 1;\n+ RETURN_ERROR_IF_SYSCALL_FAIL(PwriteFd(fd, buf, 1, random_offset));\n+ return NoError();\n+}\n+\n+PosixErrorOr<std::string> MountVerity(std::string tmpfs_dir,\n+ std::string filename) {\n+ // Mount a verity fs on the existing tmpfs mount.\n+ std::string mount_opts = \"lower_path=\" + tmpfs_dir;\n+ ASSIGN_OR_RETURN_ERRNO(TempPath verity_dir, TempPath::CreateDir());\n+ RETURN_ERROR_IF_SYSCALL_FAIL(\n+ mount(\"\", verity_dir.path().c_str(), \"verity\", 0, mount_opts.c_str()));\n+\n+ // Enable both the file and the directory.\n+ ASSIGN_OR_RETURN_ERRNO(\n+ auto fd, Open(JoinPath(verity_dir.path(), filename), O_RDONLY, 0777));\n+ RETURN_ERROR_IF_SYSCALL_FAIL(ioctl(fd.get(), FS_IOC_ENABLE_VERITY));\n+ ASSIGN_OR_RETURN_ERRNO(auto dir_fd, Open(verity_dir.path(), O_RDONLY, 0777));\n+ RETURN_ERROR_IF_SYSCALL_FAIL(ioctl(dir_fd.get(), FS_IOC_ENABLE_VERITY));\n+\n+ // Measure the root hash.\n+ uint8_t digest_array[sizeof(struct fsverity_digest) + kMaxDigestSize] = {0};\n+ struct fsverity_digest* digest =\n+ reinterpret_cast<struct fsverity_digest*>(digest_array);\n+ digest->digest_size = kMaxDigestSize;\n+ RETURN_ERROR_IF_SYSCALL_FAIL(\n+ ioctl(dir_fd.get(), FS_IOC_MEASURE_VERITY, digest));\n+\n+ // Mount a verity fs with specified root hash.\n+ mount_opts +=\n+ \",root_hash=\" + BytesToHexString(digest->digest, digest->digest_size);\n+ ASSIGN_OR_RETURN_ERRNO(TempPath verity_with_hash_dir, TempPath::CreateDir());\n+ RETURN_ERROR_IF_SYSCALL_FAIL(mount(\"\", verity_with_hash_dir.path().c_str(),\n+ \"verity\", 0, mount_opts.c_str()));\n+ // Verity directories should not be deleted. Release the TempPath objects to\n+ // prevent those directories from being deleted by the destructor.\n+ verity_dir.release();\n+ return verity_with_hash_dir.release();\n+}\n+\n+} // namespace testing\n+} // namespace gvisor\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test/util/verity_util.h", "diff": "+// Copyright 2021 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+#ifndef GVISOR_TEST_UTIL_VERITY_UTIL_H_\n+#define GVISOR_TEST_UTIL_VERITY_UTIL_H_\n+\n+#include <stdint.h>\n+\n+#include \"test/util/posix_error.h\"\n+\n+namespace gvisor {\n+namespace testing {\n+\n+#ifndef FS_IOC_ENABLE_VERITY\n+#define FS_IOC_ENABLE_VERITY 1082156677\n+#endif\n+\n+#ifndef FS_IOC_MEASURE_VERITY\n+#define FS_IOC_MEASURE_VERITY 3221513862\n+#endif\n+\n+#ifndef FS_VERITY_FL\n+#define FS_VERITY_FL 1048576\n+#endif\n+\n+#ifndef FS_IOC_GETFLAGS\n+#define FS_IOC_GETFLAGS 2148034049\n+#endif\n+\n+struct fsverity_digest {\n+ unsigned short digest_algorithm;\n+ unsigned short digest_size; /* input/output */\n+ unsigned char digest[];\n+};\n+\n+constexpr int kMaxDigestSize = 64;\n+constexpr int kDefaultDigestSize = 32;\n+constexpr char kContents[] = \"foobarbaz\";\n+constexpr char kMerklePrefix[] = \".merkle.verity.\";\n+constexpr char kMerkleRootPrefix[] = \".merkleroot.verity.\";\n+\n+// Get the Merkle tree file path for |path|.\n+std::string MerklePath(absl::string_view path);\n+\n+// Get the root Merkle tree file path for |path|.\n+std::string MerkleRootPath(absl::string_view path);\n+\n+// Provide a function to convert bytes to hex string, since\n+// absl::BytesToHexString does not seem to be compatible with golang\n+// hex.DecodeString used in verity due to zero-padding.\n+std::string BytesToHexString(uint8_t bytes[], int size);\n+\n+// Flip a random bit in the file represented by fd.\n+PosixError FlipRandomBit(int fd, int size);\n+\n+// Mount a verity on the tmpfs and enable both the file and the direcotry. Then\n+// mount a new verity with measured root hash.\n+PosixErrorOr<std::string> MountVerity(std::string tmpfs_dir,\n+ std::string filename);\n+\n+} // namespace testing\n+} // namespace gvisor\n+\n+#endif // GVISOR_TEST_UTIL_VERITY_UTIL_H_\n" } ]
Go
Apache License 2.0
google/gvisor
Add verity_mmap tests PiperOrigin-RevId: 373854462
259,860
14.05.2021 14:02:04
25,200
894187b2c6edbe367135670fb53f2e3f3d24535d
Resolve remaining O_PATH TODOs. O_PATH is now implemented in vfs2. Fixes
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/gofer/filesystem.go", "new_path": "pkg/sentry/fsimpl/gofer/filesystem.go", "diff": "@@ -961,7 +961,7 @@ func (d *dentry) open(ctx context.Context, rp *vfs.ResolvingPath, opts *vfs.Open\n}\nreturn &fd.vfsfd, nil\ncase linux.S_IFLNK:\n- // Can't open symlinks without O_PATH (which is unimplemented).\n+ // Can't open symlinks without O_PATH, which is handled at the VFS layer.\nreturn nil, syserror.ELOOP\ncase linux.S_IFSOCK:\nif d.isSynthetic() {\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/tmpfs/filesystem.go", "new_path": "pkg/sentry/fsimpl/tmpfs/filesystem.go", "diff": "@@ -465,7 +465,7 @@ func (d *dentry) open(ctx context.Context, rp *vfs.ResolvingPath, opts *vfs.Open\n}\nreturn &fd.vfsfd, nil\ncase *symlink:\n- // TODO(gvisor.dev/issue/2782): Can't open symlinks without O_PATH.\n+ // Can't open symlinks without O_PATH, which is handled at the VFS layer.\nreturn nil, syserror.ELOOP\ncase *namedPipe:\nreturn impl.pipe.Open(ctx, rp.Mount(), &d.vfsd, opts.Flags, &d.inode.locks)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/verity/verity.go", "new_path": "pkg/sentry/fsimpl/verity/verity.go", "diff": "@@ -1299,6 +1299,11 @@ func (fd *fileDescription) ConfigureMMap(ctx context.Context, opts *memmap.MMapO\nreturn vfs.GenericConfigureMMap(&fd.vfsfd, fd, opts)\n}\n+// SupportsLocks implements vfs.FileDescriptionImpl.SupportsLocks.\n+func (fd *fileDescription) SupportsLocks() bool {\n+ return fd.lowerFD.SupportsLocks()\n+}\n+\n// LockBSD implements vfs.FileDescriptionImpl.LockBSD.\nfunc (fd *fileDescription) LockBSD(ctx context.Context, uid fslock.UniqueID, ownerPID int32, t fslock.LockType, block fslock.Blocker) error {\nreturn fd.lowerFD.LockBSD(ctx, ownerPID, t, block)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/fd_table.go", "new_path": "pkg/sentry/kernel/fd_table.go", "diff": "@@ -154,10 +154,12 @@ func (f *FDTable) drop(ctx context.Context, file *fs.File) {\n// dropVFS2 drops the table reference.\nfunc (f *FDTable) dropVFS2(ctx context.Context, file *vfs.FileDescription) {\n// Release any POSIX lock possibly held by the FDTable.\n+ if file.SupportsLocks() {\nerr := file.UnlockPOSIX(ctx, f, lock.LockRange{0, lock.LockEOF})\nif err != nil && err != syserror.ENOLCK {\npanic(fmt.Sprintf(\"UnlockPOSIX failed: %v\", err))\n}\n+ }\n// Drop the table's reference.\nfile.DecRef(ctx)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/file_description.go", "new_path": "pkg/sentry/vfs/file_description.go", "diff": "@@ -454,6 +454,9 @@ type FileDescriptionImpl interface {\n// RemoveXattr removes the given extended attribute from the file.\nRemoveXattr(ctx context.Context, name string) error\n+ // SupportsLocks indicates whether file locks are supported.\n+ SupportsLocks() bool\n+\n// LockBSD tries to acquire a BSD-style advisory file lock.\nLockBSD(ctx context.Context, uid lock.UniqueID, ownerPID int32, t lock.LockType, block lock.Blocker) error\n@@ -818,6 +821,11 @@ func (fd *FileDescription) Msync(ctx context.Context, mr memmap.MappableRange) e\nreturn fd.Sync(ctx)\n}\n+// SupportsLocks indicates whether file locks are supported.\n+func (fd *FileDescription) SupportsLocks() bool {\n+ return fd.impl.SupportsLocks()\n+}\n+\n// LockBSD tries to acquire a BSD-style advisory file lock.\nfunc (fd *FileDescription) LockBSD(ctx context.Context, ownerPID int32, lockType lock.LockType, blocker lock.Blocker) error {\natomic.StoreUint32(&fd.usedLockBSD, 1)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/file_description_impl_util.go", "new_path": "pkg/sentry/vfs/file_description_impl_util.go", "diff": "@@ -413,6 +413,11 @@ type LockFD struct {\nlocks *FileLocks\n}\n+// SupportsLocks implements FileDescriptionImpl.SupportsLocks.\n+func (LockFD) SupportsLocks() bool {\n+ return true\n+}\n+\n// Init initializes fd with FileLocks to use.\nfunc (fd *LockFD) Init(locks *FileLocks) {\nfd.locks = locks\n@@ -423,28 +428,28 @@ func (fd *LockFD) Locks() *FileLocks {\nreturn fd.locks\n}\n-// LockBSD implements vfs.FileDescriptionImpl.LockBSD.\n+// LockBSD implements FileDescriptionImpl.LockBSD.\nfunc (fd *LockFD) LockBSD(ctx context.Context, uid fslock.UniqueID, ownerPID int32, t fslock.LockType, block fslock.Blocker) error {\nreturn fd.locks.LockBSD(ctx, uid, ownerPID, t, block)\n}\n-// UnlockBSD implements vfs.FileDescriptionImpl.UnlockBSD.\n+// UnlockBSD implements FileDescriptionImpl.UnlockBSD.\nfunc (fd *LockFD) UnlockBSD(ctx context.Context, uid fslock.UniqueID) error {\nfd.locks.UnlockBSD(uid)\nreturn nil\n}\n-// LockPOSIX implements vfs.FileDescriptionImpl.LockPOSIX.\n+// LockPOSIX implements FileDescriptionImpl.LockPOSIX.\nfunc (fd *LockFD) LockPOSIX(ctx context.Context, uid fslock.UniqueID, ownerPID int32, t fslock.LockType, r fslock.LockRange, block fslock.Blocker) error {\nreturn fd.locks.LockPOSIX(ctx, uid, ownerPID, t, r, block)\n}\n-// UnlockPOSIX implements vfs.FileDescriptionImpl.UnlockPOSIX.\n+// UnlockPOSIX implements FileDescriptionImpl.UnlockPOSIX.\nfunc (fd *LockFD) UnlockPOSIX(ctx context.Context, uid fslock.UniqueID, r fslock.LockRange) error {\nreturn fd.locks.UnlockPOSIX(ctx, uid, r)\n}\n-// TestPOSIX implements vfs.FileDescriptionImpl.TestPOSIX.\n+// TestPOSIX implements FileDescriptionImpl.TestPOSIX.\nfunc (fd *LockFD) TestPOSIX(ctx context.Context, uid fslock.UniqueID, t fslock.LockType, r fslock.LockRange) (linux.Flock, error) {\nreturn fd.locks.TestPOSIX(ctx, uid, t, r)\n}\n@@ -455,27 +460,68 @@ func (fd *LockFD) TestPOSIX(ctx context.Context, uid fslock.UniqueID, t fslock.L\n// +stateify savable\ntype NoLockFD struct{}\n-// LockBSD implements vfs.FileDescriptionImpl.LockBSD.\n+// SupportsLocks implements FileDescriptionImpl.SupportsLocks.\n+func (NoLockFD) SupportsLocks() bool {\n+ return false\n+}\n+\n+// LockBSD implements FileDescriptionImpl.LockBSD.\nfunc (NoLockFD) LockBSD(ctx context.Context, uid fslock.UniqueID, ownerPID int32, t fslock.LockType, block fslock.Blocker) error {\nreturn syserror.ENOLCK\n}\n-// UnlockBSD implements vfs.FileDescriptionImpl.UnlockBSD.\n+// UnlockBSD implements FileDescriptionImpl.UnlockBSD.\nfunc (NoLockFD) UnlockBSD(ctx context.Context, uid fslock.UniqueID) error {\nreturn syserror.ENOLCK\n}\n-// LockPOSIX implements vfs.FileDescriptionImpl.LockPOSIX.\n+// LockPOSIX implements FileDescriptionImpl.LockPOSIX.\nfunc (NoLockFD) LockPOSIX(ctx context.Context, uid fslock.UniqueID, ownerPID int32, t fslock.LockType, r fslock.LockRange, block fslock.Blocker) error {\nreturn syserror.ENOLCK\n}\n-// UnlockPOSIX implements vfs.FileDescriptionImpl.UnlockPOSIX.\n+// UnlockPOSIX implements FileDescriptionImpl.UnlockPOSIX.\nfunc (NoLockFD) UnlockPOSIX(ctx context.Context, uid fslock.UniqueID, r fslock.LockRange) error {\nreturn syserror.ENOLCK\n}\n-// TestPOSIX implements vfs.FileDescriptionImpl.TestPOSIX.\n+// TestPOSIX implements FileDescriptionImpl.TestPOSIX.\nfunc (NoLockFD) TestPOSIX(ctx context.Context, uid fslock.UniqueID, t fslock.LockType, r fslock.LockRange) (linux.Flock, error) {\nreturn linux.Flock{}, syserror.ENOLCK\n}\n+\n+// BadLockFD implements Lock*/Unlock* portion of FileDescriptionImpl interface\n+// returning EBADF.\n+//\n+// +stateify savable\n+type BadLockFD struct{}\n+\n+// SupportsLocks implements FileDescriptionImpl.SupportsLocks.\n+func (BadLockFD) SupportsLocks() bool {\n+ return false\n+}\n+\n+// LockBSD implements FileDescriptionImpl.LockBSD.\n+func (BadLockFD) LockBSD(ctx context.Context, uid fslock.UniqueID, ownerPID int32, t fslock.LockType, block fslock.Blocker) error {\n+ return syserror.EBADF\n+}\n+\n+// UnlockBSD implements FileDescriptionImpl.UnlockBSD.\n+func (BadLockFD) UnlockBSD(ctx context.Context, uid fslock.UniqueID) error {\n+ return syserror.EBADF\n+}\n+\n+// LockPOSIX implements FileDescriptionImpl.LockPOSIX.\n+func (BadLockFD) LockPOSIX(ctx context.Context, uid fslock.UniqueID, ownerPID int32, t fslock.LockType, r fslock.LockRange, block fslock.Blocker) error {\n+ return syserror.EBADF\n+}\n+\n+// UnlockPOSIX implements FileDescriptionImpl.UnlockPOSIX.\n+func (BadLockFD) UnlockPOSIX(ctx context.Context, uid fslock.UniqueID, r fslock.LockRange) error {\n+ return syserror.EBADF\n+}\n+\n+// TestPOSIX implements FileDescriptionImpl.TestPOSIX.\n+func (BadLockFD) TestPOSIX(ctx context.Context, uid fslock.UniqueID, t fslock.LockType, r fslock.LockRange) (linux.Flock, error) {\n+ return linux.Flock{}, syserror.EBADF\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/opath.go", "new_path": "pkg/sentry/vfs/opath.go", "diff": "@@ -24,96 +24,96 @@ import (\n\"gvisor.dev/gvisor/pkg/usermem\"\n)\n-// opathFD implements vfs.FileDescriptionImpl for a file description opened with O_PATH.\n+// opathFD implements FileDescriptionImpl for a file description opened with O_PATH.\n//\n// +stateify savable\ntype opathFD struct {\nvfsfd FileDescription\nFileDescriptionDefaultImpl\n- NoLockFD\n+ BadLockFD\n}\n-// Release implements vfs.FileDescriptionImpl.Release.\n+// Release implements FileDescriptionImpl.Release.\nfunc (fd *opathFD) Release(context.Context) {\n// noop\n}\n-// Allocate implements vfs.FileDescriptionImpl.Allocate.\n+// Allocate implements FileDescriptionImpl.Allocate.\nfunc (fd *opathFD) Allocate(ctx context.Context, mode, offset, length uint64) error {\nreturn syserror.EBADF\n}\n-// PRead implements vfs.FileDescriptionImpl.PRead.\n+// PRead implements FileDescriptionImpl.PRead.\nfunc (fd *opathFD) PRead(ctx context.Context, dst usermem.IOSequence, offset int64, opts ReadOptions) (int64, error) {\nreturn 0, syserror.EBADF\n}\n-// Read implements vfs.FileDescriptionImpl.Read.\n+// Read implements FileDescriptionImpl.Read.\nfunc (fd *opathFD) Read(ctx context.Context, dst usermem.IOSequence, opts ReadOptions) (int64, error) {\nreturn 0, syserror.EBADF\n}\n-// PWrite implements vfs.FileDescriptionImpl.PWrite.\n+// PWrite implements FileDescriptionImpl.PWrite.\nfunc (fd *opathFD) PWrite(ctx context.Context, src usermem.IOSequence, offset int64, opts WriteOptions) (int64, error) {\nreturn 0, syserror.EBADF\n}\n-// Write implements vfs.FileDescriptionImpl.Write.\n+// Write implements FileDescriptionImpl.Write.\nfunc (fd *opathFD) Write(ctx context.Context, src usermem.IOSequence, opts WriteOptions) (int64, error) {\nreturn 0, syserror.EBADF\n}\n-// Ioctl implements vfs.FileDescriptionImpl.Ioctl.\n+// Ioctl implements FileDescriptionImpl.Ioctl.\nfunc (fd *opathFD) Ioctl(ctx context.Context, uio usermem.IO, args arch.SyscallArguments) (uintptr, error) {\nreturn 0, syserror.EBADF\n}\n-// IterDirents implements vfs.FileDescriptionImpl.IterDirents.\n+// IterDirents implements FileDescriptionImpl.IterDirents.\nfunc (fd *opathFD) IterDirents(ctx context.Context, cb IterDirentsCallback) error {\nreturn syserror.EBADF\n}\n-// Seek implements vfs.FileDescriptionImpl.Seek.\n+// Seek implements FileDescriptionImpl.Seek.\nfunc (fd *opathFD) Seek(ctx context.Context, offset int64, whence int32) (int64, error) {\nreturn 0, syserror.EBADF\n}\n-// ConfigureMMap implements vfs.FileDescriptionImpl.ConfigureMMap.\n+// ConfigureMMap implements FileDescriptionImpl.ConfigureMMap.\nfunc (fd *opathFD) ConfigureMMap(ctx context.Context, opts *memmap.MMapOpts) error {\nreturn syserror.EBADF\n}\n-// ListXattr implements vfs.FileDescriptionImpl.ListXattr.\n+// ListXattr implements FileDescriptionImpl.ListXattr.\nfunc (fd *opathFD) ListXattr(ctx context.Context, size uint64) ([]string, error) {\nreturn nil, syserror.EBADF\n}\n-// GetXattr implements vfs.FileDescriptionImpl.GetXattr.\n+// GetXattr implements FileDescriptionImpl.GetXattr.\nfunc (fd *opathFD) GetXattr(ctx context.Context, opts GetXattrOptions) (string, error) {\nreturn \"\", syserror.EBADF\n}\n-// SetXattr implements vfs.FileDescriptionImpl.SetXattr.\n+// SetXattr implements FileDescriptionImpl.SetXattr.\nfunc (fd *opathFD) SetXattr(ctx context.Context, opts SetXattrOptions) error {\nreturn syserror.EBADF\n}\n-// RemoveXattr implements vfs.FileDescriptionImpl.RemoveXattr.\n+// RemoveXattr implements FileDescriptionImpl.RemoveXattr.\nfunc (fd *opathFD) RemoveXattr(ctx context.Context, name string) error {\nreturn syserror.EBADF\n}\n-// Sync implements vfs.FileDescriptionImpl.Sync.\n+// Sync implements FileDescriptionImpl.Sync.\nfunc (fd *opathFD) Sync(ctx context.Context) error {\nreturn syserror.EBADF\n}\n-// SetStat implements vfs.FileDescriptionImpl.SetStat.\n+// SetStat implements FileDescriptionImpl.SetStat.\nfunc (fd *opathFD) SetStat(ctx context.Context, opts SetStatOptions) error {\nreturn syserror.EBADF\n}\n-// Stat implements vfs.FileDescriptionImpl.Stat.\n+// Stat implements FileDescriptionImpl.Stat.\nfunc (fd *opathFD) Stat(ctx context.Context, opts StatOptions) (linux.Statx, error) {\nvfsObj := fd.vfsfd.vd.mount.vfs\nrp := vfsObj.getResolvingPath(auth.CredentialsFromContext(ctx), &PathOperation{\n" }, { "change_type": "MODIFY", "old_path": "runsc/boot/vfs.go", "new_path": "runsc/boot/vfs.go", "diff": "@@ -657,7 +657,6 @@ func (c *containerMounter) mountTmpVFS2(ctx context.Context, conf *config.Config\nStart: root,\nPath: fspath.Parse(\"/tmp\"),\n}\n- // TODO(gvisor.dev/issue/2782): Use O_PATH when available.\nfd, err := c.k.VFS().OpenAt(ctx, creds, &pop, &vfs.OpenOptions{Flags: linux.O_RDONLY | linux.O_DIRECTORY})\nswitch err {\ncase nil:\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/fcntl.cc", "new_path": "test/syscalls/linux/fcntl.cc", "diff": "@@ -390,9 +390,7 @@ TEST_F(FcntlLockTest, SetLockDir) {\n}\nTEST_F(FcntlLockTest, SetLockSymlink) {\n- // TODO(gvisor.dev/issue/2782): Replace with IsRunningWithVFS1() when O_PATH\n- // is supported.\n- SKIP_IF(IsRunningOnGvisor());\n+ SKIP_IF(IsRunningWithVFS1());\nauto file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());\nauto symlink = ASSERT_NO_ERRNO_AND_VALUE(\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/flock.cc", "new_path": "test/syscalls/linux/flock.cc", "diff": "@@ -662,9 +662,7 @@ TEST(FlockTestNoFixture, FlockDir) {\n}\nTEST(FlockTestNoFixture, FlockSymlink) {\n- // TODO(gvisor.dev/issue/2782): Replace with IsRunningWithVFS1() when O_PATH\n- // is supported.\n- SKIP_IF(IsRunningOnGvisor());\n+ SKIP_IF(IsRunningWithVFS1());\nauto file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());\nauto symlink = ASSERT_NO_ERRNO_AND_VALUE(\n" } ]
Go
Apache License 2.0
google/gvisor
Resolve remaining O_PATH TODOs. O_PATH is now implemented in vfs2. Fixes #2782. PiperOrigin-RevId: 373861410
259,853
14.05.2021 15:13:23
25,200
f8d79e94e6fbb44af264394fd96a7c7cca62f98b
Add hash15 label for tests.
[ { "change_type": "MODIFY", "old_path": "test/runner/defs.bzl", "new_path": "test/runner/defs.bzl", "diff": "@@ -88,6 +88,12 @@ def _syscall_test(\ntags = list(tags)\ntags += [full_platform, \"file_\" + file_access]\n+ # Hash this target into one of 15 buckets. This can be used to\n+ # randomly split targets between different workflows.\n+ hash15 = hash(native.package_name() + name) % 15\n+ tags.append(\"hash15:\" + str(hash15))\n+ tags.append(\"hash15\")\n+\n# Disable off-host networking.\ntags.append(\"requires-net:loopback\")\ntags.append(\"requires-net:ipv4\")\n" } ]
Go
Apache License 2.0
google/gvisor
Add hash15 label for tests. PiperOrigin-RevId: 373875071
259,896
14.05.2021 16:10:02
25,200
25f0ab3313c356fcfb9e4282eda3b2aa2278956d
Add new metric for suspicious operations. The new metric contains fields and will replace the below existing metric: opened_write_execute_file
[ { "change_type": "MODIFY", "old_path": "pkg/metric/metric.go", "new_path": "pkg/metric/metric.go", "diff": "@@ -36,10 +36,17 @@ var (\n// new metric after initialization.\nErrInitializationDone = errors.New(\"metric cannot be created after initialization is complete\")\n+ // createdSentryMetrics indicates that the sentry metrics are created.\n+ createdSentryMetrics = false\n+\n// WeirdnessMetric is a metric with fields created to track the number\n// of weird occurrences such as time fallback, partial_result and\n// vsyscall count.\nWeirdnessMetric *Uint64Metric\n+\n+ // SuspiciousOperationsMetric is a metric with fields created to detect\n+ // operations such as opening an executable file to write from a gofer.\n+ SuspiciousOperationsMetric *Uint64Metric\n)\n// Uint64Metric encapsulates a uint64 that represents some kind of metric to be\n@@ -388,13 +395,21 @@ func EmitMetricUpdate() {\n// CreateSentryMetrics creates the sentry metrics during kernel initialization.\nfunc CreateSentryMetrics() {\n- if WeirdnessMetric != nil {\n+ if createdSentryMetrics {\nreturn\n}\n- WeirdnessMetric = MustCreateNewUint64Metric(\"/weirdness\", true /* sync */, \"Increment for weird occurrences of problems such as time fallback, partial result and vsyscalls invoked in the sandbox\",\n+ createdSentryMetrics = true\n+\n+ WeirdnessMetric = MustCreateNewUint64Metric(\"/weirdness\", true /* sync */, \"Increment for weird occurrences of problems such as time fallback, partial result and vsyscalls invoked in the sandbox.\",\nField{\nname: \"weirdness_type\",\nallowedValues: []string{\"time_fallback\", \"partial_result\", \"vsyscall_count\"},\n})\n+\n+ SuspiciousOperationsMetric = MustCreateNewUint64Metric(\"/suspicious_operations\", true /* sync */, \"Increment for suspicious operations such as opening an executable file to write from a gofer.\",\n+ Field{\n+ name: \"operation_type\",\n+ allowedValues: []string{\"opened_write_execute_file\"},\n+ })\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/gofer/BUILD", "new_path": "pkg/sentry/fs/gofer/BUILD", "diff": "@@ -29,6 +29,7 @@ go_library(\n\"//pkg/fd\",\n\"//pkg/hostarch\",\n\"//pkg/log\",\n+ \"//pkg/metric\",\n\"//pkg/p9\",\n\"//pkg/refs\",\n\"//pkg/safemem\",\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/gofer/file.go", "new_path": "pkg/sentry/fs/gofer/file.go", "diff": "@@ -21,6 +21,7 @@ import (\n\"golang.org/x/sys/unix\"\n\"gvisor.dev/gvisor/pkg/context\"\n\"gvisor.dev/gvisor/pkg/log\"\n+ \"gvisor.dev/gvisor/pkg/metric\"\n\"gvisor.dev/gvisor/pkg/p9\"\n\"gvisor.dev/gvisor/pkg/sentry/device\"\n\"gvisor.dev/gvisor/pkg/sentry/fs\"\n@@ -92,6 +93,7 @@ func NewFile(ctx context.Context, dirent *fs.Dirent, name string, flags fs.FileF\nif flags.Write {\nif err := dirent.Inode.CheckPermission(ctx, fs.PermMask{Execute: true}); err == nil {\nfsmetric.GoferOpensWX.Increment()\n+ metric.SuspiciousOperationsMetric.Increment(\"opened_write_execute_file\")\nlog.Warningf(\"Opened a writable executable: %q\", name)\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/gofer/BUILD", "new_path": "pkg/sentry/fsimpl/gofer/BUILD", "diff": "@@ -54,6 +54,7 @@ go_library(\n\"//pkg/fspath\",\n\"//pkg/hostarch\",\n\"//pkg/log\",\n+ \"//pkg/metric\",\n\"//pkg/p9\",\n\"//pkg/refs\",\n\"//pkg/refsvfs2\",\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/gofer/regular_file.go", "new_path": "pkg/sentry/fsimpl/gofer/regular_file.go", "diff": "@@ -24,6 +24,7 @@ import (\n\"gvisor.dev/gvisor/pkg/context\"\n\"gvisor.dev/gvisor/pkg/hostarch\"\n\"gvisor.dev/gvisor/pkg/log\"\n+ \"gvisor.dev/gvisor/pkg/metric\"\n\"gvisor.dev/gvisor/pkg/p9\"\n\"gvisor.dev/gvisor/pkg/safemem\"\n\"gvisor.dev/gvisor/pkg/sentry/fs/fsutil\"\n@@ -60,6 +61,7 @@ func newRegularFileFD(mnt *vfs.Mount, d *dentry, flags uint32) (*regularFileFD,\n}\nif fd.vfsfd.IsWritable() && (atomic.LoadUint32(&d.mode)&0111 != 0) {\nfsmetric.GoferOpensWX.Increment()\n+ metric.SuspiciousOperationsMetric.Increment(\"opened_write_execute_file\")\n}\nif atomic.LoadInt32(&d.mmapFD) >= 0 {\nfsmetric.GoferOpensHost.Increment()\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/gofer/special_file.go", "new_path": "pkg/sentry/fsimpl/gofer/special_file.go", "diff": "@@ -21,6 +21,7 @@ import (\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/context\"\n\"gvisor.dev/gvisor/pkg/fdnotifier\"\n+ \"gvisor.dev/gvisor/pkg/metric\"\n\"gvisor.dev/gvisor/pkg/p9\"\n\"gvisor.dev/gvisor/pkg/safemem\"\n\"gvisor.dev/gvisor/pkg/sentry/fsmetric\"\n@@ -101,6 +102,7 @@ func newSpecialFileFD(h handle, mnt *vfs.Mount, d *dentry, flags uint32) (*speci\nd.fs.syncMu.Unlock()\nif fd.vfsfd.IsWritable() && (atomic.LoadUint32(&d.mode)&0111 != 0) {\nfsmetric.GoferOpensWX.Increment()\n+ metric.SuspiciousOperationsMetric.Increment(\"opened_write_execute_file\")\n}\nif h.fd >= 0 {\nfsmetric.GoferOpensHost.Increment()\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/watchdog/watchdog.go", "new_path": "pkg/sentry/watchdog/watchdog.go", "diff": "@@ -312,7 +312,7 @@ func (w *Watchdog) runTurn() {\n// New stuck task detected.\n//\n// Note that tasks blocked doing IO may be considered stuck in kernel,\n- // unless they are surrounded b\n+ // unless they are surrounded by\n// Task.UninterruptibleSleepStart/Finish.\ntc = &offender{lastUpdateTime: lastUpdateTime}\nstuckTasks.Increment()\n" } ]
Go
Apache License 2.0
google/gvisor
Add new metric for suspicious operations. The new metric contains fields and will replace the below existing metric: - opened_write_execute_file PiperOrigin-RevId: 373884604
259,896
14.05.2021 17:20:13
25,200
8e8b752524e1c1558a0858a121bb56ac1b78456c
Add stuck tasks and startup stuck tasks to weirdness metric Weirdness metric will replace the below two metrics: watchdog/stuck_startup_detected watchdog/stuck_tasks_detected
[ { "change_type": "MODIFY", "old_path": "pkg/metric/metric.go", "new_path": "pkg/metric/metric.go", "diff": "@@ -40,8 +40,8 @@ var (\ncreatedSentryMetrics = false\n// WeirdnessMetric is a metric with fields created to track the number\n- // of weird occurrences such as time fallback, partial_result and\n- // vsyscall count.\n+ // of weird occurrences such as time fallback, partial_result, vsyscall\n+ // count, watchdog startup timeouts and stuck tasks.\nWeirdnessMetric *Uint64Metric\n// SuspiciousOperationsMetric is a metric with fields created to detect\n@@ -401,10 +401,10 @@ func CreateSentryMetrics() {\ncreatedSentryMetrics = true\n- WeirdnessMetric = MustCreateNewUint64Metric(\"/weirdness\", true /* sync */, \"Increment for weird occurrences of problems such as time fallback, partial result and vsyscalls invoked in the sandbox.\",\n+ WeirdnessMetric = MustCreateNewUint64Metric(\"/weirdness\", true /* sync */, \"Increment for weird occurrences of problems such as time fallback, partial result, vsyscalls invoked in the sandbox, watchdog startup timeouts and stuck tasks.\",\nField{\nname: \"weirdness_type\",\n- allowedValues: []string{\"time_fallback\", \"partial_result\", \"vsyscall_count\"},\n+ allowedValues: []string{\"time_fallback\", \"partial_result\", \"vsyscall_count\", \"watchdog_stuck_startup\", \"watchdog_stuck_tasks\"},\n})\nSuspiciousOperationsMetric = MustCreateNewUint64Metric(\"/suspicious_operations\", true /* sync */, \"Increment for suspicious operations such as opening an executable file to write from a gofer.\",\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/watchdog/watchdog.go", "new_path": "pkg/sentry/watchdog/watchdog.go", "diff": "@@ -243,6 +243,7 @@ func (w *Watchdog) waitForStart() {\n}\nstuckStartup.Increment()\n+ metric.WeirdnessMetric.Increment(\"watchdog_stuck_startup\")\nvar buf bytes.Buffer\nbuf.WriteString(fmt.Sprintf(\"Watchdog.Start() not called within %s\", w.StartupTimeout))\n@@ -316,6 +317,7 @@ func (w *Watchdog) runTurn() {\n// Task.UninterruptibleSleepStart/Finish.\ntc = &offender{lastUpdateTime: lastUpdateTime}\nstuckTasks.Increment()\n+ metric.WeirdnessMetric.Increment(\"watchdog_stuck_tasks\")\nnewTaskFound = true\n}\nnewOffenders[t] = tc\n" } ]
Go
Apache License 2.0
google/gvisor
Add stuck tasks and startup stuck tasks to weirdness metric Weirdness metric will replace the below two metrics: - watchdog/stuck_startup_detected - watchdog/stuck_tasks_detected PiperOrigin-RevId: 373895696
259,977
17.05.2021 10:28:34
25,200
7654181cc7c4f7633a1e96280bfd32391a3fbce3
Rename variables in IP forwarding tests Previously, we named domain objects using numbers (e.g. "e1", "e2" etc). This change renames objects to clarify whether they are part of the incoming or outgoing path.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv4/ipv4_test.go", "new_path": "pkg/tcpip/network/ipv4/ipv4_test.go", "diff": "@@ -118,27 +118,27 @@ type forwardedPacket struct {\nfunc TestForwarding(t *testing.T) {\nconst (\n- nicID1 = 1\n- nicID2 = 2\n+ incomingNICID = 1\n+ outgoingNICID = 2\nrandomSequence = 123\nrandomIdent = 42\nrandomTimeOffset = 0x10203040\n)\n- ipv4Addr1 := tcpip.AddressWithPrefix{\n+ incomingIPv4Addr := tcpip.AddressWithPrefix{\nAddress: tcpip.Address(net.ParseIP(\"10.0.0.1\").To4()),\nPrefixLen: 8,\n}\n- ipv4Addr2 := tcpip.AddressWithPrefix{\n+ outgoingIPv4Addr := tcpip.AddressWithPrefix{\nAddress: tcpip.Address(net.ParseIP(\"11.0.0.1\").To4()),\nPrefixLen: 8,\n}\n- linkAddr2 := tcpip.LinkAddress(\"\\x02\\x03\\x03\\x04\\x05\\x06\")\n- remoteIPv4Addr1 := tcpip.Address(net.ParseIP(\"10.0.0.2\").To4())\n- remoteIPv4Addr2 := tcpip.Address(net.ParseIP(\"11.0.0.2\").To4())\n- unreachableIPv4Addr := tcpip.Address(net.ParseIP(\"12.0.0.2\").To4())\n- multicastIPv4Addr := tcpip.Address(net.ParseIP(\"225.0.0.0\").To4())\n- linkLocalIPv4Addr := tcpip.Address(net.ParseIP(\"169.254.0.0\").To4())\n+ outgoingLinkAddr := tcpip.LinkAddress(\"\\x02\\x03\\x03\\x04\\x05\\x06\")\n+ remoteIPv4Addr1 := tcptestutil.MustParse4(\"10.0.0.2\")\n+ remoteIPv4Addr2 := tcptestutil.MustParse4(\"11.0.0.2\")\n+ unreachableIPv4Addr := tcptestutil.MustParse4(\"12.0.0.2\")\n+ multicastIPv4Addr := tcptestutil.MustParse4(\"225.0.0.0\")\n+ linkLocalIPv4Addr := tcptestutil.MustParse4(\"169.254.0.0\")\ntests := []struct {\nname string\n@@ -345,6 +345,7 @@ func TestForwarding(t *testing.T) {\nfor _, test := range tests {\nt.Run(test.name, func(t *testing.T) {\nclock := faketime.NewManualClock()\n+\ns := stack.New(stack.Options{\nNetworkProtocols: []stack.NetworkProtocolFactory{ipv4.NewProtocol},\nTransportProtocols: []stack.TransportProtocolFactory{icmp.NewProtocol4},\n@@ -356,36 +357,36 @@ func TestForwarding(t *testing.T) {\nclock.Advance(time.Millisecond * randomTimeOffset)\n// We expect at most a single packet in response to our ICMP Echo Request.\n- e1 := channel.New(1, test.mtu, \"\")\n- if err := s.CreateNIC(nicID1, e1); err != nil {\n- t.Fatalf(\"CreateNIC(%d, _): %s\", nicID1, err)\n+ incomingEndpoint := channel.New(1, test.mtu, \"\")\n+ if err := s.CreateNIC(incomingNICID, incomingEndpoint); err != nil {\n+ t.Fatalf(\"CreateNIC(%d, _): %s\", incomingNICID, err)\n}\n- ipv4ProtoAddr1 := tcpip.ProtocolAddress{Protocol: header.IPv4ProtocolNumber, AddressWithPrefix: ipv4Addr1}\n- if err := s.AddProtocolAddress(nicID1, ipv4ProtoAddr1); err != nil {\n- t.Fatalf(\"AddProtocolAddress(%d, %#v): %s\", nicID1, ipv4ProtoAddr1, err)\n+ incomingIPv4ProtoAddr := tcpip.ProtocolAddress{Protocol: header.IPv4ProtocolNumber, AddressWithPrefix: incomingIPv4Addr}\n+ if err := s.AddProtocolAddress(incomingNICID, incomingIPv4ProtoAddr); err != nil {\n+ t.Fatalf(\"AddProtocolAddress(%d, %#v): %s\", incomingNICID, incomingIPv4ProtoAddr, err)\n}\nexpectedEmittedPacketCount := 1\nif len(test.expectedFragmentsForwarded) > expectedEmittedPacketCount {\nexpectedEmittedPacketCount = len(test.expectedFragmentsForwarded)\n}\n- e2 := channel.New(expectedEmittedPacketCount, test.mtu, linkAddr2)\n- if err := s.CreateNIC(nicID2, e2); err != nil {\n- t.Fatalf(\"CreateNIC(%d, _): %s\", nicID2, err)\n+ outgoingEndpoint := channel.New(expectedEmittedPacketCount, test.mtu, outgoingLinkAddr)\n+ if err := s.CreateNIC(outgoingNICID, outgoingEndpoint); err != nil {\n+ t.Fatalf(\"CreateNIC(%d, _): %s\", outgoingNICID, err)\n}\n- ipv4ProtoAddr2 := tcpip.ProtocolAddress{Protocol: header.IPv4ProtocolNumber, AddressWithPrefix: ipv4Addr2}\n- if err := s.AddProtocolAddress(nicID2, ipv4ProtoAddr2); err != nil {\n- t.Fatalf(\"AddProtocolAddress(%d, %#v): %s\", nicID2, ipv4ProtoAddr2, err)\n+ outgoingIPv4ProtoAddr := tcpip.ProtocolAddress{Protocol: header.IPv4ProtocolNumber, AddressWithPrefix: outgoingIPv4Addr}\n+ if err := s.AddProtocolAddress(outgoingNICID, outgoingIPv4ProtoAddr); err != nil {\n+ t.Fatalf(\"AddProtocolAddress(%d, %#v): %s\", outgoingNICID, outgoingIPv4ProtoAddr, err)\n}\ns.SetRouteTable([]tcpip.Route{\n{\n- Destination: ipv4Addr1.Subnet(),\n- NIC: nicID1,\n+ Destination: incomingIPv4Addr.Subnet(),\n+ NIC: incomingNICID,\n},\n{\n- Destination: ipv4Addr2.Subnet(),\n- NIC: nicID2,\n+ Destination: outgoingIPv4Addr.Subnet(),\n+ NIC: outgoingNICID,\n},\n})\n@@ -431,9 +432,10 @@ func TestForwarding(t *testing.T) {\nData: hdr.View().ToVectorisedView(),\n})\nrequestPkt.NetworkProtocolNumber = header.IPv4ProtocolNumber\n- e1.InjectInbound(header.IPv4ProtocolNumber, requestPkt)\n+ incomingEndpoint.InjectInbound(header.IPv4ProtocolNumber, requestPkt)\n+\n+ reply, ok := incomingEndpoint.Read()\n- reply, ok := e1.Read()\nif test.expectErrorICMP {\nif !ok {\nt.Fatalf(\"expected ICMP packet type %d through incoming NIC\", test.icmpType)\n@@ -452,7 +454,7 @@ func TestForwarding(t *testing.T) {\n}\nchecker.IPv4(t, header.IPv4(stack.PayloadSince(reply.Pkt.NetworkHeader())),\n- checker.SrcAddr(ipv4Addr1.Address),\n+ checker.SrcAddr(incomingIPv4Addr.Address),\nchecker.DstAddr(test.sourceAddr),\nchecker.TTL(ipv4.DefaultTTL),\nchecker.ICMPv4(\n@@ -470,7 +472,7 @@ func TestForwarding(t *testing.T) {\nif len(test.expectedFragmentsForwarded) != 0 {\nfragmentedPackets := []*stack.PacketBuffer{}\nfor i := 0; i < len(test.expectedFragmentsForwarded); i++ {\n- reply, ok = e2.Read()\n+ reply, ok = outgoingEndpoint.Read()\nif !ok {\nt.Fatal(\"expected ICMP Echo fragment through outgoing NIC\")\n}\n@@ -489,7 +491,7 @@ func TestForwarding(t *testing.T) {\nt.Error(err)\n}\n} else {\n- reply, ok = e2.Read()\n+ reply, ok = outgoingEndpoint.Read()\nif !ok {\nt.Fatal(\"expected ICMP Echo packet through outgoing NIC\")\n}\n@@ -508,11 +510,10 @@ func TestForwarding(t *testing.T) {\n)\n}\n} else {\n- if reply, ok = e2.Read(); ok {\n+ if reply, ok = outgoingEndpoint.Read(); ok {\nt.Fatalf(\"expected no ICMP Echo packet through outgoing NIC, instead found: %#v\", reply)\n}\n}\n-\nboolToInt := func(val bool) uint64 {\nif val {\nreturn 1\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/ipv6_test.go", "new_path": "pkg/tcpip/network/ipv6/ipv6_test.go", "diff": "@@ -3004,17 +3004,17 @@ func TestFragmentationErrors(t *testing.T) {\nfunc TestForwarding(t *testing.T) {\nconst (\n- nicID1 = 1\n- nicID2 = 2\n+ incomingNICID = 1\n+ outgoingNICID = 2\nrandomSequence = 123\nrandomIdent = 42\n)\n- ipv6Addr1 := tcpip.AddressWithPrefix{\n+ incomingIPv6Addr := tcpip.AddressWithPrefix{\nAddress: tcpip.Address(net.ParseIP(\"10::1\").To16()),\nPrefixLen: 64,\n}\n- ipv6Addr2 := tcpip.AddressWithPrefix{\n+ outgoingIPv6Addr := tcpip.AddressWithPrefix{\nAddress: tcpip.Address(net.ParseIP(\"11::1\").To16()),\nPrefixLen: 64,\n}\n@@ -3022,6 +3022,7 @@ func TestForwarding(t *testing.T) {\nAddress: tcpip.Address(net.ParseIP(\"ff00::\").To16()),\nPrefixLen: 64,\n}\n+\nremoteIPv6Addr1 := tcpip.Address(net.ParseIP(\"10::2\").To16())\nremoteIPv6Addr2 := tcpip.Address(net.ParseIP(\"11::2\").To16())\nunreachableIPv6Addr := tcpip.Address(net.ParseIP(\"12::2\").To16())\n@@ -3296,36 +3297,36 @@ func TestForwarding(t *testing.T) {\nTransportProtocols: []stack.TransportProtocolFactory{icmp.NewProtocol6},\n})\n// We expect at most a single packet in response to our ICMP Echo Request.\n- e1 := channel.New(1, header.IPv6MinimumMTU, \"\")\n- if err := s.CreateNIC(nicID1, e1); err != nil {\n- t.Fatalf(\"CreateNIC(%d, _): %s\", nicID1, err)\n+ incomingEndpoint := channel.New(1, header.IPv6MinimumMTU, \"\")\n+ if err := s.CreateNIC(incomingNICID, incomingEndpoint); err != nil {\n+ t.Fatalf(\"CreateNIC(%d, _): %s\", incomingNICID, err)\n}\n- ipv6ProtoAddr1 := tcpip.ProtocolAddress{Protocol: ProtocolNumber, AddressWithPrefix: ipv6Addr1}\n- if err := s.AddProtocolAddress(nicID1, ipv6ProtoAddr1); err != nil {\n- t.Fatalf(\"AddProtocolAddress(%d, %#v): %s\", nicID1, ipv6ProtoAddr1, err)\n+ incomingIPv6ProtoAddr := tcpip.ProtocolAddress{Protocol: ProtocolNumber, AddressWithPrefix: incomingIPv6Addr}\n+ if err := s.AddProtocolAddress(incomingNICID, incomingIPv6ProtoAddr); err != nil {\n+ t.Fatalf(\"AddProtocolAddress(%d, %#v): %s\", incomingNICID, incomingIPv6ProtoAddr, err)\n}\n- e2 := channel.New(1, header.IPv6MinimumMTU, \"\")\n- if err := s.CreateNIC(nicID2, e2); err != nil {\n- t.Fatalf(\"CreateNIC(%d, _): %s\", nicID2, err)\n+ outgoingEndpoint := channel.New(1, header.IPv6MinimumMTU, \"\")\n+ if err := s.CreateNIC(outgoingNICID, outgoingEndpoint); err != nil {\n+ t.Fatalf(\"CreateNIC(%d, _): %s\", outgoingNICID, err)\n}\n- ipv6ProtoAddr2 := tcpip.ProtocolAddress{Protocol: ProtocolNumber, AddressWithPrefix: ipv6Addr2}\n- if err := s.AddProtocolAddress(nicID2, ipv6ProtoAddr2); err != nil {\n- t.Fatalf(\"AddProtocolAddress(%d, %#v): %s\", nicID2, ipv6ProtoAddr2, err)\n+ outgoingIPv6ProtoAddr := tcpip.ProtocolAddress{Protocol: ProtocolNumber, AddressWithPrefix: outgoingIPv6Addr}\n+ if err := s.AddProtocolAddress(outgoingNICID, outgoingIPv6ProtoAddr); err != nil {\n+ t.Fatalf(\"AddProtocolAddress(%d, %#v): %s\", outgoingNICID, outgoingIPv6ProtoAddr, err)\n}\ns.SetRouteTable([]tcpip.Route{\n{\n- Destination: ipv6Addr1.Subnet(),\n- NIC: nicID1,\n+ Destination: incomingIPv6Addr.Subnet(),\n+ NIC: incomingNICID,\n},\n{\n- Destination: ipv6Addr2.Subnet(),\n- NIC: nicID2,\n+ Destination: outgoingIPv6Addr.Subnet(),\n+ NIC: outgoingNICID,\n},\n{\nDestination: multicastIPv6Addr.Subnet(),\n- NIC: nicID2,\n+ NIC: outgoingNICID,\n},\n})\n@@ -3372,9 +3373,10 @@ func TestForwarding(t *testing.T) {\nrequestPkt := stack.NewPacketBuffer(stack.PacketBufferOptions{\nData: hdr.View().ToVectorisedView(),\n})\n- e1.InjectInbound(ProtocolNumber, requestPkt)\n+ incomingEndpoint.InjectInbound(ProtocolNumber, requestPkt)\n+\n+ reply, ok := incomingEndpoint.Read()\n- reply, ok := e1.Read()\nif test.expectErrorICMP {\nif !ok {\nt.Fatalf(\"expected ICMP packet type %d through incoming NIC\", test.icmpType)\n@@ -3394,7 +3396,7 @@ func TestForwarding(t *testing.T) {\n}\nchecker.IPv6(t, header.IPv6(stack.PayloadSince(reply.Pkt.NetworkHeader())),\n- checker.SrcAddr(ipv6Addr1.Address),\n+ checker.SrcAddr(incomingIPv6Addr.Address),\nchecker.DstAddr(test.sourceAddr),\nchecker.TTL(DefaultTTL),\nchecker.ICMPv6(\n@@ -3404,14 +3406,14 @@ func TestForwarding(t *testing.T) {\n),\n)\n- if n := e2.Drain(); n != 0 {\n+ if n := outgoingEndpoint.Drain(); n != 0 {\nt.Fatalf(\"got e2.Drain() = %d, want = 0\", n)\n}\n} else if ok {\nt.Fatalf(\"expected no ICMP packet through incoming NIC, instead found: %#v\", reply)\n}\n- reply, ok = e2.Read()\n+ reply, ok = outgoingEndpoint.Read()\nif test.expectPacketForwarded {\nif !ok {\nt.Fatal(\"expected ICMP Echo Request packet through outgoing NIC\")\n@@ -3429,7 +3431,7 @@ func TestForwarding(t *testing.T) {\n),\n)\n- if n := e1.Drain(); n != 0 {\n+ if n := incomingEndpoint.Drain(); n != 0 {\nt.Fatalf(\"got e1.Drain() = %d, want = 0\", n)\n}\n} else if ok {\n" } ]
Go
Apache License 2.0
google/gvisor
Rename variables in IP forwarding tests Previously, we named domain objects using numbers (e.g. "e1", "e2" etc). This change renames objects to clarify whether they are part of the incoming or outgoing path. PiperOrigin-RevId: 374226859
259,891
17.05.2021 12:11:09
25,200
303c70194d086aef30c5e04b28836790e2c86e66
replace use of atomic with AlignedAtomicInt64
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/socketops.go", "new_path": "pkg/tcpip/socketops.go", "diff": "@@ -222,7 +222,7 @@ type SocketOptions struct {\ngetReceiveBufferLimits GetReceiveBufferLimits `state:\"manual\"`\n// receiveBufferSize determines the receive buffer size for this socket.\n- receiveBufferSize int64\n+ receiveBufferSize atomicbitops.AlignedAtomicInt64\n// mu protects the access to the below fields.\nmu sync.Mutex `state:\"nosave\"`\n@@ -653,13 +653,13 @@ func (so *SocketOptions) SetSendBufferSize(sendBufferSize int64, notify bool) {\n// GetReceiveBufferSize gets value for SO_RCVBUF option.\nfunc (so *SocketOptions) GetReceiveBufferSize() int64 {\n- return atomic.LoadInt64(&so.receiveBufferSize)\n+ return so.receiveBufferSize.Load()\n}\n// SetReceiveBufferSize sets value for SO_RCVBUF option.\nfunc (so *SocketOptions) SetReceiveBufferSize(receiveBufferSize int64, notify bool) {\nif !notify {\n- atomic.StoreInt64(&so.receiveBufferSize, receiveBufferSize)\n+ so.receiveBufferSize.Store(receiveBufferSize)\nreturn\n}\n@@ -684,8 +684,8 @@ func (so *SocketOptions) SetReceiveBufferSize(receiveBufferSize int64, notify bo\nv = math.MaxInt32\n}\n- oldSz := atomic.LoadInt64(&so.receiveBufferSize)\n+ oldSz := so.receiveBufferSize.Load()\n// Notify endpoint about change in buffer size.\nnewSz := so.handler.OnSetReceiveBufferSize(v, oldSz)\n- atomic.StoreInt64(&so.receiveBufferSize, newSz)\n+ so.receiveBufferSize.Store(newSz)\n}\n" } ]
Go
Apache License 2.0
google/gvisor
replace use of atomic with AlignedAtomicInt64
259,885
17.05.2021 13:55:03
25,200
e6cd1ff1beefb753101a3e8a43415e27bc474265
Reduce thread count in TCPResetDuringClose. This test suffers from extreme contention on tcpip/stack.AddressableEndpointState.mu via AddressableEndpointState.decAddressRef, at least when Go race detection is enabled.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_ip_tcp_generic.cc", "new_path": "test/syscalls/linux/socket_ip_tcp_generic.cc", "diff": "@@ -1155,7 +1155,7 @@ TEST_P(TCPSocketPairTest, IpMulticastLoopDefault) {\nTEST_P(TCPSocketPairTest, TCPResetDuringClose) {\nDisableSave ds; // Too many syscalls.\n- constexpr int kThreadCount = 1000;\n+ constexpr int kThreadCount = 100;\nstd::unique_ptr<ScopedThread> instances[kThreadCount];\nfor (int i = 0; i < kThreadCount; i++) {\ninstances[i] = absl::make_unique<ScopedThread>([&]() {\n" } ]
Go
Apache License 2.0
google/gvisor
Reduce thread count in TCPResetDuringClose. This test suffers from extreme contention on tcpip/stack.AddressableEndpointState.mu via AddressableEndpointState.decAddressRef, at least when Go race detection is enabled. PiperOrigin-RevId: 374273745
259,884
17.05.2021 19:42:01
25,200
32b66bb2be1b3b56138ca856045381519e210b68
Add badges for Github actions so it's easier to notice when they are failing.
[ { "change_type": "MODIFY", "old_path": ".github/workflows/stale.yml", "new_path": ".github/workflows/stale.yml", "diff": "# The stale workflow closes stale issues and pull requests, unless specific\n# tags have been applied in order to keep them open.\n-name: \"Close stale issues\"\n+name: \"Stale issues\"\n\"on\":\nschedule:\n- cron: \"0 0 * * *\"\n" }, { "change_type": "MODIFY", "old_path": "README.md", "new_path": "README.md", "diff": "[![gVisor chat](https://badges.gitter.im/gvisor/community.png)](https://gitter.im/gvisor/community)\n[![code search](https://img.shields.io/badge/code-search-blue)](https://cs.opensource.google/gvisor/gvisor)\n+[![Issue reviver](https://github.com/google/gvisor/actions/workflows/issue_reviver.yml/badge.svg)](https://github.com/google/gvisor/actions/workflows/issue_reviver.yml)\n+[![Stale issues](https://github.com/google/gvisor/actions/workflows/stale.yml/badge.svg)](https://github.com/google/gvisor/actions/workflows/stale.yml)\n+\n## What is gVisor?\n**gVisor** is an application kernel, written in Go, that implements a\n" } ]
Go
Apache License 2.0
google/gvisor
Add badges for Github actions so it's easier to notice when they are failing. PiperOrigin-RevId: 374331016
259,896
18.05.2021 14:44:09
25,200
e4984f8539560d49847fec84925333966f0c58e8
Delete /cloud/gvisor/sandbox/sentry/gofer/opened_write_execute_file metric This metric is replaced by /cloud/gvisor/sandbox/sentry/suspicious_operations metric with field value opened_write_execute_file.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/gofer/file.go", "new_path": "pkg/sentry/fs/gofer/file.go", "diff": "@@ -92,7 +92,6 @@ func NewFile(ctx context.Context, dirent *fs.Dirent, name string, flags fs.FileF\n}\nif flags.Write {\nif err := dirent.Inode.CheckPermission(ctx, fs.PermMask{Execute: true}); err == nil {\n- fsmetric.GoferOpensWX.Increment()\nmetric.SuspiciousOperationsMetric.Increment(\"opened_write_execute_file\")\nlog.Warningf(\"Opened a writable executable: %q\", name)\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/gofer/regular_file.go", "new_path": "pkg/sentry/fsimpl/gofer/regular_file.go", "diff": "@@ -60,7 +60,6 @@ func newRegularFileFD(mnt *vfs.Mount, d *dentry, flags uint32) (*regularFileFD,\nreturn nil, err\n}\nif fd.vfsfd.IsWritable() && (atomic.LoadUint32(&d.mode)&0111 != 0) {\n- fsmetric.GoferOpensWX.Increment()\nmetric.SuspiciousOperationsMetric.Increment(\"opened_write_execute_file\")\n}\nif atomic.LoadInt32(&d.mmapFD) >= 0 {\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/gofer/special_file.go", "new_path": "pkg/sentry/fsimpl/gofer/special_file.go", "diff": "@@ -101,7 +101,6 @@ func newSpecialFileFD(h handle, mnt *vfs.Mount, d *dentry, flags uint32) (*speci\nd.fs.specialFileFDs[fd] = struct{}{}\nd.fs.syncMu.Unlock()\nif fd.vfsfd.IsWritable() && (atomic.LoadUint32(&d.mode)&0111 != 0) {\n- fsmetric.GoferOpensWX.Increment()\nmetric.SuspiciousOperationsMetric.Increment(\"opened_write_execute_file\")\n}\nif h.fd >= 0 {\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsmetric/fsmetric.go", "new_path": "pkg/sentry/fsmetric/fsmetric.go", "diff": "@@ -42,7 +42,6 @@ var (\n// Metrics that only apply to fs/gofer and fsimpl/gofer.\nvar (\n- GoferOpensWX = metric.MustCreateNewUint64Metric(\"/gofer/opened_write_execute_file\", true /* sync */, \"Number of times a executable file was opened writably from a gofer.\")\nGoferOpens9P = metric.MustCreateNewUint64Metric(\"/gofer/opens_9p\", false /* sync */, \"Number of times a file was opened from a gofer and did not have a host file descriptor.\")\nGoferOpensHost = metric.MustCreateNewUint64Metric(\"/gofer/opens_host\", false /* sync */, \"Number of times a file was opened from a gofer and did have a host file descriptor.\")\nGoferReads9P = metric.MustCreateNewUint64Metric(\"/gofer/reads_9p\", false /* sync */, \"Number of 9P file reads from a gofer.\")\n" } ]
Go
Apache License 2.0
google/gvisor
Delete /cloud/gvisor/sandbox/sentry/gofer/opened_write_execute_file metric This metric is replaced by /cloud/gvisor/sandbox/sentry/suspicious_operations metric with field value opened_write_execute_file. PiperOrigin-RevId: 374509823
259,891
18.05.2021 21:55:19
25,200
8e99cfead78d012114f4478bc9e418e839d0b5f9
Be explicit about setsid() return values in pty.cc
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/pty.cc", "new_path": "test/syscalls/linux/pty.cc", "diff": "@@ -393,7 +393,7 @@ TEST(PtyTrunc, Truncate) {\n// setsid either puts us in a new session or fails because we're already the\n// session leader. Either way, this ensures we're the session leader and have\n// no controlling terminal.\n- setsid();\n+ ASSERT_THAT(setsid(), AnyOf(SyscallSucceeds(), SyscallFailsWithErrno(EPERM)));\n// Make sure we're ignoring SIGHUP, which will be sent to this process once we\n// disconnect the TTY.\n@@ -482,7 +482,7 @@ TEST(BasicPtyTest, OpenSetsControllingTTY) {\nSKIP_IF(IsRunningWithVFS1());\n// setsid either puts us in a new session or fails because we're already the\n// session leader. Either way, this ensures we're the session leader.\n- setsid();\n+ ASSERT_THAT(setsid(), AnyOf(SyscallSucceeds(), SyscallFailsWithErrno(EPERM)));\n// Make sure we're ignoring SIGHUP, which will be sent to this process once we\n// disconnect the TTY.\n@@ -509,7 +509,7 @@ TEST(BasicPtyTest, OpenMasterDoesNotSetsControllingTTY) {\nSKIP_IF(IsRunningWithVFS1());\n// setsid either puts us in a new session or fails because we're already the\n// session leader. Either way, this ensures we're the session leader.\n- setsid();\n+ ASSERT_THAT(setsid(), AnyOf(SyscallSucceeds(), SyscallFailsWithErrno(EPERM)));\nFileDescriptor master = ASSERT_NO_ERRNO_AND_VALUE(Open(\"/dev/ptmx\", O_RDWR));\n// Opening master does not set the controlling TTY, and therefore we are\n@@ -521,7 +521,7 @@ TEST(BasicPtyTest, OpenNOCTTY) {\nSKIP_IF(IsRunningWithVFS1());\n// setsid either puts us in a new session or fails because we're already the\n// session leader. Either way, this ensures we're the session leader.\n- setsid();\n+ ASSERT_THAT(setsid(), AnyOf(SyscallSucceeds(), SyscallFailsWithErrno(EPERM)));\nFileDescriptor master = ASSERT_NO_ERRNO_AND_VALUE(Open(\"/dev/ptmx\", O_RDWR));\nFileDescriptor replica = ASSERT_NO_ERRNO_AND_VALUE(\nOpenReplica(master, O_NOCTTY | O_NONBLOCK | O_RDWR));\n" } ]
Go
Apache License 2.0
google/gvisor
Be explicit about setsid() return values in pty.cc PiperOrigin-RevId: 374570219
259,891
18.05.2021 21:55:19
25,200
52394c34afce6c2a8861d556c9929b1c87c3a201
use more explicit netstack dependency restrictions Fuchsia was unable to build when building netstack transitively depended on golang.org/x/unix constants not defined in Fuchsia. The packages causing this (safemem and usermem) are no longer in the allowlist. Tested that this failed at cl/373651666, and passes now that the dependency has been removed.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/BUILD", "new_path": "pkg/tcpip/BUILD", "diff": "@@ -39,12 +39,30 @@ go_library(\ndeps_test(\nname = \"netstack_deps_test\",\nallowed = [\n+ # gVisor deps.\n+ \"//pkg/atomicbitops\",\n+ \"//pkg/buffer\",\n+ \"//pkg/context\",\n+ \"//pkg/gohacks\",\n+ \"//pkg/goid\",\n+ \"//pkg/ilist\",\n+ \"//pkg/iovec\",\n+ \"//pkg/linewriter\",\n+ \"//pkg/log\",\n+ \"//pkg/rand\",\n+ \"//pkg/sleep\",\n+ \"//pkg/state\",\n+ \"//pkg/state/wire\",\n+ \"//pkg/sync\",\n+ \"//pkg/waiter\",\n+\n+ # Other deps.\n\"@com_github_google_btree//:go_default_library\",\n\"@org_golang_x_sys//unix:go_default_library\",\n\"@org_golang_x_time//rate:go_default_library\",\n],\nallowed_prefixes = [\n- \"//\",\n+ \"//pkg/tcpip\",\n\"@org_golang_x_sys//internal/unsafeheader\",\n],\ntargets = [\n" } ]
Go
Apache License 2.0
google/gvisor
use more explicit netstack dependency restrictions Fuchsia was unable to build when building netstack transitively depended on golang.org/x/unix constants not defined in Fuchsia. The packages causing this (safemem and usermem) are no longer in the allowlist. Tested that this failed at cl/373651666, and passes now that the dependency has been removed. PiperOrigin-RevId: 374570220
259,963
19.05.2021 17:52:01
-10,800
0636c1c929da3b58d3a34262fbc6567f86bfb594
Allow use of IFF_ONE_QUEUE Before fix, use of this flag causes an error. It affects applications like OpenVPN which sets this flag for legacy reasons. According to linux/if_tun.h "This flag has no real effect".
[ { "change_type": "MODIFY", "old_path": "pkg/abi/linux/ioctl_tun.go", "new_path": "pkg/abi/linux/ioctl_tun.go", "diff": "@@ -26,4 +26,7 @@ const (\nIFF_TAP = 0x0002\nIFF_NO_PI = 0x1000\nIFF_NOFILTER = 0x1000\n+\n+ // According to linux/if_tun.h \"This flag has no real effect\"\n+ IFF_ONE_QUEUE = 0x2000\n)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netstack/tun.go", "new_path": "pkg/sentry/socket/netstack/tun.go", "diff": "@@ -40,7 +40,7 @@ func LinuxToTUNFlags(flags uint16) (tun.Flags, error) {\n// Linux adds IFF_NOFILTER (the same value as IFF_NO_PI unfortunately)\n// when there is no sk_filter. See __tun_chr_ioctl() in\n// net/drivers/tun.c.\n- if flags&^uint16(linux.IFF_TUN|linux.IFF_TAP|linux.IFF_NO_PI) != 0 {\n+ if flags&^uint16(linux.IFF_TUN|linux.IFF_TAP|linux.IFF_NO_PI|linux.IFF_ONE_QUEUE) != 0 {\nreturn tun.Flags{}, syserror.EINVAL\n}\nreturn tun.Flags{\n" } ]
Go
Apache License 2.0
google/gvisor
Allow use of IFF_ONE_QUEUE Before fix, use of this flag causes an error. It affects applications like OpenVPN which sets this flag for legacy reasons. According to linux/if_tun.h "This flag has no real effect".
259,858
19.05.2021 10:55:02
25,200
2f3eda37a4dd64f1202fac1c69ab819fb0bd7a5e
Fix nogo analysis. Ignore calls to atomic functions in case there is no analysis information. It is unclear why this has broken in some cases, perhaps these functions have been replaced by intrinsics as an optimization?
[ { "change_type": "MODIFY", "old_path": "tools/checkescape/checkescape.go", "new_path": "tools/checkescape/checkescape.go", "diff": "@@ -709,8 +709,13 @@ func run(pass *analysis.Pass, localEscapes bool) (interface{}, error) {\nreturn\n}\n- // Recursively collect information from\n- // the other analyzers.\n+ // If this package is the atomic package, the implementation\n+ // may be replaced by instrinsics that don't have analysis.\n+ if x.Pkg.Pkg.Path() == \"sync/atomic\" {\n+ return\n+ }\n+\n+ // Recursively collect information.\nvar imp packageEscapeFacts\nif !pass.ImportPackageFact(x.Pkg.Pkg, &imp) {\n// Unable to import the dependency; we must\n" } ]
Go
Apache License 2.0
google/gvisor
Fix nogo analysis. Ignore calls to atomic functions in case there is no analysis information. It is unclear why this has broken in some cases, perhaps these functions have been replaced by intrinsics as an optimization? PiperOrigin-RevId: 374682441
259,985
20.05.2021 15:07:17
25,200
af229f46a1496f39b012b4e2b244c32bb7d0667c
Fix cgroupfs mount racing with unmount. Previously, mount could discover a hierarchy being destroyed concurrently, which resulted in mount attempting to take a ref on an already destroyed cgroupfs. Reported-by:
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/cgroup.go", "new_path": "pkg/sentry/kernel/cgroup.go", "diff": "@@ -181,7 +181,23 @@ func (r *CgroupRegistry) FindHierarchy(ctypes []CgroupControllerType) *vfs.Files\nfor _, h := range r.hierarchies {\nif h.match(ctypes) {\n- h.fs.IncRef()\n+ if !h.fs.TryIncRef() {\n+ // Racing with filesystem destruction, namely h.fs.Release.\n+ // Since we hold r.mu, we know the hierarchy hasn't been\n+ // unregistered yet, but its associated filesystem is tearing\n+ // down.\n+ //\n+ // If we simply indicate the hierarchy wasn't found without\n+ // cleaning up the registry, the caller can race with the\n+ // unregister and find itself temporarily unable to create a new\n+ // hierarchy with a subset of the relevant controllers.\n+ //\n+ // To keep the result of FindHierarchy consistent with the\n+ // uniqueness of controllers enforced by Register, drop the\n+ // dying hierarchy now. The eventual unregister by the FS\n+ // teardown will become a no-op.\n+ return nil\n+ }\nreturn h.fs\n}\n}\n@@ -230,12 +246,17 @@ func (r *CgroupRegistry) Register(cs []CgroupController, fs cgroupFS) error {\nreturn nil\n}\n-// Unregister removes a previously registered hierarchy from the registry. If\n-// the controller was not previously registered, Unregister is a no-op.\n+// Unregister removes a previously registered hierarchy from the registry. If no\n+// such hierarchy is registered, Unregister is a no-op.\nfunc (r *CgroupRegistry) Unregister(hid uint32) {\nr.mu.Lock()\n- defer r.mu.Unlock()\n+ r.unregisterLocked(hid)\n+ r.mu.Unlock()\n+}\n+// Precondition: Caller must hold r.mu.\n+// +checklocks:r.mu\n+func (r *CgroupRegistry) unregisterLocked(hid uint32) {\nif h, ok := r.hierarchies[hid]; ok {\nfor name, _ := range h.controllers {\ndelete(r.controllers, name)\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/cgroup.cc", "new_path": "test/syscalls/linux/cgroup.cc", "diff": "@@ -227,6 +227,41 @@ TEST(Cgroup, MountRace) {\nEXPECT_NO_ERRNO(c.ContainsCallingProcess());\n}\n+TEST(Cgroup, MountUnmountRace) {\n+ SKIP_IF(!CgroupsAvailable());\n+\n+ TempPath mountpoint = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n+\n+ const DisableSave ds; // Too many syscalls.\n+\n+ auto mount_thread = [&mountpoint]() {\n+ for (int i = 0; i < 100; ++i) {\n+ mount(\"none\", mountpoint.path().c_str(), \"cgroup\", 0, 0);\n+ }\n+ };\n+ auto unmount_thread = [&mountpoint]() {\n+ for (int i = 0; i < 100; ++i) {\n+ umount(mountpoint.path().c_str());\n+ }\n+ };\n+ std::list<ScopedThread> threads;\n+ for (int i = 0; i < 10; ++i) {\n+ threads.emplace_back(mount_thread);\n+ }\n+ for (int i = 0; i < 10; ++i) {\n+ threads.emplace_back(unmount_thread);\n+ }\n+ for (auto& t : threads) {\n+ t.Join();\n+ }\n+\n+ // We don't know how many mount refs are remaining, since the count depends on\n+ // the ordering of mount and umount calls. Keep calling unmount until it\n+ // returns an error.\n+ while (umount(mountpoint.path().c_str()) == 0) {\n+ }\n+}\n+\nTEST(Cgroup, UnmountRepeated) {\nSKIP_IF(!CgroupsAvailable());\n" } ]
Go
Apache License 2.0
google/gvisor
Fix cgroupfs mount racing with unmount. Previously, mount could discover a hierarchy being destroyed concurrently, which resulted in mount attempting to take a ref on an already destroyed cgroupfs. Reported-by: [email protected] PiperOrigin-RevId: 374959054
259,992
20.05.2021 17:11:15
25,200
ec542dbedf2f454b8c3e126a19b6910cd9425e92
Suppress log message when there is no error
[ { "change_type": "MODIFY", "old_path": "runsc/sandbox/sandbox.go", "new_path": "runsc/sandbox/sandbox.go", "diff": "@@ -131,8 +131,9 @@ func New(conf *config.Config, args *Args) (*Sandbox, error) {\n// The Cleanup object cleans up partially created sandboxes when an error\n// occurs. Any errors occurring during cleanup itself are ignored.\nc := cleanup.Make(func() {\n- err := s.destroy()\n+ if err := s.destroy(); err != nil {\nlog.Warningf(\"error destroying sandbox: %v\", err)\n+ }\n})\ndefer c.Clean()\n" } ]
Go
Apache License 2.0
google/gvisor
Suppress log message when there is no error PiperOrigin-RevId: 374981100
260,023
20.05.2021 19:12:27
25,200
9157a91a4eca7e0811edb20952e9f22ea2c3f13e
Add protocol state to TCPINFO Add missing protocol state to TCPINFO struct and update packetimpact. This re-arranges the TCP state definitions to align with Linux. Fixes
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netstack/netstack.go", "new_path": "pkg/sentry/socket/netstack/netstack.go", "diff": "@@ -1127,7 +1127,14 @@ func getSockOptTCP(t *kernel.Task, s socket.SocketOps, ep commonEndpoint, name,\n// TODO(b/64800844): Translate fields once they are added to\n// tcpip.TCPInfoOption.\n- info := linux.TCPInfo{}\n+ info := linux.TCPInfo{\n+ State: uint8(v.State),\n+ RTO: uint32(v.RTO / time.Microsecond),\n+ RTT: uint32(v.RTT / time.Microsecond),\n+ RTTVar: uint32(v.RTTVar / time.Microsecond),\n+ SndSsthresh: v.SndSsthresh,\n+ SndCwnd: v.SndCwnd,\n+ }\nswitch v.CcState {\ncase tcpip.RTORecovery:\ninfo.CaState = linux.TCP_CA_Loss\n@@ -1138,11 +1145,6 @@ func getSockOptTCP(t *kernel.Task, s socket.SocketOps, ep commonEndpoint, name,\ncase tcpip.Open:\ninfo.CaState = linux.TCP_CA_Open\n}\n- info.RTO = uint32(v.RTO / time.Microsecond)\n- info.RTT = uint32(v.RTT / time.Microsecond)\n- info.RTTVar = uint32(v.RTTVar / time.Microsecond)\n- info.SndSsthresh = v.SndSsthresh\n- info.SndCwnd = v.SndCwnd\n// In netstack reorderSeen is updated only when RACK is enabled.\n// We only track whether the reordering is seen, which is\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/tcpip.go", "new_path": "pkg/tcpip/tcpip.go", "diff": "@@ -861,6 +861,9 @@ type SettableSocketOption interface {\nisSettableSocketOption()\n}\n+// EndpointState represents the state of an endpoint.\n+type EndpointState uint8\n+\n// CongestionControlState indicates the current congestion control state for\n// TCP sender.\ntype CongestionControlState int\n@@ -897,6 +900,9 @@ type TCPInfoOption struct {\n// RTO is the retransmission timeout for the endpoint.\nRTO time.Duration\n+ // State is the current endpoint protocol state.\n+ State EndpointState\n+\n// CcState is the congestion control state.\nCcState CongestionControlState\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/connect.go", "new_path": "pkg/tcpip/transport/tcp/connect.go", "diff": "@@ -1235,7 +1235,7 @@ func (e *endpoint) handleSegmentLocked(s *segment) (cont bool, err tcpip.Error)\n// Now check if the received segment has caused us to transition\n// to a CLOSED state, if yes then terminate processing and do\n// not invoke the sender.\n- state := e.state\n+ state := e.EndpointState()\nif state == StateClose {\n// When we get into StateClose while processing from the queue,\n// return immediately and let the protocolMainloop handle it.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/endpoint.go", "new_path": "pkg/tcpip/transport/tcp/endpoint.go", "diff": "@@ -38,19 +38,15 @@ import (\n)\n// EndpointState represents the state of a TCP endpoint.\n-type EndpointState uint32\n+type EndpointState tcpip.EndpointState\n// Endpoint states. Note that are represented in a netstack-specific manner and\n// may not be meaningful externally. Specifically, they need to be translated to\n// Linux's representation for these states if presented to userspace.\nconst (\n- // Endpoint states internal to netstack. These map to the TCP state CLOSED.\n- StateInitial EndpointState = iota\n- StateBound\n- StateConnecting // Connect() called, but the initial SYN hasn't been sent.\n- StateError\n-\n- // TCP protocol states.\n+ _ EndpointState = iota\n+ // TCP protocol states in sync with the definitions in\n+ // https://github.com/torvalds/linux/blob/7acac4b3196/include/net/tcp_states.h#L13\nStateEstablished\nStateSynSent\nStateSynRecv\n@@ -62,6 +58,12 @@ const (\nStateLastAck\nStateListen\nStateClosing\n+\n+ // Endpoint states internal to netstack.\n+ StateInitial\n+ StateBound\n+ StateConnecting // Connect() called, but the initial SYN hasn't been sent.\n+ StateError\n)\nconst (\n@@ -97,6 +99,16 @@ func (s EndpointState) connecting() bool {\n}\n}\n+// internal returns true when the state is netstack internal.\n+func (s EndpointState) internal() bool {\n+ switch s {\n+ case StateInitial, StateBound, StateConnecting, StateError:\n+ return true\n+ default:\n+ return false\n+ }\n+}\n+\n// handshake returns true when s is one of the states representing an endpoint\n// in the middle of a TCP handshake.\nfunc (s EndpointState) handshake() bool {\n@@ -422,12 +434,12 @@ type endpoint struct {\n// state must be read/set using the EndpointState()/setEndpointState()\n// methods.\n- state EndpointState `state:\".(EndpointState)\"`\n+ state uint32 `state:\".(EndpointState)\"`\n// origEndpointState is only used during a restore phase to save the\n// endpoint state at restore time as the socket is moved to it's correct\n// state.\n- origEndpointState EndpointState `state:\"nosave\"`\n+ origEndpointState uint32 `state:\"nosave\"`\nisPortReserved bool `state:\"manual\"`\nisRegistered bool `state:\"manual\"`\n@@ -747,7 +759,7 @@ func (e *endpoint) ResumeWork() {\n//\n// Precondition: e.mu must be held to call this method.\nfunc (e *endpoint) setEndpointState(state EndpointState) {\n- oldstate := EndpointState(atomic.LoadUint32((*uint32)(&e.state)))\n+ oldstate := EndpointState(atomic.LoadUint32(&e.state))\nswitch state {\ncase StateEstablished:\ne.stack.Stats().TCP.CurrentEstablished.Increment()\n@@ -764,12 +776,12 @@ func (e *endpoint) setEndpointState(state EndpointState) {\ne.stack.Stats().TCP.CurrentEstablished.Decrement()\n}\n}\n- atomic.StoreUint32((*uint32)(&e.state), uint32(state))\n+ atomic.StoreUint32(&e.state, uint32(state))\n}\n// EndpointState returns the current state of the endpoint.\nfunc (e *endpoint) EndpointState() EndpointState {\n- return EndpointState(atomic.LoadUint32((*uint32)(&e.state)))\n+ return EndpointState(atomic.LoadUint32(&e.state))\n}\n// setRecentTimestamp sets the recentTS field to the provided value.\n@@ -810,7 +822,7 @@ func newEndpoint(s *stack.Stack, netProto tcpip.NetworkProtocolNumber, waiterQue\n},\n},\nwaiterQueue: waiterQueue,\n- state: StateInitial,\n+ state: uint32(StateInitial),\nkeepalive: keepalive{\n// Linux defaults.\nidle: 2 * time.Hour,\n@@ -1956,6 +1968,11 @@ func (e *endpoint) GetSockOptInt(opt tcpip.SockOptInt) (int, tcpip.Error) {\nfunc (e *endpoint) getTCPInfo() tcpip.TCPInfoOption {\ninfo := tcpip.TCPInfoOption{}\ne.LockUser()\n+ if state := e.EndpointState(); state.internal() {\n+ info.State = tcpip.EndpointState(StateClose)\n+ } else {\n+ info.State = tcpip.EndpointState(state)\n+ }\nsnd := e.snd\nif snd != nil {\n// We do not calculate RTT before sending the data packets. If\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/endpoint_state.go", "new_path": "pkg/tcpip/transport/tcp/endpoint_state.go", "diff": "@@ -154,7 +154,7 @@ func (e *endpoint) afterLoad() {\ne.origEndpointState = e.state\n// Restore the endpoint to InitialState as it will be moved to\n// its origEndpointState during Resume.\n- e.state = StateInitial\n+ e.state = uint32(StateInitial)\n// Condition variables and mutexs are not S/R'ed so reinitialize\n// acceptCond with e.acceptMu.\ne.acceptCond = sync.NewCond(&e.acceptMu)\n@@ -167,7 +167,7 @@ func (e *endpoint) Resume(s *stack.Stack) {\ne.stack = s\ne.ops.InitHandler(e, e.stack, GetTCPSendBufferLimits, GetTCPReceiveBufferLimits)\ne.segmentQueue.thaw()\n- epState := e.origEndpointState\n+ epState := EndpointState(e.origEndpointState)\nswitch epState {\ncase StateInitial, StateBound, StateListen, StateConnecting, StateEstablished:\nvar ss tcpip.TCPSendBufferSizeRangeOption\n@@ -281,11 +281,11 @@ func (e *endpoint) Resume(s *stack.Stack) {\n}()\ncase epState == StateClose:\ne.isPortReserved = false\n- e.state = StateClose\n+ e.state = uint32(StateClose)\ne.stack.CompleteTransportEndpointCleanup(e)\ntcpip.DeleteDanglingEndpoint(e)\ncase epState == StateError:\n- e.state = StateError\n+ e.state = uint32(StateError)\ne.stack.CompleteTransportEndpointCleanup(e)\ntcpip.DeleteDanglingEndpoint(e)\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/udp/endpoint.go", "new_path": "pkg/tcpip/transport/udp/endpoint.go", "diff": "@@ -40,13 +40,14 @@ type udpPacket struct {\n}\n// EndpointState represents the state of a UDP endpoint.\n-type EndpointState uint32\n+type EndpointState tcpip.EndpointState\n// Endpoint states. Note that are represented in a netstack-specific manner and\n// may not be meaningful externally. Specifically, they need to be translated to\n// Linux's representation for these states if presented to userspace.\nconst (\n- StateInitial EndpointState = iota\n+ _ EndpointState = iota\n+ StateInitial\nStateBound\nStateConnected\nStateClosed\n@@ -98,7 +99,7 @@ type endpoint struct {\nmu sync.RWMutex `state:\"nosave\"`\n// state must be read/set using the EndpointState()/setEndpointState()\n// methods.\n- state EndpointState\n+ state uint32\nroute *stack.Route `state:\"manual\"`\ndstPort uint16\nttl uint8\n@@ -176,7 +177,7 @@ func newEndpoint(s *stack.Stack, netProto tcpip.NetworkProtocolNumber, waiterQue\n// Linux defaults to TTL=1.\nmulticastTTL: 1,\nmulticastMemberships: make(map[multicastMembership]struct{}),\n- state: StateInitial,\n+ state: uint32(StateInitial),\nuniqueID: s.UniqueID(),\n}\ne.ops.InitHandler(e, e.stack, tcpip.GetStackSendBufferLimits, tcpip.GetStackReceiveBufferLimits)\n@@ -204,12 +205,12 @@ func newEndpoint(s *stack.Stack, netProto tcpip.NetworkProtocolNumber, waiterQue\n//\n// Precondition: e.mu must be held to call this method.\nfunc (e *endpoint) setEndpointState(state EndpointState) {\n- atomic.StoreUint32((*uint32)(&e.state), uint32(state))\n+ atomic.StoreUint32(&e.state, uint32(state))\n}\n// EndpointState() returns the current state of the endpoint.\nfunc (e *endpoint) EndpointState() EndpointState {\n- return EndpointState(atomic.LoadUint32((*uint32)(&e.state)))\n+ return EndpointState(atomic.LoadUint32(&e.state))\n}\n// UniqueID implements stack.TransportEndpoint.UniqueID.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/udp/forwarder.go", "new_path": "pkg/tcpip/transport/udp/forwarder.go", "diff": "@@ -90,7 +90,7 @@ func (r *ForwarderRequest) CreateEndpoint(queue *waiter.Queue) (tcpip.Endpoint,\nep.RegisterNICID = r.pkt.NICID\nep.boundPortFlags = ep.portFlags\n- ep.state = StateConnected\n+ ep.state = uint32(StateConnected)\nep.rcvMu.Lock()\nep.rcvReady = true\n" }, { "change_type": "MODIFY", "old_path": "test/packetimpact/testbench/BUILD", "new_path": "test/packetimpact/testbench/BUILD", "diff": "@@ -16,6 +16,8 @@ go_library(\n],\nvisibility = [\"//test/packetimpact:__subpackages__\"],\ndeps = [\n+ \"//pkg/abi/linux\",\n+ \"//pkg/binary\",\n\"//pkg/hostarch\",\n\"//pkg/tcpip\",\n\"//pkg/tcpip/buffer\",\n" }, { "change_type": "MODIFY", "old_path": "test/packetimpact/testbench/dut.go", "new_path": "test/packetimpact/testbench/dut.go", "diff": "@@ -22,11 +22,13 @@ import (\n\"testing\"\n\"time\"\n- pb \"gvisor.dev/gvisor/test/packetimpact/proto/posix_server_go_proto\"\n-\n\"golang.org/x/sys/unix\"\n\"google.golang.org/grpc\"\n\"google.golang.org/grpc/keepalive\"\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n+ bin \"gvisor.dev/gvisor/pkg/binary\"\n+ \"gvisor.dev/gvisor/pkg/hostarch\"\n+ pb \"gvisor.dev/gvisor/test/packetimpact/proto/posix_server_go_proto\"\n)\n// DUT communicates with the DUT to force it to make POSIX calls.\n@@ -428,6 +430,33 @@ func (dut *DUT) GetSockOptTimevalWithErrno(ctx context.Context, t *testing.T, so\nreturn ret, timeval, errno\n}\n+// GetSockOptTCPInfo retreives TCPInfo for the given socket descriptor.\n+func (dut *DUT) GetSockOptTCPInfo(t *testing.T, sockfd int32) linux.TCPInfo {\n+ t.Helper()\n+\n+ ctx, cancel := context.WithTimeout(context.Background(), RPCTimeout)\n+ defer cancel()\n+ ret, info, err := dut.GetSockOptTCPInfoWithErrno(ctx, t, sockfd)\n+ if ret != 0 || err != unix.Errno(0) {\n+ t.Fatalf(\"failed to GetSockOptTCPInfo: %s\", err)\n+ }\n+ return info\n+}\n+\n+// GetSockOptTCPInfoWithErrno retreives TCPInfo with any errno.\n+func (dut *DUT) GetSockOptTCPInfoWithErrno(ctx context.Context, t *testing.T, sockfd int32) (int32, linux.TCPInfo, error) {\n+ t.Helper()\n+\n+ info := linux.TCPInfo{}\n+ ret, infoBytes, errno := dut.GetSockOptWithErrno(ctx, t, sockfd, unix.SOL_TCP, unix.TCP_INFO, int32(linux.SizeOfTCPInfo))\n+ if got, want := len(infoBytes), linux.SizeOfTCPInfo; got != want {\n+ t.Fatalf(\"expected %T, got %d bytes want %d bytes\", info, got, want)\n+ }\n+ bin.Unmarshal(infoBytes, hostarch.ByteOrder, &info)\n+\n+ return ret, info, errno\n+}\n+\n// Listen calls listen on the DUT and causes a fatal test failure if it doesn't\n// succeed. If more control over the timeout or error handling is needed, use\n// ListenWithErrno.\n" }, { "change_type": "MODIFY", "old_path": "test/packetimpact/tests/BUILD", "new_path": "test/packetimpact/tests/BUILD", "diff": "@@ -104,8 +104,6 @@ packetimpact_testbench(\nsrcs = [\"tcp_retransmits_test.go\"],\ndeps = [\n\"//pkg/abi/linux\",\n- \"//pkg/binary\",\n- \"//pkg/hostarch\",\n\"//pkg/tcpip/header\",\n\"//test/packetimpact/testbench\",\n\"@org_golang_x_sys//unix:go_default_library\",\n@@ -189,6 +187,7 @@ packetimpact_testbench(\nname = \"tcp_synsent_reset\",\nsrcs = [\"tcp_synsent_reset_test.go\"],\ndeps = [\n+ \"//pkg/abi/linux\",\n\"//pkg/tcpip/header\",\n\"//test/packetimpact/testbench\",\n\"@org_golang_x_sys//unix:go_default_library\",\n@@ -353,8 +352,6 @@ packetimpact_testbench(\nsrcs = [\"tcp_rack_test.go\"],\ndeps = [\n\"//pkg/abi/linux\",\n- \"//pkg/binary\",\n- \"//pkg/hostarch\",\n\"//pkg/tcpip/header\",\n\"//pkg/tcpip/seqnum\",\n\"//test/packetimpact/testbench\",\n@@ -367,8 +364,6 @@ packetimpact_testbench(\nsrcs = [\"tcp_info_test.go\"],\ndeps = [\n\"//pkg/abi/linux\",\n- \"//pkg/binary\",\n- \"//pkg/hostarch\",\n\"//pkg/tcpip/header\",\n\"//test/packetimpact/testbench\",\n\"@org_golang_x_sys//unix:go_default_library\",\n" }, { "change_type": "MODIFY", "old_path": "test/packetimpact/tests/tcp_info_test.go", "new_path": "test/packetimpact/tests/tcp_info_test.go", "diff": "@@ -21,8 +21,6 @@ import (\n\"golang.org/x/sys/unix\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n- \"gvisor.dev/gvisor/pkg/binary\"\n- \"gvisor.dev/gvisor/pkg/hostarch\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n\"gvisor.dev/gvisor/test/packetimpact/testbench\"\n)\n@@ -53,13 +51,10 @@ func TestTCPInfo(t *testing.T) {\n}\nconn.Send(t, testbench.TCP{Flags: testbench.TCPFlags(header.TCPFlagAck)})\n- info := linux.TCPInfo{}\n- infoBytes := dut.GetSockOpt(t, acceptFD, unix.SOL_TCP, unix.TCP_INFO, int32(linux.SizeOfTCPInfo))\n- if got, want := len(infoBytes), linux.SizeOfTCPInfo; got != want {\n- t.Fatalf(\"expected %T, got %d bytes want %d bytes\", info, got, want)\n+ info := dut.GetSockOptTCPInfo(t, acceptFD)\n+ if got, want := uint32(info.State), linux.TCP_ESTABLISHED; got != want {\n+ t.Fatalf(\"got %d want %d\", got, want)\n}\n- binary.Unmarshal(infoBytes, hostarch.ByteOrder, &info)\n-\nrtt := time.Duration(info.RTT) * time.Microsecond\nrttvar := time.Duration(info.RTTVar) * time.Microsecond\nrto := time.Duration(info.RTO) * time.Microsecond\n@@ -94,12 +89,7 @@ func TestTCPInfo(t *testing.T) {\nt.Fatalf(\"expected a packet with payload %v: %s\", samplePayload, err)\n}\n- info = linux.TCPInfo{}\n- infoBytes = dut.GetSockOpt(t, acceptFD, unix.SOL_TCP, unix.TCP_INFO, int32(linux.SizeOfTCPInfo))\n- if got, want := len(infoBytes), linux.SizeOfTCPInfo; got != want {\n- t.Fatalf(\"expected %T, got %d bytes want %d bytes\", info, got, want)\n- }\n- binary.Unmarshal(infoBytes, hostarch.ByteOrder, &info)\n+ info = dut.GetSockOptTCPInfo(t, acceptFD)\nif info.CaState != linux.TCP_CA_Loss {\nt.Errorf(\"expected the connection to be in loss recovery, got: %v want: %v\", info.CaState, linux.TCP_CA_Loss)\n}\n" }, { "change_type": "MODIFY", "old_path": "test/packetimpact/tests/tcp_rack_test.go", "new_path": "test/packetimpact/tests/tcp_rack_test.go", "diff": "@@ -21,8 +21,6 @@ import (\n\"golang.org/x/sys/unix\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n- \"gvisor.dev/gvisor/pkg/binary\"\n- \"gvisor.dev/gvisor/pkg/hostarch\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n\"gvisor.dev/gvisor/pkg/tcpip/seqnum\"\n\"gvisor.dev/gvisor/test/packetimpact/testbench\"\n@@ -69,12 +67,7 @@ func closeSACKConnection(t *testing.T, dut testbench.DUT, conn testbench.TCPIPv4\n}\nfunc getRTTAndRTO(t *testing.T, dut testbench.DUT, acceptFd int32) (rtt, rto time.Duration) {\n- info := linux.TCPInfo{}\n- infoBytes := dut.GetSockOpt(t, acceptFd, unix.SOL_TCP, unix.TCP_INFO, int32(linux.SizeOfTCPInfo))\n- if got, want := len(infoBytes), linux.SizeOfTCPInfo; got != want {\n- t.Fatalf(\"expected %T, got %d bytes want %d bytes\", info, got, want)\n- }\n- binary.Unmarshal(infoBytes, hostarch.ByteOrder, &info)\n+ info := dut.GetSockOptTCPInfo(t, acceptFd)\nreturn time.Duration(info.RTT) * time.Microsecond, time.Duration(info.RTO) * time.Microsecond\n}\n@@ -402,12 +395,7 @@ func TestRACKWithLostRetransmission(t *testing.T) {\n}\n// Check the congestion control state.\n- info := linux.TCPInfo{}\n- infoBytes := dut.GetSockOpt(t, acceptFd, unix.SOL_TCP, unix.TCP_INFO, int32(linux.SizeOfTCPInfo))\n- if got, want := len(infoBytes), linux.SizeOfTCPInfo; got != want {\n- t.Fatalf(\"expected %T, got %d bytes want %d bytes\", info, got, want)\n- }\n- binary.Unmarshal(infoBytes, hostarch.ByteOrder, &info)\n+ info := dut.GetSockOptTCPInfo(t, acceptFd)\nif info.CaState != linux.TCP_CA_Recovery {\nt.Fatalf(\"expected connection to be in fast recovery, want: %v got: %v\", linux.TCP_CA_Recovery, info.CaState)\n}\n" }, { "change_type": "MODIFY", "old_path": "test/packetimpact/tests/tcp_retransmits_test.go", "new_path": "test/packetimpact/tests/tcp_retransmits_test.go", "diff": "@@ -21,9 +21,6 @@ import (\n\"time\"\n\"golang.org/x/sys/unix\"\n- \"gvisor.dev/gvisor/pkg/abi/linux\"\n- \"gvisor.dev/gvisor/pkg/binary\"\n- \"gvisor.dev/gvisor/pkg/hostarch\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n\"gvisor.dev/gvisor/test/packetimpact/testbench\"\n)\n@@ -33,12 +30,7 @@ func init() {\n}\nfunc getRTO(t *testing.T, dut testbench.DUT, acceptFd int32) (rto time.Duration) {\n- info := linux.TCPInfo{}\n- infoBytes := dut.GetSockOpt(t, acceptFd, unix.SOL_TCP, unix.TCP_INFO, int32(linux.SizeOfTCPInfo))\n- if got, want := len(infoBytes), linux.SizeOfTCPInfo; got != want {\n- t.Fatalf(\"unexpected size for TCP_INFO, got %d bytes want %d bytes\", got, want)\n- }\n- binary.Unmarshal(infoBytes, hostarch.ByteOrder, &info)\n+ info := dut.GetSockOptTCPInfo(t, acceptFd)\nreturn time.Duration(info.RTO) * time.Microsecond\n}\n" }, { "change_type": "MODIFY", "old_path": "test/packetimpact/tests/tcp_synsent_reset_test.go", "new_path": "test/packetimpact/tests/tcp_synsent_reset_test.go", "diff": "@@ -20,6 +20,7 @@ import (\n\"time\"\n\"golang.org/x/sys/unix\"\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n\"gvisor.dev/gvisor/test/packetimpact/testbench\"\n)\n@@ -29,7 +30,7 @@ func init() {\n}\n// dutSynSentState sets up the dut connection in SYN-SENT state.\n-func dutSynSentState(t *testing.T) (*testbench.DUT, *testbench.TCPIPv4, uint16, uint16) {\n+func dutSynSentState(t *testing.T) (*testbench.DUT, *testbench.TCPIPv4, int32, uint16, uint16) {\nt.Helper()\ndut := testbench.NewDUT(t)\n@@ -46,26 +47,29 @@ func dutSynSentState(t *testing.T) (*testbench.DUT, *testbench.TCPIPv4, uint16,\nt.Fatalf(\"expected SYN\\n\")\n}\n- return &dut, &conn, port, clientPort\n+ return &dut, &conn, clientFD, port, clientPort\n}\n// TestTCPSynSentReset tests RFC793, p67: SYN-SENT to CLOSED transition.\nfunc TestTCPSynSentReset(t *testing.T) {\n- _, conn, _, _ := dutSynSentState(t)\n+ dut, conn, fd, _, _ := dutSynSentState(t)\ndefer conn.Close(t)\nconn.Send(t, testbench.TCP{Flags: testbench.TCPFlags(header.TCPFlagRst | header.TCPFlagAck)})\n// Expect the connection to have closed.\n- // TODO(gvisor.dev/issue/478): Check for TCP_INFO on the dut side.\nconn.Send(t, testbench.TCP{Flags: testbench.TCPFlags(header.TCPFlagAck)})\nif _, err := conn.ExpectData(t, &testbench.TCP{Flags: testbench.TCPFlags(header.TCPFlagRst)}, nil, time.Second); err != nil {\nt.Fatalf(\"expected a TCP RST\")\n}\n+ info := dut.GetSockOptTCPInfo(t, fd)\n+ if got, want := uint32(info.State), linux.TCP_CLOSE; got != want {\n+ t.Fatalf(\"got %d want %d\", got, want)\n+ }\n}\n// TestTCPSynSentRcvdReset tests RFC793, p70, SYN-SENT to SYN-RCVD to CLOSED\n// transitions.\nfunc TestTCPSynSentRcvdReset(t *testing.T) {\n- dut, c, remotePort, clientPort := dutSynSentState(t)\n+ dut, c, fd, remotePort, clientPort := dutSynSentState(t)\ndefer c.Close(t)\nconn := dut.Net.NewTCPIPv4(t, testbench.TCP{SrcPort: &remotePort, DstPort: &clientPort}, testbench.TCP{SrcPort: &clientPort, DstPort: &remotePort})\n@@ -79,9 +83,12 @@ func TestTCPSynSentRcvdReset(t *testing.T) {\n}\nconn.Send(t, testbench.TCP{Flags: testbench.TCPFlags(header.TCPFlagRst)})\n// Expect the connection to have transitioned SYN-RCVD to CLOSED.\n- // TODO(gvisor.dev/issue/478): Check for TCP_INFO on the dut side.\nconn.Send(t, testbench.TCP{Flags: testbench.TCPFlags(header.TCPFlagAck)})\nif _, err := conn.ExpectData(t, &testbench.TCP{Flags: testbench.TCPFlags(header.TCPFlagRst)}, nil, time.Second); err != nil {\nt.Fatalf(\"expected a TCP RST\")\n}\n+ info := dut.GetSockOptTCPInfo(t, fd)\n+ if got, want := uint32(info.State), linux.TCP_CLOSE; got != want {\n+ t.Fatalf(\"got %d want %d\", got, want)\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_inet_loopback.cc", "new_path": "test/syscalls/linux/socket_inet_loopback.cc", "diff": "@@ -472,6 +472,77 @@ TEST_P(SocketInetLoopbackTest, TCPListenClose) {\n}\n}\n+// Test the protocol state information returned by TCPINFO.\n+TEST_P(SocketInetLoopbackTest, TCPInfoState) {\n+ auto const& param = GetParam();\n+ TestAddress const& listener = param.listener;\n+ TestAddress const& connector = param.connector;\n+\n+ // Create the listening socket.\n+ FileDescriptor const listen_fd = ASSERT_NO_ERRNO_AND_VALUE(\n+ Socket(listener.family(), SOCK_STREAM, IPPROTO_TCP));\n+\n+ auto state = [](int fd) -> int {\n+ struct tcp_info opt = {};\n+ socklen_t optLen = sizeof(opt);\n+ EXPECT_THAT(getsockopt(fd, SOL_TCP, TCP_INFO, &opt, &optLen),\n+ SyscallSucceeds());\n+ return opt.tcpi_state;\n+ };\n+ ASSERT_EQ(state(listen_fd.get()), TCP_CLOSE);\n+\n+ sockaddr_storage listen_addr = listener.addr;\n+ ASSERT_THAT(\n+ bind(listen_fd.get(), AsSockAddr(&listen_addr), listener.addr_len),\n+ SyscallSucceeds());\n+ ASSERT_EQ(state(listen_fd.get()), TCP_CLOSE);\n+\n+ ASSERT_THAT(listen(listen_fd.get(), SOMAXCONN), SyscallSucceeds());\n+ ASSERT_EQ(state(listen_fd.get()), TCP_LISTEN);\n+\n+ // Get the port bound by the listening socket.\n+ socklen_t addrlen = listener.addr_len;\n+ ASSERT_THAT(getsockname(listen_fd.get(), AsSockAddr(&listen_addr), &addrlen),\n+ SyscallSucceeds());\n+ uint16_t const port =\n+ ASSERT_NO_ERRNO_AND_VALUE(AddrPort(listener.family(), listen_addr));\n+\n+ // Connect to the listening socket.\n+ FileDescriptor conn_fd = ASSERT_NO_ERRNO_AND_VALUE(\n+ Socket(connector.family(), SOCK_STREAM, IPPROTO_TCP));\n+ sockaddr_storage conn_addr = connector.addr;\n+ ASSERT_NO_ERRNO(SetAddrPort(connector.family(), &conn_addr, port));\n+ ASSERT_EQ(state(conn_fd.get()), TCP_CLOSE);\n+ ASSERT_THAT(RetryEINTR(connect)(conn_fd.get(), AsSockAddr(&conn_addr),\n+ connector.addr_len),\n+ SyscallSucceeds());\n+ ASSERT_EQ(state(conn_fd.get()), TCP_ESTABLISHED);\n+\n+ auto accepted =\n+ ASSERT_NO_ERRNO_AND_VALUE(Accept(listen_fd.get(), nullptr, nullptr));\n+ ASSERT_EQ(state(accepted.get()), TCP_ESTABLISHED);\n+\n+ ASSERT_THAT(close(accepted.release()), SyscallSucceeds());\n+\n+ struct pollfd pfd = {\n+ .fd = conn_fd.get(),\n+ .events = POLLIN | POLLRDHUP,\n+ };\n+ constexpr int kTimeout = 10000;\n+ int n = poll(&pfd, 1, kTimeout);\n+ ASSERT_GE(n, 0) << strerror(errno);\n+ ASSERT_EQ(n, 1);\n+ if (IsRunningOnGvisor()) {\n+ // TODO(gvisor.dev/issue/6015): Notify POLLRDHUP on incoming FIN.\n+ ASSERT_EQ(pfd.revents, POLLIN);\n+ } else {\n+ ASSERT_EQ(pfd.revents, POLLIN | POLLRDHUP);\n+ }\n+\n+ ASSERT_THAT(state(conn_fd.get()), TCP_CLOSE_WAIT);\n+ ASSERT_THAT(close(conn_fd.release()), SyscallSucceeds());\n+}\n+\nvoid TestHangupDuringConnect(const TestParam& param,\nvoid (*hangup)(FileDescriptor&)) {\nTestAddress const& listener = param.listener;\n" } ]
Go
Apache License 2.0
google/gvisor
Add protocol state to TCPINFO Add missing protocol state to TCPINFO struct and update packetimpact. This re-arranges the TCP state definitions to align with Linux. Fixes #478 PiperOrigin-RevId: 374996751
259,884
20.05.2021 19:40:12
25,200
28c78eb03ce95bd39ee6b8c6bea6482c9be11edf
Add Knative Services tutorial This adds a new short tutorial on how to run Knative services in gVisor by enabling the runtime class feature flag for Knative. Fixes
[ { "change_type": "MODIFY", "old_path": "g3doc/user_guide/tutorials/BUILD", "new_path": "g3doc/user_guide/tutorials/BUILD", "diff": "@@ -36,11 +36,20 @@ doc(\nweight = \"30\",\n)\n+doc(\n+ name = \"knative\",\n+ src = \"knative.md\",\n+ category = \"User Guide\",\n+ permalink = \"/docs/tutorials/knative/\",\n+ subcategory = \"Tutorials\",\n+ weight = \"40\",\n+)\n+\ndoc(\nname = \"cni\",\nsrc = \"cni.md\",\ncategory = \"User Guide\",\npermalink = \"/docs/tutorials/cni/\",\nsubcategory = \"Tutorials\",\n- weight = \"40\",\n+ weight = \"50\",\n)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "g3doc/user_guide/tutorials/knative.md", "diff": "+# Knative Services\n+\n+[Knative](https://knative.dev/) is a platform for running serverless workloads\n+on Kubernetes. This guide will show you how to run basic Knative workloads in\n+gVisor.\n+\n+## Prerequisites\n+\n+This guide assumes you have have a cluster that is capable of running gVisor\n+workloads. This could be a\n+[GKE Sandbox](https://cloud.google.com/kubernetes-engine/sandbox/) enabled\n+cluster on Google Cloud Platform or one you have set up yourself using\n+[containerd Quick Start](https://gvisor.dev/docs/user_guide/containerd/quick_start/).\n+\n+This guide will also assume you have Knative installed using\n+[Istio](https://istio.io/) as the network layer. You can follow the\n+[Knative installation guide](https://knative.dev/docs/install/install-serving-with-yaml/)\n+to install Knative.\n+\n+## Enable the RuntimeClass feature flag\n+\n+Knative allows the use of various parameters on Pods via\n+[feature flags](https://knative.dev/docs/serving/feature-flags/). We will enable\n+the\n+[runtimeClassName](https://knative.dev/docs/serving/feature-flags/#kubernetes-runtime-class)\n+feature flag to enable the use of the Kubernetes\n+[Runtime Class](https://kubernetes.io/docs/concepts/containers/runtime-class/).\n+\n+Edit the feature flags ConfigMap.\n+\n+```bash\n+kubectl edit configmap config-features -n knative-serving\n+```\n+\n+Add the `kubernetes.podspec-runtimeclassname: enabled` to the `data` field. Once\n+you are finished the ConfigMap will look something like this (minus all the\n+system fields).\n+\n+```yaml\n+apiVersion: v1\n+kind: ConfigMap\n+metadata:\n+ name: config-features\n+ namespace: knative-serving\n+ labels:\n+ serving.knative.dev/release: v0.22.0\n+data:\n+ kubernetes.podspec-runtimeclassname: enabled\n+```\n+\n+## Deploy the Service\n+\n+After you have set the Runtime Class feature flag you can now create Knative\n+services that specify a `runtimeClassName` in the spec.\n+\n+```bash\n+cat <<EOF | kubectl apply -f -\n+apiVersion: serving.knative.dev/v1\n+kind: Service\n+metadata:\n+ name: helloworld-go\n+spec:\n+ template:\n+ spec:\n+ runtimeClassName: gvisor\n+ containers:\n+ - image: gcr.io/knative-samples/helloworld-go\n+ env:\n+ - name: TARGET\n+ value: \"gVisor User\"\n+EOF\n+```\n+\n+You can see the pods running and their Runtime Class.\n+\n+```bash\n+kubectl get pods -o=custom-columns='NAME:.metadata.name,RUNTIME CLASS:.spec.runtimeClassName,STATUS:.status.phase'\n+```\n+\n+Output should look something like the following. Note that your service might\n+scale to zero. If you access it via it's URL you should get a new Pod.\n+\n+```\n+NAME RUNTIME CLASS STATUS\n+helloworld-go-00002-deployment-646c87b7f5-5v68s gvisor Running\n+```\n+\n+Congrats! Your Knative service is now running in gVisor!\n" }, { "change_type": "MODIFY", "old_path": "website/BUILD", "new_path": "website/BUILD", "diff": "@@ -165,6 +165,7 @@ docs(\n\"//g3doc/user_guide/tutorials:cni\",\n\"//g3doc/user_guide/tutorials:docker\",\n\"//g3doc/user_guide/tutorials:docker_compose\",\n+ \"//g3doc/user_guide/tutorials:knative\",\n\"//g3doc/user_guide/tutorials:kubernetes\",\n],\n)\n" } ]
Go
Apache License 2.0
google/gvisor
Add Knative Services tutorial This adds a new short tutorial on how to run Knative services in gVisor by enabling the runtime class feature flag for Knative. Fixes #3634 PiperOrigin-RevId: 374999528
259,884
20.05.2021 23:42:10
25,200
2bed0bb09661bcd72d2d3470329e88eb7b6966a0
Send SIGPIPE for closed pipes. Fixes Updates
[ { "change_type": "MODIFY", "old_path": "pkg/abi/linux/BUILD", "new_path": "pkg/abi/linux/BUILD", "diff": "@@ -15,6 +15,7 @@ go_library(\n\"bpf.go\",\n\"capability.go\",\n\"clone.go\",\n+ \"context.go\",\n\"dev.go\",\n\"elf.go\",\n\"epoll.go\",\n@@ -77,6 +78,7 @@ go_library(\ndeps = [\n\"//pkg/abi\",\n\"//pkg/bits\",\n+ \"//pkg/context\",\n\"//pkg/marshal\",\n\"//pkg/marshal/primitive\",\n],\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/abi/linux/context.go", "diff": "+// Copyright 2021 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package linux\n+\n+import (\n+ \"gvisor.dev/gvisor/pkg/context\"\n+)\n+\n+// contextID is the linux package's type for context.Context.Value keys.\n+type contextID int\n+\n+const (\n+ // CtxSignalNoInfoFunc is a Context.Value key for a function to send signals.\n+ CtxSignalNoInfoFunc contextID = iota\n+)\n+\n+// SignalNoInfoFuncFromContext returns a callback function that can be used to send a\n+// signal to the given context.\n+func SignalNoInfoFuncFromContext(ctx context.Context) func(Signal) error {\n+ if f := ctx.Value(CtxSignalNoInfoFunc); f != nil {\n+ return f.(func(Signal) error)\n+ }\n+ return nil\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/pipe/pipe_util.go", "new_path": "pkg/sentry/kernel/pipe/pipe_util.go", "diff": "@@ -86,6 +86,12 @@ func (p *Pipe) Write(ctx context.Context, src usermem.IOSequence) (int64, error)\nif n > 0 {\np.Notify(waiter.ReadableEvents)\n}\n+ if err == unix.EPIPE {\n+ // If we are returning EPIPE send SIGPIPE to the task.\n+ if sendSig := linux.SignalNoInfoFuncFromContext(ctx); sendSig != nil {\n+ sendSig(linux.SIGPIPE)\n+ }\n+ }\nreturn n, err\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/task_context.go", "new_path": "pkg/sentry/kernel/task_context.go", "diff": "@@ -17,6 +17,7 @@ package kernel\nimport (\n\"time\"\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/context\"\n\"gvisor.dev/gvisor/pkg/log\"\n\"gvisor.dev/gvisor/pkg/sentry/fs\"\n@@ -113,6 +114,10 @@ func (t *Task) contextValue(key interface{}, isTaskGoroutine bool) interface{} {\nreturn t.k.RealtimeClock()\ncase limits.CtxLimits:\nreturn t.tg.limits\n+ case linux.CtxSignalNoInfoFunc:\n+ return func(sig linux.Signal) error {\n+ return t.SendSignal(SignalInfoNoInfo(sig, t, t))\n+ }\ncase pgalloc.CtxMemoryFile:\nreturn t.k.mf\ncase pgalloc.CtxMemoryFileProvider:\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/BUILD", "new_path": "test/syscalls/linux/BUILD", "diff": "@@ -1575,6 +1575,7 @@ cc_binary(\n\"@com_google_absl//absl/time\",\ngtest,\n\"//test/util:posix_error\",\n+ \"//test/util:signal_util\",\n\"//test/util:temp_path\",\n\"//test/util:test_main\",\n\"//test/util:test_util\",\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/pipe.cc", "new_path": "test/syscalls/linux/pipe.cc", "diff": "#include <fcntl.h> /* Obtain O_* constant definitions */\n#include <linux/magic.h>\n+#include <signal.h>\n#include <sys/ioctl.h>\n#include <sys/statfs.h>\n#include <sys/uio.h>\n#include \"test/util/file_descriptor.h\"\n#include \"test/util/fs_util.h\"\n#include \"test/util/posix_error.h\"\n+#include \"test/util/signal_util.h\"\n#include \"test/util/temp_path.h\"\n#include \"test/util/test_util.h\"\n#include \"test/util/thread_util.h\"\n@@ -44,6 +46,28 @@ constexpr int kTestValue = 0x12345678;\n// Used for synchronization in race tests.\nconst absl::Duration syncDelay = absl::Seconds(2);\n+std::atomic<int> global_num_signals_received = 0;\n+void SigRecordingHandler(int signum, siginfo_t* siginfo,\n+ void* unused_ucontext) {\n+ global_num_signals_received++;\n+}\n+\n+PosixErrorOr<Cleanup> RegisterSignalHandler(int signum) {\n+ struct sigaction handler;\n+ handler.sa_sigaction = SigRecordingHandler;\n+ sigemptyset(&handler.sa_mask);\n+ handler.sa_flags = SA_SIGINFO;\n+ return ScopedSigaction(signum, handler);\n+}\n+\n+void WaitForSignalDelivery(absl::Duration timeout, int max_expected) {\n+ absl::Time wait_start = absl::Now();\n+ while (global_num_signals_received < max_expected &&\n+ absl::Now() - wait_start < timeout) {\n+ absl::SleepFor(absl::Milliseconds(10));\n+ }\n+}\n+\nstruct PipeCreator {\nstd::string name_;\n@@ -333,10 +357,16 @@ TEST_P(PipeTest, WriterSideClosesReadDataFirst) {\nTEST_P(PipeTest, ReaderSideCloses) {\nSKIP_IF(!CreateBlocking());\n+ const auto signal_cleanup =\n+ ASSERT_NO_ERRNO_AND_VALUE(RegisterSignalHandler(SIGPIPE));\n+\nASSERT_THAT(close(rfd_.release()), SyscallSucceeds());\nint buf = kTestValue;\nEXPECT_THAT(write(wfd_.get(), &buf, sizeof(buf)),\nSyscallFailsWithErrno(EPIPE));\n+\n+ WaitForSignalDelivery(absl::Seconds(1), 1);\n+ ASSERT_EQ(global_num_signals_received, 1);\n}\nTEST_P(PipeTest, CloseTwice) {\n@@ -355,6 +385,9 @@ TEST_P(PipeTest, CloseTwice) {\nTEST_P(PipeTest, BlockWriteClosed) {\nSKIP_IF(!CreateBlocking());\n+ const auto signal_cleanup =\n+ ASSERT_NO_ERRNO_AND_VALUE(RegisterSignalHandler(SIGPIPE));\n+\nabsl::Notification notify;\nScopedThread t([this, &notify]() {\nstd::vector<char> buf(Size());\n@@ -371,6 +404,10 @@ TEST_P(PipeTest, BlockWriteClosed) {\nnotify.WaitForNotification();\nASSERT_THAT(close(rfd_.release()), SyscallSucceeds());\n+\n+ WaitForSignalDelivery(absl::Seconds(1), 1);\n+ ASSERT_EQ(global_num_signals_received, 1);\n+\nt.Join();\n}\n@@ -379,6 +416,9 @@ TEST_P(PipeTest, BlockWriteClosed) {\nTEST_P(PipeTest, BlockPartialWriteClosed) {\nSKIP_IF(!CreateBlocking());\n+ const auto signal_cleanup =\n+ ASSERT_NO_ERRNO_AND_VALUE(RegisterSignalHandler(SIGPIPE));\n+\nScopedThread t([this]() {\nconst int pipe_size = Size();\nstd::vector<char> buf(2 * pipe_size);\n@@ -396,6 +436,10 @@ TEST_P(PipeTest, BlockPartialWriteClosed) {\n// Unblock the above.\nASSERT_THAT(close(rfd_.release()), SyscallSucceeds());\n+\n+ WaitForSignalDelivery(absl::Seconds(1), 2);\n+ ASSERT_EQ(global_num_signals_received, 2);\n+\nt.Join();\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Send SIGPIPE for closed pipes. Fixes #5974 Updates #161 PiperOrigin-RevId: 375024740
259,951
21.05.2021 03:29:15
25,200
9164154dea012f318c222e8142204a7dd7a5cde8
Clean-up netstack metrics descriptions
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netstack/netstack.go", "new_path": "pkg/sentry/socket/netstack/netstack.go", "diff": "@@ -77,41 +77,41 @@ func mustCreateGauge(name, description string) *tcpip.StatCounter {\n// Metrics contains metrics exported by netstack.\nvar Metrics = tcpip.Stats{\n- UnknownProtocolRcvdPackets: mustCreateMetric(\"/netstack/unknown_protocol_received_packets\", \"Number of packets received by netstack that were for an unknown or unsupported protocol.\"),\n- MalformedRcvdPackets: mustCreateMetric(\"/netstack/malformed_received_packets\", \"Number of packets received by netstack that were deemed malformed.\"),\n- DroppedPackets: mustCreateMetric(\"/netstack/dropped_packets\", \"Number of packets dropped by netstack due to full queues.\"),\n+ UnknownProtocolRcvdPackets: mustCreateMetric(\"/netstack/unknown_protocol_received_packets\", \"Number of packets received that were for an unknown or unsupported protocol.\"),\n+ MalformedRcvdPackets: mustCreateMetric(\"/netstack/malformed_received_packets\", \"Number of packets received that were deemed malformed.\"),\n+ DroppedPackets: mustCreateMetric(\"/netstack/dropped_packets\", \"Number of packets dropped due to full queues.\"),\nICMP: tcpip.ICMPStats{\nV4: tcpip.ICMPv4Stats{\nPacketsSent: tcpip.ICMPv4SentPacketStats{\nICMPv4PacketStats: tcpip.ICMPv4PacketStats{\n- EchoRequest: mustCreateMetric(\"/netstack/icmp/v4/packets_sent/echo_request\", \"Number of ICMPv4 echo request packets sent by netstack.\"),\n- EchoReply: mustCreateMetric(\"/netstack/icmp/v4/packets_sent/echo_reply\", \"Number of ICMPv4 echo reply packets sent by netstack.\"),\n- DstUnreachable: mustCreateMetric(\"/netstack/icmp/v4/packets_sent/dst_unreachable\", \"Number of ICMPv4 destination unreachable packets sent by netstack.\"),\n- SrcQuench: mustCreateMetric(\"/netstack/icmp/v4/packets_sent/src_quench\", \"Number of ICMPv4 source quench packets sent by netstack.\"),\n- Redirect: mustCreateMetric(\"/netstack/icmp/v4/packets_sent/redirect\", \"Number of ICMPv4 redirect packets sent by netstack.\"),\n- TimeExceeded: mustCreateMetric(\"/netstack/icmp/v4/packets_sent/time_exceeded\", \"Number of ICMPv4 time exceeded packets sent by netstack.\"),\n- ParamProblem: mustCreateMetric(\"/netstack/icmp/v4/packets_sent/param_problem\", \"Number of ICMPv4 parameter problem packets sent by netstack.\"),\n- Timestamp: mustCreateMetric(\"/netstack/icmp/v4/packets_sent/timestamp\", \"Number of ICMPv4 timestamp packets sent by netstack.\"),\n- TimestampReply: mustCreateMetric(\"/netstack/icmp/v4/packets_sent/timestamp_reply\", \"Number of ICMPv4 timestamp reply packets sent by netstack.\"),\n- InfoRequest: mustCreateMetric(\"/netstack/icmp/v4/packets_sent/info_request\", \"Number of ICMPv4 information request packets sent by netstack.\"),\n- InfoReply: mustCreateMetric(\"/netstack/icmp/v4/packets_sent/info_reply\", \"Number of ICMPv4 information reply packets sent by netstack.\"),\n+ EchoRequest: mustCreateMetric(\"/netstack/icmp/v4/packets_sent/echo_request\", \"Number of ICMPv4 echo request packets sent.\"),\n+ EchoReply: mustCreateMetric(\"/netstack/icmp/v4/packets_sent/echo_reply\", \"Number of ICMPv4 echo reply packets sent.\"),\n+ DstUnreachable: mustCreateMetric(\"/netstack/icmp/v4/packets_sent/dst_unreachable\", \"Number of ICMPv4 destination unreachable packets sent.\"),\n+ SrcQuench: mustCreateMetric(\"/netstack/icmp/v4/packets_sent/src_quench\", \"Number of ICMPv4 source quench packets sent.\"),\n+ Redirect: mustCreateMetric(\"/netstack/icmp/v4/packets_sent/redirect\", \"Number of ICMPv4 redirect packets sent.\"),\n+ TimeExceeded: mustCreateMetric(\"/netstack/icmp/v4/packets_sent/time_exceeded\", \"Number of ICMPv4 time exceeded packets sent.\"),\n+ ParamProblem: mustCreateMetric(\"/netstack/icmp/v4/packets_sent/param_problem\", \"Number of ICMPv4 parameter problem packets sent.\"),\n+ Timestamp: mustCreateMetric(\"/netstack/icmp/v4/packets_sent/timestamp\", \"Number of ICMPv4 timestamp packets sent.\"),\n+ TimestampReply: mustCreateMetric(\"/netstack/icmp/v4/packets_sent/timestamp_reply\", \"Number of ICMPv4 timestamp reply packets sent.\"),\n+ InfoRequest: mustCreateMetric(\"/netstack/icmp/v4/packets_sent/info_request\", \"Number of ICMPv4 information request packets sent.\"),\n+ InfoReply: mustCreateMetric(\"/netstack/icmp/v4/packets_sent/info_reply\", \"Number of ICMPv4 information reply packets sent.\"),\n},\n- Dropped: mustCreateMetric(\"/netstack/icmp/v4/packets_sent/dropped\", \"Number of ICMPv4 packets dropped by netstack due to link layer errors.\"),\n- RateLimited: mustCreateMetric(\"/netstack/icmp/v4/packets_sent/rate_limited\", \"Number of ICMPv4 packets dropped by netstack due to rate limit being exceeded.\"),\n+ Dropped: mustCreateMetric(\"/netstack/icmp/v4/packets_sent/dropped\", \"Number of ICMPv4 packets dropped due to link layer errors.\"),\n+ RateLimited: mustCreateMetric(\"/netstack/icmp/v4/packets_sent/rate_limited\", \"Number of ICMPv4 packets dropped due to rate limit being exceeded.\"),\n},\nPacketsReceived: tcpip.ICMPv4ReceivedPacketStats{\nICMPv4PacketStats: tcpip.ICMPv4PacketStats{\n- EchoRequest: mustCreateMetric(\"/netstack/icmp/v4/packets_received/echo_request\", \"Number of ICMPv4 echo request packets received by netstack.\"),\n- EchoReply: mustCreateMetric(\"/netstack/icmp/v4/packets_received/echo_reply\", \"Number of ICMPv4 echo reply packets received by netstack.\"),\n- DstUnreachable: mustCreateMetric(\"/netstack/icmp/v4/packets_received/dst_unreachable\", \"Number of ICMPv4 destination unreachable packets received by netstack.\"),\n- SrcQuench: mustCreateMetric(\"/netstack/icmp/v4/packets_received/src_quench\", \"Number of ICMPv4 source quench packets received by netstack.\"),\n- Redirect: mustCreateMetric(\"/netstack/icmp/v4/packets_received/redirect\", \"Number of ICMPv4 redirect packets received by netstack.\"),\n- TimeExceeded: mustCreateMetric(\"/netstack/icmp/v4/packets_received/time_exceeded\", \"Number of ICMPv4 time exceeded packets received by netstack.\"),\n- ParamProblem: mustCreateMetric(\"/netstack/icmp/v4/packets_received/param_problem\", \"Number of ICMPv4 parameter problem packets received by netstack.\"),\n- Timestamp: mustCreateMetric(\"/netstack/icmp/v4/packets_received/timestamp\", \"Number of ICMPv4 timestamp packets received by netstack.\"),\n- TimestampReply: mustCreateMetric(\"/netstack/icmp/v4/packets_received/timestamp_reply\", \"Number of ICMPv4 timestamp reply packets received by netstack.\"),\n- InfoRequest: mustCreateMetric(\"/netstack/icmp/v4/packets_received/info_request\", \"Number of ICMPv4 information request packets received by netstack.\"),\n- InfoReply: mustCreateMetric(\"/netstack/icmp/v4/packets_received/info_reply\", \"Number of ICMPv4 information reply packets received by netstack.\"),\n+ EchoRequest: mustCreateMetric(\"/netstack/icmp/v4/packets_received/echo_request\", \"Number of ICMPv4 echo request packets received.\"),\n+ EchoReply: mustCreateMetric(\"/netstack/icmp/v4/packets_received/echo_reply\", \"Number of ICMPv4 echo reply packets received.\"),\n+ DstUnreachable: mustCreateMetric(\"/netstack/icmp/v4/packets_received/dst_unreachable\", \"Number of ICMPv4 destination unreachable packets received.\"),\n+ SrcQuench: mustCreateMetric(\"/netstack/icmp/v4/packets_received/src_quench\", \"Number of ICMPv4 source quench packets received.\"),\n+ Redirect: mustCreateMetric(\"/netstack/icmp/v4/packets_received/redirect\", \"Number of ICMPv4 redirect packets received.\"),\n+ TimeExceeded: mustCreateMetric(\"/netstack/icmp/v4/packets_received/time_exceeded\", \"Number of ICMPv4 time exceeded packets received.\"),\n+ ParamProblem: mustCreateMetric(\"/netstack/icmp/v4/packets_received/param_problem\", \"Number of ICMPv4 parameter problem packets received.\"),\n+ Timestamp: mustCreateMetric(\"/netstack/icmp/v4/packets_received/timestamp\", \"Number of ICMPv4 timestamp packets received.\"),\n+ TimestampReply: mustCreateMetric(\"/netstack/icmp/v4/packets_received/timestamp_reply\", \"Number of ICMPv4 timestamp reply packets received.\"),\n+ InfoRequest: mustCreateMetric(\"/netstack/icmp/v4/packets_received/info_request\", \"Number of ICMPv4 information request packets received.\"),\n+ InfoReply: mustCreateMetric(\"/netstack/icmp/v4/packets_received/info_reply\", \"Number of ICMPv4 information reply packets received.\"),\n},\nInvalid: mustCreateMetric(\"/netstack/icmp/v4/packets_received/invalid\", \"Number of ICMPv4 packets received that the transport layer could not parse.\"),\n},\n@@ -119,40 +119,40 @@ var Metrics = tcpip.Stats{\nV6: tcpip.ICMPv6Stats{\nPacketsSent: tcpip.ICMPv6SentPacketStats{\nICMPv6PacketStats: tcpip.ICMPv6PacketStats{\n- EchoRequest: mustCreateMetric(\"/netstack/icmp/v6/packets_sent/echo_request\", \"Number of ICMPv6 echo request packets sent by netstack.\"),\n- EchoReply: mustCreateMetric(\"/netstack/icmp/v6/packets_sent/echo_reply\", \"Number of ICMPv6 echo reply packets sent by netstack.\"),\n- DstUnreachable: mustCreateMetric(\"/netstack/icmp/v6/packets_sent/dst_unreachable\", \"Number of ICMPv6 destination unreachable packets sent by netstack.\"),\n- PacketTooBig: mustCreateMetric(\"/netstack/icmp/v6/packets_sent/packet_too_big\", \"Number of ICMPv6 packet too big packets sent by netstack.\"),\n- TimeExceeded: mustCreateMetric(\"/netstack/icmp/v6/packets_sent/time_exceeded\", \"Number of ICMPv6 time exceeded packets sent by netstack.\"),\n- ParamProblem: mustCreateMetric(\"/netstack/icmp/v6/packets_sent/param_problem\", \"Number of ICMPv6 parameter problem packets sent by netstack.\"),\n- RouterSolicit: mustCreateMetric(\"/netstack/icmp/v6/packets_sent/router_solicit\", \"Number of ICMPv6 router solicit packets sent by netstack.\"),\n- RouterAdvert: mustCreateMetric(\"/netstack/icmp/v6/packets_sent/router_advert\", \"Number of ICMPv6 router advert packets sent by netstack.\"),\n- NeighborSolicit: mustCreateMetric(\"/netstack/icmp/v6/packets_sent/neighbor_solicit\", \"Number of ICMPv6 neighbor solicit packets sent by netstack.\"),\n- NeighborAdvert: mustCreateMetric(\"/netstack/icmp/v6/packets_sent/neighbor_advert\", \"Number of ICMPv6 neighbor advert packets sent by netstack.\"),\n- RedirectMsg: mustCreateMetric(\"/netstack/icmp/v6/packets_sent/redirect_msg\", \"Number of ICMPv6 redirect message packets sent by netstack.\"),\n- MulticastListenerQuery: mustCreateMetric(\"/netstack/icmp/v6/packets_sent/multicast_listener_query\", \"Number of ICMPv6 multicast listener query packets sent by netstack.\"),\n- MulticastListenerReport: mustCreateMetric(\"/netstack/icmp/v6/packets_sent/multicast_listener_report\", \"Number of ICMPv6 multicast listener report packets sent by netstack.\"),\n- MulticastListenerDone: mustCreateMetric(\"/netstack/icmp/v6/packets_sent/multicast_listener_done\", \"Number of ICMPv6 multicast listener done packets sent by netstack.\"),\n+ EchoRequest: mustCreateMetric(\"/netstack/icmp/v6/packets_sent/echo_request\", \"Number of ICMPv6 echo request packets sent.\"),\n+ EchoReply: mustCreateMetric(\"/netstack/icmp/v6/packets_sent/echo_reply\", \"Number of ICMPv6 echo reply packets sent.\"),\n+ DstUnreachable: mustCreateMetric(\"/netstack/icmp/v6/packets_sent/dst_unreachable\", \"Number of ICMPv6 destination unreachable packets sent.\"),\n+ PacketTooBig: mustCreateMetric(\"/netstack/icmp/v6/packets_sent/packet_too_big\", \"Number of ICMPv6 packet too big packets sent.\"),\n+ TimeExceeded: mustCreateMetric(\"/netstack/icmp/v6/packets_sent/time_exceeded\", \"Number of ICMPv6 time exceeded packets sent.\"),\n+ ParamProblem: mustCreateMetric(\"/netstack/icmp/v6/packets_sent/param_problem\", \"Number of ICMPv6 parameter problem packets sent.\"),\n+ RouterSolicit: mustCreateMetric(\"/netstack/icmp/v6/packets_sent/router_solicit\", \"Number of ICMPv6 router solicit packets sent.\"),\n+ RouterAdvert: mustCreateMetric(\"/netstack/icmp/v6/packets_sent/router_advert\", \"Number of ICMPv6 router advert packets sent.\"),\n+ NeighborSolicit: mustCreateMetric(\"/netstack/icmp/v6/packets_sent/neighbor_solicit\", \"Number of ICMPv6 neighbor solicit packets sent.\"),\n+ NeighborAdvert: mustCreateMetric(\"/netstack/icmp/v6/packets_sent/neighbor_advert\", \"Number of ICMPv6 neighbor advert packets sent.\"),\n+ RedirectMsg: mustCreateMetric(\"/netstack/icmp/v6/packets_sent/redirect_msg\", \"Number of ICMPv6 redirect message packets sent.\"),\n+ MulticastListenerQuery: mustCreateMetric(\"/netstack/icmp/v6/packets_sent/multicast_listener_query\", \"Number of ICMPv6 multicast listener query packets sent.\"),\n+ MulticastListenerReport: mustCreateMetric(\"/netstack/icmp/v6/packets_sent/multicast_listener_report\", \"Number of ICMPv6 multicast listener report packets sent.\"),\n+ MulticastListenerDone: mustCreateMetric(\"/netstack/icmp/v6/packets_sent/multicast_listener_done\", \"Number of ICMPv6 multicast listener done packets sent.\"),\n},\n- Dropped: mustCreateMetric(\"/netstack/icmp/v6/packets_sent/dropped\", \"Number of ICMPv6 packets dropped by netstack due to link layer errors.\"),\n- RateLimited: mustCreateMetric(\"/netstack/icmp/v6/packets_sent/rate_limited\", \"Number of ICMPv6 packets dropped by netstack due to rate limit being exceeded.\"),\n+ Dropped: mustCreateMetric(\"/netstack/icmp/v6/packets_sent/dropped\", \"Number of ICMPv6 packets dropped due to link layer errors.\"),\n+ RateLimited: mustCreateMetric(\"/netstack/icmp/v6/packets_sent/rate_limited\", \"Number of ICMPv6 packets dropped due to rate limit being exceeded.\"),\n},\nPacketsReceived: tcpip.ICMPv6ReceivedPacketStats{\nICMPv6PacketStats: tcpip.ICMPv6PacketStats{\n- EchoRequest: mustCreateMetric(\"/netstack/icmp/v6/packets_received/echo_request\", \"Number of ICMPv6 echo request packets received by netstack.\"),\n- EchoReply: mustCreateMetric(\"/netstack/icmp/v6/packets_received/echo_reply\", \"Number of ICMPv6 echo reply packets received by netstack.\"),\n- DstUnreachable: mustCreateMetric(\"/netstack/icmp/v6/packets_received/dst_unreachable\", \"Number of ICMPv6 destination unreachable packets received by netstack.\"),\n- PacketTooBig: mustCreateMetric(\"/netstack/icmp/v6/packets_received/packet_too_big\", \"Number of ICMPv6 packet too big packets received by netstack.\"),\n- TimeExceeded: mustCreateMetric(\"/netstack/icmp/v6/packets_received/time_exceeded\", \"Number of ICMPv6 time exceeded packets received by netstack.\"),\n- ParamProblem: mustCreateMetric(\"/netstack/icmp/v6/packets_received/param_problem\", \"Number of ICMPv6 parameter problem packets received by netstack.\"),\n- RouterSolicit: mustCreateMetric(\"/netstack/icmp/v6/packets_received/router_solicit\", \"Number of ICMPv6 router solicit packets received by netstack.\"),\n- RouterAdvert: mustCreateMetric(\"/netstack/icmp/v6/packets_received/router_advert\", \"Number of ICMPv6 router advert packets received by netstack.\"),\n- NeighborSolicit: mustCreateMetric(\"/netstack/icmp/v6/packets_received/neighbor_solicit\", \"Number of ICMPv6 neighbor solicit packets received by netstack.\"),\n- NeighborAdvert: mustCreateMetric(\"/netstack/icmp/v6/packets_received/neighbor_advert\", \"Number of ICMPv6 neighbor advert packets received by netstack.\"),\n- RedirectMsg: mustCreateMetric(\"/netstack/icmp/v6/packets_received/redirect_msg\", \"Number of ICMPv6 redirect message packets received by netstack.\"),\n- MulticastListenerQuery: mustCreateMetric(\"/netstack/icmp/v6/packets_received/multicast_listener_query\", \"Number of ICMPv6 multicast listener query packets received by netstack.\"),\n- MulticastListenerReport: mustCreateMetric(\"/netstack/icmp/v6/packets_received/multicast_listener_report\", \"Number of ICMPv6 multicast listener report packets sent by netstack.\"),\n- MulticastListenerDone: mustCreateMetric(\"/netstack/icmp/v6/packets_received/multicast_listener_done\", \"Number of ICMPv6 multicast listener done packets sent by netstack.\"),\n+ EchoRequest: mustCreateMetric(\"/netstack/icmp/v6/packets_received/echo_request\", \"Number of ICMPv6 echo request packets received.\"),\n+ EchoReply: mustCreateMetric(\"/netstack/icmp/v6/packets_received/echo_reply\", \"Number of ICMPv6 echo reply packets received.\"),\n+ DstUnreachable: mustCreateMetric(\"/netstack/icmp/v6/packets_received/dst_unreachable\", \"Number of ICMPv6 destination unreachable packets received.\"),\n+ PacketTooBig: mustCreateMetric(\"/netstack/icmp/v6/packets_received/packet_too_big\", \"Number of ICMPv6 packet too big packets received.\"),\n+ TimeExceeded: mustCreateMetric(\"/netstack/icmp/v6/packets_received/time_exceeded\", \"Number of ICMPv6 time exceeded packets received.\"),\n+ ParamProblem: mustCreateMetric(\"/netstack/icmp/v6/packets_received/param_problem\", \"Number of ICMPv6 parameter problem packets received.\"),\n+ RouterSolicit: mustCreateMetric(\"/netstack/icmp/v6/packets_received/router_solicit\", \"Number of ICMPv6 router solicit packets received.\"),\n+ RouterAdvert: mustCreateMetric(\"/netstack/icmp/v6/packets_received/router_advert\", \"Number of ICMPv6 router advert packets received.\"),\n+ NeighborSolicit: mustCreateMetric(\"/netstack/icmp/v6/packets_received/neighbor_solicit\", \"Number of ICMPv6 neighbor solicit packets received.\"),\n+ NeighborAdvert: mustCreateMetric(\"/netstack/icmp/v6/packets_received/neighbor_advert\", \"Number of ICMPv6 neighbor advert packets received.\"),\n+ RedirectMsg: mustCreateMetric(\"/netstack/icmp/v6/packets_received/redirect_msg\", \"Number of ICMPv6 redirect message packets received.\"),\n+ MulticastListenerQuery: mustCreateMetric(\"/netstack/icmp/v6/packets_received/multicast_listener_query\", \"Number of ICMPv6 multicast listener query packets received.\"),\n+ MulticastListenerReport: mustCreateMetric(\"/netstack/icmp/v6/packets_received/multicast_listener_report\", \"Number of ICMPv6 multicast listener report packets sent.\"),\n+ MulticastListenerDone: mustCreateMetric(\"/netstack/icmp/v6/packets_received/multicast_listener_done\", \"Number of ICMPv6 multicast listener done packets sent.\"),\n},\nUnrecognized: mustCreateMetric(\"/netstack/icmp/v6/packets_received/unrecognized\", \"Number of ICMPv6 packets received that the transport layer does not know how to parse.\"),\nInvalid: mustCreateMetric(\"/netstack/icmp/v6/packets_received/invalid\", \"Number of ICMPv6 packets received that the transport layer could not parse.\"),\n@@ -163,23 +163,23 @@ var Metrics = tcpip.Stats{\nIGMP: tcpip.IGMPStats{\nPacketsSent: tcpip.IGMPSentPacketStats{\nIGMPPacketStats: tcpip.IGMPPacketStats{\n- MembershipQuery: mustCreateMetric(\"/netstack/igmp/packets_sent/membership_query\", \"Number of IGMP Membership Query messages sent by netstack.\"),\n- V1MembershipReport: mustCreateMetric(\"/netstack/igmp/packets_sent/v1_membership_report\", \"Number of IGMPv1 Membership Report messages sent by netstack.\"),\n- V2MembershipReport: mustCreateMetric(\"/netstack/igmp/packets_sent/v2_membership_report\", \"Number of IGMPv2 Membership Report messages sent by netstack.\"),\n- LeaveGroup: mustCreateMetric(\"/netstack/igmp/packets_sent/leave_group\", \"Number of IGMP Leave Group messages sent by netstack.\"),\n+ MembershipQuery: mustCreateMetric(\"/netstack/igmp/packets_sent/membership_query\", \"Number of IGMP Membership Query messages sent.\"),\n+ V1MembershipReport: mustCreateMetric(\"/netstack/igmp/packets_sent/v1_membership_report\", \"Number of IGMPv1 Membership Report messages sent.\"),\n+ V2MembershipReport: mustCreateMetric(\"/netstack/igmp/packets_sent/v2_membership_report\", \"Number of IGMPv2 Membership Report messages sent.\"),\n+ LeaveGroup: mustCreateMetric(\"/netstack/igmp/packets_sent/leave_group\", \"Number of IGMP Leave Group messages sent.\"),\n},\n- Dropped: mustCreateMetric(\"/netstack/igmp/packets_sent/dropped\", \"Number of IGMP packets dropped by netstack due to link layer errors.\"),\n+ Dropped: mustCreateMetric(\"/netstack/igmp/packets_sent/dropped\", \"Number of IGMP packets dropped due to link layer errors.\"),\n},\nPacketsReceived: tcpip.IGMPReceivedPacketStats{\nIGMPPacketStats: tcpip.IGMPPacketStats{\n- MembershipQuery: mustCreateMetric(\"/netstack/igmp/packets_received/membership_query\", \"Number of IGMP Membership Query messages received by netstack.\"),\n- V1MembershipReport: mustCreateMetric(\"/netstack/igmp/packets_received/v1_membership_report\", \"Number of IGMPv1 Membership Report messages received by netstack.\"),\n- V2MembershipReport: mustCreateMetric(\"/netstack/igmp/packets_received/v2_membership_report\", \"Number of IGMPv2 Membership Report messages received by netstack.\"),\n- LeaveGroup: mustCreateMetric(\"/netstack/igmp/packets_received/leave_group\", \"Number of IGMP Leave Group messages received by netstack.\"),\n+ MembershipQuery: mustCreateMetric(\"/netstack/igmp/packets_received/membership_query\", \"Number of IGMP Membership Query messages received.\"),\n+ V1MembershipReport: mustCreateMetric(\"/netstack/igmp/packets_received/v1_membership_report\", \"Number of IGMPv1 Membership Report messages received.\"),\n+ V2MembershipReport: mustCreateMetric(\"/netstack/igmp/packets_received/v2_membership_report\", \"Number of IGMPv2 Membership Report messages received.\"),\n+ LeaveGroup: mustCreateMetric(\"/netstack/igmp/packets_received/leave_group\", \"Number of IGMP Leave Group messages received.\"),\n},\n- Invalid: mustCreateMetric(\"/netstack/igmp/packets_received/invalid\", \"Number of IGMP packets received by netstack that could not be parsed.\"),\n+ Invalid: mustCreateMetric(\"/netstack/igmp/packets_received/invalid\", \"Number of IGMP packets received that could not be parsed.\"),\nChecksumErrors: mustCreateMetric(\"/netstack/igmp/packets_received/checksum_errors\", \"Number of received IGMP packets with bad checksums.\"),\n- Unrecognized: mustCreateMetric(\"/netstack/igmp/packets_received/unrecognized\", \"Number of unrecognized IGMP packets received by netstack.\"),\n+ Unrecognized: mustCreateMetric(\"/netstack/igmp/packets_received/unrecognized\", \"Number of unrecognized IGMP packets received.\"),\n},\n},\nIP: tcpip.IPStats{\n" } ]
Go
Apache License 2.0
google/gvisor
Clean-up netstack metrics descriptions PiperOrigin-RevId: 375051638
260,007
21.05.2021 20:17:34
25,200
f77a24966e75271a30ee5a4eefdb90edc2eacb9e
Make many tests build with NDK. Not all the tests build yet, but many of them do now.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/BUILD", "new_path": "test/syscalls/linux/BUILD", "diff": "@@ -1517,7 +1517,8 @@ cc_binary(\ncc_binary(\nname = \"partial_bad_buffer_test\",\ntestonly = 1,\n- srcs = [\"partial_bad_buffer.cc\"],\n+ # Android does not support preadv or pwritev in r22.\n+ srcs = select_system(linux = [\"partial_bad_buffer.cc\"]),\nlinkstatic = 1,\ndeps = [\n\":socket_test_util\",\n@@ -3674,7 +3675,8 @@ cc_binary(\ncc_binary(\nname = \"sync_test\",\ntestonly = 1,\n- srcs = [\"sync.cc\"],\n+ # Android does not support syncfs in r22.\n+ srcs = select_system(linux = [\"sync.cc\"]),\nlinkstatic = 1,\ndeps = [\ngtest,\n@@ -3970,7 +3972,8 @@ cc_binary(\ncc_binary(\nname = \"utimes_test\",\ntestonly = 1,\n- srcs = [\"utimes.cc\"],\n+ # Android does not support futimesat in r22.\n+ srcs = select_system(linux = [\"utimes.cc\"]),\nlinkstatic = 1,\ndeps = [\n\"//test/util:file_descriptor\",\n@@ -4086,7 +4089,8 @@ cc_binary(\ncc_binary(\nname = \"semaphore_test\",\ntestonly = 1,\n- srcs = [\"semaphore.cc\"],\n+ # Android does not support XSI semaphores in r22.\n+ srcs = select_system(linux = [\"semaphore.cc\"]),\nlinkstatic = 1,\ndeps = [\n\"//test/util:capability_util\",\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/epoll.cc", "new_path": "test/syscalls/linux/epoll.cc", "diff": "@@ -230,6 +230,8 @@ TEST(EpollTest, WaitThenUnblock) {\nEXPECT_THAT(pthread_detach(thread), SyscallSucceeds());\n}\n+#ifndef ANDROID // Android does not support pthread_cancel\n+\nvoid sighandler(int s) {}\nvoid* signaler(void* arg) {\n@@ -272,6 +274,8 @@ TEST(EpollTest, UnblockWithSignal) {\nEXPECT_THAT(pthread_detach(thread), SyscallSucceeds());\n}\n+#endif // ANDROID\n+\nTEST(EpollTest, TimeoutNoFds) {\nauto epollfd = ASSERT_NO_ERRNO_AND_VALUE(NewEpollFD());\nstruct epoll_event result[kFDsPerEpoll];\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/exec_state_workload.cc", "new_path": "test/syscalls/linux/exec_state_workload.cc", "diff": "#include \"absl/strings/numbers.h\"\n+#ifndef ANDROID // Conflicts with existing operator<< on Android.\n+\n// Pretty-print a sigset_t.\nstd::ostream& operator<<(std::ostream& out, const sigset_t& s) {\nout << \"{ \";\n@@ -40,6 +42,8 @@ std::ostream& operator<<(std::ostream& out, const sigset_t& s) {\nreturn out;\n}\n+#endif\n+\n// Verify that the signo handler is handler.\nint CheckSigHandler(uint32_t signo, uintptr_t handler) {\nstruct sigaction sa;\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": "@@ -174,13 +174,21 @@ SocketKind IPv6TCPUnboundSocket(int type) {\nPosixError IfAddrHelper::Load() {\nRelease();\n+#ifndef ANDROID\nRETURN_ERROR_IF_SYSCALL_FAIL(getifaddrs(&ifaddr_));\n+#else\n+ // Android does not support getifaddrs in r22.\n+ return PosixError(ENOSYS, \"getifaddrs\");\n+#endif\nreturn NoError();\n}\nvoid IfAddrHelper::Release() {\nif (ifaddr_) {\n+#ifndef ANDROID\n+ // Android does not support freeifaddrs in r22.\nfreeifaddrs(ifaddr_);\n+#endif\nifaddr_ = nullptr;\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/lseek.cc", "new_path": "test/syscalls/linux/lseek.cc", "diff": "@@ -150,7 +150,7 @@ TEST(LseekTest, SeekCurrentDir) {\n// From include/linux/fs.h.\nconstexpr loff_t MAX_LFS_FILESIZE = 0x7fffffffffffffff;\n- char* dir = get_current_dir_name();\n+ char* dir = getcwd(NULL, 0);\nconst FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(Open(dir, O_RDONLY));\nASSERT_THAT(lseek(fd.get(), 0, SEEK_CUR), SyscallSucceeds());\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/pipe.cc", "new_path": "test/syscalls/linux/pipe.cc", "diff": "@@ -291,6 +291,9 @@ TEST_P(PipeTest, Seek) {\n}\n}\n+#ifndef ANDROID\n+// Android does not support preadv or pwritev in r22.\n+\nTEST_P(PipeTest, OffsetCalls) {\nSKIP_IF(!CreateBlocking());\n@@ -307,6 +310,8 @@ TEST_P(PipeTest, OffsetCalls) {\nEXPECT_THAT(pwritev(rfd_.get(), &iov, 1, 0), SyscallFailsWithErrno(ESPIPE));\n}\n+#endif // ANDROID\n+\nTEST_P(PipeTest, WriterSideCloses) {\nSKIP_IF(!CreateBlocking());\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/read.cc", "new_path": "test/syscalls/linux/read.cc", "diff": "@@ -157,7 +157,8 @@ TEST_F(ReadTest, PartialReadSIGSEGV) {\n.iov_len = size,\n},\n};\n- EXPECT_THAT(preadv(fd.get(), iov, ABSL_ARRAYSIZE(iov), 0),\n+ EXPECT_THAT(lseek(fd.get(), 0, SEEK_SET), SyscallSucceeds());\n+ EXPECT_THAT(readv(fd.get(), iov, ABSL_ARRAYSIZE(iov)),\nSyscallSucceedsWithValue(size));\n}\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_bind_to_device_util.cc", "new_path": "test/syscalls/linux/socket_bind_to_device_util.cc", "diff": "@@ -58,8 +58,10 @@ PosixErrorOr<std::unique_ptr<Tunnel>> Tunnel::New(string tunnel_name) {\n}\nstd::unordered_set<string> GetInterfaceNames() {\n- struct if_nameindex* interfaces = if_nameindex();\nstd::unordered_set<string> names;\n+#ifndef ANDROID\n+ // Android does not support if_nameindex in r22.\n+ struct if_nameindex* interfaces = if_nameindex();\nif (interfaces == nullptr) {\nreturn names;\n}\n@@ -68,6 +70,7 @@ std::unordered_set<string> GetInterfaceNames() {\nnames.insert(interface->if_name);\n}\nif_freenameindex(interfaces);\n+#endif\nreturn names;\n}\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_ipv6_udp_unbound_external_networking.cc", "new_path": "test/syscalls/linux/socket_ipv6_udp_unbound_external_networking.cc", "diff": "@@ -38,8 +38,8 @@ TEST_P(IPv6UDPUnboundExternalNetworkingSocketTest, TestJoinLeaveMulticast) {\nipv6_mreq group_req = {\n.ipv6mr_multiaddr =\nreinterpret_cast<sockaddr_in6*>(&multicast_addr.addr)->sin6_addr,\n- .ipv6mr_interface =\n- (unsigned int)ASSERT_NO_ERRNO_AND_VALUE(InterfaceIndex(\"lo\")),\n+ .ipv6mr_interface = static_cast<decltype(ipv6_mreq::ipv6mr_interface)>(\n+ ASSERT_NO_ERRNO_AND_VALUE(InterfaceIndex(\"lo\"))),\n};\nASSERT_THAT(setsockopt(receiver->get(), IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP,\n&group_req, sizeof(group_req)),\n" } ]
Go
Apache License 2.0
google/gvisor
Make many tests build with NDK. Not all the tests build yet, but many of them do now. PiperOrigin-RevId: 375209824
259,891
25.05.2021 13:19:23
25,200
f7bc60603e32d630598eca4663dfd9d03be5802f
setgid directories for VFS1 tmpfs, overlayfs, and goferfs
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/attr.go", "new_path": "pkg/sentry/fs/attr.go", "diff": "@@ -478,6 +478,20 @@ func (f FilePermissions) AnyRead() bool {\nreturn f.User.Read || f.Group.Read || f.Other.Read\n}\n+// HasSetUIDOrGID returns true if either the setuid or setgid bit is set.\n+func (f FilePermissions) HasSetUIDOrGID() bool {\n+ return f.SetUID || f.SetGID\n+}\n+\n+// DropSetUIDAndMaybeGID turns off setuid, and turns off setgid if f allows\n+// group execution.\n+func (f *FilePermissions) DropSetUIDAndMaybeGID() {\n+ f.SetUID = false\n+ if f.Group.Execute {\n+ f.SetGID = false\n+ }\n+}\n+\n// FileOwner represents ownership of a file.\n//\n// +stateify savable\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/dev/dev.go", "new_path": "pkg/sentry/fs/dev/dev.go", "diff": "package dev\nimport (\n+ \"fmt\"\n\"math\"\n\"gvisor.dev/gvisor/pkg/context\"\n@@ -90,6 +91,11 @@ func newSymlink(ctx context.Context, target string, msrc *fs.MountSource) *fs.In\n// New returns the root node of a device filesystem.\nfunc New(ctx context.Context, msrc *fs.MountSource) *fs.Inode {\n+ shm, err := tmpfs.NewDir(ctx, nil, fs.RootOwner, fs.FilePermsFromMode(0777), msrc, nil /* parent */)\n+ if err != nil {\n+ panic(fmt.Sprintf(\"tmpfs.NewDir failed: %v\", err))\n+ }\n+\ncontents := map[string]*fs.Inode{\n\"fd\": newSymlink(ctx, \"/proc/self/fd\", msrc),\n\"stdin\": newSymlink(ctx, \"/proc/self/fd/0\", msrc),\n@@ -108,7 +114,7 @@ func New(ctx context.Context, msrc *fs.MountSource) *fs.Inode {\n\"random\": newMemDevice(ctx, newRandomDevice(ctx, fs.RootOwner, 0444), msrc, randomDevMinor),\n\"urandom\": newMemDevice(ctx, newRandomDevice(ctx, fs.RootOwner, 0444), msrc, urandomDevMinor),\n- \"shm\": tmpfs.NewDir(ctx, nil, fs.RootOwner, fs.FilePermsFromMode(0777), msrc),\n+ \"shm\": shm,\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/fsutil/host_mappable.go", "new_path": "pkg/sentry/fs/fsutil/host_mappable.go", "diff": "@@ -155,12 +155,20 @@ func (h *HostMappable) DecRef(fr memmap.FileRange) {\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+func (h *HostMappable) Truncate(ctx context.Context, newSize int64, uattr fs.UnstableAttr) error {\nh.truncateMu.Lock()\ndefer h.truncateMu.Unlock()\nmask := fs.AttrMask{Size: true}\nattr := fs.UnstableAttr{Size: newSize}\n+\n+ // Truncating a file clears privilege bits.\n+ if uattr.Perms.HasSetUIDOrGID() {\n+ mask.Perms = true\n+ attr.Perms = uattr.Perms\n+ attr.Perms.DropSetUIDAndMaybeGID()\n+ }\n+\nif err := h.backingFile.SetMaskedAttributes(ctx, mask, attr, false); err != nil {\nreturn err\n}\n@@ -193,10 +201,17 @@ func (h *HostMappable) Allocate(ctx context.Context, offset int64, length int64)\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+func (h *HostMappable) Write(ctx context.Context, src usermem.IOSequence, offset int64, uattr fs.UnstableAttr) (int64, error) {\nh.truncateMu.RLock()\n+ defer h.truncateMu.RUnlock()\nn, err := src.CopyInTo(ctx, &writer{ctx: ctx, hostMappable: h, off: offset})\n- h.truncateMu.RUnlock()\n+ if n > 0 && uattr.Perms.HasSetUIDOrGID() {\n+ mask := fs.AttrMask{Perms: true}\n+ uattr.Perms.DropSetUIDAndMaybeGID()\n+ if err := h.backingFile.SetMaskedAttributes(ctx, mask, uattr, false); err != nil {\n+ return n, err\n+ }\n+ }\nreturn n, err\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/fsutil/inode_cached.go", "new_path": "pkg/sentry/fs/fsutil/inode_cached.go", "diff": "@@ -310,6 +310,12 @@ func (c *CachingInodeOperations) Truncate(ctx context.Context, inode *fs.Inode,\nnow := ktime.NowFromContext(ctx)\nmasked := fs.AttrMask{Size: true}\nattr := fs.UnstableAttr{Size: size}\n+ if c.attr.Perms.HasSetUIDOrGID() {\n+ masked.Perms = true\n+ attr.Perms = c.attr.Perms\n+ attr.Perms.DropSetUIDAndMaybeGID()\n+ c.attr.Perms = attr.Perms\n+ }\nif err := c.backingFile.SetMaskedAttributes(ctx, masked, attr, false); err != nil {\nc.dataMu.Unlock()\nreturn err\n@@ -685,13 +691,14 @@ func (rw *inodeReadWriter) ReadToBlocks(dsts safemem.BlockSeq) (uint64, error) {\nreturn done, nil\n}\n-// maybeGrowFile grows the file's size if data has been written past the old\n-// size.\n+// maybeUpdateAttrs updates the file's attributes after a write. It updates\n+// size if data has been written past the old size, and setuid/setgid if any\n+// bytes were written.\n//\n// Preconditions:\n// * rw.c.attrMu must be locked.\n// * rw.c.dataMu must be locked.\n-func (rw *inodeReadWriter) maybeGrowFile() {\n+func (rw *inodeReadWriter) maybeUpdateAttrs(nwritten uint64) {\n// If the write ends beyond the file's previous size, it causes the\n// file to grow.\nif rw.offset > rw.c.attr.Size {\n@@ -705,6 +712,12 @@ func (rw *inodeReadWriter) maybeGrowFile() {\nrw.c.attr.Usage = rw.offset\nrw.c.dirtyAttr.Usage = true\n}\n+\n+ // If bytes were written, ensure setuid and setgid are cleared.\n+ if nwritten > 0 && rw.c.attr.Perms.HasSetUIDOrGID() {\n+ rw.c.dirtyAttr.Perms = true\n+ rw.c.attr.Perms.DropSetUIDAndMaybeGID()\n+ }\n}\n// WriteFromBlocks implements safemem.Writer.WriteFromBlocks.\n@@ -732,7 +745,7 @@ func (rw *inodeReadWriter) WriteFromBlocks(srcs safemem.BlockSeq) (uint64, error\nsegMR := seg.Range().Intersect(mr)\nims, err := mf.MapInternal(seg.FileRangeOf(segMR), hostarch.Write)\nif err != nil {\n- rw.maybeGrowFile()\n+ rw.maybeUpdateAttrs(done)\nrw.c.dataMu.Unlock()\nreturn done, err\n}\n@@ -744,7 +757,7 @@ func (rw *inodeReadWriter) WriteFromBlocks(srcs safemem.BlockSeq) (uint64, error\nsrcs = srcs.DropFirst64(n)\nrw.c.dirty.MarkDirty(segMR)\nif err != nil {\n- rw.maybeGrowFile()\n+ rw.maybeUpdateAttrs(done)\nrw.c.dataMu.Unlock()\nreturn done, err\n}\n@@ -765,7 +778,7 @@ func (rw *inodeReadWriter) WriteFromBlocks(srcs safemem.BlockSeq) (uint64, error\nsrcs = srcs.DropFirst64(n)\n// Partial writes are fine. But we must stop writing.\nif n != src.NumBytes() || err != nil {\n- rw.maybeGrowFile()\n+ rw.maybeUpdateAttrs(done)\nrw.c.dataMu.Unlock()\nreturn done, err\n}\n@@ -774,7 +787,7 @@ func (rw *inodeReadWriter) WriteFromBlocks(srcs safemem.BlockSeq) (uint64, error\nseg, gap = gap.NextSegment(), FileRangeGapIterator{}\n}\n}\n- rw.maybeGrowFile()\n+ rw.maybeUpdateAttrs(done)\nrw.c.dataMu.Unlock()\nreturn done, nil\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/gofer/file.go", "new_path": "pkg/sentry/fs/gofer/file.go", "diff": "@@ -237,10 +237,20 @@ func (f *fileOperations) Write(ctx context.Context, file *fs.File, src usermem.I\n// and availability of a host-mappable FD.\nif f.inodeOperations.session().cachePolicy.useCachingInodeOps(file.Dirent.Inode) {\nn, err = f.inodeOperations.cachingInodeOps.Write(ctx, src, offset)\n- } else if f.inodeOperations.fileState.hostMappable != nil {\n- n, err = f.inodeOperations.fileState.hostMappable.Write(ctx, src, offset)\n+ } else {\n+ uattr, e := f.UnstableAttr(ctx, file)\n+ if e != nil {\n+ return 0, e\n+ }\n+ if f.inodeOperations.fileState.hostMappable != nil {\n+ n, err = f.inodeOperations.fileState.hostMappable.Write(ctx, src, offset, uattr)\n} else {\nn, err = src.CopyInTo(ctx, f.handles.readWriterAt(ctx, offset))\n+ if n > 0 && uattr.Perms.HasSetUIDOrGID() {\n+ uattr.Perms.DropSetUIDAndMaybeGID()\n+ f.inodeOperations.SetPermissions(ctx, file.Dirent.Inode, uattr.Perms)\n+ }\n+ }\n}\nif n == 0 {\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/gofer/inode.go", "new_path": "pkg/sentry/fs/gofer/inode.go", "diff": "@@ -600,11 +600,25 @@ 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+\n+ uattr, err := i.fileState.unstableAttr(ctx)\n+ if err != nil {\n+ return err\n+ }\n+\nif i.session().cachePolicy == cacheRemoteRevalidating {\n- return i.fileState.hostMappable.Truncate(ctx, length)\n+ return i.fileState.hostMappable.Truncate(ctx, length, uattr)\n+ }\n+\n+ mask := p9.SetAttrMask{Size: true}\n+ attr := p9.SetAttr{Size: uint64(length)}\n+ if uattr.Perms.HasSetUIDOrGID() {\n+ mask.Permissions = true\n+ uattr.Perms.DropSetUIDAndMaybeGID()\n+ attr.Permissions = p9.FileMode(uattr.Perms.LinuxMode())\n}\n- return i.fileState.file.setAttr(ctx, p9.SetAttrMask{Size: true}, p9.SetAttr{Size: uint64(length)})\n+ return i.fileState.file.setAttr(ctx, mask, attr)\n}\n// GetXattr implements fs.InodeOperations.GetXattr.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/gofer/path.go", "new_path": "pkg/sentry/fs/gofer/path.go", "diff": "@@ -130,7 +130,16 @@ func (i *inodeOperations) Create(ctx context.Context, dir *fs.Inode, name string\npanic(fmt.Sprintf(\"Create called with unknown or unset open flags: %v\", flags))\n}\n+ // If the parent directory has setgid enabled, change the new file's owner.\nowner := fs.FileOwnerFromContext(ctx)\n+ parentUattr, err := dir.UnstableAttr(ctx)\n+ if err != nil {\n+ return nil, err\n+ }\n+ if parentUattr.Perms.SetGID {\n+ owner.GID = parentUattr.Owner.GID\n+ }\n+\nhostFile, err := newFile.create(ctx, name, openFlags, p9.FileMode(perm.LinuxMode()), p9.UID(owner.UID), p9.GID(owner.GID))\nif err != nil {\n// Could not create the file.\n@@ -225,7 +234,18 @@ func (i *inodeOperations) CreateDirectory(ctx context.Context, dir *fs.Inode, s\nreturn syserror.ENAMETOOLONG\n}\n+ // If the parent directory has setgid enabled, change the new directory's\n+ // owner and enable setgid.\nowner := fs.FileOwnerFromContext(ctx)\n+ parentUattr, err := dir.UnstableAttr(ctx)\n+ if err != nil {\n+ return err\n+ }\n+ if parentUattr.Perms.SetGID {\n+ owner.GID = parentUattr.Owner.GID\n+ perm.SetGID = true\n+ }\n+\nif _, err := i.fileState.file.mkdir(ctx, s, p9.FileMode(perm.LinuxMode()), p9.UID(owner.UID), p9.GID(owner.GID)); err != nil {\nreturn err\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/tmpfs/fs.go", "new_path": "pkg/sentry/fs/tmpfs/fs.go", "diff": "@@ -151,5 +151,5 @@ func (f *Filesystem) Mount(ctx context.Context, device string, flags fs.MountSou\n}\n// Construct the tmpfs root.\n- return NewDir(ctx, nil, owner, perms, msrc), nil\n+ return NewDir(ctx, nil, owner, perms, msrc, nil /* parent */)\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/tmpfs/inode_file.go", "new_path": "pkg/sentry/fs/tmpfs/inode_file.go", "diff": "@@ -226,6 +226,12 @@ func (f *fileInodeOperations) Truncate(ctx context.Context, _ *fs.Inode, size in\nnow := ktime.NowFromContext(ctx)\nf.attr.ModificationTime = now\nf.attr.StatusChangeTime = now\n+\n+ // Truncating clears privilege bits.\n+ f.attr.Perms.SetUID = false\n+ if f.attr.Perms.Group.Execute {\n+ f.attr.Perms.SetGID = false\n+ }\n}\nf.dataMu.Unlock()\n@@ -363,7 +369,14 @@ func (f *fileInodeOperations) write(ctx context.Context, src usermem.IOSequence,\nnow := ktime.NowFromContext(ctx)\nf.attr.ModificationTime = now\nf.attr.StatusChangeTime = now\n- return src.CopyInTo(ctx, &fileReadWriter{f, offset})\n+ nwritten, err := src.CopyInTo(ctx, &fileReadWriter{f, offset})\n+\n+ // Writing clears privilege bits.\n+ if nwritten > 0 {\n+ f.attr.Perms.DropSetUIDAndMaybeGID()\n+ }\n+\n+ return nwritten, err\n}\ntype fileReadWriter struct {\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/tmpfs/tmpfs.go", "new_path": "pkg/sentry/fs/tmpfs/tmpfs.go", "diff": "@@ -87,7 +87,20 @@ 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) *fs.Inode {\n+func NewDir(ctx context.Context, contents map[string]*fs.Inode, owner fs.FileOwner, perms fs.FilePermissions, msrc *fs.MountSource, parent *fs.Inode) (*fs.Inode, error) {\n+ // If the parent has setgid enabled, the new directory enables it and changes\n+ // its GID.\n+ if parent != nil {\n+ parentUattr, err := parent.UnstableAttr(ctx)\n+ if err != nil {\n+ return nil, err\n+ }\n+ if parentUattr.Perms.SetGID {\n+ owner.GID = parentUattr.Owner.GID\n+ perms.SetGID = true\n+ }\n+ }\n+\nd := &Dir{\nramfsDir: ramfs.NewDir(ctx, contents, owner, perms),\nkernel: kernel.KernelFromContext(ctx),\n@@ -101,7 +114,7 @@ func NewDir(ctx context.Context, contents map[string]*fs.Inode, owner fs.FileOwn\nInodeID: tmpfsDevice.NextIno(),\nBlockSize: hostarch.PageSize,\nType: fs.Directory,\n- })\n+ }), nil\n}\n// afterLoad is invoked by stateify.\n@@ -219,11 +232,21 @@ 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), nil\n+ return NewDir(ctx, nil, fs.FileOwnerFromContext(ctx), perms, dir.MountSource, dir)\n},\nNewFile: func(ctx context.Context, dir *fs.Inode, perms fs.FilePermissions) (*fs.Inode, error) {\n+ // If the parent has setgid enabled, change the GID of the new file.\n+ owner := fs.FileOwnerFromContext(ctx)\n+ parentUattr, err := dir.UnstableAttr(ctx)\n+ if err != nil {\n+ return nil, err\n+ }\n+ if parentUattr.Perms.SetGID {\n+ owner.GID = parentUattr.Owner.GID\n+ }\n+\nuattr := fs.WithCurrentTime(ctx, fs.UnstableAttr{\n- Owner: fs.FileOwnerFromContext(ctx),\n+ Owner: owner,\nPerms: perms,\n// Always start unlinked.\nLinks: 0,\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/user/user_test.go", "new_path": "pkg/sentry/fs/user/user_test.go", "diff": "@@ -104,7 +104,10 @@ func TestGetExecUserHome(t *testing.T) {\nt.Run(name, func(t *testing.T) {\nctx := contexttest.Context(t)\nmsrc := fs.NewPseudoMountSource(ctx)\n- rootInode := tmpfs.NewDir(ctx, nil, fs.RootOwner, fs.FilePermsFromMode(0777), msrc)\n+ rootInode, err := tmpfs.NewDir(ctx, nil, fs.RootOwner, fs.FilePermsFromMode(0777), msrc, nil /* parent */)\n+ if err != nil {\n+ t.Fatalf(\"tmpfs.NewDir failed: %v\", err)\n+ }\nmns, err := fs.NewMountNamespace(ctx, rootInode)\nif err != nil {\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/overlay/regular_file.go", "new_path": "pkg/sentry/fsimpl/overlay/regular_file.go", "diff": "@@ -207,9 +207,10 @@ func (fd *regularFileFD) SetStat(ctx context.Context, opts vfs.SetStatOptions) e\nreturn err\n}\n- // Changing owners may clear one or both of the setuid and setgid bits,\n- // so we may have to update opts before setting d.mode.\n- if opts.Stat.Mask&(linux.STATX_UID|linux.STATX_GID) != 0 {\n+ // Changing owners or truncating may clear one or both of the setuid and\n+ // setgid bits, so we may have to update opts before setting d.mode.\n+ inotifyMask := opts.Stat.Mask\n+ if opts.Stat.Mask&(linux.STATX_UID|linux.STATX_GID|linux.STATX_SIZE) != 0 {\nstat, err := wrappedFD.Stat(ctx, vfs.StatOptions{\nMask: linux.STATX_MODE,\n})\n@@ -218,10 +219,14 @@ func (fd *regularFileFD) SetStat(ctx context.Context, opts vfs.SetStatOptions) e\n}\nopts.Stat.Mode = stat.Mode\nopts.Stat.Mask |= linux.STATX_MODE\n+ // Don't generate inotify IN_ATTRIB for size-only changes (truncations).\n+ if opts.Stat.Mask&(linux.STATX_UID|linux.STATX_GID) != 0 {\n+ inotifyMask |= linux.STATX_MODE\n+ }\n}\nd.updateAfterSetStatLocked(&opts)\n- if ev := vfs.InotifyEventFromStatMask(opts.Stat.Mask); ev != 0 {\n+ if ev := vfs.InotifyEventFromStatMask(inotifyMask); ev != 0 {\nd.InotifyWithParent(ctx, ev, 0, vfs.InodeEvent)\n}\nreturn nil\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/sys_file.go", "new_path": "pkg/sentry/syscalls/linux/sys_file.go", "diff": "@@ -1673,9 +1673,11 @@ func chown(t *kernel.Task, d *fs.Dirent, uid auth.UID, gid auth.GID) error {\nif err != nil {\nreturn err\n}\n+\nc := t.Credentials()\nhasCap := d.Inode.CheckCapability(t, linux.CAP_CHOWN)\nisOwner := uattr.Owner.UID == c.EffectiveKUID\n+ var clearPrivilege bool\nif uid.Ok() {\nkuid := c.UserNamespace.MapToKUID(uid)\n// Valid UID must be supplied if UID is to be changed.\n@@ -1693,6 +1695,11 @@ func chown(t *kernel.Task, d *fs.Dirent, uid auth.UID, gid auth.GID) error {\nreturn syserror.EPERM\n}\n+ // The setuid and setgid bits are cleared during a chown.\n+ if uattr.Owner.UID != kuid {\n+ clearPrivilege = true\n+ }\n+\nowner.UID = kuid\n}\nif gid.Ok() {\n@@ -1711,6 +1718,11 @@ func chown(t *kernel.Task, d *fs.Dirent, uid auth.UID, gid auth.GID) error {\nreturn syserror.EPERM\n}\n+ // The setuid and setgid bits are cleared during a chown.\n+ if uattr.Owner.GID != kgid {\n+ clearPrivilege = true\n+ }\n+\nowner.GID = kgid\n}\n@@ -1721,10 +1733,14 @@ func chown(t *kernel.Task, d *fs.Dirent, uid auth.UID, gid auth.GID) error {\nif err := d.Inode.SetOwner(t, d, owner); err != nil {\nreturn err\n}\n+ // Clear privilege bits if needed and they are set.\n+ if clearPrivilege && uattr.Perms.HasSetUIDOrGID() && !fs.IsDir(d.Inode.StableAttr) {\n+ uattr.Perms.DropSetUIDAndMaybeGID()\n+ if !d.Inode.SetPermissions(t, d, uattr.Perms) {\n+ return syserror.EPERM\n+ }\n+ }\n- // When the owner or group are changed by an unprivileged user,\n- // chown(2) also clears the set-user-ID and set-group-ID bits, but\n- // we do not support them.\nreturn nil\n}\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/setgid.cc", "new_path": "test/syscalls/linux/setgid.cc", "diff": "@@ -115,8 +115,6 @@ class SetgidDirTest : public ::testing::Test {\nvoid SetUp() override {\noriginal_gid_ = getegid();\n- SKIP_IF(IsRunningWithVFS1());\n-\n// If we can't find two usable groups, we're in an unsupporting environment.\n// Skip the test.\nPosixErrorOr<std::pair<gid_t, gid_t>> groups = Groups();\n@@ -294,8 +292,8 @@ TEST_F(SetgidDirTest, ChownFileClears) {\nEXPECT_EQ(stats.st_mode & (S_ISUID | S_ISGID), 0);\n}\n-// Chowning a file with setgid enabled, but not the group exec bit, does not\n-// clear the setgid bit. Such files are mandatory locked.\n+// Chowning a file with setgid enabled, but not the group exec bit, clears the\n+// setuid bit and not the setgid bit. Such files are mandatory locked.\nTEST_F(SetgidDirTest, ChownNoExecFileDoesNotClear) {\n// Set group to G1, create a directory, and enable setgid.\nauto g1owned = JoinPath(temp_dir_.path(), \"g1owned/\");\n@@ -345,7 +343,6 @@ struct FileModeTestcase {\nclass FileModeTest : public ::testing::TestWithParam<FileModeTestcase> {};\nTEST_P(FileModeTest, WriteToFile) {\n- SKIP_IF(IsRunningWithVFS1());\nPosixErrorOr<std::pair<gid_t, gid_t>> groups = Groups();\nSKIP_IF(!groups.ok());\n@@ -372,7 +369,6 @@ TEST_P(FileModeTest, WriteToFile) {\n}\nTEST_P(FileModeTest, TruncateFile) {\n- SKIP_IF(IsRunningWithVFS1());\nPosixErrorOr<std::pair<gid_t, gid_t>> groups = Groups();\nSKIP_IF(!groups.ok());\n" } ]
Go
Apache License 2.0
google/gvisor
setgid directories for VFS1 tmpfs, overlayfs, and goferfs PiperOrigin-RevId: 375780659
260,001
25.05.2021 16:43:50
25,200
080d122326a55f43ed8bc97c6c319d5ee87b1ca5
Enable verity after mount in verity_mount test
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/BUILD", "new_path": "test/syscalls/linux/BUILD", "diff": "@@ -1346,6 +1346,7 @@ cc_binary(\n\"//test/util:temp_path\",\n\"//test/util:test_main\",\n\"//test/util:test_util\",\n+ \"//test/util:verity_util\",\n],\n)\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/verity_mount.cc", "new_path": "test/syscalls/linux/verity_mount.cc", "diff": "#include \"test/util/capability_util.h\"\n#include \"test/util/temp_path.h\"\n#include \"test/util/test_util.h\"\n+#include \"test/util/verity_util.h\"\nnamespace gvisor {\nnamespace testing {\nnamespace {\n-// Mount verity file system on an existing gofer mount.\n+// Mount verity file system on an existing tmpfs mount.\nTEST(MountTest, MountExisting) {\n// Verity is implemented in VFS2.\nSKIP_IF(IsRunningWithVFS1());\n@@ -43,8 +44,11 @@ TEST(MountTest, MountExisting) {\n// Mount a verity file system on the existing gofer mount.\nauto const verity_dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\nstd::string opts = \"lower_path=\" + tmpfs_dir.path();\n- EXPECT_THAT(mount(\"\", verity_dir.path().c_str(), \"verity\", 0, opts.c_str()),\n+ ASSERT_THAT(mount(\"\", verity_dir.path().c_str(), \"verity\", 0, opts.c_str()),\nSyscallSucceeds());\n+ auto const fd =\n+ ASSERT_NO_ERRNO_AND_VALUE(Open(verity_dir.path(), O_RDONLY, 0777));\n+ EXPECT_THAT(ioctl(fd.get(), FS_IOC_ENABLE_VERITY), SyscallSucceeds());\n}\n} // namespace\n" } ]
Go
Apache License 2.0
google/gvisor
Enable verity after mount in verity_mount test PiperOrigin-RevId: 375823719
260,001
26.05.2021 12:19:11
25,200
9fcc44f991203343438b489389c2b861040086ac
Add verity getdents tests
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/verity/verity.go", "new_path": "pkg/sentry/fsimpl/verity/verity.go", "diff": "@@ -868,6 +868,10 @@ func (fd *fileDescription) IterDirents(ctx context.Context, cb vfs.IterDirentsCa\nfd.mu.Lock()\ndefer fd.mu.Unlock()\n+ if _, err := fd.lowerFD.Seek(ctx, fd.off, linux.SEEK_SET); err != nil {\n+ return err\n+ }\n+\nvar ds []vfs.Dirent\nerr := fd.lowerFD.IterDirents(ctx, vfs.IterDirentsCallbackFunc(func(dirent vfs.Dirent) error {\n// Do not include the Merkle tree files.\n@@ -890,8 +894,8 @@ func (fd *fileDescription) IterDirents(ctx context.Context, cb vfs.IterDirentsCa\nreturn err\n}\n- // The result should contain all children plus \".\" and \"..\".\n- if fd.d.verityEnabled() && len(ds) != len(fd.d.childrenNames)+2 {\n+ // The result should be a part of all children plus \".\" and \"..\", counting from fd.off.\n+ if fd.d.verityEnabled() && len(ds) != len(fd.d.childrenNames)+2-int(fd.off) {\nreturn fd.d.fs.alertIntegrityViolation(fmt.Sprintf(\"Unexpected children number %d\", len(ds)))\n}\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/BUILD", "new_path": "test/syscalls/BUILD", "diff": "@@ -215,6 +215,10 @@ syscall_test(\ntest = \"//test/syscalls/linux:getdents_test\",\n)\n+syscall_test(\n+ test = \"//test/syscalls/linux:verity_getdents_test\",\n+)\n+\nsyscall_test(\ntest = \"//test/syscalls/linux:getrandom_test\",\n)\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/BUILD", "new_path": "test/syscalls/linux/BUILD", "diff": "@@ -961,6 +961,22 @@ cc_binary(\n],\n)\n+cc_binary(\n+ name = \"verity_getdents_test\",\n+ testonly = 1,\n+ srcs = [\"verity_getdents.cc\"],\n+ linkstatic = 1,\n+ deps = [\n+ \"//test/util:capability_util\",\n+ gtest,\n+ \"//test/util:fs_util\",\n+ \"//test/util:temp_path\",\n+ \"//test/util:test_main\",\n+ \"//test/util:test_util\",\n+ \"//test/util:verity_util\",\n+ ],\n+)\n+\ncc_binary(\nname = \"getrandom_test\",\ntestonly = 1,\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test/syscalls/linux/verity_getdents.cc", "diff": "+// Copyright 2021 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+#include <dirent.h>\n+#include <stdint.h>\n+#include <stdlib.h>\n+#include <sys/mount.h>\n+#include <sys/syscall.h>\n+\n+#include <string>\n+#include <vector>\n+\n+#include \"gmock/gmock.h\"\n+#include \"gtest/gtest.h\"\n+#include \"test/util/capability_util.h\"\n+#include \"test/util/fs_util.h\"\n+#include \"test/util/temp_path.h\"\n+#include \"test/util/test_util.h\"\n+#include \"test/util/verity_util.h\"\n+\n+namespace gvisor {\n+namespace testing {\n+\n+namespace {\n+\n+class GetDentsTest : public ::testing::Test {\n+ protected:\n+ void SetUp() override {\n+ // Verity is implemented in VFS2.\n+ SKIP_IF(IsRunningWithVFS1());\n+\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_SYS_ADMIN)));\n+ // Mount a tmpfs file system, to be wrapped by a verity fs.\n+ tmpfs_dir_ = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n+ ASSERT_THAT(mount(\"\", tmpfs_dir_.path().c_str(), \"tmpfs\", 0, \"\"),\n+ SyscallSucceeds());\n+\n+ // Create a new file in the tmpfs mount.\n+ file_ = ASSERT_NO_ERRNO_AND_VALUE(\n+ TempPath::CreateFileWith(tmpfs_dir_.path(), kContents, 0777));\n+ filename_ = Basename(file_.path());\n+ }\n+\n+ TempPath tmpfs_dir_;\n+ TempPath file_;\n+ std::string filename_;\n+};\n+\n+TEST_F(GetDentsTest, GetDents) {\n+ std::string verity_dir =\n+ ASSERT_NO_ERRNO_AND_VALUE(MountVerity(tmpfs_dir_.path(), filename_));\n+\n+ std::vector<std::string> expect = {\".\", \"..\", filename_};\n+ EXPECT_NO_ERRNO(DirContains(verity_dir, expect, /*exclude=*/{}));\n+}\n+\n+TEST_F(GetDentsTest, Deleted) {\n+ std::string verity_dir =\n+ ASSERT_NO_ERRNO_AND_VALUE(MountVerity(tmpfs_dir_.path(), filename_));\n+\n+ EXPECT_THAT(unlink(JoinPath(tmpfs_dir_.path(), filename_).c_str()),\n+ SyscallSucceeds());\n+\n+ EXPECT_THAT(DirContains(verity_dir, /*expect=*/{}, /*exclude=*/{}),\n+ PosixErrorIs(EIO, ::testing::_));\n+}\n+\n+TEST_F(GetDentsTest, Renamed) {\n+ std::string verity_dir =\n+ ASSERT_NO_ERRNO_AND_VALUE(MountVerity(tmpfs_dir_.path(), filename_));\n+\n+ std::string new_file_name = \"renamed-\" + filename_;\n+ EXPECT_THAT(rename(JoinPath(tmpfs_dir_.path(), filename_).c_str(),\n+ JoinPath(tmpfs_dir_.path(), new_file_name).c_str()),\n+ SyscallSucceeds());\n+\n+ EXPECT_THAT(DirContains(verity_dir, /*expect=*/{}, /*exclude=*/{}),\n+ PosixErrorIs(EIO, ::testing::_));\n+}\n+\n+} // namespace\n+\n+} // namespace testing\n+} // namespace gvisor\n" } ]
Go
Apache License 2.0
google/gvisor
Add verity getdents tests PiperOrigin-RevId: 376001603
259,891
27.05.2021 14:36:35
25,200
dd2e1f07a9c0dddcdfd5f983fc338938a4b11935
Speed up TestBindToDeviceDistribution Testing only TestBindToDeviceDistribution decreased from 24s to 11s, and with TSAN from 186s to 21s. Note: using `t.Parallel()` actually slows the test down.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/transport_demuxer_test.go", "new_path": "pkg/tcpip/stack/transport_demuxer_test.go", "diff": "@@ -18,6 +18,7 @@ import (\n\"io/ioutil\"\n\"math\"\n\"math/rand\"\n+ \"strconv\"\n\"testing\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n@@ -84,7 +85,8 @@ func newDualTestContextMultiNIC(t *testing.T, mtu uint32, linkEpIDs []tcpip.NICI\n}\ntype headers struct {\n- srcPort, dstPort uint16\n+ srcPort uint16\n+ dstPort uint16\n}\nfunc newPayload() []byte {\n@@ -208,7 +210,7 @@ func TestBindToDeviceDistribution(t *testing.T) {\nreuse bool\nbindToDevice tcpip.NICID\n}\n- for _, test := range []struct {\n+ tcs := []struct {\nname string\n// endpoints will received the inject packets.\nendpoints []endpointSockopts\n@@ -217,29 +219,29 @@ func TestBindToDeviceDistribution(t *testing.T) {\nwantDistributions map[tcpip.NICID][]float64\n}{\n{\n- \"BindPortReuse\",\n+ name: \"BindPortReuse\",\n// 5 endpoints that all have reuse set.\n- []endpointSockopts{\n+ endpoints: []endpointSockopts{\n{reuse: true, bindToDevice: 0},\n{reuse: true, bindToDevice: 0},\n{reuse: true, bindToDevice: 0},\n{reuse: true, bindToDevice: 0},\n{reuse: true, bindToDevice: 0},\n},\n- map[tcpip.NICID][]float64{\n+ wantDistributions: map[tcpip.NICID][]float64{\n// Injected packets on dev0 get distributed evenly.\n1: {0.2, 0.2, 0.2, 0.2, 0.2},\n},\n},\n{\n- \"BindToDevice\",\n+ name: \"BindToDevice\",\n// 3 endpoints with various bindings.\n- []endpointSockopts{\n+ endpoints: []endpointSockopts{\n{reuse: false, bindToDevice: 1},\n{reuse: false, bindToDevice: 2},\n{reuse: false, bindToDevice: 3},\n},\n- map[tcpip.NICID][]float64{\n+ wantDistributions: map[tcpip.NICID][]float64{\n// Injected packets on dev0 go only to the endpoint bound to dev0.\n1: {1, 0, 0},\n// Injected packets on dev1 go only to the endpoint bound to dev1.\n@@ -249,9 +251,9 @@ func TestBindToDeviceDistribution(t *testing.T) {\n},\n},\n{\n- \"ReuseAndBindToDevice\",\n+ name: \"ReuseAndBindToDevice\",\n// 6 endpoints with various bindings.\n- []endpointSockopts{\n+ endpoints: []endpointSockopts{\n{reuse: true, bindToDevice: 1},\n{reuse: true, bindToDevice: 1},\n{reuse: true, bindToDevice: 2},\n@@ -259,7 +261,7 @@ func TestBindToDeviceDistribution(t *testing.T) {\n{reuse: true, bindToDevice: 2},\n{reuse: true, bindToDevice: 0},\n},\n- map[tcpip.NICID][]float64{\n+ wantDistributions: map[tcpip.NICID][]float64{\n// Injected packets on dev0 get distributed among endpoints bound to\n// dev0.\n1: {0.5, 0.5, 0, 0, 0, 0},\n@@ -270,21 +272,25 @@ func TestBindToDeviceDistribution(t *testing.T) {\n1000: {0, 0, 0, 0, 0, 1},\n},\n},\n- } {\n- for protoName, netProtoNum := range map[string]tcpip.NetworkProtocolNumber{\n+ }\n+ protos := map[string]tcpip.NetworkProtocolNumber{\n\"IPv4\": ipv4.ProtocolNumber,\n\"IPv6\": ipv6.ProtocolNumber,\n- } {\n+ }\n+\n+ for _, test := range tcs {\n+ for protoName, protoNum := range protos {\nfor device, wantDistribution := range test.wantDistributions {\n- t.Run(test.name+protoName+string(device), func(t *testing.T) {\n+ t.Run(test.name+protoName+\"-\"+strconv.Itoa(int(device)), func(t *testing.T) {\n+ // Create the NICs.\nvar devices []tcpip.NICID\nfor d := range test.wantDistributions {\ndevices = append(devices, d)\n}\nc := newDualTestContextMultiNIC(t, defaultMTU, devices)\n+ // Create endpoints and bind each to a NIC, sometimes reusing ports.\neps := make(map[tcpip.Endpoint]int)\n-\npollChannel := make(chan tcpip.Endpoint)\nfor i, endpoint := range test.endpoints {\n// Try to receive the data.\n@@ -297,7 +303,7 @@ func TestBindToDeviceDistribution(t *testing.T) {\n})\nvar err tcpip.Error\n- ep, err := c.s.NewEndpoint(udp.ProtocolNumber, netProtoNum, &wq)\n+ ep, err := c.s.NewEndpoint(udp.ProtocolNumber, protoNum, &wq)\nif err != nil {\nt.Fatalf(\"NewEndpoint failed: %s\", err)\n}\n@@ -316,21 +322,24 @@ func TestBindToDeviceDistribution(t *testing.T) {\n}\nvar dstAddr tcpip.Address\n- switch netProtoNum {\n+ switch protoNum {\ncase ipv4.ProtocolNumber:\ndstAddr = testDstAddrV4\ncase ipv6.ProtocolNumber:\ndstAddr = testDstAddrV6\ndefault:\n- t.Fatalf(\"unexpected protocol number: %d\", netProtoNum)\n+ t.Fatalf(\"unexpected protocol number: %d\", protoNum)\n}\nif err := ep.Bind(tcpip.FullAddress{Addr: dstAddr, Port: testDstPort}); err != nil {\nt.Fatalf(\"ep.Bind(...) on endpoint %d failed: %s\", i, err)\n}\n}\n- npackets := 100000\n- nports := 10000\n+ // Send packets across a range of ports, checking that packets from\n+ // the same source port are always demultiplexed to the same\n+ // destination endpoint.\n+ npackets := 10_000\n+ nports := 1_000\nif got, want := len(test.endpoints), len(wantDistribution); got != want {\nt.Fatalf(\"got len(test.endpoints) = %d, want %d\", got, want)\n}\n@@ -344,13 +353,13 @@ func TestBindToDeviceDistribution(t *testing.T) {\nsrcPort: testSrcPort + port,\ndstPort: testDstPort,\n}\n- switch netProtoNum {\n+ switch protoNum {\ncase ipv4.ProtocolNumber:\nc.sendV4Packet(payload, hdrs, device)\ncase ipv6.ProtocolNumber:\nc.sendV6Packet(payload, hdrs, device)\ndefault:\n- t.Fatalf(\"unexpected protocol number: %d\", netProtoNum)\n+ t.Fatalf(\"unexpected protocol number: %d\", protoNum)\n}\nep := <-pollChannel\n" } ]
Go
Apache License 2.0
google/gvisor
Speed up TestBindToDeviceDistribution Testing only TestBindToDeviceDistribution decreased from 24s to 11s, and with TSAN from 186s to 21s. Note: using `t.Parallel()` actually slows the test down. PiperOrigin-RevId: 376251420
259,853
27.05.2021 15:09:27
25,200
17df2df75ca092342a29694739d6fbe3bf95b770
nanosleep has to store the finish time in the restart block nanosleep has to count time that a thread spent in the stopped state.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/time/time.go", "new_path": "pkg/sentry/kernel/time/time.go", "diff": "@@ -458,25 +458,6 @@ func NewTimer(clock Clock, listener TimerListener) *Timer {\nreturn t\n}\n-// After waits for the duration to elapse according to clock and then sends a\n-// notification on the returned channel. The timer is started immediately and\n-// will fire exactly once. The second return value is the start time used with\n-// the duration.\n-//\n-// Callers must call Timer.Destroy.\n-func After(clock Clock, duration time.Duration) (*Timer, Time, <-chan struct{}) {\n- notifier, tchan := NewChannelNotifier()\n- t := NewTimer(clock, notifier)\n- now := clock.Now()\n-\n- t.Swap(Setting{\n- Enabled: true,\n- Period: 0,\n- Next: now.Add(duration),\n- })\n- return t, now, tchan\n-}\n-\n// init initializes Timer state that is not preserved across save/restore. If\n// init has already been called, calling it again is a no-op.\n//\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/sys_time.go", "new_path": "pkg/sentry/syscalls/linux/sys_time.go", "diff": "@@ -181,20 +181,20 @@ func Time(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallC\n// +stateify savable\ntype clockNanosleepRestartBlock struct {\nc ktime.Clock\n- duration time.Duration\n+ end ktime.Time\nrem hostarch.Addr\n}\n// Restart implements kernel.SyscallRestartBlock.Restart.\nfunc (n *clockNanosleepRestartBlock) Restart(t *kernel.Task) (uintptr, error) {\n- return 0, clockNanosleepFor(t, n.c, n.duration, n.rem)\n+ return 0, clockNanosleepUntil(t, n.c, n.end, n.rem, true)\n}\n// clockNanosleepUntil blocks until a specified time.\n//\n// If blocking is interrupted, the syscall is restarted with the original\n// arguments.\n-func clockNanosleepUntil(t *kernel.Task, c ktime.Clock, ts linux.Timespec) error {\n+func clockNanosleepUntil(t *kernel.Task, c ktime.Clock, end ktime.Time, rem hostarch.Addr, needRestartBlock bool) error {\nnotifier, tchan := ktime.NewChannelNotifier()\ntimer := ktime.NewTimer(c, notifier)\n@@ -202,43 +202,22 @@ func clockNanosleepUntil(t *kernel.Task, c ktime.Clock, ts linux.Timespec) error\ntimer.Swap(ktime.Setting{\nPeriod: 0,\nEnabled: true,\n- Next: ktime.FromTimespec(ts),\n+ Next: end,\n})\nerr := t.BlockWithTimer(nil, tchan)\ntimer.Destroy()\n- // Did we just block until the timeout happened?\n- if err == syserror.ETIMEDOUT {\n- return nil\n- }\n-\n- return syserror.ConvertIntr(err, syserror.ERESTARTNOHAND)\n-}\n-\n-// clockNanosleepFor blocks for a specified duration.\n-//\n-// If blocking is interrupted, the syscall is restarted with the remaining\n-// duration timeout.\n-func clockNanosleepFor(t *kernel.Task, c ktime.Clock, dur time.Duration, rem hostarch.Addr) error {\n- timer, start, tchan := ktime.After(c, dur)\n-\n- err := t.BlockWithTimer(nil, tchan)\n-\n- after := c.Now()\n-\n- timer.Destroy()\n-\nswitch err {\ncase syserror.ETIMEDOUT:\n// Slept for entire timeout.\nreturn nil\ncase syserror.ErrInterrupted:\n// Interrupted.\n- remaining := dur - after.Sub(start)\n- if remaining < 0 {\n- remaining = time.Duration(0)\n+ remaining := end.Sub(c.Now())\n+ if remaining <= 0 {\n+ return nil\n}\n// Copy out remaining time.\n@@ -248,14 +227,16 @@ func clockNanosleepFor(t *kernel.Task, c ktime.Clock, dur time.Duration, rem hos\nreturn err\n}\n}\n-\n+ if needRestartBlock {\n// Arrange for a restart with the remaining duration.\nt.SetSyscallRestartBlock(&clockNanosleepRestartBlock{\nc: c,\n- duration: remaining,\n+ end: end,\nrem: rem,\n})\nreturn syserror.ERESTART_RESTARTBLOCK\n+ }\n+ return syserror.ERESTARTNOHAND\ndefault:\npanic(fmt.Sprintf(\"Impossible BlockWithTimer error %v\", err))\n}\n@@ -278,7 +259,8 @@ func Nanosleep(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sys\n// Just like linux, we cap the timeout with the max number that int64 can\n// represent which is roughly 292 years.\ndur := time.Duration(ts.ToNsecCapped()) * time.Nanosecond\n- return 0, nil, clockNanosleepFor(t, t.Kernel().MonotonicClock(), dur, rem)\n+ c := t.Kernel().MonotonicClock()\n+ return 0, nil, clockNanosleepUntil(t, c, c.Now().Add(dur), rem, true)\n}\n// ClockNanosleep implements linux syscall clock_nanosleep(2).\n@@ -312,11 +294,11 @@ func ClockNanosleep(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kerne\n}\nif flags&linux.TIMER_ABSTIME != 0 {\n- return 0, nil, clockNanosleepUntil(t, c, req)\n+ return 0, nil, clockNanosleepUntil(t, c, ktime.FromTimespec(req), 0, false)\n}\ndur := time.Duration(req.ToNsecCapped()) * time.Nanosecond\n- return 0, nil, clockNanosleepFor(t, c, dur, rem)\n+ return 0, nil, clockNanosleepUntil(t, c, c.Now().Add(dur), rem, true)\n}\n// Gettimeofday implements linux syscall gettimeofday(2).\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/sigstop.cc", "new_path": "test/syscalls/linux/sigstop.cc", "diff": "@@ -123,6 +123,55 @@ void SleepIgnoreStopped(absl::Duration d) {\n}\n}\n+TEST(SigstopTest, RestartSyscall) {\n+ pid_t pid;\n+ constexpr absl::Duration kStopDelay = absl::Seconds(5);\n+ constexpr absl::Duration kSleepDelay = absl::Seconds(15);\n+ constexpr absl::Duration kStartupDelay = absl::Seconds(5);\n+ constexpr absl::Duration kErrorDelay = absl::Seconds(3);\n+\n+ const DisableSave ds; // Timing-related.\n+\n+ pid = fork();\n+ if (pid == 0) {\n+ struct timespec ts = {.tv_sec = kSleepDelay / absl::Seconds(1)};\n+ auto start = absl::Now();\n+ TEST_CHECK(nanosleep(&ts, nullptr) == 0);\n+ auto finish = absl::Now();\n+ // Check that time spent stopped is counted as time spent sleeping.\n+ TEST_CHECK(finish - start >= kSleepDelay);\n+ TEST_CHECK(finish - start < kSleepDelay + kErrorDelay);\n+ _exit(kChildMainThreadExitCode);\n+ }\n+ ASSERT_THAT(pid, SyscallSucceeds());\n+\n+ // Wait for the child subprocess to start sleeping before stopping it.\n+ absl::SleepFor(kStartupDelay);\n+ ASSERT_THAT(kill(pid, SIGSTOP), SyscallSucceeds());\n+ int status;\n+ EXPECT_THAT(RetryEINTR(waitpid)(pid, &status, WUNTRACED),\n+ SyscallSucceedsWithValue(pid));\n+ EXPECT_TRUE(WIFSTOPPED(status));\n+ EXPECT_EQ(SIGSTOP, WSTOPSIG(status));\n+\n+ // Sleep for shorter than the sleep in the child subprocess.\n+ absl::SleepFor(kStopDelay);\n+ ASSERT_THAT(RetryEINTR(waitpid)(pid, &status, WNOHANG),\n+ SyscallSucceedsWithValue(0));\n+\n+ // Resume the child.\n+ ASSERT_THAT(kill(pid, SIGCONT), SyscallSucceeds());\n+\n+ EXPECT_THAT(RetryEINTR(waitpid)(pid, &status, WCONTINUED),\n+ SyscallSucceedsWithValue(pid));\n+ EXPECT_TRUE(WIFCONTINUED(status));\n+\n+ // Expect it to die.\n+ ASSERT_THAT(RetryEINTR(waitpid)(pid, &status, 0), SyscallSucceeds());\n+ ASSERT_TRUE(WIFEXITED(status));\n+ ASSERT_EQ(WEXITSTATUS(status), kChildMainThreadExitCode);\n+}\n+\nvoid RunChild() {\n// Start another thread that attempts to call exit_group with a different\n// error code, in order to verify that SIGSTOP stops this thread as well.\n" } ]
Go
Apache License 2.0
google/gvisor
nanosleep has to store the finish time in the restart block nanosleep has to count time that a thread spent in the stopped state. PiperOrigin-RevId: 376258641
259,884
27.05.2021 18:55:30
25,200
e8fc815b6ef58b6faa136ef239f89ec98a8e55b4
Fix specific releases and update install instructions. Fixes
[ { "change_type": "MODIFY", "old_path": "g3doc/user_guide/install.md", "new_path": "g3doc/user_guide/install.md", "diff": "@@ -138,7 +138,9 @@ sudo add-apt-repository \"deb [arch=amd64,arm64] https://storage.googleapis.com/g\n### Specific release\n-A given release release is available at the following URL:\n+Specific releases are the latest [point release](#point-release) for a given\n+date. Specific releases should be available for any date that has a point\n+release. A given release is available at the following URL:\n`https://storage.googleapis.com/gvisor/releases/release/${yyyymmdd}/${ARCH}`\n@@ -159,7 +161,9 @@ sudo add-apt-repository \"deb [arch=amd64,arm64] https://storage.googleapis.com/g\n### Point release\n-A given point release is available at the following URL:\n+Point releases correspond to\n+[releases](https://github.com/google/gvisor/releases) tagged in the Github\n+repository. A given point release is available at the following URL:\n`https://storage.googleapis.com/gvisor/releases/release/${yyyymmdd}.${rc}/${ARCH}`\n" }, { "change_type": "MODIFY", "old_path": "tools/make_release.sh", "new_path": "tools/make_release.sh", "diff": "@@ -22,8 +22,10 @@ if [[ \"$#\" -le 2 ]]; then\nfi\nset -xeo pipefail\n-declare -r private_key=\"$1\"; shift\n-declare -r root=\"$1\"; shift\n+declare -r private_key=\"$1\"\n+shift\n+declare -r root=\"$1\"\n+shift\ndeclare -a binaries\ndeclare -a pkgs\n@@ -55,7 +57,8 @@ install_apt() {\n# If nightly, install only nightly artifacts.\nif [[ \"${NIGHTLY:-false}\" == \"true\" ]]; then\n- # The \"latest\" directory and current date.\n+ # Install the nightly release.\n+ # https://gvisor.dev/docs/user_guide/install/#nightly\nstamp=\"$(date -Idate)\"\ninstall_raw \"nightly/latest\"\ninstall_raw \"nightly/${stamp}\"\n@@ -69,13 +72,23 @@ else\nfor tag in ${tags}; do\nname=$(echo \"${tag}\" | cut -d'-' -f2)\nbase=$(echo \"${name}\" | cut -d'.' -f1)\n+ # Install the \"specific\" release. This is the latest release with the\n+ # given date.\n+ # https://gvisor.dev/docs/user_guide/install/#specific-release\n+ install_raw \"release/${base}\"\n+ # Install the \"point release\".\n+ # https://gvisor.dev/docs/user_guide/install/#point-release\ninstall_raw \"release/${name}\"\n+ # Install the latest release.\n+ # https://gvisor.dev/docs/user_guide/install/#latest-release\ninstall_raw \"release/latest\"\n+\ninstall_apt \"release\"\ninstall_apt \"${base}\"\ndone\nelse\n# Otherwise, assume it is a raw master commit.\n+ # https://gvisor.dev/docs/user_guide/install/#head\ninstall_raw \"master/latest\"\ninstall_apt \"master\"\nfi\n" } ]
Go
Apache License 2.0
google/gvisor
Fix specific releases and update install instructions. Fixes #6084 PiperOrigin-RevId: 376293659
259,992
27.05.2021 19:51:54
25,200
394c6089c3b8700164756677f53314d165f8d383
Fix test_app task-tree Executing `select {}` to wait forever triggers Go runtime deadlock detection and kills the child, causing the number actual processes be less than expected.
[ { "change_type": "MODIFY", "old_path": "pkg/test/testutil/BUILD", "new_path": "pkg/test/testutil/BUILD", "diff": "@@ -12,6 +12,7 @@ go_library(\n],\nvisibility = [\"//:sandbox\"],\ndeps = [\n+ \"//pkg/sentry/watchdog\",\n\"//pkg/sync\",\n\"//runsc/config\",\n\"//runsc/specutils\",\n" }, { "change_type": "MODIFY", "old_path": "pkg/test/testutil/testutil.go", "new_path": "pkg/test/testutil/testutil.go", "diff": "@@ -42,6 +42,7 @@ import (\n\"github.com/cenkalti/backoff\"\nspecs \"github.com/opencontainers/runtime-spec/specs-go\"\n\"golang.org/x/sys/unix\"\n+ \"gvisor.dev/gvisor/pkg/sentry/watchdog\"\n\"gvisor.dev/gvisor/pkg/sync\"\n\"gvisor.dev/gvisor/runsc/config\"\n\"gvisor.dev/gvisor/runsc/specutils\"\n@@ -184,6 +185,7 @@ func TestConfig(t *testing.T) *config.Config {\nconf.Network = config.NetworkNone\nconf.Strace = true\nconf.TestOnlyAllowRunAsCurrentUserWithoutChroot = true\n+ conf.WatchdogAction = watchdog.Panic\nreturn conf\n}\n" }, { "change_type": "MODIFY", "old_path": "test/cmd/test_app/test_app.go", "new_path": "test/cmd/test_app/test_app.go", "diff": "@@ -160,14 +160,17 @@ func (c *taskTree) SetFlags(f *flag.FlagSet) {\n// Execute implements subcommands.Command.\nfunc (c *taskTree) Execute(ctx context.Context, f *flag.FlagSet, args ...interface{}) subcommands.ExitStatus {\n- stop := testutil.StartReaper()\n- defer stop()\n-\nif c.depth == 0 {\nlog.Printf(\"Child sleeping, PID: %d\\n\", os.Getpid())\n- select {}\n+ for {\n+ time.Sleep(time.Hour)\n}\n- log.Printf(\"Parent %d sleeping, PID: %d\\n\", c.depth, os.Getpid())\n+ }\n+\n+ log.Printf(\"Parent %d creating %d children, PID: %d\\n\", c.depth, c.width, os.Getpid())\n+\n+ stop := testutil.StartReaper()\n+ defer stop()\nvar cmds []*exec.Cmd\nfor i := 0; i < c.width; i++ {\n@@ -175,7 +178,7 @@ func (c *taskTree) Execute(ctx context.Context, f *flag.FlagSet, args ...interfa\n\"/proc/self/exe\", c.Name(),\n\"--depth\", strconv.Itoa(c.depth-1),\n\"--width\", strconv.Itoa(c.width),\n- \"--pause\", strconv.FormatBool(c.pause))\n+ fmt.Sprintf(\"--pause=%t\", c.pause))\ncmd.Stdout = os.Stdout\ncmd.Stderr = os.Stderr\n@@ -190,7 +193,10 @@ func (c *taskTree) Execute(ctx context.Context, f *flag.FlagSet, args ...interfa\n}\nif c.pause {\n- select {}\n+ log.Printf(\"Parent %d sleeping, PID: %d\\n\", c.depth, os.Getpid())\n+ for {\n+ time.Sleep(time.Hour)\n+ }\n}\nreturn subcommands.ExitSuccess\n" } ]
Go
Apache License 2.0
google/gvisor
Fix test_app task-tree Executing `select {}` to wait forever triggers Go runtime deadlock detection and kills the child, causing the number actual processes be less than expected. PiperOrigin-RevId: 376298799
259,884
31.05.2021 20:00:17
25,200
4f374699818fec39dccdfcb07752fd0f728fe53d
Update comments on ambient caps to point to bug
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/auth/credentials.go", "new_path": "pkg/sentry/kernel/auth/credentials.go", "diff": "@@ -125,7 +125,7 @@ func NewUserCredentials(kuid KUID, kgid KGID, extraKGIDs []KGID, capabilities *T\ncreds.EffectiveCaps = capabilities.EffectiveCaps\ncreds.BoundingCaps = capabilities.BoundingCaps\ncreds.InheritableCaps = capabilities.InheritableCaps\n- // TODO(nlacasse): Support ambient capabilities.\n+ // TODO(gvisor.dev/issue/3166): Support ambient capabilities.\n} else {\n// If no capabilities are specified, grant capabilities consistent with\n// setresuid + setresgid from NewRootCredentials to the given uid and\n" }, { "change_type": "MODIFY", "old_path": "runsc/specutils/specutils.go", "new_path": "runsc/specutils/specutils.go", "diff": "@@ -246,7 +246,7 @@ func Capabilities(enableRaw bool, specCaps *specs.LinuxCapabilities) (*auth.Task\nif caps.PermittedCaps, err = capsFromNames(specCaps.Permitted, skipSet); err != nil {\nreturn nil, err\n}\n- // TODO(nlacasse): Support ambient capabilities.\n+ // TODO(gvisor.dev/issue/3166): Support ambient capabilities.\n}\nreturn &caps, nil\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Update comments on ambient caps to point to bug PiperOrigin-RevId: 376747671
260,019
09.12.2020 17:34:23
-28,800
98fd5c241bcaa78f5d8d28d83038f4ec50ce96ee
Fix errors for noescape cases
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/kvm/bluepill_arm64.go", "new_path": "pkg/sentry/platform/kvm/bluepill_arm64.go", "diff": "@@ -25,29 +25,6 @@ import (\nvar (\n// The action for bluepillSignal is changed by sigaction().\nbluepillSignal = unix.SIGILL\n-\n- // vcpuSErrBounce is the event of system error for bouncing KVM.\n- vcpuSErrBounce = kvmVcpuEvents{\n- exception: exception{\n- sErrPending: 1,\n- },\n- }\n-\n- // vcpuSErrNMI is the event of system error to trigger sigbus.\n- vcpuSErrNMI = kvmVcpuEvents{\n- exception: exception{\n- sErrPending: 1,\n- sErrHasEsr: 1,\n- sErrEsr: _ESR_ELx_SERR_NMI,\n- },\n- }\n-\n- // vcpuExtDabt is the event of ext_dabt.\n- vcpuExtDabt = kvmVcpuEvents{\n- exception: exception{\n- extDabtPending: 1,\n- },\n- }\n)\n// getTLS returns the value of TPIDR_EL0 register.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/kvm/bluepill_arm64_unsafe.go", "new_path": "pkg/sentry/platform/kvm/bluepill_arm64_unsafe.go", "diff": "@@ -80,11 +80,18 @@ func getHypercallID(addr uintptr) int {\n//\n//go:nosplit\nfunc bluepillStopGuest(c *vCPU) {\n+ // vcpuSErrBounce is the event of system error for bouncing KVM.\n+ vcpuSErrBounce := &kvmVcpuEvents{\n+ exception: exception{\n+ sErrPending: 1,\n+ },\n+ }\n+\nif _, _, errno := unix.RawSyscall( // escapes: no.\nunix.SYS_IOCTL,\nuintptr(c.fd),\n_KVM_SET_VCPU_EVENTS,\n- uintptr(unsafe.Pointer(&vcpuSErrBounce))); errno != 0 {\n+ uintptr(unsafe.Pointer(vcpuSErrBounce))); errno != 0 {\nthrow(\"bounce sErr injection failed\")\n}\n}\n@@ -93,12 +100,21 @@ func bluepillStopGuest(c *vCPU) {\n//\n//go:nosplit\nfunc bluepillSigBus(c *vCPU) {\n+ // vcpuSErrNMI is the event of system error to trigger sigbus.\n+ vcpuSErrNMI := &kvmVcpuEvents{\n+ exception: exception{\n+ sErrPending: 1,\n+ sErrHasEsr: 1,\n+ sErrEsr: _ESR_ELx_SERR_NMI,\n+ },\n+ }\n+\n// Host must support ARM64_HAS_RAS_EXTN.\nif _, _, errno := unix.RawSyscall( // escapes: no.\nunix.SYS_IOCTL,\nuintptr(c.fd),\n_KVM_SET_VCPU_EVENTS,\n- uintptr(unsafe.Pointer(&vcpuSErrNMI))); errno != 0 {\n+ uintptr(unsafe.Pointer(vcpuSErrNMI))); errno != 0 {\nif errno == unix.EINVAL {\nthrow(\"No ARM64_HAS_RAS_EXTN feature in host.\")\n}\n@@ -110,11 +126,18 @@ func bluepillSigBus(c *vCPU) {\n//\n//go:nosplit\nfunc bluepillExtDabt(c *vCPU) {\n+ // vcpuExtDabt is the event of ext_dabt.\n+ vcpuExtDabt := &kvmVcpuEvents{\n+ exception: exception{\n+ extDabtPending: 1,\n+ },\n+ }\n+\nif _, _, errno := unix.RawSyscall( // escapes: no.\nunix.SYS_IOCTL,\nuintptr(c.fd),\n_KVM_SET_VCPU_EVENTS,\n- uintptr(unsafe.Pointer(&vcpuExtDabt))); errno != 0 {\n+ uintptr(unsafe.Pointer(vcpuExtDabt))); errno != 0 {\nthrow(\"ext_dabt injection failed\")\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/kvm/machine_arm64_unsafe.go", "new_path": "pkg/sentry/platform/kvm/machine_arm64_unsafe.go", "diff": "@@ -140,22 +140,15 @@ func (c *vCPU) initArchState() error {\n// vbar_el1\nreg.id = _KVM_ARM64_REGS_VBAR_EL1\n-\n- fromLocation := reflect.ValueOf(ring0.Vectors).Pointer()\n- offset := fromLocation & (1<<11 - 1)\n- if offset != 0 {\n- offset = 1<<11 - offset\n- }\n-\n- toLocation := fromLocation + offset\n- data = uint64(ring0.KernelStartAddress | toLocation)\n+ vectorLocation := reflect.ValueOf(ring0.Vectors).Pointer()\n+ data = uint64(ring0.KernelStartAddress | vectorLocation)\nif err := c.setOneRegister(&reg); err != nil {\nreturn err\n}\n// Use the address of the exception vector table as\n// the MMIO address base.\n- arm64HypercallMMIOBase = toLocation\n+ arm64HypercallMMIOBase = vectorLocation\n// Initialize the PCID database.\nif hasGuestPCID {\n" } ]
Go
Apache License 2.0
google/gvisor
Fix errors for noescape cases Signed-off-by: Robin Luk <[email protected]>
260,023
01.06.2021 10:44:30
25,200
77dc0f5bc94dff28fa23812f3ad60a8b01e91138
Ignore RST received for a TCP listener The current implementation has a bug where TCP listener does not ignore RSTs from the peer. While handling RST+ACK from the peer, this bug can complete handshakes that use syncookies. This results in half-open connection delivered to the accept queue. Fixes
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/accept.go", "new_path": "pkg/tcpip/transport/tcp/accept.go", "diff": "@@ -560,6 +560,10 @@ func (e *endpoint) handleListenSegment(ctx *listenContext, s *segment) tcpip.Err\n}\nswitch {\n+ case s.flags.Contains(header.TCPFlagRst):\n+ e.stack.Stats().DroppedPackets.Increment()\n+ return nil\n+\ncase s.flags == header.TCPFlagSyn:\nif e.acceptQueueIsFull() {\ne.stack.Stats().TCP.ListenOverflowSynDrop.Increment()\n@@ -611,7 +615,7 @@ func (e *endpoint) handleListenSegment(ctx *listenContext, s *segment) tcpip.Err\ne.stack.Stats().TCP.ListenOverflowSynCookieSent.Increment()\nreturn nil\n- case (s.flags & header.TCPFlagAck) != 0:\n+ case s.flags.Contains(header.TCPFlagAck):\nif e.acceptQueueIsFull() {\n// Silently drop the ack as the application can't accept\n// the connection at this point. The ack will be\n@@ -753,6 +757,7 @@ func (e *endpoint) handleListenSegment(ctx *listenContext, s *segment) tcpip.Err\nreturn nil\ndefault:\n+ e.stack.Stats().DroppedPackets.Increment()\nreturn nil\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/tcp_test.go", "new_path": "pkg/tcpip/transport/tcp/tcp_test.go", "diff": "@@ -6238,6 +6238,54 @@ func TestPassiveFailedConnectionAttemptIncrement(t *testing.T) {\n}\n}\n+func TestListenDropIncrement(t *testing.T) {\n+ c := context.New(t, defaultMTU)\n+ defer c.Cleanup()\n+\n+ stats := c.Stack().Stats()\n+ c.Create(-1 /*epRcvBuf*/)\n+\n+ if err := c.EP.Bind(tcpip.FullAddress{Addr: context.StackAddr, Port: context.StackPort}); err != nil {\n+ t.Fatalf(\"Bind failed: %s\", err)\n+ }\n+ if err := c.EP.Listen(1 /*backlog*/); err != nil {\n+ t.Fatalf(\"Listen failed: %s\", err)\n+ }\n+\n+ initialDropped := stats.DroppedPackets.Value()\n+\n+ // Send RST, FIN segments, that are expected to be dropped by the listener.\n+ c.SendPacket(nil, &context.Headers{\n+ SrcPort: context.TestPort,\n+ DstPort: context.StackPort,\n+ Flags: header.TCPFlagRst,\n+ })\n+ c.SendPacket(nil, &context.Headers{\n+ SrcPort: context.TestPort,\n+ DstPort: context.StackPort,\n+ Flags: header.TCPFlagFin,\n+ })\n+\n+ // To ensure that the RST, FIN sent earlier are indeed received and ignored\n+ // by the listener, send a SYN and wait for the SYN to be ACKd.\n+ irs := seqnum.Value(context.TestInitialSequenceNumber)\n+ c.SendPacket(nil, &context.Headers{\n+ SrcPort: context.TestPort,\n+ DstPort: context.StackPort,\n+ Flags: header.TCPFlagSyn,\n+ SeqNum: irs,\n+ })\n+ checker.IPv4(t, c.GetPacket(), checker.TCP(checker.SrcPort(context.StackPort),\n+ checker.DstPort(context.TestPort),\n+ checker.TCPFlags(header.TCPFlagAck|header.TCPFlagSyn),\n+ checker.TCPAckNum(uint32(irs)+1),\n+ ))\n+\n+ if got, want := stats.DroppedPackets.Value(), initialDropped+2; got != want {\n+ t.Fatalf(\"got stats.DroppedPackets.Value() = %d, want = %d\", got, want)\n+ }\n+}\n+\nfunc TestEndpointBindListenAcceptState(t *testing.T) {\nc := context.New(t, defaultMTU)\ndefer c.Cleanup()\n" }, { "change_type": "MODIFY", "old_path": "test/packetimpact/tests/tcp_syncookie_test.go", "new_path": "test/packetimpact/tests/tcp_syncookie_test.go", "diff": "@@ -16,6 +16,8 @@ package tcp_syncookie_test\nimport (\n\"flag\"\n+ \"fmt\"\n+ \"math\"\n\"testing\"\n\"time\"\n@@ -28,43 +30,106 @@ func init() {\ntestbench.Initialize(flag.CommandLine)\n}\n-// TestSynCookie test if the DUT listener is replying back using syn cookies.\n-// The test does not complete the handshake by not sending the ACK to SYNACK.\n-// When syncookies are not used, this forces the listener to retransmit SYNACK.\n-// And when syncookies are being used, there is no such retransmit.\n+// TestTCPSynCookie tests for ACK handling for connections in SYNRCVD state\n+// connections with and without syncookies. It verifies if the passive open\n+// connection is indeed using syncookies before proceeding.\nfunc TestTCPSynCookie(t *testing.T) {\ndut := testbench.NewDUT(t)\n+ for _, tt := range []struct {\n+ accept bool\n+ flags header.TCPFlags\n+ }{\n+ {accept: true, flags: header.TCPFlagAck},\n+ {accept: true, flags: header.TCPFlagAck | header.TCPFlagPsh},\n+ {accept: false, flags: header.TCPFlagAck | header.TCPFlagSyn},\n+ {accept: true, flags: header.TCPFlagAck | header.TCPFlagFin},\n+ {accept: false, flags: header.TCPFlagAck | header.TCPFlagRst},\n+ {accept: false, flags: header.TCPFlagRst},\n+ } {\n+ t.Run(fmt.Sprintf(\"flags=%s\", tt.flags), func(t *testing.T) {\n+ // Make a copy before parallelizing the test and refer to that\n+ // within the test. Otherwise, the test reference could be pointing\n+ // to an incorrect variant based on how it is scheduled.\n+ test := tt\n- // Listening endpoint accepts one more connection than the listen backlog.\n- _, remotePort := dut.CreateListener(t, unix.SOCK_STREAM, unix.IPPROTO_TCP, 1 /*backlog*/)\n+ t.Parallel()\n+\n+ // Listening endpoint accepts one more connection than the listen\n+ // backlog. Listener starts using syncookies when it sees a new SYN\n+ // and has backlog size of connections in SYNRCVD state. Keep the\n+ // listen backlog 1, so that the test can define 2 connections\n+ // without and with using syncookies.\n+ listenFD, remotePort := dut.CreateListener(t, unix.SOCK_STREAM, unix.IPPROTO_TCP, 1 /*backlog*/)\n+ defer dut.Close(t, listenFD)\nvar withoutSynCookieConn testbench.TCPIPv4\nvar withSynCookieConn testbench.TCPIPv4\n- // Test if the DUT listener replies to more SYNs than listen backlog+1\nfor _, conn := range []*testbench.TCPIPv4{&withoutSynCookieConn, &withSynCookieConn} {\n*conn = dut.Net.NewTCPIPv4(t, testbench.TCP{DstPort: &remotePort}, testbench.TCP{SrcPort: &remotePort})\n}\ndefer withoutSynCookieConn.Close(t)\ndefer withSynCookieConn.Close(t)\n- checkSynAck := func(t *testing.T, conn *testbench.TCPIPv4, expectRetransmit bool) {\n- // Expect dut connection to have transitioned to SYN-RCVD state.\n- conn.Send(t, testbench.TCP{Flags: testbench.TCPFlags(header.TCPFlagSyn)})\n- if _, err := conn.ExpectData(t, &testbench.TCP{Flags: testbench.TCPFlags(header.TCPFlagSyn | header.TCPFlagAck)}, nil, time.Second); err != nil {\n- t.Fatalf(\"expected SYN-ACK, but got %s\", err)\n+ // Setup the 2 connections in SYNRCVD state and verify if one of the\n+ // connection is indeed using syncookies by checking for absence of\n+ // SYNACK retransmits.\n+ for _, c := range []struct {\n+ desc string\n+ conn *testbench.TCPIPv4\n+ expectRetransmit bool\n+ }{\n+ {desc: \"without syncookies\", conn: &withoutSynCookieConn, expectRetransmit: true},\n+ {desc: \"with syncookies\", conn: &withSynCookieConn, expectRetransmit: false},\n+ } {\n+ t.Run(c.desc, func(t *testing.T) {\n+ // Expect dut connection to have transitioned to SYNRCVD state.\n+ c.conn.Send(t, testbench.TCP{Flags: testbench.TCPFlags(header.TCPFlagSyn)})\n+ if _, err := c.conn.ExpectData(t, &testbench.TCP{Flags: testbench.TCPFlags(header.TCPFlagSyn | header.TCPFlagAck)}, nil, time.Second); err != nil {\n+ t.Fatalf(\"expected SYNACK, but got %s\", err)\n}\n- // If the DUT listener is using syn cookies, it will not retransmit SYNACK\n- got, err := conn.ExpectData(t, &testbench.TCP{SeqNum: testbench.Uint32(uint32(*conn.RemoteSeqNum(t) - 1)), Flags: testbench.TCPFlags(header.TCPFlagSyn | header.TCPFlagAck)}, nil, 2*time.Second)\n- if expectRetransmit && err != nil {\n- t.Fatalf(\"expected retransmitted SYN-ACK, but got %s\", err)\n+ // If the DUT listener is using syn cookies, it will not retransmit SYNACK.\n+ got, err := c.conn.ExpectData(t, &testbench.TCP{SeqNum: testbench.Uint32(uint32(*c.conn.RemoteSeqNum(t) - 1)), Flags: testbench.TCPFlags(header.TCPFlagSyn | header.TCPFlagAck)}, nil, 2*time.Second)\n+ if c.expectRetransmit && err != nil {\n+ t.Fatalf(\"expected retransmitted SYNACK, but got %s\", err)\n+ }\n+ if !c.expectRetransmit && err == nil {\n+ t.Fatalf(\"expected no retransmitted SYNACK, but got %s\", got)\n}\n- if !expectRetransmit && err == nil {\n- t.Fatalf(\"expected no retransmitted SYN-ACK, but got %s\", got)\n+ })\n}\n+\n+ // Check whether ACKs with the given flags completes the handshake.\n+ for _, c := range []struct {\n+ desc string\n+ conn *testbench.TCPIPv4\n+ }{\n+ {desc: \"with syncookies\", conn: &withSynCookieConn},\n+ {desc: \"without syncookies\", conn: &withoutSynCookieConn},\n+ } {\n+ t.Run(c.desc, func(t *testing.T) {\n+ pfds := dut.Poll(t, []unix.PollFd{{Fd: listenFD, Events: math.MaxInt16}}, 0 /*timeout*/)\n+ if got, want := len(pfds), 0; got != want {\n+ t.Fatalf(\"dut.Poll(...) = %d, want = %d\", got, want)\n}\n- t.Run(\"without syncookies\", func(t *testing.T) { checkSynAck(t, &withoutSynCookieConn, true /*expectRetransmit*/) })\n- t.Run(\"with syncookies\", func(t *testing.T) { checkSynAck(t, &withSynCookieConn, false /*expectRetransmit*/) })\n+ c.conn.Send(t, testbench.TCP{Flags: testbench.TCPFlags(test.flags)})\n+ pfds = dut.Poll(t, []unix.PollFd{{Fd: listenFD, Events: unix.POLLIN}}, time.Second)\n+ want := 0\n+ if test.accept {\n+ want = 1\n+ }\n+ if got := len(pfds); got != want {\n+ t.Fatalf(\"got dut.Poll(...) = %d, want = %d\", got, want)\n+ }\n+ // Accept the connection to enable poll on any subsequent connection.\n+ if test.accept {\n+ fd, _ := dut.Accept(t, listenFD)\n+ dut.Close(t, fd)\n+ }\n+ })\n+ }\n+ })\n+ }\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Ignore RST received for a TCP listener The current implementation has a bug where TCP listener does not ignore RSTs from the peer. While handling RST+ACK from the peer, this bug can complete handshakes that use syncookies. This results in half-open connection delivered to the accept queue. Fixes #6076 PiperOrigin-RevId: 376868749
259,853
01.06.2021 15:31:37
25,200
d7d8a0a5aee841dd7958b0e6bc3b544016d19c24
vfs: Don't allow to mount anything on top of detached mounts
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/mount.go", "new_path": "pkg/sentry/vfs/mount.go", "diff": "@@ -220,7 +220,7 @@ func (vfs *VirtualFilesystem) ConnectMountAt(ctx context.Context, creds *auth.Cr\nvdDentry := vd.dentry\nvdDentry.mu.Lock()\nfor {\n- if vdDentry.dead {\n+ if vd.mount.umounted || vdDentry.dead {\nvdDentry.mu.Unlock()\nvfs.mountMu.Unlock()\nvd.DecRef(ctx)\n" } ]
Go
Apache License 2.0
google/gvisor
vfs: Don't allow to mount anything on top of detached mounts PiperOrigin-RevId: 376932659
260,007
03.06.2021 09:42:42
25,200
ddcd17399b1c1083a132772702d516c154815680
Reset global_num_signals_received on RegisterSignalHandler Previously, the value of global_num_signals_received would persist between tests. Now, we reset the value to zero when we register a signal handler.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/pipe.cc", "new_path": "test/syscalls/linux/pipe.cc", "diff": "@@ -53,6 +53,7 @@ void SigRecordingHandler(int signum, siginfo_t* siginfo,\n}\nPosixErrorOr<Cleanup> RegisterSignalHandler(int signum) {\n+ global_num_signals_received = 0;\nstruct sigaction handler;\nhandler.sa_sigaction = SigRecordingHandler;\nsigemptyset(&handler.sa_mask);\n" } ]
Go
Apache License 2.0
google/gvisor
Reset global_num_signals_received on RegisterSignalHandler Previously, the value of global_num_signals_received would persist between tests. Now, we reset the value to zero when we register a signal handler. PiperOrigin-RevId: 377308357
259,992
03.06.2021 20:05:33
25,200
86cf56eb71215e24fec49272d915f80c9c569c05
Add additional mmap seccomp rule HostFileMapper.RegenerateMappings calls mmap with MAP_SHARED|MAP_FIXED and these were not allowed. Closes
[ { "change_type": "MODIFY", "old_path": "pkg/seccomp/seccomp.go", "new_path": "pkg/seccomp/seccomp.go", "diff": "@@ -36,14 +36,10 @@ const (\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-//\n-// RET_TRAP is used in violations, instead of RET_KILL_PROCESS, in the\n-// following cases:\n-// 1. Kernel doesn't support RET_KILL_PROCESS: RET_KILL_THREAD only kills the\n-// offending thread and often keeps the sentry hanging.\n-// 2. Debug: RET_TRAP generates a panic followed by a stack trace which is\n-// much easier to debug then RET_KILL_PROCESS which can't be caught.\n+// specification will trigger RET_KILL_PROCESS. If RET_KILL_PROCESS is not\n+// supported, violations will trigger RET_TRAP instead. RET_KILL_THREAD is not\n+// used because it only kills the offending thread and often keeps the sentry\n+// hanging.\n//\n// Be aware that RET_TRAP sends SIGSYS to the process and it may be ignored,\n// making it possible for the process to continue running after a violation.\n" }, { "change_type": "MODIFY", "old_path": "runsc/boot/filter/config.go", "new_path": "runsc/boot/filter/config.go", "diff": "@@ -196,6 +196,12 @@ var allowedSyscalls = seccomp.SyscallRules{\nseccomp.MatchAny{},\nseccomp.EqualTo(unix.MAP_SHARED),\n},\n+ {\n+ seccomp.MatchAny{},\n+ seccomp.MatchAny{},\n+ seccomp.MatchAny{},\n+ seccomp.EqualTo(unix.MAP_SHARED | unix.MAP_FIXED),\n+ },\n{\nseccomp.MatchAny{},\nseccomp.MatchAny{},\n" } ]
Go
Apache License 2.0
google/gvisor
Add additional mmap seccomp rule HostFileMapper.RegenerateMappings calls mmap with MAP_SHARED|MAP_FIXED and these were not allowed. Closes #6116 PiperOrigin-RevId: 377428463
259,967
04.06.2021 13:51:05
25,200
240629524905024c7564d009cbc47c7b44064219
Add bind syscall tests for ICMP and ICMPv6 Updates Updates Updates
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/BUILD", "new_path": "test/syscalls/linux/BUILD", "diff": "@@ -1572,10 +1572,13 @@ cc_binary(\nsrcs = [\"ping_socket.cc\"],\nlinkstatic = 1,\ndeps = [\n+ \":ip_socket_test_util\",\n\":socket_test_util\",\n\"//test/util:file_descriptor\",\n+ \"@com_google_absl//absl/algorithm:container\",\n+ \"@com_google_absl//absl/strings\",\n+ \"@com_google_absl//absl/types:optional\",\ngtest,\n- \"//test/util:save_util\",\n\"//test/util:test_main\",\n\"//test/util:test_util\",\n],\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": "@@ -140,6 +140,22 @@ SocketPairKind IPv4UDPUnboundSocketPair(int type) {\n/* dual_stack = */ false)};\n}\n+SocketKind ICMPUnboundSocket(int type) {\n+ std::string description =\n+ absl::StrCat(DescribeSocketType(type), \"ICMP socket\");\n+ return SocketKind{\n+ description, AF_INET, type | SOCK_DGRAM, IPPROTO_ICMP,\n+ UnboundSocketCreator(AF_INET, type | SOCK_DGRAM, IPPROTO_ICMP)};\n+}\n+\n+SocketKind ICMPv6UnboundSocket(int type) {\n+ std::string description =\n+ absl::StrCat(DescribeSocketType(type), \"ICMPv6 socket\");\n+ return SocketKind{\n+ description, AF_INET6, type | SOCK_DGRAM, IPPROTO_ICMPV6,\n+ UnboundSocketCreator(AF_INET6, type | SOCK_DGRAM, IPPROTO_ICMPV6)};\n+}\n+\nSocketKind IPv4UDPUnboundSocket(int type) {\nstd::string description =\nabsl::StrCat(DescribeSocketType(type), \"IPv4 UDP socket\");\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": "@@ -84,20 +84,28 @@ SocketPairKind DualStackUDPBidirectionalBindSocketPair(int type);\n// SocketPairs created with AF_INET and the given type.\nSocketPairKind IPv4UDPUnboundSocketPair(int type);\n+// ICMPUnboundSocket returns a SocketKind that represents a SimpleSocket created\n+// with AF_INET, SOCK_DGRAM, IPPROTO_ICMP, and the given type.\n+SocketKind ICMPUnboundSocket(int type);\n+\n+// ICMPv6UnboundSocket returns a SocketKind that represents a SimpleSocket\n+// created with AF_INET6, SOCK_DGRAM, IPPROTO_ICMPV6, and the given type.\n+SocketKind ICMPv6UnboundSocket(int type);\n+\n// IPv4UDPUnboundSocket returns a SocketKind that represents a SimpleSocket\n-// created with AF_INET, SOCK_DGRAM, and the given type.\n+// created with AF_INET, SOCK_DGRAM, IPPROTO_UDP, and the given type.\nSocketKind IPv4UDPUnboundSocket(int type);\n// IPv6UDPUnboundSocket returns a SocketKind that represents a SimpleSocket\n-// created with AF_INET6, SOCK_DGRAM, and the given type.\n+// created with AF_INET6, SOCK_DGRAM, IPPROTO_UDP, and the given type.\nSocketKind IPv6UDPUnboundSocket(int type);\n// IPv4TCPUnboundSocket returns a SocketKind that represents a SimpleSocket\n-// created with AF_INET, SOCK_STREAM and the given type.\n+// created with AF_INET, SOCK_STREAM, IPPROTO_TCP and the given type.\nSocketKind IPv4TCPUnboundSocket(int type);\n// IPv6TCPUnboundSocket returns a SocketKind that represents a SimpleSocket\n-// created with AF_INET6, SOCK_STREAM and the given type.\n+// created with AF_INET6, SOCK_STREAM, IPPROTO_TCP and the given type.\nSocketKind IPv6TCPUnboundSocket(int type);\n// IfAddrHelper is a helper class that determines the local interfaces present\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/ping_socket.cc", "new_path": "test/syscalls/linux/ping_socket.cc", "diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n+#include <errno.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <netinet/ip_icmp.h>\n#include <sys/types.h>\n#include <unistd.h>\n+#include <cctype>\n+#include <cstring>\n#include <vector>\n#include \"gtest/gtest.h\"\n+#include \"absl/algorithm/container.h\"\n+#include \"absl/strings/str_join.h\"\n+#include \"absl/types/optional.h\"\n+#include \"test/syscalls/linux/ip_socket_test_util.h\"\n#include \"test/syscalls/linux/socket_test_util.h\"\n#include \"test/util/file_descriptor.h\"\n-#include \"test/util/save_util.h\"\n#include \"test/util/test_util.h\"\n+// Note: These tests require /proc/sys/net/ipv4/ping_group_range to be\n+// configured to allow the tester to create ping sockets (see icmp(7)).\n+\nnamespace gvisor {\nnamespace testing {\nnamespace {\n@@ -42,7 +51,8 @@ TEST(PingSocket, ICMPPortExhaustion) {\nauto s = Socket(AF_INET, SOCK_DGRAM, IPPROTO_ICMP);\nif (!s.ok()) {\nASSERT_EQ(s.error().errno_value(), EACCES);\n- GTEST_SKIP();\n+ GTEST_SKIP() << \"TODO(gvisor.dev/issue/6126): Buildkite does not allow \"\n+ \"creation of ICMP or ICMPv6 sockets\";\n}\n}\n@@ -70,7 +80,212 @@ TEST(PingSocket, ICMPPortExhaustion) {\n}\n}\n-} // namespace\n+struct BindTestCase {\n+ TestAddress bind_to;\n+ int want = 0;\n+ absl::optional<int> want_gvisor;\n+};\n+\n+// Test fixture for socket binding.\n+class Fixture\n+ : public ::testing::TestWithParam<std::tuple<SocketKind, BindTestCase>> {};\n+\n+TEST_P(Fixture, Bind) {\n+ auto [socket_factory, test_case] = GetParam();\n+ auto socket = socket_factory.Create();\n+ if (!socket.ok()) {\n+ ASSERT_EQ(socket.error().errno_value(), EACCES);\n+ GTEST_SKIP() << \"TODO(gvisor.dev/issue/6126): Buildkite does not allow \"\n+ \"creation of ICMP or ICMPv6 sockets\";\n+ }\n+ auto socket_fd = std::move(socket).ValueOrDie();\n+ const int want = test_case.want_gvisor.has_value() && IsRunningOnGvisor()\n+ ? *test_case.want_gvisor\n+ : test_case.want;\n+ if (want == 0) {\n+ EXPECT_THAT(bind(socket_fd->get(), AsSockAddr(&test_case.bind_to.addr),\n+ test_case.bind_to.addr_len),\n+ SyscallSucceeds());\n+ } else {\n+ EXPECT_THAT(bind(socket_fd->get(), AsSockAddr(&test_case.bind_to.addr),\n+ test_case.bind_to.addr_len),\n+ SyscallFailsWithErrno(want));\n+ }\n+}\n+\n+std::vector<std::tuple<SocketKind, BindTestCase>> ICMPTestCases() {\n+ return ApplyVec<std::tuple<SocketKind, BindTestCase>>(\n+ [](const BindTestCase& test_case) {\n+ return std::make_tuple(ICMPUnboundSocket(0), test_case);\n+ },\n+ std::vector<BindTestCase>{\n+ {\n+ .bind_to = V4Any(),\n+ .want = 0,\n+ .want_gvisor = 0,\n+ },\n+ {\n+ .bind_to = V4Broadcast(),\n+ .want = EADDRNOTAVAIL,\n+ // TODO(gvisor.dev/issue/5711): Remove want_gvisor once ICMP\n+ // sockets are no longer allowed to bind to broadcast addresses.\n+ .want_gvisor = 0,\n+ },\n+ {\n+ .bind_to = V4Loopback(),\n+ .want = 0,\n+ },\n+ {\n+ .bind_to = V4LoopbackSubnetBroadcast(),\n+ .want = EADDRNOTAVAIL,\n+ // TODO(gvisor.dev/issue/5711): Remove want_gvisor once ICMP\n+ // sockets are no longer allowed to bind to broadcast addresses.\n+ .want_gvisor = 0,\n+ },\n+ {\n+ .bind_to = V4Multicast(),\n+ .want = EADDRNOTAVAIL,\n+ },\n+ {\n+ .bind_to = V4MulticastAllHosts(),\n+ .want = EADDRNOTAVAIL,\n+ },\n+ {\n+ .bind_to = V4AddrStr(\"IPv4UnknownUnicast\", \"192.168.1.1\"),\n+ .want = EADDRNOTAVAIL,\n+ },\n+ // TODO(gvisor.dev/issue/6021): Remove want_gvisor from all the test\n+ // cases below once ICMP sockets return EAFNOSUPPORT when binding to\n+ // IPv6 addresses.\n+ {\n+ .bind_to = V6Any(),\n+ .want = EAFNOSUPPORT,\n+ .want_gvisor = EINVAL,\n+ },\n+ {\n+ .bind_to = V6Loopback(),\n+ .want = EAFNOSUPPORT,\n+ .want_gvisor = EINVAL,\n+ },\n+ {\n+ .bind_to = V6Multicast(),\n+ .want = EAFNOSUPPORT,\n+ .want_gvisor = EINVAL,\n+ },\n+ {\n+ .bind_to = V6MulticastInterfaceLocalAllNodes(),\n+ .want = EAFNOSUPPORT,\n+ .want_gvisor = EINVAL,\n+ },\n+ {\n+ .bind_to = V6MulticastLinkLocalAllNodes(),\n+ .want = EAFNOSUPPORT,\n+ .want_gvisor = EINVAL,\n+ },\n+ {\n+ .bind_to = V6MulticastLinkLocalAllRouters(),\n+ .want = EAFNOSUPPORT,\n+ .want_gvisor = EINVAL,\n+ },\n+ {\n+ .bind_to = V6AddrStr(\"IPv6UnknownUnicast\", \"fc00::1\"),\n+ .want = EAFNOSUPPORT,\n+ .want_gvisor = EINVAL,\n+ },\n+ });\n+}\n+\n+std::vector<std::tuple<SocketKind, BindTestCase>> ICMPv6TestCases() {\n+ return ApplyVec<std::tuple<SocketKind, BindTestCase>>(\n+ [](const BindTestCase& test_case) {\n+ return std::make_tuple(ICMPv6UnboundSocket(0), test_case);\n+ },\n+ std::vector<BindTestCase>{\n+ {\n+ .bind_to = V4Any(),\n+ .want = EINVAL,\n+ },\n+ {\n+ .bind_to = V4Broadcast(),\n+ .want = EINVAL,\n+ },\n+ {\n+ .bind_to = V4Loopback(),\n+ .want = EINVAL,\n+ },\n+ {\n+ .bind_to = V4LoopbackSubnetBroadcast(),\n+ .want = EINVAL,\n+ },\n+ {\n+ .bind_to = V4Multicast(),\n+ .want = EINVAL,\n+ },\n+ {\n+ .bind_to = V4MulticastAllHosts(),\n+ .want = EINVAL,\n+ },\n+ {\n+ .bind_to = V4AddrStr(\"IPv4UnknownUnicast\", \"192.168.1.1\"),\n+ .want = EINVAL,\n+ },\n+ {\n+ .bind_to = V6Any(),\n+ .want = 0,\n+ },\n+ {\n+ .bind_to = V6Loopback(),\n+ .want = 0,\n+ },\n+ // TODO(gvisor.dev/issue/6021): Remove want_gvisor from all the\n+ // multicast test cases below once ICMPv6 sockets return EINVAL when\n+ // binding to IPv6 multicast addresses.\n+ {\n+ .bind_to = V6Multicast(),\n+ .want = EINVAL,\n+ .want_gvisor = EADDRNOTAVAIL,\n+ },\n+ {\n+ .bind_to = V6MulticastInterfaceLocalAllNodes(),\n+ .want = EINVAL,\n+ .want_gvisor = EADDRNOTAVAIL,\n+ },\n+ {\n+ .bind_to = V6MulticastLinkLocalAllNodes(),\n+ .want = EINVAL,\n+ .want_gvisor = EADDRNOTAVAIL,\n+ },\n+ {\n+ .bind_to = V6MulticastLinkLocalAllRouters(),\n+ .want = EINVAL,\n+ .want_gvisor = EADDRNOTAVAIL,\n+ },\n+ {\n+ .bind_to = V6AddrStr(\"IPv6UnknownUnicast\", \"fc00::1\"),\n+ .want = EADDRNOTAVAIL,\n+ },\n+ });\n+}\n+\n+std::vector<std::tuple<SocketKind, BindTestCase>> AllTestCases() {\n+ return VecCat<std::tuple<SocketKind, BindTestCase>>(ICMPTestCases(),\n+ ICMPv6TestCases());\n+}\n+\n+std::string TestDescription(\n+ const ::testing::TestParamInfo<Fixture::ParamType>& info) {\n+ auto [socket_factory, test_case] = info.param;\n+ std::string name = absl::StrJoin(\n+ {socket_factory.description, test_case.bind_to.description}, \"_\");\n+ absl::c_replace_if(\n+ name, [](char c) { return !std::isalnum(c); }, '_');\n+ return name;\n+}\n+\n+INSTANTIATE_TEST_SUITE_P(PingSockets, Fixture,\n+ ::testing::ValuesIn(AllTestCases()), TestDescription);\n+\n+} // namespace\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": "#include \"test/syscalls/linux/socket_test_util.h\"\n#include <arpa/inet.h>\n+#include <netinet/in.h>\n#include <poll.h>\n#include <sys/socket.h>\n@@ -798,84 +799,82 @@ TestAddress TestAddress::WithPort(uint16_t port) const {\nreturn addr;\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+namespace {\n-TestAddress V4Loopback() {\n- TestAddress t(\"V4Loopback\");\n+TestAddress V4Addr(std::string description, in_addr_t addr) {\n+ TestAddress t(std::move(description));\nt.addr.ss_family = AF_INET;\nt.addr_len = sizeof(sockaddr_in);\n- reinterpret_cast<sockaddr_in*>(&t.addr)->sin_addr.s_addr =\n- htonl(INADDR_LOOPBACK);\n+ reinterpret_cast<sockaddr_in*>(&t.addr)->sin_addr.s_addr = addr;\nreturn t;\n}\n-TestAddress V4MappedAny() {\n- TestAddress t(\"V4MappedAny\");\n+TestAddress V6Addr(std::string description, const in6_addr& addr) {\n+ TestAddress t(std::move(description));\nt.addr.ss_family = AF_INET6;\nt.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+ reinterpret_cast<sockaddr_in6*>(&t.addr)->sin6_addr = addr;\nreturn t;\n}\n+} // namespace\n+\n+TestAddress V4AddrStr(std::string description, const char* addr) {\n+ in_addr_t s_addr;\n+ inet_pton(AF_INET, addr, &s_addr);\n+ return V4Addr(description, s_addr);\n+}\n+\n+TestAddress V6AddrStr(std::string description, const char* addr) {\n+ struct in6_addr s_addr;\n+ inet_pton(AF_INET6, addr, &s_addr);\n+ return V6Addr(description, s_addr);\n+}\n+\n+TestAddress V4Any() { return V4Addr(\"V4Any\", htonl(INADDR_ANY)); }\n+\n+TestAddress V4Broadcast() {\n+ return V4Addr(\"V4Broadcast\", htonl(INADDR_BROADCAST));\n+}\n+\n+TestAddress V4Loopback() {\n+ return V4Addr(\"V4Loopback\", htonl(INADDR_LOOPBACK));\n+}\n+\n+TestAddress V4LoopbackSubnetBroadcast() {\n+ return V4AddrStr(\"V4LoopbackSubnetBroadcast\", \"127.255.255.255\");\n+}\n+\n+TestAddress V4MappedAny() { return V6AddrStr(\"V4MappedAny\", \"::ffff:0.0.0.0\"); }\n+\nTestAddress 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+ return V6AddrStr(\"V4MappedLoopback\", \"::ffff:127.0.0.1\");\n}\nTestAddress 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+ return V4Addr(\"V4Multicast\", inet_addr(kMulticastAddress));\n}\n-TestAddress V4Broadcast() {\n- TestAddress t(\"V4Broadcast\");\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_BROADCAST);\n- return t;\n+TestAddress V4MulticastAllHosts() {\n+ return V4Addr(\"V4MulticastAllHosts\", htonl(INADDR_ALLHOSTS_GROUP));\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+TestAddress V6Any() { return V6Addr(\"V6Any\", in6addr_any); }\n+\n+TestAddress V6Loopback() { return V6Addr(\"V6Loopback\", in6addr_loopback); }\n+\n+TestAddress V6Multicast() { return V6AddrStr(\"V6Multicast\", \"ff05::1234\"); }\n+\n+TestAddress V6MulticastInterfaceLocalAllNodes() {\n+ return V6AddrStr(\"V6MulticastInterfaceLocalAllNodes\", \"ff01::1\");\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+TestAddress V6MulticastLinkLocalAllNodes() {\n+ return V6AddrStr(\"V6MulticastLinkLocalAllNodes\", \"ff02::1\");\n}\n-TestAddress V6Multicast() {\n- TestAddress t(\"V6Multicast\");\n- t.addr.ss_family = AF_INET6;\n- t.addr_len = sizeof(sockaddr_in6);\n- EXPECT_EQ(\n- 1,\n- inet_pton(AF_INET6, \"ff05::1234\",\n- reinterpret_cast<sockaddr_in6*>(&t.addr)->sin6_addr.s6_addr));\n- return t;\n+TestAddress V6MulticastLinkLocalAllRouters() {\n+ return V6AddrStr(\"V6MulticastLinkLocalAllRouters\", \"ff02::2\");\n}\n// Checksum computes the internet checksum of a buffer.\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_test_util.h", "new_path": "test/syscalls/linux/socket_test_util.h", "diff": "@@ -499,15 +499,45 @@ struct TestAddress {\nconstexpr char kMulticastAddress[] = \"224.0.2.1\";\nconstexpr char kBroadcastAddress[] = \"255.255.255.255\";\n+// Returns a TestAddress with `addr` parsed as an IPv4 address described by\n+// `description`.\n+TestAddress V4AddrStr(std::string description, const char* addr);\n+// Returns a TestAddress with `addr` parsed as an IPv6 address described by\n+// `description`.\n+TestAddress V6AddrStr(std::string description, const char* addr);\n+\n+// Returns a TestAddress for the IPv4 any address.\nTestAddress V4Any();\n+// Returns a TestAddress for the IPv4 limited broadcast address.\nTestAddress V4Broadcast();\n+// Returns a TestAddress for the IPv4 loopback address.\nTestAddress V4Loopback();\n+// Returns a TestAddress for the subnet broadcast of the IPv4 loopback address.\n+TestAddress V4LoopbackSubnetBroadcast();\n+// Returns a TestAddress for the IPv4-mapped IPv6 any address.\nTestAddress V4MappedAny();\n+// Returns a TestAddress for the IPv4-mapped IPv6 loopback address.\nTestAddress V4MappedLoopback();\n+// Returns a TestAddress for a IPv4 multicast address.\nTestAddress V4Multicast();\n+// Returns a TestAddress for the IPv4 all-hosts multicast group address.\n+TestAddress V4MulticastAllHosts();\n+\n+// Returns a TestAddress for the IPv6 any address.\nTestAddress V6Any();\n+// Returns a TestAddress for the IPv6 loopback address.\nTestAddress V6Loopback();\n+// Returns a TestAddress for a IPv6 multicast address.\nTestAddress V6Multicast();\n+// Returns a TestAddress for the IPv6 interface-local all-nodes multicast group\n+// address.\n+TestAddress V6MulticastInterfaceLocalAllNodes();\n+// Returns a TestAddress for the IPv6 link-local all-nodes multicast group\n+// address.\n+TestAddress V6MulticastLinkLocalAllNodes();\n+// Returns a TestAddress for the IPv6 link-local all-routers multicast group\n+// address.\n+TestAddress V6MulticastLinkLocalAllRouters();\n// Compute the internet checksum of an IP header.\nuint16_t IPChecksum(struct iphdr ip);\n" } ]
Go
Apache License 2.0
google/gvisor
Add bind syscall tests for ICMP and ICMPv6 Updates #5711 Updates #6021 Updates #6022 PiperOrigin-RevId: 377582446
259,967
04.06.2021 15:17:04
25,200
a2c88252c84839550bef1543ed5cc904340a8a3e
Allow sniffer receive timeout durations less than one usec Fixes the erronously signaled fatal error when the sniffer receive timeout duration is less than one usec. This was caused by the converstion from float64 to int64; the integer conversion truncated the floating point to 0, which signaled the fatal error.
[ { "change_type": "MODIFY", "old_path": "test/packetimpact/testbench/rawsockets.go", "new_path": "test/packetimpact/testbench/rawsockets.go", "diff": "@@ -17,7 +17,6 @@ package testbench\nimport (\n\"encoding/binary\"\n\"fmt\"\n- \"math\"\n\"net\"\n\"testing\"\n\"time\"\n@@ -81,19 +80,20 @@ func (s *Sniffer) Recv(t *testing.T, timeout time.Duration) []byte {\ndeadline := time.Now().Add(timeout)\nfor {\n- timeout = deadline.Sub(time.Now())\n+ timeout = time.Until(deadline)\nif timeout <= 0 {\nreturn nil\n}\n- whole, frac := math.Modf(timeout.Seconds())\n- tv := unix.Timeval{\n- Sec: int64(whole),\n- Usec: int64(frac * float64(time.Second/time.Microsecond)),\n+ usec := timeout.Microseconds()\n+ if usec == 0 {\n+ // Timeout is less than a microsecond; set usec to 1 to avoid\n+ // blocking indefinitely.\n+ usec = 1\n}\n- // The following should never happen, but having this guard here is better\n- // than blocking indefinitely in the future.\n- if tv.Sec == 0 && tv.Usec == 0 {\n- t.Fatal(\"setting SO_RCVTIMEO to 0 means blocking indefinitely\")\n+ const microsInOne = 1e6\n+ tv := unix.Timeval{\n+ Sec: usec / microsInOne,\n+ Usec: usec % microsInOne,\n}\nif err := unix.SetsockoptTimeval(s.fd, unix.SOL_SOCKET, unix.SO_RCVTIMEO, &tv); err != nil {\nt.Fatalf(\"can't setsockopt SO_RCVTIMEO: %s\", err)\n" } ]
Go
Apache License 2.0
google/gvisor
Allow sniffer receive timeout durations less than one usec Fixes the erronously signaled fatal error when the sniffer receive timeout duration is less than one usec. This was caused by the converstion from float64 to int64; the integer conversion truncated the floating point to 0, which signaled the fatal error. PiperOrigin-RevId: 377600179
259,858
04.06.2021 16:27:41
25,200
fb745d7d9d73482b5b9edce380e4564d9b49d783
Update GitHub packages.
[ { "change_type": "MODIFY", "old_path": "WORKSPACE", "new_path": "WORKSPACE", "diff": "@@ -131,10 +131,10 @@ go_repository(\n)\ngo_repository(\n- name = \"com_github_google_go_github_v32\",\n- importpath = \"github.com/google/go-github/v32\",\n- sum = \"h1:GWkQOdXqviCPx7Q7Fj+KyPoGm4SwHRh8rheoPhd27II=\",\n- version = \"v32.1.0\",\n+ name = \"com_github_google_go_github_v35\",\n+ importpath = \"github.com/google/go-github/v35\",\n+ sum = \"h1:s/soW8jauhjUC3rh8JI0FePuocj0DEI9DNBg/bVplE8=\",\n+ version = \"v35.2.0\",\n)\ngo_repository(\n" }, { "change_type": "MODIFY", "old_path": "tools/github/BUILD", "new_path": "tools/github/BUILD", "diff": "@@ -8,7 +8,7 @@ go_binary(\nnogo = False,\ndeps = [\n\"//tools/github/reviver\",\n- \"@com_github_google_go_github_v32//github:go_default_library\",\n+ \"@com_github_google_go_github_v35//github:go_default_library\",\n\"@org_golang_x_oauth2//:go_default_library\",\n],\n)\n" }, { "change_type": "MODIFY", "old_path": "tools/github/reviver/BUILD", "new_path": "tools/github/reviver/BUILD", "diff": "@@ -12,7 +12,7 @@ go_library(\nvisibility = [\n\"//tools/github:__subpackages__\",\n],\n- deps = [\"@com_github_google_go_github_v32//github:go_default_library\"],\n+ deps = [\"@com_github_google_go_github_v35//github:go_default_library\"],\n)\ngo_test(\n" } ]
Go
Apache License 2.0
google/gvisor
Update GitHub packages. PiperOrigin-RevId: 377611852
259,967
04.06.2021 16:44:50
25,200
a2d340739649862a23d86f3e32f1bb3b928697ef
Forward verbose flag to packetimpact tester Forwards the testing verbose flag to the packetimpact test runner. This is necessary for debugging inside packetimpact tests. When this flag is present, all t.Logs in the packetimpact test wil be shown in the resulting test output.
[ { "change_type": "MODIFY", "old_path": "test/packetimpact/runner/dut.go", "new_path": "test/packetimpact/runner/dut.go", "diff": "@@ -363,6 +363,9 @@ func TestWithDUT(ctx context.Context, t *testing.T, mkDevice func(*dockerutil.Co\n// and receives packets and also sends POSIX socket commands to the\n// posix_server to be executed on the DUT.\ntestArgs := []string{containerTestbenchBinary}\n+ if testing.Verbose() {\n+ testArgs = append(testArgs, \"-test.v\")\n+ }\ntestArgs = append(testArgs, extraTestArgs...)\ntestArgs = append(testArgs,\nfmt.Sprintf(\"--native=%t\", native),\n@@ -395,6 +398,8 @@ func TestWithDUT(ctx context.Context, t *testing.T, mkDevice func(*dockerutil.Co\n} else if expectFailure {\nt.Logf(`test failed as expected: %v\n%s`, err, testLogs)\n+ } else if testing.Verbose() {\n+ t.Log(testLogs)\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "test/packetimpact/testbench/testbench.go", "new_path": "test/packetimpact/testbench/testbench.go", "diff": "@@ -132,6 +132,7 @@ func registerFlags(fs *flag.FlagSet) {\n// Initialize initializes the testbench, it parse the flags and sets up the\n// pool of test networks for testbench's later use.\nfunc Initialize(fs *flag.FlagSet) {\n+ testing.Init()\nregisterFlags(fs)\nflag.Parse()\nif err := loadDUTInfos(); err != nil {\n" } ]
Go
Apache License 2.0
google/gvisor
Forward verbose flag to packetimpact tester Forwards the testing verbose flag to the packetimpact test runner. This is necessary for debugging inside packetimpact tests. When this flag is present, all t.Logs in the packetimpact test wil be shown in the resulting test output. PiperOrigin-RevId: 377614550
259,885
07.06.2021 11:39:57
25,200
ee1003bde2291d6d892701b33c23bd7dd91d44f6
Implement RENAME_NOREPLACE for all VFS2 filesystem implementations.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/gofer/filesystem.go", "new_path": "pkg/sentry/fsimpl/gofer/filesystem.go", "diff": "@@ -1194,11 +1194,7 @@ func (fs *filesystem) ReadlinkAt(ctx context.Context, rp *vfs.ResolvingPath) (st\n// RenameAt implements vfs.FilesystemImpl.RenameAt.\nfunc (fs *filesystem) RenameAt(ctx context.Context, rp *vfs.ResolvingPath, oldParentVD vfs.VirtualDentry, oldName string, opts vfs.RenameOptions) error {\n- if opts.Flags != 0 {\n- // Requires 9P support.\n- return syserror.EINVAL\n- }\n-\n+ // Resolve newParent first to verify that it's on this Mount.\nvar ds *[]*dentry\nfs.renameMu.Lock()\ndefer fs.renameMuUnlockAndCheckCaching(ctx, &ds)\n@@ -1206,8 +1202,21 @@ func (fs *filesystem) RenameAt(ctx context.Context, rp *vfs.ResolvingPath, oldPa\nif err != nil {\nreturn err\n}\n+\n+ if opts.Flags&^linux.RENAME_NOREPLACE != 0 {\n+ return syserror.EINVAL\n+ }\n+ if fs.opts.interop == InteropModeShared && opts.Flags&linux.RENAME_NOREPLACE != 0 {\n+ // Requires 9P support to synchronize with other remote filesystem\n+ // users.\n+ return syserror.EINVAL\n+ }\n+\nnewName := rp.Component()\nif newName == \".\" || newName == \"..\" {\n+ if opts.Flags&linux.RENAME_NOREPLACE != 0 {\n+ return syserror.EEXIST\n+ }\nreturn syserror.EBUSY\n}\nmnt := rp.Mount()\n@@ -1280,6 +1289,9 @@ func (fs *filesystem) RenameAt(ctx context.Context, rp *vfs.ResolvingPath, oldPa\n}\nvar replacedVFSD *vfs.Dentry\nif replaced != nil {\n+ if opts.Flags&linux.RENAME_NOREPLACE != 0 {\n+ return syserror.EEXIST\n+ }\nreplacedVFSD = &replaced.vfsd\nif replaced.isDir() {\nif !renamed.isDir() {\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/kernfs/filesystem.go", "new_path": "pkg/sentry/fsimpl/kernfs/filesystem.go", "diff": "@@ -635,12 +635,6 @@ func (fs *Filesystem) ReadlinkAt(ctx context.Context, rp *vfs.ResolvingPath) (st\n// RenameAt implements vfs.FilesystemImpl.RenameAt.\nfunc (fs *Filesystem) RenameAt(ctx context.Context, rp *vfs.ResolvingPath, oldParentVD vfs.VirtualDentry, oldName string, opts vfs.RenameOptions) error {\n- // Only RENAME_NOREPLACE is supported.\n- if opts.Flags&^linux.RENAME_NOREPLACE != 0 {\n- return syserror.EINVAL\n- }\n- noReplace := opts.Flags&linux.RENAME_NOREPLACE != 0\n-\nfs.mu.Lock()\ndefer fs.processDeferredDecRefs(ctx)\ndefer fs.mu.Unlock()\n@@ -651,6 +645,13 @@ func (fs *Filesystem) RenameAt(ctx context.Context, rp *vfs.ResolvingPath, oldPa\nif err != nil {\nreturn err\n}\n+\n+ // Only RENAME_NOREPLACE is supported.\n+ if opts.Flags&^linux.RENAME_NOREPLACE != 0 {\n+ return syserror.EINVAL\n+ }\n+ noReplace := opts.Flags&linux.RENAME_NOREPLACE != 0\n+\nmnt := rp.Mount()\nif mnt != oldParentVD.Mount() {\nreturn syserror.EXDEV\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/overlay/filesystem.go", "new_path": "pkg/sentry/fsimpl/overlay/filesystem.go", "diff": "@@ -1017,10 +1017,7 @@ func (fs *filesystem) ReadlinkAt(ctx context.Context, rp *vfs.ResolvingPath) (st\n// RenameAt implements vfs.FilesystemImpl.RenameAt.\nfunc (fs *filesystem) RenameAt(ctx context.Context, rp *vfs.ResolvingPath, oldParentVD vfs.VirtualDentry, oldName string, opts vfs.RenameOptions) error {\n- if opts.Flags != 0 {\n- return syserror.EINVAL\n- }\n-\n+ // Resolve newParent first to verify that it's on this Mount.\nvar ds *[]*dentry\nfs.renameMu.Lock()\ndefer fs.renameMuUnlockAndCheckDrop(ctx, &ds)\n@@ -1028,8 +1025,16 @@ func (fs *filesystem) RenameAt(ctx context.Context, rp *vfs.ResolvingPath, oldPa\nif err != nil {\nreturn err\n}\n+\n+ if opts.Flags&^linux.RENAME_NOREPLACE != 0 {\n+ return syserror.EINVAL\n+ }\n+\nnewName := rp.Component()\nif newName == \".\" || newName == \"..\" {\n+ if opts.Flags&linux.RENAME_NOREPLACE != 0 {\n+ return syserror.EEXIST\n+ }\nreturn syserror.EBUSY\n}\nmnt := rp.Mount()\n@@ -1093,6 +1098,9 @@ func (fs *filesystem) RenameAt(ctx context.Context, rp *vfs.ResolvingPath, oldPa\nreturn err\n}\nif replaced != nil {\n+ if opts.Flags&linux.RENAME_NOREPLACE != 0 {\n+ return syserror.EEXIST\n+ }\nreplacedVFSD = &replaced.vfsd\nif replaced.isDir() {\nif !renamed.isDir() {\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/tmpfs/filesystem.go", "new_path": "pkg/sentry/fsimpl/tmpfs/filesystem.go", "diff": "@@ -496,20 +496,24 @@ func (fs *filesystem) ReadlinkAt(ctx context.Context, rp *vfs.ResolvingPath) (st\n// RenameAt implements vfs.FilesystemImpl.RenameAt.\nfunc (fs *filesystem) RenameAt(ctx context.Context, rp *vfs.ResolvingPath, oldParentVD vfs.VirtualDentry, oldName string, opts vfs.RenameOptions) error {\n- if opts.Flags != 0 {\n- // TODO(b/145974740): Support renameat2 flags.\n- return syserror.EINVAL\n- }\n-\n- // Resolve newParent first to verify that it's on this Mount.\n+ // Resolve newParentDir first to verify that it's on this Mount.\nfs.mu.Lock()\ndefer fs.mu.Unlock()\nnewParentDir, err := walkParentDirLocked(ctx, rp, rp.Start().Impl().(*dentry))\nif err != nil {\nreturn err\n}\n+\n+ if opts.Flags&^linux.RENAME_NOREPLACE != 0 {\n+ // TODO(b/145974740): Support other renameat2 flags.\n+ return syserror.EINVAL\n+ }\n+\nnewName := rp.Component()\nif newName == \".\" || newName == \"..\" {\n+ if opts.Flags&linux.RENAME_NOREPLACE != 0 {\n+ return syserror.EEXIST\n+ }\nreturn syserror.EBUSY\n}\nmnt := rp.Mount()\n@@ -556,6 +560,9 @@ func (fs *filesystem) RenameAt(ctx context.Context, rp *vfs.ResolvingPath, oldPa\n}\nreplaced, ok := newParentDir.childMap[newName]\nif ok {\n+ if opts.Flags&linux.RENAME_NOREPLACE != 0 {\n+ return syserror.EEXIST\n+ }\nreplacedDir, ok := replaced.inode.impl.(*directory)\nif ok {\nif !renamed.inode.isDir() {\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/rename.cc", "new_path": "test/syscalls/linux/rename.cc", "diff": "#include \"test/util/temp_path.h\"\n#include \"test/util/test_util.h\"\n+using ::testing::AnyOf;\n+\nnamespace gvisor {\nnamespace testing {\n@@ -438,6 +440,60 @@ TEST(RenameTest, SysfsDirectoryToSelf) {\nEXPECT_THAT(rename(path.c_str(), path.c_str()), SyscallSucceeds());\n}\n+#ifndef SYS_renameat2\n+#if defined(__x86_64__)\n+#define SYS_renameat2 316\n+#elif defined(__aarch64__)\n+#define SYS_renameat2 276\n+#else\n+#error \"Unknown architecture\"\n+#endif\n+#endif // SYS_renameat2\n+\n+#ifndef RENAME_NOREPLACE\n+#define RENAME_NOREPLACE (1 << 0)\n+#endif // RENAME_NOREPLACE\n+\n+int renameat2(int olddirfd, const char* oldpath, int newdirfd,\n+ const char* newpath, unsigned int flags) {\n+ return syscall(SYS_renameat2, olddirfd, oldpath, newdirfd, newpath, flags);\n+}\n+\n+TEST(Renameat2Test, NoReplaceSuccess) {\n+ auto f = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());\n+ std::string const newpath = NewTempAbsPath();\n+ // renameat2 may fail with ENOSYS (if the syscall is unsupported) or EINVAL\n+ // (if flags are unsupported), or succeed (if RENAME_NOREPLACE is operating\n+ // correctly).\n+ EXPECT_THAT(\n+ renameat2(AT_FDCWD, f.path().c_str(), AT_FDCWD, newpath.c_str(),\n+ RENAME_NOREPLACE),\n+ AnyOf(SyscallFailsWithErrno(AnyOf(ENOSYS, EINVAL)), SyscallSucceeds()));\n+}\n+\n+TEST(Renameat2Test, NoReplaceExisting) {\n+ auto f1 = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());\n+ auto f2 = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());\n+ // renameat2 may fail with ENOSYS (if the syscall is unsupported), EINVAL (if\n+ // flags are unsupported), or EEXIST (if RENAME_NOREPLACE is operating\n+ // correctly).\n+ EXPECT_THAT(renameat2(AT_FDCWD, f1.path().c_str(), AT_FDCWD,\n+ f2.path().c_str(), RENAME_NOREPLACE),\n+ SyscallFailsWithErrno(AnyOf(ENOSYS, EINVAL, EEXIST)));\n+}\n+\n+TEST(Renameat2Test, NoReplaceDot) {\n+ auto d1 = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n+ auto d2 = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n+ // renameat2 may fail with ENOSYS (if the syscall is unsupported), EINVAL (if\n+ // flags are unsupported), or EEXIST (if RENAME_NOREPLACE is operating\n+ // correctly).\n+ EXPECT_THAT(\n+ renameat2(AT_FDCWD, d1.path().c_str(), AT_FDCWD,\n+ absl::StrCat(d2.path(), \"/.\").c_str(), RENAME_NOREPLACE),\n+ SyscallFailsWithErrno(AnyOf(ENOSYS, EINVAL, EEXIST)));\n+}\n+\n} // namespace\n} // namespace testing\n" } ]
Go
Apache License 2.0
google/gvisor
Implement RENAME_NOREPLACE for all VFS2 filesystem implementations. PiperOrigin-RevId: 377966969
259,853
07.06.2021 12:13:22
25,200
7e4e71253ec7c06f2f4eaf387826f08a8b3373cb
cgroupfs: don't add a task in the root cgroup if it is already there.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/kernel.go", "new_path": "pkg/sentry/kernel/kernel.go", "diff": "@@ -1861,7 +1861,9 @@ func (k *Kernel) PopulateNewCgroupHierarchy(root Cgroup) {\nreturn\n}\nt.mu.Lock()\n- t.enterCgroupLocked(root)\n+ // A task can be in the cgroup if it has been created after the\n+ // cgroup hierarchy was registered.\n+ t.enterCgroupIfNotYetLocked(root)\nt.mu.Unlock()\n})\nk.tasks.mu.RUnlock()\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/task_cgroup.go", "new_path": "pkg/sentry/kernel/task_cgroup.go", "diff": "@@ -85,6 +85,14 @@ func (t *Task) enterCgroupLocked(c Cgroup) {\nc.Enter(t)\n}\n+// +checklocks:t.mu\n+func (t *Task) enterCgroupIfNotYetLocked(c Cgroup) {\n+ if _, ok := t.cgroups[c]; ok {\n+ return\n+ }\n+ t.enterCgroupLocked(c)\n+}\n+\n// LeaveCgroups removes t out from all its cgroups.\nfunc (t *Task) LeaveCgroups() {\nt.mu.Lock()\n" } ]
Go
Apache License 2.0
google/gvisor
cgroupfs: don't add a task in the root cgroup if it is already there. PiperOrigin-RevId: 377975013
259,853
07.06.2021 14:08:28
25,200
b3a44bfab826709fc618e5c14835c06539b054cf
test: use std::vector instead of allocating memory with calloc A memory that is allocated with calloc has to be freed.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/udp_socket.cc", "new_path": "test/syscalls/linux/udp_socket.cc", "diff": "@@ -791,14 +791,14 @@ TEST_P(UdpSocketTest, RecvErrorConnRefused) {\niov.iov_len = kBufLen;\nsize_t control_buf_len = CMSG_SPACE(sizeof(sock_extended_err) + addrlen_);\n- char* control_buf = static_cast<char*>(calloc(1, control_buf_len));\n+ std::vector<char> control_buf(control_buf_len);\nstruct sockaddr_storage remote;\nmemset(&remote, 0, sizeof(remote));\nstruct msghdr msg = {};\nmsg.msg_iov = &iov;\nmsg.msg_iovlen = 1;\nmsg.msg_flags = 0;\n- msg.msg_control = control_buf;\n+ msg.msg_control = control_buf.data();\nmsg.msg_controllen = control_buf_len;\nmsg.msg_name = reinterpret_cast<void*>(&remote);\nmsg.msg_namelen = addrlen_;\n" } ]
Go
Apache License 2.0
google/gvisor
test: use std::vector instead of allocating memory with calloc A memory that is allocated with calloc has to be freed. PiperOrigin-RevId: 378001409
260,004
07.06.2021 19:56:04
25,200
77930d0d5ff993d3c870a2237c09193433c89429
Exclusively lock IPv6 EP when modifying addresses ...as address add/removal updates multicast group memberships and NDP state. This partially reverts the change made to the IPv6 endpoint in
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/ipv6.go", "new_path": "pkg/tcpip/network/ipv6/ipv6.go", "diff": "@@ -1627,8 +1627,8 @@ func (e *endpoint) NetworkProtocolNumber() tcpip.NetworkProtocolNumber {\nfunc (e *endpoint) AddAndAcquirePermanentAddress(addr tcpip.AddressWithPrefix, peb stack.PrimaryEndpointBehavior, configType stack.AddressConfigType, deprecated bool) (stack.AddressEndpoint, tcpip.Error) {\n// TODO(b/169350103): add checks here after making sure we no longer receive\n// an empty address.\n- e.mu.RLock()\n- defer e.mu.RUnlock()\n+ e.mu.Lock()\n+ defer e.mu.Unlock()\nreturn e.addAndAcquirePermanentAddressLocked(addr, peb, configType, deprecated)\n}\n@@ -1669,8 +1669,8 @@ func (e *endpoint) addAndAcquirePermanentAddressLocked(addr tcpip.AddressWithPre\n// RemovePermanentAddress implements stack.AddressableEndpoint.\nfunc (e *endpoint) RemovePermanentAddress(addr tcpip.Address) tcpip.Error {\n- e.mu.RLock()\n- defer e.mu.RUnlock()\n+ e.mu.Lock()\n+ defer e.mu.Unlock()\naddressEndpoint := e.getAddressRLocked(addr)\nif addressEndpoint == nil || !addressEndpoint.GetKind().IsPermanent() {\n" } ]
Go
Apache License 2.0
google/gvisor
Exclusively lock IPv6 EP when modifying addresses ...as address add/removal updates multicast group memberships and NDP state. This partially reverts the change made to the IPv6 endpoint in https://github.com/google/gvisor/commit/ebebb3059f7c5dbe42af85715f1c51c. PiperOrigin-RevId: 378061726
260,005
08.06.2021 18:57:46
-7,200
a238b0f2f8d3a6857b552f77707b574290ce5857
Add comment on abseil/grpc dependency precedence
[ { "change_type": "MODIFY", "old_path": "WORKSPACE", "new_path": "WORKSPACE", "diff": "@@ -1254,6 +1254,9 @@ load(\"@rules_pkg//:deps.bzl\", \"rules_pkg_dependencies\")\nrules_pkg_dependencies()\n# System Call test dependencies.\n+# grpc also has a dependency on abseil but as this is before grpc dependency\n+# declaration, it will take precedence over grpc's one\n+# Version LTS 20210324.2\nhttp_archive(\nname = \"com_google_absl\",\nsha256 = \"1764491a199eb9325b177126547f03d244f86b4ff28f16f206c7b3e7e4f777ec\",\n" } ]
Go
Apache License 2.0
google/gvisor
Add comment on abseil/grpc dependency precedence Signed-off-by: Esteban Blanc <[email protected]>
259,884
08.06.2021 20:05:28
25,200
927bb26517e7181e18c714d2892595cf1de8d4db
Don't mark issues as stale.
[ { "change_type": "MODIFY", "old_path": ".github/workflows/issue_reviver.yml", "new_path": ".github/workflows/issue_reviver.yml", "diff": "# This workflow revives issues that are still referenced in the code, and may\n-# have been accidentally closed or marked stale.\n+# have been accidentally closed.\nname: \"Issue reviver\"\n\"on\":\nschedule:\n" }, { "change_type": "DELETE", "old_path": ".github/workflows/stale.yml", "new_path": null, "diff": "-# The stale workflow closes stale issues and pull requests, unless specific\n-# tags have been applied in order to keep them open.\n-name: \"Stale issues\"\n-\"on\":\n- schedule:\n- - cron: \"0 0 * * *\"\n-\n-jobs:\n- stale:\n- runs-on: ubuntu-latest\n- steps:\n- - uses: actions/stale@v3\n- with:\n- repo-token: ${{ secrets.GITHUB_TOKEN }}\n- stale-issue-label: 'stale'\n- stale-pr-label: 'stale'\n- exempt-issue-labels: 'revived, exported, type: bug, type: cleanup, type: enhancement, type: process, type: proposal, type: question'\n- exempt-pr-labels: 'ready to pull, exported'\n- stale-issue-message: 'This issue is stale because it has been open 90 days with no activity. Remove the stale label or comment or this will be closed in 30 days.'\n- stale-pr-message: 'This pull request is stale because it has been open 90 days with no activity. Remove the stale label or comment or this will be closed in 30 days.'\n- days-before-stale: 90\n- days-before-close: 30\n" }, { "change_type": "MODIFY", "old_path": "README.md", "new_path": "README.md", "diff": "![gVisor](g3doc/logo.png)\n[![Build status](https://badge.buildkite.com/3b159f20b9830461a71112566c4171c0bdfd2f980a8e4c0ae6.svg?branch=master)](https://buildkite.com/gvisor/pipeline)\n+[![Issue reviver](https://github.com/google/gvisor/actions/workflows/issue_reviver.yml/badge.svg)](https://github.com/google/gvisor/actions/workflows/issue_reviver.yml)\n[![gVisor chat](https://badges.gitter.im/gvisor/community.png)](https://gitter.im/gvisor/community)\n[![code search](https://img.shields.io/badge/code-search-blue)](https://cs.opensource.google/gvisor/gvisor)\n-[![Issue reviver](https://github.com/google/gvisor/actions/workflows/issue_reviver.yml/badge.svg)](https://github.com/google/gvisor/actions/workflows/issue_reviver.yml)\n-[![Stale issues](https://github.com/google/gvisor/actions/workflows/stale.yml/badge.svg)](https://github.com/google/gvisor/actions/workflows/stale.yml)\n-\n## What is gVisor?\n**gVisor** is an application kernel, written in Go, that implements a\n" } ]
Go
Apache License 2.0
google/gvisor
Don't mark issues as stale. PiperOrigin-RevId: 378306356
259,992
09.06.2021 15:51:03
25,200
1ca981f50f0b2ad273bbcb870bca21c4b1264504
Remove --overlayfs-stale-read flag It defaults to true and setting it to false can cause filesytem corruption.
[ { "change_type": "MODIFY", "old_path": "runsc/boot/fs.go", "new_path": "runsc/boot/fs.go", "diff": "@@ -763,12 +763,10 @@ func (c *containerMounter) createRootMount(ctx context.Context, conf *config.Con\np9FS := mustFindFilesystem(\"9p\")\nopts := p9MountData(fd, conf.FileAccess, false /* vfs2 */)\n- if conf.OverlayfsStaleRead {\n// We can't check for overlayfs here because sandbox is chroot'ed and gofer\n// can only send mount options for specs.Mounts (specs.Root is missing\n// Options field). So assume root is always on top of overlayfs.\nopts = append(opts, \"overlayfs_stale_read\")\n- }\nrootInode, err := p9FS.Mount(ctx, rootDevice, mf, strings.Join(opts, \",\"), nil)\nif err != nil {\n" }, { "change_type": "MODIFY", "old_path": "runsc/boot/vfs.go", "new_path": "runsc/boot/vfs.go", "diff": "@@ -210,12 +210,10 @@ func (c *containerMounter) createMountNamespaceVFS2(ctx context.Context, conf *c\nfd := c.fds.remove()\ndata := p9MountData(fd, conf.FileAccess, true /* vfs2 */)\n- if conf.OverlayfsStaleRead {\n// We can't check for overlayfs here because sandbox is chroot'ed and gofer\n// can only send mount options for specs.Mounts (specs.Root is missing\n// Options field). So assume root is always on top of overlayfs.\ndata = append(data, \"overlayfs_stale_read\")\n- }\nlog.Infof(\"Mounting root over 9P, ioFD: %d\", fd)\nopts := &vfs.MountOptions{\n" }, { "change_type": "MODIFY", "old_path": "runsc/cmd/gofer.go", "new_path": "runsc/cmd/gofer.go", "diff": "@@ -473,7 +473,6 @@ func adjustMountOptions(conf *config.Config, path string, opts []string) ([]stri\nrv := make([]string, len(opts))\ncopy(rv, opts)\n- if conf.OverlayfsStaleRead {\nstatfs := unix.Statfs_t{}\nif err := unix.Statfs(path, &statfs); err != nil {\nreturn nil, err\n@@ -481,6 +480,5 @@ func adjustMountOptions(conf *config.Config, path string, opts []string) ([]stri\nif statfs.Type == unix.OVERLAYFS_SUPER_MAGIC {\nrv = append(rv, \"overlayfs_stale_read\")\n}\n- }\nreturn rv, nil\n}\n" }, { "change_type": "MODIFY", "old_path": "runsc/config/config.go", "new_path": "runsc/config/config.go", "diff": "@@ -151,12 +151,6 @@ type Config struct {\n// ReferenceLeakMode sets reference leak check mode\nReferenceLeak refs.LeakMode `flag:\"ref-leak-mode\"`\n- // OverlayfsStaleRead instructs the sandbox to assume that the root mount\n- // is on a Linux overlayfs mount, which does not necessarily preserve\n- // coherence between read-only and subsequent writable file descriptors\n- // representing the \"same\" file.\n- OverlayfsStaleRead bool `flag:\"overlayfs-stale-read\"`\n-\n// CPUNumFromQuota sets CPU number count to available CPU quota, using\n// least integer value greater than or equal to quota.\n//\n" }, { "change_type": "MODIFY", "old_path": "runsc/config/flags.go", "new_path": "runsc/config/flags.go", "diff": "@@ -72,7 +72,6 @@ func RegisterFlags() {\nflag.Var(fileAccessTypePtr(FileAccessShared), \"file-access-mounts\", \"specifies which filesystem validation to use for volumes other than the root mount: shared (default), exclusive.\")\nflag.Bool(\"overlay\", false, \"wrap filesystem mounts with writable overlay. All modifications are stored in memory inside the sandbox.\")\nflag.Bool(\"verity\", false, \"specifies whether a verity file system will be mounted.\")\n- flag.Bool(\"overlayfs-stale-read\", true, \"assume root mount is an overlay filesystem\")\nflag.Bool(\"fsgofer-host-uds\", false, \"allow the gofer to mount Unix Domain Sockets.\")\nflag.Bool(\"vfs2\", false, \"enables VFSv2. This uses the new VFS layer that is faster than the previous one.\")\nflag.Bool(\"fuse\", false, \"TEST ONLY; use while FUSE in VFSv2 is landing. This allows the use of the new experimental FUSE filesystem.\")\n" } ]
Go
Apache License 2.0
google/gvisor
Remove --overlayfs-stale-read flag It defaults to true and setting it to false can cause filesytem corruption. PiperOrigin-RevId: 378518663
259,885
09.06.2021 18:22:27
25,200
0c37626a07851668307d85c40345c0998a92e30f
Decommit huge-page-aligned regions during reclaim under manual zeroing.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/pgalloc/pgalloc.go", "new_path": "pkg/sentry/pgalloc/pgalloc.go", "diff": "@@ -1062,10 +1062,20 @@ func (f *MemoryFile) runReclaim() {\nbreak\n}\n- // If ManualZeroing is in effect, pages will be zeroed on allocation\n- // and may not be freed by decommitFile, so calling decommitFile is\n- // unnecessary.\n- if !f.opts.ManualZeroing {\n+ if f.opts.ManualZeroing {\n+ // If ManualZeroing is in effect, only hugepage-aligned regions may\n+ // be safely passed to decommitFile. Pages will be zeroed on\n+ // reallocation, so we don't need to perform any manual zeroing\n+ // here, whether or not decommitFile succeeds.\n+ if startAddr, ok := hostarch.Addr(fr.Start).HugeRoundUp(); ok {\n+ if endAddr := hostarch.Addr(fr.End).HugeRoundDown(); startAddr < endAddr {\n+ decommitFR := memmap.FileRange{uint64(startAddr), uint64(endAddr)}\n+ if err := f.decommitFile(decommitFR); err != nil {\n+ log.Warningf(\"Reclaim failed to decommit %v: %v\", decommitFR, err)\n+ }\n+ }\n+ }\n+ } else {\nif err := f.decommitFile(fr); err != nil {\nlog.Warningf(\"Reclaim failed to decommit %v: %v\", fr, err)\n// Zero the pages manually. This won't reduce memory usage, but at\n" } ]
Go
Apache License 2.0
google/gvisor
Decommit huge-page-aligned regions during reclaim under manual zeroing. PiperOrigin-RevId: 378546551
259,891
09.06.2021 20:35:11
25,200
8a7b5a4a8188157a99e5f7654f9235c5332b3552
Change TODO bug to a more specific issue This lets us close a tracking bug that's too widely-scoped to be reasonably finished.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/thread_group.go", "new_path": "pkg/sentry/kernel/thread_group.go", "diff": "@@ -490,10 +490,10 @@ func (tg *ThreadGroup) SetForegroundProcessGroup(tty *TTY, pgid ProcessGroupID)\ntg.signalHandlers.mu.Lock()\ndefer tg.signalHandlers.mu.Unlock()\n- // TODO(b/129283598): \"If tcsetpgrp() is called by a member of a\n- // background process group in its session, and the calling process is\n- // not blocking or ignoring SIGTTOU, a SIGTTOU signal is sent to all\n- // members of this background process group.\"\n+ // TODO(gvisor.dev/issue/6148): \"If tcsetpgrp() is called by a member of a\n+ // background process group in its session, and the calling process is not\n+ // blocking or ignoring SIGTTOU, a SIGTTOU signal is sent to all members of\n+ // this background process group.\"\n// tty must be the controlling terminal.\nif tg.tty != tty {\n" } ]
Go
Apache License 2.0
google/gvisor
Change TODO bug to a more specific issue This lets us close a tracking bug that's too widely-scoped to be reasonably finished. PiperOrigin-RevId: 378563203
259,907
09.06.2021 22:51:28
25,200
8d87a9418aacc175d7a2fa3583f40988e05946cc
[op] Move SignalAct to abi/linux package. There were also other duplicate definitions of the same struct that I have now removed. Updates
[ { "change_type": "MODIFY", "old_path": "pkg/abi/linux/signal.go", "new_path": "pkg/abi/linux/signal.go", "diff": "@@ -227,6 +227,21 @@ type Sigevent struct {\nUnRemainder [44]byte\n}\n+// LINT.IfChange\n+\n+// SigAction represents struct sigaction.\n+//\n+// +marshal\n+// +stateify savable\n+type SigAction struct {\n+ Handler uint64\n+ Flags uint64\n+ Restorer uint64\n+ Mask SignalSet\n+}\n+\n+// LINT.ThenChange(../../safecopy/safecopy_unsafe.go)\n+\n// Possible values for Sigevent.Notify, aka struct sigevent::sigev_notify.\nconst (\nSIGEV_SIGNAL = 0\n" }, { "change_type": "MODIFY", "old_path": "pkg/safecopy/safecopy_unsafe.go", "new_path": "pkg/safecopy/safecopy_unsafe.go", "diff": "@@ -342,6 +342,9 @@ func errorFromFaultSignal(addr uintptr, sig int32) error {\n// handler however, and if this is function is being used externally then the\n// same courtesy is expected.\nfunc ReplaceSignalHandler(sig unix.Signal, handler uintptr, previous *uintptr) error {\n+ // TODO(gvisor.dev/issue/6160): This struct is the same as linux.SigAction.\n+ // Once the usermem dependency is removed from primitive, delete this replica\n+ // and remove IFTTT comments in abi/linux/signal.go.\nvar sa struct {\nhandler uintptr\nflags uint64\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/arch/BUILD", "new_path": "pkg/sentry/arch/BUILD", "diff": "@@ -15,7 +15,6 @@ go_library(\n\"arch_x86_impl.go\",\n\"auxv.go\",\n\"signal.go\",\n- \"signal_act.go\",\n\"signal_amd64.go\",\n\"signal_arm64.go\",\n\"signal_info.go\",\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/arch/arch.go", "new_path": "pkg/sentry/arch/arch.go", "diff": "@@ -134,10 +134,6 @@ type Context interface {\n// RegisterMap returns a map of all registers.\nRegisterMap() (map[string]uintptr, error)\n- // NewSignalAct returns a new object that is equivalent to struct sigaction\n- // in the guest architecture.\n- NewSignalAct() NativeSignalAct\n-\n// NewSignalStack returns a new object that is equivalent to stack_t in the\n// guest architecture.\nNewSignalStack() NativeSignalStack\n@@ -148,7 +144,7 @@ type Context interface {\n// st is the stack where the signal handler frame should be\n// constructed.\n//\n- // act is the SignalAct that specifies how this signal is being\n+ // act is the SigAction that specifies how this signal is being\n// handled.\n//\n// info is the SignalInfo of the signal being delivered.\n@@ -157,7 +153,7 @@ type Context interface {\n// stack is not going to be used).\n//\n// sigset is the signal mask before entering the signal handler.\n- SignalSetup(st *Stack, act *SignalAct, info *SignalInfo, alt *SignalStack, sigset linux.SignalSet) error\n+ SignalSetup(st *Stack, act *linux.SigAction, info *SignalInfo, alt *SignalStack, sigset linux.SignalSet) error\n// SignalRestore restores context after returning from a signal\n// handler.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/arch/signal.go", "new_path": "pkg/sentry/arch/signal.go", "diff": "@@ -19,28 +19,6 @@ import (\n\"gvisor.dev/gvisor/pkg/hostarch\"\n)\n-// SignalAct represents the action that should be taken when a signal is\n-// delivered, and is equivalent to struct sigaction.\n-//\n-// +marshal\n-// +stateify savable\n-type SignalAct struct {\n- Handler uint64\n- Flags uint64\n- Restorer uint64 // Only used on amd64.\n- Mask linux.SignalSet\n-}\n-\n-// SerializeFrom implements NativeSignalAct.SerializeFrom.\n-func (s *SignalAct) SerializeFrom(other *SignalAct) {\n- *s = *other\n-}\n-\n-// DeserializeTo implements NativeSignalAct.DeserializeTo.\n-func (s *SignalAct) DeserializeTo(other *SignalAct) {\n- *other = *s\n-}\n-\n// SignalStack represents information about a user stack, and is equivalent to\n// stack_t.\n//\n" }, { "change_type": "DELETE", "old_path": "pkg/sentry/arch/signal_act.go", "new_path": null, "diff": "-// Copyright 2018 The gVisor Authors.\n-//\n-// Licensed under the Apache License, Version 2.0 (the \"License\");\n-// you may not use this file except in compliance with the License.\n-// You may obtain a copy of the License at\n-//\n-// http://www.apache.org/licenses/LICENSE-2.0\n-//\n-// Unless required by applicable law or agreed to in writing, software\n-// distributed under the License is distributed on an \"AS IS\" BASIS,\n-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n-// See the License for the specific language governing permissions and\n-// limitations under the License.\n-\n-package arch\n-\n-import \"gvisor.dev/gvisor/pkg/marshal\"\n-\n-// Special values for SignalAct.Handler.\n-const (\n- // SignalActDefault is SIG_DFL and specifies that the default behavior for\n- // a signal should be taken.\n- SignalActDefault = 0\n-\n- // SignalActIgnore is SIG_IGN and specifies that a signal should be\n- // ignored.\n- SignalActIgnore = 1\n-)\n-\n-// Available signal flags.\n-const (\n- SignalFlagNoCldStop = 0x00000001\n- SignalFlagNoCldWait = 0x00000002\n- SignalFlagSigInfo = 0x00000004\n- SignalFlagRestorer = 0x04000000\n- SignalFlagOnStack = 0x08000000\n- SignalFlagRestart = 0x10000000\n- SignalFlagInterrupt = 0x20000000\n- SignalFlagNoDefer = 0x40000000\n- SignalFlagResetHandler = 0x80000000\n-)\n-\n-// IsSigInfo returns true iff this handle expects siginfo.\n-func (s SignalAct) IsSigInfo() bool {\n- return s.Flags&SignalFlagSigInfo != 0\n-}\n-\n-// IsNoDefer returns true iff this SignalAct has the NoDefer flag set.\n-func (s SignalAct) IsNoDefer() bool {\n- return s.Flags&SignalFlagNoDefer != 0\n-}\n-\n-// IsRestart returns true iff this SignalAct has the Restart flag set.\n-func (s SignalAct) IsRestart() bool {\n- return s.Flags&SignalFlagRestart != 0\n-}\n-\n-// IsResetHandler returns true iff this SignalAct has the ResetHandler flag set.\n-func (s SignalAct) IsResetHandler() bool {\n- return s.Flags&SignalFlagResetHandler != 0\n-}\n-\n-// IsOnStack returns true iff this SignalAct has the OnStack flag set.\n-func (s SignalAct) IsOnStack() bool {\n- return s.Flags&SignalFlagOnStack != 0\n-}\n-\n-// HasRestorer returns true iff this SignalAct has the Restorer flag set.\n-func (s SignalAct) HasRestorer() bool {\n- return s.Flags&SignalFlagRestorer != 0\n-}\n-\n-// NativeSignalAct is a type that is equivalent to struct sigaction in the\n-// guest architecture.\n-type NativeSignalAct interface {\n- marshal.Marshallable\n-\n- // SerializeFrom copies the data in the host SignalAct s into this object.\n- SerializeFrom(s *SignalAct)\n-\n- // DeserializeTo copies the data in this object into the host SignalAct s.\n- DeserializeTo(s *SignalAct)\n-}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/arch/signal_amd64.go", "new_path": "pkg/sentry/arch/signal_amd64.go", "diff": "@@ -81,11 +81,6 @@ type UContext64 struct {\nSigset linux.SignalSet\n}\n-// NewSignalAct implements Context.NewSignalAct.\n-func (c *context64) NewSignalAct() NativeSignalAct {\n- return &SignalAct{}\n-}\n-\n// NewSignalStack implements Context.NewSignalStack.\nfunc (c *context64) NewSignalStack() NativeSignalStack {\nreturn &SignalStack{}\n@@ -110,7 +105,7 @@ func (c *context64) fpuFrameSize() (size int, useXsave bool) {\n// SignalSetup implements Context.SignalSetup. (Compare to Linux's\n// arch/x86/kernel/signal.c:__setup_rt_frame().)\n-func (c *context64) SignalSetup(st *Stack, act *SignalAct, info *SignalInfo, alt *SignalStack, sigset linux.SignalSet) error {\n+func (c *context64) SignalSetup(st *Stack, act *linux.SigAction, info *SignalInfo, alt *SignalStack, sigset linux.SignalSet) error {\nsp := st.Bottom\n// \"The 128-byte area beyond the location pointed to by %rsp is considered\n@@ -187,7 +182,7 @@ func (c *context64) SignalSetup(st *Stack, act *SignalAct, info *SignalInfo, alt\n// Prior to proceeding, figure out if the frame will exhaust the range\n// for the signal stack. This is not allowed, and should immediately\n// force signal delivery (reverting to the default handler).\n- if act.IsOnStack() && alt.IsEnabled() && !alt.Contains(frameBottom) {\n+ if act.Flags&linux.SA_ONSTACK != 0 && alt.IsEnabled() && !alt.Contains(frameBottom) {\nreturn unix.EFAULT\n}\n@@ -203,7 +198,7 @@ func (c *context64) SignalSetup(st *Stack, act *SignalAct, info *SignalInfo, alt\nreturn err\n}\nucAddr := st.Bottom\n- if act.HasRestorer() {\n+ if act.Flags&linux.SA_RESTORER != 0 {\n// Push the restorer return address.\n// Note that this doesn't need to be popped.\nif _, err := primitive.CopyUint64Out(st, StackBottomMagic, act.Restorer); err != nil {\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/arch/signal_arm64.go", "new_path": "pkg/sentry/arch/signal_arm64.go", "diff": "@@ -71,18 +71,13 @@ type UContext64 struct {\nMContext SignalContext64\n}\n-// NewSignalAct implements Context.NewSignalAct.\n-func (c *context64) NewSignalAct() NativeSignalAct {\n- return &SignalAct{}\n-}\n-\n// NewSignalStack implements Context.NewSignalStack.\nfunc (c *context64) NewSignalStack() NativeSignalStack {\nreturn &SignalStack{}\n}\n// SignalSetup implements Context.SignalSetup.\n-func (c *context64) SignalSetup(st *Stack, act *SignalAct, info *SignalInfo, alt *SignalStack, sigset linux.SignalSet) error {\n+func (c *context64) SignalSetup(st *Stack, act *linux.SigAction, info *SignalInfo, alt *SignalStack, sigset linux.SignalSet) error {\nsp := st.Bottom\n// Construct the UContext64 now since we need its size.\n@@ -114,7 +109,7 @@ func (c *context64) SignalSetup(st *Stack, act *SignalAct, info *SignalInfo, alt\n// Prior to proceeding, figure out if the frame will exhaust the range\n// for the signal stack. This is not allowed, and should immediately\n// force signal delivery (reverting to the default handler).\n- if act.IsOnStack() && alt.IsEnabled() && !alt.Contains(frameBottom) {\n+ if act.Flags&linux.SA_ONSTACK != 0 && alt.IsEnabled() && !alt.Contains(frameBottom) {\nreturn unix.EFAULT\n}\n@@ -137,7 +132,7 @@ func (c *context64) SignalSetup(st *Stack, act *SignalAct, info *SignalInfo, alt\nc.Regs.Regs[0] = uint64(info.Signo)\nc.Regs.Regs[1] = uint64(infoAddr)\nc.Regs.Regs[2] = uint64(ucAddr)\n- c.Regs.Regs[30] = uint64(act.Restorer)\n+ c.Regs.Regs[30] = act.Restorer\n// Save the thread's floating point state.\nc.sigFPState = append(c.sigFPState, c.fpState)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/signal_handlers.go", "new_path": "pkg/sentry/kernel/signal_handlers.go", "diff": "@@ -16,7 +16,6 @@ package kernel\nimport (\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n- \"gvisor.dev/gvisor/pkg/sentry/arch\"\n\"gvisor.dev/gvisor/pkg/sync\"\n)\n@@ -30,14 +29,14 @@ type SignalHandlers struct {\nmu sync.Mutex `state:\"nosave\"`\n// actions is the action to be taken upon receiving each signal.\n- actions map[linux.Signal]arch.SignalAct\n+ actions map[linux.Signal]linux.SigAction\n}\n// NewSignalHandlers returns a new SignalHandlers specifying all default\n// actions.\nfunc NewSignalHandlers() *SignalHandlers {\nreturn &SignalHandlers{\n- actions: make(map[linux.Signal]arch.SignalAct),\n+ actions: make(map[linux.Signal]linux.SigAction),\n}\n}\n@@ -59,9 +58,9 @@ func (sh *SignalHandlers) CopyForExec() *SignalHandlers {\nsh.mu.Lock()\ndefer sh.mu.Unlock()\nfor sig, act := range sh.actions {\n- if act.Handler == arch.SignalActIgnore {\n- sh2.actions[sig] = arch.SignalAct{\n- Handler: arch.SignalActIgnore,\n+ if act.Handler == linux.SIG_IGN {\n+ sh2.actions[sig] = linux.SigAction{\n+ Handler: linux.SIG_IGN,\n}\n}\n}\n@@ -73,15 +72,15 @@ func (sh *SignalHandlers) IsIgnored(sig linux.Signal) bool {\nsh.mu.Lock()\ndefer sh.mu.Unlock()\nsa, ok := sh.actions[sig]\n- return ok && sa.Handler == arch.SignalActIgnore\n+ return ok && sa.Handler == linux.SIG_IGN\n}\n// dequeueActionLocked returns the SignalAct that should be used to handle sig.\n//\n// Preconditions: sh.mu must be locked.\n-func (sh *SignalHandlers) dequeueAction(sig linux.Signal) arch.SignalAct {\n+func (sh *SignalHandlers) dequeueAction(sig linux.Signal) linux.SigAction {\nact := sh.actions[sig]\n- if act.IsResetHandler() {\n+ if act.Flags&linux.SA_RESETHAND != 0 {\ndelete(sh.actions, sig)\n}\nreturn act\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/task_exit.go", "new_path": "pkg/sentry/kernel/task_exit.go", "diff": "@@ -670,10 +670,10 @@ func (t *Task) exitNotifyLocked(fromPtraceDetach bool) {\nt.parent.tg.signalHandlers.mu.Lock()\nif t.tg.terminationSignal == linux.SIGCHLD || fromPtraceDetach {\nif act, ok := t.parent.tg.signalHandlers.actions[linux.SIGCHLD]; ok {\n- if act.Handler == arch.SignalActIgnore {\n+ if act.Handler == linux.SIG_IGN {\nt.exitParentAcked = true\nsignalParent = false\n- } else if act.Flags&arch.SignalFlagNoCldWait != 0 {\n+ } else if act.Flags&linux.SA_NOCLDWAIT != 0 {\nt.exitParentAcked = true\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/task_signals.go", "new_path": "pkg/sentry/kernel/task_signals.go", "diff": "@@ -86,7 +86,7 @@ var defaultActions = map[linux.Signal]SignalAction{\n}\n// computeAction figures out what to do given a signal number\n-// and an arch.SignalAct. SIGSTOP always results in a SignalActionStop,\n+// and an linux.SigAction. SIGSTOP always results in a SignalActionStop,\n// and SIGKILL always results in a SignalActionTerm.\n// Signal 0 is always ignored as many programs use it for various internal functions\n// and don't expect it to do anything.\n@@ -97,7 +97,7 @@ var defaultActions = map[linux.Signal]SignalAction{\n// 0, the default action is taken;\n// 1, the signal is ignored;\n// anything else, the function returns SignalActionHandler.\n-func computeAction(sig linux.Signal, act arch.SignalAct) SignalAction {\n+func computeAction(sig linux.Signal, act linux.SigAction) SignalAction {\nswitch sig {\ncase linux.SIGSTOP:\nreturn SignalActionStop\n@@ -108,9 +108,9 @@ func computeAction(sig linux.Signal, act arch.SignalAct) SignalAction {\n}\nswitch act.Handler {\n- case arch.SignalActDefault:\n+ case linux.SIG_DFL:\nreturn defaultActions[sig]\n- case arch.SignalActIgnore:\n+ case linux.SIG_IGN:\nreturn SignalActionIgnore\ndefault:\nreturn SignalActionHandler\n@@ -155,7 +155,7 @@ func (t *Task) PendingSignals() linux.SignalSet {\n}\n// deliverSignal delivers the given signal and returns the following run state.\n-func (t *Task) deliverSignal(info *arch.SignalInfo, act arch.SignalAct) taskRunState {\n+func (t *Task) deliverSignal(info *arch.SignalInfo, act linux.SigAction) taskRunState {\nsigact := computeAction(linux.Signal(info.Signo), act)\nif t.haveSyscallReturn {\n@@ -172,7 +172,7 @@ func (t *Task) deliverSignal(info *arch.SignalInfo, act arch.SignalAct) taskRunS\nfallthrough\ncase sre == syserror.ERESTART_RESTARTBLOCK:\nfallthrough\n- case (sre == syserror.ERESTARTSYS && !act.IsRestart()):\n+ case (sre == syserror.ERESTARTSYS && act.Flags&linux.SA_RESTART == 0):\nt.Debugf(\"Not restarting syscall %d after errno %d: interrupted by signal %d\", t.Arch().SyscallNo(), sre, info.Signo)\nt.Arch().SetReturn(uintptr(-ExtractErrno(syserror.EINTR, -1)))\ndefault:\n@@ -236,7 +236,7 @@ func (t *Task) deliverSignal(info *arch.SignalInfo, act arch.SignalAct) taskRunS\n// deliverSignalToHandler changes the task's userspace state to enter the given\n// user-configured handler for the given signal.\n-func (t *Task) deliverSignalToHandler(info *arch.SignalInfo, act arch.SignalAct) error {\n+func (t *Task) deliverSignalToHandler(info *arch.SignalInfo, act linux.SigAction) error {\n// Signal delivery to an application handler interrupts restartable\n// sequences.\nt.rseqInterrupt()\n@@ -248,7 +248,7 @@ func (t *Task) deliverSignalToHandler(info *arch.SignalInfo, act arch.SignalAct)\n// N.B. This is a *copy* of the alternate stack that the user's signal\n// handler expects to see in its ucontext (even if it's not in use).\nalt := t.signalStack\n- if act.IsOnStack() && alt.IsEnabled() {\n+ if act.Flags&linux.SA_ONSTACK != 0 && alt.IsEnabled() {\nalt.SetOnStack()\nif !alt.Contains(sp) {\nsp = hostarch.Addr(alt.Top())\n@@ -289,7 +289,7 @@ func (t *Task) deliverSignalToHandler(info *arch.SignalInfo, act arch.SignalAct)\n// Add our signal mask.\nnewMask := t.signalMask | act.Mask\n- if !act.IsNoDefer() {\n+ if act.Flags&linux.SA_NODEFER == 0 {\nnewMask |= linux.SignalSetOf(linux.Signal(info.Signo))\n}\nt.SetSignalMask(newMask)\n@@ -572,9 +572,9 @@ func (t *Task) forceSignal(sig linux.Signal, unconditional bool) {\nfunc (t *Task) forceSignalLocked(sig linux.Signal, unconditional bool) {\nblocked := linux.SignalSetOf(sig)&t.signalMask != 0\nact := t.tg.signalHandlers.actions[sig]\n- ignored := act.Handler == arch.SignalActIgnore\n+ ignored := act.Handler == linux.SIG_IGN\nif blocked || ignored || unconditional {\n- act.Handler = arch.SignalActDefault\n+ act.Handler = linux.SIG_DFL\nt.tg.signalHandlers.actions[sig] = act\nif blocked {\nt.setSignalMaskLocked(t.signalMask &^ linux.SignalSetOf(sig))\n@@ -680,11 +680,11 @@ func (t *Task) SetSignalStack(alt arch.SignalStack) bool {\nreturn true\n}\n-// SetSignalAct atomically sets the thread group's signal action for signal sig\n+// SetSigAction atomically sets the thread group's signal action for signal sig\n// to *actptr (if actptr is not nil) and returns the old signal action.\n-func (tg *ThreadGroup) SetSignalAct(sig linux.Signal, actptr *arch.SignalAct) (arch.SignalAct, error) {\n+func (tg *ThreadGroup) SetSigAction(sig linux.Signal, actptr *linux.SigAction) (linux.SigAction, error) {\nif !sig.IsValid() {\n- return arch.SignalAct{}, syserror.EINVAL\n+ return linux.SigAction{}, syserror.EINVAL\n}\ntg.pidns.owner.mu.RLock()\n@@ -718,27 +718,6 @@ func (tg *ThreadGroup) SetSignalAct(sig linux.Signal, actptr *arch.SignalAct) (a\nreturn oldact, nil\n}\n-// CopyOutSignalAct converts the given SignalAct into an architecture-specific\n-// type and then copies it out to task memory.\n-func (t *Task) CopyOutSignalAct(addr hostarch.Addr, s *arch.SignalAct) error {\n- n := t.Arch().NewSignalAct()\n- n.SerializeFrom(s)\n- _, err := n.CopyOut(t, addr)\n- return err\n-}\n-\n-// CopyInSignalAct copies an architecture-specific sigaction type from task\n-// memory and then converts it into a SignalAct.\n-func (t *Task) CopyInSignalAct(addr hostarch.Addr) (arch.SignalAct, error) {\n- n := t.Arch().NewSignalAct()\n- var s arch.SignalAct\n- if _, err := n.CopyIn(t, addr); err != nil {\n- return s, err\n- }\n- n.DeserializeTo(&s)\n- return s, nil\n-}\n-\n// CopyOutSignalStack converts the given SignalStack into an\n// architecture-specific type and then copies it out to task memory.\nfunc (t *Task) CopyOutSignalStack(addr hostarch.Addr, s *arch.SignalStack) error {\n@@ -909,7 +888,7 @@ func (t *Task) signalStop(target *Task, code int32, status int32) {\nt.tg.signalHandlers.mu.Lock()\ndefer t.tg.signalHandlers.mu.Unlock()\nact, ok := t.tg.signalHandlers.actions[linux.SIGCHLD]\n- if !ok || (act.Handler != arch.SignalActIgnore && act.Flags&arch.SignalFlagNoCldStop == 0) {\n+ if !ok || (act.Handler != linux.SIG_IGN && act.Flags&linux.SA_NOCLDSTOP == 0) {\nsigchld := &arch.SignalInfo{\nSigno: int32(linux.SIGCHLD),\nCode: code,\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/sighandling/sighandling_unsafe.go", "new_path": "pkg/sentry/sighandling/sighandling_unsafe.go", "diff": "@@ -21,25 +21,16 @@ import (\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n)\n-// FIXME(gvisor.dev/issue/214): Move to pkg/abi/linux along with definitions in\n-// pkg/sentry/arch.\n-type sigaction struct {\n- handler uintptr\n- flags uint64\n- restorer uintptr\n- mask uint64\n-}\n-\n// IgnoreChildStop sets the SA_NOCLDSTOP flag, causing child processes to not\n// generate SIGCHLD when they stop.\nfunc IgnoreChildStop() error {\n- var sa sigaction\n+ var sa linux.SigAction\n// Get the existing signal handler information, and set the flag.\nif _, _, e := unix.RawSyscall6(unix.SYS_RT_SIGACTION, uintptr(unix.SIGCHLD), 0, uintptr(unsafe.Pointer(&sa)), linux.SignalSetSize, 0, 0); e != 0 {\nreturn e\n}\n- sa.flags |= linux.SA_NOCLDSTOP\n+ sa.Flags |= linux.SA_NOCLDSTOP\nif _, _, e := unix.RawSyscall6(unix.SYS_RT_SIGACTION, uintptr(unix.SIGCHLD), uintptr(unsafe.Pointer(&sa)), 0, linux.SignalSetSize, 0, 0); e != 0 {\nreturn e\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/strace/signal.go", "new_path": "pkg/sentry/strace/signal.go", "diff": "@@ -130,8 +130,8 @@ func sigAction(t *kernel.Task, addr hostarch.Addr) string {\nreturn \"null\"\n}\n- sa, err := t.CopyInSignalAct(addr)\n- if err != nil {\n+ var sa linux.SigAction\n+ if _, err := sa.CopyIn(t, addr); err != nil {\nreturn fmt.Sprintf(\"%#x (error copying sigaction: %v)\", addr, err)\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/sys_signal.go", "new_path": "pkg/sentry/syscalls/linux/sys_signal.go", "diff": "@@ -251,20 +251,20 @@ func RtSigaction(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.S\nreturn 0, nil, syserror.EINVAL\n}\n- var newactptr *arch.SignalAct\n+ var newactptr *linux.SigAction\nif newactarg != 0 {\n- newact, err := t.CopyInSignalAct(newactarg)\n- if err != nil {\n+ var newact linux.SigAction\n+ if _, err := newact.CopyIn(t, newactarg); err != nil {\nreturn 0, nil, err\n}\nnewactptr = &newact\n}\n- oldact, err := t.ThreadGroup().SetSignalAct(sig, newactptr)\n+ oldact, err := t.ThreadGroup().SetSigAction(sig, newactptr)\nif err != nil {\nreturn 0, nil, err\n}\nif oldactarg != 0 {\n- if err := t.CopyOutSignalAct(oldactarg, &oldact); err != nil {\n+ if _, err := oldact.CopyOut(t, oldactarg); err != nil {\nreturn 0, nil, err\n}\n}\n" } ]
Go
Apache License 2.0
google/gvisor
[op] Move SignalAct to abi/linux package. There were also other duplicate definitions of the same struct that I have now removed. Updates #214 PiperOrigin-RevId: 378579954
259,907
10.06.2021 00:58:14
25,200
a51fcf22ebe522c028e99692bbedf04daf0436cc
[op] Move SignalStack to abi/linux package. Updates
[ { "change_type": "MODIFY", "old_path": "pkg/abi/linux/BUILD", "new_path": "pkg/abi/linux/BUILD", "diff": "@@ -79,6 +79,7 @@ go_library(\n\"//pkg/abi\",\n\"//pkg/bits\",\n\"//pkg/context\",\n+ \"//pkg/hostarch\",\n\"//pkg/marshal\",\n\"//pkg/marshal/primitive\",\n],\n" }, { "change_type": "MODIFY", "old_path": "pkg/abi/linux/signal.go", "new_path": "pkg/abi/linux/signal.go", "diff": "@@ -16,6 +16,7 @@ package linux\nimport (\n\"gvisor.dev/gvisor/pkg/bits\"\n+ \"gvisor.dev/gvisor/pkg/hostarch\"\n)\nconst (\n@@ -165,7 +166,7 @@ const (\nSIG_IGN = 1\n)\n-// Signal action flags for rt_sigaction(2), from uapi/asm-generic/signal.h\n+// Signal action flags for rt_sigaction(2), from uapi/asm-generic/signal.h.\nconst (\nSA_NOCLDSTOP = 0x00000001\nSA_NOCLDWAIT = 0x00000002\n@@ -179,6 +180,12 @@ const (\nSA_ONESHOT = SA_RESETHAND\n)\n+// Signal stack flags for signalstack(2), from include/uapi/linux/signal.h.\n+const (\n+ SS_ONSTACK = 1\n+ SS_DISABLE = 2\n+)\n+\n// Signal info types.\nconst (\nSI_MASK = 0xffff0000\n@@ -242,6 +249,33 @@ type SigAction struct {\n// LINT.ThenChange(../../safecopy/safecopy_unsafe.go)\n+// SignalStack represents information about a user stack, and is equivalent to\n+// stack_t.\n+//\n+// +marshal\n+// +stateify savable\n+type SignalStack struct {\n+ Addr uint64\n+ Flags uint32\n+ _ uint32\n+ Size uint64\n+}\n+\n+// Contains checks if the stack pointer is within this stack.\n+func (s *SignalStack) Contains(sp hostarch.Addr) bool {\n+ return hostarch.Addr(s.Addr) < sp && sp <= hostarch.Addr(s.Addr+s.Size)\n+}\n+\n+// Top returns the stack's top address.\n+func (s *SignalStack) Top() hostarch.Addr {\n+ return hostarch.Addr(s.Addr + s.Size)\n+}\n+\n+// IsEnabled returns true iff this signal stack is marked as enabled.\n+func (s *SignalStack) IsEnabled() bool {\n+ return s.Flags&SS_DISABLE == 0\n+}\n+\n// Possible values for Sigevent.Notify, aka struct sigevent::sigev_notify.\nconst (\nSIGEV_SIGNAL = 0\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/arch/BUILD", "new_path": "pkg/sentry/arch/BUILD", "diff": "@@ -18,7 +18,6 @@ go_library(\n\"signal_amd64.go\",\n\"signal_arm64.go\",\n\"signal_info.go\",\n- \"signal_stack.go\",\n\"stack.go\",\n\"stack_unsafe.go\",\n\"syscalls_amd64.go\",\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/arch/arch.go", "new_path": "pkg/sentry/arch/arch.go", "diff": "@@ -134,10 +134,6 @@ type Context interface {\n// RegisterMap returns a map of all registers.\nRegisterMap() (map[string]uintptr, error)\n- // NewSignalStack returns a new object that is equivalent to stack_t in the\n- // guest architecture.\n- NewSignalStack() NativeSignalStack\n-\n// SignalSetup modifies the context in preparation for handling the\n// given signal.\n//\n@@ -153,7 +149,7 @@ type Context interface {\n// stack is not going to be used).\n//\n// sigset is the signal mask before entering the signal handler.\n- SignalSetup(st *Stack, act *linux.SigAction, info *SignalInfo, alt *SignalStack, sigset linux.SignalSet) error\n+ SignalSetup(st *Stack, act *linux.SigAction, info *SignalInfo, alt *linux.SignalStack, sigset linux.SignalSet) error\n// SignalRestore restores context after returning from a signal\n// handler.\n@@ -163,7 +159,7 @@ type Context interface {\n// rt is true if SignalRestore is being entered from rt_sigreturn and\n// false if SignalRestore is being entered from sigreturn.\n// SignalRestore returns the thread's new signal mask.\n- SignalRestore(st *Stack, rt bool) (linux.SignalSet, SignalStack, error)\n+ SignalRestore(st *Stack, rt bool) (linux.SignalSet, linux.SignalStack, error)\n// CPUIDEmulate emulates a CPUID instruction according to current register state.\nCPUIDEmulate(l log.Logger)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/arch/signal.go", "new_path": "pkg/sentry/arch/signal.go", "diff": "@@ -19,28 +19,6 @@ import (\n\"gvisor.dev/gvisor/pkg/hostarch\"\n)\n-// SignalStack represents information about a user stack, and is equivalent to\n-// stack_t.\n-//\n-// +marshal\n-// +stateify savable\n-type SignalStack struct {\n- Addr uint64\n- Flags uint32\n- _ uint32\n- Size uint64\n-}\n-\n-// SerializeFrom implements NativeSignalStack.SerializeFrom.\n-func (s *SignalStack) SerializeFrom(other *SignalStack) {\n- *s = *other\n-}\n-\n-// DeserializeTo implements NativeSignalStack.DeserializeTo.\n-func (s *SignalStack) DeserializeTo(other *SignalStack) {\n- *other = *s\n-}\n-\n// SignalInfo represents information about a signal being delivered, and is\n// equivalent to struct siginfo in linux kernel(linux/include/uapi/asm-generic/siginfo.h).\n//\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/arch/signal_amd64.go", "new_path": "pkg/sentry/arch/signal_amd64.go", "diff": "@@ -76,16 +76,11 @@ const (\ntype UContext64 struct {\nFlags uint64\nLink uint64\n- Stack SignalStack\n+ Stack linux.SignalStack\nMContext SignalContext64\nSigset linux.SignalSet\n}\n-// NewSignalStack implements Context.NewSignalStack.\n-func (c *context64) NewSignalStack() NativeSignalStack {\n- return &SignalStack{}\n-}\n-\n// From Linux 'arch/x86/include/uapi/asm/sigcontext.h' the following is the\n// size of the magic cookie at the end of the xsave frame.\n//\n@@ -105,7 +100,7 @@ func (c *context64) fpuFrameSize() (size int, useXsave bool) {\n// SignalSetup implements Context.SignalSetup. (Compare to Linux's\n// arch/x86/kernel/signal.c:__setup_rt_frame().)\n-func (c *context64) SignalSetup(st *Stack, act *linux.SigAction, info *SignalInfo, alt *SignalStack, sigset linux.SignalSet) error {\n+func (c *context64) SignalSetup(st *Stack, act *linux.SigAction, info *SignalInfo, alt *linux.SignalStack, sigset linux.SignalSet) error {\nsp := st.Bottom\n// \"The 128-byte area beyond the location pointed to by %rsp is considered\n@@ -232,15 +227,15 @@ func (c *context64) SignalSetup(st *Stack, act *linux.SigAction, info *SignalInf\n// SignalRestore implements Context.SignalRestore. (Compare to Linux's\n// arch/x86/kernel/signal.c:sys_rt_sigreturn().)\n-func (c *context64) SignalRestore(st *Stack, rt bool) (linux.SignalSet, SignalStack, error) {\n+func (c *context64) SignalRestore(st *Stack, rt bool) (linux.SignalSet, linux.SignalStack, error) {\n// Copy out the stack frame.\nvar uc UContext64\nif _, err := uc.CopyIn(st, StackBottomMagic); err != nil {\n- return 0, SignalStack{}, err\n+ return 0, linux.SignalStack{}, err\n}\nvar info SignalInfo\nif _, err := info.CopyIn(st, StackBottomMagic); err != nil {\n- return 0, SignalStack{}, err\n+ return 0, linux.SignalStack{}, err\n}\n// Restore registers.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/arch/signal_arm64.go", "new_path": "pkg/sentry/arch/signal_arm64.go", "diff": "@@ -61,7 +61,7 @@ type FpsimdContext struct {\ntype UContext64 struct {\nFlags uint64\nLink uint64\n- Stack SignalStack\n+ Stack linux.SignalStack\nSigset linux.SignalSet\n// glibc uses a 1024-bit sigset_t\n_pad [120]byte // (1024 - 64) / 8 = 120\n@@ -71,13 +71,8 @@ type UContext64 struct {\nMContext SignalContext64\n}\n-// NewSignalStack implements Context.NewSignalStack.\n-func (c *context64) NewSignalStack() NativeSignalStack {\n- return &SignalStack{}\n-}\n-\n// SignalSetup implements Context.SignalSetup.\n-func (c *context64) SignalSetup(st *Stack, act *linux.SigAction, info *SignalInfo, alt *SignalStack, sigset linux.SignalSet) error {\n+func (c *context64) SignalSetup(st *Stack, act *linux.SigAction, info *SignalInfo, alt *linux.SignalStack, sigset linux.SignalSet) error {\nsp := st.Bottom\n// Construct the UContext64 now since we need its size.\n@@ -142,15 +137,15 @@ func (c *context64) SignalSetup(st *Stack, act *linux.SigAction, info *SignalInf\n}\n// SignalRestore implements Context.SignalRestore.\n-func (c *context64) SignalRestore(st *Stack, rt bool) (linux.SignalSet, SignalStack, error) {\n+func (c *context64) SignalRestore(st *Stack, rt bool) (linux.SignalSet, linux.SignalStack, error) {\n// Copy out the stack frame.\nvar uc UContext64\nif _, err := uc.CopyIn(st, StackBottomMagic); err != nil {\n- return 0, SignalStack{}, err\n+ return 0, linux.SignalStack{}, err\n}\nvar info SignalInfo\nif _, err := info.CopyIn(st, StackBottomMagic); err != nil {\n- return 0, SignalStack{}, err\n+ return 0, linux.SignalStack{}, err\n}\n// Restore registers.\n" }, { "change_type": "DELETE", "old_path": "pkg/sentry/arch/signal_stack.go", "new_path": null, "diff": "-// Copyright 2018 The gVisor Authors.\n-//\n-// Licensed under the Apache License, Version 2.0 (the \"License\");\n-// you may not use this file except in compliance with the License.\n-// You may obtain a copy of the License at\n-//\n-// http://www.apache.org/licenses/LICENSE-2.0\n-//\n-// Unless required by applicable law or agreed to in writing, software\n-// distributed under the License is distributed on an \"AS IS\" BASIS,\n-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n-// See the License for the specific language governing permissions and\n-// limitations under the License.\n-\n-// +build 386 amd64 arm64\n-\n-package arch\n-\n-import (\n- \"gvisor.dev/gvisor/pkg/hostarch\"\n- \"gvisor.dev/gvisor/pkg/marshal\"\n-)\n-\n-const (\n- // SignalStackFlagOnStack is possible set on return from getaltstack,\n- // in order to indicate that the thread is currently on the alt stack.\n- SignalStackFlagOnStack = 1\n-\n- // SignalStackFlagDisable is a flag to indicate the stack is disabled.\n- SignalStackFlagDisable = 2\n-)\n-\n-// IsEnabled returns true iff this signal stack is marked as enabled.\n-func (s SignalStack) IsEnabled() bool {\n- return s.Flags&SignalStackFlagDisable == 0\n-}\n-\n-// Top returns the stack's top address.\n-func (s SignalStack) Top() hostarch.Addr {\n- return hostarch.Addr(s.Addr + s.Size)\n-}\n-\n-// SetOnStack marks this signal stack as in use.\n-//\n-// Note that there is no corresponding ClearOnStack, and that this should only\n-// be called on copies that are serialized to userspace.\n-func (s *SignalStack) SetOnStack() {\n- s.Flags |= SignalStackFlagOnStack\n-}\n-\n-// Contains checks if the stack pointer is within this stack.\n-func (s *SignalStack) Contains(sp hostarch.Addr) bool {\n- return hostarch.Addr(s.Addr) < sp && sp <= hostarch.Addr(s.Addr+s.Size)\n-}\n-\n-// NativeSignalStack is a type that is equivalent to stack_t in the guest\n-// architecture.\n-type NativeSignalStack interface {\n- marshal.Marshallable\n-\n- // SerializeFrom copies the data in the host SignalStack s into this\n- // object.\n- SerializeFrom(s *SignalStack)\n-\n- // DeserializeTo copies the data in this object into the host SignalStack\n- // s.\n- DeserializeTo(s *SignalStack)\n-}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/task.go", "new_path": "pkg/sentry/kernel/task.go", "diff": "@@ -151,7 +151,7 @@ type Task struct {\n// which the SA_ONSTACK flag is set.\n//\n// signalStack is exclusive to the task goroutine.\n- signalStack arch.SignalStack\n+ signalStack linux.SignalStack\n// signalQueue is a set of registered waiters for signal-related events.\n//\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/task_exec.go", "new_path": "pkg/sentry/kernel/task_exec.go", "diff": "@@ -66,7 +66,6 @@ package kernel\nimport (\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n- \"gvisor.dev/gvisor/pkg/sentry/arch\"\n\"gvisor.dev/gvisor/pkg/sentry/fs\"\n\"gvisor.dev/gvisor/pkg/sentry/mm\"\n\"gvisor.dev/gvisor/pkg/sentry/vfs\"\n@@ -181,7 +180,7 @@ func (r *runSyscallAfterExecStop) execute(t *Task) taskRunState {\nt.tg.signalHandlers = t.tg.signalHandlers.CopyForExec()\nt.endStopCond.L = &t.tg.signalHandlers.mu\n// \"Any alternate signal stack is not preserved (sigaltstack(2)).\" - execve(2)\n- t.signalStack = arch.SignalStack{Flags: arch.SignalStackFlagDisable}\n+ t.signalStack = linux.SignalStack{Flags: linux.SS_DISABLE}\n// \"The termination signal is reset to SIGCHLD (see clone(2)).\"\nt.tg.terminationSignal = linux.SIGCHLD\n// execed indicates that the process can no longer join a process group\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/task_signals.go", "new_path": "pkg/sentry/kernel/task_signals.go", "diff": "@@ -249,7 +249,7 @@ func (t *Task) deliverSignalToHandler(info *arch.SignalInfo, act linux.SigAction\n// handler expects to see in its ucontext (even if it's not in use).\nalt := t.signalStack\nif act.Flags&linux.SA_ONSTACK != 0 && alt.IsEnabled() {\n- alt.SetOnStack()\n+ alt.Flags |= linux.SS_ONSTACK\nif !alt.Contains(sp) {\nsp = hostarch.Addr(alt.Top())\n}\n@@ -641,17 +641,17 @@ func (t *Task) SetSavedSignalMask(mask linux.SignalSet) {\n}\n// SignalStack returns the task-private signal stack.\n-func (t *Task) SignalStack() arch.SignalStack {\n+func (t *Task) SignalStack() linux.SignalStack {\nt.p.PullFullState(t.MemoryManager().AddressSpace(), t.Arch())\nalt := t.signalStack\nif t.onSignalStack(alt) {\n- alt.Flags |= arch.SignalStackFlagOnStack\n+ alt.Flags |= linux.SS_ONSTACK\n}\nreturn alt\n}\n// onSignalStack returns true if the task is executing on the given signal stack.\n-func (t *Task) onSignalStack(alt arch.SignalStack) bool {\n+func (t *Task) onSignalStack(alt linux.SignalStack) bool {\nsp := hostarch.Addr(t.Arch().Stack())\nreturn alt.Contains(sp)\n}\n@@ -661,20 +661,20 @@ func (t *Task) onSignalStack(alt arch.SignalStack) bool {\n// This value may not be changed if the task is currently executing on the\n// signal stack, i.e. if t.onSignalStack returns true. In this case, this\n// function will return false. Otherwise, true is returned.\n-func (t *Task) SetSignalStack(alt arch.SignalStack) bool {\n+func (t *Task) SetSignalStack(alt linux.SignalStack) bool {\n// Check that we're not executing on the stack.\nif t.onSignalStack(t.signalStack) {\nreturn false\n}\n- if alt.Flags&arch.SignalStackFlagDisable != 0 {\n+ if alt.Flags&linux.SS_DISABLE != 0 {\n// Don't record anything beyond the flags.\n- t.signalStack = arch.SignalStack{\n- Flags: arch.SignalStackFlagDisable,\n+ t.signalStack = linux.SignalStack{\n+ Flags: linux.SS_DISABLE,\n}\n} else {\n// Mask out irrelevant parts: only disable matters.\n- alt.Flags &= arch.SignalStackFlagDisable\n+ alt.Flags &= linux.SS_DISABLE\nt.signalStack = alt\n}\nreturn true\n@@ -718,27 +718,6 @@ func (tg *ThreadGroup) SetSigAction(sig linux.Signal, actptr *linux.SigAction) (\nreturn oldact, nil\n}\n-// CopyOutSignalStack converts the given SignalStack into an\n-// architecture-specific type and then copies it out to task memory.\n-func (t *Task) CopyOutSignalStack(addr hostarch.Addr, s *arch.SignalStack) error {\n- n := t.Arch().NewSignalStack()\n- n.SerializeFrom(s)\n- _, err := n.CopyOut(t, addr)\n- return err\n-}\n-\n-// CopyInSignalStack copies an architecture-specific stack_t from task memory\n-// and then converts it into a SignalStack.\n-func (t *Task) CopyInSignalStack(addr hostarch.Addr) (arch.SignalStack, error) {\n- n := t.Arch().NewSignalStack()\n- var s arch.SignalStack\n- if _, err := n.CopyIn(t, addr); err != nil {\n- return s, err\n- }\n- n.DeserializeTo(&s)\n- return s, nil\n-}\n-\n// groupStop is a TaskStop placed on tasks that have received a stop signal\n// (SIGSTOP, SIGTSTP, SIGTTIN, SIGTTOU). (The term \"group-stop\" originates from\n// the ptrace man page.)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/task_start.go", "new_path": "pkg/sentry/kernel/task_start.go", "diff": "@@ -18,7 +18,6 @@ import (\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/context\"\n\"gvisor.dev/gvisor/pkg/hostarch\"\n- \"gvisor.dev/gvisor/pkg/sentry/arch\"\n\"gvisor.dev/gvisor/pkg/sentry/inet\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/futex\"\n@@ -131,7 +130,7 @@ func (ts *TaskSet) newTask(cfg *TaskConfig) (*Task, error) {\nrunState: (*runApp)(nil),\ninterruptChan: make(chan struct{}, 1),\nsignalMask: cfg.SignalMask,\n- signalStack: arch.SignalStack{Flags: arch.SignalStackFlagDisable},\n+ signalStack: linux.SignalStack{Flags: linux.SS_DISABLE},\nimage: *image,\nfsContext: cfg.FSContext,\nfdTable: cfg.FDTable,\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/sys_signal.go", "new_path": "pkg/sentry/syscalls/linux/sys_signal.go", "diff": "@@ -325,13 +325,12 @@ func Sigaltstack(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.S\nalt := t.SignalStack()\nif oldaddr != 0 {\n- if err := t.CopyOutSignalStack(oldaddr, &alt); err != nil {\n+ if _, err := alt.CopyOut(t, oldaddr); err != nil {\nreturn 0, nil, err\n}\n}\nif setaddr != 0 {\n- alt, err := t.CopyInSignalStack(setaddr)\n- if err != nil {\n+ if _, err := alt.CopyIn(t, setaddr); err != nil {\nreturn 0, nil, err\n}\n// The signal stack cannot be changed if the task is currently\n" } ]
Go
Apache License 2.0
google/gvisor
[op] Move SignalStack to abi/linux package. Updates #214 PiperOrigin-RevId: 378594929
259,992
10.06.2021 12:43:10
25,200
8d426b73818cf07aeee3db88478a00b80ad9aafe
Parse mmap protection and flags in strace
[ { "change_type": "MODIFY", "old_path": "pkg/refs/refcounter.go", "new_path": "pkg/refs/refcounter.go", "diff": "@@ -261,8 +261,8 @@ func (l *LeakMode) Get() interface{} {\n}\n// String implements flag.Value.\n-func (l *LeakMode) String() string {\n- switch *l {\n+func (l LeakMode) String() string {\n+ switch l {\ncase UninitializedLeakChecking:\nreturn \"uninitialized\"\ncase NoLeakChecking:\n@@ -272,7 +272,7 @@ func (l *LeakMode) String() string {\ncase LeaksLogTraces:\nreturn \"log-traces\"\n}\n- panic(fmt.Sprintf(\"invalid ref leak mode %d\", *l))\n+ panic(fmt.Sprintf(\"invalid ref leak mode %d\", l))\n}\n// leakMode stores the current mode for the reference leak checker.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/strace/BUILD", "new_path": "pkg/sentry/strace/BUILD", "diff": "@@ -11,6 +11,7 @@ go_library(\n\"futex.go\",\n\"linux64_amd64.go\",\n\"linux64_arm64.go\",\n+ \"mmap.go\",\n\"open.go\",\n\"poll.go\",\n\"ptrace.go\",\n@@ -35,7 +36,6 @@ go_library(\n\"//pkg/sentry/socket\",\n\"//pkg/sentry/socket/netlink\",\n\"//pkg/sentry/syscalls/linux\",\n- \"@org_golang_x_sys//unix:go_default_library\",\n],\n)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/strace/clone.go", "new_path": "pkg/sentry/strace/clone.go", "diff": "package strace\nimport (\n- \"golang.org/x/sys/unix\"\n\"gvisor.dev/gvisor/pkg/abi\"\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n)\n// CloneFlagSet is the set of clone(2) flags.\nvar CloneFlagSet = abi.FlagSet{\n{\n- Flag: unix.CLONE_VM,\n+ Flag: linux.CLONE_VM,\nName: \"CLONE_VM\",\n},\n{\n- Flag: unix.CLONE_FS,\n+ Flag: linux.CLONE_FS,\nName: \"CLONE_FS\",\n},\n{\n- Flag: unix.CLONE_FILES,\n+ Flag: linux.CLONE_FILES,\nName: \"CLONE_FILES\",\n},\n{\n- Flag: unix.CLONE_SIGHAND,\n+ Flag: linux.CLONE_SIGHAND,\nName: \"CLONE_SIGHAND\",\n},\n{\n- Flag: unix.CLONE_PTRACE,\n+ Flag: linux.CLONE_PTRACE,\nName: \"CLONE_PTRACE\",\n},\n{\n- Flag: unix.CLONE_VFORK,\n+ Flag: linux.CLONE_VFORK,\nName: \"CLONE_VFORK\",\n},\n{\n- Flag: unix.CLONE_PARENT,\n+ Flag: linux.CLONE_PARENT,\nName: \"CLONE_PARENT\",\n},\n{\n- Flag: unix.CLONE_THREAD,\n+ Flag: linux.CLONE_THREAD,\nName: \"CLONE_THREAD\",\n},\n{\n- Flag: unix.CLONE_NEWNS,\n+ Flag: linux.CLONE_NEWNS,\nName: \"CLONE_NEWNS\",\n},\n{\n- Flag: unix.CLONE_SYSVSEM,\n+ Flag: linux.CLONE_SYSVSEM,\nName: \"CLONE_SYSVSEM\",\n},\n{\n- Flag: unix.CLONE_SETTLS,\n+ Flag: linux.CLONE_SETTLS,\nName: \"CLONE_SETTLS\",\n},\n{\n- Flag: unix.CLONE_PARENT_SETTID,\n+ Flag: linux.CLONE_PARENT_SETTID,\nName: \"CLONE_PARENT_SETTID\",\n},\n{\n- Flag: unix.CLONE_CHILD_CLEARTID,\n+ Flag: linux.CLONE_CHILD_CLEARTID,\nName: \"CLONE_CHILD_CLEARTID\",\n},\n{\n- Flag: unix.CLONE_DETACHED,\n+ Flag: linux.CLONE_DETACHED,\nName: \"CLONE_DETACHED\",\n},\n{\n- Flag: unix.CLONE_UNTRACED,\n+ Flag: linux.CLONE_UNTRACED,\nName: \"CLONE_UNTRACED\",\n},\n{\n- Flag: unix.CLONE_CHILD_SETTID,\n+ Flag: linux.CLONE_CHILD_SETTID,\nName: \"CLONE_CHILD_SETTID\",\n},\n{\n- Flag: unix.CLONE_NEWUTS,\n+ Flag: linux.CLONE_NEWUTS,\nName: \"CLONE_NEWUTS\",\n},\n{\n- Flag: unix.CLONE_NEWIPC,\n+ Flag: linux.CLONE_NEWIPC,\nName: \"CLONE_NEWIPC\",\n},\n{\n- Flag: unix.CLONE_NEWUSER,\n+ Flag: linux.CLONE_NEWUSER,\nName: \"CLONE_NEWUSER\",\n},\n{\n- Flag: unix.CLONE_NEWPID,\n+ Flag: linux.CLONE_NEWPID,\nName: \"CLONE_NEWPID\",\n},\n{\n- Flag: unix.CLONE_NEWNET,\n+ Flag: linux.CLONE_NEWNET,\nName: \"CLONE_NEWNET\",\n},\n{\n- Flag: unix.CLONE_IO,\n+ Flag: linux.CLONE_IO,\nName: \"CLONE_IO\",\n},\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/strace/linux64_amd64.go", "new_path": "pkg/sentry/strace/linux64_amd64.go", "diff": "@@ -33,7 +33,7 @@ var linuxAMD64 = SyscallMap{\n6: makeSyscallInfo(\"lstat\", Path, Stat),\n7: makeSyscallInfo(\"poll\", PollFDs, Hex, Hex),\n8: makeSyscallInfo(\"lseek\", Hex, Hex, Hex),\n- 9: makeSyscallInfo(\"mmap\", Hex, Hex, Hex, Hex, FD, Hex),\n+ 9: makeSyscallInfo(\"mmap\", Hex, Hex, MmapProt, MmapFlags, FD, Hex),\n10: makeSyscallInfo(\"mprotect\", Hex, Hex, Hex),\n11: makeSyscallInfo(\"munmap\", Hex, Hex),\n12: makeSyscallInfo(\"brk\", Hex),\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/strace/linux64_arm64.go", "new_path": "pkg/sentry/strace/linux64_arm64.go", "diff": "@@ -246,7 +246,7 @@ var linuxARM64 = SyscallMap{\n219: makeSyscallInfo(\"keyctl\", Hex, Hex, Hex, Hex, Hex),\n220: makeSyscallInfo(\"clone\", CloneFlags, Hex, Hex, Hex, Hex),\n221: makeSyscallInfo(\"execve\", Path, ExecveStringVector, ExecveStringVector),\n- 222: makeSyscallInfo(\"mmap\", Hex, Hex, Hex, Hex, FD, Hex),\n+ 222: makeSyscallInfo(\"mmap\", Hex, Hex, MmapProt, MmapFlags, FD, Hex),\n223: makeSyscallInfo(\"fadvise64\", FD, Hex, Hex, Hex),\n224: makeSyscallInfo(\"swapon\", Hex, Hex),\n225: makeSyscallInfo(\"swapoff\", Hex),\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/strace/mmap.go", "diff": "+// Copyright 2021 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package strace\n+\n+import (\n+ \"gvisor.dev/gvisor/pkg/abi\"\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n+)\n+\n+// ProtectionFlagSet represents the protection to mmap(2).\n+var ProtectionFlagSet = abi.FlagSet{\n+ {\n+ Flag: linux.PROT_READ,\n+ Name: \"PROT_READ\",\n+ },\n+ {\n+ Flag: linux.PROT_WRITE,\n+ Name: \"PROT_WRITE\",\n+ },\n+ {\n+ Flag: linux.PROT_EXEC,\n+ Name: \"PROT_EXEC\",\n+ },\n+}\n+\n+// MmapFlagSet is the set of mmap(2) flags.\n+var MmapFlagSet = abi.FlagSet{\n+ {\n+ Flag: linux.MAP_SHARED,\n+ Name: \"MAP_SHARED\",\n+ },\n+ {\n+ Flag: linux.MAP_PRIVATE,\n+ Name: \"MAP_PRIVATE\",\n+ },\n+ {\n+ Flag: linux.MAP_FIXED,\n+ Name: \"MAP_FIXED\",\n+ },\n+ {\n+ Flag: linux.MAP_ANONYMOUS,\n+ Name: \"MAP_ANONYMOUS\",\n+ },\n+ {\n+ Flag: linux.MAP_GROWSDOWN,\n+ Name: \"MAP_GROWSDOWN\",\n+ },\n+ {\n+ Flag: linux.MAP_DENYWRITE,\n+ Name: \"MAP_DENYWRITE\",\n+ },\n+ {\n+ Flag: linux.MAP_EXECUTABLE,\n+ Name: \"MAP_EXECUTABLE\",\n+ },\n+ {\n+ Flag: linux.MAP_LOCKED,\n+ Name: \"MAP_LOCKED\",\n+ },\n+ {\n+ Flag: linux.MAP_NORESERVE,\n+ Name: \"MAP_NORESERVE\",\n+ },\n+ {\n+ Flag: linux.MAP_POPULATE,\n+ Name: \"MAP_POPULATE\",\n+ },\n+ {\n+ Flag: linux.MAP_NONBLOCK,\n+ Name: \"MAP_NONBLOCK\",\n+ },\n+ {\n+ Flag: linux.MAP_STACK,\n+ Name: \"MAP_STACK\",\n+ },\n+ {\n+ Flag: linux.MAP_HUGETLB,\n+ Name: \"MAP_HUGETLB\",\n+ },\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/strace/open.go", "new_path": "pkg/sentry/strace/open.go", "diff": "package strace\nimport (\n- \"golang.org/x/sys/unix\"\n\"gvisor.dev/gvisor/pkg/abi\"\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n)\n// OpenMode represents the mode to open(2) a file.\nvar OpenMode = abi.ValueSet{\n- unix.O_RDWR: \"O_RDWR\",\n- unix.O_WRONLY: \"O_WRONLY\",\n- unix.O_RDONLY: \"O_RDONLY\",\n+ linux.O_RDWR: \"O_RDWR\",\n+ linux.O_WRONLY: \"O_WRONLY\",\n+ linux.O_RDONLY: \"O_RDONLY\",\n}\n// OpenFlagSet is the set of open(2) flags.\nvar OpenFlagSet = abi.FlagSet{\n{\n- Flag: unix.O_APPEND,\n+ Flag: linux.O_APPEND,\nName: \"O_APPEND\",\n},\n{\n- Flag: unix.O_ASYNC,\n+ Flag: linux.O_ASYNC,\nName: \"O_ASYNC\",\n},\n{\n- Flag: unix.O_CLOEXEC,\n+ Flag: linux.O_CLOEXEC,\nName: \"O_CLOEXEC\",\n},\n{\n- Flag: unix.O_CREAT,\n+ Flag: linux.O_CREAT,\nName: \"O_CREAT\",\n},\n{\n- Flag: unix.O_DIRECT,\n+ Flag: linux.O_DIRECT,\nName: \"O_DIRECT\",\n},\n{\n- Flag: unix.O_DIRECTORY,\n+ Flag: linux.O_DIRECTORY,\nName: \"O_DIRECTORY\",\n},\n{\n- Flag: unix.O_EXCL,\n+ Flag: linux.O_EXCL,\nName: \"O_EXCL\",\n},\n{\n- Flag: unix.O_NOATIME,\n+ Flag: linux.O_NOATIME,\nName: \"O_NOATIME\",\n},\n{\n- Flag: unix.O_NOCTTY,\n+ Flag: linux.O_NOCTTY,\nName: \"O_NOCTTY\",\n},\n{\n- Flag: unix.O_NOFOLLOW,\n+ Flag: linux.O_NOFOLLOW,\nName: \"O_NOFOLLOW\",\n},\n{\n- Flag: unix.O_NONBLOCK,\n+ Flag: linux.O_NONBLOCK,\nName: \"O_NONBLOCK\",\n},\n{\n@@ -77,18 +77,22 @@ var OpenFlagSet = abi.FlagSet{\nName: \"O_PATH\",\n},\n{\n- Flag: unix.O_SYNC,\n+ Flag: linux.O_SYNC,\nName: \"O_SYNC\",\n},\n{\n- Flag: unix.O_TRUNC,\n+ Flag: linux.O_TMPFILE,\n+ Name: \"O_TMPFILE\",\n+ },\n+ {\n+ Flag: linux.O_TRUNC,\nName: \"O_TRUNC\",\n},\n}\nfunc open(val uint64) string {\n- s := OpenMode.Parse(val & unix.O_ACCMODE)\n- if flags := OpenFlagSet.Parse(val &^ unix.O_ACCMODE); flags != \"\" {\n+ s := OpenMode.Parse(val & linux.O_ACCMODE)\n+ if flags := OpenFlagSet.Parse(val &^ linux.O_ACCMODE); flags != \"\" {\ns += \"|\" + flags\n}\nreturn s\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/strace/strace.go", "new_path": "pkg/sentry/strace/strace.go", "diff": "@@ -489,6 +489,10 @@ func (i *SyscallInfo) pre(t *kernel.Task, args arch.SyscallArguments, maximumBlo\noutput = append(output, epollEvents(t, args[arg].Pointer(), 0 /* numEvents */, uint64(maximumBlobSize)))\ncase SelectFDSet:\noutput = append(output, fdSet(t, int(args[0].Int()), args[arg].Pointer()))\n+ case MmapProt:\n+ output = append(output, ProtectionFlagSet.Parse(uint64(args[arg].Uint())))\n+ case MmapFlags:\n+ output = append(output, MmapFlagSet.Parse(uint64(args[arg].Uint())))\ncase Oct:\noutput = append(output, \"0o\"+strconv.FormatUint(args[arg].Uint64(), 8))\ncase Hex:\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/strace/syscalls.go", "new_path": "pkg/sentry/strace/syscalls.go", "diff": "@@ -238,6 +238,12 @@ const (\n// EpollEvents is an array of struct epoll_event. It is the events\n// argument in epoll_wait(2)/epoll_pwait(2).\nEpollEvents\n+\n+ // MmapProt is the protection argument in mmap(2).\n+ MmapProt\n+\n+ // MmapFlags is the flags argument in mmap(2).\n+ MmapFlags\n)\n// defaultFormat is the syscall argument format to use if the actual format is\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/watchdog/watchdog.go", "new_path": "pkg/sentry/watchdog/watchdog.go", "diff": "@@ -115,14 +115,14 @@ func (a *Action) Get() interface{} {\n}\n// String returns Action's string representation.\n-func (a *Action) String() string {\n- switch *a {\n+func (a Action) String() string {\n+ switch a {\ncase LogWarning:\nreturn \"logWarning\"\ncase Panic:\nreturn \"panic\"\ndefault:\n- panic(fmt.Sprintf(\"Invalid watchdog action: %d\", *a))\n+ panic(fmt.Sprintf(\"Invalid watchdog action: %d\", a))\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "runsc/config/config.go", "new_path": "runsc/config/config.go", "diff": "@@ -239,14 +239,14 @@ func (f *FileAccessType) Get() interface{} {\n}\n// String implements flag.Value.\n-func (f *FileAccessType) String() string {\n- switch *f {\n+func (f FileAccessType) String() string {\n+ switch f {\ncase FileAccessShared:\nreturn \"shared\"\ncase FileAccessExclusive:\nreturn \"exclusive\"\n}\n- panic(fmt.Sprintf(\"Invalid file access type %v\", *f))\n+ panic(fmt.Sprintf(\"Invalid file access type %d\", f))\n}\n// NetworkType tells which network stack to use.\n@@ -288,8 +288,8 @@ func (n *NetworkType) Get() interface{} {\n}\n// String implements flag.Value.\n-func (n *NetworkType) String() string {\n- switch *n {\n+func (n NetworkType) String() string {\n+ switch n {\ncase NetworkSandbox:\nreturn \"sandbox\"\ncase NetworkHost:\n@@ -297,7 +297,7 @@ func (n *NetworkType) String() string {\ncase NetworkNone:\nreturn \"none\"\n}\n- panic(fmt.Sprintf(\"Invalid network type %v\", *n))\n+ panic(fmt.Sprintf(\"Invalid network type %d\", n))\n}\n// QueueingDiscipline is used to specify the kind of Queueing Discipline to\n@@ -335,14 +335,14 @@ func (q *QueueingDiscipline) Get() interface{} {\n}\n// String implements flag.Value.\n-func (q *QueueingDiscipline) String() string {\n- switch *q {\n+func (q QueueingDiscipline) String() string {\n+ switch q {\ncase QDiscNone:\nreturn \"none\"\ncase QDiscFIFO:\nreturn \"fifo\"\n}\n- panic(fmt.Sprintf(\"Invalid qdisc %v\", *q))\n+ panic(fmt.Sprintf(\"Invalid qdisc %d\", q))\n}\nfunc leakModePtr(v refs.LeakMode) *refs.LeakMode {\n" } ]
Go
Apache License 2.0
google/gvisor
Parse mmap protection and flags in strace PiperOrigin-RevId: 378712518
259,992
10.06.2021 13:28:06
25,200
21169357ca913de9cef50da6f235a482b7a3cfab
Add /proc/sys/vm/max_map_count Set it to int32 max because gVisor doesn't have a limit. Fixes
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/proc/sys.go", "new_path": "pkg/sentry/fs/proc/sys.go", "diff": "@@ -77,6 +77,27 @@ func (*overcommitMemory) ReadSeqFileData(ctx context.Context, h seqfile.SeqHandl\n}, 0\n}\n+// +stateify savable\n+type maxMapCount struct{}\n+\n+// NeedsUpdate implements seqfile.SeqSource.\n+func (*maxMapCount) NeedsUpdate(int64) bool {\n+ return true\n+}\n+\n+// ReadSeqFileData implements seqfile.SeqSource.\n+func (*maxMapCount) ReadSeqFileData(ctx context.Context, h seqfile.SeqHandle) ([]seqfile.SeqData, int64) {\n+ if h != nil {\n+ return nil, 0\n+ }\n+ return []seqfile.SeqData{\n+ {\n+ Buf: []byte(\"2147483647\\n\"),\n+ Handle: (*maxMapCount)(nil),\n+ },\n+ }, 0\n+}\n+\nfunc (p *proc) newKernelDir(ctx context.Context, msrc *fs.MountSource) *fs.Inode {\nh := hostname{\nSimpleFileInode: *fsutil.NewSimpleFileInode(ctx, fs.RootOwner, fs.FilePermsFromMode(0444), linux.PROC_SUPER_MAGIC),\n@@ -96,6 +117,7 @@ func (p *proc) newKernelDir(ctx context.Context, msrc *fs.MountSource) *fs.Inode\nfunc (p *proc) newVMDir(ctx context.Context, msrc *fs.MountSource) *fs.Inode {\nchildren := map[string]*fs.Inode{\n+ \"max_map_count\": seqfile.NewSeqFileInode(ctx, &maxMapCount{}, msrc),\n\"mmap_min_addr\": seqfile.NewSeqFileInode(ctx, &mmapMinAddrData{p.k}, msrc),\n\"overcommit_memory\": seqfile.NewSeqFileInode(ctx, &overcommitMemory{}, msrc),\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/proc/tasks_sys.go", "new_path": "pkg/sentry/fsimpl/proc/tasks_sys.go", "diff": "@@ -55,6 +55,7 @@ func (fs *filesystem) newSysDir(ctx context.Context, root *auth.Credentials, k *\n}),\n}),\n\"vm\": fs.newStaticDir(ctx, root, map[string]kernfs.Inode{\n+ \"max_map_count\": fs.newInode(ctx, root, 0444, newStaticFile(\"2147483647\\n\")),\n\"mmap_min_addr\": fs.newInode(ctx, root, 0444, &mmapMinAddrData{k: k}),\n\"overcommit_memory\": fs.newInode(ctx, root, 0444, newStaticFile(\"0\\n\")),\n}),\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/proc.cc", "new_path": "test/syscalls/linux/proc.cc", "diff": "@@ -2364,6 +2364,15 @@ TEST(ProcSysKernelHostname, MatchesUname) {\nEXPECT_EQ(procfs_hostname, hostname);\n}\n+TEST(ProcSysVmMaxmapCount, HasNumericValue) {\n+ const std::string val_str =\n+ ASSERT_NO_ERRNO_AND_VALUE(GetContents(\"/proc/sys/vm/max_map_count\"));\n+ int32_t val;\n+ EXPECT_TRUE(absl::SimpleAtoi(val_str, &val))\n+ << \"/proc/sys/vm/max_map_count does not contain a numeric value: \"\n+ << val_str;\n+}\n+\nTEST(ProcSysVmMmapMinAddr, HasNumericValue) {\nconst std::string mmap_min_addr_str =\nASSERT_NO_ERRNO_AND_VALUE(GetContents(\"/proc/sys/vm/mmap_min_addr\"));\n" } ]
Go
Apache License 2.0
google/gvisor
Add /proc/sys/vm/max_map_count Set it to int32 max because gVisor doesn't have a limit. Fixes #2337 PiperOrigin-RevId: 378722230
259,992
10.06.2021 13:47:43
25,200
d81fcbf85c771a75bcf6600a02b3d411c6f7e383
Set RLimits during `runsc exec`
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/control/proc.go", "new_path": "pkg/sentry/control/proc.go", "diff": "@@ -99,6 +99,9 @@ type ExecArgs struct {\n// PIDNamespace is the pid namespace for the process being executed.\nPIDNamespace *kernel.PIDNamespace\n+\n+ // Limits is the limit set for the process being executed.\n+ Limits *limits.LimitSet\n}\n// String prints the arguments as a string.\n@@ -151,6 +154,10 @@ func (proc *Proc) execAsync(args *ExecArgs) (*kernel.ThreadGroup, kernel.ThreadI\nif pidns == nil {\npidns = proc.Kernel.RootPIDNamespace()\n}\n+ limitSet := args.Limits\n+ if limitSet == nil {\n+ limitSet = limits.NewLimitSet()\n+ }\ninitArgs := kernel.CreateProcessArgs{\nFilename: args.Filename,\nArgv: args.Argv,\n@@ -161,7 +168,7 @@ func (proc *Proc) execAsync(args *ExecArgs) (*kernel.ThreadGroup, kernel.ThreadI\nCredentials: creds,\nFDTable: fdTable,\nUmask: 0022,\n- Limits: limits.NewLimitSet(),\n+ Limits: limitSet,\nMaxSymlinkTraversals: linux.MaxSymlinkTraversals,\nUTSNamespace: proc.Kernel.RootUTSNamespace(),\nIPCNamespace: proc.Kernel.RootIPCNamespace(),\n" }, { "change_type": "MODIFY", "old_path": "runsc/boot/loader.go", "new_path": "runsc/boot/loader.go", "diff": "@@ -963,10 +963,15 @@ func (l *Loader) executeAsync(args *control.ExecArgs) (kernel.ThreadID, error) {\n}\nargs.Envv = envv\n}\n+ args.PIDNamespace = tg.PIDNamespace()\n+\n+ args.Limits, err = createLimitSet(l.root.spec)\n+ if err != nil {\n+ return 0, fmt.Errorf(\"creating limits: %w\", err)\n+ }\n// Start the process.\nproc := control.Proc{Kernel: l.k}\n- args.PIDNamespace = tg.PIDNamespace()\nnewTG, tgid, ttyFile, ttyFileVFS2, err := control.ExecAsync(&proc, args)\nif err != nil {\nreturn 0, err\n" }, { "change_type": "MODIFY", "old_path": "runsc/container/container_test.go", "new_path": "runsc/container/container_test.go", "diff": "@@ -47,6 +47,62 @@ import (\n\"gvisor.dev/gvisor/runsc/specutils\"\n)\n+func TestMain(m *testing.M) {\n+ log.SetLevel(log.Debug)\n+ flag.Parse()\n+ if err := testutil.ConfigureExePath(); err != nil {\n+ panic(err.Error())\n+ }\n+ specutils.MaybeRunAsRoot()\n+ os.Exit(m.Run())\n+}\n+\n+func execute(cont *Container, name string, arg ...string) (unix.WaitStatus, error) {\n+ args := &control.ExecArgs{\n+ Filename: name,\n+ Argv: append([]string{name}, arg...),\n+ }\n+ return cont.executeSync(args)\n+}\n+\n+func executeCombinedOutput(cont *Container, name string, arg ...string) ([]byte, error) {\n+ r, w, err := os.Pipe()\n+ if err != nil {\n+ return nil, err\n+ }\n+ defer r.Close()\n+\n+ args := &control.ExecArgs{\n+ Filename: name,\n+ Argv: append([]string{name}, arg...),\n+ FilePayload: urpc.FilePayload{Files: []*os.File{os.Stdin, w, w}},\n+ }\n+ ws, err := cont.executeSync(args)\n+ w.Close()\n+ if err != nil {\n+ return nil, err\n+ }\n+ if ws != 0 {\n+ return nil, fmt.Errorf(\"exec failed, status: %v\", ws)\n+ }\n+\n+ out, err := ioutil.ReadAll(r)\n+ return out, err\n+}\n+\n+// executeSync synchronously executes a new process.\n+func (c *Container) executeSync(args *control.ExecArgs) (unix.WaitStatus, error) {\n+ pid, err := c.Execute(args)\n+ if err != nil {\n+ return 0, fmt.Errorf(\"error executing: %v\", err)\n+ }\n+ ws, err := c.WaitPID(pid)\n+ if err != nil {\n+ return 0, fmt.Errorf(\"error waiting: %v\", err)\n+ }\n+ return ws, nil\n+}\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@@ -2470,58 +2526,67 @@ func TestBindMountByOption(t *testing.T) {\n}\n}\n-func execute(cont *Container, name string, arg ...string) (unix.WaitStatus, error) {\n- args := &control.ExecArgs{\n- Filename: name,\n- Argv: append([]string{name}, arg...),\n- }\n- return cont.executeSync(args)\n+// TestRlimits sets limit to number of open files and checks that the limit\n+// is propagated to the container.\n+func TestRlimits(t *testing.T) {\n+ file, err := ioutil.TempFile(testutil.TmpDir(), \"ulimit\")\n+ if err != nil {\n+ t.Fatal(err)\n}\n+ cmd := fmt.Sprintf(\"ulimit -n > %q\", file.Name())\n-func executeCombinedOutput(cont *Container, name string, arg ...string) ([]byte, error) {\n- r, w, err := os.Pipe()\n- if err != nil {\n- return nil, err\n+ spec := testutil.NewSpecWithArgs(\"sh\", \"-c\", cmd)\n+ spec.Process.Rlimits = []specs.POSIXRlimit{\n+ {Type: \"RLIMIT_NOFILE\", Hard: 1000, Soft: 100},\n}\n- defer r.Close()\n- args := &control.ExecArgs{\n- Filename: name,\n- Argv: append([]string{name}, arg...),\n- FilePayload: urpc.FilePayload{Files: []*os.File{os.Stdin, w, w}},\n+ conf := testutil.TestConfig(t)\n+ if err := run(spec, conf); err != nil {\n+ t.Fatalf(\"Error running container: %v\", err)\n}\n- ws, err := cont.executeSync(args)\n- w.Close()\n+ got, err := ioutil.ReadFile(file.Name())\nif err != nil {\n- return nil, err\n+ t.Fatal(err)\n+ }\n+ if want := \"100\\n\"; string(got) != want {\n+ t.Errorf(\"ulimit result, got: %q, want: %q\", got, want)\n}\n- if ws != 0 {\n- return nil, fmt.Errorf(\"exec failed, status: %v\", ws)\n}\n- out, err := ioutil.ReadAll(r)\n- return out, err\n+// TestRlimitsExec sets limit to number of open files and checks that the limit\n+// is propagated to exec'd processes.\n+func TestRlimitsExec(t *testing.T) {\n+ spec := testutil.NewSpecWithArgs(\"sleep\", \"100\")\n+ spec.Process.Rlimits = []specs.POSIXRlimit{\n+ {Type: \"RLIMIT_NOFILE\", Hard: 1000, Soft: 100},\n}\n-// executeSync synchronously executes a new process.\n-func (c *Container) executeSync(args *control.ExecArgs) (unix.WaitStatus, error) {\n- pid, err := c.Execute(args)\n+ conf := testutil.TestConfig(t)\n+ _, bundleDir, cleanup, err := testutil.SetupContainer(spec, conf)\nif err != nil {\n- return 0, fmt.Errorf(\"error executing: %v\", err)\n+ t.Fatalf(\"error setting up container: %v\", err)\n}\n- ws, err := c.WaitPID(pid)\n+ defer cleanup()\n+\n+ args := Args{\n+ ID: testutil.RandomContainerID(),\n+ Spec: spec,\n+ BundleDir: bundleDir,\n+ }\n+ cont, err := New(conf, args)\nif err != nil {\n- return 0, fmt.Errorf(\"error waiting: %v\", err)\n+ t.Fatalf(\"error creating container: %v\", err)\n}\n- return ws, nil\n+ defer cont.Destroy()\n+ if err := cont.Start(conf); err != nil {\n+ t.Fatalf(\"error starting container: %v\", err)\n}\n-func TestMain(m *testing.M) {\n- log.SetLevel(log.Debug)\n- flag.Parse()\n- if err := testutil.ConfigureExePath(); err != nil {\n- panic(err.Error())\n+ got, err := executeCombinedOutput(cont, \"/bin/sh\", \"-c\", \"ulimit -n\")\n+ if err != nil {\n+ t.Fatal(err)\n+ }\n+ if want := \"100\\n\"; string(got) != want {\n+ t.Errorf(\"ulimit result, got: %q, want: %q\", got, want)\n}\n- specutils.MaybeRunAsRoot()\n- os.Exit(m.Run())\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Set RLimits during `runsc exec` PiperOrigin-RevId: 378726430
259,885
10.06.2021 15:52:10
25,200
0058fca32e8ac367c3d6b4396e1b40740d689b54
Disable all tests dependent on cloud_gvisor::testing::FuseTest.
[ { "change_type": "MODIFY", "old_path": "test/fuse/BUILD", "new_path": "test/fuse/BUILD", "diff": "@@ -2,75 +2,77 @@ load(\"//test/runner:defs.bzl\", \"syscall_test\")\npackage(licenses = [\"notice\"])\n-syscall_test(\n- fuse = \"True\",\n- test = \"//test/fuse/linux:stat_test\",\n-)\n-\n-syscall_test(\n- fuse = \"True\",\n- test = \"//test/fuse/linux:open_test\",\n-)\n-\n-syscall_test(\n- fuse = \"True\",\n- test = \"//test/fuse/linux:release_test\",\n-)\n-\n-syscall_test(\n- fuse = \"True\",\n- test = \"//test/fuse/linux:mknod_test\",\n-)\n-\n-syscall_test(\n- fuse = \"True\",\n- test = \"//test/fuse/linux:symlink_test\",\n-)\n-\n-syscall_test(\n- fuse = \"True\",\n- test = \"//test/fuse/linux:readlink_test\",\n-)\n-\n-syscall_test(\n- fuse = \"True\",\n- test = \"//test/fuse/linux:mkdir_test\",\n-)\n-\n-syscall_test(\n- fuse = \"True\",\n- test = \"//test/fuse/linux:read_test\",\n-)\n-\n-syscall_test(\n- fuse = \"True\",\n- test = \"//test/fuse/linux:write_test\",\n-)\n-\n-syscall_test(\n- fuse = \"True\",\n- test = \"//test/fuse/linux:rmdir_test\",\n-)\n-\n-syscall_test(\n- fuse = \"True\",\n- test = \"//test/fuse/linux:readdir_test\",\n-)\n-\n-syscall_test(\n- fuse = \"True\",\n- test = \"//test/fuse/linux:create_test\",\n-)\n-\n-syscall_test(\n- fuse = \"True\",\n- test = \"//test/fuse/linux:unlink_test\",\n-)\n-\n-syscall_test(\n- fuse = \"True\",\n- test = \"//test/fuse/linux:setstat_test\",\n-)\n+# FIXME(b/190750110)\n+#\n+# syscall_test(\n+# fuse = \"True\",\n+# test = \"//test/fuse/linux:stat_test\",\n+# )\n+#\n+# syscall_test(\n+# fuse = \"True\",\n+# test = \"//test/fuse/linux:open_test\",\n+# )\n+#\n+# syscall_test(\n+# fuse = \"True\",\n+# test = \"//test/fuse/linux:release_test\",\n+# )\n+#\n+# syscall_test(\n+# fuse = \"True\",\n+# test = \"//test/fuse/linux:mknod_test\",\n+# )\n+#\n+# syscall_test(\n+# fuse = \"True\",\n+# test = \"//test/fuse/linux:symlink_test\",\n+# )\n+#\n+# syscall_test(\n+# fuse = \"True\",\n+# test = \"//test/fuse/linux:readlink_test\",\n+# )\n+#\n+# syscall_test(\n+# fuse = \"True\",\n+# test = \"//test/fuse/linux:mkdir_test\",\n+# )\n+#\n+# syscall_test(\n+# fuse = \"True\",\n+# test = \"//test/fuse/linux:read_test\",\n+# )\n+#\n+# syscall_test(\n+# fuse = \"True\",\n+# test = \"//test/fuse/linux:write_test\",\n+# )\n+#\n+# syscall_test(\n+# fuse = \"True\",\n+# test = \"//test/fuse/linux:rmdir_test\",\n+# )\n+#\n+# syscall_test(\n+# fuse = \"True\",\n+# test = \"//test/fuse/linux:readdir_test\",\n+# )\n+#\n+# syscall_test(\n+# fuse = \"True\",\n+# test = \"//test/fuse/linux:create_test\",\n+# )\n+#\n+# syscall_test(\n+# fuse = \"True\",\n+# test = \"//test/fuse/linux:unlink_test\",\n+# )\n+#\n+# syscall_test(\n+# fuse = \"True\",\n+# test = \"//test/fuse/linux:setstat_test\",\n+# )\nsyscall_test(\nfuse = \"True\",\n" } ]
Go
Apache License 2.0
google/gvisor
Disable all tests dependent on cloud_gvisor::testing::FuseTest. PiperOrigin-RevId: 378753134