Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
bd694ab798e8aaffe509435ccce220a4d8048c77
[simgrid.git] / src / bindings / lua / lua_state_cloner.c
1 /* Copyright (c) 2010. The SimGrid Team.
2  * All rights reserved.                                                     */
3
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. */
6
7 /* SimGrid Lua state management                                             */
8
9 #include "lua_state_cloner.h"
10 #include "lua_utils.h"
11 #include "xbt.h"
12 #include "xbt/log.h"
13 #include <lauxlib.h>
14 #include <lualib.h>
15
16 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(lua_state_cloner, lua, "Lua state management");
17
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);
22
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);
32
33 /**
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()
37  */
38 static lua_State* sglua_get_father(lua_State* L) {
39
40                                   /* ... */
41   lua_pushstring(L, "simgrid.father");
42                                   /* ... "simgrid.father" */
43   lua_rawget(L, LUA_REGISTRYINDEX);
44                                   /* ... father */
45   lua_State* father = lua_touserdata(L, -1);
46   lua_pop(L, 1);
47                                   /* ... */
48   return father;
49 }
50
51 /**
52  * @brief Adds a reference to a maestro table to the list of known maestro
53  * tables of a state.
54  *
55  * TODO identify maestro's tables with my own IDs instead of pointers
56  * to Lua internals
57  *
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
61  */
62 void sglua_add_maestro_table(lua_State* L, int index, void* maestro_table_ptr) {
63
64   /* we will set both [ptr] -> table and [table] -> ptr */
65
66                                   /* ... */
67   lua_pushvalue(L, index);
68                                   /* ... table */
69   lua_pushstring(L, "simgrid.maestro_tables");
70                                   /* ... table "simgrid.maestro_tables" */
71   lua_rawget(L, LUA_REGISTRYINDEX);
72                                   /* ... table maestrotbs */
73   lua_pushvalue(L, -2);
74                                   /* ... table maestrotbs table */
75   lua_pushlightuserdata(L, maestro_table_ptr);
76                                   /* ... table maestrotbs table tableptr */
77   lua_pushvalue(L, -1);
78                                   /* ... table maestrotbs table tableptr tableptr */
79   lua_pushvalue(L, -3);
80                                   /* ... table maestrotbs table tableptr tableptr table */
81   lua_settable(L, -5);
82                                   /* ... table maestrotbs table tableptr */
83   lua_settable(L, -3);
84                                   /* ... table maestrotbs */
85   lua_pop(L, 2);
86                                   /* ... */
87 }
88
89 /**
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
96  */
97 static void* sglua_get_maestro_table_ptr(lua_State* L, int index) {
98
99   void* maestro_table_ptr = NULL;
100                                   /* ... */
101   lua_pushvalue(L, index);
102                                   /* ... table */
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 */
109   lua_gettable(L, -2);
110                                   /* ... table maestrotbs tableptr/nil */
111   if (!lua_isnil(L, -1)) {
112                                   /* ... table maestrotbs tableptr */
113     maestro_table_ptr = (void*) lua_topointer(L, -1);
114   }
115
116   lua_pop(L, 3);
117                                   /* ... */
118   return maestro_table_ptr;
119 }
120
121 /**
122  * @brief Pushes a table knowing a pointer to maestro's copy of this table.
123  *
124  * Pushes nil if L does not know this table in maestro.
125  *
126  * @param L a Lua state
127  * @param maestro_table_ptr pointer that identifies a table in maestro's world
128  */
129 static void sglua_get_table_by_ptr(lua_State* L, void* maestro_table_ptr) {
130
131                                   /* ... */
132   lua_pushstring(L, "simgrid.maestro_tables");
133                                   /* ... "simgrid.maestro_tables" */
134   lua_rawget(L, LUA_REGISTRYINDEX);
135                                   /* ... maestrotbs */
136   lua_pushlightuserdata(L, maestro_table_ptr);
137                                   /* ... maestrotbs tableptr */
138   lua_gettable(L, -2);
139                                   /* ... maestrotbs table/nil */
140   lua_remove(L, -2);
141                                   /* ... table/nil */
142 }
143
144 /**
145  * @brief Pops a value from the stack of a source state and pushes it on the
146  * stack of another state.
147  *
148  * If the value is a table, its content is copied recursively.
149  *
150  * TODO: add support of closures
151  *
152  * @param src the source state (not necessarily maestro)
153  * @param dst the destination state
154  */
155 void sglua_move_value(lua_State* src, lua_State *dst) {
156
157   luaL_checkany(src, -1);                  /* check the value to copy */
158
159   int indent = (lua_gettop(dst) - 1) * 6;
160   XBT_DEBUG("%sCopying data %s", sglua_get_spaces(indent), sglua_tostring(src, -1));
161
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);
164
165   switch (lua_type(src, -1)) {
166
167     case LUA_TNIL:
168       sglua_copy_nil(src, dst);
169       break;
170
171     case LUA_TNUMBER:
172       sglua_copy_number(src, dst);
173       break;
174
175     case LUA_TBOOLEAN:
176       sglua_copy_boolean(src, dst);
177       break;
178
179     case LUA_TSTRING:
180       sglua_copy_string(src, dst);
181       break;
182
183     case LUA_TFUNCTION:
184       sglua_copy_function(src, dst);
185       break;
186
187     case LUA_TTABLE:
188       sglua_copy_table(src, dst);
189       break;
190
191     case LUA_TLIGHTUSERDATA:
192       sglua_copy_lightuserdata(src, dst);
193       break;
194
195     case LUA_TUSERDATA:
196       sglua_copy_userdata(src, dst);
197       break;
198
199     case LUA_TTHREAD:
200       sglua_copy_thread(src, dst);
201       break;
202   }
203
204   /* the value has been copied to dst: remove it from src */
205   lua_pop(src, 1);
206
207   indent -= 2;
208   XBT_DEBUG("%sData copied", sglua_get_spaces(indent));
209
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);
212 }
213
214 /**
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
218  */
219 static void sglua_copy_nil(lua_State* src, lua_State* dst) {
220   lua_pushnil(dst);
221 }
222
223 /**
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
227  */
228 static void sglua_copy_number(lua_State* src, lua_State* dst) {
229   lua_pushnumber(dst, lua_tonumber(src, -1));
230 }
231
232 /**
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
236  */
237 static void sglua_copy_boolean(lua_State* src, lua_State* dst) {
238   lua_pushboolean(dst, lua_toboolean(src, -1));
239 }
240
241 /**
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
245  */
246 static void sglua_copy_string(lua_State* src, lua_State* dst) {
247
248   /* no worries about memory: lua_pushstring makes a copy */
249   lua_pushstring(dst, lua_tostring(src, -1));
250 }
251
252 /**
253  * @brief Copies the table value on the top of src to the top of dst.
254  *
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
258  * again.
259  *
260  * @param src source state
261  * @param dst destination state
262  */
263 static void sglua_copy_table(lua_State* src, lua_State* dst) {
264
265                                   /* src: ... table
266                                      dst: ... */
267   int indent = lua_gettop(dst) * 6  + 2;
268
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);
274
275     if (!sglua_is_maestro(src)) {
276       XBT_DEBUG("%sMaestro does not know this table",
277           sglua_get_spaces(indent));
278     }
279   }
280
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);
287   }
288
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);
295                                   /* dst: ... table */
296   }
297   else {
298     XBT_DEBUG("%sFirst visit of this table (%p)", sglua_get_spaces(indent),
299         table_ptr);
300                                   /* dst: ... nil */
301     lua_pop(dst, 1);
302                                   /* dst: ... */
303
304     /* first visit: create the new table in dst */
305     lua_newtable(dst);
306                                   /* dst: ... table */
307
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
311        problem? */
312     XBT_DEBUG("%sTable marked as known", sglua_get_spaces(indent));
313     xbt_assert(sglua_get_maestro_table_ptr(dst, -1) == table_ptr);
314
315     sglua_stack_dump("dst after marking the table as known (should be ... table): ", dst);
316
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 */
325       lua_pop(src, 1);
326                                   /* src: ... table */
327       lua_setmetatable(dst, -2);
328                                   /* dst: ... table */
329     }
330     else {
331                                   /* src: ... table */
332       XBT_DEBUG("%sNo metatable", sglua_get_spaces(indent));
333     }
334
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);
337
338     /* traverse the table of src and copy each element */
339     lua_pushnil(src);
340                                   /* src: ... table nil */
341     while (lua_next(src, -2) != 0) {
342                                   /* src: ... table key value */
343
344       XBT_DEBUG("%sCopying table element %s", sglua_get_spaces(indent),
345           sglua_keyvalue_tostring(src, -2, -1));
346
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);
349
350       /* copy the key */
351       lua_pushvalue(src, -2);
352                                   /* src: ... table key value key */
353       indent += 2;
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));
361
362       /* copy the value */
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));
370       indent -= 2;
371
372       /* set the table element */
373       lua_settable(dst, -3);
374                                   /* dst: ... table */
375
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);
379
380       XBT_DEBUG("%sTable element copied", sglua_get_spaces(indent));
381     }
382     XBT_DEBUG("%sFinished traversing the table", sglua_get_spaces(indent));
383   }
384 }
385
386 /**
387  * @brief Copies the function on the top of src to the top of dst.
388  *
389  * It can be a Lua function or a C function.
390  * Copying upvalues is not implemented yet (TODO).
391  *
392  * @param src source state
393  * @param dst destination state
394  */
395 static void sglua_copy_function(lua_State* src, lua_State* dst) {
396
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);
401   }
402   else {
403     /* it's a Lua function: dump it from src */
404
405     s_sglua_buffer_t buffer;
406     buffer.capacity = 64;
407     buffer.size = 0;
408     buffer.data = xbt_new(char, buffer.capacity);
409
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",
413         error);
414
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));
419   }
420 }
421
422 /**
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
426  */
427 static void sglua_copy_lightuserdata(lua_State* src, lua_State* dst) {
428   lua_pushlightuserdata(dst, lua_touserdata(src, -1));
429 }
430
431 /**
432  * @brief Copies the full userdata on the top of src to the top of dst.
433  *
434  * If the userdata has a metatable, the metatable is also copied.
435  *
436  * @param src source state
437  * @param dst destination state
438  */
439 static void sglua_copy_userdata(lua_State* src, lua_State* dst) {
440
441   int indent = lua_gettop(dst) * 6  + 2;
442
443   /* copy the data */
444                                   /* src: ... udata
445                                      dst: ... */
446   size_t size = lua_objlen(src, -1);
447   void* src_block = lua_touserdata(src, -1);
448   void* dst_block = lua_newuserdata(dst, size);
449                                   /* dst: ... udata */
450   memcpy(dst_block, src_block, size);
451
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);
460                                   /* src: ... udata mt
461                                      dst: ... udata mt */
462     lua_pop(src, 1);
463                                   /* src: ... udata */
464     lua_setmetatable(dst, -2);
465                                   /* dst: ... udata */
466
467     XBT_DEBUG("%sMetatable of userdata copied", sglua_get_spaces(indent));
468   }
469   else {
470     XBT_DEBUG("%sNo metatable for this userdata",
471         sglua_get_spaces(indent));
472                                   /* src: ... udata */
473   }
474 }
475
476 /**
477  * @brief This operation is not supported (yet?) so it just pushes nil.
478  *
479  * @param src source state
480  * @param dst destination state
481  */
482 static void sglua_copy_thread(lua_State* src, lua_State* dst) {
483
484   XBT_WARN("Copying a thread from another state is not implemented (yet?).");
485   lua_pushnil(dst);
486 }
487
488 /**
489  * @brief Copies a global value or a registry value from the maestro state.
490  *
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.
498  *
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.
502  *
503  * @param L the current state
504  * @return number of return values pushed (always 1)
505  */
506 static int l_get_from_maestro(lua_State *L) {
507
508   /* check the arguments */
509   luaL_checktype(L, 1, LUA_TTABLE);
510   const char* key = luaL_checkstring(L, 2);
511                                   /* L:      table key */
512   XBT_DEBUG("__index of '%s' begins", key);
513
514   /* want a global or a registry value? */
515   int pseudo_index;
516   if (lua_equal(L, 1, LUA_REGISTRYINDEX)) {
517     /* registry */
518     pseudo_index = LUA_REGISTRYINDEX;
519     XBT_DEBUG("Will get the value from the registry of maestro");
520   }
521   else {
522     /* global */
523     pseudo_index = LUA_GLOBALSINDEX;
524     XBT_DEBUG("Will get the value from the globals of maestro");
525   }
526
527   /* get the father */
528   lua_State* maestro = sglua_get_maestro();
529
530                                   /* L:      table key */
531
532   /* get the value from maestro */
533   lua_getfield(maestro, pseudo_index, key);
534                                   /* maestro: ... value */
535
536   /* push the value onto the stack of L */
537   sglua_move_value(maestro, L);
538                                   /* maestro: ...
539                                      L:      table key value */
540
541   /* prepare the return value of __index */
542   lua_pushvalue(L, -1);
543                                   /* L:      table key value value */
544   lua_insert(L, 1);
545                                   /* L:      value table key value */
546
547   /* save the copied value in the table for subsequent accesses */
548   lua_settable(L, -3);
549                                   /* L:      value table */
550   lua_settop(L, 1);
551                                   /* L:      value */
552
553   XBT_DEBUG("__index of '%s' returns %s", key, sglua_tostring(L, -1));
554
555   return 1;
556 }
557
558 /**
559  * @brief Creates a new Lua state and get its environment from the maestro
560  * state.
561  *
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.
567  *
568  * TODO: if the simulation runs in parallel, copy everything right now?
569  *
570  * @return the state created
571  */
572 lua_State* sglua_clone_maestro(void) {
573
574   /* create the new state */
575   lua_State *L = luaL_newstate();
576
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
584    */
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);                            /* -- */
597
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);
603                                             /* -- */
604
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");
609   luaL_openlibs(L);
610
611   XBT_DEBUG("New state created");
612
613   return L;
614 }