Logo AND Algorithmique Numérique Distribuée

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