Logo AND Algorithmique Numérique Distribuée

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