Skip to content

tty_ptsname is a safe function that builds a CStr from a possibly null ptsname() #1953

Description

@lwz23

teletypewriter::tty_ptsname is a public safe function. Its comment says it is unsafe because it calls libc::ptsname, but the function is not unsafe fn.

ptsname returns a null pointer when fd is not a pty master. The function passes that pointer straight to CStr::from_ptr:

pub fn tty_ptsname(fd: libc::c_int) -> Result<String, String> {
    let c_str: &CStr = unsafe {
        let name_ptr = ptsname(fd as *mut _);
        CStr::from_ptr(name_ptr)
    };
    ...
}

CStr::from_ptr requires a non-null, NUL-terminated string. A null pointer is immediate undefined behavior, not a Result::Err. Safe Rust can call tty_ptsname(-1) with no unsafe block.

Current file: teletypewriter/src/unix/mod.rs, tty_ptsname (around line 962 on main).

Suggested fix: if name_ptr is null, return Err (and read errno if you want a message). Do that before CStr::from_ptr. Marking the function unsafe would also match the comment, but the null check is the useful fix because the signature already returns Result.

I did not find an existing issue for ptsname / tty_ptsname.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions