1 // Copyright (c) 2014 The Chromium Embedded Framework Authors.
2 // Portions copyright (c) 2011 The Chromium Authors. All rights reserved.
3 // Use of this source code is governed by a BSD-style license that can be
4 // found in the LICENSE file.
5
6 #include "include/base/cef_logging.h"
7
8 #if defined(OS_WIN)
9 #include <windows.h>
10 #include <algorithm>
11 #include <sstream>
12 #elif defined(OS_POSIX)
13 #include <errno.h>
14 #include <stdio.h>
15 #include <string.h>
16 #endif
17
18 #include "include/internal/cef_string_types.h"
19
20 namespace cef {
21 namespace logging {
22
23 namespace {
24
25 #if defined(OS_POSIX)
26 // From base/posix/safe_strerror.cc
27
28 #if defined(__GLIBC__) || defined(OS_NACL)
29 #define USE_HISTORICAL_STRERRO_R 1
30 #else
31 #define USE_HISTORICAL_STRERRO_R 0
32 #endif
33
34 #if USE_HISTORICAL_STRERRO_R && defined(__GNUC__)
35 // GCC will complain about the unused second wrap function unless we tell it
36 // that we meant for them to be potentially unused, which is exactly what this
37 // attribute is for.
38 #define POSSIBLY_UNUSED __attribute__((unused))
39 #else
40 #define POSSIBLY_UNUSED
41 #endif
42
43 #if USE_HISTORICAL_STRERRO_R
44 // glibc has two strerror_r functions: a historical GNU-specific one that
45 // returns type char *, and a POSIX.1-2001 compliant one available since 2.3.4
46 // that returns int. This wraps the GNU-specific one.
47 static void POSSIBLY_UNUSED
wrap_posix_strerror_r(char * (* strerror_r_ptr)(int,char *,size_t),int err,char * buf,size_t len)48 wrap_posix_strerror_r(char* (*strerror_r_ptr)(int, char*, size_t),
49 int err,
50 char* buf,
51 size_t len) {
52 // GNU version.
53 char* rc = (*strerror_r_ptr)(err, buf, len);
54 if (rc != buf) {
55 // glibc did not use buf and returned a static string instead. Copy it
56 // into buf.
57 buf[0] = '\0';
58 strncat(buf, rc, len - 1);
59 }
60 // The GNU version never fails. Unknown errors get an "unknown error" message.
61 // The result is always null terminated.
62 }
63 #endif // USE_HISTORICAL_STRERRO_R
64
65 // Wrapper for strerror_r functions that implement the POSIX interface. POSIX
66 // does not define the behaviour for some of the edge cases, so we wrap it to
67 // guarantee that they are handled. This is compiled on all POSIX platforms, but
68 // it will only be used on Linux if the POSIX strerror_r implementation is
69 // being used (see below).
wrap_posix_strerror_r(int (* strerror_r_ptr)(int,char *,size_t),int err,char * buf,size_t len)70 static void POSSIBLY_UNUSED wrap_posix_strerror_r(int (*strerror_r_ptr)(int,
71 char*,
72 size_t),
73 int err,
74 char* buf,
75 size_t len) {
76 int old_errno = errno;
77 // Have to cast since otherwise we get an error if this is the GNU version
78 // (but in such a scenario this function is never called). Sadly we can't use
79 // C++-style casts because the appropriate one is reinterpret_cast but it's
80 // considered illegal to reinterpret_cast a type to itself, so we get an
81 // error in the opposite case.
82 int result = (*strerror_r_ptr)(err, buf, len);
83 if (result == 0) {
84 // POSIX is vague about whether the string will be terminated, although
85 // it indirectly implies that typically ERANGE will be returned, instead
86 // of truncating the string. We play it safe by always terminating the
87 // string explicitly.
88 buf[len - 1] = '\0';
89 } else {
90 // Error. POSIX is vague about whether the return value is itself a system
91 // error code or something else. On Linux currently it is -1 and errno is
92 // set. On BSD-derived systems it is a system error and errno is unchanged.
93 // We try and detect which case it is so as to put as much useful info as
94 // we can into our message.
95 int strerror_error; // The error encountered in strerror
96 int new_errno = errno;
97 if (new_errno != old_errno) {
98 // errno was changed, so probably the return value is just -1 or something
99 // else that doesn't provide any info, and errno is the error.
100 strerror_error = new_errno;
101 } else {
102 // Either the error from strerror_r was the same as the previous value, or
103 // errno wasn't used. Assume the latter.
104 strerror_error = result;
105 }
106 // snprintf truncates and always null-terminates.
107 snprintf(buf, len, "Error %d while retrieving error %d", strerror_error,
108 err);
109 }
110 errno = old_errno;
111 }
112
safe_strerror_r(int err,char * buf,size_t len)113 void safe_strerror_r(int err, char* buf, size_t len) {
114 if (buf == NULL || len <= 0) {
115 return;
116 }
117 // If using glibc (i.e., Linux), the compiler will automatically select the
118 // appropriate overloaded function based on the function type of strerror_r.
119 // The other one will be elided from the translation unit since both are
120 // static.
121 wrap_posix_strerror_r(&strerror_r, err, buf, len);
122 }
123
safe_strerror(int err)124 std::string safe_strerror(int err) {
125 const int buffer_size = 256;
126 char buf[buffer_size];
127 safe_strerror_r(err, buf, sizeof(buf));
128 return std::string(buf);
129 }
130 #endif // defined(OS_POSIX)
131
132 } // namespace
133
134 // MSVC doesn't like complex extern templates and DLLs.
135 #if !defined(COMPILER_MSVC)
136 // Explicit instantiations for commonly used comparisons.
137 template std::string* MakeCheckOpString<int, int>(const int&,
138 const int&,
139 const char* names);
140 template std::string* MakeCheckOpString<unsigned long, unsigned long>(
141 const unsigned long&,
142 const unsigned long&,
143 const char* names);
144 template std::string* MakeCheckOpString<unsigned long, unsigned int>(
145 const unsigned long&,
146 const unsigned int&,
147 const char* names);
148 template std::string* MakeCheckOpString<unsigned int, unsigned long>(
149 const unsigned int&,
150 const unsigned long&,
151 const char* names);
152 template std::string* MakeCheckOpString<std::string, std::string>(
153 const std::string&,
154 const std::string&,
155 const char* name);
156 #endif
157
158 #if defined(OS_WIN)
SaveLastError()159 LogMessage::SaveLastError::SaveLastError() : last_error_(::GetLastError()) {}
160
~SaveLastError()161 LogMessage::SaveLastError::~SaveLastError() {
162 ::SetLastError(last_error_);
163 }
164 #endif // defined(OS_WIN)
165
LogMessage(const char * file,int line,LogSeverity severity)166 LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
167 : severity_(severity), file_(file), line_(line) {}
168
LogMessage(const char * file,int line,std::string * result)169 LogMessage::LogMessage(const char* file, int line, std::string* result)
170 : severity_(LOG_FATAL), file_(file), line_(line) {
171 stream_ << "Check failed: " << *result;
172 delete result;
173 }
174
LogMessage(const char * file,int line,LogSeverity severity,std::string * result)175 LogMessage::LogMessage(const char* file,
176 int line,
177 LogSeverity severity,
178 std::string* result)
179 : severity_(severity), file_(file), line_(line) {
180 stream_ << "Check failed: " << *result;
181 delete result;
182 }
183
~LogMessage()184 LogMessage::~LogMessage() {
185 std::string str_newline(stream_.str());
186 cef_log(file_, line_, severity_, str_newline.c_str());
187 }
188
189 #if defined(OS_WIN)
190 // This has already been defined in the header, but defining it again as DWORD
191 // ensures that the type used in the header is equivalent to DWORD. If not,
192 // the redefinition is a compile error.
193 typedef DWORD SystemErrorCode;
194 #endif
195
GetLastSystemErrorCode()196 SystemErrorCode GetLastSystemErrorCode() {
197 #if defined(OS_WIN)
198 return ::GetLastError();
199 #elif defined(OS_POSIX)
200 return errno;
201 #else
202 #error Not implemented
203 #endif
204 }
205
206 #if defined(OS_WIN)
SystemErrorCodeToString(SystemErrorCode error_code)207 std::string SystemErrorCodeToString(SystemErrorCode error_code) {
208 const int error_message_buffer_size = 256;
209 char msgbuf[error_message_buffer_size];
210 DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
211 DWORD len = FormatMessageA(flags, NULL, error_code, 0, msgbuf,
212 arraysize(msgbuf), NULL);
213 std::stringstream ss;
214 if (len) {
215 std::string s(msgbuf);
216 // Messages returned by system end with line breaks.
217 s.erase(std::remove_if(s.begin(), s.end(), ::isspace), s.end());
218 ss << s << " (0x" << std::hex << error_code << ")";
219 } else {
220 ss << "Error (0x" << std::hex << GetLastError()
221 << ") while retrieving error. (0x" << error_code << ")";
222 }
223 return ss.str();
224 }
225 #elif defined(OS_POSIX)
SystemErrorCodeToString(SystemErrorCode error_code)226 std::string SystemErrorCodeToString(SystemErrorCode error_code) {
227 return safe_strerror(error_code);
228 }
229 #else
230 #error Not implemented
231 #endif
232
233 #if defined(OS_WIN)
Win32ErrorLogMessage(const char * file,int line,LogSeverity severity,SystemErrorCode err)234 Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
235 int line,
236 LogSeverity severity,
237 SystemErrorCode err)
238 : err_(err), log_message_(file, line, severity) {}
239
~Win32ErrorLogMessage()240 Win32ErrorLogMessage::~Win32ErrorLogMessage() {
241 stream() << ": " << SystemErrorCodeToString(err_);
242 }
243 #elif defined(OS_POSIX)
ErrnoLogMessage(const char * file,int line,LogSeverity severity,SystemErrorCode err)244 ErrnoLogMessage::ErrnoLogMessage(const char* file,
245 int line,
246 LogSeverity severity,
247 SystemErrorCode err)
248 : err_(err), log_message_(file, line, severity) {}
249
~ErrnoLogMessage()250 ErrnoLogMessage::~ErrnoLogMessage() {
251 stream() << ": " << SystemErrorCodeToString(err_);
252 }
253 #endif // OS_WIN
254
255 } // namespace logging
256 } // namespace cef
257
operator <<(std::ostream & out,const wchar_t * wstr)258 std::ostream& operator<<(std::ostream& out, const wchar_t* wstr) {
259 std::wstring tmp_str(wstr);
260 if (!tmp_str.empty()) {
261 cef_string_utf8_t str = {0};
262 cef_string_wide_to_utf8(wstr, tmp_str.size(), &str);
263 out << str.str;
264 cef_string_utf8_clear(&str);
265 }
266 return out;
267 }
268