Logo AND Algorithmique Numérique Distribuée

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