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 *) {
81 // This one is signal-safe.
82 if (write(STDERR_FILENO, data, strlen(data)) < 0) {
87 void DebugWriteToString(const char* data, void *arg) {
88 reinterpret_cast<string*>(arg)->append(data);
92 // Print a program counter and its symbol name.
93 static void DumpPCAndSymbol(DebugWriter *writerfn, void *arg, void *pc,
94 const char * const prefix) {
96 const char *symbol = "(unknown)";
97 // Symbolizes the previous address of pc because pc may be in the
98 // next function. The overrun happens when the function ends with
99 // a call to a function annotated noreturn (e.g. CHECK).
100 if (Symbolize(reinterpret_cast<char *>(pc) - 1, tmp, sizeof(tmp))) {
104 snprintf(buf, sizeof(buf), "%s@ %*p %s\n",
105 prefix, kPrintfPointerFieldWidth, pc, symbol);
110 static void DumpPC(DebugWriter *writerfn, void *arg, void *pc,
111 const char * const prefix) {
113 snprintf(buf, sizeof(buf), "%s@ %*p\n",
114 prefix, kPrintfPointerFieldWidth, pc);
118 // Dump current stack trace as directed by writerfn
119 static void DumpStackTrace(int skip_count, DebugWriter *writerfn, void *arg) {
122 int depth = GetStackTrace(stack, ARRAYSIZE(stack), skip_count+1);
123 for (int i = 0; i < depth; i++) {
124 #if defined(HAVE_SYMBOLIZE)
125 if (FLAGS_symbolize_stacktrace) {
126 DumpPCAndSymbol(writerfn, arg, stack[i], " ");
128 DumpPC(writerfn, arg, stack[i], " ");
131 DumpPC(writerfn, arg, stack[i], " ");
136 static void DumpStackTraceAndExit() {
137 DumpStackTrace(1, DebugWriteToStderr, NULL);
139 // TOOD(hamaji): Use signal instead of sigaction?
140 #ifdef HAVE_SIGACTION
141 if (IsFailureSignalHandlerInstalled()) {
142 // Set the default signal handler for SIGABRT, to avoid invoking our
143 // own signal handler installed by InstallFailureSignalHandler().
144 struct sigaction sig_action;
145 memset(&sig_action, 0, sizeof(sig_action));
146 sigemptyset(&sig_action.sa_mask);
147 sig_action.sa_handler = SIG_DFL;
148 sigaction(SIGABRT, &sig_action, NULL);
150 #endif // HAVE_SIGACTION
155 _END_GOOGLE_NAMESPACE_
157 #endif // HAVE_STACKTRACE
159 _START_GOOGLE_NAMESPACE_
161 namespace glog_internal_namespace_ {
163 const char* ProgramInvocationShortName() {
164 if (g_program_invocation_short_name != NULL) {
165 return g_program_invocation_short_name;
167 // TODO(hamaji): Use /proc/self/cmdline and so?
172 bool IsGoogleLoggingInitialized() {
173 return g_program_invocation_short_name != NULL;
176 bool is_default_thread() {
177 if (g_program_invocation_short_name == NULL) {
178 // InitGoogleLogging() not yet called, so unlikely to be in a different
182 return pthread_equal(pthread_self(), g_main_thread_id);
188 long tv_sec, tv_usec;
191 // Based on: http://www.google.com/codesearch/p?hl=en#dR3YEbitojA/os_win32.c&q=GetSystemTimeAsFileTime%20license:bsd
192 // See COPYING for copyright information.
193 static int gettimeofday(struct timeval *tv, void* tz) {
194 #define EPOCHFILETIME (116444736000000000ULL)
199 GetSystemTimeAsFileTime(&ft);
200 li.LowPart = ft.dwLowDateTime;
201 li.HighPart = ft.dwHighDateTime;
202 tt = (li.QuadPart - EPOCHFILETIME) / 10;
203 tv->tv_sec = tt / 1000000;
204 tv->tv_usec = tt % 1000000;
210 int64 CycleClock_Now() {
211 // TODO(hamaji): temporary impementation - it might be too slow.
213 gettimeofday(&tv, NULL);
214 return static_cast<int64>(tv.tv_sec) * 1000000 + tv.tv_usec;
217 int64 UsecToCycles(int64 usec) {
221 WallTime WallTime_Now() {
222 // Now, cycle clock is retuning microseconds since the epoch.
223 return CycleClock_Now() * 0.000001;
226 static int32 g_main_thread_pid = getpid();
227 int32 GetMainThreadPid() {
228 return g_main_thread_pid;
231 bool PidHasChanged() {
232 int32 pid = getpid();
233 if (g_main_thread_pid == pid) {
236 g_main_thread_pid = pid;
241 // On Linux and MacOSX, we try to use gettid().
242 #if defined OS_LINUX || defined OS_MACOSX
245 #define __NR_gettid SYS_gettid
246 #elif ! defined __i386__
247 #error "Must define __NR_gettid for non-x86 platforms"
249 #define __NR_gettid 224
252 static bool lacks_gettid = false;
254 pid_t tid = syscall(__NR_gettid);
258 // Technically, this variable has to be volatile, but there is a small
259 // performance penalty in accessing volatile variables and there should
260 // not be any serious adverse effect if a thread does not immediately see
261 // the value change to "true".
264 #endif // OS_LINUX || OS_MACOSX
266 // If gettid() could not be used, we use one of the following.
268 return getpid(); // Linux: getpid returns thread ID when gettid is absent
269 #elif defined OS_WINDOWS || defined OS_CYGWIN
270 return GetCurrentThreadId();
272 // If none of the techniques above worked, we use pthread_self().
273 return (pid_t)(uintptr_t)pthread_self();
277 const char* const_basename(const char* filepath) {
278 const char* base = strrchr(filepath, '/');
279 #ifdef OS_WINDOWS // Look for either path separator in Windows
281 base = strrchr(filepath, '\\');
283 return base ? (base+1) : filepath;
286 static string g_my_user_name;
287 const string& MyUserName() {
288 return g_my_user_name;
290 static void MyUserNameInitializer() {
291 // TODO(hamaji): Probably this is not portable.
292 #if defined(OS_WINDOWS)
293 const char* user = getenv("USERNAME");
295 const char* user = getenv("USER");
298 g_my_user_name = user;
300 g_my_user_name = "invalid-user";
303 REGISTER_MODULE_INITIALIZER(utilities, MyUserNameInitializer());
305 #ifdef HAVE_STACKTRACE
306 void DumpStackTraceToString(string* stacktrace) {
307 DumpStackTrace(1, DebugWriteToString, stacktrace);
311 // We use an atomic operation to prevent problems with calling CrashReason
312 // from inside the Mutex implementation (potentially through RAW_CHECK).
313 static const CrashReason* g_reason = 0;
315 void SetCrashReason(const CrashReason* r) {
316 sync_val_compare_and_swap(&g_reason,
317 reinterpret_cast<const CrashReason*>(0),
321 void InitGoogleLoggingUtilities(const char* argv0) {
322 CHECK(!IsGoogleLoggingInitialized())
323 << "You called InitGoogleLogging() twice!";
324 const char* slash = strrchr(argv0, '/');
326 if (!slash) slash = strrchr(argv0, '\\');
328 g_program_invocation_short_name = slash ? slash + 1 : argv0;
329 g_main_thread_id = pthread_self();
331 #ifdef HAVE_STACKTRACE
332 InstallFailureFunction(&DumpStackTraceAndExit);
336 void ShutdownGoogleLoggingUtilities() {
337 CHECK(IsGoogleLoggingInitialized())
338 << "You called ShutdownGoogleLogging() without calling InitGoogleLogging() first!";
339 g_program_invocation_short_name = NULL;
345 } // namespace glog_internal_namespace_
347 _END_GOOGLE_NAMESPACE_
349 // Make an implementation of stacktrace compiled.
351 # include STACKTRACE_H