NativeOptimizations: matrix and vector reads after wrapping typed arrays can use a detached buffer's stale pointer

Aperta
#2,124 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
4/5
Tempo stimato
3-5 giorni
Idoneità per principianti
56/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
cpp
Ambito
backend, security

Direzione di ricerca

Read Plugins/NativeOptimizations/Source/NativeOptimizations.cpp, starting with ReadMatrix and the listed transform and min/max functions. Compare their argument read order with the fix in PR #1883, then inspect the existing NativeOptimizations tests for buffer detachment coverage. Done means all remaining listed sites read script-accessible values before constructing typed array wrappers, with regression tests confirming detached buffers are not accessed.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

Follow-up to the review of #1883, which fixes this pattern in the two splat sorts. Line numbers are from Plugins/NativeOptimizations/Source/NativeOptimizations.cpp on master at 86b4026b.

Pattern

A Napi::TypedArrayOf<T> caches its data pointer and element length when it is constructed. Several NativeOptimizations functions build these wrappers first and then call Get() on another argument (a matrix's _m and its elements, or a vector's _x, _y, _z). A Get() can run JavaScript: a getter, an index accessor on an Array, or a Proxy trap. If that script detaches the buffer (ArrayBuffer.prototype.transfer()) or shrinks a resizable one, the native loop then reads and writes through the stale pointer and length.

ReadMatrix (line 10) calls transform.Get("_m") (line 12) and, for an Array, elements.Get(i) for each element (line 19).

Remaining sites

Function Typed arrays wrapped Read after the wrap Effect
TransformVector3Coordinates (_TransformVector3Coordinates) coordinates, line 66 ReadMatrix(transform), line 68 reads and writes coordinates
TransformVector3Normals (_TransformVector3Normals) normals, line 89 ReadMatrix(transform), line 91 reads and writes normals
TransformVector4Normals (_TransformVector4Normals) normals, line 108 ReadMatrix(transform), line 110 reads and writes normals
ExtractMinAndMaxIndexed (extractMinAndMaxIndexed) positions, line 195; indices as TypedArrayOf<T>, lines 204, 208, 212 minVector/maxVector _x, _y, _z, lines 163–168 reads positions and indices
ExtractMinAndMax (extractMinAndMax) positions, line 222 minVector/maxVector _x, _y, _z, lines 229–234 reads positions
sortSplats positions, line 331; indices, line 333 m.Get(2u), m.Get(6u), m.Get(10u), lines 348–350 reads positions, writes indices. Fixed in #1883.
SortSplatIndices (sortSplatIndices) positions, line 425; indices, line 426 worldMatrices.Get(part) and ReadMatrix(world), lines 443 and 448 reads positions, writes indices. Fixed in #1883.

Not affected, after reading the whole file: FlipFaces and ApplySkeleton make no Get() calls after wrapping. ReadMatrix wraps _m only after reading it. The Set() calls at the end of both extractMinAndMax* functions come after the last buffer access. The numeric arguments (offset, length, start, count, stride, indexStart, indexCount) are read with Uint32Value() on values that are already numbers, which does not run script.

Reproduction

I added this to NativeOptimizations.VertexTransformsAcceptArrayMatricesAndDefaultRanges locally (it is not committed) and ran it with macOS arm64 UnitTests builds:

// _TransformVector3Coordinates: the matrix getter moves target's storage to a new buffer.
const target = new Float32Array([1, 2, 3]);
let moved;
const matrix = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 10, 0, 0, 1];
Object.defineProperty(matrix, 0, { get() { moved = target.buffer.transfer(); return 1; } });
_native._TransformVector3Coordinates(target, { _m: matrix });
new Float32Array(moved); // QuickJS: 11,2,3 (written through the detached view). Expected: 1,2,3.

// extractMinAndMax: the min vector getter moves positions and refills the new owner.
const positions = new Float32Array([1, 2, 3]);
const min = {
    get _x() { new Float32Array(positions.buffer.transfer()).fill(100); return Infinity; },
    set _x(value) {}, _y: Infinity, _z: Infinity
};
const max = { _x: -Infinity, _y: -Infinity, _z: -Infinity };
_native.extractMinAndMax(positions, 0, 1, 3, min, max);
max._x; // QuickJS: 100 (read through the detached view from the new owner's storage). Expected: no read.
  • QuickJS (quickjs-ng, as fetched by JsRuntimeHost): both reproduce. The native call writes into, and reads from, storage that now belongs to the transferred buffer. The detach tests added in #1883 show the same for both splat sorts with the old argument order.
  • JavaScriptCore (macOS system framework): neither has a visible effect. The transferred buffer is not written, and the native call still reads the old contents. So this engine does not exercise the bug. I did not check whether the old storage is still valid memory at that point.
  • Not reproduced, found by inspection: _TransformVector3Normals, _TransformVector4Normals and extractMinAndMaxIndexed. Their structure matches the two sites above. I did not run V8, Chakra or Hermes.

Fix

#1883 uses this fix shape in 9e688dac (https://github.com/BabylonJS/BabylonNative/pull/1883/commits/9e688dacb978ff0aef6267168f958856765b52b6): validate the argument types (which does not run script), then read every scalar, matrix and vector argument, and only then construct the TypedArrayOf wrappers. After that point nothing calls back into JS.

  • For the transforms, this means moving ReadMatrix(transform) above the coordinates/normals wrap.
  • For the min/max functions, it means reading the six component values before wrapping positions and indices. ExtractMinAndMaxIndexedT would then take the six floats, or a small struct, instead of the two objects.

The #1883 tests show one way to cover it: detach the buffer from a getter, then check that the transferred buffer is untouched. Allow the call to throw, since QuickJS rejects a detached typed array once the wrap comes after the read. Skip the check when ArrayBuffer.prototype.transfer is missing.

Severity

This needs hostile or unusual script input: a matrix whose _m or elements are accessors, a Proxy, or a vector with accessor _x/_y/_z, combined with a buffer detached or resized from inside that accessor.

I checked the stock Babylon.js call sites in the bundle BN installs (babylonjs 9.37.1). The nativeOverride filters route these calls to _native only for non-Array buffers. The callers pass a Matrix (VertexData.transform), whose _m is a plain data property holding a Float32Array or plain Array. The extractMinAndMax* wrappers pass freshly constructed Vector3s, whose _x/_y/_z are plain data properties. None of these run script on Get(), so stock Babylon.js does not reach the bug as far as I verified. Script that calls the _native functions directly, or passes a crafted Matrix-like object to VertexData.transform, can reach it.

Separately, these functions do not bounds-check offset/length, start/count/stride or the index values against the buffer length. That is a different issue and is not covered here.

Lingua principale
C++
Stelle
931
Fork
169
Merge medio
2g 17h
PR unite (30g)
66

Preparare l'ambiente

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di BabylonJS/BabylonNative

Tutte le issue di BabylonJS/BabylonNative

Issue simili

Altre issue su C++

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.