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, bindings, "Lua state management");
18 static void sglua_add_maestro_table(lua_State* L, int index, void* maestro_table_ptr);
19 static void sglua_remove_maestro_table(lua_State* L, int index, void* maestro_table_ptr);
20 static void* sglua_get_maestro_table_ptr(lua_State* L, int index);
21 static void sglua_get_table_by_ptr(lua_State* L, void* table_ptr);
22 static int l_get_from_maestro(lua_State* L);
24 static void sglua_copy_nil(lua_State* src, lua_State* dst);
25 static void sglua_copy_number(lua_State* src, lua_State* dst);
26 static void sglua_copy_boolean(lua_State* src, lua_State* dst);
27 static void sglua_copy_string(lua_State* src, lua_State* dst);
28 static void sglua_copy_table(lua_State* src, lua_State* dst);
29 static void sglua_copy_function(lua_State* src, lua_State* dst);
30 static void sglua_copy_lightuserdata(lua_State* src, lua_State* dst);
31 static void sglua_copy_userdata(lua_State* src, lua_State* dst);
32 static void sglua_copy_thread(lua_State* src, lua_State* dst);
35 * @brief Adds a reference to a maestro table to the list of known maestro
38 * TODO identify maestro's tables with my own IDs instead of pointers
41 * @param L a state (can be maestro itself)
42 * @param index index of the copy of the maestro table in the stack of L
43 * @param maestro_table_ptr pointer to the original table in maestro's world
45 static void sglua_add_maestro_table(lua_State* L, int index, void* maestro_table_ptr) {
47 /* we will set both [ptr] -> table and [table] -> ptr */
50 lua_pushvalue(L, index);
52 lua_pushstring(L, "simgrid.maestro_tables");
53 /* ... table "simgrid.maestro_tables" */
54 lua_rawget(L, LUA_REGISTRYINDEX);
55 /* ... table maestrotbs */
57 /* ... table maestrotbs table */
58 lua_pushlightuserdata(L, maestro_table_ptr);
59 /* ... table maestrotbs table tableptr */
61 /* ... table maestrotbs table tableptr tableptr */
63 /* ... table maestrotbs table tableptr tableptr table */
65 /* ... table maestrotbs table tableptr */
67 /* ... table maestrotbs */
73 * @brief Removes a reference to a maestro table to the list of known maestro
76 * @param L a state (can be maestro itself)
77 * @param index index of the copy of the maestro table in the stack of L
78 * @param maestro_table_ptr pointer to the original table in maestro's world
80 static void sglua_remove_maestro_table(lua_State* L, int index, void* maestro_table_ptr) {
82 /* we will unset both [ptr] -> table and [table] -> ptr */
85 lua_pushvalue(L, index);
87 lua_pushstring(L, "simgrid.maestro_tables");
88 /* ... table "simgrid.maestro_tables" */
89 lua_rawget(L, LUA_REGISTRYINDEX);
90 /* ... table maestrotbs */
92 /* ... table maestrotbs table */
94 /* ... table maestrotbs table nil */
95 lua_pushlightuserdata(L, maestro_table_ptr);
96 /* ... table maestrotbs table nil tableptr */
98 /* ... table maestrotbs table nil tableptr nil*/
100 /* ... table maestrotbs table nil */
102 /* ... table maestrotbs */
108 * @brief For a table in the stack of L, returns a pointer that identifies the
109 * same table in in maestro's world.
110 * @param L a Lua state
111 * @param index index of a table in the stack of L
112 * @return a pointer to maestro's copy of this table, or NULL if this table
113 * did not come from maestro
115 static void* sglua_get_maestro_table_ptr(lua_State* L, int index) {
117 void* maestro_table_ptr = NULL;
119 lua_pushvalue(L, index);
121 lua_pushstring(L, "simgrid.maestro_tables");
122 /* ... table "simgrid.maestro_tables" */
123 lua_rawget(L, LUA_REGISTRYINDEX);
124 /* ... table maestrotbs */
125 lua_pushvalue(L, -2);
126 /* ... table maestrotbs table */
128 /* ... table maestrotbs tableptr/nil */
129 if (!lua_isnil(L, -1)) {
130 /* ... table maestrotbs tableptr */
131 maestro_table_ptr = (void*) lua_topointer(L, -1);
136 return maestro_table_ptr;
140 * @brief Pushes a table knowing a pointer to maestro's copy of this table.
142 * Pushes nil if L does not know this table in maestro.
144 * @param L a Lua state
145 * @param maestro_table_ptr pointer that identifies a table in maestro's world
147 static void sglua_get_table_by_ptr(lua_State* L, void* maestro_table_ptr) {
150 lua_pushstring(L, "simgrid.maestro_tables");
151 /* ... "simgrid.maestro_tables" */
152 lua_rawget(L, LUA_REGISTRYINDEX);
154 lua_pushlightuserdata(L, maestro_table_ptr);
155 /* ... maestrotbs tableptr */
157 /* ... maestrotbs table/nil */
163 * @brief Pops a value from the stack of a source state and pushes it on the
164 * stack of another state.
165 * If the value is a table, its content is copied recursively.
167 * This function is similar to lua_xmove() but it allows to move a value
168 * between two different global states.
170 * @param src the source state (not necessarily maestro)
171 * @param dst the destination state
173 void sglua_move_value(lua_State* src, lua_State* dst) {
175 sglua_copy_value(src, dst);
180 * @brief Pushes onto the stack a copy of the value on top another stack.
181 * If the value is a table, its content is copied recursively.
183 * This function allows to move a value between two different global states.
185 * @param src the source state (not necessarily maestro)
186 * @param dst the destination state
188 void sglua_copy_value(lua_State* src, lua_State* dst) {
190 luaL_checkany(src, -1); /* check the value to copy */
192 int indent = (lua_gettop(dst) - 1) * 6;
193 XBT_DEBUG("%sCopying data %s", sglua_get_spaces(indent), sglua_tostring(src, -1));
195 sglua_stack_dump("src before copying a value (should be ... value): ", src);
196 sglua_stack_dump("dst before copying a value (should be ...): ", dst);
198 switch (lua_type(src, -1)) {
201 sglua_copy_nil(src, dst);
205 sglua_copy_number(src, dst);
209 sglua_copy_boolean(src, dst);
213 sglua_copy_string(src, dst);
217 sglua_copy_function(src, dst);
221 sglua_copy_table(src, dst);
224 case LUA_TLIGHTUSERDATA:
225 sglua_copy_lightuserdata(src, dst);
229 sglua_copy_userdata(src, dst);
233 sglua_copy_thread(src, dst);
238 XBT_DEBUG("%sData copied", sglua_get_spaces(indent));
240 sglua_stack_dump("src after copying a value (should be ... value): ", src);
241 sglua_stack_dump("dst after copying a value (should be ... value): ", dst);
245 * @brief Copies the nil value on the top of src to the top of dst.
246 * @param src source state
247 * @param dst destination state
249 static void sglua_copy_nil(lua_State* src, lua_State* dst) {
254 * @brief Copies the number value on the top of src to the top of dst.
255 * @param src source state
256 * @param dst destination state
258 static void sglua_copy_number(lua_State* src, lua_State* dst) {
259 lua_pushnumber(dst, lua_tonumber(src, -1));
263 * @brief Copies the boolean value on the top of src to the top of dst.
264 * @param src source state
265 * @param dst destination state
267 static void sglua_copy_boolean(lua_State* src, lua_State* dst) {
268 lua_pushboolean(dst, lua_toboolean(src, -1));
272 * @brief Copies the string value on the top of src to the top of dst.
273 * @param src source state
274 * @param dst destination state
276 static void sglua_copy_string(lua_State* src, lua_State* dst) {
278 /* no worries about memory: lua_pushstring makes a copy */
279 lua_pushstring(dst, lua_tostring(src, -1));
283 * @brief Copies the table value on top of src to the top of dst.
285 * A deep copy of the table is made. If the table has a metatable, the
286 * metatable is also copied.
287 * If the table comes from maestro and is already known by the destination
288 * state, it is not copied again.
290 * @param src source state
291 * @param dst destination state
293 static void sglua_copy_table(lua_State* src, lua_State* dst) {
297 int indent = lua_gettop(dst) * 6 + 2;
299 /* get from maestro the pointer that identifies this table */
300 void* table_ptr = sglua_get_maestro_table_ptr(src, -1);
301 int known_by_maestro = (table_ptr != NULL);
303 if (!known_by_maestro) {
304 /* the table didn't come from maestro: nevermind, use the pointer of src */
305 table_ptr = (void*) lua_topointer(src, -1);
306 XBT_DEBUG("%sMaestro does not know this table",
307 sglua_get_spaces(indent));
310 if (sglua_is_maestro(src)) {
311 /* register the table in maestro itself */
312 XBT_DEBUG("%sKeeping track of this table in maestro itself",
313 sglua_get_spaces(indent));
314 sglua_add_maestro_table(src, -1, table_ptr);
315 known_by_maestro = 1;
316 xbt_assert(sglua_get_maestro_table_ptr(src, -1) == table_ptr);
319 /* to avoid infinite recursion, see if this table is already known by dst */
320 sglua_get_table_by_ptr(dst, table_ptr);
321 /* dst: ... table/nil */
322 if (!lua_isnil(dst, -1)) {
323 XBT_DEBUG("%sNothing to do: table already known (%p)",
324 sglua_get_spaces(indent), table_ptr);
328 XBT_DEBUG("%sFirst visit of this table (%p)", sglua_get_spaces(indent),
334 /* first visit: create the new table in dst */
338 /* mark the table as known right now to avoid infinite recursion */
339 sglua_add_maestro_table(dst, -1, table_ptr);
340 /* we may have added a table with a non-maestro pointer, but if it was the
341 * case, we will remove it later */
342 XBT_DEBUG("%sTable marked as known", sglua_get_spaces(indent));
343 xbt_assert(sglua_get_maestro_table_ptr(dst, -1) == table_ptr);
345 sglua_stack_dump("dst after marking the table as known (should be ... table): ", dst);
347 /* copy the metatable if any */
348 int has_meta_table = lua_getmetatable(src, -1);
349 /* src: ... table mt? */
350 if (has_meta_table) {
351 XBT_DEBUG("%sCopying the metatable", sglua_get_spaces(indent));
352 /* src: ... table mt */
353 sglua_copy_table(src, dst);
354 /* dst: ... table mt */
357 lua_setmetatable(dst, -2);
362 XBT_DEBUG("%sNo metatable", sglua_get_spaces(indent));
365 sglua_stack_dump("src before traversing the table (should be ... table): ", src);
366 sglua_stack_dump("dst before traversing the table (should be ... table): ", dst);
368 /* traverse the table of src and copy each element */
370 /* src: ... table nil */
371 while (lua_next(src, -2) != 0) {
372 /* src: ... table key value */
374 XBT_DEBUG("%sCopying table element %s", sglua_get_spaces(indent),
375 sglua_keyvalue_tostring(src, -2, -1));
377 sglua_stack_dump("src before copying table element (should be ... table key value): ", src);
378 sglua_stack_dump("dst before copying table element (should be ... table): ", dst);
381 lua_pushvalue(src, -2);
382 /* src: ... table key value key */
384 XBT_DEBUG("%sCopying the key part of the table element",
385 sglua_get_spaces(indent));
386 sglua_move_value(src, dst);
387 /* src: ... table key value
388 dst: ... table key */
389 XBT_DEBUG("%sCopied the key part of the table element",
390 sglua_get_spaces(indent));
393 XBT_DEBUG("%sCopying the value part of the table element",
394 sglua_get_spaces(indent));
395 sglua_move_value(src, dst);
396 /* src: ... table key
397 dst: ... table key value */
398 XBT_DEBUG("%sCopied the value part of the table element",
399 sglua_get_spaces(indent));
402 /* set the table element */
403 lua_settable(dst, -3);
406 /* the key stays on top of src for next iteration */
407 sglua_stack_dump("src before next iteration (should be ... table key): ", src);
408 sglua_stack_dump("dst before next iteration (should be ... table): ", dst);
410 XBT_DEBUG("%sTable element copied", sglua_get_spaces(indent));
412 XBT_DEBUG("%sFinished traversing the table", sglua_get_spaces(indent));
415 if (!known_by_maestro) {
416 /* actually,it was not a maestro table: forget the pointer */
417 sglua_remove_maestro_table(dst, -1, table_ptr);
422 * @brief Copies the function on the top of src to the top of dst.
424 * It can be a Lua function or a C function.
425 * Copying upvalues is not implemented yet.
427 * @param src source state
428 * @param dst destination state
430 static void sglua_copy_function(lua_State* src, lua_State* dst) {
432 if (lua_iscfunction(src, -1)) {
433 /* it's a C function */
435 XBT_DEBUG("It's a C function");
436 sglua_stack_dump("src before copying upvalues: ", src);
438 /* get the function pointer */
439 int function_index = lua_gettop(src);
440 lua_CFunction f = lua_tocfunction(src, function_index);
442 /* copy the upvalues */
444 const char* upvalue_name = NULL;
447 upvalue_name = lua_getupvalue(src, function_index, i);
449 if (upvalue_name != NULL) {
450 XBT_DEBUG("Upvalue %s", upvalue_name);
451 sglua_move_value(src, dst);
453 } while (upvalue_name != NULL);
455 sglua_stack_dump("src before copying pointer: ", src);
457 /* set the function */
458 lua_pushcclosure(dst, f, i - 1);
459 XBT_DEBUG("Function pointer copied");
462 /* it's a Lua function: dump it from src */
464 s_sglua_buffer_t buffer;
465 buffer.capacity = 128; /* an empty function uses 77 bytes */
467 buffer.data = xbt_new(char, buffer.capacity);
469 /* copy the binary chunk from src into a buffer */
470 _XBT_GNUC_UNUSED int error = lua_dump(src, sglua_memory_writer, &buffer);
471 xbt_assert(!error, "Failed to dump the function from the source state: error %d",
473 XBT_DEBUG("Fonction dumped: %zu bytes", buffer.size);
476 fwrite(buffer.data, buffer.size, buffer.size, stderr);
477 fprintf(stderr, "\n");
480 /* load the chunk into dst */
481 error = luaL_loadbuffer(dst, buffer.data, buffer.size, "(dumped function)");
482 xbt_assert(!error, "Failed to load the function into the destination state: %s",
483 lua_tostring(dst, -1));
488 * @brief Copies the light userdata on the top of src to the top of dst.
489 * @param src source state
490 * @param dst destination state
492 static void sglua_copy_lightuserdata(lua_State* src, lua_State* dst) {
493 lua_pushlightuserdata(dst, lua_touserdata(src, -1));
497 * @brief Copies the full userdata on the top of src to the top of dst.
499 * If the userdata has a metatable, the metatable is also copied.
501 * @param src source state
502 * @param dst destination state
504 static void sglua_copy_userdata(lua_State* src, lua_State* dst) {
506 int indent = lua_gettop(dst) * 6 + 2;
511 size_t size = lua_objlen(src, -1);
512 void* src_block = lua_touserdata(src, -1);
513 void* dst_block = lua_newuserdata(dst, size);
515 memcpy(dst_block, src_block, size);
517 /* copy the metatable if any */
518 int has_meta_table = lua_getmetatable(src, -1);
519 /* src: ... udata mt? */
520 if (has_meta_table) {
521 XBT_DEBUG("%sCopying metatable of userdata (%p)",
522 sglua_get_spaces(indent), lua_topointer(src, -1));
523 /* src: ... udata mt */
524 sglua_copy_table(src, dst);
529 lua_setmetatable(dst, -2);
532 XBT_DEBUG("%sMetatable of userdata copied", sglua_get_spaces(indent));
535 XBT_DEBUG("%sNo metatable for this userdata",
536 sglua_get_spaces(indent));
542 * @brief This operation is not supported (yet?) so it just pushes nil.
544 * @param src source state
545 * @param dst destination state
547 static void sglua_copy_thread(lua_State* src, lua_State* dst) {
549 XBT_WARN("Copying a thread from another state is not implemented (yet?).");
554 * @brief Copies a global value or a registry value from the maestro state.
556 * The state L must have been created by sglua_clone_maestro_state().
557 * This function is meant to be an __index metamethod.
558 * Consequently, it assumes that the stack has two elements:
559 * a table (either the environment or the registry of L) and the string key of
560 * a value that does not exist yet in this table. It copies the corresponding
561 * value from maestro and pushes it on the stack of L.
562 * If the value does not exist in maestro state either, nil is pushed.
564 * TODO: make this function thread safe. If the simulation runs in parallel,
565 * several simulated processes may trigger this __index metamethod at the same
566 * time and get globals from maestro.
568 * @param L the current state
569 * @return number of return values pushed (always 1)
571 static int l_get_from_maestro(lua_State *L) {
573 /* check the arguments */
574 luaL_checktype(L, 1, LUA_TTABLE);
575 const char* key = luaL_checkstring(L, 2);
577 XBT_DEBUG("__index of '%s' begins", key);
579 /* want a global or a registry value? */
581 if (lua_equal(L, 1, LUA_REGISTRYINDEX)) {
583 pseudo_index = LUA_REGISTRYINDEX;
584 XBT_DEBUG("Will get the value from the registry of maestro");
588 pseudo_index = LUA_GLOBALSINDEX;
589 XBT_DEBUG("Will get the value from the globals of maestro");
593 lua_State* maestro = sglua_get_maestro();
597 /* get the value from maestro */
598 lua_getfield(maestro, pseudo_index, key);
599 /* maestro: ... value */
601 /* push the value onto the stack of L */
602 sglua_move_value(maestro, L);
604 L: table key value */
606 /* prepare the return value of __index */
607 lua_pushvalue(L, -1);
608 /* L: table key value value */
610 /* L: value table key value */
612 /* save the copied value in the table for subsequent accesses */
618 XBT_DEBUG("__index of '%s' returns %s", key, sglua_tostring(L, -1));
624 * @brief Creates a new Lua state and get its environment from the maestro
627 * The state created is independent from maestro and has its own copies of
628 * global and registry values.
629 * However, the global and registry values are not copied right now from
630 * the original state; they are copied only the first time they are accessed.
631 * This behavior saves time and memory, and is okay for Simgrid's needs.
633 * TODO: if the simulation runs in parallel, copy everything right now?
635 * @return the state created
637 lua_State* sglua_clone_maestro(void) {
639 /* create the new state */
640 lua_State *L = luaL_newstate();
642 /* set its environment and its registry:
643 * - create a table newenv
644 * - create a metatable mt
645 * - set mt.__index = a function that copies the global from the father state
646 * - set mt as the metatable of the registry
647 * - set mt as the metatable of newenv
648 * - set newenv as the environment of the new state
650 lua_pushthread(L); /* thread */
651 lua_newtable(L); /* thread newenv */
652 lua_newtable(L); /* thread newenv mt */
653 lua_pushvalue(L, LUA_REGISTRYINDEX); /* thread newenv mt reg */
654 lua_pushcfunction(L, l_get_from_maestro); /* thread newenv mt reg f */
655 lua_setfield(L, -3, "__index"); /* thread newenv mt reg */
656 lua_pushvalue(L, -2); /* thread newenv mt reg mt */
657 lua_setmetatable(L, -2); /* thread newenv mt reg */
658 lua_pop(L, 1); /* thread newenv mt */
659 lua_setmetatable(L, -2); /* thread newenv */
660 lua_setfenv(L, -2); /* thread */
661 lua_pop(L, 1); /* -- */
663 /* create the table of known tables from maestro */
664 lua_pushstring(L, "simgrid.maestro_tables");
665 /* "simgrid.maestro_tables" */
666 lua_newtable(L); /* "simgrid.maestro_tables" maestrotbs */
667 lua_rawset(L, LUA_REGISTRYINDEX);
670 /* opening the standard libs is not necessary as they are
671 * inherited like any global values */
672 /* luaL_openlibs(L); */
674 XBT_DEBUG("New state created");