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()
48 #include "base/googleinit.h"
52 _START_GOOGLE_NAMESPACE_
54 static const char* g_program_invocation_short_name = NULL;
55 static pthread_t g_main_thread_id;
57 _END_GOOGLE_NAMESPACE_
59 // The following APIs are all internal.
60 #ifdef HAVE_STACKTRACE
62 #include "stacktrace.h"
63 #include "symbolize.h"
64 #include "base/commandlineflags.h"
66 DEFINE_bool(symbolize_stacktrace, true,
67 "Symbolize the stack trace in the tombstone");
69 _START_GOOGLE_NAMESPACE_
71 typedef void DebugWriter(const char*, void*);
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*);
77 static void DebugWriteToStderr(const char* data, void *unused) {
78 // This one is signal-safe.
79 write(STDERR_FILENO, data, strlen(data));
82 void DebugWriteToString(const char* data, void *arg) {
83 reinterpret_cast<string*>(arg)->append(data);
87 // Print a program counter and its symbol name.
88 static void DumpPCAndSymbol(DebugWriter *writerfn, void *arg, void *pc,
89 const char * const prefix) {
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))) {
99 snprintf(buf, sizeof(buf), "%s@ %*p %s\n",
100 prefix, kPrintfPointerFieldWidth, pc, symbol);
105 static void DumpPC(DebugWriter *writerfn, void *arg, void *pc,
106 const char * const prefix) {
108 snprintf(buf, sizeof(buf), "%s@ %*p\n",
109 prefix, kPrintfPointerFieldWidth, pc);
113 // Dump current stack trace as directed by writerfn
114 static void DumpStackTrace(int skip_count, DebugWriter *writerfn, void *arg) {
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], " ");
123 DumpPC(writerfn, arg, stack[i], " ");
126 DumpPC(writerfn, arg, stack[i], " ");
131 static void DumpStackTraceAndExit() {
132 DumpStackTrace(1, DebugWriteToStderr, NULL);
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);
145 _END_GOOGLE_NAMESPACE_
147 #endif // HAVE_STACKTRACE
149 _START_GOOGLE_NAMESPACE_
151 namespace glog_internal_namespace_ {
153 const char* ProgramInvocationShortName() {
154 if (g_program_invocation_short_name != NULL) {
155 return g_program_invocation_short_name;
157 // TODO(hamaji): Use /proc/self/cmdline and so?
162 bool IsGoogleLoggingInitialized() {
163 return g_program_invocation_short_name != NULL;
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
172 return pthread_equal(pthread_self(), g_main_thread_id);
178 long tv_sec, tv_usec;
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)
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;
200 int64 CycleClock_Now() {
201 // TODO(hamaji): temporary impementation - it might be too slow.
203 gettimeofday(&tv, NULL);
204 return static_cast<int64>(tv.tv_sec) * 1000000 + tv.tv_usec;
207 int64 UsecToCycles(int64 usec) {
211 WallTime WallTime_Now() {
212 // Now, cycle clock is retuning microseconds since the epoch.
213 return CycleClock_Now() * 0.000001;
216 static int32 g_main_thread_pid = getpid();
217 int32 GetMainThreadPid() {
218 return g_main_thread_pid;
222 // On Linux and FreeBSD, we try to use gettid().
223 #if defined OS_LINUX || defined OS_FREEBSD || defined OS_MACOSX
226 #define __NR_gettid SYS_gettid
227 #elif ! defined __i386__
228 #error "Must define __NR_gettid for non-x86 platforms"
230 #define __NR_gettid 224
233 static bool lacks_gettid = false;
235 pid_t tid = syscall(__NR_gettid);
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".
245 #endif // OS_LINUX || OS_FREEBSD
247 // If gettid() could not be used, we use one of the following.
249 return getpid(); // Linux: getpid returns thread ID when gettid is absent
250 #elif defined OS_WINDOWS || defined OS_CYGWIN
251 return GetCurrentThreadId();
253 // If none of the techniques above worked, we use pthread_self().
254 return (pid_t)pthread_self();
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
262 base = strrchr(filepath, '\\');
264 return base ? (base+1) : filepath;
267 static string g_my_user_name;
268 const string& MyUserName() {
269 return g_my_user_name;
271 static void MyUserNameInitializer() {
272 // TODO(hamaji): Probably this is not portable.
273 #if defined(OS_WINDOWS)
274 const char* user = getenv("USERNAME");
276 const char* user = getenv("USER");
279 g_my_user_name = user;
281 g_my_user_name = "invalid-user";
284 REGISTER_MODULE_INITIALIZER(utilities, MyUserNameInitializer());
286 #ifdef HAVE_STACKTRACE
287 void DumpStackTraceToString(string* stacktrace) {
288 DumpStackTrace(1, DebugWriteToString, stacktrace);
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;
296 void SetCrashReason(const CrashReason* r) {
297 sync_val_compare_and_swap(&g_reason,
298 reinterpret_cast<const CrashReason*>(0),
302 } // namespace glog_internal_namespace_
304 void InitGoogleLogging(const char* argv0) {
305 CHECK(!IsGoogleLoggingInitialized())
306 << "You called InitGoogleLogging() twice!";
307 const char* slash = strrchr(argv0, '/');
309 if (!slash) slash = strrchr(argv0, '\\');
311 g_program_invocation_short_name = slash ? slash + 1 : argv0;
312 g_main_thread_id = pthread_self();
314 #ifdef HAVE_STACKTRACE
315 InstallFailureFunction(&DumpStackTraceAndExit);
319 _END_GOOGLE_NAMESPACE_
321 // Make an implementation of stacktrace compiled.
323 # include STACKTRACE_H