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