Logo AND Algorithmique Numérique Distribuée

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