Skip to content

Instantly share code, notes, and snippets.

@lqd
Created June 30, 2016 06:34
Show Gist options
  • Save lqd/98450b32c115df630f38c8cf4bbe69d7 to your computer and use it in GitHub Desktop.
Save lqd/98450b32c115df630f38c8cf4bbe69d7 to your computer and use it in GitHub Desktop.
unsafe fn generate_start_fn_wrapper(module: BinaryenModuleRef,
c_strings: &mut Vec<CString>,
did: DefId,
name: &str,
c_string: &CString) -> BinaryenFunctionRef {
// import print i32
let print_i32_name = CString::new("print_i32").expect("");
let print_i32 = print_i32_name.as_ptr();
c_strings.push(print_i32_name);
let spectest_module_name = CString::new("spectest").expect("");
let spectest_module = spectest_module_name.as_ptr();
c_strings.push(spectest_module_name);
let print_fn_name = CString::new("print").expect("");
let print_fn = print_fn_name.as_ptr();
c_strings.push(print_fn_name);
let print_i32_args = [BinaryenInt32()];
let print_i32_ty = BinaryenAddFunctionType(module,
print_i32,
BinaryenNone(),
print_i32_args.as_ptr(),
BinaryenIndex(1));
BinaryenAddImport(module,
print_i32,
spectest_module,
print_fn,
print_i32_ty);
// #[start] wrapper fn
let wrapper_name = format!("rustfn-{}-{}-wrapper", did.krate, name);
let wrapper_name = CString::new(wrapper_name).expect("");
let wrapper_name_ptr = wrapper_name.as_ptr();
c_strings.push(wrapper_name);
let wrapper_ty = BinaryenAddFunctionType(module,
wrapper_name_ptr,
BinaryenNone(),
ptr::null_mut(),
BinaryenIndex(0));
// print the result of calling start_fn(1, 0)
let start_operands = [BinaryenConst(module, BinaryenLiteralInt32(1)),
BinaryenConst(module, BinaryenLiteralInt32(0))];
let start_call = [BinaryenCall(module,
c_string.as_ptr(),
start_operands.as_ptr(),
BinaryenIndex(start_operands.len() as _),
BinaryenInt32())];
let print_call = BinaryenCallImport(module,
print_i32,
start_call.as_ptr(),
BinaryenIndex(start_call.len() as _),
BinaryenNone());
BinaryenAddFunction(module,
wrapper_name_ptr,
wrapper_ty,
ptr::null_mut(),
BinaryenIndex(0),
print_call)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment