Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge branch 'master' of 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-2016. 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         if self.call_kind != 'Blck':
125             res.append('      SIMIX_simcall_answer(simcall);')
126         res.append('      break;')
127         res.append('')
128         return '\n'.join(res)
129
130     def body(self):
131         res = ['  ']
132         res.append(
133             'inline static %s simcall_BODY_%s(%s) {' % (self.res.rettype(),
134                                                         self.name,
135                                                         ', '.join('%s %s' % (arg.rettype(), arg.name) for arg in self.args)))
136         res.append(
137             '    /* Go to that function to follow the code flow through the simcall barrier */')
138         if self.need_handler:
139             res.append('    if (0) simcall_HANDLER_%s(%s);' % (self.name,
140                                                                ', '.join(["&SIMIX_process_self()->simcall"] + [arg.name for arg in self.args])))
141         else:
142             res.append('    if (0) SIMIX_%s(%s);' % (self.name,
143                                                      ', '.join(arg.name for arg in self.args)))
144         res.append('    return simcall<%s%s>(SIMCALL_%s%s);' % (
145             self.res.rettype(),
146             "".join([ ", " + arg.rettype() for i, arg in enumerate(self.args) ]),
147             self.name.upper(),
148             "".join([ ", " + arg.name for i, arg in enumerate(self.args) ])
149             ));
150         res.append('  }')
151         return '\n'.join(res)
152
153     def handler_prototype(self):
154         if self.need_handler:
155             return "XBT_PRIVATE %s simcall_HANDLER_%s(smx_simcall_t simcall%s);" % (self.res.rettype() if self.call_kind == 'Func' else 'void',
156                                                                                     self.name,
157                                                                                     ''.join(', %s %s' % (arg.rettype(), arg.name)
158                                                                                             for i, arg in enumerate(self.args)))
159         else:
160             return ""
161
162
163 def parse(fn):
164     simcalls = []
165     resdi = None
166     simcalls_guarded = {}
167     for line in open(fn).read().split('\n'):
168         if line.startswith('##'):
169             resdi = []
170             simcalls_guarded[re.search(r'## *(.*)', line).group(1)] = resdi
171         if line.startswith('#') or not line:
172             continue
173         match = re.match(
174             r'^(\S+)\s+([^\)\(\s]+)\s*\(*(.*)\)\s*(\[\[.*\]\])?\s*;\s*?$', line)
175         assert match, line
176         ret, name, args, attrs = match.groups()
177         sargs = []
178         if not re.match("^\s*$", args):
179             for arg in re.split(",", args):
180                 args = args.strip()
181                 match = re.match("^(.*?)\s*?(\S+)$", arg)
182                 t, n = match.groups()
183                 t = t.strip()
184                 n = n.strip()
185                 sargs.append(Arg(n, t))
186         if ret == "void":
187             ans = "Proc"
188         else:
189             ans = "Func"
190         handler = True
191         if attrs:
192             attrs = attrs[2:-2]
193             for attr in re.split(",", attrs):
194                 if attr == "block":
195                     ans = "Blck"
196                 elif attr == "nohandler":
197                     handler = False
198                 else:
199                     assert False, "Unknown attribute %s in: %s" % (attr, line)
200         sim = Simcall(name, handler, Arg('result', ret), sargs, ans)
201         if resdi is None:
202             simcalls.append(sim)
203         else:
204             resdi.append(sim)
205     return simcalls, simcalls_guarded
206
207
208 def header(name):
209     fd = open(name, 'w')
210     fd.write(
211         '/**********************************************************************/\n')
212     fd.write(
213         '/* File generated by src/simix/simcalls.py from src/simix/simcalls.in */\n')
214     fd.write(
215         '/*                                                                    */\n')
216     fd.write(
217         '/*                    DO NOT EVER CHANGE THIS FILE                    */\n')
218     fd.write(
219         '/*                                                                    */\n')
220     fd.write(
221         '/* change simcalls specification in src/simix/simcalls.in             */\n')
222     fd.write(
223         '/**********************************************************************/\n\n')
224     fd.write('/*\n')
225     fd.write(
226         ' * Note that the name comes from http://en.wikipedia.org/wiki/Popping\n')
227     fd.write(
228         ' * Indeed, the control flow is doing a strange dance in there.\n')
229     fd.write(' *\n')
230     fd.write(
231         ' * That\'s not about http://en.wikipedia.org/wiki/Poop, despite the odor :)\n')
232     fd.write(' */\n\n')
233     return fd
234
235
236 def handle(fd, func, simcalls, guarded_simcalls):
237     def nonempty(e): return e != ''
238     fd.write(
239         '\n'.join(filter(nonempty, (func(simcall) for simcall in simcalls))))
240
241     for guard, list in guarded_simcalls.items():
242         fd.write('\n#if %s\n' % (guard))
243         fd.write('\n'.join(func(simcall) for simcall in list))
244         fd.write('\n#endif\n')
245
246 if __name__ == '__main__':
247     import sys
248     simcalls, simcalls_dict = parse('simcalls.in')
249
250     ok = True
251     ok &= all(map(Simcall.check, simcalls))
252     for k, v in simcalls_dict.items():
253         ok &= all(map(Simcall.check, v))
254     # FIXME: we should not hide it
255     # if not ok:
256     #  print ("Some checks fail!")
257     #  sys.exit(1)
258
259     #
260     # smx_popping_accessors.c
261     #
262     fd = header('popping_accessors.h')
263     fd.write('#include "src/simix/popping_private.h"');
264     handle(fd, Simcall.accessors, simcalls, simcalls_dict)
265     fd.write(
266         "\n\n/* The prototype of all simcall handlers, automatically generated for you */\n\n")
267     handle(fd, Simcall.handler_prototype, simcalls, simcalls_dict)
268     fd.close()
269
270     #
271     # smx_popping_enum.c
272     #
273     fd = header("popping_enum.h")
274     fd.write('/**\n')
275     fd.write(' * @brief All possible simcalls.\n')
276     fd.write(' */\n')
277     fd.write('typedef enum {\n')
278     fd.write('  SIMCALL_NONE,\n')
279
280     handle(fd, Simcall.enum, simcalls, simcalls_dict)
281
282     fd.write('  NUM_SIMCALLS\n')
283     fd.write('} e_smx_simcall_t;\n')
284     fd.close()
285
286     #
287     # smx_popping_generated.cpp
288     #
289
290     fd = header("popping_generated.cpp")
291
292     fd.write('#include <xbt/base.h>\n')
293     fd.write('#include "smx_private.h"\n')
294     fd.write('#if HAVE_MC\n')
295     fd.write('#include "src/mc/mc_forward.hpp"\n')
296     fd.write('#endif\n')
297     fd.write('\n')
298     fd.write('XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(simix_popping);\n\n')
299
300     fd.write(
301         '/** @brief Simcalls\' names (generated from src/simix/simcalls.in) */\n')
302     fd.write('const char* simcall_names[] = {\n')
303
304     fd.write('   "SIMCALL_NONE",')
305     handle(fd, Simcall.string, simcalls, simcalls_dict)
306
307     fd.write('};\n\n')
308
309     fd.write('/** @private\n')
310     fd.write(
311         ' * @brief (in kernel mode) unpack the simcall and activate the handler\n')
312     fd.write(' * \n')
313     fd.write(' * This function is generated from src/simix/simcalls.in\n')
314     fd.write(' */\n')
315     fd.write(
316         'void SIMIX_simcall_handle(smx_simcall_t simcall, int value) {\n')
317     fd.write(
318         '  XBT_DEBUG("Handling simcall %p: %s", simcall, SIMIX_simcall_name(simcall->call));\n')
319     fd.write('  SIMCALL_SET_MC_VALUE(simcall, value);\n')
320     fd.write(
321         '  if (simcall->issuer->context->iwannadie && simcall->call != SIMCALL_PROCESS_CLEANUP)\n')
322     fd.write('    return;\n')
323     fd.write('  switch (simcall->call) {\n')
324
325     handle(fd, Simcall.case, simcalls, simcalls_dict)
326
327     fd.write('    case NUM_SIMCALLS:\n')
328     fd.write('      break;\n')
329     fd.write('    case SIMCALL_NONE:\n')
330     fd.write(
331         '      THROWF(arg_error,0,"Asked to do the noop syscall on %s@%s",\n')
332     fd.write('          SIMIX_process_get_name(simcall->issuer),\n')
333     fd.write(
334         '          sg_host_get_name(SIMIX_process_get_host(simcall->issuer))\n')
335     fd.write('          );\n')
336     fd.write('      break;\n')
337     fd.write('\n')
338     fd.write('  }\n')
339     fd.write('}\n')
340
341     fd.close()
342
343     #
344     # smx_popping_bodies.cpp
345     #
346     fd = header('popping_bodies.cpp')
347     fd.write('#include <functional>\n')
348     fd.write('#include "smx_private.h"\n')
349     fd.write('#include "src/mc/mc_forward.hpp"\n')
350     fd.write('#include "xbt/ex.h"\n')
351     fd.write('#include <simgrid/simix.hpp>\n')
352     fd.write("/** @cond */ // Please Doxygen, don't look at this\n")
353     fd.write('''
354 template<class R, class... T>
355 inline static R simcall(e_smx_simcall_t call, T const&... t)
356 {
357   smx_process_t self = SIMIX_process_self();
358   simgrid::simix::marshal(&self->simcall, call, t...);
359   if (self != simix_global->maestro_process) {
360     XBT_DEBUG("Yield process '%s' on simcall %s (%d)", self->name.c_str(),
361               SIMIX_simcall_name(self->simcall.call), (int)self->simcall.call);
362     SIMIX_process_yield(self);
363   } else {
364     SIMIX_simcall_handle(&self->simcall, 0);
365   }
366   return simgrid::simix::unmarshal<R>(self->simcall.result);
367 }
368 ''')
369     handle(fd, Simcall.body, simcalls, simcalls_dict)
370     fd.write("/** @endcond */\n");
371     fd.close()