abseil-cpp/absl/debugging/internal/stack_consumption.cc
Go to the documentation of this file.
1 //
2 // Copyright 2018 The Abseil Authors.
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 // https://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 
16 #include "absl/debugging/internal/stack_consumption.h"
17 
18 #ifdef ABSL_INTERNAL_HAVE_DEBUGGING_STACK_CONSUMPTION
19 
20 #include <signal.h>
21 #include <sys/mman.h>
22 #include <unistd.h>
23 
24 #include <string.h>
25 
26 #include "absl/base/attributes.h"
27 #include "absl/base/internal/raw_logging.h"
28 
29 namespace absl {
31 namespace debugging_internal {
32 namespace {
33 
34 // This code requires that we know the direction in which the stack
35 // grows. It is commonly believed that this can be detected by putting
36 // a variable on the stack and then passing its address to a function
37 // that compares the address of this variable to the address of a
38 // variable on the function's own stack. However, this is unspecified
39 // behavior in C++: If two pointers p and q of the same type point to
40 // different objects that are not members of the same object or
41 // elements of the same array or to different functions, or if only
42 // one of them is null, the results of p<q, p>q, p<=q, and p>=q are
43 // unspecified. Therefore, instead we hardcode the direction of the
44 // stack on platforms we know about.
45 #if defined(__i386__) || defined(__x86_64__) || defined(__ppc__) || \
46  defined(__aarch64__) || defined(__riscv)
47 constexpr bool kStackGrowsDown = true;
48 #else
49 #error Need to define kStackGrowsDown
50 #endif
51 
52 // To measure the stack footprint of some code, we create a signal handler
53 // (for SIGUSR2 say) that exercises this code on an alternate stack. This
54 // alternate stack is initialized to some known pattern (0x55, 0x55, 0x55,
55 // ...). We then self-send this signal, and after the signal handler returns,
56 // look at the alternate stack buffer to see what portion has been touched.
57 //
58 // This trick gives us the the stack footprint of the signal handler. But the
59 // signal handler, even before the code for it is exercised, consumes some
60 // stack already. We however only want the stack usage of the code inside the
61 // signal handler. To measure this accurately, we install two signal handlers:
62 // one that does nothing and just returns, and the user-provided signal
63 // handler. The difference between the stack consumption of these two signals
64 // handlers should give us the stack foorprint of interest.
65 
66 void EmptySignalHandler(int) {}
67 
68 // This is arbitrary value, and could be increase further, at the cost of
69 // memset()ting it all to known sentinel value.
70 constexpr int kAlternateStackSize = 64 << 10; // 64KiB
71 
72 constexpr int kSafetyMargin = 32;
73 constexpr char kAlternateStackFillValue = 0x55;
74 
75 // These helper functions look at the alternate stack buffer, and figure
76 // out what portion of this buffer has been touched - this is the stack
77 // consumption of the signal handler running on this alternate stack.
78 // This function will return -1 if the alternate stack buffer has not been
79 // touched. It will abort the program if the buffer has overflowed or is about
80 // to overflow.
81 int GetStackConsumption(const void* const altstack) {
82  const char* begin;
83  int increment;
84  if (kStackGrowsDown) {
85  begin = reinterpret_cast<const char*>(altstack);
86  increment = 1;
87  } else {
88  begin = reinterpret_cast<const char*>(altstack) + kAlternateStackSize - 1;
89  increment = -1;
90  }
91 
92  for (int usage_count = kAlternateStackSize; usage_count > 0; --usage_count) {
93  if (*begin != kAlternateStackFillValue) {
94  ABSL_RAW_CHECK(usage_count <= kAlternateStackSize - kSafetyMargin,
95  "Buffer has overflowed or is about to overflow");
96  return usage_count;
97  }
98  begin += increment;
99  }
100 
101  ABSL_RAW_LOG(FATAL, "Unreachable code");
102  return -1;
103 }
104 
105 } // namespace
106 
107 int GetSignalHandlerStackConsumption(void (*signal_handler)(int)) {
108  // The alt-signal-stack cannot be heap allocated because there is a
109  // bug in glibc-2.2 where some signal handler setup code looks at the
110  // current stack pointer to figure out what thread is currently running.
111  // Therefore, the alternate stack must be allocated from the main stack
112  // itself.
113  void* altstack = mmap(nullptr, kAlternateStackSize, PROT_READ | PROT_WRITE,
114  MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
115  ABSL_RAW_CHECK(altstack != MAP_FAILED, "mmap() failed");
116 
117  // Set up the alt-signal-stack (and save the older one).
118  stack_t sigstk;
119  memset(&sigstk, 0, sizeof(sigstk));
120  sigstk.ss_sp = altstack;
121  sigstk.ss_size = kAlternateStackSize;
122  sigstk.ss_flags = 0;
123  stack_t old_sigstk;
124  memset(&old_sigstk, 0, sizeof(old_sigstk));
125  ABSL_RAW_CHECK(sigaltstack(&sigstk, &old_sigstk) == 0,
126  "sigaltstack() failed");
127 
128  // Set up SIGUSR1 and SIGUSR2 signal handlers (and save the older ones).
129  struct sigaction sa;
130  memset(&sa, 0, sizeof(sa));
131  struct sigaction old_sa1, old_sa2;
132  sigemptyset(&sa.sa_mask);
133  sa.sa_flags = SA_ONSTACK;
134 
135  // SIGUSR1 maps to EmptySignalHandler.
136  sa.sa_handler = EmptySignalHandler;
137  ABSL_RAW_CHECK(sigaction(SIGUSR1, &sa, &old_sa1) == 0, "sigaction() failed");
138 
139  // SIGUSR2 maps to signal_handler.
140  sa.sa_handler = signal_handler;
141  ABSL_RAW_CHECK(sigaction(SIGUSR2, &sa, &old_sa2) == 0, "sigaction() failed");
142 
143  // Send SIGUSR1 signal and measure the stack consumption of the empty
144  // signal handler.
145  // The first signal might use more stack space. Run once and ignore the
146  // results to get that out of the way.
147  ABSL_RAW_CHECK(kill(getpid(), SIGUSR1) == 0, "kill() failed");
148 
149  memset(altstack, kAlternateStackFillValue, kAlternateStackSize);
150  ABSL_RAW_CHECK(kill(getpid(), SIGUSR1) == 0, "kill() failed");
151  int base_stack_consumption = GetStackConsumption(altstack);
152 
153  // Send SIGUSR2 signal and measure the stack consumption of signal_handler.
154  ABSL_RAW_CHECK(kill(getpid(), SIGUSR2) == 0, "kill() failed");
155  int signal_handler_stack_consumption = GetStackConsumption(altstack);
156 
157  // Now restore the old alt-signal-stack and signal handlers.
158  if (old_sigstk.ss_sp == nullptr && old_sigstk.ss_size == 0 &&
159  (old_sigstk.ss_flags & SS_DISABLE)) {
160  // https://git.musl-libc.org/cgit/musl/commit/src/signal/sigaltstack.c?id=7829f42a2c8944555439380498ab8b924d0f2070
161  // The original stack has ss_size==0 and ss_flags==SS_DISABLE, but some
162  // versions of musl have a bug that rejects ss_size==0. Work around this by
163  // setting ss_size to MINSIGSTKSZ, which should be ignored by the kernel
164  // when SS_DISABLE is set.
165  old_sigstk.ss_size = MINSIGSTKSZ;
166  }
167  ABSL_RAW_CHECK(sigaltstack(&old_sigstk, nullptr) == 0,
168  "sigaltstack() failed");
169  ABSL_RAW_CHECK(sigaction(SIGUSR1, &old_sa1, nullptr) == 0,
170  "sigaction() failed");
171  ABSL_RAW_CHECK(sigaction(SIGUSR2, &old_sa2, nullptr) == 0,
172  "sigaction() failed");
173 
174  ABSL_RAW_CHECK(munmap(altstack, kAlternateStackSize) == 0, "munmap() failed");
175  if (signal_handler_stack_consumption != -1 && base_stack_consumption != -1) {
176  return signal_handler_stack_consumption - base_stack_consumption;
177  }
178  return -1;
179 }
180 
181 } // namespace debugging_internal
183 } // namespace absl
184 
185 #endif // ABSL_INTERNAL_HAVE_DEBUGGING_STACK_CONSUMPTION
ABSL_RAW_CHECK
#define ABSL_RAW_CHECK(condition, message)
Definition: abseil-cpp/absl/base/internal/raw_logging.h:59
memset
return memset(p, 0, total)
begin
char * begin
Definition: abseil-cpp/absl/strings/internal/str_format/float_conversion.cc:1007
string.h
signal_handler
void signal_handler(uv_signal_t *req, int signum)
Definition: libuv/docs/code/queue-cancel/main.c:33
ABSL_NAMESPACE_END
#define ABSL_NAMESPACE_END
Definition: third_party/abseil-cpp/absl/base/config.h:171
ABSL_NAMESPACE_BEGIN
#define ABSL_NAMESPACE_BEGIN
Definition: third_party/abseil-cpp/absl/base/config.h:170
FATAL
#define FATAL(msg)
Definition: task.h:88
absl
Definition: abseil-cpp/absl/algorithm/algorithm.h:31
ABSL_RAW_LOG
#define ABSL_RAW_LOG(severity,...)
Definition: abseil-cpp/absl/base/internal/raw_logging.h:44


grpc
Author(s):
autogenerated on Fri May 16 2025 03:00:17