Logo AND Algorithmique Numérique Distribuée

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