Symbolizer support for mingw and cygwin (#208)
[platform/upstream/glog.git] / src / symbolize_unittest.cc
1 // Copyright (c) 2006, Google Inc.
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
6 // met:
7 //
8 //     * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 //     * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
13 // distribution.
14 //     * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
17 //
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 //
30 // Author: Satoru Takabayashi
31 //
32 // Unit tests for functions in symbolize.cc.
33
34 #include "utilities.h"
35
36 #include <signal.h>
37 #include <iostream>
38
39 #include "glog/logging.h"
40 #include "symbolize.h"
41 #include "googletest.h"
42 #include "config.h"
43
44 #ifdef HAVE_LIB_GFLAGS
45 #include <gflags/gflags.h>
46 using namespace GFLAGS_NAMESPACE;
47 #endif
48
49 using namespace std;
50 using namespace GOOGLE_NAMESPACE;
51
52 #if defined(HAVE_STACKTRACE)
53
54 #define always_inline
55
56 // A wrapper function for Symbolize() to make the unit test simple.
57 static const char *TrySymbolize(void *pc) {
58   static char symbol[4096];
59   if (Symbolize(pc, symbol, sizeof(symbol))) {
60     return symbol;
61   } else {
62     return NULL;
63   }
64 }
65
66 # if defined(__ELF__)
67
68 // This unit tests make sense only with GCC.
69 // Uses lots of GCC specific features.
70 #if defined(__GNUC__) && !defined(__OPENCC__)
71 #  if __GNUC__ >= 4
72 #    define TEST_WITH_MODERN_GCC
73 #    if __i386__  // always_inline isn't supported for x86_64 with GCC 4.1.0.
74 #      undef always_inline
75 #      define always_inline __attribute__((always_inline))
76 #      define HAVE_ALWAYS_INLINE
77 #    endif  // __i386__
78 #  else
79 #  endif  // __GNUC__ >= 4
80 #  if defined(__i386__) || defined(__x86_64__)
81 #    define TEST_X86_32_AND_64 1
82 #  endif  // defined(__i386__) || defined(__x86_64__)
83 #endif
84
85 // Make them C linkage to avoid mangled names.
86 extern "C" {
87 void nonstatic_func() {
88   volatile int a = 0;
89   ++a;
90 }
91
92 static void static_func() {
93   volatile int a = 0;
94   ++a;
95 }
96 }
97
98 TEST(Symbolize, Symbolize) {
99   // We do C-style cast since GCC 2.95.3 doesn't allow
100   // reinterpret_cast<void *>(&func).
101
102   // Compilers should give us pointers to them.
103   EXPECT_STREQ("nonstatic_func", TrySymbolize((void *)(&nonstatic_func)));
104
105   // The name of an internal linkage symbol is not specified; allow either a
106   // mangled or an unmangled name here.
107   const char *static_func_symbol = TrySymbolize((void *)(&static_func));
108   CHECK(NULL != static_func_symbol);
109   EXPECT_TRUE(strcmp("static_func", static_func_symbol) == 0 ||
110               strcmp("static_func()", static_func_symbol) == 0);
111
112   EXPECT_TRUE(NULL == TrySymbolize(NULL));
113 }
114
115 struct Foo {
116   static void func(int x);
117 };
118
119 void ATTRIBUTE_NOINLINE Foo::func(int x) {
120   volatile int a = x;
121   ++a;
122 }
123
124 // With a modern GCC, Symbolize() should return demangled symbol
125 // names.  Function parameters should be omitted.
126 #ifdef TEST_WITH_MODERN_GCC
127 TEST(Symbolize, SymbolizeWithDemangling) {
128   Foo::func(100);
129   EXPECT_STREQ("Foo::func()", TrySymbolize((void *)(&Foo::func)));
130 }
131 #endif
132
133 // Tests that verify that Symbolize footprint is within some limit.
134
135 // To measure the stack footprint of the Symbolize function, we create
136 // a signal handler (for SIGUSR1 say) that calls the Symbolize function
137 // on an alternate stack. This alternate stack is initialized to some
138 // known pattern (0x55, 0x55, 0x55, ...). We then self-send this signal,
139 // and after the signal handler returns, look at the alternate stack
140 // buffer to see what portion has been touched.
141 //
142 // This trick gives us the the stack footprint of the signal handler.
143 // But the signal handler, even before the call to Symbolize, consumes
144 // some stack already. We however only want the stack usage of the
145 // Symbolize function. To measure this accurately, we install two signal
146 // handlers: one that does nothing and just returns, and another that
147 // calls Symbolize. The difference between the stack consumption of these
148 // two signals handlers should give us the Symbolize stack foorprint.
149
150 static void *g_pc_to_symbolize;
151 static char g_symbolize_buffer[4096];
152 static char *g_symbolize_result;
153
154 static void EmptySignalHandler(int signo) {}
155
156 static void SymbolizeSignalHandler(int signo) {
157   if (Symbolize(g_pc_to_symbolize, g_symbolize_buffer,
158                 sizeof(g_symbolize_buffer))) {
159     g_symbolize_result = g_symbolize_buffer;
160   } else {
161     g_symbolize_result = NULL;
162   }
163 }
164
165 const int kAlternateStackSize = 8096;
166 const char kAlternateStackFillValue = 0x55;
167
168 // These helper functions look at the alternate stack buffer, and figure
169 // out what portion of this buffer has been touched - this is the stack
170 // consumption of the signal handler running on this alternate stack.
171 static ATTRIBUTE_NOINLINE bool StackGrowsDown(int *x) {
172   int y;
173   return &y < x;
174 }
175 static int GetStackConsumption(const char* alt_stack) {
176   int x;
177   if (StackGrowsDown(&x)) {
178     for (int i = 0; i < kAlternateStackSize; i++) {
179       if (alt_stack[i] != kAlternateStackFillValue) {
180         return (kAlternateStackSize - i);
181       }
182     }
183   } else {
184     for (int i = (kAlternateStackSize - 1); i >= 0; i--) {
185       if (alt_stack[i] != kAlternateStackFillValue) {
186         return i;
187       }
188     }
189   }
190   return -1;
191 }
192
193 #ifdef HAVE_SIGALTSTACK
194
195 // Call Symbolize and figure out the stack footprint of this call.
196 static const char *SymbolizeStackConsumption(void *pc, int *stack_consumed) {
197
198   g_pc_to_symbolize = pc;
199
200   // The alt-signal-stack cannot be heap allocated because there is a
201   // bug in glibc-2.2 where some signal handler setup code looks at the
202   // current stack pointer to figure out what thread is currently running.
203   // Therefore, the alternate stack must be allocated from the main stack
204   // itself.
205   char altstack[kAlternateStackSize];
206   memset(altstack, kAlternateStackFillValue, kAlternateStackSize);
207
208   // Set up the alt-signal-stack (and save the older one).
209   stack_t sigstk;
210   memset(&sigstk, 0, sizeof(stack_t));
211   stack_t old_sigstk;
212   sigstk.ss_sp = altstack;
213   sigstk.ss_size = kAlternateStackSize;
214   sigstk.ss_flags = 0;
215   CHECK_ERR(sigaltstack(&sigstk, &old_sigstk));
216
217   // Set up SIGUSR1 and SIGUSR2 signal handlers (and save the older ones).
218   struct sigaction sa;
219   memset(&sa, 0, sizeof(struct sigaction));
220   struct sigaction old_sa1, old_sa2;
221   sigemptyset(&sa.sa_mask);
222   sa.sa_flags = SA_ONSTACK;
223
224   // SIGUSR1 maps to EmptySignalHandler.
225   sa.sa_handler = EmptySignalHandler;
226   CHECK_ERR(sigaction(SIGUSR1, &sa, &old_sa1));
227
228   // SIGUSR2 maps to SymbolizeSignalHanlder.
229   sa.sa_handler = SymbolizeSignalHandler;
230   CHECK_ERR(sigaction(SIGUSR2, &sa, &old_sa2));
231
232   // Send SIGUSR1 signal and measure the stack consumption of the empty
233   // signal handler.
234   CHECK_ERR(kill(getpid(), SIGUSR1));
235   int stack_consumption1 = GetStackConsumption(altstack);
236
237   // Send SIGUSR2 signal and measure the stack consumption of the symbolize
238   // signal handler.
239   CHECK_ERR(kill(getpid(), SIGUSR2));
240   int stack_consumption2 = GetStackConsumption(altstack);
241
242   // The difference between the two stack consumption values is the
243   // stack footprint of the Symbolize function.
244   if (stack_consumption1 != -1 && stack_consumption2 != -1) {
245     *stack_consumed = stack_consumption2 - stack_consumption1;
246   } else {
247     *stack_consumed = -1;
248   }
249
250   // Log the stack consumption values.
251   LOG(INFO) << "Stack consumption of empty signal handler: "
252             << stack_consumption1;
253   LOG(INFO) << "Stack consumption of symbolize signal handler: "
254             << stack_consumption2;
255   LOG(INFO) << "Stack consumption of Symbolize: " << *stack_consumed;
256
257   // Now restore the old alt-signal-stack and signal handlers.
258   CHECK_ERR(sigaltstack(&old_sigstk, NULL));
259   CHECK_ERR(sigaction(SIGUSR1, &old_sa1, NULL));
260   CHECK_ERR(sigaction(SIGUSR2, &old_sa2, NULL));
261
262   return g_symbolize_result;
263 }
264
265 #ifdef __ppc64__
266 // Symbolize stack consumption should be within 4kB.
267 const int kStackConsumptionUpperLimit = 4096;
268 #else
269 // Symbolize stack consumption should be within 2kB.
270 const int kStackConsumptionUpperLimit = 2048;
271 #endif
272
273 TEST(Symbolize, SymbolizeStackConsumption) {
274   int stack_consumed;
275   const char* symbol;
276
277   symbol = SymbolizeStackConsumption((void *)(&nonstatic_func),
278                                      &stack_consumed);
279   EXPECT_STREQ("nonstatic_func", symbol);
280   EXPECT_GT(stack_consumed, 0);
281   EXPECT_LT(stack_consumed, kStackConsumptionUpperLimit);
282
283   // The name of an internal linkage symbol is not specified; allow either a
284   // mangled or an unmangled name here.
285   symbol = SymbolizeStackConsumption((void *)(&static_func),
286                                      &stack_consumed);
287   CHECK(NULL != symbol);
288   EXPECT_TRUE(strcmp("static_func", symbol) == 0 ||
289               strcmp("static_func()", symbol) == 0);
290   EXPECT_GT(stack_consumed, 0);
291   EXPECT_LT(stack_consumed, kStackConsumptionUpperLimit);
292 }
293
294 #ifdef TEST_WITH_MODERN_GCC
295 TEST(Symbolize, SymbolizeWithDemanglingStackConsumption) {
296   Foo::func(100);
297   int stack_consumed;
298   const char* symbol;
299
300   symbol = SymbolizeStackConsumption((void *)(&Foo::func), &stack_consumed);
301
302   EXPECT_STREQ("Foo::func()", symbol);
303   EXPECT_GT(stack_consumed, 0);
304   EXPECT_LT(stack_consumed, kStackConsumptionUpperLimit);
305 }
306 #endif
307
308 #endif  // HAVE_SIGALTSTACK
309
310 // x86 specific tests.  Uses some inline assembler.
311 extern "C" {
312 inline void* always_inline inline_func() {
313   register void *pc = NULL;
314 #ifdef TEST_X86_32_AND_64
315   __asm__ __volatile__("call 1f; 1: pop %0" : "=r"(pc));
316 #endif
317   return pc;
318 }
319
320 void* ATTRIBUTE_NOINLINE non_inline_func() {
321   register void *pc = NULL;
322 #ifdef TEST_X86_32_AND_64
323   __asm__ __volatile__("call 1f; 1: pop %0" : "=r"(pc));
324 #endif
325   return pc;
326 }
327
328 void ATTRIBUTE_NOINLINE TestWithPCInsideNonInlineFunction() {
329 #if defined(TEST_X86_32_AND_64) && defined(HAVE_ATTRIBUTE_NOINLINE)
330   void *pc = non_inline_func();
331   const char *symbol = TrySymbolize(pc);
332   CHECK(symbol != NULL);
333   CHECK_STREQ(symbol, "non_inline_func");
334   cout << "Test case TestWithPCInsideNonInlineFunction passed." << endl;
335 #endif
336 }
337
338 void ATTRIBUTE_NOINLINE TestWithPCInsideInlineFunction() {
339 #if defined(TEST_X86_32_AND_64) && defined(HAVE_ALWAYS_INLINE)
340   void *pc = inline_func();  // Must be inlined.
341   const char *symbol = TrySymbolize(pc);
342   CHECK(symbol != NULL);
343   CHECK_STREQ(symbol, __FUNCTION__);
344   cout << "Test case TestWithPCInsideInlineFunction passed." << endl;
345 #endif
346 }
347 }
348
349 // Test with a return address.
350 void ATTRIBUTE_NOINLINE TestWithReturnAddress() {
351 #if defined(HAVE_ATTRIBUTE_NOINLINE)
352   void *return_address = __builtin_return_address(0);
353   const char *symbol = TrySymbolize(return_address);
354   CHECK(symbol != NULL);
355   CHECK_STREQ(symbol, "main");
356   cout << "Test case TestWithReturnAddress passed." << endl;
357 #endif
358 }
359
360 # elif defined(OS_WINDOWS) || defined(OS_CYGWIN)
361
362 #ifdef _MSC_VER
363 #include <intrin.h>
364 #pragma intrinsic(_ReturnAddress)
365 #endif
366
367 struct Foo {
368   static void func(int x);
369 };
370
371 __declspec(noinline) void Foo::func(int x) {
372   volatile int a = x;
373   ++a;
374 }
375
376 TEST(Symbolize, SymbolizeWithDemangling) {
377   Foo::func(100);
378   const char* ret = TrySymbolize((void *)(&Foo::func));
379   EXPECT_STREQ("public: static void __cdecl Foo::func(int)", ret);
380 }
381
382 __declspec(noinline) void TestWithReturnAddress() {
383   void *return_address =
384 #ifdef __GNUC__ // Cygwin and MinGW support
385           __builtin_return_address(0)
386 #else
387           _ReturnAddress()
388 #endif
389           ;
390   const char *symbol = TrySymbolize(return_address);
391   CHECK(symbol != NULL);
392   CHECK_STREQ(symbol, "main");
393   cout << "Test case TestWithReturnAddress passed." << endl;
394 }
395 # endif  // __ELF__
396 #endif  // HAVE_STACKTRACE
397
398 int main(int argc, char **argv) {
399   FLAGS_logtostderr = true;
400   InitGoogleLogging(argv[0]);
401   InitGoogleTest(&argc, argv);
402 #if defined(HAVE_SYMBOLIZE)
403 # if defined(__ELF__)
404   // We don't want to get affected by the callback interface, that may be
405   // used to install some callback function at InitGoogle() time.
406   InstallSymbolizeCallback(NULL);
407
408   TestWithPCInsideInlineFunction();
409   TestWithPCInsideNonInlineFunction();
410   TestWithReturnAddress();
411   return RUN_ALL_TESTS();
412 # elif defined(OS_WINDOWS) || defined(OS_CYGWIN)
413   TestWithReturnAddress();
414   return RUN_ALL_TESTS();
415 # else  // OS_WINDOWS
416   printf("PASS (no symbolize_unittest support)\n");
417   return 0;
418 # endif  // __ELF__
419 #else
420   printf("PASS (no symbolize support)\n");
421   return 0;
422 #endif  // HAVE_SYMBOLIZE
423 }