From 3a4bf103b33cb3ed592ca3d7ac1ce3f9ebd5eae9 Mon Sep 17 00:00:00 2001 From: Uli Schlachter Date: Sun, 17 Feb 2019 10:17:47 +0100 Subject: [PATCH] Initialise Lua's pseudo-RNG from C from a good source GLib has an internal pseudo-RNG that it initialises from /dev/urandom. This commit adds code that uses this RNG to initialise various random number generators that can be used by Lua. This also removes some Lua code that initialises the random number generator badly. Signed-off-by: Uli Schlachter --- awesome.c | 28 ++++++++++++++++++++++++++++ lib/gears/filesystem.lua | 2 -- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/awesome.c b/awesome.c index 4a058acc3..4063a490e 100644 --- a/awesome.c +++ b/awesome.c @@ -71,6 +71,33 @@ static float main_loop_iteration_limit = 0.1; /** A pipe that is used to asynchronously handle SIGCHLD */ static int sigchld_pipe[2]; +/* Initialise various random number generators */ +static void +init_rng(void) +{ + /* LuaJIT uses its own, internal RNG, so initialise that */ + lua_State *L = globalconf_get_lua_State(); + + /* Get math.randomseed */ + lua_getglobal(L, "math"); + lua_getfield(L, -1, "randomseed"); + + /* Push a seed */ + lua_pushnumber(L, g_random_int() + g_random_double()); + + /* Call math.randomseed */ + lua_call(L, 1, 0); + + /* Remove "math" global */ + lua_pop(L, 1); + + /* Lua 5.1, Lua 5.2, and (sometimes) Lua 5.3 use rand()/srand() */ + srand(g_random_int()); + + /* When Lua 5.3 is built with LUA_USE_POSIX, it uses random()/srandom() */ + srandom(g_random_int()); +} + /** Call before exiting. */ void @@ -864,6 +891,7 @@ main(int argc, char **argv) /* init lua */ luaA_init(&xdg, &searchpath); string_array_wipe(&searchpath); + init_rng(); ewmh_init_lua(); diff --git a/lib/gears/filesystem.lua b/lib/gears/filesystem.lua index 26b315450..5a12b1ad4 100644 --- a/lib/gears/filesystem.lua +++ b/lib/gears/filesystem.lua @@ -153,8 +153,6 @@ function filesystem.get_dir(d) end end -math.randomseed( os.clock() % 1 * 1e6 ) - --- Get the name of a random file from a given directory. -- @tparam string path The directory to search. -- @tparam[opt] table exts Specific extensions to limit the search to. eg:`{ "jpg", "png" }`