fubark / cyber

Fast and concurrent scripting.
https://cyberscript.dev
MIT License
1.16k stars 38 forks source link

Can't run on emscripten environment. #56

Closed Andre-LA closed 1 year ago

Andre-LA commented 1 year ago

Hello, I'm trying to run Cyber on the web using emscripten (because of the SDL2 port), however, I getting an runtime error on the process.

Environment

Steps to reproduce

Expected behaviour

The expected behaviour would be seeing this message on the page's console:

creating Cyber VM
Cyber VM created
2
Success!

Observed behaviour

An exception it's thrown, with a stack trace available on the browser's console, on the page's console only creating Cyber VM it's shown, which means that the problem happens on cyVmCreate function call.

Testing code

main.c:

#include <stdio.h>
#include "cyber.h"

// host functions
void hostFetchUrl(const char *url, size_t urlLen) {}
void hostEvalJS(const char *ptr, size_t len) {}
void hostSleep(uint64_t secs, uint64_t nsecs) {}
void hostLogDebug(const char *ptr, size_t len) {}
void hostLogInfo(const char *ptr, size_t len) {}
void hostLogWarn(const char *ptr, size_t len) {}
void hostLogError(const char *ptr, size_t len) {}
double hostMilliTimestamp() {
    return 0.016;
}
void hostFileWrite(uint32_t fid, const char* str, size_t strLen) {
    printf("%s", str);
}

int main(void) {
    printf("creating Cyber VM\n");
    CyVM* vm = cyVmCreate();
    printf("Cyber VM created\n");
    CStr src = cstr(
        "a = 2\n"
        "print a"
    );
    CyValue val;
    int res = cyVmEval(vm, src, &val);
    if (res == CY_Success) {
        printf("Success!\n");
        cyVmRelease(vm, val);
    } else {
        CStr err = cyVmGetLastErrorReport(vm);
        printf("%s\n", err.charz);
    }
    cyVmDestroy(vm);
    return 0;
}

Extra note

The code above works with wasmtime, when using the wasi-sdk with the same cyber build, with (almost) same building steps.

fubark commented 1 year ago

As discussed on Discord, the issue is that Emscripten manages it's own memory while the library is compiled with it's own allocator. If this https://github.com/fubark/cyber/blob/15df569aaeb54d33590854c56fa44826769191b3/src/lib.zig#L32 is changed to alloc = std.heap.c_allocator; it should work. I guess we can also add a build option for this too.

Andre-LA commented 1 year ago

As discussed on discord, with the latest changes, alongside with the change of wasm_allocator to c_allocator on the cited line, the runtime works on emscripten without any problems.