Skip to content

Commit b7cef2f

Browse files
committed
Rollup merge of rust-lang#48624 - bdrewery:freebsd-posix-spawn, r=alexcrichton
Command: Support posix_spawn() on FreeBSD/OSX/GNU Linux
2 parents de3a63d + d740083 commit b7cef2f

File tree

5 files changed

+178
-29
lines changed

5 files changed

+178
-29
lines changed

src/libstd/sys/unix/net.rs

Lines changed: 5 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -383,42 +383,19 @@ impl IntoInner<c_int> for Socket {
383383
// believe it's thread-safe).
384384
#[cfg(target_env = "gnu")]
385385
fn on_resolver_failure() {
386+
use sys;
387+
386388
// If the version fails to parse, we treat it the same as "not glibc".
387-
if let Some(Ok(version_str)) = glibc_version_cstr().map(CStr::to_str) {
388-
if let Some(version) = parse_glibc_version(version_str) {
389-
if version < (2, 26) {
390-
unsafe { libc::res_init() };
391-
}
389+
if let Some(version) = sys::os::glibc_version() {
390+
if version < (2, 26) {
391+
unsafe { libc::res_init() };
392392
}
393393
}
394394
}
395395

396396
#[cfg(not(target_env = "gnu"))]
397397
fn on_resolver_failure() {}
398398

399-
#[cfg(target_env = "gnu")]
400-
fn glibc_version_cstr() -> Option<&'static CStr> {
401-
weak! {
402-
fn gnu_get_libc_version() -> *const libc::c_char
403-
}
404-
if let Some(f) = gnu_get_libc_version.get() {
405-
unsafe { Some(CStr::from_ptr(f())) }
406-
} else {
407-
None
408-
}
409-
}
410-
411-
// Returns Some((major, minor)) if the string is a valid "x.y" version,
412-
// ignoring any extra dot-separated parts. Otherwise return None.
413-
#[cfg(target_env = "gnu")]
414-
fn parse_glibc_version(version: &str) -> Option<(usize, usize)> {
415-
let mut parsed_ints = version.split(".").map(str::parse::<usize>).fuse();
416-
match (parsed_ints.next(), parsed_ints.next()) {
417-
(Some(Ok(major)), Some(Ok(minor))) => Some((major, minor)),
418-
_ => None
419-
}
420-
}
421-
422399
#[cfg(all(test, taget_env = "gnu"))]
423400
mod test {
424401
use super::*;

src/libstd/sys/unix/os.rs

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -546,3 +546,35 @@ pub fn getpid() -> u32 {
546546
pub fn getppid() -> u32 {
547547
unsafe { libc::getppid() as u32 }
548548
}
549+
550+
#[cfg(target_env = "gnu")]
551+
pub fn glibc_version() -> Option<(usize, usize)> {
552+
if let Some(Ok(version_str)) = glibc_version_cstr().map(CStr::to_str) {
553+
parse_glibc_version(version_str)
554+
} else {
555+
None
556+
}
557+
}
558+
559+
#[cfg(target_env = "gnu")]
560+
fn glibc_version_cstr() -> Option<&'static CStr> {
561+
weak! {
562+
fn gnu_get_libc_version() -> *const libc::c_char
563+
}
564+
if let Some(f) = gnu_get_libc_version.get() {
565+
unsafe { Some(CStr::from_ptr(f())) }
566+
} else {
567+
None
568+
}
569+
}
570+
571+
// Returns Some((major, minor)) if the string is a valid "x.y" version,
572+
// ignoring any extra dot-separated parts. Otherwise return None.
573+
#[cfg(target_env = "gnu")]
574+
fn parse_glibc_version(version: &str) -> Option<(usize, usize)> {
575+
let mut parsed_ints = version.split(".").map(str::parse::<usize>).fuse();
576+
match (parsed_ints.next(), parsed_ints.next()) {
577+
(Some(Ok(major)), Some(Ok(minor))) => Some((major, minor)),
578+
_ => None
579+
}
580+
}

src/libstd/sys/unix/process/process_unix.rs

Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,11 @@ impl Command {
3434
}
3535

3636
let (ours, theirs) = self.setup_io(default, needs_stdin)?;
37+
38+
if let Some(ret) = self.posix_spawn(&theirs, envp.as_ref())? {
39+
return Ok((ret, ours))
40+
}
41+
3742
let (input, output) = sys::pipe::anon_pipe()?;
3843

3944
let pid = unsafe {
@@ -229,6 +234,118 @@ impl Command {
229234
libc::execvp(self.get_argv()[0], self.get_argv().as_ptr());
230235
io::Error::last_os_error()
231236
}
237+
238+
#[cfg(not(any(target_os = "macos", target_os = "freebsd",
239+
all(target_os = "linux", target_env = "gnu"))))]
240+
fn posix_spawn(&mut self, _: &ChildPipes, _: Option<&CStringArray>)
241+
-> io::Result<Option<Process>>
242+
{
243+
Ok(None)
244+
}
245+
246+
// Only support platforms for which posix_spawn() can return ENOENT
247+
// directly.
248+
#[cfg(any(target_os = "macos", target_os = "freebsd",
249+
all(target_os = "linux", target_env = "gnu")))]
250+
fn posix_spawn(&mut self, stdio: &ChildPipes, envp: Option<&CStringArray>)
251+
-> io::Result<Option<Process>>
252+
{
253+
use mem;
254+
use sys;
255+
256+
if self.get_cwd().is_some() ||
257+
self.get_gid().is_some() ||
258+
self.get_uid().is_some() ||
259+
self.get_closures().len() != 0 {
260+
return Ok(None)
261+
}
262+
263+
// Only glibc 2.24+ posix_spawn() supports returning ENOENT directly.
264+
#[cfg(all(target_os = "linux", target_env = "gnu"))]
265+
{
266+
if let Some(version) = sys::os::glibc_version() {
267+
if version < (2, 24) {
268+
return Ok(None)
269+
}
270+
} else {
271+
return Ok(None)
272+
}
273+
}
274+
275+
let mut p = Process { pid: 0, status: None };
276+
277+
struct PosixSpawnFileActions(libc::posix_spawn_file_actions_t);
278+
279+
impl Drop for PosixSpawnFileActions {
280+
fn drop(&mut self) {
281+
unsafe {
282+
libc::posix_spawn_file_actions_destroy(&mut self.0);
283+
}
284+
}
285+
}
286+
287+
struct PosixSpawnattr(libc::posix_spawnattr_t);
288+
289+
impl Drop for PosixSpawnattr {
290+
fn drop(&mut self) {
291+
unsafe {
292+
libc::posix_spawnattr_destroy(&mut self.0);
293+
}
294+
}
295+
}
296+
297+
unsafe {
298+
let mut file_actions = PosixSpawnFileActions(mem::uninitialized());
299+
let mut attrs = PosixSpawnattr(mem::uninitialized());
300+
301+
libc::posix_spawnattr_init(&mut attrs.0);
302+
libc::posix_spawn_file_actions_init(&mut file_actions.0);
303+
304+
if let Some(fd) = stdio.stdin.fd() {
305+
cvt(libc::posix_spawn_file_actions_adddup2(&mut file_actions.0,
306+
fd,
307+
libc::STDIN_FILENO))?;
308+
}
309+
if let Some(fd) = stdio.stdout.fd() {
310+
cvt(libc::posix_spawn_file_actions_adddup2(&mut file_actions.0,
311+
fd,
312+
libc::STDOUT_FILENO))?;
313+
}
314+
if let Some(fd) = stdio.stderr.fd() {
315+
cvt(libc::posix_spawn_file_actions_adddup2(&mut file_actions.0,
316+
fd,
317+
libc::STDERR_FILENO))?;
318+
}
319+
320+
let mut set: libc::sigset_t = mem::uninitialized();
321+
cvt(libc::sigemptyset(&mut set))?;
322+
cvt(libc::posix_spawnattr_setsigmask(&mut attrs.0,
323+
&set))?;
324+
cvt(libc::sigaddset(&mut set, libc::SIGPIPE))?;
325+
cvt(libc::posix_spawnattr_setsigdefault(&mut attrs.0,
326+
&set))?;
327+
328+
let flags = libc::POSIX_SPAWN_SETSIGDEF |
329+
libc::POSIX_SPAWN_SETSIGMASK;
330+
cvt(libc::posix_spawnattr_setflags(&mut attrs.0, flags as _))?;
331+
332+
let envp = envp.map(|c| c.as_ptr())
333+
.unwrap_or(*sys::os::environ() as *const _);
334+
let ret = libc::posix_spawnp(
335+
&mut p.pid,
336+
self.get_argv()[0],
337+
&file_actions.0,
338+
&attrs.0,
339+
self.get_argv().as_ptr() as *const _,
340+
envp as *const _,
341+
);
342+
if ret == 0 {
343+
Ok(Some(p))
344+
} else {
345+
Err(io::Error::from_raw_os_error(ret))
346+
}
347+
}
348+
}
232349
}
233350

234351
////////////////////////////////////////////////////////////////////////////////
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
2+
// file at the top-level directory of this distribution and at
3+
// http://rust-lang.org/COPYRIGHT.
4+
//
5+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8+
// option. This file may not be copied, modified, or distributed
9+
// except according to those terms.
10+
11+
// ignore-cloudabi no processes
12+
// ignore-emscripten no processes
13+
14+
use std::io::ErrorKind;
15+
use std::process::Command;
16+
17+
fn main() {
18+
assert_eq!(Command::new("nonexistent")
19+
.spawn()
20+
.unwrap_err()
21+
.kind(),
22+
ErrorKind::NotFound);
23+
}

0 commit comments

Comments
 (0)