1 /* Page fault handling library.
2    Copyright (C) 1993-2021 Free Software Foundation, Inc.
3    Copyright (C) 2018  Nylon Chen <nylon7@andestech.com>
4 
5    This program is free software: you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 2 of the License, or
8    (at your option) any later version.
9 
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14 
15    You should have received a copy of the GNU General Public License
16    along with this program.  If not, see <https://www.gnu.org/licenses/>.  */
17 
18 /* Written by Bruno Haible and Nylon Chen.  */
19 
20 #include <config.h>
21 
22 /* Specification.  */
23 #include "sigsegv.h"
24 
25 #include <errno.h>
26 #include <stdio.h> /* declares perror */
27 #include <stdint.h> /* defines uintptr_t */
28 #include <stdlib.h>
29 #include <signal.h>
30 #if HAVE_GETRLIMIT
31 # include <sys/resource.h> /* declares struct rlimit */
32 #endif
33 
34 #ifdef __OpenBSD__
35 # include <sys/param.h> /* defines macro OpenBSD */
36 #endif
37 
38 
39 /* Version number.  */
40 int libsigsegv_version = LIBSIGSEGV_VERSION;
41 
42 
43 /* ======================= Fault handler information ======================= */
44 
45 /* Define:
46 
47      SIGSEGV_FAULT_HANDLER_ARGLIST
48           is the argument list for the actual fault handler.
49 
50    and if available (optional):
51 
52      SIGSEGV_FAULT_ADDRESS
53           is a macro for fetching the fault address.
54 
55      SIGSEGV_FAULT_CONTEXT
56           is a macro giving a pointer to the entire fault context (i.e.
57           the register set etc.).
58 
59      SIGSEGV_FAULT_STACKPOINTER
60           is a macro for fetching the stackpointer at the moment the fault
61           occurred.
62  */
63 
64 #if defined __linux__ || defined __ANDROID__ /* Linux */
65 
66 # define SIGSEGV_FAULT_HANDLER_ARGLIST  int sig, siginfo_t *sip, void *ucp
67 # define SIGSEGV_FAULT_ADDRESS  sip->si_addr
68 # define SIGSEGV_FAULT_CONTEXT  ((ucontext_t *) ucp)
69 # define SIGSEGV_FAULT_ADDRESS_FROM_SIGINFO
70 
71 # if defined __alpha__
72 
73 /* See glibc/sysdeps/unix/sysv/linux/alpha/sys/ucontext.h
74    and the definition of GET_STACK in
75    glibc/sysdeps/unix/sysv/linux/alpha/sigcontextinfo.h.
76    Note that the 'mcontext_t' defined in
77    glibc/sysdeps/unix/sysv/linux/alpha/sys/ucontext.h
78    and the 'struct sigcontext' defined in <asm/sigcontext.h>
79    are actually the same.  */
80 
81 #  define SIGSEGV_FAULT_STACKPOINTER  ((ucontext_t *) ucp)->uc_mcontext.sc_regs[30]
82 
83 # elif defined __arm64__ /* 64-bit */
84 
85 /* See glibc/sysdeps/unix/sysv/linux/aarch64/sys/ucontext.h.
86    Note that the 'mcontext_t' defined in
87    glibc/sysdeps/unix/sysv/linux/aarch64/sys/ucontext.h
88    and the 'struct sigcontext' defined in <asm/sigcontext.h>
89    are actually the same.  */
90 
91 #  define SIGSEGV_FAULT_STACKPOINTER  ((ucontext_t *) ucp)->uc_mcontext.sp
92 
93 # elif defined __arm__ || defined __armhf__ /* 32-bit */
94 
95 /* See glibc/sysdeps/unix/sysv/linux/arm/sys/ucontext.h
96    and the definition of GET_STACK in
97    glibc/sysdeps/unix/sysv/linux/arm/sigcontextinfo.h.
98    Note that the 'mcontext_t' defined in
99    glibc/sysdeps/unix/sysv/linux/arm/sys/ucontext.h
100    and the 'struct sigcontext' defined in <asm/sigcontext.h>
101    are actually the same.  */
102 
103 #  define SIGSEGV_FAULT_STACKPOINTER  ((ucontext_t *) ucp)->uc_mcontext.arm_sp
104 
105 # elif defined __cris__
106 
107 /* See glibc-ports/sysdeps/unix/sysv/linux/cris/sys/ucontext.h.
108    Note that the 'mcontext_t' defined in
109    glibc-ports/sysdeps/unix/sysv/linux/cris/sys/ucontext.h
110    and the 'struct sigcontext' defined in <asm/sigcontext.h>
111    are actually the same.  */
112 
113 #  define SIGSEGV_FAULT_STACKPOINTER  ((ucontext_t *) ucp)->uc_mcontext.usp
114 
115 # elif defined __hppa__
116 
117 /* See glibc/sysdeps/unix/sysv/linux/hppa/sys/ucontext.h.
118    Note that the 'mcontext_t' defined in
119    glibc/sysdeps/unix/sysv/linux/hppa/sys/ucontext.h
120    and the 'struct sigcontext' defined in <asm/sigcontext.h>
121    are actually the same.  */
122 
123 #  define SIGSEGV_FAULT_STACKPOINTER  ((ucontext_t *) ucp)->uc_mcontext.sc_gr[30]
124 
125 # elif defined __x86_64__ /* 64 bit registers */
126 
127 /* See glibc/sysdeps/unix/sysv/linux/x86/sys/ucontext.h
128    and the definition of GET_STACK in
129    glibc/sysdeps/unix/sysv/linux/x86_64/sigcontextinfo.h.
130    Note that the 'mcontext_t' defined in
131    glibc/sysdeps/unix/sysv/linux/x86/sys/ucontext.h
132    and the 'struct sigcontext' defined in
133    glibc/sysdeps/unix/sysv/linux/x86/bits/sigcontext.h
134    (see also <asm/sigcontext.h>)
135    are effectively the same.  */
136 
137 #  define SIGSEGV_FAULT_STACKPOINTER  ((ucontext_t *) ucp)->uc_mcontext.gregs[REG_RSP]
138 
139 # elif defined __i386__ /* 32 bit registers */
140 
141 /* See glibc/sysdeps/unix/sysv/linux/x86/sys/ucontext.h
142    and the definition of GET_STACK in
143    glibc/sysdeps/unix/sysv/linux/i386/sigcontextinfo.h.
144    Note that the 'mcontext_t' defined in
145    glibc/sysdeps/unix/sysv/linux/x86/sys/ucontext.h
146    and the 'struct sigcontext_ia32' defined in <asm/sigcontext32.h>
147    are effectively the same.  */
148 
149 #  define SIGSEGV_FAULT_STACKPOINTER  ((ucontext_t *) ucp)->uc_mcontext.gregs[REG_ESP]
150                      /* same value as ((ucontext_t *) ucp)->uc_mcontext.gregs[REG_UESP] */
151 
152 # elif defined __ia64__
153 
154 /* See glibc/sysdeps/unix/sysv/linux/ia64/sys/ucontext.h.
155    Note that the 'mcontext_t' defined in
156    glibc/sysdeps/unix/sysv/linux/ia64/sys/ucontext.h
157    and the 'struct sigcontext' defined in
158    glibc/sysdeps/unix/sysv/linux/ia64/bits/sigcontext.h
159    (see also <asm/sigcontext.h>)
160    are actually the same.  */
161 
162 /* IA-64 has two stack pointers, one that grows down, called $r12, and one
163    that grows up, called $bsp/$bspstore.  */
164 #  define SIGSEGV_FAULT_STACKPOINTER  ((ucontext_t *) ucp)->uc_mcontext.sc_gr[12]
165 
166 /* It would be better to access $bspstore instead of $bsp but I don't know
167    where to find it in 'struct sigcontext'.  Anyway, it doesn't matter
168    because $bsp and $bspstore never differ by more than ca. 1 KB.  */
169 #  define SIGSEGV_FAULT_BSP_POINTER  ((ucontext_t *) ucp)->uc_mcontext.sc_ar_bsp
170 
171 # elif defined __m68k__
172 
173 /* See glibc/sysdeps/unix/sysv/linux/m68k/sys/ucontext.h
174    and the definition of GET_STACK in
175    glibc/sysdeps/unix/sysv/linux/m68k/sigcontextinfo.h.
176    Note that the 'mcontext_t' defined in
177    glibc/sysdeps/unix/sysv/linux/m68k/sys/ucontext.h
178    and the 'struct sigcontext' defined in <asm/sigcontext.h>
179    are quite different types.  */
180 
181 #  define SIGSEGV_FAULT_STACKPOINTER  ((ucontext_t *) ucp)->uc_mcontext.gregs[R_SP]
182 
183 # elif defined __mips__ || defined __mipsn32__ || defined __mips64__
184 
185 /* See glibc/sysdeps/unix/sysv/linux/mips/sys/ucontext.h
186    and the definition of GET_STACK in
187    glibc/sysdeps/unix/sysv/linux/mips/sigcontextinfo.h.
188    Note that the 'mcontext_t' defined in
189    glibc/sysdeps/unix/sysv/linux/mips/sys/ucontext.h
190    and the 'struct sigcontext' defined in
191    glibc/sysdeps/unix/sysv/linux/mips/bits/sigcontext.h
192    (see also <asm/sigcontext.h>)
193    are effectively the same.  */
194 
195 #  define SIGSEGV_FAULT_STACKPOINTER  ((ucontext_t *) ucp)->uc_mcontext.gregs[29]
196 
197 # elif defined __nds32__
198 
199 /* See glibc/sysdeps/unix/sysv/linux/nds32/sys/ucontext.h
200    and the definition of GET_STACK in
201    glibc/sysdeps/unix/sysv/linux/nds32/sigcontextinfo.h.
202    Both are found in <https://patches-gcc.linaro.org/cover/4409/> part 08/11
203    <https://sourceware.org/ml/libc-alpha/2018-05/msg00125.html>.  */
204 
205 #  define SIGSEGV_FAULT_STACKPOINTER  ((ucontext_t *) ucp)->uc_mcontext.nds32_sp
206 
207 # elif defined __powerpc__ || defined __powerpc64__ || defined __powerpc64_elfv2__
208 
209 /* See glibc/sysdeps/unix/sysv/linux/powerpc/sys/ucontext.h
210    and the definition of GET_STACK in
211    glibc/sysdeps/unix/sysv/linux/powerpc/sigcontextinfo.h.
212    Note that the 'mcontext_t' defined in
213    glibc/sysdeps/unix/sysv/linux/powerpc/sys/ucontext.h,
214    the 'struct sigcontext' defined in <asm/sigcontext.h>,
215    and the 'struct pt_regs' defined in <asm/ptrace.h>
216    are quite different types.  */
217 
218 #  if defined __powerpc64__ || defined __powerpc64_elfv2__ /* 64-bit */
219 #   define SIGSEGV_FAULT_STACKPOINTER  ((ucontext_t *) ucp)->uc_mcontext.gp_regs[1]
220 #  else /* 32-bit */
221 /* both should be equivalent */
222 #   if 0
223 #    define SIGSEGV_FAULT_STACKPOINTER  ((ucontext_t *) ucp)->uc_mcontext.regs->gpr[1]
224 #   else
225 #    define SIGSEGV_FAULT_STACKPOINTER  ((ucontext_t *) ucp)->uc_mcontext.uc_regs->gregs[1]
226 #   endif
227 #  endif
228 
229 # elif defined __riscv32__ || __riscv64__
230 
231 /* See glibc/sysdeps/unix/sysv/linux/riscv/sys/ucontext.h
232    and the definition of GET_STACK in
233    glibc/sysdeps/unix/sysv/linux/riscv/sigcontextinfo.h.
234    Note that the 'mcontext_t' defined in
235    glibc/sysdeps/unix/sysv/linux/riscv/sys/ucontext.h
236    and the 'struct sigcontext' defined in
237    glibc/sysdeps/unix/sysv/linux/riscv/bits/sigcontext.h
238    start with the same block of 32 general-purpose registers.  */
239 
240 #  define SIGSEGV_FAULT_STACKPOINTER  ((ucontext_t *) ucp)->uc_mcontext.__gregs[REG_SP]
241 
242 # elif defined __s390__ || defined __s390x__
243 
244 /* See glibc/sysdeps/unix/sysv/linux/s390/sys/ucontext.h
245    and the definition of GET_STACK in
246    glibc/sysdeps/unix/sysv/linux/s390/sigcontextinfo.h.
247    Note that the 'mcontext_t' defined in
248    glibc/sysdeps/unix/sysv/linux/s390/sys/ucontext.h
249    and the '_sigregs' type, indirect part of 'struct sigcontext', defined
250    in <asm/sigcontext.h>, are effectively the same.  */
251 
252 #  define SIGSEGV_FAULT_STACKPOINTER  ((ucontext_t *) ucp)->uc_mcontext.gregs[15]
253 
254 # elif defined __sh__
255 
256 /* See glibc/sysdeps/unix/sysv/linux/sh/sys/ucontext.h
257    and the definition of GET_STACK in
258    glibc/sysdeps/unix/sysv/linux/sh/sigcontextinfo.h.
259    Note that the 'mcontext_t' defined in
260    glibc/sysdeps/unix/sysv/linux/sh/sys/ucontext.h
261    and the 'struct sigcontext' defined in <asm/sigcontext.h>
262    are effectively the same.  */
263 
264 #  define SIGSEGV_FAULT_STACKPOINTER  ((ucontext_t *) ucp)->uc_mcontext.gregs[15]
265 
266 # elif defined __sparc__ || defined __sparc64__
267 
268 /* See glibc/sysdeps/unix/sysv/linux/sparc/sys/ucontext.h
269    and the definition of GET_STACK in
270    glibc/sysdeps/unix/sysv/linux/sparc/{sparc32,sparc64}/sigcontextinfo.h.
271    Note that the 'mcontext_t' defined in
272    glibc/sysdeps/unix/sysv/linux/sparc/sys/ucontext.h
273    and the 'struct sigcontext' defined in
274    glibc/sysdeps/unix/sysv/linux/sparc/bits/sigcontext.h
275    (see also <asm/sigcontext.h>)
276    are quite different types.  */
277 
278 #  if defined __sparc64__/* 64-bit */
279 /* From linux-4.8.1/arch/sparc/kernel/signal_64.c, function setup_rt_frame, we
280    see that ucp is not an 'ucontext_t *' but rather a 'struct sigcontext *'
281    that happens to have the same value as sip (which is possible because a
282    'struct sigcontext' starts with 128 bytes room for the siginfo_t).  */
283 #   define SIGSEGV_FAULT_STACKPOINTER  (((struct sigcontext *) ucp)->sigc_regs.u_regs[14] + 2047)
284 #  else /* 32-bit */
285 /* From linux-4.8.1/arch/sparc/kernel/signal_32.c, function setup_rt_frame,
286    and linux-4.8.1/arch/sparc/kernel/signal32.c, function setup_rt_frame32, we
287    see that ucp is a 'struct pt_regs *' or 'struct pt_regs32 *', respectively.
288    In userland, this is a 'struct sigcontext *'.  */
289 #   define SIGSEGV_FAULT_STACKPOINTER  ((struct sigcontext *) ucp)->si_regs.u_regs[14]
290 #  endif
291 
292 /* The sip->si_addr field is correct for a normal fault, but unusable in case
293    of a stack overflow. What I observe (when running
294    tests/test-sigsegv-catch-stackoverflow1, with a printf right at the beginning
295    of sigsegv_handler) is that sip->si_addr is near 0:
296      - in 64-bit mode: sip->si_addr = 0x000000000000030F, and gdb shows me that
297        the fault occurs in an instruction 'stx %o3,[%fp+0x30f]' and %fp is 0.
298        In fact, all registers %l0..%l7 and %i0..%i7 are 0.
299      - in 32-bit mode: sip->si_addr = 0xFFFFFA64, and gdb shows me that
300        the fault occurs in an instruction 'st %g2,[%fp-1436]' and %fp is 0.
301        In fact, all registers %l0..%l7 and %i0..%i7 are 0.
302    Apparently when the stack overflow occurred, some trap has tried to move the
303    contents of the registers %l0..%l7 and %i0..%i7 (a "window" in SPARC
304    terminology) to the stack, did not succeed in doing this, replaced all these
305    register values with 0, and resumed execution at the fault location. This
306    time, due to %fp = 0, a different fault was triggered. Now it is impossible
307    to determine the real (previous) fault address because, even if know the
308    faulting instruction, the previous register values have been lost.  */
309 #  define BOGUS_FAULT_ADDRESS_UPON_STACK_OVERFLOW
310 
311 # else
312 
313 /* When adding support for other CPUs here:  */
314 
315 /* For SIGSEGV_FAULT_HANDLER_ARGLIST, see the definition of SIGCONTEXT in
316    glibc/sysdeps/unix/sysv/linux/<cpu>/sigcontextinfo.h.  */
317 
318 /* For SIGSEGV_FAULT_STACKPOINTER, see the definition of GET_STACK in
319    glibc/sysdeps/unix/sysv/linux/<cpu>/sigcontextinfo.h.  */
320 
321 # endif
322 
323 #endif
324 
325 #if defined __GNU__ /* Hurd */
326 
327 # define SIGSEGV_FAULT_HANDLER_ARGLIST  int sig, int code, struct sigcontext *scp
328 # define SIGSEGV_FAULT_ADDRESS  (unsigned long) code
329 # define SIGSEGV_FAULT_CONTEXT  scp
330 
331 # if defined __i386__
332 
333 /* scp points to a 'struct sigcontext' (defined in
334    glibc/sysdeps/mach/hurd/i386/bits/sigcontext.h).
335    The registers of this struct get pushed on the stack through
336    gnumach/i386/i386/locore.S:trapall.  */
337 /* Both sc_esp and sc_uesp appear to have the same value.
338    It appears more reliable to use sc_uesp because it is labelled as
339    "old esp, if trapped from user".  */
340 #  define SIGSEGV_FAULT_STACKPOINTER  scp->sc_uesp
341 
342 # endif
343 
344 #endif
345 
346 #if defined __FreeBSD_kernel__ || defined __FreeBSD__ || defined __DragonFly__ /* GNU/kFreeBSD, FreeBSD */
347 
348 # if defined __arm__ || defined __armhf__ || defined __arm64__
349 
350 #  define SIGSEGV_FAULT_HANDLER_ARGLIST  int sig, siginfo_t *sip, void *ucp
351 #  define SIGSEGV_FAULT_ADDRESS  sip->si_addr
352 #  define SIGSEGV_FAULT_CONTEXT  ((ucontext_t *) ucp)
353 
354 #  if defined __arm64__ /* 64-bit */
355 
356 /* See sys/arm64/include/ucontext.h.  */
357 
358 #   define SIGSEGV_FAULT_STACKPOINTER  ((ucontext_t *) ucp)->uc_mcontext.mc_gpregs.gp_sp
359 
360 #  elif defined __arm__ || defined __armhf__ /* 32-bit */
361 
362 /* See sys/arm/include/ucontext.h.  */
363 
364 #   define SIGSEGV_FAULT_STACKPOINTER  ((ucontext_t *) ucp)->uc_mcontext.__gregs[_REG_SP]
365 
366 #  endif
367 
368 # else
369 
370 /* On FreeBSD 12, both of these approaches work.  On FreeBSD derivatives, the
371    first one has more chances to work.  */
372 #  if 1
373 /* Use signal handlers without SA_SIGINFO.  */
374 
375 #   define SIGSEGV_FAULT_HANDLER_ARGLIST  int sig, int code, struct sigcontext *scp, void *addr
376 #   define SIGSEGV_FAULT_ADDRESS  addr
377 #   define SIGSEGV_FAULT_CONTEXT  scp
378 
379 /* See sys/x86/include/signal.h.  */
380 
381 #   if defined __x86_64__
382 /* 64 bit registers */
383 
384 #    define SIGSEGV_FAULT_STACKPOINTER  scp->sc_rsp
385 
386 #   elif defined __i386__
387 /* 32 bit registers */
388 
389 #    define SIGSEGV_FAULT_STACKPOINTER  scp->sc_esp
390 
391 #   endif
392 
393 #  else
394 /* Use signal handlers with SA_SIGINFO.  */
395 
396 #   define SIGSEGV_FAULT_HANDLER_ARGLIST  int sig, siginfo_t *sip, void *scp
397 #   define SIGSEGV_FAULT_ADDRESS  sip->si_addr
398 #   define SIGSEGV_FAULT_CONTEXT  ((struct sigcontext *) scp)
399 #   define SIGSEGV_FAULT_ADDRESS_FROM_SIGINFO
400 
401 /* See sys/x86/include/signal.h.  */
402 
403 #   if defined __x86_64__
404 /* 64 bit registers */
405 
406 #    define SIGSEGV_FAULT_STACKPOINTER  ((struct sigcontext *) scp)->sc_rsp
407 
408 #   elif defined __i386__
409 /* 32 bit registers */
410 
411 #    define SIGSEGV_FAULT_STACKPOINTER  ((struct sigcontext *) scp)->sc_esp
412 
413 #   endif
414 
415 #  endif
416 
417 # endif
418 
419 #endif
420 
421 #if defined __NetBSD__ /* NetBSD */
422 
423 # define SIGSEGV_FAULT_HANDLER_ARGLIST  int sig, siginfo_t *sip, void *ucp
424 # define SIGSEGV_FAULT_ADDRESS  sip->si_addr
425 # define SIGSEGV_FAULT_CONTEXT  ((ucontext_t *) ucp)
426 # define SIGSEGV_FAULT_ADDRESS_FROM_SIGINFO
427 
428 /* _UC_MACHINE_SP is a platform independent macro.
429    Defined in <machine/mcontext.h>, see
430      http://cvsweb.netbsd.org/bsdweb.cgi/src/sys/arch/$arch/include/mcontext.h
431    Supported on alpha, amd64, i386, ia64, m68k, mips, powerpc, sparc since
432    NetBSD 2.0.
433    On i386, _UC_MACHINE_SP is the same as ->uc_mcontext.__gregs[_REG_UESP],
434    and apparently the same value as       ->uc_mcontext.__gregs[_REG_ESP]. */
435 # ifdef _UC_MACHINE_SP
436 #  define SIGSEGV_FAULT_STACKPOINTER  _UC_MACHINE_SP ((ucontext_t *) ucp)
437 # endif
438 
439 #endif
440 
441 #if defined __OpenBSD__ /* OpenBSD */
442 
443 # define SIGSEGV_FAULT_HANDLER_ARGLIST  int sig, siginfo_t *sip, struct sigcontext *scp
444 # define SIGSEGV_FAULT_ADDRESS  sip->si_addr
445 # define SIGSEGV_FAULT_CONTEXT  scp
446 # define SIGSEGV_FAULT_ADDRESS_FROM_SIGINFO
447 
448 # if defined __alpha__
449 
450 /* See the definition of 'struct sigcontext' in
451    openbsd-src/sys/arch/alpha/include/signal.h.  */
452 
453 #  define SIGSEGV_FAULT_STACKPOINTER  scp->sc_regs[30]
454 
455 # elif defined __arm__ || defined __armhf__
456 
457 /* See the definition of 'struct sigcontext' in
458    openbsd-src/sys/arch/arm/include/signal.h.  */
459 
460 #  define SIGSEGV_FAULT_STACKPOINTER  scp->sc_usr_sp
461 
462 # elif defined __hppa__ || defined __hppa64__
463 
464 /* See the definition of 'struct sigcontext' in
465    openbsd-src/sys/arch/hppa/include/signal.h
466    and
467    openbsd-src/sys/arch/hppa64/include/signal.h.  */
468 
469 #  define SIGSEGV_FAULT_STACKPOINTER  scp->sc_regs[30]
470 
471 # elif defined __x86_64__
472 /* 64 bit registers */
473 
474 /* See the definition of 'struct sigcontext' in
475    openbsd-src/sys/arch/amd64/include/signal.h.  */
476 
477 #  define SIGSEGV_FAULT_STACKPOINTER  scp->sc_rsp
478 
479 # elif defined __i386__
480 /* 32 bit registers */
481 
482 /* See the definition of 'struct sigcontext' in
483    openbsd-src/sys/arch/i386/include/signal.h.  */
484 
485 #  define SIGSEGV_FAULT_STACKPOINTER  scp->sc_esp
486 
487 # elif defined __m68k__
488 
489 /* See the definition of 'struct sigcontext' in
490    openbsd-src/sys/arch/m68k/include/signal.h.  */
491 
492 #  define SIGSEGV_FAULT_STACKPOINTER  scp->sc_sp
493 
494 # elif defined __m88k__
495 
496 /* See the definition of 'struct sigcontext' in
497    openbsd-src/sys/arch/m88k/include/signal.h
498    and the definition of 'struct reg' in
499    openbsd-src/sys/arch/m88k/include/reg.h.  */
500 
501 #  if OpenBSD >= 201211 /* OpenBSD version >= 5.2 */
502 #   define SIGSEGV_FAULT_STACKPOINTER  scp->sc_regs[31]
503 #  else
504 #   define SIGSEGV_FAULT_STACKPOINTER  scp->sc_regs.r[31]
505 #  endif
506 
507 # elif defined __mips__ || defined __mipsn32__ || defined __mips64__
508 
509 /* See the definition of 'struct sigcontext' in
510    openbsd-src/sys/arch/mips64/include/signal.h.  */
511 
512 #  define SIGSEGV_FAULT_STACKPOINTER  scp->sc_regs[29]
513 
514 # elif defined __powerpc__ || defined __powerpc64__
515 
516 /* See the definition of 'struct sigcontext' and 'struct trapframe' in
517    openbsd-src/sys/arch/powerpc/include/signal.h.  */
518 
519 #  define SIGSEGV_FAULT_STACKPOINTER  scp->sc_frame.fixreg[1]
520 
521 # elif defined __sh__
522 
523 /* See the definition of 'struct sigcontext' in
524    openbsd-src/sys/arch/sh/include/signal.h
525    and the definition of 'struct reg' in
526    openbsd-src/sys/arch/sh/include/reg.h.  */
527 
528 #  if OpenBSD >= 201211 /* OpenBSD version >= 5.2 */
529 #   define SIGSEGV_FAULT_STACKPOINTER  scp->sc_reg[20-15]
530 #  else
531 #   define SIGSEGV_FAULT_STACKPOINTER  scp->sc_reg.r_r15
532 #  endif
533 
534 # elif defined __sparc__ || defined __sparc64__
535 
536 /* See the definition of 'struct sigcontext' in
537    openbsd-src/sys/arch/sparc/include/signal.h
538    and
539    openbsd-src/sys/arch/sparc64/include/signal.h.  */
540 
541 #  define SIGSEGV_FAULT_STACKPOINTER  scp->sc_sp
542 
543 # elif defined __vax__
544 
545 /* See the definition of 'struct sigcontext' in
546    openbsd-src/sys/arch/vax/include/signal.h.  */
547 
548 #  define SIGSEGV_FAULT_STACKPOINTER  scp->sc_sp
549 
550 # endif
551 
552 #endif
553 
554 #if (defined __APPLE__ && defined __MACH__) /* macOS */
555 
556 # define SIGSEGV_FAULT_HANDLER_ARGLIST  int sig, siginfo_t *sip, void *ucp
557 # define SIGSEGV_FAULT_ADDRESS  sip->si_addr
558 # define SIGSEGV_FAULT_CONTEXT  ((ucontext_t *) ucp)
559 # define SIGSEGV_FAULT_ADDRESS_FROM_SIGINFO
560 
561 # if defined __x86_64__
562 
563 /* See the definitions of
564      - 'ucontext_t' and 'struct __darwin_ucontext' in <sys/_types/_ucontext.h>,
565      - 'struct __darwin_mcontext64' in <i386/_mcontext.h>, and
566      - 'struct __darwin_x86_thread_state64' in <mach/i386/_structs.h>.  */
567 #  define SIGSEGV_FAULT_STACKPOINTER  ((ucontext_t *) ucp)->uc_mcontext->__ss.__rsp
568 
569 # elif defined __i386__
570 
571 /* See the definitions of
572      - 'ucontext_t' and 'struct __darwin_ucontext' in <sys/_types/_ucontext.h>,
573      - 'struct __darwin_mcontext32' in <i386/_mcontext.h>, and
574      - 'struct __darwin_i386_thread_state' in <mach/i386/_structs.h>.  */
575 #  define SIGSEGV_FAULT_STACKPOINTER  ((ucontext_t *) ucp)->uc_mcontext->__ss.__esp
576 
577 # elif defined __arm64__
578 
579 /* See the definitions of
580      - 'ucontext_t' and 'struct __darwin_ucontext' in <sys/_types/_ucontext.h>,
581      - 'struct __darwin_mcontext64' in <arm/_mcontext.h>, and
582      - 'struct __darwin_arm_thread_state64' in <mach/arm/_structs.h>.  */
583 #  define SIGSEGV_FAULT_STACKPOINTER  ((ucontext_t *) ucp)->uc_mcontext->__ss.__sp
584 
585 # elif defined __powerpc__
586 
587 /* See the definitions of
588      - 'ucontext_t' and 'struct __darwin_ucontext' in <sys/_structs.h>,
589      - 'struct __darwin_mcontext' in <ppc/_structs.h>, and
590      - 'struct __darwin_ppc_thread_state' in <mach/ppc/_structs.h>.  */
591 #  define SIGSEGV_FAULT_STACKPOINTER  ((ucontext_t *) ucp)->uc_mcontext->__ss.__r1
592 
593 # endif
594 
595 #endif
596 
597 #if defined _AIX /* AIX */
598 
599 # define SIGSEGV_FAULT_HANDLER_ARGLIST  int sig, siginfo_t *sip, void *ucp
600 # define SIGSEGV_FAULT_ADDRESS  sip->si_addr
601 # define SIGSEGV_FAULT_CONTEXT  ((ucontext_t *) ucp)
602 # define SIGSEGV_FAULT_ADDRESS_FROM_SIGINFO
603 
604 # if defined __powerpc__ || defined __powerpc64__
605 #  define SIGSEGV_FAULT_STACKPOINTER  ((ucontext_t *) ucp)->uc_mcontext.jmp_context.gpr[1]
606 # endif
607 
608 #endif
609 
610 #if defined __sgi /* IRIX */
611 
612 # define SIGSEGV_FAULT_HANDLER_ARGLIST  int sig, int code, struct sigcontext *scp
613 # define SIGSEGV_FAULT_ADDRESS  (unsigned long) scp->sc_badvaddr
614 # define SIGSEGV_FAULT_CONTEXT  scp
615 
616 # if defined __mips__ || defined __mipsn32__ || defined __mips64__
617 #  define SIGSEGV_FAULT_STACKPOINTER  scp->sc_regs[29]
618 # endif
619 
620 #endif
621 
622 #if defined __sun /* Solaris */
623 
624 # define SIGSEGV_FAULT_HANDLER_ARGLIST  int sig, siginfo_t *sip, void *ucp
625 # define SIGSEGV_FAULT_ADDRESS  sip->si_addr
626 # define SIGSEGV_FAULT_CONTEXT  ((ucontext_t *) ucp)
627 # define SIGSEGV_FAULT_ADDRESS_FROM_SIGINFO
628 
629 # if defined __x86_64__
630 /* 64 bit registers */
631 
632 #  define SIGSEGV_FAULT_STACKPOINTER  ((ucontext_t *) ucp)->uc_mcontext.gregs[REG_RSP]
633 
634 # elif defined __i386__
635 /* 32 bit registers */
636 
637 #  define SIGSEGV_FAULT_STACKPOINTER  ((ucontext_t *) ucp)->uc_mcontext.gregs[ESP]
638 
639 # elif defined __sparc__ || defined __sparc64__
640 
641 #  define SIGSEGV_FAULT_STACKPOINTER  ((ucontext_t *) ucp)->uc_mcontext.gregs[REG_O6]
642 
643 #  if SOLARIS11
644 
645 /* On Solaris 11.3/SPARC, both in 32-bit and 64-bit mode, when catching
646    stack overflow, the fault address is correct the first time, but is zero
647    or near zero the second time.
648    'truss tests/test-sigsegv-catch-stackoverflow1' shows it:
649 
650    In 32-bit mode:
651 
652     Incurred fault #6, FLTBOUNDS  %pc = 0x000116E8
653       siginfo: SIGSEGV SEGV_MAPERR addr=0xFFB00000
654     Received signal #11, SIGSEGV [caught]
655       siginfo: SIGSEGV SEGV_MAPERR addr=0xFFB00000
656    then
657     Incurred fault #6, FLTBOUNDS  %pc = 0x000116E8
658       siginfo: SIGSEGV SEGV_MAPERR addr=0x00000008
659     Received signal #11, SIGSEGV [caught]
660       siginfo: SIGSEGV SEGV_MAPERR addr=0x00000008
661 
662    In 64-bit mode:
663 
664     Incurred fault #6, FLTBOUNDS  %pc = 0x100001C58
665       siginfo: SIGSEGV SEGV_MAPERR addr=0xFFFFFFFF7FF00000
666     Received signal #11, SIGSEGV [caught]
667       siginfo: SIGSEGV SEGV_MAPERR addr=0xFFFFFFFF7FF00000
668    then
669     Incurred fault #6, FLTBOUNDS  %pc = 0x100001C58
670       siginfo: SIGSEGV SEGV_MAPERR addr=0x00000000
671     Received signal #11, SIGSEGV [caught]
672       siginfo: SIGSEGV SEGV_MAPERR addr=0x00000000
673  */
674 #   define BOGUS_FAULT_ADDRESS_UPON_STACK_OVERFLOW
675 
676 #  endif
677 
678 # endif
679 
680 #endif
681 
682 #if defined __CYGWIN__ /* Cygwin */
683 
684 # define SIGSEGV_FAULT_HANDLER_ARGLIST  int sig, siginfo_t *sip, void *ucp
685 # define SIGSEGV_FAULT_ADDRESS  sip->si_addr
686 # define SIGSEGV_FAULT_CONTEXT  ((ucontext_t *) ucp)
687 # define SIGSEGV_FAULT_ADDRESS_FROM_SIGINFO
688 
689 /* See the definition of 'ucontext_t' in <sys/ucontext.h> and
690    of 'struct __mcontext' in <cygwin/signal.h>.  */
691 # if defined __x86_64__
692 /* 64 bit registers */
693 #  define SIGSEGV_FAULT_STACKPOINTER  ((ucontext_t *) ucp)->uc_mcontext.rsp
694 # elif defined __i386__
695 /* 32 bit registers */
696 #  define SIGSEGV_FAULT_STACKPOINTER  ((ucontext_t *) ucp)->uc_mcontext.esp
697 # endif
698 
699 #endif
700 
701 #if defined __HAIKU__ /* Haiku */
702 
703 # define SIGSEGV_FAULT_HANDLER_ARGLIST  int sig, siginfo_t *sip, void *ucp
704 # define SIGSEGV_FAULT_ADDRESS  sip->si_addr
705 # define SIGSEGV_FAULT_CONTEXT  ((ucontext_t *) ucp)
706 # define SIGSEGV_FAULT_ADDRESS_FROM_SIGINFO
707 
708 # if defined __x86_64__
709 /* 64 bit registers */
710 
711 /* See the definition of 'ucontext_t' in <signal.h> and
712    of 'struct vregs' in <arch/x86_64/signal.h>.  */
713 
714 #  define SIGSEGV_FAULT_STACKPOINTER  ((ucontext_t *) ucp)->uc_mcontext.rsp
715 
716 # elif defined __i386__
717 /* 32 bit registers */
718 
719 /* See the definition of 'ucontext_t' in <signal.h> and
720    of 'struct vregs' in <arch/x86/signal.h>.  */
721 
722 #  define SIGSEGV_FAULT_STACKPOINTER  ((ucontext_t *) ucp)->uc_mcontext.esp
723 
724 # endif
725 
726 #endif
727 
728 /* ========================================================================== */
729 
730 /* List of signals that are sent when an invalid virtual memory address
731    is accessed, or when the stack overflows.  */
732 #if defined __GNU__ \
733     || defined __FreeBSD_kernel__ || defined __FreeBSD__ || defined __DragonFly__ \
734     || defined __NetBSD__ || defined __OpenBSD__ \
735     || (defined __APPLE__ && defined __MACH__)
736 # define SIGSEGV_FOR_ALL_SIGNALS(var,body) \
737     { int var; var = SIGSEGV; { body } var = SIGBUS; { body } }
738 #else
739 # define SIGSEGV_FOR_ALL_SIGNALS(var,body) \
740     { int var; var = SIGSEGV; { body } }
741 #endif
742 
743 /* ========================================================================== */
744 
745 /* Determine the virtual memory area of a given address.  */
746 #include "stackvma.h"
747 
748 /* ========================================================================== */
749 
750 /* On the average Unix platform, we define
751 
752    HAVE_SIGSEGV_RECOVERY
753        if there is a fault-*.h include file which defines
754        SIGSEGV_FAULT_HANDLER_ARGLIST and SIGSEGV_FAULT_ADDRESS.
755 
756    HAVE_STACK_OVERFLOW_RECOVERY
757        if HAVE_SIGALTSTACK is set and
758        at least two of the following are true:
759        A) There is a fault-*.h include file which defines
760           SIGSEGV_FAULT_HANDLER_ARGLIST and SIGSEGV_FAULT_ADDRESS.
761        B) There is a fault-*.h include file which defines
762           SIGSEGV_FAULT_HANDLER_ARGLIST and SIGSEGV_FAULT_STACKPOINTER.
763        C) There is a stackvma-*.c, other than stackvma-none.c, which
764           defines sigsegv_get_vma.
765 
766    Why? Obviously, to catch stack overflow, we need an alternate signal
767    stack; this requires kernel support. But we also need to distinguish
768    (with a reasonable confidence) a stack overflow from a regular SIGSEGV.
769    If we have A) and B), we use the
770      Heuristic AB: If the fault address is near the stack pointer, it's a
771      stack overflow.
772    If we have A) and C), we use the
773      Heuristic AC: If the fault address is near and beyond the bottom of
774      the stack's virtual memory area, it's a stack overflow.
775    If we have B) and C), we use the
776      Heuristic BC: If the stack pointer is near the bottom of the stack's
777      virtual memory area, it's a stack overflow.
778      This heuristic comes in two flavours: On OSes which let the stack's
779      VMA grow continuously, we determine the bottom by use of getrlimit().
780      On OSes which preallocate the stack's VMA with its maximum size
781      (like BeOS), we use the stack's VMA directly.
782  */
783 
784 #if HAVE_SIGSEGV_RECOVERY \
785      && !(defined SIGSEGV_FAULT_HANDLER_ARGLIST && defined SIGSEGV_FAULT_ADDRESS)
786 # error "You need to define SIGSEGV_FAULT_HANDLER_ARGLIST and SIGSEGV_FAULT_ADDRESS before you can define HAVE_SIGSEGV_RECOVERY."
787 #endif
788 #if !HAVE_SIGSEGV_RECOVERY \
789     && (defined SIGSEGV_FAULT_HANDLER_ARGLIST && defined SIGSEGV_FAULT_ADDRESS) \
790     && !(defined __FreeBSD__ && (defined __sparc__ || defined __sparc64__))
791 # if __GNUC__ || (__clang_major__ >= 4)
792 #  warning "You can define HAVE_SIGSEGV_RECOVERY on this platform."
793 # else
794 #  error "You can define HAVE_SIGSEGV_RECOVERY on this platform."
795 # endif
796 #endif
797 
798 #if HAVE_STACK_OVERFLOW_RECOVERY \
799     && !(defined SIGSEGV_FAULT_ADDRESS + defined SIGSEGV_FAULT_STACKPOINTER + HAVE_STACKVMA >= 2)
800 # error "You need to define two of SIGSEGV_FAULT_ADDRESS, SIGSEGV_FAULT_STACKPOINTER, HAVE_STACKVMA, before you can define HAVE_STACK_OVERFLOW_RECOVERY."
801 #endif
802 #if !HAVE_STACK_OVERFLOW_RECOVERY \
803     && (defined SIGSEGV_FAULT_ADDRESS + defined SIGSEGV_FAULT_STACKPOINTER + HAVE_STACKVMA >= 2) \
804     && !(defined __FreeBSD__ && (defined __sparc__ || defined __sparc64__)) \
805     && !(defined __NetBSD__ && (defined __sparc__ || defined __sparc64__))
806 # if __GNUC__ || (__clang_major__ >= 4)
807 #  warning "You can define HAVE_STACK_OVERFLOW_RECOVERY on this platform."
808 # else
809 #  error "You can define HAVE_STACK_OVERFLOW_RECOVERY on this platform."
810 # endif
811 #endif
812 
813 /* ========================================================================== */
814 
815 #if HAVE_STACK_OVERFLOW_RECOVERY
816 
817 /* ======= Leaving a signal handler executing on the alternate stack ======= */
818 
819 /* Platform dependent:
820    Leaving a signal handler executing on the alternate stack.  */
821 static void sigsegv_reset_onstack_flag (void);
822 
823 /* -------------------------- leave-sigaltstack.c -------------------------- */
824 
825 # if defined __GNU__ \
826      || defined __FreeBSD_kernel__ || defined __FreeBSD__ || defined __DragonFly__ \
827      || defined __NetBSD__ || defined __OpenBSD__
828 
829 static void
sigsegv_reset_onstack_flag(void)830 sigsegv_reset_onstack_flag (void)
831 {
832   stack_t ss;
833 
834   if (sigaltstack (NULL, &ss) >= 0)
835     {
836       ss.ss_flags &= ~SS_ONSTACK;
837       sigaltstack (&ss, NULL);
838     }
839 }
840 
841 /* --------------------------- leave-setcontext.c --------------------------- */
842 
843 # elif defined __sgi || defined __sun /* IRIX, Solaris */
844 
845 #  include <ucontext.h>
846 
847 static void
sigsegv_reset_onstack_flag(void)848 sigsegv_reset_onstack_flag (void)
849 {
850   ucontext_t uc;
851 
852   if (getcontext (&uc) >= 0)
853     /* getcontext returns twice.  We are interested in the returned context
854        only the first time, i.e. when the SS_ONSTACK bit is set.  */
855     if (uc.uc_stack.ss_flags & SS_ONSTACK)
856       {
857         uc.uc_stack.ss_flags &= ~SS_ONSTACK;
858         /* Note that setcontext() does not refill uc.  Therefore if
859            setcontext() keeps SS_ONSTACK set in the kernel, either
860            setcontext() will return -1 or getcontext() will return a
861            second time, with the SS_ONSTACK bit being cleared.  */
862         setcontext (&uc);
863       }
864 }
865 
866 /* ------------------------------ leave-nop.c ------------------------------ */
867 
868 # else
869 
870 static void
sigsegv_reset_onstack_flag(void)871 sigsegv_reset_onstack_flag (void)
872 {
873   /* Nothing to do. sigaltstack() simply looks at the stack pointer,
874      therefore SS_ONSTACK is not sticky.  */
875 }
876 
877 # endif
878 
879 /* ========================================================================== */
880 
881 # if HAVE_STACKVMA
882 
883 /* Address of the last byte belonging to the stack vma.  */
884 static uintptr_t stack_top = 0;
885 
886 /* Needs to be called once only.  */
887 static void
remember_stack_top(void * some_variable_on_stack)888 remember_stack_top (void *some_variable_on_stack)
889 {
890   struct vma_struct vma;
891 
892   if (sigsegv_get_vma ((uintptr_t) some_variable_on_stack, &vma) >= 0)
893     stack_top = vma.end - 1;
894 }
895 
896 # endif /* HAVE_STACKVMA */
897 
898 static stackoverflow_handler_t stk_user_handler = (stackoverflow_handler_t)NULL;
899 static uintptr_t stk_extra_stack;
900 static size_t stk_extra_stack_size;
901 
902 #endif /* HAVE_STACK_OVERFLOW_RECOVERY */
903 
904 #if HAVE_SIGSEGV_RECOVERY
905 
906 /* User's SIGSEGV handler.  */
907 static sigsegv_handler_t user_handler = (sigsegv_handler_t)NULL;
908 
909 #endif /* HAVE_SIGSEGV_RECOVERY */
910 
911 
912 /* Our SIGSEGV handler, with OS dependent argument list.  */
913 
914 #if HAVE_SIGSEGV_RECOVERY
915 
916 static void
sigsegv_handler(SIGSEGV_FAULT_HANDLER_ARGLIST)917 sigsegv_handler (SIGSEGV_FAULT_HANDLER_ARGLIST)
918 {
919   void *address = (void *) (SIGSEGV_FAULT_ADDRESS);
920 
921 # if HAVE_STACK_OVERFLOW_RECOVERY
922 #  if !(HAVE_STACKVMA || defined SIGSEGV_FAULT_STACKPOINTER)
923 #error "Insufficient heuristics for detecting a stack overflow.  Either define CFG_STACKVMA and HAVE_STACKVMA correctly, or define SIGSEGV_FAULT_STACKPOINTER correctly, or undefine HAVE_STACK_OVERFLOW_RECOVERY!"
924 #  endif
925 
926   /* Call user's handler.  */
927   if (user_handler && (*user_handler) (address, 0))
928     {
929       /* Handler successful.  */
930     }
931   else
932     {
933       /* Handler declined responsibility.  */
934 
935       /* Did the user install a stack overflow handler?  */
936       if (stk_user_handler)
937         {
938           /* See whether it was a stack overflow. If so, longjump away.  */
939 #  ifdef SIGSEGV_FAULT_STACKPOINTER
940           uintptr_t old_sp = (uintptr_t) (SIGSEGV_FAULT_STACKPOINTER);
941 #   ifdef __ia64
942           uintptr_t old_bsp = (uintptr_t) (SIGSEGV_FAULT_BSP_POINTER);
943 #   endif
944 #  endif
945 
946 #  if HAVE_STACKVMA
947           /* Were we able to determine the stack top?  */
948           if (stack_top)
949             {
950               /* Determine stack bounds.  */
951               int saved_errno;
952               struct vma_struct vma;
953               int ret;
954 
955               saved_errno = errno;
956               ret = sigsegv_get_vma (stack_top, &vma);
957               errno = saved_errno;
958               if (ret >= 0)
959                 {
960 #   ifndef BOGUS_FAULT_ADDRESS_UPON_STACK_OVERFLOW
961                   /* Heuristic AC: If the fault_address is nearer to the stack
962                      segment's [start,end] than to the previous segment, we
963                      consider it a stack overflow.
964                      In the case of IA-64, we know that the previous segment
965                      is the up-growing bsp segment, and either of the two
966                      stacks can overflow.  */
967                   uintptr_t addr = (uintptr_t) address;
968 
969 #    ifdef __ia64
970                   if (addr >= vma.prev_end && addr <= vma.end - 1)
971 #    else
972 #     if STACK_DIRECTION < 0
973                   if (addr >= vma.start
974                       ? (addr <= vma.end - 1)
975                       : vma.is_near_this (addr, &vma))
976 #     else
977                   if (addr <= vma.end - 1
978                       ? (addr >= vma.start)
979                       : vma.is_near_this (addr, &vma))
980 #     endif
981 #    endif
982                     {
983 #   else /* BOGUS_FAULT_ADDRESS_UPON_STACK_OVERFLOW */
984 #    if HAVE_GETRLIMIT && defined RLIMIT_STACK
985                   /* Heuristic BC: If the stack size has reached its maximal size,
986                      and old_sp is near the low end, we consider it a stack
987                      overflow.  */
988                   struct rlimit rl;
989 
990                   saved_errno = errno;
991                   ret = getrlimit (RLIMIT_STACK, &rl);
992                   errno = saved_errno;
993                   if (ret >= 0)
994                     {
995                       uintptr_t current_stack_size = vma.end - vma.start;
996                       uintptr_t max_stack_size = rl.rlim_cur;
997                       if (current_stack_size <= max_stack_size + 4096
998                           && max_stack_size <= current_stack_size + 4096
999 #    else
1000                     {
1001                       if (1
1002 #    endif
1003 #    ifdef SIGSEGV_FAULT_STACKPOINTER
1004                           /* Heuristic BC: If we know old_sp, and it is neither
1005                              near the low end, nor in the alternate stack, then
1006                              it's probably not a stack overflow.  */
1007                           && ((old_sp >= stk_extra_stack
1008                                && old_sp <= stk_extra_stack + stk_extra_stack_size)
1009 #     if STACK_DIRECTION < 0
1010                               || (old_sp <= vma.start + 4096
1011                                   && vma.start <= old_sp + 4096))
1012 #     else
1013                               || (old_sp <= vma.end + 4096
1014                                   && vma.end <= old_sp + 4096))
1015 #     endif
1016 #    endif
1017                          )
1018 #   endif /* BOGUS_FAULT_ADDRESS_UPON_STACK_OVERFLOW */
1019 #  else /* !HAVE_STACKVMA */
1020           /* Heuristic AB: If the fault address is near the stack pointer,
1021              it's a stack overflow.  */
1022           uintptr_t addr = (uintptr_t) address;
1023 
1024           if ((addr <= old_sp + 4096 && old_sp <= addr + 4096)
1025 #   ifdef __ia64
1026               || (addr <= old_bsp + 4096 && old_bsp <= addr + 4096)
1027 #   endif
1028              )
1029             {
1030                 {
1031                     {
1032 #  endif /* !HAVE_STACKVMA */
1033                         {
1034 #  ifdef SIGSEGV_FAULT_STACKPOINTER
1035                           int emergency =
1036                             (old_sp >= stk_extra_stack
1037                              && old_sp <= stk_extra_stack + stk_extra_stack_size);
1038                           stackoverflow_context_t context = (SIGSEGV_FAULT_CONTEXT);
1039 #  else
1040                           int emergency = 0;
1041                           stackoverflow_context_t context = (void *) 0;
1042 #  endif
1043                           /* Call user's handler.  */
1044                           (*stk_user_handler) (emergency, context);
1045                         }
1046                     }
1047                 }
1048             }
1049         }
1050 # endif /* HAVE_STACK_OVERFLOW_RECOVERY */
1051 
1052       if (user_handler && (*user_handler) (address, 1))
1053         {
1054           /* Handler successful.  */
1055         }
1056       else
1057         {
1058           /* Handler declined responsibility for real.  */
1059 
1060           /* Remove ourselves and dump core.  */
1061           SIGSEGV_FOR_ALL_SIGNALS (signo, signal (signo, SIG_DFL);)
1062         }
1063 
1064 # if HAVE_STACK_OVERFLOW_RECOVERY
1065     }
1066 # endif /* HAVE_STACK_OVERFLOW_RECOVERY */
1067 }
1068 
1069 #elif HAVE_STACK_OVERFLOW_RECOVERY
1070 
1071 static void
1072 # ifdef SIGSEGV_FAULT_STACKPOINTER
1073 sigsegv_handler (SIGSEGV_FAULT_HANDLER_ARGLIST)
1074 # else
1075 sigsegv_handler (int sig)
1076 # endif
1077 {
1078 # if !((HAVE_GETRLIMIT && defined RLIMIT_STACK) || defined SIGSEGV_FAULT_STACKPOINTER)
1079 #  error "Insufficient heuristics for detecting a stack overflow.  Either define SIGSEGV_FAULT_STACKPOINTER correctly, or undefine HAVE_STACK_OVERFLOW_RECOVERY!"
1080 # endif
1081 
1082   /* Did the user install a handler?  */
1083   if (stk_user_handler)
1084     {
1085       /* See whether it was a stack overflow.  If so, longjump away.  */
1086 # ifdef SIGSEGV_FAULT_STACKPOINTER
1087       uintptr_t old_sp = (uintptr_t) (SIGSEGV_FAULT_STACKPOINTER);
1088 # endif
1089 
1090       /* Were we able to determine the stack top?  */
1091       if (stack_top)
1092         {
1093           /* Determine stack bounds.  */
1094           int saved_errno;
1095           struct vma_struct vma;
1096           int ret;
1097 
1098           saved_errno = errno;
1099           ret = sigsegv_get_vma (stack_top, &vma);
1100           errno = saved_errno;
1101           if (ret >= 0)
1102             {
1103 # if HAVE_GETRLIMIT && defined RLIMIT_STACK
1104               /* Heuristic BC: If the stack size has reached its maximal size,
1105                  and old_sp is near the low end, we consider it a stack
1106                  overflow.  */
1107               struct rlimit rl;
1108 
1109               saved_errno = errno;
1110               ret = getrlimit (RLIMIT_STACK, &rl);
1111               errno = saved_errno;
1112               if (ret >= 0)
1113                 {
1114                   uintptr_t current_stack_size = vma.end - vma.start;
1115                   uintptr_t max_stack_size = rl.rlim_cur;
1116                   if (current_stack_size <= max_stack_size + 4096
1117                       && max_stack_size <= current_stack_size + 4096
1118 # else
1119                 {
1120                   if (1
1121 # endif
1122 # ifdef SIGSEGV_FAULT_STACKPOINTER
1123                       /* Heuristic BC: If we know old_sp, and it is neither
1124                          near the low end, nor in the alternate stack, then
1125                          it's probably not a stack overflow.  */
1126                       && ((old_sp >= stk_extra_stack
1127                            && old_sp <= stk_extra_stack + stk_extra_stack_size)
1128 #  if STACK_DIRECTION < 0
1129                           || (old_sp <= vma.start + 4096
1130                               && vma.start <= old_sp + 4096))
1131 #  else
1132                           || (old_sp <= vma.end + 4096
1133                               && vma.end <= old_sp + 4096))
1134 #  endif
1135 # endif
1136                      )
1137                     {
1138 # ifdef SIGSEGV_FAULT_STACKPOINTER
1139                       int emergency =
1140                         (old_sp >= stk_extra_stack
1141                          && old_sp <= stk_extra_stack + stk_extra_stack_size);
1142                       stackoverflow_context_t context = (SIGSEGV_FAULT_CONTEXT);
1143 # else
1144                       int emergency = 0;
1145                       stackoverflow_context_t context = (void *) 0;
1146 # endif
1147                       /* Call user's handler.  */
1148                       (*stk_user_handler)(emergency,context);
1149                     }
1150                 }
1151             }
1152         }
1153     }
1154 
1155   /* Remove ourselves and dump core.  */
1156   SIGSEGV_FOR_ALL_SIGNALS (signo, signal (signo, SIG_DFL);)
1157 }
1158 
1159 #endif
1160 
1161 
1162 #if HAVE_SIGSEGV_RECOVERY || HAVE_STACK_OVERFLOW_RECOVERY
1163 
1164 static void
1165 install_for (int sig)
1166 {
1167   struct sigaction action;
1168 
1169 # ifdef SIGSEGV_FAULT_ADDRESS_FROM_SIGINFO
1170   action.sa_sigaction = &sigsegv_handler;
1171 # else
1172   action.sa_handler = (void (*) (int)) &sigsegv_handler;
1173 # endif
1174   /* Block most signals while SIGSEGV is being handled.  */
1175   /* Signals SIGKILL, SIGSTOP cannot be blocked.  */
1176   /* Signals SIGCONT, SIGTSTP, SIGTTIN, SIGTTOU are not blocked because
1177      dealing with these signals seems dangerous.  */
1178   /* Signals SIGILL, SIGABRT, SIGFPE, SIGSEGV, SIGTRAP, SIGIOT, SIGEMT, SIGBUS,
1179      SIGSYS, SIGSTKFLT are not blocked because these are synchronous signals,
1180      which may require immediate intervention, otherwise the process may
1181      starve.  */
1182   sigemptyset (&action.sa_mask);
1183 # ifdef SIGHUP
1184   sigaddset (&action.sa_mask,SIGHUP);
1185 # endif
1186 # ifdef SIGINT
1187   sigaddset (&action.sa_mask,SIGINT);
1188 # endif
1189 # ifdef SIGQUIT
1190   sigaddset (&action.sa_mask,SIGQUIT);
1191 # endif
1192 # ifdef SIGPIPE
1193   sigaddset (&action.sa_mask,SIGPIPE);
1194 # endif
1195 # ifdef SIGALRM
1196   sigaddset (&action.sa_mask,SIGALRM);
1197 # endif
1198 # ifdef SIGTERM
1199   sigaddset (&action.sa_mask,SIGTERM);
1200 # endif
1201 # ifdef SIGUSR1
1202   sigaddset (&action.sa_mask,SIGUSR1);
1203 # endif
1204 # ifdef SIGUSR2
1205   sigaddset (&action.sa_mask,SIGUSR2);
1206 # endif
1207 # ifdef SIGCHLD
1208   sigaddset (&action.sa_mask,SIGCHLD);
1209 # endif
1210 # ifdef SIGCLD
1211   sigaddset (&action.sa_mask,SIGCLD);
1212 # endif
1213 # ifdef SIGURG
1214   sigaddset (&action.sa_mask,SIGURG);
1215 # endif
1216 # ifdef SIGIO
1217   sigaddset (&action.sa_mask,SIGIO);
1218 # endif
1219 # ifdef SIGPOLL
1220   sigaddset (&action.sa_mask,SIGPOLL);
1221 # endif
1222 # ifdef SIGXCPU
1223   sigaddset (&action.sa_mask,SIGXCPU);
1224 # endif
1225 # ifdef SIGXFSZ
1226   sigaddset (&action.sa_mask,SIGXFSZ);
1227 # endif
1228 # ifdef SIGVTALRM
1229   sigaddset (&action.sa_mask,SIGVTALRM);
1230 # endif
1231 # ifdef SIGPROF
1232   sigaddset (&action.sa_mask,SIGPROF);
1233 # endif
1234 # ifdef SIGPWR
1235   sigaddset (&action.sa_mask,SIGPWR);
1236 # endif
1237 # ifdef SIGLOST
1238   sigaddset (&action.sa_mask,SIGLOST);
1239 # endif
1240 # ifdef SIGWINCH
1241   sigaddset (&action.sa_mask,SIGWINCH);
1242 # endif
1243   /* Note that sigaction() implicitly adds sig itself to action.sa_mask.  */
1244   /* Ask the OS to provide a structure siginfo_t to the handler.  */
1245 # ifdef SIGSEGV_FAULT_ADDRESS_FROM_SIGINFO
1246   action.sa_flags = SA_SIGINFO;
1247 # else
1248   action.sa_flags = 0;
1249 # endif
1250 # if HAVE_STACK_OVERFLOW_RECOVERY && HAVE_SIGALTSTACK /* not BeOS */
1251   /* Work around Linux 2.2.5 bug: If SA_ONSTACK is specified but sigaltstack()
1252      has not been called, the kernel will busy loop, eating CPU time.  So
1253      avoid setting SA_ONSTACK until the user has requested stack overflow
1254      handling.  */
1255   if (stk_user_handler)
1256     action.sa_flags |= SA_ONSTACK;
1257 # endif
1258   sigaction (sig, &action, (struct sigaction *) NULL);
1259 }
1260 
1261 #endif /* HAVE_SIGSEGV_RECOVERY || HAVE_STACK_OVERFLOW_RECOVERY */
1262 
1263 int
1264 sigsegv_install_handler (sigsegv_handler_t handler)
1265 {
1266 #if HAVE_SIGSEGV_RECOVERY
1267   user_handler = handler;
1268 
1269   SIGSEGV_FOR_ALL_SIGNALS (sig, install_for (sig);)
1270 
1271   return 0;
1272 #else
1273   return -1;
1274 #endif
1275 }
1276 
1277 void
1278 sigsegv_deinstall_handler (void)
1279 {
1280 #if HAVE_SIGSEGV_RECOVERY
1281   user_handler = (sigsegv_handler_t)NULL;
1282 
1283 # if HAVE_STACK_OVERFLOW_RECOVERY
1284   if (!stk_user_handler)
1285 # endif
1286     {
1287       SIGSEGV_FOR_ALL_SIGNALS (sig, signal (sig, SIG_DFL);)
1288     }
1289 #endif
1290 }
1291 
1292 int
1293 sigsegv_leave_handler (void (*continuation) (void*, void*, void*),
1294                        void* cont_arg1, void* cont_arg2, void* cont_arg3)
1295 {
1296 #if HAVE_STACK_OVERFLOW_RECOVERY
1297   /*
1298    * Reset the system's knowledge that we are executing on the alternate
1299    * stack. If we didn't do that, siglongjmp would be needed instead of
1300    * longjmp to leave the signal handler.
1301    */
1302   sigsegv_reset_onstack_flag ();
1303 #endif
1304   (*continuation) (cont_arg1, cont_arg2, cont_arg3);
1305   return 1;
1306 }
1307 
1308 int
1309 stackoverflow_install_handler (stackoverflow_handler_t handler,
1310                                void *extra_stack, size_t extra_stack_size)
1311 {
1312 #if HAVE_STACK_OVERFLOW_RECOVERY
1313 # if HAVE_STACKVMA
1314   if (!stack_top)
1315     {
1316       int dummy;
1317       remember_stack_top (&dummy);
1318       if (!stack_top)
1319         return -1;
1320     }
1321 # endif
1322 
1323   stk_user_handler = handler;
1324   stk_extra_stack = (uintptr_t) extra_stack;
1325   stk_extra_stack_size = extra_stack_size;
1326   {
1327     stack_t ss;
1328 # if SIGALTSTACK_SS_REVERSED
1329     ss.ss_sp = (char *) extra_stack + extra_stack_size - sizeof (void *);
1330     ss.ss_size = extra_stack_size - sizeof (void *);
1331 # else
1332     ss.ss_sp = extra_stack;
1333     ss.ss_size = extra_stack_size;
1334 # endif
1335     ss.ss_flags = 0; /* no SS_DISABLE */
1336     if (sigaltstack (&ss, (stack_t*)0) < 0)
1337       return -1;
1338   }
1339 
1340   /* Install the signal handlers with SA_ONSTACK.  */
1341   SIGSEGV_FOR_ALL_SIGNALS (sig, install_for (sig);)
1342   return 0;
1343 #else
1344   return -1;
1345 #endif
1346 }
1347 
1348 void
1349 stackoverflow_deinstall_handler (void)
1350 {
1351 #if HAVE_STACK_OVERFLOW_RECOVERY
1352   stk_user_handler = (stackoverflow_handler_t) NULL;
1353 
1354 # if HAVE_SIGSEGV_RECOVERY
1355   if (user_handler)
1356     {
1357       /* Reinstall the signal handlers without SA_ONSTACK, to avoid Linux
1358          bug.  */
1359       SIGSEGV_FOR_ALL_SIGNALS (sig, install_for (sig);)
1360     }
1361   else
1362 # endif
1363     {
1364       SIGSEGV_FOR_ALL_SIGNALS (sig, signal (sig, SIG_DFL);)
1365     }
1366 
1367   {
1368     stack_t ss;
1369     ss.ss_flags = SS_DISABLE;
1370     if (sigaltstack (&ss, (stack_t *) 0) < 0)
1371       perror ("gnulib sigsegv (stackoverflow_deinstall_handler)");
1372   }
1373 #endif
1374 }
1375