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