Skip to content

Commit 4f39497

Browse files
authored
Consistently use std::ffi over libc for C types (#1355)
2 parents 2ec1ac7 + c2d35ea commit 4f39497

File tree

20 files changed

+200
-203
lines changed

20 files changed

+200
-203
lines changed

Makefile

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
PAM_SRC_DIR = src/pam
22

3-
BINDGEN_CMD = bindgen --allowlist-function '^pam_.*$$' --allowlist-var '^PAM_.*$$' --opaque-type pam_handle_t --blocklist-function pam_vsyslog --blocklist-function pam_vprompt --blocklist-function pam_vinfo --blocklist-function pam_verror --blocklist-type '.*va_list.*' --ctypes-prefix libc --no-layout-tests --sort-semantically
3+
BINDGEN_CMD = bindgen --allowlist-function '^pam_.*$$' --allowlist-var '^PAM_.*$$' --opaque-type pam_handle_t --blocklist-function pam_vsyslog --blocklist-function pam_vprompt --blocklist-function pam_vinfo --blocklist-function pam_verror --blocklist-type '.*va_list.*' --ctypes-prefix std::ffi --no-layout-tests --sort-semantically
44

55
PAM_VARIANT = $$(./get-pam-variant.bash)
66

src/cutils/mod.rs

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
use std::{
2-
ffi::{CStr, OsStr, OsString},
2+
ffi::{c_char, c_int, c_long, CStr, OsStr, OsString},
33
os::{
44
fd::{AsRawFd, BorrowedFd},
55
unix::prelude::OsStrExt,
66
},
77
};
88

9-
pub fn cerr<Int: Copy + TryInto<libc::c_long>>(res: Int) -> std::io::Result<Int> {
9+
pub fn cerr<Int: Copy + TryInto<c_long>>(res: Int) -> std::io::Result<Int> {
1010
match res.try_into() {
1111
Ok(-1) => Err(std::io::Error::last_os_error()),
1212
_ => Ok(res),
@@ -23,15 +23,15 @@ extern "C" {
2323
link_name = "__errno"
2424
)]
2525
#[cfg_attr(target_os = "linux", link_name = "__errno_location")]
26-
fn errno_location() -> *mut libc::c_int;
26+
fn errno_location() -> *mut c_int;
2727
}
2828

29-
pub fn set_errno(no: libc::c_int) {
29+
pub fn set_errno(no: c_int) {
3030
// SAFETY: errno_location is a thread-local pointer to an integer, so we are the only writers
3131
unsafe { *errno_location() = no };
3232
}
3333

34-
pub fn sysconf(name: libc::c_int) -> Option<libc::c_long> {
34+
pub fn sysconf(name: c_int) -> Option<c_long> {
3535
set_errno(0);
3636
// SAFETY: sysconf will always respond with 0 or -1 for every input
3737
cerr(unsafe { libc::sysconf(name) }).ok()
@@ -44,7 +44,7 @@ pub fn sysconf(name: libc::c_int) -> Option<libc::c_long> {
4444
/// # Safety
4545
/// This function assumes that the pointer is either a null pointer or that
4646
/// it points to a valid NUL-terminated C string.
47-
pub unsafe fn string_from_ptr(ptr: *const libc::c_char) -> String {
47+
pub unsafe fn string_from_ptr(ptr: *const c_char) -> String {
4848
if ptr.is_null() {
4949
String::new()
5050
} else {
@@ -59,7 +59,7 @@ pub unsafe fn string_from_ptr(ptr: *const libc::c_char) -> String {
5959
/// # Safety
6060
/// This function assumes that the pointer is either a null pointer or that
6161
/// it points to a valid NUL-terminated C string.
62-
pub unsafe fn os_string_from_ptr(ptr: *const libc::c_char) -> OsString {
62+
pub unsafe fn os_string_from_ptr(ptr: *const c_char) -> OsString {
6363
if ptr.is_null() {
6464
OsString::new()
6565
} else {
@@ -107,22 +107,24 @@ pub fn is_fifo(fildes: BorrowedFd) -> bool {
107107
#[allow(clippy::undocumented_unsafe_blocks)]
108108
#[cfg(test)]
109109
mod test {
110+
use std::ffi::c_char;
111+
110112
use super::{os_string_from_ptr, string_from_ptr};
111113

112114
#[test]
113115
fn miri_test_str_to_ptr() {
114116
let strp = |ptr| unsafe { string_from_ptr(ptr) };
115117
assert_eq!(strp(std::ptr::null()), "");
116-
assert_eq!(strp("\0".as_ptr() as *const libc::c_char), "");
117-
assert_eq!(strp("hello\0".as_ptr() as *const libc::c_char), "hello");
118+
assert_eq!(strp("\0".as_ptr() as *const c_char), "");
119+
assert_eq!(strp("hello\0".as_ptr() as *const c_char), "hello");
118120
}
119121

120122
#[test]
121123
fn miri_test_os_str_to_ptr() {
122124
let strp = |ptr| unsafe { os_string_from_ptr(ptr) };
123125
assert_eq!(strp(std::ptr::null()), "");
124-
assert_eq!(strp("\0".as_ptr() as *const libc::c_char), "");
125-
assert_eq!(strp("hello\0".as_ptr() as *const libc::c_char), "hello");
126+
assert_eq!(strp("\0".as_ptr() as *const c_char), "");
127+
assert_eq!(strp("hello\0".as_ptr() as *const c_char), "hello");
126128
}
127129

128130
#[test]

src/exec/event.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
use std::{
2+
ffi::c_short,
23
fmt::Debug,
34
io,
45
os::fd::{AsFd, AsRawFd, RawFd},
56
};
67

7-
use libc::{c_short, pollfd, POLLIN, POLLOUT};
8+
use libc::{pollfd, POLLIN, POLLOUT};
89

910
use crate::common::{HARDENED_ENUM_VALUE_0, HARDENED_ENUM_VALUE_1};
1011
use crate::{cutils::cerr, log::dev_debug};

src/exec/noexec.rs

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
#![cfg_attr(not(target_arch = "x86_64"), allow(unused))]
44

55
use std::alloc::{handle_alloc_error, GlobalAlloc, Layout};
6-
use std::ffi::c_void;
6+
use std::ffi::{c_int, c_uint, c_ulong, c_void};
77
use std::mem::{align_of, size_of, zeroed};
88
use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd};
99
use std::os::unix::net::UnixStream;
@@ -13,14 +13,13 @@ use std::ptr::{self, addr_of};
1313
use std::{cmp, io, thread};
1414

1515
use libc::{
16-
c_int, c_uint, c_ulong, close, cmsghdr, iovec, msghdr, prctl, recvmsg, seccomp_data,
17-
seccomp_notif, seccomp_notif_resp, seccomp_notif_sizes, sendmsg, sock_filter, sock_fprog,
18-
syscall, SYS_execve, SYS_execveat, SYS_seccomp, __errno_location, BPF_ABS, BPF_ALU, BPF_AND,
19-
BPF_JEQ, BPF_JMP, BPF_JUMP, BPF_K, BPF_LD, BPF_RET, BPF_STMT, BPF_W, CMSG_DATA, CMSG_FIRSTHDR,
20-
CMSG_LEN, CMSG_SPACE, EACCES, ENOENT, MSG_TRUNC, PR_SET_NO_NEW_PRIVS, SCM_RIGHTS,
21-
SECCOMP_FILTER_FLAG_NEW_LISTENER, SECCOMP_GET_NOTIF_SIZES, SECCOMP_RET_ALLOW,
22-
SECCOMP_RET_KILL_PROCESS, SECCOMP_SET_MODE_FILTER, SECCOMP_USER_NOTIF_FLAG_CONTINUE,
23-
SOL_SOCKET,
16+
close, cmsghdr, iovec, msghdr, prctl, recvmsg, seccomp_data, seccomp_notif, seccomp_notif_resp,
17+
seccomp_notif_sizes, sendmsg, sock_filter, sock_fprog, syscall, SYS_execve, SYS_execveat,
18+
SYS_seccomp, __errno_location, BPF_ABS, BPF_ALU, BPF_AND, BPF_JEQ, BPF_JMP, BPF_JUMP, BPF_K,
19+
BPF_LD, BPF_RET, BPF_STMT, BPF_W, CMSG_DATA, CMSG_FIRSTHDR, CMSG_LEN, CMSG_SPACE, EACCES,
20+
ENOENT, MSG_TRUNC, PR_SET_NO_NEW_PRIVS, SCM_RIGHTS, SECCOMP_FILTER_FLAG_NEW_LISTENER,
21+
SECCOMP_GET_NOTIF_SIZES, SECCOMP_RET_ALLOW, SECCOMP_RET_KILL_PROCESS, SECCOMP_SET_MODE_FILTER,
22+
SECCOMP_USER_NOTIF_FLAG_CONTINUE, SOL_SOCKET,
2423
};
2524

2625
const SECCOMP_RET_USER_NOTIF: c_uint = 0x7fc00000;
@@ -117,7 +116,7 @@ fn alloc_notify_allocs() -> NotifyAllocs {
117116
/// # Safety
118117
///
119118
/// `ioctl(fd, request, ptr)` must be safe to call
120-
unsafe fn ioctl<T>(fd: RawFd, request: libc::c_ulong, ptr: *mut T) -> Option<()> {
119+
unsafe fn ioctl<T>(fd: RawFd, request: c_ulong, ptr: *mut T) -> Option<()> {
121120
// SAFETY: By function contract
122121
if unsafe { libc::ioctl(fd, request as _, ptr) } == -1 {
123122
// SAFETY: Trivial
@@ -217,7 +216,7 @@ fn receive_fd(rx_fd: UnixStream) -> RawFd {
217216
let mut control: SingleRightAnciliaryData = unsafe { zeroed() };
218217
// SAFETY: The buf field is valid when zero-initialized.
219218
msg.msg_controllen = unsafe { control.buf.len() as _ };
220-
msg.msg_control = &mut control as *mut _ as *mut libc::c_void;
219+
msg.msg_control = &mut control as *mut _ as *mut c_void;
221220

222221
// SAFETY: A valid socket fd and a valid initialized msghdr are passed in.
223222
if unsafe { recvmsg(rx_fd.as_raw_fd(), &mut msg, 0) } == -1 {

src/log/syslog.rs

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
11
use core::fmt::{self, Write};
2+
use std::ffi::c_int;
23

34
use crate::log::{Level, Log};
45

56
pub struct Syslog;
67

78
mod internal {
89
use crate::system::syslog;
9-
use std::ffi::CStr;
10+
use std::ffi::{c_int, CStr};
1011

1112
const DOTDOTDOT_START: &[u8] = b"[...] ";
1213
const DOTDOTDOT_END: &[u8] = b" [...]";
@@ -18,8 +19,8 @@ mod internal {
1819
pub struct SysLogMessageWriter {
1920
buffer: [u8; BUFSZ],
2021
cursor: usize,
21-
facility: libc::c_int,
22-
priority: libc::c_int,
22+
facility: c_int,
23+
priority: c_int,
2324
}
2425

2526
// - whenever a SysLogMessageWriter has been constructed, a syslog message WILL be created
@@ -29,7 +30,7 @@ mod internal {
2930
// - the impl guarantees that after `line_break()`, there will be enough room available for at
3031
// least a single UTF8 character sequence (which is true since MAX_MSG_LEN >= 10)
3132
impl SysLogMessageWriter {
32-
pub fn new(priority: libc::c_int, facility: libc::c_int) -> Self {
33+
pub fn new(priority: c_int, facility: c_int) -> Self {
3334
Self {
3435
buffer: [0; BUFSZ],
3536
cursor: 0,
@@ -127,7 +128,7 @@ impl Write for SysLogMessageWriter {
127128
}
128129
}
129130

130-
const FACILITY: libc::c_int = libc::LOG_AUTH;
131+
const FACILITY: c_int = libc::LOG_AUTH;
131132

132133
impl Log for Syslog {
133134
fn log(&self, level: Level, args: &fmt::Arguments<'_>) {

src/pam/converse.rs

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
use std::ffi::{c_int, c_void};
12
use std::io;
23

34
use crate::cutils::string_from_ptr;
@@ -29,7 +30,7 @@ pub enum PamMessageStyle {
2930
}
3031

3132
impl PamMessageStyle {
32-
pub fn from_int(val: libc::c_int) -> Option<PamMessageStyle> {
33+
pub fn from_int(val: c_int) -> Option<PamMessageStyle> {
3334
use PamMessageStyle::*;
3435

3536
match val as _ {
@@ -212,11 +213,11 @@ pub(super) struct ConverserData<C> {
212213
/// this function will exhibit undefined behavior.
213214
/// * The messages from PAM are assumed to be formatted correctly.
214215
pub(super) unsafe extern "C" fn converse<C: Converser>(
215-
num_msg: libc::c_int,
216+
num_msg: c_int,
216217
msg: *mut *const pam_message,
217218
response: *mut *mut pam_response,
218-
appdata_ptr: *mut libc::c_void,
219-
) -> libc::c_int {
219+
appdata_ptr: *mut c_void,
220+
) -> c_int {
220221
let result = std::panic::catch_unwind(|| {
221222
let mut resp_bufs = Vec::with_capacity(num_msg as usize);
222223
for i in 0..num_msg as usize {
@@ -402,7 +403,7 @@ mod test {
402403
impl<'a> PamConvBorrow<'a> {
403404
fn new<C: Converser>(data: Pin<&'a mut ConverserData<C>>) -> PamConvBorrow<'a> {
404405
let appdata_ptr =
405-
unsafe { data.get_unchecked_mut() as *mut ConverserData<C> as *mut libc::c_void };
406+
unsafe { data.get_unchecked_mut() as *mut ConverserData<C> as *mut c_void };
406407
PamConvBorrow {
407408
pam_conv: pam_conv {
408409
conv: Some(converse::<C>),

src/pam/error.rs

Lines changed: 44 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1-
use std::{ffi::NulError, fmt, str::Utf8Error};
1+
use std::ffi::{c_int, NulError};
2+
use std::fmt;
3+
use std::str::Utf8Error;
24

35
use crate::cutils::string_from_ptr;
46

@@ -65,7 +67,7 @@ pub enum PamErrorType {
6567
}
6668

6769
impl PamErrorType {
68-
pub(super) fn from_int(errno: libc::c_int) -> PamErrorType {
70+
pub(super) fn from_int(errno: c_int) -> PamErrorType {
6971
use PamErrorType::*;
7072

7173
match errno as _ {
@@ -109,46 +111,46 @@ impl PamErrorType {
109111
}
110112
}
111113

112-
pub fn as_int(&self) -> libc::c_int {
114+
pub fn as_int(&self) -> c_int {
113115
use PamErrorType::*;
114116

115117
match self {
116-
Success => PAM_SUCCESS as libc::c_int,
117-
OpenError => PAM_OPEN_ERR as libc::c_int,
118-
SymbolError => PAM_SYMBOL_ERR as libc::c_int,
119-
ServiceError => PAM_SERVICE_ERR as libc::c_int,
120-
SystemError => PAM_SYSTEM_ERR as libc::c_int,
121-
BufferError => PAM_BUF_ERR as libc::c_int,
122-
ConversationError => PAM_CONV_ERR as libc::c_int,
123-
PermissionDenied => PAM_PERM_DENIED as libc::c_int,
124-
MaxTries => PAM_MAXTRIES as libc::c_int,
125-
AuthError => PAM_AUTH_ERR as libc::c_int,
126-
NewAuthTokenRequired => PAM_NEW_AUTHTOK_REQD as libc::c_int,
127-
CredentialsInsufficient => PAM_CRED_INSUFFICIENT as libc::c_int,
128-
AuthInfoUnavailable => PAM_AUTHINFO_UNAVAIL as libc::c_int,
129-
UserUnknown => PAM_USER_UNKNOWN as libc::c_int,
130-
CredentialsUnavailable => PAM_CRED_UNAVAIL as libc::c_int,
131-
CredentialsExpired => PAM_CRED_EXPIRED as libc::c_int,
132-
CredentialsError => PAM_CRED_ERR as libc::c_int,
133-
AccountExpired => PAM_ACCT_EXPIRED as libc::c_int,
134-
AuthTokenExpired => PAM_AUTHTOK_EXPIRED as libc::c_int,
135-
SessionError => PAM_SESSION_ERR as libc::c_int,
136-
AuthTokenError => PAM_AUTHTOK_ERR as libc::c_int,
137-
AuthTokenRecoveryError => PAM_AUTHTOK_RECOVERY_ERR as libc::c_int,
138-
AuthTokenLockBusy => PAM_AUTHTOK_LOCK_BUSY as libc::c_int,
139-
AuthTokenDisableAging => PAM_AUTHTOK_DISABLE_AGING as libc::c_int,
140-
NoModuleData => PAM_NO_MODULE_DATA as libc::c_int,
141-
Ignore => PAM_IGNORE as libc::c_int,
142-
Abort => PAM_ABORT as libc::c_int,
143-
TryAgain => PAM_TRY_AGAIN as libc::c_int,
144-
ModuleUnknown => PAM_MODULE_UNKNOWN as libc::c_int,
145-
BadItem => PAM_BAD_ITEM as libc::c_int,
146-
// DomainUnknown => PAM_DOMAIN_UNKNOWN as libc::c_int,
147-
// BadHandle => PAM_BAD_HANDLE as libc::c_int,
148-
// BadFeature => PAM_BAD_FEATURE as libc::c_int,
149-
// BadConstant => PAM_BAD_CONSTANT as libc::c_int,
150-
// ConverseAgain => PAM_CONV_AGAIN as libc::c_int,
151-
// Incomplete => PAM_INCOMPLETE as libc::c_int,
118+
Success => PAM_SUCCESS as c_int,
119+
OpenError => PAM_OPEN_ERR as c_int,
120+
SymbolError => PAM_SYMBOL_ERR as c_int,
121+
ServiceError => PAM_SERVICE_ERR as c_int,
122+
SystemError => PAM_SYSTEM_ERR as c_int,
123+
BufferError => PAM_BUF_ERR as c_int,
124+
ConversationError => PAM_CONV_ERR as c_int,
125+
PermissionDenied => PAM_PERM_DENIED as c_int,
126+
MaxTries => PAM_MAXTRIES as c_int,
127+
AuthError => PAM_AUTH_ERR as c_int,
128+
NewAuthTokenRequired => PAM_NEW_AUTHTOK_REQD as c_int,
129+
CredentialsInsufficient => PAM_CRED_INSUFFICIENT as c_int,
130+
AuthInfoUnavailable => PAM_AUTHINFO_UNAVAIL as c_int,
131+
UserUnknown => PAM_USER_UNKNOWN as c_int,
132+
CredentialsUnavailable => PAM_CRED_UNAVAIL as c_int,
133+
CredentialsExpired => PAM_CRED_EXPIRED as c_int,
134+
CredentialsError => PAM_CRED_ERR as c_int,
135+
AccountExpired => PAM_ACCT_EXPIRED as c_int,
136+
AuthTokenExpired => PAM_AUTHTOK_EXPIRED as c_int,
137+
SessionError => PAM_SESSION_ERR as c_int,
138+
AuthTokenError => PAM_AUTHTOK_ERR as c_int,
139+
AuthTokenRecoveryError => PAM_AUTHTOK_RECOVERY_ERR as c_int,
140+
AuthTokenLockBusy => PAM_AUTHTOK_LOCK_BUSY as c_int,
141+
AuthTokenDisableAging => PAM_AUTHTOK_DISABLE_AGING as c_int,
142+
NoModuleData => PAM_NO_MODULE_DATA as c_int,
143+
Ignore => PAM_IGNORE as c_int,
144+
Abort => PAM_ABORT as c_int,
145+
TryAgain => PAM_TRY_AGAIN as c_int,
146+
ModuleUnknown => PAM_MODULE_UNKNOWN as c_int,
147+
BadItem => PAM_BAD_ITEM as c_int,
148+
// DomainUnknown => PAM_DOMAIN_UNKNOWN as c_int,
149+
// BadHandle => PAM_BAD_HANDLE as c_int,
150+
// BadFeature => PAM_BAD_FEATURE as c_int,
151+
// BadConstant => PAM_BAD_CONSTANT as c_int,
152+
// ConverseAgain => PAM_CONV_AGAIN as c_int,
153+
// Incomplete => PAM_INCOMPLETE as c_int,
152154
UnknownErrorType(e) => *e,
153155
}
154156
}
@@ -236,15 +238,15 @@ impl fmt::Display for PamError {
236238

237239
impl PamError {
238240
/// Create a new PamError based on the error number from pam.
239-
pub(super) fn from_pam(errno: libc::c_int) -> PamError {
241+
pub(super) fn from_pam(errno: c_int) -> PamError {
240242
let tp = PamErrorType::from_int(errno);
241243
PamError::Pam(tp)
242244
}
243245
}
244246

245247
/// Returns `Ok(())` if the error code is `PAM_SUCCESS` or a `PamError` in other cases
246-
pub(super) fn pam_err(err: libc::c_int) -> Result<(), PamError> {
247-
if err == PAM_SUCCESS as libc::c_int {
248+
pub(super) fn pam_err(err: c_int) -> Result<(), PamError> {
249+
if err == PAM_SUCCESS as c_int {
248250
Ok(())
249251
} else {
250252
Err(PamError::from_pam(err))

0 commit comments

Comments
 (0)