Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Replace const reference to std::string by std::string_view (sonar).
[simgrid.git] / src / smpi / internals / smpi_utils.cpp
1 /* Copyright (c) 2016-2022. The SimGrid Team.
2  * All rights reserved.                                                     */
3
4 /* This program is free software; you can redistribute it and/or modify it
5  * under the terms of the license (GNU LGPL) which comes with this package. */
6
7 #include "smpi_utils.hpp"
8
9 #include "private.hpp"
10 #include "smpi_config.hpp"
11 #include "src/surf/xml/platf.hpp"
12 #include "xbt/file.hpp"
13 #include "xbt/log.h"
14 #include "xbt/ex.h"
15 #include "xbt/parse_units.hpp"
16 #include "xbt/sysdep.h"
17 #include <algorithm>
18 #include <boost/tokenizer.hpp>
19
20 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(smpi_utils, smpi, "Logging specific to SMPI (utils)");
21
22 extern std::string surf_parsed_filename;
23 extern int surf_parse_lineno;
24
25 namespace simgrid {
26 namespace smpi {
27 namespace utils {
28
29 double total_benched_time=0;
30 unsigned long total_malloc_size=0;
31 unsigned long total_shared_size=0;
32 unsigned int total_shared_calls=0;
33 struct alloc_metadata_t {
34   size_t size          = 0;
35   unsigned int numcall = 0;
36   int line             = 0;
37   std::string file;
38 };
39
40 struct current_buffer_metadata_t {
41   alloc_metadata_t alloc;
42   std::string name;
43 };
44
45 alloc_metadata_t max_malloc;
46 F2C* current_handle = nullptr;
47 current_buffer_metadata_t current_buffer1;
48 current_buffer_metadata_t current_buffer2;
49
50 std::unordered_map<const void*, alloc_metadata_t> allocs;
51
52 std::unordered_map<int, std::vector<std::string>> collective_calls;
53
54 std::vector<s_smpi_factor_t> parse_factor(const std::string& smpi_coef_string)
55 {
56   std::vector<s_smpi_factor_t> smpi_factor;
57
58   /** Setup the tokenizer that parses the string **/
59   using Tokenizer = boost::tokenizer<boost::char_separator<char>>;
60   boost::char_separator<char> sep(";");
61   boost::char_separator<char> factor_separator(":");
62   Tokenizer tokens(smpi_coef_string, sep);
63
64   /**
65    * Iterate over patterns like A:B:C:D;E:F;G:H
66    * These will be broken down into:
67    * A --> B, C, D
68    * E --> F
69    * G --> H
70    */
71   for (auto token_iter = tokens.begin(); token_iter != tokens.end(); ++token_iter) {
72     XBT_DEBUG("token: %s", token_iter->c_str());
73     Tokenizer factor_values(*token_iter, factor_separator);
74     s_smpi_factor_t fact;
75     xbt_assert(factor_values.begin() != factor_values.end(), "Malformed radical for smpi factor: '%s'",
76                smpi_coef_string.c_str());
77     unsigned int iteration = 0;
78     for (auto factor_iter = factor_values.begin(); factor_iter != factor_values.end(); ++factor_iter) {
79       iteration++;
80
81       if (factor_iter == factor_values.begin()) { /* first element */
82         try {
83           fact.factor = std::stoi(*factor_iter);
84         } catch (const std::invalid_argument&) {
85           throw std::invalid_argument(std::string("Invalid factor in chunk ") + std::to_string(smpi_factor.size() + 1) +
86                                       ": " + *factor_iter);
87         }
88       } else {
89         try {
90           fact.values.push_back(xbt_parse_get_time(surf_parsed_filename, surf_parse_lineno, *factor_iter, ""));
91         } catch (const std::invalid_argument&) {
92           throw std::invalid_argument(std::string("Invalid factor value ") + std::to_string(iteration) + " in chunk " +
93                                       std::to_string(smpi_factor.size() + 1) + ": " + *factor_iter);
94         }
95       }
96     }
97
98     smpi_factor.push_back(fact);
99     XBT_DEBUG("smpi_factor:\t%zu: %zu values, first: %f", fact.factor, smpi_factor.size(), fact.values[0]);
100   }
101   std::sort(smpi_factor.begin(), smpi_factor.end(), [](const s_smpi_factor_t &pa, const s_smpi_factor_t &pb) {
102     return (pa.factor < pb.factor);
103   });
104   for (auto const& fact : smpi_factor) {
105     XBT_DEBUG("smpi_factor:\t%zu: %zu values, first: %f", fact.factor, smpi_factor.size(), fact.values[0]);
106   }
107   smpi_factor.shrink_to_fit();
108
109   return smpi_factor;
110 }
111
112 void add_benched_time(double time){
113   total_benched_time += time;
114 }
115
116 void account_malloc_size(size_t size, std::string_view file, int line, const void* ptr)
117 {
118   if (smpi_cfg_display_alloc()) {
119     alloc_metadata_t metadata;
120     metadata.size = size;
121     metadata.line = line;
122     metadata.numcall = 1;
123     metadata.file    = file;
124     allocs.try_emplace(ptr, metadata);
125
126     total_malloc_size += size;
127     if(size > max_malloc.size){
128       max_malloc.size = size;
129       max_malloc.line = line;
130       max_malloc.numcall = 1;
131       max_malloc.file    = file;
132     } else if (size == max_malloc.size && max_malloc.line == line && max_malloc.file == file) {
133       max_malloc.numcall++;
134     }
135   }
136 }
137
138 void account_shared_size(size_t size){
139   if (smpi_cfg_display_alloc()) {
140     total_shared_size += size;
141     total_shared_calls++;
142   }
143 }
144
145 void print_time_analysis(double global_time){
146   if (simgrid::config::get_value<bool>("smpi/display-timing")) {
147     XBT_INFO("Simulated time: %g seconds. \n\n"
148              "The simulation took %g seconds (after parsing and platform setup)\n"
149              "%g seconds were actual computation of the application",
150              simgrid_get_clock(), global_time, total_benched_time);
151     if (total_benched_time/global_time>=0.75)
152       XBT_INFO("More than 75%% of the time was spent inside the application code.\n"
153     "You may want to use sampling functions or trace replay to reduce this.");
154   }
155 }
156
157 static void print_leaked_handles()
158 {
159   // Put the leaked non-default handles in a vector to sort them by id
160   std::vector<std::pair<unsigned int, smpi::F2C*>> handles;
161   if (simgrid::smpi::F2C::lookup() != nullptr)
162     std::copy_if(simgrid::smpi::F2C::lookup()->begin(), simgrid::smpi::F2C::lookup()->end(),
163                  std::back_inserter(handles),
164                  [](auto const& entry) { return entry.first >= simgrid::smpi::F2C::get_num_default_handles(); });
165   if (handles.empty())
166     return;
167
168   auto max            = static_cast<unsigned long>(simgrid::config::get_value<int>("smpi/list-leaks"));
169   std::string message = "Probable memory leaks in your code: SMPI detected %zu unfreed MPI handles:";
170   if (max == 0)
171     message += "\nHINT: Display types and addresses (n max) with --cfg=smpi/list-leaks:n.\n"
172                "Running smpirun with -wrapper \"valgrind --leak-check=full\" can provide more information";
173   XBT_INFO(message.c_str(), handles.size());
174   if (max == 0)
175     return;
176
177   // we cannot trust F2C::lookup()->size() > F2C::get_num_default_handles() because some default handles are already
178   // freed at this point
179   bool display_advice = false;
180   std::map<std::string, int, std::less<>> count;
181   for (const auto& [_, elem] : handles) {
182     std::string key = elem->name();
183     if ((not xbt_log_no_loc) && (not elem->call_location().empty()))
184       key += " at " + elem->call_location();
185     else
186       display_advice = true;
187     auto& result = count.try_emplace(key, 0).first->second;
188     result++;
189   }
190   if (display_advice)
191     XBT_WARN("To get more information (location of allocations), compile your code with -trace-call-location flag of "
192              "smpicc/f90");
193   unsigned int i = 0;
194   for (const auto& [key, value] : count) {
195     if (value == 1)
196       XBT_INFO("leaked handle of type %s", key.c_str());
197     else
198       XBT_INFO("%d leaked handles of type %s", value, key.c_str());
199     i++;
200     if (i == max)
201       break;
202   }
203   if (max < count.size())
204     XBT_INFO("(%lu more handle leaks hidden as you wanted to see only %lu of them)", count.size() - max, max);
205 }
206
207 static void print_leaked_buffers()
208 {
209   if (allocs.empty())
210     return;
211
212   auto max            = static_cast<unsigned long>(simgrid::config::get_value<int>("smpi/list-leaks"));
213   std::string message = "Probable memory leaks in your code: SMPI detected %zu unfreed buffers:";
214   if (max == 0)
215     message += "display types and addresses (n max) with --cfg=smpi/list-leaks:n.\nRunning smpirun with -wrapper "
216                "\"valgrind --leak-check=full\" can provide more information";
217   XBT_INFO(message.c_str(), allocs.size());
218
219   if (max == 0)
220     return;
221
222   // gather by allocation origin (only one group reported in case of no-loc or if trace-call-location is not used)
223   struct buff_leak {
224     int count;
225     size_t total_size;
226     size_t min_size;
227     size_t max_size;
228   };
229   std::map<std::string, struct buff_leak, std::less<>> leaks_aggreg;
230   for (const auto& [_, elem] : allocs) {
231     std::string key = "leaked allocations";
232     if (not xbt_log_no_loc)
233       key = elem.file + ":" + std::to_string(elem.line) + ": " + key;
234     auto& result = leaks_aggreg.try_emplace(key, buff_leak{0, 0, elem.size, elem.size}).first->second;
235     result.count++;
236     result.total_size += elem.size;
237     if (elem.size > result.max_size)
238       result.max_size = elem.size;
239     else if (elem.size < result.min_size)
240       result.min_size = elem.size;
241   }
242   // now we can order by total size.
243   std::vector<std::pair<std::string, buff_leak>> leaks(leaks_aggreg.begin(), leaks_aggreg.end());
244   std::sort(leaks.begin(), leaks.end(),
245             [](auto const& a, auto const& b) { return a.second.total_size > b.second.total_size; });
246
247   unsigned int i = 0;
248   for (const auto& [key, value] : leaks) {
249     if (value.min_size == value.max_size)
250       XBT_INFO("%s of total size %zu, called %d times, each with size %zu", key.c_str(), value.total_size, value.count,
251                value.min_size);
252     else
253       XBT_INFO("%s of total size %zu, called %d times, with minimum size %zu and maximum size %zu", key.c_str(),
254                value.total_size, value.count, value.min_size, value.max_size);
255     i++;
256     if (i == max)
257       break;
258   }
259   if (max < leaks_aggreg.size())
260     XBT_INFO("(more buffer leaks hidden as you wanted to see only %lu of them)", max);
261 }
262
263 void print_memory_analysis()
264 {
265   if (smpi_cfg_display_alloc()) {
266     print_leaked_handles();
267     print_leaked_buffers();
268
269     if(total_malloc_size != 0)
270       XBT_INFO("Memory Usage: Simulated application allocated %lu bytes during its lifetime through malloc/calloc calls.\n"
271              "Largest allocation at once from a single process was %zu bytes, at %s:%d. It was called %u times during the whole simulation.\n"
272              "If this is too much, consider sharing allocations for computation buffers.\n"
273              "This can be done automatically by setting --cfg=smpi/auto-shared-malloc-thresh to the minimum size wanted size (this can alter execution if data content is necessary)\n",
274              total_malloc_size, max_malloc.size, simgrid::xbt::Path(max_malloc.file).get_base_name().c_str(), max_malloc.line, max_malloc.numcall
275       );
276     else
277       XBT_INFO(
278           "Allocations analysis asked, but 0 bytes were allocated through malloc/calloc calls intercepted by SMPI.\n"
279           "The code may not use malloc() to allocate memory, or it was built with SMPI_NO_OVERRIDE_MALLOC");
280     if(total_shared_size != 0)
281       XBT_INFO("%lu bytes were automatically shared between processes, in %u calls\n", total_shared_size, total_shared_calls);
282   }
283 }
284
285 void set_current_handle(F2C* handle){
286   current_handle=handle;
287 }
288
289 void print_current_handle(){
290   if(current_handle){
291     if(current_handle->call_location().empty())
292       XBT_INFO("To get handle location information, pass -trace-call-location flag to smpicc/f90 as well");
293     else
294       XBT_INFO("Handle %s was allocated by a call at %s", current_handle->name().c_str(),
295                (char*)(current_handle->call_location().c_str()));
296   }
297 }
298
299 void set_current_buffer(int i, const char* name, const void* buf){
300   //clear previous one
301   if(i==1){
302     if(not current_buffer1.name.empty()){
303       current_buffer1.name="";
304     }
305     if(not current_buffer2.name.empty()){
306       current_buffer2.name="";
307     }
308   }
309   auto meta = allocs.find(buf);
310   if (meta == allocs.end()) {
311     XBT_DEBUG("Buffer %p was not allocated with malloc/calloc", buf);
312     return;
313   }
314   if(i==1){
315     current_buffer1.alloc = meta->second;
316     current_buffer1.name = name;
317   }else{
318     current_buffer2.alloc=meta->second;
319     current_buffer2.name=name;
320   }
321 }
322
323 void print_buffer_info()
324 {
325   if (not current_buffer1.name.empty())
326     XBT_INFO("Buffer %s was allocated from %s line %d, with size %zu", current_buffer1.name.c_str(),
327              current_buffer1.alloc.file.c_str(), current_buffer1.alloc.line, current_buffer1.alloc.size);
328   if (not current_buffer2.name.empty())
329     XBT_INFO("Buffer %s was allocated from %s line %d, with size %zu", current_buffer2.name.c_str(),
330              current_buffer2.alloc.file.c_str(), current_buffer2.alloc.line, current_buffer2.alloc.size);
331 }
332
333 size_t get_buffer_size(const void* buf){
334   auto meta = allocs.find(buf);
335   if (meta == allocs.end()) {
336     //we don't know this buffer (on stack or feature disabled), assume it's fine.
337     return  std::numeric_limits<std::size_t>::max();
338   }
339   return meta->second.size;
340 }
341
342 void account_free(const void* ptr){
343   if (smpi_cfg_display_alloc()) {
344     allocs.erase(ptr);
345   }
346 }
347
348 int check_collectives_ordering(MPI_Comm comm, const std::string& call)
349 {
350   unsigned int count = comm->get_collectives_count();
351   comm->increment_collectives_count();
352   if (auto vec = collective_calls.find(comm->id()); vec == collective_calls.end()) {
353     collective_calls.try_emplace(comm->id(), std::vector<std::string>{call});
354   } else {
355     // are we the first ? add the call
356     if (vec->second.size() == count) {
357       vec->second.emplace_back(call);
358     } else if (vec->second.size() > count) {
359       if (vec->second[count] != call) {
360         XBT_WARN("Collective operation mismatch. For process %ld, expected %s, got %s",
361                  simgrid::s4u::this_actor::get_pid(), vec->second[count].c_str(), call.c_str());
362         return MPI_ERR_OTHER;
363       }
364     } else {
365       THROW_IMPOSSIBLE;
366     }
367   }
368   return MPI_SUCCESS;
369 }
370 }
371 }
372 } // namespace simgrid