Skip to content

support SharedArrayBuffers with crypto.getRandomValues #421

Open

Description

@vapier

(forking off of #213)

trying to use crypto.getRandomValues on TypedArrays backed by a SharedArrayBuffer fails. example from Chrome JS console:

// works fine
> ab = new ArrayBuffer(10); u8 = new Uint8Array(ab); crypto.getRandomValues(u8);
Uint8Array(10) [134, 194, 41, 240, 231, 151, 173, 248, 154, 113, buffer: ArrayBuffer(10), byteLength: 10, byteOffset: 0, length: 10, Symbol(Symbol.toStringTag): 'Uint8Array']

// fails
> ab = new SharedArrayBuffer(10); u8 = new Uint8Array(ab); crypto.getRandomValues(u8);
VM253:1 Uncaught TypeError: Failed to execute 'getRandomValues' on 'Crypto': The provided ArrayBufferView value must not be shared.

supporting SharedArrayBuffers is important for me for 2 reasons:

  • using threads with WASI requires the WASM module be backed by a SharedArrayBuffer
  • message passing between main thread & Worker thread has lower overhead with SharedArrayBuffer

it can obviously be worked around with creating a temporary ArrayBuffer and then copying between them, but seems better to not waste the CPU cycles.

ab = new ArrayBuffer(10)
sab = new SharedArrayBuffer(10)
u8 = new Uint8Array(ab)
su8 = new Uint8Array(sab)
crypto.getRandomValues(u8)
su8.set(u8)

I'm mostly interested in crypto.getRandomValues, but if there's other APIs that would benefit, throw them in the pile I guess.

Activity

  1. Frosne commented on Jan 26, 2026

    @Frosne
    Member

    Hi :)
    Thanks for bringing this up. I was wondering if you could share a bit more context on why you think this belongs in the standard itself?

    Do you have insight into how many developers might need this? Understanding the expected demand would be really helpful :)

  2. vapier commented on Jan 26, 2026

    @vapier
    MemberAuthor

    anyone wanting to do threads and use crypto APIs. if you use WASI, their getrandom APIs are all based on this function (which is how I noticed it).

    if it isn't in the standard, then i'm not sure how it'd work otherwise. implementers aren't going to support this if the standard doesn't say it should work.

    when these APIs only support ArrayBuffers and not SharedArrayBuffers, it feels like an oversight rather than intentional.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions