cc: Make a FakeResourceProvider and use it in tests to construct.
[chromium-blink-merge.git] / content / gpu / gpu_main.cc
blobc6a59fc9c19c745e8eb5ad78dab52603d61b279b
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.
5 #include <stdlib.h>
7 #if defined(OS_WIN)
8 #include <dwmapi.h>
9 #include <windows.h>
10 #endif
12 #include "base/lazy_instance.h"
13 #include "base/message_loop/message_loop.h"
14 #include "base/metrics/histogram.h"
15 #include "base/metrics/statistics_recorder.h"
16 #include "base/rand_util.h"
17 #include "base/strings/string_number_conversions.h"
18 #include "base/strings/stringprintf.h"
19 #include "base/third_party/dynamic_annotations/dynamic_annotations.h"
20 #include "base/threading/platform_thread.h"
21 #include "base/trace_event/trace_event.h"
22 #include "build/build_config.h"
23 #include "content/child/child_process.h"
24 #include "content/common/content_constants_internal.h"
25 #include "content/common/gpu/gpu_config.h"
26 #include "content/common/gpu/gpu_messages.h"
27 #include "content/common/gpu/media/gpu_video_decode_accelerator.h"
28 #include "content/common/gpu/media/gpu_video_encode_accelerator.h"
29 #include "content/common/sandbox_linux/sandbox_linux.h"
30 #include "content/gpu/gpu_child_thread.h"
31 #include "content/gpu/gpu_process.h"
32 #include "content/gpu/gpu_watchdog_thread.h"
33 #include "content/public/common/content_client.h"
34 #include "content/public/common/content_switches.h"
35 #include "content/public/common/main_function_params.h"
36 #include "gpu/command_buffer/service/gpu_switches.h"
37 #include "gpu/config/gpu_info_collector.h"
38 #include "gpu/config/gpu_switches.h"
39 #include "gpu/config/gpu_util.h"
40 #include "ui/events/platform/platform_event_source.h"
41 #include "ui/gl/gl_implementation.h"
42 #include "ui/gl/gl_surface.h"
43 #include "ui/gl/gl_switches.h"
44 #include "ui/gl/gpu_switching_manager.h"
46 #if defined(OS_WIN)
47 #include "base/win/windows_version.h"
48 #include "base/win/scoped_com_initializer.h"
49 #include "sandbox/win/src/sandbox.h"
50 #endif
52 #if defined(USE_X11)
53 #include "ui/base/x/x11_util.h"
54 #endif
56 #if defined(OS_LINUX)
57 #include "content/public/common/sandbox_init.h"
58 #endif
60 #if defined(OS_MACOSX)
61 #include "base/message_loop/message_pump_mac.h"
62 #include "content/common/sandbox_mac.h"
63 #endif
65 #if defined(OS_CHROMEOS) && defined(ARCH_CPU_X86_FAMILY)
66 #include "content/common/gpu/media/vaapi_wrapper.h"
67 #endif
69 #if defined(SANITIZER_COVERAGE)
70 #include <sanitizer/common_interface_defs.h>
71 #include <sanitizer/coverage_interface.h>
72 #endif
74 const int kGpuTimeout = 10000;
76 namespace content {
78 namespace {
80 void GetGpuInfoFromCommandLine(gpu::GPUInfo& gpu_info,
81 const base::CommandLine& command_line);
82 bool WarmUpSandbox(const base::CommandLine& command_line);
84 #if !defined(OS_MACOSX)
85 bool CollectGraphicsInfo(gpu::GPUInfo& gpu_info);
86 #endif
88 #if defined(OS_LINUX)
89 #if !defined(OS_CHROMEOS)
90 bool CanAccessNvidiaDeviceFile();
91 #endif
92 bool StartSandboxLinux(const gpu::GPUInfo&, GpuWatchdogThread*, bool);
93 #elif defined(OS_WIN)
94 bool StartSandboxWindows(const sandbox::SandboxInterfaceInfo*);
95 #endif
97 base::LazyInstance<GpuChildThread::DeferredMessages> deferred_messages =
98 LAZY_INSTANCE_INITIALIZER;
100 bool GpuProcessLogMessageHandler(int severity,
101 const char* file, int line,
102 size_t message_start,
103 const std::string& str) {
104 std::string header = str.substr(0, message_start);
105 std::string message = str.substr(message_start);
106 deferred_messages.Get().push(new GpuHostMsg_OnLogMessage(
107 severity, header, message));
108 return false;
111 } // namespace anonymous
113 // Main function for starting the Gpu process.
114 int GpuMain(const MainFunctionParams& parameters) {
115 TRACE_EVENT0("gpu", "GpuMain");
116 base::trace_event::TraceLog::GetInstance()->SetProcessName("GPU Process");
117 base::trace_event::TraceLog::GetInstance()->SetProcessSortIndex(
118 kTraceEventGpuProcessSortIndex);
120 const base::CommandLine& command_line = parameters.command_line;
121 if (command_line.HasSwitch(switches::kGpuStartupDialog)) {
122 ChildProcess::WaitForDebugger("Gpu");
125 base::Time start_time = base::Time::Now();
127 #if defined(OS_WIN)
128 // Prevent Windows from displaying a modal dialog on failures like not being
129 // able to load a DLL.
130 SetErrorMode(
131 SEM_FAILCRITICALERRORS |
132 SEM_NOGPFAULTERRORBOX |
133 SEM_NOOPENFILEERRORBOX);
134 #elif defined(USE_X11)
135 ui::SetDefaultX11ErrorHandlers();
136 #endif
138 logging::SetLogMessageHandler(GpuProcessLogMessageHandler);
140 if (command_line.HasSwitch(switches::kSupportsDualGpus)) {
141 std::string types = command_line.GetSwitchValueASCII(
142 switches::kGpuDriverBugWorkarounds);
143 std::set<int> workarounds;
144 gpu::StringToFeatureSet(types, &workarounds);
145 if (workarounds.count(gpu::FORCE_DISCRETE_GPU) == 1)
146 ui::GpuSwitchingManager::GetInstance()->ForceUseOfDiscreteGpu();
147 else if (workarounds.count(gpu::FORCE_INTEGRATED_GPU) == 1)
148 ui::GpuSwitchingManager::GetInstance()->ForceUseOfIntegratedGpu();
151 // Initialization of the OpenGL bindings may fail, in which case we
152 // will need to tear down this process. However, we can not do so
153 // safely until the IPC channel is set up, because the detection of
154 // early return of a child process is implemented using an IPC
155 // channel error. If the IPC channel is not fully set up between the
156 // browser and GPU process, and the GPU process crashes or exits
157 // early, the browser process will never detect it. For this reason
158 // we defer tearing down the GPU process until receiving the
159 // GpuMsg_Initialize message from the browser.
160 bool dead_on_arrival = false;
162 #if defined(OS_WIN)
163 // Use a UI message loop because ANGLE and the desktop GL platform can
164 // create child windows to render to.
165 base::MessageLoop main_message_loop(base::MessageLoop::TYPE_UI);
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());
179 #else
180 base::MessageLoop main_message_loop(base::MessageLoop::TYPE_IO);
181 #endif
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.
194 #ifndef NDEBUG
195 enable_watchdog = false;
196 #endif
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
202 // startup.
203 delayed_watchdog_enable = true;
204 #endif
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 // Initializes StatisticsRecorder which tracks UMA histograms.
218 base::StatisticsRecorder::Initialize();
220 gpu::GPUInfo gpu_info;
221 // Get vendor_id, device_id, driver_version from browser process through
222 // commandline switches.
223 GetGpuInfoFromCommandLine(gpu_info, command_line);
225 #if defined(OS_CHROMEOS) && defined(ARCH_CPU_X86_FAMILY)
226 VaapiWrapper::PreSandboxInitialization();
227 #endif
229 // Warm up resources that don't need access to GPUInfo.
230 if (WarmUpSandbox(command_line)) {
231 #if defined(OS_LINUX)
232 bool initialized_sandbox = false;
233 bool initialized_gl_context = false;
234 bool should_initialize_gl_context = false;
235 // On Chrome OS ARM Mali, GPU driver userspace creates threads when
236 // initializing a GL context, so start the sandbox early.
237 if (command_line.HasSwitch(switches::kGpuSandboxStartEarly)) {
238 gpu_info.sandboxed = StartSandboxLinux(
239 gpu_info, watchdog_thread.get(), should_initialize_gl_context);
240 initialized_sandbox = true;
242 #endif // defined(OS_LINUX)
244 base::TimeTicks before_initialize_one_off = base::TimeTicks::Now();
246 // Determine if we need to initialize GL here or it has already been done.
247 bool gl_already_initialized = false;
248 #if defined(OS_MACOSX)
249 if (!command_line.HasSwitch(switches::kNoSandbox)) {
250 // On Mac, if the sandbox is enabled, then GLSurface::InitializeOneOff()
251 // is called from the sandbox warmup code before getting here.
252 gl_already_initialized = true;
254 #endif
255 if (command_line.HasSwitch(switches::kInProcessGPU)) {
256 // With in-process GPU, GLSurface::InitializeOneOff() is called from
257 // GpuChildThread before getting here.
258 gl_already_initialized = true;
261 // Load and initialize the GL implementation and locate the GL entry points.
262 bool gl_initialized =
263 gl_already_initialized
264 ? gfx::GetGLImplementation() != gfx::kGLImplementationNone
265 : gfx::GLSurface::InitializeOneOff();
266 if (gl_initialized) {
267 // We need to collect GL strings (VENDOR, RENDERER) for blacklisting
268 // purposes. However, on Mac we don't actually use them. As documented in
269 // crbug.com/222934, due to some driver issues, glGetString could take
270 // multiple seconds to finish, which in turn cause the GPU process to
271 // crash.
272 // By skipping the following code on Mac, we don't really lose anything,
273 // because the basic GPU information is passed down from browser process
274 // and we already registered them through SetGpuInfo() above.
275 base::TimeTicks before_collect_context_graphics_info =
276 base::TimeTicks::Now();
277 #if !defined(OS_MACOSX)
278 if (!CollectGraphicsInfo(gpu_info))
279 dead_on_arrival = true;
281 #if defined(OS_CHROMEOS) || defined(OS_ANDROID)
282 // Recompute gpu driver bug workarounds - this is specifically useful
283 // on systems where vendor_id/device_id aren't available.
284 if (!command_line.HasSwitch(switches::kDisableGpuDriverBugWorkarounds)) {
285 gpu::ApplyGpuDriverBugWorkarounds(
286 gpu_info, const_cast<base::CommandLine*>(&command_line));
288 #endif
290 #if defined(OS_LINUX)
291 initialized_gl_context = true;
292 #if !defined(OS_CHROMEOS)
293 if (gpu_info.gpu.vendor_id == 0x10de && // NVIDIA
294 gpu_info.driver_vendor == "NVIDIA" &&
295 !CanAccessNvidiaDeviceFile())
296 dead_on_arrival = true;
297 #endif // !defined(OS_CHROMEOS)
298 #endif // defined(OS_LINUX)
299 #endif // !defined(OS_MACOSX)
300 base::TimeDelta collect_context_time =
301 base::TimeTicks::Now() - before_collect_context_graphics_info;
302 UMA_HISTOGRAM_TIMES("GPU.CollectContextGraphicsInfo",
303 collect_context_time);
304 } else { // gl_initialized
305 VLOG(1) << "gfx::GLSurface::InitializeOneOff failed";
306 dead_on_arrival = true;
309 base::TimeDelta initialize_one_off_time =
310 base::TimeTicks::Now() - before_initialize_one_off;
311 UMA_HISTOGRAM_MEDIUM_TIMES("GPU.InitializeOneOffMediumTime",
312 initialize_one_off_time);
314 if (enable_watchdog && delayed_watchdog_enable) {
315 watchdog_thread = new GpuWatchdogThread(kGpuTimeout);
316 base::Thread::Options options;
317 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
318 watchdog_thread->StartWithOptions(options);
321 // OSMesa is expected to run very slowly, so disable the watchdog in that
322 // case.
323 if (enable_watchdog &&
324 gfx::GetGLImplementation() == gfx::kGLImplementationOSMesaGL) {
325 watchdog_thread->Stop();
326 watchdog_thread = NULL;
329 #if defined(OS_LINUX)
330 should_initialize_gl_context = !initialized_gl_context &&
331 !dead_on_arrival;
333 if (!initialized_sandbox) {
334 gpu_info.sandboxed = StartSandboxLinux(gpu_info, watchdog_thread.get(),
335 should_initialize_gl_context);
337 #elif defined(OS_WIN)
338 gpu_info.sandboxed = StartSandboxWindows(parameters.sandbox_info);
339 #elif defined(OS_MACOSX)
340 gpu_info.sandboxed = Sandbox::SandboxIsCurrentlyActive();
341 #endif
343 gpu_info.video_decode_accelerator_supported_profiles =
344 content::GpuVideoDecodeAccelerator::GetSupportedProfiles();
345 gpu_info.video_encode_accelerator_supported_profiles =
346 content::GpuVideoEncodeAccelerator::GetSupportedProfiles();
347 } else {
348 dead_on_arrival = true;
351 logging::SetLogMessageHandler(NULL);
353 GpuProcess gpu_process;
355 GpuChildThread* child_thread = new GpuChildThread(watchdog_thread.get(),
356 dead_on_arrival,
357 gpu_info,
358 deferred_messages.Get());
359 while (!deferred_messages.Get().empty())
360 deferred_messages.Get().pop();
362 child_thread->Init(start_time);
364 gpu_process.set_main_thread(child_thread);
366 if (watchdog_thread.get())
367 watchdog_thread->AddPowerObserver();
370 TRACE_EVENT0("gpu", "Run Message Loop");
371 main_message_loop.Run();
374 child_thread->StopWatchdog();
376 return 0;
379 namespace {
381 void GetGpuInfoFromCommandLine(gpu::GPUInfo& gpu_info,
382 const base::CommandLine& command_line) {
383 DCHECK(command_line.HasSwitch(switches::kGpuVendorID) &&
384 command_line.HasSwitch(switches::kGpuDeviceID) &&
385 command_line.HasSwitch(switches::kGpuDriverVersion));
386 bool success = base::HexStringToUInt(
387 command_line.GetSwitchValueASCII(switches::kGpuVendorID),
388 &gpu_info.gpu.vendor_id);
389 DCHECK(success);
390 success = base::HexStringToUInt(
391 command_line.GetSwitchValueASCII(switches::kGpuDeviceID),
392 &gpu_info.gpu.device_id);
393 DCHECK(success);
394 gpu_info.driver_vendor =
395 command_line.GetSwitchValueASCII(switches::kGpuDriverVendor);
396 gpu_info.driver_version =
397 command_line.GetSwitchValueASCII(switches::kGpuDriverVersion);
398 GetContentClient()->SetGpuInfo(gpu_info);
401 bool WarmUpSandbox(const base::CommandLine& command_line) {
403 TRACE_EVENT0("gpu", "Warm up rand");
404 // Warm up the random subsystem, which needs to be done pre-sandbox on all
405 // platforms.
406 (void) base::RandUint64();
408 return true;
411 #if !defined(OS_MACOSX)
412 bool CollectGraphicsInfo(gpu::GPUInfo& gpu_info) {
413 bool res = true;
414 gpu::CollectInfoResult result = gpu::CollectContextGraphicsInfo(&gpu_info);
415 switch (result) {
416 case gpu::kCollectInfoFatalFailure:
417 LOG(ERROR) << "gpu::CollectGraphicsInfo failed (fatal).";
418 res = false;
419 break;
420 case gpu::kCollectInfoNonFatalFailure:
421 DVLOG(1) << "gpu::CollectGraphicsInfo failed (non-fatal).";
422 break;
423 case gpu::kCollectInfoNone:
424 NOTREACHED();
425 break;
426 case gpu::kCollectInfoSuccess:
427 break;
429 GetContentClient()->SetGpuInfo(gpu_info);
430 return res;
432 #endif
434 #if defined(OS_LINUX)
435 #if !defined(OS_CHROMEOS)
436 bool CanAccessNvidiaDeviceFile() {
437 bool res = true;
438 base::ThreadRestrictions::AssertIOAllowed();
439 if (access("/dev/nvidiactl", R_OK) != 0) {
440 DVLOG(1) << "NVIDIA device file /dev/nvidiactl access denied";
441 res = false;
443 return res;
445 #endif
447 void CreateDummyGlContext() {
448 scoped_refptr<gfx::GLSurface> surface(
449 gfx::GLSurface::CreateOffscreenGLSurface(gfx::Size()));
450 if (!surface.get()) {
451 DVLOG(1) << "gfx::GLSurface::CreateOffscreenGLSurface failed";
452 return;
455 // On Linux, this is needed to make sure /dev/nvidiactl has
456 // been opened and its descriptor cached.
457 scoped_refptr<gfx::GLContext> context(gfx::GLContext::CreateGLContext(
458 NULL, surface.get(), gfx::PreferDiscreteGpu));
459 if (!context.get()) {
460 DVLOG(1) << "gfx::GLContext::CreateGLContext failed";
461 return;
464 // Similarly, this is needed for /dev/nvidia0.
465 if (context->MakeCurrent(surface.get())) {
466 context->ReleaseCurrent(surface.get());
467 } else {
468 DVLOG(1) << "gfx::GLContext::MakeCurrent failed";
472 void WarmUpSandboxNvidia(const gpu::GPUInfo& gpu_info,
473 bool should_initialize_gl_context) {
474 // We special case Optimus since the vendor_id we see may not be Nvidia.
475 bool uses_nvidia_driver = (gpu_info.gpu.vendor_id == 0x10de && // NVIDIA.
476 gpu_info.driver_vendor == "NVIDIA") ||
477 gpu_info.optimus;
478 if (uses_nvidia_driver && should_initialize_gl_context) {
479 // We need this on Nvidia to pre-open /dev/nvidiactl and /dev/nvidia0.
480 CreateDummyGlContext();
484 bool StartSandboxLinux(const gpu::GPUInfo& gpu_info,
485 GpuWatchdogThread* watchdog_thread,
486 bool should_initialize_gl_context) {
487 TRACE_EVENT0("gpu", "Initialize sandbox");
489 bool res = false;
491 WarmUpSandboxNvidia(gpu_info, should_initialize_gl_context);
493 if (watchdog_thread) {
494 // LinuxSandbox needs to be able to ensure that the thread
495 // has really been stopped.
496 LinuxSandbox::StopThread(watchdog_thread);
499 #if defined(SANITIZER_COVERAGE)
500 const std::string sancov_file_name =
501 "gpu." + base::Uint64ToString(base::RandUint64());
502 LinuxSandbox* linux_sandbox = LinuxSandbox::GetInstance();
503 linux_sandbox->sanitizer_args()->coverage_sandboxed = 1;
504 linux_sandbox->sanitizer_args()->coverage_fd =
505 __sanitizer_maybe_open_cov_file(sancov_file_name.c_str());
506 linux_sandbox->sanitizer_args()->coverage_max_block_size = 0;
507 #endif
509 // LinuxSandbox::InitializeSandbox() must always be called
510 // with only one thread.
511 res = LinuxSandbox::InitializeSandbox();
512 if (watchdog_thread) {
513 base::Thread::Options options;
514 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
515 watchdog_thread->StartWithOptions(options);
518 return res;
520 #endif // defined(OS_LINUX)
522 #if defined(OS_WIN)
523 bool StartSandboxWindows(const sandbox::SandboxInterfaceInfo* sandbox_info) {
524 TRACE_EVENT0("gpu", "Lower token");
526 // For Windows, if the target_services interface is not zero, the process
527 // is sandboxed and we must call LowerToken() before rendering untrusted
528 // content.
529 sandbox::TargetServices* target_services = sandbox_info->target_services;
530 if (target_services) {
531 #if defined(ADDRESS_SANITIZER)
532 // Bind and leak dbghelp.dll before the token is lowered, otherwise
533 // AddressSanitizer will crash when trying to symbolize a report.
534 if (!LoadLibraryA("dbghelp.dll"))
535 return false;
536 #endif
538 target_services->LowerToken();
539 return true;
542 return false;
544 #endif // defined(OS_WIN)
546 } // namespace.
548 } // namespace content