Logo AND Algorithmique Numérique Distribuée

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