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