Refactor gmx_fatal()
[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, 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 "fatalerror.h"
38
39 #ifdef HAVE_CONFIG_H
40 #include <config.h>
41 #endif
42
43 #include <cerrno>
44 #include <cstdarg>
45 #include <cstdlib>
46 #include <cstring>
47
48 #include <exception>
49
50 #include "thread_mpi/threads.h"
51
52 #include "gromacs/utility/basenetwork.h"
53 #include "gromacs/utility/baseversion.h"
54 #include "gromacs/utility/common.h"
55 #include "gromacs/utility/cstringutil.h"
56 #include "gromacs/utility/futil.h"
57 #include "gromacs/utility/gmxmpi.h"
58 #include "gromacs/utility/programcontext.h"
59 #include "gromacs/utility/smalloc.h"
60
61 static gmx_bool            bDebug         = FALSE;
62 static FILE               *log_file       = NULL;
63
64 static tMPI_Thread_mutex_t debug_mutex    = TMPI_THREAD_MUTEX_INITIALIZER;
65 static tMPI_Thread_mutex_t where_mutex    = TMPI_THREAD_MUTEX_INITIALIZER;
66
67 static const char *const   gmxuser
68     = "Please report this to the mailing list (gmx-users@gromacs.org)";
69
70 gmx_bool bDebugMode(void)
71 {
72     return bDebug;
73 }
74
75 void gmx_fatal_set_log_file(FILE *fp)
76 {
77     log_file = fp;
78 }
79
80 void _where(const char *file, int line)
81 {
82     static gmx_bool bFirst = TRUE;
83     static int      nskip  = -1;
84     static int      nwhere =  0;
85     FILE           *fp;
86     char           *temp;
87
88     if (bFirst)
89     {
90         tMPI_Thread_mutex_lock(&where_mutex);
91         if (bFirst) /* we repeat the check in the locked section because things
92                        might have changed */
93         {
94             if ((temp = getenv("WHERE")) != NULL)
95             {
96                 nskip = strtol(temp, NULL, 10);
97             }
98             bFirst = FALSE;
99         }
100         tMPI_Thread_mutex_unlock(&where_mutex);
101     }
102
103     if (nskip >= 0)
104     {
105         /* Skip the first n occasions, this allows to see where it goes wrong */
106         if (nwhere >= nskip)
107         {
108             if (log_file)
109             {
110                 fp = log_file;
111             }
112             else
113             {
114                 fp = stderr;
115             }
116             fprintf(fp, "WHERE %d, file %s - line %d\n", nwhere, file, line);
117         }
118         nwhere++;
119     }
120 }
121
122 static int fatal_errno = 0;
123
124 static void default_error_handler(const char *msg)
125 {
126     tMPI_Thread_mutex_lock(&debug_mutex);
127     if (fatal_errno == 0)
128     {
129         if (log_file)
130         {
131             fprintf(log_file, "%s\n", msg);
132         }
133         fprintf(stderr, "%s\n", msg);
134         /* we set it to no-zero because if this function is called, something
135            has gone wrong */
136         fatal_errno = 255;
137     }
138     else
139     {
140         if (fatal_errno != -1)
141         {
142             errno = fatal_errno;
143         }
144         perror(msg);
145     }
146     tMPI_Thread_mutex_unlock(&debug_mutex);
147 }
148
149 static void (*gmx_error_handler)(const char *msg) = default_error_handler;
150
151 void set_gmx_error_handler(void (*func)(const char *msg))
152 {
153     // TODO: Either this is unnecessary, or also reads to the handler should be
154     // protected by a mutex.
155     tMPI_Thread_mutex_lock(&debug_mutex);
156     gmx_error_handler = func;
157     tMPI_Thread_mutex_unlock(&debug_mutex);
158 }
159
160 static void call_error_handler(const char *key, const char *file, int line, const char *msg)
161 {
162     char        buf[10240], errerrbuf[1024];
163     const char *llines = "-------------------------------------------------------";
164     char       *strerr;
165
166     if (msg == NULL)
167     {
168         sprintf(errerrbuf, "Empty fatal_error message. %s", gmxuser);
169     }
170     // In case ProgramInfo is not initialized and there is an issue with the
171     // initialization, fall back to "GROMACS".
172     const char *programName = "GROMACS";
173     try
174     {
175         programName = gmx::getProgramContext().displayName();
176     }
177     catch (const std::exception &)
178     {
179     }
180
181     strerr = gmx_strerror(key);
182     sprintf(buf, "\n%s\nProgram %s, %s\n"
183             "Source code file: %s, line: %d\n\n"
184             "%s:\n%s\nFor more information and tips for troubleshooting, please check the GROMACS\n"
185             "website at http://www.gromacs.org/Documentation/Errors\n%s\n",
186             llines, programName, gmx_version(), file, line,
187             strerr, msg ? msg : errerrbuf, llines);
188     free(strerr);
189
190     gmx_error_handler(buf);
191 }
192
193 static void do_exit(bool bMaster, bool bFinalize)
194 {
195     if (debug)
196     {
197         fflush(debug);
198     }
199
200 #ifdef GMX_MPI
201     if (gmx_mpi_initialized())
202     {
203         if (bFinalize)
204         {
205             /* Broadcast the fatal error number possibly modified
206              * on the master process, in case the user would like
207              * to use the return status on a non-master process.
208              * The master process in cr and dd always has global rank 0.
209              */
210             MPI_Bcast(&fatal_errno, sizeof(fatal_errno), MPI_BYTE,
211                       0, MPI_COMM_WORLD);
212
213             /* Finalize nicely instead of aborting */
214             MPI_Finalize();
215         }
216         else if (bMaster)
217         {
218 #ifdef GMX_LIB_MPI
219             gmx_abort(1);
220 #endif
221         }
222         else
223         {
224             /* Let all other processes wait till the master has printed
225              * the error message and issued MPI_Abort.
226              */
227             MPI_Barrier(MPI_COMM_WORLD);
228         }
229     }
230 #else
231     GMX_UNUSED_VALUE(bMaster);
232     GMX_UNUSED_VALUE(bFinalize);
233 #endif
234
235     if (bDebugMode())
236     {
237         std::abort();
238     }
239     std::exit(1);
240 }
241
242 void gmx_fatal_mpi_va(int f_errno, const char *file, int line,
243                       gmx_bool bMaster, gmx_bool bFinalize,
244                       const char *fmt, va_list ap)
245 {
246     if (bMaster)
247     {
248         char msg[STRLEN];
249         vsprintf(msg, fmt, ap);
250
251         tMPI_Thread_mutex_lock(&debug_mutex);
252         fatal_errno = f_errno;
253         tMPI_Thread_mutex_unlock(&debug_mutex);
254
255         call_error_handler("fatal", file, line, msg);
256     }
257
258     do_exit(bMaster, bFinalize);
259 }
260
261 void gmx_fatal(int f_errno, const char *file, int line, const char *fmt, ...)
262 {
263     va_list ap;
264     va_start(ap, fmt);
265     gmx_fatal_mpi_va(f_errno, file, line, TRUE, FALSE, fmt, ap);
266     va_end(ap);
267 }
268
269 /*
270  * These files are global variables in the gromacs preprocessor
271  * Every routine in a file that includes gmx_fatal.h can write to these
272  * debug channels. Depending on the debuglevel used
273  * 0 to 3 of these filed are redirected to /dev/null
274  *
275  */
276 FILE    *debug           = NULL;
277 gmx_bool gmx_debug_at    = FALSE;
278
279 void init_debug(const int dbglevel, const char *dbgfile)
280 {
281     tMPI_Thread_mutex_lock(&debug_mutex);
282     if (!bDebug) /* another thread hasn't already run this*/
283     {
284         no_buffers();
285         debug  = gmx_ffopen(dbgfile, "w+");
286         bDebug = TRUE;
287         if (dbglevel >= 2)
288         {
289             gmx_debug_at = TRUE;
290         }
291     }
292     tMPI_Thread_mutex_unlock(&debug_mutex);
293 }
294
295 char *gmx_strerror(const char *key)
296 {
297     typedef struct {
298         const char *key, *msg;
299     } error_msg_t;
300     error_msg_t msg[] = {
301         { "bug",    "Possible bug" },
302         { "call",   "Routine should not have been called" },
303         { "comm",   "Communication (parallel processing) problem" },
304         { "fatal",  "Fatal error" },
305         { "cmd",    "Invalid command line argument" },
306         { "file",   "File input/output error" },
307         { "impl",   "Implementation restriction" },
308         { "incons", "Software inconsistency error" },
309         { "input",  "Input error or input inconsistency" },
310         { "mem",    "Memory allocation/freeing error" },
311         { "open",   "Can not open file" },
312         { "range",  "Range checking error" },
313         { NULL,     NULL}
314     };
315
316     if (key == NULL)
317     {
318         return strdup("Empty message");
319     }
320     else
321     {
322         for (size_t i = 0; msg[i].key != NULL; ++i)
323         {
324             if (strcmp(key, msg[i].key) == 0)
325             {
326                 return strdup(msg[i].msg);
327             }
328         }
329         char buf[1024];
330         sprintf(buf, "No error message associated with key %s\n%s", key, gmxuser);
331         return strdup(buf);
332     }
333 }
334
335
336 void _gmx_error(const char *key, const char *msg, const char *file, int line)
337 {
338     call_error_handler(key, file, line, msg);
339     do_exit(true, false);
340 }
341
342 void _range_check(int n, int n_min, int n_max, const char *warn_str,
343                   const char *var, const char *file, int line)
344 {
345     char buf[1024];
346
347     if ((n < n_min) || (n >= n_max))
348     {
349         if (warn_str != NULL)
350         {
351             strcpy(buf, warn_str);
352             strcat(buf, "\n");
353         }
354         else
355         {
356             buf[0] = '\0';
357         }
358
359         sprintf(buf+strlen(buf), "Variable %s has value %d. It should have been "
360                 "within [ %d .. %d ]\n", var, n, n_min, n_max);
361
362         _gmx_error("range", buf, file, line);
363     }
364 }
365
366 void gmx_warning(const char *fmt, ...)
367 {
368     va_list ap;
369     char    msg[STRLEN];
370
371     va_start(ap, fmt);
372     vsprintf(msg, fmt, ap);
373     va_end(ap);
374
375     fprintf(stderr, "\nWARNING: %s\n\n", msg);
376 }