#include "base/logging.h"
#ifdef BASE_CHECK_H_
#error "logging.h should not include check.h"
#endif
#include <limits.h>
#include <stdint.h>
#include <atomic>
#include <memory>
#include <tuple>
#include <vector>
#include "base/base_export.h"
#include "base/debug/crash_logging.h"
#include "base/immediate_crash.h"
#include "base/pending_task.h"
#include "base/process/process_handle.h"
#include "base/strings/string_piece.h"
#include "base/task/common/task_annotator.h"
#include "base/trace_event/base_tracing.h"
#include "build/build_config.h"
#if !BUILDFLAG(IS_NACL)
#include "base/auto_reset.h"
#include "base/debug/crash_logging.h"
#endif
#if defined(LEAK_SANITIZER) && !BUILDFLAG(IS_NACL)
#include "base/debug/leak_annotations.h"
#endif
#if BUILDFLAG(IS_WIN)
#include <io.h>
#include <windows.h>
typedef HANDLE FileHandle;
#define write(fd, buf, count) _write(fd, buf, static_cast<unsigned int>(count))
#define STDERR_FILENO 2
#elif BUILDFLAG(IS_APPLE)
#include <CoreFoundation/CoreFoundation.h>
#include <mach-o/dyld.h>
#include <mach/mach.h>
#include <mach/mach_time.h>
#include <os/log.h>
#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
#if BUILDFLAG(IS_NACL)
#include <sys/time.h>
#endif
#include <time.h>
#endif
#if BUILDFLAG(IS_FUCHSIA)
#include "base/fuchsia/scoped_fx_logger.h"
#endif
#if BUILDFLAG(IS_ANDROID)
#include <android/log.h>
#endif
#if BUILDFLAG(IS_OHOS)
#include "hilog_adapter.h"
#endif
#if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
#include <errno.h>
#include <paths.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#define MAX_PATH PATH_MAX
typedef FILE* FileHandle;
#endif
#include <algorithm>
#include <cstring>
#include <ctime>
#include <iomanip>
#include <ostream>
#include <string>
#include <utility>
#include "base/base_switches.h"
#include "base/command_line.h"
#include "base/containers/stack.h"
#include "base/debug/alias.h"
#include "base/debug/debugger.h"
#include "base/debug/stack_trace.h"
#include "base/debug/task_trace.h"
#include "base/functional/callback.h"
#include "base/no_destructor.h"
#include "base/path_service.h"
#include "base/posix/eintr_wrapper.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/sys_string_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/synchronization/lock.h"
#include "base/test/scoped_logging_settings.h"
#include "base/threading/platform_thread.h"
#include "base/vlog.h"
#include "build/chromeos_buildflags.h"
#if BUILDFLAG(IS_WIN)
#include "base/win/win_util.h"
#endif
#if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
#include "base/posix/safe_strerror.h"
#endif
#if BUILDFLAG(IS_CHROMEOS_ASH)
#include "base/files/scoped_file.h"
#endif
namespace logging {
namespace {
int g_min_log_level = 0;
#if BUILDFLAG(USE_RUNTIME_VLOG)
std::atomic<VlogInfo*> g_vlog_info = nullptr;
VlogInfo* GetVlogInfo() {
return g_vlog_info.load(std::memory_order_acquire);
}
bool InitializeVlogInfo(VlogInfo* vlog_info) {
VlogInfo* previous_vlog_info = nullptr;
return g_vlog_info.compare_exchange_strong(previous_vlog_info, vlog_info);
}
VlogInfo* ExchangeVlogInfo(VlogInfo* vlog_info) {
return g_vlog_info.exchange(vlog_info);
}
std::unique_ptr<VlogInfo> VlogInfoFromCommandLine() {
if (!base::CommandLine::InitializedForCurrentProcess())
return nullptr;
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
if (!command_line->HasSwitch(switches::kV) &&
!command_line->HasSwitch(switches::kVModule)) {
return nullptr;
}
#if defined(LEAK_SANITIZER) && !BUILDFLAG(IS_NACL)
ScopedLeakSanitizerDisabler lsan_disabler;
#endif
return std::make_unique<VlogInfo>(
command_line->GetSwitchValueASCII(switches::kV),
command_line->GetSwitchValueASCII(switches::kVModule), &g_min_log_level);
}
void MaybeInitializeVlogInfo() {
if (base::CommandLine::InitializedForCurrentProcess()) {
std::unique_ptr<VlogInfo> vlog_info = VlogInfoFromCommandLine();
if (vlog_info) {
if (InitializeVlogInfo(vlog_info.get())) {
vlog_info.release();
}
}
}
}
#endif
#if !BUILDFLAG(USE_RUNTIME_VLOG) && DCHECK_IS_ON()
void MaybeWarnVmodule() {
if (base::CommandLine::InitializedForCurrentProcess()) {
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kV) ||
command_line->HasSwitch(switches::kVModule)) {
LOG(WARNING)
<< "--" << switches::kV << " and --" << switches::kVModule
<< " are currently ignored. See comments in base/logging.h on "
"proper usage of USE_RUNTIME_VLOG.";
}
}
}
#endif
#if !BUILDFLAG(IS_OHOS)
const char* const log_severity_names[] = {"INFO", "WARNING", "ERROR", "FATAL", "DEBUG"};
static_assert(LOGGING_NUM_SEVERITIES == std::size(log_severity_names),
"Incorrect number of log_severity_names");
const char* log_severity_name(int severity) {
if (severity >= 0 && severity < LOGGING_NUM_SEVERITIES)
return log_severity_names[severity];
return "UNKNOWN";
}
#endif
uint32_t g_logging_destination = LOG_DEFAULT;
#if BUILDFLAG(IS_CHROMEOS)
LogFormat g_log_format = LogFormat::LOG_FORMAT_SYSLOG;
#endif
#if BUILDFLAG(IS_FUCHSIA)
base::ScopedFxLogger& GetScopedFxLogger() {
static base::NoDestructor<base::ScopedFxLogger> logger;
return *logger;
}
#endif
const int kAlwaysPrintErrorLevel = LOGGING_ERROR;
using PathString = base::FilePath::StringType;
PathString* g_log_file_name = nullptr;
FileHandle g_log_file = nullptr;
bool g_log_process_id = false;
bool g_log_thread_id = false;
bool g_log_timestamp = true;
bool g_log_tickcount = false;
const char* g_log_prefix = nullptr;
bool show_error_dialogs = false;
base::stack<LogAssertHandlerFunction>& GetLogAssertHandlerStack() {
static base::NoDestructor<base::stack<LogAssertHandlerFunction>> instance;
return *instance;
}
LogMessageHandlerFunction g_log_message_handler = nullptr;
#if !BUILDFLAG(IS_OHOS)
uint64_t TickCount() {
#if BUILDFLAG(IS_WIN)
return GetTickCount();
#elif BUILDFLAG(IS_FUCHSIA)
return static_cast<uint64_t>(
zx_clock_get_monotonic() /
static_cast<zx_time_t>(base::Time::kNanosecondsPerMicrosecond));
#elif BUILDFLAG(IS_APPLE)
return mach_absolute_time();
#elif BUILDFLAG(IS_NACL)
return clock();
#elif BUILDFLAG(IS_POSIX)
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
uint64_t absolute_micro = static_cast<uint64_t>(ts.tv_sec) * 1000000 +
static_cast<uint64_t>(ts.tv_nsec) / 1000;
return absolute_micro;
#endif
}
#endif
void DeleteFilePath(const PathString& log_name) {
#if BUILDFLAG(IS_WIN)
DeleteFile(log_name.c_str());
#elif BUILDFLAG(IS_NACL)
#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
unlink(log_name.c_str());
#else
#error Unsupported platform
#endif
}
PathString GetDefaultLogFile() {
#if BUILDFLAG(IS_WIN)
wchar_t module_name[MAX_PATH];
GetModuleFileName(nullptr, module_name, MAX_PATH);
PathString log_name = module_name;
PathString::size_type last_backslash = log_name.rfind('\\', log_name.size());
if (last_backslash != PathString::npos)
log_name.erase(last_backslash + 1);
log_name += FILE_PATH_LITERAL("debug.log");
return log_name;
#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
return PathString("debug.log");
#endif
}
#if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
base::Lock& GetLoggingLock() {
static base::NoDestructor<base::Lock> lock;
return *lock;
}
#endif
bool InitializeLogFileHandle() {
if (g_log_file)
return true;
if (!g_log_file_name) {
g_log_file_name = new PathString(GetDefaultLogFile());
}
if ((g_logging_destination & LOG_TO_FILE) == 0)
return true;
#if BUILDFLAG(IS_WIN)
g_log_file = CreateFile(g_log_file_name->c_str(), FILE_APPEND_DATA,
FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
if (g_log_file == INVALID_HANDLE_VALUE || g_log_file == nullptr) {
wchar_t system_buffer[MAX_PATH];
system_buffer[0] = 0;
DWORD len = ::GetCurrentDirectory(std::size(system_buffer), system_buffer);
if (len == 0 || len > std::size(system_buffer))
return false;
*g_log_file_name = system_buffer;
if (g_log_file_name->back() != L'\\')
*g_log_file_name += FILE_PATH_LITERAL("\\");
*g_log_file_name += FILE_PATH_LITERAL("debug.log");
g_log_file = CreateFile(g_log_file_name->c_str(), FILE_APPEND_DATA,
FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
if (g_log_file == INVALID_HANDLE_VALUE || g_log_file == nullptr) {
g_log_file = nullptr;
return false;
}
}
#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
g_log_file = fopen(g_log_file_name->c_str(), "a");
if (g_log_file == nullptr)
return false;
#else
#error Unsupported platform
#endif
return true;
}
void CloseFile(FileHandle log) {
#if BUILDFLAG(IS_WIN)
CloseHandle(log);
#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
fclose(log);
#else
#error Unsupported platform
#endif
}
void CloseLogFileUnlocked() {
if (!g_log_file)
return;
CloseFile(g_log_file);
g_log_file = nullptr;
if (!g_log_file_name)
g_logging_destination &= ~LOG_TO_FILE;
}
#if BUILDFLAG(IS_FUCHSIA)
inline FuchsiaLogSeverity LogSeverityToFuchsiaLogSeverity(
LogSeverity severity) {
switch (severity) {
case LOGGING_INFO:
return FUCHSIA_LOG_INFO;
case LOGGING_WARNING:
return FUCHSIA_LOG_WARNING;
case LOGGING_ERROR:
return FUCHSIA_LOG_ERROR;
case LOGGING_FATAL:
return FUCHSIA_LOG_ERROR;
}
if (severity > -3) {
return FUCHSIA_LOG_DEBUG;
}
return FUCHSIA_LOG_TRACE;
}
#endif
void WriteToFd(int fd, const char* data, size_t length) {
size_t bytes_written = 0;
long rv;
while (bytes_written < length) {
rv = HANDLE_EINTR(write(fd, data + bytes_written, length - bytes_written));
if (rv < 0) {
break;
}
bytes_written += static_cast<size_t>(rv);
}
}
void SetLogFatalCrashKey(LogMessage* log_message) {
#if !BUILDFLAG(IS_NACL)
static bool guarded = false;
if (guarded)
return;
base::AutoReset<bool> guard(&guarded, true);
static auto* const crash_key = base::debug::AllocateCrashKeyString(
"LOG_FATAL", base::debug::CrashKeySize::Size1024);
base::debug::SetCrashKeyString(crash_key, log_message->BuildCrashString());
#endif
}
std::string BuildCrashString(const char* file,
int line,
const char* message_without_prefix) {
if (file) {
const char* slash = strrchr(file,
#if BUILDFLAG(IS_WIN)
'\\'
#else
'/'
#endif
);
if (slash) {
file = slash + 1;
}
}
return base::StringPrintf("%s:%d: %s", file, line, message_without_prefix);
}
void traceLogMessage(const char* file, int line, const std::string& message) {
TRACE_EVENT_INSTANT("log", "LogMessage", [&](perfetto::EventContext ctx) {
perfetto::protos::pbzero::LogMessage* log = ctx.event()->set_log_message();
log->set_source_location_iid(base::trace_event::InternedSourceLocation::Get(
&ctx, base::trace_event::TraceSourceLocation(nullptr,
file, line)));
log->set_body_iid(
base::trace_event::InternedLogMessage::Get(&ctx, message));
});
}
}
#if BUILDFLAG(DCHECK_IS_CONFIGURABLE)
BASE_EXPORT logging::LogSeverity LOGGING_DCHECK = LOGGING_INFO;
#endif
std::ostream* g_swallow_stream;
bool BaseInitLoggingImpl(const LoggingSettings& settings) {
#if BUILDFLAG(IS_NACL)
CHECK_EQ(settings.logging_dest & ~(LOG_TO_SYSTEM_DEBUG_LOG | LOG_TO_STDERR),
0u);
#endif
#if BUILDFLAG(IS_CHROMEOS)
g_log_format = settings.log_format;
#endif
#if BUILDFLAG(USE_RUNTIME_VLOG)
MaybeInitializeVlogInfo();
#endif
#if !BUILDFLAG(USE_RUNTIME_VLOG) && DCHECK_IS_ON()
MaybeWarnVmodule();
#endif
g_logging_destination = settings.logging_dest;
#if BUILDFLAG(IS_FUCHSIA)
if (g_logging_destination & LOG_TO_SYSTEM_DEBUG_LOG) {
GetScopedFxLogger() = base::ScopedFxLogger::CreateForProcess();
}
#endif
if ((g_logging_destination & LOG_TO_FILE) == 0)
return true;
#if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
base::AutoLock guard(GetLoggingLock());
#endif
CloseLogFileUnlocked();
#if BUILDFLAG(IS_CHROMEOS_ASH)
if (settings.log_file) {
DCHECK(!settings.log_file_path);
g_log_file = settings.log_file;
return true;
}
#endif
DCHECK(settings.log_file_path) << "LOG_TO_FILE set but no log_file_path!";
if (!g_log_file_name)
g_log_file_name = new PathString();
*g_log_file_name = settings.log_file_path;
if (settings.delete_old == DELETE_OLD_LOG_FILE)
DeleteFilePath(*g_log_file_name);
return InitializeLogFileHandle();
}
void SetMinLogLevel(int level) {
g_min_log_level = std::min(LOGGING_FATAL, level);
}
int GetMinLogLevel() {
return g_min_log_level;
}
bool ShouldCreateLogMessage(int severity) {
if (severity < g_min_log_level)
return false;
return g_logging_destination != LOG_NONE || g_log_message_handler ||
severity >= kAlwaysPrintErrorLevel;
}
bool ShouldLogToStderr(int severity) {
if (g_logging_destination & LOG_TO_STDERR)
return true;
#if BUILDFLAG(IS_FUCHSIA)
return false;
#else
if (severity >= kAlwaysPrintErrorLevel)
return (g_logging_destination & ~LOG_TO_FILE) == LOG_NONE;
return false;
#endif
}
int GetVlogVerbosity() {
return std::max(-1, LOG_INFO - GetMinLogLevel());
}
int GetVlogLevelHelper(const char* file, size_t N) {
DCHECK_GT(N, 0U);
#if BUILDFLAG(USE_RUNTIME_VLOG)
VlogInfo* vlog_info = GetVlogInfo();
return vlog_info ?
vlog_info->GetVlogLevel(base::StringPiece(file, N - 1)) :
GetVlogVerbosity();
#else
return GetVlogVerbosity();
#endif
}
void SetLogItems(bool enable_process_id, bool enable_thread_id,
bool enable_timestamp, bool enable_tickcount) {
g_log_process_id = enable_process_id;
g_log_thread_id = enable_thread_id;
g_log_timestamp = enable_timestamp;
g_log_tickcount = enable_tickcount;
}
void SetLogPrefix(const char* prefix) {
DCHECK(!prefix ||
base::ContainsOnlyChars(prefix, "abcdefghijklmnopqrstuvwxyz"));
g_log_prefix = prefix;
}
void SetShowErrorDialogs(bool enable_dialogs) {
show_error_dialogs = enable_dialogs;
}
ScopedLogAssertHandler::ScopedLogAssertHandler(
LogAssertHandlerFunction handler) {
GetLogAssertHandlerStack().push(std::move(handler));
}
ScopedLogAssertHandler::~ScopedLogAssertHandler() {
GetLogAssertHandlerStack().pop();
}
void SetLogMessageHandler(LogMessageHandlerFunction handler) {
g_log_message_handler = handler;
}
LogMessageHandlerFunction GetLogMessageHandler() {
return g_log_message_handler;
}
#if defined(OHOS_LOGGER_REPORT)
LoggerCallbackFunction g_logger_callback = nullptr;
void SetLoggerCallbackToBase(LoggerCallbackFunction loggerCallback) {
g_logger_callback = loggerCallback;
}
bool IsEnableLoggerReport()
{
static bool is_enable = false;
if (is_enable) {
return true;
}
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
if (command_line == nullptr) {
return false;
}
if (command_line->HasSwitch(switches::kEnableLoggerReport)) {
is_enable = true;
return true;
}
return false;
}
#endif
#if !defined(NDEBUG)
void DisplayDebugMessageInDialog(const std::string& str) {
if (str.empty())
return;
if (!show_error_dialogs)
return;
#if BUILDFLAG(IS_WIN)
if (base::win::IsUser32AndGdi32Available()) {
MessageBoxW(nullptr, base::as_wcstr(base::UTF8ToUTF16(str)), L"Fatal error",
MB_OK | MB_ICONHAND | MB_TOPMOST);
} else {
OutputDebugStringW(base::as_wcstr(base::UTF8ToUTF16(str)));
}
#endif
}
#endif
LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
: severity_(severity), file_(file), line_(line) {
Init(file, line);
}
LogMessage::LogMessage(const char* file, int line, const char* condition)
: severity_(LOGGING_FATAL), file_(file), line_(line) {
Init(file, line);
stream_ << "Check failed: " << condition << ". ";
}
#if defined(OHOS_LOGGER_REPORT)
LogMessage::LogMessage(const char* file, int line, LogSeverity severity, LogPriority priority)
: severity_(severity), file_(file), line_(line), priority_(priority) {
Init(file, line);
}
#endif
#if defined(OHOS_LOGGER_REPORT)
NO_SANITIZE("cfi-icall")
#endif
LogMessage::~LogMessage() {
size_t stack_start = stream_.str().length();
#if !defined(OFFICIAL_BUILD) && !BUILDFLAG(IS_NACL) && !defined(__UCLIBC__) && \
!BUILDFLAG(IS_AIX)
if (severity_ == LOGGING_FATAL && !base::debug::BeingDebugged()) {
base::debug::StackTrace stack_trace;
stream_ << std::endl;
stack_trace.OutputToStream(&stream_);
base::debug::TaskTrace task_trace;
if (!task_trace.empty())
task_trace.OutputToStream(&stream_);
const auto* task = base::TaskAnnotator::CurrentTaskForThread();
if (task && task->ipc_hash) {
stream_ << "IPC message handler context: "
<< base::StringPrintf("0x%08X", task->ipc_hash) << std::endl;
}
base::debug::OutputCrashKeysToStream(stream_);
}
#endif
stream_ << std::endl;
std::string str_newline(stream_.str());
traceLogMessage(
file_, line_,
std::string(base::StringPiece(str_newline).substr(message_start_)));
if (severity_ == LOGGING_FATAL
#if defined(OHOS_LOGGER_REPORT)
|| priority_ == PRIORITY_FATAL
#endif
)
SetLogFatalCrashKey(this);
if (g_log_message_handler &&
g_log_message_handler(severity_, file_, line_, message_start_,
str_newline)) {
return;
}
if ((g_logging_destination & LOG_TO_SYSTEM_DEBUG_LOG) != 0) {
#if BUILDFLAG(IS_WIN)
OutputDebugStringA(str_newline.c_str());
#elif BUILDFLAG(IS_APPLE)
const bool log_to_system = []() {
struct stat stderr_stat;
if (fstat(fileno(stderr), &stderr_stat) == -1) {
return true;
}
if (!S_ISCHR(stderr_stat.st_mode)) {
return false;
}
struct stat dev_null_stat;
if (stat(_PATH_DEVNULL, &dev_null_stat) == -1) {
return true;
}
return !S_ISCHR(dev_null_stat.st_mode) ||
stderr_stat.st_rdev == dev_null_stat.st_rdev;
}();
if (log_to_system) {
CFBundleRef main_bundle = CFBundleGetMainBundle();
CFStringRef main_bundle_id_cf =
main_bundle ? CFBundleGetIdentifier(main_bundle) : nullptr;
std::string main_bundle_id =
main_bundle_id_cf ? base::SysCFStringRefToUTF8(main_bundle_id_cf)
: std::string("");
const class OSLog {
public:
explicit OSLog(const char* subsystem)
: os_log_(subsystem ? os_log_create(subsystem, "chromium_logging")
: OS_LOG_DEFAULT) {}
OSLog(const OSLog&) = delete;
OSLog& operator=(const OSLog&) = delete;
~OSLog() {
if (os_log_ != OS_LOG_DEFAULT) {
os_release(os_log_);
}
}
os_log_t get() const { return os_log_; }
private:
os_log_t os_log_;
} log(main_bundle_id.empty() ? nullptr : main_bundle_id.c_str());
const os_log_type_t os_log_type = [](LogSeverity severity) {
switch (severity) {
case LOGGING_INFO:
return OS_LOG_TYPE_INFO;
case LOGGING_WARNING:
return OS_LOG_TYPE_DEFAULT;
case LOGGING_ERROR:
return OS_LOG_TYPE_ERROR;
case LOGGING_FATAL:
return OS_LOG_TYPE_FAULT;
case LOGGING_VERBOSE:
return OS_LOG_TYPE_DEBUG;
default:
return OS_LOG_TYPE_DEFAULT;
}
}(severity_);
os_log_with_type(log.get(), os_log_type, "%{public}s",
str_newline.c_str());
}
#elif BUILDFLAG(IS_ANDROID)
android_LogPriority priority =
(severity_ < 0) ? ANDROID_LOG_VERBOSE : ANDROID_LOG_UNKNOWN;
switch (severity_) {
case LOGGING_INFO:
priority = ANDROID_LOG_INFO;
break;
case LOGGING_WARNING:
priority = ANDROID_LOG_WARN;
break;
case LOGGING_ERROR:
priority = ANDROID_LOG_ERROR;
break;
case LOGGING_FATAL:
priority = ANDROID_LOG_FATAL;
break;
}
const char kAndroidLogTag[] = "chromium";
#if DCHECK_IS_ON()
std::vector<std::string> lines = base::SplitString(
str_newline, "\n", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL);
lines.pop_back();
for (const auto& line : lines)
__android_log_write(priority, kAndroidLogTag, line.c_str());
#else
__android_log_write(priority, kAndroidLogTag, str_newline.c_str());
#endif
#elif BUILDFLAG(IS_OHOS)
#if defined(OHOS_LOGGER_REPORT)
if ((severity_ == LOGGING_FEEDBACK || severity_ == LOGGING_URL) &&
IsEnableLoggerReport() && g_logger_callback != nullptr) {
LogSeverity policys = LOGGING_VERBOSE;
switch (severity_) {
case LOGGING_FEEDBACK:
policys = LOGGING_FEEDBACK;
break;
case LOGGING_URL:
policys = LOGGING_URL;
priority_ = PRIORITY_INFO;
break;
}
g_logger_callback(priority_, ohos_tag_, policys, str_newline);
return;
}
#endif
auto priority = (severity_ < 0) ? OHOS::NWeb::LogLevelAdapter::DEBUG
: OHOS::NWeb::LogLevelAdapter::LEVEL_MAX;
switch (severity_) {
case LOGGING_INFO:
priority = OHOS::NWeb::LogLevelAdapter::INFO;
break;
case LOGGING_WARNING:
priority = OHOS::NWeb::LogLevelAdapter::WARN;
break;
case LOGGING_ERROR:
priority = OHOS::NWeb::LogLevelAdapter::ERROR;
break;
case LOGGING_FATAL:
priority = OHOS::NWeb::LogLevelAdapter::FATAL;
break;
case LOGGING_DEBUG:
priority = OHOS::NWeb::LogLevelAdapter::DEBUG;
}
OHOS::NWeb::HiLogAdapter::PrintLog(priority, tag_.c_str(), "%{public}s", str_newline.c_str());
#elif BUILDFLAG(IS_FUCHSIA)
const auto message = base::StringPiece(str_newline).substr(message_start_);
GetScopedFxLogger().LogMessage(file_, static_cast<uint32_t>(line_),
message.substr(0, message.size() - 1),
LogSeverityToFuchsiaLogSeverity(severity_));
#endif
}
if (ShouldLogToStderr(severity_)) {
WriteToFd(STDERR_FILENO, str_newline.data(), str_newline.size());
}
if ((g_logging_destination & LOG_TO_FILE) != 0) {
#if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
base::AutoLock guard(GetLoggingLock());
#endif
if (InitializeLogFileHandle()) {
#if BUILDFLAG(IS_WIN)
DWORD num_written;
WriteFile(g_log_file,
static_cast<const void*>(str_newline.c_str()),
static_cast<DWORD>(str_newline.length()),
&num_written,
nullptr);
#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
std::ignore =
fwrite(str_newline.data(), str_newline.size(), 1, g_log_file);
fflush(g_log_file);
#else
#error Unsupported platform
#endif
}
}
if (severity_ == LOGGING_FATAL) {
char str_stack[1024];
base::strlcpy(str_stack, str_newline.data(), std::size(str_stack));
base::debug::Alias(&str_stack);
if (!GetLogAssertHandlerStack().empty()) {
LogAssertHandlerFunction log_assert_handler =
GetLogAssertHandlerStack().top();
if (log_assert_handler) {
log_assert_handler.Run(
file_, line_,
base::StringPiece(str_newline.c_str() + message_start_,
stack_start - message_start_),
base::StringPiece(str_newline.c_str() + stack_start));
}
} else {
#ifndef NDEBUG
if (!base::debug::BeingDebugged()) {
DisplayDebugMessageInDialog(stream_.str());
}
#endif
base::ImmediateCrash();
}
}
}
std::string LogMessage::BuildCrashString() const {
return logging::BuildCrashString(file(), line(),
str().c_str() + message_start_);
}
void LogMessage::Init(const char* file, int line) {
#if BUILDFLAG(IS_OHOS)
base::StringPiece filename;
base::StringPiece message(file);
size_t tagStart = message.find_first_of('#');
if (tagStart == base::StringPiece::npos) {
tag_ = std::string("chromium");
filename = message;
#ifdef OHOS_LOGGER_REPORT
ohos_tag_ = std::string("mainprocess");
#endif
} else {
tag_ = std::string(message.substr(0, tagStart));
#ifdef OHOS_LOGGER_REPORT
ohos_tag_ = std::string(message.substr(0, tagStart));
#endif
filename = message.substr(tagStart + 1, message.size() - tagStart);
}
#else
base::StringPiece filename(file);
#endif
size_t last_slash_pos = filename.find_last_of("\\/");
if (last_slash_pos != base::StringPiece::npos)
filename.remove_prefix(last_slash_pos + 1);
#if BUILDFLAG(IS_CHROMEOS)
if (g_log_format == LogFormat::LOG_FORMAT_SYSLOG) {
InitWithSyslogPrefix(
filename, line, TickCount(), log_severity_name(severity_), g_log_prefix,
g_log_process_id, g_log_thread_id, g_log_timestamp, g_log_tickcount);
} else
#endif
{
stream_ << '[';
#if !BUILDFLAG(IS_OHOS)
if (g_log_prefix)
stream_ << g_log_prefix << ':';
if (g_log_process_id)
stream_ << base::GetUniqueIdForProcess() << ':';
if (g_log_thread_id)
stream_ << base::PlatformThread::CurrentId() << ':';
if (g_log_timestamp) {
#if BUILDFLAG(IS_WIN)
SYSTEMTIME local_time;
GetLocalTime(&local_time);
stream_ << std::setfill('0')
<< std::setw(2) << local_time.wMonth
<< std::setw(2) << local_time.wDay
<< '/'
<< std::setw(2) << local_time.wHour
<< std::setw(2) << local_time.wMinute
<< std::setw(2) << local_time.wSecond
<< '.'
<< std::setw(3) << local_time.wMilliseconds
<< ':';
#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
timeval tv;
gettimeofday(&tv, nullptr);
time_t t = tv.tv_sec;
struct tm local_time;
localtime_r(&t, &local_time);
struct tm* tm_time = &local_time;
stream_ << std::setfill('0')
<< std::setw(2) << 1 + tm_time->tm_mon
<< std::setw(2) << tm_time->tm_mday
<< '/'
<< std::setw(2) << tm_time->tm_hour
<< std::setw(2) << tm_time->tm_min
<< std::setw(2) << tm_time->tm_sec
<< '.'
<< std::setw(6) << tv.tv_usec
<< ':';
#else
#error Unsupported platform
#endif
}
if (g_log_tickcount)
stream_ << TickCount() << ':';
if (severity_ >= 0) {
stream_ << log_severity_name(severity_);
} else {
stream_ << "VERBOSE" << -severity_;
}
stream_ << ":" << filename << "(" << line << ")] ";
#else
stream_ << filename << ":" << line << "] ";
#endif
}
message_start_ = stream_.str().length();
}
#if BUILDFLAG(IS_WIN)
typedef DWORD SystemErrorCode;
#endif
SystemErrorCode GetLastSystemErrorCode() {
#if BUILDFLAG(IS_WIN)
return ::GetLastError();
#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
return errno;
#endif
}
BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code) {
#if BUILDFLAG(IS_WIN)
const int kErrorMessageBufferSize = 256;
char msgbuf[kErrorMessageBufferSize];
DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
DWORD len = FormatMessageA(flags, nullptr, error_code, 0, msgbuf,
std::size(msgbuf), nullptr);
if (len) {
return base::CollapseWhitespaceASCII(msgbuf, true) +
base::StringPrintf(" (0x%lX)", error_code);
}
return base::StringPrintf("Error (0x%lX) while retrieving error. (0x%lX)",
GetLastError(), error_code);
#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
return base::safe_strerror(error_code) +
base::StringPrintf(" (%d)", error_code);
#endif
}
#if BUILDFLAG(IS_WIN)
Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
int line,
LogSeverity severity,
SystemErrorCode err)
: LogMessage(file, line, severity), err_(err) {}
Win32ErrorLogMessage::~Win32ErrorLogMessage() {
stream() << ": " << SystemErrorCodeToString(err_);
DWORD last_error = err_;
base::debug::Alias(&last_error);
}
#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
ErrnoLogMessage::ErrnoLogMessage(const char* file,
int line,
LogSeverity severity,
SystemErrorCode err)
: LogMessage(file, line, severity), err_(err) {}
ErrnoLogMessage::~ErrnoLogMessage() {
stream() << ": " << SystemErrorCodeToString(err_);
int last_error = err_;
base::debug::Alias(&last_error);
}
#endif
void CloseLogFile() {
#if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
base::AutoLock guard(GetLoggingLock());
#endif
CloseLogFileUnlocked();
}
#if BUILDFLAG(IS_CHROMEOS_ASH)
FILE* DuplicateLogFILE() {
if ((g_logging_destination & LOG_TO_FILE) == 0 || !InitializeLogFileHandle())
return nullptr;
int log_fd = fileno(g_log_file);
if (log_fd == -1)
return nullptr;
base::ScopedFD dup_fd(dup(log_fd));
if (dup_fd == -1)
return nullptr;
FILE* duplicate = fdopen(dup_fd.get(), "a");
if (!duplicate)
return nullptr;
std::ignore = dup_fd.release();
return duplicate;
}
#endif
ScopedLoggingSettings::ScopedLoggingSettings()
: min_log_level_(g_min_log_level),
logging_destination_(g_logging_destination),
#if BUILDFLAG(IS_CHROMEOS)
log_format_(g_log_format),
#endif
enable_process_id_(g_log_process_id),
enable_thread_id_(g_log_thread_id),
enable_timestamp_(g_log_timestamp),
enable_tickcount_(g_log_tickcount),
log_prefix_(g_log_prefix),
message_handler_(g_log_message_handler) {
if (g_log_file_name)
log_file_name_ = std::make_unique<PathString>(*g_log_file_name);
if (g_log_file) {
CHECK(g_log_file_name) << "Un-named |log_file| is not supported.";
CloseLogFileUnlocked();
}
}
ScopedLoggingSettings::~ScopedLoggingSettings() {
CHECK(InitLogging({
.logging_dest = logging_destination_,
.log_file_path = log_file_name_ ? log_file_name_->data() : nullptr,
#if BUILDFLAG(IS_CHROMEOS)
.log_format = log_format_
#endif
})) << "~ScopedLoggingSettings() failed to restore settings.";
SetMinLogLevel(min_log_level_);
SetLogItems(enable_process_id_, enable_thread_id_, enable_timestamp_,
enable_tickcount_);
SetLogPrefix(log_prefix_);
SetLogMessageHandler(message_handler_);
}
#if BUILDFLAG(IS_CHROMEOS)
void ScopedLoggingSettings::SetLogFormat(LogFormat log_format) const {
g_log_format = log_format;
}
#endif
void RawLog(int level, const char* message) {
if (level >= g_min_log_level && message) {
const size_t message_len = strlen(message);
WriteToFd(STDERR_FILENO, message, message_len);
if (message_len > 0 && message[message_len - 1] != '\n') {
long rv;
do {
rv = HANDLE_EINTR(write(STDERR_FILENO, "\n", 1));
if (rv < 0) {
break;
}
} while (rv != 1);
}
}
if (level == LOGGING_FATAL)
base::ImmediateCrash();
}
#undef write
#if BUILDFLAG(IS_WIN)
bool IsLoggingToFileEnabled() {
return g_logging_destination & LOG_TO_FILE;
}
std::wstring GetLogFileFullPath() {
if (g_log_file_name)
return *g_log_file_name;
return std::wstring();
}
#endif
#if !BUILDFLAG(USE_RUNTIME_VLOG)
int GetDisableAllVLogLevel() {
return -1;
}
#endif
ScopedVmoduleSwitches::ScopedVmoduleSwitches() = default;
#if BUILDFLAG(USE_RUNTIME_VLOG)
VlogInfo* ScopedVmoduleSwitches::CreateVlogInfoWithSwitches(
const std::string& vmodule_switch) {
MaybeInitializeVlogInfo();
VlogInfo* base_vlog_info = GetVlogInfo();
if (!base_vlog_info) {
return new VlogInfo("", vmodule_switch, &g_min_log_level);
}
return base_vlog_info->WithSwitches(vmodule_switch);
}
void ScopedVmoduleSwitches::InitWithSwitches(
const std::string& vmodule_switch) {
CHECK(!scoped_vlog_info_);
{
#if defined(LEAK_SANITIZER) && !BUILDFLAG(IS_NACL)
ScopedLeakSanitizerDisabler lsan_disabler;
#endif
scoped_vlog_info_ = CreateVlogInfoWithSwitches(vmodule_switch);
}
previous_vlog_info_ = ExchangeVlogInfo(scoped_vlog_info_);
}
ScopedVmoduleSwitches::~ScopedVmoduleSwitches() {
VlogInfo* replaced_vlog_info = ExchangeVlogInfo(previous_vlog_info_);
CHECK_EQ(replaced_vlog_info, scoped_vlog_info_);
}
#else
void ScopedVmoduleSwitches::InitWithSwitches(
const std::string& vmodule_switch) {}
ScopedVmoduleSwitches::~ScopedVmoduleSwitches() = default;
#endif
}
std::ostream& std::operator<<(std::ostream& out, const wchar_t* wstr) {
return out << (wstr ? base::WStringPiece(wstr) : base::WStringPiece());
}
std::ostream& std::operator<<(std::ostream& out, const std::wstring& wstr) {
return out << base::WStringPiece(wstr);
}
std::ostream& std::operator<<(std::ostream& out, const char16_t* str16) {
return out << (str16 ? base::StringPiece16(str16) : base::StringPiece16());
}
std::ostream& std::operator<<(std::ostream& out, const std::u16string& str16) {
return out << base::StringPiece16(str16);
}