[LTP] [PATCH] syscalls/dup202: make sure fds are not equal to ofd

Thadeu Lima de Souza Cascardo cascardo@canonical.com
Fri Dec 17 15:21:30 CET 2021


If the test is executed by a process which has many open file descriptors,
creat may end up returning ofd == 10, which it will try to dup2 to, and,
then, SAFE_CLOSE will be run twice over fd=10, making it fail the second
time.

Test output would be like this:
dup202.c:90: TPASS: original(100444) and duped(100444) are the same mode
dup202.c:90: TPASS: original(100222) and duped(100222) are the same mode
dup202.c:90: TPASS: original(100666) and duped(100666) are the same mode
dup202.c:78: TINFO: original mode 0777, new mode 0444 after chmod
dup202.c:90: TPASS: original(100444) and duped(100444) are the same mode
dup202.c:94: TBROK: close(10) failed: EBADF (9)

It is easy to reproduce by simply exec'ing the test from a program that
has fds 0 to 10 opened.

Fix it by allocating enough file descriptors on the setup phase, and
assigning those new file descriptors to the fds that are going to be dup2
to.

Signed-off-by: Thadeu Lima de Souza Cascardo <cascardo@canonical.com>
Reported-by: Krzysztof Kozlowski <krzysztof.kozlowski@canonical.com>
---
 testcases/kernel/syscalls/dup2/dup202.c | 17 ++++++++++++++++-
 1 file changed, 16 insertions(+), 1 deletion(-)

diff --git a/testcases/kernel/syscalls/dup2/dup202.c b/testcases/kernel/syscalls/dup2/dup202.c
index 64c800d35a10..659f3a4ecdff 100644
--- a/testcases/kernel/syscalls/dup2/dup202.c
+++ b/testcases/kernel/syscalls/dup2/dup202.c
@@ -29,7 +29,7 @@ static char testfile[40];
 static int ofd = -1, nfd = -1;
 
 /* set these to a known index into our local file descriptor table */
-static int duprdo = 10, dupwro = 20, duprdwr = 30;
+static int duprdo, dupwro, duprdwr;
 
 static struct tcase {
 	int *nfd;
@@ -47,8 +47,23 @@ static struct tcase {
 
 static void setup(void)
 {
+	int nextfd;
+
 	umask(0);
 	sprintf(testfile, "dup202.%d", getpid());
+
+	/* Pick up fds that are known not to collide with creat */
+	nextfd = SAFE_CREAT(testfile, 0777);
+	duprdo = SAFE_DUP(nextfd);
+	dupwro = SAFE_DUP(nextfd);
+	duprdwr = SAFE_DUP(nextfd);
+	/* SAFE_CLOSE will set fd to -1 */
+	close(duprdwr);
+	close(dupwro);
+	close(duprdo);
+	SAFE_CLOSE(nextfd);
+	SAFE_UNLINK(testfile);
+
 }
 
 static void cleanup(void)
-- 
2.32.0



More information about the ltp mailing list