Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
0b12f49afc4614c62de2fce6f82f41272a044f39
[simgrid.git] / src / simix / simcalls.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 # Copyright (c) 2014. The SimGrid Team.
5 # All rights reserved.
6
7 # This program is free software; you can redistribute it and/or modify it
8 # under the terms of the license (GNU LGPL) which comes with this package.
9
10 import re, glob
11
12 types = [('TCHAR', 'char', 'c')
13         ,('TSTRING', 'const char*', 'cc')
14         ,('TINT', 'int', 'i')
15         ,('TLONG', 'long', 'l')
16         ,('TUCHAR', 'unsigned char', 'uc')
17         ,('TUSHORT', 'unsigned short', 'us')
18         ,('TUINT', 'unsigned int', 'ui')
19         ,('TULONG', 'unsigned long', 'ul')
20         ,('TFLOAT', 'float', 'f')
21         ,('TDOUBLE', 'double', 'd')
22         ,('TDPTR', 'void*', 'dp')
23         ,('TFPTR', 'FPtr', 'fp')
24         ,('TCPTR', 'const void*', 'cp')
25         ,('TSIZE', 'size_t', 'sz')
26         ,('TSGSIZE', 'sg_size_t', 'sgsz')
27         ,('TSGOFF', 'sg_offset_t', 'sgoff')
28         ,('TVOID', 'void', '')
29         ,('TDSPEC', 'void*', 'dp')
30         ,('TFSPEC', 'FPtr', 'fp')]
31
32 class Arg(object):
33   simcall_types = {k:v for _,k,v in types}
34   def __init__(self, name, type, casted=None):
35     self.name = name 
36     self.type = type
37     self.casted = casted
38     assert type in self.simcall_types, '%s not in (%s)'%(type, ', '.join(self.simcall_types.keys()))
39
40   def field(self):
41     return self.simcall_types[self.type]
42
43   def ret(self):
44     return '%s'%self.casted if self.casted else self.type
45
46   def cast(self):
47     return '(%s)'%self.casted if self.casted else '' 
48
49 class Simcall(object):
50   simcalls_BODY = None
51   simcalls_PRE = None
52   def __init__(self, name, res, args, has_answer=True):
53     self.name = name
54     self.res = res
55     self.args = args
56     self.has_answer = has_answer
57
58   def check(self):
59     # smx_user.c  simcall_BODY_
60     # smx_*.c void SIMIX_pre_host_on(smx_simcall_t simcall, smx_host_t h)
61     self.check_body()
62     self.check_pre()
63
64   def check_body(self):
65     if self.simcalls_BODY is None:
66       f = open('smx_user.c')
67       self.simcalls_BODY = set(re.findall('simcall_BODY_(.*?)\(', f.read()))
68       f.close()
69     if self.name not in self.simcalls_BODY:
70       print '# ERROR: No function calling simcall_BODY_%s'%self.name
71       print '# Add something like this to smx_user.c:'
72       print '''%s simcall_%s(%s)
73 {
74   return simcall_BODY_%s(%s);
75 }\n'''%(self.res.ret()
76      ,self.name
77      ,', '.join('%s %s'%(arg.ret(), arg.name)
78                   for arg in self.args)
79      ,self.name
80      ,', '.join(arg.name for arg in self.args))
81       return False
82     return True
83
84   def check_pre(self):
85     if self.simcalls_PRE is None:
86       self.simcalls_PRE = set()
87       for fn in glob.glob('smx_*') + glob.glob('../mc/*'):
88         f = open(fn)
89         self.simcalls_PRE |= set(re.findall('SIMIX_pre_(.*?)\(', f.read()))
90         f.close()
91     if self.name not in self.simcalls_PRE:
92       print '# ERROR: No function called SIMIX_pre_%s'%self.name
93       print '# Add something like this to smx_.*.c:'
94       print '''%s SIMIX_pre_%s(smx_simcall_t simcall%s)
95 {
96   // Your code handling the simcall
97 }\n'''%(self.res.ret()
98        ,self.name
99        ,''.join(', %s %s'%(arg.ret(), arg.name)
100                   for arg in self.args))
101       return False
102     return True
103
104   def enum(self):
105     return 'SIMCALL_%s,'%(self.name.upper())
106
107   def string(self):
108     return '[SIMCALL_%s] = "SIMCALL_%s",'%(self.name.upper(), self.name.upper())        
109   
110   def result_getter_setter(self):
111     return '%s\n%s'%(self.result_getter(), self.result_setter())
112   
113   def result_getter(self):
114     return '' if self.res.type == 'void' else '''static inline %s simcall_%s__get__result(smx_simcall_t simcall){
115   return %s simcall->result.%s;
116 }'''%(self.res.ret(), self.name, self.res.cast(), self.res.field())
117
118   def result_setter(self):
119     return '' if self.res.type == 'void' else '''static inline void simcall_%s__set__result(smx_simcall_t simcall, %s result){
120     simcall->result.%s = result;
121 }'''%(self.name, self.res.type, self.res.field())
122
123   def args_getter_setter(self):
124     res = []
125     for i in range(len(self.args)):
126       res.append(self.arg_getter(i))
127       res.append(self.arg_setter(i))
128     return '\n'.join(res)
129
130   def arg_getter(self, i):
131     arg = self.args[i]
132     return '''static inline %s simcall_%s__get__%s(smx_simcall_t simcall){
133   return %s simcall->args[%i].%s;
134 }'''%(arg.ret(), self.name, arg.name, arg.cast(), i, arg.field())
135
136   def arg_setter(self, i):
137     arg = self.args[i]
138     return '''static inline void simcall_%s__set__%s(smx_simcall_t simcall, %s arg){
139     simcall->args[%i].%s = arg;
140 }'''%(self.name, arg.name, arg.type, i, arg.field())
141
142   def case(self):
143     return '''case SIMCALL_%s:
144       %sSIMIX_pre_%s(simcall %s);
145       %sbreak;  
146 '''%(self.name.upper(), 
147      'simcall->result.%s = '%self.res.field() if self.res.type != 'void' and self.has_answer else ' ',
148      self.name,
149      ''.join(', %s simcall->args[%d].%s'%(arg.cast(), i, arg.field()) 
150              for i, arg in enumerate(self.args)),
151      'SIMIX_simcall_answer(simcall);\n      ' if self.has_answer else ' ')
152
153   def body(self):
154     return '''  inline static %s simcall_BODY_%s(%s) {
155     smx_process_t self = SIMIX_process_self();
156
157     /* Go to that function to follow the code flow through the simcall barrier */
158     if (0) SIMIX_pre_%s(%s);
159     /* end of the guide intended to the poor programmer wanting to go from MSG to Surf */
160
161     self->simcall.call = SIMCALL_%s;
162     memset(&self->simcall.result, 0, sizeof(self->simcall.result));
163     memset(self->simcall.args, 0, sizeof(self->simcall.args));
164 %s
165     if (self != simix_global->maestro_process) {
166       XBT_DEBUG("Yield process '%%s' on simcall %%s (%%d)", self->name,
167                 SIMIX_simcall_name(self->simcall.call), (int)self->simcall.call);
168       SIMIX_process_yield(self);
169     } else {
170       SIMIX_simcall_enter(&self->simcall, 0);
171     }    
172     %s
173   }'''%(self.res.ret()
174        ,self.name
175        ,', '.join('%s %s'%(arg.ret(), arg.name)
176                   for arg in self.args)
177        ,self.name
178        ,', '.join(["&self->simcall"]+ [arg.name for arg in self.args])
179        ,self.name.upper()
180        ,'\n'.join('    self->simcall.args[%d].%s = (%s) %s;'%(i, arg.field(), arg.type, arg.name)
181                   for i, arg in enumerate(self.args))
182        ,'' if self.res.type == 'void' else 'return self->simcall.result.%s;'%self.res.field())
183
184 def parse(fn):
185   res = []
186   resdi = None
187   resd = {}
188   for line in open(fn).read().split('\n'):
189     if line.startswith('##'):
190       resdi = []
191       resd[re.search(r'## *(.*)', line).group(1)] = resdi
192     if line.startswith('#') or not line:
193       continue
194     match = re.match(r'(\S*?) *(\S*?) *\((.*?)(?:, *(.*?))?\) *(.*)', line)
195     assert match, line
196     name, ans, rest, resc, args = match.groups()
197     sargs = []
198     for n,t,c in re.findall(r'\((.*?), *(.*?)(?:, *(.*?))?\)', args):
199       sargs.append(Arg(n,t,c))
200     sim = Simcall(name, Arg('result', rest, resc), sargs, ans == 'True')
201     if resdi is None:
202       res.append(sim)
203     else:
204       resdi.append(sim)
205   return res, resd
206
207 def write(fn, func, scs, scd,pre="",post=""):
208   f = open(fn, 'w')
209   f.write('/*********************************************\n')
210   f.write(' * File Generated by src/simix/simcalls.py   *\n')
211   f.write(' *                from src/simix/simcalls.in *\n')
212   f.write(' * Do not modify this file, add new simcalls *\n')
213   f.write(' * in src/simix/simcalls.in                  *\n')  
214   f.write(' *********************************************/\n\n')
215   f.write(pre)
216   f.write('\n'.join(func(sc) for sc in scs))
217   for k, v in scd.items():
218     f.write('\n#ifdef %s\n%s\n#endif\n'%(k, '\n'.join(func(sc) for sc in v)))
219   f.write(post)
220   f.close()
221
222 if __name__=='__main__':
223   import sys
224   simcalls, simcalls_dict = parse('simcalls.in')
225   
226   ok = True
227   ok &= all(map(Simcall.check, simcalls))
228   for k,v in simcalls_dict.items():
229     ok &= all(map(Simcall.check, v))
230   #if not ok:
231   #  sys.exit(1)
232
233   write('simcalls_generated_enum.h', Simcall.enum, simcalls, simcalls_dict,"""
234 /**
235  * @brief All possible simcalls.
236  */
237 typedef enum {
238 SIMCALL_NONE,
239   ""","""
240 SIMCALL_NEW_API_INIT,
241 NUM_SIMCALLS
242 } e_smx_simcall_t;
243   """)
244   
245   write('simcalls_generated_string.c', Simcall.string, simcalls, simcalls_dict)
246   write('simcalls_generated_res_getter_setter.h', Simcall.result_getter_setter, simcalls, simcalls_dict)
247   write('simcalls_generated_args_getter_setter.h', Simcall.args_getter_setter, simcalls, simcalls_dict)
248   
249   
250   write('smx_simcall_enter.c', Simcall.case, simcalls, simcalls_dict,"""
251
252 #include "smx_private.h"
253 #ifdef HAVE_MC
254 #include "mc/mc_private.h"
255 #endif
256
257 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(simix_smurf);
258
259 /**
260  * @brief unpack the simcall and activate the handler in kernel mode
261  */
262 void SIMIX_simcall_enter(smx_simcall_t simcall, int value)
263 {
264   XBT_DEBUG("Handling simcall %p: %s", simcall, SIMIX_simcall_name(simcall->call));
265   SIMCALL_SET_MC_VALUE(simcall, value);
266   if (simcall->issuer->context->iwannadie && simcall->call != SIMCALL_PROCESS_CLEANUP)
267     return;
268   switch (simcall->call) {
269   ""","""
270     case NUM_SIMCALLS:
271       break;
272     case SIMCALL_NONE:
273       THROWF(arg_error,0,"Asked to do the noop syscall on %s@%s",
274           SIMIX_process_get_name(simcall->issuer),
275           SIMIX_host_get_name(SIMIX_process_get_host(simcall->issuer))
276           );
277       break;
278
279     /* ****************************************************************************************** */
280     /* TUTORIAL: New API                                                                        */
281     /* ****************************************************************************************** */
282     case SIMCALL_NEW_API_INIT:
283       SIMIX_pre_new_api_fct(simcall);
284       break;
285   }
286 }
287   """)
288   
289   
290   write('simcalls_generated_body.c', Simcall.body, simcalls, simcalls_dict)