Logo AND Algorithmique Numérique Distribuée

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