From 605c4cda2f5c274f0b9fc874d254d62944a93a37 Mon Sep 17 00:00:00 2001 From: Kyle Evans Date: Mon, 13 Apr 2020 17:55:31 +0000 Subject: [PATCH] close_range/closefrom: fix regression from close_range introduction close_range will clamp the range between [0, fdp->fd_lastfile], but failed to take into account that fdp->fd_lastfile can become -1 if all fds are closed. =-( In this scenario, just return because there's nothing further we can do at the moment. Add a test case for this, fork() and simply closefrom(0) twice in the child; on the second invocation, fdp->fd_lastfile == -1 and will trigger a panic before this change. X-MFC-With: r359836 --- sys/kern/kern_descrip.c | 8 ++++++++ tests/sys/file/closefrom_test.c | 18 +++++++++++++++++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/sys/kern/kern_descrip.c b/sys/kern/kern_descrip.c index 580956c5a0e3..dce930b09fe6 100644 --- a/sys/kern/kern_descrip.c +++ b/sys/kern/kern_descrip.c @@ -1333,6 +1333,14 @@ kern_close_range(struct thread *td, u_int lowfd, u_int highfd) ret = EINVAL; goto out; } + + /* + * If fdp->fd_lastfile == -1, we're dealing with either a fresh file + * table or one in which every fd has been closed. Just return + * successful; there's nothing left to do. + */ + if (fdp->fd_lastfile == -1) + goto out; /* Clamped to [lowfd, fd_lastfile] */ highfd = MIN(highfd, fdp->fd_lastfile); for (fd = lowfd; fd <= highfd; fd++) { diff --git a/tests/sys/file/closefrom_test.c b/tests/sys/file/closefrom_test.c index 7ce93415519e..8516f7f2598c 100644 --- a/tests/sys/file/closefrom_test.c +++ b/tests/sys/file/closefrom_test.c @@ -146,7 +146,7 @@ main(void) pid_t pid; int fd, i, start; - printf("1..19\n"); + printf("1..20\n"); /* We better start up with fd's 0, 1, and 2 open. */ start = devnull(); @@ -309,5 +309,21 @@ main(void) fail("close_range", "highest fd %d", fd); ok("close_range"); + /* Fork a child process to test closefrom(0) twice. */ + pid = fork(); + if (pid < 0) + fail_err("fork"); + if (pid == 0) { + /* Child. */ + closefrom(0); + closefrom(0); + cok(info, "closefrom(0)"); + } + if (wait(NULL) < 0) + fail_err("wait"); + if (info->failed) + fail(info->tag, "%s", info->message); + ok(info->tag); + return (0); }