Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Display leak origin in message, if -trace-call-location is used.
[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
19 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(smpi_utils, smpi, "Logging specific to SMPI (utils)");
20
21 extern std::string surf_parsed_filename;
22 extern int surf_parse_lineno;
23
24 namespace simgrid {
25 namespace smpi {
26 namespace utils {
27
28 double total_benched_time=0;
29 unsigned long total_malloc_size=0;
30 unsigned long total_shared_size=0;
31 unsigned int total_shared_calls=0;
32 struct MaxMalloc {
33   size_t size          = 0;
34   unsigned int numcall = 0;
35   int line             = 0;
36   std::string file;
37 };
38 MaxMalloc max_malloc;
39 F2C* current_handle=0;
40
41 std::vector<s_smpi_factor_t> parse_factor(const std::string& smpi_coef_string)
42 {
43   std::vector<s_smpi_factor_t> smpi_factor;
44
45   /** Setup the tokenizer that parses the string **/
46   using Tokenizer = boost::tokenizer<boost::char_separator<char>>;
47   boost::char_separator<char> sep(";");
48   boost::char_separator<char> factor_separator(":");
49   Tokenizer tokens(smpi_coef_string, sep);
50
51   /**
52    * Iterate over patterns like A:B:C:D;E:F;G:H
53    * These will be broken down into:
54    * A --> B, C, D
55    * E --> F
56    * G --> H
57    */
58   for (Tokenizer::iterator token_iter = tokens.begin(); token_iter != tokens.end(); ++token_iter) {
59     XBT_DEBUG("token : %s", token_iter->c_str());
60     Tokenizer factor_values(*token_iter, factor_separator);
61     s_smpi_factor_t fact;
62     xbt_assert(factor_values.begin() != factor_values.end(), "Malformed radical for smpi factor: '%s'",
63                smpi_coef_string.c_str());
64     unsigned int iteration = 0;
65     for (Tokenizer::iterator factor_iter = factor_values.begin(); factor_iter != factor_values.end(); ++factor_iter) {
66       iteration++;
67
68       if (factor_iter == factor_values.begin()) { /* first element */
69         try {
70           fact.factor = std::stoi(*factor_iter);
71         } catch (const std::invalid_argument&) {
72           throw std::invalid_argument(std::string("Invalid factor in chunk ") + std::to_string(smpi_factor.size() + 1) +
73                                       ": " + *factor_iter);
74         }
75       } else {
76         try {
77           fact.values.push_back(
78               xbt_parse_get_time(surf_parsed_filename, surf_parse_lineno, (*factor_iter).c_str(), "smpi factor", ""));
79         } catch (const std::invalid_argument&) {
80           throw std::invalid_argument(std::string("Invalid factor value ") + std::to_string(iteration) + " in chunk " +
81                                       std::to_string(smpi_factor.size() + 1) + ": " + *factor_iter);
82         }
83       }
84     }
85
86     smpi_factor.push_back(fact);
87     XBT_DEBUG("smpi_factor:\t%zu : %zu values, first: %f", fact.factor, smpi_factor.size(), fact.values[0]);
88   }
89   std::sort(smpi_factor.begin(), smpi_factor.end(), [](const s_smpi_factor_t &pa, const s_smpi_factor_t &pb) {
90     return (pa.factor < pb.factor);
91   });
92   for (auto const& fact : smpi_factor) {
93     XBT_DEBUG("smpi_factor:\t%zu : %zu values, first: %f", fact.factor, smpi_factor.size() ,fact.values[0]);
94   }
95   smpi_factor.shrink_to_fit();
96
97   return smpi_factor;
98 }
99
100 void add_benched_time(double time){
101   total_benched_time += time;
102 }
103
104 void account_malloc_size(size_t size, const char* file, int line){
105   total_malloc_size += size;
106   if(size > max_malloc.size){
107     max_malloc.size = size;
108     max_malloc.line = line;
109     max_malloc.numcall = 1;
110     max_malloc.file = std::string(file);
111   }else if(size == max_malloc.size && max_malloc.line == line && not max_malloc.file.compare(file)){
112     max_malloc.numcall++;
113   }
114 }
115
116 void account_shared_size(size_t size){
117   total_shared_size += size;
118   total_shared_calls++;
119 }
120
121 void print_time_analysis(double global_time){
122   if (simgrid::config::get_value<bool>("smpi/display-timing")) {
123     XBT_INFO("Simulated time: %g seconds. \n\n"
124         "The simulation took %g seconds (after parsing and platform setup)\n"
125         "%g seconds were actual computation of the application",
126         SIMIX_get_clock(), global_time , total_benched_time);
127     if (total_benched_time/global_time>=0.75)
128       XBT_INFO("More than 75%% of the time was spent inside the application code.\n"
129     "You may want to use sampling functions or trace replay to reduce this.");
130   }
131 }
132
133 void print_memory_analysis()
134 {
135   // Put the leaked non-default handles in a vector to sort them by id
136   std::vector<std::pair<unsigned int, smpi::F2C*>> handles;
137   if (simgrid::smpi::F2C::lookup() != nullptr)
138     std::copy_if(simgrid::smpi::F2C::lookup()->begin(), simgrid::smpi::F2C::lookup()->end(),
139                  std::back_inserter(handles),
140                  [](auto const& entry) { return entry.first >= simgrid::smpi::F2C::get_num_default_handles(); });
141
142   if (not handles.empty()) {
143     XBT_INFO("Probable memory leaks in your code: SMPI detected %zu unfreed MPI handles : "
144              "display types and addresses (n max) with --cfg=smpi/list-leaks:n.\n"
145              "Running smpirun with -wrapper \"valgrind --leak-check=full\" can provide more information",
146              handles.size());
147     auto max = static_cast<unsigned long>(simgrid::config::get_value<int>("smpi/list-leaks"));
148     if (max > 0) { // we cannot trust F2C::lookup()->size() > F2C::get_num_default_handles() because some default
149                    // handles are already freed at this point
150       std::sort(handles.begin(), handles.end(), [](auto const& a, auto const& b) { return a.first < b.first; });
151       bool truncate = max < handles.size();
152       if (truncate)
153         handles.resize(max);
154       bool printed_advice=false;
155       for (const auto& p : handles) {
156         if (xbt_log_no_loc || p.second->call_location().empty()) {
157           if (!printed_advice){
158             XBT_INFO("To get more information (location of allocations), compile your code with -trace-call-location flag of smpicc/f90");
159             printed_advice=true;
160           }
161           XBT_INFO("Leaked handle of type %s", p.second->name().c_str());
162         } else {
163           XBT_INFO("Leaked handle of type %s at %s", p.second->name().c_str(), p.second->call_location().c_str());
164         }
165       }
166       if (truncate)
167         XBT_INFO("(more handle leaks hidden as you wanted to see only %lu of them)", max);
168     }
169   }
170
171   if (simgrid::config::get_value<bool>("smpi/display-allocs")) {
172     if(total_malloc_size != 0)
173       XBT_INFO("Memory Usage: Simulated application allocated %lu bytes during its lifetime through malloc/calloc calls.\n"
174              "Largest allocation at once from a single process was %zu bytes, at %s:%d. It was called %u times during the whole simulation.\n"
175              "If this is too much, consider sharing allocations for computation buffers.\n"
176              "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",
177              total_malloc_size, max_malloc.size, simgrid::xbt::Path(max_malloc.file).get_base_name().c_str(), max_malloc.line, max_malloc.numcall
178       );
179     else
180       XBT_INFO("Allocations analysis asked, but 0 bytes were allocated through malloc/calloc calls intercepted by SMPI.\n"
181                "Either code is using other ways of allocating memory, or it was built with SMPI_NO_OVERRIDE_MALLOC");
182     if(total_shared_size != 0)
183       XBT_INFO("%lu bytes were automatically shared between processes, in %u calls\n", total_shared_size, total_shared_calls);
184   }
185 }
186
187 void set_current_handle(F2C* handle){
188   current_handle=handle;
189 }
190
191 void print_current_handle(){
192   if(current_handle){
193     if(current_handle->call_location().empty())
194       XBT_INFO("To get handle location information, pass -trace-call-location flag to smpicc/f90 as well");
195     else
196       XBT_INFO("Handle %s was allocated by a call at %s", current_handle->name().c_str(),
197                (char*)(current_handle->call_location().c_str()));
198   }
199 }
200
201 }
202 }
203 } // namespace simgrid