| 6 |
| 7 | #include <limits.h> |
| 8 | #include <stdint.h> |
| 9 |
| 10 | #include "base/pending_task.h" |
| 11 | #include "base/stl_util.h" |
| 12 | #include "base/task/common/task_annotator.h" |
| 13 | #include "base/trace_event/trace_event.h" |
| 14 | #include "build/build_config.h" |
| 15 |
| 16 | #if defined(OS_WIN) |
| 17 | #include <io.h> |
| 18 | #include <windows.h> |
| 19 | typedef HANDLE FileHandle; |
| 20 | typedef HANDLE MutexHandle; |
| 21 | // Windows warns on using write(). It prefers _write(). |
| 22 | #define write(fd, buf, count) _write(fd, buf, static_cast<unsigned int>(count)) |
| 23 | // Windows doesn't define STDERR_FILENO. Define it here. |
| 24 | #define STDERR_FILENO 2 |
| 25 |
| 26 | #elif defined(OS_MACOSX) |
| 27 | // In MacOS 10.12 and iOS 10.0 and later ASL (Apple System Log) was deprecated |
| 28 | // in favor of OS_LOG (Unified Logging). |
| 29 | #include <AvailabilityMacros.h> |
| 30 | #if defined(OS_IOS) |
| 31 | #if !defined(__IPHONE_10_0) || __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_10_0 |
| 32 | #define USE_ASL |
| 33 | #endif |
| 34 | #else // !defined(OS_IOS) |
| 35 | #if !defined(MAC_OS_X_VERSION_10_12) || \ |
| 36 | MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_12 |
| 37 | #define USE_ASL |
| 38 | #endif |
| 39 | #endif // defined(OS_IOS) |
| 40 |
| 41 | #if defined(USE_ASL) |
| 42 | #include <asl.h> |
| 43 | #else |
| 44 | #include <os/log.h> |
| 45 | #endif |
| 46 |
| 47 | #include <CoreFoundation/CoreFoundation.h> |
| 48 | #include <mach/mach.h> |
| 49 | #include <mach/mach_time.h> |
| 50 | #include <mach-o/dyld.h> |
| 51 |
| 52 | #elif defined(OS_POSIX) || defined(OS_FUCHSIA) |
| 53 | #if defined(OS_NACL) |
| 54 | #include <sys/time.h> // timespec doesn't seem to be in <time.h> |
| 55 | #endif |
| 56 | #include <time.h> |
| 57 | #endif |
| 58 |
| 59 | #if defined(OS_FUCHSIA) |
| 60 | #include <lib/syslog/global.h> |
| 61 | #include <lib/syslog/logger.h> |
| 62 | #include <zircon/process.h> |
| 63 | #include <zircon/syscalls.h> |
| 64 | #endif |
| 65 |
| 66 | #if defined(OS_ANDROID) |
| 67 | #include <android/log.h> |
| 68 | #endif |
| 69 |
| 70 | #if defined(OS_POSIX) || defined(OS_FUCHSIA) |
| 71 | #include <errno.h> |
| 72 | #include <paths.h> |
| 73 | #include <pthread.h> |
| 74 | #include <stdio.h> |
| 75 | #include <stdlib.h> |
| 76 | #include <string.h> |
| 77 | #include <sys/stat.h> |
| 78 | #include "base/process/process_handle.h" |
| 79 | #define MAX_PATH PATH_MAX |
| 80 | typedef FILE* FileHandle; |
| 81 | typedef pthread_mutex_t* MutexHandle; |
| 82 | #endif |
| 83 |
| 84 | #include <algorithm> |
| 85 | #include <cstring> |
| 86 | #include <ctime> |
| 87 | #include <iomanip> |
| 88 | #include <ostream> |
| 89 | #include <string> |
| 90 | #include <utility> |
| 91 |
| 92 | #include "base/base_switches.h" |
| 93 | #include "base/callback.h" |
| 94 | #include "base/command_line.h" |
| 95 | #include "base/containers/stack.h" |
| 96 | #include "base/debug/activity_tracker.h" |
| 97 | #include "base/debug/alias.h" |
| 98 | #include "base/debug/debugger.h" |
| 99 | #include "base/debug/stack_trace.h" |
| 100 | #include "base/debug/task_trace.h" |
| 101 | #include "base/no_destructor.h" |
| 102 | #include "base/path_service.h" |
| 103 | #include "base/posix/eintr_wrapper.h" |
| 104 | #include "base/strings/string_piece.h" |
| 105 | #include "base/strings/string_split.h" |
| 106 | #include "base/strings/string_util.h" |
| 107 | #include "base/strings/stringprintf.h" |
| 108 | #include "base/strings/sys_string_conversions.h" |
| 109 | #include "base/strings/utf_string_conversions.h" |
| 110 | #include "base/synchronization/lock_impl.h" |
| 111 | #include "base/threading/platform_thread.h" |
| 112 | #include "base/vlog.h" |
| 113 |
| 114 | #if defined(OS_WIN) |
| 115 | #include "base/win/win_util.h" |
| 116 | #endif |
| 117 |
| 118 | #if defined(OS_POSIX) || defined(OS_FUCHSIA) |
| 119 | #include "base/posix/safe_strerror.h" |
| 120 | #endif |
| 121 |
| 122 | #if defined(OS_CHROMEOS) |
| 123 | #include "base/files/scoped_file.h" |
| 124 | #endif |
| 125 |
| 126 | namespace logging { |
| 127 |
| 128 | namespace { |
| 129 |
| 130 | VlogInfo* g_vlog_info = nullptr; |
| 131 | VlogInfo* g_vlog_info_prev = nullptr; |
| 132 |
| 133 | const char* const log_severity_names[] = {"INFO", "WARNING", "ERROR", "FATAL"}; |
| 134 | static_assert(LOG_NUM_SEVERITIES == base::size(log_severity_names), |
| 135 | "Incorrect number of log_severity_names"); |
| 136 |
| 137 | const char* log_severity_name(int severity) { |
| 138 | if (severity >= 0 && severity < LOG_NUM_SEVERITIES) |
| 139 | return log_severity_names[severity]; |
| 140 | return "UNKNOWN"; |
| 141 | } |
| 142 |
| 143 | int g_min_log_level = 0; |
| 144 |
| 145 | // Specifies the process' logging sink(s), represented as a combination of |
| 146 | // LoggingDestination values joined by bitwise OR. |
| 147 | int g_logging_destination = LOG_DEFAULT; |
| 148 |
| 149 | // For LOG_ERROR and above, always print to stderr. |
| 150 | const int kAlwaysPrintErrorLevel = LOG_ERROR; |
| 151 |
| 152 | // Which log file to use? This is initialized by InitLogging or |
| 153 | // will be lazily initialized to the default value when it is |
| 154 | // first needed. |
| 155 | using PathString = base::FilePath::StringType; |
| 156 | PathString* g_log_file_name = nullptr; |
| 157 |
| 158 | // This file is lazily opened and the handle may be nullptr |
| 159 | FileHandle g_log_file = nullptr; |
| 160 |
| 161 | // What should be prepended to each message? |
| 162 | bool g_log_process_id = false; |
| 163 | bool g_log_thread_id = false; |
| 164 | bool g_log_timestamp = true; |
| 165 | bool g_log_tickcount = false; |
| 166 | const char* g_log_prefix = nullptr; |
| 167 |
| 168 | // Should we pop up fatal debug messages in a dialog? |
| 169 | bool show_error_dialogs = false; |
| 170 |
| 171 | // An assert handler override specified by the client to be called instead of |
| 172 | // the debug message dialog and process termination. Assert handlers are stored |
| 173 | // in stack to allow overriding and restoring. |
| 174 | base::stack<LogAssertHandlerFunction>& GetLogAssertHandlerStack() { |
| 175 | static base::NoDestructor<base::stack<LogAssertHandlerFunction>> instance; |
| 176 | return *instance; |
| 177 | } |
| 178 |
| 179 | // A log message handler that gets notified of every log message we process. |
| 180 | LogMessageHandlerFunction log_message_handler = nullptr; |
| 181 |
| 182 | uint64_t TickCount() { |
| 183 | #if defined(OS_WIN) |
| 184 | return GetTickCount(); |
| 185 | #elif defined(OS_FUCHSIA) |
| 186 | return zx_clock_get_monotonic() / |
| 187 | static_cast<zx_time_t>(base::Time::kNanosecondsPerMicrosecond); |
| 188 | #elif defined(OS_MACOSX) |
| 189 | return mach_absolute_time(); |
| 190 | #elif defined(OS_NACL) |
| 191 | // NaCl sadly does not have _POSIX_TIMERS enabled in sys/features.h |
| 192 | // So we have to use clock() for now. |
| 193 | return clock(); |
| 194 | #elif defined(OS_POSIX) |
| 195 | struct timespec ts; |
| 196 | clock_gettime(CLOCK_MONOTONIC, &ts); |
| 197 |
| 198 | uint64_t absolute_micro = static_cast<int64_t>(ts.tv_sec) * 1000000 + |
| 199 | static_cast<int64_t>(ts.tv_nsec) / 1000; |
| 200 |
| 201 | return absolute_micro; |
| 202 | #endif |
| 203 | } |
| 204 |
| 205 | void DeleteFilePath(const PathString& log_name) { |
| 206 | #if defined(OS_WIN) |
| 207 | DeleteFile(log_name.c_str()); |
| 208 | #elif defined(OS_NACL) |
| 209 | // Do nothing; unlink() isn't supported on NaCl. |
| 210 | #elif defined(OS_POSIX) || defined(OS_FUCHSIA) |
| 211 | unlink(log_name.c_str()); |
| 212 | #else |
| 213 | #error Unsupported platform |
| 214 | #endif |
| 215 | } |
| 216 |
| 217 | PathString GetDefaultLogFile() { |
| 218 | #if defined(OS_WIN) |
| 219 | // On Windows we use the same path as the exe. |
| 220 | wchar_t module_name[MAX_PATH]; |
| 221 | GetModuleFileName(nullptr, module_name, MAX_PATH); |
| 222 |
| 223 | PathString log_name = module_name; |
| 224 | PathString::size_type last_backslash = log_name.rfind('\\', log_name.size()); |
| 225 | if (last_backslash != PathString::npos) |
| 226 | log_name.erase(last_backslash + 1); |
| 227 | log_name += FILE_PATH_LITERAL("debug.log"); |
| 228 | return log_name; |
| 229 | #elif defined(OS_POSIX) || defined(OS_FUCHSIA) |
| 230 | // On other platforms we just use the current directory. |
| 231 | return PathString("debug.log"); |
| 232 | #endif |
| 233 | } |
| 234 |
| 235 | // We don't need locks on Windows for atomically appending to files. The OS |
| 236 | // provides this functionality. |
| 237 | #if defined(OS_POSIX) || defined(OS_FUCHSIA) |
| 238 | // This class acts as a wrapper for locking the logging files. |
| 239 | // LoggingLock::Init() should be called from the main thread before any logging |
| 240 | // is done. Then whenever logging, be sure to have a local LoggingLock |
| 241 | // instance on the stack. This will ensure that the lock is unlocked upon |
| 242 | // exiting the frame. |
| 243 | // LoggingLocks can not be nested. |
| 244 | class LoggingLock { |
| 245 | public: |
| 246 | LoggingLock() { |
| 247 | LockLogging(); |
| 248 | } |
| 249 |
| 250 | ~LoggingLock() { |
| 251 | UnlockLogging(); |
| 252 | } |
| 253 |
| 254 | static void Init(LogLockingState lock_log, const PathChar* new_log_file) { |
| 255 | if (initialized) |
| 256 | return; |
| 257 | lock_log_file = lock_log; |
| 258 |
| 259 | if (lock_log_file != LOCK_LOG_FILE) |
| 260 | log_lock = new base::internal::LockImpl(); |
| 261 |
| 262 | initialized = true; |
| 263 | } |
| 264 |
| 265 | private: |
| 266 | static void LockLogging() { |
| 267 | if (lock_log_file == LOCK_LOG_FILE) { |
| 268 | pthread_mutex_lock(&log_mutex); |
| 269 | } else { |
| 270 | // use the lock |
| 271 | log_lock->Lock(); |
| 272 | } |
| 273 | } |
| 274 |
| 275 | static void UnlockLogging() { |
| 276 | if (lock_log_file == LOCK_LOG_FILE) { |
| 277 | pthread_mutex_unlock(&log_mutex); |
| 278 | } else { |
| 279 | log_lock->Unlock(); |
| 280 | } |
| 281 | } |
| 282 |
| 283 | // The lock is used if log file locking is false. It helps us avoid problems |
| 284 | // with multiple threads writing to the log file at the same time. Use |
| 285 | // LockImpl directly instead of using Lock, because Lock makes logging calls. |
| 286 | static base::internal::LockImpl* log_lock; |
| 287 |
| 288 | // When we don't use a lock, we are using a global mutex. We need to do this |
| 289 | // because LockFileEx is not thread safe. |
| 290 | static pthread_mutex_t log_mutex; |
| 291 |
| 292 | static bool initialized; |
| 293 | static LogLockingState lock_log_file; |
| 294 | }; |
| 295 |
| 296 | // static |
| 297 | bool LoggingLock::initialized = false; |
| 298 | // static |
| 299 | base::internal::LockImpl* LoggingLock::log_lock = nullptr; |
| 300 | // static |
| 301 | LogLockingState LoggingLock::lock_log_file = LOCK_LOG_FILE; |
| 302 |
| 303 | pthread_mutex_t LoggingLock::log_mutex = PTHREAD_MUTEX_INITIALIZER; |
| 304 |
| 305 | #endif // OS_POSIX || OS_FUCHSIA |
| 306 |
| 307 | // Called by logging functions to ensure that |g_log_file| is initialized |
| 308 | // and can be used for writing. Returns false if the file could not be |
| 309 | // initialized. |g_log_file| will be nullptr in this case. |
| 310 | bool InitializeLogFileHandle() { |
| 311 | if (g_log_file) |
| 312 | return true; |
| 313 |
| 314 | if (!g_log_file_name) { |
| 315 | // Nobody has called InitLogging to specify a debug log file, so here we |
| 316 | // initialize the log file name to a default. |
| 317 | g_log_file_name = new PathString(GetDefaultLogFile()); |
| 318 | } |
| 319 |
| 320 | if ((g_logging_destination & LOG_TO_FILE) == 0) |
| 321 | return true; |
| 322 |
| 323 | #if defined(OS_WIN) |
| 324 | // The FILE_APPEND_DATA access mask ensures that the file is atomically |
| 325 | // appended to across accesses from multiple threads. |
| 326 | // https://msdn.microsoft.com/en-us/library/windows/desktop/aa364399(v=vs.85).aspx |
| 327 | // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx |
| 328 | g_log_file = CreateFile(g_log_file_name->c_str(), FILE_APPEND_DATA, |
| 329 | FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, |
| 330 | OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); |
| 331 | if (g_log_file == INVALID_HANDLE_VALUE || g_log_file == nullptr) { |
| 332 | // We are intentionally not using FilePath or FileUtil here to reduce the |
| 333 | // dependencies of the logging implementation. For e.g. FilePath and |
| 334 | // FileUtil depend on shell32 and user32.dll. This is not acceptable for |
| 335 | // some consumers of base logging like chrome_elf, etc. |
| 336 | // Please don't change the code below to use FilePath. |
| 337 | // try the current directory |
| 338 | wchar_t system_buffer[MAX_PATH]; |
| 339 | system_buffer[0] = 0; |
| 340 | DWORD len = ::GetCurrentDirectory(base::size(system_buffer), system_buffer); |
| 341 | if (len == 0 || len > base::size(system_buffer)) |
| 342 | return false; |
| 343 |
| 344 | *g_log_file_name = system_buffer; |
| 345 | // Append a trailing backslash if needed. |
| 346 | if (g_log_file_name->back() != L'\\') |
| 347 | *g_log_file_name += FILE_PATH_LITERAL("\\"); |
| 348 | *g_log_file_name += FILE_PATH_LITERAL("debug.log"); |
| 349 |
| 350 | g_log_file = CreateFile(g_log_file_name->c_str(), FILE_APPEND_DATA, |
| 351 | FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, |
| 352 | OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); |
| 353 | if (g_log_file == INVALID_HANDLE_VALUE || g_log_file == nullptr) { |
| 354 | g_log_file = nullptr; |
| 355 | return false; |
| 356 | } |
| 357 | } |
| 358 | #elif defined(OS_POSIX) || defined(OS_FUCHSIA) |
| 359 | g_log_file = fopen(g_log_file_name->c_str(), "a"); |
| 360 | if (g_log_file == nullptr) |
| 361 | return false; |
| 362 | #else |
| 363 | #error Unsupported platform |
| 364 | #endif |
| 365 |
| 366 | return true; |
| 367 | } |
| 368 |
| 369 | void CloseFile(FileHandle log) { |
| 370 | #if defined(OS_WIN) |
| 371 | CloseHandle(log); |
| 372 | #elif defined(OS_POSIX) || defined(OS_FUCHSIA) |
| 373 | fclose(log); |
| 374 | #else |
| 375 | #error Unsupported platform |
| 376 | #endif |
| 377 | } |
| 378 |
| 379 | void CloseLogFileUnlocked() { |
| 380 | if (!g_log_file) |
| 381 | return; |
| 382 |
| 383 | CloseFile(g_log_file); |
| 384 | g_log_file = nullptr; |
| 385 |
| 386 | // If we initialized logging via an externally-provided file descriptor, we |
| 387 | // won't have a log path set and shouldn't try to reopen the log file. |
| 388 | if (!g_log_file_name) |
| 389 | g_logging_destination &= ~LOG_TO_FILE; |
| 390 | } |
| 391 |
| 392 | } // namespace |
| 393 |
| 394 | #if defined(DCHECK_IS_CONFIGURABLE) |
| 395 | // In DCHECK-enabled Chrome builds, allow the meaning of LOG_DCHECK to be |
| 396 | // determined at run-time. We default it to INFO, to avoid it triggering |
| 397 | // crashes before the run-time has explicitly chosen the behaviour. |
| 398 | BASE_EXPORT logging::LogSeverity LOG_DCHECK = LOG_INFO; |
| 399 | #endif // defined(DCHECK_IS_CONFIGURABLE) |
| 400 |
| 401 | // This is never instantiated, it's just used for EAT_STREAM_PARAMETERS to have |
| 402 | // an object of the correct type on the LHS of the unused part of the ternary |
| 403 | // operator. |
| 404 | std::ostream* g_swallow_stream; |
| 405 |
| 406 | bool BaseInitLoggingImpl(const LoggingSettings& settings) { |
| 407 | #if defined(OS_NACL) |
| 408 | // Can log only to the system debug log and stderr. |
| 409 | CHECK_EQ(settings.logging_dest & ~(LOG_TO_SYSTEM_DEBUG_LOG | LOG_TO_STDERR), |
| 410 | 0u); |
| 411 | #endif |
| 412 |
| 413 | base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); |
| 414 | // Don't bother initializing |g_vlog_info| unless we use one of the |
| 415 | // vlog switches. |
| 416 | if (command_line->HasSwitch(switches::kV) || |
| 417 | command_line->HasSwitch(switches::kVModule)) { |
| 418 | // NOTE: If |g_vlog_info| has already been initialized, it might be in use |
| 419 | // by another thread. Don't delete the old VLogInfo, just create a second |
| 420 | // one. We keep track of both to avoid memory leak warnings. |
| 421 | CHECK(!g_vlog_info_prev); |
| 422 | g_vlog_info_prev = g_vlog_info; |
| 423 |
| 424 | g_vlog_info = |
| 425 | new VlogInfo(command_line->GetSwitchValueASCII(switches::kV), |
| 426 | command_line->GetSwitchValueASCII(switches::kVModule), |
| 427 | &g_min_log_level); |
| 428 | } |
| 429 |
| 430 | g_logging_destination = settings.logging_dest; |
| 431 |
| 432 | #if defined(OS_FUCHSIA) |
| 433 | if (g_logging_destination & LOG_TO_SYSTEM_DEBUG_LOG) { |
| 434 | fx_logger_config_t config; |
| 435 | config.min_severity = FX_LOG_INFO; |
| 436 | config.console_fd = -1; |
| 437 | config.log_service_channel = ZX_HANDLE_INVALID; |
| 438 | std::string log_tag = command_line->GetProgram().BaseName().AsUTF8Unsafe(); |
| 439 | const char* log_tag_data = log_tag.data(); |
| 440 | config.tags = &log_tag_data; |
| 441 | config.num_tags = 1; |
| 442 | fx_log_init_with_config(&config); |
| 443 | } |
| 444 | #endif |
| 445 |
| 446 | // ignore file options unless logging to file is set. |
| 447 | if ((g_logging_destination & LOG_TO_FILE) == 0) |
| 448 | return true; |
| 449 |
| 450 | #if defined(OS_POSIX) || defined(OS_FUCHSIA) |
| 451 | LoggingLock::Init(settings.lock_log, settings.log_file_path); |
| 452 | LoggingLock logging_lock; |
| 453 | #endif |
| 454 |
| 455 | // Calling InitLogging twice or after some log call has already opened the |
| 456 | // default log file will re-initialize to the new options. |
| 457 | CloseLogFileUnlocked(); |
| 458 |
| 459 | #if defined(OS_CHROMEOS) |
| 460 | if (settings.log_file) { |
| 461 | DCHECK(!settings.log_file_path); |
| 462 | g_log_file = settings.log_file; |
| 463 | return true; |
| 464 | } |
| 465 | #endif |
| 466 |
| 467 | if (!g_log_file_name) |
| 468 | g_log_file_name = new PathString(); |
| 469 | *g_log_file_name = settings.log_file_path; |
| 470 | if (settings.delete_old == DELETE_OLD_LOG_FILE) |
| 471 | DeleteFilePath(*g_log_file_name); |
| 472 |
| 473 | return InitializeLogFileHandle(); |
| 474 | } |
| 475 |
| 476 | void SetMinLogLevel(int level) { |
| 477 | g_min_log_level = std::min(LOG_FATAL, level); |
| 478 | } |
| 479 |
| 480 | int GetMinLogLevel() { |
| 481 | return g_min_log_level; |
| 482 | } |
| 483 |
| 484 | bool ShouldCreateLogMessage(int severity) { |
| 485 | if (severity < g_min_log_level) |
| 486 | return false; |
| 487 |
| 488 | // Return true here unless we know ~LogMessage won't do anything. |
| 489 | return g_logging_destination != LOG_NONE || log_message_handler || |
| 490 | severity >= kAlwaysPrintErrorLevel; |
| 491 | } |
| 492 |
| 493 | // Returns true when LOG_TO_STDERR flag is set, or |severity| is high. |
| 494 | // If |severity| is high then true will be returned when no log destinations are |
| 495 | // set, or only LOG_TO_FILE is set, since that is useful for local development |
| 496 | // and debugging. |
| 497 | bool ShouldLogToStderr(int severity) { |
| 498 | if (g_logging_destination & LOG_TO_STDERR) |
| 499 | return true; |
| 500 | if (severity >= kAlwaysPrintErrorLevel) |
| 501 | return (g_logging_destination & ~LOG_TO_FILE) == LOG_NONE; |
| 502 | return false; |
| 503 | } |
| 504 |
| 505 | int GetVlogVerbosity() { |
| 506 | return std::max(-1, LOG_INFO - GetMinLogLevel()); |
| 507 | } |
| 508 |
| 509 | int GetVlogLevelHelper(const char* file, size_t N) { |
| 510 | DCHECK_GT(N, 0U); |
| 511 | // Note: |g_vlog_info| may change on a different thread during startup |
| 512 | // (but will always be valid or nullptr). |
| 513 | VlogInfo* vlog_info = g_vlog_info; |
| 514 | return vlog_info ? |
| 515 | vlog_info->GetVlogLevel(base::StringPiece(file, N - 1)) : |
| 516 | GetVlogVerbosity(); |
| 517 | } |
| 518 |
| 519 | void SetLogItems(bool enable_process_id, bool enable_thread_id, |
| 520 | bool enable_timestamp, bool enable_tickcount) { |
| 521 | g_log_process_id = enable_process_id; |
| 522 | g_log_thread_id = enable_thread_id; |
| 523 | g_log_timestamp = enable_timestamp; |
| 524 | g_log_tickcount = enable_tickcount; |
| 525 | } |
| 526 |
| 527 | void SetLogPrefix(const char* prefix) { |
| 528 | DCHECK(!prefix || |
| 529 | base::ContainsOnlyChars(prefix, "abcdefghijklmnopqrstuvwxyz")); |
| 530 | g_log_prefix = prefix; |
| 531 | } |
| 532 |
| 533 | void SetShowErrorDialogs(bool enable_dialogs) { |
| 534 | show_error_dialogs = enable_dialogs; |
| 535 | } |
| 536 |
| 537 | ScopedLogAssertHandler::ScopedLogAssertHandler( |
| 538 | LogAssertHandlerFunction handler) { |
| 539 | GetLogAssertHandlerStack().push(std::move(handler)); |
| 540 | } |
| 541 |
| 542 | ScopedLogAssertHandler::~ScopedLogAssertHandler() { |
| 543 | GetLogAssertHandlerStack().pop(); |
| 544 | } |
| 545 |
| 546 | void SetLogMessageHandler(LogMessageHandlerFunction handler) { |
| 547 | log_message_handler = handler; |
| 548 | } |
| 549 |
| 550 | LogMessageHandlerFunction GetLogMessageHandler() { |
| 551 | return log_message_handler; |
| 552 | } |
| 553 |
| 554 | // Explicit instantiations for commonly used comparisons. |
| 555 | template std::string* MakeCheckOpString<int, int>( |
| 556 | const int&, const int&, const char* names); |
| 557 | template std::string* MakeCheckOpString<unsigned long, unsigned long>( |
| 558 | const unsigned long&, const unsigned long&, const char* names); |
| 559 | template std::string* MakeCheckOpString<unsigned long, unsigned int>( |
| 560 | const unsigned long&, const unsigned int&, const char* names); |
| 561 | template std::string* MakeCheckOpString<unsigned int, unsigned long>( |
| 562 | const unsigned int&, const unsigned long&, const char* names); |
| 563 | template std::string* MakeCheckOpString<std::string, std::string>( |
| 564 | const std::string&, const std::string&, const char* name); |
| 565 |
| 566 | void MakeCheckOpValueString(std::ostream* os, std::nullptr_t p) { |
| 567 | (*os) << "nullptr"; |
| 568 | } |
| 569 |
| 570 | #if !defined(NDEBUG) |
| 571 | // Displays a message box to the user with the error message in it. |
| 572 | // Used for fatal messages, where we close the app simultaneously. |
| 573 | // This is for developers only; we don't use this in circumstances |
| 574 | // (like release builds) where users could see it, since users don't |
| 575 | // understand these messages anyway. |
| 576 | void DisplayDebugMessageInDialog(const std::string& str) { |
| 577 | if (str.empty()) |
| 578 | return; |
| 579 |
| 580 | if (!show_error_dialogs) |
| 581 | return; |
| 582 |
| 583 | #if defined(OS_WIN) |
| 584 | // We intentionally don't implement a dialog on other platforms. |
| 585 | // You can just look at stderr. |
| 586 | if (base::win::IsUser32AndGdi32Available()) { |
| 587 | MessageBoxW(nullptr, base::as_wcstr(base::UTF8ToUTF16(str)), L"Fatal error", |
| 588 | MB_OK | MB_ICONHAND | MB_TOPMOST); |
| 589 | } else { |
| 590 | OutputDebugStringW(base::as_wcstr(base::UTF8ToUTF16(str))); |
| 591 | } |
| 592 | #endif // defined(OS_WIN) |
| 593 | } |
| 594 | #endif // !defined(NDEBUG) |
| 595 |
| 596 | LogMessage::LogMessage(const char* file, int line, LogSeverity severity) |
| 597 | : severity_(severity), file_(file), line_(line) { |
| 598 | Init(file, line); |
| 599 | } |
| 600 |
| 601 | LogMessage::LogMessage(const char* file, int line, const char* condition) |
| 602 | : severity_(LOG_FATAL), file_(file), line_(line) { |
| 603 | Init(file, line); |
| 604 | stream_ << "Check failed: " << condition << ". "; |
| 605 | } |
| 606 |
| 607 | LogMessage::LogMessage(const char* file, int line, std::string* result) |
| 608 | : severity_(LOG_FATAL), file_(file), line_(line) { |
| 609 | Init(file, line); |
| 610 | stream_ << "Check failed: " << *result; |
| 611 | delete result; |
| 612 | } |
| 613 |
| 614 | LogMessage::LogMessage(const char* file, int line, LogSeverity severity, |
| 615 | std::string* result) |
| 616 | : severity_(severity), file_(file), line_(line) { |
| 617 | Init(file, line); |
| 618 | stream_ << "Check failed: " << *result; |
| 619 | delete result; |
| 620 | } |
| 621 |
| 622 | LogMessage::~LogMessage() { |
| 623 | size_t stack_start = stream_.tellp(); |
| 624 | #if !defined(OFFICIAL_BUILD) && !defined(OS_NACL) && !defined(__UCLIBC__) && \ |
| 625 | !defined(OS_AIX) |
| 626 | if (severity_ == LOG_FATAL && !base::debug::BeingDebugged()) { |
| 627 | // Include a stack trace on a fatal, unless a debugger is attached. |
| 628 | base::debug::StackTrace stack_trace; |
| 629 | stream_ << std::endl; // Newline to separate from log message. |
| 630 | stack_trace.OutputToStream(&stream_); |
| 631 | base::debug::TaskTrace task_trace; |
| 632 | if (!task_trace.empty()) |
| 633 | task_trace.OutputToStream(&stream_); |
| 634 |
| 635 | // Include the IPC context, if any. |
| 636 | // TODO(chrisha): Integrate with symbolization once those tools exist! |
| 637 | const auto* task = base::TaskAnnotator::CurrentTaskForThread(); |
| 638 | if (task && task->ipc_hash) { |
| 639 | stream_ << "IPC message handler context: " |
| 640 | << base::StringPrintf("0x%08X", task->ipc_hash) << std::endl; |
| 641 | } |
| 642 | } |
| 643 | #endif |
| 644 | stream_ << std::endl; |
| 645 | std::string str_newline(stream_.str()); |
| 646 | TRACE_LOG_MESSAGE( |
| 647 | file_, base::StringPiece(str_newline).substr(message_start_), line_); |
| 648 |
| 649 | // Give any log message handler first dibs on the message. |
| 650 | if (log_message_handler && |
| 651 | log_message_handler(severity_, file_, line_, |
| 652 | message_start_, str_newline)) { |
| 653 | // The handler took care of it, no further processing. |
| 654 | return; |
| 655 | } |
| 656 |
| 657 | if ((g_logging_destination & LOG_TO_SYSTEM_DEBUG_LOG) != 0) { |
| 658 | #if defined(OS_WIN) |
| 659 | OutputDebugStringA(str_newline.c_str()); |
| 660 | #elif defined(OS_MACOSX) |
| 661 | // In LOG_TO_SYSTEM_DEBUG_LOG mode, log messages are always written to |
| 662 | // stderr. If stderr is /dev/null, also log via ASL (Apple System Log) or |
| 663 | // its successor OS_LOG. If there's something weird about stderr, assume |
| 664 | // that log messages are going nowhere and log via ASL/OS_LOG too. |
| 665 | // Messages logged via ASL/OS_LOG show up in Console.app. |
| 666 | // |
| 667 | // Programs started by launchd, as UI applications normally are, have had |
| 668 | // stderr connected to /dev/null since OS X 10.8. Prior to that, stderr was |
| 669 | // a pipe to launchd, which logged what it received (see log_redirect_fd in |
| 670 | // 10.7.5 launchd-392.39/launchd/src/launchd_core_logic.c). |
| 671 | // |
| 672 | // Another alternative would be to determine whether stderr is a pipe to |
| 673 | // launchd and avoid logging via ASL only in that case. See 10.7.5 |
| 674 | // CF-635.21/CFUtilities.c also_do_stderr(). This would result in logging to |
| 675 | // both stderr and ASL/OS_LOG even in tests, where it's undesirable to log |
| 676 | // to the system log at all. |
| 677 | // |
| 678 | // Note that the ASL client by default discards messages whose levels are |
| 679 | // below ASL_LEVEL_NOTICE. It's possible to change that with |
| 680 | // asl_set_filter(), but this is pointless because syslogd normally applies |
| 681 | // the same filter. |
| 682 | const bool log_to_system = []() { |
| 683 | struct stat stderr_stat; |
| 684 | if (fstat(fileno(stderr), &stderr_stat) == -1) { |
| 685 | return true; |
| 686 | } |
| 687 | if (!S_ISCHR(stderr_stat.st_mode)) { |
| 688 | return false; |
| 689 | } |
| 690 |
| 691 | struct stat dev_null_stat; |
| 692 | if (stat(_PATH_DEVNULL, &dev_null_stat) == -1) { |
| 693 | return true; |
| 694 | } |
| 695 |
| 696 | return !S_ISCHR(dev_null_stat.st_mode) || |
| 697 | stderr_stat.st_rdev == dev_null_stat.st_rdev; |
| 698 | }(); |
| 699 |
| 700 | if (log_to_system) { |
| 701 | // Log roughly the same way that CFLog() and NSLog() would. See 10.10.5 |
| 702 | // CF-1153.18/CFUtilities.c __CFLogCString(). |
| 703 | CFBundleRef main_bundle = CFBundleGetMainBundle(); |
| 704 | CFStringRef main_bundle_id_cf = |
| 705 | main_bundle ? CFBundleGetIdentifier(main_bundle) : nullptr; |
| 706 | std::string main_bundle_id = |
| 707 | main_bundle_id_cf ? base::SysCFStringRefToUTF8(main_bundle_id_cf) |
| 708 | : std::string(""); |
| 709 | #if defined(USE_ASL) |
| 710 | // The facility is set to the main bundle ID if available. Otherwise, |
| 711 | // "com.apple.console" is used. |
| 712 | const class ASLClient { |
| 713 | public: |
| 714 | explicit ASLClient(const std::string& facility) |
| 715 | : client_(asl_open(nullptr, facility.c_str(), ASL_OPT_NO_DELAY)) {} |
| 716 | ~ASLClient() { asl_close(client_); } |
| 717 |
| 718 | aslclient get() const { return client_; } |
| 719 |
| 720 | private: |
| 721 | aslclient client_; |
| 722 | DISALLOW_COPY_AND_ASSIGN(ASLClient); |
| 723 | } asl_client(main_bundle_id.empty() ? main_bundle_id |
| 724 | : "com.apple.console"); |
| 725 |
| 726 | const class ASLMessage { |
| 727 | public: |
| 728 | ASLMessage() : message_(asl_new(ASL_TYPE_MSG)) {} |
| 729 | ~ASLMessage() { asl_free(message_); } |
| 730 |
| 731 | aslmsg get() const { return message_; } |
| 732 |
| 733 | private: |
| 734 | aslmsg message_; |
| 735 | DISALLOW_COPY_AND_ASSIGN(ASLMessage); |
| 736 | } asl_message; |
| 737 |
| 738 | // By default, messages are only readable by the admin group. Explicitly |
| 739 | // make them readable by the user generating the messages. |
| 740 | char euid_string[12]; |
| 741 | snprintf(euid_string, base::size(euid_string), "%d", geteuid()); |
| 742 | asl_set(asl_message.get(), ASL_KEY_READ_UID, euid_string); |
| 743 |
| 744 | // Map Chrome log severities to ASL log levels. |
| 745 | const char* const asl_level_string = [](LogSeverity severity) { |
| 746 | // ASL_LEVEL_* are ints, but ASL needs equivalent strings. This |
| 747 | // non-obvious two-step macro trick achieves what's needed. |
| 748 | // https://gcc.gnu.org/onlinedocs/cpp/Stringification.html |
| 749 | #define ASL_LEVEL_STR(level) ASL_LEVEL_STR_X(level) |
| 750 | #define ASL_LEVEL_STR_X(level) #level |
| 751 | switch (severity) { |
| 752 | case LOG_INFO: |
| 753 | return ASL_LEVEL_STR(ASL_LEVEL_INFO); |
| 754 | case LOG_WARNING: |
| 755 | return ASL_LEVEL_STR(ASL_LEVEL_WARNING); |
| 756 | case LOG_ERROR: |
| 757 | return ASL_LEVEL_STR(ASL_LEVEL_ERR); |
| 758 | case LOG_FATAL: |
| 759 | return ASL_LEVEL_STR(ASL_LEVEL_CRIT); |
| 760 | default: |
| 761 | return severity < 0 ? ASL_LEVEL_STR(ASL_LEVEL_DEBUG) |
| 762 | : ASL_LEVEL_STR(ASL_LEVEL_NOTICE); |
| 763 | } |
| 764 | #undef ASL_LEVEL_STR |
| 765 | #undef ASL_LEVEL_STR_X |
| 766 | }(severity_); |
| 767 | asl_set(asl_message.get(), ASL_KEY_LEVEL, asl_level_string); |
| 768 |
| 769 | asl_set(asl_message.get(), ASL_KEY_MSG, str_newline.c_str()); |
| 770 |
| 771 | asl_send(asl_client.get(), asl_message.get()); |
| 772 | #else // !defined(USE_ASL) |
| 773 | const class OSLog { |
| 774 | public: |
| 775 | explicit OSLog(const char* subsystem) |
| 776 | : os_log_(subsystem ? os_log_create(subsystem, "chromium_logging") |
| 777 | : OS_LOG_DEFAULT) {} |
| 778 | ~OSLog() { |
| 779 | if (os_log_ != OS_LOG_DEFAULT) { |
| 780 | os_release(os_log_); |
| 781 | } |
| 782 | } |
| 783 | os_log_t get() const { return os_log_; } |
| 784 |
| 785 | private: |
| 786 | os_log_t os_log_; |
| 787 | DISALLOW_COPY_AND_ASSIGN(OSLog); |
| 788 | } log(main_bundle_id.empty() ? nullptr : main_bundle_id.c_str()); |
| 789 | const os_log_type_t os_log_type = [](LogSeverity severity) { |
| 790 | switch (severity) { |
| 791 | case LOG_INFO: |
| 792 | return OS_LOG_TYPE_INFO; |
| 793 | case LOG_WARNING: |
| 794 | return OS_LOG_TYPE_DEFAULT; |
| 795 | case LOG_ERROR: |
| 796 | return OS_LOG_TYPE_ERROR; |
| 797 | case LOG_FATAL: |
| 798 | return OS_LOG_TYPE_FAULT; |
| 799 | default: |
| 800 | return severity < 0 ? OS_LOG_TYPE_DEBUG : OS_LOG_TYPE_DEFAULT; |
| 801 | } |
| 802 | }(severity_); |
| 803 | os_log_with_type(log.get(), os_log_type, "%{public}s", |
| 804 | str_newline.c_str()); |
| 805 | #endif // defined(USE_ASL) |
| 806 | } |
| 807 | #elif defined(OS_ANDROID) |
| 808 | android_LogPriority priority = |
| 809 | (severity_ < 0) ? ANDROID_LOG_VERBOSE : ANDROID_LOG_UNKNOWN; |
| 810 | switch (severity_) { |
| 811 | case LOG_INFO: |
| 812 | priority = ANDROID_LOG_INFO; |
| 813 | break; |
| 814 | case LOG_WARNING: |
| 815 | priority = ANDROID_LOG_WARN; |
| 816 | break; |
| 817 | case LOG_ERROR: |
| 818 | priority = ANDROID_LOG_ERROR; |
| 819 | break; |
| 820 | case LOG_FATAL: |
| 821 | priority = ANDROID_LOG_FATAL; |
| 822 | break; |
| 823 | } |
| 824 | const char kAndroidLogTag[] = "chromium"; |
| 825 | #if DCHECK_IS_ON() |
| 826 | // Split the output by new lines to prevent the Android system from |
| 827 | // truncating the log. |
| 828 | std::vector<std::string> lines = base::SplitString( |
| 829 | str_newline, "\n", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL); |
| 830 | // str_newline has an extra newline appended to it (at the top of this |
| 831 | // function), so skip the last split element to avoid needlessly |
| 832 | // logging an empty string. |
| 833 | lines.pop_back(); |
| 834 | for (const auto& line : lines) |
| 835 | __android_log_write(priority, kAndroidLogTag, line.c_str()); |
| 836 | #else |
| 837 | // The Android system may truncate the string if it's too long. |
| 838 | __android_log_write(priority, kAndroidLogTag, str_newline.c_str()); |
| 839 | #endif |
| 840 | #elif defined(OS_FUCHSIA) |
| 841 | fx_log_severity_t severity = FX_LOG_INFO; |
| 842 | switch (severity_) { |
| 843 | case LOG_INFO: |
| 844 | severity = FX_LOG_INFO; |
| 845 | break; |
| 846 | case LOG_WARNING: |
| 847 | severity = FX_LOG_WARNING; |
| 848 | break; |
| 849 | case LOG_ERROR: |
| 850 | severity = FX_LOG_ERROR; |
| 851 | break; |
| 852 | case LOG_FATAL: |
| 853 | // Don't use FX_LOG_FATAL, otherwise fx_logger_log() will abort(). |
| 854 | severity = FX_LOG_ERROR; |
| 855 | break; |
| 856 | } |
| 857 |
| 858 | fx_logger_t* logger = fx_log_get_logger(); |
| 859 | if (logger) { |
| 860 | // Temporarily remove the trailing newline from |str_newline|'s C-string |
| 861 | // representation, since fx_logger will add a newline of its own. |
| 862 | str_newline.pop_back(); |
| 863 | std::string message = |
| 864 | base::StringPrintf("%s(%d) %s", file_basename_, line_, |
| 865 | str_newline.c_str() + message_start_); |
| 866 | fx_logger_log(logger, severity, nullptr, message.data()); |
| 867 | str_newline.push_back('\n'); |
| 868 | } |
| 869 | #endif // OS_FUCHSIA |
| 870 | } |
| 871 |
| 872 | if (ShouldLogToStderr(severity_)) { |
| 873 | ignore_result(fwrite(str_newline.data(), str_newline.size(), 1, stderr)); |
| 874 | fflush(stderr); |
| 875 | } |
| 876 |
| 877 | if ((g_logging_destination & LOG_TO_FILE) != 0) { |
| 878 | // We can have multiple threads and/or processes, so try to prevent them |
| 879 | // from clobbering each other's writes. |
| 880 | // If the client app did not call InitLogging, and the lock has not |
| 881 | // been created do it now. We do this on demand, but if two threads try |
| 882 | // to do this at the same time, there will be a race condition to create |
| 883 | // the lock. This is why InitLogging should be called from the main |
| 884 | // thread at the beginning of execution. |
| 885 | #if defined(OS_POSIX) || defined(OS_FUCHSIA) |
| 886 | LoggingLock::Init(LOCK_LOG_FILE, nullptr); |
| 887 | LoggingLock logging_lock; |
| 888 | #endif |
| 889 | if (InitializeLogFileHandle()) { |
| 890 | #if defined(OS_WIN) |
| 891 | DWORD num_written; |
| 892 | WriteFile(g_log_file, |
| 893 | static_cast<const void*>(str_newline.c_str()), |
| 894 | static_cast<DWORD>(str_newline.length()), |
| 895 | &num_written, |
| 896 | nullptr); |
| 897 | #elif defined(OS_POSIX) || defined(OS_FUCHSIA) |
| 898 | ignore_result(fwrite( |
| 899 | str_newline.data(), str_newline.size(), 1, g_log_file)); |
| 900 | fflush(g_log_file); |
| 901 | #else |
| 902 | #error Unsupported platform |
| 903 | #endif |
| 904 | } |
| 905 | } |
| 906 |
| 907 | if (severity_ == LOG_FATAL) { |
| 908 | // Write the log message to the global activity tracker, if running. |
| 909 | base::debug::GlobalActivityTracker* tracker = |
| 910 | base::debug::GlobalActivityTracker::Get(); |
| 911 | if (tracker) |
| 912 | tracker->RecordLogMessage(str_newline); |
| 913 |
| 914 | // Ensure the first characters of the string are on the stack so they |
| 915 | // are contained in minidumps for diagnostic purposes. We place start |
| 916 | // and end marker values at either end, so we can scan captured stacks |
| 917 | // for the data easily. |
| 918 | struct { |
| 919 | uint32_t start_marker = 0xbedead01; |
| 920 | char data[1024]; |
| 921 | uint32_t end_marker = 0x5050dead; |
| 922 | } str_stack; |
| 923 | base::strlcpy(str_stack.data, str_newline.data(), |
| 924 | base::size(str_stack.data)); |
| 925 | base::debug::Alias(&str_stack); |
| 926 |
| 927 | if (!GetLogAssertHandlerStack().empty()) { |
| 928 | LogAssertHandlerFunction log_assert_handler = |
| 929 | GetLogAssertHandlerStack().top(); |
| 930 |
| 931 | if (log_assert_handler) { |
| 932 | log_assert_handler.Run( |
| 933 | file_, line_, |
| 934 | base::StringPiece(str_newline.c_str() + message_start_, |
| 935 | stack_start - message_start_), |
| 936 | base::StringPiece(str_newline.c_str() + stack_start)); |
| 937 | } |
| 938 | } else { |
| 939 | // Don't use the string with the newline, get a fresh version to send to |
| 940 | // the debug message process. We also don't display assertions to the |
| 941 | // user in release mode. The enduser can't do anything with this |
| 942 | // information, and displaying message boxes when the application is |
| 943 | // hosed can cause additional problems. |
| 944 | #ifndef NDEBUG |
| 945 | if (!base::debug::BeingDebugged()) { |
| 946 | // Displaying a dialog is unnecessary when debugging and can complicate |
| 947 | // debugging. |
| 948 | DisplayDebugMessageInDialog(stream_.str()); |
| 949 | } |
| 950 | #endif |
| 951 | // Crash the process to generate a dump. |
| 952 | #if defined(OFFICIAL_BUILD) && defined(NDEBUG) |
| 953 | IMMEDIATE_CRASH(); |
| 954 | #else |
| 955 | base::debug::BreakDebugger(); |
| 956 | #endif |
| 957 | } |
| 958 | } |
| 959 | } |
| 960 |
| 961 | // writes the common header info to the stream |
| 962 | void LogMessage::Init(const char* file, int line) { |
| 963 | base::StringPiece filename(file); |
| 964 | size_t last_slash_pos = filename.find_last_of("\\/"); |
| 965 | if (last_slash_pos != base::StringPiece::npos) |
| 966 | filename.remove_prefix(last_slash_pos + 1); |
| 967 |
| 968 | // Stores the base name as the null-terminated suffix substring of |filename|. |
| 969 | file_basename_ = filename.data(); |
| 970 |
| 971 | // TODO(darin): It might be nice if the columns were fixed width. |
| 972 |
| 973 | stream_ << '['; |
| 974 | if (g_log_prefix) |
| 975 | stream_ << g_log_prefix << ':'; |
| 976 | if (g_log_process_id) |
| 977 | stream_ << base::GetUniqueIdForProcess() << ':'; |
| 978 | if (g_log_thread_id) |
| 979 | stream_ << base::PlatformThread::CurrentId() << ':'; |
| 980 | if (g_log_timestamp) { |
| 981 | #if defined(OS_WIN) |
| 982 | SYSTEMTIME local_time; |
| 983 | GetLocalTime(&local_time); |
| 984 | stream_ << std::setfill('0') |
| 985 | << std::setw(2) << local_time.wMonth |
| 986 | << std::setw(2) << local_time.wDay |
| 987 | << '/' |
| 988 | << std::setw(2) << local_time.wHour |
| 989 | << std::setw(2) << local_time.wMinute |
| 990 | << std::setw(2) << local_time.wSecond |
| 991 | << '.' |
| 992 | << std::setw(3) |
| 993 | << local_time.wMilliseconds |
| 994 | << ':'; |
| 995 | #elif defined(OS_POSIX) || defined(OS_FUCHSIA) |
| 996 | timeval tv; |
| 997 | gettimeofday(&tv, nullptr); |
| 998 | time_t t = tv.tv_sec; |
| 999 | struct tm local_time; |
| 1000 | localtime_r(&t, &local_time); |
| 1001 | struct tm* tm_time = &local_time; |
| 1002 | stream_ << std::setfill('0') |
| 1003 | << std::setw(2) << 1 + tm_time->tm_mon |
| 1004 | << std::setw(2) << tm_time->tm_mday |
| 1005 | << '/' |
| 1006 | << std::setw(2) << tm_time->tm_hour |
| 1007 | << std::setw(2) << tm_time->tm_min |
| 1008 | << std::setw(2) << tm_time->tm_sec |
| 1009 | << '.' |
| 1010 | << std::setw(6) << tv.tv_usec |
| 1011 | << ':'; |
| 1012 | #else |
| 1013 | #error Unsupported platform |
| 1014 | #endif |
| 1015 | } |
| 1016 | if (g_log_tickcount) |
| 1017 | stream_ << TickCount() << ':'; |
| 1018 | if (severity_ >= 0) |
| 1019 | stream_ << log_severity_name(severity_); |
| 1020 | else |
| 1021 | stream_ << "VERBOSE" << -severity_; |
| 1022 |
| 1023 | stream_ << ":" << filename << "(" << line << ")] "; |
| 1024 |
| 1025 | message_start_ = stream_.str().length(); |
| 1026 | } |
| 1027 |
| 1028 | #if defined(OS_WIN) |
| 1029 | // This has already been defined in the header, but defining it again as DWORD |
| 1030 | // ensures that the type used in the header is equivalent to DWORD. If not, |
| 1031 | // the redefinition is a compile error. |
| 1032 | typedef DWORD SystemErrorCode; |
| 1033 | #endif |
| 1034 |
| 1035 | SystemErrorCode GetLastSystemErrorCode() { |
| 1036 | #if defined(OS_WIN) |
| 1037 | return ::GetLastError(); |
| 1038 | #elif defined(OS_POSIX) || defined(OS_FUCHSIA) |
| 1039 | return errno; |
| 1040 | #endif |
| 1041 | } |
| 1042 |
| 1043 | BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code) { |
| 1044 | #if defined(OS_WIN) |
| 1045 | const int kErrorMessageBufferSize = 256; |
| 1046 | char msgbuf[kErrorMessageBufferSize]; |
| 1047 | DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS; |
| 1048 | DWORD len = FormatMessageA(flags, nullptr, error_code, 0, msgbuf, |
| 1049 | base::size(msgbuf), nullptr); |
| 1050 | if (len) { |
| 1051 | // Messages returned by system end with line breaks. |
| 1052 | return base::CollapseWhitespaceASCII(msgbuf, true) + |
| 1053 | base::StringPrintf(" (0x%lX)", error_code); |
| 1054 | } |
| 1055 | return base::StringPrintf("Error (0x%lX) while retrieving error. (0x%lX)", |
| 1056 | GetLastError(), error_code); |
| 1057 | #elif defined(OS_POSIX) || defined(OS_FUCHSIA) |
| 1058 | return base::safe_strerror(error_code) + |
| 1059 | base::StringPrintf(" (%d)", error_code); |
| 1060 | #endif // defined(OS_WIN) |
| 1061 | } |
| 1062 |
| 1063 |
| 1064 | #if defined(OS_WIN) |
| 1065 | Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file, |
| 1066 | int line, |
| 1067 | LogSeverity severity, |
| 1068 | SystemErrorCode err) |
| 1069 | : err_(err), |
| 1070 | log_message_(file, line, severity) { |
| 1071 | } |
| 1072 |
| 1073 | Win32ErrorLogMessage::~Win32ErrorLogMessage() { |
| 1074 | stream() << ": " << SystemErrorCodeToString(err_); |
| 1075 | // We're about to crash (CHECK). Put |err_| on the stack (by placing it in a |
| 1076 | // field) and use Alias in hopes that it makes it into crash dumps. |
| 1077 | DWORD last_error = err_; |
| 1078 | base::debug::Alias(&last_error); |
| 1079 | } |
| 1080 | #elif defined(OS_POSIX) || defined(OS_FUCHSIA) |
| 1081 | ErrnoLogMessage::ErrnoLogMessage(const char* file, |
| 1082 | int line, |
| 1083 | LogSeverity severity, |
| 1084 | SystemErrorCode err) |
| 1085 | : err_(err), |
| 1086 | log_message_(file, line, severity) { |
| 1087 | } |
| 1088 |
| 1089 | ErrnoLogMessage::~ErrnoLogMessage() { |
| 1090 | stream() << ": " << SystemErrorCodeToString(err_); |
| 1091 | // We're about to crash (CHECK). Put |err_| on the stack (by placing it in a |
| 1092 | // field) and use Alias in hopes that it makes it into crash dumps. |
| 1093 | int last_error = err_; |
| 1094 | base::debug::Alias(&last_error); |
| 1095 | } |
| 1096 | #endif // defined(OS_WIN) |
| 1097 |
| 1098 | void CloseLogFile() { |
| 1099 | #if defined(OS_POSIX) || defined(OS_FUCHSIA) |
| 1100 | LoggingLock logging_lock; |
| 1101 | #endif |
| 1102 | CloseLogFileUnlocked(); |
| 1103 | } |
| 1104 |
| 1105 | #if defined(OS_CHROMEOS) |
| 1106 | FILE* DuplicateLogFILE() { |
| 1107 | if ((g_logging_destination & LOG_TO_FILE) == 0 || !InitializeLogFileHandle()) |
| 1108 | return nullptr; |
| 1109 |
| 1110 | int log_fd = fileno(g_log_file); |
| 1111 | if (log_fd == -1) |
| 1112 | return nullptr; |
| 1113 | base::ScopedFD dup_fd(dup(log_fd)); |
| 1114 | if (dup_fd == -1) |
| 1115 | return nullptr; |
| 1116 | FILE* duplicate = fdopen(dup_fd.get(), "a"); |
| 1117 | if (!duplicate) |
| 1118 | return nullptr; |
| 1119 | ignore_result(dup_fd.release()); |
| 1120 | return duplicate; |
| 1121 | } |
| 1122 | #endif |
| 1123 |
| 1124 | void RawLog(int level, const char* message) { |
| 1125 | if (level >= g_min_log_level && message) { |
| 1126 | size_t bytes_written = 0; |
| 1127 | const size_t message_len = strlen(message); |
| 1128 | int rv; |
| 1129 | while (bytes_written < message_len) { |
| 1130 | rv = HANDLE_EINTR( |
| 1131 | write(STDERR_FILENO, message + bytes_written, |
| 1132 | message_len - bytes_written)); |
| 1133 | if (rv < 0) { |
| 1134 | // Give up, nothing we can do now. |
| 1135 | break; |
| 1136 | } |
| 1137 | bytes_written += rv; |
| 1138 | } |
| 1139 |
| 1140 | if (message_len > 0 && message[message_len - 1] != '\n') { |
| 1141 | do { |
| 1142 | rv = HANDLE_EINTR(write(STDERR_FILENO, "\n", 1)); |
| 1143 | if (rv < 0) { |
| 1144 | // Give up, nothing we can do now. |
| 1145 | break; |
| 1146 | } |
| 1147 | } while (rv != 1); |
| 1148 | } |
| 1149 | } |
| 1150 |
| 1151 | if (level == LOG_FATAL) |
| 1152 | base::debug::BreakDebugger(); |
| 1153 | } |
| 1154 |
| 1155 | // This was defined at the beginning of this file. |
| 1156 | #undef write |
| 1157 |
| 1158 | #if defined(OS_WIN) |
| 1159 | bool IsLoggingToFileEnabled() { |
| 1160 | return g_logging_destination & LOG_TO_FILE; |
| 1161 | } |
| 1162 |
| 1163 | std::wstring GetLogFileFullPath() { |
| 1164 | if (g_log_file_name) |
| 1165 | return *g_log_file_name; |
| 1166 | return std::wstring(); |
| 1167 | } |
| 1168 | #endif |
| 1169 |
| 1170 | BASE_EXPORT void LogErrorNotReached(const char* file, int line) { |
| 1171 | LogMessage(file, line, LOG_ERROR).stream() |
| 1172 | << "NOTREACHED() hit."; |
| 1173 | } |
| 1174 |
| 1175 | } // namespace logging |
| 1176 |
| 1177 | std::ostream& std::operator<<(std::ostream& out, const wchar_t* wstr) { |
| 1178 | return out << (wstr ? base::WideToUTF8(wstr) : std::string()); |
| 1179 | } |
| 1180 |