Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Generate automatically the simcall_HANDLER_* prototypes
[simgrid.git] / src / simix / simcalls.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 # Copyright (c) 2014. 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, res, args, has_answer=True):
52     self.name = name
53     self.res = res
54     self.args = args
55     self.has_answer = has_answer
56
57   def check(self):
58       # libsmx.c  simcall_BODY_
59       if self.simcalls_BODY is None:
60           f = open('libsmx.c')
61           self.simcalls_BODY = set(re.findall('simcall_BODY_(.*?)\(', f.read()))
62           f.close()
63       if self.name not in self.simcalls_BODY:
64           print '# ERROR: No function calling simcall_BODY_%s'%self.name
65           print '# Add something like this to libsmx.c:'
66           print '%s simcall_%s(%s) {'%(self.res.rettype() ,self.name ,', '.join('%s %s'%(arg.rettype(), arg.name) for arg in self.args))
67           print '  return simcall_BODY_%s(%s);'%(self.name)
68           print '}'
69           return False
70       
71       # smx_*.c void simcall_HANDLER_host_on(smx_simcall_t simcall, smx_host_t h)
72       if self.simcalls_PRE is None:
73         self.simcalls_PRE = set()
74         for fn in glob.glob('smx_*') + glob.glob('../mc/*'):
75             f = open(fn)
76             self.simcalls_PRE |= set(re.findall('simcall_HANDLER_(.*?)\(', f.read()))
77             f.close()
78       if self.name not in self.simcalls_PRE:
79           print '# ERROR: No function called simcall_HANDLER_%s'%self.name
80           print '# Add something like this to the relevant C file (like smx_io.c if it\'s an IO call):'
81           print '%s simcall_HANDLER_%s(smx_simcall_t simcall%s) {'%(self.res.rettype()
82                                                                     ,self.name                                               
83                                                                     ,''.join(', %s %s'%(arg.rettype(), arg.name)
84                                                                              for arg in self.args))
85           print '  // Your code handling the simcall'
86           print '}'
87           return False
88       return True
89
90   def enum(self):
91     return '  SIMCALL_%s,'%(self.name.upper())
92
93   def string(self):
94     return '[SIMCALL_%s] = "SIMCALL_%s",'%(self.name.upper(), self.name.upper())        
95
96   def accessors(self):
97     res = []
98     # Arguments getter/setters
99     for i in range(len(self.args)):
100         arg = self.args[i]
101         res.append('')
102         res.append('static inline %s simcall_%s__get__%s(smx_simcall_t simcall){'%(arg.rettype(), self.name, arg.name))
103         res.append('  return %s simcall->args[%i].%s;'%(arg.cast(), i, arg.field()))
104         res.append('}')
105         res.append('')
106         res.append('static inline void simcall_%s__set__%s(smx_simcall_t simcall, %s arg){'%(self.name, arg.name, arg.type))
107         res.append('    simcall->args[%i].%s = arg;'%(i, arg.field()))
108         res.append('}')
109       
110     # Return value getter/setters
111     if self.res.type != 'void':
112         res.append('static inline %s simcall_%s__get__result(smx_simcall_t simcall){'%(self.res.rettype(), self.name))
113         res.append('    return %s simcall->result.%s;'%(self.res.cast(), self.res.field()))
114         res.append('}')
115         res.append('static inline void simcall_%s__set__result(smx_simcall_t simcall, %s result){'%(self.name, self.res.type,))
116         res.append('    simcall->result.%s = result;'%(self.res.field()))
117         res.append('}')
118     return '\n'.join(res)
119
120   def case(self):
121     return '''case SIMCALL_%s:
122       %ssimcall_HANDLER_%s(simcall %s);
123       %sbreak;  
124 '''%(self.name.upper(), 
125      'simcall->result.%s = '%self.res.field() if self.res.type != 'void' and self.has_answer else ' ',
126      self.name,
127      ''.join(', %s simcall->args[%d].%s'%(arg.cast(), i, arg.field()) 
128              for i, arg in enumerate(self.args)),
129      'SIMIX_simcall_answer(simcall);\n      ' if self.has_answer else ' ')
130
131   def body(self):
132     return '''  
133 inline static %s simcall_BODY_%s(%s) {
134     smx_process_t self = SIMIX_process_self();
135
136     /* Go to that function to follow the code flow through the simcall barrier */
137     if (0) simcall_HANDLER_%s(%s);
138     /* end of the guide intended to the poor programmer wanting to go from MSG to Surf */
139
140     self->simcall.call = SIMCALL_%s;
141     memset(&self->simcall.result, 0, sizeof(self->simcall.result));
142     memset(self->simcall.args, 0, sizeof(self->simcall.args));
143 %s
144     if (self != simix_global->maestro_process) {
145       XBT_DEBUG("Yield process '%%s' on simcall %%s (%%d)", self->name,
146                 SIMIX_simcall_name(self->simcall.call), (int)self->simcall.call);
147       SIMIX_process_yield(self);
148     } else {
149       SIMIX_simcall_handle(&self->simcall, 0);
150     }    
151     %s
152   }'''%(self.res.rettype()
153        ,self.name
154        ,', '.join('%s %s'%(arg.rettype(), arg.name)
155                   for arg in self.args)
156        ,self.name
157        ,', '.join(["&self->simcall"]+ [arg.name for arg in self.args])
158        ,self.name.upper()
159        ,'\n'.join('    self->simcall.args[%d].%s = (%s) %s;'%(i, arg.field(), arg.type, arg.name)
160                   for i, arg in enumerate(self.args))
161        ,'' if self.res.type == 'void' else 'return self->simcall.result.%s;'%self.res.field())
162   
163   def handler_prototype(self):
164       return "%s simcall_HANDLER_%s(smx_simcall_t simcall%s);"%(self.res.rettype() if self.has_answer else 'void', self.name, ''.join(', %s %s'%(arg.rettype(), arg.name) 
165              for i, arg in enumerate(self.args)))
166
167 def parse(fn):
168   simcalls = []
169   resdi = None
170   simcalls_guarded = {}
171   for line in open(fn).read().split('\n'):
172     if line.startswith('##'):
173       resdi = []
174       simcalls_guarded[re.search(r'## *(.*)', line).group(1)] = resdi
175     if line.startswith('#') or not line:
176       continue
177     match = re.match(r'(\S*?) *(\S*?) *\((.*?)(?:, *(.*?))?\) *(.*)', line)
178     assert match, line
179     name, ans, rest, resc, args = match.groups()
180     sargs = []
181     for n,t,c in re.findall(r'\((.*?), *(.*?)(?:, *(.*?))?\)', args):
182       sargs.append(Arg(n,t,c))
183     sim = Simcall(name, Arg('result', rest, resc), sargs, ans == 'True')
184     if resdi is None:
185       simcalls.append(sim)
186     else:
187       resdi.append(sim)
188   return simcalls, simcalls_guarded
189
190 def header(name):
191     fd = open(name, 'w')
192     fd.write('/**********************************************************************/\n')
193     fd.write('/* File generated by src/simix/simcalls.py from src/simix/simcalls.in */\n')
194     fd.write('/*                                                                    */\n')
195     fd.write('/*                    DO NOT EVER CHANGE THIS FILE                    */\n')
196     fd.write('/*                                                                    */\n')
197     fd.write('/* change simcalls specification in src/simix/simcalls.in             */\n')  
198     fd.write('/**********************************************************************/\n\n')
199     fd.write('/*\n')
200     fd.write(' * Note that the name comes from http://en.wikipedia.org/wiki/Popping\n') 
201     fd.write(' * Indeed, the control flow is doing a strange dance in there.\n')
202     fd.write(' *\n')
203     fd.write(' * That\'s not about http://en.wikipedia.org/wiki/Poop, despite the odor :)\n')
204     fd.write(' */\n\n')
205     return fd
206
207 def handle(fd,func, simcalls, guarded_simcalls):
208     fd.write('\n'.join(func(simcall) for simcall in simcalls))
209     for guard, list in guarded_simcalls.items():
210         fd.write('\n#ifdef %s\n'%(guard))
211         fd.write('\n'.join(func(simcall) for simcall in list))
212         fd.write('\n#endif\n')
213
214 if __name__=='__main__':
215   import sys
216   simcalls, simcalls_dict = parse('simcalls.in')
217   
218   ok = True
219   ok &= all(map(Simcall.check, simcalls))
220   for k,v in simcalls_dict.items():
221     ok &= all(map(Simcall.check, v))
222   # FIXME: we should not hide it
223   #if not ok:
224   #  print ("Some checks fail!")
225   #  sys.exit(1)
226
227   ###
228   ### smx_popping_accessors.c
229   ###
230   fd = header('popping_accessors.h')
231   handle(fd, Simcall.accessors, simcalls, simcalls_dict)
232   fd.write("\n\n/* The prototype of all simcall handlers, automatically generated for you */\n\n")
233   handle(fd, Simcall.handler_prototype, simcalls, simcalls_dict)
234   fd.close()
235
236   ###
237   ### smx_popping_enum.c
238   ###
239   fd = header("popping_enum.h")
240   fd.write('/**\n')
241   fd.write(' * @brief All possible simcalls.\n')
242   fd.write(' */\n')
243   fd.write('typedef enum {\n')
244   fd.write('  SIMCALL_NONE,\n')
245   
246   handle(fd, Simcall.enum, simcalls, simcalls_dict)
247   
248   fd.write('  NUM_SIMCALLS\n')
249   fd.write('} e_smx_simcall_t;\n')
250   fd.close()
251
252   ###
253   ### smx_popping_generated.c
254   ###
255   
256   fd = header("popping_generated.c")
257   
258   fd.write('#include "smx_private.h"\n');
259   fd.write('#ifdef HAVE_MC\n');
260   fd.write('#include "mc/mc_private.h"\n');
261   fd.write('#endif\n');
262   fd.write('\n');
263   fd.write('XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(simix_popping);\n\n');
264   
265   fd.write('/** @brief Simcalls\' names (generated from src/simix/simcalls.in) */\n')
266   fd.write('const char* simcall_names[] = {\n')
267
268   handle(fd, Simcall.string, simcalls, simcalls_dict)
269
270   fd.write('[SIMCALL_NONE] = "NONE"\n')
271   fd.write('};\n\n')
272
273
274   fd.write('/**\n');
275   fd.write(' * @brief (in kernel mode) unpack the simcall and activate the handler\n');
276   fd.write(' * \n')
277   fd.write(' * This function is generated from src/simix/simcalls.in\n')
278   fd.write(' */\n');
279   fd.write('void SIMIX_simcall_handle(smx_simcall_t simcall, int value) {\n');
280   fd.write('  XBT_DEBUG("Handling simcall %p: %s", simcall, SIMIX_simcall_name(simcall->call));\n');
281   fd.write('  SIMCALL_SET_MC_VALUE(simcall, value);\n');
282   fd.write('  if (simcall->issuer->context->iwannadie && simcall->call != SIMCALL_PROCESS_CLEANUP)\n');
283   fd.write('    return;\n');
284   fd.write('  switch (simcall->call) {\n');
285
286   handle(fd, Simcall.case, simcalls, simcalls_dict)
287
288   fd.write('    case NUM_SIMCALLS:\n');
289   fd.write('      break;\n');
290   fd.write('    case SIMCALL_NONE:\n');
291   fd.write('      THROWF(arg_error,0,"Asked to do the noop syscall on %s@%s",\n');
292   fd.write('          SIMIX_process_get_name(simcall->issuer),\n');
293   fd.write('          SIMIX_host_get_name(SIMIX_process_get_host(simcall->issuer))\n');
294   fd.write('          );\n');
295   fd.write('      break;\n');
296   fd.write('\n');
297   fd.write('  }\n');
298   fd.write('}\n');
299   
300   fd.close()
301   
302   ###
303   ### smx_popping_bodies.c
304   ###
305   fd = header('popping_bodies.c')
306   fd.write('#include "smx_private.h"\n')
307   fd.write('#include "mc/mc_interface.h"\n')
308   fd.write('#include "xbt/ex.h"\n')
309   handle(fd, Simcall.body, simcalls, simcalls_dict)
310   fd.close()