Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions tests/by-util/test_env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1885,6 +1885,23 @@ fn test_simulation_of_terminal_pty_pipes_into_data_and_sends_eot_automatically()
std::assert_eq!(String::from_utf8_lossy(out.stderr()), "");
}

#[cfg(target_os = "linux")]
#[test]
fn test_simulation_of_terminal_not_inherited_by_other_commands() {
let scene = TestScenario::new("util");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sleep 1 would be enough, no?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.


let mut cmd = scene.ccmd("env");
cmd.args(&["sleep", "1"]);
cmd.terminal_simulation(true);
let mut child = cmd.run_no_wait();
scene
.ccmd("env")
.args(&["ls", "-l", "/proc/self/fd/"])
.succeeds()
.stdout_does_not_contain("/dev/ptmx");
child.kill();
}

#[test]
#[cfg(not(windows))]
fn test_emoji_env_vars() {
Expand Down
7 changes: 4 additions & 3 deletions tests/by-util/test_more.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,9 @@ fn run_more_with_pty(
fn quit_more(controller: &mut File, mut child: uutests::util::UChild) {
controller.write_all(b"q").unwrap();
child.delay(50);
// Not all options quit on `q` here, and a `more` left behind spins once
// its terminal hangs up.
child.kill();
}

#[cfg(unix)]
Expand Down Expand Up @@ -110,9 +113,7 @@ fn test_alive(args: &[&str]) {

assert!(child.is_alive(), "Command should still be alive");

// cleanup
controller.write_all(b"q").unwrap();
child.delay(50);
quit_more(&mut controller, child);
}

#[test]
Expand Down
2 changes: 1 addition & 1 deletion tests/uutests/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ uucore = { workspace = true, features = [

[target.'cfg(unix)'.dependencies]
nix = { workspace = true, features = ["fs", "term"] }
rustix = { workspace = true, features = ["process"] }
rustix = { workspace = true, features = ["process", "pty", "termios"] }

[target.'cfg(any(target_os = "freebsd", target_os = "hurd", target_os = "linux", target_os = "android", target_os = "netbsd"))'.dependencies]
xattr = { workspace = true }
Expand Down
72 changes: 66 additions & 6 deletions tests/uutests/src/lib/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.

//spell-checker:ignore (linux) rlimit prlimit coreutil ggroups uchild uncaptured scmd SHLVL canonicalized openpty
//spell-checker:ignore (linux) rlimit prlimit coreutil ggroups uchild uncaptured scmd SHLVL canonicalized openpty openpt grantpt unlockpt ptsname tcsetwinsize CLOEXEC RDWR SETFD
//spell-checker:ignore (linux) winsize xpixel ypixel setrlimit Fsize SIGBUS SIGSEGV SIGXFSZ EFBIG sigbus tmpfs mksocket
//spell-checker:ignore (ToDO) ttyname

Expand Down Expand Up @@ -2038,7 +2038,11 @@ impl UCommand {
let OpenptyResult {
slave: pi_slave,
master: pi_master,
} = nix::pty::openpty(&terminal_size, None).unwrap();
} = open_pty(Some(&terminal_size));
// Read the echo, as a terminal would. This also keeps the PTY
// open until the child closes it, so closing stdin doesn't hang it up.
let mut echo = File::from(pi_master.try_clone().unwrap());
thread::spawn(move || io::copy(&mut echo, &mut io::sink()));
stdin_pty = Some(File::from(pi_master));
command.stdin(pi_slave);
}
Expand All @@ -2047,7 +2051,7 @@ impl UCommand {
let OpenptyResult {
slave: po_slave,
master: po_master,
} = nix::pty::openpty(&terminal_size, None).unwrap();
} = open_pty(Some(&terminal_size));
captured_stdout = Self::spawn_reader_thread(
captured_stdout,
po_master,
Expand All @@ -2060,7 +2064,7 @@ impl UCommand {
let OpenptyResult {
slave: pe_slave,
master: pe_master,
} = nix::pty::openpty(&terminal_size, None).unwrap();
} = open_pty(Some(&terminal_size));
captured_stderr = Self::spawn_reader_thread(
captured_stderr,
pe_master,
Expand Down Expand Up @@ -3038,6 +3042,63 @@ pub fn whoami() -> String {
})
}

/// Open a PTY whose two ends are close-on-exec, so that commands started by
/// other tests in the meantime don't inherit them.
#[cfg(all(unix, not(target_os = "redox")))]
fn open_pty(size: Option<&libc::winsize>) -> OpenptyResult {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This fails to compile on NetBSD targets:

$ RUSTC_BOOTSTRAP=1 cargo clippy -q -Zbuild-std -p uutests --target i686-unknown-netbsd
error[E0432]: unresolved import `rustix::pty::ptsname`
    --> tests/uutests/src/lib/util.rs:3057:57
     |
3057 |         use rustix::pty::{OpenptFlags, grantpt, openpt, ptsname, unlockpt};
     |                                                         ^^^^^^^ no `ptsname` in `pty`
     |
note: found an item that was configured out
    --> ~/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/rustix-1.1.5/src/pty.rs:135:8
     |
 124 |       any(
     |  ________-
 125 | |         apple,
 126 | |         linux_like,
 127 | |         target_os = "freebsd",
 128 | |         target_os = "fuchsia",
 129 | |         target_os = "illumos"
 130 | |     )
     | |_____- the item is gated here
...
 135 |   pub fn ptsname<Fd: AsFd, B: Into<Vec<u8>>>(fd: Fd, reuse: B) -> io::Result<CString> {
     |          ^^^^^^^

For more information about this error, try `rustc --explain E0432`.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will address in #14252

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, I missed that rustix has no ptsname on NetBSD.

#[cfg(any(
target_os = "linux",
target_os = "android",
target_os = "freebsd",
target_os = "netbsd"
))]
{
use rustix::fs::{Mode, OFlags, open};
use rustix::pty::{OpenptFlags, grantpt, openpt, ptsname, unlockpt};
use rustix::termios::{Winsize, tcsetwinsize};

let master =
openpt(OpenptFlags::RDWR | OpenptFlags::NOCTTY | OpenptFlags::CLOEXEC).unwrap();
grantpt(&master).unwrap();
unlockpt(&master).unwrap();
let name = ptsname(&master, Vec::new()).unwrap();
let slave = open(
name,
OFlags::RDWR | OFlags::NOCTTY | OFlags::CLOEXEC,
Mode::empty(),
)
.unwrap();
if let Some(size) = size {
let size = Winsize {
ws_row: size.ws_row,
ws_col: size.ws_col,
ws_xpixel: size.ws_xpixel,
ws_ypixel: size.ws_ypixel,
};
tcsetwinsize(&slave, size).unwrap();
}
OpenptyResult { master, slave }
}

// Elsewhere a PTY can't be opened close-on-exec, so a command started
// between openpty and fcntl can still inherit it.
#[cfg(not(any(
target_os = "linux",
target_os = "android",
target_os = "freebsd",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same cfg list twice, could it be a single cfg_if! or an else branch?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's no cfg_if in the tree, and cfg_select! isn't available at our 1.88 MSRV. A cfg!() if/else would need both branches to compile everywhere, but OpenptFlags::CLOEXEC only exists on Linux, Android, FreeBSD and NetBSD. I can name the list once with a cfg_aliases build.rs in uutests, if you prefer.

target_os = "netbsd"
)))]
{
use nix::fcntl::{FcntlArg, FdFlag, fcntl};

let pty = nix::pty::openpty(size, None).unwrap();
for fd in [&pty.master, &pty.slave] {
fcntl(fd, FcntlArg::F_SETFD(FdFlag::FD_CLOEXEC)).unwrap();
}
pty
}
}

/// Create a PTY (pseudo-terminal) for testing utilities that require a TTY.
///
/// Returns a tuple of (path, controller, replica) where:
Expand All @@ -3046,9 +3107,8 @@ pub fn whoami() -> String {
/// - replica: The replica file
#[cfg(all(unix, not(target_os = "redox")))]
pub fn pty_path() -> (String, File, File) {
use nix::pty::openpty;
use nix::unistd::ttyname;
let pty = openpty(None, None).expect("Failed to create PTY");
let pty = open_pty(None);
let path = ttyname(&pty.slave)
.expect("Failed to get PTY path")
.to_string_lossy()
Expand Down
Loading