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.
4 
5 #include <stddef.h>
6 #include <utility>
7 
8 #include "base/base_switches.h"
9 #include "base/command_line.h"
10 #include "base/debug/debugger.h"
11 #include "base/debug/leak_annotations.h"
12 #include "base/i18n/rtl.h"
13 #include "base/message_loop/message_pump.h"
14 #include "base/message_loop/message_pump_type.h"
15 #include "base/metrics/histogram_macros.h"
16 #include "base/optional.h"
17 #include "base/pending_task.h"
18 #include "base/run_loop.h"
19 #include "base/strings/string_number_conversions.h"
20 #include "base/system/sys_info.h"
21 #include "base/task/sequence_manager/sequence_manager.h"
22 #include "base/threading/platform_thread.h"
23 #include "base/timer/hi_res_timer_manager.h"
24 #include "base/trace_event/trace_event.h"
25 #include "build/build_config.h"
26 #include "content/common/content_constants_internal.h"
27 #include "content/common/content_switches_internal.h"
28 #include "content/common/skia_utils.h"
29 #include "content/public/common/content_switches.h"
30 #include "content/public/common/main_function_params.h"
31 #include "content/public/renderer/content_renderer_client.h"
32 #include "content/public/renderer/render_thread.h"
33 #include "content/renderer/render_process_impl.h"
34 #include "content/renderer/render_thread_impl.h"
35 #include "content/renderer/renderer_main_platform_delegate.h"
36 #include "media/media_buildflags.h"
37 #include "mojo/public/cpp/bindings/mojo_buildflags.h"
38 #include "ppapi/buildflags/buildflags.h"
39 #include "sandbox/policy/switches.h"
40 #include "services/tracing/public/cpp/trace_startup.h"
41 #include "third_party/blink/public/platform/platform.h"
42 #include "third_party/blink/public/platform/scheduler/web_thread_scheduler.h"
43 #include "third_party/webrtc_overrides/init_webrtc.h"  // nogncheck
44 #include "ui/base/ui_base_switches.h"
45 
46 #if defined(OS_ANDROID)
47 #include "base/android/library_loader/library_loader_hooks.h"
48 #endif  // OS_ANDROID
49 
50 #if defined(OS_MAC)
51 #include <Carbon/Carbon.h>
52 #include <signal.h>
53 #include <unistd.h>
54 
55 #include "base/mac/scoped_nsautorelease_pool.h"
56 #include "base/message_loop/message_pump_mac.h"
57 #include "third_party/blink/public/web/web_view.h"
58 #endif  // OS_MAC
59 
60 #if defined(OS_CHROMEOS)
61 #include "chromeos/system/core_scheduling.h"
62 #include "content/renderer/performance_manager/mechanisms/userspace_swap_renderer_initialization_impl.h"
63 #endif  // OS_CHROMEOS
64 
65 #if BUILDFLAG(ENABLE_PLUGINS)
66 #include "content/renderer/pepper/pepper_plugin_registry.h"
67 #endif
68 
69 #if BUILDFLAG(MOJO_RANDOM_DELAYS_ENABLED)
70 #include "mojo/public/cpp/bindings/lib/test_random_mojo_delays.h"
71 #endif
72 
73 namespace content {
74 namespace {
75 
76 // This function provides some ways to test crash and assertion handling
77 // behavior of the renderer.
HandleRendererErrorTestParameters(const base::CommandLine & command_line)78 static void HandleRendererErrorTestParameters(
79     const base::CommandLine& command_line) {
80   if (command_line.HasSwitch(switches::kWaitForDebugger))
81     base::debug::WaitForDebugger(60, true);
82 
83   if (command_line.HasSwitch(switches::kRendererStartupDialog))
84     WaitForDebugger("Renderer");
85 }
86 
CreateMainThreadMessagePump()87 std::unique_ptr<base::MessagePump> CreateMainThreadMessagePump() {
88 #if defined(OS_MAC)
89   // As long as scrollbars on Mac are painted with Cocoa, the message pump
90   // needs to be backed by a Foundation-level loop to process NSTimers. See
91   // http://crbug.com/306348#c24 for details.
92   return base::MessagePump::Create(base::MessagePumpType::NS_RUNLOOP);
93 #elif defined(OS_FUCHSIA)
94   // Allow FIDL APIs on renderer main thread.
95   return base::MessagePump::Create(base::MessagePumpType::IO);
96 #else
97   return base::MessagePump::Create(base::MessagePumpType::DEFAULT);
98 #endif
99 }
100 
101 }  // namespace
102 
103 // mainline routine for running as the Renderer process
RendererMain(const MainFunctionParams & parameters)104 int RendererMain(const MainFunctionParams& parameters) {
105   // Don't use the TRACE_EVENT0 macro because the tracing infrastructure doesn't
106   // expect synchronous events around the main loop of a thread.
107   TRACE_EVENT_ASYNC_BEGIN1("startup", "RendererMain", 0, "zygote_child", false);
108 
109   base::trace_event::TraceLog::GetInstance()->set_process_name("Renderer");
110   base::trace_event::TraceLog::GetInstance()->SetProcessSortIndex(
111       kTraceEventRendererProcessSortIndex);
112 
113   const base::CommandLine& command_line = parameters.command_line;
114 
115 #if defined(OS_MAC)
116   base::mac::ScopedNSAutoreleasePool* pool = parameters.autorelease_pool;
117 #endif  // OS_MAC
118 
119 #if defined(OS_CHROMEOS)
120   // As Zygote process starts up earlier than browser process gets its own
121   // locale (at login time for Chrome OS), we have to set the ICU default
122   // locale for renderer process here.
123   // ICU locale will be used for fallback font selection etc.
124   if (command_line.HasSwitch(switches::kLang)) {
125     const std::string locale =
126         command_line.GetSwitchValueASCII(switches::kLang);
127     base::i18n::SetICUDefaultLocale(locale);
128   }
129 
130   // When we start the renderer on ChromeOS if the system has core scheduling
131   // available we want to turn it on.
132   chromeos::system::EnableCoreSchedulingIfAvailable();
133 
134   base::Optional<
135       performance_manager::mechanism::UserspaceSwapRendererInitializationImpl>
136       swap_init;
137   if (performance_manager::mechanism::UserspaceSwapRendererInitializationImpl::
138           UserspaceSwapSupportedAndEnabled()) {
139     swap_init.emplace();
140 
141     PLOG_IF(ERROR, !swap_init->PreSandboxSetup())
142         << "Unable to complete presandbox userspace swap initialization";
143   }
144 #endif
145 
146   InitializeSkia();
147 
148   // This function allows pausing execution using the --renderer-startup-dialog
149   // flag allowing us to attach a debugger.
150   // Do not move this function down since that would mean we can't easily debug
151   // whatever occurs before it.
152   HandleRendererErrorTestParameters(command_line);
153 
154   RendererMainPlatformDelegate platform(parameters);
155 
156   base::PlatformThread::SetName("CrRendererMain");
157 
158   // Force main thread initialization. When the implementation is based on a
159   // better means of determining which is the main thread, remove.
160   RenderThread::IsMainThread();
161 
162 #if defined(OS_ANDROID)
163   // If we have any pending LibraryLoader histograms, record them.
164   base::android::RecordLibraryLoaderRendererHistograms();
165 #endif
166 
167   base::Optional<base::Time> initial_virtual_time;
168   if (command_line.HasSwitch(switches::kInitialVirtualTime)) {
169     double initial_time;
170     if (base::StringToDouble(
171             command_line.GetSwitchValueASCII(switches::kInitialVirtualTime),
172             &initial_time)) {
173       initial_virtual_time = base::Time::FromDoubleT(initial_time);
174     }
175   }
176 
177   blink::Platform::InitializeBlink();
178   std::unique_ptr<blink::scheduler::WebThreadScheduler> main_thread_scheduler =
179       blink::scheduler::WebThreadScheduler::CreateMainThreadScheduler(
180           CreateMainThreadMessagePump(), initial_virtual_time);
181 
182   platform.PlatformInitialize();
183 
184 #if BUILDFLAG(ENABLE_PLUGINS)
185   // Load pepper plugins before engaging the sandbox.
186   PepperPluginRegistry::GetInstance();
187 #endif
188   // Initialize WebRTC before engaging the sandbox.
189   // NOTE: On linux, this call could already have been made from
190   // zygote_main_linux.cc.  However, calling multiple times from the same thread
191   // is OK.
192   InitializeWebRtcModule();
193 
194   {
195     bool should_run_loop = true;
196     bool need_sandbox =
197         !command_line.HasSwitch(sandbox::policy::switches::kNoSandbox);
198 
199 #if !defined(OS_WIN) && !defined(OS_MAC)
200     // Sandbox is enabled before RenderProcess initialization on all platforms,
201     // except Windows and Mac.
202     // TODO(markus): Check if it is OK to remove ifdefs for Windows and Mac.
203     if (need_sandbox) {
204       should_run_loop = platform.EnableSandbox();
205       need_sandbox = false;
206     }
207 #endif
208 
209     std::unique_ptr<RenderProcess> render_process = RenderProcessImpl::Create();
210     // It's not a memory leak since RenderThread has the same lifetime
211     // as a renderer process.
212     base::RunLoop run_loop;
213     new RenderThreadImpl(run_loop.QuitClosure(),
214                          std::move(main_thread_scheduler));
215 
216 #if defined(OS_CHROMEOS)
217     // Once the sandbox has been entered and initialization of render threads
218     // complete we will transfer FDs to the browser, or close them on failure.
219     // This should always be called because it will also transfer the errno that
220     // prevented the creation of the userfaultfd if applicable.
221     if (swap_init) {
222       swap_init->TransferFDsOrCleanup();
223 
224       // No need to leave this around any further.
225       swap_init.reset();
226     }
227 #endif
228 
229 #if defined(OS_POSIX) && !defined(OS_ANDROID) && !defined(OS_MAC)
230     // Startup tracing is usually enabled earlier, but if we forked from a
231     // zygote, we can only enable it after mojo IPC support is brought up
232     // initialized by RenderThreadImpl, because the mojo broker has to create
233     // the tracing SMB on our behalf due to the zygote sandbox.
234     if (parameters.zygote_child) {
235       tracing::EnableStartupTracingIfNeeded();
236       TRACE_EVENT_ASYNC_BEGIN1("startup", "RendererMain", 0, "zygote_child",
237                                true);
238     }
239 #endif  // OS_POSIX && !OS_ANDROID && !OS_MAC
240 
241     if (need_sandbox)
242       should_run_loop = platform.EnableSandbox();
243 
244 #if BUILDFLAG(MOJO_RANDOM_DELAYS_ENABLED)
245     mojo::BeginRandomMojoDelays();
246 #endif
247 
248     base::HighResolutionTimerManager hi_res_timer_manager;
249 
250     if (should_run_loop) {
251 #if defined(OS_MAC)
252       if (pool)
253         pool->Recycle();
254 #endif
255       TRACE_EVENT_ASYNC_BEGIN0("toplevel", "RendererMain.START_MSG_LOOP", 0);
256       run_loop.Run();
257       TRACE_EVENT_ASYNC_END0("toplevel", "RendererMain.START_MSG_LOOP", 0);
258     }
259 
260 #if defined(LEAK_SANITIZER)
261     // Run leak detection before RenderProcessImpl goes out of scope. This helps
262     // ignore shutdown-only leaks.
263     __lsan_do_leak_check();
264 #endif
265   }
266   platform.PlatformUninitialize();
267   TRACE_EVENT_ASYNC_END0("startup", "RendererMain", 0);
268   return 0;
269 }
270 
271 }  // namespace content
272