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 "base/base_switches.h"
6 #include "base/command_line.h"
7 #include "base/debug/debugger.h"
8 #include "base/debug/stack_trace.h"
9 #include "base/debug/trace_event.h"
10 #include "base/i18n/rtl.h"
11 #include "base/memory/ref_counted.h"
12 #include "base/message_loop/message_loop.h"
13 #include "base/metrics/field_trial.h"
14 #include "base/metrics/histogram.h"
15 #include "base/metrics/statistics_recorder.h"
16 #include "base/metrics/stats_counters.h"
17 #include "base/path_service.h"
18 #include "base/pending_task.h"
19 #include "base/strings/string_util.h"
20 #include "base/threading/platform_thread.h"
21 #include "base/time/time.h"
22 #include "base/timer/hi_res_timer_manager.h"
23 #include "content/child/child_process.h"
24 #include "content/common/content_constants_internal.h"
25 #include "content/public/common/content_switches.h"
26 #include "content/public/common/main_function_params.h"
27 #include "content/public/renderer/content_renderer_client.h"
28 #include "content/renderer/browser_plugin/browser_plugin_manager_impl.h"
29 #include "content/renderer/pepper/pepper_plugin_registry.h"
30 #include "content/renderer/render_process_impl.h"
31 #include "content/renderer/render_thread_impl.h"
32 #include "content/renderer/renderer_main_platform_delegate.h"
33 #include "ui/base/ui_base_switches.h"
34 #include "webkit/child/webkit_child_helpers.h"
35 #include "webkit/glue/webkit_glue.h"
37 #if defined(OS_ANDROID)
38 #include "base/android/sys_utils.h"
39 #include "third_party/skia/include/core/SkGraphics.h"
42 #if defined(OS_MACOSX)
43 #include <Carbon/Carbon.h>
47 #include "base/mac/mac_util.h"
48 #include "base/mac/scoped_nsautorelease_pool.h"
49 #include "third_party/WebKit/public/web/WebView.h"
52 #if defined(ENABLE_WEBRTC)
53 #include "third_party/libjingle/overrides/init_webrtc.h"
58 // This function provides some ways to test crash and assertion handling
59 // behavior of the renderer.
60 static void HandleRendererErrorTestParameters(const CommandLine& command_line) {
61 if (command_line.HasSwitch(switches::kWaitForDebugger))
62 base::debug::WaitForDebugger(60, true);
64 if (command_line.HasSwitch(switches::kRendererStartupDialog))
65 ChildProcess::WaitForDebugger("Renderer");
67 // This parameter causes an assertion.
68 if (command_line.HasSwitch(switches::kRendererAssertTest)) {
73 // This is a simplified version of the browser Jankometer, which measures
74 // the processing time of tasks on the render thread.
75 class RendererMessageLoopObserver : public base::MessageLoop::TaskObserver {
77 RendererMessageLoopObserver()
78 : process_times_(base::Histogram::FactoryGet(
79 "Chrome.ProcMsgL RenderThread",
80 1, 3600000, 50, base::Histogram::kUmaTargetedHistogramFlag)) {}
81 virtual ~RendererMessageLoopObserver() {}
83 virtual void WillProcessTask(const base::PendingTask& pending_task) OVERRIDE {
84 begin_process_message_ = base::TimeTicks::Now();
87 virtual void DidProcessTask(const base::PendingTask& pending_task) OVERRIDE {
88 if (!begin_process_message_.is_null())
89 process_times_->AddTime(base::TimeTicks::Now() - begin_process_message_);
93 base::TimeTicks begin_process_message_;
94 base::HistogramBase* const process_times_;
95 DISALLOW_COPY_AND_ASSIGN(RendererMessageLoopObserver);
98 // For measuring memory usage after each task. Behind a command line flag.
99 class MemoryObserver : public base::MessageLoop::TaskObserver {
102 virtual ~MemoryObserver() {}
104 virtual void WillProcessTask(const base::PendingTask& pending_task) OVERRIDE {
107 virtual void DidProcessTask(const base::PendingTask& pending_task) OVERRIDE {
108 HISTOGRAM_MEMORY_KB("Memory.RendererUsed", webkit_glue::MemoryUsageKB());
111 DISALLOW_COPY_AND_ASSIGN(MemoryObserver);
116 // mainline routine for running as the Renderer process
117 int RendererMain(const MainFunctionParams& parameters) {
118 TRACE_EVENT_BEGIN_ETW("RendererMain", 0, "");
119 base::debug::TraceLog::GetInstance()->SetProcessName("Renderer");
120 base::debug::TraceLog::GetInstance()->SetProcessSortIndex(
121 kTraceEventRendererProcessSortIndex);
123 const CommandLine& parsed_command_line = parameters.command_line;
125 #if defined(OS_MACOSX)
126 base::mac::ScopedNSAutoreleasePool* pool = parameters.autorelease_pool;
129 #if defined(OS_CHROMEOS)
130 // As Zygote process starts up earlier than browser process gets its own
131 // locale (at login time for Chrome OS), we have to set the ICU default
132 // locale for renderer process here.
133 // ICU locale will be used for fallback font selection etc.
134 if (parsed_command_line.HasSwitch(switches::kLang)) {
135 const std::string locale =
136 parsed_command_line.GetSwitchValueASCII(switches::kLang);
137 base::i18n::SetICUDefaultLocale(locale);
141 #if defined(OS_ANDROID)
142 const int kMB = 1024 * 1024;
143 size_t font_cache_limit =
144 base::android::SysUtils::IsLowEndDevice() ? kMB : 8 * kMB;
145 SkGraphics::SetFontCacheLimit(font_cache_limit);
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(parsed_command_line);
154 RendererMainPlatformDelegate platform(parameters);
157 base::StatsCounterTimer stats_counter_timer("Content.RendererInit");
158 base::StatsScope<base::StatsCounterTimer> startup_timer(stats_counter_timer);
160 RendererMessageLoopObserver task_observer;
161 #if defined(OS_MACOSX)
162 // As long as we use Cocoa in the renderer (for the forseeable future as of
163 // now; see http://crbug.com/13890 for info) we need to have a UI loop.
164 base::MessageLoop main_message_loop(base::MessageLoop::TYPE_UI);
166 // The main message loop of the renderer services doesn't have IO or UI tasks,
167 // unless in-process-plugins is used.
168 base::MessageLoop main_message_loop(RenderProcessImpl::InProcessPlugins()
169 ? base::MessageLoop::TYPE_UI
170 : base::MessageLoop::TYPE_DEFAULT);
172 main_message_loop.AddTaskObserver(&task_observer);
174 scoped_ptr<MemoryObserver> memory_observer;
175 if (parsed_command_line.HasSwitch(switches::kMemoryMetrics)) {
176 memory_observer.reset(new MemoryObserver());
177 main_message_loop.AddTaskObserver(memory_observer.get());
180 base::PlatformThread::SetName("CrRendererMain");
182 platform.PlatformInitialize();
184 bool no_sandbox = parsed_command_line.HasSwitch(switches::kNoSandbox);
185 platform.InitSandboxTests(no_sandbox);
187 // Initialize histogram statistics gathering system.
188 base::StatisticsRecorder::Initialize();
190 // Initialize statistical testing infrastructure. We set the entropy provider
191 // to NULL to disallow the renderer process from creating its own one-time
192 // randomized trials; they should be created in the browser process.
193 base::FieldTrialList field_trial_list(NULL);
194 // Ensure any field trials in browser are reflected into renderer.
195 if (parsed_command_line.HasSwitch(switches::kForceFieldTrials)) {
196 // Field trials are created in an "activated" state to ensure they get
197 // reported in crash reports.
198 bool result = base::FieldTrialList::CreateTrialsFromString(
199 parsed_command_line.GetSwitchValueASCII(switches::kForceFieldTrials),
200 base::FieldTrialList::ACTIVATE_TRIALS);
204 #if defined(ENABLE_PLUGINS)
205 // Load pepper plugins before engaging the sandbox.
206 PepperPluginRegistry::GetInstance();
208 #if defined(ENABLE_WEBRTC)
209 // Initialize WebRTC before engaging the sandbox.
210 // NOTE: On linux, this call could already have been made from
211 // zygote_main_linux.cc. However, calling multiple times from the same thread
213 InitializeWebRtcModule();
217 #if defined(OS_WIN) || defined(OS_MACOSX)
218 // TODO(markus): Check if it is OK to unconditionally move this
220 RenderProcessImpl render_process;
221 new RenderThreadImpl();
223 bool run_loop = true;
225 run_loop = platform.EnableSandbox();
227 LOG(ERROR) << "Running without renderer sandbox";
229 // For convenience, we print the stack trace for crashes. We can't get
230 // symbols when the sandbox is enabled, so only try when the sandbox is
232 base::debug::EnableInProcessStackDumping();
235 #if defined(OS_POSIX) && !defined(OS_MACOSX)
236 RenderProcessImpl render_process;
237 new RenderThreadImpl();
240 base::HighResolutionTimerManager hi_res_timer_manager;
242 platform.RunSandboxTests(no_sandbox);
244 startup_timer.Stop(); // End of Startup Time Measurement.
247 #if defined(OS_MACOSX)
251 TRACE_EVENT_BEGIN_ETW("RendererMain.START_MSG_LOOP", 0, 0);
252 base::MessageLoop::current()->Run();
253 TRACE_EVENT_END_ETW("RendererMain.START_MSG_LOOP", 0, 0);
256 platform.PlatformUninitialize();
257 TRACE_EVENT_END_ETW("RendererMain", 0, "");
261 } // namespace content