Is accessing WebAssembly memory using TypedArrays incorrect on Big Endian systems?

Hey all. I think I've found an endianness compatibility issue with the way people are usually accessing WebAssembly memory, which I've described here: https://github.com/mdn/content/issues/25569.

The basic idea is that WebAssembly linear memory is always little-endian. But people are accessing it with new Uint32Array and the like, which interpret multi-byte accesses using the platform endianness, which will break on big-endian platforms.

I was hoping some people experienced with the ECMAScript and Wasm specs could weigh in on whether this is a correct reading. Am I along the right lines here?

1 Like

TypedArray use the native endianness for performance, whereas DataView will default to big endian. As far as I know this is fairly well documented.

TypedArray actually let you discover a lot of other implementation specific quirks, like how there are in fact multiple NaN values.

The fact that WebAssembly uses little endian can indeed create issues, but since neither spec can change that at this point, the best that could be done is to make the compatibility issue clear in developer resources for those programs that share memory between JS and WebAssembly. I actually doubt that JS programs reading WebAssembly written memory (or vice versa) would rely on TypedArray since I'd assume the shared memory would usually contain data of various types.

So the impression is right that developers should be discouraged from using anything other than {Ui,I}nt8Array to view WASM memory? Note that using Uint8Array to view memory is listed in the resizable arraybuffer usage examples. Currently, MDN has examples that create Uint32Arrays from memory.buffer, so if this is nonportable, we would need to update our content.

UInt8Array is fine in itself. The problem is for any multi-byte data. So the portability issue is regarding any multi-byte TypedArray.

I assume the MDN examples should be updated, yes.

1 Like

Thanks for confirming. The MDN content will be updated.

1 Like

I'm wondering if an option on the constructor of TypedArrays would make sense to force a certain endianness interpretation of the bytes. That would have to go through the proposal process. I am still doubtful however that many use cases would use multi-byte TypedArray to access Wasm memory.