Fix remaining copyright headers
[alexxy/gromacs.git] / src / gromacs / gmxlib / gmx_fatal.c
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, 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 #ifdef HAVE_CONFIG_H
38 #include <config.h>
39 #endif
40
41 #include <sysstuff.h>
42 #include <ctype.h>
43 #include <errno.h>
44 #include <stdarg.h>
45 #include <string.h>
46 #include "gromacs/fileio/futil.h"
47 #include "main.h"
48 #include "network.h"
49 #include "gmx_fatal.h"
50 #include "copyrite.h"
51 #include "macros.h"
52 #include "string2.h"
53 #include "smalloc.h"
54 #include "gromacs/fileio/gmxfio.h"
55
56 #include "gromacs/utility/gmxmpi.h"
57
58 #include "gromacs/legacyheaders/thread_mpi/threads.h"
59
60 static gmx_bool bDebug         = FALSE;
61 static char    *fatal_tmp_file = NULL;
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 static tMPI_Thread_mutex_t fatal_tmp_mutex = TMPI_THREAD_MUTEX_INITIALIZER;
67
68
69 gmx_bool bDebugMode(void)
70 {
71     gmx_bool ret;
72 #if 0
73     tMPI_Thread_mutex_lock(&debug_mutex);
74 #endif
75     ret = bDebug;
76 #if 0
77     tMPI_Thread_mutex_unlock(&debug_mutex);
78 #endif
79     return bDebug;
80 }
81
82 void gmx_fatal_set_log_file(FILE *fp)
83 {
84     log_file = fp;
85 }
86
87 void _where(const char *file, int line)
88 {
89     static gmx_bool bFirst = TRUE;
90     static int      nskip  = -1;
91     static int      nwhere =  0;
92     FILE           *fp;
93     char           *temp;
94
95     if (bFirst)
96     {
97         tMPI_Thread_mutex_lock(&where_mutex);
98         if (bFirst) /* we repeat the check in the locked section because things
99                        might have changed */
100         {
101             if ((temp = getenv("WHERE")) != NULL)
102             {
103                 nskip = strtol(temp, NULL, 10);
104             }
105             bFirst = FALSE;
106         }
107         tMPI_Thread_mutex_unlock(&where_mutex);
108     }
109
110     if (nskip >= 0)
111     {
112         /* Skip the first n occasions, this allows to see where it goes wrong */
113         if (nwhere >= nskip)
114         {
115             if (log_file)
116             {
117                 fp = log_file;
118             }
119             else
120             {
121                 fp = stderr;
122             }
123             fprintf(fp, "WHERE %d, file %s - line %d\n", nwhere, file, line);
124         }
125         nwhere++;
126     }
127 }
128
129 static void bputc(char *msg, int *len, char ch)
130 {
131     msg[(*len)++] = ch;
132 }
133
134 static void bputs(char *msg, int *len, const char *s, int fld)
135 {
136     for (fld -= (int)strlen(s); fld > 0; fld--)
137     {
138         bputc(msg, len, ' ');
139     }
140     while (*s)
141     {
142         bputc(msg, len, *(s++));
143     }
144 }
145
146 static void bputd(char *msg, int *len, int d)
147 {
148     if (d < 10)
149     {
150         bputc(msg, len, d+'0');
151     }
152     else
153     {
154         bputc(msg, len, d-10+'a');
155     }
156 }
157
158 static void bputi(char *msg, int *len, int val, int radix, int fld, gmx_bool bNeg)
159 {
160     int fmax = 0;
161
162     if (bNeg)
163     {
164         fmax = 1;
165     }
166
167     if (val < radix)
168     {
169         for (fld--; fld > fmax; fld--)
170         {
171             bputc(msg, len, ' ');
172         }
173         if (bNeg)
174         {
175             bputc(msg, len, '-');
176         }
177         bputd(msg, len, val);
178     }
179     else
180     {
181         if (bNeg)
182         {
183             bputc(msg, len, '-');
184         }
185         bputi(msg, len, val/radix, radix, fld-1, FALSE);
186         bputd(msg, len, val%radix);
187     }
188 }
189
190 static int getfld(const char **p)
191 {
192     int fld;
193
194     fld = 0;
195     while (isdigit(**p))
196     {
197         fld = (fld*10)+((*((*p)++))-'0');
198     }
199     return fld;
200 }
201
202 /*static void _halt(char *file,int line,char *reason)
203    {
204    fprintf(stderr,"\nHALT in file %s line %d because:\n\t%s\n",
205       file,line,reason);
206    exit(1);
207    }
208  */
209
210 static int fatal_errno = 0;
211
212 static void quit_gmx(const char *msg)
213 {
214     tMPI_Thread_mutex_lock(&debug_mutex);
215     if (fatal_errno == 0)
216     {
217         if (log_file)
218         {
219             fprintf(log_file, "%s\n", msg);
220         }
221         fprintf(stderr, "%s\n", msg);
222         /* we set it to no-zero because if this function is called, something
223            has gone wrong */
224         fatal_errno = 255;
225     }
226     else
227     {
228         if (fatal_errno != -1)
229         {
230             errno = fatal_errno;
231         }
232         perror(msg);
233     }
234
235 #ifdef GMX_LIB_MPI
236     if (gmx_mpi_initialized())
237     {
238         int  nnodes;
239         int  noderank;
240
241         nnodes   = gmx_node_num();
242         noderank = gmx_node_rank();
243
244         if (nnodes > 1)
245         {
246             fprintf(stderr, "Error on node %d, will try to stop all the nodes\n",
247                     noderank);
248         }
249         gmx_abort(noderank, nnodes, -1);
250     }
251 #endif
252
253     if (debug)
254     {
255         fflush(debug);
256     }
257     if (bDebugMode())
258     {
259         fprintf(stderr, "dump core (y/n):");
260         fflush(stderr);
261         if (toupper(getc(stdin)) != 'N')
262         {
263             (void) abort();
264         }
265     }
266
267     exit(fatal_errno);
268     tMPI_Thread_mutex_unlock(&debug_mutex);
269 }
270
271 /* The function below should be identical to quit_gmx,
272  * except that is does not actually quit and call gmx_abort.
273  */
274 static void quit_gmx_noquit(const char *msg)
275 {
276     tMPI_Thread_mutex_lock(&debug_mutex);
277     if (!fatal_errno)
278     {
279         if (log_file)
280         {
281             fprintf(log_file, "%s\n", msg);
282         }
283         fprintf(stderr, "%s\n", msg);
284         /* we set it to no-zero because if this function is called, something
285            has gone wrong */
286         fatal_errno = 255;
287     }
288     else
289     {
290         if (fatal_errno != -1)
291         {
292             errno = fatal_errno;
293         }
294         perror(msg);
295     }
296
297 #ifndef GMX_LIB_MPI
298     if (debug)
299     {
300         fflush(debug);
301     }
302     if (bDebugMode())
303     {
304         fprintf(stderr, "dump core (y/n):");
305         fflush(stderr);
306         if (toupper(getc(stdin)) != 'N')
307         {
308             (void) abort();
309         }
310     }
311 #endif
312
313     tMPI_Thread_mutex_unlock(&debug_mutex);
314 }
315
316 void _set_fatal_tmp_file(const char *fn, const char *file, int line)
317 {
318     tMPI_Thread_mutex_lock(&fatal_tmp_mutex);
319     if (fatal_tmp_file == NULL)
320     {
321         fatal_tmp_file = strdup(fn);
322     }
323     else
324     {
325         fprintf(stderr, "BUGWARNING: fatal_tmp_file already set at %s:%d",
326                 file, line);
327     }
328     tMPI_Thread_mutex_unlock(&fatal_tmp_mutex);
329 }
330
331 void _unset_fatal_tmp_file(const char *fn, const char *file, int line)
332 {
333     tMPI_Thread_mutex_lock(&fatal_tmp_mutex);
334     if (strcmp(fn, fatal_tmp_file) == 0)
335     {
336         sfree(fatal_tmp_file);
337         fatal_tmp_file = NULL;
338     }
339     else
340     {
341         fprintf(stderr, "BUGWARNING: file %s not set as fatal_tmp_file at %s:%d",
342                 fn, file, line);
343     }
344     tMPI_Thread_mutex_unlock(&fatal_tmp_mutex);
345 }
346
347 static void clean_fatal_tmp_file()
348 {
349     tMPI_Thread_mutex_lock(&fatal_tmp_mutex);
350     if (fatal_tmp_file)
351     {
352         fprintf(stderr, "Cleaning up temporary file %s\n", fatal_tmp_file);
353         remove(fatal_tmp_file);
354         sfree(fatal_tmp_file);
355         fatal_tmp_file = NULL;
356     }
357     tMPI_Thread_mutex_unlock(&fatal_tmp_mutex);
358 }
359
360 static void parse_printf_args(const char *fmt, va_list *ap, char *msg)
361 {
362     int     len;
363     const char *p;
364     char    cval, *sval;
365     char    ibuf[64], ifmt[64];
366     int     index, ival, fld;
367     double  dval;
368
369     len = 0;
370     for (p = fmt; *p; p++)
371     {
372         if (*p != '%')
373         {
374             bputc(msg, &len, *p);
375         }
376         else
377         {
378             p++;
379             fld = getfld(&p);
380             switch (*p)
381             {
382                 case 'x':
383                     ival = va_arg(*ap, int);
384                     sprintf(ifmt, "0x%%%dx", fld);
385                     sprintf(ibuf, ifmt, (unsigned int)ival);
386                     for (index = 0; (index < (int)strlen(ibuf)); index++)
387                     {
388                         bputc(msg, &len, ibuf[index]);
389                     }
390                     break;
391                 case 'd':
392                     ival = va_arg(*ap, int);
393                     sprintf(ifmt, "%%%dd", fld);
394                     sprintf(ibuf, ifmt, ival);
395                     for (index = 0; (index < (int)strlen(ibuf)); index++)
396                     {
397                         bputc(msg, &len, ibuf[index]);
398                     }
399                     break;
400                 case 'u':
401                     ival = va_arg(*ap, unsigned);
402                     sprintf(ifmt, "%%%du", fld);
403                     sprintf(ibuf, ifmt, ival);
404                     for (index = 0; (index < (int)strlen(ibuf)); index++)
405                     {
406                         bputc(msg, &len, ibuf[index]);
407                     }
408                     break;
409                 case 'f':
410                     dval = va_arg(*ap, double);
411                     sprintf(ifmt, "%%%df", fld);
412                     sprintf(ibuf, ifmt, dval);
413                     for (index = 0; (index < (int)strlen(ibuf)); index++)
414                     {
415                         bputc(msg, &len, ibuf[index]);
416                     }
417                     break;
418                 case 'g':
419                     dval = va_arg(*ap, double);
420                     sprintf(ifmt, "%%%dg", fld);
421                     sprintf(ibuf, ifmt, dval);
422                     for (index = 0; (index < (int)strlen(ibuf)); index++)
423                     {
424                         bputc(msg, &len, ibuf[index]);
425                     }
426                     break;
427                 case 'c':
428                     cval = (char) va_arg(*ap, int); /* char is promoted to int */
429                     bputc(msg, &len, cval);
430                     break;
431                 case 's':
432                     sval = va_arg(*ap, char *);
433                     if (sval == NULL)
434                     {
435                         sval = strdup("(null)");
436                     }
437                     bputs(msg, &len, sval, fld);
438                     break;
439                 case '%':
440                     bputc(msg, &len, *p);
441                     break;
442                 default:
443                     break;
444             }
445         }
446     }
447
448     bputc(msg, &len, '\0');
449 }
450
451 void gmx_fatal(int f_errno, const char *file, int line, const char *fmt, ...)
452 {
453     va_list ap;
454     char    msg[STRLEN];
455
456     va_start(ap, fmt);
457
458     clean_fatal_tmp_file();
459
460     parse_printf_args(fmt, &ap, msg);
461
462     va_end(ap);
463
464     tMPI_Thread_mutex_lock(&debug_mutex);
465     fatal_errno = f_errno;
466     tMPI_Thread_mutex_unlock(&debug_mutex);
467
468     _gmx_error("fatal", msg, file, line);
469 }
470
471 void gmx_fatal_collective(int f_errno, const char *file, int line,
472                           const t_commrec *cr, gmx_domdec_t *dd,
473                           const char *fmt, ...)
474 {
475     gmx_bool    bFinalize;
476     va_list ap;
477     char    msg[STRLEN];
478 #ifdef GMX_MPI
479     int     result;
480 #endif
481
482     bFinalize = TRUE;
483
484 #ifdef GMX_MPI
485     /* Check if we are calling on all processes in MPI_COMM_WORLD */
486     if (cr != NULL)
487     {
488         MPI_Comm_compare(cr->mpi_comm_mysim, MPI_COMM_WORLD, &result);
489     }
490     else
491     {
492         MPI_Comm_compare(dd->mpi_comm_all, MPI_COMM_WORLD, &result);
493     }
494     /* Any result except MPI_UNEQUAL allows us to call MPI_Finalize */
495     bFinalize = (result != MPI_UNEQUAL);
496 #endif
497
498     if ((cr != NULL && MASTER(cr)  ) ||
499         (dd != NULL && DDMASTER(dd)))
500     {
501         va_start(ap, fmt);
502
503         clean_fatal_tmp_file();
504
505         parse_printf_args(fmt, &ap, msg);
506
507         va_end(ap);
508
509         tMPI_Thread_mutex_lock(&debug_mutex);
510         fatal_errno = f_errno;
511         tMPI_Thread_mutex_unlock(&debug_mutex);
512
513         if (bFinalize)
514         {
515             /* Use an error handler that does not quit */
516             set_gmx_error_handler(quit_gmx_noquit);
517         }
518
519         _gmx_error("fatal", msg, file, line);
520     }
521
522 #ifdef GMX_MPI
523     if (bFinalize)
524     {
525         /* Broadcast the fatal error number possibly modified
526          * on the master process, in case the user would like
527          * to use the return status on a non-master process.
528          * The master process in cr and dd always has global rank 0.
529          */
530         MPI_Bcast(&fatal_errno, sizeof(fatal_errno), MPI_BYTE,
531                   0, MPI_COMM_WORLD);
532
533         /* Finalize nicely instead of aborting */
534         MPI_Finalize();
535     }
536     else
537     {
538         /* Let all other processes wait till the master has printed
539          * the error message and issued MPI_Abort.
540          */
541         MPI_Barrier(MPI_COMM_WORLD);
542     }
543 #endif
544
545     exit(fatal_errno);
546 }
547
548 void _invalid_case(const char *fn, int line)
549 {
550     gmx_fatal(FARGS, "Invalid case in switch statement, file %s, line %d",
551               fn, line);
552 }
553
554 void _unexpected_eof(const char *fn, int line, const char *srcfn, int srcline)
555 {
556     gmx_fatal(FARGS, "Unexpected end of file in file %s at line %d\n"
557               "(Source file %s, line %d)", fn, line, srcfn, srcline);
558 }
559
560 /*
561  * These files are global variables in the gromacs preprocessor
562  * Every routine in a file that includes gmx_fatal.h can write to these
563  * debug channels. Depending on the debuglevel used
564  * 0 to 3 of these filed are redirected to /dev/null
565  *
566  */
567 FILE *debug           = NULL;
568 gmx_bool gmx_debug_at = FALSE;
569
570 void init_debug(const int dbglevel, const char *dbgfile)
571 {
572     tMPI_Thread_mutex_lock(&debug_mutex);
573     if (!bDebug) /* another thread hasn't already run this*/
574     {
575         no_buffers();
576         debug  = gmx_fio_fopen(dbgfile, "w+");
577         bDebug = TRUE;
578         if (dbglevel >= 2)
579         {
580             gmx_debug_at = TRUE;
581         }
582     }
583     tMPI_Thread_mutex_unlock(&debug_mutex);
584 }
585
586 #if (defined __sgi && defined USE_SGI_FPE)
587 static void user_routine(unsigned us[5], int ii[2])
588 {
589     fprintf(stderr, "User routine us=(%u,%u,%u,%u,%u) ii=(%d,%d)\n",
590             us[0], us[1], us[2], us[3], us[4], ii[0], ii[1]);
591     fprintf(stderr, "Exception encountered! Dumping core\n");
592     abort();
593 }
594
595 static void abort_routine(unsigned int **ii)
596 {
597     fprintf(stderr, "Abort routine\n");
598     abort();
599 }
600
601 static void handle_signals(int n)
602 {
603     fprintf(stderr, "Handle signals: n = %d\n", n);
604     fprintf(stderr, "Dumping core\n");
605     abort();
606 }
607
608 void doexceptions(void)
609 {
610 #include <sigfpe.h>
611 #include <signal.h>
612     int hs[] = { SIGILL, SIGFPE, SIGTRAP, SIGEMT, SIGSYS };
613
614     int onoff, en_mask, abort_action, i;
615
616     tMPI_Thread_mutex_lock(&debug_mutex);
617     onoff   = _DEBUG;
618     en_mask = _EN_UNDERFL | _EN_OVERFL | _EN_DIVZERO |
619         _EN_INVALID | _EN_INT_OVERFL;
620     abort_action = _ABORT_ON_ERROR;
621     handle_sigfpes(onoff, en_mask, user_routine, abort_action, abort_routine);
622
623     for (i = 0; (i < asize(hs)); i++)
624     {
625         signal(hs[i], handle_signals);
626     }
627     tMPI_Thread_mutex_unlock(&debug_mutex);
628 }
629 #endif /* __sgi and FPE */
630
631 static const char *gmxuser = "Please report this to the mailing list (gmx-users@gromacs.org)";
632
633 static void (*gmx_error_handler)(const char *msg) = quit_gmx;
634
635 void set_gmx_error_handler(void (*func)(const char *msg))
636 {
637     tMPI_Thread_mutex_lock(&debug_mutex);
638     gmx_error_handler = func;
639     tMPI_Thread_mutex_unlock(&debug_mutex);
640 }
641
642 char *gmx_strerror(const char *key)
643 {
644     typedef struct {
645         const char *key, *msg;
646     } error_msg_t;
647     error_msg_t msg[] = {
648         { "bug",    "Possible bug" },
649         { "call",   "Routine should not have been called" },
650         { "comm",   "Communication (parallel processing) problem" },
651         { "fatal",  "Fatal error" },
652         { "cmd",    "Invalid command line argument" },
653         { "file",   "File input/output error" },
654         { "impl",   "Implementation restriction" },
655         { "incons", "Software inconsistency error" },
656         { "input",  "Input error or input inconsistency" },
657         { "mem",    "Memory allocation/freeing error" },
658         { "open",   "Can not open file" },
659         { "range",  "Range checking error" }
660     };
661 #define NMSG asize(msg)
662     char buf[1024];
663     size_t i;
664
665     if (key == NULL)
666     {
667         return strdup("Empty message");
668     }
669     else
670     {
671         for (i = 0; (i < NMSG); i++)
672         {
673             if (strcmp(key, msg[i].key) == 0)
674             {
675                 break;
676             }
677         }
678         if (i == NMSG)
679         {
680             sprintf(buf, "No error message associated with key %s\n%s", key, gmxuser);
681             return strdup(buf);
682         }
683         else
684         {
685             return strdup(msg[i].msg);
686         }
687     }
688 }
689
690
691 void _gmx_error(const char *key, const char *msg, const char *file, int line)
692 {
693     char buf[10240], tmpbuf[1024], errerrbuf[1024];
694     int  cqnum;
695     const char *llines = "-------------------------------------------------------";
696     char *strerr;
697
698     /* protect the audience from suggestive discussions */
699
700     if (msg == NULL)
701     {
702         sprintf(errerrbuf, "Empty fatal_error message. %s", gmxuser);
703     }
704
705     cool_quote(tmpbuf, 1023, &cqnum);
706     strerr = gmx_strerror(key);
707     sprintf(buf, "\n%s\nProgram %s, %s\n"
708             "Source code file: %s, line: %d\n\n"
709             "%s:\n%s\nFor more information and tips for troubleshooting, please check the GROMACS\n"
710             "website at http://www.gromacs.org/Documentation/Errors\n%s\n\n%s\n",
711             llines, ShortProgram(), GromacsVersion(), file, line,
712             strerr, msg ? msg : errerrbuf, llines, tmpbuf);
713     free(strerr);
714
715     gmx_error_handler(buf);
716 }
717
718 void _range_check(int n, int n_min, int n_max, const char *warn_str,
719                   const char *var, const char *file, int line)
720 {
721     char buf[1024];
722
723     if ((n < n_min) || (n >= n_max))
724     {
725         if (warn_str != NULL)
726         {
727             strcpy(buf, warn_str);
728             strcat(buf, "\n");
729         }
730         else
731         {
732             buf[0] = '\0';
733         }
734
735         sprintf(buf+strlen(buf), "Variable %s has value %d. It should have been "
736                 "within [ %d .. %d ]\n", var, n, n_min, n_max);
737
738         _gmx_error("range", buf, file, line);
739     }
740 }
741
742 void gmx_warning(const char *fmt, ...)
743 {
744     va_list ap;
745     char msg[STRLEN];
746
747     va_start(ap, fmt);
748
749     parse_printf_args(fmt, &ap, msg);
750
751     va_end(ap);
752
753     fprintf(stderr, "\nWARNING: %s\n\n", msg);
754 }