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_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 Adds a reference to a maestro table to the list of known maestro
37 * TODO identify maestro's tables with my own IDs instead of pointers
40 * @param L a state (can be maestro itself)
41 * @param index index of the copy of the maestro table in the stack of L
42 * @param maestro_table_ptr pointer to the original table in maestro's world
44 void sglua_add_maestro_table(lua_State* L, int index, void* maestro_table_ptr) {
46 /* we will set both [ptr] -> table and [table] -> ptr */
49 lua_pushvalue(L, index);
51 lua_pushstring(L, "simgrid.maestro_tables");
52 /* ... table "simgrid.maestro_tables" */
53 lua_rawget(L, LUA_REGISTRYINDEX);
54 /* ... table maestrotbs */
56 /* ... table maestrotbs table */
57 lua_pushlightuserdata(L, maestro_table_ptr);
58 /* ... table maestrotbs table tableptr */
60 /* ... table maestrotbs table tableptr tableptr */
62 /* ... table maestrotbs table tableptr tableptr table */
64 /* ... table maestrotbs table tableptr */
66 /* ... table maestrotbs */
72 * @brief For a table in the stack of L, returns a pointer that identifies the
73 * same table in in maestro's world.
74 * @param L a Lua state
75 * @param index index of a table in the stack of L
76 * @return a pointer to maestro's copy of this table, or NULL if this table
77 * did not come from maestro
79 static void* sglua_get_maestro_table_ptr(lua_State* L, int index) {
81 void* maestro_table_ptr = NULL;
83 lua_pushvalue(L, index);
85 lua_pushstring(L, "simgrid.maestro_tables");
86 /* ... table "simgrid.maestro_tables" */
87 lua_rawget(L, LUA_REGISTRYINDEX);
88 /* ... table maestrotbs */
90 /* ... table maestrotbs table */
92 /* ... table maestrotbs tableptr/nil */
93 if (!lua_isnil(L, -1)) {
94 /* ... table maestrotbs tableptr */
95 maestro_table_ptr = (void*) lua_topointer(L, -1);
100 return maestro_table_ptr;
104 * @brief Pushes a table knowing a pointer to maestro's copy of this table.
106 * Pushes nil if L does not know this table in maestro.
108 * @param L a Lua state
109 * @param maestro_table_ptr pointer that identifies a table in maestro's world
111 static void sglua_get_table_by_ptr(lua_State* L, void* maestro_table_ptr) {
114 lua_pushstring(L, "simgrid.maestro_tables");
115 /* ... "simgrid.maestro_tables" */
116 lua_rawget(L, LUA_REGISTRYINDEX);
118 lua_pushlightuserdata(L, maestro_table_ptr);
119 /* ... maestrotbs tableptr */
121 /* ... maestrotbs table/nil */
127 * @brief Pops a value from the stack of a source state and pushes it on the
128 * stack of another state.
129 * If the value is a table, its content is copied recursively.
131 * This function is similar to lua_xmove() but it allows to move a value
132 * between two different global states.
134 * @param src the source state (not necessarily maestro)
135 * @param dst the destination state
137 void sglua_move_value(lua_State* src, lua_State *dst) {
139 luaL_checkany(src, -1); /* check the value to copy */
141 int indent = (lua_gettop(dst) - 1) * 6;
142 XBT_DEBUG("%sCopying data %s", sglua_get_spaces(indent), sglua_tostring(src, -1));
144 sglua_stack_dump("src before copying a value (should be ... value): ", src);
145 sglua_stack_dump("dst before copying a value (should be ...): ", dst);
147 switch (lua_type(src, -1)) {
150 sglua_copy_nil(src, dst);
154 sglua_copy_number(src, dst);
158 sglua_copy_boolean(src, dst);
162 sglua_copy_string(src, dst);
166 sglua_copy_function(src, dst);
170 sglua_copy_table(src, dst);
173 case LUA_TLIGHTUSERDATA:
174 sglua_copy_lightuserdata(src, dst);
178 sglua_copy_userdata(src, dst);
182 sglua_copy_thread(src, dst);
186 /* the value has been copied to dst: remove it from src */
190 XBT_DEBUG("%sData copied", sglua_get_spaces(indent));
192 sglua_stack_dump("src after copying a value (should be ...): ", src);
193 sglua_stack_dump("dst after copying a value (should be ... value): ", dst);
197 * @brief Copies the nil value on the top of src to the top of dst.
198 * @param src source state
199 * @param dst destination state
201 static void sglua_copy_nil(lua_State* src, lua_State* dst) {
206 * @brief Copies the number value on the top of src to the top of dst.
207 * @param src source state
208 * @param dst destination state
210 static void sglua_copy_number(lua_State* src, lua_State* dst) {
211 lua_pushnumber(dst, lua_tonumber(src, -1));
215 * @brief Copies the boolean 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_boolean(lua_State* src, lua_State* dst) {
220 lua_pushboolean(dst, lua_toboolean(src, -1));
224 * @brief Copies the string 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_string(lua_State* src, lua_State* dst) {
230 /* no worries about memory: lua_pushstring makes a copy */
231 lua_pushstring(dst, lua_tostring(src, -1));
235 * @brief Copies the table value on the top of src to the top of dst.
237 * A deep copy of the table is made. If the table has a metatable, the
238 * metatable is also copied.
239 * If the table is already known by the destination state, it is not copied
242 * @param src source state
243 * @param dst destination state
245 static void sglua_copy_table(lua_State* src, lua_State* dst) {
249 int indent = lua_gettop(dst) * 6 + 2;
251 /* get from maestro the pointer that identifies this table */
252 void* table_ptr = sglua_get_maestro_table_ptr(src, -1);
253 if (table_ptr == NULL) {
254 /* the table didn't come from maestro: nevermind, use the pointer of src */
255 table_ptr = (void*) lua_topointer(src, -1);
257 if (!sglua_is_maestro(src)) {
258 XBT_DEBUG("%sMaestro does not know this table",
259 sglua_get_spaces(indent));
263 if (sglua_is_maestro(src)) {
264 /* register the table in maestro itself */
265 XBT_DEBUG("%sKeeping track of this table in maestro itself",
266 sglua_get_spaces(indent));
267 sglua_add_maestro_table(src, -1, table_ptr);
268 xbt_assert(sglua_get_maestro_table_ptr(src, -1) == table_ptr);
271 /* to avoid infinite recursion, see if this table is already known by dst */
272 sglua_get_table_by_ptr(dst, table_ptr);
273 /* dst: ... table/nil */
274 if (!lua_isnil(dst, -1)) {
275 XBT_DEBUG("%sNothing to do: table already known (%p)",
276 sglua_get_spaces(indent), table_ptr);
280 XBT_DEBUG("%sFirst visit of this table (%p)", sglua_get_spaces(indent),
286 /* first visit: create the new table in dst */
290 /* mark the table as known right now to avoid infinite recursion */
291 sglua_add_maestro_table(dst, -1, table_ptr);
292 /* FIXME: we may have added a table with a non-maestro pointer, is this a
294 XBT_DEBUG("%sTable marked as known", sglua_get_spaces(indent));
295 xbt_assert(sglua_get_maestro_table_ptr(dst, -1) == table_ptr);
297 sglua_stack_dump("dst after marking the table as known (should be ... table): ", dst);
299 /* copy the metatable if any */
300 int has_meta_table = lua_getmetatable(src, -1);
301 /* src: ... table mt? */
302 if (has_meta_table) {
303 XBT_DEBUG("%sCopying the metatable", sglua_get_spaces(indent));
304 /* src: ... table mt */
305 sglua_copy_table(src, dst);
306 /* dst: ... table mt */
309 lua_setmetatable(dst, -2);
314 XBT_DEBUG("%sNo metatable", sglua_get_spaces(indent));
317 sglua_stack_dump("src before traversing the table (should be ... table): ", src);
318 sglua_stack_dump("dst before traversing the table (should be ... table): ", dst);
320 /* traverse the table of src and copy each element */
322 /* src: ... table nil */
323 while (lua_next(src, -2) != 0) {
324 /* src: ... table key value */
326 XBT_DEBUG("%sCopying table element %s", sglua_get_spaces(indent),
327 sglua_keyvalue_tostring(src, -2, -1));
329 sglua_stack_dump("src before copying table element (should be ... table key value): ", src);
330 sglua_stack_dump("dst before copying table element (should be ... table): ", dst);
333 lua_pushvalue(src, -2);
334 /* src: ... table key value key */
336 XBT_DEBUG("%sCopying the key part of the table element",
337 sglua_get_spaces(indent));
338 sglua_move_value(src, dst);
339 /* src: ... table key value
340 dst: ... table key */
341 XBT_DEBUG("%sCopied the key part of the table element",
342 sglua_get_spaces(indent));
345 XBT_DEBUG("%sCopying the value part of the table element",
346 sglua_get_spaces(indent));
347 sglua_move_value(src, dst);
348 /* src: ... table key
349 dst: ... table key value */
350 XBT_DEBUG("%sCopied the value part of the table element",
351 sglua_get_spaces(indent));
354 /* set the table element */
355 lua_settable(dst, -3);
358 /* the key stays on top of src for next iteration */
359 sglua_stack_dump("src before next iteration (should be ... table key): ", src);
360 sglua_stack_dump("dst before next iteration (should be ... table): ", dst);
362 XBT_DEBUG("%sTable element copied", sglua_get_spaces(indent));
364 XBT_DEBUG("%sFinished traversing the table", sglua_get_spaces(indent));
369 * @brief Copies the function on the top of src to the top of dst.
371 * It can be a Lua function or a C function.
372 * Copying upvalues is not implemented yet.
374 * @param src source state
375 * @param dst destination state
377 static void sglua_copy_function(lua_State* src, lua_State* dst) {
379 if (lua_iscfunction(src, -1)) {
380 /* it's a C function */
382 XBT_DEBUG("It's a C function");
383 sglua_stack_dump("src before copying upvalues: ", src);
385 /* get the function pointer */
386 int function_index = lua_gettop(src);
387 lua_CFunction f = lua_tocfunction(src, function_index);
389 /* copy the upvalues */
391 const char* upvalue_name = NULL;
394 upvalue_name = lua_getupvalue(src, function_index, i);
396 if (upvalue_name != NULL) {
397 XBT_DEBUG("Upvalue %s", upvalue_name);
398 sglua_move_value(src, dst);
400 } while (upvalue_name != NULL);
402 sglua_stack_dump("src before copying pointer: ", src);
404 /* set the function */
405 lua_pushcclosure(dst, f, i - 1);
406 XBT_DEBUG("Function pointer copied");
409 /* it's a Lua function: dump it from src */
411 s_sglua_buffer_t buffer;
412 buffer.capacity = 128; /* an empty function uses 77 bytes */
414 buffer.data = xbt_new(char, buffer.capacity);
416 /* copy the binary chunk from src into a buffer */
417 int error = lua_dump(src, sglua_memory_writer, &buffer);
418 xbt_assert(!error, "Failed to dump the function from the source state: error %d",
420 XBT_DEBUG("Fonction dumped: %zu bytes", buffer.size);
423 fwrite(buffer.data, buffer.size, buffer.size, stderr);
424 fprintf(stderr, "\n");
427 /* load the chunk into dst */
428 error = luaL_loadbuffer(dst, buffer.data, buffer.size, "(dumped function)");
429 xbt_assert(!error, "Failed to load the function into the destination state: %s",
430 lua_tostring(dst, -1));
435 * @brief Copies the light userdata on the top of src to the top of dst.
436 * @param src source state
437 * @param dst destination state
439 static void sglua_copy_lightuserdata(lua_State* src, lua_State* dst) {
440 lua_pushlightuserdata(dst, lua_touserdata(src, -1));
444 * @brief Copies the full userdata on the top of src to the top of dst.
446 * If the userdata has a metatable, the metatable is also copied.
448 * @param src source state
449 * @param dst destination state
451 static void sglua_copy_userdata(lua_State* src, lua_State* dst) {
453 int indent = lua_gettop(dst) * 6 + 2;
458 size_t size = lua_objlen(src, -1);
459 void* src_block = lua_touserdata(src, -1);
460 void* dst_block = lua_newuserdata(dst, size);
462 memcpy(dst_block, src_block, size);
464 /* copy the metatable if any */
465 int has_meta_table = lua_getmetatable(src, -1);
466 /* src: ... udata mt? */
467 if (has_meta_table) {
468 XBT_DEBUG("%sCopying metatable of userdata (%p)",
469 sglua_get_spaces(indent), lua_topointer(src, -1));
470 /* src: ... udata mt */
471 sglua_copy_table(src, dst);
476 lua_setmetatable(dst, -2);
479 XBT_DEBUG("%sMetatable of userdata copied", sglua_get_spaces(indent));
482 XBT_DEBUG("%sNo metatable for this userdata",
483 sglua_get_spaces(indent));
489 * @brief This operation is not supported (yet?) so it just pushes nil.
491 * @param src source state
492 * @param dst destination state
494 static void sglua_copy_thread(lua_State* src, lua_State* dst) {
496 XBT_WARN("Copying a thread from another state is not implemented (yet?).");
501 * @brief Copies a global value or a registry value from the maestro state.
503 * The state L must have been created by sglua_clone_maestro_state().
504 * This function is meant to be an __index metamethod.
505 * Consequently, it assumes that the stack has two elements:
506 * a table (either the environment or the registry of L) and the string key of
507 * a value that does not exist yet in this table. It copies the corresponding
508 * value from maestro and pushes it on the stack of L.
509 * If the value does not exist in maestro state either, nil is pushed.
511 * TODO: make this function thread safe. If the simulation runs in parallel,
512 * several simulated processes may trigger this __index metamethod at the same
513 * time and get globals from maestro.
515 * @param L the current state
516 * @return number of return values pushed (always 1)
518 static int l_get_from_maestro(lua_State *L) {
520 /* check the arguments */
521 luaL_checktype(L, 1, LUA_TTABLE);
522 const char* key = luaL_checkstring(L, 2);
524 XBT_DEBUG("__index of '%s' begins", key);
526 /* want a global or a registry value? */
528 if (lua_equal(L, 1, LUA_REGISTRYINDEX)) {
530 pseudo_index = LUA_REGISTRYINDEX;
531 XBT_DEBUG("Will get the value from the registry of maestro");
535 pseudo_index = LUA_GLOBALSINDEX;
536 XBT_DEBUG("Will get the value from the globals of maestro");
540 lua_State* maestro = sglua_get_maestro();
544 /* get the value from maestro */
545 lua_getfield(maestro, pseudo_index, key);
546 /* maestro: ... value */
548 /* push the value onto the stack of L */
549 sglua_move_value(maestro, L);
551 L: table key value */
553 /* prepare the return value of __index */
554 lua_pushvalue(L, -1);
555 /* L: table key value value */
557 /* L: value table key value */
559 /* save the copied value in the table for subsequent accesses */
565 XBT_DEBUG("__index of '%s' returns %s", key, sglua_tostring(L, -1));
571 * @brief Creates a new Lua state and get its environment from the maestro
574 * The state created is independent from maestro and has its own copies of
575 * global and registry values.
576 * However, the global and registry values are not copied right now from
577 * the original state; they are copied only the first time they are accessed.
578 * This behavior saves time and memory, and is okay for Simgrid's needs.
580 * TODO: if the simulation runs in parallel, copy everything right now?
582 * @return the state created
584 lua_State* sglua_clone_maestro(void) {
586 /* create the new state */
587 lua_State *L = luaL_newstate();
589 /* set its environment and its registry:
590 * - create a table newenv
591 * - create a metatable mt
592 * - set mt.__index = a function that copies the global from the father state
593 * - set mt as the metatable of the registry
594 * - set mt as the metatable of newenv
595 * - set newenv as the environment of the new state
597 lua_pushthread(L); /* thread */
598 lua_newtable(L); /* thread newenv */
599 lua_newtable(L); /* thread newenv mt */
600 lua_pushvalue(L, LUA_REGISTRYINDEX); /* thread newenv mt reg */
601 lua_pushcfunction(L, l_get_from_maestro); /* thread newenv mt reg f */
602 lua_setfield(L, -3, "__index"); /* thread newenv mt reg */
603 lua_pushvalue(L, -2); /* thread newenv mt reg mt */
604 lua_setmetatable(L, -2); /* thread newenv mt reg */
605 lua_pop(L, 1); /* thread newenv mt */
606 lua_setmetatable(L, -2); /* thread newenv */
607 lua_setfenv(L, -2); /* thread */
608 lua_pop(L, 1); /* -- */
610 /* create the table of known tables from maestro */
611 lua_pushstring(L, "simgrid.maestro_tables");
612 /* "simgrid.maestro_tables" */
613 lua_newtable(L); /* "simgrid.maestro_tables" maestrotbs*/
614 lua_rawset(L, LUA_REGISTRYINDEX);
617 /* opening the standard libs is not necessary as they are
618 * inherited like any global values */
619 /* luaL_openlibs(L); */
621 XBT_DEBUG("New state created");