Logo AND Algorithmique Numérique Distribuée

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