8000 Rework ffi calls by CohenArthur · Pull Request #490 · jinko-core/jinko · GitHub
[go: up one dir, main page]

Skip to content
Merged
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
27 changes: 27 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,14 @@ nom = "7.0"
linefeed = { version = "0.6", optional = true }
downcast-rs = "1.2"
anyhow = "1.0"
libffi = { version = "2.0.0", optional = true }
libloading = { version = "0.7", optional = true }
lazy_static = "1.4"

[features]
default = ["repl", "ffi"]
repl = ["linefeed"]
ffi = ["libloading"]
ffi = ["libloading", "libffi"]

[dev-dependencies]
libc = "0.2"
Expand Down
147 changes: 104 additions & 43 deletions src/ffi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@
//! FIXME

use crate::instruction::{FunctionCall, FunctionDec};
use crate::log;
use crate::{
Context, ErrKind, Error, FromObjectInstance, JkInt, JkString, ObjectInstance, ToObjectInstance,
log, Context, ErrKind, Error, FromObjectInstance, JkBool, JkFloat, JkInt, JkString,
ObjectInstance, ToObjectInstance,
};

use libffi::high::{arg, call as ffi_call, Arg as FfiArg, CodePtr};
use libloading::{Library, Symbol};
use std::ffi::CString;
use std::mem::transmute;
use std::os::raw::c_char;

use std::ffi::{CStr, CString};
use std::path::{Path, PathBuf};

fn find_lib(paths: &[PathBuf], lib_path: &Path) -> Result<Library, Error> {
Expand Down Expand Up @@ -87,6 +87,13 @@ pub fn link_with(ctx: &mut Context, lib_path: PathBuf) -> Result<(), Error> {
Ok(())
}

enum FfiJkArg {
Int(i64),
Float(f64),
Pointer(*const ()),
Error,
}

pub fn execute(
dec: &FunctionDec,
call: &FunctionCall,
Expand All @@ -95,65 +102,119 @@ pub fn execute(
log!("ext call: {}", call.name());
let sym = call.name().as_bytes();

// FIXME: Don't unwrap
let args: Vec<ObjectInstance> = call
let mut errors = vec![];

let jk_args: Vec<ObjectInstance> = call
.args()
.iter()
.map(|arg| arg.execute(ctx).unwrap())
.collect();

// We need pointers for strings to live long enough... So keep them here
// for the duration of the function call
let mut strings = Vec::new();

// FIXME: Don't unwrap
let ffi_jk_args: Vec<FfiJkArg> = jk_args
.iter()
.zip(
dec.args()
.iter()
.map(|dec_arg| dec_arg.get_type().id().to_owned()),
)
.map(|(arg_value, arg_ty)| match arg_ty.as_str() {
"int" => FfiJkArg::Int(JkInt::from_instance(arg_value).0),
"bool" => FfiJkArg::Int(JkBool::from_instance(arg_value).0 as i64),
"float" => FfiJkArg::Float(JkFloat::from_instance(arg_value).0),
"string" => {
let arg = JkString::from_instance(arg_value).0;
10000 let arg = CString::new(arg).unwrap();
let res = FfiJkArg::Pointer(arg.as_ptr() as *const ());
strings.push(arg);
res
}
_ => {
errors.push(Error::new(ErrKind::ExternFunc).with_msg(format!(
"ffi module does not support calls with arguments of type {} yet",
arg_ty
)));
FfiJkArg::Error
}
})
.collect();

if !errors.is_empty() {
errors.into_iter().for_each(|e| ctx.error(e));
return Err(Error::new(ErrKind::ExternFunc));
}

// At this point, we cannot have errors anymore and will have returned from
// the function instead of making the call
let args: Vec<FfiArg> = ffi_jk_args
.iter()
.map(|ffi_jk_arg| match ffi_jk_arg {
FfiJkArg::Int(i) => arg(i),
FfiJkArg::Float(f) => arg(f),
FfiJkArg::Pointer(p) => arg(p),
_ => unreachable!(),
})
.collect();

for lib in ctx.libs().iter() {
// FIXME: Rework this
let func = unsafe { lib.get::<Symbol<fn()>>(sym) };
let func = match func {
Ok(func) => func,
Ok(func) => CodePtr::from_ptr(unsafe { func.into_raw().into_raw() }),
Err(_) => continue,
};
match call.args().len() {
0 => match dec.ty() {

unsafe {
match dec.ty() {
None => {
func();
ffi_call::<()>(func, &args);
return Ok(None);
}
Some(ty) => match ty.id() {
"int" => {
let func = unsafe { transmute::<fn(), fn() -> i64>(**func) };
let res = func();
return Ok(Some(JkInt::from(res).to_instance()));
return Ok(Some(
JkInt::from(ffi_call::<i64>(func, &args)).to_instance(),
))
}
_ => unreachable!(),
},
},
1 => match dec.args()[0].get_type().id() {
"string" => match dec.ty() {
None => {
let func = unsafe { transmute::<fn(), fn(*const c_char)>(**func) };
let arg = JkString::from_instance(&args[0]).0;
let arg = CString::new(arg.as_str()).unwrap();
let arg = arg.as_ptr();
func(arg);
return Ok(None);
"bool" => {
return Ok(Some(
JkBool::from(ffi_call::<i32>(func, &args) != 0).to_instance(),
))
}
"string" => {
let raw_ptr = ffi_call::<*mut i8>(func, &args);
log!("Pointer: {:p}", raw_ptr);
// FIXME: Do we really want to return an empty string if the ffi
// function returns NULL?
return if raw_ptr.is_null() {
Ok(Some(JkString::from(String::new()).to_instance()))
} else {
Ok(Some(
JkString::from(CStr::from_ptr(raw_ptr).to_str().unwrap())
.to_instance(),
))
};
}
_ => {
ctx.error(Error::new(ErrKind::ExternFunc).with_msg(format!(
"ffi module does not support {} as a return type",
ty
)));
return Err(Error::new(ErrKind::ExternFunc));
}
Some(ty) => match ty.id() {
"int" => {
let func =
unsafe { transmute::<fn(), fn(*const c_char) -> i64>(**func) };
let arg = JkString::from_instance(&args[0]).0;
let arg = CString::new(arg.as_str()).unwrap();
let arg = arg.as_ptr();
let res = func(arg);
return Ok(Some(JkInt::from(res).to_instance()));
}
_ => unreachable!(),
},
},
_ => unreachable!(),
},
_ => unreachable!(),
}
}
}

Err(Error::new(ErrKind::ExternFunc)
.with_msg(format!("cannot call external function `{}`", call.name())))
Err(Error::new(ErrKind::ExternFunc).with_msg(format!(
"could not find external function `{}`",
call.name()
)))
}

#[cfg(test)]
Expand Down
36 changes: 18 additions & 18 deletions tests/fixtures/clib/lib.c
Original file line number Diff line number Diff line change
@@ -1,26 +1,26 @@
// Multiple arguments are passed to native functions via a "vector" of JkInstances. It's
// actually a singular instance that contains multiple instances. FIXME Is it?
// Multiple arguments are passed to native functions via a "vector" of
// JkInstances. It's actually a singular instance that contains multiple
// instances. FIXME Is it?

// We need to represent any jinko values safely in order to use a singular function
// type when getting functions on the Rust side from the shared library.
// We have to use a Symbol<T>, which isn't flexible at all. It can be a Symbol<fn(i32) -> i32>,
// or Symbol<i32> for a value, but we cannot change the type dynamically (at least not
// simply, and not without reflection).
// We need to represent any jinko values safely in order to use a singular
// function type when getting functions on the Rust side from the shared
// library. We have to use a Symbol<T>, which isn't flexible at all. It can be a
// Symbol<fn(i32) -> i32>, or Symbol<i32> for a value, but we cannot change the
// type dynamically (at least not simply, and not without reflection).

#include <stdio.h>
#include <string.h>

int square(int a) {
return a * a;
}
int square(int a) { return a * a; }

int no_arg() {
return 15;
}
int no_arg() { return 15; }

int add(int lhs, int rhs) {
return lhs + rhs;
}
int add(int lhs, int rhs) { return lhs + rhs; }

void print_something() {
printf("jinko called\n");
void print_something() { printf("jinko called\n"); }

void receive_const_char_ptr(const char *ptr) {
printf("received: `%s` (%lu bytes)\n", ptr, strlen(ptr));
}

const char *return_const_char_ptr(void) { return "C library returned!"; }
Binary file modified tests/fixtures/clib/lib.so
Binary file not shown.
0