diff --git a/CHANGELOG.md b/CHANGELOG.md index c26f0ca..b9acb41 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -55,6 +55,8 @@ is in the [`1.0.0-rc.0`](#100-rc0---2026-05-26) entry below. past the ceiling in a single allocation. Each raises the same catchable `"resulting string too large"` error as `string.rep` and `..`, before the result is built (#425). +- `math.random` and `math.randomseed` use a generator kept in the VM state, so + a script can no longer reseed or draw from the host process's `:rand` state. ## [1.0.2] - 2026-07-28 diff --git a/lib/lua/vm/state.ex b/lib/lua/vm/state.ex index 054bfc5..0fa491b 100644 --- a/lib/lua/vm/state.ex +++ b/lib/lua/vm/state.ex @@ -65,7 +65,10 @@ defmodule Lua.VM.State do # scanned and spec-parsed once, not every call. Threaded in the # struct (not ETS/process dictionary) to preserve value semantics; # bounded in `Lua.VM.Stdlib.String`. - format_cache: %{} + format_cache: %{}, + # Seeded on first draw: a seed set here would be shared by every + # VM built from the memoized bootstrap template. + rand_state: nil @type t :: %__MODULE__{ call_stack: list(), @@ -83,7 +86,8 @@ defmodule Lua.VM.State do private: map(), multi_return_count: non_neg_integer(), g_ref: nil | {:tref, non_neg_integer()}, - format_cache: %{optional(binary()) => list()} + format_cache: %{optional(binary()) => list()}, + rand_state: :rand.state() | nil } @doc """ @@ -173,6 +177,7 @@ defmodule Lua.VM.State do | `tables`, `table_next_id` | `call_stack`, `call_depth` | | `userdata`, `userdata_next_id` | `open_upvalues` | | `metatables`, `upvalue_cells`, `private` | `multi_return_count` | + | `rand_state` | | The instruction tally `instruction_count` is also carried forward (monotonic max), not reset to the entry value: the work a protected call burned must still count @@ -200,6 +205,7 @@ defmodule Lua.VM.State do metatables: raised.metatables, upvalue_cells: raised.upvalue_cells, private: raised.private, + rand_state: raised.rand_state, instruction_count: max(entry.instruction_count, raised.instruction_count) } end diff --git a/lib/lua/vm/stdlib/math.ex b/lib/lua/vm/stdlib/math.ex index f605449..028a7a6 100644 --- a/lib/lua/vm/stdlib/math.ex +++ b/lib/lua/vm/stdlib/math.ex @@ -429,13 +429,13 @@ defmodule Lua.VM.Stdlib.Math do # math.random([m [, n]]) defp math_random([], state) do - # Returns a float in [0, 1) - {[:rand.uniform()], state} + {float, rand_state} = :rand.uniform_s(generator(state)) + {[float], %{state | rand_state: rand_state}} end defp math_random([m], state) when is_integer(m) and m > 0 do - # Returns an integer in [1, m] - {[:rand.uniform(m)], state} + {integer, rand_state} = :rand.uniform_s(m, generator(state)) + {[integer], %{state | rand_state: rand_state}} end # Lua 5.3 ยง6.7: the interval `[m, n]` is too large when its span `n - m` @@ -449,9 +449,8 @@ defmodule Lua.VM.Stdlib.Math do end defp math_random([m, n], state) when is_integer(m) and is_integer(n) and m <= n do - # Returns an integer in [m, n] - range = n - m + 1 - {[m + :rand.uniform(range) - 1], state} + {offset, rand_state} = :rand.uniform_s(n - m + 1, generator(state)) + {[m + offset - 1], %{state | rand_state: rand_state}} end defp math_random([m, n | _], _state) when is_integer(m) and is_integer(n) do @@ -478,13 +477,11 @@ defmodule Lua.VM.Stdlib.Math do # math.randomseed(x [, y]) defp math_randomseed([x], state) when is_integer(x) do - :rand.seed(:exsss, {x, 0, 0}) - {[], state} + {[], seed_generator(state, {x, 0, 0})} end defp math_randomseed([x, y], state) when is_integer(x) and is_integer(y) do - :rand.seed(:exsss, {x, y, 0}) - {[], state} + {[], seed_generator(state, {x, y, 0})} end defp math_randomseed([x, y | _], _state) when is_integer(x) do @@ -507,6 +504,16 @@ defmodule Lua.VM.Stdlib.Math do raise ArgumentError.value_expected("math.randomseed", 1) end + defp seed_generator(state, seed), do: %{state | rand_state: :rand.seed_s(:exsss, seed)} + + defp generator(%State{rand_state: nil}), do: :rand.seed_s(:exsss, unpredictable_seed()) + defp generator(%State{rand_state: rand_state}), do: rand_state + + defp unpredictable_seed do + <> = :crypto.strong_rand_bytes(24) + {a, b, c} + end + # math.sin(x) defp math_sin([x], state) when is_number(x) do {[:math.sin(x / 1)], state} diff --git a/mix.exs b/mix.exs index 833061c..84a8c40 100644 --- a/mix.exs +++ b/mix.exs @@ -112,7 +112,7 @@ defmodule Lua.MixProject do # Run "mix help compile.app" to learn about applications. def application do [ - extra_applications: [:logger] + extra_applications: [:logger, :crypto] ] end diff --git a/test/lua/vm/stdlib/math_test.exs b/test/lua/vm/stdlib/math_test.exs index 861d504..8349052 100644 --- a/test/lua/vm/stdlib/math_test.exs +++ b/test/lua/vm/stdlib/math_test.exs @@ -379,4 +379,56 @@ defmodule Lua.VM.Stdlib.MathTest do assert run!(~s|return tonumber("0x.")|) == [nil] end end + + describe "math.random generator state" do + test "seeding and drawing leave the host process's :rand state untouched" do + :rand.seed(:exsss, {1, 2, 3}) + host_state = :rand.export_seed() + + Lua.eval!(Lua.new(), """ + local first = math.random() + math.randomseed(42) + return first, math.random(), math.random(10), math.random(5, 15) + """) + + assert :rand.export_seed() == host_state + end + + test "the same seed replays the same sequence, across evaluations and host :rand calls" do + {in_one_evaluation, _lua} = + Lua.eval!(Lua.new(), "math.randomseed(42) return math.random(1 << 40), math.random(1 << 40)") + + {[], lua} = Lua.eval!(Lua.new(), "math.randomseed(42)") + :rand.seed(:exsss, {1, 2, 3}) + {[first], lua} = Lua.eval!(lua, "return math.random(1 << 40)") + :rand.uniform() + {[second], _lua} = Lua.eval!(lua, "return math.random(1 << 40)") + + assert [first, second] == in_one_evaluation + end + + test "unseeded VMs from the same template draw different sequences under the same host seed" do + draw = fn -> + :rand.seed(:exsss, {1, 2, 3}) + {values, _lua} = Lua.eval!(Lua.new(), "return math.random(1 << 40), math.random(1 << 40)") + values + end + + refute draw.() == draw.() + end + + test "a draw made inside a failed pcall is not replayed after it" do + {direct, _lua} = Lua.eval!(Lua.new(), "math.randomseed(7) return math.random(1 << 40), math.random(1 << 40)") + + {through_pcall, _lua} = + Lua.eval!(Lua.new(), """ + math.randomseed(7) + local inside + pcall(function() inside = math.random(1 << 40) error("boom") end) + return inside, math.random(1 << 40) + """) + + assert through_pcall == direct + end + end end