From 433445b692d5686bd85d5617c81c5949f2758d15 Mon Sep 17 00:00:00 2001 From: Sami Liedes Date: Sat, 14 Nov 2026 04:19:47 +0100 Subject: [PATCH 1/2] C-FFI: declare C functions returning void as void With `-Z c-ffi --c-lib`, a C function `void f(int)` declared in Rust as `fn f(x: i32)` could not be linked: Kani declared it as returning `struct Unit`, and goto-cc rejected the C definition as a conflicting declaration ("type classes differ"). The only workaround was to change the C to return `struct Unit` (as tests/kani/ForeignItems/lib.c did), which is not possible for unmodified C code. Declare user C-FFI functions whose Rust return type is `()` as returning `void`. Direct calls already discard a unit result. When such a function is coerced to a Rust function pointer, cast its address to the Rust pointer type (returning `struct Unit`): calls through the pointer do not use the unit result, and CBMC's function pointer removal ignores the return type in that case, so the function remains a call target. The Rust allocation shims in kani_lib.c are unchanged. tests/kani/ForeignItems/lib.c now defines its two void functions as `void`, and extern_fn_ptr.rs checks a call through a pointer to one. Resolves #2151, resolves #1817 Co-Authored-By: Claude Opus 5.5 --- .../codegen/foreign_function.rs | 18 +++++++++++-- .../codegen_cprover_gotoc/codegen/rvalue.rs | 7 ++++- tests/kani/ForeignItems/extern_fn_ptr.rs | 13 +++++++++ tests/kani/ForeignItems/lib.c | 27 ++----------------- 4 files changed, 37 insertions(+), 28 deletions(-) diff --git a/kani-compiler/src/codegen_cprover_gotoc/codegen/foreign_function.rs b/kani-compiler/src/codegen_cprover_gotoc/codegen/foreign_function.rs index f72a91c398d9..92c0d60065c8 100644 --- a/kani-compiler/src/codegen_cprover_gotoc/codegen/foreign_function.rs +++ b/kani-compiler/src/codegen_cprover_gotoc/codegen/foreign_function.rs @@ -73,7 +73,10 @@ impl GotocCtx<'_, '_> { // TODO: Add proper casting and clashing definitions check. // https://github.com/model-checking/kani/issues/2426 self.ensure(mangled_fn_name, |gcx, _| { - let typ = gcx.codegen_ffi_type(instance); + // A C function returning `void` is declared in Rust as returning `()`. + // Declare it as returning `void`, not `struct Unit`, so that it links + // with its C definition. + let typ = gcx.codegen_ffi_type_with(instance, true); Symbol::function(mangled_fn_name, typ, None, instance.name(), loc) .with_is_extern(true) }) @@ -158,6 +161,13 @@ impl GotocCtx<'_, '_> { /// Generate type for the given foreign instance. fn codegen_ffi_type(&mut self, instance: Instance) -> Type { + self.codegen_ffi_type_with(instance, false) + } + + /// Generate type for the given foreign instance. If `unit_as_void`, a function whose + /// return type is `()` returns `void`; [`Self::codegen_foreign_call`] does not assign + /// the result of such a call. + fn codegen_ffi_type_with(&mut self, instance: Instance, unit_as_void: bool) -> Type { let fn_name = instance.mangled_name(); let fn_abi = instance.fn_abi().unwrap(); let loc = self.codegen_span_stable(instance.def.span()); @@ -190,7 +200,11 @@ impl GotocCtx<'_, '_> { arg_type.as_parameter(Some(arg_name.into()), Some(base_name.into())) }) .collect(); - let ret_type = self.codegen_ty_stable(fn_abi.ret.ty); + let ret_type = if unit_as_void && fn_abi.ret.ty.kind().is_unit() { + Type::empty() + } else { + self.codegen_ty_stable(fn_abi.ret.ty) + }; if fn_abi.c_variadic { Type::variadic_code(params, ret_type) diff --git a/kani-compiler/src/codegen_cprover_gotoc/codegen/rvalue.rs b/kani-compiler/src/codegen_cprover_gotoc/codegen/rvalue.rs index 07593bd5315b..7ac7ba43beef 100644 --- a/kani-compiler/src/codegen_cprover_gotoc/codegen/rvalue.rs +++ b/kani-compiler/src/codegen_cprover_gotoc/codegen/rvalue.rs @@ -1338,7 +1338,12 @@ impl GotocCtx<'_, '_> { let instance = Instance::resolve(def, &args).unwrap(); // We need to handle this case in a special way because `codegen_operand_stable` compiles FnDefs to dummy structs. // (cf. the function documentation) - self.codegen_func_expr(instance, loc).address_of() + let fn_ptr = self.codegen_func_expr(instance, loc).address_of(); + // A C function returning `void` is declared with that return type under + // `-Z c-ffi` (see `codegen_foreign_fn`), while the Rust function pointer + // type returns `struct Unit`. Calls through the pointer do not use a unit + // result, so CBMC accepts the function as a target of the cast pointer. + fn_ptr.cast_to(self.codegen_ty_stable(t)) } _ => unreachable!(), }, diff --git a/tests/kani/ForeignItems/extern_fn_ptr.rs b/tests/kani/ForeignItems/extern_fn_ptr.rs index e884f9316010..556e9521c86d 100644 --- a/tests/kani/ForeignItems/extern_fn_ptr.rs +++ b/tests/kani/ForeignItems/extern_fn_ptr.rs @@ -9,6 +9,8 @@ extern "C" { /// Returns i + 2 fn takes_int(i: u32) -> u32; + /// `void mutates_ptr(uint32_t *p)` in C: decrements `*p` + fn mutates_ptr(p: &mut u32); } fn call_on(input: u32, func: Option u32>) -> Option { @@ -21,3 +23,14 @@ fn check_extern_fn_ptr() { assert_eq!(call_on(0, None), None); assert_eq!(call_on(input, Some(takes_int)).unwrap(), unsafe { takes_int(input) }); } + +/// A pointer to a C function returning `void` (`unsafe extern "C" fn(&mut u32)` in Rust). +#[kani::proof] +fn check_extern_void_fn_ptr() { + let mut x: u32 = kani::any(); + kani::assume(x > 0); + let before = x; + let f: unsafe extern "C" fn(&mut u32) = mutates_ptr; + unsafe { f(&mut x) }; + assert_eq!(x, before - 1); +} diff --git a/tests/kani/ForeignItems/lib.c b/tests/kani/ForeignItems/lib.c index 71def3e7b87a..352d075666d5 100644 --- a/tests/kani/ForeignItems/lib.c +++ b/tests/kani/ForeignItems/lib.c @@ -7,13 +7,6 @@ #include #include -/// Mapping unit to `void` works for functions with no return type but not for -/// variables with type unit. We treat both uniformly by declaring an empty -/// struct type: `struct Unit {}` and a global variable `struct Unit VoidUnit` -/// returned by all void functions (both declared by the Kani compiler). -struct Unit; -extern struct Unit VoidUnit; - size_t my_add(size_t num, ...) { va_list argp; @@ -55,15 +48,7 @@ struct Foo2 { uint32_t S = 12; -// Note: We changed the return type from `void` to `struct Unit` when upgrading -// to a newer CBMC version with stricter type-checking. This is a temporary -// change until C-FFI support is added. -// -struct Unit update_static() -{ - S++; - return VoidUnit; -} +void update_static() { S++; } uint32_t takes_int(uint32_t i) { return i + 2; } @@ -78,15 +63,7 @@ uint32_t takes_ptr_option(uint32_t *p) } } -// Note: We changed the return type from `void` to `struct Unit` when upgrading -// to a newer CBMC version with stricter type-checking. This is a temporary -// change until C-FFI support is added. -// -struct Unit mutates_ptr(uint32_t *p) -{ - *p -= 1; - return VoidUnit; -} +void mutates_ptr(uint32_t *p) { *p -= 1; } uint32_t name_in_c(uint32_t i) { return i + 2; } From 9dc936ed150416f69bf1522bf294a79a7743b2cc Mon Sep 17 00:00:00 2001 From: Sami Liedes Date: Sun, 15 Nov 2026 00:39:57 +0100 Subject: [PATCH 2/2] Add regression tests for C-FFI functions returning void Regression tests for #2151 and #1817. On Kani 0.68.0 each of them fails to link: goto-cc reports "conflicting function declarations" ("type classes differ") between the C `void` definition and Kani's declaration returning `struct Unit`. tests/kani/ForeignItems/void_return.rs links plain C `void` functions (void_fns.c) and checks their side effects, so the calls cannot be dropped: - no parameters, updating a global (the minimal case); - a symbolic argument; - several parameters with an out pointer, and two pointer parameters; - a function pointer with two `void` targets. tests/expected/c-ffi-void checks that the calls are not vacuous, both direct and through a function pointer: a cover of the side effect is satisfied and an assertion it contradicts fails. Without the cast of the function's address to the Rust pointer type, the pointer harnesses make kani-compiler panic ("assign statement with unequal types"). Co-Authored-By: Claude Opus 5.5 --- tests/expected/c-ffi-void/expected | 14 +++++ tests/expected/c-ffi-void/main.rs | 30 +++++++++++ tests/expected/c-ffi-void/void_fns.c | 6 +++ tests/kani/ForeignItems/void_fns.c | 26 ++++++++++ tests/kani/ForeignItems/void_return.rs | 71 ++++++++++++++++++++++++++ 5 files changed, 147 insertions(+) create mode 100644 tests/expected/c-ffi-void/expected create mode 100644 tests/expected/c-ffi-void/main.rs create mode 100644 tests/expected/c-ffi-void/void_fns.c create mode 100644 tests/kani/ForeignItems/void_fns.c create mode 100644 tests/kani/ForeignItems/void_return.rs diff --git a/tests/expected/c-ffi-void/expected b/tests/expected/c-ffi-void/expected new file mode 100644 index 000000000000..6f230f66b5e4 --- /dev/null +++ b/tests/expected/c-ffi-void/expected @@ -0,0 +1,14 @@ +Status: SATISFIED\ +Description: "pointer call decremented" + +Failed Checks: "pointer call left x unchanged" + +Status: SATISFIED\ +Description: "direct call decremented" + +Failed Checks: "direct call left x unchanged" + +Summary:\ +Verification failed for - check_fn_ptr_call\ +Verification failed for - check_direct_call\ +Complete - 0 successfully verified harnesses, 2 failures, 2 total. diff --git a/tests/expected/c-ffi-void/main.rs b/tests/expected/c-ffi-void/main.rs new file mode 100644 index 000000000000..032c33b7068c --- /dev/null +++ b/tests/expected/c-ffi-void/main.rs @@ -0,0 +1,30 @@ +// Copyright Kani Contributors +// SPDX-License-Identifier: Apache-2.0 OR MIT +// kani-flags: -Z c-ffi --c-lib tests/expected/c-ffi-void/void_fns.c + +//! Check that a C function returning `void` is really executed, both when called directly and +//! through a Rust function pointer: an assertion its side effect contradicts must fail, and a +//! cover of the effect must be satisfied. (A dropped call, or a pointer call that resolved to no +//! target, would let the assertion pass.) + +extern "C" { + /// `void decrement(uint32_t *p)` in C. + fn decrement(p: &mut u32); +} + +#[kani::proof] +fn check_direct_call() { + let mut x: u32 = 1; + unsafe { decrement(&mut x) }; + kani::cover!(x == 0, "direct call decremented"); + assert!(x == 1, "direct call left x unchanged"); +} + +#[kani::proof] +fn check_fn_ptr_call() { + let mut x: u32 = 1; + let f: unsafe extern "C" fn(&mut u32) = decrement; + unsafe { f(&mut x) }; + kani::cover!(x == 0, "pointer call decremented"); + assert!(x == 1, "pointer call left x unchanged"); +} diff --git a/tests/expected/c-ffi-void/void_fns.c b/tests/expected/c-ffi-void/void_fns.c new file mode 100644 index 000000000000..f1f715001973 --- /dev/null +++ b/tests/expected/c-ffi-void/void_fns.c @@ -0,0 +1,6 @@ +// Copyright Kani Contributors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +#include + +void decrement(uint32_t *p) { *p -= 1; } diff --git a/tests/kani/ForeignItems/void_fns.c b/tests/kani/ForeignItems/void_fns.c new file mode 100644 index 000000000000..33a3e54c267f --- /dev/null +++ b/tests/kani/ForeignItems/void_fns.c @@ -0,0 +1,26 @@ +// Copyright Kani Contributors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +// C functions returning `void`, for void_return.rs. They are plain C: Kani +// must link them as they are (no `struct Unit` return type). + +#include + +uint32_t COUNTER = 0; + +void increment(void) { COUNTER++; } + +void set_counter(uint32_t value) { COUNTER = value; } + +void add_into(uint32_t *out, uint32_t a, uint32_t b) { *out = a + b; } + +void swap(uint32_t *a, uint32_t *b) +{ + uint32_t tmp = *a; + *a = *b; + *b = tmp; +} + +void add_one(uint32_t *p) { *p += 1; } + +void double_it(uint32_t *p) { *p *= 2; } diff --git a/tests/kani/ForeignItems/void_return.rs b/tests/kani/ForeignItems/void_return.rs new file mode 100644 index 000000000000..dc52a2f2e631 --- /dev/null +++ b/tests/kani/ForeignItems/void_return.rs @@ -0,0 +1,71 @@ +// Copyright Kani Contributors +// SPDX-License-Identifier: Apache-2.0 OR MIT +// kani-flags: -Z c-ffi --c-lib tests/kani/ForeignItems/void_fns.c + +//! Check that C functions returning `void`, declared in Rust without a return type, link with +//! their C definitions and are called. Each harness asserts on the function's side effect, so +//! the call cannot be dropped. +//! See and +//! . + +extern "C" { + static mut COUNTER: u32; + + fn increment(); + fn set_counter(value: u32); + fn add_into(out: *mut u32, a: u32, b: u32); + fn swap(a: &mut u32, b: &mut u32); + fn add_one(p: &mut u32); + fn double_it(p: &mut u32); +} + +/// The minimal case: no parameters, no result, a global side effect. +#[kani::proof] +fn check_void_no_args() { + unsafe { + assert_eq!(COUNTER, 0); + increment(); + increment(); + assert_eq!(COUNTER, 2); + } +} + +/// A symbolic argument. +#[kani::proof] +fn check_void_with_arg() { + let value: u32 = kani::any(); + unsafe { + set_counter(value); + assert_eq!(COUNTER, value); + } +} + +/// Several parameters, the result written through a raw pointer. +#[kani::proof] +fn check_void_out_param() { + let a: u32 = kani::any(); + let b: u32 = kani::any(); + let mut out: u32 = kani::any(); + unsafe { add_into(&mut out, a, b) }; + assert_eq!(out, a.wrapping_add(b)); +} + +/// Two pointer parameters. +#[kani::proof] +fn check_void_two_pointers() { + let (x, y): (u32, u32) = (kani::any(), kani::any()); + let (mut a, mut b) = (x, y); + unsafe { swap(&mut a, &mut b) }; + assert_eq!((a, b), (y, x)); +} + +/// A function pointer that may point to either of two `void` functions. +#[kani::proof] +fn check_void_fn_ptr_two_targets() { + let before: u32 = kani::any_where(|v| *v < 1000); + let use_add: bool = kani::any(); + let f: unsafe extern "C" fn(&mut u32) = if use_add { add_one } else { double_it }; + let mut x = before; + unsafe { f(&mut x) }; + assert_eq!(x, if use_add { before + 1 } else { before * 2 }); +}