Define DumpPCAndSymbol() only when HAVE_SYMBOLIZE is defined.
[platform/upstream/glog.git] / src / utilities.cc
1 // Copyright (c) 2008, 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: Shinichiro Hamaji
31
32 #include "utilities.h"
33
34 #include <stdio.h>
35 #include <stdlib.h>
36
37 #include <signal.h>
38 #ifdef HAVE_SYS_TIME_H
39 # include <sys/time.h>
40 #endif
41 #include <time.h>
42 #if defined(HAVE_SYSCALL_H)
43 #include <syscall.h>                 // for syscall()
44 #elif defined(HAVE_SYS_SYSCALL_H)
45 #include <sys/syscall.h>                 // for syscall()
46 #endif
47
48 #include "base/googleinit.h"
49
50 using std::string;
51
52 _START_GOOGLE_NAMESPACE_
53
54 static const char* g_program_invocation_short_name = NULL;
55 static pthread_t g_main_thread_id;
56
57 _END_GOOGLE_NAMESPACE_
58
59 // The following APIs are all internal.
60 #ifdef HAVE_STACKTRACE
61
62 #include "stacktrace.h"
63 #include "symbolize.h"
64 #include "base/commandlineflags.h"
65
66 DEFINE_bool(symbolize_stacktrace, true,
67             "Symbolize the stack trace in the tombstone");
68
69 _START_GOOGLE_NAMESPACE_
70
71 typedef void DebugWriter(const char*, void*);
72
73 // The %p field width for printf() functions is two characters per byte.
74 // For some environments, add two extra bytes for the leading "0x".
75 static const int kPrintfPointerFieldWidth = 2 + 2 * sizeof(void*);
76
77 static void DebugWriteToStderr(const char* data, void *unused) {
78   // This one is signal-safe.
79   write(STDERR_FILENO, data, strlen(data));
80 }
81
82 void DebugWriteToString(const char* data, void *arg) {
83   reinterpret_cast<string*>(arg)->append(data);
84 }
85
86 #ifdef HAVE_SYMBOLIZE
87 // Print a program counter and its symbol name.
88 static void DumpPCAndSymbol(DebugWriter *writerfn, void *arg, void *pc,
89                             const char * const prefix) {
90   char tmp[1024];
91   const char *symbol = "(unknown)";
92   // Symbolizes the previous address of pc because pc may be in the
93   // next function.  The overrun happens when the function ends with
94   // a call to a function annotated noreturn (e.g. CHECK).
95   if (Symbolize(reinterpret_cast<char *>(pc) - 1, tmp, sizeof(tmp))) {
96       symbol = tmp;
97   }
98   char buf[1024];
99   snprintf(buf, sizeof(buf), "%s@ %*p  %s\n",
100            prefix, kPrintfPointerFieldWidth, pc, symbol);
101   writerfn(buf, arg);
102 }
103 #endif
104
105 static void DumpPC(DebugWriter *writerfn, void *arg, void *pc,
106                    const char * const prefix) {
107   char buf[100];
108   snprintf(buf, sizeof(buf), "%s@ %*p\n",
109            prefix, kPrintfPointerFieldWidth, pc);
110   writerfn(buf, arg);
111 }
112
113 // Dump current stack trace as directed by writerfn
114 static void DumpStackTrace(int skip_count, DebugWriter *writerfn, void *arg) {
115   // Print stack trace
116   void* stack[32];
117   int depth = GetStackTrace(stack, ARRAYSIZE(stack), skip_count+1);
118   for (int i = 0; i < depth; i++) {
119 #if defined(HAVE_SYMBOLIZE)
120     if (FLAGS_symbolize_stacktrace) {
121       DumpPCAndSymbol(writerfn, arg, stack[i], "    ");
122     } else {
123       DumpPC(writerfn, arg, stack[i], "    ");
124     }
125 #else
126     DumpPC(writerfn, arg, stack[i], "    ");
127 #endif
128   }
129 }
130
131 static void DumpStackTraceAndExit() {
132   DumpStackTrace(1, DebugWriteToStderr, NULL);
133
134   // Set the default signal handler for SIGABRT, to avoid invoking our
135   // own signal handler installed by InstallFailedSignalHandler().
136   struct sigaction sig_action;
137   memset(&sig_action, 0, sizeof(sig_action));
138   sigemptyset(&sig_action.sa_mask);
139   sig_action.sa_handler = SIG_DFL;
140   sigaction(SIGABRT, &sig_action, NULL);
141
142   abort();
143 }
144
145 _END_GOOGLE_NAMESPACE_
146
147 #endif  // HAVE_STACKTRACE
148
149 _START_GOOGLE_NAMESPACE_
150
151 namespace glog_internal_namespace_ {
152
153 const char* ProgramInvocationShortName() {
154   if (g_program_invocation_short_name != NULL) {
155     return g_program_invocation_short_name;
156   } else {
157     // TODO(hamaji): Use /proc/self/cmdline and so?
158     return "UNKNOWN";
159   }
160 }
161
162 bool IsGoogleLoggingInitialized() {
163   return g_program_invocation_short_name != NULL;
164 }
165
166 bool is_default_thread() {
167   if (g_program_invocation_short_name == NULL) {
168     // InitGoogleLogging() not yet called, so unlikely to be in a different
169     // thread
170     return true;
171   } else {
172     return pthread_equal(pthread_self(), g_main_thread_id);
173   }
174 }
175
176 #ifdef OS_WINDOWS
177 struct timeval {
178   long tv_sec, tv_usec;
179 };
180
181 // Based on: http://www.google.com/codesearch/p?hl=en#dR3YEbitojA/os_win32.c&q=GetSystemTimeAsFileTime%20license:bsd
182 // See COPYING for copyright information.
183 static int gettimeofday(struct timeval *tv, void* tz) {
184 #define EPOCHFILETIME (116444736000000000ULL)
185   FILETIME ft;
186   LARGE_INTEGER li;
187   uint64 tt;
188
189   GetSystemTimeAsFileTime(&ft);
190   li.LowPart = ft.dwLowDateTime;
191   li.HighPart = ft.dwHighDateTime;
192   tt = (li.QuadPart - EPOCHFILETIME) / 10;
193   tv->tv_sec = tt / 1000000;
194   tv->tv_usec = tt % 1000000;
195
196   return 0;
197 }
198 #endif
199
200 int64 CycleClock_Now() {
201   // TODO(hamaji): temporary impementation - it might be too slow.
202   struct timeval tv;
203   gettimeofday(&tv, NULL);
204   return static_cast<int64>(tv.tv_sec) * 1000000 + tv.tv_usec;
205 }
206
207 int64 UsecToCycles(int64 usec) {
208   return usec;
209 }
210
211 WallTime WallTime_Now() {
212   // Now, cycle clock is retuning microseconds since the epoch.
213   return CycleClock_Now() * 0.000001;
214 }
215
216 static int32 g_main_thread_pid = getpid();
217 int32 GetMainThreadPid() {
218   return g_main_thread_pid;
219 }
220
221 pid_t GetTID() {
222   // On Linux and FreeBSD, we try to use gettid().
223 #if defined OS_LINUX || defined OS_FREEBSD || defined OS_MACOSX
224 #ifndef __NR_gettid
225 #ifdef OS_MACOSX
226 #define __NR_gettid SYS_gettid
227 #elif ! defined __i386__
228 #error "Must define __NR_gettid for non-x86 platforms"
229 #else
230 #define __NR_gettid 224
231 #endif
232 #endif
233   static bool lacks_gettid = false;
234   if (!lacks_gettid) {
235     pid_t tid = syscall(__NR_gettid);
236     if (tid != -1) {
237       return tid;
238     }
239     // Technically, this variable has to be volatile, but there is a small
240     // performance penalty in accessing volatile variables and there should
241     // not be any serious adverse effect if a thread does not immediately see
242     // the value change to "true".
243     lacks_gettid = true;
244   }
245 #endif  // OS_LINUX || OS_FREEBSD
246
247   // If gettid() could not be used, we use one of the following.
248 #if defined OS_LINUX
249   return getpid();  // Linux:  getpid returns thread ID when gettid is absent
250 #elif defined OS_WINDOWS || defined OS_CYGWIN
251   return GetCurrentThreadId();
252 #else
253   // If none of the techniques above worked, we use pthread_self().
254   return (pid_t)pthread_self();
255 #endif
256 }
257
258 const char* const_basename(const char* filepath) {
259   const char* base = strrchr(filepath, '/');
260 #ifdef OS_WINDOWS  // Look for either path separator in Windows
261   if (!base)
262     base = strrchr(filepath, '\\');
263 #endif
264   return base ? (base+1) : filepath;
265 }
266
267 static string g_my_user_name;
268 const string& MyUserName() {
269   return g_my_user_name;
270 }
271 static void MyUserNameInitializer() {
272   // TODO(hamaji): Probably this is not portable.
273 #if defined(OS_WINDOWS)
274   const char* user = getenv("USERNAME");
275 #else
276   const char* user = getenv("USER");
277 #endif
278   if (user != NULL) {
279     g_my_user_name = user;
280   } else {
281     g_my_user_name = "invalid-user";
282   }
283 }
284 REGISTER_MODULE_INITIALIZER(utilities, MyUserNameInitializer());
285
286 #ifdef HAVE_STACKTRACE
287 void DumpStackTraceToString(string* stacktrace) {
288   DumpStackTrace(1, DebugWriteToString, stacktrace);
289 }
290 #endif
291
292 // We use an atomic operation to prevent problems with calling CrashReason
293 // from inside the Mutex implementation (potentially through RAW_CHECK).
294 static const CrashReason* g_reason = 0;
295
296 void SetCrashReason(const CrashReason* r) {
297   sync_val_compare_and_swap(&g_reason,
298                             reinterpret_cast<const CrashReason*>(0),
299                             r);
300 }
301
302 }  // namespace glog_internal_namespace_
303
304 void InitGoogleLogging(const char* argv0) {
305   CHECK(!IsGoogleLoggingInitialized())
306       << "You called InitGoogleLogging() twice!";
307   const char* slash = strrchr(argv0, '/');
308 #ifdef OS_WINDOWS
309   if (!slash)  slash = strrchr(argv0, '\\');
310 #endif
311   g_program_invocation_short_name = slash ? slash + 1 : argv0;
312   g_main_thread_id = pthread_self();
313
314 #ifdef HAVE_STACKTRACE
315   InstallFailureFunction(&DumpStackTraceAndExit);
316 #endif
317 }
318
319 _END_GOOGLE_NAMESPACE_
320
321 // Make an implementation of stacktrace compiled.
322 #ifdef STACKTRACE_H
323 # include STACKTRACE_H
324 #endif