1 // Copyright (c) 2008, Google Inc.
2 // All rights reserved.
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
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
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.
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.
30 // Author: Shinichiro Hamaji
32 #include "utilities.h"
38 #ifdef HAVE_SYS_TIME_H
39 # include <sys/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()
51 #include "base/googleinit.h"
55 _START_GOOGLE_NAMESPACE_
57 static const char* g_program_invocation_short_name = NULL;
58 static pthread_t g_main_thread_id;
60 _END_GOOGLE_NAMESPACE_
62 // The following APIs are all internal.
63 #ifdef HAVE_STACKTRACE
65 #include "stacktrace.h"
66 #include "symbolize.h"
67 #include "base/commandlineflags.h"
69 GLOG_DEFINE_bool(symbolize_stacktrace, true,
70 "Symbolize the stack trace in the tombstone");
72 _START_GOOGLE_NAMESPACE_
74 typedef void DebugWriter(const char*, void*);
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*);
80 static void DebugWriteToStderr(const char* data, void *unused) {
81 // This one is signal-safe.
82 write(STDERR_FILENO, data, strlen(data));
85 void DebugWriteToString(const char* data, void *arg) {
86 reinterpret_cast<string*>(arg)->append(data);
90 // Print a program counter and its symbol name.
91 static void DumpPCAndSymbol(DebugWriter *writerfn, void *arg, void *pc,
92 const char * const prefix) {
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))) {
102 snprintf(buf, sizeof(buf), "%s@ %*p %s\n",
103 prefix, kPrintfPointerFieldWidth, pc, symbol);
108 static void DumpPC(DebugWriter *writerfn, void *arg, void *pc,
109 const char * const prefix) {
111 snprintf(buf, sizeof(buf), "%s@ %*p\n",
112 prefix, kPrintfPointerFieldWidth, pc);
116 // Dump current stack trace as directed by writerfn
117 static void DumpStackTrace(int skip_count, DebugWriter *writerfn, void *arg) {
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], " ");
126 DumpPC(writerfn, arg, stack[i], " ");
129 DumpPC(writerfn, arg, stack[i], " ");
134 static void DumpStackTraceAndExit() {
135 DumpStackTrace(1, DebugWriteToStderr, NULL);
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);
148 _END_GOOGLE_NAMESPACE_
150 #endif // HAVE_STACKTRACE
152 _START_GOOGLE_NAMESPACE_
154 namespace glog_internal_namespace_ {
156 const char* ProgramInvocationShortName() {
157 if (g_program_invocation_short_name != NULL) {
158 return g_program_invocation_short_name;
160 // TODO(hamaji): Use /proc/self/cmdline and so?
165 bool IsGoogleLoggingInitialized() {
166 return g_program_invocation_short_name != NULL;
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
175 return pthread_equal(pthread_self(), g_main_thread_id);
181 long tv_sec, tv_usec;
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)
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;
203 int64 CycleClock_Now() {
204 // TODO(hamaji): temporary impementation - it might be too slow.
206 gettimeofday(&tv, NULL);
207 return static_cast<int64>(tv.tv_sec) * 1000000 + tv.tv_usec;
210 int64 UsecToCycles(int64 usec) {
214 WallTime WallTime_Now() {
215 // Now, cycle clock is retuning microseconds since the epoch.
216 return CycleClock_Now() * 0.000001;
219 static int32 g_main_thread_pid = getpid();
220 int32 GetMainThreadPid() {
221 return g_main_thread_pid;
225 // On Linux and FreeBSD, we try to use gettid().
226 #if defined OS_LINUX || defined OS_FREEBSD || defined OS_MACOSX
229 #define __NR_gettid SYS_gettid
230 #elif ! defined __i386__
231 #error "Must define __NR_gettid for non-x86 platforms"
233 #define __NR_gettid 224
236 static bool lacks_gettid = false;
238 pid_t tid = syscall(__NR_gettid);
242 // Technically, this variable has to be volatile, but there is a small
243 // performance penalty in accessing volatile variables and there should
244 // not be any serious adverse effect if a thread does not immediately see
245 // the value change to "true".
248 #endif // OS_LINUX || OS_FREEBSD
250 // If gettid() could not be used, we use one of the following.
252 return getpid(); // Linux: getpid returns thread ID when gettid is absent
253 #elif defined OS_WINDOWS || defined OS_CYGWIN
254 return GetCurrentThreadId();
256 // If none of the techniques above worked, we use pthread_self().
257 return (pid_t)(uintptr_t)pthread_self();
261 const char* const_basename(const char* filepath) {
262 const char* base = strrchr(filepath, '/');
263 #ifdef OS_WINDOWS // Look for either path separator in Windows
265 base = strrchr(filepath, '\\');
267 return base ? (base+1) : filepath;
270 static string g_my_user_name;
271 const string& MyUserName() {
272 return g_my_user_name;
274 static void MyUserNameInitializer() {
275 // TODO(hamaji): Probably this is not portable.
276 #if defined(OS_WINDOWS)
277 const char* user = getenv("USERNAME");
279 const char* user = getenv("USER");
282 g_my_user_name = user;
284 g_my_user_name = "invalid-user";
287 REGISTER_MODULE_INITIALIZER(utilities, MyUserNameInitializer());
289 #ifdef HAVE_STACKTRACE
290 void DumpStackTraceToString(string* stacktrace) {
291 DumpStackTrace(1, DebugWriteToString, stacktrace);
295 // We use an atomic operation to prevent problems with calling CrashReason
296 // from inside the Mutex implementation (potentially through RAW_CHECK).
297 static const CrashReason* g_reason = 0;
299 void SetCrashReason(const CrashReason* r) {
300 sync_val_compare_and_swap(&g_reason,
301 reinterpret_cast<const CrashReason*>(0),
305 } // namespace glog_internal_namespace_
307 void InitGoogleLogging(const char* argv0) {
308 CHECK(!IsGoogleLoggingInitialized())
309 << "You called InitGoogleLogging() twice!";
310 const char* slash = strrchr(argv0, '/');
312 if (!slash) slash = strrchr(argv0, '\\');
314 g_program_invocation_short_name = slash ? slash + 1 : argv0;
315 g_main_thread_id = pthread_self();
317 #ifdef HAVE_STACKTRACE
318 InstallFailureFunction(&DumpStackTraceAndExit);
322 void ShutdownGoogleLogging() {
323 CHECK(IsGoogleLoggingInitialized())
324 << "You called ShutdownGoogleLogging() without InitGoogleLogging() first!";
330 _END_GOOGLE_NAMESPACE_
332 // Make an implementation of stacktrace compiled.
334 # include STACKTRACE_H