1 /* Stack overflow handling.
2
3 Copyright (C) 2002, 2004, 2006, 2008-2023 Free Software Foundation, Inc.
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 3 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 Paul Eggert. */
19
20 /* NOTES:
21
22 A program that uses alloca, dynamic arrays, or large local
23 variables may extend the stack by more than a page at a time. If
24 so, when the stack overflows the operating system may not detect
25 the overflow until the program uses the array, and this module may
26 incorrectly report a program error instead of a stack overflow.
27
28 To avoid this problem, allocate only small objects on the stack; a
29 program should be OK if it limits single allocations to a page or
30 less. Allocate larger arrays in static storage, or on the heap
31 (e.g., with malloc). Yes, this is a pain, but we don't know of any
32 better solution that is portable.
33
34 No attempt has been made to deal with multithreaded applications. */
35
36 #include <config.h>
37
38 #include "c-stack.h"
39
40 #include <errno.h>
41 #include <inttypes.h>
42 #include <signal.h>
43 #include <stddef.h>
44 #include <stdlib.h>
45 #include <string.h>
46 #include <unistd.h>
47
48 #if DEBUG
49 # include <stdio.h>
50 #endif
51
52 #include <sigsegv.h>
53
54 #include "exitfail.h"
55 #include "idx.h"
56 #include "ignore-value.h"
57
58 #include "gettext.h"
59 #define _(msgid) gettext (msgid)
60
61 #if HAVE_STACK_OVERFLOW_RECOVERY
62
63 /* Storage for the alternate signal stack.
64 64 KiB is not too large for Gnulib-using apps, and is large enough
65 for all known platforms. Smaller sizes may run into trouble.
66 For example, libsigsegv 2.6 through 2.8 have a bug where some
67 architectures use more than the Linux default of an 8 KiB alternate
68 stack when deciding if a fault was caused by stack overflow. */
69 static max_align_t alternate_signal_stack[(64 * 1024
70 + sizeof (max_align_t) - 1)
71 / sizeof (max_align_t)];
72
73 /* The user-specified action to take when a SEGV-related program error
74 or stack overflow occurs. */
75 static _GL_ASYNC_SAFE void (* volatile segv_action) (int);
76
77 /* Translated messages for program errors and stack overflow. Do not
78 translate them in the signal handler, since gettext is not
79 async-signal-safe. */
80 static char const * volatile program_error_message;
81 static char const * volatile stack_overflow_message;
82
83 /* Output an error message, then exit with status EXIT_FAILURE if it
84 appears to have been a stack overflow, or with a core dump
85 otherwise. This function is async-signal-safe. */
86
87 static char const * volatile progname;
88
89 static _GL_ASYNC_SAFE _Noreturn void
90 die (int signo)
91 {
92 segv_action (signo);
93 char const *message = signo ? program_error_message : stack_overflow_message;
94
95 /* If the message is short, write it all at once to avoid
96 interleaving with other messages. Avoid writev as it is not
97 documented to be async-signal-safe. */
98 size_t prognamelen = strlen (progname);
99 size_t messagelen = strlen (message);
100 static char const separator[] = {':', ' '};
101 char buf[sizeof alternate_signal_stack / 16 + sizeof separator];
102 idx_t buflen;
103 if (prognamelen + messagelen < sizeof buf - sizeof separator)
104 {
105 char *p = mempcpy (buf, progname, prognamelen);
106 p = mempcpy (p, separator, sizeof separator);
107 p = mempcpy (p, message, messagelen);
108 *p++ = '\n';
109 buflen = p - buf;
110 }
111 else
112 {
113 ignore_value (write (STDERR_FILENO, progname, prognamelen));
114 ignore_value (write (STDERR_FILENO, separator, sizeof separator));
115 ignore_value (write (STDERR_FILENO, message, messagelen));
116 buf[0] = '\n';
117 buflen = 1;
118 }
119 ignore_value (write (STDERR_FILENO, buf, buflen));
120
121 if (! signo)
122 _exit (exit_failure);
123 raise (signo);
124 abort ();
125 }
126
127 static _GL_ASYNC_SAFE void
128 null_action (_GL_UNUSED int signo)
129 {
130 }
131
132 /* Pacify GCC 9.3.1, which otherwise would complain about segv_handler. */
133 # if 4 < __GNUC__ + (6 <= __GNUC_MINOR__)
134 # pragma GCC diagnostic ignored "-Wsuggest-attribute=pure"
135 # endif
136
137 /* Nonzero if general segv handler could not be installed. */
138 static volatile int segv_handler_missing;
139
140 /* Handle a segmentation violation and exit if it cannot be stack
141 overflow. This function is async-signal-safe. */
142
143 static _GL_ASYNC_SAFE int
144 segv_handler (_GL_UNUSED void *address, int serious)
145 {
146 # if DEBUG
147 {
148 char buf[1024];
149 int saved_errno = errno;
150 ignore_value (write (STDERR_FILENO, buf,
151 sprintf (buf, "segv_handler serious=%d\n", serious)));
152 errno = saved_errno;
153 }
154 # endif
155
156 /* If this fault is not serious, return 0 to let the stack overflow
157 handler take a shot at it. */
158 if (!serious)
159 return 0;
160 die (SIGSEGV);
161 }
162
163 /* Handle a segmentation violation that is likely to be a stack
164 overflow and exit. This function is async-signal-safe. */
165
166 static _GL_ASYNC_SAFE _Noreturn void
167 overflow_handler (int emergency, _GL_UNUSED stackoverflow_context_t context)
168 {
169 # if DEBUG
170 {
171 char buf[1024];
172 ignore_value (write (STDERR_FILENO, buf,
173 sprintf (buf, ("overflow_handler emergency=%d"
174 " segv_handler_missing=%d\n"),
175 emergency, segv_handler_missing)));
176 }
177 # endif
178
179 die ((!emergency || segv_handler_missing) ? 0 : SIGSEGV);
180 }
181
182 int
183 c_stack_action (_GL_ASYNC_SAFE void (*action) (int))
184 {
185 segv_action = action ? action : null_action;
186 program_error_message = _("program error");
187 stack_overflow_message = _("stack overflow");
188 progname = getprogname ();
189
190 /* Always install the overflow handler. */
191 if (stackoverflow_install_handler (overflow_handler,
192 alternate_signal_stack,
193 sizeof alternate_signal_stack))
194 {
195 errno = ENOTSUP;
196 return -1;
197 }
198 /* Try installing a general handler; if it fails, then treat all
199 segv as stack overflow. */
200 segv_handler_missing = sigsegv_install_handler (segv_handler);
201 return 0;
202 }
203
204 #else /* !HAVE_STACK_OVERFLOW_RECOVERY */
205
206 int
207 c_stack_action (_GL_ASYNC_SAFE void (*action) (_GL_UNUSED int) )
208 {
209 errno = ENOTSUP;
210 return -1;
211 }
212
213 #endif