Skip to content

Javy QuickJS and host function #754

@kakawait

Description

@kakawait

I'm pretty sure isn't a bug! I may misunderstand a concept, but I'm trying to use javy + quickjs with host function.

I've snippetted something like (which is totally a copy past of a doc snippet + UT code)

public static void main(String[] args) {
    var func = new HostFunction(
            "console2",
            "log2",
            List.of(ValueType.I32, ValueType.I32),
            List.of(),
            (Instance instance, long... args2) -> {
                var len = (int) args2[0];
                var offset = (int) args2[1];
                var message = instance.memory().readString(offset, len);
                System.out.println(message);
                return null;
            });


    ByteArrayInputStream stdin = new ByteArrayInputStream("".getBytes(UTF_8));
    var stdout = new ByteArrayOutputStream();
    var stderr = new ByteArrayOutputStream();

    var wasiOpts =
            WasiOptions.builder()
                    .withStdout(stdout)
                    .withStderr(stderr)
                    .withStdin(stdin)
                    .build();

    var wasi = WasiPreview1.builder().withOptions(wasiOpts).build();
    var quickjs =
            Instance.builder(loadModule("quickjs-provider.javy-dynamic.wasm"))
                    .withImportValues(
                            ImportValues.builder().addFunction(func).addFunction(wasi.toHostFunctions()).build())
                    .build();

    var greetingMsg = "Hello QuickJS!";

    byte[] jsCode = ("import { log2 } from 'console2'; console2.log2('test');").getBytes(UTF_8);
    var ptr =
            quickjs.export("canonical_abi_realloc")
                    .apply(
                            0, // original_ptr
                            0, // original_size
                            1, // alignment
                            jsCode.length // new size
                    )[0];

    quickjs.memory().write((int) ptr, jsCode);
    var aggregatedCodePtr = quickjs.export("compile_src").apply(ptr, jsCode.length)[0];

    var codePtr = quickjs.memory().readI32((int) aggregatedCodePtr); // 32 bit
    var codeLength = quickjs.memory().readU32((int) aggregatedCodePtr + 4);

    quickjs.export("eval_bytecode").apply(codePtr, codeLength);

    // stderr?
    System.out.println(stderr.toString(UTF_8));
}

But when running I've following error

Exception in thread "main" com.dylibso.chicory.runtime.TrapException: Trapped on unreachable instruction

Thus I'd like to know, if it's even possible to mix dynamic javy with quickjs and host function?
And yes, have you some tips for me?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions