Logo AND Algorithmique Numérique Distribuée

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