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

c#: Handle Cabi realloc post return #1145

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
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
179 changes: 125 additions & 54 deletions crates/csharp/src/function.rs
Original file line number Diff line number Diff line change
Expand Up @@ -716,7 +716,7 @@ impl Bindgen for FunctionBindgen<'_, '_> {
// );
}

Instruction::ListCanonLower { element, realloc } => {
Instruction::ListCanonLower { element, .. } => {
let list: &String = &operands[0];
match self.interface_gen.direction {
Direction::Import => {
Expand All @@ -738,29 +738,20 @@ impl Bindgen for FunctionBindgen<'_, '_> {
results.push(format!("({list}).Length"));
}
Direction::Export => {
let (_, ty) = list_element_info(element);
let address = self.locals.tmp("address");
let buffer = self.locals.tmp("buffer");
let gc_handle = self.locals.tmp("gcHandle");
let size = self.interface_gen.csharp_gen.sizes.size(element).size_wasm32();
let byte_length = self.locals.tmp("byteLength");
uwrite!(
self.src,
"
byte[] {buffer} = new byte[({size}) * {list}.Length];
Buffer.BlockCopy({list}.ToArray(), 0, {buffer}, 0, ({size}) * {list}.Length);
var {gc_handle} = GCHandle.Alloc({buffer}, GCHandleType.Pinned);
var {address} = {gc_handle}.AddrOfPinnedObject();
var {byte_length} = ({size}) * {list}.Length;
var {address} = NativeMemory.Alloc((nuint)({byte_length}));
{list}.AsSpan().CopyTo(new Span<{ty}>({address},{byte_length}));
"
);

if realloc.is_none() {
self.needs_cleanup = true;
uwrite!(
self.src,
"
cleanups.Add(()=> {gc_handle}.Free());
");
}
results.push(format!("((IntPtr)({address})).ToInt32()"));
results.push(format!("(int)({address})"));
results.push(format!("{list}.Length"));
}
}
Expand All @@ -785,33 +776,45 @@ impl Bindgen for FunctionBindgen<'_, '_> {

Instruction::StringLower { realloc } => {
let op = &operands[0];
let interop_string = self.locals.tmp("interopString");
let str_ptr = self.locals.tmp("strPtr");
let utf8_bytes = self.locals.tmp("utf8Bytes");
let length = self.locals.tmp("length");
let gc_handle = self.locals.tmp("gcHandle");
uwriteln!(
self.src,
"
var {utf8_bytes} = Encoding.UTF8.GetBytes({op});
var {length} = {utf8_bytes}.Length;
var {gc_handle} = GCHandle.Alloc({utf8_bytes}, GCHandleType.Pinned);
var {interop_string} = {gc_handle}.AddrOfPinnedObject();
"
);

if realloc.is_none() {
results.push(format!("{interop_string}.ToInt32()"));
uwriteln!(
self.src,
"
var {utf8_bytes} = Encoding.UTF8.GetBytes({op});
var {length} = {utf8_bytes}.Length;
var {gc_handle} = GCHandle.Alloc({utf8_bytes}, GCHandleType.Pinned);
var {str_ptr} = {gc_handle}.AddrOfPinnedObject();
"
);

self.needs_cleanup = true;
uwrite!(
self.src,
"
cleanups.Add(()=> {gc_handle}.Free());
");
"
);
results.push(format!("{str_ptr}.ToInt32()"));
} else {
results.push(format!("{interop_string}.ToInt32()"));
let string_span = self.locals.tmp("stringSpan");
uwriteln!(
self.src,
"
var {string_span} = {op}.AsSpan();
var {length} = Encoding.UTF8.GetByteCount({string_span});
var {str_ptr} = NativeMemory.Alloc((nuint){length});
Encoding.UTF8.GetBytes({string_span}, new Span<byte>({str_ptr}, {length}));
"
);
results.push(format!("(int){str_ptr}"));
}
results.push(format!("{length}"));

results.push(format!("{length}"));
if FunctionKind::Freestanding == *self.kind || self.interface_gen.direction == Direction::Export {
self.interface_gen.require_interop_using("System.Text");
self.interface_gen.require_interop_using("System.Runtime.InteropServices");
Expand All @@ -834,7 +837,7 @@ impl Bindgen for FunctionBindgen<'_, '_> {
));
}

Instruction::ListLower { element, .. } => {
Instruction::ListLower { element, realloc } => {
let Block {
body,
results: block_results,
Expand All @@ -859,22 +862,37 @@ impl Bindgen for FunctionBindgen<'_, '_> {
);
let ret_area = self.locals.tmp("retArea");

self.needs_cleanup = true;
uwrite!(
self.src,
"
void* {address};
if (({size} * {list}.Count) < 1024) {{
var {ret_area} = stackalloc {element_type}[({array_size}*{list}.Count)+1];
{address} = (void*)(((int){ret_area}) + ({align} - 1) & -{align});
}}
else
{{
var {buffer_size} = {size} * (nuint){list}.Count;
{address} = NativeMemory.AlignedAlloc({buffer_size}, {align});
cleanups.Add(()=> NativeMemory.AlignedFree({address}));
}}
match realloc {
None => {
self.needs_cleanup = true;
uwrite!(self.src,
"
void* {address};
if (({size} * {list}.Count) < 1024) {{
var {ret_area} = stackalloc {element_type}[({array_size}*{list}.Count)+1];
{address} = (void*)(((int){ret_area}) + ({align} - 1) & -{align});
}}
else
{{
var {buffer_size} = {size} * (nuint){list}.Count;
{address} = NativeMemory.AlignedAlloc({buffer_size}, {align});
}}
cleanups.Add(()=> NativeMemory.AlignedFree({address}));
"
);
}
Some(_) => {
uwrite!(self.src,
"
var {buffer_size} = {size} * (nuint){list}.Count;
void* {address} = NativeMemory.AlignedAlloc({buffer_size}, {align});
"
);
}
}

uwrite!(self.src,
"
for (int {index} = 0; {index} < {list}.Count; ++{index}) {{
{ty} {block_element} = {list}[{index}];
int {base} = (int){address} + ({index} * {size});
Expand Down Expand Up @@ -1018,7 +1036,7 @@ impl Bindgen for FunctionBindgen<'_, '_> {
}
}

Instruction::Return { amt: _, func } => {
Instruction::Return { amt, .. } => {
if self.needs_cleanup {
self.src.insert_str(0, "var cleanups = new List<Action>();
");
Expand All @@ -1031,7 +1049,7 @@ impl Bindgen for FunctionBindgen<'_, '_> {
}

if !matches!((self.interface_gen.direction, self.kind), (Direction::Import, FunctionKind::Constructor(_))) {
match func.results.len() {
match *amt {
0 => (),
1 => {
self.handle_result_import(operands);
Expand All @@ -1047,19 +1065,72 @@ impl Bindgen for FunctionBindgen<'_, '_> {
Instruction::Malloc { .. } => unimplemented!(),

Instruction::GuestDeallocate { .. } => {
uwriteln!(self.src, r#"Console.WriteLine("TODO: deallocate buffer for indirect parameters");"#);
// the original alloc here comes from cabi_realloc implementation (wasi-libc in .net)
uwriteln!(self.src, r#"NativeMemory.Free((void*){});"#, operands[0]);
pavelsavara marked this conversation as resolved.
Show resolved Hide resolved
}

Instruction::GuestDeallocateString => {
uwriteln!(self.src, r#"Console.WriteLine("TODO: deallocate buffer for string");"#);
uwriteln!(self.src, r#"NativeMemory.Free((void*){});"#, operands[0]);
}

Instruction::GuestDeallocateVariant { .. } => {
uwriteln!(self.src, r#"Console.WriteLine("TODO: deallocate buffer for variant");"#);
Instruction::GuestDeallocateVariant { blocks } => {
let cases = self
.blocks
.drain(self.blocks.len() - blocks..)
.enumerate()
.map(|(i, Block { body, results, .. })| {
assert!(results.is_empty());

format!(
"case {i}: {{
{body}
break;
}}"
)
})
.collect::<Vec<_>>()
.join("\n");

let op = &operands[0];

uwrite!(
self.src,
"
switch ({op}) {{
{cases}
}}
"
);
}

Instruction::GuestDeallocateList { .. } => {
uwriteln!(self.src, r#"Console.WriteLine("TODO: deallocate buffer for list");"#);
Instruction::GuestDeallocateList { element: element_type } => {
let Block {
body,
results: block_results,
base,
element: _,
} = self.blocks.pop().unwrap();
assert!(block_results.is_empty());

let address = &operands[0];
let length = &operands[1];
let size = self.interface_gen.csharp_gen.sizes.size(element_type).size_wasm32();

if !body.trim().is_empty() {
let index = self.locals.tmp("index");

uwrite!(
self.src,
"
for (int {index} = 0; {index} < {length}; ++{index}) {{
int {base} = (int){address} + ({index} * {size});
{body}
}}
"
);
}

uwriteln!(self.src, r#"NativeMemory.Free((void*){});"#, operands[0]);
}

Instruction::HandleLower {
Expand Down
31 changes: 27 additions & 4 deletions crates/csharp/src/interface.rs
Original file line number Diff line number Diff line change
Expand Up @@ -389,7 +389,7 @@ impl InterfaceGenerator<'_> {
&func.item_name(),
&func.kind,
(0..sig.params.len()).map(|i| format!("p{i}")).collect(),
results,
results.clone(),
);

abi::call(
Expand Down Expand Up @@ -460,13 +460,36 @@ impl InterfaceGenerator<'_> {
"#
);

if !sig.results.is_empty() {
if abi::guest_export_needs_post_return(self.resolve, func) {
let params = sig
.results
.iter()
.enumerate()
.map(|(i, param)| {
let ty = crate::world_generator::wasm_type(*param);
format!("{ty} p{i}")
})
.collect::<Vec<_>>()
.join(", ");

let mut bindgen = FunctionBindgen::new(
self,
"INVALID",
&func.kind,
(0..sig.results.len()).map(|i| format!("p{i}")).collect(),
Vec::new(),
);

abi::post_return(bindgen.interface_gen.resolve, func, &mut bindgen, false);

let src = bindgen.src;

uwrite!(
self.csharp_interop_src,
r#"
[UnmanagedCallersOnly(EntryPoint = "cabi_post_{export_name}")]
{access} static void cabi_post_{interop_name}({wasm_result_type} returnValue) {{
Console.WriteLine("TODO: cabi_post_{export_name}");
{access} static unsafe void cabi_post_{interop_name}({params}) {{
{src}
}}
"#
);
Expand Down
Loading