diff --git a/src/header/stdio/getdelim.rs b/src/header/stdio/getdelim.rs index f6898b3a93..19be72bb11 100644 --- a/src/header/stdio/getdelim.rs +++ b/src/header/stdio/getdelim.rs @@ -1,5 +1,8 @@ // https://pubs.opengroup.org/onlinepubs/9699919799/functions/getline.html +// TODO: set this for entire crate when possible +#![deny(unsafe_op_in_unsafe_fn)] + use alloc::{string::String, vec::Vec}; use core::{fmt::Write, intrinsics::unlikely, ops::Deref, ptr}; @@ -27,7 +30,7 @@ pub unsafe extern "C" fn getline( n: *mut size_t, stream: *mut FILE, ) -> ssize_t { - getdelim(lineptr, n, b'\n' as c_int, stream) + unsafe { getdelim(lineptr, n, b'\n' as c_int, stream) } } // One *could* read the standard as 'getdelim sets the stream error flag on *any* error, though @@ -55,15 +58,17 @@ pub unsafe extern "C" fn getdelim( delim: c_int, stream: *mut FILE, ) -> ssize_t { - let (lineptr, n, stream) = - if let (Some(ptr), Some(n), Some(file)) = (lineptr.as_mut(), n.as_mut(), stream.as_mut()) { - (ptr, n, file) - } else { - ERRNO.set(EINVAL); - return -1 as ssize_t; - }; + let (lineptr, n, stream) = if let (Some(ptr), Some(n), Some(file)) = + (unsafe { lineptr.as_mut() }, unsafe { n.as_mut() }, unsafe { + stream.as_mut() + }) { + (ptr, n, file) + } else { + ERRNO.set(EINVAL); + return -1 as ssize_t; + }; - if feof(stream) != 0 || ferror(stream) != 0 { + if unsafe { feof(stream) } != 0 || unsafe { ferror(stream) } != 0 { return -1 as ssize_t; } @@ -121,7 +126,7 @@ pub unsafe extern "C" fn getdelim( *n = count + 1; // The advantage in always realloc'ing is that even if the user supplies a wrong n, this // doesn't break - *lineptr = stdlib::realloc(*lineptr as *mut c_void, *n) as *mut c_char; + *lineptr = unsafe { stdlib::realloc(*lineptr as *mut c_void, *n) } as *mut c_char; if unlikely(lineptr.is_null() && *n != 0usize) { // memory error; realloc returns NULL on alloc'ing 0 bytes ERRNO.set(ENOMEM); @@ -129,10 +134,10 @@ pub unsafe extern "C" fn getdelim( } // Copy buf to lineptr - ptr::copy(buf.as_ptr(), *lineptr as *mut u8, count); + unsafe { ptr::copy(buf.as_ptr(), *lineptr as *mut u8, count) }; // NUL terminate lineptr - *lineptr.offset(count as isize) = 0; + unsafe { *lineptr.offset(count as isize) = 0 }; // TODO remove /*eprintln!( diff --git a/src/header/stdio/mod.rs b/src/header/stdio/mod.rs index ac99bbfebd..a38dd2de72 100644 --- a/src/header/stdio/mod.rs +++ b/src/header/stdio/mod.rs @@ -2,6 +2,9 @@ //! //! See . +// TODO: set this for entire crate when possible +#![deny(unsafe_op_in_unsafe_fn)] + use alloc::{ borrow::{Borrow, BorrowMut}, boxed::Box, @@ -296,7 +299,7 @@ impl<'a> Drop for LockGuard<'a> { /// Clears EOF and ERR indicators on a stream #[unsafe(no_mangle)] pub unsafe extern "C" fn clearerr(stream: *mut FILE) { - let mut stream = (*stream).lock(); + let mut stream = unsafe { (*stream).lock() }; stream.flags &= !(F_EOF | F_ERR); } @@ -309,7 +312,7 @@ pub unsafe extern "C" fn ctermid(s: *mut c_char) -> *mut c_char { return &raw mut TERMID as *mut c_char; } - strncpy(s, &raw mut TERMID as *mut c_char, L_ctermid) + unsafe { strncpy(s, &raw mut TERMID as *mut c_char, L_ctermid) } } /// See @@ -321,25 +324,29 @@ pub unsafe extern "C" fn cuserid(s: *mut c_char) -> *mut c_char { let mut pwd: pwd::passwd = unsafe { mem::zeroed() }; let mut pwdbuf: *mut pwd::passwd = unsafe { mem::zeroed() }; if s != ptr::null_mut() { - *s.add(0) = 0; + unsafe { + *s.add(0) = 0; + } } - pwd::getpwuid_r( - unistd::geteuid(), - &mut pwd, - buf.as_mut_ptr(), - buf.len(), - &mut pwdbuf, - ); + unsafe { + pwd::getpwuid_r( + unistd::geteuid(), + &mut pwd, + buf.as_mut_ptr(), + buf.len(), + &mut pwdbuf, + ) + }; if pwdbuf == ptr::null_mut() { return s; } if s != ptr::null_mut() { - strncpy(s, (*pwdbuf).pw_name, unistd::L_cuserid); + unsafe { strncpy(s, (*pwdbuf).pw_name, unistd::L_cuserid) }; return s; } - (*pwdbuf).pw_name + unsafe { (*pwdbuf).pw_name } } /// See . @@ -350,8 +357,8 @@ pub unsafe extern "C" fn cuserid(s: *mut c_char) -> *mut c_char { /// prior to using this function. #[unsafe(no_mangle)] pub unsafe extern "C" fn fclose(stream: *mut FILE) -> c_int { - let stream = &mut *stream; - flockfile(stream); + let stream = unsafe { &mut *stream }; + unsafe { flockfile(stream) }; let mut r = stream.flush().is_err(); // TODO: better error handling @@ -360,11 +367,11 @@ pub unsafe extern "C" fn fclose(stream: *mut FILE) -> c_int { if stream.flags & constants::F_PERM == 0 { // Not one of stdin, stdout or stderr - let mut stream = Box::from_raw(stream); + let mut stream = unsafe { Box::from_raw(stream) }; // Reference files aren't closed on drop, so pretend to be a reference stream.file.reference = true; } else { - funlockfile(stream); + unsafe { funlockfile(stream) }; } r as c_int @@ -375,7 +382,7 @@ pub unsafe extern "C" fn fclose(stream: *mut FILE) -> c_int { /// Open a file from a file descriptor #[unsafe(no_mangle)] pub unsafe extern "C" fn fdopen(fildes: c_int, mode: *const c_char) -> *mut FILE { - helpers::_fdopen(fildes, CStr::from_ptr(mode)) + helpers::_fdopen(fildes, unsafe { CStr::from_ptr(mode) }) .map(|f| Box::into_raw(f)) .or_errno_null_mut() } @@ -385,7 +392,7 @@ pub unsafe extern "C" fn fdopen(fildes: c_int, mode: *const c_char) -> *mut FILE /// Check for EOF #[unsafe(no_mangle)] pub unsafe extern "C" fn feof(stream: *mut FILE) -> c_int { - let stream = (*stream).lock(); + let stream = unsafe { (*stream).lock() }; stream.flags & F_EOF } @@ -394,7 +401,7 @@ pub unsafe extern "C" fn feof(stream: *mut FILE) -> c_int { /// Check for ERR #[unsafe(no_mangle)] pub unsafe extern "C" fn ferror(stream: *mut FILE) -> c_int { - let stream = (*stream).lock(); + let stream = unsafe { (*stream).lock() }; stream.flags & F_ERR } @@ -408,15 +415,15 @@ pub unsafe extern "C" fn fflush(stream: *mut FILE) -> c_int { if stream.is_null() { //TODO: flush all files! - if fflush(stdout) != 0 { + if unsafe { fflush(stdout) } != 0 { return EOF; } - if fflush(stderr) != 0 { + if unsafe { fflush(stderr) } != 0 { return EOF; } } else { - let mut stream = (*stream).lock(); + let mut stream = unsafe { unsafe { (*stream).lock() } }; if stream.flush().is_err() { return EOF; } @@ -430,12 +437,12 @@ pub unsafe extern "C" fn fflush(stream: *mut FILE) -> c_int { /// Get a single char from a stream #[unsafe(no_mangle)] pub unsafe extern "C" fn fgetc(stream: *mut FILE) -> c_int { - let mut stream = (*stream).lock(); + let mut stream = unsafe { (*stream).lock() }; if let Err(_) = (*stream).try_set_byte_orientation_unlocked() { return -1; } - getc_unlocked(&mut *stream) + unsafe { getc_unlocked(&mut *stream) } } /// See . @@ -443,11 +450,11 @@ pub unsafe extern "C" fn fgetc(stream: *mut FILE) -> c_int { /// Get the position of the stream and store it in pos #[unsafe(no_mangle)] pub unsafe extern "C" fn fgetpos(stream: *mut FILE, pos: *mut fpos_t) -> c_int { - let off = ftello(stream); + let off = unsafe { ftello(stream) }; if off < 0 { return -1; } - *pos = off; + unsafe { *pos = off }; 0 } @@ -460,7 +467,7 @@ pub unsafe extern "C" fn fgets( max: c_int, stream: *mut FILE, ) -> *mut c_char { - let mut stream = (*stream).lock(); + let mut stream = unsafe { (*stream).lock() }; if let Err(_) = (*stream).try_set_byte_orientation_unlocked() { return ptr::null_mut(); } @@ -473,8 +480,8 @@ pub unsafe extern "C" fn fgets( if left >= 1 { let unget_read_size = cmp::min(left, stream.unget.len()); for _ in 0..unget_read_size { - *out = stream.unget.pop().unwrap() as c_char; - out = out.offset(1); + unsafe { *out = stream.unget.pop().unwrap() as c_char }; + out = unsafe { out.offset(1) }; } left -= unget_read_size; } @@ -499,14 +506,14 @@ pub unsafe extern "C" fn fgets( let newline = buf[..len].iter().position(|&c| c == b'\n'); let len = newline.map(|i| i + 1).unwrap_or(len); - ptr::copy_nonoverlapping(buf.as_ptr(), out as *mut u8, len); + unsafe { ptr::copy_nonoverlapping(buf.as_ptr(), out as *mut u8, len) }; (len, newline.is_some()) }; stream.consume(read); - out = out.add(read); + out = unsafe { out.add(read) }; left -= read; if exit { @@ -516,7 +523,7 @@ pub unsafe extern "C" fn fgets( if max >= 1 { // Write the NUL byte - *out = 0; + unsafe { *out = 0 }; } if wrote { original } else { ptr::null_mut() } } @@ -526,7 +533,7 @@ pub unsafe extern "C" fn fgets( /// Get the underlying file descriptor #[unsafe(no_mangle)] pub unsafe extern "C" fn fileno(stream: *mut FILE) -> c_int { - let stream = (*stream).lock(); + let stream = unsafe { (*stream).lock() }; *stream.file } @@ -537,7 +544,7 @@ pub unsafe extern "C" fn fileno(stream: *mut FILE) -> c_int { /// locked #[unsafe(no_mangle)] pub unsafe extern "C" fn flockfile(file: *mut FILE) { - if let Err(e) = (*file).lock.lock() { + if let Err(e) = unsafe { (*file).lock.lock() } { println!("RELIBC: flockfile error {}", e) } } @@ -547,7 +554,7 @@ pub unsafe extern "C" fn flockfile(file: *mut FILE) { /// Open the file in mode `mode` #[unsafe(no_mangle)] pub unsafe extern "C" fn fopen(filename: *const c_char, mode: *const c_char) -> *mut FILE { - let initial_mode = *mode; + let initial_mode = unsafe { *mode }; if initial_mode != b'r' as c_char && initial_mode != b'w' as c_char && initial_mode != b'a' as c_char @@ -556,7 +563,7 @@ pub unsafe extern "C" fn fopen(filename: *const c_char, mode: *const c_char) -> return ptr::null_mut(); } - let flags = helpers::parse_mode_flags(CStr::from_ptr(mode)); + let flags = helpers::parse_mode_flags(unsafe { CStr::from_ptr(mode) }); let new_mode = if flags & fcntl::O_CREAT == fcntl::O_CREAT { 0o666 @@ -564,16 +571,16 @@ pub unsafe extern "C" fn fopen(filename: *const c_char, mode: *const c_char) -> 0 }; - let fd = fcntl::open(filename, flags, new_mode); + let fd = unsafe { fcntl::open(filename, flags, new_mode) }; if fd < 0 { return ptr::null_mut(); } if flags & fcntl::O_CLOEXEC > 0 { - fcntl::fcntl(fd, fcntl::F_SETFD, fcntl::FD_CLOEXEC as c_ulonglong); + unsafe { fcntl::fcntl(fd, fcntl::F_SETFD, fcntl::FD_CLOEXEC as c_ulonglong) }; } - helpers::_fdopen(fd, CStr::from_ptr(mode)) + helpers::_fdopen(fd, unsafe { CStr::from_ptr(mode) }) .map(|f| Box::into_raw(f)) .map_err(|err| { // TODO: guard type @@ -593,7 +600,7 @@ pub unsafe extern "C" fn fopen(filename: *const c_char, mode: *const c_char) -> #[unsafe(no_mangle)] pub unsafe extern "C" fn __fpurge(stream: *mut FILE) { if !stream.is_null() { - let mut stream = (*stream).lock(); + let mut stream = unsafe { (*stream).lock() }; stream.purge(); } } @@ -603,12 +610,12 @@ pub unsafe extern "C" fn __fpurge(stream: *mut FILE) { /// Insert a character into the stream #[unsafe(no_mangle)] pub unsafe extern "C" fn fputc(c: c_int, stream: *mut FILE) -> c_int { - let mut stream = (*stream).lock(); + let mut stream = unsafe { (*stream).lock() }; if let Err(_) = (*stream).try_set_byte_orientation_unlocked() { return -1; } - putc_unlocked(c, &mut *stream) + unsafe { putc_unlocked(c, &mut *stream) } } /// See . @@ -616,12 +623,12 @@ pub unsafe extern "C" fn fputc(c: c_int, stream: *mut FILE) -> c_int { /// Insert a string into a stream #[unsafe(no_mangle)] pub unsafe extern "C" fn fputs(s: *const c_char, stream: *mut FILE) -> c_int { - let mut stream = (*stream).lock(); + let mut stream = unsafe { (*stream).lock() }; if let Err(_) = (*stream).try_set_byte_orientation_unlocked() { return -1; } - let buf = slice::from_raw_parts(s as *mut u8, strlen(s)); + let buf = unsafe { slice::from_raw_parts(s as *mut u8, strlen(s)) }; if stream.write_all(&buf).is_ok() { 0 @@ -644,12 +651,12 @@ pub unsafe extern "C" fn fread( return 0; } - let mut stream = (*stream).lock(); + let mut stream = unsafe { (*stream).lock() }; if let Err(_) = (*stream).try_set_byte_orientation_unlocked() { return 0; } - let buf = slice::from_raw_parts_mut(ptr as *mut u8, size as usize * nitems as usize); + let buf = unsafe { slice::from_raw_parts_mut(ptr as *mut u8, size as usize * nitems as usize) }; let mut read = 0; while read < buf.len() { match stream.read(&mut buf[read..]) { @@ -667,52 +674,56 @@ pub unsafe extern "C" fn freopen( mode: *const c_char, stream: &mut FILE, ) -> *mut FILE { - let mut flags = helpers::parse_mode_flags(CStr::from_ptr(mode)); - flockfile(stream); + let mut flags = helpers::parse_mode_flags(unsafe { CStr::from_ptr(mode) }); + unsafe { flockfile(stream) }; let _ = stream.flush(); if filename.is_null() { // Reopen stream in new mode if flags & fcntl::O_CLOEXEC > 0 { - fcntl::fcntl( - *stream.file, - fcntl::F_SETFD, - fcntl::FD_CLOEXEC as c_ulonglong, - ); + unsafe { + fcntl::fcntl( + *stream.file, + fcntl::F_SETFD, + fcntl::FD_CLOEXEC as c_ulonglong, + ) + }; } flags &= !(fcntl::O_CREAT | fcntl::O_EXCL | fcntl::O_CLOEXEC); - if fcntl::fcntl(*stream.file, fcntl::F_SETFL, flags as c_ulonglong) < 0 { - funlockfile(stream); - fclose(stream); + if unsafe { fcntl::fcntl(*stream.file, fcntl::F_SETFL, flags as c_ulonglong) } < 0 { + unsafe { funlockfile(stream) }; + unsafe { fclose(stream) }; return ptr::null_mut(); } } else { - let new = fopen(filename, mode); + let new = unsafe { fopen(filename, mode) }; if new.is_null() { - funlockfile(stream); - fclose(stream); + unsafe { funlockfile(stream) }; + unsafe { fclose(stream) }; return ptr::null_mut(); } - let new = &mut *new; // Should be safe, new is not null + let new = unsafe { &mut *new }; // Should be safe, new is not null if *new.file == *stream.file { new.file.fd = -1; } else if Sys::dup2(*new.file, *stream.file).or_minus_one_errno() == -1 - || fcntl::fcntl( - *stream.file, - fcntl::F_SETFL, - (flags & fcntl::O_CLOEXEC) as c_ulonglong, - ) < 0 + || unsafe { + fcntl::fcntl( + *stream.file, + fcntl::F_SETFL, + (flags & fcntl::O_CLOEXEC) as c_ulonglong, + ) + } < 0 { - funlockfile(stream); - fclose(new); - fclose(stream); + unsafe { funlockfile(stream) }; + unsafe { fclose(new) }; + unsafe { fclose(stream) }; return ptr::null_mut(); } stream.flags = (stream.flags & constants::F_PERM) | new.flags; - fclose(new); + unsafe { fclose(new) }; } stream.orientation = 0; - funlockfile(stream); + unsafe { funlockfile(stream) }; stream } @@ -721,7 +732,7 @@ pub unsafe extern "C" fn freopen( /// Seek to an offset `offset` from `whence` #[unsafe(no_mangle)] pub unsafe extern "C" fn fseek(stream: *mut FILE, offset: c_long, whence: c_int) -> c_int { - fseeko(stream, offset as off_t, whence) + unsafe { fseeko(stream, offset as off_t, whence) } } /// See . @@ -729,8 +740,8 @@ pub unsafe extern "C" fn fseek(stream: *mut FILE, offset: c_long, whence: c_int) /// Seek to an offset `offset` from `whence` #[unsafe(no_mangle)] pub unsafe extern "C" fn fseeko(stream: *mut FILE, off: off_t, whence: c_int) -> c_int { - let mut stream = (*stream).lock(); - fseek_locked(&mut *stream, off, whence) + let mut stream = unsafe { (*stream).lock() }; + unsafe { fseek_locked(&mut *stream, off, whence) } } pub unsafe fn fseek_locked(stream: &mut FILE, mut off: off_t, whence: c_int) -> c_int { @@ -762,7 +773,7 @@ pub unsafe fn fseek_locked(stream: &mut FILE, mut off: off_t, whence: c_int) -> /// Seek to a position `pos` in the file from the beginning of the file #[unsafe(no_mangle)] pub unsafe extern "C" fn fsetpos(stream: *mut FILE, pos: *const fpos_t) -> c_int { - fseeko(stream, *pos, SEEK_SET) + unsafe { fseeko(stream, *pos, SEEK_SET) } } /// See . @@ -770,7 +781,7 @@ pub unsafe extern "C" fn fsetpos(stream: *mut FILE, pos: *const fpos_t) -> c_int /// Get the current position of the cursor in the file #[unsafe(no_mangle)] pub unsafe extern "C" fn ftell(stream: *mut FILE) -> c_long { - ftello(stream) as c_long + unsafe { ftello(stream) as c_long } } /// See . @@ -778,8 +789,8 @@ pub unsafe extern "C" fn ftell(stream: *mut FILE) -> c_long { /// Get the current position of the cursor in the file #[unsafe(no_mangle)] pub unsafe extern "C" fn ftello(stream: *mut FILE) -> off_t { - let mut stream = (*stream).lock(); - ftell_locked(&mut *stream) + let mut stream = unsafe { (*stream).lock() }; + unsafe { ftell_locked(&mut *stream) } } pub unsafe extern "C" fn ftell_locked(stream: &mut FILE) -> off_t { @@ -798,7 +809,7 @@ pub unsafe extern "C" fn ftell_locked(stream: &mut FILE) -> off_t { /// Try to lock the file. Returns 0 for success, 1 for failure #[unsafe(no_mangle)] pub unsafe extern "C" fn ftrylockfile(file: *mut FILE) -> c_int { - if (*file).lock.try_lock().is_ok() { + if unsafe { (*file).lock.try_lock() }.is_ok() { 0 } else { 1 @@ -810,7 +821,7 @@ pub unsafe extern "C" fn ftrylockfile(file: *mut FILE) -> c_int { /// Unlock the file #[unsafe(no_mangle)] pub unsafe extern "C" fn funlockfile(file: *mut FILE) { - if let Err(e) = (*file).lock.unlock() { + if let Err(e) = unsafe { (*file).lock.unlock() } { println!("RELIBC: funlockfile error {}", e) } } @@ -828,12 +839,12 @@ pub unsafe extern "C" fn fwrite( if size == 0 || nitems == 0 { return 0; } - let mut stream = (*stream).lock(); + let mut stream = unsafe { (*stream).lock() }; if let Err(_) = (*stream).try_set_byte_orientation_unlocked() { return 0; } - let buf = slice::from_raw_parts(ptr as *const u8, size as usize * nitems as usize); + let buf = unsafe { slice::from_raw_parts(ptr as *const u8, size as usize * nitems as usize) }; let mut written = 0; while written < buf.len() { match stream.write(&buf[written..]) { @@ -849,8 +860,8 @@ pub unsafe extern "C" fn fwrite( /// Get a single char from a stream #[unsafe(no_mangle)] pub unsafe extern "C" fn getc(stream: *mut FILE) -> c_int { - let mut stream = (*stream).lock(); - getc_unlocked(&mut *stream) + let mut stream = unsafe { (*stream).lock() }; + unsafe { getc_unlocked(&mut *stream) } } /// See . @@ -858,7 +869,7 @@ pub unsafe extern "C" fn getc(stream: *mut FILE) -> c_int { /// Get a single char from `stdin` #[unsafe(no_mangle)] pub unsafe extern "C" fn getchar() -> c_int { - fgetc(&mut *stdin) + unsafe { fgetc(&mut *stdin) } } /// See . @@ -866,13 +877,13 @@ pub unsafe extern "C" fn getchar() -> c_int { /// Get a char from a stream without locking the stream #[unsafe(no_mangle)] pub unsafe extern "C" fn getc_unlocked(stream: *mut FILE) -> c_int { - if let Err(_) = (*stream).try_set_byte_orientation_unlocked() { + if let Err(_) = unsafe { (*stream).try_set_byte_orientation_unlocked() } { return -1; } let mut buf = [0]; - match (*stream).read(&mut buf) { + match unsafe { (*stream).read(&mut buf) } { Ok(0) | Err(_) => EOF, Ok(_) => buf[0] as c_int, } @@ -883,7 +894,7 @@ pub unsafe extern "C" fn getc_unlocked(stream: *mut FILE) -> c_int { /// Get a char from `stdin` without locking `stdin` #[unsafe(no_mangle)] pub unsafe extern "C" fn getchar_unlocked() -> c_int { - getc_unlocked(&mut *stdin) + unsafe { getc_unlocked(&mut *stdin) } } /// See . @@ -894,7 +905,7 @@ pub unsafe extern "C" fn getchar_unlocked() -> c_int { /// Get a string from `stdin` #[unsafe(no_mangle)] pub unsafe extern "C" fn gets(s: *mut c_char) -> *mut c_char { - fgets(s, c_int::max_value(), &mut *stdin) + unsafe { fgets(s, c_int::max_value(), &mut *stdin) } } /// See . @@ -905,12 +916,14 @@ pub unsafe extern "C" fn gets(s: *mut c_char) -> *mut c_char { #[unsafe(no_mangle)] pub unsafe extern "C" fn getw(stream: *mut FILE) -> c_int { let mut ret: c_int = 0; - if fread( - &mut ret as *mut _ as *mut c_void, - mem::size_of_val(&ret), - 1, - stream, - ) > 0 + if unsafe { + fread( + &mut ret as *mut _ as *mut c_void, + mem::size_of_val(&ret), + 1, + stream, + ) + } > 0 { ret } else { @@ -923,7 +936,7 @@ pub unsafe extern "C" fn getw(stream: *mut FILE) -> c_int { pub unsafe extern "C" fn pclose(stream: *mut FILE) -> c_int { // TODO: rusty error handling? let pid = { - let mut stream = (*stream).lock(); + let mut stream = unsafe { (*stream).lock() }; if let Some(pid) = stream.pid.take() { pid @@ -933,7 +946,7 @@ pub unsafe extern "C" fn pclose(stream: *mut FILE) -> c_int { } }; - fclose(stream); + unsafe { fclose(stream) }; let mut wstatus = 0; if Sys::waitpid(pid, Some(Out::from_mut(&mut wstatus)), 0).or_minus_one_errno() == -1 { @@ -955,7 +968,9 @@ pub unsafe extern "C" fn perror(s: *const c_char) { let mut w = platform::FileWriter::new(2); // The prefix, `s`, is optional (empty or NULL) according to the spec - match CStr::from_nullable_ptr(s).and_then(|s_cstr| str::from_utf8(s_cstr.to_bytes()).ok()) { + match unsafe { CStr::from_nullable_ptr(s) } + .and_then(|s_cstr| str::from_utf8(s_cstr.to_bytes()).ok()) + { Some(s_str) if !s_str.is_empty() => w .write_fmt(format_args!("{}: {}\n", s_str, err_str)) .unwrap(), @@ -968,7 +983,7 @@ pub unsafe extern "C" fn perror(s: *const c_char) { pub unsafe extern "C" fn popen(command: *const c_char, mode: *const c_char) -> *mut FILE { //TODO: share code with system - let mode = CStr::from_ptr(mode); + let mode = unsafe { CStr::from_ptr(mode) }; let mut cloexec = false; let mut write_opt = None; @@ -993,11 +1008,11 @@ pub unsafe extern "C" fn popen(command: *const c_char, mode: *const c_char) -> * }; let mut pipes = [-1, -1]; - if unistd::pipe(pipes.as_mut_ptr()) != 0 { + if unsafe { unistd::pipe(pipes.as_mut_ptr()) } != 0 { return ptr::null_mut(); } - let child_pid = unistd::fork(); + let child_pid = unsafe { unistd::fork() }; if child_pid == 0 { let command_nonnull = if command.is_null() { "exit 0\0".as_ptr() @@ -1020,12 +1035,12 @@ pub unsafe extern "C" fn popen(command: *const c_char, mode: *const c_char) -> * if write { match unistd::dup2(pipes[0], 0) { 0 => {} - e => stdlib::exit(127), + e => unsafe { stdlib::exit(127) }, } } else { match unistd::dup2(pipes[1], 1) { 1 => {} - e => stdlib::exit(127), + e => unsafe { stdlib::exit(127) }, } } @@ -1033,9 +1048,9 @@ pub unsafe extern "C" fn popen(command: *const c_char, mode: *const c_char) -> * unistd::close(pipes[1]); } - unistd::execv(shell as *const c_char, args.as_ptr() as *const *mut c_char); + unsafe { unistd::execv(shell as *const c_char, args.as_ptr() as *const *mut c_char) }; - stdlib::exit(127); + unsafe { stdlib::exit(127) }; unreachable!(); } else if child_pid > 0 { @@ -1063,8 +1078,8 @@ pub unsafe extern "C" fn popen(command: *const c_char, mode: *const c_char) -> * /// Put a character `c` into `stream` #[unsafe(no_mangle)] pub unsafe extern "C" fn putc(c: c_int, stream: *mut FILE) -> c_int { - let mut stream = (*stream).lock(); - putc_unlocked(c, &mut *stream) + let mut stream = unsafe { (*stream).lock() }; + unsafe { putc_unlocked(c, &mut *stream) } } /// See . @@ -1072,7 +1087,7 @@ pub unsafe extern "C" fn putc(c: c_int, stream: *mut FILE) -> c_int { /// Put a character `c` into `stdout` #[unsafe(no_mangle)] pub unsafe extern "C" fn putchar(c: c_int) -> c_int { - fputc(c, &mut *stdout) + unsafe { fputc(c, &mut *stdout) } } /// See . @@ -1080,11 +1095,11 @@ pub unsafe extern "C" fn putchar(c: c_int) -> c_int { /// Put a character `c` into `stream` without locking `stream` #[unsafe(no_mangle)] pub unsafe extern "C" fn putc_unlocked(c: c_int, stream: *mut FILE) -> c_int { - if let Err(_) = (*stream).try_set_byte_orientation_unlocked() { + if let Err(_) = unsafe { (*stream).try_set_byte_orientation_unlocked() } { return -1; } - match (*stream).write(&[c as u8]) { + match unsafe { (*stream).write(&[c as u8]) } { Ok(0) | Err(_) => EOF, Ok(_) => c, } @@ -1095,7 +1110,7 @@ pub unsafe extern "C" fn putc_unlocked(c: c_int, stream: *mut FILE) -> c_int { /// Put a character `c` into `stdout` without locking `stdout` #[unsafe(no_mangle)] pub unsafe extern "C" fn putchar_unlocked(c: c_int) -> c_int { - putc_unlocked(c, stdout) + unsafe { putc_unlocked(c, stdout) } } /// See . @@ -1103,12 +1118,12 @@ pub unsafe extern "C" fn putchar_unlocked(c: c_int) -> c_int { /// Put a string `s` into `stdout` #[unsafe(no_mangle)] pub unsafe extern "C" fn puts(s: *const c_char) -> c_int { - let mut stream = (&mut *stdout).lock(); + let mut stream = unsafe { (&mut *stdout).lock() }; if let Err(_) = (*stream).try_set_byte_orientation_unlocked() { return -1; } - let buf = slice::from_raw_parts(s as *mut u8, strlen(s)); + let buf = unsafe { slice::from_raw_parts(s as *mut u8, strlen(s)) }; if stream.write_all(&buf).is_err() { return -1; @@ -1126,7 +1141,7 @@ pub unsafe extern "C" fn puts(s: *const c_char) -> c_int { /// Put an integer `w` into `stream` #[unsafe(no_mangle)] pub unsafe extern "C" fn putw(w: c_int, stream: *mut FILE) -> c_int { - fwrite(&w as *const c_int as _, mem::size_of_val(&w), 1, stream) as i32 - 1 + (unsafe { fwrite(&w as *const c_int as _, mem::size_of_val(&w), 1, stream) }) as i32 - 1 } /// See . @@ -1134,7 +1149,7 @@ pub unsafe extern "C" fn putw(w: c_int, stream: *mut FILE) -> c_int { /// Delete file or directory `path` #[unsafe(no_mangle)] pub unsafe extern "C" fn remove(path: *const c_char) -> c_int { - let path = CStr::from_ptr(path); + let path = unsafe { CStr::from_ptr(path) }; Sys::unlink(path) .or_else(|_err| Sys::rmdir(path)) .map(|()| 0) @@ -1144,8 +1159,8 @@ pub unsafe extern "C" fn remove(path: *const c_char) -> c_int { /// See . #[unsafe(no_mangle)] pub unsafe extern "C" fn rename(oldpath: *const c_char, newpath: *const c_char) -> c_int { - let oldpath = CStr::from_ptr(oldpath); - let newpath = CStr::from_ptr(newpath); + let oldpath = unsafe { CStr::from_ptr(oldpath) }; + let newpath = unsafe { CStr::from_ptr(newpath) }; Sys::rename(oldpath, newpath) .map(|()| 0) .or_minus_one_errno() @@ -1159,8 +1174,8 @@ pub unsafe extern "C" fn renameat( new_dir: c_int, new_path: *const c_char, ) -> c_int { - let old_path = CStr::from_ptr(old_path); - let new_path = CStr::from_ptr(new_path); + let old_path = unsafe { CStr::from_ptr(old_path) }; + let new_path = unsafe { CStr::from_ptr(new_path) }; Sys::renameat(old_dir, old_path, new_dir, new_path) .map(|()| 0) .or_minus_one_errno() @@ -1177,8 +1192,8 @@ pub unsafe extern "C" fn renameat2( new_path: *const c_char, flags: c_uint, ) -> c_int { - let old_path = CStr::from_ptr(old_path); - let new_path = CStr::from_ptr(new_path); + let old_path = unsafe { CStr::from_ptr(old_path) }; + let new_path = unsafe { CStr::from_ptr(new_path) }; Sys::renameat2(old_dir, old_path, new_dir, new_path, flags) .map(|()| 0) .or_minus_one_errno() @@ -1189,7 +1204,7 @@ pub unsafe extern "C" fn renameat2( /// Rewind `stream` back to the beginning of it #[unsafe(no_mangle)] pub unsafe extern "C" fn rewind(stream: *mut FILE) { - fseeko(stream, 0, SEEK_SET); + unsafe { fseeko(stream, 0, SEEK_SET) }; } /// See . @@ -1197,12 +1212,14 @@ pub unsafe extern "C" fn rewind(stream: *mut FILE) { /// Reset `stream` to use buffer `buf`. Buffer must be `BUFSIZ` in length #[unsafe(no_mangle)] pub unsafe extern "C" fn setbuf(stream: *mut FILE, buf: *mut c_char) { - setvbuf( - stream, - buf, - if buf.is_null() { _IONBF } else { _IOFBF }, - BUFSIZ as usize, - ); + unsafe { + setvbuf( + stream, + buf, + if buf.is_null() { _IONBF } else { _IOFBF }, + BUFSIZ as usize, + ) + }; } /// See . @@ -1212,7 +1229,7 @@ pub unsafe extern "C" fn setbuf(stream: *mut FILE, buf: *mut c_char) { /// Set buffering of `stream` to line buffered #[unsafe(no_mangle)] pub unsafe extern "C" fn setlinebuf(stream: *mut FILE) { - setvbuf(stream, ptr::null_mut(), _IOLBF, 0); + unsafe { setvbuf(stream, ptr::null_mut(), _IOLBF, 0) }; } /// See . @@ -1226,7 +1243,7 @@ pub unsafe extern "C" fn setvbuf( mode: c_int, mut size: size_t, ) -> c_int { - let mut stream = (*stream).lock(); + let mut stream = unsafe { (*stream).lock() }; // Set a buffer of size `size` if no buffer is given stream.read_buf = if buf.is_null() || size == 0 { if size == 0 { @@ -1238,7 +1255,7 @@ pub unsafe extern "C" fn setvbuf( Buffer::Owned(vec![0; size as usize]) // } } else { - Buffer::Borrowed(slice::from_raw_parts_mut(buf as *mut u8, size)) + Buffer::Borrowed(unsafe { slice::from_raw_parts_mut(buf as *mut u8, size) }) }; stream.flags |= F_SVB; 0 @@ -1250,39 +1267,42 @@ pub unsafe extern "C" fn setvbuf( #[unsafe(no_mangle)] pub unsafe extern "C" fn tempnam(dir: *const c_char, pfx: *const c_char) -> *mut c_char { unsafe fn is_appropriate(pos_dir: *const c_char) -> bool { - !pos_dir.is_null() && unistd::access(pos_dir, unistd::W_OK) == 0 + !pos_dir.is_null() && unsafe { unistd::access(pos_dir, unistd::W_OK) } == 0 } // directory search order is env!(TMPDIR), dir, P_tmpdir, "/tmp" let dirname = { - let tmpdir = stdlib::getenv(b"TMPDIR\0".as_ptr() as _); + let tmpdir = unsafe { stdlib::getenv(b"TMPDIR\0".as_ptr() as _) }; [tmpdir, dir, P_tmpdir.as_ptr() as _] .iter() .copied() - .skip_while(|&d| !is_appropriate(d)) + .skip_while(|&d| !unsafe { is_appropriate(d) }) .next() .unwrap_or(b"/tmp\0".as_ptr() as _) }; - let dirname_len = string::strlen(dirname); + let dirname_len = unsafe { string::strlen(dirname) }; - let prefix_len = string::strnlen_s(pfx, 5); + let prefix_len = unsafe { string::strnlen_s(pfx, 5) }; // allocate enough for dirname "/" prefix "XXXXXX\0" let mut out_buf = - platform::alloc(dirname_len + 1 + prefix_len + L_tmpnam as usize + 1) as *mut c_char; + unsafe { platform::alloc(dirname_len + 1 + prefix_len + L_tmpnam as usize + 1) } + as *mut c_char; if !out_buf.is_null() { // copy the directory name and prefix into the allocated buffer - out_buf.copy_from_nonoverlapping(dirname, dirname_len); - *out_buf.add(dirname_len) = b'/' as _; - out_buf - .add(dirname_len + 1) - .copy_from_nonoverlapping(pfx, prefix_len); + unsafe { out_buf.copy_from_nonoverlapping(dirname, dirname_len) }; + unsafe { *out_buf.add(dirname_len) = b'/' as _ }; + unsafe { + out_buf + .add(dirname_len + 1) + .copy_from_nonoverlapping(pfx, prefix_len) + }; // use the same mechanism as tmpnam to get the file name - if tmpnam_inner(out_buf, dirname_len + 1 + prefix_len).is_null() { + if unsafe { tmpnam_inner(out_buf, dirname_len + 1 + prefix_len) }.is_null() { // failed to find a valid file name, so we need to free the buffer - platform::free(out_buf as _); + unsafe { platform::free(out_buf as _) }; out_buf = ptr::null_mut(); } } @@ -1295,15 +1315,15 @@ pub unsafe extern "C" fn tempnam(dir: *const c_char, pfx: *const c_char) -> *mut pub unsafe extern "C" fn tmpfile() -> *mut FILE { let mut file_name = *b"/tmp/tmpfileXXXXXX\0"; let file_name = file_name.as_mut_ptr() as *mut c_char; - let fd = stdlib::mkstemp(file_name); + let fd = unsafe { stdlib::mkstemp(file_name) }; if fd < 0 { return ptr::null_mut(); } - let fp = fdopen(fd, c"w+".as_ptr()); + let fp = unsafe { fdopen(fd, c"w+".as_ptr()) }; { - let file_name = CStr::from_ptr(file_name); + let file_name = unsafe { CStr::from_ptr(file_name) }; Sys::unlink(file_name); } @@ -1325,21 +1345,27 @@ pub unsafe extern "C" fn tmpnam(s: *mut c_char) -> *mut c_char { s }; - *buf = b'/' as _; - tmpnam_inner(buf, 1) + unsafe { *buf = b'/' as _ }; + unsafe { tmpnam_inner(buf, 1) } } unsafe extern "C" fn tmpnam_inner(buf: *mut c_char, offset: usize) -> *mut c_char { const TEMPLATE: &[u8] = b"XXXXXX\0"; - buf.add(offset) - .copy_from_nonoverlapping(TEMPLATE.as_ptr() as _, TEMPLATE.len()); + unsafe { + buf.add(offset) + .copy_from_nonoverlapping(TEMPLATE.as_ptr() as _, TEMPLATE.len()) + }; let err = platform::ERRNO.get(); - stdlib::mktemp(buf); + unsafe { stdlib::mktemp(buf) }; platform::ERRNO.set(err); - if *buf == 0 { ptr::null_mut() } else { buf } + if unsafe { *buf } == 0 { + ptr::null_mut() + } else { + buf + } } /// See . @@ -1347,7 +1373,7 @@ unsafe extern "C" fn tmpnam_inner(buf: *mut c_char, offset: usize) -> *mut c_cha /// Push character `c` back onto `stream` so it'll be read next #[unsafe(no_mangle)] pub unsafe extern "C" fn ungetc(c: c_int, stream: *mut FILE) -> c_int { - let mut stream = (*stream).lock(); + let mut stream = unsafe { (*stream).lock() }; if let Err(_) = (*stream).try_set_byte_orientation_unlocked() { return -1; } @@ -1359,12 +1385,12 @@ pub unsafe extern "C" fn ungetc(c: c_int, stream: *mut FILE) -> c_int { /// See . #[unsafe(no_mangle)] pub unsafe extern "C" fn vfprintf(file: *mut FILE, format: *const c_char, ap: va_list) -> c_int { - let mut file = (*file).lock(); + let mut file = unsafe { (*file).lock() }; if let Err(_) = file.try_set_byte_orientation_unlocked() { return -1; } - printf::printf(&mut *file, CStr::from_ptr(format), ap) + unsafe { printf::printf(&mut *file, CStr::from_ptr(format), ap) } } /// See . @@ -1374,7 +1400,7 @@ pub unsafe extern "C" fn fprintf( format: *const c_char, mut __valist: ... ) -> c_int { - vfprintf(file, format, __valist.as_va_list()) + unsafe { vfprintf(file, format, __valist.as_va_list()) } } /// See . @@ -1386,25 +1412,25 @@ pub unsafe extern "C" fn vdprintf(fd: c_int, format: *const c_char, ap: va_list) // borrowing the file descriptor here f.reference = true; - printf::printf(f, CStr::from_ptr(format), ap) + unsafe { printf::printf(f, CStr::from_ptr(format), ap) } } /// See . #[unsafe(no_mangle)] pub unsafe extern "C" fn dprintf(fd: c_int, format: *const c_char, mut __valist: ...) -> c_int { - vdprintf(fd, format, __valist.as_va_list()) + unsafe { vdprintf(fd, format, __valist.as_va_list()) } } /// See . #[unsafe(no_mangle)] pub unsafe extern "C" fn vprintf(format: *const c_char, ap: va_list) -> c_int { - vfprintf(&mut *stdout, format, ap) + unsafe { vfprintf(&mut *stdout, format, ap) } } /// See . #[unsafe(no_mangle)] pub unsafe extern "C" fn printf(format: *const c_char, mut __valist: ...) -> c_int { - vfprintf(&mut *stdout, format, __valist.as_va_list()) + unsafe { vfprintf(&mut *stdout, format, __valist.as_va_list()) } } /// See . @@ -1415,10 +1441,10 @@ pub unsafe extern "C" fn vasprintf( ap: va_list, ) -> c_int { let mut alloc_writer = CVec::new(); - let ret = printf::printf(&mut alloc_writer, CStr::from_ptr(format), ap); + let ret = unsafe { printf::printf(&mut alloc_writer, CStr::from_ptr(format), ap) }; alloc_writer.push(0).unwrap(); alloc_writer.shrink_to_fit().unwrap(); - *strp = alloc_writer.leak() as *mut c_char; + unsafe { *strp = alloc_writer.leak() as *mut c_char }; ret } @@ -1429,7 +1455,7 @@ pub unsafe extern "C" fn asprintf( format: *const c_char, mut __valist: ... ) -> c_int { - vasprintf(strp, format, __valist.as_va_list()) + unsafe { vasprintf(strp, format, __valist.as_va_list()) } } /// See . @@ -1440,11 +1466,13 @@ pub unsafe extern "C" fn vsnprintf( format: *const c_char, ap: va_list, ) -> c_int { - printf::printf( - &mut platform::StringWriter(s as *mut u8, n as usize), - CStr::from_ptr(format), - ap, - ) + unsafe { + printf::printf( + &mut platform::StringWriter(s as *mut u8, n as usize), + CStr::from_ptr(format), + ap, + ) + } } /// See . @@ -1455,21 +1483,25 @@ pub unsafe extern "C" fn snprintf( format: *const c_char, mut __valist: ... ) -> c_int { - printf::printf( - &mut platform::StringWriter(s as *mut u8, n as usize), - CStr::from_ptr(format), - __valist.as_va_list(), - ) + unsafe { + printf::printf( + &mut platform::StringWriter(s as *mut u8, n as usize), + CStr::from_ptr(format), + __valist.as_va_list(), + ) + } } /// See . #[unsafe(no_mangle)] pub unsafe extern "C" fn vsprintf(s: *mut c_char, format: *const c_char, ap: va_list) -> c_int { - printf::printf( - &mut platform::UnsafeStringWriter(s as *mut u8), - CStr::from_ptr(format), - ap, - ) + unsafe { + printf::printf( + &mut platform::UnsafeStringWriter(s as *mut u8), + CStr::from_ptr(format), + ap, + ) + } } /// See . @@ -1479,25 +1511,27 @@ pub unsafe extern "C" fn sprintf( format: *const c_char, mut __valist: ... ) -> c_int { - printf::printf( - &mut platform::UnsafeStringWriter(s as *mut u8), - CStr::from_ptr(format), - __valist.as_va_list(), - ) + unsafe { + printf::printf( + &mut platform::UnsafeStringWriter(s as *mut u8), + CStr::from_ptr(format), + __valist.as_va_list(), + ) + } } /// See . #[unsafe(no_mangle)] pub unsafe extern "C" fn vfscanf(file: *mut FILE, format: *const c_char, ap: va_list) -> c_int { let ret = { - let mut file = (*file).lock(); + let mut file = unsafe { (*file).lock() }; if let Err(_) = file.try_set_byte_orientation_unlocked() { return -1; } let f: &mut FILE = &mut *file; let reader: LookAheadReader = f.into(); - scanf::scanf(reader, format, ap) + unsafe { scanf::scanf(reader, format, ap) } }; ret } @@ -1509,26 +1543,26 @@ pub unsafe extern "C" fn fscanf( format: *const c_char, mut __valist: ... ) -> c_int { - vfscanf(file, format, __valist.as_va_list()) + unsafe { vfscanf(file, format, __valist.as_va_list()) } } /// See . #[unsafe(no_mangle)] pub unsafe extern "C" fn vscanf(format: *const c_char, ap: va_list) -> c_int { - vfscanf(&mut *stdin, format, ap) + unsafe { vfscanf(&mut *stdin, format, ap) } } /// See . #[unsafe(no_mangle)] pub unsafe extern "C" fn scanf(format: *const c_char, mut __valist: ...) -> c_int { - vfscanf(&mut *stdin, format, __valist.as_va_list()) + unsafe { vfscanf(&mut *stdin, format, __valist.as_va_list()) } } /// See . #[unsafe(no_mangle)] pub unsafe extern "C" fn vsscanf(s: *const c_char, format: *const c_char, ap: va_list) -> c_int { let reader = (s as *const u8).into(); - scanf::scanf(reader, format, ap) + unsafe { scanf::scanf(reader, format, ap) } } /// See . @@ -1539,14 +1573,14 @@ pub unsafe extern "C" fn sscanf( mut __valist: ... ) -> c_int { let reader = (s as *const u8).into(); - scanf::scanf(reader, format, __valist.as_va_list()) + unsafe { scanf::scanf(reader, format, __valist.as_va_list()) } } pub unsafe fn flush_io_streams() { let flush = |stream: *mut FILE| { - let stream = &mut *stream; + let stream = unsafe { &mut *stream }; let _ = stream.flush(); }; - flush(stdout); - flush(stderr); + flush(unsafe { stdout }); + flush(unsafe { stderr }); } diff --git a/src/header/stdio/printf.rs b/src/header/stdio/printf.rs index d2d49bd47f..8f5cc41e50 100644 --- a/src/header/stdio/printf.rs +++ b/src/header/stdio/printf.rs @@ -1,3 +1,6 @@ +// TODO: set this for entire crate when possible +#![deny(unsafe_op_in_unsafe_fn)] + // TODO: reuse more code with the wide printf impl use crate::{ c_str::{self, CStr, NulStr}, @@ -59,11 +62,11 @@ impl Number { pub(crate) unsafe fn resolve(self, varargs: &mut VaListCache, ap: &mut VaList) -> usize { let arg = match self { Number::Static(num) => return num, - Number::Index(i) => varargs.get(i - 1, ap, None), + Number::Index(i) => unsafe { varargs.get(i - 1, ap, None) }, Number::Next => { let i = varargs.i; varargs.i += 1; - varargs.get(i, ap, None) + unsafe { varargs.get(i, ap, None) } } }; match arg { @@ -108,44 +111,44 @@ impl VaArg { (FmtKind::Percent, _) => panic!("Can't call arg_from on %"), (FmtKind::Char, IntKind::Long) | (FmtKind::Char, IntKind::LongLong) => { - VaArg::wint_t(ap.arg::()) + VaArg::wint_t(unsafe { ap.arg::() }) } (FmtKind::Char, _) | (FmtKind::Unsigned, IntKind::Byte) | (FmtKind::Signed, IntKind::Byte) => { // c_int is passed but truncated to c_char - VaArg::c_char(ap.arg::() as c_char) + VaArg::c_char(unsafe { ap.arg::() } as c_char) } (FmtKind::Unsigned, IntKind::Short) | (FmtKind::Signed, IntKind::Short) => { // c_int is passed but truncated to c_short - VaArg::c_short(ap.arg::() as c_short) + VaArg::c_short(unsafe { ap.arg::() } as c_short) } (FmtKind::Unsigned, IntKind::Int) | (FmtKind::Signed, IntKind::Int) => { - VaArg::c_int(ap.arg::()) + VaArg::c_int(unsafe { ap.arg::() }) } (FmtKind::Unsigned, IntKind::Long) | (FmtKind::Signed, IntKind::Long) => { - VaArg::c_long(ap.arg::()) + VaArg::c_long(unsafe { ap.arg::() }) } (FmtKind::Unsigned, IntKind::LongLong) | (FmtKind::Signed, IntKind::LongLong) => { - VaArg::c_longlong(ap.arg::()) + VaArg::c_longlong(unsafe { ap.arg::() }) } (FmtKind::Unsigned, IntKind::IntMax) | (FmtKind::Signed, IntKind::IntMax) => { - VaArg::intmax_t(ap.arg::()) + VaArg::intmax_t(unsafe { ap.arg::() }) } (FmtKind::Unsigned, IntKind::PtrDiff) | (FmtKind::Signed, IntKind::PtrDiff) => { - VaArg::ptrdiff_t(ap.arg::()) + VaArg::ptrdiff_t(unsafe { ap.arg::() }) } (FmtKind::Unsigned, IntKind::Size) | (FmtKind::Signed, IntKind::Size) => { - VaArg::ssize_t(ap.arg::()) + VaArg::ssize_t(unsafe { ap.arg::() }) } (FmtKind::AnyNotation, _) | (FmtKind::Decimal, _) | (FmtKind::Scientific, _) => { - VaArg::c_double(ap.arg::()) + VaArg::c_double(unsafe { ap.arg::() }) } (FmtKind::GetWritten, _) | (FmtKind::Pointer, _) | (FmtKind::String, _) => { - VaArg::pointer(ap.arg::<*const c_void>()) + VaArg::pointer(unsafe { ap.arg::<*const c_void>() }) } } } @@ -188,40 +191,40 @@ impl VaArg { (FmtKind::Percent, _) => panic!("Can't call transmute on %"), (FmtKind::Char, IntKind::Long) | (FmtKind::Char, IntKind::LongLong) => { - VaArg::wint_t(untyped.wint_t) + VaArg::wint_t(unsafe { untyped.wint_t }) } (FmtKind::Char, _) | (FmtKind::Unsigned, IntKind::Byte) - | (FmtKind::Signed, IntKind::Byte) => VaArg::c_char(untyped.c_char), + | (FmtKind::Signed, IntKind::Byte) => VaArg::c_char(unsafe { untyped.c_char }), (FmtKind::Unsigned, IntKind::Short) | (FmtKind::Signed, IntKind::Short) => { - VaArg::c_short(untyped.c_short) + VaArg::c_short(unsafe { untyped.c_short }) } (FmtKind::Unsigned, IntKind::Int) | (FmtKind::Signed, IntKind::Int) => { - VaArg::c_int(untyped.c_int) + VaArg::c_int(unsafe { untyped.c_int }) } (FmtKind::Unsigned, IntKind::Long) | (FmtKind::Signed, IntKind::Long) => { - VaArg::c_long(untyped.c_long) + VaArg::c_long(unsafe { untyped.c_long }) } (FmtKind::Unsigned, IntKind::LongLong) | (FmtKind::Signed, IntKind::LongLong) => { - VaArg::c_longlong(untyped.c_longlong) + VaArg::c_longlong(unsafe { untyped.c_longlong }) } (FmtKind::Unsigned, IntKind::IntMax) | (FmtKind::Signed, IntKind::IntMax) => { - VaArg::intmax_t(untyped.intmax_t) + VaArg::intmax_t(unsafe { untyped.intmax_t }) } (FmtKind::Unsigned, IntKind::PtrDiff) | (FmtKind::Signed, IntKind::PtrDiff) => { - VaArg::ptrdiff_t(untyped.ptrdiff_t) + VaArg::ptrdiff_t(unsafe { untyped.ptrdiff_t }) } (FmtKind::Unsigned, IntKind::Size) | (FmtKind::Signed, IntKind::Size) => { - VaArg::ssize_t(untyped.ssize_t) + VaArg::ssize_t(unsafe { untyped.ssize_t }) } (FmtKind::AnyNotation, _) | (FmtKind::Decimal, _) | (FmtKind::Scientific, _) => { - VaArg::c_double(untyped.c_double) + VaArg::c_double(unsafe { untyped.c_double }) } (FmtKind::GetWritten, _) | (FmtKind::Pointer, _) | (FmtKind::String, _) => { - VaArg::pointer(untyped.pointer) + VaArg::pointer(unsafe { untyped.pointer }) } } } @@ -243,7 +246,7 @@ impl VaListCache { let mut arg = arg; if let Some((fmtkind, intkind)) = default { // ...but as a different type - arg = arg.transmute(fmtkind, intkind); + arg = unsafe { arg.transmute(fmtkind, intkind) }; } return arg; } @@ -254,13 +257,13 @@ impl VaListCache { // point. Reaching here means there are unused gaps in the // arguments. Ultimately we'll have to settle down with // defaulting to c_int. - self.args.push(VaArg::c_int(ap.arg::())) + self.args.push(VaArg::c_int(unsafe { ap.arg::() })) } // Add the value to the cache self.args.push(match default { - Some((fmtkind, intkind)) => VaArg::arg_from(fmtkind, intkind, ap), - None => VaArg::c_int(ap.arg::()), + Some((fmtkind, intkind)) => unsafe { VaArg::arg_from(fmtkind, intkind, ap) }, + None => VaArg::c_int(unsafe { ap.arg::() }), }); // Return the value @@ -656,7 +659,9 @@ pub(crate) unsafe fn inner_printf( } for num in &[arg.min_width, arg.precision.unwrap_or(Number::Static(0))] { match num { - Number::Next => varargs.args.push(VaArg::c_int(ap.arg::())), + Number::Next => varargs + .args + .push(VaArg::c_int(unsafe { ap.arg::() })), Number::Index(i) => { positional.insert(i - 1, (FmtKind::Signed, IntKind::Int)); } @@ -669,13 +674,13 @@ pub(crate) unsafe fn inner_printf( } None => varargs .args - .push(VaArg::arg_from(arg.fmtkind, arg.intkind, &mut ap)), + .push(unsafe { VaArg::arg_from(arg.fmtkind, arg.intkind, &mut ap) }), } } // Make sure, in order, the positional arguments exist with the specified type for (i, arg) in positional { - varargs.get(i, &mut ap, Some(arg)); + unsafe { varargs.get(i, &mut ap, Some(arg)) }; } // Main loop @@ -701,10 +706,10 @@ pub(crate) unsafe fn inner_printf( let mut left = arg.left; let sign_reserve = arg.sign_reserve; let sign_always = arg.sign_always; - let min_width = arg.min_width.resolve(&mut varargs, &mut ap); + let min_width = unsafe { arg.min_width.resolve(&mut varargs, &mut ap) }; let precision = arg .precision - .map(|n| n.resolve(&mut varargs, &mut ap)) + .map(|n| unsafe { n.resolve(&mut varargs, &mut ap) }) .filter(|&n| (n as c_int) >= 0); let pad_zero = if zero { min_width } else { 0 }; let signed_space = match pad_zero { @@ -741,7 +746,9 @@ pub(crate) unsafe fn inner_printf( match fmtkind { FmtKind::Percent => w.write_all(&[b'%'])?, FmtKind::Signed => { - let string = match varargs.get(index, &mut ap, Some((arg.fmtkind, arg.intkind))) { + let string = match unsafe { + varargs.get(index, &mut ap, Some((arg.fmtkind, arg.intkind))) + } { VaArg::c_char(i) => i.to_string(), VaArg::c_double(i) => panic!("this should not be possible"), VaArg::c_int(i) => i.to_string(), @@ -789,7 +796,9 @@ pub(crate) unsafe fn inner_printf( pad(w, left, b' ', final_len..pad_space)?; } FmtKind::Unsigned => { - let string = match varargs.get(index, &mut ap, Some((arg.fmtkind, arg.intkind))) { + let string = match unsafe { + varargs.get(index, &mut ap, Some((arg.fmtkind, arg.intkind))) + } { VaArg::c_char(i) => fmt_int::<_, T>(fmt, i as c_uchar), VaArg::c_double(i) => panic!("this should not be possible"), VaArg::c_int(i) => fmt_int::<_, T>(fmt, i as c_uint), @@ -848,7 +857,9 @@ pub(crate) unsafe fn inner_printf( pad(w, left, b' ', final_len..pad_space)?; } FmtKind::Scientific => { - let float = match varargs.get(index, &mut ap, Some((arg.fmtkind, arg.intkind))) { + let float = match unsafe { + varargs.get(index, &mut ap, Some((arg.fmtkind, arg.intkind))) + } { VaArg::c_double(i) => i, _ => panic!("this should not be possible"), }; @@ -864,7 +875,9 @@ pub(crate) unsafe fn inner_printf( } } FmtKind::Decimal => { - let float = match varargs.get(index, &mut ap, Some((arg.fmtkind, arg.intkind))) { + let float = match unsafe { + varargs.get(index, &mut ap, Some((arg.fmtkind, arg.intkind))) + } { VaArg::c_double(i) => i, _ => panic!("this should not be possible"), }; @@ -877,7 +890,9 @@ pub(crate) unsafe fn inner_printf( } } FmtKind::AnyNotation => { - let float = match varargs.get(index, &mut ap, Some((arg.fmtkind, arg.intkind))) { + let float = match unsafe { + varargs.get(index, &mut ap, Some((arg.fmtkind, arg.intkind))) + } { VaArg::c_double(i) => i, _ => panic!("this should not be possible"), }; @@ -909,7 +924,9 @@ pub(crate) unsafe fn inner_printf( } } FmtKind::String => { - let ptr = match varargs.get(index, &mut ap, Some((arg.fmtkind, arg.intkind))) { + let ptr = match unsafe { + varargs.get(index, &mut ap, Some((arg.fmtkind, arg.intkind))) + } { VaArg::pointer(p) => p, _ => panic!("this should not be possible"), } as *const c_char; @@ -924,8 +941,8 @@ pub(crate) unsafe fn inner_printf( let mut ptr = ptr as *const wchar_t; let mut string = String::new(); - while *ptr != 0 { - let c = match char::from_u32(*ptr as _) { + while unsafe { *ptr } != 0 { + let c = match char::from_u32(unsafe { *ptr } as _) { Some(c) => c, None => { platform::ERRNO.set(EILSEQ); @@ -936,7 +953,7 @@ pub(crate) unsafe fn inner_printf( break; } string.push(c); - ptr = ptr.add(1); + ptr = unsafe { ptr.add(1) }; } pad(w, !left, b' ', string.len()..pad_space)?; @@ -944,40 +961,44 @@ pub(crate) unsafe fn inner_printf( pad(w, left, b' ', string.len()..pad_space)?; } else { let mut len = 0; - while *ptr.add(len) != 0 && len < max { + while unsafe { *ptr.add(len) } != 0 && len < max { len += 1; } pad(w, !left, b' ', len..pad_space)?; - w.write_all(slice::from_raw_parts(ptr as *const u8, len))?; + w.write_all(unsafe { slice::from_raw_parts(ptr as *const u8, len) })?; pad(w, left, b' ', len..pad_space)?; } } } - FmtKind::Char => match varargs.get(index, &mut ap, Some((arg.fmtkind, arg.intkind))) { - VaArg::c_char(c) => { - pad(w, !left, b' ', 1..pad_space)?; - w.write_all(&[c as u8])?; - pad(w, left, b' ', 1..pad_space)?; - } - VaArg::wint_t(c) => { - let c = match char::from_u32(c as _) { - Some(c) => c, - None => { - platform::ERRNO.set(EILSEQ); - return Err(io::last_os_error()); - } - }; - let mut buf = [0; 4]; + FmtKind::Char => { + match unsafe { varargs.get(index, &mut ap, Some((arg.fmtkind, arg.intkind))) } { + VaArg::c_char(c) => { + pad(w, !left, b' ', 1..pad_space)?; + w.write_all(&[c as u8])?; + pad(w, left, b' ', 1..pad_space)?; + } + VaArg::wint_t(c) => { + let c = match char::from_u32(c as _) { + Some(c) => c, + None => { + platform::ERRNO.set(EILSEQ); + return Err(io::last_os_error()); + } + }; + let mut buf = [0; 4]; - pad(w, !left, b' ', 1..pad_space)?; - w.write_all(c.encode_utf8(&mut buf).as_bytes())?; - pad(w, left, b' ', 1..pad_space)?; + pad(w, !left, b' ', 1..pad_space)?; + w.write_all(c.encode_utf8(&mut buf).as_bytes())?; + pad(w, left, b' ', 1..pad_space)?; + } + _ => unreachable!("this should not be possible"), } - _ => unreachable!("this should not be possible"), - }, + } FmtKind::Pointer => { - let ptr = match varargs.get(index, &mut ap, Some((arg.fmtkind, arg.intkind))) { + let ptr = match unsafe { + varargs.get(index, &mut ap, Some((arg.fmtkind, arg.intkind))) + } { VaArg::pointer(p) => p, _ => panic!("this should not be possible"), }; @@ -1002,20 +1023,26 @@ pub(crate) unsafe fn inner_printf( pad(w, left, b' ', len..pad_space)?; } FmtKind::GetWritten => { - let ptr = match varargs.get(index, &mut ap, Some((arg.fmtkind, arg.intkind))) { + let ptr = match unsafe { + varargs.get(index, &mut ap, Some((arg.fmtkind, arg.intkind))) + } { VaArg::pointer(p) => p, _ => panic!("this should not be possible"), }; match intkind { - IntKind::Byte => *(ptr as *mut c_char) = w.written as c_char, - IntKind::Short => *(ptr as *mut c_short) = w.written as c_short, - IntKind::Int => *(ptr as *mut c_int) = w.written as c_int, - IntKind::Long => *(ptr as *mut c_long) = w.written as c_long, - IntKind::LongLong => *(ptr as *mut c_longlong) = w.written as c_longlong, - IntKind::IntMax => *(ptr as *mut intmax_t) = w.written as intmax_t, - IntKind::PtrDiff => *(ptr as *mut ptrdiff_t) = w.written as ptrdiff_t, - IntKind::Size => *(ptr as *mut size_t) = w.written as size_t, + IntKind::Byte => unsafe { *(ptr as *mut c_char) = w.written as c_char }, + IntKind::Short => unsafe { *(ptr as *mut c_short) = w.written as c_short }, + IntKind::Int => unsafe { *(ptr as *mut c_int) = w.written as c_int }, + IntKind::Long => unsafe { *(ptr as *mut c_long) = w.written as c_long }, + IntKind::LongLong => unsafe { + *(ptr as *mut c_longlong) = w.written as c_longlong + }, + IntKind::IntMax => unsafe { *(ptr as *mut intmax_t) = w.written as intmax_t }, + IntKind::PtrDiff => unsafe { + *(ptr as *mut ptrdiff_t) = w.written as ptrdiff_t + }, + IntKind::Size => unsafe { *(ptr as *mut size_t) = w.written as size_t }, } } } @@ -1292,5 +1319,5 @@ pub(crate) unsafe fn inner_printf( /// Behavior is undefined if any of the following conditions are violated: /// - `ap` must follow the safety contract of variable arguments of C. pub unsafe fn printf(w: impl Write, format: CStr, ap: VaList) -> c_int { - inner_printf::(w, format, ap).unwrap_or(-1) + unsafe { inner_printf::(w, format, ap).unwrap_or(-1) } } diff --git a/src/header/stdio/scanf.rs b/src/header/stdio/scanf.rs index 84c37b4712..02a2fd8461 100644 --- a/src/header/stdio/scanf.rs +++ b/src/header/stdio/scanf.rs @@ -17,8 +17,8 @@ enum IntKind { /// Helper function for progressing a C string unsafe fn next_byte(string: &mut *const c_char) -> Result { - let c = **string as u8; - *string = string.offset(1); + let c = unsafe { **string } as u8; + *string = unsafe { string.offset(1) }; if c == 0 { Err(-1) } else { Ok(c) } } @@ -67,8 +67,8 @@ unsafe fn inner_scanf( } } - while *format != 0 { - let mut c = next_byte(&mut format)?; + while unsafe { *format } != 0 { + let mut c = unsafe { next_byte(&mut format) }?; if c == b' ' { maybe_read!(noreset); @@ -87,18 +87,18 @@ unsafe fn inner_scanf( } r.commit(); } else { - c = next_byte(&mut format)?; + c = unsafe { next_byte(&mut format) }?; let mut ignore = false; if c == b'*' { ignore = true; - c = next_byte(&mut format)?; + c = unsafe { next_byte(&mut format) }?; } let mut width = String::new(); while c >= b'0' && c <= b'9' { width.push(c as char); - c = next_byte(&mut format)?; + c = unsafe { next_byte(&mut format) }?; } let mut width = if width.is_empty() { None @@ -137,7 +137,7 @@ unsafe fn inner_scanf( _ => break, }; - c = next_byte(&mut format)?; + c = unsafe { next_byte(&mut format) }?; } if c != b'n' { @@ -231,7 +231,7 @@ unsafe fn inner_scanf( n.parse::<$type>().map_err(|_| 0)? }; if !ignore { - *ap.arg::<*mut $type>() = n; + unsafe { *ap.arg::<*mut $type>() = n }; matched += 1; } }}; @@ -251,7 +251,7 @@ unsafe fn inner_scanf( $type::from_str_radix(&n, radix).map_err(|_| 0)? }; if !ignore { - *ap.arg::<*mut $final>() = n as $final; + unsafe { *ap.arg::<*mut $final>() = n as $final}; matched += 1; } }}; @@ -329,12 +329,16 @@ unsafe fn inner_scanf( } } - let mut ptr: Option<*mut c_char> = if ignore { None } else { Some(ap.arg()) }; + let mut ptr: Option<*mut c_char> = if ignore { + None + } else { + Some(unsafe { ap.arg() }) + }; while width.map(|w| w > 0).unwrap_or(true) && !(byte as char).is_whitespace() { if let Some(ref mut ptr) = ptr { - **ptr = byte as c_char; - *ptr = ptr.offset(1); + unsafe { **ptr = byte as c_char }; + *ptr = unsafe { ptr.offset(1) }; } width = width.map(|w| w - 1); if width.map(|w| w > 0).unwrap_or(true) && !read!() { @@ -344,17 +348,21 @@ unsafe fn inner_scanf( } if let Some(ptr) = ptr { - *ptr = 0; + unsafe { *ptr = 0 }; matched += 1; r.commit(); } } b'c' => { - let ptr: Option<*mut c_char> = if ignore { None } else { Some(ap.arg()) }; + let ptr: Option<*mut c_char> = if ignore { + None + } else { + Some(unsafe { ap.arg() }) + }; for i in 0..width.unwrap_or(1) { if let Some(ptr) = ptr { - *ptr.add(i) = byte as c_char; + unsafe { *ptr.add(i) = byte as c_char }; } width = width.map(|w| w - 1); if width.map(|w| w > 0).unwrap_or(true) && !read!() { @@ -369,11 +377,11 @@ unsafe fn inner_scanf( } } b'[' => { - c = next_byte(&mut format)?; + c = unsafe { next_byte(&mut format) }?; let mut matches = Vec::new(); let invert = if c == b'^' { - c = next_byte(&mut format)?; + c = unsafe { next_byte(&mut format) }?; true } else { false @@ -383,12 +391,12 @@ unsafe fn inner_scanf( loop { matches.push(c); prev = c; - c = next_byte(&mut format)?; + c = unsafe { next_byte(&mut format) }?; if c == b'-' { if prev == b']' { continue; } - c = next_byte(&mut format)?; + c = unsafe { next_byte(&mut format) }?; if c == b']' { matches.push(b'-'); break; @@ -403,15 +411,19 @@ unsafe fn inner_scanf( } } - let mut ptr: Option<*mut c_char> = if ignore { None } else { Some(ap.arg()) }; + let mut ptr: Option<*mut c_char> = if ignore { + None + } else { + Some(unsafe { ap.arg() }) + }; // While we haven't used up all the width, and it matches let mut data_stored = false; while width.map(|w| w > 0).unwrap_or(true) && !invert == matches.contains(&byte) { if let Some(ref mut ptr) = ptr { - **ptr = byte as c_char; - *ptr = ptr.offset(1); + unsafe { **ptr = byte as c_char }; + *ptr = unsafe { ptr.offset(1) }; data_stored = true; } r.commit(); @@ -426,13 +438,13 @@ unsafe fn inner_scanf( } if data_stored { - *ptr.unwrap() = 0; + unsafe { *ptr.unwrap() = 0 }; matched += 1; } } b'n' => { if !ignore { - *ap.arg::<*mut c_int>() = count as c_int; + unsafe { *ap.arg::<*mut c_int>() = count as c_int }; } } _ => return Err(-1), @@ -453,7 +465,7 @@ unsafe fn inner_scanf( } pub unsafe fn scanf(r: LookAheadReader, format: *const c_char, ap: va_list) -> c_int { - match inner_scanf(r, format, ap) { + match unsafe { inner_scanf(r, format, ap) } { Ok(n) => n, Err(n) => n, }