1 /* SimGrid Lua bindings */
3 /* Copyright (c) 2010. The SimGrid Team.
4 * All rights reserved. */
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
11 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(lua, bindings, "Lua Bindings");
13 static lua_State *lua_maestro_state;
15 #define TASK_MODULE_NAME "simgrid.Task"
16 #define HOST_MODULE_NAME "simgrid.Host"
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"
24 * @brief A chunk of memory.
26 * TODO replace this by a dynar
28 typedef struct s_buffer {
32 } s_buffer_t, *buffer_t;
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 lua_State* get_father(lua_State* L);
39 static void move_value(lua_State* src, lua_State* dst);
40 static void move_value_impl(lua_State* src, lua_State* dst, const char* name);
41 static int l_get_from_father(lua_State* L);
42 static lua_State *clone_lua_state(lua_State* L);
43 static m_task_t check_task(lua_State *L, int index);
44 static void register_c_functions(lua_State *L);
46 /* ********************************************************************************* */
47 /* helper functions */
48 /* ********************************************************************************* */
51 * @brief Returns a string representation of a value in the Lua stack.
53 * This function is for debugging purposes.
54 * It always returns the same pointer.
56 * @param L the Lua state
57 * @param index index in the stack
58 * @return a string representation of the value at this index
60 static const char* value_tostring(lua_State* L, int index) {
64 switch (lua_type(L, index)) {
71 sprintf(buff, "%.3f", lua_tonumber(L, index));
75 sprintf(buff, "%s", lua_toboolean(L, index) ? "true" : "false");
79 snprintf(buff, 63, "'%s'", lua_tostring(L, index));
83 if (lua_iscfunction(L, index)) {
84 sprintf(buff, "C-function");
87 sprintf(buff, "function");
92 sprintf(buff, "table(%p)", lua_topointer(L, index));
95 case LUA_TLIGHTUSERDATA:
97 sprintf(buff, "userdata(%p)", lua_touserdata(L, index));
101 sprintf(buff, "thread");
108 * @brief Returns a string representation of a key-value pair.
110 * This function is for debugging purposes.
111 * It always returns the same pointer.
113 * @param L the Lua state
114 * @param key_index index of the key
115 * @param value_index index of the value
116 * @return a string representation of the key-value pair
118 static const char* keyvalue_tostring(lua_State* L, int key_index, int value_index) {
120 static char buff[64];
121 /* value_tostring also always returns the same pointer */
122 int len = snprintf(buff, 63, "[%s] -> ", value_tostring(L, key_index));
123 snprintf(buff + len, 63 - len, "%s", value_tostring(L, value_index));
128 * @brief Returns a string composed of the specified number of spaces.
130 * This function is for debugging purposes.
131 * It always returns the same pointer.
133 * @param length length of the string
134 * @return a string of this length with only spaces
136 static const char* get_spaces(int length) {
138 static char spaces[128];
140 xbt_assert(length < 128);
141 memset(spaces, ' ', length);
142 spaces[length] = '\0';
147 * @brief Dumps the Lua stack if debug logs are enabled.
148 * @param msg a message to print
149 * @param L a Lua state
151 static void stack_dump(const char* msg, lua_State* L)
153 if (XBT_LOG_ISENABLED(lua, xbt_log_priority_debug)) {
157 int top = lua_gettop(L);
164 for (i = 1; i <= top; i++) { /* repeat for each level */
166 p += sprintf(p, "%s", value_tostring(L, i));
167 p += sprintf(p, " "); /* put a separator */
169 XBT_DEBUG("%s%s", msg, buff);
174 * @brief Writes the specified data into a memory buffer.
176 * This function is a valid lua_Writer that writes into a memory buffer passed
179 * @param L a lua state
180 * @param source some data
181 * @param sz number of bytes of data
182 * @param user_data the memory buffer to write
184 static int writer(lua_State* L, const void* source, size_t size, void* userdata) {
186 buffer_t buffer = (buffer_t) userdata;
187 while (buffer->capacity < buffer->size + size) {
188 buffer->capacity *= 2;
189 buffer->data = xbt_realloc(buffer->data, buffer->capacity);
191 memcpy(buffer->data + buffer->size, source, size);
192 buffer->size += size;
198 * @brief Returns the father of a state.
199 * @param L a Lua state
202 static lua_State* get_father(lua_State* L) {
205 lua_pushstring(L, "simgrid.father");
206 /* ... "simgrid.father" */
207 lua_rawget(L, LUA_REGISTRYINDEX);
209 lua_State* father = lua_touserdata(L, -1);
216 * @brief Pops a value from a state and pushes it onto the stack of another
219 * @param src the source state
220 * @param dst the destination state
222 static void move_value(lua_State* src, lua_State* dst) {
226 /* get the list of visited tables from father at index 1 of dst */
229 lua_getfield(dst, LUA_REGISTRYINDEX, "simgrid.father_visited_tables");
230 /* dst: ... visited */
232 /* dst: visited ... */
234 move_value_impl(src, dst, value_tostring(src, -1));
236 dst: visited ... value */
239 stack_dump("src after xmove: ", src);
240 stack_dump("dst after xmove: ", dst);
245 * @brief Pops a value from the stack of a source state and pushes it on the
246 * stack of another state.
248 * If the value is a table, its content is copied recursively. To avoid cycles,
249 * a table of previously visited tables must be present at index 1 of dst.
250 * Its keys are pointers to visited tables in src and its values are the tables
253 * TODO: add support of closures
255 * @param src the source state
256 * @param dst the destination state, with a list of visited tables at index 1
257 * @param name a name describing the value
259 static void move_value_impl(lua_State* src, lua_State *dst, const char* name) {
261 luaL_checkany(src, -1); /* check the value to copy */
262 luaL_checktype(dst, 1, LUA_TTABLE); /* check the presence of a table of
263 previously visited tables */
265 int indent = (lua_gettop(dst) - 1) * 6;
266 XBT_DEBUG("%sCopying data %s", get_spaces(indent), name);
269 stack_dump("src before copying a value (should be ... value): ", src);
270 stack_dump("dst before copying a value (should be visited ...): ", dst);
272 switch (lua_type(src, -1)) {
279 lua_pushnumber(dst, lua_tonumber(src, -1));
283 lua_pushboolean(dst, lua_toboolean(src, -1));
287 /* no worries about memory: lua_pushstring makes a copy */
288 lua_pushstring(dst, lua_tostring(src, -1));
292 /* it's a function that does not exist yet in L2 */
294 if (lua_iscfunction(src, -1)) {
295 /* it's a C function: just copy the pointer */
296 lua_CFunction f = lua_tocfunction(src, -1);
297 lua_pushcfunction(dst, f);
300 /* it's a Lua function: dump it from src */
301 XBT_DEBUG("%sDumping Lua function '%s'", get_spaces(indent), name);
304 buffer.capacity = 64;
306 buffer.data = xbt_new(char, buffer.capacity);
308 /* copy the binary chunk from src into a buffer */
309 int error = lua_dump(src, writer, &buffer);
310 xbt_assert(!error, "Failed to dump function '%s' from the source state: error %d",
313 /* load the chunk into dst */
314 error = luaL_loadbuffer(dst, buffer.data, buffer.size, name);
315 xbt_assert(!error, "Failed to load function '%s' into the destination state: %s",
316 name, lua_tostring(dst, -1));
317 XBT_DEBUG("%sFunction '%s' successfully loaded", get_spaces(indent), name);
323 /* first register the table in the source state itself */
324 lua_getfield(src, LUA_REGISTRYINDEX, "simgrid.visited_tables");
325 /* src: ... table visited */
326 lua_pushlightuserdata(src, (void*) lua_topointer(src, -1));
327 /* src: ... table visited psrctable */
328 lua_pushvalue(src, -3);
329 /* src: ... table visited psrctable table */
330 lua_settable(src, -3);
331 /* src: ... table visited */
335 /* see if this table was already known by dst */
336 lua_pushlightuserdata(dst, (void*) lua_topointer(src, -1));
337 /* dst: visited ... psrctable */
338 lua_gettable(dst, 1);
339 /* dst: visited ... table/nil */
340 if (lua_istable(dst, -1)) {
341 XBT_DEBUG("%sNothing to do: table already visited (%p)",
342 get_spaces(indent), lua_topointer(src, -1));
343 /* dst: visited ... table */
346 XBT_DEBUG("%sFirst visit of this table (%p)", get_spaces(indent),
347 lua_topointer(src, -1));
348 /* dst: visited ... nil */
350 /* dst: visited ... */
352 /* first visit: create the new table in dst */
354 /* dst: visited ... table */
356 /* mark the table as visited to avoid infinite recursion */
357 lua_pushlightuserdata(dst, (void*) lua_topointer(src, -1));
358 /* dst: visited ... table psrctable */
359 lua_pushvalue(dst, -2);
360 /* dst: visited ... table psrctable table */
361 lua_settable(dst, 1);
362 /* dst: visited ... table */
363 XBT_DEBUG("%sTable marked as visited", get_spaces(indent));
365 stack_dump("dst after marking the table as visited (should be visited ... table): ", dst);
367 /* copy the metatable if any */
368 int has_meta_table = lua_getmetatable(src, -1);
369 /* src: ... table mt? */
370 if (has_meta_table) {
371 XBT_DEBUG("%sCopying metatable", get_spaces(indent));
372 /* src: ... table mt */
373 move_value_impl(src, dst, "metatable");
375 dst: visited ... table mt */
376 lua_setmetatable(dst, -2);
377 /* dst: visited ... table */
380 XBT_DEBUG("%sNo metatable", get_spaces(indent));
383 stack_dump("src before traversing the table (should be ... table): ", src);
384 stack_dump("dst before traversing the table (should be visited ... table): ", dst);
386 /* traverse the table of src and copy each element */
388 /* src: ... table nil */
389 while (lua_next(src, -2) != 0) {
390 /* src: ... table key value */
392 XBT_DEBUG("%sCopying table element %s", get_spaces(indent), keyvalue_tostring(src, -2, -1));
394 stack_dump("src before copying table element (should be ... table key value): ", src);
395 stack_dump("dst before copying table element (should be visited ... table): ", dst);
398 lua_pushvalue(src, -2);
399 /* src: ... table key value key */
401 XBT_DEBUG("%sCopying the key part of the table element", get_spaces(indent));
402 move_value_impl(src, dst, value_tostring(src, -1));
403 /* src: ... table key value
404 dst: visited ... table key */
405 XBT_DEBUG("%sCopied the key part of the table element", get_spaces(indent));
408 XBT_DEBUG("%sCopying the value part of the table element", get_spaces(indent));
409 move_value_impl(src, dst, value_tostring(src, -1));
410 /* src: ... table key
411 dst: visited ... table key value */
412 XBT_DEBUG("%sCopied the value part of the table element", get_spaces(indent));
415 /* set the table element */
416 lua_settable(dst, -3);
417 /* dst: visited ... table */
419 /* the key stays on top of src for next iteration */
420 stack_dump("src before next iteration (should be ... table key): ", src);
421 stack_dump("dst before next iteration (should be visited ... table): ", dst);
423 XBT_DEBUG("%sTable element copied", get_spaces(indent));
425 XBT_DEBUG("%sFinished traversing the table", get_spaces(indent));
429 case LUA_TLIGHTUSERDATA:
430 lua_pushlightuserdata(dst, lua_touserdata(src, -1));
438 size_t size = lua_objlen(src, -1);
439 void* src_block = lua_touserdata(src, -1);
440 void* dst_block = lua_newuserdata(dst, size);
441 /* dst: visited ... udata */
442 memcpy(dst_block, src_block, size);
444 /* copy the metatable if any */
445 int has_meta_table = lua_getmetatable(src, -1);
446 /* src: ... udata mt? */
447 if (has_meta_table) {
448 XBT_DEBUG("%sCopying metatable of userdata (%p)", get_spaces(indent),
449 lua_topointer(src, -1));
450 /* src: ... udata mt */
451 lua_State* father = get_father(dst);
453 if (father != NULL) {
454 XBT_DEBUG("%sGet the metatable from my father", get_spaces(indent));
455 /* find the same metatable in the father state */
456 /* TODO find in visited_tables of src the pointer to the same
457 * metatable in the father world, then copy the metatable from the
458 * father world into dst
460 lua_pushstring(father, "simgrid.visited_tables");
461 /* father: ... "simgrid.visited_tables" */
462 lua_rawget(father, LUA_REGISTRYINDEX);
463 /* father: ... visited */
464 lua_pushlightuserdata(father, (void*) lua_topointer(src, -1));
465 /* father: ... visited pfathermt */
466 lua_gettable(father, -2);
467 /* father: ... visited mt */
468 move_value_impl(father, dst, "(father metatable)");
469 /* father: ... visited
470 dst: visited ... udata mt */
475 XBT_DEBUG("%sI have no father", get_spaces(indent));
476 move_value_impl(src, dst, "metatable");
478 dst: visited ... udata mt */
480 lua_setmetatable(dst, -2);
481 /* dst: visited ... udata */
483 XBT_DEBUG("%sMetatable of userdata copied", get_spaces(indent));
486 XBT_DEBUG("%sNo metatable for this userdata", get_spaces(indent));
493 XBT_WARN("Cannot copy a thread from the source state.");
498 /* pop the value from src */
502 XBT_DEBUG("%sData copied", get_spaces(indent));
504 stack_dump("src after copying a value (should be ...): ", src);
505 stack_dump("dst after copying a value (should be visited ... value): ", dst);
509 * @brief Copies a global value or a registry value from the father state.
511 * The state L must have a father, i.e. it should have been created by
513 * This function is meant to be an __index metamethod.
514 * Consequently, it assumes that the stack has two elements:
515 * a table (either the environment or the registry of L) and the string key of
516 * a value that does not exist yet in this table. It copies the corresponding
517 * value from the father state and pushes it on the stack of L.
518 * If the value does not exist in the father state either, nil is pushed.
520 * TODO: make this function thread safe. If the simulation runs in parallel,
521 * several simulated processes may trigger this __index metamethod at the same
522 * time and get globals from maestro.
524 * @param L the current state
525 * @return number of return values pushed (always 1)
527 static int l_get_from_father(lua_State *L) {
529 /* check the arguments */
530 luaL_checktype(L, 1, LUA_TTABLE);
531 const char* key = luaL_checkstring(L, 2);
533 XBT_DEBUG("__index of '%s' begins", key);
535 /* want a global or a registry value? */
537 if (lua_equal(L, 1, LUA_REGISTRYINDEX)) {
539 pseudo_index = LUA_REGISTRYINDEX;
540 XBT_DEBUG("Will get the value from the registry of the father");
544 pseudo_index = LUA_GLOBALSINDEX;
545 XBT_DEBUG("Will get the value from the globals of the father");
549 lua_State* father = get_father(L);
551 if (father == NULL) {
552 XBT_WARN("This state has no father");
559 /* get the list of visited tables */
560 lua_pushstring(L, "simgrid.father_visited_tables");
561 /* L: table key "simgrid.father_visited_tables" */
562 lua_rawget(L, LUA_REGISTRYINDEX);
563 /* L: table key visited */
565 /* L: visited table key */
567 /* get the value from the father */
568 lua_getfield(father, pseudo_index, key);
569 /* father: ... value */
571 /* push the value onto the stack of L */
572 move_value_impl(father, L, key);
574 L: visited table key value */
576 /* L: table key value */
578 /* prepare the return value of __index */
579 lua_pushvalue(L, -1);
580 /* L: table key value value */
582 /* L: value table key value */
584 /* save the copied value in the table for subsequent accesses */
590 XBT_DEBUG("__index of '%s' returns %s", key, value_tostring(L, -1));
596 * @brief Creates a new Lua state and get its environment from an existing state.
598 * The state created is independent from the existing one and has its own
599 * copies of global variables and functions.
600 * However, the global variables and functions are not copied right now from
601 * the original state; they are copied only the first time they are accessed.
602 * This behavior saves time and memory, and is okay for Simgrid's needs.
604 * @param father an existing state
605 * @return the state created
607 static lua_State* clone_lua_state(lua_State *father) {
609 /* create the new state */
610 lua_State *L = luaL_newstate();
612 /* set its environment and its registry:
613 * - create a table newenv
614 * - create a metatable mt
615 * - set mt.__index = a function that copies the global from the father state
616 * - set mt as the metatable of the registry
617 * - set mt as the metatable of newenv
618 * - set newenv as the environment of the new state
620 lua_pushthread(L); /* thread */
621 lua_newtable(L); /* thread newenv */
622 lua_newtable(L); /* thread newenv mt */
623 lua_pushvalue(L, LUA_REGISTRYINDEX); /* thread newenv mt reg */
624 lua_pushcfunction(L, l_get_from_father); /* thread newenv mt reg f */
625 lua_setfield(L, -3, "__index"); /* thread newenv mt reg */
626 lua_pushvalue(L, -2); /* thread newenv mt reg mt */
627 lua_setmetatable(L, -2); /* thread newenv mt reg */
628 lua_pop(L, 1); /* thread newenv mt */
629 lua_setmetatable(L, -2); /* thread newenv */
630 lua_setfenv(L, -2); /* thread */
631 lua_pop(L, 1); /* -- */
633 /* set a pointer to the father */
634 lua_pushstring(L, "simgrid.father"); /* "simgrid.father" */
635 lua_pushlightuserdata(L, father); /* "simgrid.father" father */
636 lua_rawset(L, LUA_REGISTRYINDEX);
639 /* create the table of visited tables from the father */
640 lua_pushstring(L, "simgrid.father_visited_tables");
641 /* "simgrid.father_visited_tables" */
642 lua_newtable(L); /* "simgrid.father_visited_tables" visited */
643 lua_rawset(L, LUA_REGISTRYINDEX);
646 /* create the table of my own visited tables */
647 /* TODO simgrid.father_visited_tables probably becomes useless */
648 lua_pushstring(L, "simgrid.visited_tables");
649 /* "simgrid.visited_tables" */
650 lua_newtable(L); /* "simgrid.visited_tables" visited */
651 lua_rawset(L, LUA_REGISTRYINDEX);
654 /* open the standard libs (theoretically, this is not necessary as they can
655 * be inherited like any global values, but without a proper support of
656 * closures, iterators like ipairs don't work). */
657 XBT_DEBUG("Metatable of globals and registry set, opening standard libraries now");
660 XBT_DEBUG("New state created");
666 static void *my_checkudata (lua_State *L, int ud, const char *tname) {
667 void *p = lua_touserdata(L, ud);
668 lua_getfield(L, LUA_REGISTRYINDEX, tname);
669 const void* correct_mt = lua_topointer(L, -1);
671 int has_mt = lua_getmetatable(L, ud);
672 const void* actual_mt = NULL;
673 if (has_mt) { actual_mt = lua_topointer(L, -1); lua_pop(L, 1); }
674 XBT_DEBUG("Checking the task's metatable: expected %p, found %p", correct_mt, actual_mt);
675 stack_dump("my_checkudata: ", L);
677 if (p == NULL || !lua_getmetatable(L, ud) || !lua_rawequal(L, -1, -2))
678 luaL_typerror(L, ud, tname);
685 * @brief Ensures that a userdata on the stack is a task
686 * and returns the pointer inside the userdata.
687 * @param L a Lua state
688 * @param index an index in the Lua stack
689 * @return the task at this index
691 static m_task_t checkTask(lua_State * L, int index)
694 luaL_checktype(L, index, LUA_TTABLE);
695 lua_getfield(L, index, "__simgrid_task");
697 pi = (m_task_t *) luaL_checkudata(L, lua_gettop(L), TASK_MODULE_NAME);
700 luaL_typerror(L, index, TASK_MODULE_NAME);
703 luaL_error(L, "null Task");
708 /* ********************************************************************************* */
709 /* wrapper functions */
710 /* ********************************************************************************* */
713 * A task is either something to compute somewhere, or something to exchange between two hosts (or both).
714 * It is defined by a computing amount and a message size.
723 * @brief Constructs a new task with the specified processing amount and amount
726 * @param name Task's name
728 * @param computeDuration A value of the processing amount (in flop) needed to process the task.
729 * If 0, then it cannot be executed with the execute() method.
730 * This value has to be >= 0.
732 * @param messageSize A value of amount of data (in bytes) needed to transfert this task.
733 * If 0, then it cannot be transfered with the get() and put() methods.
734 * This value has to be >= 0.
736 static int Task_new(lua_State * L)
738 XBT_DEBUG("Task new...");
739 const char *name = luaL_checkstring(L, 1);
740 int comp_size = luaL_checkint(L, 2);
741 int msg_size = luaL_checkint(L, 3);
742 m_task_t msg_task = MSG_task_create(name, comp_size, msg_size, NULL);
743 lua_newtable(L); /* create a table, put the userdata on top of it */
744 m_task_t *lua_task = (m_task_t *) lua_newuserdata(L, sizeof(m_task_t));
745 *lua_task = msg_task;
746 luaL_getmetatable(L, TASK_MODULE_NAME);
747 lua_setmetatable(L, -2);
748 lua_setfield(L, -2, "__simgrid_task"); /* put the userdata as field of the table */
749 /* remove the args from the stack */
756 static int Task_get_name(lua_State * L)
758 m_task_t tk = checkTask(L, -1);
759 lua_pushstring(L, MSG_task_get_name(tk));
763 static int Task_computation_duration(lua_State * L)
765 m_task_t tk = checkTask(L, -1);
766 lua_pushnumber(L, MSG_task_get_compute_duration(tk));
770 static int Task_execute(lua_State * L)
772 m_task_t tk = checkTask(L, -1);
773 int res = MSG_task_execute(tk);
774 lua_pushnumber(L, res);
778 static int Task_destroy(lua_State * L)
780 m_task_t tk = checkTask(L, -1);
781 int res = MSG_task_destroy(tk);
782 lua_pushnumber(L, res);
786 static int Task_send(lua_State * L)
788 //stack_dump("send ", L);
789 m_task_t tk = checkTask(L, 1);
790 const char *mailbox = luaL_checkstring(L, 2);
791 lua_pop(L, 1); // remove the string so that the task is on top of it
792 MSG_task_set_data(tk, L); // Copy my stack into the task, so that the receiver can copy the lua task directly
793 MSG_error_t res = MSG_task_send(tk, mailbox);
794 while (MSG_task_get_data(tk) != NULL) // Don't mess up with my stack: the receiver didn't copy the data yet
795 MSG_process_sleep(0); // yield
800 XBT_DEBUG("MSG_task_send failed : Timeout");
802 case MSG_TRANSFER_FAILURE:
803 XBT_DEBUG("MSG_task_send failed : Transfer Failure");
805 case MSG_HOST_FAILURE:
806 XBT_DEBUG("MSG_task_send failed : Host Failure ");
810 ("MSG_task_send failed : Unexpected error , please report this bug");
816 static int Task_recv_with_timeout(lua_State *L)
819 const char *mailbox = luaL_checkstring(L, -2);
820 int timeout = luaL_checknumber(L, -1);
821 MSG_error_t res = MSG_task_receive_with_timeout(&tk, mailbox, timeout);
824 lua_State *sender_stack = MSG_task_get_data(tk);
826 stack_dump("sender before moving data: ", sender_stack);
827 stack_dump("receiver before moving data: ", L);
829 move_value(sender_stack, L); // copy the data directly from sender's stack
831 stack_dump("sender after moving data: ", sender_stack);
832 stack_dump("receiver after moving data: ", L);
834 MSG_task_set_data(tk, NULL);
839 XBT_DEBUG("MSG_task_receive failed : Timeout");
841 case MSG_TRANSFER_FAILURE:
842 XBT_DEBUG("MSG_task_receive failed : Transfer Failure");
844 case MSG_HOST_FAILURE:
845 XBT_DEBUG("MSG_task_receive failed : Host Failure ");
848 XBT_ERROR("MSG_task_receive failed : Unexpected error , please report this bug");
856 static int Task_recv(lua_State * L)
858 lua_pushnumber(L, -1.0);
859 return Task_recv_with_timeout(L);
862 static const luaL_reg Task_methods[] = {
864 {"name", Task_get_name},
865 {"computation_duration", Task_computation_duration},
866 {"execute", Task_execute},
867 {"destroy", Task_destroy},
870 {"recv_timeout", Task_recv_with_timeout},
874 static int Task_gc(lua_State * L)
876 m_task_t tk = checkTask(L, -1);
878 MSG_task_destroy(tk);
882 static int Task_tostring(lua_State * L)
884 lua_pushfstring(L, "Task :%p", lua_touserdata(L, 1));
888 static const luaL_reg Task_meta[] = {
890 {"__tostring", Task_tostring},
897 static m_host_t checkHost(lua_State * L, int index)
900 luaL_checktype(L, index, LUA_TTABLE);
901 lua_getfield(L, index, "__simgrid_host");
902 pi = (m_host_t *) luaL_checkudata(L, lua_gettop(L), HOST_MODULE_NAME);
904 luaL_typerror(L, index, HOST_MODULE_NAME);
907 luaL_error(L, "null Host");
912 static int Host_get_by_name(lua_State * L)
914 const char *name = luaL_checkstring(L, 1);
915 XBT_DEBUG("Getting Host from name...");
916 m_host_t msg_host = MSG_get_host_by_name(name);
918 luaL_error(L, "null Host : MSG_get_host_by_name failed");
920 lua_newtable(L); /* create a table, put the userdata on top of it */
921 m_host_t *lua_host = (m_host_t *) lua_newuserdata(L, sizeof(m_host_t));
922 *lua_host = msg_host;
923 luaL_getmetatable(L, HOST_MODULE_NAME);
924 lua_setmetatable(L, -2);
925 lua_setfield(L, -2, "__simgrid_host"); /* put the userdata as field of the table */
926 /* remove the args from the stack */
931 static int Host_get_name(lua_State * L)
933 m_host_t ht = checkHost(L, -1);
934 lua_pushstring(L, MSG_host_get_name(ht));
938 static int Host_number(lua_State * L)
940 lua_pushnumber(L, MSG_get_host_number());
944 static int Host_at(lua_State * L)
946 int index = luaL_checkinteger(L, 1);
947 m_host_t host = MSG_get_host_table()[index - 1]; // lua indexing start by 1 (lua[1] <=> C[0])
948 lua_newtable(L); /* create a table, put the userdata on top of it */
949 m_host_t *lua_host = (m_host_t *) lua_newuserdata(L, sizeof(m_host_t));
951 luaL_getmetatable(L, HOST_MODULE_NAME);
952 lua_setmetatable(L, -2);
953 lua_setfield(L, -2, "__simgrid_host"); /* put the userdata as field of the table */
958 static int Host_self(lua_State * L)
960 m_host_t host = MSG_host_self();
962 m_host_t *lua_host =(m_host_t *)lua_newuserdata(L,sizeof(m_host_t));
964 luaL_getmetatable(L, HOST_MODULE_NAME);
965 lua_setmetatable(L, -2);
966 lua_setfield(L, -2, "__simgrid_host");
970 static int Host_get_property_value(lua_State * L)
972 m_host_t ht = checkHost(L, -2);
973 const char *prop = luaL_checkstring(L, -1);
974 lua_pushstring(L,MSG_host_get_property_value(ht,prop));
978 static int Host_sleep(lua_State *L)
980 int time = luaL_checknumber(L, -1);
981 MSG_process_sleep(time);
985 static int Host_destroy(lua_State *L)
987 m_host_t ht = checkHost(L, -1);
988 __MSG_host_destroy(ht);
992 /* ********************************************************************************* */
993 /* lua_stub_generator functions */
994 /* ********************************************************************************* */
996 xbt_dict_t process_function_set;
997 xbt_dynar_t process_list;
998 xbt_dict_t machine_set;
999 static s_process_t process;
1001 void s_process_free(void *process)
1003 s_process_t *p = (s_process_t *) process;
1005 for (i = 0; i < p->argc; i++)
1011 static int gras_add_process_function(lua_State * L)
1014 const char *process_host = luaL_checkstring(L, 1);
1015 const char *process_function = luaL_checkstring(L, 2);
1017 if (xbt_dict_is_empty(machine_set)
1018 || xbt_dict_is_empty(process_function_set)
1019 || xbt_dynar_is_empty(process_list)) {
1020 process_function_set = xbt_dict_new();
1021 process_list = xbt_dynar_new(sizeof(s_process_t), s_process_free);
1022 machine_set = xbt_dict_new();
1025 xbt_dict_set(machine_set, process_host, NULL, NULL);
1026 xbt_dict_set(process_function_set, process_function, NULL, NULL);
1029 process.argv = xbt_new(char *, 1);
1030 process.argv[0] = xbt_strdup(process_function);
1031 process.host = strdup(process_host);
1034 while (lua_next(L, 3) != 0) {
1035 arg = lua_tostring(L, -1);
1038 xbt_realloc(process.argv, (process.argc) * sizeof(char *));
1039 process.argv[(process.argc) - 1] = xbt_strdup(arg);
1041 XBT_DEBUG("index = %f , arg = %s \n", lua_tonumber(L, -2),
1042 lua_tostring(L, -1));
1046 //add to the process list
1047 xbt_dynar_push(process_list, &process);
1052 static int gras_generate(lua_State * L)
1054 const char *project_name = luaL_checkstring(L, 1);
1055 generate_sim(project_name);
1056 generate_rl(project_name);
1057 generate_makefile_local(project_name);
1061 /***********************************
1063 **********************************/
1064 static int trace_start(lua_State *L)
1072 static int trace_category(lua_State * L)
1075 TRACE_category(luaL_checkstring(L, 1));
1080 static int trace_set_task_category(lua_State *L)
1083 TRACE_msg_set_task_category(checkTask(L, -2), luaL_checkstring(L, -1));
1088 static int trace_end(lua_State *L)
1096 // *********** Register Methods ******************************************* //
1101 static const luaL_reg Host_methods[] = {
1102 {"getByName", Host_get_by_name},
1103 {"name", Host_get_name},
1104 {"number", Host_number},
1106 {"self", Host_self},
1107 {"getPropValue", Host_get_property_value},
1108 {"sleep", Host_sleep},
1109 {"destroy", Host_destroy},
1110 // Bypass XML Methods
1111 {"setFunction", console_set_function},
1112 {"setProperty", console_host_set_property},
1116 static int Host_gc(lua_State * L)
1118 m_host_t ht = checkHost(L, -1);
1124 static int Host_tostring(lua_State * L)
1126 lua_pushfstring(L, "Host :%p", lua_touserdata(L, 1));
1130 static const luaL_reg Host_meta[] = {
1132 {"__tostring", Host_tostring},
1139 static const luaL_reg AS_methods[] = {
1140 {"new", console_add_AS},
1141 {"addHost", console_add_host},
1142 {"addLink", console_add_link},
1143 {"addRoute", console_add_route},
1150 static const luaL_reg Trace_methods[] = {
1151 {"start", trace_start},
1152 {"category", trace_category},
1153 {"setTaskCategory", trace_set_task_category},
1154 {"finish", trace_end},
1159 * Environment related
1163 * @brief Runs a Lua function as a new simulated process.
1164 * @param argc number of arguments of the function
1165 * @param argv name of the Lua function and array of its arguments
1166 * @return result of the function
1168 static int run_lua_code(int argc, char **argv)
1170 XBT_DEBUG("Run lua code %s", argv[0]);
1172 lua_State *L = clone_lua_state(lua_maestro_state);
1175 /* start the function */
1176 lua_getglobal(L, argv[0]);
1177 xbt_assert(lua_isfunction(L, -1),
1178 "The lua function %s does not seem to exist", argv[0]);
1180 /* push arguments onto the stack */
1182 for (i = 1; i < argc; i++)
1183 lua_pushstring(L, argv[i]);
1185 /* call the function */
1187 err = lua_pcall(L, argc - 1, 1, 0);
1188 xbt_assert(err == 0, "error running function `%s': %s", argv[0],
1189 lua_tostring(L, -1));
1191 /* retrieve result */
1192 if (lua_isnumber(L, -1)) {
1193 res = lua_tonumber(L, -1);
1194 lua_pop(L, 1); /* pop returned value */
1197 XBT_DEBUG("Execution of Lua code %s is over", (argv ? argv[0] : "(null)"));
1202 static int launch_application(lua_State * L)
1204 const char *file = luaL_checkstring(L, 1);
1205 MSG_function_register_default(run_lua_code);
1206 MSG_launch_application(file);
1210 static int create_environment(lua_State * L)
1212 const char *file = luaL_checkstring(L, 1);
1213 XBT_DEBUG("Loading environment file %s", file);
1214 MSG_create_environment(file);
1218 static int debug(lua_State * L)
1220 const char *str = luaL_checkstring(L, 1);
1221 XBT_DEBUG("%s", str);
1225 static int info(lua_State * L)
1227 const char *str = luaL_checkstring(L, 1);
1228 XBT_INFO("%s", str);
1232 static int run(lua_State * L)
1238 static int clean(lua_State * L)
1245 * Bypass XML Parser (lua console)
1249 * Register platform for MSG
1251 static int msg_register_platform(lua_State * L)
1253 /* Tell Simgrid we dont wanna use its parser */
1254 surf_parse = console_parse_platform;
1255 surf_parse_reset_callbacks();
1256 surf_config_models_setup(NULL);
1257 MSG_create_environment(NULL);
1262 * Register platform for Simdag
1265 static int sd_register_platform(lua_State * L)
1267 surf_parse = console_parse_platform_wsL07;
1268 surf_parse_reset_callbacks();
1269 surf_config_models_setup(NULL);
1270 SD_create_environment(NULL);
1275 * Register platform for gras
1277 static int gras_register_platform(lua_State * L)
1279 /* Tell Simgrid we dont wanna use surf parser */
1280 surf_parse = console_parse_platform;
1281 surf_parse_reset_callbacks();
1282 surf_config_models_setup(NULL);
1283 gras_create_environment(NULL);
1288 * Register applicaiton for MSG
1290 static int msg_register_application(lua_State * L)
1292 MSG_function_register_default(run_lua_code);
1293 surf_parse = console_parse_application;
1294 MSG_launch_application(NULL);
1299 * Register application for gras
1301 static int gras_register_application(lua_State * L)
1303 gras_function_register_default(run_lua_code);
1304 surf_parse = console_parse_application;
1305 gras_launch_application(NULL);
1309 static const luaL_Reg simgrid_funcs[] = {
1310 {"create_environment", create_environment},
1311 {"launch_application", launch_application},
1317 {"platform", create_environment},
1318 {"application", launch_application},
1319 /* methods to bypass XML parser */
1320 {"msg_register_platform", msg_register_platform},
1321 {"sd_register_platform", sd_register_platform},
1322 {"msg_register_application", msg_register_application},
1323 {"gras_register_platform", gras_register_platform},
1324 {"gras_register_application", gras_register_application},
1325 /* gras sub generator method */
1326 {"gras_set_process_function", gras_add_process_function},
1327 {"gras_generate", gras_generate},
1331 /* ********************************************************************************* */
1332 /* module management functions */
1333 /* ********************************************************************************* */
1335 #define LUA_MAX_ARGS_COUNT 10 /* maximum amount of arguments we can get from lua on command line */
1337 int luaopen_simgrid(lua_State *L); // Fuck gcc: we don't need that prototype
1340 * This function is called automatically by the Lua interpreter when some Lua code requires
1341 * the "simgrid" module.
1342 * @param L the Lua state
1344 int luaopen_simgrid(lua_State *L)
1346 XBT_DEBUG("luaopen_simgrid *****");
1348 /* Get the command line arguments from the lua interpreter */
1349 char **argv = malloc(sizeof(char *) * LUA_MAX_ARGS_COUNT);
1351 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? */
1353 lua_getglobal(L, "arg");
1354 /* if arg is a null value, it means we use lua only as a script to init platform
1355 * else it should be a table and then take arg in consideration
1357 if (lua_istable(L, -1)) {
1361 lua_pushinteger(L, argc - 2);
1362 lua_gettable(L, -2);
1363 if (lua_isnil(L, -1)) {
1366 xbt_assert(lua_isstring(L, -1),
1367 "argv[%d] got from lua is no string", argc - 1);
1368 xbt_assert(argc < LUA_MAX_ARGS_COUNT,
1369 "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",
1370 __FILE__, LUA_MAX_ARGS_COUNT - 1);
1371 argv[argc - 1] = (char *) luaL_checkstring(L, -1);
1373 XBT_DEBUG("Got command line argument %s from lua", argv[argc - 1]);
1376 argv[argc--] = NULL;
1378 /* Initialize the MSG core */
1379 MSG_global_init(&argc, argv);
1380 XBT_DEBUG("Still %d arguments on command line", argc); // FIXME: update the lua's arg table to reflect the changes from SimGrid
1383 /* Keep the context mechanism informed of our lua world today */
1384 lua_maestro_state = L;
1386 /* initialize access to my tables by children Lua states */
1388 lua_setfield(L, LUA_REGISTRYINDEX, "simgrid.visited_tables");
1390 register_c_functions(L);
1396 * Makes the appropriate Simgrid functions available to the Lua world.
1397 * @param L a Lua world
1399 void register_c_functions(lua_State *L) {
1401 /* register the core C functions to lua */
1402 luaL_register(L, "simgrid", simgrid_funcs);
1404 /* register the task methods to lua */
1405 luaL_openlib(L, TASK_MODULE_NAME, Task_methods, 0); // create methods table, add it to the globals
1406 luaL_newmetatable(L, TASK_MODULE_NAME); // create metatable for Task, add it to the Lua registry
1407 luaL_openlib(L, 0, Task_meta, 0); // fill metatable
1408 lua_pushliteral(L, "__index");
1409 lua_pushvalue(L, -3); // dup methods table
1410 lua_rawset(L, -3); // matatable.__index = methods
1411 lua_pushliteral(L, "__metatable");
1412 lua_pushvalue(L, -3); // dup methods table
1413 lua_rawset(L, -3); // hide metatable:metatable.__metatable = methods
1414 lua_pop(L, 1); // drop metatable
1416 /* register the hosts methods to lua */
1417 luaL_openlib(L, HOST_MODULE_NAME, Host_methods, 0);
1418 luaL_newmetatable(L, HOST_MODULE_NAME);
1419 luaL_openlib(L, 0, Host_meta, 0);
1420 lua_pushliteral(L, "__index");
1421 lua_pushvalue(L, -3);
1423 lua_pushliteral(L, "__metatable");
1424 lua_pushvalue(L, -3);
1428 /* register the links methods to lua */
1429 luaL_openlib(L, AS_MODULE_NAME, AS_methods, 0);
1430 luaL_newmetatable(L, AS_MODULE_NAME);
1433 /* register the Tracing functions to lua */
1434 luaL_openlib(L, TRACE_MODULE_NAME, Trace_methods, 0);
1435 luaL_newmetatable(L, TRACE_MODULE_NAME);