1 // Copyright 2011 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
6 #include "base/command_line.h"
7 #include "base/debug/leak_annotations.h"
8 #include "base/message_loop/message_pump_type.h"
9 #include "base/power_monitor/power_monitor.h"
10 #include "base/run_loop.h"
11 #include "base/task/single_thread_task_executor.h"
12 #include "base/threading/platform_thread.h"
13 #include "base/timer/hi_res_timer_manager.h"
14 #include "build/build_config.h"
15 #include "build/chromeos_buildflags.h"
16 #include "components/services/screen_ai/buildflags/buildflags.h"
17 #include "content/child/child_process.h"
18 #include "content/common/content_switches_internal.h"
19 #include "content/common/partition_alloc_support.h"
20 #include "content/public/common/content_client.h"
21 #include "content/public/common/content_switches.h"
22 #include "content/public/common/main_function_params.h"
23 #include "content/public/utility/content_utility_client.h"
24 #include "content/utility/utility_thread_impl.h"
25 #include "printing/buildflags/buildflags.h"
26 #include "sandbox/policy/mojom/sandbox.mojom.h"
27 #include "sandbox/policy/sandbox.h"
28 #include "sandbox/policy/sandbox_type.h"
29 #include "services/tracing/public/cpp/trace_startup.h"
30 #include "third_party/abseil-cpp/absl/types/optional.h"
31 #include "third_party/icu/source/common/unicode/unistr.h"
32 #include "third_party/icu/source/i18n/unicode/timezone.h"
34 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
35 #include "content/utility/speech/speech_recognition_sandbox_hook_linux.h"
36 #if BUILDFLAG(ENABLE_PRINTING)
37 #include "printing/sandbox/print_backend_sandbox_hook_linux.h"
39 #include "sandbox/policy/linux/sandbox_linux.h"
40 #include "services/audio/audio_sandbox_hook_linux.h"
41 #include "services/network/network_sandbox_hook_linux.h"
44 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_ASH)
45 #include "gpu/config/gpu_info_collector.h"
46 #include "media/gpu/sandbox/hardware_video_decoding_sandbox_hook_linux.h"
48 // gn check is not smart enough to realize that this include only applies to
49 // Linux/ash-chrome and the BUILD.gn dependencies correctly account for that.
50 #include "third_party/angle/src/gpu_info_util/SystemInfo.h" // nogncheck
51 #endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_ASH)
53 #if BUILDFLAG(IS_CHROMEOS_ASH)
54 #include "ash/services/ime/ime_sandbox_hook.h"
55 #include "chromeos/ash/components/assistant/buildflags.h"
56 #include "chromeos/services/tts/tts_sandbox_hook.h"
58 #if BUILDFLAG(ENABLE_CROS_LIBASSISTANT)
59 #include "chromeos/ash/services/libassistant/libassistant_sandbox_hook.h" // nogncheck
60 #endif // BUILDFLAG(ENABLE_CROS_LIBASSISTANT)
61 #endif // BUILDFLAG(IS_CHROMEOS_ASH)
63 #if BUILDFLAG(ENABLE_SCREEN_AI_SERVICE)
64 #include "components/services/screen_ai/sandbox/screen_ai_sandbox_hook_linux.h" // nogncheck
68 #include "base/message_loop/message_pump_mac.h"
72 #include "base/rand_util.h"
73 #include "base/win/win_util.h"
74 #include "base/win/windows_version.h"
75 #include "sandbox/win/src/sandbox.h"
77 sandbox::TargetServices* g_utility_target_services = nullptr;
82 // Mainline routine for running as the utility process.
83 int UtilityMain(MainFunctionParams parameters) {
84 base::MessagePumpType message_pump_type =
85 parameters.command_line->HasSwitch(switches::kMessageLoopTypeUi)
86 ? base::MessagePumpType::UI
88 : base::MessagePumpType::ECORE;
90 : base::MessagePumpType::DEFAULT;
95 sandbox::policy::SandboxTypeFromCommandLine(*parameters.command_line);
96 if (sandbox_type != sandbox::mojom::Sandbox::kNoSandbox) {
97 // On Mac, the TYPE_UI pump for the main thread is an NSApplication loop.
98 // In a sandboxed utility process, NSApp attempts to acquire more Mach
99 // resources than a restrictive sandbox policy should allow. Services that
100 // require a TYPE_UI pump generally just need a NS/CFRunLoop to pump system
101 // work sources, so choose that pump type instead. A NSRunLoop MessagePump
102 // is used for TYPE_UI MessageLoops on non-main threads.
103 base::MessagePump::OverrideMessagePumpForUIFactory(
104 []() -> std::unique_ptr<base::MessagePump> {
105 return std::make_unique<base::MessagePumpNSRunLoop>();
110 #if BUILDFLAG(IS_FUCHSIA)
111 // On Fuchsia always use IO threads to allow FIDL calls.
112 if (message_pump_type == base::MessagePumpType::DEFAULT)
113 message_pump_type = base::MessagePumpType::IO;
114 #endif // BUILDFLAG(IS_FUCHSIA)
116 if (parameters.command_line->HasSwitch(switches::kTimeZoneForTesting)) {
117 std::string time_zone = parameters.command_line->GetSwitchValueASCII(
118 switches::kTimeZoneForTesting);
119 icu::TimeZone::adoptDefault(
120 icu::TimeZone::createTimeZone(icu::UnicodeString(time_zone.c_str())));
123 // The main task executor of the utility process.
124 base::SingleThreadTaskExecutor main_thread_task_executor(message_pump_type);
125 base::PlatformThread::SetName("CrUtilityMain");
127 if (parameters.command_line->HasSwitch(switches::kUtilityStartupDialog)) {
128 const std::string utility_sub_type =
129 parameters.command_line->GetSwitchValueASCII(switches::kUtilitySubType);
130 auto dialog_match = parameters.command_line->GetSwitchValueASCII(
131 switches::kUtilityStartupDialog);
132 if (dialog_match.empty() || dialog_match == utility_sub_type) {
133 WaitForDebugger(utility_sub_type.empty() ? "Utility" : utility_sub_type);
137 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
138 // Initializes the sandbox before any threads are created.
139 // TODO(jorgelo): move this after GTK initialization when we enable a strict
140 // Seccomp-BPF policy.
142 sandbox::policy::SandboxTypeFromCommandLine(*parameters.command_line);
143 sandbox::policy::SandboxLinux::PreSandboxHook pre_sandbox_hook;
144 switch (sandbox_type) {
145 case sandbox::mojom::Sandbox::kNetwork:
146 pre_sandbox_hook = base::BindOnce(&network::NetworkPreSandboxHook);
148 #if BUILDFLAG(ENABLE_OOP_PRINTING)
149 case sandbox::mojom::Sandbox::kPrintBackend:
150 pre_sandbox_hook = base::BindOnce(&printing::PrintBackendPreSandboxHook);
152 #endif // BUILDFLAG(ENABLE_OOP_PRINTING)
153 case sandbox::mojom::Sandbox::kAudio:
154 pre_sandbox_hook = base::BindOnce(&audio::AudioPreSandboxHook);
156 case sandbox::mojom::Sandbox::kSpeechRecognition:
158 base::BindOnce(&speech::SpeechRecognitionPreSandboxHook);
160 #if BUILDFLAG(ENABLE_SCREEN_AI_SERVICE)
161 case sandbox::mojom::Sandbox::kScreenAI:
162 pre_sandbox_hook = base::BindOnce(&screen_ai::ScreenAIPreSandboxHook);
165 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_ASH)
166 case sandbox::mojom::Sandbox::kHardwareVideoDecoding:
168 base::BindOnce(&media::HardwareVideoDecodingPreSandboxHook);
170 #endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_ASH)
171 #if BUILDFLAG(IS_CHROMEOS_ASH)
172 case sandbox::mojom::Sandbox::kIme:
173 pre_sandbox_hook = base::BindOnce(&ash::ime::ImePreSandboxHook);
175 case sandbox::mojom::Sandbox::kTts:
176 pre_sandbox_hook = base::BindOnce(&chromeos::tts::TtsPreSandboxHook);
178 #if BUILDFLAG(ENABLE_CROS_LIBASSISTANT)
179 case sandbox::mojom::Sandbox::kLibassistant:
181 base::BindOnce(&ash::libassistant::LibassistantPreSandboxHook);
183 #endif // BUILDFLAG(ENABLE_CROS_LIBASSISTANT)
184 #endif // BUILDFLAG(IS_CHROMEOS_ASH)
188 if (!sandbox::policy::IsUnsandboxedSandboxType(sandbox_type) &&
189 (parameters.zygote_child || !pre_sandbox_hook.is_null())) {
190 sandbox::policy::SandboxLinux::Options sandbox_options;
191 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_ASH)
192 if (sandbox_type == sandbox::mojom::Sandbox::kHardwareVideoDecoding) {
193 // The kHardwareVideoDecoding sandbox needs to know the GPU type in order
194 // to select the right policy.
195 gpu::GPUInfo gpu_info{};
196 gpu::CollectBasicGraphicsInfo(&gpu_info);
197 sandbox_options.use_amd_specific_policies =
198 angle::IsAMD(gpu_info.active_gpu().vendor_id);
200 #endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_ASH)
201 sandbox::policy::Sandbox::Initialize(
202 sandbox_type, std::move(pre_sandbox_hook), sandbox_options);
204 #elif BUILDFLAG(IS_WIN)
205 g_utility_target_services = parameters.sandbox_info->target_services;
208 ChildProcess utility_process(base::ThreadType::kDefault);
209 GetContentClient()->utility()->PostIOThreadCreated(
210 utility_process.io_task_runner());
211 base::RunLoop run_loop;
212 utility_process.set_main_thread(
213 new UtilityThreadImpl(run_loop.QuitClosure()));
215 #if BUILDFLAG(IS_POSIX) && !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_MAC)
216 // Startup tracing is usually enabled earlier, but if we forked from a zygote,
217 // we can only enable it after mojo IPC support is brought up initialized by
218 // UtilityThreadImpl, because the mojo broker has to create the tracing SMB on
219 // our behalf due to the zygote sandbox.
220 if (parameters.zygote_child)
221 tracing::EnableStartupTracingIfNeeded();
222 #endif // BUILDFLAG(IS_POSIX) && !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_MAC)
224 // Both utility process and service utility process would come
225 // here, but the later is launched without connection to service manager, so
226 // there has no base::PowerMonitor be created(See ChildThreadImpl::Init()).
227 // As base::PowerMonitor is necessary to base::HighResolutionTimerManager, for
228 // such case we just disable base::HighResolutionTimerManager for now.
229 // Note that disabling base::HighResolutionTimerManager means high resolution
230 // timer is always disabled no matter on battery or not, but it should have
231 // no any bad influence because currently service utility process is not using
232 // any high resolution timer.
233 // TODO(leonhsl): Once http://crbug.com/646833 got resolved, re-enable
234 // base::HighResolutionTimerManager here for future possible usage of high
235 // resolution timer in service utility process.
236 absl::optional<base::HighResolutionTimerManager> hi_res_timer_manager;
237 if (base::PowerMonitor::IsInitialized()) {
238 hi_res_timer_manager.emplace();
241 #if BUILDFLAG(IS_WIN)
243 sandbox::policy::SandboxTypeFromCommandLine(*parameters.command_line);
244 DVLOG(1) << "Sandbox type: " << static_cast<int>(sandbox_type);
246 // https://crbug.com/1076771 https://crbug.com/1075487 Premature unload of
247 // shell32 caused process to crash during process shutdown. See also a
248 // separate fix for https://crbug.com/1139752. Fixed in Windows 11.
249 if (base::win::GetVersion() < base::win::Version::WIN11) {
250 HMODULE shell32_pin = ::LoadLibrary(L"shell32.dll");
251 UNREFERENCED_PARAMETER(shell32_pin);
254 // Not all utility processes require DPI awareness as this context only
255 // pertains to certain workloads & impacted system API calls (e.g. UX
256 // scaling or per-monitor windowing). We do not blanket apply DPI awareness
257 // as utility processes running within a kService sandbox with the Win32K
258 // Lockdown policy applied may crash when calling EnableHighDPISupport. See
260 if (sandbox_type == sandbox::mojom::Sandbox::kMediaFoundationCdm) {
261 // The Media Foundation Utility Process needs to be marked as DPI aware so
262 // the Media Engine & CDM can correctly identify the target monitor for
263 // video output. This is required to ensure that the proper monitor is
264 // queried for hardware capabilities & any settings are applied to the
266 base::win::EnableHighDPISupport();
269 if (!sandbox::policy::IsUnsandboxedSandboxType(sandbox_type) &&
270 sandbox_type != sandbox::mojom::Sandbox::kCdm &&
271 sandbox_type != sandbox::mojom::Sandbox::kMediaFoundationCdm &&
272 sandbox_type != sandbox::mojom::Sandbox::kWindowsSystemProxyResolver) {
273 if (!g_utility_target_services)
276 // Ensure RtlGenRandom is warm before the token is lowered; otherwise,
277 // base::RandBytes() will CHECK fail when v8 is initialized.
278 base::RandBytes(&buffer, sizeof(buffer));
280 g_utility_target_services->LowerToken();
284 internal::PartitionAllocSupport::Get()->ReconfigureAfterTaskRunnerInit(
285 switches::kUtilityProcess);
289 #if defined(LEAK_SANITIZER)
290 // Invoke LeakSanitizer before shutting down the utility thread, to avoid
291 // reporting shutdown-only leaks.
292 __lsan_do_leak_check();
298 } // namespace content