简单串一下浏览器启动的整个流程. 这样可以将 chromium 的框架串起来, 作者志大才疏, 有写的不好地方还请指出.
Chromium 的入口文件设计是不同系统有各自的入口文件, 最终都会汇总到统一的核心启动逻辑:
这个最短:
该文件仅用于 Linux 等类 Unix 系统, 是基于 Aura 界面框架的入口实现, 其核心是直接调用 ChromeMain(argc, argv), 无需中间 DLL 加载层, 与 Windows 需通过 chrome.dll 启动的逻辑完全不同.
贴出主要部分:
主要是在通过 dlopen 动态加载框架, 从加载的框架中查找并调用 ChromeMain 函数, 传入命令行参数, 最终通过 exit 退出以保证栈回溯完整性
只贴出主要的 main 函数:
初始化命令行, 设置工作目录, 各种奔溃处理..., 实际上是 loader->Launch 在进一步加载, 进入 chrome\app\main_dll_loader_win.cc:
仍然是用进入 ChromeMain 函数.
又是各种乱七八糟的不同平台的参数处理, 初始化等等, 值得注意的是在这里处理了无头模式, 然后调用 ContentMain 进一步启动, 来到 content\public\app\content_main.h:
在跟入默认实现 content\app\content_main.cc:
又是初始化一堆, 接着跟入 content_main_runner->Run, 来到 content\app\content_main_runner_impl.cc:
主进程启动时不携带 --type 参数, 则 process_type.empty() 是 true, 所以我们先不管子进程, 也就是 if (!process_type.empty()) 中的逻辑.
注册一下这三种进程的回调类:
这段代码, 初始化了 Mojo, 用于进程通信, 然后又初始化一大堆, 可以自己读读. 在跟入 RunBrowserProcessMain:
delegate->RunProcess 对一些平台做了些处理, 不太重要, 继续跟入 BrowserMain, 来到 content\browser\browser_main.cc:
这个就是生命周期控制函数,
首先看下 main_runner->Initialize, 跟入, 来到 content\browser\browser_main_runner_impl.cc:
可以看到这里初始化一大堆, 什么 ui, font, skia..., 再跟入 main_runner->Run:
在跟入 RunMainMessageLoop:
不管三七二十一, 跟入 main_run_loop->Run, 来到了 base\task\sequence_manager\thread_controller_with_message_pump_impl.cc:
在跟入 pump_->Run, 发现不同平台还是有不同的实现:

我们看 base\message_loop\message_pump_default.cc 中的:
大体上就是一套任务队列机制, 所有任务(UI 事件, 网络回调, 延迟任务, 空闲任务等)最终都会被放入任务队列中, 消息泵循环的核心就是"从队列取任务→执行→再取"的循环, 这是整套机制的底层基础.
回到最开始 ContentMainRunnerImpl::Run, 还记得有一个主进程子进程的分流吗, 我们从这里开始看, 跟人 RunOtherNamedProcessTypeMain 来到 content\app\content_main_runner_impl.cc:
一个个来看.
仍然是启动子进程加入消息队列. 等待主进程派发任务.
好了, 到此为止吧.
#include "build/build_config.h"
extern "C" {
int ChromeMain(int argc, const char** argv);
}
int main(int argc, const char** argv) {
return ChromeMain(argc, argv);
}
#include "build/build_config.h"
extern "C" {
int ChromeMain(int argc, const char** argv);
}
int main(int argc, const char** argv) {
return ChromeMain(argc, argv);
}
__attribute__((visibility("default"))) int main(int argc, char* argv[]) {
partition_alloc::EarlyMallocZoneRegistration();
uint32_t exec_path_size = 0;
int rv = _NSGetExecutablePath(NULL, &exec_path_size);
if (rv != -1) {
FatalError("_NSGetExecutablePath: get length failed.");
}
std::unique_ptr<char[]> exec_path(new char[exec_path_size]);
rv = _NSGetExecutablePath(exec_path.get(), &exec_path_size);
if (rv != 0) {
FatalError("_NSGetExecutablePath: get path failed.");
}
#if defined(HELPER_EXECUTABLE) // 如果是辅助可执行程序(Helper)
sandbox::SeatbeltExecServer::CreateFromArgumentsResult seatbelt =
sandbox::SeatbeltExecServer::CreateFromArguments(exec_path.get(), argc,
argv);
if (seatbelt.sandbox_required) {
if (!seatbelt.server) {
FatalError("Failed to create seatbelt sandbox server.");
}
if (!seatbelt.server->InitializeSandbox()) {
FatalError("Failed to initialize sandbox.");
}
}
const char rel_path[] = "../../../../" PRODUCT_FULLNAME_STRING " Framework";
#else // 非辅助程序(主程序)
const char rel_path[] = "../Frameworks/" PRODUCT_FULLNAME_STRING
" Framework.framework/Versions/" CHROME_VERSION_STRING
"/" PRODUCT_FULLNAME_STRING " Framework";
#endif // defined(HELPER_EXECUTABLE)
const char* parent_dir = dirname(exec_path.get());
if (!parent_dir) {
FatalError("dirname %s: %s.", exec_path.get(), strerror(errno));
}
const size_t parent_dir_len = strlen(parent_dir);
const size_t rel_path_len = strlen(rel_path);
const size_t framework_path_size = parent_dir_len + rel_path_len + 2;
std::unique_ptr<char[]> framework_path(new char[framework_path_size]);
snprintf(framework_path.get(), framework_path_size, "%s/%s", parent_dir,
rel_path);
void* library =
dlopen(framework_path.get(), RTLD_LAZY | RTLD_LOCAL | RTLD_FIRST);
if (!library) {
FatalError("dlopen %s: %s.", framework_path.get(), dlerror());
}
const ChromeMainPtr chrome_main =
reinterpret_cast<ChromeMainPtr>(dlsym(library, "ChromeMain"));
if (!chrome_main) {
FatalError("dlsym ChromeMain: %s.", dlerror());
}
rv = chrome_main(argc, argv);
exit(rv);
}
__attribute__((visibility("default"))) int main(int argc, char* argv[]) {
partition_alloc::EarlyMallocZoneRegistration();
uint32_t exec_path_size = 0;
int rv = _NSGetExecutablePath(NULL, &exec_path_size);
if (rv != -1) {
FatalError("_NSGetExecutablePath: get length failed.");
}
std::unique_ptr<char[]> exec_path(new char[exec_path_size]);
rv = _NSGetExecutablePath(exec_path.get(), &exec_path_size);
if (rv != 0) {
FatalError("_NSGetExecutablePath: get path failed.");
}
#if defined(HELPER_EXECUTABLE) // 如果是辅助可执行程序(Helper)
sandbox::SeatbeltExecServer::CreateFromArgumentsResult seatbelt =
sandbox::SeatbeltExecServer::CreateFromArguments(exec_path.get(), argc,
argv);
if (seatbelt.sandbox_required) {
if (!seatbelt.server) {
FatalError("Failed to create seatbelt sandbox server.");
}
if (!seatbelt.server->InitializeSandbox()) {
FatalError("Failed to initialize sandbox.");
}
}
const char rel_path[] = "../../../../" PRODUCT_FULLNAME_STRING " Framework";
#else // 非辅助程序(主程序)
const char rel_path[] = "../Frameworks/" PRODUCT_FULLNAME_STRING
" Framework.framework/Versions/" CHROME_VERSION_STRING
"/" PRODUCT_FULLNAME_STRING " Framework";
#endif // defined(HELPER_EXECUTABLE)
const char* parent_dir = dirname(exec_path.get());
if (!parent_dir) {
FatalError("dirname %s: %s.", exec_path.get(), strerror(errno));
}
const size_t parent_dir_len = strlen(parent_dir);
const size_t rel_path_len = strlen(rel_path);
const size_t framework_path_size = parent_dir_len + rel_path_len + 2;
std::unique_ptr<char[]> framework_path(new char[framework_path_size]);
snprintf(framework_path.get(), framework_path_size, "%s/%s", parent_dir,
rel_path);
void* library =
dlopen(framework_path.get(), RTLD_LAZY | RTLD_LOCAL | RTLD_FIRST);
if (!library) {
FatalError("dlopen %s: %s.", framework_path.get(), dlerror());
}
const ChromeMainPtr chrome_main =
reinterpret_cast<ChromeMainPtr>(dlsym(library, "ChromeMain"));
if (!chrome_main) {
FatalError("dlsym ChromeMain: %s.", dlerror());
}
rv = chrome_main(argc, argv);
exit(rv);
}
#if !defined(WIN_CONSOLE_APP)
int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE prev, wchar_t*, int) {
#else // 控制台应用入口:main
int main() {
HINSTANCE instance = GetModuleHandle(nullptr);
#endif // !defined(WIN_CONSOLE_APP)
#if defined(ARCH_CPU_32_BITS)
enum class FiberStatus { kConvertFailed, kCreateFiberFailed, kSuccess };
FiberStatus fiber_status = FiberStatus::kSuccess;
DWORD fiber_error = ERROR_SUCCESS;
if (!::IsThreadAFiber()) {
constexpr size_t kStackSize = 4 * 1024 * 1024;
LPVOID original_fiber =
::ConvertThreadToFiberEx(nullptr, FIBER_FLAG_FLOAT_SWITCH);
if (original_fiber) {
FiberState fiber_state = {instance, original_fiber};
LPVOID big_stack_fiber = ::CreateFiberEx(
0, kStackSize, FIBER_FLAG_FLOAT_SWITCH, FiberBinder, &fiber_state);
if (big_stack_fiber) {
::SwitchToFiber(big_stack_fiber);
::DeleteFiber(big_stack_fiber);
::ConvertFiberToThread();
return fiber_state.fiber_result;
}
fiber_status = FiberStatus::kCreateFiberFailed;
} else {
fiber_status = FiberStatus::kConvertFailed;
}
fiber_error = ::GetLastError();
base::debug::Alias(&fiber_error);
}
#endif // defined(ARCH_CPU_32_BITS)
SetCwdForBrowserProcess();
install_static::InitializeFromPrimaryModule();
SignalInitializeCrashReporting();
if (IsBrowserProcess())
chrome::DisableDelayLoadFailureHooksForMainExecutable();
#if defined(ARCH_CPU_32_BITS)
CHECK_EQ(fiber_status, FiberStatus::kSuccess);
#endif // defined(ARCH_CPU_32_BITS)
base::EnableTerminationOnOutOfMemory();
logging::RegisterAbslAbortHook();
base::CommandLine::Init(0, nullptr);
const base::CommandLine* command_line =
base::CommandLine::ForCurrentProcess();
const std::string process_type =
command_line->GetSwitchValueASCII(switches::kProcessType);
#if !defined(COMPONENT_BUILD) && DCHECK_IS_ON()
base::FeatureList::FailOnFeatureAccessWithoutFeatureList();
base::debug::HandleHooks::AddIATPatch(CURRENT_MODULE());
#endif // !defined(COMPONENT_BUILD) && DCHECK_IS_ON()
DCHECK(process_type.empty() ||
HasValidWindowsPrefetchArgument(*command_line));
if (process_type == crash_reporter::switches::kCrashpadHandler) {
std::unique_ptr<ExitCodeWatcher> exit_code_watcher;
crash_reporter::SetupFallbackCrashHandling(*command_line);
if (!command_line->HasSwitch("no-periodic-tasks")) {
crashpad::InitialClientData initial_client_data;
if (initial_client_data.InitializeFromString(
command_line->GetSwitchValueASCII("initial-client-data"))) {
HANDLE duplicate_handle = INVALID_HANDLE_VALUE;
if (DuplicateHandle(
::GetCurrentProcess(), initial_client_data.client_process(),
::GetCurrentProcess(), &duplicate_handle,
PROCESS_QUERY_INFORMATION, FALSE, DUPLICATE_SAME_ACCESS)) {
base::Process parent_process(duplicate_handle);
exit_code_watcher = std::make_unique<ExitCodeWatcher>();
if (exit_code_watcher->Initialize(std::move(parent_process))) {
exit_code_watcher->StartWatching();
}
}
}
}
DCHECK(command_line->HasSwitch(switches::kUserDataDir));
base::FilePath user_data_dir =
command_line->GetSwitchValuePath(switches::kUserDataDir);
int crashpad_status = crash_reporter::RunAsCrashpadHandler(
*base::CommandLine::ForCurrentProcess(), user_data_dir,
switches::kProcessType, switches::kUserDataDir);
if (crashpad_status != 0 && exit_code_watcher) {
exit_code_watcher->StopWatching();
}
return crashpad_status;
}
else if (process_type == crash_reporter::switches::kFallbackCrashHandler) {
return RunFallbackCrashHandler(*command_line);
}
const base::TimeTicks exe_entry_point_ticks = base::TimeTicks::Now();
SignalChromeElf();
base::AtExitManager exit_manager;
if (AttemptFastNotify(*command_line))
return 0;
VLOG(1) << "About to load main DLL.";
MainDllLoader* loader = MakeMainDllLoader();
int rc = loader->Launch(instance, exe_entry_point_ticks);
loader->RelaunchChromeBrowserWithNewCommandLineIfNeeded();
delete loader;
if (process_type == switches::kUtilityProcess) {
base::Process::TerminateCurrentProcessImmediately(rc);
}
return rc;
}
#if !defined(WIN_CONSOLE_APP)
int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE prev, wchar_t*, int) {
#else // 控制台应用入口:main
int main() {
HINSTANCE instance = GetModuleHandle(nullptr);
#endif // !defined(WIN_CONSOLE_APP)
#if defined(ARCH_CPU_32_BITS)
enum class FiberStatus { kConvertFailed, kCreateFiberFailed, kSuccess };
FiberStatus fiber_status = FiberStatus::kSuccess;
DWORD fiber_error = ERROR_SUCCESS;
if (!::IsThreadAFiber()) {
constexpr size_t kStackSize = 4 * 1024 * 1024;
LPVOID original_fiber =
::ConvertThreadToFiberEx(nullptr, FIBER_FLAG_FLOAT_SWITCH);
if (original_fiber) {
FiberState fiber_state = {instance, original_fiber};
LPVOID big_stack_fiber = ::CreateFiberEx(
0, kStackSize, FIBER_FLAG_FLOAT_SWITCH, FiberBinder, &fiber_state);
if (big_stack_fiber) {
::SwitchToFiber(big_stack_fiber);
::DeleteFiber(big_stack_fiber);
::ConvertFiberToThread();
return fiber_state.fiber_result;
}
fiber_status = FiberStatus::kCreateFiberFailed;
} else {
fiber_status = FiberStatus::kConvertFailed;
}
fiber_error = ::GetLastError();
base::debug::Alias(&fiber_error);
}
#endif // defined(ARCH_CPU_32_BITS)
SetCwdForBrowserProcess();
install_static::InitializeFromPrimaryModule();
SignalInitializeCrashReporting();
if (IsBrowserProcess())
chrome::DisableDelayLoadFailureHooksForMainExecutable();
#if defined(ARCH_CPU_32_BITS)
CHECK_EQ(fiber_status, FiberStatus::kSuccess);
#endif // defined(ARCH_CPU_32_BITS)
base::EnableTerminationOnOutOfMemory();
logging::RegisterAbslAbortHook();
base::CommandLine::Init(0, nullptr);
const base::CommandLine* command_line =
base::CommandLine::ForCurrentProcess();
const std::string process_type =
command_line->GetSwitchValueASCII(switches::kProcessType);
#if !defined(COMPONENT_BUILD) && DCHECK_IS_ON()
base::FeatureList::FailOnFeatureAccessWithoutFeatureList();
base::debug::HandleHooks::AddIATPatch(CURRENT_MODULE());
#endif // !defined(COMPONENT_BUILD) && DCHECK_IS_ON()
DCHECK(process_type.empty() ||
HasValidWindowsPrefetchArgument(*command_line));
if (process_type == crash_reporter::switches::kCrashpadHandler) {
std::unique_ptr<ExitCodeWatcher> exit_code_watcher;
crash_reporter::SetupFallbackCrashHandling(*command_line);
if (!command_line->HasSwitch("no-periodic-tasks")) {
crashpad::InitialClientData initial_client_data;
if (initial_client_data.InitializeFromString(
command_line->GetSwitchValueASCII("initial-client-data"))) {
HANDLE duplicate_handle = INVALID_HANDLE_VALUE;
if (DuplicateHandle(
::GetCurrentProcess(), initial_client_data.client_process(),
::GetCurrentProcess(), &duplicate_handle,
PROCESS_QUERY_INFORMATION, FALSE, DUPLICATE_SAME_ACCESS)) {
base::Process parent_process(duplicate_handle);
exit_code_watcher = std::make_unique<ExitCodeWatcher>();
if (exit_code_watcher->Initialize(std::move(parent_process))) {
exit_code_watcher->StartWatching();
}
}
}
}
DCHECK(command_line->HasSwitch(switches::kUserDataDir));
base::FilePath user_data_dir =
command_line->GetSwitchValuePath(switches::kUserDataDir);
int crashpad_status = crash_reporter::RunAsCrashpadHandler(
*base::CommandLine::ForCurrentProcess(), user_data_dir,
switches::kProcessType, switches::kUserDataDir);
if (crashpad_status != 0 && exit_code_watcher) {
exit_code_watcher->StopWatching();
}
return crashpad_status;
}
else if (process_type == crash_reporter::switches::kFallbackCrashHandler) {
return RunFallbackCrashHandler(*command_line);
}
const base::TimeTicks exe_entry_point_ticks = base::TimeTicks::Now();
SignalChromeElf();
base::AtExitManager exit_manager;
if (AttemptFastNotify(*command_line))
return 0;
VLOG(1) << "About to load main DLL.";
MainDllLoader* loader = MakeMainDllLoader();
int rc = loader->Launch(instance, exe_entry_point_ticks);
loader->RelaunchChromeBrowserWithNewCommandLineIfNeeded();
delete loader;
if (process_type == switches::kUtilityProcess) {
base::Process::TerminateCurrentProcessImmediately(rc);
}
return rc;
}
int MainDllLoader::Launch(HINSTANCE instance,
base::TimeTicks exe_entry_point_ticks) {
const base::CommandLine& cmd_line = *base::CommandLine::ForCurrentProcess();
process_type_ = cmd_line.GetSwitchValueASCII(switches::kProcessType);
sandbox::SandboxInterfaceInfo sandbox_info = {nullptr};
const bool is_browser = process_type_.empty();
const bool is_sandboxed =
sandbox::policy::SandboxTypeFromCommandLine(cmd_line) !=
sandbox::mojom::Sandbox::kNoSandbox;
if (is_browser || is_sandboxed) {
content::InitializeSandboxInfo(
&sandbox_info,
IsExtensionPointDisableSet()
? sandbox::MITIGATION_EXTENSION_POINT_DISABLE
: 0);
}
base::TimeTicks preread_begin_ticks;
base::TimeTicks preread_end_ticks;
base::FilePath file;
dll_ =
Load(&file, cmd_line, is_browser, preread_begin_ticks, preread_end_ticks);
if (!dll_)
return CHROME_RESULT_CODE_MISSING_DATA;
if (!is_browser) {
::SetProcessShutdownParameters(kNonBrowserShutdownPriority - 1,
SHUTDOWN_NORETRY);
}
OnBeforeLaunch(process_type_, file);
DLL_MAIN chrome_main =
reinterpret_cast<DLL_MAIN>(::GetProcAddress(dll_, "ChromeMain"));
int rc = chrome_main(instance, &sandbox_info,
exe_entry_point_ticks.ToInternalValue(),
preread_begin_ticks.ToInternalValue(),
preread_end_ticks.ToInternalValue());
return rc;
}
int MainDllLoader::Launch(HINSTANCE instance,
base::TimeTicks exe_entry_point_ticks) {
const base::CommandLine& cmd_line = *base::CommandLine::ForCurrentProcess();
process_type_ = cmd_line.GetSwitchValueASCII(switches::kProcessType);
sandbox::SandboxInterfaceInfo sandbox_info = {nullptr};
const bool is_browser = process_type_.empty();
const bool is_sandboxed =
sandbox::policy::SandboxTypeFromCommandLine(cmd_line) !=
sandbox::mojom::Sandbox::kNoSandbox;
if (is_browser || is_sandboxed) {
content::InitializeSandboxInfo(
&sandbox_info,
IsExtensionPointDisableSet()
? sandbox::MITIGATION_EXTENSION_POINT_DISABLE
: 0);
}
base::TimeTicks preread_begin_ticks;
base::TimeTicks preread_end_ticks;
base::FilePath file;
dll_ =
Load(&file, cmd_line, is_browser, preread_begin_ticks, preread_end_ticks);
if (!dll_)
return CHROME_RESULT_CODE_MISSING_DATA;
if (!is_browser) {
::SetProcessShutdownParameters(kNonBrowserShutdownPriority - 1,
SHUTDOWN_NORETRY);
}
OnBeforeLaunch(process_type_, file);
DLL_MAIN chrome_main =
reinterpret_cast<DLL_MAIN>(::GetProcAddress(dll_, "ChromeMain"));
int rc = chrome_main(instance, &sandbox_info,
exe_entry_point_ticks.ToInternalValue(),
preread_begin_ticks.ToInternalValue(),
preread_end_ticks.ToInternalValue());
return rc;
}
#if BUILDFLAG(IS_WIN) // Windows平台
DLLEXPORT int __cdecl ChromeMain(HINSTANCE instance,
sandbox::SandboxInterfaceInfo* sandbox_info,
int64_t exe_entry_point_ticks,
int64_t preread_begin_ticks,
int64_t preread_end_ticks) {
#elif BUILDFLAG(IS_POSIX) // POSIX兼容平台(Linux, macOS等)
int ChromeMain(int argc, const char** argv) {
#else
#error Unknown platform. // 未识别的平台, 编译报错
#endif
#if BUILDFLAG(IS_LINUX) // Linux平台专用:可能从可执行文件路径推断Chrome渠道(如稳定版, 测试版)
PossiblyDetermineFallbackChromeChannel(argv[0]);
#endif
#if BUILDFLAG(IS_WIN) // Windows平台初始化逻辑
install_static::InitializeFromPrimaryModule();
#if !defined(COMPONENT_BUILD) && DCHECK_IS_ON()
base::debug::HandleHooks::AddIATPatch(CURRENT_MODULE());
#endif // !defined(COMPONENT_BUILD) && DCHECK_IS_ON()
StartupTimestamps timestamps{
base::TimeTicks::FromInternalValue(exe_entry_point_ticks),
base::TimeTicks::FromInternalValue(preread_begin_ticks),
base::TimeTicks::FromInternalValue(preread_end_ticks)};
ChromeMainDelegate chrome_main_delegate(timestamps);
#else // 非Windows平台:创建主委托对象, 仅记录程序入口时间戳
ChromeMainDelegate chrome_main_delegate(
{.exe_entry_point_ticks = base::TimeTicks::Now()});
#endif
content::ContentMainParams params(&chrome_main_delegate);
#if BUILDFLAG(IS_WIN) // Windows平台专用配置
auto crash_on_detach_resetter = base::ScopedClosureRunner(
base::BindOnce(&base::win::SetShouldCrashOnProcessDetach,
base::win::ShouldCrashOnProcessDetach()));
base::win::SetShouldCrashOnProcessDetach(true);
base::win::SetAbortBehaviorForCrashReporting();
params.instance = instance;
params.sandbox_info = sandbox_info;
base::debug::SetDumpWithoutCrashingFunction(&DumpProcessWithoutCrash);
if (install_static::InstallDetails::Get().VersionMismatch())
base::debug::DumpWithoutCrashing();
#else // 非Windows平台:给Content参数赋值命令行参数
params.argc = argc;
params.argv = argv;
base::CommandLine::Init(params.argc, params.argv);
#endif // BUILDFLAG(IS_WIN)
base::CommandLine::Init(0, nullptr);
[[maybe_unused]] base::CommandLine* command_line(
base::CommandLine::ForCurrentProcess());
#if BUILDFLAG(IS_WIN) // Windows平台:若命令行带--raise-timer-frequency, 提高定时器中断频率(1ms)
if (base::CommandLine::ForCurrentProcess()->HasSwitch(
::switches::kRaiseTimerFrequency)) {
timeBeginPeriod(1);
}
#endif
#if BUILDFLAG(IS_MAC) // macOS平台:设置Bundle覆盖(处理资源路径等)
SetUpBundleOverrides();
#endif
#if BUILDFLAG(IS_LINUX) // Linux平台:向命令行追加额外参数
AppendExtraArgumentsToCommandLine(command_line);
#endif
base::PoissonAllocationSampler::Init();
std::unique_ptr<headless::HeadlessModeHandle> headless_mode_handle;
if (headless::IsHeadlessMode()) {
if (command_line->GetArgs().size() > 1) {
LOG(ERROR) << "Multiple targets are not supported in headless mode.";
return CHROME_RESULT_CODE_UNSUPPORTED_PARAM;
}
auto init_headless_mode = headless::InitHeadlessMode();
if (!init_headless_mode.has_value()) {
LOG(ERROR) << init_headless_mode.error();
return EXIT_FAILURE;
}
headless_mode_handle = std::move(init_headless_mode.value());
} else {
#ifdef ENABLE_OLD_HEADLESS_INFO
if (headless::IsOldHeadlessMode()) {
ShowOldHeadlessInfoMaybe(command_line);
return EXIT_FAILURE;
}
#endif // ENABLE_OLD_HEADLESS_INFO
}
#if BUILDFLAG(IS_MAC) // macOS平台:若辅助程序被系统或第三方应用意外启动, 优雅退出
if (IsHelperAppLaunchedBySystemOrThirdPartyApplication()) {
return 0;
}
#endif
int rv = content::ContentMain(std::move(params));
if (IsNormalResultCode(static_cast<ResultCode>(rv))) {
return content::RESULT_CODE_NORMAL_EXIT;
}
return rv;
}
#if BUILDFLAG(IS_WIN) // Windows平台
DLLEXPORT int __cdecl ChromeMain(HINSTANCE instance,
sandbox::SandboxInterfaceInfo* sandbox_info,
int64_t exe_entry_point_ticks,
int64_t preread_begin_ticks,
int64_t preread_end_ticks) {
#elif BUILDFLAG(IS_POSIX) // POSIX兼容平台(Linux, macOS等)
int ChromeMain(int argc, const char** argv) {
#else
#error Unknown platform. // 未识别的平台, 编译报错
#endif
#if BUILDFLAG(IS_LINUX) // Linux平台专用:可能从可执行文件路径推断Chrome渠道(如稳定版, 测试版)
PossiblyDetermineFallbackChromeChannel(argv[0]);
#endif
#if BUILDFLAG(IS_WIN) // Windows平台初始化逻辑
install_static::InitializeFromPrimaryModule();
#if !defined(COMPONENT_BUILD) && DCHECK_IS_ON()
base::debug::HandleHooks::AddIATPatch(CURRENT_MODULE());
#endif // !defined(COMPONENT_BUILD) && DCHECK_IS_ON()
StartupTimestamps timestamps{
base::TimeTicks::FromInternalValue(exe_entry_point_ticks),
base::TimeTicks::FromInternalValue(preread_begin_ticks),
base::TimeTicks::FromInternalValue(preread_end_ticks)};
ChromeMainDelegate chrome_main_delegate(timestamps);
#else // 非Windows平台:创建主委托对象, 仅记录程序入口时间戳
ChromeMainDelegate chrome_main_delegate(
{.exe_entry_point_ticks = base::TimeTicks::Now()});
#endif
content::ContentMainParams params(&chrome_main_delegate);
#if BUILDFLAG(IS_WIN) // Windows平台专用配置
auto crash_on_detach_resetter = base::ScopedClosureRunner(
base::BindOnce(&base::win::SetShouldCrashOnProcessDetach,
base::win::ShouldCrashOnProcessDetach()));
base::win::SetShouldCrashOnProcessDetach(true);
base::win::SetAbortBehaviorForCrashReporting();
params.instance = instance;
params.sandbox_info = sandbox_info;
base::debug::SetDumpWithoutCrashingFunction(&DumpProcessWithoutCrash);
if (install_static::InstallDetails::Get().VersionMismatch())
base::debug::DumpWithoutCrashing();
#else // 非Windows平台:给Content参数赋值命令行参数
params.argc = argc;
params.argv = argv;
base::CommandLine::Init(params.argc, params.argv);
#endif // BUILDFLAG(IS_WIN)
base::CommandLine::Init(0, nullptr);
[[maybe_unused]] base::CommandLine* command_line(
base::CommandLine::ForCurrentProcess());
#if BUILDFLAG(IS_WIN) // Windows平台:若命令行带--raise-timer-frequency, 提高定时器中断频率(1ms)
if (base::CommandLine::ForCurrentProcess()->HasSwitch(
::switches::kRaiseTimerFrequency)) {
timeBeginPeriod(1);
}
#endif
#if BUILDFLAG(IS_MAC) // macOS平台:设置Bundle覆盖(处理资源路径等)
SetUpBundleOverrides();
#endif
#if BUILDFLAG(IS_LINUX) // Linux平台:向命令行追加额外参数
AppendExtraArgumentsToCommandLine(command_line);
#endif
base::PoissonAllocationSampler::Init();
std::unique_ptr<headless::HeadlessModeHandle> headless_mode_handle;
if (headless::IsHeadlessMode()) {
if (command_line->GetArgs().size() > 1) {
LOG(ERROR) << "Multiple targets are not supported in headless mode.";
return CHROME_RESULT_CODE_UNSUPPORTED_PARAM;
}
auto init_headless_mode = headless::InitHeadlessMode();
if (!init_headless_mode.has_value()) {
LOG(ERROR) << init_headless_mode.error();
return EXIT_FAILURE;
}
headless_mode_handle = std::move(init_headless_mode.value());
} else {
#ifdef ENABLE_OLD_HEADLESS_INFO
if (headless::IsOldHeadlessMode()) {
ShowOldHeadlessInfoMaybe(command_line);
return EXIT_FAILURE;
}
#endif // ENABLE_OLD_HEADLESS_INFO
}
#if BUILDFLAG(IS_MAC) // macOS平台:若辅助程序被系统或第三方应用意外启动, 优雅退出
if (IsHelperAppLaunchedBySystemOrThirdPartyApplication()) {
return 0;
}
#endif
int rv = content::ContentMain(std::move(params));
if (IsNormalResultCode(static_cast<ResultCode>(rv))) {
return content::RESULT_CODE_NORMAL_EXIT;
}
return rv;
}
#if BUILDFLAG(IS_ANDROID) // Android平台专用声明
CONTENT_EXPORT void SetContentMainDelegate(ContentMainDelegate* delegate);
#else // 非Android平台(Windows, Linux, macOS等)
CONTENT_EXPORT int ContentMain(ContentMainParams params);
#endif
#if BUILDFLAG(IS_ANDROID) // Android平台专用声明
CONTENT_EXPORT void SetContentMainDelegate(ContentMainDelegate* delegate);
#else // 非Android平台(Windows, Linux, macOS等)
CONTENT_EXPORT int ContentMain(ContentMainParams params);
#endif
NO_STACK_PROTECTOR int ContentMain(ContentMainParams params) {
auto runner = ContentMainRunner::Create();
return RunContentProcess(std::move(params), runner.get());
}
NO_STACK_PROTECTOR int RunContentProcess(
ContentMainParams params,
ContentMainRunner* content_main_runner) {
base::FeatureList::FailOnFeatureAccessWithoutFeatureList();
int exit_code = -1;
#if BUILDFLAG(IS_MAC) // macOS平台:创建自动释放池(管理Objective-C对象生命周期)
base::apple::ScopedNSAutoreleasePool autorelease_pool;
#endif
static bool is_initialized = false;
#if !BUILDFLAG(IS_ANDROID) // 非Android平台强制检查:确保仅初始化一次(DCHECK断言失败会崩溃)
DCHECK(!is_initialized);
#endif
if (is_initialized) {
content_main_runner->ReInitializeParams(std::move(params));
}
else {
is_initialized = true;
#if BUILDFLAG(IS_APPLE) && PA_BUILDFLAG(USE_ALLOCATOR_SHIM) // Apple平台且启用分配器垫片:初始化垫片
allocator_shim::InitializeAllocatorShim();
#endif
base::EnableTerminationOnOutOfMemory();
logging::RegisterAbslAbortHook();
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) // Linux/ChromeOS平台:禁用DBUS自动启动
const int kNoOverrideIfAlreadySet = 0;
setenv("DBUS_SESSION_BUS_ADDRESS", "disabled:", kNoOverrideIfAlreadySet);
#endif
#if BUILDFLAG(IS_WIN) // Windows平台专用初始化
base::win::RegisterInvalidParamHandler();
ui::win::CreateATLModuleIfNeeded();
#endif // BUILDFLAG(IS_WIN)
#if !BUILDFLAG(IS_ANDROID) // 非Android平台:初始化命令行
int argc = 0;
const char** argv = nullptr;
#if !BUILDFLAG(IS_WIN) // 非Windows平台:从参数获取命令行(Windows平台忽略argc/argv)
argc = params.argc;
argv = params.argv;
#endif
base::CommandLine::Init(argc, argv);
#if BUILDFLAG(IS_POSIX) // POSIX平台:从文件描述符表填充文件描述符存储
PopulateFileDescriptorStoreFromFdTable();
#endif
base::EnableTerminationOnHeapCorruption();
base::SetProcessTitleFromCommandLine(argv);
#endif // !BUILDFLAG(IS_ANDROID)
InitTimeTicksAtUnixEpoch();
#if BUILDFLAG(IS_POSIX) && !BUILDFLAG(IS_ANDROID)
setlocale(LC_ALL, "");
setlocale(LC_NUMERIC, "C");
SetupSignalHandlers();
#endif
#if BUILDFLAG(IS_WIN) // Windows平台:初始化CRT(C运行时库)
base::win::SetupCRT(*base::CommandLine::ForCurrentProcess());
#endif
#if BUILDFLAG(IS_MAC) // macOS平台专用初始化
params.autorelease_pool = &autorelease_pool;
InitializeMac();
#endif
#if BUILDFLAG(IS_IOS) // iOS平台专用配置
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
command_line->AppendSwitch(switches::kEnableViewport);
command_line->AppendSwitch(embedder_support::kUseMobileUserAgent);
#if BUILDFLAG(IS_IOS_TVOS) // tvOS平台:默认启用单进程模式和空间导航
command_line->AppendSwitch(switches::kSingleProcess);
command_line->AppendSwitch(switches::kEnableSpatialNavigation);
#endif
#endif
#if (BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_LINUX)) && !defined(COMPONENT_BUILD)
base::subtle::EnableFDOwnershipEnforcement(true);
#endif
ui::RegisterPathProvider();
exit_code = content_main_runner->Initialize(std::move(params));
if (exit_code >= 0) {
return exit_code;
}
#if BUILDFLAG(IS_WIN) // Windows平台:路由标准输入输出到控制台
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kHeadless)) {
base::RouteStdioToConsole( false);
} else if (command_line->HasSwitch(switches::kEnableLogging)) {
bool create_console = command_line->GetSwitchValueASCII(
switches::kEnableLogging) != "handle";
base::RouteStdioToConsole(create_console);
}
#endif
base::trace_event::TraceLog::GetInstance()->AddOwnedEnabledStateObserver(
base::WrapUnique(new TracingEnabledStateObserver));
}
if (IsSubprocess())
CommonSubprocessInit();
exit_code = content_main_runner->Run();
#if !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_IOS) // 非Android/iOS平台:执行关闭清理
content_main_runner->Shutdown();
#endif
return exit_code;
}
NO_STACK_PROTECTOR int ContentMain(ContentMainParams params) {
auto runner = ContentMainRunner::Create();
return RunContentProcess(std::move(params), runner.get());
}
NO_STACK_PROTECTOR int RunContentProcess(
ContentMainParams params,
ContentMainRunner* content_main_runner) {
base::FeatureList::FailOnFeatureAccessWithoutFeatureList();
int exit_code = -1;
#if BUILDFLAG(IS_MAC) // macOS平台:创建自动释放池(管理Objective-C对象生命周期)
base::apple::ScopedNSAutoreleasePool autorelease_pool;
#endif
static bool is_initialized = false;
#if !BUILDFLAG(IS_ANDROID) // 非Android平台强制检查:确保仅初始化一次(DCHECK断言失败会崩溃)
DCHECK(!is_initialized);
#endif
if (is_initialized) {
content_main_runner->ReInitializeParams(std::move(params));
}
else {
is_initialized = true;
#if BUILDFLAG(IS_APPLE) && PA_BUILDFLAG(USE_ALLOCATOR_SHIM) // Apple平台且启用分配器垫片:初始化垫片
allocator_shim::InitializeAllocatorShim();
#endif
base::EnableTerminationOnOutOfMemory();
logging::RegisterAbslAbortHook();
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) // Linux/ChromeOS平台:禁用DBUS自动启动
const int kNoOverrideIfAlreadySet = 0;
setenv("DBUS_SESSION_BUS_ADDRESS", "disabled:", kNoOverrideIfAlreadySet);
#endif
#if BUILDFLAG(IS_WIN) // Windows平台专用初始化
base::win::RegisterInvalidParamHandler();
ui::win::CreateATLModuleIfNeeded();
#endif // BUILDFLAG(IS_WIN)
#if !BUILDFLAG(IS_ANDROID) // 非Android平台:初始化命令行
int argc = 0;
const char** argv = nullptr;
#if !BUILDFLAG(IS_WIN) // 非Windows平台:从参数获取命令行(Windows平台忽略argc/argv)
argc = params.argc;
argv = params.argv;
#endif
base::CommandLine::Init(argc, argv);
#if BUILDFLAG(IS_POSIX) // POSIX平台:从文件描述符表填充文件描述符存储
PopulateFileDescriptorStoreFromFdTable();
#endif
base::EnableTerminationOnHeapCorruption();
base::SetProcessTitleFromCommandLine(argv);
#endif // !BUILDFLAG(IS_ANDROID)
InitTimeTicksAtUnixEpoch();
#if BUILDFLAG(IS_POSIX) && !BUILDFLAG(IS_ANDROID)
setlocale(LC_ALL, "");
setlocale(LC_NUMERIC, "C");
SetupSignalHandlers();
#endif
#if BUILDFLAG(IS_WIN) // Windows平台:初始化CRT(C运行时库)
base::win::SetupCRT(*base::CommandLine::ForCurrentProcess());
#endif
#if BUILDFLAG(IS_MAC) // macOS平台专用初始化
params.autorelease_pool = &autorelease_pool;
InitializeMac();
#endif
#if BUILDFLAG(IS_IOS) // iOS平台专用配置
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
command_line->AppendSwitch(switches::kEnableViewport);
command_line->AppendSwitch(embedder_support::kUseMobileUserAgent);
#if BUILDFLAG(IS_IOS_TVOS) // tvOS平台:默认启用单进程模式和空间导航
command_line->AppendSwitch(switches::kSingleProcess);
command_line->AppendSwitch(switches::kEnableSpatialNavigation);
#endif
#endif
#if (BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_LINUX)) && !defined(COMPONENT_BUILD)
base::subtle::EnableFDOwnershipEnforcement(true);
#endif
ui::RegisterPathProvider();
exit_code = content_main_runner->Initialize(std::move(params));
if (exit_code >= 0) {
return exit_code;
}
#if BUILDFLAG(IS_WIN) // Windows平台:路由标准输入输出到控制台
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kHeadless)) {
base::RouteStdioToConsole( false);
} else if (command_line->HasSwitch(switches::kEnableLogging)) {
bool create_console = command_line->GetSwitchValueASCII(
switches::kEnableLogging) != "handle";
base::RouteStdioToConsole(create_console);
}
#endif
base::trace_event::TraceLog::GetInstance()->AddOwnedEnabledStateObserver(
base::WrapUnique(new TracingEnabledStateObserver));
}
if (IsSubprocess())
CommonSubprocessInit();
exit_code = content_main_runner->Run();
#if !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_IOS) // 非Android/iOS平台:执行关闭清理
content_main_runner->Shutdown();
#endif
return exit_code;
}
NO_STACK_PROTECTOR int ContentMainRunnerImpl::Run() {
DCHECK(is_initialized_);
DCHECK(content_main_params_);
DCHECK(!is_shutdown_);
const base::CommandLine* command_line =
base::CommandLine::ForCurrentProcess();
std::string process_type =
command_line->GetSwitchValueASCII(switches::kProcessType);
#if defined(ADDRESS_SANITIZER) // 启用地址 sanitizer(内存检测工具)时
base::debug::AsanService::GetInstance()->Initialize();
base::debug::AsanService::GetInstance()->AddErrorCallback(AsanProcessInfoCB);
#endif
bool needs_startup_tracing_after_sandbox_init = false;
if (!process_type.empty()) {
if (process_type != switches::kZygoteProcess) {
if (delegate_->ShouldCreateFeatureList(
ContentMainDelegate::InvokedInChildProcess())) {
InitializeFieldTrialAndFeatureList();
}
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) // Linux/ChromeOS平台:初始化跟踪系统
if (process_type == switches::kGpuProcess) {
tracing::InitTracingPostFeatureList(false,
true);
} else {
needs_startup_tracing_after_sandbox_init = true;
}
#else // 非Linux/ChromeOS平台:初始化跟踪(禁用消费者, 不支持线程重启跟踪)
tracing::InitTracingPostFeatureList(false,
false);
#endif
if (delegate_->ShouldInitializeMojo(
ContentMainDelegate::InvokedInChildProcess())) {
InitializeMojoCore();
}
delegate_->PostEarlyInitialization(
ContentMainDelegate::InvokedInChildProcess());
base::allocator::PartitionAllocSupport::Get()
->ReconfigureAfterFeatureListInit(process_type);
}
}
MainFunctionParams main_params(command_line);
main_params.ui_task = std::move(content_main_params_->ui_task);
main_params.created_main_parts_closure =
std::move(content_main_params_->created_main_parts_closure);
main_params.needs_startup_tracing_after_sandbox_init =
needs_startup_tracing_after_sandbox_init;
#if BUILDFLAG(IS_WIN) // Windows平台:传递沙箱信息
main_params.sandbox_info = content_main_params_->sandbox_info;
#elif BUILDFLAG(IS_MAC) // macOS平台:传递自动释放池
main_params.autorelease_pool = content_main_params_->autorelease_pool;
#endif
const bool start_minimal_browser = content_main_params_->minimal_browser_mode;
content_main_params_.reset();
RegisterMainThreadFactories();
if (process_type.empty())
return RunBrowser(std::move(main_params), start_minimal_browser);
return RunOtherNamedProcessTypeMain(process_type, std::move(main_params),
delegate_);
}
NO_STACK_PROTECTOR int ContentMainRunnerImpl::Run() {
DCHECK(is_initialized_);
DCHECK(content_main_params_);
DCHECK(!is_shutdown_);
const base::CommandLine* command_line =
base::CommandLine::ForCurrentProcess();
std::string process_type =
command_line->GetSwitchValueASCII(switches::kProcessType);
#if defined(ADDRESS_SANITIZER) // 启用地址 sanitizer(内存检测工具)时
base::debug::AsanService::GetInstance()->Initialize();
base::debug::AsanService::GetInstance()->AddErrorCallback(AsanProcessInfoCB);
#endif
bool needs_startup_tracing_after_sandbox_init = false;
if (!process_type.empty()) {
if (process_type != switches::kZygoteProcess) {
if (delegate_->ShouldCreateFeatureList(
ContentMainDelegate::InvokedInChildProcess())) {
InitializeFieldTrialAndFeatureList();
}
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) // Linux/ChromeOS平台:初始化跟踪系统
if (process_type == switches::kGpuProcess) {
tracing::InitTracingPostFeatureList(false,
true);
} else {
needs_startup_tracing_after_sandbox_init = true;
}
#else // 非Linux/ChromeOS平台:初始化跟踪(禁用消费者, 不支持线程重启跟踪)
tracing::InitTracingPostFeatureList(false,
false);
#endif
if (delegate_->ShouldInitializeMojo(
ContentMainDelegate::InvokedInChildProcess())) {
InitializeMojoCore();
}
delegate_->PostEarlyInitialization(
ContentMainDelegate::InvokedInChildProcess());
base::allocator::PartitionAllocSupport::Get()
->ReconfigureAfterFeatureListInit(process_type);
}
}
MainFunctionParams main_params(command_line);
main_params.ui_task = std::move(content_main_params_->ui_task);
main_params.created_main_parts_closure =
std::move(content_main_params_->created_main_parts_closure);
main_params.needs_startup_tracing_after_sandbox_init =
needs_startup_tracing_after_sandbox_init;
#if BUILDFLAG(IS_WIN) // Windows平台:传递沙箱信息
main_params.sandbox_info = content_main_params_->sandbox_info;
#elif BUILDFLAG(IS_MAC) // macOS平台:传递自动释放池
main_params.autorelease_pool = content_main_params_->autorelease_pool;
#endif
const bool start_minimal_browser = content_main_params_->minimal_browser_mode;
content_main_params_.reset();
RegisterMainThreadFactories();
if (process_type.empty())
return RunBrowser(std::move(main_params), start_minimal_browser);
return RunOtherNamedProcessTypeMain(process_type, std::move(main_params),
delegate_);
}
static void RegisterMainThreadFactories() {
UtilityProcessHost::RegisterUtilityMainThreadFactory(
CreateInProcessUtilityThread);
RenderProcessHostImpl::RegisterRendererMainThreadFactory(
CreateInProcessRendererThread);
content::RegisterGpuMainThreadFactory(CreateInProcessGpuThread);
}
UtilityMainThreadFactoryFunction g_utility_main_thread_factory = nullptr;
void UtilityProcessHost::RegisterUtilityMainThreadFactory(
UtilityMainThreadFactoryFunction create) {
g_utility_main_thread_factory = create;
}
base::Thread* CreateInProcessUtilityThread(
const InProcessChildThreadParams& params) {
return new InProcessUtilityThread(params);
}
RendererMainThreadFactoryFunction g_renderer_main_thread_factory = nullptr;
void RenderProcessHostImpl::RegisterRendererMainThreadFactory(
RendererMainThreadFactoryFunction create) {
g_renderer_main_thread_factory = create;
}
base::Thread* CreateInProcessRendererThread(
const InProcessChildThreadParams& params,
int32_t renderer_client_id) {
return new InProcessRendererThread(params, renderer_client_id);
}
GpuMainThreadFactoryFunction g_gpu_main_thread_factory = nullptr;
void RegisterGpuMainThreadFactory(GpuMainThreadFactoryFunction create) {
g_gpu_main_thread_factory = create;
}
base::Thread* CreateInProcessGpuThread(
const InProcessChildThreadParams& params,
const gpu::GpuPreferences& gpu_preferences) {
return new InProcessGpuThread(params, gpu_preferences);
}
static void RegisterMainThreadFactories() {
UtilityProcessHost::RegisterUtilityMainThreadFactory(
CreateInProcessUtilityThread);
RenderProcessHostImpl::RegisterRendererMainThreadFactory(
CreateInProcessRendererThread);
content::RegisterGpuMainThreadFactory(CreateInProcessGpuThread);
}
UtilityMainThreadFactoryFunction g_utility_main_thread_factory = nullptr;
void UtilityProcessHost::RegisterUtilityMainThreadFactory(
UtilityMainThreadFactoryFunction create) {
g_utility_main_thread_factory = create;
}
base::Thread* CreateInProcessUtilityThread(
const InProcessChildThreadParams& params) {
return new InProcessUtilityThread(params);
}
RendererMainThreadFactoryFunction g_renderer_main_thread_factory = nullptr;
void RenderProcessHostImpl::RegisterRendererMainThreadFactory(
RendererMainThreadFactoryFunction create) {
g_renderer_main_thread_factory = create;
}
base::Thread* CreateInProcessRendererThread(
const InProcessChildThreadParams& params,
int32_t renderer_client_id) {
return new InProcessRendererThread(params, renderer_client_id);
}
GpuMainThreadFactoryFunction g_gpu_main_thread_factory = nullptr;
void RegisterGpuMainThreadFactory(GpuMainThreadFactoryFunction create) {
g_gpu_main_thread_factory = create;
}
base::Thread* CreateInProcessGpuThread(
const InProcessChildThreadParams& params,
const gpu::GpuPreferences& gpu_preferences) {
return new InProcessGpuThread(params, gpu_preferences);
}
int ContentMainRunnerImpl::RunBrowser(MainFunctionParams main_params,
bool start_minimal_browser) {
TRACE_EVENT_INSTANT0("startup", "ContentMainRunnerImpl::RunBrowser(begin)",
TRACE_EVENT_SCOPE_THREAD);
if (is_browser_main_loop_started_)
return -1;
if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kSingleProcess)) {
mojo::SyncCallRestrictions::DisableSyncCallInterrupts();
}
variations::MaybeUnpackVariationsStateFile();
if (!mojo_ipc_support_) {
const ContentMainDelegate::InvokedInBrowserProcess invoked_in_browser{
.is_running_test = !main_params.ui_task.is_null()};
if (delegate_->ShouldCreateFeatureList(invoked_in_browser)) {
base::FieldTrialList* leaked_field_trial_list =
SetUpFieldTrialsAndFeatureList().release();
ANNOTATE_LEAKING_OBJECT_PTR(leaked_field_trial_list);
std::ignore = leaked_field_trial_list;
}
if (delegate_->ShouldInitializeMojo(invoked_in_browser)) {
InitializeMojoCore();
}
browser_memory_consumer_registry_ = std::make_unique<
base::ScopedMemoryConsumerRegistry<BrowserMemoryConsumerRegistry>>();
std::optional<int> pre_browser_main_exit_code = delegate_->PreBrowserMain();
if (pre_browser_main_exit_code.has_value())
return pre_browser_main_exit_code.value();
#if BUILDFLAG(IS_WIN) // Windows平台特有处理
if (l10n_util::GetLocaleOverrides().empty()) {
l10n_util::OverrideLocaleWithUILanguageList();
}
#endif
BrowserTaskExecutor::Create();
auto* provider = delegate_->CreateVariationsIdsProvider();
if (!provider) {
variations::VariationsIdsProvider::CreateInstance(
variations::VariationsIdsProvider::Mode::kUseSignedInState);
}
std::optional<int> post_early_initialization_exit_code =
delegate_->PostEarlyInitialization(invoked_in_browser);
if (post_early_initialization_exit_code.has_value())
return post_early_initialization_exit_code.value();
if (base::HangWatcher::IsEnabled()) {
base::HangWatcher::CreateHangWatcherInstance();
base::ScopedClosureRunner unregister_thread_closure(
base::HangWatcher::RegisterThread(
base::HangWatcher::ThreadType::kMainThread));
std::ignore = unregister_thread_closure.Release();
base::HangWatcher::GetInstance()->Start();
}
#if BUILDFLAG(IS_ANDROID) // Android平台特有:初始化性能追踪(Perfetto)
if (delegate_->ShouldInitializePerfetto(invoked_in_browser)) {
tracing::InitTracingPostFeatureList(
true,
false,
base::BindRepeating(&ShouldAllowSystemTracingConsumer));
}
#else // 非Android平台:直接初始化Perfetto追踪
tracing::InitTracingPostFeatureList(
true,
false,
base::BindRepeating(&ShouldAllowSystemTracingConsumer));
#endif
StartBrowserThreadPool();
BrowserTaskExecutor::
InstallPartitionAllocSchedulerLoopQuarantineTaskObserver();
base::PowerMonitor::GetInstance()->Initialize(
MakePowerMonitorDeviceSource(), true);
ProcessVisibilityTracker::GetInstance();
#if BUILDFLAG(IS_ANDROID) // Android平台特有:初始化性能/电池指标
SetupCpuTimeMetrics();
AndroidBatteryMetrics::CreateInstance();
#endif
GetContentClient()->browser()->SetIsMinimalMode(start_minimal_browser);
if (start_minimal_browser) {
ForceInProcessNetworkService();
content::FirstPartySetsHandlerImpl::GetInstance()->Init(
base::FilePath(), net::LocalSetDeclaration());
}
discardable_shared_memory_manager_ =
std::make_unique<discardable_memory::DiscardableSharedMemoryManager>();
mojo_ipc_support_ =
std::make_unique<MojoIpcSupport>(BrowserTaskExecutor::CreateIOThread());
GetContentClient()->browser()->BindBrowserControlInterface(
MaybeAcceptMojoInvitation());
download::SetIOTaskRunner(mojo_ipc_support_->io_thread()->task_runner());
InitializeBrowserMemoryInstrumentationClient();
#if BUILDFLAG(IS_ANDROID) // Android平台特有:最小化模式启动完成通知
if (start_minimal_browser) {
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, base::BindOnce(&MinimalBrowserStartupComplete));
}
#endif
}
base::allocator::PartitionAllocSupport::Get()
->ReconfigureAfterFeatureListInit("");
base::allocator::PartitionAllocSupport::Get()->ReconfigureAfterTaskRunnerInit(
"");
if (start_minimal_browser) {
DVLOG(0) << "Chrome is running in minimal browser mode.";
return -1;
}
is_browser_main_loop_started_ = true;
main_params.startup_data = mojo_ipc_support_->CreateBrowserStartupData();
return RunBrowserProcessMain(std::move(main_params), delegate_);
}
int ContentMainRunnerImpl::RunBrowser(MainFunctionParams main_params,
bool start_minimal_browser) {
TRACE_EVENT_INSTANT0("startup", "ContentMainRunnerImpl::RunBrowser(begin)",
TRACE_EVENT_SCOPE_THREAD);
if (is_browser_main_loop_started_)
return -1;
if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kSingleProcess)) {
mojo::SyncCallRestrictions::DisableSyncCallInterrupts();
}
variations::MaybeUnpackVariationsStateFile();
if (!mojo_ipc_support_) {
const ContentMainDelegate::InvokedInBrowserProcess invoked_in_browser{
.is_running_test = !main_params.ui_task.is_null()};
if (delegate_->ShouldCreateFeatureList(invoked_in_browser)) {
base::FieldTrialList* leaked_field_trial_list =
SetUpFieldTrialsAndFeatureList().release();
ANNOTATE_LEAKING_OBJECT_PTR(leaked_field_trial_list);
std::ignore = leaked_field_trial_list;
}
if (delegate_->ShouldInitializeMojo(invoked_in_browser)) {
InitializeMojoCore();
}
browser_memory_consumer_registry_ = std::make_unique<
base::ScopedMemoryConsumerRegistry<BrowserMemoryConsumerRegistry>>();
std::optional<int> pre_browser_main_exit_code = delegate_->PreBrowserMain();
if (pre_browser_main_exit_code.has_value())
return pre_browser_main_exit_code.value();
#if BUILDFLAG(IS_WIN) // Windows平台特有处理
if (l10n_util::GetLocaleOverrides().empty()) {
l10n_util::OverrideLocaleWithUILanguageList();
}
#endif
BrowserTaskExecutor::Create();
auto* provider = delegate_->CreateVariationsIdsProvider();
if (!provider) {
variations::VariationsIdsProvider::CreateInstance(
variations::VariationsIdsProvider::Mode::kUseSignedInState);
}
std::optional<int> post_early_initialization_exit_code =
delegate_->PostEarlyInitialization(invoked_in_browser);
if (post_early_initialization_exit_code.has_value())
return post_early_initialization_exit_code.value();
if (base::HangWatcher::IsEnabled()) {
base::HangWatcher::CreateHangWatcherInstance();
base::ScopedClosureRunner unregister_thread_closure(
base::HangWatcher::RegisterThread(
base::HangWatcher::ThreadType::kMainThread));
std::ignore = unregister_thread_closure.Release();
base::HangWatcher::GetInstance()->Start();
}
#if BUILDFLAG(IS_ANDROID) // Android平台特有:初始化性能追踪(Perfetto)
if (delegate_->ShouldInitializePerfetto(invoked_in_browser)) {
tracing::InitTracingPostFeatureList(
true,
false,
base::BindRepeating(&ShouldAllowSystemTracingConsumer));
}
#else // 非Android平台:直接初始化Perfetto追踪
tracing::InitTracingPostFeatureList(
true,
false,
base::BindRepeating(&ShouldAllowSystemTracingConsumer));
#endif
StartBrowserThreadPool();
BrowserTaskExecutor::
InstallPartitionAllocSchedulerLoopQuarantineTaskObserver();
base::PowerMonitor::GetInstance()->Initialize(
MakePowerMonitorDeviceSource(), true);
ProcessVisibilityTracker::GetInstance();
#if BUILDFLAG(IS_ANDROID) // Android平台特有:初始化性能/电池指标
SetupCpuTimeMetrics();
AndroidBatteryMetrics::CreateInstance();
#endif
GetContentClient()->browser()->SetIsMinimalMode(start_minimal_browser);
if (start_minimal_browser) {
ForceInProcessNetworkService();
content::FirstPartySetsHandlerImpl::GetInstance()->Init(
base::FilePath(), net::LocalSetDeclaration());
}
discardable_shared_memory_manager_ =
std::make_unique<discardable_memory::DiscardableSharedMemoryManager>();
mojo_ipc_support_ =
std::make_unique<MojoIpcSupport>(BrowserTaskExecutor::CreateIOThread());
GetContentClient()->browser()->BindBrowserControlInterface(
MaybeAcceptMojoInvitation());
download::SetIOTaskRunner(mojo_ipc_support_->io_thread()->task_runner());
InitializeBrowserMemoryInstrumentationClient();
#if BUILDFLAG(IS_ANDROID) // Android平台特有:最小化模式启动完成通知
if (start_minimal_browser) {
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, base::BindOnce(&MinimalBrowserStartupComplete));
}
#endif
}
base::allocator::PartitionAllocSupport::Get()
->ReconfigureAfterFeatureListInit("");
base::allocator::PartitionAllocSupport::Get()->ReconfigureAfterTaskRunnerInit(
"");
if (start_minimal_browser) {
DVLOG(0) << "Chrome is running in minimal browser mode.";
return -1;
}
is_browser_main_loop_started_ = true;
main_params.startup_data = mojo_ipc_support_->CreateBrowserStartupData();
return RunBrowserProcessMain(std::move(main_params), delegate_);
}
int RunBrowserProcessMain(MainFunctionParams main_function_params,
ContentMainDelegate* delegate) {
#if BUILDFLAG(IS_WIN) // Windows平台特有:处理控制台控制事件(如Ctrl+C, 关闭控制台窗口)
if (delegate->ShouldHandleConsoleControlEvents()) {
InstallConsoleControlHandler(true);
}
#endif
auto exit_code = delegate->RunProcess("", std::move(main_function_params));
if (std::holds_alternative<int>(exit_code)) {
DCHECK_GE(std::get<int>(exit_code), 0);
return std::get<int>(exit_code);
}
return BrowserMain(std::move(std::get<MainFunctionParams>(exit_code)));
}
int RunBrowserProcessMain(MainFunctionParams main_function_params,
ContentMainDelegate* delegate) {
#if BUILDFLAG(IS_WIN) // Windows平台特有:处理控制台控制事件(如Ctrl+C, 关闭控制台窗口)
if (delegate->ShouldHandleConsoleControlEvents()) {
InstallConsoleControlHandler(true);
}
#endif
auto exit_code = delegate->RunProcess("", std::move(main_function_params));
if (std::holds_alternative<int>(exit_code)) {
DCHECK_GE(std::get<int>(exit_code), 0);
return std::get<int>(exit_code);
}
return BrowserMain(std::move(std::get<MainFunctionParams>(exit_code)));
}
int BrowserMain(MainFunctionParams parameters) {
TRACE_EVENT_INSTANT0("startup", "BrowserMain", TRACE_EVENT_SCOPE_THREAD);
base::CurrentProcess::GetInstance().SetProcessType(
base::CurrentProcessType::PROCESS_BROWSER);
std::unique_ptr<BrowserMainRunnerImpl> main_runner(
BrowserMainRunnerImpl::Create());
int exit_code = main_runner->Initialize(std::move(parameters));
if (exit_code >= 0)
return exit_code;
exit_code = main_runner->Run();
const int64_t shutdown_time =
base::TimeTicks::Now().since_origin().InSeconds();
base::debug::Alias(&shutdown_time);
main_runner->Shutdown();
return exit_code;
}
int BrowserMain(MainFunctionParams parameters) {
TRACE_EVENT_INSTANT0("startup", "BrowserMain", TRACE_EVENT_SCOPE_THREAD);
base::CurrentProcess::GetInstance().SetProcessType(
base::CurrentProcessType::PROCESS_BROWSER);
std::unique_ptr<BrowserMainRunnerImpl> main_runner(
BrowserMainRunnerImpl::Create());
int exit_code = main_runner->Initialize(std::move(parameters));
if (exit_code >= 0)
return exit_code;
exit_code = main_runner->Run();
const int64_t shutdown_time =
base::TimeTicks::Now().since_origin().InSeconds();
base::debug::Alias(&shutdown_time);
main_runner->Shutdown();
return exit_code;
}
int BrowserMainRunnerImpl::Initialize(MainFunctionParams parameters) {
SCOPED_UMA_HISTOGRAM_LONG_TIMER(
"Startup.BrowserMainRunnerImplInitializeLongTime");
TRACE_EVENT0("startup", "BrowserMainRunnerImpl::Initialize");
if (!initialization_started_) {
initialization_started_ = true;
SkGraphics::Init();
if (parameters.command_line->HasSwitch(switches::kWaitForDebugger)) {
base::debug::WaitForDebugger(60, true);
}
if (parameters.command_line->HasSwitch(switches::kBrowserStartupDialog)) {
WaitForDebugger("Browser");
}
#if BUILDFLAG(IS_WIN)
base::win::EnableHighDPISupport();
ole_initializer_ = std::make_unique<ui::ScopedOleInitializer>();
#endif // BUILDFLAG(IS_WIN)
gfx::InitializeFonts();
auto created_main_parts_closure =
std::move(parameters.created_main_parts_closure);
main_loop_ = std::make_unique<BrowserMainLoop>(
std::move(parameters), std::move(scoped_execution_fence_));
main_loop_->Init();
if (created_main_parts_closure) {
std::move(created_main_parts_closure).Run(main_loop_->parts());
}
const int early_init_error_code = main_loop_->EarlyInitialization();
if (early_init_error_code > 0) {
main_loop_->CreateMessageLoopForEarlyShutdown();
return early_init_error_code;
}
if (!main_loop_->InitializeToolkit()) {
main_loop_->CreateMessageLoopForEarlyShutdown();
return 1;
}
main_loop_->PreCreateMainMessageLoop();
main_loop_->CreateMainMessageLoop();
main_loop_->PostCreateMainMessageLoop();
ui::InitializeInputMethod();
}
main_loop_->CreateStartupTasks();
int result_code = main_loop_->GetResultCode();
if (result_code > 0) {
return result_code;
}
return -1;
}
int BrowserMainRunnerImpl::Initialize(MainFunctionParams parameters) {
SCOPED_UMA_HISTOGRAM_LONG_TIMER(
"Startup.BrowserMainRunnerImplInitializeLongTime");
TRACE_EVENT0("startup", "BrowserMainRunnerImpl::Initialize");
if (!initialization_started_) {
initialization_started_ = true;
SkGraphics::Init();
if (parameters.command_line->HasSwitch(switches::kWaitForDebugger)) {
base::debug::WaitForDebugger(60, true);
}
if (parameters.command_line->HasSwitch(switches::kBrowserStartupDialog)) {
WaitForDebugger("Browser");
}
#if BUILDFLAG(IS_WIN)
base::win::EnableHighDPISupport();
ole_initializer_ = std::make_unique<ui::ScopedOleInitializer>();
#endif // BUILDFLAG(IS_WIN)
gfx::InitializeFonts();
auto created_main_parts_closure =
std::move(parameters.created_main_parts_closure);
main_loop_ = std::make_unique<BrowserMainLoop>(
std::move(parameters), std::move(scoped_execution_fence_));
main_loop_->Init();
if (created_main_parts_closure) {
std::move(created_main_parts_closure).Run(main_loop_->parts());
}
const int early_init_error_code = main_loop_->EarlyInitialization();
if (early_init_error_code > 0) {
main_loop_->CreateMessageLoopForEarlyShutdown();
return early_init_error_code;
}
if (!main_loop_->InitializeToolkit()) {
main_loop_->CreateMessageLoopForEarlyShutdown();
return 1;
}
main_loop_->PreCreateMainMessageLoop();
main_loop_->CreateMainMessageLoop();
main_loop_->PostCreateMainMessageLoop();
ui::InitializeInputMethod();
}