Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Portability fun with FreeBSD
[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
405     simgrid::smpi::Colls::set_collectives();
406     simgrid::smpi::Colls::smpi_coll_cleanup_callback=nullptr;
407     smpi_cpu_threshold = xbt_cfg_get_double("smpi/cpu-threshold");
408     smpi_host_speed = xbt_cfg_get_double("smpi/host-speed");
409     const char* smpi_privatize_option = xbt_cfg_get_string("smpi/privatize-global-variables");
410     if (std::strcmp(smpi_privatize_option, "no") == 0)
411       smpi_privatize_global_variables = SMPI_PRIVATIZE_NONE;
412     else if (std::strcmp(smpi_privatize_option, "yes") == 0)
413       smpi_privatize_global_variables = SMPI_PRIVATIZE_DEFAULT;
414     else if (std::strcmp(smpi_privatize_option, "mmap") == 0)
415       smpi_privatize_global_variables = SMPI_PRIVATIZE_MMAP;
416     else if (std::strcmp(smpi_privatize_option, "dlopen") == 0)
417       smpi_privatize_global_variables = SMPI_PRIVATIZE_DLOPEN;
418
419     // Some compatibility stuff:
420     else if (std::strcmp(smpi_privatize_option, "1") == 0)
421       smpi_privatize_global_variables = SMPI_PRIVATIZE_DEFAULT;
422     else if (std::strcmp(smpi_privatize_option, "0") == 0)
423       smpi_privatize_global_variables = SMPI_PRIVATIZE_NONE;
424
425     else
426       xbt_die("Invalid value for smpi/privatize-global-variables: %s",
427         smpi_privatize_option);
428
429     if (smpi_cpu_threshold < 0)
430       smpi_cpu_threshold = DBL_MAX;
431
432     char* val = xbt_cfg_get_string("smpi/shared-malloc");
433     if (!strcasecmp(val, "yes") || !strcmp(val, "1") || !strcasecmp(val, "on") || !strcasecmp(val, "global")) {
434       smpi_cfg_shared_malloc = shmalloc_global;
435     } else if (!strcasecmp(val, "local")) {
436       smpi_cfg_shared_malloc = shmalloc_local;
437     } else if (!strcasecmp(val, "no") || !strcmp(val, "0") || !strcasecmp(val, "off")) {
438       smpi_cfg_shared_malloc = shmalloc_none;
439     } else {
440       xbt_die("Invalid value '%s' for option smpi/shared-malloc. Possible values: 'on' or 'global', 'local', 'off'",
441               val);
442     }
443 }
444
445 static int execute_command(const char * const argv[])
446 {
447   pid_t pid;
448   int status;
449   if (posix_spawnp(&pid, argv[0], nullptr, nullptr, (char* const*) argv, environ) != 0)
450     return 127;
451   if (waitpid(pid, &status, 0) != pid)
452     return 127;
453   return status;
454 }
455
456 typedef std::function<int(int argc, char *argv[])> smpi_entry_point_type;
457 typedef int (* smpi_c_entry_point_type)(int argc, char **argv);
458 typedef void (* smpi_fortran_entry_point_type)(void);
459
460 static int smpi_run_entry_point(smpi_entry_point_type entry_point, std::vector<std::string> args)
461 {
462   const int argc = args.size();
463   std::unique_ptr<char*[]> argv(new char*[argc + 1]);
464   for (int i = 0; i != argc; ++i)
465     argv[i] = args[i].empty() ? const_cast<char*>(""): &args[i].front();
466   argv[argc] = nullptr;
467
468   int res = entry_point(argc, argv.get());
469   if (res != 0){
470     XBT_WARN("SMPI process did not return 0. Return value : %d", res);
471     smpi_process()->set_return_value(res);
472   }
473   return 0;
474 }
475
476 // TODO, remove the number of functions involved here
477 static smpi_entry_point_type smpi_resolve_function(void* handle)
478 {
479   smpi_fortran_entry_point_type entry_point2 =
480     (smpi_fortran_entry_point_type) dlsym(handle, "user_main_");
481   if (entry_point2 != nullptr) {
482     // fprintf(stderr, "EP user_main_=%p\n", entry_point2);
483     return [entry_point2](int argc, char** argv) {
484       smpi_process_init(&argc, &argv);
485       entry_point2();
486       return 0;
487     };
488   }
489
490   smpi_c_entry_point_type entry_point = (smpi_c_entry_point_type) dlsym(handle, "main");
491   if (entry_point != nullptr) {
492     // fprintf(stderr, "EP main=%p\n", entry_point);
493     return entry_point;
494   }
495
496   return smpi_entry_point_type();
497 }
498
499 int smpi_main(const char* executable, int argc, char *argv[])
500 {
501   srand(SMPI_RAND_SEED);
502
503   if (getenv("SMPI_PRETEND_CC") != nullptr) {
504     /* Hack to ensure that smpicc can pretend to be a simple compiler. Particularly handy to pass it to the
505      * configuration tools */
506     return 0;
507   }
508
509   TRACE_global_init(&argc, argv);
510
511   SIMIX_global_init(&argc, argv);
512   MSG_init(&argc,argv);
513
514   SMPI_switch_data_segment = &smpi_switch_data_segment;
515
516   simgrid::s4u::Host::onCreation.connect([](simgrid::s4u::Host& host) {
517     host.extension_set(new simgrid::smpi::SmpiHost(&host));
518   });
519
520   // parse the platform file: get the host list
521   SIMIX_create_environment(argv[1]);
522   SIMIX_comm_set_copy_data_callback(smpi_comm_copy_buffer_callback);
523
524   static std::size_t rank = 0;
525
526   if (smpi_privatize_global_variables == SMPI_PRIVATIZE_DLOPEN) {
527
528     std::string executable_copy = executable;
529
530     // Prepare the copy of the binary (open the file and get its size)
531     // (fdin will remain open for the whole process execution. That's a sort of leak but we can live with it)
532     int fdin = open(executable_copy.c_str(), O_RDONLY);
533     xbt_assert(fdin >= 0, "Cannot read from %s", executable_copy.c_str());
534     struct stat fdin_stat;
535     fstat(fdin, &fdin_stat);
536     off_t fdin_size = fdin_stat.st_size;
537
538     simix_global->default_function = [executable_copy, fdin, fdin_size](std::vector<std::string> args) {
539       return std::function<void()>([executable_copy, fdin, fdin_size, args] {
540
541         // Copy the dynamic library:
542         std::string target_executable = executable_copy
543           + "_" + std::to_string(getpid())
544           + "_" + std::to_string(rank++) + ".so";
545
546         int fdout = open(target_executable.c_str(), O_WRONLY);
547         xbt_assert(fdout >= 0, "Cannot write into %s", target_executable.c_str());
548
549 #if HAVE_SENDFILE
550         sendfile(fdout, fdin, NULL, fdin_size);
551 #else
552         XBT_WARN("Copy %d bytes into %s", static_cast<int>(fdin_size), target_executable.c_str());
553         const int bufsize = 1024 * 1024 * 4;
554         char buf[bufsize];
555         while (int got = read(fdin, buf, bufsize)) {
556           if (got == -1) {
557             xbt_assert(errno == EINTR, "Cannot read from %s", executable_copy.c_str());
558           } else {
559             char* p  = buf;
560             int todo = got;
561             while (int done = write(fdout, p, todo)) {
562               if (done == -1) {
563                 xbt_assert(errno == EINTR, "Cannot write into %s", target_executable.c_str());
564               } else {
565                 p += done;
566                 todo -= done;
567               }
568             }
569           }
570         }
571 #endif
572         close(fdout);
573
574         // Load the copy and resolve the entry point:
575         void* handle = dlopen(target_executable.c_str(), RTLD_LAZY | RTLD_LOCAL | RTLD_DEEPBIND);
576         unlink(target_executable.c_str());
577         if (handle == nullptr)
578           xbt_die("dlopen failed");
579         smpi_entry_point_type entry_point = smpi_resolve_function(handle);
580         if (!entry_point)
581           xbt_die("Could not resolve entry point");
582
583         smpi_run_entry_point(entry_point, args);
584       });
585     };
586
587   }
588   else {
589
590     // Load the dynamic library and resolve the entry point:
591     void* handle = dlopen(executable, RTLD_LAZY | RTLD_LOCAL | RTLD_DEEPBIND);
592     if (handle == nullptr)
593       xbt_die("dlopen failed for %s", executable);
594     smpi_entry_point_type entry_point = smpi_resolve_function(handle);
595     if (!entry_point)
596       xbt_die("main not found in %s", executable);
597     // TODO, register the executable for SMPI privatization
598
599     // Execute the same entry point for each simulated process:
600     simix_global->default_function = [entry_point](std::vector<std::string> args) {
601       return std::function<void()>([entry_point, args] {
602         smpi_run_entry_point(entry_point, args);
603       });
604     };
605
606   }
607
608   SIMIX_launch_application(argv[2]);
609
610   SMPI_init();
611
612   /* Clean IO before the run */
613   fflush(stdout);
614   fflush(stderr);
615
616   if (MC_is_active()) {
617     MC_run();
618   } else {
619   
620     SIMIX_run();
621
622     xbt_os_walltimer_stop(global_timer);
623     if (xbt_cfg_get_boolean("smpi/display-timing")){
624       double global_time = xbt_os_timer_elapsed(global_timer);
625       XBT_INFO("Simulated time: %g seconds. \n\n"
626           "The simulation took %g seconds (after parsing and platform setup)\n"
627           "%g seconds were actual computation of the application",
628           SIMIX_get_clock(), global_time , smpi_total_benched_time);
629           
630       if (smpi_total_benched_time/global_time>=0.75)
631       XBT_INFO("More than 75%% of the time was spent inside the application code.\n"
632       "You may want to use sampling functions or trace replay to reduce this.");
633     }
634   }
635   int count = smpi_process_count();
636   int i, ret=0;
637   for (i = 0; i < count; i++) {
638     if(process_data[i]->return_value()!=0){
639       ret=process_data[i]->return_value();//return first non 0 value
640       break;
641     }
642   }
643   smpi_global_destroy();
644
645   TRACE_end();
646
647   return ret;
648 }
649
650 // Called either directly from the user code, or from the code called by smpirun
651 void SMPI_init(){
652   smpi_init_logs();
653   smpi_init_options();
654   smpi_global_init();
655   smpi_check_options();
656   TRACE_smpi_alloc();
657   simgrid::surf::surfExitCallbacks.connect(TRACE_smpi_release);
658   if(smpi_privatize_global_variables == SMPI_PRIVATIZE_MMAP)
659     smpi_initialize_global_memory_segments();
660 }
661
662 void SMPI_finalize(){
663   smpi_global_destroy();
664 }
665
666 void smpi_mpi_init() {
667   if(smpi_init_sleep > 0) 
668     simcall_process_sleep(smpi_init_sleep);
669 }
670
671 double smpi_mpi_wtime(){
672   double time;
673   if (smpi_process()->initialized() != 0 && smpi_process()->finalized() == 0 && smpi_process()->sampling() == 0) {
674     smpi_bench_end();
675     time = SIMIX_get_clock();
676     // to avoid deadlocks if used as a break condition, such as
677     //     while (MPI_Wtime(...) < time_limit) {
678     //       ....
679     //     }
680     // because the time will not normally advance when only calls to MPI_Wtime
681     // are made -> deadlock (MPI_Wtime never reaches the time limit)
682     if(smpi_wtime_sleep > 0) 
683       simcall_process_sleep(smpi_wtime_sleep);
684     smpi_bench_begin();
685   } else {
686     time = SIMIX_get_clock();
687   }
688   return time;
689 }
690