Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Lua: more debugging info
[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, bindings, "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 Adds a reference to a maestro table to the list of known maestro
35  * tables of a state.
36  *
37  * TODO identify maestro's tables with my own IDs instead of pointers
38  * to Lua internals
39  *
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
43  */
44 void sglua_add_maestro_table(lua_State* L, int index, void* maestro_table_ptr) {
45
46   /* we will set both [ptr] -> table and [table] -> ptr */
47
48                                   /* ... */
49   lua_pushvalue(L, index);
50                                   /* ... table */
51   lua_pushstring(L, "simgrid.maestro_tables");
52                                   /* ... table "simgrid.maestro_tables" */
53   lua_rawget(L, LUA_REGISTRYINDEX);
54                                   /* ... table maestrotbs */
55   lua_pushvalue(L, -2);
56                                   /* ... table maestrotbs table */
57   lua_pushlightuserdata(L, maestro_table_ptr);
58                                   /* ... table maestrotbs table tableptr */
59   lua_pushvalue(L, -1);
60                                   /* ... table maestrotbs table tableptr tableptr */
61   lua_pushvalue(L, -3);
62                                   /* ... table maestrotbs table tableptr tableptr table */
63   lua_settable(L, -5);
64                                   /* ... table maestrotbs table tableptr */
65   lua_settable(L, -3);
66                                   /* ... table maestrotbs */
67   lua_pop(L, 2);
68                                   /* ... */
69 }
70
71 /**
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
78  */
79 static void* sglua_get_maestro_table_ptr(lua_State* L, int index) {
80
81   void* maestro_table_ptr = NULL;
82                                   /* ... */
83   lua_pushvalue(L, index);
84                                   /* ... table */
85   lua_pushstring(L, "simgrid.maestro_tables");
86                                   /* ... table "simgrid.maestro_tables" */
87   lua_rawget(L, LUA_REGISTRYINDEX);
88                                   /* ... table maestrotbs */
89   lua_pushvalue(L, -2);
90                                   /* ... table maestrotbs table */
91   lua_gettable(L, -2);
92                                   /* ... table maestrotbs tableptr/nil */
93   if (!lua_isnil(L, -1)) {
94                                   /* ... table maestrotbs tableptr */
95     maestro_table_ptr = (void*) lua_topointer(L, -1);
96   }
97
98   lua_pop(L, 3);
99                                   /* ... */
100   return maestro_table_ptr;
101 }
102
103 /**
104  * @brief Pushes a table knowing a pointer to maestro's copy of this table.
105  *
106  * Pushes nil if L does not know this table in maestro.
107  *
108  * @param L a Lua state
109  * @param maestro_table_ptr pointer that identifies a table in maestro's world
110  */
111 static void sglua_get_table_by_ptr(lua_State* L, void* maestro_table_ptr) {
112
113                                   /* ... */
114   lua_pushstring(L, "simgrid.maestro_tables");
115                                   /* ... "simgrid.maestro_tables" */
116   lua_rawget(L, LUA_REGISTRYINDEX);
117                                   /* ... maestrotbs */
118   lua_pushlightuserdata(L, maestro_table_ptr);
119                                   /* ... maestrotbs tableptr */
120   lua_gettable(L, -2);
121                                   /* ... maestrotbs table/nil */
122   lua_remove(L, -2);
123                                   /* ... table/nil */
124 }
125
126 /**
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.
130  *
131  * This function is similar to lua_xmove() but it allows to move a value
132  * between two different global states.
133  *
134  * @param src the source state (not necessarily maestro)
135  * @param dst the destination state
136  */
137 void sglua_move_value(lua_State* src, lua_State *dst) {
138
139   luaL_checkany(src, -1);                  /* check the value to copy */
140
141   int indent = (lua_gettop(dst) - 1) * 6;
142   XBT_DEBUG("%sCopying data %s", sglua_get_spaces(indent), sglua_tostring(src, -1));
143
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);
146
147   switch (lua_type(src, -1)) {
148
149     case LUA_TNIL:
150       sglua_copy_nil(src, dst);
151       break;
152
153     case LUA_TNUMBER:
154       sglua_copy_number(src, dst);
155       break;
156
157     case LUA_TBOOLEAN:
158       sglua_copy_boolean(src, dst);
159       break;
160
161     case LUA_TSTRING:
162       sglua_copy_string(src, dst);
163       break;
164
165     case LUA_TFUNCTION:
166       sglua_copy_function(src, dst);
167       break;
168
169     case LUA_TTABLE:
170       sglua_copy_table(src, dst);
171       break;
172
173     case LUA_TLIGHTUSERDATA:
174       sglua_copy_lightuserdata(src, dst);
175       break;
176
177     case LUA_TUSERDATA:
178       sglua_copy_userdata(src, dst);
179       break;
180
181     case LUA_TTHREAD:
182       sglua_copy_thread(src, dst);
183       break;
184   }
185
186   /* the value has been copied to dst: remove it from src */
187   lua_pop(src, 1);
188
189   indent -= 2;
190   XBT_DEBUG("%sData copied", sglua_get_spaces(indent));
191
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);
194 }
195
196 /**
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
200  */
201 static void sglua_copy_nil(lua_State* src, lua_State* dst) {
202   lua_pushnil(dst);
203 }
204
205 /**
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
209  */
210 static void sglua_copy_number(lua_State* src, lua_State* dst) {
211   lua_pushnumber(dst, lua_tonumber(src, -1));
212 }
213
214 /**
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
218  */
219 static void sglua_copy_boolean(lua_State* src, lua_State* dst) {
220   lua_pushboolean(dst, lua_toboolean(src, -1));
221 }
222
223 /**
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
227  */
228 static void sglua_copy_string(lua_State* src, lua_State* dst) {
229
230   /* no worries about memory: lua_pushstring makes a copy */
231   lua_pushstring(dst, lua_tostring(src, -1));
232 }
233
234 /**
235  * @brief Copies the table value on the top of src to the top of dst.
236  *
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
240  * again.
241  *
242  * @param src source state
243  * @param dst destination state
244  */
245 static void sglua_copy_table(lua_State* src, lua_State* dst) {
246
247                                   /* src: ... table
248                                      dst: ... */
249   int indent = lua_gettop(dst) * 6  + 2;
250
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);
256
257     if (!sglua_is_maestro(src)) {
258       XBT_DEBUG("%sMaestro does not know this table",
259           sglua_get_spaces(indent));
260     }
261   }
262
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);
269   }
270
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);
277                                   /* dst: ... table */
278   }
279   else {
280     XBT_DEBUG("%sFirst visit of this table (%p)", sglua_get_spaces(indent),
281         table_ptr);
282                                   /* dst: ... nil */
283     lua_pop(dst, 1);
284                                   /* dst: ... */
285
286     /* first visit: create the new table in dst */
287     lua_newtable(dst);
288                                   /* dst: ... table */
289
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
293        problem? */
294     XBT_DEBUG("%sTable marked as known", sglua_get_spaces(indent));
295     xbt_assert(sglua_get_maestro_table_ptr(dst, -1) == table_ptr);
296
297     sglua_stack_dump("dst after marking the table as known (should be ... table): ", dst);
298
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 */
307       lua_pop(src, 1);
308                                   /* src: ... table */
309       lua_setmetatable(dst, -2);
310                                   /* dst: ... table */
311     }
312     else {
313                                   /* src: ... table */
314       XBT_DEBUG("%sNo metatable", sglua_get_spaces(indent));
315     }
316
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);
319
320     /* traverse the table of src and copy each element */
321     lua_pushnil(src);
322                                   /* src: ... table nil */
323     while (lua_next(src, -2) != 0) {
324                                   /* src: ... table key value */
325
326       XBT_DEBUG("%sCopying table element %s", sglua_get_spaces(indent),
327           sglua_keyvalue_tostring(src, -2, -1));
328
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);
331
332       /* copy the key */
333       lua_pushvalue(src, -2);
334                                   /* src: ... table key value key */
335       indent += 2;
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));
343
344       /* copy the value */
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));
352       indent -= 2;
353
354       /* set the table element */
355       lua_settable(dst, -3);
356                                   /* dst: ... table */
357
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);
361
362       XBT_DEBUG("%sTable element copied", sglua_get_spaces(indent));
363     }
364     XBT_DEBUG("%sFinished traversing the table", sglua_get_spaces(indent));
365   }
366 }
367
368 /**
369  * @brief Copies the function on the top of src to the top of dst.
370  *
371  * It can be a Lua function or a C function.
372  * Copying upvalues is not implemented yet.
373  *
374  * @param src source state
375  * @param dst destination state
376  */
377 static void sglua_copy_function(lua_State* src, lua_State* dst) {
378
379   if (lua_iscfunction(src, -1)) {
380     /* it's a C function */
381
382     XBT_DEBUG("It's a C function");
383     sglua_stack_dump("src before copying upvalues: ", src);
384
385     /* get the function pointer */
386     int function_index = lua_gettop(src);
387     lua_CFunction f = lua_tocfunction(src, function_index);
388
389     /* copy the upvalues */
390     int i = 0;
391     const char* upvalue_name = NULL;
392     do {
393       i++;
394       upvalue_name = lua_getupvalue(src, function_index, i);
395
396       if (upvalue_name != NULL) {
397         XBT_DEBUG("Upvalue %s", upvalue_name);
398         sglua_move_value(src, dst);
399       }
400     } while (upvalue_name != NULL);
401
402     sglua_stack_dump("src before copying pointer: ", src);
403
404     /* set the function */
405     lua_pushcclosure(dst, f, i - 1);
406     XBT_DEBUG("Function pointer copied");
407   }
408   else {
409     /* it's a Lua function: dump it from src */
410
411     s_sglua_buffer_t buffer;
412     buffer.capacity = 128; /* an empty function uses 77 bytes */
413     buffer.size = 0;
414     buffer.data = xbt_new(char, buffer.capacity);
415
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",
419         error);
420     XBT_DEBUG("Fonction dumped: %zu bytes", buffer.size);
421
422     /*
423     fwrite(buffer.data, buffer.size, buffer.size, stderr);
424     fprintf(stderr, "\n");
425     */
426
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));
431   }
432 }
433
434 /**
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
438  */
439 static void sglua_copy_lightuserdata(lua_State* src, lua_State* dst) {
440   lua_pushlightuserdata(dst, lua_touserdata(src, -1));
441 }
442
443 /**
444  * @brief Copies the full userdata on the top of src to the top of dst.
445  *
446  * If the userdata has a metatable, the metatable is also copied.
447  *
448  * @param src source state
449  * @param dst destination state
450  */
451 static void sglua_copy_userdata(lua_State* src, lua_State* dst) {
452
453   int indent = lua_gettop(dst) * 6  + 2;
454
455   /* copy the data */
456                                   /* src: ... udata
457                                      dst: ... */
458   size_t size = lua_objlen(src, -1);
459   void* src_block = lua_touserdata(src, -1);
460   void* dst_block = lua_newuserdata(dst, size);
461                                   /* dst: ... udata */
462   memcpy(dst_block, src_block, size);
463
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);
472                                   /* src: ... udata mt
473                                      dst: ... udata mt */
474     lua_pop(src, 1);
475                                   /* src: ... udata */
476     lua_setmetatable(dst, -2);
477                                   /* dst: ... udata */
478
479     XBT_DEBUG("%sMetatable of userdata copied", sglua_get_spaces(indent));
480   }
481   else {
482     XBT_DEBUG("%sNo metatable for this userdata",
483         sglua_get_spaces(indent));
484                                   /* src: ... udata */
485   }
486 }
487
488 /**
489  * @brief This operation is not supported (yet?) so it just pushes nil.
490  *
491  * @param src source state
492  * @param dst destination state
493  */
494 static void sglua_copy_thread(lua_State* src, lua_State* dst) {
495
496   XBT_WARN("Copying a thread from another state is not implemented (yet?).");
497   lua_pushnil(dst);
498 }
499
500 /**
501  * @brief Copies a global value or a registry value from the maestro state.
502  *
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.
510  *
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.
514  *
515  * @param L the current state
516  * @return number of return values pushed (always 1)
517  */
518 static int l_get_from_maestro(lua_State *L) {
519
520   /* check the arguments */
521   luaL_checktype(L, 1, LUA_TTABLE);
522   const char* key = luaL_checkstring(L, 2);
523                                   /* L:      table key */
524   XBT_DEBUG("__index of '%s' begins", key);
525
526   /* want a global or a registry value? */
527   int pseudo_index;
528   if (lua_equal(L, 1, LUA_REGISTRYINDEX)) {
529     /* registry */
530     pseudo_index = LUA_REGISTRYINDEX;
531     XBT_DEBUG("Will get the value from the registry of maestro");
532   }
533   else {
534     /* global */
535     pseudo_index = LUA_GLOBALSINDEX;
536     XBT_DEBUG("Will get the value from the globals of maestro");
537   }
538
539   /* get the father */
540   lua_State* maestro = sglua_get_maestro();
541
542                                   /* L:      table key */
543
544   /* get the value from maestro */
545   lua_getfield(maestro, pseudo_index, key);
546                                   /* maestro: ... value */
547
548   /* push the value onto the stack of L */
549   sglua_move_value(maestro, L);
550                                   /* maestro: ...
551                                      L:      table key value */
552
553   /* prepare the return value of __index */
554   lua_pushvalue(L, -1);
555                                   /* L:      table key value value */
556   lua_insert(L, 1);
557                                   /* L:      value table key value */
558
559   /* save the copied value in the table for subsequent accesses */
560   lua_settable(L, -3);
561                                   /* L:      value table */
562   lua_settop(L, 1);
563                                   /* L:      value */
564
565   XBT_DEBUG("__index of '%s' returns %s", key, sglua_tostring(L, -1));
566
567   return 1;
568 }
569
570 /**
571  * @brief Creates a new Lua state and get its environment from the maestro
572  * state.
573  *
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.
579  *
580  * TODO: if the simulation runs in parallel, copy everything right now?
581  *
582  * @return the state created
583  */
584 lua_State* sglua_clone_maestro(void) {
585
586   /* create the new state */
587   lua_State *L = luaL_newstate();
588
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
596    */
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);                            /* -- */
609
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);
615                                             /* -- */
616
617   /* opening the standard libs is not necessary as they are
618    * inherited like any global values */
619   /* luaL_openlibs(L); */
620
621   XBT_DEBUG("New state created");
622
623   return L;
624 }