Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
empty out src/simix/smx_context.cpp
[simgrid.git] / src / kernel / EngineImpl.cpp
1 /* Copyright (c) 2016-2021. The SimGrid Team. All rights reserved.          */
2
3 /* This program is free software; you can redistribute it and/or modify it
4  * under the terms of the license (GNU LGPL) which comes with this package. */
5
6 #include <simgrid/Exception.hpp>
7 #include <simgrid/kernel/Timer.hpp>
8 #include <simgrid/kernel/routing/NetPoint.hpp>
9 #include <simgrid/kernel/routing/NetZoneImpl.hpp>
10 #include <simgrid/s4u/Host.hpp>
11 #include <simgrid/sg_config.hpp>
12
13 #include "mc/mc.h"
14 #include "src/kernel/EngineImpl.hpp"
15 #include "src/kernel/resource/profile/Profile.hpp"
16 #include "src/mc/mc_record.hpp"
17 #include "src/mc/mc_replay.hpp"
18 #include "src/smpi/include/smpi_actor.hpp"
19 #include "src/surf/network_interface.hpp"
20 #include "src/surf/xml/platf.hpp"
21 #include "surf/surf.hpp"          //surf_presolve() and surf_solve()
22 #include "xbt/xbt_modinter.h"     /* whether initialization was already done */
23
24 #include <boost/algorithm/string/predicate.hpp>
25 #ifndef _WIN32
26 #include <dlfcn.h>
27 #endif /* _WIN32 */
28
29 #if SIMGRID_HAVE_MC
30 #include "src/mc/remote/AppSide.hpp"
31 #endif
32
33 XBT_LOG_NEW_DEFAULT_CATEGORY(ker_engine, "Logging specific to Engine (kernel)");
34 namespace simgrid {
35 namespace kernel {
36 EngineImpl* EngineImpl::instance_ = nullptr; /* That singleton is awful too. */
37
38 config::Flag<double> cfg_breakpoint{"debug/breakpoint",
39                                     "When non-negative, raise a SIGTRAP after given (simulated) time", -1.0};
40 config::Flag<bool> cfg_verbose_exit{"debug/verbose-exit", "Display the actor status at exit", true};
41
42 xbt_dynar_t get_actors_addr()
43 {
44 #if SIMGRID_HAVE_MC
45   return EngineImpl::get_instance()->get_actors_vector();
46 #else
47   xbt_die("This function is intended to be used when compiling with MC");
48 #endif
49 }
50
51 xbt_dynar_t get_dead_actors_addr()
52 {
53 #if SIMGRID_HAVE_MC
54   return EngineImpl::get_instance()->get_dead_actors_vector();
55 #else
56   xbt_die("This function is intended to be used when compiling with MC");
57 #endif
58 }
59
60 constexpr std::initializer_list<std::pair<const char*, context::ContextFactoryInitializer>> context_factories = {
61 #if HAVE_RAW_CONTEXTS
62     {"raw", &context::raw_factory},
63 #endif
64 #if HAVE_UCONTEXT_CONTEXTS
65     {"ucontext", &context::sysv_factory},
66 #endif
67 #if HAVE_BOOST_CONTEXTS
68     {"boost", &context::boost_factory},
69 #endif
70     {"thread", &context::thread_factory},
71 };
72
73 static_assert(context_factories.size() > 0, "No context factories are enabled for this build");
74
75 // Create the list of possible contexts:
76 static inline std::string contexts_list()
77 {
78   std::string res;
79   std::string sep = "";
80   for (auto const& factory : context_factories) {
81     res += sep + factory.first;
82     sep = ", ";
83   }
84   return res;
85 }
86
87 static config::Flag<std::string> context_factory_name("contexts/factory",
88                                                       (std::string("Possible values: ") + contexts_list()).c_str(),
89                                                       context_factories.begin()->first);
90
91 } // namespace kernel
92 } // namespace simgrid
93
94 XBT_ATTRIB_NORETURN static void inthandler(int)
95 {
96   if (simgrid::kernel::cfg_verbose_exit) {
97     XBT_INFO("CTRL-C pressed. The current status will be displayed before exit (disable that behavior with option "
98              "'debug/verbose-exit').");
99     simgrid::kernel::EngineImpl::get_instance()->display_all_actor_status();
100   } else {
101     XBT_INFO("CTRL-C pressed, exiting. Hiding the current process status since 'debug/verbose-exit' is set to false.");
102   }
103   exit(1);
104 }
105
106 #ifndef _WIN32
107 static void segvhandler(int signum, siginfo_t* siginfo, void* /*context*/)
108 {
109   if ((siginfo->si_signo == SIGSEGV && siginfo->si_code == SEGV_ACCERR) || siginfo->si_signo == SIGBUS) {
110     fprintf(stderr,
111             "Access violation or Bus error detected.\n"
112             "This probably comes from a programming error in your code, or from a stack\n"
113             "overflow. If you are certain of your code, try increasing the stack size\n"
114             "   --cfg=contexts/stack-size:XXX (current size is %u KiB).\n"
115             "\n"
116             "If it does not help, this may have one of the following causes:\n"
117             "a bug in SimGrid, a bug in the OS or a bug in a third-party libraries.\n"
118             "Failing hardware can sometimes generate such errors too.\n"
119             "\n"
120             "If you think you've found a bug in SimGrid, please report it along with a\n"
121             "Minimal Working Example (MWE) reproducing your problem and a full backtrace\n"
122             "of the fault captured with gdb or valgrind.\n",
123             simgrid::kernel::context::stack_size / 1024);
124   } else if (siginfo->si_signo == SIGSEGV) {
125     fprintf(stderr, "Segmentation fault.\n");
126 #if HAVE_SMPI
127     if (smpi_enabled() && smpi_cfg_privatization() == SmpiPrivStrategies::NONE) {
128 #if HAVE_PRIVATIZATION
129       fprintf(stderr, "Try to enable SMPI variable privatization with --cfg=smpi/privatization:yes.\n");
130 #else
131       fprintf(stderr, "Sadly, your system does not support --cfg=smpi/privatization:yes (yet).\n");
132 #endif /* HAVE_PRIVATIZATION */
133     }
134 #endif /* HAVE_SMPI */
135   }
136   std::raise(signum);
137 }
138
139 /**
140  * Install signal handler for SIGSEGV.  Check that nobody has already installed
141  * its own handler.  For example, the Java VM does this.
142  */
143 static void install_segvhandler()
144 {
145   stack_t old_stack;
146
147   if (simgrid::kernel::context::Context::install_sigsegv_stack(&old_stack, true) == -1) {
148     XBT_WARN("Failed to register alternate signal stack: %s", strerror(errno));
149     return;
150   }
151   if (not(old_stack.ss_flags & SS_DISABLE)) {
152     XBT_DEBUG("An alternate stack was already installed (sp=%p, size=%zu, flags=%x). Restore it.", old_stack.ss_sp,
153               old_stack.ss_size, (unsigned)old_stack.ss_flags);
154     sigaltstack(&old_stack, nullptr);
155   }
156
157   struct sigaction action;
158   struct sigaction old_action;
159   action.sa_sigaction = &segvhandler;
160   action.sa_flags     = SA_ONSTACK | SA_RESETHAND | SA_SIGINFO;
161   sigemptyset(&action.sa_mask);
162
163   /* Linux tend to raise only SIGSEGV where other systems also raise SIGBUS on severe error */
164   for (int sig : {SIGSEGV, SIGBUS}) {
165     if (sigaction(sig, &action, &old_action) == -1) {
166       XBT_WARN("Failed to register signal handler for signal %d: %s", sig, strerror(errno));
167       continue;
168     }
169     if ((old_action.sa_flags & SA_SIGINFO) || old_action.sa_handler != SIG_DFL) {
170       XBT_DEBUG("A signal handler was already installed for signal %d (%p). Restore it.", sig,
171                 (old_action.sa_flags & SA_SIGINFO) ? (void*)old_action.sa_sigaction : (void*)old_action.sa_handler);
172       sigaction(sig, &old_action, nullptr);
173     }
174   }
175 }
176
177 #endif /* _WIN32 */
178
179 namespace simgrid {
180 namespace kernel {
181
182 EngineImpl::~EngineImpl()
183 {
184   /* Since hosts_ is a std::map, the hosts are destroyed in the lexicographic order, which ensures that the output is
185    * reproducible.
186    */
187   while (not hosts_.empty())
188     hosts_.begin()->second->destroy();
189
190   /* Also delete the other data */
191   delete netzone_root_;
192   for (auto const& kv : netpoints_)
193     delete kv.second;
194
195   while (not links_.empty())
196     links_.begin()->second->destroy();
197
198   for (auto const& kv : mailboxes_)
199     delete kv.second;
200
201     /* Free the remaining data structures */
202 #if SIMGRID_HAVE_MC
203   xbt_dynar_free(&actors_vector_);
204   xbt_dynar_free(&dead_actors_vector_);
205 #endif
206   /* clear models before freeing handle, network models can use external callback defined in the handle */
207   models_prio_.clear();
208 }
209
210 void EngineImpl::initialize(int* argc, char** argv)
211 {
212   xbt_assert(EngineImpl::instance_ == nullptr,
213              "It is currently forbidden to create more than one instance of kernel::EngineImpl");
214   EngineImpl::instance_ = this;
215 #if SIMGRID_HAVE_MC
216   // The communication initialization is done ASAP, as we need to get some init parameters from the MC for different
217   // layers. But simix_global needs to be created, as we send the address of some of its fields to the MC that wants to
218   // read them directly.
219   simgrid::mc::AppSide::initialize();
220 #endif
221
222   if (xbt_initialized == 0) {
223     xbt_init(argc, argv);
224
225     sg_config_init(argc, argv);
226   }
227
228   instance_->context_mod_init();
229
230   /* Prepare to display some more info when dying on Ctrl-C pressing */
231   std::signal(SIGINT, inthandler);
232
233 #ifndef _WIN32
234   install_segvhandler();
235 #endif
236
237   /* register a function to be called by SURF after the environment creation */
238   sg_platf_init();
239   s4u::Engine::on_platform_created.connect(surf_presolve);
240
241   if (config::get_value<bool>("debug/clean-atexit"))
242     atexit(shutdown);
243 }
244
245 void EngineImpl::context_mod_init() const
246 {
247   xbt_assert(not instance_->has_context_factory());
248
249 #if HAVE_SMPI && (defined(__APPLE__) || defined(__NetBSD__))
250   smpi_init_options_internal(false);
251   std::string priv = config::get_value<std::string>("smpi/privatization");
252   if (context_factory_name == "thread" && (priv == "dlopen" || priv == "yes" || priv == "default" || priv == "1")) {
253     XBT_WARN("dlopen+thread broken on Apple and BSD. Switching to raw contexts.");
254     context_factory_name = "raw";
255   }
256 #endif
257
258 #if HAVE_SMPI && defined(__FreeBSD__)
259   smpi_init_options_internal(false);
260   if (context_factory_name == "thread" && config::get_value<std::string>("smpi/privatization") != "no") {
261     XBT_WARN("mmap broken on FreeBSD, but dlopen+thread broken too. Switching to dlopen+raw contexts.");
262     context_factory_name = "raw";
263   }
264 #endif
265
266   /* select the context factory to use to create the contexts */
267   if (context::factory_initializer != nullptr) { // Give Java a chance to hijack the factory mechanism
268     instance_->set_context_factory(context::factory_initializer());
269     return;
270   }
271   /* use the factory specified by --cfg=contexts/factory:value */
272   for (auto const& factory : context_factories)
273     if (context_factory_name == factory.first) {
274       instance_->set_context_factory(factory.second());
275       break;
276     }
277
278   if (not instance_->has_context_factory()) {
279     XBT_ERROR("Invalid context factory specified. Valid factories on this machine:");
280 #if HAVE_RAW_CONTEXTS
281     XBT_ERROR("  raw: high performance context factory implemented specifically for SimGrid");
282 #else
283     XBT_ERROR("  (raw contexts were disabled at compilation time on this machine -- check configure logs for details)");
284 #endif
285 #if HAVE_UCONTEXT_CONTEXTS
286     XBT_ERROR("  ucontext: classical system V contexts (implemented with makecontext, swapcontext and friends)");
287 #else
288     XBT_ERROR("  (ucontext was disabled at compilation time on this machine -- check configure logs for details)");
289 #endif
290 #if HAVE_BOOST_CONTEXTS
291     XBT_ERROR("  boost: this uses the boost libraries context implementation");
292 #else
293     XBT_ERROR("  (boost was disabled at compilation time on this machine -- check configure logs for details. Did you "
294               "install the libboost-context-dev package?)");
295 #endif
296     XBT_ERROR("  thread: slow portability layer using pthreads as provided by gcc");
297     xbt_die("Please use a valid factory.");
298   }
299 }
300
301 void EngineImpl::shutdown()
302 {
303   if (EngineImpl::instance_ == nullptr)
304     return;
305   XBT_DEBUG("EngineImpl::shutdown() called. Simulation's over.");
306 #if HAVE_SMPI
307   if (not instance_->actor_list_.empty()) {
308     if (smpi_process()->initialized()) {
309       xbt_die("Process exited without calling MPI_Finalize - Killing simulation");
310     } else {
311       XBT_WARN("Process called exit when leaving - Skipping cleanups");
312       return;
313     }
314   }
315 #endif
316
317   if (instance_->has_actors_to_run() && simgrid_get_clock() <= 0.0) {
318     XBT_CRITICAL("   ");
319     XBT_CRITICAL("The time is still 0, and you still have processes ready to run.");
320     XBT_CRITICAL("It seems that you forgot to run the simulation that you setup.");
321     xbt_die("Bailing out to avoid that stop-before-start madness. Please fix your code.");
322   }
323
324   /* Kill all actors (but maestro) */
325   instance_->maestro_->kill_all();
326   instance_->run_all_actors();
327   instance_->empty_trash();
328
329   /* Let's free maestro now */
330   instance_->destroy_maestro();
331
332   /* Finish context module and SURF */
333   instance_->destroy_context_factory();
334
335   while (not timer::kernel_timers().empty()) {
336     delete timer::kernel_timers().top().second;
337     timer::kernel_timers().pop();
338   }
339
340   tmgr_finalize();
341   sg_platf_exit();
342
343   delete instance_;
344   instance_ = nullptr;
345 }
346
347 void EngineImpl::load_platform(const std::string& platf)
348 {
349   double start = xbt_os_time();
350   if (boost::algorithm::ends_with(platf, ".so") or boost::algorithm::ends_with(platf, ".dylib")) {
351 #ifdef _WIN32
352     xbt_die("loading platform through shared library isn't supported on windows");
353 #else
354     void* handle = dlopen(platf.c_str(), RTLD_LAZY);
355     xbt_assert(handle, "Impossible to open platform file: %s", platf.c_str());
356     platf_handle_           = std::unique_ptr<void, std::function<int(void*)>>(handle, dlclose);
357     using load_fct_t = void (*)(const simgrid::s4u::Engine&);
358     auto callable           = (load_fct_t)dlsym(platf_handle_.get(), "load_platform");
359     const char* dlsym_error = dlerror();
360     xbt_assert(not dlsym_error, "Error: %s", dlsym_error);
361     callable(*simgrid::s4u::Engine::get_instance());
362 #endif /* _WIN32 */
363   } else {
364     parse_platform_file(platf);
365   }
366
367   double end = xbt_os_time();
368   XBT_DEBUG("PARSE TIME: %g", (end - start));
369 }
370
371 void EngineImpl::load_deployment(const std::string& file) const
372 {
373   sg_platf_exit();
374   sg_platf_init();
375
376   surf_parse_open(file);
377   surf_parse();
378   surf_parse_close();
379 }
380
381 void EngineImpl::register_function(const std::string& name, const actor::ActorCodeFactory& code)
382 {
383   registered_functions[name] = code;
384 }
385 void EngineImpl::register_default(const actor::ActorCodeFactory& code)
386 {
387   default_function = code;
388 }
389
390 void EngineImpl::add_model(std::shared_ptr<resource::Model> model, const std::vector<resource::Model*>& dependencies)
391 {
392   auto model_name = model->get_name();
393   xbt_assert(models_prio_.find(model_name) == models_prio_.end(),
394              "Model %s already exists, use model.set_name() to change its name", model_name.c_str());
395
396   for (const auto dep : dependencies) {
397     xbt_assert(models_prio_.find(dep->get_name()) != models_prio_.end(),
398                "Model %s doesn't exists. Impossible to use it as dependency.", dep->get_name().c_str());
399   }
400   models_.push_back(model.get());
401   models_prio_[model_name] = std::move(model);
402 }
403
404 void EngineImpl::add_split_duplex_link(const std::string& name, std::unique_ptr<resource::SplitDuplexLinkImpl> link)
405 {
406   split_duplex_links_[name] = std::move(link);
407 }
408
409 /** Wake up all actors waiting for a Surf action to finish */
410 void EngineImpl::wake_all_waiting_actors() const
411 {
412   for (auto const& model : models_) {
413     XBT_DEBUG("Handling the failed actions (if any)");
414     while (auto* action = model->extract_failed_action()) {
415       XBT_DEBUG("   Handling Action %p", action);
416       if (action->get_activity() != nullptr)
417         activity::ActivityImplPtr(action->get_activity())->post();
418     }
419     XBT_DEBUG("Handling the terminated actions (if any)");
420     while (auto* action = model->extract_done_action()) {
421       XBT_DEBUG("   Handling Action %p", action);
422       if (action->get_activity() == nullptr)
423         XBT_DEBUG("probably vcpu's action %p, skip", action);
424       else
425         activity::ActivityImplPtr(action->get_activity())->post();
426     }
427   }
428 }
429 /**
430  * @brief Executes the actors in actors_to_run.
431  *
432  * The actors in actors_to_run are run (in parallel if possible). On exit, actors_to_run is empty, and actors_that_ran
433  * contains the list of actors that just ran.  The two lists are swapped so, be careful when using them before and after
434  * a call to this function.
435  */
436 void EngineImpl::run_all_actors()
437 {
438   instance_->get_context_factory()->run_all();
439
440   actors_to_run_.swap(actors_that_ran_);
441   actors_to_run_.clear();
442 }
443
444 actor::ActorImpl* EngineImpl::get_actor_by_pid(aid_t pid)
445 {
446   auto item = actor_list_.find(pid);
447   if (item != actor_list_.end())
448     return item->second;
449
450   // Search the trash
451   for (auto& a : actors_to_destroy_)
452     if (a.get_pid() == pid)
453       return &a;
454   return nullptr; // Not found, even in the trash
455 }
456
457 /** Execute all the tasks that are queued, e.g. `.then()` callbacks of futures. */
458 bool EngineImpl::execute_tasks()
459 {
460   if (tasks.empty())
461     return false;
462
463   std::vector<xbt::Task<void()>> tasksTemp;
464   do {
465     // We don't want the callbacks to modify the vector we are iterating over:
466     tasks.swap(tasksTemp);
467
468     // Execute all the queued tasks:
469     for (auto& task : tasksTemp)
470       task();
471
472     tasksTemp.clear();
473   } while (not tasks.empty());
474
475   return true;
476 }
477
478 void EngineImpl::remove_daemon(actor::ActorImpl* actor)
479 {
480   auto it = daemons_.find(actor);
481   xbt_assert(it != daemons_.end(), "The dying daemon is not a daemon after all. Please report that bug.");
482   daemons_.erase(it);
483 }
484
485 void EngineImpl::add_actor_to_run_list_no_check(actor::ActorImpl* actor)
486 {
487   XBT_DEBUG("Inserting [%p] %s(%s) in the to_run list", actor, actor->get_cname(), actor->get_host()->get_cname());
488   actors_to_run_.push_back(actor);
489 }
490
491 void EngineImpl::add_actor_to_run_list(actor::ActorImpl* actor)
492 {
493   if (std::find(begin(actors_to_run_), end(actors_to_run_), actor) != end(actors_to_run_)) {
494     XBT_DEBUG("Actor %s is already in the to_run list", actor->get_cname());
495   } else {
496     XBT_DEBUG("Inserting [%p] %s(%s) in the to_run list", actor, actor->get_cname(), actor->get_host()->get_cname());
497     actors_to_run_.push_back(actor);
498   }
499 }
500 void EngineImpl::empty_trash()
501 {
502   while (not actors_to_destroy_.empty()) {
503     actor::ActorImpl* actor = &actors_to_destroy_.front();
504     actors_to_destroy_.pop_front();
505     XBT_DEBUG("Getting rid of %s (refcount: %d)", actor->get_cname(), actor->get_refcount());
506     intrusive_ptr_release(actor);
507   }
508 #if SIMGRID_HAVE_MC
509   xbt_dynar_reset(dead_actors_vector_);
510 #endif
511 }
512
513 void EngineImpl::display_all_actor_status() const
514 {
515   XBT_INFO("%zu actors are still running, waiting for something.", actor_list_.size());
516   /*  List the actors and their state */
517   XBT_INFO("Legend of the following listing: \"Actor <pid> (<name>@<host>): <status>\"");
518   for (auto const& kv : actor_list_) {
519     actor::ActorImpl* actor = kv.second;
520
521     if (actor->waiting_synchro_) {
522       const char* synchro_description = "unknown";
523
524       if (boost::dynamic_pointer_cast<kernel::activity::ExecImpl>(actor->waiting_synchro_) != nullptr)
525         synchro_description = "execution";
526
527       if (boost::dynamic_pointer_cast<kernel::activity::CommImpl>(actor->waiting_synchro_) != nullptr)
528         synchro_description = "communication";
529
530       if (boost::dynamic_pointer_cast<kernel::activity::SleepImpl>(actor->waiting_synchro_) != nullptr)
531         synchro_description = "sleeping";
532
533       if (boost::dynamic_pointer_cast<kernel::activity::RawImpl>(actor->waiting_synchro_) != nullptr)
534         synchro_description = "synchronization";
535
536       if (boost::dynamic_pointer_cast<kernel::activity::IoImpl>(actor->waiting_synchro_) != nullptr)
537         synchro_description = "I/O";
538
539       XBT_INFO("Actor %ld (%s@%s): waiting for %s activity %#zx (%s) in state %d to finish", actor->get_pid(),
540                actor->get_cname(), actor->get_host()->get_cname(), synchro_description,
541                (xbt_log_no_loc ? (size_t)0xDEADBEEF : (size_t)actor->waiting_synchro_.get()),
542                actor->waiting_synchro_->get_cname(), (int)actor->waiting_synchro_->state_);
543     } else {
544       XBT_INFO("Actor %ld (%s@%s) simcall %s", actor->get_pid(), actor->get_cname(), actor->get_host()->get_cname(),
545                SIMIX_simcall_name(actor->simcall_));
546     }
547   }
548 }
549
550 void EngineImpl::run()
551 {
552   if (MC_record_replay_is_active()) {
553     mc::replay(MC_record_path());
554     empty_trash();
555     return;
556   }
557
558   double time = 0;
559
560   do {
561     XBT_DEBUG("New Schedule Round; size(queue)=%zu", actors_to_run_.size());
562
563     if (cfg_breakpoint >= 0.0 && simgrid_get_clock() >= cfg_breakpoint) {
564       XBT_DEBUG("Breakpoint reached (%g)", cfg_breakpoint.get());
565       cfg_breakpoint = -1.0;
566 #ifdef SIGTRAP
567       std::raise(SIGTRAP);
568 #else
569       std::raise(SIGABRT);
570 #endif
571     }
572
573     execute_tasks();
574
575     while (not actors_to_run_.empty()) {
576       XBT_DEBUG("New Sub-Schedule Round; size(queue)=%zu", actors_to_run_.size());
577
578       /* Run all actors that are ready to run, possibly in parallel */
579       run_all_actors();
580
581       /* answer sequentially and in a fixed arbitrary order all the simcalls that were issued during that sub-round */
582
583       /* WARNING, the order *must* be fixed or you'll jeopardize the simulation reproducibility (see RR-7653) */
584
585       /* Here, the order is ok because:
586        *
587        *   Short proof: only maestro adds stuff to the actors_to_run array, so the execution order of user contexts do
588        *   not impact its order.
589        *
590        *   Long proof: actors remain sorted through an arbitrary (implicit, complex but fixed) order in all cases.
591        *
592        *   - if there is no kill during the simulation, actors remain sorted according by their PID.
593        *     Rationale: This can be proved inductively.
594        *        Assume that actors_to_run is sorted at a beginning of one round (it is at round 0: the deployment file
595        *        is parsed linearly).
596        *        Let's show that it is still so at the end of this round.
597        *        - if an actor is added when being created, that's from maestro. It can be either at startup
598        *          time (and then in PID order), or in response to a process_create simcall. Since simcalls are handled
599        *          in arbitrary order (inductive hypothesis), we are fine.
600        *        - If an actor is added because it's getting killed, its subsequent actions shouldn't matter
601        *        - If an actor gets added to actors_to_run because one of their blocking action constituting the meat
602        *          of a simcall terminates, we're still good. Proof:
603        *          - You are added from ActorImpl::simcall_answer() only. When this function is called depends on the
604        *            resource kind (network, cpu, disk, whatever), but the same arguments hold. Let's take communications
605        *            as an example.
606        *          - For communications, this function is called from SIMIX_comm_finish().
607        *            This function itself don't mess with the order since simcalls are handled in FIFO order.
608        *            The function is called:
609        *            - before the comm starts (invalid parameters, or resource already dead or whatever).
610        *              The order then trivial holds since maestro didn't interrupt its handling of the simcall yet
611        *            - because the communication failed or were canceled after startup. In this case, it's called from
612        *              the function we are in, by the chunk:
613        *                       set = model->states.failed_action_set;
614        *                       while ((synchro = extract(set)))
615        *                          SIMIX_simcall_post((smx_synchro_t) synchro->data);
616        *              This order is also fixed because it depends of the order in which the surf actions were
617        *              added to the system, and only maestro can add stuff this way, through simcalls.
618        *              We thus use the inductive hypothesis once again to conclude that the order in which synchros are
619        *              popped out of the set does not depend on the user code's execution order.
620        *            - because the communication terminated. In this case, synchros are served in the order given by
621        *                       set = model->states.done_action_set;
622        *                       while ((synchro = extract(set)))
623        *                          SIMIX_simcall_post((smx_synchro_t) synchro->data);
624        *              and the argument is very similar to the previous one.
625        *            So, in any case, the orders of calls to CommImpl::finish() do not depend on the order in which user
626        *            actors are executed.
627        *          So, in any cases, the orders of actors within actors_to_run do not depend on the order in which
628        *          user actors were executed previously.
629        *     So, if there is no killing in the simulation, the simulation reproducibility is not jeopardized.
630        *   - If there is some actor killings, the order is changed by this decision that comes from user-land
631        *     But this decision may not have been motivated by a situation that were different because the simulation is
632        *     not reproducible.
633        *     So, even the order change induced by the actor killing is perfectly reproducible.
634        *
635        *   So science works, bitches [http://xkcd.com/54/].
636        *
637        *   We could sort the actors_that_ran array completely so that we can describe the order in which simcalls are
638        *   handled (like "according to the PID of issuer"), but it's not mandatory (order is fixed already even if
639        *   unfriendly).
640        *   That would thus be a pure waste of time.
641        */
642
643       for (auto const& actor : actors_that_ran_) {
644         if (actor->simcall_.call_ != simix::Simcall::NONE) {
645           actor->simcall_handle(0);
646         }
647       }
648
649       execute_tasks();
650       do {
651         wake_all_waiting_actors();
652       } while (execute_tasks());
653
654       /* If only daemon actors remain, cancel their actions, mark them to die and reschedule them */
655       if (actor_list_.size() == daemons_.size())
656         for (auto const& dmon : daemons_) {
657           XBT_DEBUG("Kill %s", dmon->get_cname());
658           maestro_->kill(dmon);
659         }
660     }
661
662     time = timer::Timer::next();
663     if (time > -1.0 || not actor_list_.empty()) {
664       XBT_DEBUG("Calling surf_solve");
665       time = surf_solve(time);
666       XBT_DEBUG("Moving time ahead : %g", time);
667     }
668
669     /* Notify all the hosts that have failed */
670     /* FIXME: iterate through the list of failed host and mark each of them */
671     /* as failed. On each host, signal all the running actors with host_fail */
672
673     // Execute timers and tasks until there isn't anything to be done:
674     bool again = false;
675     do {
676       again = timer::Timer::execute_all();
677       if (execute_tasks())
678         again = true;
679       wake_all_waiting_actors();
680     } while (again);
681
682     /* Clean actors to destroy */
683     empty_trash();
684
685     XBT_DEBUG("### time %f, #actors %zu, #to_run %zu", time, actor_list_.size(), actors_to_run_.size());
686
687     if (time < 0. && actors_to_run_.empty() && not actor_list_.empty()) {
688       if (actor_list_.size() <= daemons_.size()) {
689         XBT_CRITICAL("Oops! Daemon actors cannot do any blocking activity (communications, synchronization, etc) "
690                      "once the simulation is over. Please fix your on_exit() functions.");
691       } else {
692         XBT_CRITICAL("Oops! Deadlock or code not perfectly clean.");
693       }
694       display_all_actor_status();
695       simgrid::s4u::Engine::on_deadlock();
696       for (auto const& kv : actor_list_) {
697         XBT_DEBUG("Kill %s", kv.second->get_cname());
698         maestro_->kill(kv.second);
699       }
700     }
701   } while (time > -1.0 || has_actors_to_run());
702
703   if (not actor_list_.empty())
704     THROW_IMPOSSIBLE;
705
706   simgrid::s4u::Engine::on_simulation_end();
707 }
708 } // namespace kernel
709 } // namespace simgrid
710
711 void SIMIX_run() // XBT_ATTRIB_DEPRECATED_v332
712 {
713   simgrid::kernel::EngineImpl::get_instance()->run();
714 }