xref: /petsc/src/sys/error/checkptr.c (revision d96cc911b64c80119868f58f2ea4711e3a6b3d32)
1 #include <petsc-private/petscimpl.h>
2 
3 /* ---------------------------------------------------------------------------------------*/
4 #if defined(PETSC_HAVE_SETJMP_H) && defined(PETSC_HAVE_SIGINFO_T)
5 #include <signal.h>
6 #include <setjmp.h>
7 PETSC_EXTERN jmp_buf PetscSegvJumpBuf;
8 PETSC_EXTERN void PetscSegv_sigaction(int, siginfo_t*, void *);
9 /*@C
10      PetscCheckPointer - Returns PETSC_TRUE if a pointer points to accessible data
11 
12    Not Collective
13 
14    Input Parameters:
15 +     ptr - the pointer
16 -     dtype - the type of data the pointer is suppose to point to
17 
18    Level: developer
19 
20 @*/
21 PetscBool PetscCheckPointer(const void *ptr,PetscDataType dtype)
22 {
23   struct sigaction sa,oldsa;
24 
25   if (PETSC_RUNNING_ON_VALGRIND) return PETSC_TRUE;
26   if (!ptr) return PETSC_FALSE;
27 
28   sigemptyset(&sa.sa_mask);
29   sa.sa_sigaction = PetscSegv_sigaction;
30   sa.sa_flags   = SA_SIGINFO;
31   sigaction(SIGSEGV, &sa, &oldsa);
32 
33   if (setjmp(PetscSegvJumpBuf)) {
34     /* A segv was triggered in the code below hence we return with an error code */
35     sigaction(SIGSEGV, &oldsa, NULL);/* reset old signal hanlder */
36     return PETSC_FALSE;
37   } else {
38     switch (dtype) {
39     case PETSC_INT:{
40       PETSC_UNUSED PetscInt x = (PetscInt)*(volatile PetscInt*)ptr;
41       break;
42     }
43 #if defined(PETSC_USE_COMPLEX)
44     case PETSC_SCALAR:{         /* C++ is seriously dysfunctional with volatile std::complex. */
45       PetscReal xreal = ((volatile PetscReal*)ptr)[0],ximag = ((volatile PetscReal*)ptr)[1];
46       PETSC_UNUSED volatile PetscScalar x = xreal + PETSC_i*ximag;
47       break;
48     }
49 #endif
50     case PETSC_REAL:{
51       PETSC_UNUSED PetscReal x = *(volatile PetscReal*)ptr;
52       break;
53     }
54     case PETSC_BOOL:{
55       PETSC_UNUSED PetscBool x = *(volatile PetscBool*)ptr;
56       break;
57     }
58     case PETSC_ENUM:{
59       PETSC_UNUSED PetscEnum x = *(volatile PetscEnum*)ptr;
60       break;
61     }
62     case PETSC_CHAR:{
63       PETSC_UNUSED char *x = *(char*volatile*)ptr;
64       break;
65     }
66     case PETSC_OBJECT:{
67       PETSC_UNUSED volatile PetscClassId classid = ((PetscObject)ptr)->classid;
68       break;
69     }
70     default:;
71     }
72   }
73   sigaction(SIGSEGV, &oldsa, NULL); /* reset old signal hanlder */
74   return PETSC_TRUE;
75 }
76 #else
77 PetscBool PetscCheckPointer(const void *ptr,PETSC_UNUSED PetscDataType dtype)
78 {
79   if (!ptr) return PETSC_FALSE;
80   return PETSC_TRUE;
81 }
82 #endif
83