1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
12 #include "base/lazy_instance.h"
13 #include "base/message_loop/message_loop.h"
14 #include "base/metrics/histogram.h"
15 #include "base/rand_util.h"
16 #include "base/strings/string_number_conversions.h"
17 #include "base/strings/stringprintf.h"
18 #include "base/third_party/dynamic_annotations/dynamic_annotations.h"
19 #include "base/threading/platform_thread.h"
20 #include "base/trace_event/trace_event.h"
21 #include "build/build_config.h"
22 #include "content/child/child_process.h"
23 #include "content/common/content_constants_internal.h"
24 #include "content/common/gpu/gpu_config.h"
25 #include "content/common/gpu/gpu_messages.h"
26 #include "content/common/gpu/media/gpu_video_encode_accelerator.h"
27 #include "content/common/sandbox_linux/sandbox_linux.h"
28 #include "content/gpu/gpu_child_thread.h"
29 #include "content/gpu/gpu_process.h"
30 #include "content/gpu/gpu_watchdog_thread.h"
31 #include "content/public/common/content_client.h"
32 #include "content/public/common/content_switches.h"
33 #include "content/public/common/main_function_params.h"
34 #include "gpu/command_buffer/service/gpu_switches.h"
35 #include "gpu/config/gpu_info_collector.h"
36 #include "gpu/config/gpu_util.h"
37 #include "ui/events/platform/platform_event_source.h"
38 #include "ui/gl/gl_implementation.h"
39 #include "ui/gl/gl_surface.h"
40 #include "ui/gl/gl_switches.h"
41 #include "ui/gl/gpu_switching_manager.h"
44 #include "base/win/windows_version.h"
45 #include "base/win/scoped_com_initializer.h"
46 #include "sandbox/win/src/sandbox.h"
50 #include "ui/base/x/x11_util.h"
54 #include "content/public/common/sandbox_init.h"
57 #if defined(OS_MACOSX)
58 #include "base/message_loop/message_pump_mac.h"
59 #include "content/common/sandbox_mac.h"
62 #if defined(SANITIZER_COVERAGE)
63 #include <sanitizer/common_interface_defs.h>
66 const int kGpuTimeout
= 10000;
72 void GetGpuInfoFromCommandLine(gpu::GPUInfo
& gpu_info
,
73 const base::CommandLine
& command_line
);
74 bool WarmUpSandbox(const base::CommandLine
& command_line
);
76 #if !defined(OS_MACOSX)
77 bool CollectGraphicsInfo(gpu::GPUInfo
& gpu_info
);
81 #if !defined(OS_CHROMEOS)
82 bool CanAccessNvidiaDeviceFile();
84 bool StartSandboxLinux(const gpu::GPUInfo
&, GpuWatchdogThread
*, bool);
86 bool StartSandboxWindows(const sandbox::SandboxInterfaceInfo
*);
89 base::LazyInstance
<GpuChildThread::DeferredMessages
> deferred_messages
=
90 LAZY_INSTANCE_INITIALIZER
;
92 bool GpuProcessLogMessageHandler(int severity
,
93 const char* file
, int line
,
95 const std::string
& str
) {
96 std::string header
= str
.substr(0, message_start
);
97 std::string message
= str
.substr(message_start
);
98 deferred_messages
.Get().push(new GpuHostMsg_OnLogMessage(
99 severity
, header
, message
));
103 } // namespace anonymous
105 // Main function for starting the Gpu process.
106 int GpuMain(const MainFunctionParams
& parameters
) {
107 TRACE_EVENT0("gpu", "GpuMain");
108 base::trace_event::TraceLog::GetInstance()->SetProcessName("GPU Process");
109 base::trace_event::TraceLog::GetInstance()->SetProcessSortIndex(
110 kTraceEventGpuProcessSortIndex
);
112 const base::CommandLine
& command_line
= parameters
.command_line
;
113 if (command_line
.HasSwitch(switches::kGpuStartupDialog
)) {
114 ChildProcess::WaitForDebugger("Gpu");
117 base::Time start_time
= base::Time::Now();
120 // Prevent Windows from displaying a modal dialog on failures like not being
121 // able to load a DLL.
123 SEM_FAILCRITICALERRORS
|
124 SEM_NOGPFAULTERRORBOX
|
125 SEM_NOOPENFILEERRORBOX
);
126 #elif defined(USE_X11)
127 ui::SetDefaultX11ErrorHandlers();
130 logging::SetLogMessageHandler(GpuProcessLogMessageHandler
);
132 if (command_line
.HasSwitch(switches::kSupportsDualGpus
)) {
133 std::string types
= command_line
.GetSwitchValueASCII(
134 switches::kGpuDriverBugWorkarounds
);
135 std::set
<int> workarounds
;
136 gpu::StringToFeatureSet(types
, &workarounds
);
137 if (workarounds
.count(gpu::FORCE_DISCRETE_GPU
) == 1)
138 ui::GpuSwitchingManager::GetInstance()->ForceUseOfDiscreteGpu();
139 else if (workarounds
.count(gpu::FORCE_INTEGRATED_GPU
) == 1)
140 ui::GpuSwitchingManager::GetInstance()->ForceUseOfIntegratedGpu();
143 // Initialization of the OpenGL bindings may fail, in which case we
144 // will need to tear down this process. However, we can not do so
145 // safely until the IPC channel is set up, because the detection of
146 // early return of a child process is implemented using an IPC
147 // channel error. If the IPC channel is not fully set up between the
148 // browser and GPU process, and the GPU process crashes or exits
149 // early, the browser process will never detect it. For this reason
150 // we defer tearing down the GPU process until receiving the
151 // GpuMsg_Initialize message from the browser.
152 bool dead_on_arrival
= false;
155 base::MessageLoop::Type message_loop_type
= base::MessageLoop::TYPE_IO
;
156 // Unless we're running on desktop GL, we don't need a UI message
157 // loop, so avoid its use to work around apparent problems with some
158 // third-party software.
159 if (command_line
.HasSwitch(switches::kUseGL
) &&
160 command_line
.GetSwitchValueASCII(switches::kUseGL
) ==
161 gfx::kGLImplementationDesktopName
) {
162 message_loop_type
= base::MessageLoop::TYPE_UI
;
164 base::MessageLoop
main_message_loop(message_loop_type
);
165 #elif defined(OS_LINUX) && defined(USE_X11)
166 // We need a UI loop so that we can grab the Expose events. See GLSurfaceGLX
167 // and https://crbug.com/326995.
168 base::MessageLoop
main_message_loop(base::MessageLoop::TYPE_UI
);
169 scoped_ptr
<ui::PlatformEventSource
> event_source
=
170 ui::PlatformEventSource::CreateDefault();
171 #elif defined(OS_LINUX)
172 base::MessageLoop
main_message_loop(base::MessageLoop::TYPE_DEFAULT
);
173 #elif defined(OS_MACOSX)
174 // This is necessary for CoreAnimation layers hosted in the GPU process to be
175 // drawn. See http://crbug.com/312462.
176 scoped_ptr
<base::MessagePump
> pump(new base::MessagePumpCFRunLoop());
177 base::MessageLoop
main_message_loop(pump
.Pass());
179 base::MessageLoop
main_message_loop(base::MessageLoop::TYPE_IO
);
182 base::PlatformThread::SetName("CrGpuMain");
184 // In addition to disabling the watchdog if the command line switch is
185 // present, disable the watchdog on valgrind because the code is expected
186 // to run slowly in that case.
187 bool enable_watchdog
=
188 !command_line
.HasSwitch(switches::kDisableGpuWatchdog
) &&
189 !RunningOnValgrind();
191 // Disable the watchdog in debug builds because they tend to only be run by
192 // developers who will not appreciate the watchdog killing the GPU process.
194 enable_watchdog
= false;
197 bool delayed_watchdog_enable
= false;
199 #if defined(OS_CHROMEOS)
200 // Don't start watchdog immediately, to allow developers to switch to VT2 on
202 delayed_watchdog_enable
= true;
205 scoped_refptr
<GpuWatchdogThread
> watchdog_thread
;
207 // Start the GPU watchdog only after anything that is expected to be time
208 // consuming has completed, otherwise the process is liable to be aborted.
209 if (enable_watchdog
&& !delayed_watchdog_enable
) {
210 watchdog_thread
= new GpuWatchdogThread(kGpuTimeout
);
211 base::Thread::Options options
;
212 options
.timer_slack
= base::TIMER_SLACK_MAXIMUM
;
213 watchdog_thread
->StartWithOptions(options
);
216 gpu::GPUInfo gpu_info
;
217 // Get vendor_id, device_id, driver_version from browser process through
218 // commandline switches.
219 GetGpuInfoFromCommandLine(gpu_info
, command_line
);
221 base::TimeDelta collect_context_time
;
222 base::TimeDelta initialize_one_off_time
;
224 // Warm up resources that don't need access to GPUInfo.
225 if (WarmUpSandbox(command_line
)) {
226 #if defined(OS_LINUX)
227 bool initialized_sandbox
= false;
228 bool initialized_gl_context
= false;
229 bool should_initialize_gl_context
= false;
230 // On Chrome OS ARM Mali, GPU driver userspace creates threads when
231 // initializing a GL context, so start the sandbox early.
232 if (command_line
.HasSwitch(switches::kGpuSandboxStartEarly
)) {
233 gpu_info
.sandboxed
= StartSandboxLinux(
234 gpu_info
, watchdog_thread
.get(), should_initialize_gl_context
);
235 initialized_sandbox
= true;
237 #endif // defined(OS_LINUX)
239 base::TimeTicks before_initialize_one_off
= base::TimeTicks::Now();
241 // Determine if we need to initialize GL here or it has already been done.
242 bool gl_already_initialized
= false;
243 #if defined(OS_MACOSX)
244 if (!command_line
.HasSwitch(switches::kNoSandbox
)) {
245 // On Mac, if the sandbox is enabled, then GLSurface::InitializeOneOff()
246 // is called from the sandbox warmup code before getting here.
247 gl_already_initialized
= true;
250 if (command_line
.HasSwitch(switches::kInProcessGPU
)) {
251 // With in-process GPU, GLSurface::InitializeOneOff() is called from
252 // GpuChildThread before getting here.
253 gl_already_initialized
= true;
256 // Load and initialize the GL implementation and locate the GL entry points.
257 bool gl_initialized
=
258 gl_already_initialized
259 ? gfx::GetGLImplementation() != gfx::kGLImplementationNone
260 : gfx::GLSurface::InitializeOneOff();
261 if (gl_initialized
) {
262 // We need to collect GL strings (VENDOR, RENDERER) for blacklisting
263 // purposes. However, on Mac we don't actually use them. As documented in
264 // crbug.com/222934, due to some driver issues, glGetString could take
265 // multiple seconds to finish, which in turn cause the GPU process to
267 // By skipping the following code on Mac, we don't really lose anything,
268 // because the basic GPU information is passed down from browser process
269 // and we already registered them through SetGpuInfo() above.
270 base::TimeTicks before_collect_context_graphics_info
=
271 base::TimeTicks::Now();
272 #if !defined(OS_MACOSX)
273 if (!CollectGraphicsInfo(gpu_info
))
274 dead_on_arrival
= true;
276 #if defined(OS_CHROMEOS) || defined(OS_ANDROID)
277 // Recompute gpu driver bug workarounds - this is specifically useful
278 // on systems where vendor_id/device_id aren't available.
279 if (!command_line
.HasSwitch(switches::kDisableGpuDriverBugWorkarounds
)) {
280 gpu::ApplyGpuDriverBugWorkarounds(
281 gpu_info
, const_cast<base::CommandLine
*>(&command_line
));
285 #if defined(OS_LINUX)
286 initialized_gl_context
= true;
287 #if !defined(OS_CHROMEOS)
288 if (gpu_info
.gpu
.vendor_id
== 0x10de && // NVIDIA
289 gpu_info
.driver_vendor
== "NVIDIA" &&
290 !CanAccessNvidiaDeviceFile())
291 dead_on_arrival
= true;
292 #endif // !defined(OS_CHROMEOS)
293 #endif // defined(OS_LINUX)
294 #endif // !defined(OS_MACOSX)
295 collect_context_time
=
296 base::TimeTicks::Now() - before_collect_context_graphics_info
;
297 } else { // gl_initialized
298 VLOG(1) << "gfx::GLSurface::InitializeOneOff failed";
299 dead_on_arrival
= true;
302 initialize_one_off_time
=
303 base::TimeTicks::Now() - before_initialize_one_off
;
305 if (enable_watchdog
&& delayed_watchdog_enable
) {
306 watchdog_thread
= new GpuWatchdogThread(kGpuTimeout
);
307 base::Thread::Options options
;
308 options
.timer_slack
= base::TIMER_SLACK_MAXIMUM
;
309 watchdog_thread
->StartWithOptions(options
);
312 // OSMesa is expected to run very slowly, so disable the watchdog in that
314 if (enable_watchdog
&&
315 gfx::GetGLImplementation() == gfx::kGLImplementationOSMesaGL
) {
316 watchdog_thread
->Stop();
317 watchdog_thread
= NULL
;
320 #if defined(OS_LINUX)
321 should_initialize_gl_context
= !initialized_gl_context
&&
324 if (!initialized_sandbox
) {
325 gpu_info
.sandboxed
= StartSandboxLinux(gpu_info
, watchdog_thread
.get(),
326 should_initialize_gl_context
);
328 #elif defined(OS_WIN)
329 gpu_info
.sandboxed
= StartSandboxWindows(parameters
.sandbox_info
);
330 #elif defined(OS_MACOSX)
331 gpu_info
.sandboxed
= Sandbox::SandboxIsCurrentlyActive();
334 gpu_info
.video_encode_accelerator_supported_profiles
=
335 content::GpuVideoEncodeAccelerator::GetSupportedProfiles();
337 dead_on_arrival
= true;
340 logging::SetLogMessageHandler(NULL
);
342 GpuProcess gpu_process
;
344 // These UMA must be stored after GpuProcess is constructed as it
345 // initializes StatisticsRecorder which tracks the histograms.
346 UMA_HISTOGRAM_TIMES("GPU.CollectContextGraphicsInfo", collect_context_time
);
347 UMA_HISTOGRAM_TIMES("GPU.InitializeOneOffTime", initialize_one_off_time
);
349 GpuChildThread
* child_thread
= new GpuChildThread(watchdog_thread
.get(),
352 deferred_messages
.Get());
353 while (!deferred_messages
.Get().empty())
354 deferred_messages
.Get().pop();
356 child_thread
->Init(start_time
);
358 gpu_process
.set_main_thread(child_thread
);
360 if (watchdog_thread
.get())
361 watchdog_thread
->AddPowerObserver();
364 TRACE_EVENT0("gpu", "Run Message Loop");
365 main_message_loop
.Run();
368 child_thread
->StopWatchdog();
375 void GetGpuInfoFromCommandLine(gpu::GPUInfo
& gpu_info
,
376 const base::CommandLine
& command_line
) {
377 DCHECK(command_line
.HasSwitch(switches::kGpuVendorID
) &&
378 command_line
.HasSwitch(switches::kGpuDeviceID
) &&
379 command_line
.HasSwitch(switches::kGpuDriverVersion
));
380 bool success
= base::HexStringToUInt(
381 command_line
.GetSwitchValueASCII(switches::kGpuVendorID
),
382 &gpu_info
.gpu
.vendor_id
);
384 success
= base::HexStringToUInt(
385 command_line
.GetSwitchValueASCII(switches::kGpuDeviceID
),
386 &gpu_info
.gpu
.device_id
);
388 gpu_info
.driver_vendor
=
389 command_line
.GetSwitchValueASCII(switches::kGpuDriverVendor
);
390 gpu_info
.driver_version
=
391 command_line
.GetSwitchValueASCII(switches::kGpuDriverVersion
);
392 GetContentClient()->SetGpuInfo(gpu_info
);
395 bool WarmUpSandbox(const base::CommandLine
& command_line
) {
397 TRACE_EVENT0("gpu", "Warm up rand");
398 // Warm up the random subsystem, which needs to be done pre-sandbox on all
400 (void) base::RandUint64();
405 #if !defined(OS_MACOSX)
406 bool CollectGraphicsInfo(gpu::GPUInfo
& gpu_info
) {
408 gpu::CollectInfoResult result
= gpu::CollectContextGraphicsInfo(&gpu_info
);
410 case gpu::kCollectInfoFatalFailure
:
411 LOG(ERROR
) << "gpu::CollectGraphicsInfo failed (fatal).";
414 case gpu::kCollectInfoNonFatalFailure
:
415 DVLOG(1) << "gpu::CollectGraphicsInfo failed (non-fatal).";
417 case gpu::kCollectInfoNone
:
420 case gpu::kCollectInfoSuccess
:
423 GetContentClient()->SetGpuInfo(gpu_info
);
428 #if defined(OS_LINUX)
429 #if !defined(OS_CHROMEOS)
430 bool CanAccessNvidiaDeviceFile() {
432 base::ThreadRestrictions::AssertIOAllowed();
433 if (access("/dev/nvidiactl", R_OK
) != 0) {
434 DVLOG(1) << "NVIDIA device file /dev/nvidiactl access denied";
441 void CreateDummyGlContext() {
442 scoped_refptr
<gfx::GLSurface
> surface(
443 gfx::GLSurface::CreateOffscreenGLSurface(gfx::Size()));
444 if (!surface
.get()) {
445 DVLOG(1) << "gfx::GLSurface::CreateOffscreenGLSurface failed";
449 // On Linux, this is needed to make sure /dev/nvidiactl has
450 // been opened and its descriptor cached.
451 scoped_refptr
<gfx::GLContext
> context(gfx::GLContext::CreateGLContext(
452 NULL
, surface
.get(), gfx::PreferDiscreteGpu
));
453 if (!context
.get()) {
454 DVLOG(1) << "gfx::GLContext::CreateGLContext failed";
458 // Similarly, this is needed for /dev/nvidia0.
459 if (context
->MakeCurrent(surface
.get())) {
460 context
->ReleaseCurrent(surface
.get());
462 DVLOG(1) << "gfx::GLContext::MakeCurrent failed";
466 void WarmUpSandboxNvidia(const gpu::GPUInfo
& gpu_info
,
467 bool should_initialize_gl_context
) {
468 // We special case Optimus since the vendor_id we see may not be Nvidia.
469 bool uses_nvidia_driver
= (gpu_info
.gpu
.vendor_id
== 0x10de && // NVIDIA.
470 gpu_info
.driver_vendor
== "NVIDIA") ||
472 if (uses_nvidia_driver
&& should_initialize_gl_context
) {
473 // We need this on Nvidia to pre-open /dev/nvidiactl and /dev/nvidia0.
474 CreateDummyGlContext();
478 bool StartSandboxLinux(const gpu::GPUInfo
& gpu_info
,
479 GpuWatchdogThread
* watchdog_thread
,
480 bool should_initialize_gl_context
) {
481 TRACE_EVENT0("gpu", "Initialize sandbox");
485 WarmUpSandboxNvidia(gpu_info
, should_initialize_gl_context
);
487 if (watchdog_thread
) {
488 // LinuxSandbox needs to be able to ensure that the thread
489 // has really been stopped.
490 LinuxSandbox::StopThread(watchdog_thread
);
493 #if defined(SANITIZER_COVERAGE)
494 const std::string sancov_file_name
=
495 "gpu." + base::Uint64ToString(base::RandUint64());
496 LinuxSandbox
* linux_sandbox
= LinuxSandbox::GetInstance();
497 linux_sandbox
->sanitizer_args()->coverage_sandboxed
= 1;
498 linux_sandbox
->sanitizer_args()->coverage_fd
=
499 __sanitizer_maybe_open_cov_file(sancov_file_name
.c_str());
500 linux_sandbox
->sanitizer_args()->coverage_max_block_size
= 0;
503 // LinuxSandbox::InitializeSandbox() must always be called
504 // with only one thread.
505 res
= LinuxSandbox::InitializeSandbox();
506 if (watchdog_thread
) {
507 base::Thread::Options options
;
508 options
.timer_slack
= base::TIMER_SLACK_MAXIMUM
;
509 watchdog_thread
->StartWithOptions(options
);
514 #endif // defined(OS_LINUX)
517 bool StartSandboxWindows(const sandbox::SandboxInterfaceInfo
* sandbox_info
) {
518 TRACE_EVENT0("gpu", "Lower token");
520 // For Windows, if the target_services interface is not zero, the process
521 // is sandboxed and we must call LowerToken() before rendering untrusted
523 sandbox::TargetServices
* target_services
= sandbox_info
->target_services
;
524 if (target_services
) {
525 #if defined(ADDRESS_SANITIZER)
526 // Bind and leak dbghelp.dll before the token is lowered, otherwise
527 // AddressSanitizer will crash when trying to symbolize a report.
528 if (!LoadLibraryA("dbghelp.dll"))
532 target_services
->LowerToken();
538 #endif // defined(OS_WIN)
542 } // namespace content