Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Don't free there for intel compiler, it breaks.
[simgrid.git] / src / smpi / internals / smpi_global.cpp
1 /* Copyright (c) 2007-2018. 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/s4u/Engine.hpp"
8 #include "smpi_coll.hpp"
9 #include "smpi_f2c.hpp"
10 #include "smpi_host.hpp"
11 #include "src/kernel/activity/CommImpl.hpp"
12 #include "src/simix/smx_private.hpp"
13 #include "src/smpi/include/smpi_actor.hpp"
14 #include "xbt/config.hpp"
15
16 #include <cfloat> /* DBL_MAX */
17 #include <dlfcn.h>
18 #include <fcntl.h>
19 #include <fstream>
20
21 #if not defined(__APPLE__)
22 #include <link.h>
23 #endif
24
25 #if defined(__APPLE__)
26 # include <AvailabilityMacros.h>
27 # ifndef MAC_OS_X_VERSION_10_12
28 #   define MAC_OS_X_VERSION_10_12 101200
29 # endif
30 # define HAVE_WORKING_MMAP (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_12)
31 #elif defined(__FreeBSD__)
32 # define HAVE_WORKING_MMAP 0
33 #else
34 # define HAVE_WORKING_MMAP 1
35 #endif
36
37 #if HAVE_SENDFILE
38 #include <sys/sendfile.h>
39 #endif
40
41 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(smpi_kernel, smpi, "Logging specific to SMPI (kernel)");
42 #include <boost/tokenizer.hpp>
43 #include <boost/algorithm/string.hpp> /* trim_right / trim_left */
44
45 #if SMPI_IFORT
46   extern "C" void for_rtl_init_ (int *, char **);
47   extern "C" void for_rtl_finish_ ();
48 #elif SMPI_FLANG
49   extern "C" void __io_set_argc(int);
50   extern "C" void __io_set_argv(char **);
51 #elif SMPI_GFORTRAN
52   extern "C" void _gfortran_set_args(int, char **);
53 #endif
54
55 #ifndef RTLD_DEEPBIND
56 /* RTLD_DEEPBIND is a bad idea of GNU ld that obviously does not exist on other platforms
57  * See https://www.akkadia.org/drepper/dsohowto.pdf
58  * and https://lists.freebsd.org/pipermail/freebsd-current/2016-March/060284.html
59 */
60 #define RTLD_DEEPBIND 0
61 #endif
62
63 #if HAVE_PAPI
64 #include "papi.h"
65 std::string papi_default_config_name = "default";
66 std::map</* computation unit name */ std::string, papi_process_data> units2papi_setup;
67 #endif
68
69 using simgrid::s4u::Actor;
70 using simgrid::s4u::ActorPtr;
71 std::unordered_map<std::string, double> location2speedup;
72
73 static std::map</*process_id*/ ActorPtr, simgrid::smpi::ActorExt*> process_data;
74 int process_count = 0;
75 static int smpi_exit_status = 0;
76 int smpi_universe_size = 0;
77 extern double smpi_total_benched_time;
78 xbt_os_timer_t global_timer;
79 static std::vector<std::string> privatize_libs_paths;
80 /**
81  * Setting MPI_COMM_WORLD to MPI_COMM_UNINITIALIZED (it's a variable)
82  * is important because the implementation of MPI_Comm checks
83  * "this == MPI_COMM_UNINITIALIZED"? If yes, it uses smpi_process()->comm_world()
84  * instead of "this".
85  * This is basically how we only have one global variable but all processes have
86  * different communicators (the one their SMPI instance uses).
87  *
88  * See smpi_comm.cpp and the functions therein for details.
89  */
90 MPI_Comm MPI_COMM_WORLD = MPI_COMM_UNINITIALIZED;
91 MPI_Errhandler *MPI_ERRORS_RETURN = nullptr;
92 MPI_Errhandler *MPI_ERRORS_ARE_FATAL = nullptr;
93 MPI_Errhandler *MPI_ERRHANDLER_NULL = nullptr;
94 // No instance gets manually created; check also the smpirun.in script as
95 // this default name is used there as well (when the <actor> tag is generated).
96 static const std::string smpi_default_instance_name("smpirun");
97 static simgrid::config::Flag<double> smpi_wtime_sleep(
98   "smpi/wtime", "Minimum time to inject inside a call to MPI_Wtime", 0.0);
99 static simgrid::config::Flag<double> smpi_init_sleep(
100   "smpi/init", "Time to inject inside a call to MPI_Init", 0.0);
101
102 void (*smpi_comm_copy_data_callback) (smx_activity_t, void*, size_t) = &smpi_comm_copy_buffer_callback;
103
104 int smpi_process_count()
105 {
106   return process_count;
107 }
108
109 simgrid::smpi::ActorExt* smpi_process()
110 {
111   ActorPtr me = Actor::self();
112
113   if (me == nullptr) // This happens sometimes (eg, when linking against NS3 because it pulls openMPI...)
114     return nullptr;
115
116   return process_data.at(me);
117 }
118
119 simgrid::smpi::ActorExt* smpi_process_remote(ActorPtr actor)
120 {
121   return process_data.at(actor);
122 }
123
124 MPI_Comm smpi_process_comm_self(){
125   return smpi_process()->comm_self();
126 }
127
128 void smpi_process_init(int *argc, char ***argv){
129   simgrid::smpi::ActorExt::init(argc, argv);
130 }
131
132 int smpi_process_index(){
133   return simgrid::s4u::this_actor::get_pid();
134 }
135
136 void * smpi_process_get_user_data(){
137   return Actor::self()->get_impl()->get_user_data();
138 }
139
140 void smpi_process_set_user_data(void *data){
141   Actor::self()->get_impl()->set_user_data(data);
142 }
143
144
145 int smpi_global_size()
146 {
147   char *value = getenv("SMPI_GLOBAL_SIZE");
148   xbt_assert(value,"Please set env var SMPI_GLOBAL_SIZE to the expected number of processes.");
149
150   return xbt_str_parse_int(value, "SMPI_GLOBAL_SIZE contains a non-numerical value: %s");
151 }
152
153 void smpi_comm_set_copy_data_callback(void (*callback) (smx_activity_t, void*, size_t))
154 {
155   smpi_comm_copy_data_callback = callback;
156 }
157
158 static void memcpy_private(void* dest, const void* src, std::vector<std::pair<size_t, size_t>>& private_blocks)
159 {
160   for (auto const& block : private_blocks)
161     memcpy((uint8_t*)dest+block.first, (uint8_t*)src+block.first, block.second-block.first);
162 }
163
164 static void check_blocks(std::vector<std::pair<size_t, size_t>> &private_blocks, size_t buff_size) {
165   for (auto const& block : private_blocks)
166     xbt_assert(block.first <= block.second && block.second <= buff_size, "Oops, bug in shared malloc.");
167 }
168
169 void smpi_comm_copy_buffer_callback(smx_activity_t synchro, void *buff, size_t buff_size)
170 {
171   simgrid::kernel::activity::CommImplPtr comm =
172       boost::dynamic_pointer_cast<simgrid::kernel::activity::CommImpl>(synchro);
173   int src_shared                        = 0;
174   int dst_shared                        = 0;
175   size_t src_offset                     = 0;
176   size_t dst_offset                     = 0;
177   std::vector<std::pair<size_t, size_t>> src_private_blocks;
178   std::vector<std::pair<size_t, size_t>> dst_private_blocks;
179   XBT_DEBUG("Copy the data over");
180   if((src_shared=smpi_is_shared(buff, src_private_blocks, &src_offset))) {
181     XBT_DEBUG("Sender %p is shared. Let's ignore it.", buff);
182     src_private_blocks = shift_and_frame_private_blocks(src_private_blocks, src_offset, buff_size);
183   }
184   else {
185     src_private_blocks.clear();
186     src_private_blocks.push_back(std::make_pair(0, buff_size));
187   }
188   if((dst_shared=smpi_is_shared((char*)comm->dst_buff, dst_private_blocks, &dst_offset))) {
189     XBT_DEBUG("Receiver %p is shared. Let's ignore it.", (char*)comm->dst_buff);
190     dst_private_blocks = shift_and_frame_private_blocks(dst_private_blocks, dst_offset, buff_size);
191   }
192   else {
193     dst_private_blocks.clear();
194     dst_private_blocks.push_back(std::make_pair(0, buff_size));
195   }
196   check_blocks(src_private_blocks, buff_size);
197   check_blocks(dst_private_blocks, buff_size);
198   auto private_blocks = merge_private_blocks(src_private_blocks, dst_private_blocks);
199   check_blocks(private_blocks, buff_size);
200   void* tmpbuff=buff;
201   if ((smpi_privatize_global_variables == SmpiPrivStrategies::MMAP) &&
202       (static_cast<char*>(buff) >= smpi_data_exe_start) &&
203       (static_cast<char*>(buff) < smpi_data_exe_start + smpi_data_exe_size)) {
204     XBT_DEBUG("Privatization : We are copying from a zone inside global memory... Saving data to temp buffer !");
205     smpi_switch_data_segment(comm->src_proc->iface());
206     tmpbuff = static_cast<void*>(xbt_malloc(buff_size));
207     memcpy_private(tmpbuff, buff, private_blocks);
208   }
209
210   if ((smpi_privatize_global_variables == SmpiPrivStrategies::MMAP) && ((char*)comm->dst_buff >= smpi_data_exe_start) &&
211       ((char*)comm->dst_buff < smpi_data_exe_start + smpi_data_exe_size)) {
212     XBT_DEBUG("Privatization : We are copying to a zone inside global memory - Switch data segment");
213     smpi_switch_data_segment(comm->dst_proc->iface());
214   }
215   XBT_DEBUG("Copying %zu bytes from %p to %p", buff_size, tmpbuff,comm->dst_buff);
216   memcpy_private(comm->dst_buff, tmpbuff, private_blocks);
217
218   if (comm->detached) {
219     // if this is a detached send, the source buffer was duplicated by SMPI
220     // sender to make the original buffer available to the application ASAP
221     xbt_free(buff);
222     //It seems that the request is used after the call there this should be free somewhere else but where???
223     //xbt_free(comm->comm.src_data);// inside SMPI the request is kept inside the user data and should be free
224     comm->src_buff = nullptr;
225   }
226   if (tmpbuff != buff)
227     xbt_free(tmpbuff);
228 }
229
230 void smpi_comm_null_copy_buffer_callback(smx_activity_t comm, void *buff, size_t buff_size)
231 {
232   /* nothing done in this version */
233 }
234
235 static void smpi_check_options()
236 {
237   //check correctness of MPI parameters
238
239   xbt_assert(simgrid::config::get_value<int>("smpi/async-small-thresh") <=
240              simgrid::config::get_value<int>("smpi/send-is-detached-thresh"));
241
242   if (simgrid::config::is_default("smpi/host-speed")) {
243     XBT_INFO("You did not set the power of the host running the simulation.  "
244              "The timings will certainly not be accurate.  "
245              "Use the option \"--cfg=smpi/host-speed:<flops>\" to set its value."
246              "Check http://simgrid.org/simgrid/latest/doc/options.html#options_smpi_bench for more information.");
247   }
248
249   xbt_assert(simgrid::config::get_value<double>("smpi/cpu-threshold") >= 0,
250              "The 'smpi/cpu-threshold' option cannot have negative values [anymore]. If you want to discard "
251              "the simulation of any computation, please use 'smpi/simulate-computation:no' instead.");
252 }
253
254 int smpi_enabled() {
255   return not process_data.empty();
256 }
257
258 void smpi_global_init()
259 {
260   if (not MC_is_active()) {
261     global_timer = xbt_os_timer_new();
262     xbt_os_walltimer_start(global_timer);
263   }
264
265   std::string filename = simgrid::config::get_value<std::string>("smpi/comp-adjustment-file");
266   if (not filename.empty()) {
267     std::ifstream fstream(filename);
268     if (not fstream.is_open()) {
269       xbt_die("Could not open file %s. Does it exist?", filename.c_str());
270     }
271
272     std::string line;
273     typedef boost::tokenizer< boost::escaped_list_separator<char>> Tokenizer;
274     std::getline(fstream, line); // Skip the header line
275     while (std::getline(fstream, line)) {
276       Tokenizer tok(line);
277       Tokenizer::iterator it  = tok.begin();
278       Tokenizer::iterator end = std::next(tok.begin());
279
280       std::string location = *it;
281       boost::trim(location);
282       location2speedup.insert(std::pair<std::string, double>(location, std::stod(*end)));
283     }
284   }
285
286 #if HAVE_PAPI
287   // This map holds for each computation unit (such as "default" or "process1" etc.)
288   // the configuration as given by the user (counter data as a pair of (counter_name, counter_counter))
289   // and the (computed) event_set.
290
291   if (not simgrid::config::get_value<std::string>("smpi/papi-events").empty()) {
292     if (PAPI_library_init(PAPI_VER_CURRENT) != PAPI_VER_CURRENT)
293       XBT_ERROR("Could not initialize PAPI library; is it correctly installed and linked?"
294                 " Expected version is %u", PAPI_VER_CURRENT);
295
296     typedef boost::tokenizer<boost::char_separator<char>> Tokenizer;
297     boost::char_separator<char> separator_units(";");
298     std::string str = simgrid::config::get_value<std::string>("smpi/papi-events");
299     Tokenizer tokens(str, separator_units);
300
301     // Iterate over all the computational units. This could be processes, hosts, threads, ranks... You name it.
302     // I'm not exactly sure what we will support eventually, so I'll leave it at the general term "units".
303     for (auto const& unit_it : tokens) {
304       boost::char_separator<char> separator_events(":");
305       Tokenizer event_tokens(unit_it, separator_events);
306
307       int event_set = PAPI_NULL;
308       if (PAPI_create_eventset(&event_set) != PAPI_OK) {
309         // TODO: Should this let the whole simulation die?
310         XBT_CRITICAL("Could not create PAPI event set during init.");
311       }
312
313       // NOTE: We cannot use a map here, as we must obey the order of the counters
314       // This is important for PAPI: We need to map the values of counters back
315       // to the event_names (so, when PAPI_read() has finished)!
316       papi_counter_t counters2values;
317
318       // Iterate over all counters that were specified for this specific
319       // unit.
320       // Note that we need to remove the name of the unit
321       // (that could also be the "default" value), which always comes first.
322       // Hence, we start at ++(events.begin())!
323       for (Tokenizer::iterator events_it = ++(event_tokens.begin()); events_it != event_tokens.end(); ++events_it) {
324
325         int event_code   = PAPI_NULL;
326         char* event_name = const_cast<char*>((*events_it).c_str());
327         if (PAPI_event_name_to_code(event_name, &event_code) == PAPI_OK) {
328           if (PAPI_add_event(event_set, event_code) != PAPI_OK) {
329             XBT_ERROR("Could not add PAPI event '%s'. Skipping.", event_name);
330             continue;
331           } else {
332             XBT_DEBUG("Successfully added PAPI event '%s' to the event set.", event_name);
333           }
334         } else {
335           XBT_CRITICAL("Could not find PAPI event '%s'. Skipping.", event_name);
336           continue;
337         }
338
339         counters2values.push_back(
340             // We cannot just pass *events_it, as this is of type const basic_string
341             std::make_pair<std::string, long long>(std::string(*events_it), 0));
342       }
343
344       std::string unit_name    = *(event_tokens.begin());
345       papi_process_data config = {.counter_data = std::move(counters2values), .event_set = event_set};
346
347       units2papi_setup.insert(std::make_pair(unit_name, std::move(config)));
348     }
349   }
350 #endif
351 }
352
353 void smpi_global_destroy()
354 {
355   smpi_bench_destroy();
356   smpi_shared_destroy();
357   smpi_deployment_cleanup_instances();
358
359   if (simgrid::smpi::Colls::smpi_coll_cleanup_callback != nullptr)
360     simgrid::smpi::Colls::smpi_coll_cleanup_callback();
361
362   MPI_COMM_WORLD = MPI_COMM_NULL;
363
364   if (not MC_is_active()) {
365     xbt_os_timer_free(global_timer);
366   }
367
368   if (smpi_privatize_global_variables == SmpiPrivStrategies::MMAP)
369     smpi_destroy_global_memory_segments();
370   smpi_free_static();
371   if(simgrid::smpi::F2C::lookup() != nullptr)
372     simgrid::smpi::F2C::delete_lookup();
373 }
374
375 static void smpi_init_options(){
376   // return if already called
377   if (smpi_cpu_threshold > -1)
378     return;
379   simgrid::smpi::Colls::set_collectives();
380   simgrid::smpi::Colls::smpi_coll_cleanup_callback = nullptr;
381   smpi_cpu_threshold                               = simgrid::config::get_value<double>("smpi/cpu-threshold");
382   smpi_host_speed                                  = simgrid::config::get_value<double>("smpi/host-speed");
383   xbt_assert(smpi_host_speed > 0.0, "You're trying to set the host_speed to a non-positive value (given: %f)", smpi_host_speed);
384   std::string smpi_privatize_option = simgrid::config::get_value<std::string>("smpi/privatization");
385   if (smpi_privatize_option == "no" || smpi_privatize_option == "0")
386     smpi_privatize_global_variables = SmpiPrivStrategies::NONE;
387   else if (smpi_privatize_option == "yes" || smpi_privatize_option == "1")
388     smpi_privatize_global_variables = SmpiPrivStrategies::DEFAULT;
389   else if (smpi_privatize_option == "mmap")
390     smpi_privatize_global_variables = SmpiPrivStrategies::MMAP;
391   else if (smpi_privatize_option == "dlopen")
392     smpi_privatize_global_variables = SmpiPrivStrategies::DLOPEN;
393   else
394     xbt_die("Invalid value for smpi/privatization: '%s'", smpi_privatize_option.c_str());
395
396   if (not SMPI_switch_data_segment) {
397     XBT_DEBUG("Running without smpi_main(); disable smpi/privatization.");
398     smpi_privatize_global_variables = SmpiPrivStrategies::NONE;
399   }
400 #if !HAVE_WORKING_MMAP
401   if (smpi_privatize_global_variables == SmpiPrivStrategies::MMAP) {
402     XBT_INFO("mmap privatization is broken on this platform, switching to dlopen privatization instead.");
403     smpi_privatize_global_variables = SmpiPrivStrategies::DLOPEN;
404   }
405 #endif
406
407   if (smpi_cpu_threshold < 0)
408     smpi_cpu_threshold = DBL_MAX;
409
410   std::string val = simgrid::config::get_value<std::string>("smpi/shared-malloc");
411   if ((val == "yes") || (val == "1") || (val == "on") || (val == "global")) {
412     smpi_cfg_shared_malloc = SharedMallocType::GLOBAL;
413   } else if (val == "local") {
414     smpi_cfg_shared_malloc = SharedMallocType::LOCAL;
415   } else if ((val == "no") || (val == "0") || (val == "off")) {
416     smpi_cfg_shared_malloc = SharedMallocType::NONE;
417   } else {
418     xbt_die("Invalid value '%s' for option smpi/shared-malloc. Possible values: 'on' or 'global', 'local', 'off'",
419             val.c_str());
420   }
421 }
422
423 typedef std::function<int(int argc, char *argv[])> smpi_entry_point_type;
424 typedef int (* smpi_c_entry_point_type)(int argc, char **argv);
425 typedef void (*smpi_fortran_entry_point_type)();
426
427 static int smpi_run_entry_point(smpi_entry_point_type entry_point, std::vector<std::string> args)
428 {
429   char noarg[]   = {'\0'};
430   int argc = args.size();
431   char** argv = new char*[argc + 1];
432   for (int i = 0; i != argc; ++i)
433     argv[i] = args[i].empty() ? noarg : xbt_strdup(&args[i].front());
434   argv[argc] = nullptr;
435   simgrid::smpi::ActorExt::init(&argc, &argv);
436 #if SMPI_IFORT
437   for_rtl_init_ (&argc, argv);
438 #elif SMPI_FLANG
439   __io_set_argc(argc);
440   __io_set_argv(argv);
441 #elif SMPI_GFORTRAN
442   _gfortran_set_args(argc, argv);
443 #endif 
444   int res = entry_point(argc, argv);
445
446 #if SMPI_IFORT
447   for_rtl_finish_ ();
448 #else
449   for (int i = 0; i != argc; ++i)
450     xbt_free(argv[i]);
451   xbt_free(argv);
452 #endif
453
454   if (res != 0){
455     XBT_WARN("SMPI process did not return 0. Return value : %d", res);
456     if (smpi_exit_status == 0)
457       smpi_exit_status = res;
458   }
459   return 0;
460 }
461
462
463 // TODO, remove the number of functions involved here
464 static smpi_entry_point_type smpi_resolve_function(void* handle)
465 {
466   smpi_fortran_entry_point_type entry_point_fortran = (smpi_fortran_entry_point_type)dlsym(handle, "user_main_");
467   if (entry_point_fortran != nullptr) {
468     return [entry_point_fortran](int argc, char** argv) {
469       entry_point_fortran();
470       return 0;
471     };
472   }
473
474   smpi_c_entry_point_type entry_point = (smpi_c_entry_point_type)dlsym(handle, "main");
475   if (entry_point != nullptr) {
476     return entry_point;
477   }
478
479   return smpi_entry_point_type();
480 }
481
482 static void smpi_copy_file(std::string src, std::string target, off_t fdin_size)
483 {
484   int fdin = open(src.c_str(), O_RDONLY);
485   xbt_assert(fdin >= 0, "Cannot read from %s. Please make sure that the file exists and is executable.", src.c_str());
486   int fdout = open(target.c_str(), O_CREAT | O_RDWR, S_IRWXU);
487   xbt_assert(fdout >= 0, "Cannot write into %s", target.c_str());
488
489   XBT_DEBUG("Copy %ld bytes into %s", static_cast<long>(fdin_size), target.c_str());
490 #if HAVE_SENDFILE
491   ssize_t sent_size = sendfile(fdout, fdin, NULL, fdin_size);
492   xbt_assert(sent_size == fdin_size, "Error while copying %s: only %zd bytes copied instead of %ld (errno: %d -- %s)",
493              target.c_str(), sent_size, fdin_size, errno, strerror(errno));
494 #else
495   const int bufsize = 1024 * 1024 * 4;
496   char buf[bufsize];
497   while (int got = read(fdin, buf, bufsize)) {
498     if (got == -1) {
499       xbt_assert(errno == EINTR, "Cannot read from %s", src.c_str());
500     } else {
501       char* p  = buf;
502       int todo = got;
503       while (int done = write(fdout, p, todo)) {
504         if (done == -1) {
505           xbt_assert(errno == EINTR, "Cannot write into %s", target.c_str());
506         } else {
507           p += done;
508           todo -= done;
509         }
510       }
511     }
512   }
513 #endif
514   close(fdin);
515   close(fdout);
516 }
517
518 #if not defined(__APPLE__)
519 static int visit_libs(struct dl_phdr_info* info, size_t, void* data)
520 {
521   char* libname = (char*)(data);
522   const char *path = info->dlpi_name;
523   if(strstr(path, libname)){
524     strncpy(libname, path, 512);
525     return 1;
526   }
527   
528   return 0;
529 }
530 #endif
531
532 static void smpi_init_privatization_dlopen(std::string executable)
533 {
534   // Prepare the copy of the binary (get its size)
535   struct stat fdin_stat;
536   stat(executable.c_str(), &fdin_stat);
537   off_t fdin_size         = fdin_stat.st_size;
538   static std::size_t rank = 0;
539
540   std::string libnames = simgrid::config::get_value<std::string>("smpi/privatize-libs");
541   if (not libnames.empty()) {
542     // split option
543     std::vector<std::string> privatize_libs;
544     boost::split(privatize_libs, libnames, boost::is_any_of(";"));
545
546     for (auto const& libname : privatize_libs) {
547       // load the library once to add it to the local libs, to get the absolute path
548       void* libhandle = dlopen(libname.c_str(), RTLD_LAZY);
549       // get library name from path
550       char fullpath[512] = {'\0'};
551       strcpy(fullpath, libname.c_str());
552 #if not defined(__APPLE__)
553       int ret = dl_iterate_phdr(visit_libs, fullpath);
554       if (ret == 0)
555         xbt_die("Can't find a linked %s - check the setting you gave to smpi/privatize-libs", fullpath);
556       else
557         XBT_DEBUG("Extra lib to privatize found : %s", fullpath);
558 #else
559       xbt_die("smpi/privatize-libs is not (yet) compatible with OSX");
560 #endif
561       privatize_libs_paths.push_back(fullpath);
562       dlclose(libhandle);
563     }
564   }
565
566   simix_global->default_function = [executable, fdin_size](std::vector<std::string> args) {
567     return std::function<void()>([executable, fdin_size, args] {
568
569       // Copy the dynamic library:
570       std::string target_executable =
571           executable + "_" + std::to_string(getpid()) + "_" + std::to_string(rank) + ".so";
572
573       smpi_copy_file(executable, target_executable, fdin_size);
574       // if smpi/privatize-libs is set, duplicate pointed lib and link each executable copy to a different one.
575       std::string target_lib;
576       for (auto const& libpath : privatize_libs_paths) {
577         // if we were given a full path, strip it
578         size_t index = libpath.find_last_of("/\\");
579         std::string libname;
580         if (index != std::string::npos)
581           libname = libpath.substr(index + 1);
582
583         if (not libname.empty()) {
584           // load the library to add it to the local libs, to get the absolute path
585           struct stat fdin_stat2;
586           stat(libpath.c_str(), &fdin_stat2);
587           off_t fdin_size2 = fdin_stat2.st_size;
588
589           // Copy the dynamic library, the new name must be the same length as the old one
590           // just replace the name with 7 digits for the rank and the rest of the name.
591           unsigned int pad = 7;
592           if (libname.length() < pad)
593             pad = libname.length();
594           target_lib =
595               std::string(pad - std::to_string(rank).length(), '0') + std::to_string(rank) + libname.substr(pad);
596           XBT_DEBUG("copy lib %s to %s, with size %lld", libpath.c_str(), target_lib.c_str(), (long long)fdin_size2);
597           smpi_copy_file(libpath, target_lib, fdin_size2);
598
599           std::string sedcommand = "sed -i -e 's/" + libname + "/" + target_lib + "/g' " + target_executable;
600           int ret                = system(sedcommand.c_str());
601           if (ret != 0)
602             xbt_die("error while applying sed command %s \n", sedcommand.c_str());
603         }
604       }
605
606       rank++;
607       // Load the copy and resolve the entry point:
608       void* handle    = dlopen(target_executable.c_str(), RTLD_LAZY | RTLD_LOCAL | RTLD_DEEPBIND);
609       int saved_errno = errno;
610       if (simgrid::config::get_value<bool>("smpi/keep-temps") == false) {
611         unlink(target_executable.c_str());
612         if (not target_lib.empty())
613           unlink(target_lib.c_str());
614       }
615       if (handle == nullptr)
616         xbt_die("dlopen failed: %s (errno: %d -- %s)", dlerror(), saved_errno, strerror(saved_errno));
617       smpi_entry_point_type entry_point = smpi_resolve_function(handle);
618       if (not entry_point)
619         xbt_die("Could not resolve entry point");
620       smpi_run_entry_point(entry_point, args);
621     });
622   };
623 }
624
625 static void smpi_init_privatization_no_dlopen(std::string executable)
626 {
627   if (smpi_privatize_global_variables == SmpiPrivStrategies::MMAP)
628     smpi_prepare_global_memory_segment();
629   // Load the dynamic library and resolve the entry point:
630   void* handle = dlopen(executable.c_str(), RTLD_LAZY | RTLD_LOCAL);
631   if (handle == nullptr)
632     xbt_die("dlopen failed for %s: %s (errno: %d -- %s)", executable.c_str(), dlerror(), errno, strerror(errno));
633   smpi_entry_point_type entry_point = smpi_resolve_function(handle);
634   if (not entry_point)
635     xbt_die("main not found in %s", executable.c_str());
636   if (smpi_privatize_global_variables == SmpiPrivStrategies::MMAP)
637     smpi_backup_global_memory_segment();
638
639   // Execute the same entry point for each simulated process:
640   simix_global->default_function = [entry_point](std::vector<std::string> args) {
641     return std::function<void()>([entry_point, args] { smpi_run_entry_point(entry_point, args); });
642   };
643 }
644
645 int smpi_main(const char* executable, int argc, char* argv[])
646 {
647   srand(SMPI_RAND_SEED);
648
649   if (getenv("SMPI_PRETEND_CC") != nullptr) {
650     /* Hack to ensure that smpicc can pretend to be a simple compiler. Particularly handy to pass it to the
651      * configuration tools */
652     return 0;
653   }
654
655   TRACE_global_init();
656   SIMIX_global_init(&argc, argv);
657
658   SMPI_switch_data_segment = &smpi_switch_data_segment;
659
660   // TODO This will not be executed in the case where smpi_main is not called,
661   // e.g., not for smpi_msg_masterslave. This should be moved to another location
662   // that is always called -- maybe close to Actor::on_creation?
663   simgrid::s4u::Host::on_creation.connect(
664       [](simgrid::s4u::Host& host) { host.extension_set(new simgrid::smpi::Host(&host)); });
665
666   // parse the platform file: get the host list
667   simgrid::s4u::Engine::get_instance()->load_platform(argv[1]);
668   SIMIX_comm_set_copy_data_callback(smpi_comm_copy_buffer_callback);
669
670   smpi_init_options();
671   if (smpi_privatize_global_variables == SmpiPrivStrategies::DLOPEN)
672     smpi_init_privatization_dlopen(executable);
673   else
674     smpi_init_privatization_no_dlopen(executable);
675
676   SMPI_init();
677   simgrid::s4u::Engine::get_instance()->load_deployment(argv[2]);
678   SMPI_app_instance_register(smpi_default_instance_name.c_str(), nullptr,
679                              process_data.size()); // This call has a side effect on process_count...
680   MPI_COMM_WORLD = *smpi_deployment_comm_world(smpi_default_instance_name);
681   smpi_universe_size = process_count;
682
683
684   /* Clean IO before the run */
685   fflush(stdout);
686   fflush(stderr);
687
688   if (MC_is_active()) {
689     MC_run();
690   } else {
691
692     SIMIX_run();
693
694     xbt_os_walltimer_stop(global_timer);
695     if (simgrid::config::get_value<bool>("smpi/display-timing")) {
696       double global_time = xbt_os_timer_elapsed(global_timer);
697       XBT_INFO("Simulated time: %g seconds. \n\n"
698           "The simulation took %g seconds (after parsing and platform setup)\n"
699           "%g seconds were actual computation of the application",
700           SIMIX_get_clock(), global_time , smpi_total_benched_time);
701
702       if (smpi_total_benched_time/global_time>=0.75)
703       XBT_INFO("More than 75%% of the time was spent inside the application code.\n"
704       "You may want to use sampling functions or trace replay to reduce this.");
705     }
706   }
707   smpi_global_destroy();
708
709   return smpi_exit_status;
710 }
711
712 // Called either directly from the user code, or from the code called by smpirun
713 void SMPI_init(){
714   simgrid::s4u::Actor::on_creation.connect([](simgrid::s4u::ActorPtr actor) {
715     if (not actor->is_daemon()) {
716       process_data.insert({actor, new simgrid::smpi::ActorExt(actor, nullptr)});
717     }
718   });
719   simgrid::s4u::Actor::on_destruction.connect([](simgrid::s4u::ActorPtr actor) {
720     auto it = process_data.find(actor);
721     if (it != process_data.end()) {
722       delete it->second;
723       process_data.erase(it);
724     }
725   });
726
727   smpi_init_options();
728   smpi_global_init();
729   smpi_check_options();
730 }
731
732 void SMPI_finalize(){
733   smpi_global_destroy();
734 }
735
736 void smpi_mpi_init() {
737   smpi_init_fortran_types();
738   if(smpi_init_sleep > 0)
739     simcall_process_sleep(smpi_init_sleep);
740 }
741
742 double smpi_mpi_wtime(){
743   double time;
744   if (smpi_process()->initialized() != 0 && smpi_process()->finalized() == 0 && smpi_process()->sampling() == 0) {
745     smpi_bench_end();
746     time = SIMIX_get_clock();
747     // to avoid deadlocks if used as a break condition, such as
748     //     while (MPI_Wtime(...) < time_limit) {
749     //       ....
750     //     }
751     // because the time will not normally advance when only calls to MPI_Wtime
752     // are made -> deadlock (MPI_Wtime never reaches the time limit)
753     if(smpi_wtime_sleep > 0)
754       simcall_process_sleep(smpi_wtime_sleep);
755     smpi_bench_begin();
756   } else {
757     time = SIMIX_get_clock();
758   }
759   return time;
760 }
761