quickjs-emscripten
quickjs-emscripten copied to clipboard
exchange TypedArray or Buffer between host and vm
can i exchange TypedArray or Buffer between host and vm ?
i want to use libsodium-wrapper in vm, but it need crypto.getRandomValues
function,
so when i try to impl the crypto.getRandomValues in vm, i notice that this function is a node impl and the web polyfill use randombytes to wrap browser crypto.randomBytes
function to impl crypto.getRandomValues
function.
but the randomBytes
and getRandomValues
all process the Buffer or TypedArray .
// crypto.randomBytes define in nodejs crypto
function randomBytes(size: number): Buffer;
function randomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void;
function pseudoRandomBytes(size: number): Buffer;
function pseudoRandomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void;
// crypto.getRandomValues define in `lib.dom.d.ts`
getRandomValues<T extends ArrayBufferView | null>(array: T): T;
so , i think it can impl like :
vm request some random -> tell the host -> host generate crypto random Buffer -> pass random Buffer to vm -> get the crypto random Buffer
vm.randomBytes() call -> host.randomBytes() call -> host return random buffer -> vm.randomBytes() return
can i pass TypedArray or Buffer from host to vm ?
Currently you cannot directly pass a ArrayBuffer or similar to the VM, although it’s an interesting use-case, because we might be able to expose raw data like this directly to the VM without copying in the future.
For now, I suggest converting your random bytes to an Array of number on the host, sending to the vm, and converting from array of number to TypedArray inside the guest.
This was released in v0.24.0: https://github.com/justjake/quickjs-emscripten/blob/main/CHANGELOG.md#v0240
Docs: https://github.com/justjake/quickjs-emscripten/blob/main/doc/quickjs-emscripten/classes/QuickJSContext.md#newarraybuffer