Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Adding test for SURF concurrency feature
[simgrid.git] / src / simix / simcalls.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 # Copyright (c) 2014-2015. The SimGrid Team. 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
9 import re, glob
10
11 types = [('TCHAR', 'char', 'c')
12         ,('TSTRING', 'const char*', 'cc')
13         ,('TINT', 'int', 'i')
14         ,('TLONG', 'long', 'l')
15         ,('TUCHAR', 'unsigned char', 'uc')
16         ,('TUSHORT', 'unsigned short', 'us')
17         ,('TUINT', 'unsigned int', 'ui')
18         ,('TULONG', 'unsigned long', 'ul')
19         ,('TFLOAT', 'float', 'f')
20         ,('TDOUBLE', 'double', 'd')
21         ,('TDPTR', 'void*', 'dp')
22         ,('TFPTR', 'FPtr', 'fp')
23         ,('TCPTR', 'const void*', 'cp')
24         ,('TSIZE', 'size_t', 'sz')
25         ,('TSGSIZE', 'sg_size_t', 'sgsz')
26         ,('TSGOFF', 'sg_offset_t', 'sgoff')
27         ,('TVOID', 'void', '')
28         ,('TDSPEC', 'void*', 'dp')
29         ,('TFSPEC', 'FPtr', 'fp')]
30
31 class Arg(object):
32   simcall_types = {k:v for _,k,v in types}
33   def __init__(self, name, type, casted=None):
34     self.name = name 
35     self.type = type
36     self.casted = casted
37     assert type in self.simcall_types, '%s not in (%s)'%(type, ', '.join(self.simcall_types.keys()))
38
39   def field(self):
40     return self.simcall_types[self.type]
41
42   def rettype(self):
43     return '%s'%self.casted if self.casted else self.type
44
45   def cast(self):
46     return '(%s)'%self.casted if self.casted else '' 
47
48 class Simcall(object):
49   simcalls_BODY = None
50   simcalls_PRE = None
51   def __init__(self, name, handler, res, args, call_kind):
52     self.name = name
53     self.res = res
54     self.args = args
55     self.need_handler = handler
56     self.call_kind = call_kind
57
58   def check(self):
59       # libsmx.c  simcall_BODY_
60       if self.simcalls_BODY is None:
61           f = open('libsmx.cpp')
62           self.simcalls_BODY = set(re.findall('simcall_BODY_(.*?)\(', f.read()))
63           f.close()
64       if self.name not in self.simcalls_BODY:
65           print '# ERROR: No function calling simcall_BODY_%s'%self.name
66           print '# Add something like this to libsmx.c:'
67           print '%s simcall_%s(%s) {'%(self.res.rettype() ,self.name ,', '.join('%s %s'%(arg.rettype(), arg.name) for arg in self.args))
68           print '  return simcall_BODY_%s(%s);'%(self.name)
69           print '}'
70           return False
71       
72       # smx_*.c void simcall_HANDLER_host_on(smx_simcall_t simcall, smx_host_t h)
73       if self.simcalls_PRE is None:
74         self.simcalls_PRE = set()
75         for fn in glob.glob('smx_*') + glob.glob('../mc/*'):
76             f = open(fn)
77             self.simcalls_PRE |= set(re.findall('simcall_HANDLER_(.*?)\(', f.read()))
78             f.close()
79       if self.need_handler:
80           if (self.name not in self.simcalls_PRE):
81               print '# ERROR: No function called simcall_HANDLER_%s'%self.name
82               print '# Add something like this to the relevant C file (like smx_io.c if it\'s an IO call):'
83               print '%s simcall_HANDLER_%s(smx_simcall_t simcall%s) {'%(self.res.rettype()
84                                                                         ,self.name                                               
85                                                                         ,''.join(', %s %s'%(arg.rettype(), arg.name)
86                                                                              for arg in self.args))
87               print '  // Your code handling the simcall'
88               print '}'
89               return False
90       else:
91           if (self.name in self.simcalls_PRE):
92               print '# ERROR: You have a function called simcall_HANDLER_%s, but that simcall is not using any handler'%self.name
93               print '# Either change your simcall definition, or kill that function'
94               return False
95       return True
96
97   def enum(self):
98     return '  SIMCALL_%s,'%(self.name.upper())
99
100   def string(self):
101     return '  "SIMCALL_%s",'% self.name.upper()
102
103   def accessors(self):
104     res = []
105     res.append('')
106     # Arguments getter/setters
107     for i in range(len(self.args)):
108         arg = self.args[i]
109         res.append('static inline %s simcall_%s__get__%s(smx_simcall_t simcall) {'%(arg.rettype(), self.name, arg.name))
110         res.append('  return %s simcall->args[%i].%s;'%(arg.cast(), i, arg.field()))
111         res.append('}')
112         res.append('static inline void simcall_%s__set__%s(smx_simcall_t simcall, %s arg) {'%(self.name, arg.name, arg.type))
113         res.append('    simcall->args[%i].%s = arg;'%(i, arg.field()))
114         res.append('}')
115       
116     # Return value getter/setters
117     if self.res.type != 'void':
118         res.append('static inline %s simcall_%s__get__result(smx_simcall_t simcall){'%(self.res.rettype(), self.name))
119         res.append('    return %s simcall->result.%s;'%(self.res.cast(), self.res.field()))
120         res.append('}')
121         res.append('static inline void simcall_%s__set__result(smx_simcall_t simcall, %s result){'%(self.name, self.res.type,))
122         res.append('    simcall->result.%s = result;'%(self.res.field()))
123         res.append('}')
124     return '\n'.join(res)
125
126   def case(self):
127       res = []
128       res.append('case SIMCALL_%s:'%(self.name.upper()))
129       if self.need_handler:
130           res.append('      %ssimcall_HANDLER_%s(simcall %s);'%('simcall->result.%s = '%self.res.field() if self.call_kind == 'Func' else ' ',
131                                                                 self.name,
132                                                                 ''.join(', %s simcall->args[%d].%s'%(arg.cast(), i, arg.field()) 
133                                                                         for i, arg in enumerate(self.args))))
134       else:
135           res.append('      %sSIMIX_%s(%s);'%('simcall->result.%s = '%self.res.field() if self.call_kind == 'Func' else ' ',
136                                                 self.name,  
137                                                 ','.join('%s simcall->args[%d].%s'%(arg.cast(), i, arg.field()) 
138                                                          for i, arg in enumerate(self.args))))
139       res.append('      %sbreak;  \n'%('SIMIX_simcall_answer(simcall);\n      ' if self.call_kind != 'Blck' else ' '))  
140       return '\n'.join(res)
141
142   def body(self):
143       res = ['  ']
144       res.append('inline static %s simcall_BODY_%s(%s) {'%(self.res.rettype(),
145                                                            self.name,
146                                                            ', '.join('%s %s'%(arg.rettype(), arg.name) for arg in self.args)))
147       res.append('    smx_process_t self = SIMIX_process_self();')
148       res.append('')
149       res.append('    /* Go to that function to follow the code flow through the simcall barrier */')
150       if self.need_handler:
151           res.append('    if (0) simcall_HANDLER_%s(%s);'%(self.name,
152                                                            ', '.join(["&self->simcall"]+ [arg.name for arg in self.args])))
153       else:
154           res.append('    if (0) SIMIX_%s(%s);'%(self.name,
155                                                    ', '.join(arg.name for arg in self.args)))
156       res.append('    /* end of the guide intended to the poor programmer wanting to go from MSG to Surf */')
157       res.append('')
158       res.append('    self->simcall.call = SIMCALL_%s;'%(self.name.upper()))
159       res.append('    memset(&self->simcall.result, 0, sizeof(self->simcall.result));')
160       res.append('    memset(self->simcall.args, 0, sizeof(self->simcall.args));')
161       res.append('\n'.join('    self->simcall.args[%d].%s = (%s) %s;'%(i, arg.field(), arg.type, arg.name)
162                   for i, arg in enumerate(self.args)))
163       res.append('    if (self != simix_global->maestro_process) {')
164       res.append('      XBT_DEBUG("Yield process \'%s\' on simcall %s (%d)", self->name,')
165       res.append('                SIMIX_simcall_name(self->simcall.call), (int)self->simcall.call);')
166       res.append('      SIMIX_process_yield(self);')
167       res.append('    } else {')
168       res.append('      SIMIX_simcall_handle(&self->simcall, 0);')
169       res.append('    }    ')   
170       if self.res.type != 'void':
171           res.append('    return (%s) self->simcall.result.%s;' % 
172               (self.res.rettype(), self.res.field()))
173       else:
174           res.append('    ')
175       res.append('  }')
176       return '\n'.join(res)
177
178       
179   def handler_prototype(self):
180       if self.need_handler:
181           return "XBT_PRIVATE %s simcall_HANDLER_%s(smx_simcall_t simcall%s);"%(self.res.rettype() if self.call_kind == 'Func' else 'void', 
182                                                                     self.name, 
183                                                                     ''.join(', %s %s'%(arg.rettype(), arg.name) 
184                     for i, arg in enumerate(self.args)))
185       else:
186           return ""
187
188 def parse(fn):
189   simcalls = []
190   resdi = None
191   simcalls_guarded = {}
192   for line in open(fn).read().split('\n'):
193     if line.startswith('##'):
194       resdi = []
195       simcalls_guarded[re.search(r'## *(.*)', line).group(1)] = resdi
196     if line.startswith('#') or not line:
197       continue
198     match = re.match(r'(\S*?) *(\S*?) *(\S*?) *\((.*?)(?:, *(.*?))?\) *(.*)', line)
199     assert match, line
200     ans, handler, name, rest, resc, args = match.groups()
201     assert (ans == 'Proc' or ans == 'Func' or ans == 'Blck'),"Invalid call type: '%s'. Faulty line:\n%s\n"%(ans,line)
202     assert (handler == 'H' or handler == '-'),"Invalid need_handler indication: '%s'. Faulty line:\n%s\n"%(handler,line)
203     sargs = []
204     for n,t,c in re.findall(r'\((.*?), *(.*?)(?:, *(.*?))?\)', args):
205       sargs.append(Arg(n,t,c))
206     sim = Simcall(name, handler=='H', Arg('result', rest, resc), sargs, ans)
207     if resdi is None:
208       simcalls.append(sim)
209     else:
210       resdi.append(sim)
211   return simcalls, simcalls_guarded
212
213 def header(name):
214     fd = open(name, 'w')
215     fd.write('/**********************************************************************/\n')
216     fd.write('/* File generated by src/simix/simcalls.py from src/simix/simcalls.in */\n')
217     fd.write('/*                                                                    */\n')
218     fd.write('/*                    DO NOT EVER CHANGE THIS FILE                    */\n')
219     fd.write('/*                                                                    */\n')
220     fd.write('/* change simcalls specification in src/simix/simcalls.in             */\n')  
221     fd.write('/**********************************************************************/\n\n')
222     fd.write('/*\n')
223     fd.write(' * Note that the name comes from http://en.wikipedia.org/wiki/Popping\n') 
224     fd.write(' * Indeed, the control flow is doing a strange dance in there.\n')
225     fd.write(' *\n')
226     fd.write(' * That\'s not about http://en.wikipedia.org/wiki/Poop, despite the odor :)\n')
227     fd.write(' */\n\n')
228     return fd
229
230 def handle(fd,func, simcalls, guarded_simcalls):
231     def nonempty(e): return e != ''
232     fd.write('\n'.join( filter(nonempty, (func(simcall) for simcall in simcalls))))
233     
234     for guard, list in guarded_simcalls.items():
235         fd.write('\n#ifdef %s\n'%(guard))
236         fd.write('\n'.join(func(simcall) for simcall in list))
237         fd.write('\n#endif\n')
238
239 if __name__=='__main__':
240   import sys
241   simcalls, simcalls_dict = parse('simcalls.in')
242   
243   ok = True
244   ok &= all(map(Simcall.check, simcalls))
245   for k,v in simcalls_dict.items():
246     ok &= all(map(Simcall.check, v))
247   # FIXME: we should not hide it
248   #if not ok:
249   #  print ("Some checks fail!")
250   #  sys.exit(1)
251
252   ###
253   ### smx_popping_accessors.c
254   ###
255   fd = header('popping_accessors.h')
256   handle(fd, Simcall.accessors, simcalls, simcalls_dict)
257   fd.write("\n\n/* The prototype of all simcall handlers, automatically generated for you */\n\n")
258   handle(fd, Simcall.handler_prototype, simcalls, simcalls_dict)
259   fd.close()
260
261   ###
262   ### smx_popping_enum.c
263   ###
264   fd = header("popping_enum.h")
265   fd.write('/**\n')
266   fd.write(' * @brief All possible simcalls.\n')
267   fd.write(' */\n')
268   fd.write('typedef enum {\n')
269   fd.write('  SIMCALL_NONE,\n')
270   
271   handle(fd, Simcall.enum, simcalls, simcalls_dict)
272   
273   fd.write('  NUM_SIMCALLS\n')
274   fd.write('} e_smx_simcall_t;\n')
275   fd.close()
276
277   ###
278   ### smx_popping_generated.cpp
279   ###
280   
281   fd = header("popping_generated.cpp")
282   
283   fd.write('#include <xbt/base.h>\n');
284   fd.write('#include "smx_private.h"\n');
285   fd.write('#ifdef HAVE_MC\n');
286   fd.write('#include "src/mc/mc_forward.h"\n');
287   fd.write('#endif\n');
288   fd.write('\n');
289   fd.write('XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(simix_popping);\n\n');
290   
291   fd.write('/** @brief Simcalls\' names (generated from src/simix/simcalls.in) */\n')
292   fd.write('const char* simcall_names[] = {\n')
293
294   fd.write('   "SIMCALL_NONE",');
295   handle(fd, Simcall.string, simcalls, simcalls_dict)
296
297   fd.write('};\n\n')
298
299
300   fd.write('/**\n');
301   fd.write(' * @brief (in kernel mode) unpack the simcall and activate the handler\n');
302   fd.write(' * \n')
303   fd.write(' * This function is generated from src/simix/simcalls.in\n')
304   fd.write(' */\n');
305   fd.write('void SIMIX_simcall_handle(smx_simcall_t simcall, int value) {\n');
306   fd.write('  XBT_DEBUG("Handling simcall %p: %s", simcall, SIMIX_simcall_name(simcall->call));\n');
307   fd.write('  SIMCALL_SET_MC_VALUE(simcall, value);\n');
308   fd.write('  if (simcall->issuer->context->iwannadie && simcall->call != SIMCALL_PROCESS_CLEANUP)\n');
309   fd.write('    return;\n');
310   fd.write('  switch (simcall->call) {\n');
311
312   handle(fd, Simcall.case, simcalls, simcalls_dict)
313
314   fd.write('    case NUM_SIMCALLS:\n');
315   fd.write('      break;\n');
316   fd.write('    case SIMCALL_NONE:\n');
317   fd.write('      THROWF(arg_error,0,"Asked to do the noop syscall on %s@%s",\n');
318   fd.write('          SIMIX_process_get_name(simcall->issuer),\n');
319   fd.write('          sg_host_get_name(SIMIX_process_get_host(simcall->issuer))\n');
320   fd.write('          );\n');
321   fd.write('      break;\n');
322   fd.write('\n');
323   fd.write('  }\n');
324   fd.write('}\n');
325   
326   fd.close()
327   
328   ###
329   ### smx_popping_bodies.cpp
330   ###
331   fd = header('popping_bodies.cpp')
332   fd.write('#include "smx_private.h"\n')
333   fd.write('#include "src/mc/mc_forward.h"\n')
334   fd.write('#include "xbt/ex.h"\n')
335   fd.write('#include <simgrid/simix.hpp>\n')
336   handle(fd, Simcall.body, simcalls, simcalls_dict)
337   fd.close()