#include <optional>
#include "base/allocator/partition_alloc_support.h"
#include "base/command_line.h"
#include "base/debug/alias.h"
#include "base/debug/leak_annotations.h"
#include "base/functional/bind.h"
#include "base/immediate_crash.h"
#include "base/message_loop/message_pump_type.h"
#include "base/metrics/histogram_functions.h"
#include "base/power_monitor/power_monitor.h"
#include "base/run_loop.h"
#include "base/task/single_thread_task_executor.h"
#include "base/threading/hang_watcher.h"
#include "base/threading/platform_thread.h"
#include "base/time/time.h"
#include "base/timer/hi_res_timer_manager.h"
#include "build/build_config.h"
#include "components/services/on_device_translation/buildflags/buildflags.h"
#include "content/child/child_process.h"
#include "content/common/content_switches_internal.h"
#include "content/common/features.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/utility/content_utility_client.h"
#include "content/utility/on_device_model/on_device_model_sandbox_init.h"
#include "content/utility/utility_thread_impl.h"
#include "printing/buildflags/buildflags.h"
#include "sandbox/policy/mojom/sandbox.mojom.h"
#include "sandbox/policy/sandbox.h"
#include "sandbox/policy/sandbox_type.h"
#include "services/on_device_model/public/mojom/on_device_model_service.mojom.h"
#include "services/tracing/public/cpp/trace_startup.h"
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || USE_VAAPI
#include "base/file_descriptor_store.h"
#include "base/files/file_util.h"
#include "base/pickle.h"
#include "content/child/sandboxed_process_thread_type_handler.h"
#include "content/common/gpu_pre_sandbox_hook_linux.h"
#include "content/public/common/content_descriptor_keys.h"
#include "content/utility/speech/speech_recognition_sandbox_hook_linux.h"
#include "media/gpu/buildflags.h"
#include "media/media_buildflags.h"
#include "sandbox/policy/linux/sandbox_linux.h"
#include "services/audio/audio_sandbox_hook_linux.h"
#include "services/network/network_sandbox_hook_linux.h"
#include "services/screen_ai/buildflags/buildflags.h"
#include "services/shape_detection/shape_detection_sandbox_hook.h"
#if BUILDFLAG(USE_LINUX_VIDEO_ACCELERATION)
#include "gpu/config/gpu_info_collector.h"
#include "media/gpu/sandbox/hardware_video_encoding_sandbox_hook_linux.h"
#include "third_party/angle/src/gpu_info_util/SystemInfo.h"
#if BUILDFLAG(USE_VAAPI)
#include "media/gpu/vaapi/vaapi_wrapper.h"
#include "media/mojo/mojom/video_decoder_factory_process.mojom.h"
#endif
#endif
#if BUILDFLAG(ALLOW_OOP_VIDEO_DECODER)
#include "media/gpu/sandbox/hardware_video_decoding_sandbox_hook_linux.h"
#endif
#if BUILDFLAG(ENABLE_PRINTING)
#include "printing/sandbox/print_backend_sandbox_hook_linux.h"
#endif
#if (BUILDFLAG(ENABLE_SCREEN_AI_SERVICE) && !defined(COMPONENT_BUILD) && \
(BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_OHOS)))
#include "services/screen_ai/public/cpp/utilities.h"
#include "services/screen_ai/sandbox/screen_ai_sandbox_hook_linux.h"
#endif
#endif
#if BUILDFLAG(IS_CHROMEOS)
#include "chromeos/ash/services/ime/ime_sandbox_hook.h"
#include "chromeos/services/tts/tts_sandbox_hook.h"
#endif
#if BUILDFLAG(IS_MAC)
#include "base/message_loop/message_pump_apple.h"
#endif
#if BUILDFLAG(IS_WIN)
#include "base/debug/crash_logging.h"
#include "base/native_library.h"
#include "base/rand_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/synchronization/waitable_event.h"
#include "base/win/scoped_com_initializer.h"
#include "base/win/win_util.h"
#include "base/win/windows_handle_util.h"
#include "base/win/windows_version.h"
#include "content/utility/sandbox_delegate_data.mojom.h"
#include "sandbox/policy/win/sandbox_warmup.h"
#include "sandbox/win/src/sandbox.h"
#endif
#if BUILDFLAG(IS_OHOS)
#include "base/file_descriptor_store.h"
#include "base/files/file_util.h"
#include "base/pickle.h"
#include "content/common/gpu_pre_sandbox_hook_linux.h"
#include "content/public/common/content_descriptor_keys.h"
#include "content/utility/speech/speech_recognition_sandbox_hook_linux.h"
#include "sandbox/policy/linux/sandbox_linux.h"
#include "services/audio/audio_sandbox_hook_linux.h"
#include "services/network/network_sandbox_hook_linux.h"
#endif
#if BUILDFLAG(IS_WIN)
sandbox::TargetServices* g_utility_target_services = nullptr;
#endif
#if BUILDFLAG(ENABLE_ON_DEVICE_TRANSLATION) && \
(BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS))
#include "components/services/on_device_translation/sandbox_hook.h"
#endif
namespace content {
namespace {
#if !defined(COMPONENT_BUILD) && \
(BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_OHOS))
std::vector<std::string> GetNetworkContextsParentDirectories() {
base::MemoryMappedFile::Region region;
base::ScopedFD read_pipe_fd = base::FileDescriptorStore::GetInstance().TakeFD(
kNetworkContextParentDirsDescriptor, ®ion);
DCHECK(region == base::MemoryMappedFile::Region::kWholeFile);
std::string dirs_str;
if (!base::ReadStreamToString(fdopen(read_pipe_fd.get(), "r"), &dirs_str)) {
LOG(FATAL) << "Failed to read network context parents dirs from pipe.";
}
base::Pickle dirs_pickle =
base::Pickle::WithUnownedBuffer(base::as_byte_span(dirs_str));
base::PickleIterator dirs_pickle_iter(dirs_pickle);
std::vector<std::string> dirs;
std::string dir;
while (dirs_pickle_iter.ReadString(&dir)) {
dirs.push_back(dir);
}
CHECK(dirs_pickle_iter.ReachedEnd());
return dirs;
}
bool ShouldUseAmdGpuPolicy(sandbox::mojom::Sandbox sandbox_type) {
#if !BUILDFLAG(IS_OHOS)
#if BUILDFLAG(USE_LINUX_VIDEO_ACCELERATION) || \
BUILDFLAG(ALLOW_OOP_VIDEO_DECODER)
const bool obtain_gpu_info =
sandbox_type == sandbox::mojom::Sandbox::kHardwareVideoDecoding ||
sandbox_type == sandbox::mojom::Sandbox::kHardwareVideoEncoding;
if (obtain_gpu_info) {
gpu::GPUInfo gpu_info{};
gpu::CollectBasicGraphicsInfo(&gpu_info);
return angle::IsAMD(gpu_info.active_gpu().vendor_id);
}
#endif
#endif
return false;
}
#endif
#if BUILDFLAG(IS_WIN)
bool PreLockdownSandboxHook(base::span<const uint8_t> delegate_blob) {
CHECK(!delegate_blob.empty());
content::mojom::sandbox::UtilityConfigPtr sandbox_config;
if (!content::mojom::sandbox::UtilityConfig::Deserialize(
delegate_blob.data(), delegate_blob.size(), &sandbox_config)) {
NOTREACHED();
}
if (!sandbox_config->preload_libraries.empty()) {
for (const auto& library_path : sandbox_config->preload_libraries) {
CHECK(library_path.IsAbsolute());
base::NativeLibraryLoadError lib_error;
HMODULE h_mod = base::LoadNativeLibrary(library_path, &lib_error);
if (!h_mod) {
base::debug::Alias(&lib_error);
std::string dll_name_str = base::WideToUTF8(library_path.value());
DEBUG_ALIAS_FOR_CSTR(dll_name, dll_name_str.c_str(), 256);
SCOPED_CRASH_KEY_STRING256("PreSandboxHook", "ModuleName", dll_name);
NOTREACHED();
}
}
}
HANDLE event =
base::win::Uint32ToHandle(sandbox_config->bootstrap_event_handle);
CHECK(event && event != INVALID_HANDLE_VALUE);
CHECK(::SetEvent(event));
CHECK(::CloseHandle(event));
return true;
}
#endif
void SetUtilityThreadName(const std::string& utility_sub_type) {
auto first_period = utility_sub_type.find('.');
base::PlatformThread::SetName(utility_sub_type.substr(0, first_period) +
".CrUtilityMain");
}
}
int UtilityMain(MainFunctionParams parameters) {
if (parameters.command_line->HasSwitch(
switches::kUtilityImmediateCrashForTesting)) {
base::ImmediateCrash();
}
base::MessagePumpType message_pump_type =
parameters.command_line->HasSwitch(switches::kMessageLoopTypeUi)
? base::MessagePumpType::UI
: base::MessagePumpType::DEFAULT;
#if BUILDFLAG(IS_MAC)
auto sandbox_type =
sandbox::policy::SandboxTypeFromCommandLine(*parameters.command_line);
if (sandbox_type != sandbox::mojom::Sandbox::kNoSandbox) {
base::MessagePump::OverrideMessagePumpForUIFactory(
[]() -> std::unique_ptr<base::MessagePump> {
return std::make_unique<base::MessagePumpNSRunLoop>();
});
}
#endif
#if BUILDFLAG(IS_FUCHSIA)
if (message_pump_type == base::MessagePumpType::DEFAULT)
message_pump_type = base::MessagePumpType::IO;
#endif
base::SingleThreadTaskExecutor main_thread_task_executor(
message_pump_type, true);
const std::string utility_sub_type =
parameters.command_line->GetSwitchValueASCII(switches::kUtilitySubType);
SetUtilityThreadName(utility_sub_type);
if (parameters.command_line->HasSwitch(switches::kUtilityStartupDialog)) {
auto dialog_match = parameters.command_line->GetSwitchValueASCII(
switches::kUtilityStartupDialog);
if (dialog_match.empty() || dialog_match == utility_sub_type) {
WaitForDebugger(utility_sub_type.empty() ? "Utility" : utility_sub_type);
}
}
if (utility_sub_type == on_device_model::mojom::OnDeviceModelService::Name_) {
CHECK(on_device_model::PreSandboxInit());
}
#if !defined(COMPONENT_BUILD) && \
(BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || defined(IS_OHOS) && USE_VAAPI)
#if BUILDFLAG(USE_LINUX_VIDEO_ACCELERATION) && BUILDFLAG(USE_VAAPI)
if (utility_sub_type == media::mojom::VideoDecoderFactoryProcess::Name_) {
media::VaapiWrapper::PreSandboxInitialization(
true);
}
#endif
SandboxedProcessThreadTypeHandler::Create();
auto sandbox_type =
sandbox::policy::SandboxTypeFromCommandLine(*parameters.command_line);
sandbox::policy::SandboxLinux::Options sandbox_options;
sandbox::policy::SandboxLinux::PreSandboxHook pre_sandbox_hook;
switch (sandbox_type) {
case sandbox::mojom::Sandbox::kNetwork:
pre_sandbox_hook = base::BindOnce(&network::NetworkPreSandboxHook,
GetNetworkContextsParentDirectories());
break;
case sandbox::mojom::Sandbox::kPrintBackend:
#if BUILDFLAG(ENABLE_OOP_PRINTING)
pre_sandbox_hook = base::BindOnce(&printing::PrintBackendPreSandboxHook);
break;
#else
NOTREACHED();
#endif
case sandbox::mojom::Sandbox::kAudio:
pre_sandbox_hook = base::BindOnce(&audio::AudioPreSandboxHook);
break;
#if !BUILDFLAG(IS_OHOS)
case sandbox::mojom::Sandbox::kOnDeviceModelExecution:
on_device_model::AddSandboxLinuxOptions(sandbox_options);
pre_sandbox_hook = base::BindOnce(&on_device_model::PreSandboxHook);
break;
#endif
case sandbox::mojom::Sandbox::kSpeechRecognition:
pre_sandbox_hook =
base::BindOnce(&speech::SpeechRecognitionPreSandboxHook);
break;
#if BUILDFLAG(ENABLE_ON_DEVICE_TRANSLATION) && \
(BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS))
case sandbox::mojom::Sandbox::kOnDeviceTranslation:
pre_sandbox_hook = base::BindOnce(
&on_device_translation::OnDeviceTranslationSandboxHook);
break;
#endif
case sandbox::mojom::Sandbox::kScreenAI:
#if defined(ENABLE_SCREEN_AI_SERVICE) && ENABLE_SCREEN_AI_SERVICE && \
!defined(COMPONENT_BUILD)
pre_sandbox_hook =
base::BindOnce(&screen_ai::ScreenAIPreSandboxHook,
parameters.command_line->GetSwitchValuePath(
screen_ai::GetBinaryPathSwitch()));
break;
#else
NOTREACHED();
#endif
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
case sandbox::mojom::Sandbox::kShapeDetection:
pre_sandbox_hook =
base::BindOnce(&shape_detection::ShapeDetectionPreSandboxHook);
break;
#if BUILDFLAG(ALLOW_OOP_VIDEO_DECODER)
case sandbox::mojom::Sandbox::kHardwareVideoDecoding:
pre_sandbox_hook =
base::BindOnce(&media::HardwareVideoDecodingPreSandboxHook);
break;
#endif
#if !BUILDFLAG(IS_OHOS)
#if BUILDFLAG(USE_LINUX_VIDEO_ACCELERATION)
case sandbox::mojom::Sandbox::kHardwareVideoEncoding:
pre_sandbox_hook =
base::BindOnce(&media::HardwareVideoEncodingPreSandboxHook);
break;
#endif
#endif
#endif
#if BUILDFLAG(IS_CHROMEOS)
case sandbox::mojom::Sandbox::kIme:
pre_sandbox_hook = base::BindOnce(&ash::ime::ImePreSandboxHook);
break;
case sandbox::mojom::Sandbox::kTts:
pre_sandbox_hook = base::BindOnce(&chromeos::tts::TtsPreSandboxHook);
break;
#endif
default:
break;
}
if (!sandbox::policy::IsUnsandboxedSandboxType(sandbox_type) &&
(parameters.zygote_child || !pre_sandbox_hook.is_null())) {
sandbox_options.use_amd_specific_policies =
ShouldUseAmdGpuPolicy(sandbox_type);
sandbox::policy::Sandbox::Initialize(
sandbox_type, std::move(pre_sandbox_hook), sandbox_options);
}
if (parameters.needs_startup_tracing_after_sandbox_init) {
tracing::InitTracingPostFeatureList(false,
false);
}
if (base::HangWatcher::IsEnabled() &&
!base::HangWatcher::GetInstance()->IsStarted()) {
DCHECK(parameters.hang_watcher_not_started_time.has_value());
base::TimeDelta uncovered_hang_watcher_time =
base::TimeTicks::Now() -
parameters.hang_watcher_not_started_time.value();
base::UmaHistogramTimes("HangWatcher.UtilityProcess.UncoveredStartupTime",
uncovered_hang_watcher_time);
base::HangWatcher::GetInstance()->Start();
}
#elif BUILDFLAG(IS_WIN)
std::optional<base::win::ScopedCOMInitializer> scoped_com_initializer;
if (message_pump_type == base::MessagePumpType::UI) {
scoped_com_initializer.emplace();
CHECK(scoped_com_initializer->Succeeded());
}
g_utility_target_services = parameters.sandbox_info->target_services;
if (g_utility_target_services) {
auto delegate_data = g_utility_target_services->GetDelegateData();
if (delegate_data.has_value() && !delegate_data->empty()) {
PreLockdownSandboxHook(delegate_data.value());
}
}
auto sandbox_type =
sandbox::policy::SandboxTypeFromCommandLine(*parameters.command_line);
DVLOG(1) << "Sandbox type: " << static_cast<int>(sandbox_type);
if (base::win::GetVersion() < base::win::Version::WIN11) {
HMODULE shell32_pin = ::LoadLibrary(L"shell32.dll");
UNREFERENCED_PARAMETER(shell32_pin);
}
if (sandbox_type == sandbox::mojom::Sandbox::kMediaFoundationCdm) {
base::win::EnableHighDPISupport();
}
if (!sandbox::policy::IsUnsandboxedSandboxType(sandbox_type) &&
sandbox_type != sandbox::mojom::Sandbox::kCdm &&
sandbox_type != sandbox::mojom::Sandbox::kMediaFoundationCdm) {
if (!g_utility_target_services)
return false;
sandbox::policy::WarmupRandomnessInfrastructure();
sandbox::policy::MaybeDelayloadDbghelp();
g_utility_target_services->LowerToken();
}
#endif
ChildProcess utility_process(base::ThreadType::kDefault);
GetContentClient()->utility()->PostIOThreadCreated(
utility_process.io_task_runner());
base::RunLoop run_loop;
utility_process.set_main_thread(
new UtilityThreadImpl(run_loop.QuitClosure()));
std::optional<base::HighResolutionTimerManager> hi_res_timer_manager;
if (base::PowerMonitor::GetInstance()->IsInitialized()) {
hi_res_timer_manager.emplace();
}
base::allocator::PartitionAllocSupport::Get()->ReconfigureAfterTaskRunnerInit(
switches::kUtilityProcess);
run_loop.Run();
if (utility_sub_type == on_device_model::mojom::OnDeviceModelService::Name_) {
CHECK(on_device_model::Shutdown());
}
#if defined(LEAK_SANITIZER)
__lsan_do_leak_check();
#endif
return 0;
}
}