Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FFI using type argument as array length #1538

Closed
qsctr opened this issue Jun 30, 2023 · 0 comments
Closed

FFI using type argument as array length #1538

qsctr opened this issue Jun 30, 2023 · 0 comments
Labels
FFI Foreign function interface question Not a task, but rather a question or discussion topic wontfix For issues that we've reviewed and decided do not require changes.

Comments

@qsctr
Copy link
Contributor

qsctr commented Jun 30, 2023

A Cryptol user reports:

I ran into some surprising behavior in the Cryptol FFI yesterday. Let's say you have a foreign function that takes an array whose length is defined as an expression involving a type parameter:

foreign myfunc :
  {n} (fin n)
  => [n + 1][32] -> [32]

The array gets passed to the FFI function as a length followed by a pointer.

#[no_mangle]
#[export_name = "myfunc"]
pub extern "C" fn myfunc(n: usize, v: *const u32) -> u32 {
    eprintln!("In FFI: n = {n}");
    n as u32
}

It looks like Cryptol is passing in the value of the type parameter as the array length, instead of using the value of the expression. Example output:

Cryptol> :l /home/cryptol/ffi_test.cry
Loading module Cryptol
Loading module Main
Loading dynamic library ffi_test.so
Main> let v = [1, 2] : [2][32]
Main> myfunc v
In FFI: n = 1
0x00000001

This is actually the intended behavior. Sequences are not passed as a pair of length and pointer, but rather the pointer only. Additionally, numeric type arguments are passed as size_t's at the beginning of the argument list. Therefore, myfunc receiving n as the first argument rather than n+1 is correct. The size of any array can always be determined since it is some arithmetic expression built from some type arguments which are always passed explicitly. You can read more here and here.

cc @eddywestbrook @weaversa

@qsctr qsctr added question Not a task, but rather a question or discussion topic wontfix For issues that we've reviewed and decided do not require changes. FFI Foreign function interface labels Jun 30, 2023
@qsctr qsctr closed this as completed Jun 30, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
FFI Foreign function interface question Not a task, but rather a question or discussion topic wontfix For issues that we've reviewed and decided do not require changes.
Projects
None yet
Development

No branches or pull requests

1 participant