Logo AND Algorithmique Numérique Distribuée

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