Logo AND Algorithmique Numérique Distribuée

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