Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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)
})
Expand Down Expand Up @@ -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());
Expand Down Expand Up @@ -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)
Expand Down
7 changes: 6 additions & 1 deletion kani-compiler/src/codegen_cprover_gotoc/codegen/rvalue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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!(),
},
Expand Down
14 changes: 14 additions & 0 deletions tests/expected/c-ffi-void/expected
Original file line number Diff line number Diff line change
@@ -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.
30 changes: 30 additions & 0 deletions tests/expected/c-ffi-void/main.rs
Original file line number Diff line number Diff line change
@@ -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");
}
6 changes: 6 additions & 0 deletions tests/expected/c-ffi-void/void_fns.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// Copyright Kani Contributors
// SPDX-License-Identifier: Apache-2.0 OR MIT

#include <stdint.h>

void decrement(uint32_t *p) { *p -= 1; }
13 changes: 13 additions & 0 deletions tests/kani/ForeignItems/extern_fn_ptr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<unsafe extern "C" fn(u32) -> u32>) -> Option<u32> {
Expand All @@ -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);
}
27 changes: 2 additions & 25 deletions tests/kani/ForeignItems/lib.c
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,6 @@
#include <stdio.h>
#include <string.h>

/// 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;
Expand Down Expand Up @@ -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.
// <https://github.com/model-checking/kani/issues/1817>
struct Unit update_static()
{
S++;
return VoidUnit;
}
void update_static() { S++; }

uint32_t takes_int(uint32_t i) { return i + 2; }

Expand All @@ -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.
// <https://github.com/model-checking/kani/issues/1817>
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; }

Expand Down
26 changes: 26 additions & 0 deletions tests/kani/ForeignItems/void_fns.c
Original file line number Diff line number Diff line change
@@ -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 <stdint.h>

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; }
71 changes: 71 additions & 0 deletions tests/kani/ForeignItems/void_return.rs
Original file line number Diff line number Diff line change
@@ -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 <https://github.com/model-checking/kani/issues/2151> and
//! <https://github.com/model-checking/kani/issues/1817>.

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 });
}
Loading