1 /* Copyright (c) 2010. The SimGrid Team.
2 * All rights reserved. */
4 /* This program is free software; you can redistribute it and/or modify it
5 * under the terms of the license (GNU LGPL) which comes with this package. */
7 /* SimGrid Lua state management */
9 #include "lua_state_cloner.h"
10 #include "lua_utils.h"
16 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(lua_state_cloner, lua, "Lua state management");
18 static void sglua_add_maestro_table(lua_State* L, int index, void* maestro_table_ptr);
19 static void* sglua_get_maestro_table_ptr(lua_State* L, int index);
20 static void sglua_get_table_by_ptr(lua_State* L, void* table_ptr);
21 static int l_get_from_maestro(lua_State* L);
23 static void sglua_copy_nil(lua_State* src, lua_State* dst);
24 static void sglua_copy_number(lua_State* src, lua_State* dst);
25 static void sglua_copy_boolean(lua_State* src, lua_State* dst);
26 static void sglua_copy_string(lua_State* src, lua_State* dst);
27 static void sglua_copy_table(lua_State* src, lua_State* dst);
28 static void sglua_copy_function(lua_State* src, lua_State* dst);
29 static void sglua_copy_lightuserdata(lua_State* src, lua_State* dst);
30 static void sglua_copy_userdata(lua_State* src, lua_State* dst);
31 static void sglua_copy_thread(lua_State* src, lua_State* dst);
34 * @brief Returns the father of a state, i.e. the state that created it.
35 * @param L a Lua state
36 * @return its father, or NULL if the state was not created by sglua_clone_state()
38 static lua_State* sglua_get_father(lua_State* L) {
41 lua_pushstring(L, "simgrid.father");
42 /* ... "simgrid.father" */
43 lua_rawget(L, LUA_REGISTRYINDEX);
45 lua_State* father = lua_touserdata(L, -1);
52 * @brief Adds a reference to a maestro table to the list of known maestro
55 * TODO identify maestro's tables with my own IDs instead of pointers
58 * @param L a state (can be maestro itself)
59 * @param index index of the copy of the maestro table in the stack of L
60 * @param maestro_table_ptr pointer to the original table in maestro's world
62 void sglua_add_maestro_table(lua_State* L, int index, void* maestro_table_ptr) {
64 /* we will set both [ptr] -> table and [table] -> ptr */
67 lua_pushvalue(L, index);
69 lua_pushstring(L, "simgrid.maestro_tables");
70 /* ... table "simgrid.maestro_tables" */
71 lua_rawget(L, LUA_REGISTRYINDEX);
72 /* ... table maestrotbs */
74 /* ... table maestrotbs table */
75 lua_pushlightuserdata(L, maestro_table_ptr);
76 /* ... table maestrotbs table tableptr */
78 /* ... table maestrotbs table tableptr tableptr */
80 /* ... table maestrotbs table tableptr tableptr table */
82 /* ... table maestrotbs table tableptr */
84 /* ... table maestrotbs */
90 * @brief For a table in the stack of L, returns a pointer that identifies the
91 * same table in in maestro's world.
92 * @param L a Lua state
93 * @param index index of a table in the stack of L
94 * @return a pointer to maestro's copy of this table, or NULL if this table
95 * did not come from maestro
97 static void* sglua_get_maestro_table_ptr(lua_State* L, int index) {
99 void* maestro_table_ptr = NULL;
101 lua_pushvalue(L, index);
103 lua_pushstring(L, "simgrid.maestro_tables");
104 /* ... table "simgrid.maestro_tables" */
105 lua_rawget(L, LUA_REGISTRYINDEX);
106 /* ... table maestrotbs */
107 lua_pushvalue(L, -2);
108 /* ... table maestrotbs table */
110 /* ... table maestrotbs tableptr/nil */
111 if (!lua_isnil(L, -1)) {
112 /* ... table maestrotbs tableptr */
113 maestro_table_ptr = (void*) lua_topointer(L, -1);
118 return maestro_table_ptr;
122 * @brief Pushes a table knowing a pointer to maestro's copy of this table.
124 * Pushes nil if L does not know this table in maestro.
126 * @param L a Lua state
127 * @param maestro_table_ptr pointer that identifies a table in maestro's world
129 static void sglua_get_table_by_ptr(lua_State* L, void* maestro_table_ptr) {
132 lua_pushstring(L, "simgrid.maestro_tables");
133 /* ... "simgrid.maestro_tables" */
134 lua_rawget(L, LUA_REGISTRYINDEX);
136 lua_pushlightuserdata(L, maestro_table_ptr);
137 /* ... maestrotbs tableptr */
139 /* ... maestrotbs table/nil */
145 * @brief Pops a value from the stack of a source state and pushes it on the
146 * stack of another state.
148 * If the value is a table, its content is copied recursively.
150 * TODO: add support of closures
152 * @param src the source state (not necessarily maestro)
153 * @param dst the destination state
155 void sglua_move_value(lua_State* src, lua_State *dst) {
157 luaL_checkany(src, -1); /* check the value to copy */
159 int indent = (lua_gettop(dst) - 1) * 6;
160 XBT_DEBUG("%sCopying data %s", sglua_get_spaces(indent), sglua_tostring(src, -1));
162 sglua_stack_dump("src before copying a value (should be ... value): ", src);
163 sglua_stack_dump("dst before copying a value (should be ...): ", dst);
165 switch (lua_type(src, -1)) {
168 sglua_copy_nil(src, dst);
172 sglua_copy_number(src, dst);
176 sglua_copy_boolean(src, dst);
180 sglua_copy_string(src, dst);
184 sglua_copy_function(src, dst);
188 sglua_copy_table(src, dst);
191 case LUA_TLIGHTUSERDATA:
192 sglua_copy_lightuserdata(src, dst);
196 sglua_copy_userdata(src, dst);
200 sglua_copy_thread(src, dst);
204 /* the value has been copied to dst: remove it from src */
208 XBT_DEBUG("%sData copied", sglua_get_spaces(indent));
210 sglua_stack_dump("src after copying a value (should be ...): ", src);
211 sglua_stack_dump("dst after copying a value (should be ... value): ", dst);
215 * @brief Copies the nil value on the top of src to the top of dst.
216 * @param src source state
217 * @param dst destination state
219 static void sglua_copy_nil(lua_State* src, lua_State* dst) {
224 * @brief Copies the number value on the top of src to the top of dst.
225 * @param src source state
226 * @param dst destination state
228 static void sglua_copy_number(lua_State* src, lua_State* dst) {
229 lua_pushnumber(dst, lua_tonumber(src, -1));
233 * @brief Copies the boolean value on the top of src to the top of dst.
234 * @param src source state
235 * @param dst destination state
237 static void sglua_copy_boolean(lua_State* src, lua_State* dst) {
238 lua_pushboolean(dst, lua_toboolean(src, -1));
242 * @brief Copies the string value on the top of src to the top of dst.
243 * @param src source state
244 * @param dst destination state
246 static void sglua_copy_string(lua_State* src, lua_State* dst) {
248 /* no worries about memory: lua_pushstring makes a copy */
249 lua_pushstring(dst, lua_tostring(src, -1));
253 * @brief Copies the table value on the top of src to the top of dst.
255 * A deep copy of the table is made. If the table has a metatable, the
256 * metatable is also copied.
257 * If the table is already known by the destination state, it is not copied
260 * @param src source state
261 * @param dst destination state
263 static void sglua_copy_table(lua_State* src, lua_State* dst) {
267 int indent = lua_gettop(dst) * 6 + 2;
269 /* get from maestro the pointer that identifies this table */
270 void* table_ptr = sglua_get_maestro_table_ptr(src, -1);
271 if (table_ptr == NULL) {
272 /* the table didn't come from maestro: nevermind, use the pointer of src */
273 table_ptr = (void*) lua_topointer(src, -1);
275 if (!sglua_is_maestro(src)) {
276 XBT_DEBUG("%sMaestro does not know this table",
277 sglua_get_spaces(indent));
281 if (sglua_is_maestro(src)) {
282 /* register the table in maestro itself */
283 XBT_DEBUG("%sKeeping track of this table in maestro itself",
284 sglua_get_spaces(indent));
285 sglua_add_maestro_table(src, -1, table_ptr);
286 xbt_assert(sglua_get_maestro_table_ptr(src, -1) == table_ptr);
289 /* to avoid infinite recursion, see if this table is already known by dst */
290 sglua_get_table_by_ptr(dst, table_ptr);
291 /* dst: ... table/nil */
292 if (!lua_isnil(dst, -1)) {
293 XBT_DEBUG("%sNothing to do: table already known (%p)",
294 sglua_get_spaces(indent), table_ptr);
298 XBT_DEBUG("%sFirst visit of this table (%p)", sglua_get_spaces(indent),
304 /* first visit: create the new table in dst */
308 /* mark the table as known right now to avoid infinite recursion */
309 sglua_add_maestro_table(dst, -1, table_ptr);
310 /* FIXME: we may have added a table with a non-maestro pointer, is this a
312 XBT_DEBUG("%sTable marked as known", sglua_get_spaces(indent));
313 xbt_assert(sglua_get_maestro_table_ptr(dst, -1) == table_ptr);
315 sglua_stack_dump("dst after marking the table as known (should be ... table): ", dst);
317 /* copy the metatable if any */
318 int has_meta_table = lua_getmetatable(src, -1);
319 /* src: ... table mt? */
320 if (has_meta_table) {
321 XBT_DEBUG("%sCopying the metatable", sglua_get_spaces(indent));
322 /* src: ... table mt */
323 sglua_copy_table(src, dst);
324 /* dst: ... table mt */
327 lua_setmetatable(dst, -2);
332 XBT_DEBUG("%sNo metatable", sglua_get_spaces(indent));
335 sglua_stack_dump("src before traversing the table (should be ... table): ", src);
336 sglua_stack_dump("dst before traversing the table (should be ... table): ", dst);
338 /* traverse the table of src and copy each element */
340 /* src: ... table nil */
341 while (lua_next(src, -2) != 0) {
342 /* src: ... table key value */
344 XBT_DEBUG("%sCopying table element %s", sglua_get_spaces(indent),
345 sglua_keyvalue_tostring(src, -2, -1));
347 sglua_stack_dump("src before copying table element (should be ... table key value): ", src);
348 sglua_stack_dump("dst before copying table element (should be ... table): ", dst);
351 lua_pushvalue(src, -2);
352 /* src: ... table key value key */
354 XBT_DEBUG("%sCopying the key part of the table element",
355 sglua_get_spaces(indent));
356 sglua_move_value(src, dst);
357 /* src: ... table key value
358 dst: ... table key */
359 XBT_DEBUG("%sCopied the key part of the table element",
360 sglua_get_spaces(indent));
363 XBT_DEBUG("%sCopying the value part of the table element",
364 sglua_get_spaces(indent));
365 sglua_move_value(src, dst);
366 /* src: ... table key
367 dst: ... table key value */
368 XBT_DEBUG("%sCopied the value part of the table element",
369 sglua_get_spaces(indent));
372 /* set the table element */
373 lua_settable(dst, -3);
376 /* the key stays on top of src for next iteration */
377 sglua_stack_dump("src before next iteration (should be ... table key): ", src);
378 sglua_stack_dump("dst before next iteration (should be ... table): ", dst);
380 XBT_DEBUG("%sTable element copied", sglua_get_spaces(indent));
382 XBT_DEBUG("%sFinished traversing the table", sglua_get_spaces(indent));
387 * @brief Copies the function on the top of src to the top of dst.
389 * It can be a Lua function or a C function.
390 * Copying upvalues is not implemented yet (TODO).
392 * @param src source state
393 * @param dst destination state
395 static void sglua_copy_function(lua_State* src, lua_State* dst) {
397 if (lua_iscfunction(src, -1)) {
398 /* it's a C function: just copy the pointer */
399 lua_CFunction f = lua_tocfunction(src, -1);
400 lua_pushcfunction(dst, f);
403 /* it's a Lua function: dump it from src */
405 s_sglua_buffer_t buffer;
406 buffer.capacity = 64;
408 buffer.data = xbt_new(char, buffer.capacity);
410 /* copy the binary chunk from src into a buffer */
411 int error = lua_dump(src, sglua_memory_writer, &buffer);
412 xbt_assert(!error, "Failed to dump the function from the source state: error %d",
415 /* load the chunk into dst */
416 error = luaL_loadbuffer(dst, buffer.data, buffer.size, "(dumped function)");
417 xbt_assert(!error, "Failed to load the function into the destination state: %s",
418 lua_tostring(dst, -1));
423 * @brief Copies the light userdata on the top of src to the top of dst.
424 * @param src source state
425 * @param dst destination state
427 static void sglua_copy_lightuserdata(lua_State* src, lua_State* dst) {
428 lua_pushlightuserdata(dst, lua_touserdata(src, -1));
432 * @brief Copies the full userdata on the top of src to the top of dst.
434 * If the userdata has a metatable, the metatable is also copied.
436 * @param src source state
437 * @param dst destination state
439 static void sglua_copy_userdata(lua_State* src, lua_State* dst) {
441 int indent = lua_gettop(dst) * 6 + 2;
446 size_t size = lua_objlen(src, -1);
447 void* src_block = lua_touserdata(src, -1);
448 void* dst_block = lua_newuserdata(dst, size);
450 memcpy(dst_block, src_block, size);
452 /* copy the metatable if any */
453 int has_meta_table = lua_getmetatable(src, -1);
454 /* src: ... udata mt? */
455 if (has_meta_table) {
456 XBT_DEBUG("%sCopying metatable of userdata (%p)",
457 sglua_get_spaces(indent), lua_topointer(src, -1));
458 /* src: ... udata mt */
459 sglua_copy_table(src, dst);
464 lua_setmetatable(dst, -2);
467 XBT_DEBUG("%sMetatable of userdata copied", sglua_get_spaces(indent));
470 XBT_DEBUG("%sNo metatable for this userdata",
471 sglua_get_spaces(indent));
477 * @brief This operation is not supported (yet?) so it just pushes nil.
479 * @param src source state
480 * @param dst destination state
482 static void sglua_copy_thread(lua_State* src, lua_State* dst) {
484 XBT_WARN("Copying a thread from another state is not implemented (yet?).");
489 * @brief Copies a global value or a registry value from the maestro state.
491 * The state L must have been created by sglua_clone_maestro_state().
492 * This function is meant to be an __index metamethod.
493 * Consequently, it assumes that the stack has two elements:
494 * a table (either the environment or the registry of L) and the string key of
495 * a value that does not exist yet in this table. It copies the corresponding
496 * value from maestro and pushes it on the stack of L.
497 * If the value does not exist in maestro state either, nil is pushed.
499 * TODO: make this function thread safe. If the simulation runs in parallel,
500 * several simulated processes may trigger this __index metamethod at the same
501 * time and get globals from maestro.
503 * @param L the current state
504 * @return number of return values pushed (always 1)
506 static int l_get_from_maestro(lua_State *L) {
508 /* check the arguments */
509 luaL_checktype(L, 1, LUA_TTABLE);
510 const char* key = luaL_checkstring(L, 2);
512 XBT_DEBUG("__index of '%s' begins", key);
514 /* want a global or a registry value? */
516 if (lua_equal(L, 1, LUA_REGISTRYINDEX)) {
518 pseudo_index = LUA_REGISTRYINDEX;
519 XBT_DEBUG("Will get the value from the registry of maestro");
523 pseudo_index = LUA_GLOBALSINDEX;
524 XBT_DEBUG("Will get the value from the globals of maestro");
528 lua_State* maestro = sglua_get_maestro();
532 /* get the value from maestro */
533 lua_getfield(maestro, pseudo_index, key);
534 /* maestro: ... value */
536 /* push the value onto the stack of L */
537 sglua_move_value(maestro, L);
539 L: table key value */
541 /* prepare the return value of __index */
542 lua_pushvalue(L, -1);
543 /* L: table key value value */
545 /* L: value table key value */
547 /* save the copied value in the table for subsequent accesses */
553 XBT_DEBUG("__index of '%s' returns %s", key, sglua_tostring(L, -1));
559 * @brief Creates a new Lua state and get its environment from the maestro
562 * The state created is independent from maestro and has its own copies of
563 * global and registry values.
564 * However, the global and registry values are not copied right now from
565 * the original state; they are copied only the first time they are accessed.
566 * This behavior saves time and memory, and is okay for Simgrid's needs.
568 * TODO: if the simulation runs in parallel, copy everything right now?
570 * @return the state created
572 lua_State* sglua_clone_maestro(void) {
574 /* create the new state */
575 lua_State *L = luaL_newstate();
577 /* set its environment and its registry:
578 * - create a table newenv
579 * - create a metatable mt
580 * - set mt.__index = a function that copies the global from the father state
581 * - set mt as the metatable of the registry
582 * - set mt as the metatable of newenv
583 * - set newenv as the environment of the new state
585 lua_pushthread(L); /* thread */
586 lua_newtable(L); /* thread newenv */
587 lua_newtable(L); /* thread newenv mt */
588 lua_pushvalue(L, LUA_REGISTRYINDEX); /* thread newenv mt reg */
589 lua_pushcfunction(L, l_get_from_maestro); /* thread newenv mt reg f */
590 lua_setfield(L, -3, "__index"); /* thread newenv mt reg */
591 lua_pushvalue(L, -2); /* thread newenv mt reg mt */
592 lua_setmetatable(L, -2); /* thread newenv mt reg */
593 lua_pop(L, 1); /* thread newenv mt */
594 lua_setmetatable(L, -2); /* thread newenv */
595 lua_setfenv(L, -2); /* thread */
596 lua_pop(L, 1); /* -- */
598 /* create the table of known tables from maestro */
599 lua_pushstring(L, "simgrid.maestro_tables");
600 /* "simgrid.maestro_tables" */
601 lua_newtable(L); /* "simgrid.maestro_tables" maestrotbs*/
602 lua_rawset(L, LUA_REGISTRYINDEX);
605 /* open the standard libs (theoretically, this is not necessary as they can
606 * be inherited like any global values, but without a proper support of
607 * closures, iterators like ipairs don't work). */
608 XBT_DEBUG("Metatable of globals and registry set, opening standard libraries now");
611 XBT_DEBUG("New state created");