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"
35 #ifdef HAVE_SYS_TIME_H
36 # include <sys/time.h>
39 #if defined(HAVE_SYSCALL_H)
40 #include <syscall.h> // for syscall()
41 #elif defined(HAVE_SYS_SYSCALL_H)
42 #include <sys/syscall.h> // for syscall()
45 #include "base/googleinit.h"
49 _START_GOOGLE_NAMESPACE_
51 static const char* g_program_invocation_short_name = NULL;
52 static pthread_t g_main_thread_id;
54 _END_GOOGLE_NAMESPACE_
56 // The following APIs are all internal.
57 #ifdef HAVE_STACKTRACE
59 #include "stacktrace.h"
60 #include "symbolize.h"
61 #include "base/commandlineflags.h"
63 DEFINE_bool(symbolize_stacktrace, true,
64 "Symbolize the stack trace in the tombstone");
66 _START_GOOGLE_NAMESPACE_
68 typedef void DebugWriter(const char*, void*);
70 // The %p field width for printf() functions is two characters per byte.
71 // For some environments, add two extra bytes for the leading "0x".
72 static const int kPrintfPointerFieldWidth = 2 + 2 * sizeof(void*);
74 static void DebugWriteToStderr(const char* data, void *unused) {
75 // This one is signal-safe.
76 write(STDERR_FILENO, data, strlen(data));
79 void DebugWriteToString(const char* data, void *arg) {
80 reinterpret_cast<string*>(arg)->append(data);
83 // Print a program counter and its symbol name.
84 static void DumpPCAndSymbol(DebugWriter *writerfn, void *arg, void *pc,
85 const char * const prefix) {
87 const char *symbol = "(unknown)";
88 // Symbolizes the previous address of pc because pc may be in the
89 // next function. The overrun happens when the function ends with
90 // a call to a function annotated noreturn (e.g. CHECK).
91 if (Symbolize(reinterpret_cast<char *>(pc) - 1, tmp, sizeof(tmp))) {
95 snprintf(buf, sizeof(buf), "%s@ %*p %s\n",
96 prefix, kPrintfPointerFieldWidth, pc, symbol);
100 // Print a program counter and the corresponding stack frame size.
101 static void DumpPCAndFrameSize(DebugWriter *writerfn, void *arg, void *pc,
102 int framesize, const char * const prefix) {
104 if (framesize <= 0) {
105 snprintf(buf, sizeof(buf), "%s@ %*p (unknown)\n",
106 prefix, kPrintfPointerFieldWidth, pc);
108 snprintf(buf, sizeof(buf), "%s@ %*p %9d\n",
109 prefix, kPrintfPointerFieldWidth, pc, framesize);
114 static void DumpPC(DebugWriter *writerfn, void *arg, void *pc,
115 const char * const prefix) {
117 snprintf(buf, sizeof(buf), "%s@ %*p\n",
118 prefix, kPrintfPointerFieldWidth, pc);
122 // Dump current stack trace as directed by writerfn
123 static void DumpStackTrace(int skip_count, DebugWriter *writerfn, void *arg) {
126 int depth = GetStackTrace(stack, ARRAYSIZE(stack), skip_count+1);
127 for (int i = 0; i < depth; i++) {
128 #if defined(HAVE_SYMBOLIZE)
129 if (FLAGS_symbolize_stacktrace) {
130 DumpPCAndSymbol(writerfn, arg, stack[i], " ");
132 DumpPC(writerfn, arg, stack[i], " ");
135 DumpPC(writerfn, arg, stack[i], " ");
140 static void DumpStackTraceAndExit() {
141 DumpStackTrace(1, DebugWriteToStderr, NULL);
143 // Set the default signal handler for SIGABRT, to avoid invoking our
144 // own signal handler installed by InstallFailedSignalHandler().
145 struct sigaction sig_action = {}; // Zero-clear.
146 sigemptyset(&sig_action.sa_mask);
147 sig_action.sa_handler = SIG_DFL;
148 sigaction(SIGABRT, &sig_action, NULL);
153 _END_GOOGLE_NAMESPACE_
155 #endif // HAVE_STACKTRACE
157 _START_GOOGLE_NAMESPACE_
159 namespace glog_internal_namespace_ {
161 const char* ProgramInvocationShortName() {
162 if (g_program_invocation_short_name != NULL) {
163 return g_program_invocation_short_name;
165 // TODO(hamaji): Use /proc/self/cmdline and so?
170 bool IsGoogleLoggingInitialized() {
171 return g_program_invocation_short_name != NULL;
174 bool is_default_thread() {
175 if (g_program_invocation_short_name == NULL) {
176 // InitGoogleLogging() not yet called, so unlikely to be in a different
180 return pthread_equal(pthread_self(), g_main_thread_id);
184 int64 CycleClock_Now() {
185 // TODO(hamaji): temporary impementation - it might be too slow.
189 return (static_cast<int64>(now.wSecond) * 1000000 +
190 static_cast<int64>(now.wMilliseconds) * 1000);
193 gettimeofday(&tv, NULL);
194 return static_cast<int64>(tv.tv_sec) * 1000000 + tv.tv_usec;
198 int64 UsecToCycles(int64 usec) {
202 WallTime WallTime_Now() {
203 // Now, cycle clock is retuning microseconds since the epoch.
204 return CycleClock_Now() * 0.000001;
207 static int32 g_main_thread_pid = getpid();
208 int32 GetMainThreadPid() {
209 return g_main_thread_pid;
213 // On Linux and FreeBSD, we try to use gettid().
214 #if defined OS_LINUX || defined OS_FREEBSD || defined OS_MACOSX
217 #define __NR_gettid SYS_gettid
218 #elif ! defined __i386__
219 #error "Must define __NR_gettid for non-x86 platforms"
221 #define __NR_gettid 224
224 static bool lacks_gettid = false;
226 pid_t tid = syscall(__NR_gettid);
230 // Technically, this variable has to be volatile, but there is a small
231 // performance penalty in accessing volatile variables and there should
232 // not be any serious adverse effect if a thread does not immediately see
233 // the value change to "true".
236 #endif // OS_LINUX || OS_FREEBSD
238 // If gettid() could not be used, we use one of the following.
240 return getpid(); // Linux: getpid returns thread ID when gettid is absent
241 #elif defined OS_WINDOWS || defined OS_CYGWIN
242 return GetCurrentThreadId();
244 // If none of the techniques above worked, we use pthread_self().
245 return (pid_t)pthread_self();
249 const char* const_basename(const char* filepath) {
250 const char* base = strrchr(filepath, '/');
251 #ifdef OS_WINDOWS // Look for either path separator in Windows
253 base = strrchr(filepath, '\\');
255 return base ? (base+1) : filepath;
258 static string g_my_user_name;
259 const string& MyUserName() {
260 return g_my_user_name;
262 static void MyUserNameInitializer() {
263 // TODO(hamaji): Probably this is not portable.
264 const char* user = getenv("USER");
266 g_my_user_name = user;
268 g_my_user_name = "invalid-user";
271 REGISTER_MODULE_INITIALIZER(utilities, MyUserNameInitializer());
273 #ifdef HAVE_STACKTRACE
274 void DumpStackTraceToString(string* stacktrace) {
275 DumpStackTrace(1, DebugWriteToString, stacktrace);
279 // We use an atomic operation to prevent problems with calling CrashReason
280 // from inside the Mutex implementation (potentially through RAW_CHECK).
281 static const CrashReason* g_reason = 0;
283 void SetCrashReason(const CrashReason* r) {
284 sync_val_compare_and_swap(&g_reason,
285 reinterpret_cast<const CrashReason*>(0),
289 } // namespace glog_internal_namespace_
291 void InitGoogleLogging(const char* argv0) {
292 const char* slash = strrchr(argv0, '/');
294 if (!slash) slash = strrchr(argv0, '\\');
296 g_program_invocation_short_name = slash ? slash + 1 : argv0;
297 g_main_thread_id = pthread_self();
299 #ifdef HAVE_STACKTRACE
300 InstallFailureFunction(&DumpStackTraceAndExit);
304 _END_GOOGLE_NAMESPACE_
306 // Make an implementation of stacktrace compiled.
308 # include STACKTRACE_H