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