#include "content/browser/browser_main_loop.h"
#include <stddef.h>
#include <algorithm>
#include <memory>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include "base/base_switches.h"
#include "base/command_line.h"
#include "base/feature_list.h"
#include "base/functional/bind.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/memory/memory_pressure_monitor.h"
#include "base/memory/ptr_util.h"
#include "base/metrics/field_trial.h"
#include "base/metrics/histogram_macros.h"
#include "base/metrics/user_metrics.h"
#include "base/no_destructor.h"
#include "base/path_service.h"
#include "base/pending_task.h"
#include "base/power_monitor/power_monitor.h"
#include "base/power_monitor/power_monitor_source.h"
#include "base/process/process_metrics.h"
#include "base/rand_util.h"
#include "base/run_loop.h"
#include "base/scoped_observation.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/synchronization/waitable_event.h"
#include "base/system/system_monitor.h"
#include "base/task/current_thread.h"
#include "base/task/deferred_sequenced_task_runner.h"
#include "base/task/sequenced_task_runner.h"
#include "base/task/single_thread_task_runner.h"
#include "base/task/thread_pool/initialization_util.h"
#include "base/threading/thread.h"
#include "base/threading/thread_restrictions.h"
#include "base/time/time.h"
#include "base/timer/hi_res_timer_manager.h"
#include "base/trace_event/memory_dump_manager.h"
#include "base/trace_event/trace_event.h"
#include "build/branding_buildflags.h"
#include "build/build_config.h"
#include "build/chromecast_buildflags.h"
#include "build/chromeos_buildflags.h"
#include "cc/base/histograms.h"
#include "components/discardable_memory/service/discardable_shared_memory_manager.h"
#include "components/memory_pressure/multi_source_memory_pressure_monitor.h"
#include "components/power_monitor/make_power_monitor_device_source.h"
#include "components/services/storage/dom_storage/storage_area_impl.h"
#include "components/tracing/common/trace_startup_config.h"
#include "components/tracing/common/tracing_switches.h"
#include "components/variations/fake_crash.h"
#include "components/viz/host/compositing_mode_reporter_impl.h"
#include "components/viz/host/gpu_host_impl.h"
#include "components/viz/host/host_frame_sink_manager.h"
#include "content/browser/accessibility/browser_accessibility_state_impl.h"
#include "content/browser/browser_thread_impl.h"
#include "content/browser/child_process_security_policy_impl.h"
#include "content/browser/compositor/viz_process_transport_factory.h"
#include "content/browser/download/save_file_manager.h"
#include "content/browser/field_trial_synchronizer.h"
#include "content/browser/first_party_sets/first_party_sets_handler_impl.h"
#include "content/browser/first_party_sets/local_set_declaration.h"
#include "content/browser/gpu/browser_gpu_channel_host_factory.h"
#include "content/browser/gpu/browser_gpu_client_delegate.h"
#include "content/browser/gpu/compositor_util.h"
#include "content/browser/gpu/gpu_data_manager_impl.h"
#include "content/browser/gpu/gpu_disk_cache_factory.h"
#include "content/browser/gpu/gpu_process_host.h"
#include "content/browser/media/media_internals.h"
#include "content/browser/media/media_keys_listener_manager_impl.h"
#include "content/browser/memory_pressure/user_level_memory_pressure_signal_generator.h"
#include "content/browser/metrics/histogram_synchronizer.h"
#include "content/browser/network/browser_online_state_observer.h"
#include "content/browser/network_service_instance_impl.h"
#include "content/browser/renderer_host/media/media_stream_manager.h"
#include "content/browser/renderer_host/render_process_host_impl.h"
#include "content/browser/scheduler/browser_task_executor.h"
#include "content/browser/scheduler/responsiveness/watcher.h"
#include "content/browser/screenlock_monitor/screenlock_monitor.h"
#include "content/browser/screenlock_monitor/screenlock_monitor_device_source.h"
#include "content/browser/sms/sms_provider.h"
#include "content/browser/speech/speech_recognition_manager_impl.h"
#include "content/browser/speech/tts_controller_impl.h"
#include "content/browser/startup_data_impl.h"
#include "content/browser/startup_task_runner.h"
#include "content/browser/tracing/background_tracing_manager_impl.h"
#include "content/browser/tracing/startup_tracing_controller.h"
#include "content/browser/tracing/tracing_controller_impl.h"
#include "content/browser/utility_process_host.h"
#include "content/browser/webrtc/webrtc_internals.h"
#include "content/browser/webui/content_web_ui_configs.h"
#include "content/browser/webui/url_data_manager.h"
#include "content/common/content_switches_internal.h"
#include "content/common/pseudonymization_salt.h"
#include "content/common/skia_utils.h"
#include "content/common/thread_pool_util.h"
#include "content/public/browser/audio_service.h"
#include "content/public/browser/browser_main_parts.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/content_browser_client.h"
#include "content/public/browser/device_service.h"
#include "content/public/browser/network_service_instance.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/service_process_host.h"
#include "content/public/browser/site_isolation_policy.h"
#include "content/public/common/content_client.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/main_function_params.h"
#include "content/public/common/result_codes.h"
#include "content/public/common/zygote/zygote_buildflags.h"
#include "crypto/crypto_buildflags.h"
#include "device/fido/hid/fido_hid_discovery.h"
#include "device/gamepad/gamepad_service.h"
#include "media/audio/audio_manager.h"
#include "media/audio/audio_system.h"
#include "media/audio/audio_thread_impl.h"
#include "media/base/user_input_monitor.h"
#include "media/media_buildflags.h"
#include "media/midi/midi_service.h"
#include "media/mojo/buildflags.h"
#include "mojo/core/embedder/embedder.h"
#include "mojo/core/embedder/scoped_ipc_support.h"
#include "mojo/public/cpp/bindings/mojo_buildflags.h"
#include "mojo/public/cpp/bindings/sync_call_restrictions.h"
#include "net/base/network_change_notifier.h"
#include "net/socket/client_socket_factory.h"
#include "net/ssl/ssl_config_service.h"
#include "ppapi/buildflags/buildflags.h"
#include "services/audio/service.h"
#include "services/data_decoder/data_decoder_service.h"
#include "services/data_decoder/public/cpp/service_provider.h"
#include "services/data_decoder/public/mojom/data_decoder_service.mojom.h"
#include "services/network/public/cpp/network_switches.h"
#include "services/network/public/mojom/network_service.mojom.h"
#include "services/network/transitional_url_loader_factory_owner.h"
#include "skia/ext/event_tracer_impl.h"
#include "skia/ext/skia_memory_dump_provider.h"
#include "sql/sql_memory_dump_provider.h"
#include "ui/base/clipboard/clipboard.h"
#include "ui/display/display_features.h"
#include "ui/gfx/font_render_params.h"
#include "ui/gfx/switches.h"
#if defined(USE_AURA) || BUILDFLAG(IS_MAC)
#include "content/browser/compositor/image_transport_factory.h"
#endif
#if defined(USE_AURA)
#include "content/public/browser/context_factory.h"
#include "ui/aura/env.h"
#endif
#if BUILDFLAG(IS_ANDROID)
#include "base/android/jni_android.h"
#include "base/trace_event/cpufreq_monitor_android.h"
#include "components/tracing/common/graphics_memory_dump_provider_android.h"
#include "content/browser/android/browser_startup_controller.h"
#include "content/browser/android/launcher_thread.h"
#include "content/browser/android/scoped_surface_request_manager.h"
#include "content/browser/android/tracing_controller_android.h"
#include "content/browser/font_unique_name_lookup/font_unique_name_lookup.h"
#include "content/browser/screen_orientation/screen_orientation_delegate_android.h"
#include "media/base/android/media_drm_bridge_client.h"
#include "ui/android/screen_android.h"
#include "ui/display/screen.h"
#include "ui/gl/gl_surface.h"
#endif
#if BUILDFLAG(IS_OHOS) && defined(OHOS_ENABLE_CDM)
#include "media/base/ohos/ohos_media_drm_bridge_client.h"
#endif
#if BUILDFLAG(IS_MAC)
#include "base/mac/scoped_nsautorelease_pool.h"
#include "content/browser/renderer_host/browser_compositor_view_mac.h"
#include "content/browser/theme_helper_mac.h"
#include "ui/accelerated_widget_mac/window_resize_helper_mac.h"
#endif
#if BUILDFLAG(IS_WIN)
#include <commctrl.h>
#include <shellapi.h>
#include <windows.h>
#include "base/threading/platform_thread_win.h"
#include "net/base/winsock_init.h"
#include "sandbox/policy/win/sandbox_win.h"
#include "sandbox/win/src/sandbox.h"
#endif
#if BUILDFLAG(IS_CHROMEOS_ASH)
#include "device/bluetooth/bluetooth_adapter_factory.h"
#include "services/data_decoder/public/cpp/data_decoder.h"
#endif
#if defined(USE_GLIB)
#include <glib-object.h>
#endif
#if BUILDFLAG(IS_WIN)
#include "media/device_monitors/system_message_window_win.h"
#include "sandbox/win/src/process_mitigations.h"
#elif (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)) && defined(USE_UDEV)
#include "media/device_monitors/device_monitor_udev.h"
#elif BUILDFLAG(IS_MAC)
#include "media/device_monitors/device_monitor_mac.h"
#endif
#if BUILDFLAG(IS_FUCHSIA)
#include <lib/zx/job.h>
#include "base/fuchsia/default_job.h"
#include "base/fuchsia/fuchsia_logging.h"
#endif
#if BUILDFLAG(IS_POSIX) && !BUILDFLAG(IS_MAC)
#include "content/browser/sandbox_host_linux.h"
#endif
#if BUILDFLAG(ENABLE_PLUGINS)
#include "content/browser/plugin_service_impl.h"
#endif
#if BUILDFLAG(ENABLE_LIBRARY_CDMS) || BUILDFLAG(IS_ANDROID)
#include "content/browser/media/cdm_registry_impl.h"
#endif
#if BUILDFLAG(USE_NSS_CERTS)
#include "crypto/nss_util.h"
#endif
#if defined(ENABLE_IPC_FUZZER) && BUILDFLAG(IS_MAC)
#include "base/mac/foundation_util.h"
#endif
#if BUILDFLAG(MOJO_RANDOM_DELAYS_ENABLED)
#include "mojo/public/cpp/bindings/lib/test_random_mojo_delays.h"
#endif
#if defined(OHOS_WPT)
#include "content/browser/font_unique_name_lookup/font_unique_name_lookup.h"
#endif
#ifdef DestroyAll
#undef DestroyAll
#endif
namespace content {
namespace {
#if defined(USE_GLIB)
static void GLibLogHandler(const gchar* log_domain,
GLogLevelFlags log_level,
const gchar* message,
gpointer userdata) {
if (!log_domain)
log_domain = "<unknown>";
if (!message)
message = "<no message>";
GLogLevelFlags always_fatal_flags = g_log_set_always_fatal(G_LOG_LEVEL_MASK);
g_log_set_always_fatal(always_fatal_flags);
GLogLevelFlags fatal_flags =
g_log_set_fatal_mask(log_domain, G_LOG_LEVEL_MASK);
g_log_set_fatal_mask(log_domain, fatal_flags);
if ((always_fatal_flags | fatal_flags) & log_level) {
LOG(DFATAL) << log_domain << ": " << message;
} else if (log_level & (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL)) {
LOG(ERROR) << log_domain << ": " << message;
} else if (log_level & (G_LOG_LEVEL_WARNING)) {
LOG(WARNING) << log_domain << ": " << message;
} else if (log_level &
(G_LOG_LEVEL_MESSAGE | G_LOG_LEVEL_INFO | G_LOG_LEVEL_DEBUG)) {
LOG(INFO) << log_domain << ": " << message;
} else {
NOTREACHED();
LOG(DFATAL) << log_domain << ": " << message;
}
}
static void SetUpGLibLogHandler() {
const char* const kLogDomains[] = {nullptr, "Gtk", "Gdk", "GLib",
"GLib-GObject"};
for (size_t i = 0; i < std::size(kLogDomains); i++) {
g_log_set_handler(
kLogDomains[i],
static_cast<GLogLevelFlags>(G_LOG_FLAG_RECURSION | G_LOG_FLAG_FATAL |
G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL |
G_LOG_LEVEL_WARNING),
GLibLogHandler, nullptr);
}
}
#endif
NOINLINE void ResetThread_IO(
std::unique_ptr<BrowserProcessIOThread> io_thread) {
io_thread.reset();
}
enum WorkerPoolType : size_t {
BACKGROUND = 0,
BACKGROUND_BLOCKING,
FOREGROUND,
FOREGROUND_BLOCKING,
WORKER_POOL_COUNT
};
#if BUILDFLAG(IS_FUCHSIA)
void InitDefaultJob() {
zx::job job;
zx_status_t result = zx::job::create(*zx::job::default_job(), 0, &job);
ZX_CHECK(ZX_OK == result, result) << "zx_job_create";
base::SetDefaultJob(std::move(job));
}
#endif
#if defined(ENABLE_IPC_FUZZER)
bool GetBuildDirectory(base::FilePath* result) {
if (!base::PathService::Get(base::DIR_EXE, result))
return false;
#if BUILDFLAG(IS_MAC)
if (base::mac::AmIBundled()) {
*result = result->DirName().DirName().DirName();
}
#endif
return true;
}
void SetFileUrlPathAliasForIpcFuzzer() {
if (base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kFileUrlPathAlias))
return;
base::FilePath build_directory;
if (!GetBuildDirectory(&build_directory)) {
LOG(ERROR) << "Failed to get build directory for /gen path alias.";
return;
}
const base::CommandLine::StringType alias_switch =
FILE_PATH_LITERAL("/gen=") + build_directory.AppendASCII("gen").value();
base::CommandLine::ForCurrentProcess()->AppendSwitchNative(
switches::kFileUrlPathAlias, alias_switch);
}
#endif
std::unique_ptr<base::MemoryPressureMonitor> CreateMemoryPressureMonitor(
const base::CommandLine& command_line) {
if (command_line.HasSwitch(switches::kBrowserTest))
return nullptr;
std::unique_ptr<memory_pressure::MultiSourceMemoryPressureMonitor> monitor;
#if BUILDFLAG(IS_APPLE) || BUILDFLAG(IS_WIN) || BUILDFLAG(IS_FUCHSIA) || \
BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
monitor =
std::make_unique<memory_pressure::MultiSourceMemoryPressureMonitor>();
#endif
if (monitor)
monitor->MaybeStartPlatformVoter();
return monitor;
}
#if BUILDFLAG(IS_CHROMEOS_ASH)
mojo::PendingRemote<data_decoder::mojom::BleScanParser> GetBleScanParser() {
static base::NoDestructor<data_decoder::DataDecoder> decoder;
mojo::PendingRemote<data_decoder::mojom::BleScanParser> ble_scan_parser;
decoder->GetService()->BindBleScanParser(
ble_scan_parser.InitWithNewPipeAndPassReceiver());
return ble_scan_parser;
}
#endif
#if BUILDFLAG(IS_WIN)
BASE_FEATURE(kBrowserDynamicCodeDisabled,
"BrowserDynamicCodeDisabled",
base::FEATURE_DISABLED_BY_DEFAULT);
#endif
class OopDataDecoder : public data_decoder::ServiceProvider {
public:
OopDataDecoder() { data_decoder::ServiceProvider::Set(this); }
OopDataDecoder(const OopDataDecoder&) = delete;
OopDataDecoder& operator=(const OopDataDecoder&) = delete;
~OopDataDecoder() override { data_decoder::ServiceProvider::Set(nullptr); }
void BindDataDecoderService(
mojo::PendingReceiver<data_decoder::mojom::DataDecoderService> receiver)
override {
ServiceProcessHost::Launch(
std::move(receiver),
ServiceProcessHost::Options()
.WithDisplayName("Data Decoder Service")
.Pass());
}
};
class InProcessDataDecoder : public data_decoder::ServiceProvider {
public:
InProcessDataDecoder()
: task_runner_(GetIOThreadTaskRunner({})) {
data_decoder::ServiceProvider::Set(this);
}
InProcessDataDecoder(const InProcessDataDecoder&) = delete;
InProcessDataDecoder& operator=(const InProcessDataDecoder&) = delete;
~InProcessDataDecoder() {
data_decoder::ServiceProvider::Set(nullptr);
}
void BindDataDecoderService(
mojo::PendingReceiver<data_decoder::mojom::DataDecoderService> receiver) {
if (!task_runner_->RunsTasksInCurrentSequence()) {
task_runner_->PostTask(
FROM_HERE,
base::BindOnce(&InProcessDataDecoder::BindDataDecoderService,
weak_ptr_factory_.GetWeakPtr(), std::move(receiver)));
return;
}
receivers_.Add(&service_, std::move(receiver));
}
private:
const scoped_refptr<base::SequencedTaskRunner> task_runner_;
data_decoder::DataDecoderService service_;
mojo::ReceiverSet<data_decoder::mojom::DataDecoderService> receivers_;
base::WeakPtrFactory<InProcessDataDecoder> weak_ptr_factory_{this};
};
void BindHidManager(mojo::PendingReceiver<device::mojom::HidManager> receiver) {
#if !BUILDFLAG(IS_ANDROID)
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
GetUIThreadTaskRunner({})->PostTask(
FROM_HERE, base::BindOnce(&BindHidManager, std::move(receiver)));
return;
}
GetDeviceService().BindHidManager(std::move(receiver));
#endif
}
uint32_t GenerateBrowserSalt() {
uint32_t salt;
do {
salt = base::RandUint64();
} while (salt == 0);
return salt;
}
}
BrowserMainLoop* g_current_browser_main_loop = nullptr;
#if BUILDFLAG(IS_ANDROID)
namespace {
bool g_post_startup_tasks = true;
}
void BrowserMainLoop::EnableStartupTasks(bool enabled) {
g_post_startup_tasks = enabled;
}
#endif
BrowserMainLoop* BrowserMainLoop::GetInstance() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
return g_current_browser_main_loop;
}
media::AudioManager* BrowserMainLoop::GetAudioManager() {
return g_current_browser_main_loop->audio_manager();
}
BrowserMainLoop::BrowserMainLoop(
MainFunctionParams parameters,
std::unique_ptr<base::ThreadPoolInstance::ScopedExecutionFence>
scoped_execution_fence)
: parameters_(std::move(parameters)),
parsed_command_line_(*parameters_.command_line),
result_code_(RESULT_CODE_NORMAL_EXIT),
created_threads_(false),
scoped_execution_fence_(std::move(scoped_execution_fence))
#if !BUILDFLAG(IS_ANDROID)
,
scoped_best_effort_execution_fence_(absl::in_place)
#endif
{
DCHECK(!g_current_browser_main_loop);
DCHECK(scoped_execution_fence_)
<< "ThreadPool must be halted before kicking off content.";
g_current_browser_main_loop = this;
}
BrowserMainLoop::~BrowserMainLoop() {
DCHECK_EQ(this, g_current_browser_main_loop);
ui::Clipboard::DestroyClipboardForCurrentThread();
g_current_browser_main_loop = nullptr;
}
void BrowserMainLoop::Init() {
TRACE_EVENT0("startup", "BrowserMainLoop::Init");
if (parameters_.startup_data) {
StartupDataImpl* startup_data =
static_cast<StartupDataImpl*>(parameters_.startup_data.get());
DCHECK(!io_thread_);
io_thread_ = std::move(startup_data->io_thread);
DCHECK(!mojo_ipc_support_);
mojo_ipc_support_ = std::move(startup_data->mojo_ipc_support);
parameters_.startup_data.reset();
}
parts_ = GetContentClient()->browser()->CreateBrowserMainParts(
!!parameters_.ui_task);
}
int BrowserMainLoop::EarlyInitialization() {
TRACE_EVENT0("startup", "BrowserMainLoop::EarlyInitialization");
#if BUILDFLAG(USE_ZYGOTE)
DCHECK(SandboxHostLinux::GetInstance()->IsInitialized());
#endif
#if defined(USE_GLIB)
#if !GLIB_CHECK_VERSION(2, 35, 0)
g_type_init();
#endif
SetUpGLibLogHandler();
#endif
if (parts_) {
const int pre_early_init_error_code = parts_->PreEarlyInitialization();
if (pre_early_init_error_code != RESULT_CODE_NORMAL_EXIT)
return pre_early_init_error_code;
}
#if BUILDFLAG(IS_WIN)
base::InitializePlatformThreadFeatures();
#endif
DCHECK(base::CurrentUIThread::IsSet());
base::PlatformThread::SetCurrentThreadType(base::ThreadType::kCompositing);
#if BUILDFLAG(IS_APPLE) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || \
BUILDFLAG(IS_ANDROID)
base::IncreaseFdLimitTo(8192);
#endif
#if BUILDFLAG(IS_WIN)
net::EnsureWinsockInit();
#endif
#if BUILDFLAG(USE_NSS_CERTS)
crypto::EnsureNSPRInit();
#endif
#if BUILDFLAG(IS_FUCHSIA)
InitDefaultJob();
zx_status_t result =
zx::job::default_job()->set_critical(0, *zx::process::self());
ZX_CHECK(ZX_OK == result, result) << "zx_job_set_critical";
#endif
#if BUILDFLAG(IS_WIN)
if (!parsed_command_line_->HasSwitch(switches::kSingleProcess) &&
base::FeatureList::IsEnabled(kBrowserDynamicCodeDisabled) &&
parameters_.sandbox_info && parameters_.sandbox_info->broker_services) {
parameters_.sandbox_info->broker_services->RatchetDownSecurityMitigations(
sandbox::MITIGATION_DYNAMIC_CODE_DISABLE_WITH_OPT_OUT);
}
#endif
if (parsed_command_line_->HasSwitch(switches::kRendererProcessLimit)) {
std::string limit_string = parsed_command_line_->GetSwitchValueASCII(
switches::kRendererProcessLimit);
size_t process_limit;
if (base::StringToSizeT(limit_string, &process_limit)) {
RenderProcessHost::SetMaxRendererProcessCount(process_limit);
}
}
if (parts_)
parts_->PostEarlyInitialization();
return RESULT_CODE_NORMAL_EXIT;
}
void BrowserMainLoop::PreCreateMainMessageLoop() {
TRACE_EVENT0(
"startup",
"BrowserMainLoop::CreateMainMessageLoop:PreCreateMainMessageLoop");
if (parts_) {
parts_->PreCreateMainMessageLoop();
}
}
void BrowserMainLoop::CreateMainMessageLoop() {
TRACE_EVENT0("startup", "BrowserMainLoop::CreateMainMessageLoop");
base::PlatformThread::SetName("CrBrowserMain");
DCHECK(base::SingleThreadTaskRunner::HasCurrentDefault());
DCHECK(base::CurrentUIThread::IsSet());
main_thread_.reset(new BrowserThreadImpl(
BrowserThread::UI, base::SingleThreadTaskRunner::GetCurrentDefault()));
}
void BrowserMainLoop::PostCreateMainMessageLoop() {
TRACE_EVENT0("startup", "BrowserMainLoop::PostCreateMainMessageLoop");
{
TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SystemMonitor");
system_monitor_ = std::make_unique<base::SystemMonitor>();
}
{
TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:PowerMonitor");
if (!base::PowerMonitor::IsInitialized())
base::PowerMonitor::Initialize(MakePowerMonitorDeviceSource());
}
{
TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:HighResTimerManager");
hi_res_timer_manager_ =
std::make_unique<base::HighResolutionTimerManager>();
}
{
TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:NetworkChangeNotifier");
network_change_notifier_ = net::NetworkChangeNotifier::CreateIfNeeded();
}
{
TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:ScreenlockMonitor");
std::unique_ptr<ScreenlockMonitorSource> screenlock_monitor_source =
std::make_unique<ScreenlockMonitorDeviceSource>();
screenlock_monitor_ = std::make_unique<ScreenlockMonitor>(
std::move(screenlock_monitor_source));
}
{
TRACE_EVENT0("startup",
"BrowserMainLoop::Subsystem:ContentWebUIController");
RegisterContentWebUIConfigs();
}
{
TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:OnlineStateObserver");
online_state_observer_ = std::make_unique<BrowserOnlineStateObserver>();
}
{ base::SetRecordActionTaskRunner(GetUIThreadTaskRunner({})); }
if (!parsed_command_line_->HasSwitch(switches::kSingleProcess)) {
base::DiscardableMemoryAllocator::SetInstance(
discardable_memory::DiscardableSharedMemoryManager::Get());
}
if (parts_)
parts_->PostCreateMainMessageLoop();
#if BUILDFLAG(IS_ANDROID)
{
TRACE_EVENT0("startup",
"BrowserMainLoop::Subsystem:ScopedSurfaceRequestManager");
if (UsingInProcessGpu()) {
gpu::ScopedSurfaceRequestConduit::SetInstance(
ScopedSurfaceRequestManager::GetInstance());
}
}
if (!parsed_command_line_->HasSwitch(
switches::kDisableScreenOrientationLock)) {
TRACE_EVENT0("startup",
"BrowserMainLoop::Subsystem:ScreenOrientationProvider");
screen_orientation_delegate_ =
std::make_unique<ScreenOrientationDelegateAndroid>();
}
base::trace_event::TraceLog::GetInstance()->AddEnabledStateObserver(
base::trace_event::CPUFreqMonitor::GetInstance());
#endif
if (UsingInProcessGpu()) {
InitializeSkia();
} else {
InitSkiaEventTracer();
base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
skia::SkiaMemoryDumpProvider::GetInstance(), "Skia", nullptr);
InitializeSkiaAnalyticAntialiasing();
}
base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
sql::SqlMemoryDumpProvider::GetInstance(), "Sql", nullptr);
#if BUILDFLAG(IS_CHROMEOS_ASH)
device::BluetoothAdapterFactory::SetBleScanParserCallback(
base::BindRepeating(&GetBleScanParser));
#else
network::TransitionalURLLoaderFactoryOwner::DisallowUsageInProcess();
#endif
{
TRACE_EVENT0("startup",
"BrowserMainLoop::Subsystem:BrowserAccessibilityStateImpl");
BrowserAccessibilityStateImpl::GetInstance()->InitBackgroundTasks();
}
}
void BrowserMainLoop::CreateMessageLoopForEarlyShutdown() {
CreateMainMessageLoop();
}
int BrowserMainLoop::PreCreateThreads() {
TRACE_EVENT0("startup", "BrowserMainLoop::PreCreateThreads");
DCHECK(!GpuDataManagerImpl::Initialized());
if (parts_) {
result_code_ = parts_->PreCreateThreads();
}
InitializeMemoryManagementComponent();
#if BUILDFLAG(IS_ANDROID)
memory_pressure::UserLevelMemoryPressureSignalGenerator::Initialize();
#endif
#if BUILDFLAG(ENABLE_PLUGINS)
{
TRACE_EVENT0("startup", "BrowserMainLoop::PluginService");
PluginService::GetInstance()->Init();
}
#endif
#if BUILDFLAG(ENABLE_LIBRARY_CDMS) || BUILDFLAG(IS_ANDROID)
CdmRegistry::GetInstance()->Init();
#endif
#if BUILDFLAG(IS_OHOS) && defined(OHOS_ENABLE_CDM)
CdmRegistry::GetInstance()->Init();
LOG(INFO) << "[DRM]" << __func__;
#endif
#if BUILDFLAG(IS_MAC)
ui::WindowResizeHelperMac::Get()->Init(
base::SingleThreadTaskRunner::GetCurrentDefault());
#endif
GpuDataManagerImpl::GetInstance();
DCHECK(GpuDataManagerImpl::Initialized());
GpuDataManagerImpl::GetInstance()->StartUmaTimer();
#if !BUILDFLAG(GOOGLE_CHROME_BRANDING) || BUILDFLAG(IS_ANDROID) || \
BUILDFLAG(IS_IOS)
if (parsed_command_line_->HasSwitch(switches::kSingleProcess))
RenderProcessHost::SetRunRendererInProcess(true);
#endif
SiteIsolationPolicy::ApplyGlobalIsolatedOrigins();
SetPseudonymizationSalt(GenerateBrowserSalt());
return result_code_;
}
void BrowserMainLoop::CreateStartupTasks() {
TRACE_EVENT0("startup", "BrowserMainLoop::CreateStartupTasks");
DCHECK(!startup_task_runner_);
#if BUILDFLAG(IS_ANDROID)
if (!g_post_startup_tasks)
return;
startup_task_runner_ = std::make_unique<StartupTaskRunner>(
base::BindOnce(&BrowserStartupComplete),
GetUIThreadTaskRunner({BrowserTaskType::kDefault}));
#else
startup_task_runner_ = std::make_unique<StartupTaskRunner>(
base::OnceCallback<void(int)>(),
base::SingleThreadTaskRunner::GetCurrentDefault());
#endif
StartupTask pre_create_threads = base::BindOnce(
&BrowserMainLoop::PreCreateThreads, base::Unretained(this));
startup_task_runner_->AddTask(std::move(pre_create_threads));
StartupTask create_threads =
base::BindOnce(&BrowserMainLoop::CreateThreads, base::Unretained(this));
startup_task_runner_->AddTask(std::move(create_threads));
StartupTask post_create_threads = base::BindOnce(
&BrowserMainLoop::PostCreateThreads, base::Unretained(this));
startup_task_runner_->AddTask(std::move(post_create_threads));
StartupTask pre_main_message_loop_run = base::BindOnce(
&BrowserMainLoop::PreMainMessageLoopRun, base::Unretained(this));
startup_task_runner_->AddTask(std::move(pre_main_message_loop_run));
#if BUILDFLAG(IS_ANDROID)
StartupTask intercept_main_message_loop_run = base::BindOnce(
[](BrowserMainLoop* self) {
self->InterceptMainMessageLoopRun();
return self->result_code_;
},
base::Unretained(this));
startup_task_runner_->AddTask(std::move(intercept_main_message_loop_run));
#endif
#if BUILDFLAG(IS_ANDROID)
startup_task_runner_->StartRunningTasksAsync();
#else
startup_task_runner_->RunAllTasksNow();
#endif
}
scoped_refptr<base::SingleThreadTaskRunner>
BrowserMainLoop::GetResizeTaskRunner() {
#if BUILDFLAG(IS_MAC)
scoped_refptr<base::SingleThreadTaskRunner> task_runner =
ui::WindowResizeHelperMac::Get()->task_runner();
return task_runner ? task_runner
: base::SingleThreadTaskRunner::GetCurrentDefault();
#else
return base::SingleThreadTaskRunner::GetCurrentDefault();
#endif
}
gpu::GpuChannelEstablishFactory*
BrowserMainLoop::gpu_channel_establish_factory() const {
return BrowserGpuChannelHostFactory::instance();
}
#if BUILDFLAG(IS_ANDROID)
void BrowserMainLoop::SynchronouslyFlushStartupTasks() {
startup_task_runner_->RunAllTasksNow();
}
#endif
int BrowserMainLoop::CreateThreads() {
TRACE_EVENT0("startup,rail", "BrowserMainLoop::CreateThreads");
scoped_execution_fence_.reset();
if (!io_thread_) {
io_thread_ = BrowserTaskExecutor::CreateIOThread();
}
io_thread_->RegisterAsBrowserThread();
BrowserTaskExecutor::InitializeIOThread();
GetContentClient()->browser()->PostAfterStartupTask(
FROM_HERE, base::SequencedTaskRunner::GetCurrentDefault(),
base::BindOnce(
[](BrowserMainLoop* browser_main_loop) {
content::BrowserTaskExecutor::OnStartupComplete();
browser_main_loop->scoped_best_effort_execution_fence_.reset();
},
base::Unretained(this)));
created_threads_ = true;
return result_code_;
}
int BrowserMainLoop::PostCreateThreads() {
TRACE_EVENT0("startup", "BrowserMainLoop::PostCreateThreads");
tracing_controller_ = std::make_unique<content::TracingControllerImpl>();
content::BackgroundTracingManagerImpl::GetInstance()
.AddMetadataGeneratorFunction();
if (parts_)
parts_->PostCreateThreads();
PostCreateThreadsImpl();
return result_code_;
}
int BrowserMainLoop::PreMainMessageLoopRun() {
TRACE_EVENT0("startup", "BrowserMainLoop::PreMainMessageLoopRun");
#if BUILDFLAG(IS_ANDROID)
bool use_display_wide_color_gamut =
GetContentClient()->browser()->GetWideColorGamutHeuristic() ==
ContentBrowserClient::WideColorGamutHeuristic::kUseDisplay;
ui::SetScreenAndroid(use_display_wide_color_gamut);
#endif
if (parts_)
result_code_ = parts_->PreMainMessageLoopRun();
if (result_code_ == RESULT_CODE_NORMAL_EXIT) {
FirstPartySetsHandlerImpl::GetInstance()->Init(
GetContentClient()->browser()->GetFirstPartySetsDirectory(),
LocalSetDeclaration(
base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
network::switches::kUseFirstPartySet)));
}
variations::MaybeScheduleFakeCrash();
base::CurrentThread::Get()->RegisterOnNextIdleCallback(base::BindOnce(
[](BrowserMainLoop* self) {
if (self->parts_)
self->parts_->OnFirstIdle();
self->responsiveness_watcher_->OnFirstIdle();
auto enable_message_pump_metrics =
base::BindRepeating([](const char* thread_name) {
base::CurrentThread::Get()->EnableMessagePumpTimeKeeperMetrics(
thread_name);
});
enable_message_pump_metrics.Run("BrowserUI");
GetIOThreadTaskRunner({})->PostTask(
FROM_HERE, BindOnce(enable_message_pump_metrics, "BrowserIO"));
},
base::Unretained(this)));
base::DisallowUnresponsiveTasks();
responsiveness_watcher_ = new responsiveness::Watcher;
responsiveness_watcher_->SetUp();
return result_code_;
}
BrowserMainLoop::ProceedWithMainMessageLoopRun
BrowserMainLoop::InterceptMainMessageLoopRun() {
if (parts_ && !parts_->ShouldInterceptMainMessageLoopRun())
return ProceedWithMainMessageLoopRun(false);
if (parameters_.ui_task) {
std::move(parameters_.ui_task).Run();
return ProceedWithMainMessageLoopRun(false);
}
return ProceedWithMainMessageLoopRun(true);
}
void BrowserMainLoop::RunMainMessageLoop() {
#if BUILDFLAG(IS_ANDROID)
NOTREACHED();
#else
if (InterceptMainMessageLoopRun() != ProceedWithMainMessageLoopRun(true))
return;
auto main_run_loop = std::make_unique<base::RunLoop>();
if (parts_)
parts_->WillRunMainMessageLoop(main_run_loop);
#if BUILDFLAG(IS_MAC)
if (parameters_.autorelease_pool)
parameters_.autorelease_pool->Recycle();
#endif
DCHECK(main_run_loop);
main_run_loop->Run();
#endif
}
void BrowserMainLoop::PreShutdown() {
#ifdef LEAK_SANITIZER
#if BUILDFLAG(IS_MAC)
if (parameters_.autorelease_pool)
parameters_.autorelease_pool->Recycle();
#endif
__lsan_do_leak_check();
#endif
base::CurrentThread::Get()->RegisterOnNextIdleCallback(base::NullCallback());
ui::Clipboard::OnPreShutdownForCurrentThread();
}
void BrowserMainLoop::ShutdownThreadsAndCleanUp() {
if (!created_threads_) {
return;
}
TRACE_EVENT0("shutdown", "BrowserMainLoop::ShutdownThreadsAndCleanUp");
base::PermanentThreadAllowance::AllowBlocking();
GetIOThreadTaskRunner({})->PostTask(
FROM_HERE, base::BindOnce(base::IgnoreResult(
&base::PermanentThreadAllowance::AllowBlocking)));
base::PermanentThreadAllowance::AllowBaseSyncPrimitives();
GetIOThreadTaskRunner({})->PostTask(
FROM_HERE,
base::BindOnce(base::IgnoreResult(
&base::PermanentThreadAllowance::AllowBaseSyncPrimitives)));
if (RenderProcessHost::run_renderer_in_process())
RenderProcessHostImpl::ShutDownInProcessRenderer();
if (parts_) {
TRACE_EVENT0("shutdown",
"BrowserMainLoop::Subsystem:PostMainMessageLoopRun");
parts_->PostMainMessageLoopRun();
}
if (midi_service_) {
TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:MidiService");
midi_service_->Shutdown();
}
{
TRACE_EVENT0("shutdown",
"BrowserMainLoop::Subsystem:SpeechRecognitionManager");
io_thread_->task_runner()->DeleteSoon(
FROM_HERE, speech_recognition_manager_.release());
}
TtsControllerImpl::GetInstance()->Shutdown();
memory_pressure_monitor_.reset();
ShutDownNetworkService();
BrowserProcessIOThread::ProcessHostCleanUp();
#if BUILDFLAG(IS_MAC)
BrowserCompositorMac::DisableRecyclingForShutdown();
#endif
#if defined(USE_AURA)
if (env_) {
env_->set_context_factory(nullptr);
}
#endif
#if defined(USE_AURA) || BUILDFLAG(IS_MAC)
{
TRACE_EVENT0("shutdown",
"BrowserMainLoop::Subsystem:ImageTransportFactory");
ImageTransportFactory::Terminate();
}
#endif
#if !BUILDFLAG(IS_ANDROID)
host_frame_sink_manager_.reset();
compositing_mode_reporter_impl_.reset();
#endif
#if BUILDFLAG(IS_WIN)
system_message_window_.reset();
#elif BUILDFLAG(IS_MAC)
device_monitor_mac_.reset();
#endif
if (BrowserGpuChannelHostFactory::instance())
BrowserGpuChannelHostFactory::instance()->CloseChannel();
mojo_ipc_support_.reset();
if (save_file_manager_)
save_file_manager_->Shutdown();
{
TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IOThread");
ResetThread_IO(std::move(io_thread_));
}
{
TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:ThreadPool");
base::ThreadPoolInstance::Get()->Shutdown();
}
{
TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUChannelFactory");
if (BrowserGpuChannelHostFactory::instance()) {
BrowserGpuChannelHostFactory::Terminate();
}
}
{
TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GamepadService");
device::GamepadService::GetInstance()->Terminate();
}
{
TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DeleteDataSources");
URLDataManager::DeleteDataSources();
}
{
TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:AudioMan");
if (audio_manager_ && !audio_manager_->Shutdown()) {
std::ignore = audio_manager_.release();
std::ignore = user_input_monitor_.release();
}
std::ignore = audio_system_.release();
}
if (parts_) {
TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:PostDestroyThreads");
parts_->PostDestroyThreads();
}
}
media::AudioManager* BrowserMainLoop::audio_manager() const {
DCHECK(audio_manager_) << "AudioManager is not instantiated - running the "
"audio service out of process?";
return audio_manager_.get();
}
void BrowserMainLoop::GetCompositingModeReporter(
mojo::PendingReceiver<viz::mojom::CompositingModeReporter> receiver) {
#if BUILDFLAG(IS_ANDROID)
return;
#else
compositing_mode_reporter_impl_->BindReceiver(std::move(receiver));
#endif
}
void BrowserMainLoop::PostCreateThreadsImpl() {
TRACE_EVENT0("startup", "BrowserMainLoop::PostCreateThreadsImpl");
InitializeMojo();
#if BUILDFLAG(IS_OHOS)
data_decoder_service_provider_ = std::make_unique<InProcessDataDecoder>();
#else
data_decoder_service_provider_ = std::make_unique<OopDataDecoder>();
#endif
HistogramSynchronizer::GetInstance();
FieldTrialSynchronizer::CreateInstance();
if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kSingleProcess)) {
cc::SetClientNameForMetrics("Browser");
}
InitGpuDiskCacheFactorySingleton();
viz::GpuHostImpl::InitFontRenderParams(
gfx::GetFontRenderParams(gfx::FontRenderParamsQuery(), nullptr));
bool always_uses_gpu = true;
bool established_gpu_channel = false;
#if BUILDFLAG(IS_ANDROID)
established_gpu_channel = false;
always_uses_gpu = ShouldStartGpuProcessOnBrowserStartup();
BrowserGpuChannelHostFactory::Initialize(established_gpu_channel);
#else
established_gpu_channel = true;
if (parsed_command_line_->HasSwitch(switches::kDisableGpu) ||
parsed_command_line_->HasSwitch(switches::kDisableGpuCompositing) ||
parsed_command_line_->HasSwitch(switches::kDisableGpuEarlyInit)) {
established_gpu_channel = always_uses_gpu = false;
}
host_frame_sink_manager_ = std::make_unique<viz::HostFrameSinkManager>();
BrowserGpuChannelHostFactory::Initialize(established_gpu_channel);
compositing_mode_reporter_impl_ =
std::make_unique<viz::CompositingModeReporterImpl>();
auto transport_factory = std::make_unique<VizProcessTransportFactory>(
BrowserGpuChannelHostFactory::instance(), GetResizeTaskRunner(),
compositing_mode_reporter_impl_.get());
transport_factory->ConnectHostFrameSinkManager();
ImageTransportFactory::SetFactory(std::move(transport_factory));
#if defined(USE_AURA)
env_->set_context_factory(GetContextFactory());
#endif
#endif
#if BUILDFLAG(IS_ANDROID)
base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
tracing::GraphicsMemoryDumpProvider::GetInstance(), "AndroidGraphics",
nullptr);
#endif
{
TRACE_EVENT0("startup", "PostCreateThreads::Subsystem:AudioMan");
InitializeAudio();
}
{
TRACE_EVENT0("startup", "PostCreateThreads::Subsystem:MidiService");
midi_service_ = std::make_unique<midi::MidiService>();
}
{
TRACE_EVENT0("startup", "PostCreateThreads::Subsystem:Devices");
device::GamepadService::GetInstance()->StartUp(
base::BindRepeating(&BindHidManager));
#if !BUILDFLAG(IS_ANDROID)
device::FidoHidDiscovery::SetHidManagerBinder(
base::BindRepeating(&BindHidManager));
#endif
}
#if BUILDFLAG(IS_WIN)
system_message_window_ = std::make_unique<media::SystemMessageWindowWin>();
#elif (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)) && defined(USE_UDEV)
device_monitor_linux_ = std::make_unique<media::DeviceMonitorLinux>();
#elif BUILDFLAG(IS_MAC)
device_monitor_mac_ = std::make_unique<media::DeviceMonitorMac>(
base::ThreadPool::CreateSingleThreadTaskRunner(
{base::TaskPriority::USER_VISIBLE}));
#endif
WebRTCInternals::CreateSingletonInstance();
{
TRACE_EVENT0("startup",
"BrowserMainLoop::PostCreateThreads:InitMediaStreamManager");
media_stream_manager_ =
std::make_unique<MediaStreamManager>(audio_system_.get());
}
{
TRACE_EVENT0("startup",
"BrowserMainLoop::PostCreateThreads:InitSpeechRecognition");
speech_recognition_manager_.reset(new SpeechRecognitionManagerImpl(
audio_system_.get(), media_stream_manager_.get()));
}
{
TRACE_EVENT0("startup",
"BrowserMainLoop::PostCreateThreads::InitUserInputMonitor");
user_input_monitor_ = media::UserInputMonitor::Create(
io_thread_->task_runner(),
base::SingleThreadTaskRunner::GetCurrentDefault());
}
{
TRACE_EVENT0("startup",
"BrowserMainLoop::PostCreateThreads::SaveFileManager");
save_file_manager_ = new SaveFileManager();
}
std::vector<base::PlatformThreadId> allowed_clipboard_threads;
allowed_clipboard_threads.push_back(base::PlatformThread::CurrentId());
#if BUILDFLAG(IS_WIN)
allowed_clipboard_threads.push_back(io_thread_->GetThreadId());
#endif
ui::Clipboard::SetAllowedThreads(allowed_clipboard_threads);
if (!established_gpu_channel && always_uses_gpu) {
TRACE_EVENT_INSTANT0("gpu", "Post task to launch GPU process",
TRACE_EVENT_SCOPE_THREAD);
GpuProcessHost::Get(GPU_PROCESS_KIND_SANDBOXED, true );
}
#if BUILDFLAG(IS_WIN)
GpuDataManagerImpl::GetInstance()->PostCreateThreads();
#endif
if (MediaKeysListenerManager::IsMediaKeysListenerManagerEnabled()) {
media_keys_listener_manager_ =
std::make_unique<MediaKeysListenerManagerImpl>();
}
#if BUILDFLAG(IS_MAC)
ThemeHelperMac::GetInstance();
#endif
#if BUILDFLAG(IS_ANDROID)
media::SetMediaDrmBridgeClient(GetContentClient()->GetMediaDrmBridgeClient());
if (base::FeatureList::IsEnabled(features::kFontSrcLocalMatching)) {
FontUniqueNameLookup::GetInstance();
}
#endif
#if BUILDFLAG(IS_OHOS) && defined(OHOS_ENABLE_CDM)
media::SetMediaDrmBridgeClient(GetContentClient()->GetMediaDrmBridgeClient());
#endif
#if defined(OHOS_WPT)
if (base::FeatureList::IsEnabled(features::kFontSrcLocalMatching)) {
FontUniqueNameLookup::GetInstance();
}
#endif
#if defined(ENABLE_IPC_FUZZER)
SetFileUrlPathAliasForIpcFuzzer();
#endif
}
bool BrowserMainLoop::UsingInProcessGpu() const {
return parsed_command_line_->HasSwitch(switches::kSingleProcess) ||
parsed_command_line_->HasSwitch(switches::kInProcessGPU);
}
void BrowserMainLoop::InitializeMemoryManagementComponent() {
memory_pressure_monitor_ = CreateMemoryPressureMonitor(*parsed_command_line_);
}
bool BrowserMainLoop::InitializeToolkit() {
TRACE_EVENT0("startup", "BrowserMainLoop::InitializeToolkit");
#if BUILDFLAG(IS_WIN)
INITCOMMONCONTROLSEX config;
config.dwSize = sizeof(config);
config.dwICC = ICC_WIN95_CLASSES;
if (!InitCommonControlsEx(&config))
PLOG(FATAL);
#endif
#if defined(USE_AURA)
env_ = aura::Env::CreateInstance();
if (!env_)
return false;
#endif
if (parts_)
parts_->ToolkitInitialized();
return true;
}
void BrowserMainLoop::InitializeMojo() {
if (!parsed_command_line_->HasSwitch(switches::kSingleProcess)) {
mojo::SyncCallRestrictions::DisallowSyncCall();
}
StartupTracingController::GetInstance().StartIfNeeded();
#if BUILDFLAG(MOJO_RANDOM_DELAYS_ENABLED)
mojo::BeginRandomMojoDelays();
#endif
}
void BrowserMainLoop::InitializeAudio() {
DCHECK(!audio_manager_);
audio_manager_ = GetContentClient()->browser()->CreateAudioManager(
MediaInternals::GetInstance());
DCHECK_EQ(!!audio_manager_,
GetContentClient()->browser()->OverridesAudioManager());
if (!audio_manager_ &&
(base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kSingleProcess) ||
!base::FeatureList::IsEnabled(features::kAudioServiceOutOfProcess))) {
audio_manager_ =
media::AudioManager::Create(std::make_unique<media::AudioThreadImpl>(),
MediaInternals::GetInstance());
CHECK(audio_manager_);
}
if (audio_manager_) {
TRACE_EVENT_INSTANT0("startup", "Starting Audio service task runner",
TRACE_EVENT_SCOPE_THREAD);
#if BUILDFLAG(IS_MAC)
DCHECK(audio_manager_->GetTaskRunner()->BelongsToCurrentThread());
#endif
audio::Service::GetInProcessTaskRunner()->StartWithTaskRunner(
audio_manager_->GetTaskRunner());
}
if (base::FeatureList::IsEnabled(features::kAudioServiceLaunchOnStartup)) {
content::GetUIThreadTaskRunner({base::TaskPriority::BEST_EFFORT})
->PostTask(FROM_HERE, base::BindOnce([]() {
TRACE_EVENT0("audio", "Starting audio service");
GetAudioService();
}));
}
audio_system_ = CreateAudioSystemForAudioService();
CHECK(audio_system_);
}
bool BrowserMainLoop::AudioServiceOutOfProcess() const {
return base::FeatureList::IsEnabled(features::kAudioServiceOutOfProcess) &&
!GetContentClient()->browser()->OverridesAudioManager();
}
SmsProvider* BrowserMainLoop::GetSmsProvider() {
if (!sms_provider_) {
sms_provider_ = SmsProvider::Create();
}
return sms_provider_.get();
}
void BrowserMainLoop::SetSmsProviderForTesting(
std::unique_ptr<SmsProvider> provider) {
sms_provider_ = std::move(provider);
}
base::PlatformThreadId BrowserMainLoop::GetIOThreadId() {
CHECK(io_thread_ && io_thread_->IsRunning());
return io_thread_->GetThreadId();
}
}