Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Somehow fix the killing of actors in Java
[simgrid.git] / src / simix / ActorImpl.cpp
1 /* Copyright (c) 2007-2018. 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 "mc/mc.h"
7 #include "simgrid/Exception.hpp"
8 #include "smx_private.hpp"
9 #include "src/kernel/activity/CommImpl.hpp"
10 #include "src/kernel/activity/ExecImpl.hpp"
11 #include "src/kernel/activity/IoImpl.hpp"
12 #include "src/kernel/activity/SleepImpl.hpp"
13 #include "src/kernel/activity/SynchroRaw.hpp"
14 #include "src/mc/mc_replay.hpp"
15 #include "src/mc/remote/Client.hpp"
16 #include "src/simix/smx_host_private.hpp"
17 #include "src/simix/smx_io_private.hpp"
18 #include "src/simix/smx_synchro_private.hpp"
19 #include "src/surf/HostImpl.hpp"
20 #include "src/surf/cpu_interface.hpp"
21
22 #ifdef HAVE_SMPI
23 #include "src/smpi/include/private.hpp"
24 #endif
25
26 #include <boost/range/algorithm.hpp>
27
28 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(simix_process, simix, "Logging specific to SIMIX (process)");
29
30 unsigned long simix_process_maxpid = 0;
31
32 /**
33  * @brief Returns the current agent.
34  *
35  * This functions returns the currently running SIMIX process.
36  *
37  * @return The SIMIX process
38  */
39 smx_actor_t SIMIX_process_self()
40 {
41   smx_context_t self_context = SIMIX_context_self();
42
43   return (self_context != nullptr) ? self_context->process() : nullptr;
44 }
45
46 /**
47  * @brief Returns whether a process has pending asynchronous communications.
48  * @return true if there are asynchronous communications in this process
49  */
50 int SIMIX_process_has_pending_comms(smx_actor_t process) {
51
52   return process->comms.size() > 0;
53 }
54
55 /**
56  * @brief Moves a process to the list of processes to destroy.
57  */
58 void SIMIX_process_cleanup(smx_actor_t process)
59 {
60   XBT_DEBUG("Cleanup process %s (%p), waiting synchro %p", process->get_cname(), process,
61             process->waiting_synchro.get());
62
63   process->finished_ = true;
64   SIMIX_process_on_exit_runall(process);
65
66   /* Unregister from the kill timer if any */
67   if (process->kill_timer != nullptr) {
68     SIMIX_timer_remove(process->kill_timer);
69     process->kill_timer = nullptr;
70   }
71
72   simix_global->mutex.lock();
73
74   /* cancel non-blocking communications */
75   while (not process->comms.empty()) {
76     smx_activity_t synchro = process->comms.front();
77     process->comms.pop_front();
78     simgrid::kernel::activity::CommImplPtr comm =
79         boost::static_pointer_cast<simgrid::kernel::activity::CommImpl>(synchro);
80
81     /* make sure no one will finish the comm after this process is destroyed,
82      * because src_proc or dst_proc would be an invalid pointer */
83
84     if (comm->src_proc == process) {
85       XBT_DEBUG("Found an unfinished send comm %p (detached = %d), state %d, src = %p, dst = %p", comm.get(),
86                 comm->detached, (int)comm->state_, comm->src_proc, comm->dst_proc);
87       comm->src_proc = nullptr;
88
89     } else if (comm->dst_proc == process) {
90       XBT_DEBUG("Found an unfinished recv comm %p, state %d, src = %p, dst = %p", comm.get(), (int)comm->state_,
91                 comm->src_proc, comm->dst_proc);
92       comm->dst_proc = nullptr;
93
94       if (comm->detached && comm->src_proc != nullptr) {
95         /* the comm will be freed right now, remove it from the sender */
96         comm->src_proc->comms.remove(comm);
97       }
98     } else {
99       xbt_die("Communication synchro %p is in my list but I'm not the sender nor the receiver", synchro.get());
100     }
101     comm->cancel();
102   }
103
104   XBT_DEBUG("%s@%s(%ld) should not run anymore", process->get_cname(), process->iface()->get_host()->get_cname(),
105             process->pid_);
106   simix_global->process_list.erase(process->pid_);
107   if (process->host_ && process->host_process_list_hook.is_linked())
108     simgrid::xbt::intrusive_erase(process->host_->pimpl_->process_list_, *process);
109   if (not process->smx_destroy_list_hook.is_linked()) {
110 #if SIMGRID_HAVE_MC
111     xbt_dynar_push_as(simix_global->dead_actors_vector, smx_actor_t, process);
112 #endif
113     simix_global->process_to_destroy.push_back(*process);
114   }
115   process->context_->iwannadie = false;
116
117   simix_global->mutex.unlock();
118 }
119
120 /**
121  * Garbage collection
122  *
123  * Should be called some time to time to free the memory allocated for processes that have finished (or killed).
124  */
125 void SIMIX_process_empty_trash()
126 {
127   while (not simix_global->process_to_destroy.empty()) {
128     smx_actor_t process = &simix_global->process_to_destroy.front();
129     simix_global->process_to_destroy.pop_front();
130     XBT_DEBUG("Getting rid of %p",process);
131     intrusive_ptr_release(process);
132   }
133 #if SIMGRID_HAVE_MC
134   xbt_dynar_reset(simix_global->dead_actors_vector);
135 #endif
136 }
137
138 namespace simgrid {
139
140 namespace kernel {
141 namespace actor {
142
143 ActorImpl::~ActorImpl()
144 {
145   delete this->context_;
146 }
147
148 static void dying_daemon(int /*exit_status*/, void* data)
149 {
150   std::vector<ActorImpl*>* vect = &simix_global->daemons;
151
152   auto it = std::find(vect->begin(), vect->end(), static_cast<ActorImpl*>(data));
153   xbt_assert(it != vect->end(), "The dying daemon is not a daemon after all. Please report that bug.");
154
155   /* Don't move the whole content since we don't really care about the order */
156   std::swap(*it, vect->back());
157   vect->pop_back();
158 }
159
160 /** This process will be terminated automatically when the last non-daemon process finishes */
161 void ActorImpl::daemonize()
162 {
163   if (not daemon_) {
164     daemon_ = true;
165     simix_global->daemons.push_back(this);
166     SIMIX_process_on_exit(this, dying_daemon, this);
167   }
168 }
169
170 simgrid::s4u::Actor* ActorImpl::restart()
171 {
172   XBT_DEBUG("Restarting process %s on %s", get_cname(), host_->get_cname());
173
174   // retrieve the arguments of the old process
175   simgrid::kernel::actor::ProcessArg arg = ProcessArg(host_, this);
176
177   // kill the old process
178   SIMIX_process_kill(this, (this == simix_global->maestro_process) ? this : SIMIX_process_self());
179
180   // start the new process
181   ActorImpl* actor = simix_global->create_process_function(arg.name.c_str(), std::move(arg.code), arg.data, arg.host,
182                                                            arg.properties.get(), nullptr);
183   simcall_process_set_kill_time(actor, arg.kill_time);
184   actor->set_auto_restart(arg.auto_restart);
185
186   return actor->ciface();
187 }
188
189 smx_activity_t ActorImpl::suspend(ActorImpl* issuer)
190 {
191   if (suspended_) {
192     XBT_DEBUG("Actor '%s' is already suspended", get_cname());
193     return nullptr;
194   }
195
196   suspended_ = true;
197
198   /* If we are suspending another actor that is waiting on a sync, suspend its synchronization. */
199   if (this != issuer) {
200     if (waiting_synchro)
201       waiting_synchro->suspend();
202     /* If the other actor is not waiting, its suspension is delayed to when the actor is rescheduled. */
203
204     return nullptr;
205   } else {
206     return SIMIX_execution_start("suspend", "", 0.0, 1.0, 0.0, this->host_);
207   }
208 }
209
210 void ActorImpl::resume()
211 {
212   XBT_IN("process = %p", this);
213
214   if (context_->iwannadie) {
215     XBT_VERB("Ignoring request to suspend an actor that is currently dying.");
216     return;
217   }
218
219   if (not suspended_)
220     return;
221   suspended_ = false;
222
223   /* resume the synchronization that was blocking the resumed actor. */
224   if (waiting_synchro)
225     waiting_synchro->resume();
226
227   XBT_OUT();
228 }
229
230 smx_activity_t ActorImpl::sleep(double duration)
231 {
232   if (host_->is_off())
233     throw_exception(std::make_exception_ptr(simgrid::HostFailureException(
234         XBT_THROW_POINT, std::string("Host ") + std::string(host_->get_cname()) + " failed, you cannot sleep there.")));
235
236   simgrid::kernel::activity::SleepImpl* synchro = new simgrid::kernel::activity::SleepImpl();
237   synchro->host                                 = host_;
238   synchro->surf_sleep                           = host_->pimpl_cpu->sleep(duration);
239   synchro->surf_sleep->set_data(synchro);
240   XBT_DEBUG("Create sleep synchronization %p", synchro);
241
242   return synchro;
243 }
244
245 void ActorImpl::throw_exception(std::exception_ptr e)
246 {
247   exception = e;
248
249   if (suspended_)
250     resume();
251
252   /* cancel the blocking synchro if any */
253   if (waiting_synchro) {
254
255     simgrid::kernel::activity::ExecImplPtr exec =
256         boost::dynamic_pointer_cast<simgrid::kernel::activity::ExecImpl>(waiting_synchro);
257     if (exec != nullptr && exec->surf_action_)
258       exec->surf_action_->cancel();
259
260     simgrid::kernel::activity::CommImplPtr comm =
261         boost::dynamic_pointer_cast<simgrid::kernel::activity::CommImpl>(waiting_synchro);
262     if (comm != nullptr) {
263       comms.remove(comm);
264       comm->cancel();
265     }
266
267     simgrid::kernel::activity::SleepImplPtr sleep =
268         boost::dynamic_pointer_cast<simgrid::kernel::activity::SleepImpl>(waiting_synchro);
269     if (sleep != nullptr) {
270       SIMIX_process_sleep_destroy(waiting_synchro);
271       if (std::find(begin(simix_global->process_to_run), end(simix_global->process_to_run), this) ==
272               end(simix_global->process_to_run) &&
273           this != SIMIX_process_self()) {
274         XBT_DEBUG("Inserting %s in the to_run list", get_cname());
275         simix_global->process_to_run.push_back(this);
276       }
277     }
278
279     simgrid::kernel::activity::RawImplPtr raw =
280         boost::dynamic_pointer_cast<simgrid::kernel::activity::RawImpl>(waiting_synchro);
281     if (raw != nullptr) {
282       SIMIX_synchro_stop_waiting(this, &simcall);
283     }
284
285     simgrid::kernel::activity::IoImplPtr io =
286         boost::dynamic_pointer_cast<simgrid::kernel::activity::IoImpl>(waiting_synchro);
287     if (io != nullptr) {
288       delete io.get();
289     }
290   }
291   waiting_synchro = nullptr;
292 }
293
294 void create_maestro(simgrid::simix::ActorCode code)
295 {
296   smx_actor_t maestro = nullptr;
297   /* Create maestro process and initialize it */
298   maestro           = new simgrid::kernel::actor::ActorImpl();
299   maestro->pid_     = simix_process_maxpid++;
300   maestro->name_    = "";
301   maestro->set_user_data(nullptr);
302
303   if (not code) {
304     maestro->context_ = SIMIX_context_new(simgrid::simix::ActorCode(), nullptr, maestro);
305   } else {
306     if (not simix_global)
307       xbt_die("simix is not initialized, please call MSG_init first");
308     maestro->context_ = simix_global->context_factory->create_maestro(code, maestro);
309   }
310
311   maestro->simcall.issuer = maestro;
312   simix_global->maestro_process = maestro;
313 }
314
315 } // namespace actor
316 }
317 }
318
319 /** @brief Creates and runs the maestro process */
320 void SIMIX_maestro_create(void (*code)(void*), void* data)
321 {
322   simgrid::kernel::actor::create_maestro(std::bind(code, data));
323 }
324
325 /**
326  * @brief Internal function to create a process.
327  *
328  * This function actually creates the process.
329  * It may be called when a SIMCALL_PROCESS_CREATE simcall occurs,
330  * or directly for SIMIX internal purposes. The sure thing is that it's called from maestro context.
331  *
332  * @return the process created
333  */
334 smx_actor_t SIMIX_process_create(std::string name, simgrid::simix::ActorCode code, void* data, simgrid::s4u::Host* host,
335                                  std::unordered_map<std::string, std::string>* properties, smx_actor_t parent_process)
336 {
337
338   XBT_DEBUG("Start process %s on host '%s'", name.c_str(), host->get_cname());
339
340   if (host->is_off()) {
341     XBT_WARN("Cannot launch process '%s' on failed host '%s'", name.c_str(), host->get_cname());
342     return nullptr;
343   }
344
345   smx_actor_t process = new simgrid::kernel::actor::ActorImpl();
346
347   xbt_assert(code && host != nullptr, "Invalid parameters");
348   /* Process data */
349   process->pid_           = simix_process_maxpid++;
350   process->name_          = simgrid::xbt::string(name);
351   process->host_          = host;
352   process->set_user_data(data);
353   process->simcall.issuer = process;
354
355   if (parent_process != nullptr) {
356     process->ppid_ = parent_process->pid_;
357   }
358
359   process->code         = code;
360
361   XBT_VERB("Create context %s", process->get_cname());
362   process->context_ = SIMIX_context_new(std::move(code), simix_global->cleanup_process_function, process);
363
364   /* Add properties */
365   if (properties != nullptr)
366     for (auto const& kv : *properties)
367       process->set_property(kv.first, kv.second);
368
369   /* Add the process to its host's process list */
370   host->pimpl_->process_list_.push_back(*process);
371
372   XBT_DEBUG("Start context '%s'", process->get_cname());
373
374   /* Now insert it in the global process list and in the process to run list */
375   simix_global->process_list[process->pid_] = process;
376   XBT_DEBUG("Inserting %s(%s) in the to_run list", process->get_cname(), host->get_cname());
377   simix_global->process_to_run.push_back(process);
378   intrusive_ptr_add_ref(process);
379
380   /* The onCreation() signal must be delayed until there, where the pid and everything is set */
381   simgrid::s4u::ActorPtr tmp = process->iface(); // Passing this directly to onCreation will lead to crashes
382   simgrid::s4u::Actor::on_creation(tmp);
383
384   return process;
385 }
386
387 smx_actor_t SIMIX_process_attach(const char* name, void* data, const char* hostname,
388                                  std::unordered_map<std::string, std::string>* properties, smx_actor_t parent_process)
389 {
390   // This is mostly a copy/paste from SIMIX_process_new(),
391   // it'd be nice to share some code between those two functions.
392
393   sg_host_t host = sg_host_by_name(hostname);
394   XBT_DEBUG("Attach process %s on host '%s'", name, hostname);
395
396   if (host->is_off()) {
397     XBT_WARN("Cannot launch process '%s' on failed host '%s'", name, hostname);
398     return nullptr;
399   }
400
401   smx_actor_t process = new simgrid::kernel::actor::ActorImpl();
402   /* Process data */
403   process->pid_  = simix_process_maxpid++;
404   process->name_ = std::string(name);
405   process->host_ = host;
406   process->set_user_data(data);
407   process->simcall.issuer = process;
408
409   if (parent_process != nullptr) {
410     process->ppid_ = parent_process->pid_;
411   }
412
413   /* Process data for auto-restart */
414   process->code = nullptr;
415
416   XBT_VERB("Create context %s", process->get_cname());
417   if (not simix_global)
418     xbt_die("simix is not initialized, please call MSG_init first");
419   process->context_ = simix_global->context_factory->attach(simix_global->cleanup_process_function, process);
420
421   /* Add properties */
422   if (properties != nullptr)
423     for (auto const& kv : *properties)
424       process->set_property(kv.first, kv.second);
425
426   /* Add the process to it's host process list */
427   host->pimpl_->process_list_.push_back(*process);
428
429   /* Now insert it in the global process list and in the process to run list */
430   simix_global->process_list[process->pid_] = process;
431   XBT_DEBUG("Inserting %s(%s) in the to_run list", process->get_cname(), host->get_cname());
432   simix_global->process_to_run.push_back(process);
433   intrusive_ptr_add_ref(process);
434
435   auto* context = dynamic_cast<simgrid::kernel::context::AttachContext*>(process->context_);
436   if (not context)
437     xbt_die("Not a suitable context");
438
439   context->attach_start();
440
441   /* The onCreation() signal must be delayed until there, where the pid and everything is set */
442   simgrid::s4u::ActorPtr tmp = process->iface(); // Passing this directly to onCreation will lead to crashes
443   simgrid::s4u::Actor::on_creation(tmp);
444
445   return process;
446 }
447
448 void SIMIX_process_detach()
449 {
450   auto* context = dynamic_cast<simgrid::kernel::context::AttachContext*>(SIMIX_context_self());
451   if (not context)
452     xbt_die("Not a suitable context");
453
454   auto process = context->process();
455   simix_global->cleanup_process_function(process);
456   context->attach_stop();
457 }
458
459 /**
460  * @brief Executes the processes from simix_global->process_to_run.
461  *
462  * The processes of simix_global->process_to_run are run (in parallel if
463  * possible).  On exit, simix_global->process_to_run is empty, and
464  * simix_global->process_that_ran contains the list of processes that just ran.
465  * The two lists are swapped so, be careful when using them before and after a
466  * call to this function.
467  */
468 void SIMIX_process_runall()
469 {
470   SIMIX_context_runall();
471
472   simix_global->process_to_run.swap(simix_global->process_that_ran);
473   simix_global->process_to_run.clear();
474 }
475
476 /**
477  * @brief Internal function to kill a SIMIX process.
478  *
479  * This function may be called when a SIMCALL_PROCESS_KILL simcall occurs,
480  * or directly for SIMIX internal purposes.
481  *
482  * @param process poor victim
483  * @param issuer the process which has sent the PROCESS_KILL. Important to not schedule twice the same process.
484  */
485 void SIMIX_process_kill(smx_actor_t process, smx_actor_t issuer) {
486
487   if (process->finished_) {
488     XBT_DEBUG("Ignoring request to kill process %s@%s that is already dead", process->get_cname(),
489               process->host_->get_cname());
490     return;
491   }
492
493   XBT_DEBUG("Actor '%s'@%s is killing actor '%s'@%s", issuer->get_cname(),
494             (issuer->host_ == nullptr ? "(null)" : issuer->host_->get_cname()), process->get_cname(),
495             process->host_->get_cname());
496
497   process->context_->iwannadie = true;
498   process->blocked_            = false;
499   process->suspended_          = false;
500   process->exception = nullptr;
501
502   // Forcefully kill the actor if its host is turned off. Not an HostFailureException because you should not survive that
503   if (process->host_->is_off()) {
504     /* HORRIBLE HACK: Don't throw an StopRequest exception in Java, because it breaks sometimes.
505      *
506      * It seems to break for the actors started from the Java world, with new Process()
507      * while it works for the ones started from the C world, with the deployment file.
508      * When it happens, the simulation stops brutally with a message "untrapped exception StopRequest".
509      *
510      * From what I understand, it works for the native actors because they have a nice try/catch block around their main
511      * but I fail to have something like that for pure Java actors. That's probably a story of C->Java vs Java->C
512      * calling conventions. The right solution may be to have try/catch(StopRequest) blocks around each native call in
513      * JNI. ie, protect every Java->C++ call from C++ exceptions. But this sounds long and painful to do before we
514      * switch to an automatic generator such as SWIG. For now, we don't throw here that exception that we sometimes fail
515      * to catch.
516      *
517      * One of the unfortunate outcome is that the threads started from the deployment file are not stopped anymore.
518      * Or maybe this is the actors stopping gracefully as opposed to the killed ones? Or maybe this is absolutely all
519      * actors of the Java simulation? I'm not sure. Anyway. Because of them, the simulation hangs at the end, waiting
520      * for them to stop but they won't. The current answer to that is very brutal:
521      * we do a "exit(0)" to kill the JVM from the C code after the call to MSG_run(). Definitely unpleasant.
522      */
523
524     if (simgrid::kernel::context::factory_initializer == nullptr) // Only Java sets a factory_initializer, for now
525       process->throw_exception(std::make_exception_ptr(simgrid::kernel::context::Context::StopRequest("Host failed")));
526   }
527
528   /* destroy the blocking synchro if any */
529   if (process->waiting_synchro != nullptr) {
530
531     simgrid::kernel::activity::ExecImplPtr exec =
532         boost::dynamic_pointer_cast<simgrid::kernel::activity::ExecImpl>(process->waiting_synchro);
533     simgrid::kernel::activity::CommImplPtr comm =
534         boost::dynamic_pointer_cast<simgrid::kernel::activity::CommImpl>(process->waiting_synchro);
535     simgrid::kernel::activity::SleepImplPtr sleep =
536         boost::dynamic_pointer_cast<simgrid::kernel::activity::SleepImpl>(process->waiting_synchro);
537     simgrid::kernel::activity::RawImplPtr raw =
538         boost::dynamic_pointer_cast<simgrid::kernel::activity::RawImpl>(process->waiting_synchro);
539     simgrid::kernel::activity::IoImplPtr io =
540         boost::dynamic_pointer_cast<simgrid::kernel::activity::IoImpl>(process->waiting_synchro);
541
542     if (exec != nullptr) {
543       if (exec->surf_action_) {
544         exec->surf_action_->cancel();
545         exec->surf_action_->unref();
546         exec->surf_action_ = nullptr;
547       }
548     } else if (comm != nullptr) {
549       process->comms.remove(process->waiting_synchro);
550       comm->cancel();
551       // Remove first occurrence of &process->simcall:
552       auto i = boost::range::find(process->waiting_synchro->simcalls_, &process->simcall);
553       if (i != process->waiting_synchro->simcalls_.end())
554         process->waiting_synchro->simcalls_.remove(&process->simcall);
555     } else if (sleep != nullptr) {
556       if (sleep->surf_sleep)
557         sleep->surf_sleep->cancel();
558       sleep->post();
559     } else if (raw != nullptr) {
560       SIMIX_synchro_stop_waiting(process, &process->simcall);
561
562     } else if (io != nullptr) {
563       delete io.get();
564     } else {
565       simgrid::kernel::activity::ActivityImplPtr activity = process->waiting_synchro;
566       xbt_die("Activity %s is of unknown type %s", activity->name_.c_str(),
567               simgrid::xbt::demangle(typeid(activity).name()).get());
568     }
569
570     process->waiting_synchro = nullptr;
571   }
572   if (std::find(begin(simix_global->process_to_run), end(simix_global->process_to_run), process) ==
573           end(simix_global->process_to_run) &&
574       process != issuer) {
575     XBT_DEBUG("Inserting %s in the to_run list", process->get_cname());
576     simix_global->process_to_run.push_back(process);
577   }
578 }
579
580 /** @deprecated When this function gets removed, also remove the xbt_ex class, that is only there to help users to
581  * transition */
582 void SIMIX_process_throw(smx_actor_t process, xbt_errcat_t cat, int value, const char *msg) {
583   SMX_EXCEPTION(process, cat, value, msg);
584
585   if (process->suspended_)
586     process->resume();
587
588   /* cancel the blocking synchro if any */
589   if (process->waiting_synchro) {
590
591     simgrid::kernel::activity::ExecImplPtr exec =
592         boost::dynamic_pointer_cast<simgrid::kernel::activity::ExecImpl>(process->waiting_synchro);
593     if (exec != nullptr && exec->surf_action_)
594       exec->surf_action_->cancel();
595
596     simgrid::kernel::activity::CommImplPtr comm =
597         boost::dynamic_pointer_cast<simgrid::kernel::activity::CommImpl>(process->waiting_synchro);
598     if (comm != nullptr) {
599       process->comms.remove(comm);
600       comm->cancel();
601     }
602
603     simgrid::kernel::activity::SleepImplPtr sleep =
604         boost::dynamic_pointer_cast<simgrid::kernel::activity::SleepImpl>(process->waiting_synchro);
605     if (sleep != nullptr) {
606       SIMIX_process_sleep_destroy(process->waiting_synchro);
607       if (std::find(begin(simix_global->process_to_run), end(simix_global->process_to_run), process) ==
608               end(simix_global->process_to_run) &&
609           process != SIMIX_process_self()) {
610         XBT_DEBUG("Inserting %s in the to_run list", process->get_cname());
611         simix_global->process_to_run.push_back(process);
612       }
613     }
614
615     simgrid::kernel::activity::RawImplPtr raw =
616         boost::dynamic_pointer_cast<simgrid::kernel::activity::RawImpl>(process->waiting_synchro);
617     if (raw != nullptr) {
618       SIMIX_synchro_stop_waiting(process, &process->simcall);
619     }
620
621     simgrid::kernel::activity::IoImplPtr io =
622         boost::dynamic_pointer_cast<simgrid::kernel::activity::IoImpl>(process->waiting_synchro);
623     if (io != nullptr) {
624       delete io.get();
625     }
626   }
627   process->waiting_synchro = nullptr;
628
629 }
630
631 /**
632  * @brief Kills all running processes.
633  * @param issuer this one will not be killed
634  */
635 void SIMIX_process_killall(smx_actor_t issuer)
636 {
637   for (auto const& kv : simix_global->process_list)
638     if (kv.second != issuer)
639       SIMIX_process_kill(kv.second, issuer);
640 }
641
642 void SIMIX_process_change_host(smx_actor_t actor, sg_host_t dest)
643 {
644   xbt_assert((actor != nullptr), "Invalid parameters");
645   simgrid::xbt::intrusive_erase(actor->host_->pimpl_->process_list_, *actor);
646   actor->host_ = dest;
647   dest->pimpl_->process_list_.push_back(*actor);
648 }
649
650 void simcall_HANDLER_process_suspend(smx_simcall_t simcall, smx_actor_t process)
651 {
652   smx_activity_t sync_suspend = process->suspend(simcall->issuer);
653
654   if (process != simcall->issuer) {
655     SIMIX_simcall_answer(simcall);
656   } else {
657     sync_suspend->simcalls_.push_back(simcall);
658     process->waiting_synchro = sync_suspend;
659     process->waiting_synchro->suspend();
660   }
661   /* If we are suspending ourselves, then just do not finish the simcall now */
662 }
663
664 int SIMIX_process_get_maxpid() {
665   return simix_process_maxpid;
666 }
667
668 int SIMIX_process_count()
669 {
670   return simix_global->process_list.size();
671 }
672
673 void* SIMIX_process_self_get_data()
674 {
675   smx_actor_t self = SIMIX_process_self();
676
677   if (not self) {
678     return nullptr;
679   }
680   return self->get_user_data();
681 }
682
683 void SIMIX_process_self_set_data(void *data)
684 {
685   SIMIX_process_self()->set_user_data(data);
686 }
687
688
689 /* needs to be public and without simcall because it is called
690    by exceptions and logging events */
691 const char* SIMIX_process_self_get_name() {
692
693   smx_actor_t process = SIMIX_process_self();
694   if (process == nullptr || process == simix_global->maestro_process)
695     return "maestro";
696
697   return process->get_cname();
698 }
699
700 void simcall_HANDLER_process_join(smx_simcall_t simcall, smx_actor_t process, double timeout)
701 {
702   if (process->finished_) {
703     // The joined process is already finished, just wake up the issuer process right away
704     simcall_process_sleep__set__result(simcall, SIMIX_DONE);
705     SIMIX_simcall_answer(simcall);
706     return;
707   }
708   smx_activity_t sync = SIMIX_process_join(simcall->issuer, process, timeout);
709   sync->simcalls_.push_back(simcall);
710   simcall->issuer->waiting_synchro = sync;
711 }
712
713 smx_activity_t SIMIX_process_join(smx_actor_t issuer, smx_actor_t process, double timeout)
714 {
715   smx_activity_t res = issuer->sleep(timeout);
716   intrusive_ptr_add_ref(res.get());
717   SIMIX_process_on_exit(process,
718                         [](int, void* arg) {
719                           auto sleep = static_cast<simgrid::kernel::activity::SleepImpl*>(arg);
720                           if (sleep->surf_sleep)
721                             sleep->surf_sleep->finish(simgrid::kernel::resource::Action::State::FINISHED);
722                           intrusive_ptr_release(sleep);
723                         },
724                         res.get());
725   return res;
726 }
727
728 void simcall_HANDLER_process_sleep(smx_simcall_t simcall, double duration)
729 {
730   if (MC_is_active() || MC_record_replay_is_active()) {
731     MC_process_clock_add(simcall->issuer, duration);
732     simcall_process_sleep__set__result(simcall, SIMIX_DONE);
733     SIMIX_simcall_answer(simcall);
734     return;
735   }
736   smx_activity_t sync = simcall->issuer->sleep(duration);
737   sync->simcalls_.push_back(simcall);
738   simcall->issuer->waiting_synchro = sync;
739 }
740
741 void SIMIX_process_sleep_destroy(smx_activity_t synchro)
742 {
743   XBT_DEBUG("Destroy sleep synchro %p", synchro.get());
744   simgrid::kernel::activity::SleepImplPtr sleep =
745       boost::dynamic_pointer_cast<simgrid::kernel::activity::SleepImpl>(synchro);
746
747   if (sleep->surf_sleep) {
748     sleep->surf_sleep->unref();
749     sleep->surf_sleep = nullptr;
750   }
751 }
752
753 /**
754  * @brief Calling this function makes the process to yield.
755  *
756  * Only the current process can call this function, giving back the control to maestro.
757  *
758  * @param self the current process
759  */
760 void SIMIX_process_yield(smx_actor_t self)
761 {
762   XBT_DEBUG("Yield actor '%s'", self->get_cname());
763
764   /* Go into sleep and return control to maestro */
765   self->context_->suspend();
766
767   /* Ok, maestro returned control to us */
768   XBT_DEBUG("Control returned to me: '%s'", self->get_cname());
769
770   if (self->context_->iwannadie) {
771     XBT_DEBUG("I wanna die!");
772     self->finished_ = true;
773     /* execute the on_exit functions */
774     SIMIX_process_on_exit_runall(self);
775
776     if (self->auto_restart_ && self->host_->is_off() &&
777         watched_hosts.find(self->host_->get_cname()) == watched_hosts.end()) {
778       XBT_DEBUG("Push host %s to watched_hosts because it's off and %s needs to restart", self->host_->get_cname(),
779                 self->get_cname());
780       watched_hosts.insert(self->host_->get_cname());
781     }
782
783     XBT_DEBUG("Process %s@%s is dead", self->get_cname(), self->host_->get_cname());
784     self->context_->stop();
785     xbt_backtrace_display_current();
786     xbt_die("I should be dead by now.");
787   }
788
789   if (self->suspended_) {
790     XBT_DEBUG("Hey! I'm suspended.");
791     xbt_assert(self->exception != nullptr, "Gasp! This exception may be lost by subsequent calls.");
792     self->suspended_ = false;
793     self->suspend(self);
794   }
795
796   if (self->exception != nullptr) {
797     XBT_DEBUG("Wait, maestro left me an exception");
798     std::exception_ptr exception = std::move(self->exception);
799     self->exception = nullptr;
800     std::rethrow_exception(std::move(exception));
801   }
802
803   if (SMPI_switch_data_segment && not self->finished_) {
804     SMPI_switch_data_segment(self->iface());
805   }
806 }
807
808 /** @brief Returns the list of processes to run. */
809 const std::vector<smx_actor_t>& simgrid::simix::process_get_runnable()
810 {
811   return simix_global->process_to_run;
812 }
813
814 /** @brief Returns the process from PID. */
815 smx_actor_t SIMIX_process_from_PID(aid_t PID)
816 {
817   auto process = simix_global->process_list.find(PID);
818   return process == simix_global->process_list.end() ? nullptr : process->second;
819 }
820
821 void SIMIX_process_on_exit_runall(smx_actor_t process) {
822   simgrid::s4u::Actor::on_destruction(process->iface());
823   smx_process_exit_status_t exit_status = (process->context_->iwannadie) ? SMX_EXIT_FAILURE : SMX_EXIT_SUCCESS;
824   while (not process->on_exit.empty()) {
825     s_smx_process_exit_fun_t exit_fun = process->on_exit.back();
826     process->on_exit.pop_back();
827     (exit_fun.fun)(exit_status, exit_fun.arg);
828   }
829 }
830
831 void SIMIX_process_on_exit(smx_actor_t process, int_f_pvoid_pvoid_t fun, void* data)
832 {
833   SIMIX_process_on_exit(process, [fun](int a, void* b) { fun((void*)(intptr_t)a, b); }, data);
834 }
835
836 void SIMIX_process_on_exit(smx_actor_t process, std::function<void(int, void*)> fun, void* data)
837 {
838   xbt_assert(process, "current process not found: are you in maestro context ?");
839
840   process->on_exit.emplace_back(s_smx_process_exit_fun_t{fun, data});
841 }
842
843 /** @brief Restart a process, starting it again from the beginning. */
844 /**
845  * @ingroup simix_process_management
846  * @brief Creates and runs a new SIMIX process.
847  *
848  * The structure and the corresponding thread are created and put in the list of ready processes.
849  *
850  * @param name a name for the process. It is for user-level information and can be nullptr.
851  * @param code the main function of the process
852  * @param data a pointer to any data one may want to attach to the new object. It is for user-level information and can
853  * be nullptr.
854  * It can be retrieved with the method ActorImpl::getUserData().
855  * @param host where the new agent is executed.
856  * @param argc first argument passed to @a code
857  * @param argv second argument passed to @a code
858  * @param properties the properties of the process
859  */
860 smx_actor_t simcall_process_create(std::string name, xbt_main_func_t code, void* data, sg_host_t host, int argc,
861                                    char** argv, std::unordered_map<std::string, std::string>* properties)
862 {
863   auto wrapped_code = simgrid::xbt::wrap_main(code, argc, argv);
864   for (int i = 0; i != argc; ++i)
865     xbt_free(argv[i]);
866   xbt_free(argv);
867   smx_actor_t res = simcall_process_create(name, std::move(wrapped_code), data, host, properties);
868   return res;
869 }
870
871 smx_actor_t simcall_process_create(std::string name, simgrid::simix::ActorCode code, void* data, sg_host_t host,
872                                    std::unordered_map<std::string, std::string>* properties)
873 {
874   smx_actor_t self = SIMIX_process_self();
875   return simgrid::simix::simcall([name, code, data, host, properties, self] {
876     return SIMIX_process_create(name, std::move(code), data, host, properties, self);
877   });
878 }