Skip to content

The TypedArray constructor validates its ArrayBuffer arguments in the wrong order #1738

Description

@d01c2

Reproduction

// the misaligned offset should be reported before the buffer is examined
const buffer = new ArrayBuffer(8);
buffer.transfer();
new Uint16Array(buffer, 1);

// the length should be coerced before the offset is bounds-checked
new Float16Array(new ArrayBuffer(1), 4, { valueOf() { throw 0; } });

Expected

RangeError for the first, and the 0 thrown by valueOf for the second.

V8 (15.6.20):

$ v8 -e 'const buffer = new ArrayBuffer(8); buffer.transfer(); new Uint16Array(buffer, 1);'
unnamed:1: RangeError: start offset of Uint16Array should be a multiple of 2
$ v8 -e 'new Float16Array(new ArrayBuffer(1), 4, { valueOf() { throw 0; } });'
unnamed:1: 0

Actual (QuickJS-ng)

$ qjs -e 'const buffer = new ArrayBuffer(8); buffer.transfer(); new Uint16Array(buffer, 1);'
TypeError: ArrayBuffer is detached
$ qjs -e 'new Float16Array(new ArrayBuffer(1), 4, { valueOf() { throw 0; } });'
RangeError: invalid offset

Spec

InitializeTypedArrayFromArrayBuffer rejects a misaligned offset immediately after ToIndex(byteOffset), then coerces length with ToIndex, and only after that tests the buffer for detachment and checks the offset against the buffer's byte length.

QuickJS performs the same checks in a different order, testing the buffer first and coercing length last. Every check is present and each gives the right answer in isolation, so the two programs above are two symptoms of one reordering rather than two separate defects. Varying which condition holds makes the order readable:

$ qjs -e 'const b = new ArrayBuffer(8); b.transfer(); new Uint16Array(b, 4, { valueOf() { throw 0; } });'
TypeError: ArrayBuffer is detached      # V8: 0
$ qjs -e 'new Uint16Array(new ArrayBuffer(8), 1);'
RangeError: invalid offset              # V8: RangeError, same step
$ qjs -e 'new Uint16Array(new ArrayBuffer(2), 8, { valueOf() { throw 0; } });'
RangeError: invalid offset              # V8: 0
$ qjs -e 'new Uint16Array(new ArrayBuffer(8), 4, { valueOf() { throw 0; } });'
0                                       # V8: 0, both agree once nothing else fails

JavaScriptCore, SpiderMonkey, GraalJS and V8 agree with the specified order on all of these.

Versions

  • QuickJS-ng: 0.17.0
  • V8: 15.6.20

Activity

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

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