@@ -60,6 +60,28 @@ pub unsafe fn init(argc: isize, argv: *const *const u8, sigpipe: u8) {
6060 }
6161
6262 unsafe fn sanitize_standard_fds ( ) {
63+ let mut opened_devnull = -1 ;
64+ let mut open_devnull = || {
65+ #[ cfg( not( all( target_os = "linux" , target_env = "gnu" ) ) ) ]
66+ use libc:: open as open64;
67+ #[ cfg( all( target_os = "linux" , target_env = "gnu" ) ) ]
68+ use libc:: open64;
69+
70+ if opened_devnull != -1 {
71+ if libc:: dup ( opened_devnull) != -1 {
72+ return ;
73+ }
74+ }
75+ opened_devnull = open64 ( c"/dev/null" . as_ptr ( ) , libc:: O_RDWR , 0 ) ;
76+ if opened_devnull == -1 {
77+ // If the stream is closed but we failed to reopen it, abort the
78+ // process. Otherwise we wouldn't preserve the safety of
79+ // operations on the corresponding Rust object Stdin, Stdout, or
80+ // Stderr.
81+ libc:: abort ( ) ;
82+ }
83+ } ;
84+
6385 // fast path with a single syscall for systems with poll()
6486 #[ cfg( not( any(
6587 miri,
@@ -75,11 +97,6 @@ pub unsafe fn init(argc: isize, argv: *const *const u8, sigpipe: u8) {
7597 target_vendor = "apple" ,
7698 ) ) ) ]
7799 ' poll: {
78- #[ cfg( not( all( target_os = "linux" , target_env = "gnu" ) ) ) ]
79- use libc:: open as open64;
80- #[ cfg( all( target_os = "linux" , target_env = "gnu" ) ) ]
81- use libc:: open64;
82-
83100 use crate :: sys:: os:: errno;
84101 let pfds: & mut [ _ ] = & mut [
85102 libc:: pollfd { fd : 0 , events : 0 , revents : 0 } ,
@@ -107,13 +124,7 @@ pub unsafe fn init(argc: isize, argv: *const *const u8, sigpipe: u8) {
107124 if pfd. revents & libc:: POLLNVAL == 0 {
108125 continue ;
109126 }
110- if open64 ( c"/dev/null" . as_ptr ( ) , libc:: O_RDWR , 0 ) == -1 {
111- // If the stream is closed but we failed to reopen it, abort the
112- // process. Otherwise we wouldn't preserve the safety of
113- // operations on the corresponding Rust object Stdin, Stdout, or
114- // Stderr.
115- libc:: abort ( ) ;
116- }
127+ open_devnull ( ) ;
117128 }
118129 return ;
119130 }
@@ -130,21 +141,10 @@ pub unsafe fn init(argc: isize, argv: *const *const u8, sigpipe: u8) {
130141 target_os = "vita" ,
131142 ) ) ) ]
132143 {
133- #[ cfg( not( all( target_os = "linux" , target_env = "gnu" ) ) ) ]
134- use libc:: open as open64;
135- #[ cfg( all( target_os = "linux" , target_env = "gnu" ) ) ]
136- use libc:: open64;
137-
138144 use crate :: sys:: os:: errno;
139145 for fd in 0 ..3 {
140146 if libc:: fcntl ( fd, libc:: F_GETFD ) == -1 && errno ( ) == libc:: EBADF {
141- if open64 ( c"/dev/null" . as_ptr ( ) , libc:: O_RDWR , 0 ) == -1 {
142- // If the stream is closed but we failed to reopen it, abort the
143- // process. Otherwise we wouldn't preserve the safety of
144- // operations on the corresponding Rust object Stdin, Stdout, or
145- // Stderr.
146- libc:: abort ( ) ;
147- }
147+ open_devnull ( ) ;
148148 }
149149 }
150150 }
0 commit comments