Logo AND Algorithmique Numérique Distribuée

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