Logo AND Algorithmique Numérique Distribuée

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