Skip to content

Commit c3482af

Browse files
committed
Fix file descriptor assignment issues on Windows
1 parent b73673e commit c3482af

File tree

2 files changed

+46
-1
lines changed

2 files changed

+46
-1
lines changed

libc/intrin/reservefd.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ int __reservefd_unlocked(int start) {
7272
if (_cmpxchg(&g_fds.p[fd].kind, kFdEmpty, kFdReserved)) {
7373
// g_fds.f isn't guarded by our mutex
7474
do {
75-
f2 = MAX(fd + 1, f1);
75+
f2 = MIN(fd + 1, f1);
7676
} while (!atomic_compare_exchange_weak_explicit(
7777
&g_fds.f, &f1, f2, memory_order_release, memory_order_relaxed));
7878
return fd;

test/posix/lowest_fd_test.c

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
// Copyright 2024 Justine Alexandra Roberts Tunney
2+
//
3+
// Permission to use, copy, modify, and/or distribute this software for
4+
// any purpose with or without fee is hereby granted, provided that the
5+
// above copyright notice and this permission notice appear in all copies.
6+
//
7+
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
8+
// WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
9+
// WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
10+
// AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
11+
// DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
12+
// PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
13+
// TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
14+
// PERFORMANCE OF THIS SOFTWARE.
15+
16+
#include <fcntl.h>
17+
#include <unistd.h>
18+
19+
int main(int argc, char *argv[]) {
20+
21+
// ensure most file descriptors are closed
22+
for (int fildes = 3; fildes < 80; ++fildes)
23+
close(fildes);
24+
25+
// create new file descriptor
26+
if (open("/dev/urandom", O_RDONLY) != 3)
27+
return 2;
28+
29+
// copy file descriptor to higher number
30+
if (fcntl(3, F_DUPFD, 70) != 70)
31+
return 3;
32+
33+
// new file descriptor should go for lowest number
34+
int fd;
35+
if ((fd = open("/dev/urandom", O_RDONLY)) != 4)
36+
return 4;
37+
38+
// move file descriptor to higher number
39+
if (close(3))
40+
return 5;
41+
42+
// new file descriptor should go for lowest number
43+
if (open("/dev/urandom", O_RDONLY) != 3)
44+
return 6;
45+
}

0 commit comments

Comments
 (0)