NixOS / nix

Nix, the purely functional package manager
https://nixos.org/
GNU Lesser General Public License v2.1
12.77k stars 1.52k forks source link

Weird file descriptors #5674

Closed jacereda closed 2 years ago

jacereda commented 2 years ago

File descriptors returned byopen aren't consecutive when entering nix develop.

$ nix develop nixpkgs#hello
$ cat >fds.c <<EOF
#include <fcntl.h>
#include <stdio.h>
int main() {
  for (int i = 0; i < 20; i++) printf("%d\n", open("/dev/null", O_RDWR));
  return 0;
}
EOF
$ gcc fds.c
$ ./a.out
3
4
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

I would expect the FDs to be consecutive. This results in a test failure in https://github.com/jart/cosmopolitan/blob/d6a039821f927cc81b71e11f21599ff93e1fed62/test/libc/calls/fcntl_test.c#L61

nix-env (Nix) 2.4

jacereda commented 2 years ago

Should this use AutoCloseFD?

https://github.com/NixOS/nix/blob/1f7584d24c9e50207d74de26be0771d8377ed695/src/libutil/util.cc#L424

nbraud commented 2 years ago

@jacereda FWIW, this isn't “weird”. Per open(2), and on Linux only:

The file descriptor returned by a successful call will be the lowest-numbered file descriptor not currently open for the process.

As you noticed, it's impossible for an application to ensure it's not started with extraneous fds open. That said, I agree that nix develop probably shouldn't leak internal file descriptors, and your proposed fix seems sensible.