Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
this static function is now useless
[simgrid.git] / src / smpi / smpi_global.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 <dlfcn.h>
7 #include <fcntl.h>
8 #include <spawn.h>
9 #include <sys/stat.h>
10 #include <sys/types.h>
11 #include <sys/wait.h>
12
13 #include "mc/mc.h"
14 #include "private.h"
15 #include "private.hpp"
16 #include "simgrid/s4u/Mailbox.hpp"
17 #include "simgrid/sg_config.h"
18 #include "src/kernel/activity/SynchroComm.hpp"
19 #include "src/mc/mc_record.h"
20 #include "src/mc/mc_replay.h"
21 #include "src/msg/msg_private.h"
22 #include "src/simix/smx_private.h"
23 #include "src/surf/surf_interface.hpp"
24 #include "src/smpi/SmpiHost.hpp"
25 #include "surf/surf.h"
26 #include "xbt/replay.hpp"
27 #include <xbt/config.hpp>
28
29 #include <float.h> /* DBL_MAX */
30 #include <fstream>
31 #include <map>
32 #include <stdint.h>
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <string>
36 #include <utility>
37 #include <vector>
38 #include <memory>
39
40 #if HAVE_SENDFILE
41 #include <sys/sendfile.h>
42 #endif
43
44 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(smpi_kernel, smpi, "Logging specific to SMPI (kernel)");
45 #include <boost/tokenizer.hpp>
46 #include <boost/algorithm/string.hpp> /* trim_right / trim_left */
47
48 #ifndef RTLD_DEEPBIND
49 /* RTLD_DEEPBIND is a bad idea of GNU ld that obviously does not exist on other platforms
50  * See https://www.akkadia.org/drepper/dsohowto.pdf
51  * and https://lists.freebsd.org/pipermail/freebsd-current/2016-March/060284.html
52 */
53 #define RTLD_DEEPBIND 0
54 #endif
55
56 /* Mac OSX does not have any header file providing that definition so we have to duplicate it here. Bummers. */
57 extern char** environ; /* we use it in posix_spawnp below */
58
59 #if HAVE_PAPI
60 #include "papi.h"
61 const char* papi_default_config_name = "default";
62
63 struct papi_process_data {
64   papi_counter_t counter_data;
65   int event_set;
66 };
67
68 #endif
69 std::unordered_map<std::string, double> location2speedup;
70
71 simgrid::smpi::Process **process_data = nullptr;
72 int process_count = 0;
73 int smpi_universe_size = 0;
74 int* index_to_process_data = nullptr;
75 extern double smpi_total_benched_time;
76 xbt_os_timer_t global_timer;
77 MPI_Comm MPI_COMM_WORLD = MPI_COMM_UNINITIALIZED;
78 MPI_Errhandler *MPI_ERRORS_RETURN = nullptr;
79 MPI_Errhandler *MPI_ERRORS_ARE_FATAL = nullptr;
80 MPI_Errhandler *MPI_ERRHANDLER_NULL = nullptr;
81 static simgrid::config::Flag<double> smpi_wtime_sleep(
82   "smpi/wtime", "Minimum time to inject inside a call to MPI_Wtime", 0.0);
83 static simgrid::config::Flag<double> smpi_init_sleep(
84   "smpi/init", "Time to inject inside a call to MPI_Init", 0.0);
85
86 void (*smpi_comm_copy_data_callback) (smx_activity_t, void*, size_t) = &smpi_comm_copy_buffer_callback;
87
88
89
90 int smpi_process_count()
91 {
92   return process_count;
93 }
94
95 simgrid::smpi::Process* smpi_process()
96 {
97   simgrid::MsgActorExt* msgExt = static_cast<simgrid::MsgActorExt*>(SIMIX_process_self()->data);
98   return static_cast<simgrid::smpi::Process*>(msgExt->data);
99 }
100
101 simgrid::smpi::Process* smpi_process_remote(int index)
102 {
103   return process_data[index_to_process_data[index]];
104 }
105
106 MPI_Comm smpi_process_comm_self(){
107   return smpi_process()->comm_self();
108 }
109
110 void smpi_process_init(int *argc, char ***argv){
111   simgrid::smpi::Process::init(argc, argv);
112 }
113
114 int smpi_process_index(){
115   return smpi_process()->index();
116 }
117
118
119 int smpi_global_size()
120 {
121   char *value = getenv("SMPI_GLOBAL_SIZE");
122   xbt_assert(value,"Please set env var SMPI_GLOBAL_SIZE to the expected number of processes.");
123
124   return xbt_str_parse_int(value, "SMPI_GLOBAL_SIZE contains a non-numerical value: %s");
125 }
126
127 void smpi_comm_set_copy_data_callback(void (*callback) (smx_activity_t, void*, size_t))
128 {
129   smpi_comm_copy_data_callback = callback;
130 }
131
132 void smpi_comm_copy_buffer_callback(smx_activity_t synchro, void *buff, size_t buff_size)
133 {
134
135   simgrid::kernel::activity::Comm *comm = dynamic_cast<simgrid::kernel::activity::Comm*>(synchro);
136
137   XBT_DEBUG("Copy the data over");
138   if(smpi_is_shared(buff)){
139     XBT_DEBUG("Sender %p is shared. Let's ignore it.", buff);
140   }else if(smpi_is_shared((char*)comm->dst_buff)){
141     XBT_DEBUG("Receiver %p is shared. Let's ignore it.", (char*)comm->dst_buff);
142   }else{
143     void* tmpbuff=buff;
144     if((smpi_privatize_global_variables == SMPI_PRIVATIZE_MMAP) && (static_cast<char*>(buff) >= smpi_start_data_exe)
145         && (static_cast<char*>(buff) < smpi_start_data_exe + smpi_size_data_exe )
146       ){
147          XBT_DEBUG("Privatization : We are copying from a zone inside global memory... Saving data to temp buffer !");
148
149          smpi_switch_data_segment(
150              (static_cast<simgrid::smpi::Process*>((static_cast<simgrid::MsgActorExt*>(comm->src_proc->data)->data))->index()));
151          tmpbuff = static_cast<void*>(xbt_malloc(buff_size));
152          memcpy(tmpbuff, buff, buff_size);
153     }
154
155     if((smpi_privatize_global_variables == SMPI_PRIVATIZE_MMAP) && ((char*)comm->dst_buff >= smpi_start_data_exe)
156         && ((char*)comm->dst_buff < smpi_start_data_exe + smpi_size_data_exe )){
157          XBT_DEBUG("Privatization : We are copying to a zone inside global memory - Switch data segment");
158          smpi_switch_data_segment(
159              (static_cast<simgrid::smpi::Process*>((static_cast<simgrid::MsgActorExt*>(comm->dst_proc->data)->data))->index()));
160     }
161
162     XBT_DEBUG("Copying %zu bytes from %p to %p", buff_size, tmpbuff,comm->dst_buff);
163     memcpy(comm->dst_buff, tmpbuff, buff_size);
164
165     if (comm->detached) {
166       // if this is a detached send, the source buffer was duplicated by SMPI
167       // sender to make the original buffer available to the application ASAP
168       xbt_free(buff);
169       //It seems that the request is used after the call there this should be free somewhere else but where???
170       //xbt_free(comm->comm.src_data);// inside SMPI the request is kept inside the user data and should be free
171       comm->src_buff = nullptr;
172     }
173     if(tmpbuff!=buff)xbt_free(tmpbuff);
174   }
175
176 }
177
178 void smpi_comm_null_copy_buffer_callback(smx_activity_t comm, void *buff, size_t buff_size)
179 {
180   /* nothing done in this version */
181 }
182
183 static void smpi_check_options(){
184   //check correctness of MPI parameters
185
186    xbt_assert(xbt_cfg_get_int("smpi/async-small-thresh") <= xbt_cfg_get_int("smpi/send-is-detached-thresh"));
187
188    if (xbt_cfg_is_default_value("smpi/host-speed")) {
189      XBT_INFO("You did not set the power of the host running the simulation.  "
190               "The timings will certainly not be accurate.  "
191               "Use the option \"--cfg=smpi/host-speed:<flops>\" to set its value."
192               "Check http://simgrid.org/simgrid/latest/doc/options.html#options_smpi_bench for more information.");
193    }
194
195    xbt_assert(xbt_cfg_get_double("smpi/cpu-threshold") >=0,
196        "The 'smpi/cpu-threshold' option cannot have negative values [anymore]. If you want to discard "
197        "the simulation of any computation, please use 'smpi/simulate-computation:no' instead.");
198 }
199
200 int smpi_enabled() {
201   return process_data != nullptr;
202 }
203
204 void smpi_global_init()
205 {
206   MPI_Group group;
207
208   if (!MC_is_active()) {
209     global_timer = xbt_os_timer_new();
210     xbt_os_walltimer_start(global_timer);
211   }
212
213   if (xbt_cfg_get_string("smpi/comp-adjustment-file")[0] != '\0') { 
214     std::string filename {xbt_cfg_get_string("smpi/comp-adjustment-file")};
215     std::ifstream fstream(filename);
216     if (!fstream.is_open()) {
217       xbt_die("Could not open file %s. Does it exist?", filename.c_str());
218     }
219
220     std::string line;
221     typedef boost::tokenizer< boost::escaped_list_separator<char>> Tokenizer;
222     std::getline(fstream, line); // Skip the header line
223     while (std::getline(fstream, line)) {
224       Tokenizer tok(line);
225       Tokenizer::iterator it  = tok.begin();
226       Tokenizer::iterator end = std::next(tok.begin());
227
228       std::string location = *it;
229       boost::trim(location);
230       location2speedup.insert(std::pair<std::string, double>(location, std::stod(*end)));
231     }
232   }
233
234 #if HAVE_PAPI
235   // This map holds for each computation unit (such as "default" or "process1" etc.)
236   // the configuration as given by the user (counter data as a pair of (counter_name, counter_counter))
237   // and the (computed) event_set.
238   std::map</* computation unit name */ std::string, papi_process_data> units2papi_setup;
239
240   if (xbt_cfg_get_string("smpi/papi-events")[0] != '\0') {
241     if (PAPI_library_init(PAPI_VER_CURRENT) != PAPI_VER_CURRENT)
242       XBT_ERROR("Could not initialize PAPI library; is it correctly installed and linked?"
243                 " Expected version is %i",
244                 PAPI_VER_CURRENT);
245
246     typedef boost::tokenizer<boost::char_separator<char>> Tokenizer;
247     boost::char_separator<char> separator_units(";");
248     std::string str = std::string(xbt_cfg_get_string("smpi/papi-events"));
249     Tokenizer tokens(str, separator_units);
250
251     // Iterate over all the computational units. This could be
252     // processes, hosts, threads, ranks... You name it. I'm not exactly
253     // sure what we will support eventually, so I'll leave it at the
254     // general term "units".
255     for (auto& unit_it : tokens) {
256       boost::char_separator<char> separator_events(":");
257       Tokenizer event_tokens(unit_it, separator_events);
258
259       int event_set = PAPI_NULL;
260       if (PAPI_create_eventset(&event_set) != PAPI_OK) {
261         // TODO: Should this let the whole simulation die?
262         XBT_CRITICAL("Could not create PAPI event set during init.");
263       }
264
265       // NOTE: We cannot use a map here, as we must obey the order of the counters
266       // This is important for PAPI: We need to map the values of counters back
267       // to the event_names (so, when PAPI_read() has finished)!
268       papi_counter_t counters2values;
269
270       // Iterate over all counters that were specified for this specific
271       // unit.
272       // Note that we need to remove the name of the unit
273       // (that could also be the "default" value), which always comes first.
274       // Hence, we start at ++(events.begin())!
275       for (Tokenizer::iterator events_it = ++(event_tokens.begin()); events_it != event_tokens.end(); events_it++) {
276
277         int event_code   = PAPI_NULL;
278         char* event_name = const_cast<char*>((*events_it).c_str());
279         if (PAPI_event_name_to_code(event_name, &event_code) == PAPI_OK) {
280           if (PAPI_add_event(event_set, event_code) != PAPI_OK) {
281             XBT_ERROR("Could not add PAPI event '%s'. Skipping.", event_name);
282             continue;
283           } else {
284             XBT_DEBUG("Successfully added PAPI event '%s' to the event set.", event_name);
285           }
286         } else {
287           XBT_CRITICAL("Could not find PAPI event '%s'. Skipping.", event_name);
288           continue;
289         }
290
291         counters2values.push_back(
292             // We cannot just pass *events_it, as this is of type const basic_string
293             std::make_pair<std::string, long long>(std::string(*events_it), 0));
294       }
295
296       std::string unit_name    = *(event_tokens.begin());
297       papi_process_data config = {.counter_data = std::move(counters2values), .event_set = event_set};
298
299       units2papi_setup.insert(std::make_pair(unit_name, std::move(config)));
300     }
301   }
302 #endif
303
304   int smpirun = 0;
305   msg_bar_t finalization_barrier = nullptr;
306   if (process_count == 0){
307     process_count = SIMIX_process_count();
308     smpirun=1;
309     finalization_barrier = MSG_barrier_init(process_count);
310   }
311   smpi_universe_size = process_count;
312   process_data       = new simgrid::smpi::Process*[process_count];
313   for (int i = 0; i < process_count; i++) {
314     process_data[i] = new simgrid::smpi::Process(i, finalization_barrier);
315   }
316   //if the process was launched through smpirun script we generate a global mpi_comm_world
317   //if not, we let MPI_COMM_NULL, and the comm world will be private to each mpi instance
318   if (smpirun) {
319     group = new  simgrid::smpi::Group(process_count);
320     MPI_COMM_WORLD = new  simgrid::smpi::Comm(group, nullptr);
321     MPI_Attr_put(MPI_COMM_WORLD, MPI_UNIVERSE_SIZE, reinterpret_cast<void *>(process_count));
322
323     for (int i = 0; i < process_count; i++)
324       group->set_mapping(i, i);
325   }
326 }
327
328 void smpi_global_destroy()
329 {
330   int count = smpi_process_count();
331
332   smpi_bench_destroy();
333   smpi_shared_destroy();
334   if (MPI_COMM_WORLD != MPI_COMM_UNINITIALIZED){
335       delete MPI_COMM_WORLD->group();
336       MSG_barrier_destroy(process_data[0]->finalization_barrier());
337   }else{
338       smpi_deployment_cleanup_instances();
339   }
340   for (int i = 0; i < count; i++) {
341     if(process_data[i]->comm_self()!=MPI_COMM_NULL){
342       simgrid::smpi::Comm::destroy(process_data[i]->comm_self());
343     }
344     if(process_data[i]->comm_intra()!=MPI_COMM_NULL){
345       simgrid::smpi::Comm::destroy(process_data[i]->comm_intra());
346     }
347     xbt_os_timer_free(process_data[i]->timer());
348     xbt_mutex_destroy(process_data[i]->mailboxes_mutex());
349     delete process_data[i];
350   }
351   delete[] process_data;
352   process_data = nullptr;
353
354   if (MPI_COMM_WORLD != MPI_COMM_UNINITIALIZED){
355     MPI_COMM_WORLD->cleanup_smp();
356     MPI_COMM_WORLD->cleanup_attr<simgrid::smpi::Comm>();
357     if(simgrid::smpi::Colls::smpi_coll_cleanup_callback!=nullptr)
358       simgrid::smpi::Colls::smpi_coll_cleanup_callback();
359     delete MPI_COMM_WORLD;
360   }
361
362   MPI_COMM_WORLD = MPI_COMM_NULL;
363
364   if (!MC_is_active()) {
365     xbt_os_timer_free(global_timer);
366   }
367
368   xbt_free(index_to_process_data);
369   if(smpi_privatize_global_variables == SMPI_PRIVATIZE_MMAP)
370     smpi_destroy_global_memory_segments();
371   smpi_free_static();
372 }
373
374 extern "C" {
375
376 static void smpi_init_logs(){
377
378   /* Connect log categories.  See xbt/log.c */
379
380   XBT_LOG_CONNECT(smpi);  /* Keep this line as soon as possible in this function: xbt_log_appender_file.c depends on it
381                              DO NOT connect this in XBT or so, or it will be useless to xbt_log_appender_file.c */
382   XBT_LOG_CONNECT(instr_smpi);
383   XBT_LOG_CONNECT(smpi_bench);
384   XBT_LOG_CONNECT(smpi_coll);
385   XBT_LOG_CONNECT(smpi_colls);
386   XBT_LOG_CONNECT(smpi_comm);
387   XBT_LOG_CONNECT(smpi_datatype);
388   XBT_LOG_CONNECT(smpi_dvfs);
389   XBT_LOG_CONNECT(smpi_group);
390   XBT_LOG_CONNECT(smpi_kernel);
391   XBT_LOG_CONNECT(smpi_mpi);
392   XBT_LOG_CONNECT(smpi_memory);
393   XBT_LOG_CONNECT(smpi_op);
394   XBT_LOG_CONNECT(smpi_pmpi);
395   XBT_LOG_CONNECT(smpi_request);
396   XBT_LOG_CONNECT(smpi_replay);
397   XBT_LOG_CONNECT(smpi_rma);
398   XBT_LOG_CONNECT(smpi_shared);
399   XBT_LOG_CONNECT(smpi_utils);
400 }
401 }
402
403 static void smpi_init_options(){
404     //return if already called
405     if(smpi_cpu_threshold!=-1)
406       return;
407     simgrid::smpi::Colls::set_collectives();
408     simgrid::smpi::Colls::smpi_coll_cleanup_callback=nullptr;
409     smpi_cpu_threshold = xbt_cfg_get_double("smpi/cpu-threshold");
410     smpi_host_speed = xbt_cfg_get_double("smpi/host-speed");
411     const char* smpi_privatize_option = xbt_cfg_get_string("smpi/privatize-global-variables");
412     if (std::strcmp(smpi_privatize_option, "no") == 0)
413       smpi_privatize_global_variables = SMPI_PRIVATIZE_NONE;
414     else if (std::strcmp(smpi_privatize_option, "yes") == 0)
415       smpi_privatize_global_variables = SMPI_PRIVATIZE_DEFAULT;
416     else if (std::strcmp(smpi_privatize_option, "mmap") == 0)
417       smpi_privatize_global_variables = SMPI_PRIVATIZE_MMAP;
418     else if (std::strcmp(smpi_privatize_option, "dlopen") == 0)
419       smpi_privatize_global_variables = SMPI_PRIVATIZE_DLOPEN;
420
421     // Some compatibility stuff:
422     else if (std::strcmp(smpi_privatize_option, "1") == 0)
423       smpi_privatize_global_variables = SMPI_PRIVATIZE_DEFAULT;
424     else if (std::strcmp(smpi_privatize_option, "0") == 0)
425       smpi_privatize_global_variables = SMPI_PRIVATIZE_NONE;
426
427     else
428       xbt_die("Invalid value for smpi/privatize-global-variables: %s",
429         smpi_privatize_option);
430
431     if (smpi_cpu_threshold < 0)
432       smpi_cpu_threshold = DBL_MAX;
433
434     char* val = xbt_cfg_get_string("smpi/shared-malloc");
435     if (!strcasecmp(val, "yes") || !strcmp(val, "1") || !strcasecmp(val, "on") || !strcasecmp(val, "global")) {
436       smpi_cfg_shared_malloc = shmalloc_global;
437     } else if (!strcasecmp(val, "local")) {
438       smpi_cfg_shared_malloc = shmalloc_local;
439     } else if (!strcasecmp(val, "no") || !strcmp(val, "0") || !strcasecmp(val, "off")) {
440       smpi_cfg_shared_malloc = shmalloc_none;
441     } else {
442       xbt_die("Invalid value '%s' for option smpi/shared-malloc. Possible values: 'on' or 'global', 'local', 'off'",
443               val);
444     }
445 }
446
447 typedef std::function<int(int argc, char *argv[])> smpi_entry_point_type;
448 typedef int (* smpi_c_entry_point_type)(int argc, char **argv);
449 typedef void (* smpi_fortran_entry_point_type)(void);
450
451 static int smpi_run_entry_point(smpi_entry_point_type entry_point, std::vector<std::string> args)
452 {
453   const int argc = args.size();
454   std::unique_ptr<char*[]> argv(new char*[argc + 1]);
455   for (int i = 0; i != argc; ++i)
456     argv[i] = args[i].empty() ? const_cast<char*>(""): &args[i].front();
457   argv[argc] = nullptr;
458
459   int res = entry_point(argc, argv.get());
460   if (res != 0){
461     XBT_WARN("SMPI process did not return 0. Return value : %d", res);
462     smpi_process()->set_return_value(res);
463   }
464   return 0;
465 }
466
467 // TODO, remove the number of functions involved here
468 static smpi_entry_point_type smpi_resolve_function(void* handle)
469 {
470   smpi_fortran_entry_point_type entry_point2 =
471     (smpi_fortran_entry_point_type) dlsym(handle, "user_main_");
472   if (entry_point2 != nullptr) {
473     // fprintf(stderr, "EP user_main_=%p\n", entry_point2);
474     return [entry_point2](int argc, char** argv) {
475       smpi_process_init(&argc, &argv);
476       entry_point2();
477       return 0;
478     };
479   }
480
481   smpi_c_entry_point_type entry_point = (smpi_c_entry_point_type) dlsym(handle, "main");
482   if (entry_point != nullptr) {
483     // fprintf(stderr, "EP main=%p\n", entry_point);
484     return entry_point;
485   }
486
487   return smpi_entry_point_type();
488 }
489
490 int smpi_main(const char* executable, int argc, char *argv[])
491 {
492   srand(SMPI_RAND_SEED);
493
494   if (getenv("SMPI_PRETEND_CC") != nullptr) {
495     /* Hack to ensure that smpicc can pretend to be a simple compiler. Particularly handy to pass it to the
496      * configuration tools */
497     return 0;
498   }
499
500   TRACE_global_init(&argc, argv);
501
502   SIMIX_global_init(&argc, argv);
503   MSG_init(&argc,argv);
504
505   SMPI_switch_data_segment = &smpi_switch_data_segment;
506
507   simgrid::s4u::Host::onCreation.connect([](simgrid::s4u::Host& host) {
508     host.extension_set(new simgrid::smpi::SmpiHost(&host));
509   });
510
511   // parse the platform file: get the host list
512   SIMIX_create_environment(argv[1]);
513   SIMIX_comm_set_copy_data_callback(smpi_comm_copy_buffer_callback);
514
515   static std::size_t rank = 0;
516
517   smpi_init_options();
518
519   if (smpi_privatize_global_variables == SMPI_PRIVATIZE_DLOPEN) {
520
521     std::string executable_copy = executable;
522
523     // Prepare the copy of the binary (open the file and get its size)
524     // (fdin will remain open for the whole process execution. That's a sort of leak but we can live with it)
525     int fdin = open(executable_copy.c_str(), O_RDONLY);
526     xbt_assert(fdin >= 0, "Cannot read from %s", executable_copy.c_str());
527     struct stat fdin_stat;
528     fstat(fdin, &fdin_stat);
529     off_t fdin_size = fdin_stat.st_size;
530
531     simix_global->default_function = [executable_copy, fdin, fdin_size](std::vector<std::string> args) {
532       return std::function<void()>([executable_copy, fdin, fdin_size, args] {
533
534         // Copy the dynamic library:
535         std::string target_executable = executable_copy
536           + "_" + std::to_string(getpid())
537           + "_" + std::to_string(rank++) + ".so";
538
539         int fdout = open(target_executable.c_str(), O_WRONLY);
540         xbt_assert(fdout >= 0, "Cannot write into %s", target_executable.c_str());
541
542 #if HAVE_SENDFILE
543         sendfile(fdout, fdin, NULL, fdin_size);
544 #else
545         XBT_WARN("Copy %d bytes into %s", static_cast<int>(fdin_size), target_executable.c_str());
546         const int bufsize = 1024 * 1024 * 4;
547         char buf[bufsize];
548         while (int got = read(fdin, buf, bufsize)) {
549           if (got == -1) {
550             xbt_assert(errno == EINTR, "Cannot read from %s", executable_copy.c_str());
551           } else {
552             char* p  = buf;
553             int todo = got;
554             while (int done = write(fdout, p, todo)) {
555               if (done == -1) {
556                 xbt_assert(errno == EINTR, "Cannot write into %s", target_executable.c_str());
557               } else {
558                 p += done;
559                 todo -= done;
560               }
561             }
562           }
563         }
564 #endif
565         close(fdout);
566
567         // Load the copy and resolve the entry point:
568         void* handle = dlopen(target_executable.c_str(), RTLD_LAZY | RTLD_LOCAL | RTLD_DEEPBIND);
569         unlink(target_executable.c_str());
570         if (handle == nullptr)
571           xbt_die("dlopen failed");
572         smpi_entry_point_type entry_point = smpi_resolve_function(handle);
573         if (!entry_point)
574           xbt_die("Could not resolve entry point");
575
576         smpi_run_entry_point(entry_point, args);
577       });
578     };
579
580   }
581   else {
582
583     // Load the dynamic library and resolve the entry point:
584     void* handle = dlopen(executable, RTLD_LAZY | RTLD_LOCAL | RTLD_DEEPBIND);
585     if (handle == nullptr)
586       xbt_die("dlopen failed for %s", executable);
587     smpi_entry_point_type entry_point = smpi_resolve_function(handle);
588     if (!entry_point)
589       xbt_die("main not found in %s", executable);
590     // TODO, register the executable for SMPI privatization
591
592     // Execute the same entry point for each simulated process:
593     simix_global->default_function = [entry_point](std::vector<std::string> args) {
594       return std::function<void()>([entry_point, args] {
595         smpi_run_entry_point(entry_point, args);
596       });
597     };
598
599   }
600
601   SIMIX_launch_application(argv[2]);
602
603   SMPI_init();
604
605   /* Clean IO before the run */
606   fflush(stdout);
607   fflush(stderr);
608
609   if (MC_is_active()) {
610     MC_run();
611   } else {
612   
613     SIMIX_run();
614
615     xbt_os_walltimer_stop(global_timer);
616     if (xbt_cfg_get_boolean("smpi/display-timing")){
617       double global_time = xbt_os_timer_elapsed(global_timer);
618       XBT_INFO("Simulated time: %g seconds. \n\n"
619           "The simulation took %g seconds (after parsing and platform setup)\n"
620           "%g seconds were actual computation of the application",
621           SIMIX_get_clock(), global_time , smpi_total_benched_time);
622           
623       if (smpi_total_benched_time/global_time>=0.75)
624       XBT_INFO("More than 75%% of the time was spent inside the application code.\n"
625       "You may want to use sampling functions or trace replay to reduce this.");
626     }
627   }
628   int count = smpi_process_count();
629   int i, ret=0;
630   for (i = 0; i < count; i++) {
631     if(process_data[i]->return_value()!=0){
632       ret=process_data[i]->return_value();//return first non 0 value
633       break;
634     }
635   }
636   smpi_global_destroy();
637
638   TRACE_end();
639
640   return ret;
641 }
642
643 // Called either directly from the user code, or from the code called by smpirun
644 void SMPI_init(){
645   smpi_init_logs();
646   smpi_init_options();
647   smpi_global_init();
648   smpi_check_options();
649   TRACE_smpi_alloc();
650   simgrid::surf::surfExitCallbacks.connect(TRACE_smpi_release);
651   if(smpi_privatize_global_variables == SMPI_PRIVATIZE_MMAP)
652     smpi_initialize_global_memory_segments();
653 }
654
655 void SMPI_finalize(){
656   smpi_global_destroy();
657 }
658
659 void smpi_mpi_init() {
660   if(smpi_init_sleep > 0) 
661     simcall_process_sleep(smpi_init_sleep);
662 }
663
664 double smpi_mpi_wtime(){
665   double time;
666   if (smpi_process()->initialized() != 0 && smpi_process()->finalized() == 0 && smpi_process()->sampling() == 0) {
667     smpi_bench_end();
668     time = SIMIX_get_clock();
669     // to avoid deadlocks if used as a break condition, such as
670     //     while (MPI_Wtime(...) < time_limit) {
671     //       ....
672     //     }
673     // because the time will not normally advance when only calls to MPI_Wtime
674     // are made -> deadlock (MPI_Wtime never reaches the time limit)
675     if(smpi_wtime_sleep > 0) 
676       simcall_process_sleep(smpi_wtime_sleep);
677     smpi_bench_begin();
678   } else {
679     time = SIMIX_get_clock();
680   }
681   return time;
682 }
683