Skip to content

Commit

Permalink
[dart2wasm] Use JS Math.random to initialize non-secure Random seed
Browse files Browse the repository at this point in the history
When a seed is not provided to `Random`, call JS `Math.random` to get
two doubles between 0.0 and 1.0, scale the doubles to 32-bit integers,
and combine to a single 64-bit.

Similar to VM, this seed is generated once during the lifetime of the
program and then updated using the PRNG class `_Random`.

Fixes #56609.

Change-Id: Iaf846c63ff26d353ba6c4a94f61b0bab32624509
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/383241
Reviewed-by: Martin Kustermann <[email protected]>
Commit-Queue: Ömer Ağacan <[email protected]>
  • Loading branch information
osa1 authored and Commit Queue committed Sep 2, 2024
1 parent 957b3a8 commit 5e3fbe1
Showing 1 changed file with 17 additions and 2 deletions.
19 changes: 17 additions & 2 deletions sdk/lib/_internal/wasm/lib/math_patch.dart
Original file line number Diff line number Diff line change
Expand Up @@ -226,8 +226,11 @@ class _Random implements Random {

static int _setupSeed(int seed) => mix64(seed);

// TODO: Make this actually random
static int _initialSeed() => 0xCAFEBABEDEADBEEF;
static int _initialSeed() {
final low = (_jsMath.random() * 4294967295.0).toInt();
final high = (_jsMath.random() * 4294967295.0).toInt();
return ((high << 32) | low);
}

static int _nextSeed() {
// Trigger the PRNG once to change the internal state.
Expand All @@ -248,6 +251,18 @@ extension _JSCryptoGetRandomValues on _JSCrypto {
external void getRandomValues(JSUint8Array array);
}

@JS('Math')
external _JSMath get _jsMathGetter;

final _JSMath _jsMath = _jsMathGetter;

extension type _JSMath._(JSObject _jsMath) implements JSObject {}

extension _JSMathRandom on _JSMath {
@JS('random')
external double random();
}

class _SecureRandom implements Random {
final JSUint8ArrayImpl _buffer = JSUint8ArrayImpl(8);

Expand Down

0 comments on commit 5e3fbe1

Please sign in to comment.