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