Logo AND Algorithmique Numérique Distribuée

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