Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Count all intercepted allocations/deallocations in order to build a small leak-checker.
[simgrid.git] / src / smpi / internals / smpi_utils.cpp
1 /* Copyright (c) 2016-2021. 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 "src/surf/xml/platf_private.hpp"
10 #include "xbt/log.h"
11 #include "xbt/parse_units.hpp"
12 #include "xbt/sysdep.h"
13 #include "xbt/file.hpp"
14 #include <boost/tokenizer.hpp>
15 #include "smpi_config.hpp"
16 #include "src/simix/smx_private.hpp"
17 #include <algorithm>
18 #include "private.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::vector<s_smpi_factor_t> parse_factor(const std::string& smpi_coef_string)
53 {
54   std::vector<s_smpi_factor_t> smpi_factor;
55
56   /** Setup the tokenizer that parses the string **/
57   using Tokenizer = boost::tokenizer<boost::char_separator<char>>;
58   boost::char_separator<char> sep(";");
59   boost::char_separator<char> factor_separator(":");
60   Tokenizer tokens(smpi_coef_string, sep);
61
62   /**
63    * Iterate over patterns like A:B:C:D;E:F;G:H
64    * These will be broken down into:
65    * A --> B, C, D
66    * E --> F
67    * G --> H
68    */
69   for (Tokenizer::iterator token_iter = tokens.begin(); token_iter != tokens.end(); ++token_iter) {
70     XBT_DEBUG("token : %s", token_iter->c_str());
71     Tokenizer factor_values(*token_iter, factor_separator);
72     s_smpi_factor_t fact;
73     xbt_assert(factor_values.begin() != factor_values.end(), "Malformed radical for smpi factor: '%s'",
74                smpi_coef_string.c_str());
75     unsigned int iteration = 0;
76     for (Tokenizer::iterator factor_iter = factor_values.begin(); factor_iter != factor_values.end(); ++factor_iter) {
77       iteration++;
78
79       if (factor_iter == factor_values.begin()) { /* first element */
80         try {
81           fact.factor = std::stoi(*factor_iter);
82         } catch (const std::invalid_argument&) {
83           throw std::invalid_argument(std::string("Invalid factor in chunk ") + std::to_string(smpi_factor.size() + 1) +
84                                       ": " + *factor_iter);
85         }
86       } else {
87         try {
88           fact.values.push_back(
89               xbt_parse_get_time(surf_parsed_filename, surf_parse_lineno, (*factor_iter).c_str(), "smpi factor", ""));
90         } catch (const std::invalid_argument&) {
91           throw std::invalid_argument(std::string("Invalid factor value ") + std::to_string(iteration) + " in chunk " +
92                                       std::to_string(smpi_factor.size() + 1) + ": " + *factor_iter);
93         }
94       }
95     }
96
97     smpi_factor.push_back(fact);
98     XBT_DEBUG("smpi_factor:\t%zu : %zu values, first: %f", fact.factor, smpi_factor.size(), fact.values[0]);
99   }
100   std::sort(smpi_factor.begin(), smpi_factor.end(), [](const s_smpi_factor_t &pa, const s_smpi_factor_t &pb) {
101     return (pa.factor < pb.factor);
102   });
103   for (auto const& fact : smpi_factor) {
104     XBT_DEBUG("smpi_factor:\t%zu : %zu values, first: %f", fact.factor, smpi_factor.size() ,fact.values[0]);
105   }
106   smpi_factor.shrink_to_fit();
107
108   return smpi_factor;
109 }
110
111 void add_benched_time(double time){
112   total_benched_time += time;
113 }
114
115 void account_malloc_size(size_t size, std::string file, int line, void* ptr){
116   if (smpi_cfg_display_alloc()) {
117     alloc_metadata_t metadata;
118     metadata.size = size;
119     metadata.line = line;
120     metadata.numcall = 1;
121     metadata.file = std::string(file);
122     allocs.insert(std::make_pair(ptr, metadata));
123
124     total_malloc_size += size;
125     if(size > max_malloc.size){
126       max_malloc.size = size;
127       max_malloc.line = line;
128       max_malloc.numcall = 1;
129       max_malloc.file = std::string(file);
130     }else if(size == max_malloc.size && max_malloc.line == line && not max_malloc.file.compare(file)){
131       max_malloc.numcall++;
132     }
133   }
134 }
135
136 void account_shared_size(size_t size){
137   if (smpi_cfg_display_alloc()) {
138     total_shared_size += size;
139     total_shared_calls++;
140   }
141 }
142
143 void print_time_analysis(double global_time){
144   if (simgrid::config::get_value<bool>("smpi/display-timing")) {
145     XBT_INFO("Simulated time: %g seconds. \n\n"
146         "The simulation took %g seconds (after parsing and platform setup)\n"
147         "%g seconds were actual computation of the application",
148         SIMIX_get_clock(), global_time , total_benched_time);
149     if (total_benched_time/global_time>=0.75)
150       XBT_INFO("More than 75%% of the time was spent inside the application code.\n"
151     "You may want to use sampling functions or trace replay to reduce this.");
152   }
153 }
154
155 void print_memory_analysis()
156 {
157   if (smpi_cfg_display_alloc()) {
158     // Put the leaked non-default handles in a vector to sort them by id
159     std::vector<std::pair<unsigned int, smpi::F2C*>> handles;
160     if (simgrid::smpi::F2C::lookup() != nullptr)
161       std::copy_if(simgrid::smpi::F2C::lookup()->begin(), simgrid::smpi::F2C::lookup()->end(),
162                    std::back_inserter(handles),
163                    [](auto const& entry) { return entry.first >= simgrid::smpi::F2C::get_num_default_handles(); });
164
165     auto max = static_cast<unsigned long>(simgrid::config::get_value<int>("smpi/list-leaks"));
166     if (not handles.empty()) {
167       XBT_INFO("Probable memory leaks in your code: SMPI detected %zu unfreed MPI handles : "
168                "display types and addresses (n max) with --cfg=smpi/list-leaks:n.\n"
169                "Running smpirun with -wrapper \"valgrind --leak-check=full\" can provide more information",
170                handles.size());
171       if (max > 0) { // we cannot trust F2C::lookup()->size() > F2C::get_num_default_handles() because some default
172                      // handles are already freed at this point
173         std::sort(handles.begin(), handles.end(), [](auto const& a, auto const& b) { return a.first < b.first; });
174         bool truncate = max < handles.size();
175         if (truncate)
176           handles.resize(max);
177         bool printed_advice=false;
178         for (const auto& p : handles) {
179           if (xbt_log_no_loc || p.second->call_location().empty()) {
180             if (!printed_advice){
181               XBT_INFO("To get more information (location of allocations), compile your code with -trace-call-location flag of smpicc/f90");
182               printed_advice=true;
183             }
184             XBT_INFO("Leaked handle of type %s", p.second->name().c_str());
185           } else {
186             XBT_INFO("Leaked handle of type %s at %s", p.second->name().c_str(), p.second->call_location().c_str());
187           }
188         }
189         if (truncate)
190           XBT_INFO("(more handle leaks hidden as you wanted to see only %lu of them)", max);
191       }
192     }
193
194     if (not allocs.empty()) {
195       std::vector<std::pair<const void*, alloc_metadata_t>> leaks;
196       std::copy(allocs.begin(),
197               allocs.end(),
198               std::back_inserter<std::vector<std::pair<const void*, alloc_metadata_t>>>(leaks));
199       XBT_INFO("Probable memory leaks in your code: SMPI detected %zu unfreed buffers : "
200                "display types and addresses (n max) with --cfg=smpi/list-leaks:n.\n"
201                "Running smpirun with -wrapper \"valgrind --leak-check=full\" can provide more information",
202                leaks.size());
203       if (max > 0) {
204         std::sort(leaks.begin(), leaks.end(), [](auto const& a, auto const& b) { return a.second.size < b.second.size; });
205         bool truncate = max < leaks.size();
206         if (truncate)
207           leaks.resize(max);
208         for (const auto& p : leaks) {
209           if (xbt_log_no_loc) {
210             XBT_INFO("Leaked buffer of size %zu", p.second.size);
211           } else {
212             XBT_INFO("Leaked buffer of size %zu, allocated in file %s at line %d", p.second.size, p.second.file.c_str(), p.second.line);
213           }
214         }
215         if (truncate)
216           XBT_INFO("(more buffer leaks hidden as you wanted to see only %lu of them)", max);
217       }
218     }
219
220     if(total_malloc_size != 0)
221       XBT_INFO("Memory Usage: Simulated application allocated %lu bytes during its lifetime through malloc/calloc calls.\n"
222              "Largest allocation at once from a single process was %zu bytes, at %s:%d. It was called %u times during the whole simulation.\n"
223              "If this is too much, consider sharing allocations for computation buffers.\n"
224              "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",
225              total_malloc_size, max_malloc.size, simgrid::xbt::Path(max_malloc.file).get_base_name().c_str(), max_malloc.line, max_malloc.numcall
226       );
227     else
228       XBT_INFO("Allocations analysis asked, but 0 bytes were allocated through malloc/calloc calls intercepted by SMPI.\n"
229                "Either code is using other ways of allocating memory, or it was built with SMPI_NO_OVERRIDE_MALLOC");
230     if(total_shared_size != 0)
231       XBT_INFO("%lu bytes were automatically shared between processes, in %u calls\n", total_shared_size, total_shared_calls);
232   }
233 }
234
235 void set_current_handle(F2C* handle){
236   current_handle=handle;
237 }
238
239 void print_current_handle(){
240   if(current_handle){
241     if(current_handle->call_location().empty())
242       XBT_INFO("To get handle location information, pass -trace-call-location flag to smpicc/f90 as well");
243     else
244       XBT_INFO("Handle %s was allocated by a call at %s", current_handle->name().c_str(),
245                (char*)(current_handle->call_location().c_str()));
246   }
247 }
248
249 void set_current_buffer(int i, const char* name, const void* buf){
250   //clear previous one
251   if(i==1){
252     if(not current_buffer1.name.empty()){
253       current_buffer1.name="";
254     }
255     if(not current_buffer2.name.empty()){
256       current_buffer2.name="";
257     }
258   }
259   auto meta = allocs.find(buf);
260   if (meta == allocs.end()) {
261     XBT_DEBUG("Buffer %p was not allocated with malloc/calloc", buf);
262     return;
263   }
264   if(i==1){
265     current_buffer1.alloc = meta->second;
266     current_buffer1.name = name;
267   }else{
268     current_buffer2.alloc=meta->second;
269     current_buffer2.name=name;
270   }
271 }
272
273 void print_buffer_info(){
274     if(not current_buffer1.name.empty())
275       XBT_INFO("Buffer %s was allocated from %s line %d, with size %zu", current_buffer1.name.c_str(), current_buffer1.alloc.file.c_str(), current_buffer1.alloc.line, current_buffer1.alloc.size);
276     if(not current_buffer2.name.empty())
277       XBT_INFO("Buffer %s was allocated from %s line %d, with size %zu", current_buffer2.name.c_str(), current_buffer2.alloc.file.c_str(), current_buffer2.alloc.line, current_buffer2.alloc.size);    
278 }
279
280 size_t get_buffer_size(const void* buf){
281   auto meta = allocs.find(buf);
282   if (meta == allocs.end()) {
283     //we don't know this buffer (on stack or feature disabled), assume it's fine.
284     return  std::numeric_limits<std::size_t>::max();
285   }
286   return meta->second.size;
287 }
288
289 void account_free(const void* ptr){
290   if (smpi_cfg_display_alloc()) {
291     allocs.erase(ptr);
292   }
293 }
294
295 }
296 }
297 } // namespace simgrid