Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Compile the safe part of MC in default mode too
[simgrid.git] / src / kernel / EngineImpl.cpp
1 /* Copyright (c) 2016-2023. 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
12 #include "src/kernel/EngineImpl.hpp"
13 #include "src/kernel/resource/StandardLinkImpl.hpp"
14 #include "src/kernel/resource/profile/Profile.hpp"
15 #include "src/kernel/xml/platf.hpp"
16 #include "src/mc/mc.h"
17 #include "src/mc/mc_record.hpp"
18 #include "src/mc/mc_replay.hpp"
19 #include "src/mc/remote/AppSide.hpp"
20 #include "src/simgrid/math_utils.h"
21 #include "src/simgrid/sg_config.hpp"
22 #include "src/smpi/include/smpi_actor.hpp"
23
24 #include "xbt/log.hpp"
25
26 #include <boost/algorithm/string/predicate.hpp>
27 #include <dlfcn.h>
28
29 XBT_LOG_NEW_DEFAULT_CATEGORY(ker_engine, "Logging specific to Engine (kernel)");
30
31 namespace simgrid::kernel {
32 double EngineImpl::now_           = 0.0;
33 EngineImpl* EngineImpl::instance_ = nullptr; /* That singleton is awful too. */
34
35 config::Flag<double> cfg_breakpoint{"debug/breakpoint",
36                                     "When non-negative, raise a SIGTRAP after given (simulated) time", -1.0};
37 config::Flag<bool> cfg_verbose_exit{"debug/verbose-exit", "Display the actor status at exit", true};
38
39 constexpr std::initializer_list<std::pair<const char*, context::ContextFactory* (*)()>> context_factories = {
40 #if HAVE_RAW_CONTEXTS
41     {"raw", &context::raw_factory},
42 #endif
43 #if HAVE_UCONTEXT_CONTEXTS
44     {"ucontext", &context::sysv_factory},
45 #endif
46 #if HAVE_BOOST_CONTEXTS
47     {"boost", &context::boost_factory},
48 #endif
49     {"thread", &context::thread_factory},
50 };
51
52 static_assert(context_factories.size() > 0, "No context factories are enabled for this build");
53
54 // Create the list of possible contexts:
55 static inline std::string contexts_list()
56 {
57   std::string res;
58   std::string sep = "";
59   for (auto const& [factory_name, _] : context_factories) {
60     res += sep + factory_name;
61     sep = ", ";
62   }
63   return res;
64 }
65
66 static config::Flag<std::string> context_factory_name("contexts/factory",
67                                                       ("Possible values: " + contexts_list()).c_str(),
68                                                       context_factories.begin()->first);
69
70 } // namespace simgrid::kernel
71
72 XBT_ATTRIB_NORETURN static void inthandler(int)
73 {
74   if (simgrid::kernel::cfg_verbose_exit) {
75     XBT_INFO("CTRL-C pressed. The current status will be displayed before exit (disable that behavior with option "
76              "'debug/verbose-exit').");
77     simgrid::kernel::EngineImpl::get_instance()->display_all_actor_status();
78   } else {
79     XBT_INFO("CTRL-C pressed, exiting. Hiding the current process status since 'debug/verbose-exit' is set to false.");
80   }
81   exit(1);
82 }
83
84 static void segvhandler(int signum, siginfo_t* siginfo, void* /*context*/)
85 {
86   if ((siginfo->si_signo == SIGSEGV && siginfo->si_code == SEGV_ACCERR) || siginfo->si_signo == SIGBUS) {
87     fprintf(stderr,
88             "Access violation or Bus error detected.\n"
89             "This probably comes from a programming error in your code, or from a stack\n"
90             "overflow. If you are certain of your code, try increasing the stack size\n"
91             "   --cfg=contexts/stack-size:XXX (current size is %u KiB).\n"
92             "\n"
93             "If it does not help, this may have one of the following causes:\n"
94             "a bug in SimGrid, a bug in the OS or a bug in a third-party libraries.\n"
95             "Failing hardware can sometimes generate such errors too.\n"
96             "\n"
97             "If you think you've found a bug in SimGrid, please report it along with a\n"
98             "Minimal Working Example (MWE) reproducing your problem and a full backtrace\n"
99             "of the fault captured with gdb or valgrind.\n",
100             simgrid::kernel::context::Context::stack_size / 1024);
101   } else if (siginfo->si_signo == SIGSEGV) {
102     fprintf(stderr, "Segmentation fault.\n");
103 #if HAVE_SMPI
104     if (SMPI_is_inited() && smpi_cfg_privatization() == SmpiPrivStrategies::NONE) {
105 #if HAVE_PRIVATIZATION
106       fprintf(stderr, "Try to enable SMPI variable privatization with --cfg=smpi/privatization:yes.\n");
107 #else
108       fprintf(stderr, "Sadly, your system does not support --cfg=smpi/privatization:yes (yet).\n");
109 #endif /* HAVE_PRIVATIZATION */
110     }
111 #endif /* HAVE_SMPI */
112   }
113   std::raise(signum);
114 }
115
116 static void install_signal_handlers()
117 {
118   /* Install signal handler for SIGINT */
119   std::signal(SIGINT, inthandler);
120
121   /* Install signal handler for SIGSEGV */
122   if (simgrid::kernel::context::Context::install_sigsegv_stack(true) == -1) {
123     XBT_WARN("Failed to register alternate signal stack: %s", strerror(errno));
124     return;
125   }
126
127   struct sigaction action;
128   action.sa_sigaction = &segvhandler;
129   action.sa_flags     = SA_ONSTACK | SA_RESETHAND | SA_SIGINFO;
130   sigemptyset(&action.sa_mask);
131
132   /* Linux tend to raise only SIGSEGV where other systems also raise SIGBUS on severe error */
133   for (int sig : {SIGSEGV, SIGBUS}) {
134     if (sigaction(sig, &action, nullptr) == -1)
135       XBT_WARN("Failed to register signal handler for signal %d: %s", sig, strerror(errno));
136   }
137 }
138
139 static simgrid::config::Flag<bool> cfg_dbg_clean_atexit{
140     "debug/clean-atexit", "Whether to cleanup SimGrid at exit. Disable it if your code segfaults after its end.", true};
141
142 namespace simgrid::kernel {
143
144 EngineImpl::~EngineImpl()
145 {
146   /* Also delete the other data */
147   delete netzone_root_;
148   for (auto const& [_, netpoint] : netpoints_)
149     delete netpoint;
150
151   for (auto const& [_, mailbox] : mailboxes_)
152     delete mailbox;
153
154   /* Kill all actors (but maestro) */
155   maestro_->kill_all();
156   run_all_actors();
157   empty_trash();
158
159   delete maestro_;
160   delete context_factory_;
161
162   /* clear models before freeing handle, network models can use external callback defined in the handle */
163   models_prio_.clear();
164 }
165
166 void EngineImpl::initialize(int* argc, char** argv)
167 {
168   xbt_assert(EngineImpl::instance_ == nullptr,
169              "It is currently forbidden to create more than one instance of kernel::EngineImpl");
170   EngineImpl::instance_ = this;
171   // The communication initialization is done ASAP, as we need to get some init parameters from the MC for different
172   // layers. But instance_ needs to be created, as we send the address of some of its fields to the MC that wants to
173   // read them directly.
174   simgrid::mc::AppSide::initialize();
175
176   if (static bool inited = false; not inited) {
177     inited = true;
178     xbt_log_init(argc, argv);
179
180     simgrid::xbt::install_exception_handler();
181
182     sg_config_init(argc, argv);
183   }
184
185   cmdline_.assign(argv, argv + *argc);
186
187   instance_->context_mod_init();
188
189   install_signal_handlers();
190
191   /* register a function to be called after the environment creation */
192   s4u::Engine::on_platform_created_cb([this]() { this->presolve(); });
193
194   if (cfg_dbg_clean_atexit)
195     atexit(shutdown);
196 }
197
198 void EngineImpl::context_mod_init() const
199 {
200   xbt_assert(not instance_->has_context_factory());
201
202 #if HAVE_SMPI && defined(__NetBSD__)
203   smpi_init_options_internal(false);
204   std::string priv = config::get_value<std::string>("smpi/privatization");
205   if (context_factory_name == "thread" && (priv == "dlopen" || priv == "yes" || priv == "default" || priv == "1")) {
206     XBT_WARN("dlopen+thread broken on Apple and BSD. Switching to raw contexts.");
207     context_factory_name = "raw";
208   }
209 #endif
210
211 #if HAVE_SMPI && defined(__FreeBSD__)
212   smpi_init_options_internal(false);
213   if (context_factory_name == "thread" && config::get_value<std::string>("smpi/privatization") != "no") {
214     XBT_WARN("mmap broken on FreeBSD, but dlopen+thread broken too. Switching to dlopen+raw contexts.");
215     context_factory_name = "raw";
216   }
217 #endif
218
219   /* use the factory specified by --cfg=contexts/factory:value */
220   for (auto const& [factory_name, factory] : context_factories)
221     if (context_factory_name == factory_name) {
222       instance_->set_context_factory(factory());
223       break;
224     }
225
226   if (not instance_->has_context_factory()) {
227     XBT_ERROR("Invalid context factory specified. Valid factories on this machine:");
228 #if HAVE_RAW_CONTEXTS
229     XBT_ERROR("  raw: high performance context factory implemented specifically for SimGrid");
230 #else
231     XBT_ERROR("  (raw contexts were disabled at compilation time on this machine -- check configure logs for details)");
232 #endif
233 #if HAVE_UCONTEXT_CONTEXTS
234     XBT_ERROR("  ucontext: classical system V contexts (implemented with makecontext, swapcontext and friends)");
235 #else
236     XBT_ERROR("  (ucontext was disabled at compilation time on this machine -- check configure logs for details)");
237 #endif
238 #if HAVE_BOOST_CONTEXTS
239     XBT_ERROR("  boost: this uses the boost libraries context implementation");
240 #else
241     XBT_ERROR("  (boost was disabled at compilation time on this machine -- check configure logs for details. Did you "
242               "install the libboost-context-dev package?)");
243 #endif
244     XBT_ERROR("  thread: slow portability layer using standard threads as provided by libstdc");
245     xbt_die("Please use a valid factory.");
246   }
247 }
248
249 void EngineImpl::shutdown()
250 {
251   if (EngineImpl::instance_ == nullptr)
252     return;
253   XBT_DEBUG("EngineImpl::shutdown() called. Simulation's over.");
254 #if HAVE_SMPI
255   if (not instance_->actor_list_.empty()) {
256     if (smpi_process() && smpi_process()->initialized()) {
257       xbt_die("Process exited without calling MPI_Finalize - Killing simulation");
258     } else {
259       XBT_WARN("Process called exit when leaving - Skipping cleanups");
260       return;
261     }
262   }
263 #endif
264
265   if (instance_->has_actors_to_run() && simgrid_get_clock() <= 0.0) {
266     XBT_CRITICAL("   ");
267     XBT_CRITICAL("The time is still 0, and you still have processes ready to run.");
268     XBT_CRITICAL("It seems that you forgot to run the simulation that you setup.");
269     xbt_die("Bailing out to avoid that stop-before-start madness. Please fix your code.");
270   }
271
272   while (not timer::kernel_timers().empty()) {
273     delete timer::kernel_timers().top().second;
274     timer::kernel_timers().pop();
275   }
276
277   tmgr_finalize();
278   sg_platf_parser_finalize();
279
280   delete instance_;
281   instance_ = nullptr;
282 }
283
284 void EngineImpl::seal_platform() const
285 {
286   /* Seal only once */
287   static bool sealed = false;
288   if (sealed)
289     return;
290   sealed = true;
291
292   /* seal netzone root, recursively seal children netzones, hosts and disks */
293   netzone_root_->seal();
294 }
295
296 void EngineImpl::load_platform(const std::string& platf)
297 {
298   double start = xbt_os_time();
299   if (boost::algorithm::ends_with(platf, ".so") || boost::algorithm::ends_with(platf, ".dylib")) {
300     void* handle = dlopen(platf.c_str(), RTLD_LAZY);
301     xbt_assert(handle, "Impossible to open platform file: %s", platf.c_str());
302     platf_handle_           = std::unique_ptr<void, std::function<int(void*)>>(handle, dlclose);
303     using load_fct_t = void (*)(const simgrid::s4u::Engine&);
304     auto callable           = (load_fct_t)dlsym(platf_handle_.get(), "load_platform");
305     const char* dlsym_error = dlerror();
306     xbt_assert(not dlsym_error, "Error: %s", dlsym_error);
307     callable(*simgrid::s4u::Engine::get_instance());
308   } else {
309     parse_platform_file(platf);
310   }
311
312   double end = xbt_os_time();
313   XBT_DEBUG("PARSE TIME: %g", (end - start));
314 }
315
316 void EngineImpl::load_deployment(const std::string& file) const
317 {
318   sg_platf_parser_finalize();
319
320   simgrid_parse_open(file);
321   simgrid_parse();
322   simgrid_parse_close();
323 }
324
325 void EngineImpl::register_function(const std::string& name, const actor::ActorCodeFactory& code)
326 {
327   registered_functions[name] = code;
328 }
329 void EngineImpl::register_default(const actor::ActorCodeFactory& code)
330 {
331   default_function = code;
332 }
333
334 void EngineImpl::add_model(std::shared_ptr<resource::Model> model, const std::vector<resource::Model*>& dependencies)
335 {
336   auto model_name = model->get_name();
337   xbt_assert(models_prio_.find(model_name) == models_prio_.end(),
338              "Model %s already exists, use model.set_name() to change its name", model_name.c_str());
339
340   for (const auto* dep : dependencies) {
341     xbt_assert(models_prio_.find(dep->get_name()) != models_prio_.end(),
342                "Model %s doesn't exists. Impossible to use it as dependency.", dep->get_name().c_str());
343   }
344   models_.push_back(model.get());
345   models_prio_[model_name] = std::move(model);
346 }
347
348 /** Wake up all actors waiting for an action to finish */
349 void EngineImpl::handle_ended_actions() const
350 {
351   for (auto const& model : models_) {
352     XBT_DEBUG("Handling the failed actions (if any)");
353     while (auto* action = model->extract_failed_action()) {
354       XBT_DEBUG("   Handling Action %p", action);
355       if (action->get_activity() != nullptr) { // Skip vcpu actions
356         // Action failures are not automatically reported when the action is started by maestro (as in SimDAG)
357         if (action->get_activity()->get_actor() == maestro_)
358           action->get_activity()->get_iface()->complete(s4u::Activity::State::FAILED);
359
360         activity::ActivityImplPtr(action->get_activity())->finish();
361       }
362     }
363     XBT_DEBUG("Handling the terminated actions (if any)");
364     while (auto* action = model->extract_done_action()) {
365       XBT_DEBUG("   Handling Action %p", action);
366       if (action->get_activity() != nullptr) {
367         // Action termination are not automatically reported when the action is started by maestro (as in SimDAG)
368         action->get_activity()->set_finish_time(action->get_finish_time());
369
370         if (action->get_activity()->get_actor() == maestro_)
371           action->get_activity()->get_iface()->complete(s4u::Activity::State::FINISHED);
372
373         activity::ActivityImplPtr(action->get_activity())->finish();
374       }
375     }
376   }
377 }
378 /**
379  * @brief Executes the actors in actors_to_run.
380  *
381  * The actors in actors_to_run are run (in parallel if possible). On exit, actors_to_run is empty, and actors_that_ran
382  * contains the list of actors that just ran.  The two lists are swapped so, be careful when using them before and after
383  * a call to this function.
384  */
385 void EngineImpl::run_all_actors()
386 {
387   instance_->get_context_factory()->run_all(actors_to_run_);
388
389   for (auto const& actor : actors_to_run_)
390     if (actor->to_be_freed())
391       actor->cleanup_from_kernel();
392
393   actors_to_run_.swap(actors_that_ran_);
394   actors_to_run_.clear();
395 }
396
397 actor::ActorImpl* EngineImpl::get_actor_by_pid(aid_t pid)
398 {
399   auto item = actor_list_.find(pid);
400   return item == actor_list_.end() ? nullptr : item->second;
401 }
402
403 void EngineImpl::remove_daemon(actor::ActorImpl* actor)
404 {
405   auto it = daemons_.find(actor);
406   xbt_assert(it != daemons_.end(), "The dying daemon is not a daemon after all. Please report that bug.");
407   daemons_.erase(it);
408 }
409
410 void EngineImpl::add_actor_to_run_list_no_check(actor::ActorImpl* actor)
411 {
412   XBT_DEBUG("Inserting [%p] %s(%s) in the to_run list", actor, actor->get_cname(), actor->get_host()->get_cname());
413   actors_to_run_.push_back(actor);
414 }
415
416 void EngineImpl::add_actor_to_run_list(actor::ActorImpl* actor)
417 {
418   if (std::find(begin(actors_to_run_), end(actors_to_run_), actor) != end(actors_to_run_)) {
419     XBT_DEBUG("Actor %s is already in the to_run list", actor->get_cname());
420   } else {
421     XBT_DEBUG("Inserting [%p] %s(%s) in the to_run list", actor, actor->get_cname(), actor->get_host()->get_cname());
422     actors_to_run_.push_back(actor);
423   }
424 }
425 void EngineImpl::empty_trash()
426 {
427   while (not actors_to_destroy_.empty()) {
428     actor::ActorImpl* actor = &actors_to_destroy_.front();
429     actors_to_destroy_.pop_front();
430     XBT_DEBUG("Getting rid of %s (refcount: %d)", actor->get_cname(), actor->get_refcount());
431     intrusive_ptr_release(actor);
432   }
433 }
434
435 void EngineImpl::display_all_actor_status() const
436 {
437   XBT_INFO("%zu actors are still running, waiting for something.", actor_list_.size());
438   /*  List the actors and their state */
439   XBT_INFO("Legend of the following listing: \"Actor <pid> (<name>@<host>): <status>\"");
440   for (auto const& [_, actor] : actor_list_) {
441     if (actor->waiting_synchro_) {
442       const char* synchro_description = "unknown";
443
444       if (boost::dynamic_pointer_cast<kernel::activity::ExecImpl>(actor->waiting_synchro_) != nullptr)
445         synchro_description = "execution";
446
447       if (boost::dynamic_pointer_cast<kernel::activity::CommImpl>(actor->waiting_synchro_) != nullptr)
448         synchro_description = "communication";
449
450       if (boost::dynamic_pointer_cast<kernel::activity::SleepImpl>(actor->waiting_synchro_) != nullptr)
451         synchro_description = "sleeping";
452
453       if (boost::dynamic_pointer_cast<kernel::activity::SynchroImpl>(actor->waiting_synchro_) != nullptr)
454         synchro_description = "synchronization";
455
456       if (boost::dynamic_pointer_cast<kernel::activity::IoImpl>(actor->waiting_synchro_) != nullptr)
457         synchro_description = "I/O";
458
459       XBT_INFO("Actor %ld (%s@%s): waiting for %s activity %#zx (%s) in state %s to finish %s", actor->get_pid(),
460                actor->get_cname(), actor->get_host()->get_cname(), synchro_description,
461                (xbt_log_no_loc ? (size_t)0xDEADBEEF : (size_t)actor->waiting_synchro_.get()),
462                actor->waiting_synchro_->get_cname(), actor->waiting_synchro_->get_state_str(),
463                (actor->simcall_.observer_ != nullptr && not xbt_log_no_loc
464                     ? actor->simcall_.observer_->to_string().c_str()
465                     : ""));
466     } else {
467       XBT_INFO("Actor %ld (%s@%s) simcall %s", actor->get_pid(), actor->get_cname(), actor->get_host()->get_cname(),
468                (actor->simcall_.observer_ != nullptr ? actor->simcall_.observer_->to_string().c_str()
469                                                      : actor->simcall_.get_cname()));
470     }
471   }
472 }
473
474 void EngineImpl::presolve() const
475 {
476   XBT_DEBUG("Consume all trace events occurring before the starting time.");
477   double next_event_date;
478   while ((next_event_date = profile::future_evt_set.next_date()) != -1.0) {
479     if (next_event_date > now_)
480       break;
481
482     double value                 = -1.0;
483     resource::Resource* resource = nullptr;
484     while (auto* event = profile::future_evt_set.pop_leq(next_event_date, &value, &resource)) {
485       if (value >= 0)
486         resource->apply_event(event, value);
487     }
488   }
489
490   XBT_DEBUG("Set every models in the right state by updating them to 0.");
491   for (auto const& model : models_)
492     model->update_actions_state(now_, 0.0);
493 }
494
495 double EngineImpl::solve(double max_date) const
496 {
497   double time_delta            = -1.0; /* duration */
498   double value                 = -1.0;
499   resource::Resource* resource = nullptr;
500
501   if (max_date != -1.0) {
502     xbt_assert(max_date >= now_, "You asked to simulate up to %f, but that's in the past already", max_date);
503
504     time_delta = max_date - now_;
505   }
506
507   XBT_DEBUG("Looking for next event in all models");
508   for (auto model : models_) {
509     if (not model->next_occurring_event_is_idempotent()) {
510       continue;
511     }
512     double next_event = model->next_occurring_event(now_);
513     if ((time_delta < 0.0 || next_event < time_delta) && next_event >= 0.0) {
514       time_delta = next_event;
515     }
516   }
517
518   XBT_DEBUG("Min for resources (remember that NS3 don't update that value): %f", time_delta);
519
520   XBT_DEBUG("Looking for next trace event");
521
522   while (true) { // Handle next occurring events until none remains
523     double next_event_date = profile::future_evt_set.next_date();
524     XBT_DEBUG("Next TRACE event: %f", next_event_date);
525
526     for (auto model : models_) {
527       /* Skip all idempotent models, they were already treated above
528        * NS3 is the one to handled here */
529       if (model->next_occurring_event_is_idempotent())
530         continue;
531
532       if (next_event_date != -1.0) {
533         time_delta = std::min(next_event_date - now_, time_delta);
534       } else {
535         time_delta = std::max(next_event_date - now_, time_delta); // Get the positive component
536       }
537
538       XBT_DEBUG("Run the NS3 network at most %fs", time_delta);
539       // run until min or next flow
540       double model_next_action_end = model->next_occurring_event(time_delta);
541
542       XBT_DEBUG("Min for network : %f", model_next_action_end);
543       if (model_next_action_end >= 0.0)
544         time_delta = model_next_action_end;
545     }
546
547     if (next_event_date < 0.0 || (next_event_date > now_ + time_delta)) {
548       // next event may have already occurred or will after the next resource change, then bail out
549       XBT_DEBUG("no next usable TRACE event. Stop searching for it");
550       break;
551     }
552
553     XBT_DEBUG("Updating models (min = %g, NOW = %g, next_event_date = %g)", time_delta, now_, next_event_date);
554
555     while (auto* event = profile::future_evt_set.pop_leq(next_event_date, &value, &resource)) {
556       if(value<0)
557               continue;
558       if (resource->is_used()) {
559         time_delta = next_event_date - now_;
560         XBT_DEBUG("This event invalidates the next_occurring_event() computation of models. Next event set to %f",
561                   time_delta);
562       }
563       // FIXME: I'm too lame to update now_ live, so I change it and restore it so that the real update works
564       double round_start = now_;
565       now_               = next_event_date;
566       /* update state of the corresponding resource to the new value. Does not touch lmm.
567          It will be modified if needed when updating actions */
568       XBT_DEBUG("Calling update_resource_state for resource %s", resource->get_cname());
569       resource->apply_event(event, value);
570       now_ = round_start;
571     }
572   }
573
574   /* FIXME: Moved this test to here to avoid stopping simulation if there are actions running on cpus and all cpus are
575    * with availability = 0. This may cause an infinite loop if one cpu has a trace with periodicity = 0 and the other a
576    * trace with periodicity > 0.
577    * The options are: all traces with same periodicity(0 or >0) or we need to change the way how the events are managed
578    */
579   if (time_delta < 0) {
580     XBT_DEBUG("No next event at all. Bail out now.");
581     return -1.0;
582   }
583
584   XBT_DEBUG("Duration set to %f", time_delta);
585
586   // Bump the time: jump into the future
587   now_ += time_delta;
588
589   // Inform the models of the date change
590   for (auto const& model : models_)
591     model->update_actions_state(now_, time_delta);
592
593   s4u::Engine::on_time_advance(time_delta);
594
595   return time_delta;
596 }
597
598 void EngineImpl::run(double max_date)
599 {
600   seal_platform();
601
602   if (MC_is_active()) {
603     mc::AppSide::get()->main_loop();
604     THROW_IMPOSSIBLE; // main_loop never returns
605   }
606
607   if (MC_record_replay_is_active()) {
608     mc::RecordTrace::replay(MC_record_path());
609     empty_trash();
610     return;
611   }
612
613   double elapsed_time = -1;
614   const std::set<s4u::Activity*>* vetoed_activities = s4u::Activity::get_vetoed_activities();
615
616   do {
617     XBT_DEBUG("New Schedule Round; size(queue)=%zu", actors_to_run_.size());
618
619     if (cfg_breakpoint >= 0.0 && simgrid_get_clock() >= cfg_breakpoint) {
620       XBT_DEBUG("Breakpoint reached (%g)", cfg_breakpoint.get());
621       cfg_breakpoint = -1.0; // Let the simulation continue without hiting the breakpoint again and again
622 #ifdef SIGTRAP
623       std::raise(SIGTRAP);
624 #else
625       std::raise(SIGABRT);
626 #endif
627     }
628
629     while (not actors_to_run_.empty()) {
630       XBT_DEBUG("New Sub-Schedule Round; size(queue)=%zu", actors_to_run_.size());
631
632       /* Run all actors that are ready to run, possibly in parallel */
633       run_all_actors();
634
635       /* answer sequentially and in a fixed arbitrary order all the simcalls that were issued during that sub-round.
636        * The order must be fixed for the simulation to be reproducible (see RR-7653). It's OK here because only maestro
637        * changes the list. Killer actors are moved to the end to let victims finish their simcall before dying, but
638        * the order remains reproducible (even if arbitrarily). No need to sort the vector for sake of reproducibility.
639        */
640       for (auto const& actor : actors_that_ran_)
641         if (actor->simcall_.call_ != actor::Simcall::Type::NONE)
642           actor->simcall_handle(0);
643
644       handle_ended_actions();
645
646       /* If only daemon actors remain, cancel their actions, mark them to die and reschedule them */
647       if (actor_list_.size() == daemons_.size())
648         for (auto const& dmon : daemons_) {
649           XBT_DEBUG("Kill %s", dmon->get_cname());
650           maestro_->kill(dmon);
651         }
652     }
653
654     // Compute the max_date of the next solve.
655     // It's either when a timer occurs, or when user-specified deadline is reached, or -1 if none is given
656     double next_time = timer::Timer::next();
657     if (next_time < 0 && max_date > -1) {
658       next_time = max_date;
659     } else if (next_time > -1 && max_date > -1) { // either both <0, or both >0
660       next_time = std::min(next_time, max_date);
661     }
662
663     XBT_DEBUG("Calling solve(%g) %g", next_time, now_);
664     elapsed_time = solve(next_time);
665     XBT_DEBUG("Moving time ahead. NOW=%g; elapsed: %g", now_, elapsed_time);
666
667     // Execute timers until there isn't anything to be done:
668     bool again = false;
669     do {
670       again = timer::Timer::execute_all();
671       handle_ended_actions();
672     } while (again);
673
674     /* Clean actors to destroy */
675     empty_trash();
676
677     XBT_DEBUG("### elapsed time %f, #actors %zu, #to_run %zu, #vetoed %d", elapsed_time, actor_list_.size(),
678               actors_to_run_.size(), (vetoed_activities == nullptr ? -1 : static_cast<int>(vetoed_activities->size())));
679
680     if (elapsed_time < 0. && actors_to_run_.empty() && not actor_list_.empty()) {
681       if (actor_list_.size() <= daemons_.size()) {
682         XBT_CRITICAL("Oops! Daemon actors cannot do any blocking activity (communications, synchronization, etc) "
683                      "once the simulation is over. Please fix your on_exit() functions.");
684       } else {
685         XBT_CRITICAL("Oops! Deadlock detected, some activities are still around but will never complete. "
686                      "This usually happens when the user code is not perfectly clean.");
687       }
688       display_all_actor_status();
689       simgrid::s4u::Engine::on_deadlock();
690       for (auto const& [_, actor] : actor_list_) {
691         XBT_DEBUG("Kill %s", actor->get_cname());
692         maestro_->kill(actor);
693       }
694     }
695   } while ((vetoed_activities == nullptr || vetoed_activities->empty()) &&
696            ((elapsed_time > -1.0 && not double_equals(max_date, now_, 0.00001)) || has_actors_to_run()));
697
698   if (not actor_list_.empty() && max_date < 0 && not(vetoed_activities == nullptr || vetoed_activities->empty()))
699     THROW_IMPOSSIBLE;
700
701   simgrid::s4u::Engine::on_simulation_end();
702 }
703
704 double EngineImpl::get_clock()
705 {
706   return now_;
707 }
708 } // namespace simgrid::kernel