Logo AND Algorithmique Numérique Distribuée

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