* Add LOG_TO_STRING.
[platform/upstream/glog.git] / src / raw_logging.cc
1 // Copyright 2006 Google Inc. All Rights Reserved.
2 // Author: Maxim Lifantsev
3 //
4 // logging_unittest.cc covers the functionality herein
5
6 #include "utilities.h"
7
8 #include <stdarg.h>
9 #include <stdio.h>
10 #include <errno.h>
11 #ifdef HAVE_UNISTD_H
12 # include <unistd.h>               // for close() and write()
13 #endif
14 #include <fcntl.h>                 // for open()
15 #include <time.h>
16 #include "config.h"
17 #include "glog/logging.h"          // To pick up flag settings etc.
18 #include "glog/raw_logging.h"
19 #include "base/commandlineflags.h"
20
21 #ifdef HAVE_STACKTRACE
22 # include "stacktrace.h"
23 #endif
24
25 #if defined(HAVE_SYSCALL_H)
26 #include <syscall.h>                 // for syscall()
27 #elif defined(HAVE_SYS_SYSCALL_H)
28 #include <sys/syscall.h>                 // for syscall()
29 #endif
30 #ifdef HAVE_UNISTD_H
31 # include <unistd.h>
32 #endif
33
34 #if defined(HAVE_SYSCALL_H) || defined(HAVE_SYS_SYSCALL_H)
35 # define safe_write(fd, s, len)  syscall(SYS_write, fd, s, len)
36 #else
37   // Not so safe, but what can you do?
38 # define safe_write(fd, s, len)  write(fd, s, len)
39 #endif
40
41 _START_GOOGLE_NAMESPACE_
42
43 // Data for RawLog__ below. We simply pick up the latest
44 // time data created by a normal log message to avoid calling
45 // localtime_r which can allocate memory.
46 static struct ::tm last_tm_time_for_raw_log;
47 static int last_usecs_for_raw_log;
48
49 void RawLog__SetLastTime(const struct ::tm& t, int usecs) {
50   memcpy(&last_tm_time_for_raw_log, &t, sizeof(last_tm_time_for_raw_log));
51   last_usecs_for_raw_log = usecs;
52 }
53
54 // CAVEAT: vsnprintf called from *DoRawLog below has some (exotic) code paths
55 // that invoke malloc() and getenv() that might acquire some locks.
56 // If this becomes a problem we should reimplement a subset of vsnprintf
57 // that does not need locks and malloc.
58
59 // Helper for RawLog__ below.
60 // *DoRawLog writes to *buf of *size and move them past the written portion.
61 // It returns true iff there was no overflow or error.
62 static bool DoRawLog(char** buf, int* size, const char* format, ...) {
63   va_list ap;
64   va_start(ap, format);
65   int n = vsnprintf(*buf, *size, format, ap);
66   va_end(ap);
67   if (n < 0 || n > *size) return false;
68   *size -= n;
69   *buf += n;
70   return true;
71 }
72
73 // Helper for RawLog__ below.
74 inline static bool VADoRawLog(char** buf, int* size,
75                               const char* format, va_list ap) {
76   int n = vsnprintf(*buf, *size, format, ap);
77   if (n < 0 || n > *size) return false;
78   *size -= n;
79   *buf += n;
80   return true;
81 }
82
83 static const int kLogBufSize = 3000;
84 static bool crashed = false;
85 static CrashReason crash_reason;
86 static char crash_buf[kLogBufSize + 1] = { 0 };  // Will end in '\0'
87
88 void RawLog__(LogSeverity severity, const char* file, int line,
89               const char* format, ...) {
90   if (!(FLAGS_logtostderr || severity >= FLAGS_stderrthreshold ||
91         FLAGS_alsologtostderr || !IsGoogleLoggingInitialized())) {
92     return;  // this stderr log message is suppressed
93   }
94   // can't call localtime_r here: it can allocate
95   struct ::tm& t = last_tm_time_for_raw_log;
96   char buffer[kLogBufSize];
97   char* buf = buffer;
98   int size = sizeof(buffer);
99
100   // NOTE: this format should match the specification in base/logging.h
101   DoRawLog(&buf, &size, "%c%02d%02d %02d:%02d:%02d.%06d %5u %s:%d] RAW: ",
102            LogSeverityNames[severity][0],
103            1 + t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec,
104            last_usecs_for_raw_log,
105            static_cast<unsigned int>(GetTID()),
106            const_basename(const_cast<char *>(file)), line);
107
108   // Record the position and size of the buffer after the prefix
109   const char* msg_start = buf;
110   const int msg_size = size;
111
112   va_list ap;
113   va_start(ap, format);
114   bool no_chop = VADoRawLog(&buf, &size, format, ap);
115   va_end(ap);
116   if (no_chop) {
117     DoRawLog(&buf, &size, "\n");
118   } else {
119     DoRawLog(&buf, &size, "RAW_LOG ERROR: The Message was too long!\n");
120   }
121   // We make a raw syscall to write directly to the stderr file descriptor,
122   // avoiding FILE buffering (to avoid invoking malloc()), and bypassing
123   // libc (to side-step any libc interception).
124   // We write just once to avoid races with other invocations of RawLog__.
125   safe_write(STDERR_FILENO, buffer, strlen(buffer));
126   if (severity == FATAL)  {
127     if (!sync_val_compare_and_swap(&crashed, false, true)) {
128       crash_reason.filename = file;
129       crash_reason.line_number = line;
130       memcpy(crash_buf, msg_start, msg_size);  // Don't include prefix
131       crash_reason.message = crash_buf;
132 #ifdef HAVE_STACKTRACE
133       crash_reason.depth =
134           GetStackTrace(crash_reason.stack, ARRAYSIZE(crash_reason.stack), 1);
135 #else
136       crash_reason.depth = 0;
137 #endif
138       SetCrashReason(&crash_reason);
139     }
140     LogMessage::Fail();  // abort()
141   }
142 }
143
144 _END_GOOGLE_NAMESPACE_