rsepassi / zigcoro

A Zig coroutine library
BSD Zero Clause License
83 stars 6 forks source link

segmentation fault on xawait #21

Open Pismice opened 1 month ago

Pismice commented 1 month ago

When running this basic code I get a segmentation fault on the line where I xawait.

This is the code:

const libcoro = @import("libcoro");

fn myCoroutine(x: *usize) usize {
    x.* += 1;
    libcoro.xsuspend();
    x.* += 3;
    libcoro.xsuspend();
    return x.* + 20;
}

pub fn main() !void {
    const allocator = std.heap.page_allocator;
    const stack = try libcoro.stackAlloc(allocator, null);
    //    defer allocator.free(stack);

    var x: usize = 0;

    const frame = try libcoro.xasync(myCoroutine, .{&x}, stack);
    const res = libcoro.xawait(frame);

    std.debug.print("res: {}\n", .{res});
}

This is the backtrace:

 Segmentation fault at address 0x0
/home/tetratrux/.cache/zig/p/122058b315816dbabd2a812fb22d5670c4b3a4ca8e12ef3b6f02e48de66638e74ff9/src/coro.zig:612:13: 0x10796a4 in check (croco)
        if (magic_number_ptr.* != magic_number or //
            ^
/home/tetratrux/.cache/zig/p/122058b315816dbabd2a812fb22d5670c4b3a4ca8e12ef3b6f02e48de66638e74ff9/src/coro.zig:153:28: 0x1068bde in xsuspendSafe (croco)
    try StackOverflow.check(coro);
                           ^
/home/tetratrux/.cache/zig/p/122058b315816dbabd2a812fb22d5670c4b3a4ca8e12ef3b6f02e48de66638e74ff9/src/coro.zig:132:17: 0x103650b in xsuspend (croco)
    xsuspendSafe() catch |e| {
                ^
/home/tetratrux/.cache/zig/p/122058b315816dbabd2a812fb22d5670c4b3a4ca8e12ef3b6f02e48de66638e74ff9/src/coro.zig:77:39: 0x10338c2 in xawait__anon_2457 (croco)
    while (f.status != .Done) xsuspend();
                                      ^
/home/tetratrux/kDrive/A_HEIG/ZIG/croco/src/main.zig:20:31: 0x10337f8 in main (croco)
    const res = libcoro.xawait(frame);
                              ^
/home/tetratrux/.zvm/0.12.0/lib/std/start.zig:511:37: 0x1033e8e in main (croco)
            const result = root.main() catch |err| {

Any idea why this could happen ?

xdBronch commented 3 weeks ago

iiuc await is only used when the coroutine is completed but you still have suspension points. adding 2 calls to libcoro.xresume(frame); before the call to xawait makes the test case pass with the same being the case using zigs async in 0.10.1. im still quite unfamiliar with zigcoro as well as async in general so someone please correct me if im wrong