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 //      http://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 {
30 namespace debugging_internal {
31 namespace {
32 
33 // This code requires that we know the direction in which the stack
34 // grows. It is commonly believed that this can be detected by putting
35 // a variable on the stack and then passing its address to a function
36 // that compares the address of this variable to the address of a
37 // variable on the function's own stack. However, this is unspecified
38 // behavior in C++: If two pointers p and q of the same type point to
39 // different objects that are not members of the same object or
40 // elements of the same array or to different functions, or if only
41 // one of them is null, the results of p<q, p>q, p<=q, and p>=q are
42 // unspecified. Therefore, instead we hardcode the direction of the
43 // stack on platforms we know about.
44 #if defined(__i386__) || defined(__x86_64__) || defined(__ppc__)
45 constexpr bool kStackGrowsDown = true;
46 #else
47 #error Need to define kStackGrowsDown
48 #endif
49 
50 // To measure the stack footprint of some code, we create a signal handler
51 // (for SIGUSR2 say) that exercises this code on an alternate stack. This
52 // alternate stack is initialized to some known pattern (0x55, 0x55, 0x55,
53 // ...). We then self-send this signal, and after the signal handler returns,
54 // look at the alternate stack buffer to see what portion has been touched.
55 //
56 // This trick gives us the the stack footprint of the signal handler.  But the
57 // signal handler, even before the code for it is exercised, consumes some
58 // stack already. We however only want the stack usage of the code inside the
59 // signal handler. To measure this accurately, we install two signal handlers:
60 // one that does nothing and just returns, and the user-provided signal
61 // handler. The difference between the stack consumption of these two signals
62 // handlers should give us the stack foorprint of interest.
63 
EmptySignalHandler(int)64 void EmptySignalHandler(int) {}
65 
66 // This is arbitrary value, and could be increase further, at the cost of
67 // memset()ting it all to known sentinel value.
68 constexpr int kAlternateStackSize = 64 << 10;  // 64KiB
69 
70 constexpr int kSafetyMargin = 32;
71 constexpr char kAlternateStackFillValue = 0x55;
72 
73 // These helper functions look at the alternate stack buffer, and figure
74 // out what portion of this buffer has been touched - this is the stack
75 // consumption of the signal handler running on this alternate stack.
76 // This function will return -1 if the alternate stack buffer has not been
77 // touched. It will abort the program if the buffer has overflowed or is about
78 // to overflow.
GetStackConsumption(const void * const altstack)79 int GetStackConsumption(const void* const altstack) {
80   const char* begin;
81   int increment;
82   if (kStackGrowsDown) {
83     begin = reinterpret_cast<const char*>(altstack);
84     increment = 1;
85   } else {
86     begin = reinterpret_cast<const char*>(altstack) + kAlternateStackSize - 1;
87     increment = -1;
88   }
89 
90   for (int usage_count = kAlternateStackSize; usage_count > 0; --usage_count) {
91     if (*begin != kAlternateStackFillValue) {
92       ABSL_RAW_CHECK(usage_count <= kAlternateStackSize - kSafetyMargin,
93                      "Buffer has overflowed or is about to overflow");
94       return usage_count;
95     }
96     begin += increment;
97   }
98 
99   ABSL_RAW_LOG(FATAL, "Unreachable code");
100   return -1;
101 }
102 
103 }  // namespace
104 
GetSignalHandlerStackConsumption(void (* signal_handler)(int))105 int GetSignalHandlerStackConsumption(void (*signal_handler)(int)) {
106   // The alt-signal-stack cannot be heap allocated because there is a
107   // bug in glibc-2.2 where some signal handler setup code looks at the
108   // current stack pointer to figure out what thread is currently running.
109   // Therefore, the alternate stack must be allocated from the main stack
110   // itself.
111   void* altstack = mmap(nullptr, kAlternateStackSize, PROT_READ | PROT_WRITE,
112                         MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
113   ABSL_RAW_CHECK(altstack != MAP_FAILED, "mmap() failed");
114 
115   // Set up the alt-signal-stack (and save the older one).
116   stack_t sigstk;
117   memset(&sigstk, 0, sizeof(sigstk));
118   stack_t old_sigstk;
119   sigstk.ss_sp = altstack;
120   sigstk.ss_size = kAlternateStackSize;
121   sigstk.ss_flags = 0;
122   ABSL_RAW_CHECK(sigaltstack(&sigstk, &old_sigstk) == 0,
123                  "sigaltstack() failed");
124 
125   // Set up SIGUSR1 and SIGUSR2 signal handlers (and save the older ones).
126   struct sigaction sa;
127   memset(&sa, 0, sizeof(sa));
128   struct sigaction old_sa1, old_sa2;
129   sigemptyset(&sa.sa_mask);
130   sa.sa_flags = SA_ONSTACK;
131 
132   // SIGUSR1 maps to EmptySignalHandler.
133   sa.sa_handler = EmptySignalHandler;
134   ABSL_RAW_CHECK(sigaction(SIGUSR1, &sa, &old_sa1) == 0, "sigaction() failed");
135 
136   // SIGUSR2 maps to signal_handler.
137   sa.sa_handler = signal_handler;
138   ABSL_RAW_CHECK(sigaction(SIGUSR2, &sa, &old_sa2) == 0, "sigaction() failed");
139 
140   // Send SIGUSR1 signal and measure the stack consumption of the empty
141   // signal handler.
142   // The first signal might use more stack space. Run once and ignore the
143   // results to get that out of the way.
144   ABSL_RAW_CHECK(kill(getpid(), SIGUSR1) == 0, "kill() failed");
145 
146   memset(altstack, kAlternateStackFillValue, kAlternateStackSize);
147   ABSL_RAW_CHECK(kill(getpid(), SIGUSR1) == 0, "kill() failed");
148   int base_stack_consumption = GetStackConsumption(altstack);
149 
150   // Send SIGUSR2 signal and measure the stack consumption of signal_handler.
151   ABSL_RAW_CHECK(kill(getpid(), SIGUSR2) == 0, "kill() failed");
152   int signal_handler_stack_consumption = GetStackConsumption(altstack);
153 
154   // Now restore the old alt-signal-stack and signal handlers.
155   ABSL_RAW_CHECK(sigaltstack(&old_sigstk, nullptr) == 0,
156                  "sigaltstack() failed");
157   ABSL_RAW_CHECK(sigaction(SIGUSR1, &old_sa1, nullptr) == 0,
158                  "sigaction() failed");
159   ABSL_RAW_CHECK(sigaction(SIGUSR2, &old_sa2, nullptr) == 0,
160                  "sigaction() failed");
161 
162   ABSL_RAW_CHECK(munmap(altstack, kAlternateStackSize) == 0, "munmap() failed");
163   if (signal_handler_stack_consumption != -1 && base_stack_consumption != -1) {
164     return signal_handler_stack_consumption - base_stack_consumption;
165   }
166   return -1;
167 }
168 
169 }  // namespace debugging_internal
170 }  // namespace absl
171 
172 #endif  // ABSL_INTERNAL_HAVE_DEBUGGING_STACK_CONSUMPTION
173