Apply re-formatting to C++ in src/ tree.
[alexxy/gromacs.git] / src / gromacs / utility / fatalerror.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
5  * Copyright (c) 2001-2004, The GROMACS development team.
6  * Copyright (c) 2013,2014,2015,2016,2017, The GROMACS development team.
7  * Copyright (c) 2018,2019,2020, by the GROMACS development team, led by
8  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
9  * and including many others, as listed in the AUTHORS file in the
10  * top-level source directory and at http://www.gromacs.org.
11  *
12  * GROMACS is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU Lesser General Public License
14  * as published by the Free Software Foundation; either version 2.1
15  * of the License, or (at your option) any later version.
16  *
17  * GROMACS is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20  * Lesser General Public License for more details.
21  *
22  * You should have received a copy of the GNU Lesser General Public
23  * License along with GROMACS; if not, see
24  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
25  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
26  *
27  * If you want to redistribute modifications to GROMACS, please
28  * consider that scientific software is very special. Version
29  * control is crucial - bugs must be traceable. We will be happy to
30  * consider code for inclusion in the official distribution, but
31  * derived work must not be called official GROMACS. Details are found
32  * in the README & COPYING files - if they are missing, get the
33  * official version at http://www.gromacs.org.
34  *
35  * To help us fund GROMACS development, we humbly ask that you cite
36  * the research papers on the package. Check out http://www.gromacs.org.
37  */
38 #include "gmxpre.h"
39
40 #include "fatalerror.h"
41
42 #include "config.h"
43
44 #include <cerrno>
45 #include <cstddef>
46 #include <cstdlib>
47 #include <cstring>
48
49 #include <exception>
50
51 #include "gromacs/utility/basedefinitions.h"
52 #include "gromacs/utility/baseversion.h"
53 #include "gromacs/utility/cstringutil.h"
54 #include "gromacs/utility/futil.h"
55 #include "gromacs/utility/mutex.h"
56 #include "gromacs/utility/programcontext.h"
57 #include "gromacs/utility/stringutil.h"
58
59 #include "errorcodes.h"
60
61 #if GMX_MPI
62 #    include "gromacs/utility/basenetwork.h"
63 #    include "gromacs/utility/gmxmpi.h"
64 #endif
65
66 #include "errorformat.h"
67
68 static bool bDebug = false;
69
70 FILE*    debug        = nullptr;
71 gmx_bool gmx_debug_at = FALSE;
72
73 static FILE*      log_file = nullptr;
74 static gmx::Mutex error_mutex;
75
76 using Lock = gmx::lock_guard<gmx::Mutex>;
77
78 void gmx_init_debug(const int dbglevel, const char* dbgfile)
79 {
80     if (!bDebug)
81     {
82         gmx_disable_file_buffering();
83         debug  = gmx_ffopen(dbgfile, "w+");
84         bDebug = true;
85         if (dbglevel >= 2)
86         {
87             gmx_debug_at = TRUE;
88         }
89     }
90 }
91
92 gmx_bool bDebugMode()
93 {
94     return bDebug;
95 }
96
97 void gmx_fatal_set_log_file(FILE* fp)
98 {
99     log_file = fp;
100 }
101
102 static void default_error_handler(const char* title, const std::string& msg, const char* file, int line)
103 {
104     if (log_file)
105     {
106         gmx::internal::printFatalErrorHeader(log_file, title, nullptr, file, line);
107         gmx::internal::printFatalErrorMessageLine(log_file, msg.c_str(), 0);
108         gmx::internal::printFatalErrorFooter(log_file);
109     }
110     gmx::internal::printFatalErrorHeader(stderr, title, nullptr, file, line);
111     gmx::internal::printFatalErrorMessageLine(stderr, msg.c_str(), 0);
112     gmx::internal::printFatalErrorFooter(stderr);
113 }
114
115 static gmx_error_handler_t gmx_error_handler = default_error_handler;
116
117 void gmx_set_error_handler(gmx_error_handler_t func)
118 {
119     Lock lock(error_mutex);
120     gmx_error_handler = func;
121 }
122
123 static const char* gmx_strerror(const char* key)
124 {
125     struct ErrorKeyEntry
126     {
127         const char* key;
128         const char* msg;
129     };
130     ErrorKeyEntry map[] = { { "call", "Routine should not have been called" },
131                             { "comm", "Communication (parallel processing) problem" },
132                             { "fatal", "Fatal error" },
133                             { "file", "File input/output error" },
134                             { "impl", "Implementation restriction" },
135                             { "incons", "Software inconsistency error" },
136                             { "input", "Input error or input inconsistency" },
137                             { "mem", "Memory allocation/freeing error" },
138                             { "open", "Cannot open file" },
139                             { "range", "Range checking error" } };
140
141     if (key == nullptr)
142     {
143         return "NULL error type (should not occur)";
144     }
145     for (const ErrorKeyEntry& entry : map)
146     {
147         if (std::strcmp(key, entry.key) == 0)
148         {
149             return entry.msg;
150         }
151     }
152     return gmx::getErrorCodeString(gmx::eeUnknownError);
153 }
154
155 static void call_error_handler(const char* key, const char* file, int line, const std::string& msg)
156 {
157     Lock lock(error_mutex);
158     gmx_error_handler(gmx_strerror(key), msg.empty() ? "Empty gmx_fatal message (bug)." : msg, file, line);
159 }
160
161 void gmx_exit_on_fatal_error(ExitType exitType, int returnValue)
162 {
163     if (log_file)
164     {
165         std::fflush(log_file);
166     }
167     if (debug)
168     {
169         std::fflush(debug);
170     }
171     std::fflush(stdout);
172     std::fflush(stderr);
173
174 #if GMX_MPI
175     if (gmx_mpi_initialized())
176     {
177         switch (exitType)
178         {
179             case ExitType_CleanExit: MPI_Finalize(); break;
180             case ExitType_Abort:
181 #    if GMX_LIB_MPI
182                 gmx_abort(returnValue);
183 #    else
184                 break;
185 #    endif
186             case ExitType_NonMasterAbort:
187                 // Let all other processes wait till the master has printed
188                 // the error message and issued MPI_Abort.
189                 MPI_Barrier(MPI_COMM_WORLD);
190                 break;
191         }
192     }
193 #endif
194
195     if (!GMX_FAHCORE)
196     {
197         if (exitType == ExitType_CleanExit)
198         {
199             std::exit(returnValue);
200         }
201         // We cannot use std::exit() if other threads may still be executing, since that would cause
202         // destructors to be called for global objects that may still be in use elsewhere.
203         std::_Exit(returnValue);
204     }
205 }
206
207 void gmx_fatal_mpi_va(int /*f_errno*/,
208                       const char* file,
209                       int         line,
210                       gmx_bool    bMaster,
211                       gmx_bool    bFinalize,
212                       const char* fmt,
213                       va_list     ap)
214 {
215     if (bMaster)
216     {
217         std::string msg = gmx::formatStringV(fmt, ap);
218         call_error_handler("fatal", file, line, msg);
219     }
220
221     ExitType exitType = ExitType_CleanExit;
222     if (!bFinalize)
223     {
224         exitType = bMaster ? ExitType_Abort : ExitType_NonMasterAbort;
225     }
226     gmx_exit_on_fatal_error(exitType, 1);
227 }
228
229 void gmx_fatal(int f_errno, const char* file, int line, gmx_fmtstr const char* fmt, ...)
230 {
231     va_list ap;
232     va_start(ap, fmt);
233     gmx_fatal_mpi_va(f_errno, file, line, TRUE, FALSE, fmt, ap);
234     va_end(ap);
235 }
236
237 void _gmx_error(const char* key, const std::string& msg, const char* file, int line)
238 {
239     call_error_handler(key, file, line, msg);
240     gmx_exit_on_fatal_error(ExitType_Abort, 1);
241 }
242
243 void _range_check(int n, int n_min, int n_max, const char* warn_str, const char* var, const char* file, int line)
244 {
245     if ((n < n_min) || (n >= n_max))
246     {
247         std::string buf;
248         if (warn_str != nullptr)
249         {
250             buf = warn_str;
251             buf += "\n";
252         }
253
254         buf += gmx::formatString(
255                 "Variable %s has value %d. It should have been "
256                 "within [ %d .. %d ]\n",
257                 var,
258                 n,
259                 n_min,
260                 n_max);
261
262         _gmx_error("range", buf, file, line);
263     }
264 }
265
266 void gmx_warning(gmx_fmtstr const char* fmt, ...)
267 {
268     va_list ap;
269     char    msg[STRLEN];
270
271     va_start(ap, fmt);
272     vsprintf(msg, fmt, ap);
273     va_end(ap);
274
275     fprintf(stderr, "\nWARNING: %s\n\n", msg);
276 }