Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
dcde461ad9403d4a0a06e6e317bed169f59e965c
[simgrid.git] / src / bindings / lua / simgrid_lua.c
1 /* SimGrid Lua bindings                                                     */
2
3 /* Copyright (c) 2010. The SimGrid Team.
4  * All rights reserved.                                                     */
5
6 /* This program is free software; you can redistribute it and/or modify it
7  * under the terms of the license (GNU LGPL) which comes with this package. */
8 #include "simgrid_lua.h"
9 #include <string.h> // memcpy
10
11 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(lua, bindings, "Lua Bindings");
12
13 static lua_State *lua_maestro_state;
14
15 #define TASK_MODULE_NAME "simgrid.Task"
16 #define HOST_MODULE_NAME "simgrid.Host"
17 // Surf (bypass XML)
18 #define LINK_MODULE_NAME "simgrid.Link"
19 #define ROUTE_MODULE_NAME "simgrid.Route"
20 #define AS_MODULE_NAME "simgrid.AS"
21 #define TRACE_MODULE_NAME "simgrid.Trace"
22
23 /**
24  * @brief A chunk of memory.
25  *
26  * TODO replace this by a dynar
27  */
28 typedef struct s_buffer {
29   char* data;
30   size_t size;
31   size_t capacity;
32 } s_buffer_t, *buffer_t;
33
34 static const char* value_tostring(lua_State* L, int index);
35 static const char* keyvalue_tostring(lua_State* L, int key_index, int value_index);
36 static void stack_dump(const char *msg, lua_State* L);
37 static int writer(lua_State* L, const void* source, size_t size, void* userdata);
38 static void move_value(lua_State* dst, lua_State* src, const char* name);
39 static int l_get_from_father(lua_State* L);
40 static lua_State *clone_lua_state(lua_State* L);
41 static m_task_t check_task(lua_State *L, int index);
42 static void register_c_functions(lua_State *L);
43
44 /* ********************************************************************************* */
45 /*                            helper functions                                       */
46 /* ********************************************************************************* */
47
48 /**
49  * @brief Returns a string representation of a value in the Lua stack.
50  *
51  * This function is for debugging purposes.
52  * It always returns the same pointer.
53  *
54  * @param L the Lua state
55  * @param index index in the stack
56  * @return a string representation of the value at this index
57  */
58 static const char* value_tostring(lua_State* L, int index) {
59
60   static char buff[64];
61
62   switch (lua_type(L, index)) {
63
64     case LUA_TNIL:
65       sprintf(buff, "nil");
66       break;
67
68     case LUA_TNUMBER:
69       sprintf(buff, "%.3f", lua_tonumber(L, index));
70       break;
71
72     case LUA_TBOOLEAN:
73       sprintf(buff, "%s", lua_toboolean(L, index) ? "true" : "false");
74       break;
75
76     case LUA_TSTRING:
77       snprintf(buff, 63, "'%s'", lua_tostring(L, index));
78       break;
79
80     case LUA_TFUNCTION:
81       if (lua_iscfunction(L, index)) {
82         sprintf(buff, "C-function");
83       }
84       else {
85         sprintf(buff, "function");
86       }
87       break;
88
89     case LUA_TTABLE:
90       sprintf(buff, "table(%zu)", lua_objlen(L, index));
91       break;
92
93     case LUA_TLIGHTUSERDATA:
94     case LUA_TUSERDATA:
95       sprintf(buff, "userdata(%p)", lua_touserdata(L, index));
96       break;
97
98     case LUA_TTHREAD:
99       sprintf(buff, "thread");
100       break;
101   }
102   return buff;
103 }
104
105 /**
106  * @brief Returns a string representation of a key-value pair.
107  *
108  * This function is for debugging purposes.
109  * It always returns the same pointer.
110  *
111  * @param L the Lua state
112  * @param key_index index of the key
113  * @param value_index index of the value
114  * @return a string representation of the key-value pair
115  */
116 static const char* keyvalue_tostring(lua_State* L, int key_index, int value_index) {
117
118   static char buff[64];
119   /* value_tostring also always returns the same pointer */
120   int len = snprintf(buff, 63, "%s -> ", value_tostring(L, key_index));
121   snprintf(buff + len, 63 - len, "%s", value_tostring(L, value_index));
122   return buff;
123 }
124
125 /**
126  * @brief Returns a string composed of the specified number of spaces.
127  *
128  * This function is for debugging purposes.
129  * It always returns the same pointer.
130  *
131  * @param length length of the string
132  * @return a string of this length with only spaces
133  */
134 static const char* get_spaces(int length) {
135
136   static char spaces[128];
137
138   xbt_assert(length < 128);
139   memset(spaces, ' ', length);
140   spaces[length] = '\0';
141   return spaces;
142 }
143
144 /**
145  * @brief Dumps the Lua stack if debug logs are enabled.
146  * @param msg a message to print
147  * @param L a Lua state
148  */
149 static void stack_dump(const char* msg, lua_State* L)
150 {
151   if (XBT_LOG_ISENABLED(lua, xbt_log_priority_debug)) {
152     char buff[2048];
153     char* p = buff;
154     int i;
155     int top = lua_gettop(L);
156
157     if (1) return;
158
159     fflush(stdout);
160
161     p[0] = '\0';
162     for (i = 1; i <= top; i++) {  /* repeat for each level */
163
164       p += sprintf(p, "%s", value_tostring(L, i));
165       p += sprintf(p, " ");       /* put a separator */
166     }
167     XBT_DEBUG("%s%s", msg, buff);
168   }
169 }
170
171 /**
172  * @brief Writes the specified data into a memory buffer.
173  *
174  * This function is a valid lua_Writer that writes into a memory buffer passed
175  * as userdata.
176  *
177  * @param L a lua state
178  * @param source some data
179  * @param sz number of bytes of data
180  * @param user_data the memory buffer to write
181  */
182 static int writer(lua_State* L, const void* source, size_t size, void* userdata) {
183
184   buffer_t buffer = (buffer_t) userdata;
185   while (buffer->capacity < buffer->size + size) {
186     buffer->capacity *= 2;
187     buffer->data = xbt_realloc(buffer->data, buffer->capacity);
188   }
189   memcpy(buffer->data + buffer->size, source, size);
190   buffer->size += size;
191
192   return 0;
193 }
194
195 /**
196  * @brief Pops a value from the stack of a source state and pushes it on the
197  * stack of another state.
198  *
199  * If the value is a table, its content is copied recursively. To avoid cycles,
200  * a table of previsously visited tables must be present at index 1 of dst.
201  * Its keys are pointers to visited tables in src and its values are the tables
202  * already built.
203  *
204  * TODO: add support of closures
205  *
206  * @param src the source state
207  * @param dst the destination state
208  * @param name a name describing the value
209  */
210 static void move_value(lua_State* dst, lua_State *src, const char* name) {
211
212   luaL_checkany(src, -1);                  /* check the value to copy */
213   luaL_checktype(dst, 1, LUA_TTABLE);      /* check the presence of a table of
214                                               previously visited tables */
215
216   int indentation_level = (lua_gettop(dst) - 1) * 6;
217   const char* indent = get_spaces(indentation_level);
218
219   XBT_DEBUG("%sCopying value %s", indent, name);
220   indent = get_spaces(indentation_level + 2);
221
222   stack_dump("src before copying a value (should be ... value): ", src);
223   stack_dump("dst before copying a value (should be visited ...): ", dst);
224
225   switch (lua_type(src, -1)) {
226
227     case LUA_TNIL:
228       lua_pushnil(dst);
229       break;
230
231     case LUA_TNUMBER:
232       lua_pushnumber(dst, lua_tonumber(src, -1));
233       break;
234
235     case LUA_TBOOLEAN:
236       lua_pushboolean(dst, lua_toboolean(src, -1));
237       break;
238
239     case LUA_TSTRING:
240       /* no worries about memory: lua_pushstring makes a copy */
241       lua_pushstring(dst, lua_tostring(src, -1));
242       break;
243
244     case LUA_TFUNCTION:
245       /* it's a function that does not exist yet in L2 */
246
247       if (lua_iscfunction(src, -1)) {
248         /* it's a C function: just copy the pointer */
249         lua_CFunction f = lua_tocfunction(src, -1);
250         lua_pushcfunction(dst, f);
251       }
252       else {
253         /* it's a Lua function: dump it from src */
254         XBT_DEBUG("%sDumping Lua function '%s'", indent, name);
255
256         s_buffer_t buffer;
257         buffer.capacity = 64;
258         buffer.size = 0;
259         buffer.data = xbt_new(char, buffer.capacity);
260
261         /* copy the binary chunk from src into a buffer */
262         int error = lua_dump(src, writer, &buffer);
263         xbt_assert(!error, "Failed to dump function '%s' from the source state: error %d",
264               name, error);
265
266         /* load the chunk into dst */
267         error = luaL_loadbuffer(dst, buffer.data, buffer.size, name);
268         xbt_assert(!error, "Failed to load function '%s' from the source state: %s",
269             name, lua_tostring(dst, -1));
270         XBT_DEBUG("%sFunction '%s' successfully dumped from source state.", indent, name);
271       }
272       break;
273
274     case LUA_TTABLE:
275
276       /* see if this table was already visited */
277       lua_pushlightuserdata(dst, (void*) lua_topointer(src, -1));
278                                   /* dst: visited ... psrctable */
279       lua_gettable(dst, 1);
280                                   /* dst: visited ... table/nil */
281       if (lua_istable(dst, -1)) {
282         XBT_DEBUG("%sNothing to do: table already visited", indent);
283                                   /* dst: visited ... table */
284       }
285       else {
286         XBT_DEBUG("%sFirst visit of this table", indent);
287                                   /* dst: visited ... nil */
288         lua_pop(dst, 1);
289                                   /* dst: visited ... */
290
291         /* first visit: create the new table in dst */
292         lua_newtable(dst);
293                                   /* dst: visited ... table */
294
295         /* mark the table as visited to avoid infinite recursion */
296         lua_pushlightuserdata(dst, (void*) lua_topointer(src, -1));
297                                   /* dst: visited ... table psrctable */
298         lua_pushvalue(dst, -2);
299                                   /* dst: visited ... table psrctable table */
300         lua_settable(dst, 1);
301                                   /* dst: visited ... table */
302         XBT_DEBUG("%sTable marked as visited", indent);
303
304         stack_dump("dst after marking the table as visited (should be visited ... table): ", dst);
305
306         /* copy the metatable if any */
307         int has_meta_table = lua_getmetatable(src, -1);
308                                   /* src: ... table mt? */
309         if (has_meta_table) {
310           XBT_DEBUG("%sCopying metatable", indent);
311                                   /* src: ... table mt */
312           move_value(dst, src, "metatable");
313                                   /* src: ... table
314                                      dst: visited ... table mt */
315           lua_setmetatable(dst, -2);
316                                   /* dst: visited ... table */
317         }
318         else {
319           XBT_DEBUG("%sNo metatable", indent);
320         }
321
322         stack_dump("src before traversing the table (should be ... table): ", src);
323         stack_dump("dst before traversing the table (should be visited ... table): ", dst);
324
325         /* traverse the table of src and copy each element */
326         lua_pushnil(src);
327                                   /* src: ... table nil */
328         while (lua_next(src, -2) != 0) {
329                                   /* src: ... table key value */
330
331           XBT_DEBUG("%sCopying table element %s", indent, keyvalue_tostring(src, -2, -1));
332           indent = get_spaces(indentation_level + 4);
333
334           stack_dump("src before copying table element (should be ... table key value): ", src);
335           stack_dump("dst before copying table element (should be visited ... table): ", dst);
336
337           /* copy the key */
338           lua_pushvalue(src, -2);
339                                   /* src: ... table key value key */
340           XBT_DEBUG("%sCopying the key part of the table element", indent);
341           move_value(dst, src, value_tostring(src, -1));
342                                   /* src: ... table key value
343                                      dst: visited ... table key */
344           XBT_DEBUG("%sCopied the key part of the table element", indent);
345
346           /* copy the value */
347           XBT_DEBUG("%sCopying the value part of the table element", indent);
348           move_value(dst, src, value_tostring(src, -1));
349                                   /* src: ... table key
350                                      dst: visited ... table key value */
351           XBT_DEBUG("%sCopied the value part of the table element", indent);
352
353           /* set the table element */
354           lua_settable(dst, -3);
355                                   /* dst: visited ... table */
356
357           /* the key stays on top of src for next iteration */
358           stack_dump("src before next iteration (should be ... table key): ", src);
359           stack_dump("dst before next iteration (should be visited ... table): ", dst);
360
361           indent = get_spaces(indentation_level + 2);
362         }
363         XBT_DEBUG("%sFinished traversing the table", indent);
364       }
365       break;
366
367     case LUA_TLIGHTUSERDATA:
368       lua_pushlightuserdata(dst, lua_touserdata(src, -1));
369       break;
370
371     case LUA_TUSERDATA:
372       XBT_WARN("Copying a full userdata is not supported yet.");
373       lua_pushnil(dst);
374       break;
375
376     case LUA_TTHREAD:
377       XBT_WARN("Cannot copy a thread from the source state.");
378       lua_pushnil(dst);
379       break;
380   }
381
382   /* pop the value from src */
383   lua_pop(src, 1);
384
385   indent = get_spaces(indentation_level);
386   XBT_DEBUG("%sCopied the value", indent);
387
388   stack_dump("src after copying a value (should be ...): ", src);
389   stack_dump("dst after copying a value (should be visited ... value): ", dst);
390 }
391
392 /**
393  * @brief Copies a global value from the father state.
394  *
395  * The state L must have a father, i.e. it should have been created by
396  * clone_lua_state().
397  * This function is meant to be an __index metamethod.
398  * Consequently, it assumes that the stack has two elements:
399  * a table (usually the environment of L) and the string key of a value
400  * that does not exist yet in this table. It copies the corresponding global
401  * value from the father state and pushes it on the stack of L.
402  * If the global value does not exist in the father state either, nil is
403  * pushed.
404  *
405  * TODO: make this function thread safe. If the simulation runs in parallel,
406  * several simulated processes may trigger this __index metamethod at the same
407  * time and get globals from maestro.
408  *
409  * @param L the current state
410  * @return number of return values pushed (always 1)
411  */
412 static int l_get_from_father(lua_State *L) {
413
414   /* retrieve the father */
415   lua_getfield(L, LUA_REGISTRYINDEX, "simgrid.father_state");
416   lua_State* father = lua_touserdata(L, -1);
417   xbt_assert(father != NULL, "This Lua state has no father");
418   lua_pop(L, 1);
419
420   /* get the global from the father */
421   const char* key = luaL_checkstring(L, 2);    /* L:      table key */
422   lua_getglobal(father, key);                  /* father: ... value */
423   XBT_DEBUG("__index of '%s' begins", key);
424
425   /* push the value onto the stack of L */
426   lua_newtable(L);                             /* L:      table key visited */
427   lua_insert(L, 1);                            /* L:      visited table key */
428   move_value(L, father, key);                  /* father: ...
429                                                   L:      visited table key value */
430   lua_remove(L, 1);                            /* L:      table key value */
431
432   /* prepare the return value of __index */
433   lua_pushvalue(L, -1);                        /* L:      table key value value */
434   lua_insert(L, 1);                            /* L:      value table key value */
435
436   /* save the copied value in the table for subsequent accesses */
437   lua_settable(L, -3);                         /* L:      value table */
438   lua_remove(L, 2);                            /* L:      value */
439
440   XBT_DEBUG("__index of '%s' returns %s", key, value_tostring(L, -1));
441
442   return 1;
443 }
444
445 /**
446  * @brief Creates a new Lua state and get its environment from an existing state.
447  *
448  * The state created is independent from the existing one and has its own
449  * copies of global variables and functions.
450  * However, the global variables and functions are not copied right now from
451  * the original state; they are copied only the first time they are accessed.
452  * This behavior saves time and memory, and is okay for Simgrid's needs.
453  *
454  * @param father an existing state
455  * @return the state created
456  */
457 static lua_State* clone_lua_state(lua_State *father) {
458
459   /* create the new state */
460   lua_State *L = luaL_newstate();
461
462   /* set its environment:
463    * - create a table newenv
464    * - create a metatable mt
465    * - set mt.__index = a function that copies the global from the father state
466    * - set mt as the metatable of newenv
467    * - set newenv as the environment of the new state
468    */
469   lua_pushthread(L);                        /* thread */
470   lua_newtable(L);                          /* thread newenv */
471   lua_newtable(L);                          /* thread newenv mt */
472   lua_pushcfunction(L, l_get_from_father);  /* thread newenv mt f */
473   lua_setfield(L, -2, "__index");           /* thread newenv mt */
474   lua_setmetatable(L, -2);                  /* thread newenv */
475   lua_setfenv(L, -2);                       /* thread */
476   lua_pop(L, 1);                            /* -- */
477
478   /* open the standard libs (theoretically, this is not necessary as they can
479    * be inherited like any global values, but without a proper support of
480    * closures, iterators like ipairs don't work). */
481   luaL_openlibs(L);
482
483   /* set a pointer to the father */
484   lua_pushlightuserdata(L, father);
485   lua_setfield(L, LUA_REGISTRYINDEX, "simgrid.father_state");
486
487   /* copy the registry */
488   lua_pushvalue(father, LUA_REGISTRYINDEX);    /* father: ... reg */
489   lua_newtable(L);                             /* L: visited */
490   move_value(L, father, "registry");           /* father: ...
491                                                   L: visited newreg */
492
493   /* set the pointer again */
494   lua_pushlightuserdata(L, father);            /* L: visited newreg father */
495   lua_setfield(L, -1, "simgrid.father_state"); /* L: visited newreg */
496   lua_replace(L, LUA_REGISTRYINDEX);           /* L: visited */
497   lua_pop(L, 1);                               /* L: -- */
498
499   XBT_DEBUG("New state created");
500
501   return L;
502 }
503
504 /**
505  * @brief Ensures that a userdata on the stack is a task
506  * and returns the pointer inside the userdata.
507  * @param L a Lua state
508  * @param index an index in the Lua stack
509  * @return the task at this index
510  */
511 static m_task_t checkTask(lua_State * L, int index)
512 {
513   m_task_t *pi, tk;
514   luaL_checktype(L, index, LUA_TTABLE);
515   lua_getfield(L, index, "__simgrid_task");
516   pi = (m_task_t *) luaL_checkudata(L, -1, TASK_MODULE_NAME);
517   if (pi == NULL)
518     luaL_typerror(L, index, TASK_MODULE_NAME);
519   tk = *pi;
520   if (!tk)
521     luaL_error(L, "null Task");
522   lua_pop(L, 1);
523   return tk;
524 }
525
526 /* ********************************************************************************* */
527 /*                           wrapper functions                                       */
528 /* ********************************************************************************* */
529
530 /**
531  * A task is either something to compute somewhere, or something to exchange between two hosts (or both).
532  * It is defined by a computing amount and a message size.
533  *
534  */
535
536 /* *              * *
537  * * Constructors * *
538  * *              * */
539
540 /**
541  * @brief Constructs a new task with the specified processing amount and amount
542  * of data needed.
543  *
544  * @param name  Task's name
545  *
546  * @param computeDuration       A value of the processing amount (in flop) needed to process the task.
547  *                              If 0, then it cannot be executed with the execute() method.
548  *                              This value has to be >= 0.
549  *
550  * @param messageSize           A value of amount of data (in bytes) needed to transfert this task.
551  *                              If 0, then it cannot be transfered with the get() and put() methods.
552  *                              This value has to be >= 0.
553  */
554 static int Task_new(lua_State * L)
555 {
556   XBT_DEBUG("Task new...");
557   const char *name = luaL_checkstring(L, 1);
558   int comp_size = luaL_checkint(L, 2);
559   int msg_size = luaL_checkint(L, 3);
560   m_task_t msg_task = MSG_task_create(name, comp_size, msg_size, NULL);
561   lua_newtable(L);              /* create a table, put the userdata on top of it */
562   m_task_t *lua_task = (m_task_t *) lua_newuserdata(L, sizeof(m_task_t));
563   *lua_task = msg_task;
564   luaL_getmetatable(L, TASK_MODULE_NAME);
565   lua_setmetatable(L, -2);
566   lua_setfield(L, -2, "__simgrid_task");        /* put the userdata as field of the table */
567   /* remove the args from the stack */
568   lua_remove(L, 1);
569   lua_remove(L, 1);
570   lua_remove(L, 1);
571   return 1;
572 }
573
574 static int Task_get_name(lua_State * L)
575 {
576   m_task_t tk = checkTask(L, -1);
577   lua_pushstring(L, MSG_task_get_name(tk));
578   return 1;
579 }
580
581 static int Task_computation_duration(lua_State * L)
582 {
583   m_task_t tk = checkTask(L, -1);
584   lua_pushnumber(L, MSG_task_get_compute_duration(tk));
585   return 1;
586 }
587
588 static int Task_execute(lua_State * L)
589 {
590   m_task_t tk = checkTask(L, -1);
591   int res = MSG_task_execute(tk);
592   lua_pushnumber(L, res);
593   return 1;
594 }
595
596 static int Task_destroy(lua_State * L)
597 {
598   m_task_t tk = checkTask(L, -1);
599   int res = MSG_task_destroy(tk);
600   lua_pushnumber(L, res);
601   return 1;
602 }
603
604 static int Task_send(lua_State * L)
605 {
606   //stackDump("send ",L);
607   m_task_t tk = checkTask(L, 1);
608   const char *mailbox = luaL_checkstring(L, 2);
609   lua_pop(L, 1);                // remove the string so that the task is on top of it
610   MSG_task_set_data(tk, L);     // Copy my stack into the task, so that the receiver can copy the lua task directly
611   MSG_error_t res = MSG_task_send(tk, mailbox);
612   while (MSG_task_get_data(tk) != NULL) // Don't mess up with my stack: the receiver didn't copy the data yet
613     MSG_process_sleep(0);       // yield
614
615   if (res != MSG_OK)
616     switch (res) {
617     case MSG_TIMEOUT:
618       XBT_DEBUG("MSG_task_send failed : Timeout");
619       break;
620     case MSG_TRANSFER_FAILURE:
621       XBT_DEBUG("MSG_task_send failed : Transfer Failure");
622       break;
623     case MSG_HOST_FAILURE:
624       XBT_DEBUG("MSG_task_send failed : Host Failure ");
625       break;
626     default:
627       XBT_ERROR
628           ("MSG_task_send failed : Unexpected error , please report this bug");
629       break;
630     }
631   return 0;
632 }
633
634 static int Task_recv_with_timeout(lua_State *L)
635 {
636   m_task_t tk = NULL;
637   const char *mailbox = luaL_checkstring(L, -2);
638   int timeout = luaL_checknumber(L, -1);
639   MSG_error_t res = MSG_task_receive_with_timeout(&tk, mailbox, timeout);
640
641   if (res == MSG_OK) {
642     lua_State *sender_stack = MSG_task_get_data(tk);
643     lua_xmove(sender_stack, L, 1);        // copy the data directly from sender's stack
644     MSG_task_set_data(tk, NULL);
645   }
646   else {
647     switch (res) {
648     case MSG_TIMEOUT:
649       XBT_DEBUG("MSG_task_receive failed : Timeout");
650       break;
651     case MSG_TRANSFER_FAILURE:
652       XBT_DEBUG("MSG_task_receive failed : Transfer Failure");
653       break;
654     case MSG_HOST_FAILURE:
655       XBT_DEBUG("MSG_task_receive failed : Host Failure ");
656       break;
657     default:
658       XBT_ERROR("MSG_task_receive failed : Unexpected error , please report this bug");
659       break;
660     }
661     lua_pushnil(L);
662   }
663   return 1;
664 }
665
666 static int Task_recv(lua_State * L)
667 {
668   lua_pushnumber(L, -1.0);
669   return Task_recv_with_timeout(L);
670 }
671
672 static const luaL_reg Task_methods[] = {
673   {"new", Task_new},
674   {"name", Task_get_name},
675   {"computation_duration", Task_computation_duration},
676   {"execute", Task_execute},
677   {"destroy", Task_destroy},
678   {"send", Task_send},
679   {"recv", Task_recv},
680   {"recv_timeout", Task_recv_with_timeout},
681   {NULL, NULL}
682 };
683
684 static int Task_gc(lua_State * L)
685 {
686   m_task_t tk = checkTask(L, -1);
687   if (tk)
688     MSG_task_destroy(tk);
689   return 0;
690 }
691
692 static int Task_tostring(lua_State * L)
693 {
694   lua_pushfstring(L, "Task :%p", lua_touserdata(L, 1));
695   return 1;
696 }
697
698 static const luaL_reg Task_meta[] = {
699   {"__gc", Task_gc},
700   {"__tostring", Task_tostring},
701   {NULL, NULL}
702 };
703
704 /**
705  * Host
706  */
707 static m_host_t checkHost(lua_State * L, int index)
708 {
709   m_host_t *pi, ht;
710   luaL_checktype(L, index, LUA_TTABLE);
711   lua_getfield(L, index, "__simgrid_host");
712   pi = (m_host_t *) luaL_checkudata(L, -1, HOST_MODULE_NAME);
713   if (pi == NULL)
714     luaL_typerror(L, index, HOST_MODULE_NAME);
715   ht = *pi;
716   if (!ht)
717     luaL_error(L, "null Host");
718   lua_pop(L, 1);
719   return ht;
720 }
721
722 static int Host_get_by_name(lua_State * L)
723 {
724   const char *name = luaL_checkstring(L, 1);
725   XBT_DEBUG("Getting Host from name...");
726   m_host_t msg_host = MSG_get_host_by_name(name);
727   if (!msg_host) {
728     luaL_error(L, "null Host : MSG_get_host_by_name failed");
729   }
730   lua_newtable(L);              /* create a table, put the userdata on top of it */
731   m_host_t *lua_host = (m_host_t *) lua_newuserdata(L, sizeof(m_host_t));
732   *lua_host = msg_host;
733   luaL_getmetatable(L, HOST_MODULE_NAME);
734   lua_setmetatable(L, -2);
735   lua_setfield(L, -2, "__simgrid_host");        /* put the userdata as field of the table */
736   /* remove the args from the stack */
737   lua_remove(L, 1);
738   return 1;
739 }
740
741 static int Host_get_name(lua_State * L)
742 {
743   m_host_t ht = checkHost(L, -1);
744   lua_pushstring(L, MSG_host_get_name(ht));
745   return 1;
746 }
747
748 static int Host_number(lua_State * L)
749 {
750   lua_pushnumber(L, MSG_get_host_number());
751   return 1;
752 }
753
754 static int Host_at(lua_State * L)
755 {
756   int index = luaL_checkinteger(L, 1);
757   m_host_t host = MSG_get_host_table()[index - 1];      // lua indexing start by 1 (lua[1] <=> C[0])
758   lua_newtable(L);              /* create a table, put the userdata on top of it */
759   m_host_t *lua_host = (m_host_t *) lua_newuserdata(L, sizeof(m_host_t));
760   *lua_host = host;
761   luaL_getmetatable(L, HOST_MODULE_NAME);
762   lua_setmetatable(L, -2);
763   lua_setfield(L, -2, "__simgrid_host");        /* put the userdata as field of the table */
764   return 1;
765
766 }
767
768 static int Host_self(lua_State * L)
769 {
770   m_host_t host = MSG_host_self();
771   lua_newtable(L);
772   m_host_t *lua_host =(m_host_t *)lua_newuserdata(L,sizeof(m_host_t));
773   *lua_host = host;
774   luaL_getmetatable(L, HOST_MODULE_NAME);
775   lua_setmetatable(L, -2);
776   lua_setfield(L, -2, "__simgrid_host");
777   return 1;
778 }
779
780 static int Host_get_property_value(lua_State * L)
781 {
782   m_host_t ht = checkHost(L, -2);
783   const char *prop = luaL_checkstring(L, -1);
784   lua_pushstring(L,MSG_host_get_property_value(ht,prop));
785   return 1;
786 }
787
788 static int Host_sleep(lua_State *L)
789 {
790   int time = luaL_checknumber(L, -1);
791   MSG_process_sleep(time);
792   return 1;
793 }
794
795 static int Host_destroy(lua_State *L)
796 {
797   m_host_t ht = checkHost(L, -1);
798   __MSG_host_destroy(ht);
799   return 1;
800 }
801
802 /* ********************************************************************************* */
803 /*                           lua_stub_generator functions                            */
804 /* ********************************************************************************* */
805
806 xbt_dict_t process_function_set;
807 xbt_dynar_t process_list;
808 xbt_dict_t machine_set;
809 static s_process_t process;
810
811 void s_process_free(void *process)
812 {
813   s_process_t *p = (s_process_t *) process;
814   int i;
815   for (i = 0; i < p->argc; i++)
816     free(p->argv[i]);
817   free(p->argv);
818   free(p->host);
819 }
820
821 static int gras_add_process_function(lua_State * L)
822 {
823   const char *arg;
824   const char *process_host = luaL_checkstring(L, 1);
825   const char *process_function = luaL_checkstring(L, 2);
826
827   if (xbt_dict_is_empty(machine_set)
828       || xbt_dict_is_empty(process_function_set)
829       || xbt_dynar_is_empty(process_list)) {
830     process_function_set = xbt_dict_new();
831     process_list = xbt_dynar_new(sizeof(s_process_t), s_process_free);
832     machine_set = xbt_dict_new();
833   }
834
835   xbt_dict_set(machine_set, process_host, NULL, NULL);
836   xbt_dict_set(process_function_set, process_function, NULL, NULL);
837
838   process.argc = 1;
839   process.argv = xbt_new(char *, 1);
840   process.argv[0] = xbt_strdup(process_function);
841   process.host = strdup(process_host);
842
843   lua_pushnil(L);
844   while (lua_next(L, 3) != 0) {
845     arg = lua_tostring(L, -1);
846     process.argc++;
847     process.argv =
848         xbt_realloc(process.argv, (process.argc) * sizeof(char *));
849     process.argv[(process.argc) - 1] = xbt_strdup(arg);
850
851     XBT_DEBUG("index = %f , arg = %s \n", lua_tonumber(L, -2),
852            lua_tostring(L, -1));
853     lua_pop(L, 1);
854   }
855   lua_pop(L, 1);
856   //add to the process list
857   xbt_dynar_push(process_list, &process);
858   return 0;
859 }
860
861
862 static int gras_generate(lua_State * L)
863 {
864   const char *project_name = luaL_checkstring(L, 1);
865   generate_sim(project_name);
866   generate_rl(project_name);
867   generate_makefile_local(project_name);
868   return 0;
869 }
870
871 /***********************************
872  *      Tracing
873  **********************************/
874 static int trace_start(lua_State *L)
875 {
876 #ifdef HAVE_TRACING
877   TRACE_start();
878 #endif
879   return 1;
880 }
881
882 static int trace_category(lua_State * L)
883 {
884 #ifdef HAVE_TRACING
885   TRACE_category(luaL_checkstring(L, 1));
886 #endif
887   return 1;
888 }
889
890 static int trace_set_task_category(lua_State *L)
891 {
892 #ifdef HAVE_TRACING
893   TRACE_msg_set_task_category(checkTask(L, -2), luaL_checkstring(L, -1));
894 #endif
895   return 1;
896 }
897
898 static int trace_end(lua_State *L)
899 {
900 #ifdef HAVE_TRACING
901   TRACE_end();
902 #endif
903   return 1;
904 }
905
906 // *********** Register Methods ******************************************* //
907
908 /*
909  * Host Methods
910  */
911 static const luaL_reg Host_methods[] = {
912   {"getByName", Host_get_by_name},
913   {"name", Host_get_name},
914   {"number", Host_number},
915   {"at", Host_at},
916   {"self", Host_self},
917   {"getPropValue", Host_get_property_value},
918   {"sleep", Host_sleep},
919   {"destroy", Host_destroy},
920   // Bypass XML Methods
921   {"setFunction", console_set_function},
922   {"setProperty", console_host_set_property},
923   {NULL, NULL}
924 };
925
926 static int Host_gc(lua_State * L)
927 {
928   m_host_t ht = checkHost(L, -1);
929   if (ht)
930     ht = NULL;
931   return 0;
932 }
933
934 static int Host_tostring(lua_State * L)
935 {
936   lua_pushfstring(L, "Host :%p", lua_touserdata(L, 1));
937   return 1;
938 }
939
940 static const luaL_reg Host_meta[] = {
941   {"__gc", Host_gc},
942   {"__tostring", Host_tostring},
943   {0, 0}
944 };
945
946 /*
947  * AS Methods
948  */
949 static const luaL_reg AS_methods[] = {
950   {"new", console_add_AS},
951   {"addHost", console_add_host},
952   {"addLink", console_add_link},
953   {"addRoute", console_add_route},
954   {NULL, NULL}
955 };
956
957 /**
958  * Tracing Functions
959  */
960 static const luaL_reg Trace_methods[] = {
961   {"start", trace_start},
962   {"category", trace_category},
963   {"setTaskCategory", trace_set_task_category},
964   {"finish", trace_end},
965   {NULL, NULL}
966 };
967
968 /*
969  * Environment related
970  */
971
972 /**
973  * @brief Runs a Lua function as a new simulated process.
974  * @param argc number of arguments of the function
975  * @param argv name of the Lua function and array of its arguments
976  * @return result of the function
977  */
978 static int run_lua_code(int argc, char **argv)
979 {
980   XBT_DEBUG("Run lua code %s", argv[0]);
981
982   lua_State *L = clone_lua_state(lua_maestro_state);
983   int res = 1;
984
985   /* start the function */
986   lua_getglobal(L, argv[0]);
987   xbt_assert(lua_isfunction(L, -1),
988               "The lua function %s does not seem to exist", argv[0]);
989
990   /* push arguments onto the stack */
991   int i;
992   for (i = 1; i < argc; i++)
993     lua_pushstring(L, argv[i]);
994
995   /* call the function */
996   int err;
997   err = lua_pcall(L, argc - 1, 1, 0);
998   xbt_assert(err == 0, "error running function `%s': %s", argv[0],
999               lua_tostring(L, -1));
1000
1001   /* retrieve result */
1002   if (lua_isnumber(L, -1)) {
1003     res = lua_tonumber(L, -1);
1004     lua_pop(L, 1);              /* pop returned value */
1005   }
1006
1007   XBT_DEBUG("Execution of Lua code %s is over", (argv ? argv[0] : "(null)"));
1008
1009   return res;
1010 }
1011
1012 static int launch_application(lua_State * L)
1013 {
1014   const char *file = luaL_checkstring(L, 1);
1015   MSG_function_register_default(run_lua_code);
1016   MSG_launch_application(file);
1017   return 0;
1018 }
1019
1020 static int create_environment(lua_State * L)
1021 {
1022   const char *file = luaL_checkstring(L, 1);
1023   XBT_DEBUG("Loading environment file %s", file);
1024   MSG_create_environment(file);
1025   return 0;
1026 }
1027
1028 static int debug(lua_State * L)
1029 {
1030   const char *str = luaL_checkstring(L, 1);
1031   XBT_DEBUG("%s", str);
1032   return 0;
1033 }
1034
1035 static int info(lua_State * L)
1036 {
1037   const char *str = luaL_checkstring(L, 1);
1038   XBT_INFO("%s", str);
1039   return 0;
1040 }
1041
1042 static int run(lua_State * L)
1043 {
1044   MSG_main();
1045   return 0;
1046 }
1047
1048 static int clean(lua_State * L)
1049 {
1050   MSG_clean();
1051   return 0;
1052 }
1053
1054 /*
1055  * Bypass XML Parser (lua console)
1056  */
1057
1058 /*
1059  * Register platform for MSG
1060  */
1061 static int msg_register_platform(lua_State * L)
1062 {
1063   /* Tell Simgrid we dont wanna use its parser */
1064   surf_parse = console_parse_platform;
1065   surf_parse_reset_callbacks();
1066   surf_config_models_setup(NULL);
1067   MSG_create_environment(NULL);
1068   return 0;
1069 }
1070
1071 /*
1072  * Register platform for Simdag
1073  */
1074
1075 static int sd_register_platform(lua_State * L)
1076 {
1077   surf_parse = console_parse_platform_wsL07;
1078   surf_parse_reset_callbacks();
1079   surf_config_models_setup(NULL);
1080   SD_create_environment(NULL);
1081   return 0;
1082 }
1083
1084 /*
1085  * Register platform for gras
1086  */
1087 static int gras_register_platform(lua_State * L)
1088 {
1089   /* Tell Simgrid we dont wanna use surf parser */
1090   surf_parse = console_parse_platform;
1091   surf_parse_reset_callbacks();
1092   surf_config_models_setup(NULL);
1093   gras_create_environment(NULL);
1094   return 0;
1095 }
1096
1097 /**
1098  * Register applicaiton for MSG
1099  */
1100 static int msg_register_application(lua_State * L)
1101 {
1102   MSG_function_register_default(run_lua_code);
1103   surf_parse = console_parse_application;
1104   MSG_launch_application(NULL);
1105   return 0;
1106 }
1107
1108 /*
1109  * Register application for gras
1110  */
1111 static int gras_register_application(lua_State * L)
1112 {
1113   gras_function_register_default(run_lua_code);
1114   surf_parse = console_parse_application;
1115   gras_launch_application(NULL);
1116   return 0;
1117 }
1118
1119 static const luaL_Reg simgrid_funcs[] = {
1120   {"create_environment", create_environment},
1121   {"launch_application", launch_application},
1122   {"debug", debug},
1123   {"info", info},
1124   {"run", run},
1125   {"clean", clean},
1126   /* short names */
1127   {"platform", create_environment},
1128   {"application", launch_application},
1129   /* methods to bypass XML parser */
1130   {"msg_register_platform", msg_register_platform},
1131   {"sd_register_platform", sd_register_platform},
1132   {"msg_register_application", msg_register_application},
1133   {"gras_register_platform", gras_register_platform},
1134   {"gras_register_application", gras_register_application},
1135   /* gras sub generator method */
1136   {"gras_set_process_function", gras_add_process_function},
1137   {"gras_generate", gras_generate},
1138   {NULL, NULL}
1139 };
1140
1141 /* ********************************************************************************* */
1142 /*                       module management functions                                 */
1143 /* ********************************************************************************* */
1144
1145 #define LUA_MAX_ARGS_COUNT 10   /* maximum amount of arguments we can get from lua on command line */
1146
1147 int luaopen_simgrid(lua_State *L);     // Fuck gcc: we don't need that prototype
1148
1149 /**
1150  * This function is called automatically by the Lua interpreter when some Lua code requires
1151  * the "simgrid" module.
1152  * @param L the Lua state
1153  */
1154 int luaopen_simgrid(lua_State *L)
1155 {
1156   XBT_DEBUG("luaopen_simgrid *****");
1157
1158   /* Get the command line arguments from the lua interpreter */
1159   char **argv = malloc(sizeof(char *) * LUA_MAX_ARGS_COUNT);
1160   int argc = 1;
1161   argv[0] = (char *) "/usr/bin/lua";    /* Lie on the argv[0] so that the stack dumping facilities find the right binary. FIXME: what if lua is not in that location? */
1162
1163   lua_getglobal(L, "arg");
1164   /* if arg is a null value, it means we use lua only as a script to init platform
1165    * else it should be a table and then take arg in consideration
1166    */
1167   if (lua_istable(L, -1)) {
1168     int done = 0;
1169     while (!done) {
1170       argc++;
1171       lua_pushinteger(L, argc - 2);
1172       lua_gettable(L, -2);
1173       if (lua_isnil(L, -1)) {
1174         done = 1;
1175       } else {
1176         xbt_assert(lua_isstring(L, -1),
1177                     "argv[%d] got from lua is no string", argc - 1);
1178         xbt_assert(argc < LUA_MAX_ARGS_COUNT,
1179                     "Too many arguments, please increase LUA_MAX_ARGS_COUNT in %s before recompiling SimGrid if you insist on having more than %d args on command line",
1180                     __FILE__, LUA_MAX_ARGS_COUNT - 1);
1181         argv[argc - 1] = (char *) luaL_checkstring(L, -1);
1182         lua_pop(L, 1);
1183         XBT_DEBUG("Got command line argument %s from lua", argv[argc - 1]);
1184       }
1185     }
1186     argv[argc--] = NULL;
1187
1188     /* Initialize the MSG core */
1189     MSG_global_init(&argc, argv);
1190     XBT_DEBUG("Still %d arguments on command line", argc); // FIXME: update the lua's arg table to reflect the changes from SimGrid
1191   }
1192
1193   /* Keep the context mechanism informed of our lua world today */
1194   lua_maestro_state = L;
1195
1196   register_c_functions(L);
1197
1198   return 1;
1199 }
1200
1201 /**
1202  * Makes the appropriate Simgrid functions available to the Lua world.
1203  * @param L a Lua world
1204  */
1205 void register_c_functions(lua_State *L) {
1206
1207   /* register the core C functions to lua */
1208   luaL_register(L, "simgrid", simgrid_funcs);
1209
1210   /* register the task methods to lua */
1211   luaL_openlib(L, TASK_MODULE_NAME, Task_methods, 0);   // create methods table, add it to the globals
1212   luaL_newmetatable(L, TASK_MODULE_NAME);       // create metatable for Task, add it to the Lua registry
1213   luaL_openlib(L, 0, Task_meta, 0);     // fill metatable
1214   lua_pushliteral(L, "__index");
1215   lua_pushvalue(L, -3);         // dup methods table
1216   lua_rawset(L, -3);            // matatable.__index = methods
1217   lua_pushliteral(L, "__metatable");
1218   lua_pushvalue(L, -3);         // dup methods table
1219   lua_rawset(L, -3);            // hide metatable:metatable.__metatable = methods
1220   lua_pop(L, 1);                // drop metatable
1221
1222   /* register the hosts methods to lua */
1223   luaL_openlib(L, HOST_MODULE_NAME, Host_methods, 0);
1224   luaL_newmetatable(L, HOST_MODULE_NAME);
1225   luaL_openlib(L, 0, Host_meta, 0);
1226   lua_pushliteral(L, "__index");
1227   lua_pushvalue(L, -3);
1228   lua_rawset(L, -3);
1229   lua_pushliteral(L, "__metatable");
1230   lua_pushvalue(L, -3);
1231   lua_rawset(L, -3);
1232   lua_pop(L, 1);
1233
1234   /* register the links methods to lua */
1235   luaL_openlib(L, AS_MODULE_NAME, AS_methods, 0);
1236   luaL_newmetatable(L, AS_MODULE_NAME);
1237   lua_pop(L, 1);
1238
1239   /* register the Tracing functions to lua */
1240   luaL_openlib(L, TRACE_MODULE_NAME, Trace_methods, 0);
1241   luaL_newmetatable(L, TRACE_MODULE_NAME);
1242   lua_pop(L, 1);
1243 }