Split lines with many copyright years
[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 by 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 static gmx::Mutex where_mutex;
70
71 FILE*    debug        = nullptr;
72 gmx_bool gmx_debug_at = FALSE;
73
74 static FILE*      log_file = nullptr;
75 static gmx::Mutex error_mutex;
76
77 using Lock = gmx::lock_guard<gmx::Mutex>;
78
79 void gmx_init_debug(const int dbglevel, const char* dbgfile)
80 {
81     if (!bDebug)
82     {
83         gmx_disable_file_buffering();
84         debug  = gmx_ffopen(dbgfile, "w+");
85         bDebug = true;
86         if (dbglevel >= 2)
87         {
88             gmx_debug_at = TRUE;
89         }
90     }
91 }
92
93 gmx_bool bDebugMode()
94 {
95     return bDebug;
96 }
97
98 void gmx_fatal_set_log_file(FILE* fp)
99 {
100     log_file = fp;
101 }
102
103 static void default_error_handler(const char* title, const std::string& msg, const char* file, int line)
104 {
105     if (log_file)
106     {
107         gmx::internal::printFatalErrorHeader(log_file, title, nullptr, file, line);
108         gmx::internal::printFatalErrorMessageLine(log_file, msg.c_str(), 0);
109         gmx::internal::printFatalErrorFooter(log_file);
110     }
111     gmx::internal::printFatalErrorHeader(stderr, title, nullptr, file, line);
112     gmx::internal::printFatalErrorMessageLine(stderr, msg.c_str(), 0);
113     gmx::internal::printFatalErrorFooter(stderr);
114 }
115
116 static gmx_error_handler_t gmx_error_handler = default_error_handler;
117
118 void gmx_set_error_handler(gmx_error_handler_t func)
119 {
120     Lock lock(error_mutex);
121     gmx_error_handler = func;
122 }
123
124 static const char* gmx_strerror(const char* key)
125 {
126     struct ErrorKeyEntry
127     {
128         const char* key;
129         const char* msg;
130     };
131     ErrorKeyEntry map[] = { { "call", "Routine should not have been called" },
132                             { "comm", "Communication (parallel processing) problem" },
133                             { "fatal", "Fatal error" },
134                             { "file", "File input/output error" },
135                             { "impl", "Implementation restriction" },
136                             { "incons", "Software inconsistency error" },
137                             { "input", "Input error or input inconsistency" },
138                             { "mem", "Memory allocation/freeing error" },
139                             { "open", "Cannot open file" },
140                             { "range", "Range checking error" } };
141
142     if (key == nullptr)
143     {
144         return "NULL error type (should not occur)";
145     }
146     for (const ErrorKeyEntry& entry : map)
147     {
148         if (std::strcmp(key, entry.key) == 0)
149         {
150             return entry.msg;
151         }
152     }
153     return gmx::getErrorCodeString(gmx::eeUnknownError);
154 }
155
156 static void call_error_handler(const char* key, const char* file, int line, const std::string& msg)
157 {
158     Lock lock(error_mutex);
159     gmx_error_handler(gmx_strerror(key), msg.empty() ? "Empty gmx_fatal message (bug)." : msg, file, line);
160 }
161
162 void gmx_exit_on_fatal_error(ExitType exitType, int returnValue)
163 {
164     if (log_file)
165     {
166         std::fflush(log_file);
167     }
168     if (debug)
169     {
170         std::fflush(debug);
171     }
172     std::fflush(stdout);
173     std::fflush(stderr);
174
175 #if GMX_MPI
176     if (gmx_mpi_initialized())
177     {
178         switch (exitType)
179         {
180             case ExitType_CleanExit: MPI_Finalize(); break;
181             case ExitType_Abort:
182 #    if GMX_LIB_MPI
183                 gmx_abort(returnValue);
184 #    else
185                 break;
186 #    endif
187             case ExitType_NonMasterAbort:
188                 // Let all other processes wait till the master has printed
189                 // the error message and issued MPI_Abort.
190                 MPI_Barrier(MPI_COMM_WORLD);
191                 break;
192         }
193     }
194 #endif
195
196     if (exitType == ExitType_CleanExit)
197     {
198         std::exit(returnValue);
199     }
200     // We cannot use std::exit() if other threads may still be executing, since that would cause
201     // destructors to be called for global objects that may still be in use elsewhere.
202     std::_Exit(returnValue);
203 }
204
205 void gmx_fatal_mpi_va(int /*f_errno*/,
206                       const char* file,
207                       int         line,
208                       gmx_bool    bMaster,
209                       gmx_bool    bFinalize,
210                       const char* fmt,
211                       va_list     ap)
212 {
213     if (bMaster)
214     {
215         std::string msg = gmx::formatStringV(fmt, ap);
216         call_error_handler("fatal", file, line, msg);
217     }
218
219     ExitType exitType = ExitType_CleanExit;
220     if (!bFinalize)
221     {
222         exitType = bMaster ? ExitType_Abort : ExitType_NonMasterAbort;
223     }
224     gmx_exit_on_fatal_error(exitType, 1);
225 }
226
227 void gmx_fatal(int f_errno, const char* file, int line, gmx_fmtstr const char* fmt, ...)
228 {
229     va_list ap;
230     va_start(ap, fmt);
231     gmx_fatal_mpi_va(f_errno, file, line, TRUE, FALSE, fmt, ap);
232     va_end(ap);
233 }
234
235 void _gmx_error(const char* key, const std::string& msg, const char* file, int line)
236 {
237     call_error_handler(key, file, line, msg);
238     gmx_exit_on_fatal_error(ExitType_Abort, 1);
239 }
240
241 void _range_check(int n, int n_min, int n_max, const char* warn_str, const char* var, const char* file, int line)
242 {
243     if ((n < n_min) || (n >= n_max))
244     {
245         std::string buf;
246         if (warn_str != nullptr)
247         {
248             buf = warn_str;
249             buf += "\n";
250         }
251
252         buf += gmx::formatString(
253                 "Variable %s has value %d. It should have been "
254                 "within [ %d .. %d ]\n",
255                 var, n, n_min, n_max);
256
257         _gmx_error("range", buf, file, line);
258     }
259 }
260
261 void gmx_warning(gmx_fmtstr const char* fmt, ...)
262 {
263     va_list ap;
264     char    msg[STRLEN];
265
266     va_start(ap, fmt);
267     vsprintf(msg, fmt, ap);
268     va_end(ap);
269
270     fprintf(stderr, "\nWARNING: %s\n\n", msg);
271 }