Logo AND Algorithmique Numérique Distribuée

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