Flush logs unsafely before program fails in the signal handler.
[platform/upstream/glog.git] / src / signalhandler_unittest.cc
1 // Copyright 2008 Google Inc. All Rights Reserved.
2 // Author: satorux@google.com (Satoru Takabayashi)
3 //
4 // This is a helper binary for testing signalhandler.cc.  The actual test
5 // is done in signalhandler_unittest.sh.
6
7 #include "utilities.h"
8
9 #include <pthread.h>
10 #include <signal.h>
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <string>
14 #include "glog/logging.h"
15
16 using namespace GOOGLE_NAMESPACE;
17
18 void* DieInThread(void*) {
19   fprintf(stderr, "0x%lx is dying\n", pthread_self());
20   // Use volatile to prevent from these to be optimized away.
21   volatile int a = 0;
22   volatile int b = 1 / a;
23 }
24
25 void WriteToStdout(const char* data, int size) {
26   write(STDOUT_FILENO, data, size);
27 }
28
29 int main(int argc, char **argv) {
30 #if defined(HAVE_STACKTRACE) && defined(HAVE_SYMBOLIZE)
31   InitGoogleLogging(argv[0]);
32   InstallFailureSignalHandler();
33   const std::string command = argc > 1 ? argv[1] : "none";
34   if (command == "segv") {
35     // We'll check if this is outputted.
36     LOG(INFO) << "create the log file";
37     LOG(INFO) << "a message before segv";
38     // We assume 0xDEAD is not writable.
39     int *a = (int*)0xDEAD;
40     *a = 0;
41   } else if (command == "loop") {
42     fprintf(stderr, "looping\n");
43     while (true);
44   } else if (command == "die_in_thread") {
45     pthread_t thread;
46     pthread_create(&thread, NULL, &DieInThread, NULL);
47     pthread_join(thread, NULL);
48   } else if (command == "dump_to_stdout") {
49     InstallFailureWriter(WriteToStdout);
50     abort();
51   } else {
52     // Tell the shell script
53     puts("OK");
54   }
55 #endif
56   return 0;
57 }