diff options
Diffstat (limited to 'test/syscalls')
36 files changed, 984 insertions, 120 deletions
diff --git a/test/syscalls/BUILD b/test/syscalls/BUILD index 95dc9157b..4ac511740 100644 --- a/test/syscalls/BUILD +++ b/test/syscalls/BUILD @@ -255,7 +255,7 @@ syscall_test(test = "//test/syscalls/linux:pause_test") syscall_test( size = "large", - add_overlay = False, # TODO(gvisor.dev/issue/318): enable when fixed. + add_overlay = True, shard_count = 5, test = "//test/syscalls/linux:pipe_test", ) @@ -609,8 +609,6 @@ syscall_test(test = "//test/syscalls/linux:sysret_test") syscall_test( size = "medium", shard_count = 10, - # FIXME(b/135470853) - tags = ["flaky"], test = "//test/syscalls/linux:tcp_socket_test", ) diff --git a/test/syscalls/linux/BUILD b/test/syscalls/linux/BUILD index 7e3ad08a9..4735284ba 100644 --- a/test/syscalls/linux/BUILD +++ b/test/syscalls/linux/BUILD @@ -985,6 +985,7 @@ cc_binary( "//test/util:file_descriptor", "//test/util:logging", "//test/util:memory_util", + "//test/util:multiprocess_util", "//test/util:posix_error", "//test/util:temp_path", "//test/util:test_main", @@ -1176,6 +1177,7 @@ cc_binary( "//test/util:temp_path", "//test/util:test_main", "//test/util:test_util", + "//test/util:thread_util", "@com_google_absl//absl/strings", "@com_google_googletest//:gtest", ], @@ -2939,6 +2941,8 @@ cc_binary( testonly = 1, srcs = ["tcp_socket.cc"], linkstatic = 1, + # FIXME(b/135470853) + tags = ["flaky"], deps = [ ":socket_test_util", "//test/util:file_descriptor", @@ -2997,6 +3001,8 @@ cc_binary( testonly = 1, srcs = ["timers.cc"], linkstatic = 1, + # FIXME(b/136599201) + tags = ["flaky"], deps = [ "//test/util:cleanup", "//test/util:logging", @@ -3339,3 +3345,18 @@ cc_binary( "@com_google_googletest//:gtest", ], ) + +cc_binary( + name = "proc_net_tcp_test", + testonly = 1, + srcs = ["proc_net_tcp.cc"], + linkstatic = 1, + deps = [ + ":ip_socket_test_util", + "//test/util:file_descriptor", + "//test/util:test_main", + "//test/util:test_util", + "@com_google_absl//absl/strings", + "@com_google_googletest//:gtest", + ], +) diff --git a/test/syscalls/linux/chmod.cc b/test/syscalls/linux/chmod.cc index 79e98597f..7e918b9b2 100644 --- a/test/syscalls/linux/chmod.cc +++ b/test/syscalls/linux/chmod.cc @@ -140,7 +140,8 @@ TEST(ChmodTest, FchmodatFile) { SyscallSucceeds()); ASSERT_THAT( - fchmodat(parent_fd, std::string(Basename(temp_file.path())).c_str(), 0444, 0), + fchmodat(parent_fd, std::string(Basename(temp_file.path())).c_str(), 0444, + 0), SyscallSucceeds()); EXPECT_THAT(close(parent_fd), SyscallSucceeds()); @@ -165,8 +166,9 @@ TEST(ChmodTest, FchmodatDir) { SyscallSucceeds()); EXPECT_THAT(close(fd), SyscallSucceeds()); - ASSERT_THAT(fchmodat(parent_fd, std::string(Basename(dir.path())).c_str(), 0, 0), - SyscallSucceeds()); + ASSERT_THAT( + fchmodat(parent_fd, std::string(Basename(dir.path())).c_str(), 0, 0), + SyscallSucceeds()); EXPECT_THAT(close(parent_fd), SyscallSucceeds()); EXPECT_THAT(open(dir.path().c_str(), O_RDONLY | O_DIRECTORY), diff --git a/test/syscalls/linux/chown.cc b/test/syscalls/linux/chown.cc index eb1762ddf..2e82f0b3a 100644 --- a/test/syscalls/linux/chown.cc +++ b/test/syscalls/linux/chown.cc @@ -186,10 +186,10 @@ INSTANTIATE_TEST_SUITE_P( return errorFromReturn("fchownat-fd", rc); }, [](const std::string& path, uid_t owner, gid_t group) -> PosixError { - ASSIGN_OR_RETURN_ERRNO( - auto dirfd, Open(std::string(Dirname(path)), O_DIRECTORY | O_RDONLY)); - int rc = fchownat(dirfd.get(), std::string(Basename(path)).c_str(), owner, - group, 0); + ASSIGN_OR_RETURN_ERRNO(auto dirfd, Open(std::string(Dirname(path)), + O_DIRECTORY | O_RDONLY)); + int rc = fchownat(dirfd.get(), std::string(Basename(path)).c_str(), + owner, group, 0); MaybeSave(); return errorFromReturn("fchownat-dirfd", rc); })); diff --git a/test/syscalls/linux/chroot.cc b/test/syscalls/linux/chroot.cc index a4354ff62..498c45f16 100644 --- a/test/syscalls/linux/chroot.cc +++ b/test/syscalls/linux/chroot.cc @@ -273,7 +273,8 @@ TEST(ChrootTest, ProcMemSelfMapsNoEscapeProcOpen) { ASSERT_GT(bytes_read, 0); // Finally we want to make sure the maps don't contain the chroot path - ASSERT_EQ(std::string(buf, bytes_read).find(temp_dir.path()), std::string::npos); + ASSERT_EQ(std::string(buf, bytes_read).find(temp_dir.path()), + std::string::npos); } // Test that mounts outside the chroot will not appear in /proc/self/mounts or diff --git a/test/syscalls/linux/exceptions.cc b/test/syscalls/linux/exceptions.cc index 0da4c817d..370e85166 100644 --- a/test/syscalls/linux/exceptions.cc +++ b/test/syscalls/linux/exceptions.cc @@ -56,6 +56,26 @@ void inline Int3Normal() { asm(".byte 0xcd, 0x03\r\n"); } void inline Int3Compact() { asm(".byte 0xcc\r\n"); } +void InIOHelper(int width, int value) { + EXPECT_EXIT( + { + switch (width) { + case 1: + asm volatile("inb %%dx, %%al" ::"d"(value) : "%eax"); + break; + case 2: + asm volatile("inw %%dx, %%ax" ::"d"(value) : "%eax"); + break; + case 4: + asm volatile("inl %%dx, %%eax" ::"d"(value) : "%eax"); + break; + default: + FAIL() << "invalid input width, only 1, 2 or 4 is allowed"; + } + }, + ::testing::KilledBySignal(SIGSEGV), ""); +} + TEST(ExceptionTest, Halt) { // In order to prevent the regular handler from messing with things (and // perhaps refaulting until some other signal occurs), we reset the handler to @@ -87,6 +107,20 @@ TEST(ExceptionTest, DivideByZero) { ::testing::KilledBySignal(SIGFPE), ""); } +TEST(ExceptionTest, IOAccessFault) { + // See above. + struct sigaction sa = {}; + sa.sa_handler = SIG_DFL; + auto const cleanup = ASSERT_NO_ERRNO_AND_VALUE(ScopedSigaction(SIGSEGV, sa)); + + InIOHelper(1, 0x0); + InIOHelper(2, 0x7); + InIOHelper(4, 0x6); + InIOHelper(1, 0xffff); + InIOHelper(2, 0xffff); + InIOHelper(4, 0xfffd); +} + TEST(ExceptionTest, Alignment) { SetAlignmentCheck(); ClearAlignmentCheck(); diff --git a/test/syscalls/linux/exec.cc b/test/syscalls/linux/exec.cc index 06c322a99..4c7c95321 100644 --- a/test/syscalls/linux/exec.cc +++ b/test/syscalls/linux/exec.cc @@ -255,7 +255,8 @@ TEST(ExecDeathTest, InterpreterScriptArgNUL) { TempPath script = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith( GetAbsoluteTestTmpdir(), - absl::StrCat("#!", link.path(), " foo", std::string(1, '\0'), "bar"), 0755)); + absl::StrCat("#!", link.path(), " foo", std::string(1, '\0'), "bar"), + 0755)); CheckOutput(script.path(), {script.path()}, {}, ArgEnvExitStatus(2, 0), absl::StrCat(link.path(), "\nfoo\n", script.path(), "\n")); diff --git a/test/syscalls/linux/exec_proc_exe_workload.cc b/test/syscalls/linux/exec_proc_exe_workload.cc index b3fbd5042..b790fe5be 100644 --- a/test/syscalls/linux/exec_proc_exe_workload.cc +++ b/test/syscalls/linux/exec_proc_exe_workload.cc @@ -21,7 +21,8 @@ #include "test/util/posix_error.h" int main(int argc, char** argv, char** envp) { - std::string exe = gvisor::testing::ProcessExePath(getpid()).ValueOrDie(); + std::string exe = + gvisor::testing::ProcessExePath(getpid()).ValueOrDie(); if (exe[0] != '/') { std::cerr << "relative path: " << exe << std::endl; exit(1); diff --git a/test/syscalls/linux/file_base.h b/test/syscalls/linux/file_base.h index b5b972c07..36efabcae 100644 --- a/test/syscalls/linux/file_base.h +++ b/test/syscalls/linux/file_base.h @@ -160,7 +160,7 @@ class SocketTest : public ::testing::Test { // MatchesStringLength checks that a tuple argument of (struct iovec *, int) // corresponding to an iovec array and its length, contains data that matches -// the std::string length strlen. +// the string length strlen. MATCHER_P(MatchesStringLength, strlen, "") { struct iovec* iovs = arg.first; int niov = arg.second; @@ -177,7 +177,7 @@ MATCHER_P(MatchesStringLength, strlen, "") { // MatchesStringValue checks that a tuple argument of (struct iovec *, int) // corresponding to an iovec array and its length, contains data that matches -// the std::string value str. +// the string value str. MATCHER_P(MatchesStringValue, str, "") { struct iovec* iovs = arg.first; int len = strlen(str); diff --git a/test/syscalls/linux/flock.cc b/test/syscalls/linux/flock.cc index d89cfcbd7..b4a91455d 100644 --- a/test/syscalls/linux/flock.cc +++ b/test/syscalls/linux/flock.cc @@ -428,7 +428,7 @@ TEST_F(FlockTest, TestDupFdFollowedByLock) { ASSERT_THAT(flock(fd.get(), LOCK_UN), SyscallSucceedsWithValue(0)); } -// NOTE: These blocking tests are not perfect. Unfortunantely it's very hard to +// NOTE: These blocking tests are not perfect. Unfortunately it's very hard to // determine if a thread was actually blocked in the kernel so we're forced // to use timing. TEST_F(FlockTest, BlockingLockNoBlockingForSharedLocks_NoRandomSave) { diff --git a/test/syscalls/linux/getdents.cc b/test/syscalls/linux/getdents.cc index d146c8db7..8e4efa8d6 100644 --- a/test/syscalls/linux/getdents.cc +++ b/test/syscalls/linux/getdents.cc @@ -364,7 +364,7 @@ TYPED_TEST(GetdentsTest, PartialBuffer) { } // Open many file descriptors, then scan through /proc/self/fd to find and close -// them all. (The latter is commonly used to handle races betweek fork/execve +// them all. (The latter is commonly used to handle races between fork/execve // and the creation of unwanted non-O_CLOEXEC file descriptors.) This tests that // getdents iterates correctly despite mutation of /proc/self/fd. TYPED_TEST(GetdentsTest, ProcSelfFd) { @@ -437,6 +437,19 @@ TYPED_TEST(GetdentsTest, SeekResetsCursor) { EXPECT_EQ(expect, this->ReadAndCountAllEntries(&dirents)); } +// Test that getdents() after SEEK_END succeeds. +// This is a regression test for #128. +TYPED_TEST(GetdentsTest, Issue128ProcSeekEnd) { + auto fd = + ASSERT_NO_ERRNO_AND_VALUE(Open("/proc/self", O_RDONLY | O_DIRECTORY)); + typename TestFixture::DirentBufferType dirents(256); + + ASSERT_THAT(lseek(fd.get(), 0, SEEK_END), SyscallSucceeds()); + ASSERT_THAT(RetryEINTR(syscall)(this->SyscallNum(), fd.get(), dirents.Data(), + dirents.Size()), + SyscallSucceeds()); +} + // Some tests using the glibc readdir interface. TEST(ReaddirTest, OpenDir) { DIR* dev; diff --git a/test/syscalls/linux/inotify.cc b/test/syscalls/linux/inotify.cc index 6a3539e22..7384c27dc 100644 --- a/test/syscalls/linux/inotify.cc +++ b/test/syscalls/linux/inotify.cc @@ -122,8 +122,8 @@ std::string DumpEvents(const std::vector<Event>& events, int indent_level) { (events.size() > 1) ? "s" : ""); int i = 0; for (const Event& ev : events) { - ss << StreamFormat("%sevents[%d]: %s\n", std::string(indent_level, '\t'), i++, - DumpEvent(ev)); + ss << StreamFormat("%sevents[%d]: %s\n", std::string(indent_level, '\t'), + i++, DumpEvent(ev)); } return ss.str(); } @@ -295,10 +295,10 @@ PosixErrorOr<std::vector<Event>> DrainEvents(int fd) { if (event.len > 0) { TEST_CHECK(static_cast<int>(sizeof(struct inotify_event) + event.len) <= readlen); - ev.name = - std::string(cursor + offsetof(struct inotify_event, name)); // NOLINT + ev.name = std::string(cursor + + offsetof(struct inotify_event, name)); // NOLINT // Name field should always be smaller than event.len, otherwise we have - // a buffer overflow. The two sizes aren't equal because the std::string + // a buffer overflow. The two sizes aren't equal because the string // constructor will stop at the first null byte, while event.name may be // padded up to event.len using multiple null bytes. TEST_CHECK(ev.name.size() <= event.len); @@ -319,7 +319,8 @@ PosixErrorOr<FileDescriptor> InotifyInit1(int flags) { return FileDescriptor(fd); } -PosixErrorOr<int> InotifyAddWatch(int fd, const std::string& path, uint32_t mask) { +PosixErrorOr<int> InotifyAddWatch(int fd, const std::string& path, + uint32_t mask) { int wd; EXPECT_THAT(wd = inotify_add_watch(fd, path.c_str(), mask), SyscallSucceeds()); @@ -980,8 +981,8 @@ TEST(Inotify, WatchOnRelativePath) { EXPECT_THAT(chdir(root.path().c_str()), SyscallSucceeds()); // Add a watch on file1 with a relative path. - const int wd = ASSERT_NO_ERRNO_AND_VALUE( - InotifyAddWatch(fd.get(), std::string(Basename(file1.path())), IN_ALL_EVENTS)); + const int wd = ASSERT_NO_ERRNO_AND_VALUE(InotifyAddWatch( + fd.get(), std::string(Basename(file1.path())), IN_ALL_EVENTS)); // Perform a read on file1, this should generate an IN_ACCESS event. char c; diff --git a/test/syscalls/linux/itimer.cc b/test/syscalls/linux/itimer.cc index 57ffd1595..51ce323b9 100644 --- a/test/syscalls/linux/itimer.cc +++ b/test/syscalls/linux/itimer.cc @@ -197,12 +197,17 @@ int TestSIGALRMToMainThread() { // (but don't guarantee it), so we expect to see most samples on the main // thread. // + // The number of SIGALRMs delivered to a worker should not exceed 20% + // of the number of total signals expected (this is somewhat arbitrary). + const int worker_threshold = result.expected_total / 5; + + // // Linux only guarantees timers will never expire before the requested time. // Thus, we only check the upper bound and also it at least have one sample. TEST_CHECK(result.main_thread_samples <= result.expected_total); TEST_CHECK(result.main_thread_samples > 0); for (int num : result.worker_samples) { - TEST_CHECK_MSG(num <= 50, "worker received too many samples"); + TEST_CHECK_MSG(num <= worker_threshold, "worker received too many samples"); } return 0; diff --git a/test/syscalls/linux/madvise.cc b/test/syscalls/linux/madvise.cc index f6ad4d18b..08ff4052c 100644 --- a/test/syscalls/linux/madvise.cc +++ b/test/syscalls/linux/madvise.cc @@ -29,6 +29,7 @@ #include "test/util/file_descriptor.h" #include "test/util/logging.h" #include "test/util/memory_util.h" +#include "test/util/multiprocess_util.h" #include "test/util/posix_error.h" #include "test/util/temp_path.h" #include "test/util/test_util.h" @@ -136,6 +137,115 @@ TEST(MadviseDontneedTest, IgnoresPermissions) { EXPECT_THAT(madvise(m.ptr(), m.len(), MADV_DONTNEED), SyscallSucceeds()); } +TEST(MadviseDontforkTest, AddressLength) { + auto m = + ASSERT_NO_ERRNO_AND_VALUE(MmapAnon(kPageSize, PROT_NONE, MAP_PRIVATE)); + char *addr = static_cast<char *>(m.ptr()); + + // Address must be page aligned. + EXPECT_THAT(madvise(addr + 1, kPageSize, MADV_DONTFORK), + SyscallFailsWithErrno(EINVAL)); + + // Zero length madvise always succeeds. + EXPECT_THAT(madvise(addr, 0, MADV_DONTFORK), SyscallSucceeds()); + + // Length must not roll over after rounding up. + size_t badlen = std::numeric_limits<std::size_t>::max() - (kPageSize / 2); + EXPECT_THAT(madvise(0, badlen, MADV_DONTFORK), SyscallFailsWithErrno(EINVAL)); + + // Length need not be page aligned - it is implicitly rounded up. + EXPECT_THAT(madvise(addr, 1, MADV_DONTFORK), SyscallSucceeds()); + EXPECT_THAT(madvise(addr, kPageSize, MADV_DONTFORK), SyscallSucceeds()); +} + +TEST(MadviseDontforkTest, DontforkShared) { + // Mmap two shared file-backed pages and MADV_DONTFORK the second page. + TempPath f = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith( + /* parent = */ GetAbsoluteTestTmpdir(), + /* content = */ std::string(kPageSize * 2, 2), + TempPath::kDefaultFileMode)); + FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(Open(f.path(), O_RDWR)); + + Mapping m = ASSERT_NO_ERRNO_AND_VALUE(Mmap( + nullptr, kPageSize * 2, PROT_READ | PROT_WRITE, MAP_SHARED, fd.get(), 0)); + + const Mapping ms1 = Mapping(reinterpret_cast<void *>(m.addr()), kPageSize); + const Mapping ms2 = + Mapping(reinterpret_cast<void *>(m.addr() + kPageSize), kPageSize); + m.release(); + + ASSERT_THAT(madvise(ms2.ptr(), kPageSize, MADV_DONTFORK), SyscallSucceeds()); + + const auto rest = [&] { + // First page is mapped in child and modifications are visible to parent + // via the shared mapping. + TEST_CHECK(IsMapped(ms1.addr())); + ExpectAllMappingBytes(ms1, 2); + memset(ms1.ptr(), 1, kPageSize); + ExpectAllMappingBytes(ms1, 1); + + // Second page must not be mapped in child. + TEST_CHECK(!IsMapped(ms2.addr())); + }; + + EXPECT_THAT(InForkedProcess(rest), IsPosixErrorOkAndHolds(0)); + + ExpectAllMappingBytes(ms1, 1); // page contents modified by child. + ExpectAllMappingBytes(ms2, 2); // page contents unchanged. +} + +TEST(MadviseDontforkTest, DontforkAnonPrivate) { + // Mmap three anonymous pages and MADV_DONTFORK the middle page. + Mapping m = ASSERT_NO_ERRNO_AND_VALUE( + MmapAnon(kPageSize * 3, PROT_READ | PROT_WRITE, MAP_PRIVATE)); + const Mapping mp1 = Mapping(reinterpret_cast<void *>(m.addr()), kPageSize); + const Mapping mp2 = + Mapping(reinterpret_cast<void *>(m.addr() + kPageSize), kPageSize); + const Mapping mp3 = + Mapping(reinterpret_cast<void *>(m.addr() + 2 * kPageSize), kPageSize); + m.release(); + + ASSERT_THAT(madvise(mp2.ptr(), kPageSize, MADV_DONTFORK), SyscallSucceeds()); + + // Verify that all pages are zeroed and memset the first, second and third + // pages to 1, 2, and 3 respectively. + ExpectAllMappingBytes(mp1, 0); + memset(mp1.ptr(), 1, kPageSize); + + ExpectAllMappingBytes(mp2, 0); + memset(mp2.ptr(), 2, kPageSize); + + ExpectAllMappingBytes(mp3, 0); + memset(mp3.ptr(), 3, kPageSize); + + const auto rest = [&] { + // Verify first page is mapped, verify its contents and then modify the + // page. The mapping is private so the modifications are not visible to + // the parent. + TEST_CHECK(IsMapped(mp1.addr())); + ExpectAllMappingBytes(mp1, 1); + memset(mp1.ptr(), 11, kPageSize); + ExpectAllMappingBytes(mp1, 11); + + // Verify second page is not mapped. + TEST_CHECK(!IsMapped(mp2.addr())); + + // Verify third page is mapped, verify its contents and then modify the + // page. The mapping is private so the modifications are not visible to + // the parent. + TEST_CHECK(IsMapped(mp3.addr())); + ExpectAllMappingBytes(mp3, 3); + memset(mp3.ptr(), 13, kPageSize); + ExpectAllMappingBytes(mp3, 13); + }; + EXPECT_THAT(InForkedProcess(rest), IsPosixErrorOkAndHolds(0)); + + // The fork and COW by child should not affect the parent mappings. + ExpectAllMappingBytes(mp1, 1); + ExpectAllMappingBytes(mp2, 2); + ExpectAllMappingBytes(mp3, 3); +} + } // namespace } // namespace testing diff --git a/test/syscalls/linux/memfd.cc b/test/syscalls/linux/memfd.cc index 3494bcd13..e57b49a4a 100644 --- a/test/syscalls/linux/memfd.cc +++ b/test/syscalls/linux/memfd.cc @@ -60,7 +60,8 @@ int memfd_create(const std::string& name, unsigned int flags) { return syscall(__NR_memfd_create, name.c_str(), flags); } -PosixErrorOr<FileDescriptor> MemfdCreate(const std::string& name, uint32_t flags) { +PosixErrorOr<FileDescriptor> MemfdCreate(const std::string& name, + uint32_t flags) { int fd = memfd_create(name, flags); if (fd < 0) { return PosixError( diff --git a/test/syscalls/linux/mknod.cc b/test/syscalls/linux/mknod.cc index febf2eb14..4c45766c7 100644 --- a/test/syscalls/linux/mknod.cc +++ b/test/syscalls/linux/mknod.cc @@ -90,7 +90,7 @@ TEST(MknodTest, Fifo) { ASSERT_THAT(stat(fifo.c_str(), &st), SyscallSucceeds()); EXPECT_TRUE(S_ISFIFO(st.st_mode)); - std::string msg = "some string"; + std::string msg = "some std::string"; std::vector<char> buf(512); // Read-end of the pipe. @@ -116,7 +116,7 @@ TEST(MknodTest, FifoOtrunc) { ASSERT_THAT(stat(fifo.c_str(), &st), SyscallSucceeds()); EXPECT_TRUE(S_ISFIFO(st.st_mode)); - std::string msg = "some string"; + std::string msg = "some std::string"; std::vector<char> buf(512); // Read-end of the pipe. ScopedThread t([&fifo, &buf, &msg]() { @@ -144,7 +144,7 @@ TEST(MknodTest, FifoTruncNoOp) { ASSERT_THAT(stat(fifo.c_str(), &st), SyscallSucceeds()); EXPECT_TRUE(S_ISFIFO(st.st_mode)); - std::string msg = "some string"; + std::string msg = "some std::string"; std::vector<char> buf(512); // Read-end of the pipe. ScopedThread t([&fifo, &buf, &msg]() { diff --git a/test/syscalls/linux/mmap.cc b/test/syscalls/linux/mmap.cc index 5b5b4c2e8..a112316e9 100644 --- a/test/syscalls/linux/mmap.cc +++ b/test/syscalls/linux/mmap.cc @@ -113,7 +113,7 @@ class MMapTest : public ::testing::Test { size_t length_ = 0; }; -// Matches if arg contains the same contents as std::string str. +// Matches if arg contains the same contents as string str. MATCHER_P(EqualsMemory, str, "") { if (0 == memcmp(arg, str.c_str(), str.size())) { return true; @@ -1086,8 +1086,8 @@ TEST_F(MMapFileTest, WriteShared) { ASSERT_THAT(Read(buf.data(), buf.size()), SyscallSucceedsWithValue(buf.size())); // Cast to void* to avoid EXPECT_THAT assuming buf.data() is a - // NUL-terminated C std::string. EXPECT_THAT will try to print a char* as a C - // std::string, possibly overruning the buffer. + // NUL-terminated C string. EXPECT_THAT will try to print a char* as a C + // string, possibly overruning the buffer. EXPECT_THAT(reinterpret_cast<void*>(buf.data()), EqualsMemory(std::string(kFileContents))); } @@ -1122,6 +1122,7 @@ TEST_F(MMapFileTest, WriteSharedBeyondEnd) { ASSERT_THAT(Read(buf.data(), buf.size()), SyscallSucceedsWithValue(first.size())); // Cast to void* to avoid EXPECT_THAT assuming buf.data() is a + // NUL-terminated C string. EXPECT_THAT will try to print a char* as a C // NUL-terminated C std::string. EXPECT_THAT will try to print a char* as a C // std::string, possibly overruning the buffer. EXPECT_THAT(reinterpret_cast<void*>(buf.data()), EqualsMemory(first)); @@ -1159,8 +1160,8 @@ TEST_F(MMapFileTest, WriteSharedTruncateUp) { ASSERT_THAT(Read(buf.data(), buf.size()), SyscallSucceedsWithValue(buf.size())); // Cast to void* to avoid EXPECT_THAT assuming buf.data() is a - // NUL-terminated C std::string. EXPECT_THAT will try to print a char* as a C - // std::string, possibly overruning the buffer. + // NUL-terminated C string. EXPECT_THAT will try to print a char* as a C + // string, possibly overruning the buffer. EXPECT_THAT(reinterpret_cast<void*>(buf.data()), EqualsMemory(first)); EXPECT_THAT(reinterpret_cast<void*>(buf.data() + kPageSize / 2), EqualsMemory(second)); @@ -1234,8 +1235,8 @@ TEST_F(MMapFileTest, WriteSharedTruncateDownThenUp) { ASSERT_THAT(Read(buf.data(), buf.size()), SyscallSucceedsWithValue(buf.size())); // Cast to void* to avoid EXPECT_THAT assuming buf.data() is a - // NUL-terminated C std::string. EXPECT_THAT will try to print a char* as a C - // std::string, possibly overruning the buffer. + // NUL-terminated C string. EXPECT_THAT will try to print a char* as a C + // string, possibly overruning the buffer. EXPECT_THAT(reinterpret_cast<void*>(buf.data()), EqualsMemory(zeroed)); } @@ -1363,8 +1364,8 @@ TEST_F(MMapFileTest, WritePrivate) { ASSERT_THAT(Read(buf.data(), buf.size()), SyscallSucceedsWithValue(buf.size())); // Cast to void* to avoid EXPECT_THAT assuming buf.data() is a - // NUL-terminated C std::string. EXPECT_THAT will try to print a char* as a C - // std::string, possibly overruning the buffer. + // NUL-terminated C string. EXPECT_THAT will try to print a char* as a C + // string, possibly overruning the buffer. EXPECT_THAT(reinterpret_cast<void*>(buf.data()), EqualsMemory(std::string(len, '\0'))); } diff --git a/test/syscalls/linux/mremap.cc b/test/syscalls/linux/mremap.cc index 7298d4ca8..64e435cb7 100644 --- a/test/syscalls/linux/mremap.cc +++ b/test/syscalls/linux/mremap.cc @@ -46,17 +46,6 @@ PosixErrorOr<void*> Mremap(void* old_address, size_t old_size, size_t new_size, return rv; } -// Returns true if the page containing addr is mapped. -bool IsMapped(uintptr_t addr) { - int const rv = msync(reinterpret_cast<void*>(addr & ~(kPageSize - 1)), - kPageSize, MS_ASYNC); - if (rv == 0) { - return true; - } - TEST_PCHECK_MSG(errno == ENOMEM, "msync failed with unexpected errno"); - return false; -} - // Fixture for mremap tests parameterized by mmap flags. using MremapParamTest = ::testing::TestWithParam<int>; diff --git a/test/syscalls/linux/open.cc b/test/syscalls/linux/open.cc index 42646bb02..e0525f386 100644 --- a/test/syscalls/linux/open.cc +++ b/test/syscalls/linux/open.cc @@ -28,6 +28,7 @@ #include "test/util/fs_util.h" #include "test/util/temp_path.h" #include "test/util/test_util.h" +#include "test/util/thread_util.h" namespace gvisor { namespace testing { @@ -214,6 +215,42 @@ TEST_F(OpenTest, AppendOnly) { SyscallSucceedsWithValue(kBufSize * 3)); } +TEST_F(OpenTest, AppendConcurrentWrite) { + constexpr int kThreadCount = 5; + constexpr int kBytesPerThread = 10000; + std::unique_ptr<ScopedThread> threads[kThreadCount]; + + // In case of the uncached policy, we expect that a file system can be changed + // externally, so we create a new inode each time when we open a file and we + // can't guarantee that writes to files with O_APPEND will work correctly. + SKIP_IF(getenv("GVISOR_GOFER_UNCACHED")); + + EXPECT_THAT(truncate(test_file_name_.c_str(), 0), SyscallSucceeds()); + + std::string filename = test_file_name_; + DisableSave ds; // Too many syscalls. + // Start kThreadCount threads which will write concurrently into the same + // file. + for (int i = 0; i < kThreadCount; i++) { + threads[i] = absl::make_unique<ScopedThread>([filename]() { + const FileDescriptor fd = + ASSERT_NO_ERRNO_AND_VALUE(Open(filename, O_RDWR | O_APPEND)); + + for (int j = 0; j < kBytesPerThread; j++) { + EXPECT_THAT(WriteFd(fd.get(), &j, 1), SyscallSucceedsWithValue(1)); + } + }); + } + for (int i = 0; i < kThreadCount; i++) { + threads[i]->Join(); + } + + // Check that the size of the file is correct. + struct stat st; + EXPECT_THAT(stat(test_file_name_.c_str(), &st), SyscallSucceeds()); + EXPECT_EQ(st.st_size, kThreadCount * kBytesPerThread); +} + TEST_F(OpenTest, Truncate) { { // First write some data to the new file and close it. diff --git a/test/syscalls/linux/pipe.cc b/test/syscalls/linux/pipe.cc index 1f4422f4e..65afb90f3 100644 --- a/test/syscalls/linux/pipe.cc +++ b/test/syscalls/linux/pipe.cc @@ -339,11 +339,13 @@ TEST_P(PipeTest, BlockPartialWriteClosed) { SKIP_IF(!CreateBlocking()); ScopedThread t([this]() { - std::vector<char> buf(2 * Size()); + const int pipe_size = Size(); + std::vector<char> buf(2 * pipe_size); + // Write more than fits in the buffer. Blocks then returns partial write // when the other end is closed. The next call returns EPIPE. ASSERT_THAT(write(wfd_.get(), buf.data(), buf.size()), - SyscallSucceedsWithValue(Size())); + SyscallSucceedsWithValue(pipe_size)); EXPECT_THAT(write(wfd_.get(), buf.data(), buf.size()), SyscallFailsWithErrno(EPIPE)); }); diff --git a/test/syscalls/linux/proc.cc b/test/syscalls/linux/proc.cc index 2177665c8..b440ba0df 100644 --- a/test/syscalls/linux/proc.cc +++ b/test/syscalls/linux/proc.cc @@ -206,8 +206,8 @@ PosixError WithSubprocess(SubprocessCallback const& running, } // Access the file returned by name when a subprocess is running. -PosixError AccessWhileRunning(std::function<std::string(int pid)> name, int flags, - std::function<void(int fd)> access) { +PosixError AccessWhileRunning(std::function<std::string(int pid)> name, + int flags, std::function<void(int fd)> access) { FileDescriptor fd; return WithSubprocess( [&](int pid) -> PosixError { @@ -221,8 +221,8 @@ PosixError AccessWhileRunning(std::function<std::string(int pid)> name, int flag } // Access the file returned by name when the a subprocess is zombied. -PosixError AccessWhileZombied(std::function<std::string(int pid)> name, int flags, - std::function<void(int fd)> access) { +PosixError AccessWhileZombied(std::function<std::string(int pid)> name, + int flags, std::function<void(int fd)> access) { FileDescriptor fd; return WithSubprocess( [&](int pid) -> PosixError { @@ -239,8 +239,8 @@ PosixError AccessWhileZombied(std::function<std::string(int pid)> name, int flag } // Access the file returned by name when the a subprocess is exited. -PosixError AccessWhileExited(std::function<std::string(int pid)> name, int flags, - std::function<void(int fd)> access) { +PosixError AccessWhileExited(std::function<std::string(int pid)> name, + int flags, std::function<void(int fd)> access) { FileDescriptor fd; return WithSubprocess( [&](int pid) -> PosixError { @@ -704,7 +704,8 @@ TEST(ProcSelfExe, Absolute) { // Sanity check for /proc/cpuinfo fields that must be present. TEST(ProcCpuinfo, RequiredFieldsArePresent) { - std::string proc_cpuinfo = ASSERT_NO_ERRNO_AND_VALUE(GetContents("/proc/cpuinfo")); + std::string proc_cpuinfo = + ASSERT_NO_ERRNO_AND_VALUE(GetContents("/proc/cpuinfo")); ASSERT_FALSE(proc_cpuinfo.empty()); std::vector<std::string> cpuinfo_fields = absl::StrSplit(proc_cpuinfo, '\n'); @@ -743,7 +744,8 @@ TEST(ProcCpuinfo, DeniesWrite) { // Sanity checks that uptime is present. TEST(ProcUptime, IsPresent) { - std::string proc_uptime = ASSERT_NO_ERRNO_AND_VALUE(GetContents("/proc/uptime")); + std::string proc_uptime = + ASSERT_NO_ERRNO_AND_VALUE(GetContents("/proc/uptime")); ASSERT_FALSE(proc_uptime.empty()); std::vector<std::string> uptime_parts = absl::StrSplit(proc_uptime, ' '); @@ -775,7 +777,8 @@ TEST(ProcUptime, IsPresent) { } TEST(ProcMeminfo, ContainsBasicFields) { - std::string proc_meminfo = ASSERT_NO_ERRNO_AND_VALUE(GetContents("/proc/meminfo")); + std::string proc_meminfo = + ASSERT_NO_ERRNO_AND_VALUE(GetContents("/proc/meminfo")); EXPECT_THAT(proc_meminfo, AllOf(ContainsRegex(R"(MemTotal:\s+[0-9]+ kB)"), ContainsRegex(R"(MemFree:\s+[0-9]+ kB)"))); } @@ -853,12 +856,14 @@ TEST(ProcStat, Fields) { } TEST(ProcLoadavg, EndsWithNewline) { - std::string proc_loadvg = ASSERT_NO_ERRNO_AND_VALUE(GetContents("/proc/loadavg")); + std::string proc_loadvg = + ASSERT_NO_ERRNO_AND_VALUE(GetContents("/proc/loadavg")); EXPECT_EQ(proc_loadvg.back(), '\n'); } TEST(ProcLoadavg, Fields) { - std::string proc_loadvg = ASSERT_NO_ERRNO_AND_VALUE(GetContents("/proc/loadavg")); + std::string proc_loadvg = + ASSERT_NO_ERRNO_AND_VALUE(GetContents("/proc/loadavg")); std::vector<std::string> lines = absl::StrSplit(proc_loadvg, '\n'); // Single line. @@ -1238,10 +1243,12 @@ TEST(ProcPidStatTest, VmStats) { EXPECT_NE('0', data_str[0]); } -// Parse an array of NUL-terminated char* arrays, returning a vector of strings. +// Parse an array of NUL-terminated char* arrays, returning a vector of +// strings. std::vector<std::string> ParseNulTerminatedStrings(std::string contents) { EXPECT_EQ('\0', contents.back()); - // The split will leave an empty std::string if the NUL-byte remains, so pop it. + // The split will leave an empty string if the NUL-byte remains, so pop + // it. contents.pop_back(); return absl::StrSplit(contents, '\0'); @@ -1491,7 +1498,8 @@ TEST(ProcPidFile, SubprocessExited) { } PosixError DirContainsImpl(absl::string_view path, - const std::vector<std::string>& targets, bool strict) { + const std::vector<std::string>& targets, + bool strict) { ASSIGN_OR_RETURN_ERRNO(auto listing, ListDir(path, false)); bool success = true; @@ -1530,8 +1538,8 @@ PosixError DirContainsExactly(absl::string_view path, return DirContainsImpl(path, targets, true); } -PosixError EventuallyDirContainsExactly(absl::string_view path, - const std::vector<std::string>& targets) { +PosixError EventuallyDirContainsExactly( + absl::string_view path, const std::vector<std::string>& targets) { constexpr int kRetryCount = 100; const absl::Duration kRetryDelay = absl::Milliseconds(100); @@ -1553,11 +1561,13 @@ TEST(ProcTask, Basic) { DirContains("/proc/self/task", {".", "..", absl::StrCat(getpid())})); } -std::vector<std::string> TaskFiles(const std::vector<std::string>& initial_contents, - const std::vector<pid_t>& pids) { +std::vector<std::string> TaskFiles( + const std::vector<std::string>& initial_contents, + const std::vector<pid_t>& pids) { return VecCat<std::string>( initial_contents, - ApplyVec<std::string>([](const pid_t p) { return absl::StrCat(p); }, pids)); + ApplyVec<std::string>([](const pid_t p) { return absl::StrCat(p); }, + pids)); } std::vector<std::string> TaskFiles(const std::vector<pid_t>& pids) { @@ -1894,7 +1904,8 @@ void CheckDuplicatesRecursively(std::string path) { continue; } - ASSERT_EQ(children.find(std::string(dp->d_name)), children.end()) << dp->d_name; + ASSERT_EQ(children.find(std::string(dp->d_name)), children.end()) + << dp->d_name; children.insert(std::string(dp->d_name)); ASSERT_NE(dp->d_type, DT_UNKNOWN); @@ -1908,25 +1919,6 @@ void CheckDuplicatesRecursively(std::string path) { TEST(Proc, NoDuplicates) { CheckDuplicatesRecursively("/proc"); } -TEST(Proc, Getdents) { - int child_pid = fork(); - ASSERT_GE(child_pid, 0); - if (child_pid == 0) { - while(1){ - sleep(100); - } - } - ASSERT_THAT(child_pid, SyscallSucceeds()); - char name[100]; - char buf[1024]; - int fd; - sprintf(name, "/proc/%d/task", child_pid); - fd = open(name, O_RDONLY | O_DIRECTORY); - ASSERT_THAT(kill(child_pid, SIGKILL), SyscallSucceeds()); - ASSERT_THAT(waitpid(child_pid, NULL, 0), SyscallSucceedsWithValue(child_pid)); - ASSERT_THAT(syscall(SYS_getdents, fd, buf, 1024), SyscallFailsWithErrno(ENOENT)); -} - // Most /proc/PID files are owned by the task user with SUID_DUMP_USER. TEST(ProcPid, UserDumpableOwner) { int before; @@ -1972,6 +1964,22 @@ TEST(ProcPid, RootDumpableOwner) { EXPECT_THAT(st.st_gid, AnyOf(Eq(0), Eq(65534))); } +TEST(Proc, GetdentsEnoent) { + FileDescriptor fd; + ASSERT_NO_ERRNO(WithSubprocess( + [&](int pid) -> PosixError { + // Running. + ASSIGN_OR_RETURN_ERRNO(fd, Open(absl::StrCat("/proc/", pid, "/task"), + O_RDONLY | O_DIRECTORY)); + + return NoError(); + }, + nullptr, nullptr)); + char buf[1024]; + ASSERT_THAT(syscall(SYS_getdents, fd.get(), buf, sizeof(buf)), + SyscallFailsWithErrno(ENOENT)); +} + } // namespace } // namespace testing } // namespace gvisor diff --git a/test/syscalls/linux/proc_net_tcp.cc b/test/syscalls/linux/proc_net_tcp.cc new file mode 100644 index 000000000..578b20680 --- /dev/null +++ b/test/syscalls/linux/proc_net_tcp.cc @@ -0,0 +1,281 @@ +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include <sys/socket.h> +#include <sys/stat.h> +#include <sys/types.h> +#include <unistd.h> + +#include "gtest/gtest.h" +#include "gtest/gtest.h" +#include "absl/strings/numbers.h" +#include "absl/strings/str_join.h" +#include "absl/strings/str_split.h" +#include "test/syscalls/linux/ip_socket_test_util.h" +#include "test/util/file_descriptor.h" +#include "test/util/test_util.h" + +namespace gvisor { +namespace testing { +namespace { + +using absl::StrCat; +using absl::StrSplit; + +constexpr char kProcNetTCPHeader[] = + " sl local_address rem_address st tx_queue rx_queue tr tm->when " + "retrnsmt uid timeout inode " + " "; + +// Possible values of the "st" field in a /proc/net/tcp entry. Source: Linux +// kernel, include/net/tcp_states.h. +enum { + TCP_ESTABLISHED = 1, + TCP_SYN_SENT, + TCP_SYN_RECV, + TCP_FIN_WAIT1, + TCP_FIN_WAIT2, + TCP_TIME_WAIT, + TCP_CLOSE, + TCP_CLOSE_WAIT, + TCP_LAST_ACK, + TCP_LISTEN, + TCP_CLOSING, + TCP_NEW_SYN_RECV, + + TCP_MAX_STATES +}; + +// TCPEntry represents a single entry from /proc/net/tcp. +struct TCPEntry { + uint32_t local_addr; + uint16_t local_port; + + uint32_t remote_addr; + uint16_t remote_port; + + uint64_t state; + uint64_t uid; + uint64_t inode; +}; + +uint32_t IP(const struct sockaddr* addr) { + auto* in_addr = reinterpret_cast<const struct sockaddr_in*>(addr); + return in_addr->sin_addr.s_addr; +} + +uint16_t Port(const struct sockaddr* addr) { + auto* in_addr = reinterpret_cast<const struct sockaddr_in*>(addr); + return ntohs(in_addr->sin_port); +} + +// Finds the first entry in 'entries' for which 'predicate' returns true. +// Returns true on match, and sets 'match' to point to the matching entry. +bool FindBy(std::vector<TCPEntry> entries, TCPEntry* match, + std::function<bool(const TCPEntry&)> predicate) { + for (int i = 0; i < entries.size(); ++i) { + if (predicate(entries[i])) { + *match = entries[i]; + return true; + } + } + return false; +} + +bool FindByLocalAddr(std::vector<TCPEntry> entries, TCPEntry* match, + const struct sockaddr* addr) { + uint32_t host = IP(addr); + uint16_t port = Port(addr); + return FindBy(entries, match, [host, port](const TCPEntry& e) { + return (e.local_addr == host && e.local_port == port); + }); +} + +bool FindByRemoteAddr(std::vector<TCPEntry> entries, TCPEntry* match, + const struct sockaddr* addr) { + uint32_t host = IP(addr); + uint16_t port = Port(addr); + return FindBy(entries, match, [host, port](const TCPEntry& e) { + return (e.remote_addr == host && e.remote_port == port); + }); +} + +// Returns a parsed representation of /proc/net/tcp entries. +PosixErrorOr<std::vector<TCPEntry>> ProcNetTCPEntries() { + std::string content; + RETURN_IF_ERRNO(GetContents("/proc/net/tcp", &content)); + + bool found_header = false; + std::vector<TCPEntry> entries; + std::vector<std::string> lines = StrSplit(content, '\n'); + std::cerr << "<contents of /proc/net/tcp>" << std::endl; + for (std::string line : lines) { + std::cerr << line << std::endl; + + if (!found_header) { + EXPECT_EQ(line, kProcNetTCPHeader); + found_header = true; + continue; + } + if (line.empty()) { + continue; + } + + // Parse a single entry from /proc/net/tcp. + // + // Example entries: + // + // clang-format off + // + // sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode + // 0: 00000000:006F 00000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 1968 1 0000000000000000 100 0 0 10 0 + // 1: 0100007F:7533 00000000:0000 0A 00000000:00000000 00:00000000 00000000 120 0 10684 1 0000000000000000 100 0 0 10 0 + // ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ + // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 + // + // clang-format on + + TCPEntry entry; + std::vector<std::string> fields = + StrSplit(line, absl::ByAnyChar(": "), absl::SkipEmpty()); + + ASSIGN_OR_RETURN_ERRNO(entry.local_addr, AtoiBase(fields[1], 16)); + ASSIGN_OR_RETURN_ERRNO(entry.local_port, AtoiBase(fields[2], 16)); + + ASSIGN_OR_RETURN_ERRNO(entry.remote_addr, AtoiBase(fields[3], 16)); + ASSIGN_OR_RETURN_ERRNO(entry.remote_port, AtoiBase(fields[4], 16)); + + ASSIGN_OR_RETURN_ERRNO(entry.state, AtoiBase(fields[5], 16)); + ASSIGN_OR_RETURN_ERRNO(entry.uid, Atoi<uint64_t>(fields[11])); + ASSIGN_OR_RETURN_ERRNO(entry.inode, Atoi<uint64_t>(fields[13])); + + entries.push_back(entry); + } + std::cerr << "<end of /proc/net/tcp>" << std::endl; + + return entries; +} + +TEST(ProcNetTCP, Exists) { + const std::string content = + ASSERT_NO_ERRNO_AND_VALUE(GetContents("/proc/net/tcp")); + const std::string header_line = StrCat(kProcNetTCPHeader, "\n"); + if (IsRunningOnGvisor()) { + // Should be just the header since we don't have any tcp sockets yet. + EXPECT_EQ(content, header_line); + } else { + // On a general linux machine, we could have abitrary sockets on the system, + // so just check the header. + EXPECT_THAT(content, ::testing::StartsWith(header_line)); + } +} + +TEST(ProcNetTCP, EntryUID) { + auto sockets = + ASSERT_NO_ERRNO_AND_VALUE(IPv4TCPAcceptBindSocketPair(0).Create()); + std::vector<TCPEntry> entries = + ASSERT_NO_ERRNO_AND_VALUE(ProcNetTCPEntries()); + TCPEntry e; + EXPECT_TRUE(FindByLocalAddr(entries, &e, sockets->first_addr())); + EXPECT_EQ(e.uid, geteuid()); + EXPECT_TRUE(FindByRemoteAddr(entries, &e, sockets->first_addr())); + EXPECT_EQ(e.uid, geteuid()); +} + +TEST(ProcNetTCP, BindAcceptConnect) { + auto sockets = + ASSERT_NO_ERRNO_AND_VALUE(IPv4TCPAcceptBindSocketPair(0).Create()); + std::vector<TCPEntry> entries = + ASSERT_NO_ERRNO_AND_VALUE(ProcNetTCPEntries()); + // We can only make assertions about the total number of entries if we control + // the entire "machine". + if (IsRunningOnGvisor()) { + EXPECT_EQ(entries.size(), 2); + } + + TCPEntry e; + EXPECT_TRUE(FindByLocalAddr(entries, &e, sockets->first_addr())); + EXPECT_TRUE(FindByRemoteAddr(entries, &e, sockets->first_addr())); +} + +TEST(ProcNetTCP, InodeReasonable) { + auto sockets = + ASSERT_NO_ERRNO_AND_VALUE(IPv4TCPAcceptBindSocketPair(0).Create()); + std::vector<TCPEntry> entries = + ASSERT_NO_ERRNO_AND_VALUE(ProcNetTCPEntries()); + + TCPEntry accepted_entry; + ASSERT_TRUE(FindByLocalAddr(entries, &accepted_entry, sockets->first_addr())); + EXPECT_NE(accepted_entry.inode, 0); + + TCPEntry client_entry; + ASSERT_TRUE(FindByRemoteAddr(entries, &client_entry, sockets->first_addr())); + EXPECT_NE(client_entry.inode, 0); + EXPECT_NE(accepted_entry.inode, client_entry.inode); +} + +TEST(ProcNetTCP, State) { + std::unique_ptr<FileDescriptor> server = + ASSERT_NO_ERRNO_AND_VALUE(IPv4TCPUnboundSocket(0).Create()); + + auto test_addr = V4Loopback(); + ASSERT_THAT( + bind(server->get(), reinterpret_cast<struct sockaddr*>(&test_addr.addr), + test_addr.addr_len), + SyscallSucceeds()); + + struct sockaddr addr; + socklen_t addrlen = sizeof(struct sockaddr); + ASSERT_THAT(getsockname(server->get(), &addr, &addrlen), SyscallSucceeds()); + ASSERT_EQ(addrlen, sizeof(struct sockaddr)); + + ASSERT_THAT(listen(server->get(), 10), SyscallSucceeds()); + std::vector<TCPEntry> entries = + ASSERT_NO_ERRNO_AND_VALUE(ProcNetTCPEntries()); + TCPEntry listen_entry; + ASSERT_TRUE(FindByLocalAddr(entries, &listen_entry, &addr)); + EXPECT_EQ(listen_entry.state, TCP_LISTEN); + + std::unique_ptr<FileDescriptor> client = + ASSERT_NO_ERRNO_AND_VALUE(IPv4TCPUnboundSocket(0).Create()); + ASSERT_THAT(connect(client->get(), &addr, addrlen), SyscallSucceeds()); + entries = ASSERT_NO_ERRNO_AND_VALUE(ProcNetTCPEntries()); + ASSERT_TRUE(FindByLocalAddr(entries, &listen_entry, &addr)); + EXPECT_EQ(listen_entry.state, TCP_LISTEN); + TCPEntry client_entry; + ASSERT_TRUE(FindByRemoteAddr(entries, &client_entry, &addr)); + EXPECT_EQ(client_entry.state, TCP_ESTABLISHED); + + FileDescriptor accepted = + ASSERT_NO_ERRNO_AND_VALUE(Accept(server->get(), nullptr, nullptr)); + + const uint32_t accepted_local_host = IP(&addr); + const uint16_t accepted_local_port = Port(&addr); + + entries = ASSERT_NO_ERRNO_AND_VALUE(ProcNetTCPEntries()); + TCPEntry accepted_entry; + ASSERT_TRUE(FindBy(entries, &accepted_entry, + [client_entry, accepted_local_host, + accepted_local_port](const TCPEntry& e) { + return e.local_addr == accepted_local_host && + e.local_port == accepted_local_port && + e.remote_addr == client_entry.local_addr && + e.remote_port == client_entry.local_port; + })); + EXPECT_EQ(accepted_entry.state, TCP_ESTABLISHED); +} + +} // namespace +} // namespace testing +} // namespace gvisor diff --git a/test/syscalls/linux/proc_net_unix.cc b/test/syscalls/linux/proc_net_unix.cc index 82d325c17..9b9be66ff 100644 --- a/test/syscalls/linux/proc_net_unix.cc +++ b/test/syscalls/linux/proc_net_unix.cc @@ -67,7 +67,7 @@ std::string ExtractPath(const struct sockaddr* addr) { // Abstract socket paths are null padded to the end of the struct // sockaddr. However, these null bytes may or may not show up in // /proc/net/unix depending on the kernel version. Truncate after the first - // null byte (by treating path as a c-std::string). + // null byte (by treating path as a c-string). return StrCat("@", &path[1]); } return std::string(path); @@ -80,7 +80,7 @@ PosixErrorOr<std::vector<UnixEntry>> ProcNetUnixEntries() { bool skipped_header = false; std::vector<UnixEntry> entries; - std::vector<std::string> lines = absl::StrSplit(content, absl::ByAnyChar("\n")); + std::vector<std::string> lines = absl::StrSplit(content, '\n'); std::cerr << "<contents of /proc/net/unix>" << std::endl; for (std::string line : lines) { // Emit the proc entry to the test output to provide context for the test @@ -123,7 +123,8 @@ PosixErrorOr<std::vector<UnixEntry>> ProcNetUnixEntries() { UnixEntry entry; // Process the first 6 fields, up to but not including "Inode". - std::vector<std::string> fields = absl::StrSplit(line, absl::MaxSplits(' ', 6)); + std::vector<std::string> fields = + absl::StrSplit(line, absl::MaxSplits(' ', 6)); if (fields.size() < 7) { return PosixError(EINVAL, StrFormat("Invalid entry: '%s'\n", line)); @@ -162,7 +163,7 @@ PosixErrorOr<std::vector<UnixEntry>> ProcNetUnixEntries() { // Finds the first entry in 'entries' for which 'predicate' returns true. // Returns true on match, and sets 'match' to point to the matching entry. bool FindBy(std::vector<UnixEntry> entries, UnixEntry* match, - std::function<bool(UnixEntry)> predicate) { + std::function<bool(const UnixEntry&)> predicate) { for (int i = 0; i < entries.size(); ++i) { if (predicate(entries[i])) { *match = entries[i]; @@ -174,7 +175,8 @@ bool FindBy(std::vector<UnixEntry> entries, UnixEntry* match, bool FindByPath(std::vector<UnixEntry> entries, UnixEntry* match, const std::string& path) { - return FindBy(entries, match, [path](UnixEntry e) { return e.path == path; }); + return FindBy(entries, match, + [path](const UnixEntry& e) { return e.path == path; }); } TEST(ProcNetUnix, Exists) { diff --git a/test/syscalls/linux/pty.cc b/test/syscalls/linux/pty.cc index f926ac0f9..d1ab4703f 100644 --- a/test/syscalls/linux/pty.cc +++ b/test/syscalls/linux/pty.cc @@ -105,7 +105,7 @@ struct Field { uint64_t value; }; -// ParseFields returns a std::string representation of value, using the names in +// ParseFields returns a string representation of value, using the names in // fields. std::string ParseFields(const Field* fields, size_t len, uint64_t value) { bool first = true; diff --git a/test/syscalls/linux/raw_socket_icmp.cc b/test/syscalls/linux/raw_socket_icmp.cc index 24d9dc79a..7fe7c03a5 100644 --- a/test/syscalls/linux/raw_socket_icmp.cc +++ b/test/syscalls/linux/raw_socket_icmp.cc @@ -234,7 +234,7 @@ TEST_F(RawSocketICMPTest, MultipleSocketReceive) { } // A raw ICMP socket and ping socket should both receive the ICMP packets -// indended for the ping socket. +// intended for the ping socket. TEST_F(RawSocketICMPTest, RawAndPingSockets) { SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW))); diff --git a/test/syscalls/linux/readv_common.h b/test/syscalls/linux/readv_common.h index b16179fca..2fa40c35f 100644 --- a/test/syscalls/linux/readv_common.h +++ b/test/syscalls/linux/readv_common.h @@ -20,7 +20,7 @@ namespace gvisor { namespace testing { -// A NUL-terminated std::string containing the data used by tests using the following +// A NUL-terminated string containing the data used by tests using the following // test helpers. extern const char kReadvTestData[]; diff --git a/test/syscalls/linux/sendfile.cc b/test/syscalls/linux/sendfile.cc index 2fbb3f4ef..e5d72e28a 100644 --- a/test/syscalls/linux/sendfile.cc +++ b/test/syscalls/linux/sendfile.cc @@ -135,7 +135,7 @@ TEST(SendFileTest, SendTriviallyWithBothFilesReadWrite) { TEST(SendFileTest, SendAndUpdateFileOffset) { // Create temp files. - // Test input std::string length must be > 2 AND even. + // Test input string length must be > 2 AND even. constexpr char kData[] = "The slings and arrows of outrageous fortune,"; constexpr int kDataSize = sizeof(kData) - 1; constexpr int kHalfDataSize = kDataSize / 2; @@ -180,7 +180,7 @@ TEST(SendFileTest, SendAndUpdateFileOffset) { TEST(SendFileTest, SendAndUpdateFileOffsetFromNonzeroStartingPoint) { // Create temp files. - // Test input std::string length must be > 2 AND divisible by 4. + // Test input string length must be > 2 AND divisible by 4. constexpr char kData[] = "The slings and arrows of outrageous fortune,"; constexpr int kDataSize = sizeof(kData) - 1; constexpr int kHalfDataSize = kDataSize / 2; @@ -233,7 +233,7 @@ TEST(SendFileTest, SendAndUpdateFileOffsetFromNonzeroStartingPoint) { TEST(SendFileTest, SendAndUpdateGivenOffset) { // Create temp files. - // Test input std::string length must be >= 4 AND divisible by 4. + // Test input string length must be >= 4 AND divisible by 4. constexpr char kData[] = "Or to take Arms against a Sea of troubles,"; constexpr int kDataSize = sizeof(kData) + 1; constexpr int kHalfDataSize = kDataSize / 2; diff --git a/test/syscalls/linux/socket_netlink_route.cc b/test/syscalls/linux/socket_netlink_route.cc index 53dd1ca78..b5c38f27e 100644 --- a/test/syscalls/linux/socket_netlink_route.cc +++ b/test/syscalls/linux/socket_netlink_route.cc @@ -151,8 +151,8 @@ TEST(NetlinkRouteTest, GetPeerName) { // the value is considered ok. // 2: A description of what the sockopt value is expected to be. Should complete // the sentence "<value> was unexpected, expected <description>" -using SockOptTest = - ::testing::TestWithParam<std::tuple<int, std::function<bool(int)>, std::string>>; +using SockOptTest = ::testing::TestWithParam< + std::tuple<int, std::function<bool(int)>, std::string>>; TEST_P(SockOptTest, GetSockOpt) { int sockopt = std::get<0>(GetParam()); diff --git a/test/syscalls/linux/socket_unix_cmsg.cc b/test/syscalls/linux/socket_unix_cmsg.cc index b0ab26847..1092e29b1 100644 --- a/test/syscalls/linux/socket_unix_cmsg.cc +++ b/test/syscalls/linux/socket_unix_cmsg.cc @@ -220,7 +220,7 @@ TEST_P(UnixSocketPairCmsgTest, BasicFDPassNoSpaceMsgCtrunc) { // BasicFDPassNullControlMsgCtrunc sends an FD and sets contradictory values for // msg_controllen and msg_control. msg_controllen is set to the correct size to -// accomidate the FD, but msg_control is set to NULL. In this case, msg_control +// accommodate the FD, but msg_control is set to NULL. In this case, msg_control // should override msg_controllen. TEST_P(UnixSocketPairCmsgTest, BasicFDPassNullControlMsgCtrunc) { // FIXME(gvisor.dev/issue/207): Fix handling of NULL msg_control. @@ -531,7 +531,7 @@ TEST_P(UnixSocketPairCmsgTest, FDPassInterspersed1) { } // FDPassInterspersed2 checks that sent control messages cannot be read after -// their assocated data has been read while ignoring the control message by +// their associated data has been read while ignoring the control message by // using read(2) instead of recvmsg(2). TEST_P(UnixSocketPairCmsgTest, FDPassInterspersed2) { auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair()); diff --git a/test/syscalls/linux/socket_unix_unbound_stream.cc b/test/syscalls/linux/socket_unix_unbound_stream.cc index 091d546b3..e483d2777 100644 --- a/test/syscalls/linux/socket_unix_unbound_stream.cc +++ b/test/syscalls/linux/socket_unix_unbound_stream.cc @@ -29,7 +29,7 @@ namespace { using UnixStreamSocketPairTest = SocketPairTest; // FDPassPartialRead checks that sent control messages cannot be read after -// any of their assocated data has been read while ignoring the control message +// any of their associated data has been read while ignoring the control message // by using read(2) instead of recvmsg(2). TEST_P(UnixStreamSocketPairTest, FDPassPartialRead) { auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair()); diff --git a/test/syscalls/linux/stat.cc b/test/syscalls/linux/stat.cc index 80ba67496..510f7bee5 100644 --- a/test/syscalls/linux/stat.cc +++ b/test/syscalls/linux/stat.cc @@ -16,7 +16,9 @@ #include <fcntl.h> #include <sys/stat.h> #include <sys/statfs.h> +#include <sys/types.h> #include <unistd.h> + #include <string> #include <vector> @@ -554,6 +556,103 @@ TEST(SimpleStatTest, AnonDeviceAllocatesUniqueInodesAcrossSaveRestore) { EXPECT_EQ(st2_after.st_ino, st2.st_ino); } +#ifndef SYS_statx +#if defined(__x86_64__) +#define SYS_statx 332 +#else +#error "Unknown architecture" +#endif +#endif // SYS_statx + +#ifndef STATX_ALL +#define STATX_ALL 0x00000fffU +#endif // STATX_ALL + +// struct kernel_statx_timestamp is a Linux statx_timestamp struct. +struct kernel_statx_timestamp { + int64_t tv_sec; + uint32_t tv_nsec; + int32_t __reserved; +}; + +// struct kernel_statx is a Linux statx struct. Old versions of glibc do not +// expose it. See include/uapi/linux/stat.h +struct kernel_statx { + uint32_t stx_mask; + uint32_t stx_blksize; + uint64_t stx_attributes; + uint32_t stx_nlink; + uint32_t stx_uid; + uint32_t stx_gid; + uint16_t stx_mode; + uint16_t __spare0[1]; + uint64_t stx_ino; + uint64_t stx_size; + uint64_t stx_blocks; + uint64_t stx_attributes_mask; + struct kernel_statx_timestamp stx_atime; + struct kernel_statx_timestamp stx_btime; + struct kernel_statx_timestamp stx_ctime; + struct kernel_statx_timestamp stx_mtime; + uint32_t stx_rdev_major; + uint32_t stx_rdev_minor; + uint32_t stx_dev_major; + uint32_t stx_dev_minor; + uint64_t __spare2[14]; +}; + +int statx(int dirfd, const char *pathname, int flags, unsigned int mask, + struct kernel_statx *statxbuf) { + return syscall(SYS_statx, dirfd, pathname, flags, mask, statxbuf); +} + +TEST_F(StatTest, StatxAbsPath) { + SKIP_IF(!IsRunningOnGvisor() && statx(-1, nullptr, 0, 0, 0) < 0 && + errno == ENOSYS); + + struct kernel_statx stx; + EXPECT_THAT(statx(-1, test_file_name_.c_str(), 0, STATX_ALL, &stx), + SyscallSucceeds()); + EXPECT_TRUE(S_ISREG(stx.stx_mode)); +} + +TEST_F(StatTest, StatxRelPathDirFD) { + SKIP_IF(!IsRunningOnGvisor() && statx(-1, nullptr, 0, 0, 0) < 0 && + errno == ENOSYS); + + struct kernel_statx stx; + auto const dirfd = + ASSERT_NO_ERRNO_AND_VALUE(Open(GetAbsoluteTestTmpdir(), O_RDONLY)); + auto filename = std::string(Basename(test_file_name_)); + + EXPECT_THAT(statx(dirfd.get(), filename.c_str(), 0, STATX_ALL, &stx), + SyscallSucceeds()); + EXPECT_TRUE(S_ISREG(stx.stx_mode)); +} + +TEST_F(StatTest, StatxRelPathCwd) { + SKIP_IF(!IsRunningOnGvisor() && statx(-1, nullptr, 0, 0, 0) < 0 && + errno == ENOSYS); + + ASSERT_THAT(chdir(GetAbsoluteTestTmpdir().c_str()), SyscallSucceeds()); + auto filename = std::string(Basename(test_file_name_)); + struct kernel_statx stx; + EXPECT_THAT(statx(AT_FDCWD, filename.c_str(), 0, STATX_ALL, &stx), + SyscallSucceeds()); + EXPECT_TRUE(S_ISREG(stx.stx_mode)); +} + +TEST_F(StatTest, StatxEmptyPath) { + SKIP_IF(!IsRunningOnGvisor() && statx(-1, nullptr, 0, 0, 0) < 0 && + errno == ENOSYS); + + const auto fd = ASSERT_NO_ERRNO_AND_VALUE(Open(test_file_name_, O_RDONLY)); + struct kernel_statx stx; + EXPECT_THAT(statx(fd.get(), "", AT_EMPTY_PATH, STATX_ALL, &stx), + SyscallSucceeds()); + EXPECT_TRUE(S_ISREG(stx.stx_mode)); +} + } // namespace } // namespace testing diff --git a/test/syscalls/linux/symlink.cc b/test/syscalls/linux/symlink.cc index 494072a9b..b249ff91f 100644 --- a/test/syscalls/linux/symlink.cc +++ b/test/syscalls/linux/symlink.cc @@ -272,6 +272,105 @@ TEST(SymlinkTest, ChmodSymlink) { EXPECT_EQ(FilePermission(newpath), 0777); } +class ParamSymlinkTest : public ::testing::TestWithParam<std::string> {}; + +// Test that creating an existing symlink with creat will create the target. +TEST_P(ParamSymlinkTest, CreatLinkCreatesTarget) { + const std::string target = GetParam(); + const std::string linkpath = NewTempAbsPath(); + + ASSERT_THAT(symlink(target.c_str(), linkpath.c_str()), SyscallSucceeds()); + + int fd; + EXPECT_THAT(fd = creat(linkpath.c_str(), 0666), SyscallSucceeds()); + ASSERT_THAT(close(fd), SyscallSucceeds()); + + ASSERT_THAT(chdir(GetAbsoluteTestTmpdir().c_str()), SyscallSucceeds()); + struct stat st; + EXPECT_THAT(stat(target.c_str(), &st), SyscallSucceeds()); + + ASSERT_THAT(unlink(linkpath.c_str()), SyscallSucceeds()); + ASSERT_THAT(unlink(target.c_str()), SyscallSucceeds()); +} + +// Test that opening an existing symlink with O_CREAT will create the target. +TEST_P(ParamSymlinkTest, OpenLinkCreatesTarget) { + const std::string target = GetParam(); + const std::string linkpath = NewTempAbsPath(); + + ASSERT_THAT(symlink(target.c_str(), linkpath.c_str()), SyscallSucceeds()); + + int fd; + EXPECT_THAT(fd = open(linkpath.c_str(), O_CREAT, 0666), SyscallSucceeds()); + ASSERT_THAT(close(fd), SyscallSucceeds()); + + ASSERT_THAT(chdir(GetAbsoluteTestTmpdir().c_str()), SyscallSucceeds()); + struct stat st; + EXPECT_THAT(stat(target.c_str(), &st), SyscallSucceeds()); + + ASSERT_THAT(unlink(linkpath.c_str()), SyscallSucceeds()); + ASSERT_THAT(unlink(target.c_str()), SyscallSucceeds()); +} + +// Test that opening a self-symlink with O_CREAT will fail with ELOOP. +TEST_P(ParamSymlinkTest, CreateExistingSelfLink) { + ASSERT_THAT(chdir(GetAbsoluteTestTmpdir().c_str()), SyscallSucceeds()); + + const std::string linkpath = GetParam(); + ASSERT_THAT(symlink(linkpath.c_str(), linkpath.c_str()), SyscallSucceeds()); + + EXPECT_THAT(open(linkpath.c_str(), O_CREAT, 0666), + SyscallFailsWithErrno(ELOOP)); + + ASSERT_THAT(unlink(linkpath.c_str()), SyscallSucceeds()); +} + +// Test that opening a file that is a symlink to its parent directory fails +// with ELOOP. +TEST_P(ParamSymlinkTest, CreateExistingParentLink) { + ASSERT_THAT(chdir(GetAbsoluteTestTmpdir().c_str()), SyscallSucceeds()); + + const std::string linkpath = GetParam(); + const std::string target = JoinPath(linkpath, "child"); + ASSERT_THAT(symlink(target.c_str(), linkpath.c_str()), SyscallSucceeds()); + + EXPECT_THAT(open(linkpath.c_str(), O_CREAT, 0666), + SyscallFailsWithErrno(ELOOP)); + + ASSERT_THAT(unlink(linkpath.c_str()), SyscallSucceeds()); +} + +// Test that opening an existing symlink with O_CREAT|O_EXCL will fail with +// EEXIST. +TEST_P(ParamSymlinkTest, OpenLinkExclFails) { + const std::string target = GetParam(); + const std::string linkpath = NewTempAbsPath(); + + ASSERT_THAT(symlink(target.c_str(), linkpath.c_str()), SyscallSucceeds()); + + EXPECT_THAT(open(linkpath.c_str(), O_CREAT | O_EXCL, 0666), + SyscallFailsWithErrno(EEXIST)); + + ASSERT_THAT(unlink(linkpath.c_str()), SyscallSucceeds()); +} + +// Test that opening an existing symlink with O_CREAT|O_NOFOLLOW will fail with +// ELOOP. +TEST_P(ParamSymlinkTest, OpenLinkNoFollowFails) { + const std::string target = GetParam(); + const std::string linkpath = NewTempAbsPath(); + + ASSERT_THAT(symlink(target.c_str(), linkpath.c_str()), SyscallSucceeds()); + + EXPECT_THAT(open(linkpath.c_str(), O_CREAT | O_NOFOLLOW, 0666), + SyscallFailsWithErrno(ELOOP)); + + ASSERT_THAT(unlink(linkpath.c_str()), SyscallSucceeds()); +} + +INSTANTIATE_TEST_SUITE_P(AbsAndRelTarget, ParamSymlinkTest, + ::testing::Values(NewTempAbsPath(), NewTempRelPath())); + } // namespace } // namespace testing diff --git a/test/syscalls/linux/tcp_socket.cc b/test/syscalls/linux/tcp_socket.cc index 5efeb96c8..4597e91e3 100644 --- a/test/syscalls/linux/tcp_socket.cc +++ b/test/syscalls/linux/tcp_socket.cc @@ -265,10 +265,16 @@ TEST_P(TcpSocketTest, BlockingLargeWrite_NoRandomSave) { ScopedThread t([this, &read_bytes]() { // Avoid interrupting the blocking write in main thread. const DisableSave ds; + + // Take ownership of the FD so that we close it on failure. This will + // unblock the blocking write below. + FileDescriptor fd(t_); + t_ = -1; + char readbuf[2500] = {}; int n = -1; while (n != 0) { - ASSERT_THAT(n = RetryEINTR(read)(t_, &readbuf, sizeof(readbuf)), + ASSERT_THAT(n = RetryEINTR(read)(fd.get(), &readbuf, sizeof(readbuf)), SyscallSucceeds()); read_bytes += n; } @@ -342,10 +348,16 @@ TEST_P(TcpSocketTest, BlockingLargeSend_NoRandomSave) { ScopedThread t([this, &read_bytes]() { // Avoid interrupting the blocking write in main thread. const DisableSave ds; + + // Take ownership of the FD so that we close it on failure. This will + // unblock the blocking write below. + FileDescriptor fd(t_); + t_ = -1; + char readbuf[2500] = {}; int n = -1; while (n != 0) { - ASSERT_THAT(n = RetryEINTR(read)(t_, &readbuf, sizeof(readbuf)), + ASSERT_THAT(n = RetryEINTR(read)(fd.get(), &readbuf, sizeof(readbuf)), SyscallSucceeds()); read_bytes += n; } diff --git a/test/syscalls/linux/udp_socket.cc b/test/syscalls/linux/udp_socket.cc index 31db8a2ad..1bb0307c4 100644 --- a/test/syscalls/linux/udp_socket.cc +++ b/test/syscalls/linux/udp_socket.cc @@ -12,6 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +#include <arpa/inet.h> #include <fcntl.h> #include <linux/errqueue.h> #include <netinet/in.h> @@ -304,12 +305,50 @@ TEST_P(UdpSocketTest, ReceiveAfterConnect) { SyscallSucceedsWithValue(sizeof(buf))); // Receive the data. - char received[512]; + char received[sizeof(buf)]; EXPECT_THAT(recv(s_, received, sizeof(received), 0), SyscallSucceedsWithValue(sizeof(received))); EXPECT_EQ(memcmp(buf, received, sizeof(buf)), 0); } +TEST_P(UdpSocketTest, ReceiveAfterDisconnect) { + // Connect s_ to loopback:TestPort, and bind t_ to loopback:TestPort. + ASSERT_THAT(connect(s_, addr_[0], addrlen_), SyscallSucceeds()); + ASSERT_THAT(bind(t_, addr_[0], addrlen_), SyscallSucceeds()); + ASSERT_THAT(connect(t_, addr_[1], addrlen_), SyscallSucceeds()); + + // Get the address s_ was bound to during connect. + struct sockaddr_storage addr; + socklen_t addrlen = sizeof(addr); + EXPECT_THAT(getsockname(s_, reinterpret_cast<sockaddr*>(&addr), &addrlen), + SyscallSucceeds()); + EXPECT_EQ(addrlen, addrlen_); + + for (int i = 0; i < 2; i++) { + // Send from t_ to s_. + char buf[512]; + RandomizeBuffer(buf, sizeof(buf)); + EXPECT_THAT(getsockname(s_, reinterpret_cast<sockaddr*>(&addr), &addrlen), + SyscallSucceeds()); + ASSERT_THAT(sendto(t_, buf, sizeof(buf), 0, + reinterpret_cast<sockaddr*>(&addr), addrlen), + SyscallSucceedsWithValue(sizeof(buf))); + + // Receive the data. + char received[sizeof(buf)]; + EXPECT_THAT(recv(s_, received, sizeof(received), 0), + SyscallSucceedsWithValue(sizeof(received))); + EXPECT_EQ(memcmp(buf, received, sizeof(buf)), 0); + + // Disconnect s_. + struct sockaddr addr = {}; + addr.sa_family = AF_UNSPEC; + ASSERT_THAT(connect(s_, &addr, sizeof(addr.sa_family)), SyscallSucceeds()); + // Connect s_ loopback:TestPort. + ASSERT_THAT(connect(s_, addr_[0], addrlen_), SyscallSucceeds()); + } +} + TEST_P(UdpSocketTest, Connect) { ASSERT_THAT(connect(s_, addr_[0], addrlen_), SyscallSucceeds()); @@ -335,6 +374,112 @@ TEST_P(UdpSocketTest, Connect) { EXPECT_EQ(memcmp(&peer, addr_[2], addrlen_), 0); } +TEST_P(UdpSocketTest, DisconnectAfterBind) { + ASSERT_THAT(bind(s_, addr_[1], addrlen_), SyscallSucceeds()); + // Connect the socket. + ASSERT_THAT(connect(s_, addr_[0], addrlen_), SyscallSucceeds()); + + struct sockaddr_storage addr = {}; + addr.ss_family = AF_UNSPEC; + EXPECT_THAT( + connect(s_, reinterpret_cast<sockaddr*>(&addr), sizeof(addr.ss_family)), + SyscallSucceeds()); + + // Check that we're still bound. + socklen_t addrlen = sizeof(addr); + EXPECT_THAT(getsockname(s_, reinterpret_cast<sockaddr*>(&addr), &addrlen), + SyscallSucceeds()); + + EXPECT_EQ(addrlen, addrlen_); + EXPECT_EQ(memcmp(&addr, addr_[1], addrlen_), 0); + + addrlen = sizeof(addr); + EXPECT_THAT(getpeername(s_, reinterpret_cast<sockaddr*>(&addr), &addrlen), + SyscallFailsWithErrno(ENOTCONN)); +} + +TEST_P(UdpSocketTest, DisconnectAfterBindToAny) { + struct sockaddr_storage baddr = {}; + socklen_t addrlen; + auto port = *Port(reinterpret_cast<struct sockaddr_storage*>(addr_[1])); + if (addr_[0]->sa_family == AF_INET) { + auto addr_in = reinterpret_cast<struct sockaddr_in*>(&baddr); + addr_in->sin_family = AF_INET; + addr_in->sin_port = port; + inet_pton(AF_INET, "0.0.0.0", + reinterpret_cast<void*>(&addr_in->sin_addr.s_addr)); + } else { + auto addr_in = reinterpret_cast<struct sockaddr_in6*>(&baddr); + addr_in->sin6_family = AF_INET6; + addr_in->sin6_port = port; + inet_pton(AF_INET6, + "::", reinterpret_cast<void*>(&addr_in->sin6_addr.s6_addr)); + addr_in->sin6_scope_id = 0; + } + ASSERT_THAT(bind(s_, reinterpret_cast<sockaddr*>(&baddr), addrlen_), + SyscallSucceeds()); + // Connect the socket. + ASSERT_THAT(connect(s_, addr_[0], addrlen_), SyscallSucceeds()); + + struct sockaddr_storage addr = {}; + addr.ss_family = AF_UNSPEC; + EXPECT_THAT( + connect(s_, reinterpret_cast<sockaddr*>(&addr), sizeof(addr.ss_family)), + SyscallSucceeds()); + + // Check that we're still bound. + addrlen = sizeof(addr); + EXPECT_THAT(getsockname(s_, reinterpret_cast<sockaddr*>(&addr), &addrlen), + SyscallSucceeds()); + + EXPECT_EQ(addrlen, addrlen_); + EXPECT_EQ(memcmp(&addr, &baddr, addrlen), 0); + + addrlen = sizeof(addr); + EXPECT_THAT(getpeername(s_, reinterpret_cast<sockaddr*>(&addr), &addrlen), + SyscallFailsWithErrno(ENOTCONN)); +} + +TEST_P(UdpSocketTest, Disconnect) { + for (int i = 0; i < 2; i++) { + // Try to connect again. + EXPECT_THAT(connect(s_, addr_[2], addrlen_), SyscallSucceeds()); + + // Check that we're connected to the right peer. + struct sockaddr_storage peer; + socklen_t peerlen = sizeof(peer); + EXPECT_THAT(getpeername(s_, reinterpret_cast<sockaddr*>(&peer), &peerlen), + SyscallSucceeds()); + EXPECT_EQ(peerlen, addrlen_); + EXPECT_EQ(memcmp(&peer, addr_[2], addrlen_), 0); + + // Try to disconnect. + struct sockaddr_storage addr = {}; + addr.ss_family = AF_UNSPEC; + EXPECT_THAT( + connect(s_, reinterpret_cast<sockaddr*>(&addr), sizeof(addr.ss_family)), + SyscallSucceeds()); + + peerlen = sizeof(peer); + EXPECT_THAT(getpeername(s_, reinterpret_cast<sockaddr*>(&peer), &peerlen), + SyscallFailsWithErrno(ENOTCONN)); + + // Check that we're still bound. + socklen_t addrlen = sizeof(addr); + EXPECT_THAT(getsockname(s_, reinterpret_cast<sockaddr*>(&addr), &addrlen), + SyscallSucceeds()); + EXPECT_EQ(addrlen, addrlen_); + EXPECT_EQ(*Port(&addr), 0); + } +} + +TEST_P(UdpSocketTest, ConnectBadAddress) { + struct sockaddr addr = {}; + addr.sa_family = addr_[0]->sa_family; + ASSERT_THAT(connect(s_, &addr, sizeof(addr.sa_family)), + SyscallFailsWithErrno(EINVAL)); +} + TEST_P(UdpSocketTest, SendToAddressOtherThanConnected) { ASSERT_THAT(connect(s_, addr_[0], addrlen_), SyscallSucceeds()); @@ -397,7 +542,7 @@ TEST_P(UdpSocketTest, SendAndReceiveNotConnected) { SyscallSucceedsWithValue(sizeof(buf))); // Receive the data. - char received[512]; + char received[sizeof(buf)]; EXPECT_THAT(recv(s_, received, sizeof(received), 0), SyscallSucceedsWithValue(sizeof(received))); EXPECT_EQ(memcmp(buf, received, sizeof(buf)), 0); @@ -419,7 +564,7 @@ TEST_P(UdpSocketTest, SendAndReceiveConnected) { SyscallSucceedsWithValue(sizeof(buf))); // Receive the data. - char received[512]; + char received[sizeof(buf)]; EXPECT_THAT(recv(s_, received, sizeof(received), 0), SyscallSucceedsWithValue(sizeof(received))); EXPECT_EQ(memcmp(buf, received, sizeof(buf)), 0); @@ -462,7 +607,7 @@ TEST_P(UdpSocketTest, ReceiveBeforeConnect) { ASSERT_THAT(connect(s_, addr_[1], addrlen_), SyscallSucceeds()); // Receive the data. It works because it was sent before the connect. - char received[512]; + char received[sizeof(buf)]; EXPECT_THAT(recv(s_, received, sizeof(received), 0), SyscallSucceedsWithValue(sizeof(received))); EXPECT_EQ(memcmp(buf, received, sizeof(buf)), 0); @@ -491,7 +636,7 @@ TEST_P(UdpSocketTest, ReceiveFrom) { SyscallSucceedsWithValue(sizeof(buf))); // Receive the data and sender address. - char received[512]; + char received[sizeof(buf)]; struct sockaddr_storage addr; socklen_t addrlen = sizeof(addr); EXPECT_THAT(recvfrom(s_, received, sizeof(received), 0, diff --git a/test/syscalls/linux/unix_domain_socket_test_util.cc b/test/syscalls/linux/unix_domain_socket_test_util.cc index ff28850b2..7fb9eed8d 100644 --- a/test/syscalls/linux/unix_domain_socket_test_util.cc +++ b/test/syscalls/linux/unix_domain_socket_test_util.cc @@ -53,7 +53,7 @@ SocketPairKind UnixDomainSocketPair(int type) { SocketPairKind FilesystemBoundUnixDomainSocketPair(int type) { std::string description = absl::StrCat(DescribeUnixDomainSocketType(type), - " created with filesystem binding"); + " created with filesystem binding"); if ((type & SOCK_DGRAM) == SOCK_DGRAM) { return SocketPairKind{ description, AF_UNIX, type, 0, @@ -65,8 +65,9 @@ SocketPairKind FilesystemBoundUnixDomainSocketPair(int type) { } SocketPairKind AbstractBoundUnixDomainSocketPair(int type) { - std::string description = absl::StrCat(DescribeUnixDomainSocketType(type), - " created with abstract namespace binding"); + std::string description = + absl::StrCat(DescribeUnixDomainSocketType(type), + " created with abstract namespace binding"); if ((type & SOCK_DGRAM) == SOCK_DGRAM) { return SocketPairKind{ description, AF_UNIX, type, 0, @@ -78,7 +79,7 @@ SocketPairKind AbstractBoundUnixDomainSocketPair(int type) { SocketPairKind SocketpairGoferUnixDomainSocketPair(int type) { std::string description = absl::StrCat(DescribeUnixDomainSocketType(type), - " created with the socketpair gofer"); + " created with the socketpair gofer"); return SocketPairKind{description, AF_UNIX, type, 0, SocketpairGoferSocketPairCreator(AF_UNIX, type, 0)}; } diff --git a/test/syscalls/linux/unix_domain_socket_test_util.h b/test/syscalls/linux/unix_domain_socket_test_util.h index aae990245..5eca0b7f0 100644 --- a/test/syscalls/linux/unix_domain_socket_test_util.h +++ b/test/syscalls/linux/unix_domain_socket_test_util.h @@ -21,7 +21,7 @@ namespace gvisor { namespace testing { -// DescribeUnixDomainSocketType returns a human-readable std::string explaining the +// DescribeUnixDomainSocketType returns a human-readable string explaining the // given Unix domain socket type. std::string DescribeUnixDomainSocketType(int type); @@ -40,7 +40,7 @@ SocketPairKind FilesystemBoundUnixDomainSocketPair(int type); SocketPairKind AbstractBoundUnixDomainSocketPair(int type); // SocketpairGoferUnixDomainSocketPair returns a SocketPairKind that was created -// with two sockets conected to the socketpair gofer. +// with two sockets connected to the socketpair gofer. SocketPairKind SocketpairGoferUnixDomainSocketPair(int type); // SocketpairGoferFileSocketPair returns a SocketPairKind that was created with |