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>
64 #include <sanitizer/coverage_interface.h>
67 const int kGpuTimeout
= 10000;
73 void GetGpuInfoFromCommandLine(gpu::GPUInfo
& gpu_info
,
74 const base::CommandLine
& command_line
);
75 bool WarmUpSandbox(const base::CommandLine
& command_line
);
77 #if !defined(OS_MACOSX)
78 bool CollectGraphicsInfo(gpu::GPUInfo
& gpu_info
);
82 #if !defined(OS_CHROMEOS)
83 bool CanAccessNvidiaDeviceFile();
85 bool StartSandboxLinux(const gpu::GPUInfo
&, GpuWatchdogThread
*, bool);
87 bool StartSandboxWindows(const sandbox::SandboxInterfaceInfo
*);
90 base::LazyInstance
<GpuChildThread::DeferredMessages
> deferred_messages
=
91 LAZY_INSTANCE_INITIALIZER
;
93 bool GpuProcessLogMessageHandler(int severity
,
94 const char* file
, int line
,
96 const std::string
& str
) {
97 std::string header
= str
.substr(0, message_start
);
98 std::string message
= str
.substr(message_start
);
99 deferred_messages
.Get().push(new GpuHostMsg_OnLogMessage(
100 severity
, header
, message
));
104 } // namespace anonymous
106 // Main function for starting the Gpu process.
107 int GpuMain(const MainFunctionParams
& parameters
) {
108 TRACE_EVENT0("gpu", "GpuMain");
109 base::trace_event::TraceLog::GetInstance()->SetProcessName("GPU Process");
110 base::trace_event::TraceLog::GetInstance()->SetProcessSortIndex(
111 kTraceEventGpuProcessSortIndex
);
113 const base::CommandLine
& command_line
= parameters
.command_line
;
114 if (command_line
.HasSwitch(switches::kGpuStartupDialog
)) {
115 ChildProcess::WaitForDebugger("Gpu");
118 base::Time start_time
= base::Time::Now();
121 // Prevent Windows from displaying a modal dialog on failures like not being
122 // able to load a DLL.
124 SEM_FAILCRITICALERRORS
|
125 SEM_NOGPFAULTERRORBOX
|
126 SEM_NOOPENFILEERRORBOX
);
127 #elif defined(USE_X11)
128 ui::SetDefaultX11ErrorHandlers();
131 logging::SetLogMessageHandler(GpuProcessLogMessageHandler
);
133 if (command_line
.HasSwitch(switches::kSupportsDualGpus
)) {
134 std::string types
= command_line
.GetSwitchValueASCII(
135 switches::kGpuDriverBugWorkarounds
);
136 std::set
<int> workarounds
;
137 gpu::StringToFeatureSet(types
, &workarounds
);
138 if (workarounds
.count(gpu::FORCE_DISCRETE_GPU
) == 1)
139 ui::GpuSwitchingManager::GetInstance()->ForceUseOfDiscreteGpu();
140 else if (workarounds
.count(gpu::FORCE_INTEGRATED_GPU
) == 1)
141 ui::GpuSwitchingManager::GetInstance()->ForceUseOfIntegratedGpu();
144 // Initialization of the OpenGL bindings may fail, in which case we
145 // will need to tear down this process. However, we can not do so
146 // safely until the IPC channel is set up, because the detection of
147 // early return of a child process is implemented using an IPC
148 // channel error. If the IPC channel is not fully set up between the
149 // browser and GPU process, and the GPU process crashes or exits
150 // early, the browser process will never detect it. For this reason
151 // we defer tearing down the GPU process until receiving the
152 // GpuMsg_Initialize message from the browser.
153 bool dead_on_arrival
= false;
156 base::MessageLoop::Type message_loop_type
= base::MessageLoop::TYPE_IO
;
157 // Unless we're running on desktop GL, we don't need a UI message
158 // loop, so avoid its use to work around apparent problems with some
159 // third-party software.
160 if (command_line
.HasSwitch(switches::kUseGL
) &&
161 command_line
.GetSwitchValueASCII(switches::kUseGL
) ==
162 gfx::kGLImplementationDesktopName
) {
163 message_loop_type
= base::MessageLoop::TYPE_UI
;
165 base::MessageLoop
main_message_loop(message_loop_type
);
166 #elif defined(OS_LINUX) && defined(USE_X11)
167 // We need a UI loop so that we can grab the Expose events. See GLSurfaceGLX
168 // and https://crbug.com/326995.
169 base::MessageLoop
main_message_loop(base::MessageLoop::TYPE_UI
);
170 scoped_ptr
<ui::PlatformEventSource
> event_source
=
171 ui::PlatformEventSource::CreateDefault();
172 #elif defined(OS_LINUX)
173 base::MessageLoop
main_message_loop(base::MessageLoop::TYPE_DEFAULT
);
174 #elif defined(OS_MACOSX)
175 // This is necessary for CoreAnimation layers hosted in the GPU process to be
176 // drawn. See http://crbug.com/312462.
177 scoped_ptr
<base::MessagePump
> pump(new base::MessagePumpCFRunLoop());
178 base::MessageLoop
main_message_loop(pump
.Pass());
180 base::MessageLoop
main_message_loop(base::MessageLoop::TYPE_IO
);
183 base::PlatformThread::SetName("CrGpuMain");
185 // In addition to disabling the watchdog if the command line switch is
186 // present, disable the watchdog on valgrind because the code is expected
187 // to run slowly in that case.
188 bool enable_watchdog
=
189 !command_line
.HasSwitch(switches::kDisableGpuWatchdog
) &&
190 !RunningOnValgrind();
192 // Disable the watchdog in debug builds because they tend to only be run by
193 // developers who will not appreciate the watchdog killing the GPU process.
195 enable_watchdog
= false;
198 bool delayed_watchdog_enable
= false;
200 #if defined(OS_CHROMEOS)
201 // Don't start watchdog immediately, to allow developers to switch to VT2 on
203 delayed_watchdog_enable
= true;
206 scoped_refptr
<GpuWatchdogThread
> watchdog_thread
;
208 // Start the GPU watchdog only after anything that is expected to be time
209 // consuming has completed, otherwise the process is liable to be aborted.
210 if (enable_watchdog
&& !delayed_watchdog_enable
) {
211 watchdog_thread
= new GpuWatchdogThread(kGpuTimeout
);
212 base::Thread::Options options
;
213 options
.timer_slack
= base::TIMER_SLACK_MAXIMUM
;
214 watchdog_thread
->StartWithOptions(options
);
217 gpu::GPUInfo gpu_info
;
218 // Get vendor_id, device_id, driver_version from browser process through
219 // commandline switches.
220 GetGpuInfoFromCommandLine(gpu_info
, command_line
);
222 base::TimeDelta collect_context_time
;
223 base::TimeDelta initialize_one_off_time
;
225 // Warm up resources that don't need access to GPUInfo.
226 if (WarmUpSandbox(command_line
)) {
227 #if defined(OS_LINUX)
228 bool initialized_sandbox
= false;
229 bool initialized_gl_context
= false;
230 bool should_initialize_gl_context
= false;
231 // On Chrome OS ARM Mali, GPU driver userspace creates threads when
232 // initializing a GL context, so start the sandbox early.
233 if (command_line
.HasSwitch(switches::kGpuSandboxStartEarly
)) {
234 gpu_info
.sandboxed
= StartSandboxLinux(
235 gpu_info
, watchdog_thread
.get(), should_initialize_gl_context
);
236 initialized_sandbox
= true;
238 #endif // defined(OS_LINUX)
240 base::TimeTicks before_initialize_one_off
= base::TimeTicks::Now();
242 // Determine if we need to initialize GL here or it has already been done.
243 bool gl_already_initialized
= false;
244 #if defined(OS_MACOSX)
245 if (!command_line
.HasSwitch(switches::kNoSandbox
)) {
246 // On Mac, if the sandbox is enabled, then GLSurface::InitializeOneOff()
247 // is called from the sandbox warmup code before getting here.
248 gl_already_initialized
= true;
251 if (command_line
.HasSwitch(switches::kInProcessGPU
)) {
252 // With in-process GPU, GLSurface::InitializeOneOff() is called from
253 // GpuChildThread before getting here.
254 gl_already_initialized
= true;
257 // Load and initialize the GL implementation and locate the GL entry points.
258 bool gl_initialized
=
259 gl_already_initialized
260 ? gfx::GetGLImplementation() != gfx::kGLImplementationNone
261 : gfx::GLSurface::InitializeOneOff();
262 if (gl_initialized
) {
263 // We need to collect GL strings (VENDOR, RENDERER) for blacklisting
264 // purposes. However, on Mac we don't actually use them. As documented in
265 // crbug.com/222934, due to some driver issues, glGetString could take
266 // multiple seconds to finish, which in turn cause the GPU process to
268 // By skipping the following code on Mac, we don't really lose anything,
269 // because the basic GPU information is passed down from browser process
270 // and we already registered them through SetGpuInfo() above.
271 base::TimeTicks before_collect_context_graphics_info
=
272 base::TimeTicks::Now();
273 #if !defined(OS_MACOSX)
274 if (!CollectGraphicsInfo(gpu_info
))
275 dead_on_arrival
= true;
277 #if defined(OS_CHROMEOS) || defined(OS_ANDROID)
278 // Recompute gpu driver bug workarounds - this is specifically useful
279 // on systems where vendor_id/device_id aren't available.
280 if (!command_line
.HasSwitch(switches::kDisableGpuDriverBugWorkarounds
)) {
281 gpu::ApplyGpuDriverBugWorkarounds(
282 gpu_info
, const_cast<base::CommandLine
*>(&command_line
));
286 #if defined(OS_LINUX)
287 initialized_gl_context
= true;
288 #if !defined(OS_CHROMEOS)
289 if (gpu_info
.gpu
.vendor_id
== 0x10de && // NVIDIA
290 gpu_info
.driver_vendor
== "NVIDIA" &&
291 !CanAccessNvidiaDeviceFile())
292 dead_on_arrival
= true;
293 #endif // !defined(OS_CHROMEOS)
294 #endif // defined(OS_LINUX)
295 #endif // !defined(OS_MACOSX)
296 collect_context_time
=
297 base::TimeTicks::Now() - before_collect_context_graphics_info
;
298 } else { // gl_initialized
299 VLOG(1) << "gfx::GLSurface::InitializeOneOff failed";
300 dead_on_arrival
= true;
303 initialize_one_off_time
=
304 base::TimeTicks::Now() - before_initialize_one_off
;
306 if (enable_watchdog
&& delayed_watchdog_enable
) {
307 watchdog_thread
= new GpuWatchdogThread(kGpuTimeout
);
308 base::Thread::Options options
;
309 options
.timer_slack
= base::TIMER_SLACK_MAXIMUM
;
310 watchdog_thread
->StartWithOptions(options
);
313 // OSMesa is expected to run very slowly, so disable the watchdog in that
315 if (enable_watchdog
&&
316 gfx::GetGLImplementation() == gfx::kGLImplementationOSMesaGL
) {
317 watchdog_thread
->Stop();
318 watchdog_thread
= NULL
;
321 #if defined(OS_LINUX)
322 should_initialize_gl_context
= !initialized_gl_context
&&
325 if (!initialized_sandbox
) {
326 gpu_info
.sandboxed
= StartSandboxLinux(gpu_info
, watchdog_thread
.get(),
327 should_initialize_gl_context
);
329 #elif defined(OS_WIN)
330 gpu_info
.sandboxed
= StartSandboxWindows(parameters
.sandbox_info
);
331 #elif defined(OS_MACOSX)
332 gpu_info
.sandboxed
= Sandbox::SandboxIsCurrentlyActive();
335 gpu_info
.video_encode_accelerator_supported_profiles
=
336 content::GpuVideoEncodeAccelerator::GetSupportedProfiles();
338 dead_on_arrival
= true;
341 logging::SetLogMessageHandler(NULL
);
343 GpuProcess gpu_process
;
345 // These UMA must be stored after GpuProcess is constructed as it
346 // initializes StatisticsRecorder which tracks the histograms.
347 UMA_HISTOGRAM_TIMES("GPU.CollectContextGraphicsInfo", collect_context_time
);
348 UMA_HISTOGRAM_TIMES("GPU.InitializeOneOffTime", initialize_one_off_time
);
350 GpuChildThread
* child_thread
= new GpuChildThread(watchdog_thread
.get(),
353 deferred_messages
.Get());
354 while (!deferred_messages
.Get().empty())
355 deferred_messages
.Get().pop();
357 child_thread
->Init(start_time
);
359 gpu_process
.set_main_thread(child_thread
);
361 if (watchdog_thread
.get())
362 watchdog_thread
->AddPowerObserver();
365 TRACE_EVENT0("gpu", "Run Message Loop");
366 main_message_loop
.Run();
369 child_thread
->StopWatchdog();
376 void GetGpuInfoFromCommandLine(gpu::GPUInfo
& gpu_info
,
377 const base::CommandLine
& command_line
) {
378 DCHECK(command_line
.HasSwitch(switches::kGpuVendorID
) &&
379 command_line
.HasSwitch(switches::kGpuDeviceID
) &&
380 command_line
.HasSwitch(switches::kGpuDriverVersion
));
381 bool success
= base::HexStringToUInt(
382 command_line
.GetSwitchValueASCII(switches::kGpuVendorID
),
383 &gpu_info
.gpu
.vendor_id
);
385 success
= base::HexStringToUInt(
386 command_line
.GetSwitchValueASCII(switches::kGpuDeviceID
),
387 &gpu_info
.gpu
.device_id
);
389 gpu_info
.driver_vendor
=
390 command_line
.GetSwitchValueASCII(switches::kGpuDriverVendor
);
391 gpu_info
.driver_version
=
392 command_line
.GetSwitchValueASCII(switches::kGpuDriverVersion
);
393 GetContentClient()->SetGpuInfo(gpu_info
);
396 bool WarmUpSandbox(const base::CommandLine
& command_line
) {
398 TRACE_EVENT0("gpu", "Warm up rand");
399 // Warm up the random subsystem, which needs to be done pre-sandbox on all
401 (void) base::RandUint64();
406 #if !defined(OS_MACOSX)
407 bool CollectGraphicsInfo(gpu::GPUInfo
& gpu_info
) {
409 gpu::CollectInfoResult result
= gpu::CollectContextGraphicsInfo(&gpu_info
);
411 case gpu::kCollectInfoFatalFailure
:
412 LOG(ERROR
) << "gpu::CollectGraphicsInfo failed (fatal).";
415 case gpu::kCollectInfoNonFatalFailure
:
416 DVLOG(1) << "gpu::CollectGraphicsInfo failed (non-fatal).";
418 case gpu::kCollectInfoNone
:
421 case gpu::kCollectInfoSuccess
:
424 GetContentClient()->SetGpuInfo(gpu_info
);
429 #if defined(OS_LINUX)
430 #if !defined(OS_CHROMEOS)
431 bool CanAccessNvidiaDeviceFile() {
433 base::ThreadRestrictions::AssertIOAllowed();
434 if (access("/dev/nvidiactl", R_OK
) != 0) {
435 DVLOG(1) << "NVIDIA device file /dev/nvidiactl access denied";
442 void CreateDummyGlContext() {
443 scoped_refptr
<gfx::GLSurface
> surface(
444 gfx::GLSurface::CreateOffscreenGLSurface(gfx::Size()));
445 if (!surface
.get()) {
446 DVLOG(1) << "gfx::GLSurface::CreateOffscreenGLSurface failed";
450 // On Linux, this is needed to make sure /dev/nvidiactl has
451 // been opened and its descriptor cached.
452 scoped_refptr
<gfx::GLContext
> context(gfx::GLContext::CreateGLContext(
453 NULL
, surface
.get(), gfx::PreferDiscreteGpu
));
454 if (!context
.get()) {
455 DVLOG(1) << "gfx::GLContext::CreateGLContext failed";
459 // Similarly, this is needed for /dev/nvidia0.
460 if (context
->MakeCurrent(surface
.get())) {
461 context
->ReleaseCurrent(surface
.get());
463 DVLOG(1) << "gfx::GLContext::MakeCurrent failed";
467 void WarmUpSandboxNvidia(const gpu::GPUInfo
& gpu_info
,
468 bool should_initialize_gl_context
) {
469 // We special case Optimus since the vendor_id we see may not be Nvidia.
470 bool uses_nvidia_driver
= (gpu_info
.gpu
.vendor_id
== 0x10de && // NVIDIA.
471 gpu_info
.driver_vendor
== "NVIDIA") ||
473 if (uses_nvidia_driver
&& should_initialize_gl_context
) {
474 // We need this on Nvidia to pre-open /dev/nvidiactl and /dev/nvidia0.
475 CreateDummyGlContext();
479 bool StartSandboxLinux(const gpu::GPUInfo
& gpu_info
,
480 GpuWatchdogThread
* watchdog_thread
,
481 bool should_initialize_gl_context
) {
482 TRACE_EVENT0("gpu", "Initialize sandbox");
486 WarmUpSandboxNvidia(gpu_info
, should_initialize_gl_context
);
488 if (watchdog_thread
) {
489 // LinuxSandbox needs to be able to ensure that the thread
490 // has really been stopped.
491 LinuxSandbox::StopThread(watchdog_thread
);
494 #if defined(SANITIZER_COVERAGE)
495 const std::string sancov_file_name
=
496 "gpu." + base::Uint64ToString(base::RandUint64());
497 LinuxSandbox
* linux_sandbox
= LinuxSandbox::GetInstance();
498 linux_sandbox
->sanitizer_args()->coverage_sandboxed
= 1;
499 linux_sandbox
->sanitizer_args()->coverage_fd
=
500 __sanitizer_maybe_open_cov_file(sancov_file_name
.c_str());
501 linux_sandbox
->sanitizer_args()->coverage_max_block_size
= 0;
504 // LinuxSandbox::InitializeSandbox() must always be called
505 // with only one thread.
506 res
= LinuxSandbox::InitializeSandbox();
507 if (watchdog_thread
) {
508 base::Thread::Options options
;
509 options
.timer_slack
= base::TIMER_SLACK_MAXIMUM
;
510 watchdog_thread
->StartWithOptions(options
);
515 #endif // defined(OS_LINUX)
518 bool StartSandboxWindows(const sandbox::SandboxInterfaceInfo
* sandbox_info
) {
519 TRACE_EVENT0("gpu", "Lower token");
521 // For Windows, if the target_services interface is not zero, the process
522 // is sandboxed and we must call LowerToken() before rendering untrusted
524 sandbox::TargetServices
* target_services
= sandbox_info
->target_services
;
525 if (target_services
) {
526 #if defined(ADDRESS_SANITIZER)
527 // Bind and leak dbghelp.dll before the token is lowered, otherwise
528 // AddressSanitizer will crash when trying to symbolize a report.
529 if (!LoadLibraryA("dbghelp.dll"))
533 target_services
->LowerToken();
539 #endif // defined(OS_WIN)
543 } // namespace content