Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Changes way to find lualib.h and lauxlib.h.
[simgrid.git] / src / bindings / lua / simgrid_lua.c
1 /* SimGrid Lua bindings                                                     */
2
3 /* Copyright (c) 2010, the SimGrid team. All right reserved.                */
4
5 /* This program is free software; you can redistribute it and/or modify it
6  * under the terms of the license (GNU LGPL) which comes with this package. */
7
8 #include <stdio.h>
9 #include <lauxlib.h>
10 #include <lualib.h>
11
12 #include "msg/msg.h"
13 #include "xbt.h"
14
15 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(lua,bindings,"Lua Bindings");
16
17 #define TASK_MODULE_NAME "simgrid.Task"
18
19 /* ********************************************************************************* */
20 /*                            helper functions                                       */
21 /* ********************************************************************************* */
22
23 static void stackDump (lua_State *L) {
24   char buff[2048];
25   char *p=buff;
26   int i;
27   int top = lua_gettop(L);
28   void *ptr;
29   fflush(stdout);
30   p+=sprintf(p,"STACK(top=%d): ",top);
31   for (i = 1; i <= top; i++) {  /* repeat for each level */
32     int t = lua_type(L, i);
33     switch (t) {
34
35     case LUA_TSTRING:  /* strings */
36       p+=sprintf(p,"`%s'", lua_tostring(L, i));
37       break;
38
39     case LUA_TBOOLEAN:  /* booleans */
40       p+=sprintf(p,lua_toboolean(L, i) ? "true" : "false");
41       break;
42
43     case LUA_TNUMBER:  /* numbers */
44       p+=sprintf(p,"%g", lua_tonumber(L, i));
45       break;
46
47     default:  /* other values */
48       if ((ptr = luaL_checkudata(L,i,TASK_MODULE_NAME))) {
49         p+=sprintf(p,"task");
50       } else {
51         p+=printf(p,"%s", lua_typename(L, t));
52       }
53       break;
54
55     }
56     p+=sprintf(p,"  ");  /* put a separator */
57   }
58   DEBUG1("%s",buff);
59 }
60
61 /** @brief ensures that a userdata on the stack is a task and returns the pointer inside the userdata */
62 static m_task_t checkTask (lua_State *L,int index) {
63   m_task_t *pi,tk;
64   luaL_checktype(L,index,LUA_TUSERDATA);
65   pi = (m_task_t*)luaL_checkudata(L,index,TASK_MODULE_NAME);
66   if(pi == NULL)
67     luaL_typerror(L,index,TASK_MODULE_NAME);
68   tk = *pi;
69   if(!tk)
70     luaL_error(L,"null Task");
71   return  tk;
72 }
73
74 /** @brief leaves a new userdata on top of the stack, sets its metatable, and sets the Task pointer inside the userdata */
75 static m_task_t *pushTask (lua_State *L,m_task_t tk) {
76   m_task_t *pi = (m_task_t*)lua_newuserdata(L,sizeof(m_task_t));
77   *pi=tk;
78   luaL_getmetatable(L,TASK_MODULE_NAME);
79   lua_setmetatable(L,-2);
80   return pi;
81
82 }
83
84
85 /* ********************************************************************************* */
86 /*                           wrapper functions                                       */
87 /* ********************************************************************************* */
88
89 static int Task_new(lua_State* L) {
90   const char *name=luaL_checkstring(L,1);
91   int comp_size = luaL_checkint(L,2);
92   int msg_size = luaL_checkint(L,3);
93   // FIXME: data shouldn't be NULL I guess
94   pushTask(L,MSG_task_create(name,comp_size,msg_size,NULL));
95   DEBUG0("Created task");
96   return 1;
97 }
98
99 static int Task_get_name(lua_State *L) {
100   m_task_t tk = checkTask(L,1);
101   lua_pushstring(L,MSG_task_get_name(tk));
102   return 1;
103 }
104
105 static int Task_computation_duration(lua_State *L){
106   m_task_t tk = checkTask(L,1);
107   lua_pushnumber(L,MSG_task_get_compute_duration (tk));
108   return 1;
109 }
110
111 static int Task_execute(lua_State *L){
112   m_task_t tk = checkTask(L,1);
113   int res = MSG_task_execute(tk);
114   lua_pushnumber(L,res);
115   return 1;
116 }
117
118 static int Task_destroy(lua_State *L) {
119   m_task_t tk = checkTask(L,1);
120   int res = MSG_task_destroy(tk);
121   lua_pushnumber(L,res);
122   return 1;
123 }
124 static int Task_send(lua_State *L)  {
125   m_task_t tk = checkTask(L,1);
126   const char *mailbox = luaL_checkstring(L,2);
127   int res = MSG_task_send(tk,mailbox);
128   res++;//FIXME: check it instead of avoiding the warning
129   return 0;
130 }
131 static int Task_recv(lua_State *L)  {
132   m_task_t tk = NULL;
133   const char *mailbox = luaL_checkstring(L,1);
134   int res = MSG_task_receive(&tk,mailbox);
135   MSG_task_ref(tk); //FIXME: kill it once a ctask cannot be in more than one luatask anymore
136   res++;//FIXME: check it instead of avoiding the warning
137   DEBUG1("Task Name : >>>%s",MSG_task_get_name(tk));
138   pushTask(L,tk);
139   return 1;
140 }
141
142 static const luaL_reg Task_methods[] = {
143     {"new",   Task_new},
144     {"name",  Task_get_name},
145     {"computation_duration",  Task_computation_duration},
146     {"execute", Task_execute},
147     {"destroy", Task_destroy},
148     {"send",    Task_send},
149     {"recv",    Task_recv},
150     {0,0}
151 };
152 static int Task_gc(lua_State *L) {
153   m_task_t tk=checkTask(L,1);
154   if (tk) MSG_task_destroy(tk);
155   //printf("GoodBye Task(%p)\n",lua_touserdata(L,1));
156   return 0;
157 }
158
159 static int Task_tostring(lua_State *L) {
160   lua_pushfstring(L, "Task :%p",lua_touserdata(L,1));
161   return 1;
162 }
163
164
165 static const luaL_reg Task_meta[] = {
166     {"__gc",  Task_gc},
167     {"__tostring",  Task_tostring},
168     {0,0}
169 };
170
171 /*
172  * Environment related
173  */
174 extern lua_State *simgrid_lua_state;
175
176 static int run_lua_code(int argc,char **argv) {
177   DEBUG1("Run lua code %s",argv[0]);
178 //  fprintf(stderr,"Run lua code %s\n", (argv ? argv[0] : "(null)"));
179   lua_State *L = lua_newthread(simgrid_lua_state);
180   int ref = luaL_ref(simgrid_lua_state, LUA_REGISTRYINDEX); // protect the thread from being garbage collected
181   int res = 1;
182
183   /* Start the co-routine */
184   lua_getglobal(L,argv[0]);
185   xbt_assert1(lua_isfunction(L,-1),
186       "The lua function %s does not seem to exist",argv[0]);
187
188   // push arguments onto the stack
189   int i;
190   for(i=1;i<argc;i++)
191     lua_pushstring(L,argv[i]);
192
193   // Call the function (in resume)
194   xbt_assert2(lua_pcall(L, argc-1, 1, 0) == 0,
195     "error running function `%s': %s",argv[0], lua_tostring(L, -1));
196
197   /* retrieve result */
198   if (lua_isnumber(L, -1)) {
199     res = lua_tonumber(L, -1);
200     lua_pop(L, 1);  /* pop returned value */
201   }
202
203   // cleanups
204   luaL_unref(simgrid_lua_state,LUA_REGISTRYINDEX,ref );
205   DEBUG1("Execution of lua code %s is over", (argv ? argv[0] : "(null)"));
206   return res;
207 }
208 static int launch_application(lua_State *L) {
209   const char * file = luaL_checkstring(L,1);
210   MSG_function_register_default(run_lua_code);
211   MSG_launch_application(file);
212   return 0;
213 }
214 #include "simix/simix.h" //FIXME: KILLME when debugging on simix internals become useless
215 static int create_environment(lua_State *L) {
216   const char *file = luaL_checkstring(L,1);
217   DEBUG1("Loading environment file %s",file);
218   MSG_create_environment(file);
219   smx_host_t *hosts = SIMIX_host_get_table();
220   int i;
221   for (i=0;i<SIMIX_host_get_number();i++) {
222     DEBUG1("We have an host %s", SIMIX_host_get_name(hosts[i]));
223   }
224
225   return 0;
226 }
227 static int debug(lua_State *L) {
228   const char *str = luaL_checkstring(L,1);
229   DEBUG1("%s",str);
230   return 0;
231 }
232 static int info(lua_State *L) {
233   const char *str = luaL_checkstring(L,1);
234   INFO1("%s",str);
235   return 0;
236 }
237 static int run(lua_State *L) {
238   MSG_main();
239   return 0;
240 }
241 static int clean(lua_State *L) {
242   MSG_clean();
243   return 0;
244 }
245 static const luaL_Reg simgrid_funcs[] = {
246     { "create_environment", create_environment},
247     { "launch_application", launch_application},
248     { "debug", debug},
249     { "info", info},
250     { "run", run},
251     { "clean", clean},
252     /* short names */
253     { "platform", create_environment},
254     { "application", launch_application},
255     { NULL, NULL }
256 };
257
258 /* ********************************************************************************* */
259 /*                       module management functions                                 */
260 /* ********************************************************************************* */
261
262 extern const char*xbt_ctx_factory_to_use; /*Hack: let msg load directly the right factory */
263
264 #define LUA_MAX_ARGS_COUNT 10 /* maximum amount of arguments we can get from lua on command line */
265
266 int luaopen_simgrid(lua_State* L); // Fuck gcc: we don't need that prototype
267 int luaopen_simgrid(lua_State* L) {
268   //xbt_ctx_factory_to_use = "lua";
269
270   char **argv=malloc(sizeof(char*)*LUA_MAX_ARGS_COUNT);
271   int argc=1;
272   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? */
273   /* Get the command line arguments from the lua interpreter */
274   lua_getglobal(L,"arg");
275   xbt_assert1(lua_istable(L,-1),"arg parameter is not a table but a %s",lua_typename(L,-1));
276   int done=0;
277   while (!done) {
278     argc++;
279     lua_pushinteger(L,argc-2);
280     lua_gettable(L,-2);
281     if (lua_isnil(L,-1)) {
282       done = 1;
283     } else {
284       xbt_assert1(lua_isstring(L,-1),"argv[%d] got from lua is no string",argc-1);
285       xbt_assert2(argc<LUA_MAX_ARGS_COUNT,
286            "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",
287            __FILE__,LUA_MAX_ARGS_COUNT-1);
288       argv[argc-1] = (char*)luaL_checkstring(L,-1);
289       lua_pop(L,1);
290       DEBUG1("Got command line argument %s from lua",argv[argc-1]);
291     }
292   }
293   argv[argc--]=NULL;
294
295   /* Initialize the MSG core */
296   MSG_global_init(&argc,argv);
297   DEBUG1("Still %d arguments on command line",argc); // FIXME: update the lua's arg table to reflect the changes from SimGrid
298
299   /* register the core C functions to lua */
300   luaL_register(L, "simgrid", simgrid_funcs);
301   /* register the tasks to lua */
302   luaL_openlib(L,TASK_MODULE_NAME,Task_methods,0); //create methods table,add it to the globals
303   luaL_newmetatable(L,TASK_MODULE_NAME); //create metatable for Task,add it to the Lua registry
304   luaL_openlib(L,0,Task_meta,0);// fill metatable
305   lua_pushliteral(L,"__index");
306   lua_pushvalue(L,-3);  //dup methods table
307   lua_rawset(L,-3); //matatable.__index = methods
308   lua_pushliteral(L,"__metatable");
309   lua_pushvalue(L,-3);  //dup methods table
310   lua_rawset(L,-3); //hide metatable:metatable.__metatable = methods
311   lua_pop(L,1);   //drop metatable
312
313   /* Keep the context mechanism informed of our lua world today */
314   simgrid_lua_state = L;
315
316   return 1;
317 }