From d539b134ef659c1dcd0cfbfe5c871be539de8afb Mon Sep 17 00:00:00 2001 From: sourceturner <126549-sourceturner@users.noreply.gitlab.redox-os.org> Date: Fri, 16 Jan 2026 21:54:04 +0100 Subject: [PATCH 01/11] Use unsafe blocks in float.h implementation --- src/header/float/mod.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/header/float/mod.rs b/src/header/float/mod.rs index 4c989e7961..52c36df8d8 100644 --- a/src/header/float/mod.rs +++ b/src/header/float/mod.rs @@ -2,6 +2,9 @@ //! //! See . +// TODO: set this for entire crate when possible +#![deny(unsafe_op_in_unsafe_fn)] + use crate::{ header::_fenv::{FE_TONEAREST, fegetround}, platform::types::c_int, @@ -13,7 +16,7 @@ pub const FLT_RADIX: c_int = 2; /// See . #[unsafe(no_mangle)] pub unsafe extern "C" fn flt_rounds() -> c_int { - match fegetround() { + match unsafe { fegetround() } { FE_TONEAREST => 1, _ => -1, } From 12807920b65e23cb3778d6d0f6757b98ca30ad5b Mon Sep 17 00:00:00 2001 From: sourceturner <126549-sourceturner@users.noreply.gitlab.redox-os.org> Date: Fri, 16 Jan 2026 22:01:00 +0100 Subject: [PATCH 02/11] Use unsafe blocks in ifaddrs.h implementation --- src/header/ifaddrs/mod.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/header/ifaddrs/mod.rs b/src/header/ifaddrs/mod.rs index 3df9df0244..5e59e8b9ad 100644 --- a/src/header/ifaddrs/mod.rs +++ b/src/header/ifaddrs/mod.rs @@ -1,5 +1,8 @@ //! `ifaddrs.h` implementation +// TODO: set this for entire crate when possible +#![deny(unsafe_op_in_unsafe_fn)] + use core::ptr; use crate::{ @@ -27,8 +30,8 @@ pub struct ifaddrs { #[unsafe(no_mangle)] pub unsafe extern "C" fn freeifaddrs(mut ifa: *mut ifaddrs) { while !ifa.is_null() { - let next = (*ifa).ifa_next; - stdlib::free(ifa.cast()); + let next = unsafe { (*ifa).ifa_next }; + unsafe { stdlib::free(ifa.cast()) }; ifa = next; } } From 827df02158d1997f46b686984035233e8f385c90 Mon Sep 17 00:00:00 2001 From: sourceturner <126549-sourceturner@users.noreply.gitlab.redox-os.org> Date: Fri, 16 Jan 2026 22:02:18 +0100 Subject: [PATCH 03/11] Use unsafe blocks in locale.h implementation --- src/header/locale/mod.rs | 43 +++++++++++++++++++++++----------------- 1 file changed, 25 insertions(+), 18 deletions(-) diff --git a/src/header/locale/mod.rs b/src/header/locale/mod.rs index 0e064d888e..696b26995d 100644 --- a/src/header/locale/mod.rs +++ b/src/header/locale/mod.rs @@ -2,6 +2,9 @@ //! //! See . +// TODO: set this for entire crate when possible +#![deny(unsafe_op_in_unsafe_fn)] + use alloc::{boxed::Box, ffi::CString, string::String}; use core::{ptr, str::FromStr}; @@ -38,28 +41,28 @@ static mut THREAD_LOCALE: *mut LocaleData = ptr::null_mut(); /// See . #[unsafe(no_mangle)] pub unsafe extern "C" fn localeconv() -> *mut lconv { - let current = uselocale(ptr::null_mut()); + let current = unsafe { uselocale(ptr::null_mut()) }; if current == LC_GLOBAL_LOCALE || current.is_null() { - if !GLOBAL_LOCALE.is_null() { + if !unsafe { GLOBAL_LOCALE.is_null() } { // safety: GLOBAL_LOCALE is never set to null again - &raw mut (*GLOBAL_LOCALE).data.lconv + unsafe { &raw mut (*GLOBAL_LOCALE).data.lconv } } else { &raw mut POSIX_LOCALE } } else { let current = current as *mut LocaleData; - &raw mut (*current).lconv + unsafe { &raw mut (*current).lconv } } } /// See . #[unsafe(no_mangle)] pub unsafe extern "C" fn setlocale(category: c_int, locale: *const c_char) -> *mut c_char { - if GLOBAL_LOCALE.is_null() { + if unsafe { GLOBAL_LOCALE.is_null() } { let new_global = GlobalLocaleData::new(); - GLOBAL_LOCALE = Box::into_raw(new_global); + unsafe { GLOBAL_LOCALE = Box::into_raw(new_global) }; }; - let Some(mut global) = GLOBAL_LOCALE.as_mut() else { + let Some(mut global) = (unsafe { GLOBAL_LOCALE.as_mut() }) else { return ptr::null_mut(); }; @@ -70,7 +73,7 @@ pub unsafe extern "C" fn setlocale(category: c_int, locale: *const c_char) -> *m return name.as_ptr() as *mut c_char; } - let name = CStr::from_ptr(locale).to_str().unwrap_or("C"); + let name = unsafe { CStr::from_ptr(locale).to_str().unwrap_or("C") }; let locale_file = if name == "" || name == "C" || name == "POSIX" { // TODO: name == "" should read from LANG env @@ -94,17 +97,19 @@ pub unsafe extern "C" fn setlocale(category: c_int, locale: *const c_char) -> *m /// See . #[unsafe(no_mangle)] pub unsafe extern "C" fn uselocale(newloc: locale_t) -> locale_t { - let old_loc = if THREAD_LOCALE.is_null() { + let old_loc = if unsafe { THREAD_LOCALE.is_null() } { LC_GLOBAL_LOCALE } else { - THREAD_LOCALE as locale_t + (unsafe { THREAD_LOCALE }) as locale_t }; if !newloc.is_null() { - THREAD_LOCALE = if newloc == LC_GLOBAL_LOCALE { - ptr::null_mut() - } else { - newloc as *mut LocaleData + unsafe { + THREAD_LOCALE = if newloc == LC_GLOBAL_LOCALE { + ptr::null_mut() + } else { + newloc as *mut LocaleData + } }; } @@ -114,7 +119,9 @@ pub unsafe extern "C" fn uselocale(newloc: locale_t) -> locale_t { /// See . #[unsafe(no_mangle)] pub unsafe extern "C" fn newlocale(mask: c_int, locale: *const c_char, base: locale_t) -> locale_t { - let name = CStr::from_ptr(locale).to_string_lossy().into_owned(); + let name = unsafe { CStr::from_ptr(locale) } + .to_string_lossy() + .into_owned(); let name = name.as_str(); let mut new_locale = if name == "" || name == "C" || name == "POSIX" { // TODO: name == "" should read from LANG env @@ -126,7 +133,7 @@ pub unsafe extern "C" fn newlocale(mask: c_int, locale: *const c_char, base: loc // borrowing here let base = base as *const _ as *const LocaleData; if let Ok(new_locale) = new_locale.as_mut() { - if let Some(base) = base.as_ref() { + if let Some(base) = unsafe { base.as_ref() } { // copy old values if not containing the mask if (mask & LC_NUMERIC_MASK) == 0 { new_locale.copy_category(base, LC_NUMERIC); @@ -145,7 +152,7 @@ pub unsafe extern "C" fn newlocale(mask: c_int, locale: *const c_char, base: loc #[unsafe(no_mangle)] pub unsafe extern "C" fn freelocale(loc: locale_t) { if !loc.is_null() && loc != LC_GLOBAL_LOCALE { - drop(Box::from_raw(loc as *mut LocaleData)); + drop(unsafe { Box::from_raw(loc as *mut LocaleData) }); } } @@ -160,7 +167,7 @@ pub unsafe extern "C" fn duplocale(loc: locale_t) -> locale_t { } else { // borrowing here let loc = loc as *const _ as *const LocaleData; - Box::into_raw(Box::from((*loc).clone())) as locale_t + Box::into_raw(unsafe { Box::from((*loc).clone()) }) as locale_t } } From a27518ef2fba4452d40d46a8856af52c10204c33 Mon Sep 17 00:00:00 2001 From: sourceturner <126549-sourceturner@users.noreply.gitlab.redox-os.org> Date: Fri, 16 Jan 2026 22:03:17 +0100 Subject: [PATCH 04/11] Use unsafe blocks in malloc.h implementation --- src/header/malloc/mod.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/header/malloc/mod.rs b/src/header/malloc/mod.rs index 54977f414b..c3a04d930b 100644 --- a/src/header/malloc/mod.rs +++ b/src/header/malloc/mod.rs @@ -2,6 +2,9 @@ //! //! Non-POSIX, see . +// TODO: set this for entire crate when possible +#![deny(unsafe_op_in_unsafe_fn)] + use crate::{ header::errno::ENOMEM, platform::{ @@ -28,7 +31,7 @@ pub unsafe extern "C" fn pvalloc(size: size_t) -> *mut c_void { match num_pages.checked_mul(page_size) { Some(alloc_size) => { - let ptr = platform::alloc_align(alloc_size, page_size); + let ptr = unsafe { platform::alloc_align(alloc_size, page_size) }; if ptr.is_null() { platform::ERRNO.set(ENOMEM); } @@ -44,5 +47,5 @@ pub unsafe extern "C" fn pvalloc(size: size_t) -> *mut c_void { /// See . #[unsafe(no_mangle)] pub unsafe extern "C" fn malloc_usable_size(ptr: *mut c_void) -> size_t { - platform::alloc_usable_size(ptr) + unsafe { platform::alloc_usable_size(ptr) } } From c22fa8af96dba44a16635e56dadaaf2310d5c2be Mon Sep 17 00:00:00 2001 From: sourceturner <126549-sourceturner@users.noreply.gitlab.redox-os.org> Date: Fri, 16 Jan 2026 22:05:48 +0100 Subject: [PATCH 05/11] Use unsafe blocks in net_if.h implementation --- src/header/net_if/mod.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/header/net_if/mod.rs b/src/header/net_if/mod.rs index 1798b9fe5c..beaf2f5a29 100644 --- a/src/header/net_if/mod.rs +++ b/src/header/net_if/mod.rs @@ -2,6 +2,9 @@ //! //! See . +// TODO: set this for entire crate when possible +#![deny(unsafe_op_in_unsafe_fn)] + use core::ptr::null; use alloc::ffi::CString; @@ -81,7 +84,7 @@ pub unsafe extern "C" fn if_nametoindex(name: *const c_char) -> c_uint { if name == null::() { return 0; } - let name = CStr::from_ptr(name).to_str().unwrap_or(""); + let name = unsafe { CStr::from_ptr(name).to_str().unwrap_or("") }; if name.eq("stub") { return 1; } From 23fb2dd042d452a04d62f7f8f852db4ea86c872c Mon Sep 17 00:00:00 2001 From: sourceturner <126549-sourceturner@users.noreply.gitlab.redox-os.org> Date: Fri, 16 Jan 2026 22:11:28 +0100 Subject: [PATCH 06/11] Use unsafe blocks in pwd.h implementation --- src/header/pwd/mod.rs | 61 ++++++++++++++++++++++++------------------- 1 file changed, 34 insertions(+), 27 deletions(-) diff --git a/src/header/pwd/mod.rs b/src/header/pwd/mod.rs index 20322d6178..8d0a71a8ea 100644 --- a/src/header/pwd/mod.rs +++ b/src/header/pwd/mod.rs @@ -2,6 +2,9 @@ //! //! See . +// TODO: set this for entire crate when possible +#![deny(unsafe_op_in_unsafe_fn)] + use alloc::{boxed::Box, vec::Vec}; use core::{ ops::{Deref, DerefMut}, @@ -211,16 +214,16 @@ unsafe fn mux( ) -> c_int { match status { Ok(owned) => { - *out = owned.reference; - *result = out; + unsafe { *out = owned.reference }; + unsafe { *result = out }; 0 } Err(Cause::Eof) => { - *result = ptr::null_mut(); + unsafe { *result = ptr::null_mut() }; 0 } Err(Cause::Other) => { - *result = ptr::null_mut(); + unsafe { *result = ptr::null_mut() }; -1 } } @@ -273,17 +276,19 @@ pub unsafe extern "C" fn getpwnam_r( size: size_t, result: *mut *mut passwd, ) -> c_int { - mux( - pwd_lookup( - |parts| strcmp(parts.pw_name, name) == 0, - Some(DestBuffer { - ptr: buf as *mut u8, - len: size, - }), - ), - out, - result, - ) + unsafe { + mux( + pwd_lookup( + |parts| strcmp(parts.pw_name, name) == 0, + Some(DestBuffer { + ptr: buf as *mut u8, + len: size, + }), + ), + out, + result, + ) + } } /// See . @@ -303,18 +308,20 @@ pub unsafe extern "C" fn getpwuid_r( size: size_t, result: *mut *mut passwd, ) -> c_int { - let slice = core::slice::from_raw_parts_mut(buf as *mut u8, size); - mux( - pwd_lookup( - |part| part.pw_uid == uid, - Some(DestBuffer { - ptr: buf as *mut u8, - len: size, - }), - ), - out, - result, - ) + let slice = unsafe { core::slice::from_raw_parts_mut(buf as *mut u8, size) }; + unsafe { + mux( + pwd_lookup( + |part| part.pw_uid == uid, + Some(DestBuffer { + ptr: buf as *mut u8, + len: size, + }), + ), + out, + result, + ) + } } /// See . From 2e055a6d98b286e5625c97e69bdfbc4ae4757824 Mon Sep 17 00:00:00 2001 From: sourceturner <126549-sourceturner@users.noreply.gitlab.redox-os.org> Date: Fri, 16 Jan 2026 22:12:09 +0100 Subject: [PATCH 07/11] Use unsafe blocks in regex.h implementation --- src/header/regex/mod.rs | 31 +++++++++++++++++++------------ 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/src/header/regex/mod.rs b/src/header/regex/mod.rs index 4127fa6f06..9b4c37ffaa 100644 --- a/src/header/regex/mod.rs +++ b/src/header/regex/mod.rs @@ -2,6 +2,9 @@ //! //! See . +// TODO: set this for entire crate when possible +#![deny(unsafe_op_in_unsafe_fn)] + use crate::{ header::string::strlen, platform::types::{c_char, c_int, c_void, size_t}, @@ -55,7 +58,7 @@ pub const REG_BADRPT: c_int = 14; #[unsafe(no_mangle)] #[linkage = "weak"] // redefined in GIT pub unsafe extern "C" fn regcomp(out: *mut regex_t, pat: *const c_char, cflags: c_int) -> c_int { - let pat = slice::from_raw_parts(pat as *const u8, strlen(pat)); + let pat = unsafe { slice::from_raw_parts(pat as *const u8, strlen(pat)) }; let res = PosixRegexBuilder::new(pat) .with_default_classes() .extended(cflags & REG_EXTENDED == REG_EXTENDED) @@ -64,11 +67,13 @@ pub unsafe extern "C" fn regcomp(out: *mut regex_t, pat: *const c_char, cflags: match res { Ok(mut branches) => { let re_nsub = PosixRegex::new(Cow::Borrowed(&branches)).count_groups(); - *out = regex_t { - ptr: Box::into_raw(Box::new(branches)) as *mut c_void, + unsafe { + *out = regex_t { + ptr: Box::into_raw(Box::new(branches)) as *mut c_void, - cflags, - re_nsub, + cflags, + re_nsub, + } }; 0 } @@ -87,7 +92,7 @@ pub unsafe extern "C" fn regcomp(out: *mut regex_t, pat: *const c_char, cflags: #[unsafe(no_mangle)] #[linkage = "weak"] // redefined in GIT pub unsafe extern "C" fn regfree(regex: *mut regex_t) { - Box::from_raw((*regex).ptr); + unsafe { Box::from_raw((*regex).ptr) }; } /// See . @@ -100,14 +105,14 @@ pub unsafe extern "C" fn regexec( pmatch: *mut regmatch_t, eflags: c_int, ) -> c_int { - let regex = &*regex; + let regex = unsafe { &*regex }; // Allow specifying a compiler argument to the executor and viceversa // because why not? let flags = regex.cflags | eflags; - let input = slice::from_raw_parts(input as *const u8, strlen(input)); - let branches = &*(regex.ptr as *mut Tree); + let input = unsafe { slice::from_raw_parts(input as *const u8, strlen(input)) }; + let branches = unsafe { &*(regex.ptr as *mut Tree) }; let matches = PosixRegex::new(Cow::Borrowed(&branches)) .case_insensitive(flags & REG_ICASE == REG_ICASE) @@ -121,9 +126,11 @@ pub unsafe extern "C" fn regexec( for i in 0..nmatch { let (start, end) = first.get(i).and_then(|&range| range).unwrap_or((!0, !0)); - *pmatch.add(i) = regmatch_t { - rm_so: start, - rm_eo: end, + unsafe { + *pmatch.add(i) = regmatch_t { + rm_so: start, + rm_eo: end, + } }; } } From a426887528dbb76a3f216aea48b89fa0a24e41b4 Mon Sep 17 00:00:00 2001 From: sourceturner <126549-sourceturner@users.noreply.gitlab.redox-os.org> Date: Fri, 16 Jan 2026 22:13:10 +0100 Subject: [PATCH 08/11] Use unsafe blocks in semaphore.h implementation --- src/header/semaphore/mod.rs | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/src/header/semaphore/mod.rs b/src/header/semaphore/mod.rs index 77006f134e..f9e3b1778e 100644 --- a/src/header/semaphore/mod.rs +++ b/src/header/semaphore/mod.rs @@ -2,6 +2,9 @@ //! //! See . +// TODO: set this for entire crate when possible +#![deny(unsafe_op_in_unsafe_fn)] + use crate::{ header::time::{CLOCK_MONOTONIC, CLOCK_REALTIME, timespec}, platform::types::{c_char, c_int, c_long, c_uint, clockid_t}, @@ -26,14 +29,14 @@ pub unsafe extern "C" fn sem_close(sem: *mut sem_t) -> c_int { /// See . #[unsafe(no_mangle)] pub unsafe extern "C" fn sem_destroy(sem: *mut sem_t) -> c_int { - core::ptr::drop_in_place(sem.cast::()); + unsafe { core::ptr::drop_in_place(sem.cast::()) }; 0 } /// See . #[unsafe(no_mangle)] pub unsafe extern "C" fn sem_getvalue(sem: *mut sem_t, sval: *mut c_int) -> c_int { - sval.write(get(sem).value() as c_int); + unsafe { sval.write(get(sem).value() as c_int) }; 0 } @@ -41,7 +44,7 @@ pub unsafe extern "C" fn sem_getvalue(sem: *mut sem_t, sval: *mut c_int) -> c_in /// See . #[unsafe(no_mangle)] pub unsafe extern "C" fn sem_init(sem: *mut sem_t, _pshared: c_int, value: c_uint) -> c_int { - sem.cast::().write(RlctSempahore::new(value)); + unsafe { sem.cast::().write(RlctSempahore::new(value)) }; 0 } @@ -59,7 +62,7 @@ pub unsafe extern "C" fn sem_open( /// See . #[unsafe(no_mangle)] pub unsafe extern "C" fn sem_post(sem: *mut sem_t) -> c_int { - get(sem).post(1); + unsafe { get(sem) }.post(1); 0 } @@ -67,7 +70,7 @@ pub unsafe extern "C" fn sem_post(sem: *mut sem_t) -> c_int { /// See . #[unsafe(no_mangle)] pub unsafe extern "C" fn sem_trywait(sem: *mut sem_t) -> c_int { - get(sem).try_wait(); + unsafe { get(sem) }.try_wait(); 0 } @@ -81,7 +84,7 @@ pub unsafe extern "C" fn sem_unlink(name: *const c_char) -> c_int { /// See . #[unsafe(no_mangle)] pub unsafe extern "C" fn sem_wait(sem: *mut sem_t) -> c_int { - get(sem).wait(None, CLOCK_MONOTONIC); + unsafe { get(sem) }.wait(None, CLOCK_MONOTONIC); 0 } @@ -93,7 +96,7 @@ pub unsafe extern "C" fn sem_clockwait( clock_id: clockid_t, abstime: *const timespec, ) -> c_int { - get(sem).wait(Some(&*abstime), clock_id); + unsafe { get(sem) }.wait(Some(&unsafe { *abstime }), clock_id); 0 } @@ -101,11 +104,11 @@ pub unsafe extern "C" fn sem_clockwait( /// See . #[unsafe(no_mangle)] pub unsafe extern "C" fn sem_timedwait(sem: *mut sem_t, abstime: *const timespec) -> c_int { - get(sem).wait(Some(&*abstime), CLOCK_REALTIME); + unsafe { get(sem) }.wait(Some(&unsafe { *abstime }), CLOCK_REALTIME); 0 } unsafe fn get<'any>(sem: *mut sem_t) -> &'any RlctSempahore { - &*sem.cast() + unsafe { &*sem.cast() } } From b3add2465467dfecef62d62de8337fa0b0d0eece Mon Sep 17 00:00:00 2001 From: sourceturner <126549-sourceturner@users.noreply.gitlab.redox-os.org> Date: Fri, 16 Jan 2026 22:14:06 +0100 Subject: [PATCH 09/11] Use unsafe blocks in signal.h implementation --- src/header/signal/mod.rs | 131 +++++++++++++++++++++------------------ 1 file changed, 71 insertions(+), 60 deletions(-) diff --git a/src/header/signal/mod.rs b/src/header/signal/mod.rs index 63a02cf577..e773350958 100644 --- a/src/header/signal/mod.rs +++ b/src/header/signal/mod.rs @@ -2,6 +2,9 @@ //! //! See . +// TODO: set this for entire crate when possible +#![deny(unsafe_op_in_unsafe_fn)] + use core::{arch::global_asm, mem, ptr}; use cbitset::BitSet; @@ -141,16 +144,16 @@ unsafe extern "C" { unsafe extern "C" fn __sigsetjmp_tail(jb: *mut u64, ret: i32) -> i32 { let set = jb.wrapping_add(9); if ret > 0 { - sigprocmask(SIG_SETMASK, set, ptr::null_mut()); + unsafe { sigprocmask(SIG_SETMASK, set, ptr::null_mut()) }; } else { - sigprocmask(SIG_SETMASK, ptr::null_mut(), set); + unsafe { sigprocmask(SIG_SETMASK, ptr::null_mut(), set) }; } ret } #[unsafe(no_mangle)] pub unsafe extern "C" fn siglongjmp(jb: *mut u64, ret: i32) { - setjmp::longjmp(jb, ret); + unsafe { setjmp::longjmp(jb, ret) }; } /// See . @@ -177,10 +180,10 @@ pub extern "C" fn killpg(pgrp: pid_t, sig: c_int) -> c_int { #[unsafe(no_mangle)] pub unsafe extern "C" fn pthread_kill(thread: pthread_t, sig: c_int) -> c_int { let os_tid = { - let pthread = &*(thread as *const crate::pthread::Pthread); - pthread.os_tid.get().read() + let pthread = unsafe { &*(thread as *const crate::pthread::Pthread) }; + unsafe { pthread.os_tid.get().read() } }; - crate::header::pthread::e(Sys::rlct_kill(os_tid, sig as usize)) + crate::header::pthread::e(unsafe { Sys::rlct_kill(os_tid, sig as usize) }) } /// See . @@ -191,7 +194,7 @@ pub unsafe extern "C" fn pthread_sigmask( oldset: *mut sigset_t, ) -> c_int { // On Linux and Redox, pthread_sigmask and sigprocmask are equivalent - if sigprocmask(how, set, oldset) == 0 { + if unsafe { sigprocmask(how, set, oldset) } == 0 { 0 } else { //TODO: Fix race @@ -212,7 +215,7 @@ pub unsafe extern "C" fn sigaction( act: *const sigaction, oact: *mut sigaction, ) -> c_int { - Sys::sigaction(sig, act.as_ref(), oact.as_mut()) + Sys::sigaction(sig, unsafe { act.as_ref() }, unsafe { oact.as_mut() }) .map(|()| 0) .or_minus_one_errno() } @@ -236,9 +239,11 @@ pub unsafe extern "C" fn sigaddset(set: *mut sigset_t, signo: c_int) -> c_int { /// See . #[unsafe(no_mangle)] pub unsafe extern "C" fn sigaltstack(ss: *const stack_t, old_ss: *mut stack_t) -> c_int { - Sys::sigaltstack(ss.as_ref(), old_ss.as_mut()) - .map(|()| 0) - .or_minus_one_errno() + unsafe { + Sys::sigaltstack(ss.as_ref(), old_ss.as_mut()) + .map(|()| 0) + .or_minus_one_errno() + } } /// See . @@ -260,7 +265,7 @@ pub unsafe extern "C" fn sigdelset(set: *mut sigset_t, signo: c_int) -> c_int { /// See . #[unsafe(no_mangle)] pub unsafe extern "C" fn sigemptyset(set: *mut sigset_t) -> c_int { - if let Some(set) = (set as *mut SigSet).as_mut() { + if let Some(set) = unsafe { (set as *mut SigSet).as_mut() } { set.clear(); } 0 @@ -269,7 +274,7 @@ pub unsafe extern "C" fn sigemptyset(set: *mut sigset_t) -> c_int { /// See . #[unsafe(no_mangle)] pub unsafe extern "C" fn sigfillset(set: *mut sigset_t) -> c_int { - if let Some(set) = (set as *mut SigSet).as_mut() { + if let Some(set) = unsafe { (set as *mut SigSet).as_mut() } { set.fill(.., true); } 0 @@ -285,10 +290,10 @@ pub unsafe extern "C" fn sighold(sig: c_int) -> c_int { let mut pset = mem::MaybeUninit::::uninit(); unsafe { sigemptyset(pset.as_mut_ptr()) }; let mut set = unsafe { pset.assume_init() }; - if sigaddset(&mut set, sig) < 0 { + if unsafe { sigaddset(&mut set, sig) } < 0 { return -1; } - sigprocmask(SIG_BLOCK, &set, ptr::null_mut()) + unsafe { sigprocmask(SIG_BLOCK, &set, ptr::null_mut()) } } /// See . @@ -367,18 +372,18 @@ pub extern "C" fn signal( #[unsafe(no_mangle)] pub unsafe extern "C" fn sigpause(sig: c_int) -> c_int { let mut pset = mem::MaybeUninit::::uninit(); - sigprocmask(0, ptr::null_mut(), pset.as_mut_ptr()); - let mut set = pset.assume_init(); - if sigdelset(&mut set, sig) == -1 { + unsafe { sigprocmask(0, ptr::null_mut(), pset.as_mut_ptr()) }; + let mut set = unsafe { pset.assume_init() }; + if unsafe { sigdelset(&mut set, sig) } == -1 { return -1; } - sigsuspend(&set) + unsafe { sigsuspend(&set) } } /// See . #[unsafe(no_mangle)] pub unsafe extern "C" fn sigpending(set: *mut sigset_t) -> c_int { - (|| Sys::sigpending(set.as_mut().ok_or(Errno(EFAULT))?))() + (|| Sys::sigpending(unsafe { set.as_mut().ok_or(Errno(EFAULT)) }?))() .map(|()| 0) .or_minus_one_errno() } @@ -395,8 +400,8 @@ pub unsafe extern "C" fn sigprocmask( oset: *mut sigset_t, ) -> c_int { (|| { - let set = set.as_ref().map(|&block| block & !RLCT_SIGNAL_MASK); - let mut oset = oset.as_mut(); + let set = unsafe { set.as_ref().map(|&block| block & !RLCT_SIGNAL_MASK) }; + let mut oset = unsafe { oset.as_mut() }; Sys::sigprocmask( how, @@ -421,12 +426,12 @@ pub unsafe extern "C" fn sigprocmask( #[unsafe(no_mangle)] pub unsafe extern "C" fn sigrelse(sig: c_int) -> c_int { let mut pset = mem::MaybeUninit::::uninit(); - sigemptyset(pset.as_mut_ptr()); - let mut set = pset.assume_init(); - if sigaddset(&mut set, sig) < 0 { + unsafe { sigemptyset(pset.as_mut_ptr()) }; + let mut set = unsafe { pset.assume_init() }; + if unsafe { sigaddset(&mut set, sig) } < 0 { return -1; } - sigprocmask(SIG_UNBLOCK, &mut set, ptr::null_mut()) + unsafe { sigprocmask(SIG_UNBLOCK, &mut set, ptr::null_mut()) } } /// See . @@ -441,16 +446,16 @@ pub unsafe extern "C" fn sigset( ) -> Option { let mut old_sa = mem::MaybeUninit::uninit(); let mut pset = mem::MaybeUninit::::uninit(); - let sig_hold: Option = mem::transmute(SIG_HOLD); - let sig_err: Option = mem::transmute(SIG_ERR); - sigemptyset(pset.as_mut_ptr()); - let mut set = pset.assume_init(); - if sigaddset(&mut set, sig) < 0 { + let sig_hold: Option = unsafe { mem::transmute(SIG_HOLD) }; + let sig_err: Option = unsafe { mem::transmute(SIG_ERR) }; + unsafe { sigemptyset(pset.as_mut_ptr()) }; + let mut set = unsafe { pset.assume_init() }; + if unsafe { sigaddset(&mut set, sig) } < 0 { return sig_err; } else { if func == sig_hold { - if sigaction(sig, ptr::null_mut(), old_sa.as_mut_ptr()) < 0 - || sigprocmask(SIG_BLOCK, &mut set, &mut set) < 0 + if unsafe { sigaction(sig, ptr::null_mut(), old_sa.as_mut_ptr()) } < 0 + || unsafe { sigprocmask(SIG_BLOCK, &mut set, &mut set) } < 0 { mem::forget(old_sa); return sig_err; @@ -462,36 +467,36 @@ pub unsafe extern "C" fn sigset( sa_restorer: None, // set by platform if applicable sa_mask: sigset_t::default(), }; - sigemptyset(&mut sa.sa_mask); - if sigaction(sig, &sa, old_sa.as_mut_ptr()) < 0 - || sigprocmask(SIG_UNBLOCK, &mut set, &mut set) < 0 + unsafe { sigemptyset(&mut sa.sa_mask) }; + if unsafe { sigaction(sig, &sa, old_sa.as_mut_ptr()) } < 0 + || unsafe { sigprocmask(SIG_UNBLOCK, &mut set, &mut set) } < 0 { mem::forget(old_sa); return sig_err; } } } - if sigismember(&mut set, sig) == 1 { + if unsafe { sigismember(&mut set, sig) } == 1 { return sig_hold; } - old_sa.assume_init().sa_handler + unsafe { old_sa.assume_init().sa_handler } } /// See . #[unsafe(no_mangle)] pub unsafe extern "C" fn sigsuspend(sigmask: *const sigset_t) -> c_int { - Err(Sys::sigsuspend(&*sigmask)).or_minus_one_errno() + Err(Sys::sigsuspend(unsafe { &*sigmask })).or_minus_one_errno() } /// See . #[unsafe(no_mangle)] pub unsafe extern "C" fn sigwait(set: *const sigset_t, sig: *mut c_int) -> c_int { let mut pinfo = mem::MaybeUninit::::uninit(); - if sigtimedwait(set, pinfo.as_mut_ptr(), ptr::null_mut()) < 0 { + if unsafe { sigtimedwait(set, pinfo.as_mut_ptr(), ptr::null_mut()) } < 0 { return -1; } - let info = pinfo.assume_init(); - (*sig) = info.si_signo; + let info = unsafe { pinfo.assume_init() }; + unsafe { (*sig) = info.si_signo }; 0 } @@ -505,15 +510,17 @@ pub unsafe extern "C" fn sigtimedwait( // to differentiate between sigtimedwait and sigwaitinfo internally tp: *const timespec, ) -> c_int { - Sys::sigtimedwait(&*set, sig.as_mut(), tp.as_ref()) - .map(|()| 0) - .or_minus_one_errno() + Sys::sigtimedwait(unsafe { &*set }, unsafe { sig.as_mut() }, unsafe { + tp.as_ref() + }) + .map(|()| 0) + .or_minus_one_errno() } /// See . #[unsafe(no_mangle)] pub unsafe extern "C" fn sigwaitinfo(set: *const sigset_t, sig: *mut siginfo_t) -> c_int { - sigtimedwait(set, sig, core::ptr::null()) + unsafe { sigtimedwait(set, sig, core::ptr::null()) } } pub(crate) const SIGNAL_STRINGS: [&str; 32] = [ @@ -559,15 +566,17 @@ pub unsafe extern "C" fn psignal(sig: c_int, prefix: *const c_char) { .and_then(|idx| SIGNAL_STRINGS.get(idx)) .unwrap_or(&SIGNAL_STRINGS[0]); let description = &c_description[..c_description.len() - 1]; - let prefix = CStr::from_ptr(prefix).to_string_lossy(); + let prefix = unsafe { CStr::from_ptr(prefix).to_string_lossy() }; // TODO: stack vec or print directly? let string = alloc::format!("{prefix}:{description}\n"); // TODO: better internal libc API? - let _ = unistd::write( - unistd::STDERR_FILENO, - string.as_bytes().as_ptr().cast(), - string.as_bytes().len(), - ); + let _ = unsafe { + unistd::write( + unistd::STDERR_FILENO, + string.as_bytes().as_ptr().cast(), + string.as_bytes().len(), + ) + }; } /// See . @@ -582,9 +591,9 @@ pub unsafe extern "C" fn psiginfo(info: *const siginfo_t, prefix: *const c_char) si_addr, si_status, si_value, - } = &*info; - let sival_ptr = si_value.sival_ptr; - let prefix = CStr::from_ptr(prefix).to_string_lossy(); + } = unsafe { &*info }; + let sival_ptr = unsafe { si_value.sival_ptr }; + let prefix = unsafe { CStr::from_ptr(prefix).to_string_lossy() }; // TODO: stack vec or print directly? let string = alloc::format!( "{prefix}:siginfo_t {{ @@ -600,11 +609,13 @@ pub unsafe extern "C" fn psiginfo(info: *const siginfo_t, prefix: *const c_char) " ); // TODO: better internal libc API? - let _ = unistd::write( - unistd::STDERR_FILENO, - string.as_bytes().as_ptr().cast(), - string.as_bytes().len(), - ); + let _ = unsafe { + unistd::write( + unistd::STDERR_FILENO, + string.as_bytes().as_ptr().cast(), + string.as_bytes().len(), + ) + }; } #[unsafe(no_mangle)] From b3f7db83cfd92ccb8fe2f08603550587aa251fdc Mon Sep 17 00:00:00 2001 From: sourceturner <126549-sourceturner@users.noreply.gitlab.redox-os.org> Date: Fri, 16 Jan 2026 22:14:47 +0100 Subject: [PATCH 10/11] Use unsafe blocks in stdio.h implementation --- src/header/stdio/getdelim.rs | 29 ++- src/header/stdio/mod.rs | 420 +++++++++++++++++++---------------- src/header/stdio/printf.rs | 177 ++++++++------- src/header/stdio/scanf.rs | 64 +++--- 4 files changed, 384 insertions(+), 306 deletions(-) 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, } From f72ecfd8dcf89dc51241437289e721fde3d16ca4 Mon Sep 17 00:00:00 2001 From: sourceturner <126549-sourceturner@users.noreply.gitlab.redox-os.org> Date: Fri, 16 Jan 2026 22:15:53 +0100 Subject: [PATCH 11/11] Use unsafe blocks in string.h implementation --- src/header/string/mod.rs | 185 ++++++++++++++++++++------------------- 1 file changed, 94 insertions(+), 91 deletions(-) diff --git a/src/header/string/mod.rs b/src/header/string/mod.rs index e9dcd77b13..a40d6160cc 100644 --- a/src/header/string/mod.rs +++ b/src/header/string/mod.rs @@ -54,7 +54,7 @@ pub unsafe extern "C" fn memchr( needle: c_int, len: size_t, ) -> *mut c_void { - let haystack = slice::from_raw_parts(haystack as *const u8, len as usize); + let haystack = unsafe { slice::from_raw_parts(haystack as *const u8, len as usize) }; match memchr::memchr(needle as u8, haystack) { Some(index) => haystack[index..].as_ptr() as *mut c_void, @@ -71,28 +71,28 @@ pub unsafe extern "C" fn memcmp(s1: *const c_void, s2: *const c_void, n: usize) for _ in 0..div { // SAFETY: `s1` and `s2` are `*const c_void`, which only guarantees byte // alignment. Hence `a` and `b` may be unaligned. - if a.read_unaligned() != b.read_unaligned() { + if unsafe { a.read_unaligned() } != unsafe { b.read_unaligned() } { for i in 0..mem::size_of::() { - let c = *(a.cast::()).add(i); - let d = *(b.cast::()).add(i); + let c = unsafe { *(a.cast::()).add(i) }; + let d = unsafe { *(b.cast::()).add(i) }; if c != d { return c as c_int - d as c_int; } } unreachable!() } - a = a.offset(1); - b = b.offset(1); + a = unsafe { a.offset(1) }; + b = unsafe { b.offset(1) }; } let mut a = a.cast::(); let mut b = b.cast::(); for _ in 0..rem { - if *a != *b { - return *a as c_int - *b as c_int; + if unsafe { *a } != unsafe { *b } { + return unsafe { *a } as c_int - unsafe { *b } as c_int; } - a = a.offset(1); - b = b.offset(1); + a = unsafe { a.offset(1) }; + b = unsafe { b.offset(1) }; } 0 } @@ -108,7 +108,7 @@ pub unsafe extern "C" fn memcmp(s1: *const c_void, s2: *const c_void, n: usize) #[unsafe(no_mangle)] pub unsafe extern "C" fn memcpy(s1: *mut c_void, s2: *const c_void, n: size_t) -> *mut c_void { for i in 0..n { - *(s1 as *mut u8).add(i) = *(s2 as *const u8).add(i); + unsafe { *(s1 as *mut u8).add(i) = *(s2 as *const u8).add(i) }; } s1 } @@ -158,13 +158,13 @@ pub unsafe extern "C" fn memmove(s1: *mut c_void, s2: *const c_void, n: size_t) let mut i = n; while i != 0 { i -= 1; - *(s1 as *mut u8).add(i) = *(s2 as *const u8).add(i); + unsafe { *(s1 as *mut u8).add(i) = *(s2 as *const u8).add(i) }; } } else { // copy from beginning let mut i = 0; while i < n { - *(s1 as *mut u8).add(i) = *(s2 as *const u8).add(i); + unsafe { *(s1 as *mut u8).add(i) = *(s2 as *const u8).add(i) }; i += 1; } } @@ -178,7 +178,7 @@ pub unsafe extern "C" fn memrchr( needle: c_int, len: size_t, ) -> *mut c_void { - let haystack = slice::from_raw_parts(haystack as *const u8, len as usize); + let haystack = unsafe { slice::from_raw_parts(haystack as *const u8, len as usize) }; match memchr::memrchr(needle as u8, haystack) { Some(index) => haystack[index..].as_ptr() as *mut c_void, @@ -190,7 +190,7 @@ pub unsafe extern "C" fn memrchr( #[unsafe(no_mangle)] pub unsafe extern "C" fn memset(s: *mut c_void, c: c_int, n: size_t) -> *mut c_void { for i in 0..n { - *(s as *mut u8).add(i) = c as u8; + unsafe { *(s as *mut u8).add(i) = c as u8 }; } s } @@ -199,14 +199,14 @@ pub unsafe extern "C" fn memset(s: *mut c_void, c: c_int, n: size_t) -> *mut c_v #[unsafe(no_mangle)] pub unsafe extern "C" fn stpcpy(mut s1: *mut c_char, mut s2: *const c_char) -> *mut c_char { loop { - *s1 = *s2; + unsafe { *s1 = *s2 }; - if *s1 == 0 { + if unsafe { *s1 } == 0 { break; } - s1 = s1.add(1); - s2 = s2.add(1); + s1 = unsafe { s1.add(1) }; + s2 = unsafe { s2.add(1) }; } s1 @@ -220,18 +220,18 @@ pub unsafe extern "C" fn stpncpy( mut n: size_t, ) -> *mut c_char { while n > 0 { - *s1 = *s2; + unsafe { *s1 = *s2 }; - if *s1 == 0 { + if unsafe { *s1 } == 0 { break; } n -= 1; - s1 = s1.add(1); - s2 = s2.add(1); + s1 = unsafe { s1.add(1) }; + s2 = unsafe { s2.add(1) }; } - memset(s1.cast(), 0, n); + unsafe { memset(s1.cast(), 0, n) }; s1 } @@ -239,13 +239,13 @@ pub unsafe extern "C" fn stpncpy( /// Non-POSIX, see . #[unsafe(no_mangle)] pub unsafe extern "C" fn strcasestr(haystack: *const c_char, needle: *const c_char) -> *mut c_char { - inner_strstr(haystack, needle, !32) + unsafe { inner_strstr(haystack, needle, !32) } } /// See . #[unsafe(no_mangle)] pub unsafe extern "C" fn strcat(s1: *mut c_char, s2: *const c_char) -> *mut c_char { - strncat(s1, s2, usize::MAX) + unsafe { strncat(s1, s2, usize::MAX) } } /// See . @@ -275,13 +275,13 @@ pub unsafe extern "C" fn strchr(mut s: *const c_char, c: c_int) -> *mut c_char { pub unsafe extern "C" fn strchrnul(s: *const c_char, c: c_int) -> *mut c_char { let mut s = s.cast_mut(); loop { - if *s == c as _ { + if unsafe { *s } == c as _ { break; } - if *s == 0 { + if unsafe { *s } == 0 { break; } - s = s.add(1); + s = unsafe { s.add(1) }; } s } @@ -289,14 +289,14 @@ pub unsafe extern "C" fn strchrnul(s: *const c_char, c: c_int) -> *mut c_char { /// See . #[unsafe(no_mangle)] pub unsafe extern "C" fn strcmp(s1: *const c_char, s2: *const c_char) -> c_int { - strncmp(s1, s2, usize::MAX) + unsafe { strncmp(s1, s2, usize::MAX) } } /// See . #[unsafe(no_mangle)] pub unsafe extern "C" fn strcoll(s1: *const c_char, s2: *const c_char) -> c_int { // relibc has no locale stuff (yet) - strcmp(s1, s2) + unsafe { strcmp(s1, s2) } } // TODO: strcoll_l @@ -324,18 +324,18 @@ pub unsafe fn inner_strspn(s1: *const c_char, s2: *const c_char, cmp: bool) -> s let mut set = BitSet256::new(); - while *s2 != 0 { - set.insert(*s2 as usize); - s2 = s2.offset(1); + while unsafe { *s2 } != 0 { + set.insert(unsafe { *s2 } as usize); + s2 = unsafe { s2.offset(1) }; } let mut i = 0; - while *s1 != 0 { - if set.contains(*s1 as usize) != cmp { + while unsafe { *s1 } != 0 { + if set.contains(unsafe { *s1 } as usize) != cmp { break; } i += 1; - s1 = s1.offset(1); + s1 = unsafe { s1.offset(1) }; } i } @@ -343,13 +343,13 @@ pub unsafe fn inner_strspn(s1: *const c_char, s2: *const c_char, cmp: bool) -> s /// See . #[unsafe(no_mangle)] pub unsafe extern "C" fn strcspn(s1: *const c_char, s2: *const c_char) -> size_t { - inner_strspn(s1, s2, false) + unsafe { inner_strspn(s1, s2, false) } } /// See . #[unsafe(no_mangle)] pub unsafe extern "C" fn strdup(s1: *const c_char) -> *mut c_char { - strndup(s1, usize::MAX) + unsafe { strndup(s1, usize::MAX) } } /// See . @@ -358,17 +358,16 @@ pub unsafe extern "C" fn strerror(errnum: c_int) -> *mut c_char { use core::fmt::Write; static strerror_buf: RawCell<[u8; STRERROR_MAX]> = RawCell::new([0; STRERROR_MAX]); - let mut w = platform::StringWriter( - strerror_buf.unsafe_mut().as_mut_ptr(), - strerror_buf.unsafe_ref().len(), - ); + let mut w = platform::StringWriter(unsafe { strerror_buf.unsafe_mut().as_mut_ptr() }, unsafe { + strerror_buf.unsafe_ref().len() + }); let _ = match STR_ERROR.get(errnum as usize) { Some(e) => w.write_str(e), None => w.write_fmt(format_args!("Unknown error {}", errnum)), }; - strerror_buf.unsafe_mut().as_mut_ptr() as *mut c_char + (unsafe { strerror_buf.unsafe_mut().as_mut_ptr() }) as *mut c_char } // TODO: strerror_l @@ -376,17 +375,17 @@ pub unsafe extern "C" fn strerror(errnum: c_int) -> *mut c_char { /// See . #[unsafe(no_mangle)] pub unsafe extern "C" fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: size_t) -> c_int { - let msg = strerror(errnum); - let len = strlen(msg); + let msg = unsafe { strerror(errnum) }; + let len = unsafe { strlen(msg) }; if len >= buflen { if buflen != 0 { - memcpy(buf as *mut c_void, msg as *const c_void, buflen - 1); - *buf.add(buflen - 1) = 0; + unsafe { memcpy(buf as *mut c_void, msg as *const c_void, buflen - 1) }; + unsafe { *buf.add(buflen - 1) = 0 }; } return ERANGE as c_int; } - memcpy(buf as *mut c_void, msg as *const c_void, len + 1); + unsafe { memcpy(buf as *mut c_void, msg as *const c_void, len + 1) }; 0 } @@ -402,18 +401,18 @@ pub unsafe extern "C" fn strlcat(dst: *mut c_char, src: *const c_char, dstsize: #[unsafe(no_mangle)] pub unsafe extern "C" fn strsep(str_: *mut *mut c_char, sep: *const c_char) -> *mut c_char { - let s = *str_; + let s = unsafe { *str_ }; if s.is_null() { return ptr::null_mut(); } - let mut end = s.add(strcspn(s, sep)); - if *end != 0 { - *end = 0; - end = end.add(1); + let mut end = unsafe { s.add(strcspn(s, sep)) }; + if unsafe { *end } != 0 { + unsafe { *end = 0 }; + end = unsafe { end.add(1) }; } else { end = ptr::null_mut(); } - *str_ = end; + unsafe { *str_ = end }; s } @@ -452,18 +451,18 @@ pub unsafe extern "C" fn strlen(s: *const c_char) -> size_t { /// See . #[unsafe(no_mangle)] pub unsafe extern "C" fn strncat(s1: *mut c_char, s2: *const c_char, n: size_t) -> *mut c_char { - let len = strlen(s1.cast()); + let len = unsafe { strlen(s1.cast()) }; let mut i = 0; while i < n { - let b = *s2.add(i); + let b = unsafe { *s2.add(i) }; if b == 0 { break; } - *s1.add(len + i) = b; + unsafe { *s1.add(len + i) = b }; i += 1; } - *s1.add(len + i) = 0; + unsafe { *s1.add(len + i) = 0 }; s1 } @@ -473,8 +472,8 @@ pub unsafe extern "C" fn strncat(s1: *mut c_char, s2: *const c_char, n: size_t) pub unsafe extern "C" fn strncmp(s1: *const c_char, s2: *const c_char, n: size_t) -> c_int { for i in 0..n { // These must be cast as u8 to have correct comparisons - let a = *s1.add(i) as u8; - let b = *s2.add(i) as u8; + let a = unsafe { *s1.add(i) } as u8; + let b = unsafe { *s2.add(i) } as u8; if a != b || a == 0 { return (a as c_int) - (b as c_int); } @@ -486,25 +485,25 @@ pub unsafe extern "C" fn strncmp(s1: *const c_char, s2: *const c_char, n: size_t /// See . #[unsafe(no_mangle)] pub unsafe extern "C" fn strncpy(s1: *mut c_char, s2: *const c_char, n: size_t) -> *mut c_char { - stpncpy(s1, s2, n); + unsafe { stpncpy(s1, s2, n) }; s1 } /// See . #[unsafe(no_mangle)] pub unsafe extern "C" fn strndup(s1: *const c_char, size: size_t) -> *mut c_char { - let len = strnlen(s1, size); + let len = unsafe { strnlen(s1, size) }; // the "+ 1" is to account for the NUL byte - let buffer = platform::alloc(len + 1) as *mut c_char; + let buffer = unsafe { platform::alloc(len + 1) } as *mut c_char; if buffer.is_null() { platform::ERRNO.set(ENOMEM as c_int); } else { //memcpy(buffer, s1, len) for i in 0..len { - *buffer.add(i) = *s1.add(i); + unsafe { *buffer.add(i) = *s1.add(i) }; } - *buffer.add(len) = 0; + unsafe { *buffer.add(len) = 0 }; } buffer @@ -519,14 +518,18 @@ pub unsafe extern "C" fn strnlen(s: *const c_char, size: size_t) -> size_t { /// Non-POSIX, see . #[unsafe(no_mangle)] pub unsafe extern "C" fn strnlen_s(s: *const c_char, size: size_t) -> size_t { - if s.is_null() { 0 } else { strnlen(s, size) } + if s.is_null() { + 0 + } else { + unsafe { strnlen(s, size) } + } } /// See . #[unsafe(no_mangle)] pub unsafe extern "C" fn strpbrk(s1: *const c_char, s2: *const c_char) -> *mut c_char { - let p = s1.add(strcspn(s1, s2)); - if *p != 0 { + let p = unsafe { s1.add(strcspn(s1, s2)) }; + if unsafe { *p } != 0 { p as *mut c_char } else { ptr::null_mut() @@ -536,12 +539,12 @@ pub unsafe extern "C" fn strpbrk(s1: *const c_char, s2: *const c_char) -> *mut c /// See . #[unsafe(no_mangle)] pub unsafe extern "C" fn strrchr(s: *const c_char, c: c_int) -> *mut c_char { - let len = strlen(s) as isize; + let len = unsafe { strlen(s) } as isize; let c = c as c_char; let mut i = len - 1; while i >= 0 { - if *s.offset(i) == c { - return s.offset(i) as *mut c_char; + if unsafe { *s.offset(i) } == c { + return unsafe { s.offset(i) } as *mut c_char; } i -= 1; } @@ -560,7 +563,7 @@ pub unsafe extern "C" fn strsignal(sig: c_int) -> *mut c_char { /// See . #[unsafe(no_mangle)] pub unsafe extern "C" fn strspn(s1: *const c_char, s2: *const c_char) -> size_t { - inner_strspn(s1, s2, true) + unsafe { inner_strspn(s1, s2, true) } } unsafe fn inner_strstr( @@ -568,21 +571,21 @@ unsafe fn inner_strstr( needle: *const c_char, mask: c_char, ) -> *mut c_char { - while *haystack != 0 { + while unsafe { *haystack } != 0 { let mut i = 0; loop { - if *needle.offset(i) == 0 { + if unsafe { *needle.offset(i) } == 0 { // We reached the end of the needle, everything matches this far return haystack as *mut c_char; } - if *haystack.offset(i) & mask != *needle.offset(i) & mask { + if unsafe { *haystack.offset(i) } & mask != unsafe { *needle.offset(i) } & mask { break; } i += 1; } - haystack = haystack.offset(1); + haystack = unsafe { haystack.offset(1) }; } ptr::null_mut() } @@ -590,14 +593,14 @@ unsafe fn inner_strstr( /// See . #[unsafe(no_mangle)] pub unsafe extern "C" fn strstr(haystack: *const c_char, needle: *const c_char) -> *mut c_char { - inner_strstr(haystack, needle, !0) + unsafe { inner_strstr(haystack, needle, !0) } } /// See . #[unsafe(no_mangle)] pub unsafe extern "C" fn strtok(s1: *mut c_char, delimiter: *const c_char) -> *mut c_char { static mut HAYSTACK: *mut c_char = ptr::null_mut(); - strtok_r(s1, delimiter, &raw mut HAYSTACK) + unsafe { strtok_r(s1, delimiter, &raw mut HAYSTACK) } } /// See . @@ -610,28 +613,28 @@ pub unsafe extern "C" fn strtok_r( // musl returns null if both s and lasts are null, it sets s to lasts otherwise let mut haystack = s; if haystack.is_null() { - if (*lasts).is_null() { + if (unsafe { *lasts }).is_null() { return ptr::null_mut(); } - haystack = *lasts; + haystack = unsafe { *lasts }; } // Skip past any extra delimiter left over from previous call - haystack = haystack.add(strspn(haystack, delimiter)); - if *haystack == 0 { - *lasts = haystack; + haystack = unsafe { haystack.add(strspn(haystack, delimiter)) }; + if unsafe { *haystack } == 0 { + unsafe { *lasts = haystack }; return ptr::null_mut(); } // Build token by injecting null byte into delimiter let token = haystack; - haystack = strpbrk(token, delimiter); + haystack = unsafe { strpbrk(token, delimiter) }; if !haystack.is_null() { - haystack.write(0); - haystack = haystack.add(1); - *lasts = haystack; + unsafe { haystack.write(0) }; + haystack = unsafe { haystack.add(1) }; + unsafe { *lasts = haystack }; } else { - *lasts = token.add(strlen(token)); + unsafe { *lasts = token.add(strlen(token)) }; } token @@ -641,9 +644,9 @@ pub unsafe extern "C" fn strtok_r( #[unsafe(no_mangle)] pub unsafe extern "C" fn strxfrm(s1: *mut c_char, s2: *const c_char, n: size_t) -> size_t { // relibc has no locale stuff (yet) - let len = strlen(s2); + let len = unsafe { strlen(s2) }; if len < n { - strcpy(s1, s2); + unsafe { strcpy(s1, s2) }; } len }