1 /*=========================================================================
2 
3   Program:   Visualization Toolkit
4   Module:    vtkFloatingPointExceptions.cxx
5 
6   Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
7   All rights reserved.
8   See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
9 
10      This software is distributed WITHOUT ANY WARRANTY; without even
11      the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
12      PURPOSE.  See the above copyright notice for more information.
13 
14 =========================================================================*/
15 
16 #include "vtkFloatingPointExceptions.h"
17 
18 #include "vtkFloatingPointExceptionsConfigure.h"
19 
20 #if defined(VTK_USE_FENV)
21 #include <csignal>
22 #include <fenv.h>
23 #endif
24 
25 // for _controlfp
26 #ifdef _MSC_VER
27 #include <float.h>
28 #endif
29 
30 #if defined(VTK_USE_FENV)
31 //------------------------------------------------------------------------------
32 // Signal handler for floating point exceptions in anonymous namespace
33 namespace
34 {
35 
signal_handler(int signal)36 void signal_handler(int signal)
37 {
38   cerr << "Error: Floating point exception detected. Signal " << signal << endl;
39   // This should possibly throw an exception rather than abort, abort should
40   // at least give access to the stack when it fails here.
41   abort();
42 }
43 
44 } // End anonymous namespace
45 #endif
46 
47 //------------------------------------------------------------------------------
48 // Description:
49 // Enable floating point exceptions.
Enable()50 void vtkFloatingPointExceptions::Enable()
51 {
52 #ifdef _MSC_VER
53   // enable floating point exceptions on MSVC
54   _controlfp(_EM_DENORMAL | _EM_UNDERFLOW | _EM_INEXACT, _MCW_EM);
55 #endif //_MSC_VER
56 #if defined(VTK_USE_FENV)
57   // This should work on all platforms
58   feenableexcept(FE_DIVBYZERO | FE_INVALID);
59   // Set the signal handler
60   signal(SIGFPE, signal_handler);
61 #endif
62 }
63 
64 //------------------------------------------------------------------------------
65 // Description:
66 // Disable floating point exceptions.
Disable()67 void vtkFloatingPointExceptions::Disable()
68 {
69 #ifdef _MSC_VER
70   // disable floating point exceptions on MSVC
71   _controlfp(
72     _EM_INVALID | _EM_DENORMAL | _EM_ZERODIVIDE | _EM_OVERFLOW | _EM_UNDERFLOW | _EM_INEXACT,
73     _MCW_EM);
74 #endif //_MSC_VER
75 #if defined(VTK_USE_FENV)
76   fedisableexcept(FE_DIVBYZERO | FE_INVALID);
77 #endif
78 }
79