Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Use new/delete for smx_process_arg_t
[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 types = [(
13     'TCHAR', 'char', 'c'), ('TSTRING', 'const char*', 'cc'), ('TINT', 'int', 'i'), ('TLONG', 'long', 'l'), ('TUCHAR', 'unsigned char', 'uc'), ('TUSHORT', 'unsigned short', 'us'), ('TUINT', 'unsigned int', 'ui'), ('TULONG', 'unsigned long', 'ul'), ('TFLOAT', 'float', 'f'),
14     ('TDOUBLE', 'double', 'd'), ('TDPTR', 'void*', 'dp'), ('TFPTR', 'FPtr', 'fp'), ('TCPTR', 'const void*', 'cp'), ('TSIZE', 'size_t', 'sz'), ('TSGSIZE', 'sg_size_t', 'sgsz'), ('TSGOFF', 'sg_offset_t', 'sgoff'), ('TVOID', 'void', ''), ('TDSPEC', 'void*', 'dp'), ('TFSPEC', 'FPtr', 'fp')]
15
16
17 class Arg(object):
18     simcall_types = {k: v for _, k, v in types}
19
20     def __init__(self, name, type, casted=None):
21         self.name = name
22         self.type = type
23         self.casted = casted
24         assert type in self.simcall_types, '%s not in (%s)' % (
25             type, ', '.join(self.simcall_types.keys()))
26
27     def field(self):
28         return self.simcall_types[self.type]
29
30     def rettype(self):
31         return '%s' % self.casted if self.casted else self.type
32
33     def cast(self):
34         return '(%s)' % self.casted if self.casted else ''
35
36
37 class Simcall(object):
38     simcalls_BODY = None
39     simcalls_PRE = None
40
41     def __init__(self, name, handler, res, args, call_kind):
42         self.name = name
43         self.res = res
44         self.args = args
45         self.need_handler = handler
46         self.call_kind = call_kind
47
48     def check(self):
49         # libsmx.c  simcall_BODY_
50         if self.simcalls_BODY is None:
51             f = open('libsmx.cpp')
52             self.simcalls_BODY = set(
53                 re.findall('simcall_BODY_(.*?)\(', f.read()))
54             f.close()
55         if self.name not in self.simcalls_BODY:
56             print '# ERROR: No function calling simcall_BODY_%s' % self.name
57             print '# Add something like this to libsmx.c:'
58             print '%s simcall_%s(%s) {' % (self.res.rettype(), self.name, ', '.join('%s %s' % (arg.rettype(), arg.name) for arg in self.args))
59             print '  return simcall_BODY_%s(%s);' % (self.name)
60             print '}'
61             return False
62
63         # smx_*.c void simcall_HANDLER_host_on(smx_simcall_t simcall,
64         # smx_host_t h)
65         if self.simcalls_PRE is None:
66             self.simcalls_PRE = set()
67             for fn in glob.glob('smx_*') + glob.glob('../mc/*'):
68                 f = open(fn)
69                 self.simcalls_PRE |= set(
70                     re.findall('simcall_HANDLER_(.*?)\(', f.read()))
71                 f.close()
72         if self.need_handler:
73             if (self.name not in self.simcalls_PRE):
74                 print '# ERROR: No function called simcall_HANDLER_%s' % self.name
75                 print '# Add something like this to the relevant C file (like smx_io.c if it\'s an IO call):'
76                 print '%s simcall_HANDLER_%s(smx_simcall_t simcall%s) {' % (self.res.rettype(), self.name, ''.join(', %s %s' % (arg.rettype(), arg.name)
77                                                                                                                    for arg in self.args))
78                 print '  // Your code handling the simcall'
79                 print '}'
80                 return False
81         else:
82             if (self.name in self.simcalls_PRE):
83                 print '# ERROR: You have a function called simcall_HANDLER_%s, but that simcall is not using any handler' % self.name
84                 print '# Either change your simcall definition, or kill that function'
85                 return False
86         return True
87
88     def enum(self):
89         return '  SIMCALL_%s,' % (self.name.upper())
90
91     def string(self):
92         return '  "SIMCALL_%s",' % self.name.upper()
93
94     def accessors(self):
95         res = []
96         res.append('')
97         # Arguments getter/setters
98         for i in range(len(self.args)):
99             arg = self.args[i]
100             res.append('static inline %s simcall_%s__get__%s(smx_simcall_t simcall) {' % (
101                 arg.rettype(), self.name, arg.name))
102             res.append(
103                 '  return %s simcall->args[%i].%s;' % (arg.cast(), i, arg.field()))
104             res.append('}')
105             res.append('static inline void simcall_%s__set__%s(smx_simcall_t simcall, %s arg) {' % (
106                 self.name, arg.name, arg.type))
107             res.append('    simcall->args[%i].%s = arg;' % (i, arg.field()))
108             res.append('}')
109
110         # Return value getter/setters
111         if self.res.type != 'void':
112             res.append(
113                 'static inline %s simcall_%s__get__result(smx_simcall_t simcall){' % (self.res.rettype(), self.name))
114             res.append('    return %s simcall->result.%s;' %
115                        (self.res.cast(), self.res.field()))
116             res.append('}')
117             res.append(
118                 'static inline void simcall_%s__set__result(smx_simcall_t simcall, %s result){' % (self.name, self.res.type,))
119             res.append('    simcall->result.%s = result;' % (self.res.field()))
120             res.append('}')
121         return '\n'.join(res)
122
123     def case(self):
124         res = []
125         res.append('case SIMCALL_%s:' % (self.name.upper()))
126         if self.need_handler:
127             res.append(
128                 '      %ssimcall_HANDLER_%s(simcall %s);' % ('simcall->result.%s = ' % self.res.field() if self.call_kind == 'Func' else ' ',
129                                                              self.name,
130                                                              ''.join(', %s simcall->args[%d].%s' % (arg.cast(), i, arg.field())
131                                                                      for i, arg in enumerate(self.args))))
132         else:
133             res.append(
134                 '      %sSIMIX_%s(%s);' % ('simcall->result.%s = ' % self.res.field() if self.call_kind == 'Func' else ' ',
135                                            self.name,
136                                            ','.join('%s simcall->args[%d].%s' % (arg.cast(), i, arg.field())
137                                                     for i, arg in enumerate(self.args))))
138         res.append('      %sbreak;  \n' %
139                    ('SIMIX_simcall_answer(simcall);\n      ' if self.call_kind != 'Blck' else ' '))
140         return '\n'.join(res)
141
142     def body(self):
143         res = ['  ']
144         res.append(
145             'inline static %s simcall_BODY_%s(%s) {' % (self.res.rettype(),
146                                                         self.name,
147                                                         ', '.join('%s %s' % (arg.rettype(), arg.name) for arg in self.args)))
148         res.append('    smx_process_t self = SIMIX_process_self();')
149         res.append('')
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(["&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(
159             '    /* end of the guide intended to the poor programmer wanting to go from MSG to Surf */')
160         res.append('')
161         res.append('    self->simcall.call = SIMCALL_%s;' %
162                    (self.name.upper()))
163         res.append(
164             '    memset(&self->simcall.result, 0, sizeof(self->simcall.result));')
165         res.append(
166             '    memset(self->simcall.args, 0, sizeof(self->simcall.args));')
167         res.append('\n'.join('    self->simcall.args[%d].%s = (%s) %s;' % (i, arg.field(), arg.type, arg.name)
168                              for i, arg in enumerate(self.args)))
169         res.append('    if (self != simix_global->maestro_process) {')
170         res.append(
171             '      XBT_DEBUG("Yield process \'%s\' on simcall %s (%d)", self->name,')
172         res.append(
173             '                SIMIX_simcall_name(self->simcall.call), (int)self->simcall.call);')
174         res.append('      SIMIX_process_yield(self);')
175         res.append('    } else {')
176         res.append('      SIMIX_simcall_handle(&self->simcall, 0);')
177         res.append('    }    ')
178         if self.res.type != 'void':
179             res.append('    return (%s) self->simcall.result.%s;' %
180                        (self.res.rettype(), self.res.field()))
181         else:
182             res.append('    ')
183         res.append('  }')
184         return '\n'.join(res)
185
186     def handler_prototype(self):
187         if self.need_handler:
188             return "XBT_PRIVATE %s simcall_HANDLER_%s(smx_simcall_t simcall%s);" % (self.res.rettype() if self.call_kind == 'Func' else 'void',
189                                                                                     self.name,
190                                                                                     ''.join(', %s %s' % (arg.rettype(), arg.name)
191                                                                                             for i, arg in enumerate(self.args)))
192         else:
193             return ""
194
195
196 def parse(fn):
197     simcalls = []
198     resdi = None
199     simcalls_guarded = {}
200     for line in open(fn).read().split('\n'):
201         if line.startswith('##'):
202             resdi = []
203             simcalls_guarded[re.search(r'## *(.*)', line).group(1)] = resdi
204         if line.startswith('#') or not line:
205             continue
206         match = re.match(
207             r'(\S*?) *(\S*?) *(\S*?) *\((.*?)(?:, *(.*?))?\) *(.*)', line)
208         assert match, line
209         ans, handler, name, rest, resc, args = match.groups()
210         assert (ans == 'Proc' or ans == 'Func' or ans == 'Blck'), "Invalid call type: '%s'. Faulty line:\n%s\n" % (
211             ans, line)
212         assert (handler == 'H' or handler == '-'), "Invalid need_handler indication: '%s'. Faulty line:\n%s\n" % (
213             handler, line)
214         sargs = []
215         for n, t, c in re.findall(r'\((.*?), *(.*?)(?:, *(.*?))?\)', args):
216             sargs.append(Arg(n, t, c))
217         sim = Simcall(name, handler == 'H',
218                       Arg('result', rest, resc), sargs, ans)
219         if resdi is None:
220             simcalls.append(sim)
221         else:
222             resdi.append(sim)
223     return simcalls, simcalls_guarded
224
225
226 def header(name):
227     fd = open(name, 'w')
228     fd.write(
229         '/**********************************************************************/\n')
230     fd.write(
231         '/* File generated by src/simix/simcalls.py from src/simix/simcalls.in */\n')
232     fd.write(
233         '/*                                                                    */\n')
234     fd.write(
235         '/*                    DO NOT EVER CHANGE THIS FILE                    */\n')
236     fd.write(
237         '/*                                                                    */\n')
238     fd.write(
239         '/* change simcalls specification in src/simix/simcalls.in             */\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): return e != ''
256     fd.write(
257         '\n'.join(filter(nonempty, (func(simcall) for simcall in simcalls))))
258
259     for guard, list in guarded_simcalls.items():
260         fd.write('\n#if %s\n' % (guard))
261         fd.write('\n'.join(func(simcall) for simcall in list))
262         fd.write('\n#endif\n')
263
264 if __name__ == '__main__':
265     import sys
266     simcalls, simcalls_dict = parse('simcalls.in')
267
268     ok = True
269     ok &= all(map(Simcall.check, simcalls))
270     for k, v in simcalls_dict.items():
271         ok &= all(map(Simcall.check, v))
272     # FIXME: we should not hide it
273     # if not ok:
274     #  print ("Some checks fail!")
275     #  sys.exit(1)
276
277     #
278     # smx_popping_accessors.c
279     #
280     fd = header('popping_accessors.h')
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     # smx_popping_enum.c
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     # smx_popping_generated.cpp
305     #
306
307     fd = header("popping_generated.cpp")
308
309     fd.write('#include <xbt/base.h>\n')
310     fd.write('#include "smx_private.h"\n')
311     fd.write('#if HAVE_MC\n')
312     fd.write('#include "src/mc/mc_forward.hpp"\n')
313     fd.write('#endif\n')
314     fd.write('\n')
315     fd.write('XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(simix_popping);\n\n')
316
317     fd.write(
318         '/** @brief Simcalls\' names (generated from src/simix/simcalls.in) */\n')
319     fd.write('const char* simcall_names[] = {\n')
320
321     fd.write('   "SIMCALL_NONE",')
322     handle(fd, Simcall.string, simcalls, simcalls_dict)
323
324     fd.write('};\n\n')
325
326     fd.write('/** @private\n')
327     fd.write(
328         ' * @brief (in kernel mode) unpack the simcall and activate the handler\n')
329     fd.write(' * \n')
330     fd.write(' * This function is generated from src/simix/simcalls.in\n')
331     fd.write(' */\n')
332     fd.write(
333         'void SIMIX_simcall_handle(smx_simcall_t simcall, int value) {\n')
334     fd.write(
335         '  XBT_DEBUG("Handling simcall %p: %s", simcall, SIMIX_simcall_name(simcall->call));\n')
336     fd.write('  SIMCALL_SET_MC_VALUE(simcall, value);\n')
337     fd.write(
338         '  if (simcall->issuer->context->iwannadie && simcall->call != SIMCALL_PROCESS_CLEANUP)\n')
339     fd.write('    return;\n')
340     fd.write('  switch (simcall->call) {\n')
341
342     handle(fd, Simcall.case, simcalls, simcalls_dict)
343
344     fd.write('    case NUM_SIMCALLS:\n')
345     fd.write('      break;\n')
346     fd.write('    case SIMCALL_NONE:\n')
347     fd.write(
348         '      THROWF(arg_error,0,"Asked to do the noop syscall on %s@%s",\n')
349     fd.write('          SIMIX_process_get_name(simcall->issuer),\n')
350     fd.write(
351         '          sg_host_get_name(SIMIX_process_get_host(simcall->issuer))\n')
352     fd.write('          );\n')
353     fd.write('      break;\n')
354     fd.write('\n')
355     fd.write('  }\n')
356     fd.write('}\n')
357
358     fd.close()
359
360     #
361     # smx_popping_bodies.cpp
362     #
363     fd = header('popping_bodies.cpp')
364     fd.write('#include "smx_private.h"\n')
365     fd.write('#include "src/mc/mc_forward.hpp"\n')
366     fd.write('#include "xbt/ex.h"\n')
367     fd.write('#include <simgrid/simix.hpp>\n')
368     fd.write("/** @cond */ // Please Doxygen, don't look at this\n")
369     handle(fd, Simcall.body, simcalls, simcalls_dict)
370     fd.write("/** @endcond */\n");
371     fd.close()