From 44a6715584a7bafe6b9b2601d1d44a238dce948c Mon Sep 17 00:00:00 2001 From: Andrew Kaster Date: Sun, 27 Jun 2021 21:16:21 -0600 Subject: [PATCH] Tests: TestProcFs cannot assume stdin/stdout/stderr are the same If someone runs the test with shell redirection going on, or in a way that changes any of the standard file descriptors this assumption will not hold. When running from a terminal normally, it is true however. Instead, check that /proc/self/fd/[0,1,2] are symlinks, and can be stat-d by verifying that both stat and lstat succeed, and give different struct stat contents. --- Tests/Kernel/TestProcFS.cpp | 42 ++++++++++++++++++++++++++----------- 1 file changed, 30 insertions(+), 12 deletions(-) diff --git a/Tests/Kernel/TestProcFS.cpp b/Tests/Kernel/TestProcFS.cpp index 105a8c8c75..8f219288c0 100644 --- a/Tests/Kernel/TestProcFS.cpp +++ b/Tests/Kernel/TestProcFS.cpp @@ -6,27 +6,45 @@ #include #include +#include #include TEST_CASE(test_process_fd_readlink) { - char expected_link[MAXPATHLEN]; - char buf[MAXPATHLEN]; + // Make sure that stdin, stdout and stderr are actually symlinks that point somewhere interesting + // Sadly we can't assume that they all point to the same file. + struct stat stat_buf = {}; + struct stat lstat_buf = {}; + auto rc = stat("/proc/self/fd/0", &stat_buf); + EXPECT_EQ(rc, 0); + rc = lstat("/proc/self/fd/0", &lstat_buf); + EXPECT_EQ(rc, 0); + EXPECT_NE(0, memcmp(&stat_buf, &lstat_buf, sizeof(struct stat))); - // Read the symlink value for stdin, stdout and stderr - auto link_length = readlink("/proc/self/fd/0", expected_link, sizeof(expected_link)); - expected_link[link_length] = '\0'; + stat_buf = {}; + lstat_buf = {}; + rc = stat("/proc/self/fd/1", &stat_buf); + EXPECT_EQ(rc, 0); + rc = lstat("/proc/self/fd/1", &lstat_buf); + EXPECT_EQ(rc, 0); + EXPECT_NE(0, memcmp(&stat_buf, &lstat_buf, sizeof(struct stat))); - link_length = readlink("/proc/self/fd/1", buf, sizeof(buf)); - buf[link_length] = '\0'; - EXPECT_EQ(0, strcmp(buf, expected_link)); - - link_length = readlink("/proc/self/fd/2", buf, sizeof(buf)); - buf[link_length] = '\0'; - EXPECT_EQ(0, strcmp(buf, expected_link)); + stat_buf = {}; + lstat_buf = {}; + rc = stat("/proc/self/fd/2", &stat_buf); + EXPECT_EQ(rc, 0); + rc = lstat("/proc/self/fd/2", &lstat_buf); + EXPECT_EQ(rc, 0); + EXPECT_NE(0, memcmp(&stat_buf, &lstat_buf, sizeof(struct stat))); // Create a new file descriptor that is a dup of 0 with various big values in order to reproduce issue #7820. // We should get the same link value for each fd that was duplicated. + char expected_link[MAXPATHLEN]; + char buf[MAXPATHLEN]; + + // Read the symlink for stdin, stdout and stderr + auto link_length = readlink("/proc/self/fd/0", expected_link, sizeof(expected_link)); + expected_link[link_length] = '\0'; // 255 is the first broken file descriptor that was discovered and might be used by other software (e.g. bash) auto new_fd = dup2(0, 255);