- add sources.
[platform/framework/web/crosswalk.git] / src / chrome / browser / chrome_browser_main.cc
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 "chrome/browser/chrome_browser_main.h"
6
7 #if defined(TOOLKIT_GTK)
8 #include <gtk/gtk.h>
9 #endif
10
11 #include <string>
12 #include <vector>
13
14 #include "base/at_exit.h"
15 #include "base/bind.h"
16 #include "base/command_line.h"
17 #include "base/debug/crash_logging.h"
18 #include "base/debug/debugger.h"
19 #include "base/debug/trace_event.h"
20 #include "base/file_util.h"
21 #include "base/files/file_path.h"
22 #include "base/metrics/field_trial.h"
23 #include "base/metrics/histogram.h"
24 #include "base/path_service.h"
25 #include "base/prefs/json_pref_store.h"
26 #include "base/prefs/pref_registry_simple.h"
27 #include "base/prefs/pref_service.h"
28 #include "base/prefs/pref_value_store.h"
29 #include "base/prefs/scoped_user_pref_update.h"
30 #include "base/process/process_info.h"
31 #include "base/run_loop.h"
32 #include "base/strings/string_number_conversions.h"
33 #include "base/strings/string_piece.h"
34 #include "base/strings/string_split.h"
35 #include "base/strings/sys_string_conversions.h"
36 #include "base/strings/utf_string_conversions.h"
37 #include "base/sys_info.h"
38 #include "base/threading/platform_thread.h"
39 #include "base/time/time.h"
40 #include "base/values.h"
41 #include "build/build_config.h"
42 #include "chrome/browser/about_flags.h"
43 #include "chrome/browser/browser_process.h"
44 #include "chrome/browser/browser_process_impl.h"
45 #include "chrome/browser/browser_process_platform_part.h"
46 #include "chrome/browser/browser_shutdown.h"
47 #include "chrome/browser/chrome_browser_main_extra_parts.h"
48 #include "chrome/browser/component_updater/component_updater_service.h"
49 #include "chrome/browser/component_updater/flash_component_installer.h"
50 #include "chrome/browser/component_updater/pnacl/pnacl_component_installer.h"
51 #include "chrome/browser/component_updater/recovery_component_installer.h"
52 #include "chrome/browser/component_updater/swiftshader_component_installer.h"
53 #include "chrome/browser/component_updater/widevine_cdm_component_installer.h"
54 #include "chrome/browser/defaults.h"
55 #include "chrome/browser/extensions/extension_protocols.h"
56 #include "chrome/browser/extensions/extension_service.h"
57 #include "chrome/browser/extensions/extension_system.h"
58 #include "chrome/browser/extensions/startup_helper.h"
59 #include "chrome/browser/first_run/first_run.h"
60 #include "chrome/browser/first_run/upgrade_util.h"
61 #include "chrome/browser/google/google_search_counter.h"
62 #include "chrome/browser/google/google_util.h"
63 #include "chrome/browser/gpu/gl_string_manager.h"
64 #include "chrome/browser/jankometer.h"
65 #include "chrome/browser/language_usage_metrics.h"
66 #include "chrome/browser/media/media_capture_devices_dispatcher.h"
67 #include "chrome/browser/metrics/field_trial_synchronizer.h"
68 #include "chrome/browser/metrics/metrics_log.h"
69 #include "chrome/browser/metrics/metrics_service.h"
70 #include "chrome/browser/metrics/thread_watcher.h"
71 #include "chrome/browser/metrics/tracking_synchronizer.h"
72 #include "chrome/browser/metrics/variations/variations_http_header_provider.h"
73 #include "chrome/browser/metrics/variations/variations_service.h"
74 #include "chrome/browser/nacl_host/nacl_browser_delegate_impl.h"
75 #include "chrome/browser/nacl_host/nacl_process_host.h"
76 #include "chrome/browser/net/chrome_net_log.h"
77 #include "chrome/browser/net/crl_set_fetcher.h"
78 #include "chrome/browser/notifications/desktop_notification_service.h"
79 #include "chrome/browser/notifications/desktop_notification_service_factory.h"
80 #include "chrome/browser/performance_monitor/performance_monitor.h"
81 #include "chrome/browser/performance_monitor/startup_timer.h"
82 #include "chrome/browser/plugins/plugin_prefs.h"
83 #include "chrome/browser/pref_service_flags_storage.h"
84 #include "chrome/browser/prefs/chrome_pref_service_factory.h"
85 #include "chrome/browser/prefs/command_line_pref_store.h"
86 #include "chrome/browser/prefs/pref_metrics_service.h"
87 #include "chrome/browser/printing/cloud_print/cloud_print_proxy_service.h"
88 #include "chrome/browser/printing/cloud_print/cloud_print_proxy_service_factory.h"
89 #include "chrome/browser/process_singleton.h"
90 #include "chrome/browser/profiles/profile.h"
91 #include "chrome/browser/profiles/profile_manager.h"
92 #include "chrome/browser/profiles/profiles_state.h"
93 #include "chrome/browser/service/service_process_control.h"
94 #include "chrome/browser/shell_integration.h"
95 #include "chrome/browser/three_d_api_observer.h"
96 #include "chrome/browser/translate/translate_manager.h"
97 #include "chrome/browser/ui/app_list/app_list_service.h"
98 #include "chrome/browser/ui/browser.h"
99 #include "chrome/browser/ui/browser_finder.h"
100 #include "chrome/browser/ui/host_desktop.h"
101 #include "chrome/browser/ui/startup/default_browser_prompt.h"
102 #include "chrome/browser/ui/startup/startup_browser_creator.h"
103 #include "chrome/browser/ui/uma_browsing_activity_observer.h"
104 #include "chrome/browser/ui/user_data_dir_dialog.h"
105 #include "chrome/browser/ui/webui/chrome_web_ui_controller_factory.h"
106 #include "chrome/browser/user_data_dir_extractor.h"
107 #include "chrome/common/chrome_constants.h"
108 #include "chrome/common/chrome_paths.h"
109 #include "chrome/common/chrome_result_codes.h"
110 #include "chrome/common/chrome_switches.h"
111 #include "chrome/common/crash_keys.h"
112 #include "chrome/common/env_vars.h"
113 #include "chrome/common/logging_chrome.h"
114 #include "chrome/common/net/net_resource_provider.h"
115 #include "chrome/common/pref_names.h"
116 #include "chrome/common/profiling.h"
117 #include "chrome/installer/util/google_update_settings.h"
118 #include "components/nacl/browser/nacl_browser.h"
119 #include "components/startup_metric_utils/startup_metric_utils.h"
120 #include "content/public/browser/browser_thread.h"
121 #include "content/public/browser/notification_observer.h"
122 #include "content/public/browser/notification_registrar.h"
123 #include "content/public/browser/notification_service.h"
124 #include "content/public/browser/notification_types.h"
125 #include "content/public/browser/site_instance.h"
126 #include "content/public/common/content_client.h"
127 #include "content/public/common/content_switches.h"
128 #include "content/public/common/main_function_params.h"
129 #include "grit/app_locale_settings.h"
130 #include "grit/browser_resources.h"
131 #include "grit/chromium_strings.h"
132 #include "grit/generated_resources.h"
133 #include "grit/platform_locale_settings.h"
134 #include "net/base/net_module.h"
135 #include "net/base/sdch_manager.h"
136 #include "net/cookies/cookie_monster.h"
137 #include "net/http/http_network_layer.h"
138 #include "net/http/http_stream_factory.h"
139 #include "net/url_request/url_request.h"
140 #include "ui/base/l10n/l10n_util.h"
141 #include "ui/base/layout.h"
142 #include "ui/base/resource/resource_bundle.h"
143
144 #if !defined(OS_ANDROID)
145 #include "chrome/browser/ui/active_tab_tracker.h"
146 #endif
147
148 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
149 #include "chrome/browser/first_run/upgrade_util_linux.h"
150 #include "chrome/browser/sxs_linux.h"
151 #endif
152
153 #if defined(OS_CHROMEOS)
154 #include "chrome/browser/chromeos/settings/cros_settings.h"
155 #include "chromeos/chromeos_switches.h"
156 #include "chromeos/settings/cros_settings_names.h"
157 #endif
158
159 // TODO(port): several win-only methods have been pulled out of this, but
160 // BrowserMain() as a whole needs to be broken apart so that it's usable by
161 // other platforms. For now, it's just a stub. This is a serious work in
162 // progress and should not be taken as an indication of a real refactoring.
163
164 #if defined(OS_WIN)
165 #include "base/environment.h"  // For PreRead experiment.
166 #include "base/win/windows_version.h"
167 #include "chrome/browser/browser_util_win.h"
168 #include "chrome/browser/chrome_browser_main_win.h"
169 #include "chrome/browser/first_run/try_chrome_dialog_view.h"
170 #include "chrome/browser/first_run/upgrade_util_win.h"
171 #include "chrome/browser/ui/network_profile_bubble.h"
172 #include "chrome/common/net/url_fixer_upper.h"
173 #include "chrome/installer/util/helper.h"
174 #include "chrome/installer/util/install_util.h"
175 #include "chrome/installer/util/shell_util.h"
176 #include "net/base/net_util.h"
177 #include "printing/printed_document.h"
178 #include "ui/base/l10n/l10n_util_win.h"
179 #include "ui/gfx/win/dpi.h"
180 #endif  // defined(OS_WIN)
181
182 #if defined(OS_MACOSX)
183 #include <Security/Security.h>
184
185 #include "base/mac/scoped_nsautorelease_pool.h"
186 #include "chrome/browser/mac/keystone_glue.h"
187 #endif
188
189 #if defined(ENABLE_RLZ)
190 #include "chrome/browser/rlz/rlz.h"
191 #endif
192
193 #if defined(TOOLKIT_VIEWS)
194 #include "ui/views/focus/accelerator_handler.h"
195 #endif
196
197 #if defined(USE_AURA)
198 #include "ui/aura/env.h"
199 #endif
200
201 using content::BrowserThread;
202
203 namespace {
204
205 // This function provides some ways to test crash and assertion handling
206 // behavior of the program.
207 void HandleTestParameters(const CommandLine& command_line) {
208   // This parameter causes an assertion.
209   if (command_line.HasSwitch(switches::kBrowserAssertTest)) {
210     DCHECK(false);
211   }
212
213   // This parameter causes a null pointer crash (crash reporter trigger).
214   if (command_line.HasSwitch(switches::kBrowserCrashTest)) {
215     int* bad_pointer = NULL;
216     *bad_pointer = 0;
217   }
218 }
219
220 void AddFirstRunNewTabs(StartupBrowserCreator* browser_creator,
221                         const std::vector<GURL>& new_tabs) {
222   for (std::vector<GURL>::const_iterator it = new_tabs.begin();
223        it != new_tabs.end(); ++it) {
224     if (it->is_valid())
225       browser_creator->AddFirstRunTab(*it);
226   }
227 }
228
229 // Returns the new local state object, guaranteed non-NULL.
230 // |local_state_task_runner| must be a shutdown-blocking task runner.
231 PrefService* InitializeLocalState(
232     base::SequencedTaskRunner* local_state_task_runner,
233     const CommandLine& parsed_command_line) {
234   TRACE_EVENT0("startup", "ChromeBrowserMainParts::InitializeLocalState")
235   base::FilePath local_state_path;
236   PathService::Get(chrome::FILE_LOCAL_STATE, &local_state_path);
237   bool local_state_file_exists = base::PathExists(local_state_path);
238
239   // Load local state.  This includes the application locale so we know which
240   // locale dll to load.  This also causes local state prefs to be registered.
241   PrefService* local_state = g_browser_process->local_state();
242   DCHECK(local_state);
243
244 #if defined(OS_WIN)
245   if (first_run::IsChromeFirstRun()) {
246     // During first run we read the google_update registry key to find what
247     // language the user selected when downloading the installer. This
248     // becomes our default language in the prefs.
249     // Other platforms obey the system locale.
250     std::wstring install_lang;
251     if (GoogleUpdateSettings::GetLanguage(&install_lang)) {
252       local_state->SetString(prefs::kApplicationLocale,
253                              WideToASCII(install_lang));
254     }
255   }
256 #endif  // defined(OS_WIN)
257
258   // If the local state file for the current profile doesn't exist and the
259   // parent profile command line flag is present, then we should inherit some
260   // local state from the parent profile.
261   // Checking that the local state file for the current profile doesn't exist
262   // is the most robust way to determine whether we need to inherit or not
263   // since the parent profile command line flag can be present even when the
264   // current profile is not a new one, and in that case we do not want to
265   // inherit and reset the user's setting.
266   //
267   // TODO(mnissler): We should probably just instantiate a
268   // JSONPrefStore here instead of an entire PrefService. Once this is
269   // addressed, the call to browser_prefs::RegisterLocalState can move
270   // to chrome_prefs::CreateLocalState.
271   if (!local_state_file_exists &&
272       parsed_command_line.HasSwitch(switches::kParentProfile)) {
273     base::FilePath parent_profile =
274         parsed_command_line.GetSwitchValuePath(switches::kParentProfile);
275     scoped_refptr<PrefRegistrySimple> registry = new PrefRegistrySimple();
276     scoped_ptr<PrefService> parent_local_state(
277         chrome_prefs::CreateLocalState(
278             parent_profile,
279             local_state_task_runner,
280             g_browser_process->policy_service(),
281             registry,
282             false));
283     registry->RegisterStringPref(prefs::kApplicationLocale, std::string());
284     // Right now, we only inherit the locale setting from the parent profile.
285     local_state->SetString(
286         prefs::kApplicationLocale,
287         parent_local_state->GetString(prefs::kApplicationLocale));
288   }
289
290 #if defined(OS_CHROMEOS)
291   if (parsed_command_line.HasSwitch(chromeos::switches::kLoginManager)) {
292     std::string owner_locale = local_state->GetString(prefs::kOwnerLocale);
293     // Ensure that we start with owner's locale.
294     if (!owner_locale.empty() &&
295         local_state->GetString(prefs::kApplicationLocale) != owner_locale &&
296         !local_state->IsManagedPreference(prefs::kApplicationLocale)) {
297       local_state->SetString(prefs::kApplicationLocale, owner_locale);
298     }
299   }
300 #endif
301
302   return local_state;
303 }
304
305 // Returns the path that contains the profile that should be loaded
306 // on process startup.
307 base::FilePath GetStartupProfilePath(const base::FilePath& user_data_dir,
308                                      const CommandLine& command_line) {
309   if (command_line.HasSwitch(switches::kProfileDirectory)) {
310     return user_data_dir.Append(
311         command_line.GetSwitchValuePath(switches::kProfileDirectory));
312   }
313
314   // If we are showing the app list then chrome isn't shown so load the app
315   // list's profile rather than chrome's.
316   if (command_line.HasSwitch(switches::kShowAppList)) {
317     return AppListService::Get(chrome::HOST_DESKTOP_TYPE_NATIVE)->
318         GetProfilePath(user_data_dir);
319   }
320
321   return g_browser_process->profile_manager()->GetLastUsedProfileDir(
322       user_data_dir);
323 }
324
325 // Initializes the profile, possibly doing some user prompting to pick a
326 // fallback profile. Returns the newly created profile, or NULL if startup
327 // should not continue.
328 Profile* CreateProfile(const content::MainFunctionParams& parameters,
329                        const base::FilePath& user_data_dir,
330                        const CommandLine& parsed_command_line) {
331   TRACE_EVENT0("startup", "ChromeBrowserMainParts::CreateProfile")
332   if (profiles::IsMultipleProfilesEnabled() &&
333       parsed_command_line.HasSwitch(switches::kProfileDirectory)) {
334     g_browser_process->local_state()->SetString(prefs::kProfileLastUsed,
335         parsed_command_line.GetSwitchValueASCII(switches::kProfileDirectory));
336     // Clear kProfilesLastActive since the user only wants to launch a specific
337     // profile.
338     ListPrefUpdate update(g_browser_process->local_state(),
339                           prefs::kProfilesLastActive);
340     ListValue* profile_list = update.Get();
341     profile_list->Clear();
342   }
343
344   Profile* profile = NULL;
345 #if defined(OS_CHROMEOS)
346   // TODO(ivankr): http://crbug.com/83792
347   profile = g_browser_process->profile_manager()->GetDefaultProfile(
348       user_data_dir);
349 #else
350   base::FilePath profile_path =
351       GetStartupProfilePath(user_data_dir, parsed_command_line);
352   profile = g_browser_process->profile_manager()->GetProfile(
353       profile_path);
354 #endif
355   if (profile)
356     return profile;
357
358 #if !defined(OS_WIN)
359   // TODO(port): fix this.  See comments near the definition of
360   // user_data_dir.  It is better to CHECK-fail here than it is to
361   // silently exit because of missing code in the above test.
362   CHECK(profile) << "Cannot get default profile.";
363 #endif
364
365   return NULL;
366 }
367
368 #if defined(OS_MACOSX)
369 OSStatus KeychainCallback(SecKeychainEvent keychain_event,
370                           SecKeychainCallbackInfo* info, void* context) {
371   return noErr;
372 }
373 #endif
374
375 void RegisterComponentsForUpdate(const CommandLine& command_line) {
376   ComponentUpdateService* cus = g_browser_process->component_updater();
377
378   // Registration can be before or after cus->Start() so it is ok to post
379   // a task to the UI thread to do registration once you done the necessary
380   // file IO to know you existing component version.
381 #if !defined(OS_CHROMEOS)
382   RegisterRecoveryComponent(cus, g_browser_process->local_state());
383   RegisterPepperFlashComponent(cus);
384   RegisterSwiftShaderComponent(cus);
385 #endif
386
387   g_browser_process->pnacl_component_installer()->RegisterPnaclComponent(
388       cus, command_line);
389
390 #if !defined(OS_CHROMEOS)
391   RegisterWidevineCdmComponent(cus);
392
393   // CRLSetFetcher attempts to load a CRL set from either the local disk or
394   // network.
395   if (!command_line.HasSwitch(switches::kDisableCRLSets))
396     g_browser_process->crl_set_fetcher()->StartInitialLoad(cus);
397 #endif
398
399   cus->Start();
400 }
401
402 bool ProcessSingletonNotificationCallback(
403     const CommandLine& command_line,
404     const base::FilePath& current_directory) {
405   // Drop the request if the browser process is already in shutdown path.
406   if (!g_browser_process || g_browser_process->IsShuttingDown())
407     return false;
408
409   if (command_line.HasSwitch(switches::kOriginalProcessStartTime)) {
410     std::string start_time_string =
411         command_line.GetSwitchValueASCII(switches::kOriginalProcessStartTime);
412     int64 remote_start_time;
413     if (base::StringToInt64(start_time_string, &remote_start_time)) {
414       base::TimeDelta elapsed =
415           base::Time::Now() - base::Time::FromInternalValue(remote_start_time);
416       if (command_line.HasSwitch(switches::kFastStart)) {
417         UMA_HISTOGRAM_LONG_TIMES(
418             "Startup.WarmStartTimeFromRemoteProcessStartFast", elapsed);
419       } else {
420         UMA_HISTOGRAM_LONG_TIMES(
421             "Startup.WarmStartTimeFromRemoteProcessStart", elapsed);
422       }
423     }
424   }
425
426   g_browser_process->platform_part()->PlatformSpecificCommandLineProcessing(
427       command_line);
428
429   // TODO(erikwright): Consider removing this - AFAIK it is no longer used.
430   // Handle the --uninstall-extension startup action. This needs to done here in
431   // the process that is running with the target profile, otherwise the
432   // uninstall will fail to unload and remove all components.
433   if (command_line.HasSwitch(switches::kUninstallExtension)) {
434     // The uninstall extension switch can't be combined with the profile
435     // directory switch.
436     DCHECK(!command_line.HasSwitch(switches::kProfileDirectory));
437
438     Profile* profile = ProfileManager::GetLastUsedProfile();
439     if (!profile) {
440       // We should never be called before the profile has been created.
441       NOTREACHED();
442       return true;
443     }
444
445     extensions::StartupHelper extension_startup_helper;
446     extension_startup_helper.UninstallExtension(command_line, profile);
447     return true;
448   }
449
450   base::FilePath user_data_dir =
451       g_browser_process->profile_manager()->user_data_dir();
452   base::FilePath startup_profile_dir =
453       GetStartupProfilePath(user_data_dir, command_line);
454
455   StartupBrowserCreator::ProcessCommandLineAlreadyRunning(
456       command_line, current_directory, startup_profile_dir);
457   return true;
458 }
459
460 void LaunchDevToolsHandlerIfNeeded(const CommandLine& command_line) {
461   if (command_line.HasSwitch(::switches::kRemoteDebuggingPort)) {
462     std::string port_str =
463         command_line.GetSwitchValueASCII(::switches::kRemoteDebuggingPort);
464     int port;
465     if (base::StringToInt(port_str, &port) && port > 0 && port < 65535) {
466       std::string frontend_str;
467       if (command_line.HasSwitch(::switches::kRemoteDebuggingFrontend)) {
468         frontend_str = command_line.GetSwitchValueASCII(
469             ::switches::kRemoteDebuggingFrontend);
470       }
471       g_browser_process->CreateDevToolsHttpProtocolHandler(
472           chrome::HOST_DESKTOP_TYPE_NATIVE,
473           "127.0.0.1",
474           port,
475           frontend_str);
476     } else {
477       DLOG(WARNING) << "Invalid http debugger port number " << port;
478     }
479   }
480 }
481
482 // Heap allocated class that listens for first page load, kicks off stat
483 // recording and then deletes itself.
484 class LoadCompleteListener : public content::NotificationObserver {
485  public:
486   LoadCompleteListener() {
487     registrar_.Add(this,
488                    content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
489                    content::NotificationService::AllSources());
490   }
491   virtual ~LoadCompleteListener() {}
492
493   // content::NotificationObserver implementation.
494   virtual void Observe(int type,
495                        const content::NotificationSource& source,
496                        const content::NotificationDetails& details) OVERRIDE {
497     DCHECK_EQ(content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME, type);
498     startup_metric_utils::OnInitialPageLoadComplete();
499     delete this;
500   }
501
502  private:
503   content::NotificationRegistrar registrar_;
504   DISALLOW_COPY_AND_ASSIGN(LoadCompleteListener);
505 };
506
507 }  // namespace
508
509 namespace chrome_browser {
510 // This error message is not localized because we failed to load the
511 // localization data files.
512 const char kMissingLocaleDataTitle[] = "Missing File Error";
513 const char kMissingLocaleDataMessage[] =
514     "Unable to find locale data files. Please reinstall.";
515 }  // namespace chrome_browser
516
517 // BrowserMainParts ------------------------------------------------------------
518
519 // static
520 bool ChromeBrowserMainParts::disable_enforcing_cookie_policies_for_tests_ =
521     false;
522
523 ChromeBrowserMainParts::ChromeBrowserMainParts(
524     const content::MainFunctionParams& parameters)
525     : parameters_(parameters),
526       parsed_command_line_(parameters.command_line),
527       result_code_(content::RESULT_CODE_NORMAL_EXIT),
528       startup_watcher_(new StartupTimeBomb()),
529       shutdown_watcher_(new ShutdownWatcherHelper()),
530       startup_timer_(new performance_monitor::StartupTimer()),
531       browser_field_trials_(parameters.command_line),
532       translate_manager_(NULL),
533       profile_(NULL),
534       run_message_loop_(true),
535       notify_result_(ProcessSingleton::PROCESS_NONE),
536       local_state_(NULL),
537       restart_last_session_(false) {
538   // If we're running tests (ui_task is non-null).
539   if (parameters.ui_task)
540     browser_defaults::enable_help_app = false;
541
542   // Chrome disallows cookies by default. All code paths that want to use
543   // cookies need to go through one of Chrome's URLRequestContexts which have
544   // a ChromeNetworkDelegate attached that selectively allows cookies again.
545   if (!disable_enforcing_cookie_policies_for_tests_)
546     net::URLRequest::SetDefaultCookiePolicyToBlock();
547 }
548
549 ChromeBrowserMainParts::~ChromeBrowserMainParts() {
550   for (int i = static_cast<int>(chrome_extra_parts_.size())-1; i >= 0; --i)
551     delete chrome_extra_parts_[i];
552   chrome_extra_parts_.clear();
553 }
554
555 // This will be called after the command-line has been mutated by about:flags
556 void ChromeBrowserMainParts::SetupMetricsAndFieldTrials() {
557   TRACE_EVENT0("startup", "ChromeBrowserMainParts::SetupMetricsAndFieldTrials");
558   // Must initialize metrics after labs have been converted into switches,
559   // but before field trials are set up (so that client ID is available for
560   // one-time randomized field trials).
561 #if defined(OS_WIN)
562   if (parsed_command_line_.HasSwitch(switches::kChromeFrame))
563     MetricsLog::set_version_extension("-F");
564 #elif defined(ARCH_CPU_64_BITS)
565   MetricsLog::set_version_extension("-64");
566 #endif  // defined(OS_WIN)
567
568   // Initialize FieldTrialList to support FieldTrials that use one-time
569   // randomization.
570   MetricsService* metrics = browser_process_->metrics_service();
571   bool metrics_reporting_enabled = IsMetricsReportingEnabled();
572   if (metrics_reporting_enabled)
573     metrics->ForceClientIdCreation();  // Needed below.
574   field_trial_list_.reset(
575       new base::FieldTrialList(
576           metrics->CreateEntropyProvider(metrics_reporting_enabled).release()));
577
578   const CommandLine* command_line = CommandLine::ForCurrentProcess();
579   if (command_line->HasSwitch(switches::kEnableBenchmarking))
580     base::FieldTrial::EnableBenchmarking();
581
582   // Ensure any field trials specified on the command line are initialized.
583   // Also stop the metrics service so that we don't pollute UMA.
584   if (command_line->HasSwitch(switches::kForceFieldTrials)) {
585     // Create field trials without activating them, so that this behaves in a
586     // consistent manner with field trials created from the server.
587     bool result = base::FieldTrialList::CreateTrialsFromString(
588         command_line->GetSwitchValueASCII(switches::kForceFieldTrials),
589         base::FieldTrialList::DONT_ACTIVATE_TRIALS);
590     CHECK(result) << "Invalid --" << switches::kForceFieldTrials
591                   << " list specified.";
592   }
593   if (command_line->HasSwitch(switches::kForceVariationIds)) {
594     // Create default variation ids which will always be included in the
595     // X-Chrome-Variations request header.
596     chrome_variations::VariationsHttpHeaderProvider* provider =
597         chrome_variations::VariationsHttpHeaderProvider::GetInstance();
598     bool result = provider->SetDefaultVariationIds(
599         command_line->GetSwitchValueASCII(switches::kForceVariationIds));
600     CHECK(result) << "Invalid --" << switches::kForceVariationIds
601                   << " list specified.";
602   }
603   chrome_variations::VariationsService* variations_service =
604       browser_process_->variations_service();
605   if (variations_service)
606     variations_service->CreateTrialsFromSeed();
607
608   // This must be called after the local state is initialized.
609   browser_field_trials_.SetupFieldTrials(local_state_);
610
611   SetupPlatformFieldTrials();
612
613   // Initialize FieldTrialSynchronizer system. This is a singleton and is used
614   // for posting tasks via base::Bind. Its deleted when it goes out of scope.
615   // Even though base::Bind does AddRef and Release, the object will not be
616   // deleted after the Task is executed.
617   field_trial_synchronizer_ = new FieldTrialSynchronizer();
618 }
619
620 // ChromeBrowserMainParts: |SetupMetricsAndFieldTrials()| related --------------
621
622 void ChromeBrowserMainParts::StartMetricsRecording() {
623   TRACE_EVENT0("startup", "ChromeBrowserMainParts::StartMetricsRecording");
624   MetricsService* metrics = g_browser_process->metrics_service();
625
626   // TODO(miu): Metrics reporting is disabled in DEBUG builds until ill-fired
627   // DCHECKs are fixed, and/or we reconsider whether metrics reporting should
628   // really ever be enabled for debug builds.  http://crbug.com/156979
629 #if defined(NDEBUG)
630   const bool only_do_metrics_recording =
631       parsed_command_line_.HasSwitch(switches::kMetricsRecordingOnly) ||
632       parsed_command_line_.HasSwitch(switches::kEnableBenchmarking);
633 #else
634   const bool only_do_metrics_recording = true;
635 #endif
636   if (only_do_metrics_recording) {
637     // If we're testing then we don't care what the user preference is, we turn
638     // on recording, but not reporting, otherwise tests fail.
639     metrics->StartRecordingForTests();
640     return;
641   }
642
643   if (IsMetricsReportingEnabled())
644     metrics->Start();
645 }
646
647 bool ChromeBrowserMainParts::IsMetricsReportingEnabled() {
648   // If the user permits metrics reporting with the checkbox in the
649   // prefs, we turn on recording.  We disable metrics completely for
650   // non-official builds.  This can be forced with a flag.
651   const CommandLine* command_line = CommandLine::ForCurrentProcess();
652   if (command_line->HasSwitch(switches::kEnableMetricsReportingForTesting))
653     return true;
654
655   bool enabled = false;
656   // The debug build doesn't send UMA logs when FieldTrials are forced.
657   if (command_line->HasSwitch(switches::kForceFieldTrials))
658     return false;
659
660 #if defined(GOOGLE_CHROME_BUILD)
661 #if defined(OS_CHROMEOS)
662   chromeos::CrosSettings::Get()->GetBoolean(chromeos::kStatsReportingPref,
663                                             &enabled);
664 #else
665   enabled = local_state_->GetBoolean(prefs::kMetricsReportingEnabled);
666 #endif  // #if defined(OS_CHROMEOS)
667 #endif  // defined(GOOGLE_CHROME_BUILD)
668   return enabled;
669 }
670
671 void ChromeBrowserMainParts::RecordBrowserStartupTime() {
672   // Don't record any metrics if UI was displayed before this point e.g.
673   // warning dialogs.
674   if (startup_metric_utils::WasNonBrowserUIDisplayed())
675     return;
676
677 #if defined(OS_ANDROID)
678   // On Android the first run is handled in Java code, and the C++ side of
679   // Chrome doesn't know if this is the first run. This will cause some
680   // inaccuracy in the UMA statistics, but this should be minor (first runs are
681   // rare).
682   bool is_first_run = false;
683 #else
684   bool is_first_run = first_run::IsChromeFirstRun();
685 #endif
686
687 // CurrentProcessInfo::CreationTime() is currently only implemented on some
688 // platforms.
689 #if defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
690   const base::Time process_creation_time =
691       base::CurrentProcessInfo::CreationTime();
692
693   if (!is_first_run && !process_creation_time.is_null()) {
694     base::TimeDelta delay = base::Time::Now() - process_creation_time;
695     UMA_HISTOGRAM_LONG_TIMES_100("Startup.BrowserMessageLoopStartTime", delay);
696   }
697 #endif  // defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
698
699   // Record collected startup metrics.
700   startup_metric_utils::OnBrowserStartupComplete(is_first_run);
701
702   // Deletes self.
703   new LoadCompleteListener();
704 }
705
706 // -----------------------------------------------------------------------------
707 // TODO(viettrungluu): move more/rest of BrowserMain() into BrowserMainParts.
708
709 #if defined(OS_WIN)
710 #define DLLEXPORT __declspec(dllexport)
711
712 // We use extern C for the prototype DLLEXPORT to avoid C++ name mangling.
713 extern "C" {
714 DLLEXPORT void __cdecl RelaunchChromeBrowserWithNewCommandLineIfNeeded();
715 }
716
717 DLLEXPORT void __cdecl RelaunchChromeBrowserWithNewCommandLineIfNeeded() {
718   // Need an instance of AtExitManager to handle singleton creations and
719   // deletions.  We need this new instance because, the old instance created
720   // in ChromeMain() got destructed when the function returned.
721   base::AtExitManager exit_manager;
722   upgrade_util::RelaunchChromeBrowserWithNewCommandLineIfNeeded();
723 }
724 #endif
725
726 // content::BrowserMainParts implementation ------------------------------------
727
728 void ChromeBrowserMainParts::PreEarlyInitialization() {
729   TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreEarlyInitialization");
730   for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
731     chrome_extra_parts_[i]->PreEarlyInitialization();
732 }
733
734 void ChromeBrowserMainParts::PostEarlyInitialization() {
735   TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostEarlyInitialization");
736   for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
737     chrome_extra_parts_[i]->PostEarlyInitialization();
738 }
739
740 void ChromeBrowserMainParts::ToolkitInitialized() {
741   TRACE_EVENT0("startup", "ChromeBrowserMainParts::ToolkitInitialized");
742   for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
743     chrome_extra_parts_[i]->ToolkitInitialized();
744 }
745
746 void ChromeBrowserMainParts::PreMainMessageLoopStart() {
747   TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopStart");
748   for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
749     chrome_extra_parts_[i]->PreMainMessageLoopStart();
750 }
751
752 void ChromeBrowserMainParts::PostMainMessageLoopStart() {
753   TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopStart");
754   for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
755     chrome_extra_parts_[i]->PostMainMessageLoopStart();
756 }
757
758 int ChromeBrowserMainParts::PreCreateThreads() {
759   TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreads");
760   result_code_ = PreCreateThreadsImpl();
761   // These members must be initialized before returning from this function.
762 #if !defined(OS_ANDROID)
763   DCHECK(master_prefs_.get());
764   DCHECK(browser_creator_.get());
765 #endif
766
767   if (result_code_ == 0) {
768     for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
769       chrome_extra_parts_[i]->PreCreateThreads();
770   }
771
772   return result_code_;
773 }
774
775 int ChromeBrowserMainParts::PreCreateThreadsImpl() {
776   TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreadsImpl")
777   run_message_loop_ = false;
778   {
779     TRACE_EVENT0("startup",
780       "ChromeBrowserMainParts::PreCreateThreadsImpl:GetUserDataDir");
781     user_data_dir_ = chrome::GetUserDataDir(parameters());
782   }
783
784   // Force MediaCaptureDevicesDispatcher to be created on UI thread.
785   MediaCaptureDevicesDispatcher::GetInstance();
786
787   // Android's first run is done in Java instead of native.
788 #if !defined(OS_ANDROID)
789   process_singleton_.reset(new ChromeProcessSingleton(
790       user_data_dir_, base::Bind(&ProcessSingletonNotificationCallback)));
791
792   // Cache first run state early.
793   first_run::IsChromeFirstRun();
794 #endif
795
796   scoped_refptr<base::SequencedTaskRunner> local_state_task_runner =
797       JsonPrefStore::GetTaskRunnerForFile(
798           base::FilePath(chrome::kLocalStorePoolName),
799           BrowserThread::GetBlockingPool());
800
801   {
802     TRACE_EVENT0("startup",
803       "ChromeBrowserMainParts::PreCreateThreadsImpl:InitBrowswerProcessImpl");
804     browser_process_.reset(new BrowserProcessImpl(local_state_task_runner.get(),
805                                                   parsed_command_line()));
806   }
807
808   if (parsed_command_line().HasSwitch(switches::kEnableProfiling)) {
809     TRACE_EVENT0("startup",
810         "ChromeBrowserMainParts::PreCreateThreadsImpl:InitProfiling");
811     // User wants to override default tracking status.
812     std::string flag =
813       parsed_command_line().GetSwitchValueASCII(switches::kEnableProfiling);
814     // Default to basic profiling (no parent child support).
815     tracked_objects::ThreadData::Status status =
816           tracked_objects::ThreadData::PROFILING_ACTIVE;
817     if (flag.compare("0") != 0)
818       status = tracked_objects::ThreadData::DEACTIVATED;
819     else if (flag.compare("child") != 0)
820       status = tracked_objects::ThreadData::PROFILING_CHILDREN_ACTIVE;
821     tracked_objects::ThreadData::InitializeAndSetTrackingStatus(status);
822   }
823
824   if (parsed_command_line().HasSwitch(switches::kProfilingOutputFile)) {
825     tracking_objects_.set_output_file_path(
826         parsed_command_line().GetSwitchValuePath(
827             switches::kProfilingOutputFile));
828   }
829
830   local_state_ = InitializeLocalState(
831       local_state_task_runner.get(), parsed_command_line());
832
833 #if !defined(OS_ANDROID)
834   // These members must be initialized before returning from this function.
835   master_prefs_.reset(new first_run::MasterPrefs);
836   // Android doesn't use StartupBrowserCreator.
837   browser_creator_.reset(new StartupBrowserCreator);
838   // TODO(yfriedman): Refactor Android to re-use UMABrowsingActivityObserver
839   chrome::UMABrowsingActivityObserver::Init();
840 #endif
841
842 #if !defined(OS_CHROMEOS)
843   // Convert active labs into switches. This needs to be done before
844   // ResourceBundle::InitSharedInstanceWithLocale as some loaded resources are
845   // affected by experiment flags (--touch-optimized-ui in particular). Not
846   // needed on Android as there aren't experimental flags.
847   // On ChromeOS system level flags are applied from the device settings from
848   // the session manager.
849   {
850     TRACE_EVENT0("startup",
851         "ChromeBrowserMainParts::PreCreateThreadsImpl:ConvertFlags");
852     about_flags::PrefServiceFlagsStorage flags_storage_(
853         g_browser_process->local_state());
854     about_flags::ConvertFlagsToSwitches(&flags_storage_,
855                                         CommandLine::ForCurrentProcess(),
856                                         about_flags::kAddSentinels);
857   }
858 #endif
859
860   local_state_->UpdateCommandLinePrefStore(
861       new CommandLinePrefStore(CommandLine::ForCurrentProcess()));
862
863   // Reset the command line in the crash report details, since we may have
864   // just changed it to include experiments.
865   crash_keys::SetSwitchesFromCommandLine(CommandLine::ForCurrentProcess());
866
867   // If we're running tests (ui_task is non-null), then the ResourceBundle
868   // has already been initialized.
869   if (parameters().ui_task &&
870       !local_state_->IsManagedPreference(prefs::kApplicationLocale)) {
871     browser_process_->SetApplicationLocale("en-US");
872   } else {
873     // Mac starts it earlier in |PreMainMessageLoopStart()| (because it is
874     // needed when loading the MainMenu.nib and the language doesn't depend on
875     // anything since it comes from Cocoa.
876 #if defined(OS_MACOSX)
877     browser_process_->SetApplicationLocale(l10n_util::GetLocaleOverride());
878 #else
879     const std::string locale =
880         local_state_->GetString(prefs::kApplicationLocale);
881
882 #if defined(OS_WIN)
883     gfx::EnableHighDPISupport();
884 #endif
885
886     // On a POSIX OS other than ChromeOS, the parameter that is passed to the
887     // method InitSharedInstance is ignored.
888
889     TRACE_EVENT_BEGIN0("startup",
890         "ChromeBrowserMainParts::PreCreateThreadsImpl:InitResourceBundle");
891     const std::string loaded_locale =
892         ResourceBundle::InitSharedInstanceWithLocale(locale, NULL);
893     TRACE_EVENT_END0("startup",
894         "ChromeBrowserMainParts::PreCreateThreadsImpl:InitResourceBundle");
895
896     if (loaded_locale.empty() &&
897         !parsed_command_line().HasSwitch(switches::kNoErrorDialogs)) {
898       ShowMissingLocaleMessageBox();
899       return chrome::RESULT_CODE_MISSING_DATA;
900     }
901     CHECK(!loaded_locale.empty()) << "Locale could not be found for " << locale;
902     browser_process_->SetApplicationLocale(loaded_locale);
903
904     base::FilePath resources_pack_path;
905     PathService::Get(chrome::FILE_RESOURCES_PACK, &resources_pack_path);
906     {
907       TRACE_EVENT0("startup",
908           "ChromeBrowserMainParts::PreCreateThreadsImpl:AddDataPack");
909       ResourceBundle::GetSharedInstance().AddDataPackFromPath(
910           resources_pack_path, ui::SCALE_FACTOR_NONE);
911     }
912 #endif  // defined(OS_MACOSX)
913   }
914
915 #if defined(TOOLKIT_GTK)
916   g_set_application_name(l10n_util::GetStringUTF8(IDS_PRODUCT_NAME).c_str());
917 #endif
918
919   // Android does first run in Java instead of native.
920   // Chrome OS has its own out-of-box-experience code.
921 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
922   // On first run, we need to process the predictor preferences before the
923   // browser's profile_manager object is created, but after ResourceBundle
924   // is initialized.
925   if (first_run::IsChromeFirstRun()) {
926     first_run::ProcessMasterPreferencesResult pmp_result =
927         first_run::ProcessMasterPreferences(user_data_dir_,
928                                             master_prefs_.get());
929     if (pmp_result == first_run::EULA_EXIT_NOW)
930       return chrome::RESULT_CODE_EULA_REFUSED;
931
932     if (!parsed_command_line().HasSwitch(switches::kApp) &&
933         !parsed_command_line().HasSwitch(switches::kAppId) &&
934         !parsed_command_line().HasSwitch(switches::kShowAppList)) {
935       AddFirstRunNewTabs(browser_creator_.get(), master_prefs_->new_tabs);
936     }
937
938     // TODO(macourteau): refactor preferences that are copied from
939     // master_preferences into local_state, as a "local_state" section in
940     // master preferences. If possible, a generic solution would be prefered
941     // over a copy one-by-one of specific preferences. Also see related TODO
942     // in first_run.h.
943
944     // Store the initial VariationsService seed in local state, if it exists
945     // in master prefs.
946     if (!master_prefs_->variations_seed.empty()) {
947       local_state_->SetString(prefs::kVariationsSeed,
948                               master_prefs_->variations_seed);
949       // Set the variation seed date to the current system time. If the user's
950       // clock is incorrect, this may cause some field trial expiry checks to
951       // not do the right thing until the next seed update from the server,
952       // when this value will be updated.
953       local_state_->SetInt64(prefs::kVariationsSeedDate,
954                              base::Time::Now().ToInternalValue());
955     }
956
957     if (!master_prefs_->suppress_default_browser_prompt_for_version.empty()) {
958       local_state_->SetString(
959           prefs::kBrowserSuppressDefaultBrowserPrompt,
960           master_prefs_->suppress_default_browser_prompt_for_version);
961     }
962
963     AppListService::Get(chrome::HOST_DESKTOP_TYPE_NATIVE)->HandleFirstRun();
964   }
965 #endif
966
967 #if defined(OS_LINUX) || defined(OS_OPENBSD) || defined(OS_MACOSX)
968   // Set the product channel for crash reports.
969   base::debug::SetCrashKeyValue(crash_keys::kChannel,
970       chrome::VersionInfo::GetVersionStringModifier());
971 #endif
972
973   // Initialize tracking synchronizer system.
974   tracking_synchronizer_ = new chrome_browser_metrics::TrackingSynchronizer();
975
976   // Now that all preferences have been registered, set the install date
977   // for the uninstall metrics if this is our first run. This only actually
978   // gets used if the user has metrics reporting enabled at uninstall time.
979   int64 install_date = local_state_->GetInt64(prefs::kInstallDate);
980   if (install_date == 0)
981     local_state_->SetInt64(prefs::kInstallDate, base::Time::Now().ToTimeT());
982
983 #if defined(OS_MACOSX)
984   // Get the Keychain API to register for distributed notifications on the main
985   // thread, which has a proper CFRunloop, instead of later on the I/O thread,
986   // which doesn't. This ensures those notifications will get delivered
987   // properly. See issue 37766.
988   // (Note that the callback mask here is empty. I don't want to register for
989   // any callbacks, I just want to initialize the mechanism.)
990   SecKeychainAddCallback(&KeychainCallback, 0, NULL);
991 #endif
992
993 #if defined(OS_CHROMEOS)
994   // Must be done after g_browser_process is constructed, before
995   // SetupMetricsAndFieldTrials().
996   chromeos::CrosSettings::Initialize();
997 #endif
998
999   // Now the command line has been mutated based on about:flags, we can setup
1000   // metrics and initialize field trials. The field trials are needed by
1001   // IOThread's initialization which happens in BrowserProcess:PreCreateThreads.
1002   SetupMetricsAndFieldTrials();
1003
1004   // ChromeOS needs ResourceBundle::InitSharedInstance to be called before this.
1005   browser_process_->PreCreateThreads();
1006
1007   return content::RESULT_CODE_NORMAL_EXIT;
1008 }
1009
1010 void ChromeBrowserMainParts::PreMainMessageLoopRun() {
1011   TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRun");
1012   result_code_ = PreMainMessageLoopRunImpl();
1013
1014   for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1015     chrome_extra_parts_[i]->PreMainMessageLoopRun();
1016 }
1017
1018 // PreMainMessageLoopRun calls these extra stages in the following order:
1019 //  PreMainMessageLoopRunImpl()
1020 //   ... initial setup, including browser_process_ setup.
1021 //   PreProfileInit()
1022 //   ... additional setup, including CreateProfile()
1023 //   PostProfileInit()
1024 //   ... additional setup
1025 //   PreBrowserStart()
1026 //   ... browser_creator_->Start (OR parameters().ui_task->Run())
1027 //   PostBrowserStart()
1028
1029 void ChromeBrowserMainParts::PreProfileInit() {
1030   TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreProfileInit");
1031
1032 #if !defined(OS_ANDROID)
1033   ProfileManager* profile_manager = g_browser_process->profile_manager();
1034
1035   // First check if any ephemeral profiles are left behind because of browser
1036   // crash and schedule them for deletion and then proceed with getting the set
1037   // of profiles to open.
1038   ProfileInfoCache& profile_cache = profile_manager->GetProfileInfoCache();
1039   size_t profiles_count = profile_cache.GetNumberOfProfiles();
1040   std::vector<base::FilePath> profiles_to_delete;
1041   for (size_t i = 0;i < profiles_count; ++i) {
1042     if (profile_cache.ProfileIsEphemeralAtIndex(i))
1043       profiles_to_delete.push_back(profile_cache.GetPathOfProfileAtIndex(i));
1044   }
1045   for (size_t i = 0;i < profiles_to_delete.size(); ++i) {
1046     profile_manager->ScheduleProfileForDeletion(
1047         profiles_to_delete[i], ProfileManager::CreateCallback());
1048   }
1049 #endif  // OS_ANDROID
1050
1051   for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1052     chrome_extra_parts_[i]->PreProfileInit();
1053 }
1054
1055 void ChromeBrowserMainParts::PostProfileInit() {
1056   TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostProfileInit");
1057   LaunchDevToolsHandlerIfNeeded(parsed_command_line());
1058   for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1059     chrome_extra_parts_[i]->PostProfileInit();
1060 }
1061
1062 void ChromeBrowserMainParts::PreBrowserStart() {
1063   TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreBrowserStart");
1064   for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1065     chrome_extra_parts_[i]->PreBrowserStart();
1066
1067   three_d_observer_.reset(new ThreeDAPIObserver());
1068 }
1069
1070 void ChromeBrowserMainParts::PostBrowserStart() {
1071   TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostBrowserStart");
1072   for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1073     chrome_extra_parts_[i]->PostBrowserStart();
1074 #if !defined(OS_ANDROID)
1075   // Allow ProcessSingleton to process messages.
1076   process_singleton_->Unlock();
1077 #endif
1078 }
1079
1080 void ChromeBrowserMainParts::SetupPlatformFieldTrials() {
1081   // Base class implementation of this does nothing.
1082 }
1083
1084 int ChromeBrowserMainParts::PreMainMessageLoopRunImpl() {
1085   TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRunImpl");
1086 #if !defined(OS_ANDROID)
1087   if (CommandLine::ForCurrentProcess()->HasSwitch(
1088           switches::kTrackActiveVisitTime)) {
1089     active_tab_tracker_.reset(new ActiveTabTracker());
1090     // TODO(sky): nuke this when all ports support ActiveTabTracker.
1091     if (!active_tab_tracker_->is_valid())
1092       active_tab_tracker_.reset();
1093   }
1094 #endif
1095
1096   // Android updates the metrics service dynamically depending on whether the
1097   // application is in the foreground or not. Do not start here.
1098 #if !defined(OS_ANDROID)
1099   // Now that the file thread has been started, start recording.
1100   MetricsService::SetExecutionPhase(MetricsService::START_METRICS_RECORDING);
1101   StartMetricsRecording();
1102 #endif
1103
1104   // Create watchdog thread after creating all other threads because it will
1105   // watch the other threads and they must be running.
1106   browser_process_->watchdog_thread();
1107
1108   // Do any initializating in the browser process that requires all threads
1109   // running.
1110   browser_process_->PreMainMessageLoopRun();
1111
1112   // Record last shutdown time into a histogram.
1113   browser_shutdown::ReadLastShutdownInfo();
1114
1115 #if defined(OS_WIN)
1116   // On Windows, we use our startup as an opportunity to do upgrade/uninstall
1117   // tasks.  Those care whether the browser is already running.  On Linux/Mac,
1118   // upgrade/uninstall happen separately.
1119   bool already_running = browser_util::IsBrowserAlreadyRunning();
1120
1121   // If the command line specifies 'uninstall' then we need to work here
1122   // unless we detect another chrome browser running.
1123   if (parsed_command_line().HasSwitch(switches::kUninstall)) {
1124     return DoUninstallTasks(already_running);
1125   }
1126
1127   if (parsed_command_line().HasSwitch(switches::kHideIcons) ||
1128       parsed_command_line().HasSwitch(switches::kShowIcons)) {
1129     return ChromeBrowserMainPartsWin::HandleIconsCommands(
1130         parsed_command_line_);
1131   }
1132 #endif
1133
1134   if (parsed_command_line().HasSwitch(switches::kMakeDefaultBrowser)) {
1135     return ShellIntegration::SetAsDefaultBrowser() ?
1136         static_cast<int>(content::RESULT_CODE_NORMAL_EXIT) :
1137         static_cast<int>(chrome::RESULT_CODE_SHELL_INTEGRATION_FAILED);
1138   }
1139
1140   // Android doesn't support extensions and doesn't implement ProcessSingleton.
1141 #if !defined(OS_ANDROID)
1142   // If the command line specifies --pack-extension, attempt the pack extension
1143   // startup action and exit.
1144   if (parsed_command_line().HasSwitch(switches::kPackExtension)) {
1145     extensions::StartupHelper extension_startup_helper;
1146     if (extension_startup_helper.PackExtension(parsed_command_line()))
1147       return content::RESULT_CODE_NORMAL_EXIT;
1148     return chrome::RESULT_CODE_PACK_EXTENSION_ERROR;
1149   }
1150
1151   // If we're being launched just to check the connector policy, we are
1152   // short-lived and don't want to be passing that switch off.
1153   bool pass_command_line = !parsed_command_line().HasSwitch(
1154       switches::kCheckCloudPrintConnectorPolicy);
1155
1156   if (pass_command_line) {
1157     // When another process is running, use that process instead of starting a
1158     // new one. NotifyOtherProcess will currently give the other process up to
1159     // 20 seconds to respond. Note that this needs to be done before we attempt
1160     // to read the profile.
1161     notify_result_ = process_singleton_->NotifyOtherProcessOrCreate();
1162     UMA_HISTOGRAM_ENUMERATION("NotifyOtherProcessOrCreate.Result",
1163                                notify_result_,
1164                                ProcessSingleton::NUM_NOTIFY_RESULTS);
1165     switch (notify_result_) {
1166       case ProcessSingleton::PROCESS_NONE:
1167         // No process already running, fall through to starting a new one.
1168         break;
1169
1170       case ProcessSingleton::PROCESS_NOTIFIED:
1171 #if defined(OS_POSIX) && !defined(OS_MACOSX)
1172         printf("%s\n", base::SysWideToNativeMB(UTF16ToWide(
1173             l10n_util::GetStringUTF16(IDS_USED_EXISTING_BROWSER))).c_str());
1174 #endif
1175         // Having a differentiated return type for testing allows for tests to
1176         // verify proper handling of some switches. When not testing, stick to
1177         // the standard Unix convention of returning zero when things went as
1178         // expected.
1179         if (parsed_command_line().HasSwitch(switches::kTestType))
1180           return chrome::RESULT_CODE_NORMAL_EXIT_PROCESS_NOTIFIED;
1181         return content::RESULT_CODE_NORMAL_EXIT;
1182
1183       case ProcessSingleton::PROFILE_IN_USE:
1184         return chrome::RESULT_CODE_PROFILE_IN_USE;
1185
1186       case ProcessSingleton::LOCK_ERROR:
1187         LOG(ERROR) << "Failed to create a ProcessSingleton for your profile "
1188                       "directory. This means that running multiple instances "
1189                       "would start multiple browser processes rather than "
1190                       "opening a new window in the existing process. Aborting "
1191                       "now to avoid profile corruption.";
1192         return chrome::RESULT_CODE_PROFILE_IN_USE;
1193
1194       default:
1195         NOTREACHED();
1196     }
1197   }
1198
1199 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
1200   if (sxs_linux::ShouldMigrateUserDataDir())
1201     return sxs_linux::MigrateUserDataDir();
1202 #endif  // defined(OS_LINUX) && !defined(OS_CHROMEOS)
1203
1204   first_run::CreateSentinelIfNeeded();
1205 #endif  // !defined(OS_ANDROID)
1206
1207   // Desktop construction occurs here, (required before profile creation).
1208   PreProfileInit();
1209
1210   std::string try_chrome =
1211       parsed_command_line().GetSwitchValueASCII(switches::kTryChromeAgain);
1212   if (!try_chrome.empty()) {
1213 #if defined(OS_WIN)
1214     // Setup.exe has determined that we need to run a retention experiment
1215     // and has lauched chrome to show the experiment UI. It is guaranteed that
1216     // no other Chrome is currently running as the process singleton was
1217     // sucessfully grabbed above.
1218     int try_chrome_int;
1219     base::StringToInt(try_chrome, &try_chrome_int);
1220     TryChromeDialogView::Result answer = TryChromeDialogView::Show(
1221         try_chrome_int,
1222         base::Bind(&ChromeProcessSingleton::SetActiveModalDialog,
1223                    base::Unretained(process_singleton_.get())));
1224     if (answer == TryChromeDialogView::NOT_NOW)
1225       return chrome::RESULT_CODE_NORMAL_EXIT_CANCEL;
1226     if (answer == TryChromeDialogView::UNINSTALL_CHROME)
1227       return chrome::RESULT_CODE_NORMAL_EXIT_EXP2;
1228     // At this point the user is willing to try chrome again.
1229     if (answer == TryChromeDialogView::TRY_CHROME_AS_DEFAULT) {
1230       // Only set in the unattended case, the interactive case is Windows 8.
1231       if (ShellIntegration::CanSetAsDefaultBrowser() ==
1232           ShellIntegration::SET_DEFAULT_UNATTENDED)
1233         ShellIntegration::SetAsDefaultBrowser();
1234     }
1235 #else
1236     // We don't support retention experiments on Mac or Linux.
1237     return content::RESULT_CODE_NORMAL_EXIT;
1238 #endif  // defined(OS_WIN)
1239   }
1240
1241   // Profile creation ----------------------------------------------------------
1242
1243   // Called before CreateProfile because creating the profile can trigger
1244   // calls to GetDefaultProfile().
1245   ProfileManager::AllowGetDefaultProfile();
1246
1247   MetricsService::SetExecutionPhase(MetricsService::CREATE_PROFILE);
1248   profile_ = CreateProfile(parameters(), user_data_dir_, parsed_command_line());
1249   if (!profile_)
1250     return content::RESULT_CODE_NORMAL_EXIT;
1251
1252 #if defined(ENABLE_BACKGROUND)
1253   // Autoload any profiles which are running background apps.
1254   // TODO(rlp): Do this on a separate thread. See http://crbug.com/99075.
1255   browser_process_->profile_manager()->AutoloadProfiles();
1256 #endif
1257   // Post-profile init ---------------------------------------------------------
1258
1259 #if defined(OS_WIN)
1260   // Do the tasks if chrome has been upgraded while it was last running.
1261   if (!already_running && upgrade_util::DoUpgradeTasks(parsed_command_line()))
1262     return content::RESULT_CODE_NORMAL_EXIT;
1263
1264   // Check if there is any machine level Chrome installed on the current
1265   // machine. If yes and the current Chrome process is user level, we do not
1266   // allow the user level Chrome to run. So we notify the user and uninstall
1267   // user level Chrome.
1268   // Note this check should only happen here, after all the checks above
1269   // (uninstall, resource bundle initialization, other chrome browser
1270   // processes etc).
1271   // Do not allow this to occur for Chrome Frame user-to-system handoffs.
1272   if (!parsed_command_line().HasSwitch(switches::kChromeFrame) &&
1273       ChromeBrowserMainPartsWin::CheckMachineLevelInstall()) {
1274     return chrome::RESULT_CODE_MACHINE_LEVEL_INSTALL_EXISTS;
1275   }
1276 #endif
1277
1278   // Create the TranslateManager singleton.
1279   translate_manager_ = TranslateManager::GetInstance();
1280   DCHECK(translate_manager_ != NULL);
1281
1282   // Needs to be done before PostProfileInit, since login manager on CrOS is
1283   // called inside PostProfileInit.
1284   content::WebUIControllerFactory::RegisterFactory(
1285       ChromeWebUIControllerFactory::GetInstance());
1286
1287   // NaClBrowserDelegateImpl is accessed inside PostProfileInit().
1288   // So make sure to create it before that.
1289 #if !defined(DISABLE_NACL)
1290   NaClBrowserDelegateImpl* delegate = new NaClBrowserDelegateImpl(
1291     extensions::ExtensionSystem::Get(profile_)->info_map());
1292   nacl::NaClBrowser::SetDelegate(delegate);
1293 #endif
1294
1295   // TODO(stevenjb): Move WIN and MACOSX specific code to appropriate Parts.
1296   // (requires supporting early exit).
1297   PostProfileInit();
1298
1299   // Retrieve cached GL strings from local state and use them for GPU
1300   // blacklist decisions.
1301   if (g_browser_process->gl_string_manager())
1302     g_browser_process->gl_string_manager()->Initialize();
1303
1304   // Create an instance of GpuModeManager to watch gpu mode pref change.
1305   g_browser_process->gpu_mode_manager();
1306
1307 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1308   // Show the First Run UI if this is the first time Chrome has been run on
1309   // this computer, or we're being compelled to do so by a command line flag.
1310   // Note that this be done _after_ the PrefService is initialized and all
1311   // preferences are registered, since some of the code that the importer
1312   // touches reads preferences.
1313   if (first_run::IsChromeFirstRun()) {
1314     first_run::AutoImport(profile_,
1315                           master_prefs_->homepage_defined,
1316                           master_prefs_->do_import_items,
1317                           master_prefs_->dont_import_items,
1318                           master_prefs_->import_bookmarks_path);
1319
1320     // Note: this can pop the first run consent dialog on linux.
1321     first_run::DoPostImportTasks(profile_, master_prefs_->make_chrome_default);
1322
1323     if (!master_prefs_->suppress_first_run_default_browser_prompt) {
1324       browser_creator_->set_show_main_browser_window(
1325           !chrome::ShowFirstRunDefaultBrowserPrompt(profile_));
1326     } else {
1327       browser_creator_->set_is_default_browser_dialog_suppressed(true);
1328     }
1329   }
1330 #endif  // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1331
1332 #if defined(OS_WIN)
1333   // Sets things up so that if we crash from this point on, a dialog will
1334   // popup asking the user to restart chrome. It is done this late to avoid
1335   // testing against a bunch of special cases that are taken care early on.
1336   ChromeBrowserMainPartsWin::PrepareRestartOnCrashEnviroment(
1337       parsed_command_line());
1338
1339   // Registers Chrome with the Windows Restart Manager, which will restore the
1340   // Chrome session when the computer is restarted after a system update.
1341   // This could be run as late as WM_QUERYENDSESSION for system update reboots,
1342   // but should run on startup if extended to handle crashes/hangs/patches.
1343   // Also, better to run once here than once for each HWND's WM_QUERYENDSESSION.
1344   if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
1345     ChromeBrowserMainPartsWin::RegisterApplicationRestart(
1346         parsed_command_line());
1347   }
1348
1349   // Verify that the profile is not on a network share and if so prepare to show
1350   // notification to the user.
1351   if (NetworkProfileBubble::ShouldCheckNetworkProfile(profile_)) {
1352     content::BrowserThread::PostTask(content::BrowserThread::FILE, FROM_HERE,
1353         base::Bind(&NetworkProfileBubble::CheckNetworkProfile,
1354                    profile_->GetPath()));
1355   }
1356 #endif  // OS_WIN
1357
1358 #if defined(ENABLE_RLZ) && !defined(OS_CHROMEOS)
1359   // Init the RLZ library. This just binds the dll and schedules a task on the
1360   // file thread to be run sometime later. If this is the first run we record
1361   // the installation event.
1362   PrefService* pref_service = profile_->GetPrefs();
1363   int ping_delay = first_run::IsChromeFirstRun() ? master_prefs_->ping_delay :
1364       pref_service->GetInteger(first_run::GetPingDelayPrefName().c_str());
1365   // Negative ping delay means to send ping immediately after a first search is
1366   // recorded.
1367   RLZTracker::InitRlzFromProfileDelayed(
1368       profile_, first_run::IsChromeFirstRun(), ping_delay < 0,
1369       base::TimeDelta::FromMilliseconds(abs(ping_delay)));
1370 #endif  // defined(ENABLE_RLZ) && !defined(OS_CHROMEOS)
1371
1372   // Configure modules that need access to resources.
1373   net::NetModule::SetResourceProvider(chrome_common_net::NetResourceProvider);
1374
1375   // In unittest mode, this will do nothing.  In normal mode, this will create
1376   // the global IntranetRedirectDetector instance, which will promptly go to
1377   // sleep for seven seconds (to avoid slowing startup), and wake up afterwards
1378   // to see if it should do anything else.
1379   //
1380   // A simpler way of doing all this would be to have some function which could
1381   // give the time elapsed since startup, and simply have this object check that
1382   // when asked to initialize itself, but this doesn't seem to exist.
1383   //
1384   // This can't be created in the BrowserProcessImpl constructor because it
1385   // needs to read prefs that get set after that runs.
1386   browser_process_->intranet_redirect_detector();
1387   GoogleSearchCounter::RegisterForNotifications();
1388
1389   // Disable SDCH filtering if switches::kEnableSdch is 0.
1390   int sdch_enabled = 1;
1391   if (parsed_command_line().HasSwitch(switches::kEnableSdch)) {
1392     base::StringToInt(parsed_command_line().GetSwitchValueASCII(
1393         switches::kEnableSdch), &sdch_enabled);
1394     if (!sdch_enabled)
1395       net::SdchManager::EnableSdchSupport(false);
1396   }
1397
1398   if (parsed_command_line().HasSwitch(switches::kEnableWatchdog))
1399     InstallJankometer(parsed_command_line());
1400
1401 #if defined(OS_WIN) && !defined(GOOGLE_CHROME_BUILD)
1402   if (parsed_command_line().HasSwitch(switches::kDebugPrint)) {
1403     base::FilePath path =
1404         parsed_command_line().GetSwitchValuePath(switches::kDebugPrint);
1405     printing::PrintedDocument::set_debug_dump_path(path);
1406   }
1407 #endif
1408
1409   HandleTestParameters(parsed_command_line());
1410   browser_process_->metrics_service()->RecordBreakpadHasDebugger(
1411       base::debug::BeingDebugged());
1412
1413   LanguageUsageMetrics::RecordAcceptLanguages(
1414       profile_->GetPrefs()->GetString(prefs::kAcceptLanguages));
1415   LanguageUsageMetrics::RecordApplicationLanguage(
1416       browser_process_->GetApplicationLocale());
1417
1418   // The extension service may be available at this point. If the command line
1419   // specifies --uninstall-extension, attempt the uninstall extension startup
1420   // action.
1421   if (parsed_command_line().HasSwitch(switches::kUninstallExtension)) {
1422     extensions::StartupHelper extension_startup_helper;
1423     if (extension_startup_helper.UninstallExtension(
1424             parsed_command_line(), profile_))
1425       return content::RESULT_CODE_NORMAL_EXIT;
1426     return chrome::RESULT_CODE_UNINSTALL_EXTENSION_ERROR;
1427   }
1428
1429   // Start watching for hangs during startup. We disarm this hang detector when
1430   // ThreadWatcher takes over or when browser is shutdown or when
1431   // startup_watcher_ is deleted.
1432   MetricsService::SetExecutionPhase(MetricsService::STARTUP_TIMEBOMB_ARM);
1433   startup_watcher_->Arm(base::TimeDelta::FromSeconds(300));
1434
1435   // On mobile, need for clean shutdown arises only when the application comes
1436   // to foreground (i.e. MetricsService::OnAppEnterForeground is called).
1437   // http://crbug.com/179143
1438 #if !defined(OS_ANDROID)
1439   // Start watching for a hang.
1440   MetricsService::LogNeedForCleanShutdown();
1441 #endif
1442
1443 #if defined(ENABLE_FULL_PRINTING)
1444   // Create the instance of the cloud print proxy service so that it can launch
1445   // the service process if needed. This is needed because the service process
1446   // might have shutdown because an update was available.
1447   // TODO(torne): this should maybe be done with
1448   // BrowserContextKeyedServiceFactory::ServiceIsCreatedWithBrowserContext()
1449   // instead?
1450   CloudPrintProxyServiceFactory::GetForProfile(profile_);
1451 #endif
1452
1453   // Start watching all browser threads for responsiveness.
1454   MetricsService::SetExecutionPhase(MetricsService::THREAD_WATCHER_START);
1455   ThreadWatcherList::StartWatchingAll(parsed_command_line());
1456
1457 #if !defined(DISABLE_NACL)
1458   if (parsed_command_line().HasSwitch(switches::kPnaclDir)) {
1459     PathService::Override(chrome::DIR_PNACL_BASE,
1460                           parsed_command_line().GetSwitchValuePath(
1461                               switches::kPnaclDir));
1462   }
1463
1464   content::BrowserThread::PostTask(
1465       content::BrowserThread::IO,
1466       FROM_HERE,
1467       base::Bind(NaClProcessHost::EarlyStartup));
1468 #endif
1469
1470   // Make sure initial prefs are recorded
1471   PrefMetricsService::Factory::GetForProfile(profile_);
1472
1473   PreBrowserStart();
1474
1475   // Instantiate the notification UI manager, as this triggers a perf timer
1476   // used to measure startup time. TODO(stevenjb): Figure out what is actually
1477   // triggering the timer and call that explicitly in the approprate place.
1478   // http://crbug.com/105065.
1479   browser_process_->notification_ui_manager();
1480
1481 #if defined(OS_ANDROID)
1482   chrome_variations::VariationsService* variations_service =
1483       browser_process_->variations_service();
1484   if (variations_service)
1485     variations_service->StartRepeatedVariationsSeedFetch();
1486 #else
1487   // Most general initialization is behind us, but opening a
1488   // tab and/or session restore and such is still to be done.
1489   base::TimeTicks browser_open_start = base::TimeTicks::Now();
1490
1491   // We are in regular browser boot sequence. Open initial tabs and enter the
1492   // main message loop.
1493   int result_code;
1494 #if defined(OS_CHROMEOS)
1495   // On ChromeOS multiple profiles doesn't apply, and will break if we load
1496   // them this early as the cryptohome hasn't yet been mounted (which happens
1497   // only once we log in.
1498   std::vector<Profile*> last_opened_profiles;
1499 #else
1500   std::vector<Profile*> last_opened_profiles =
1501       g_browser_process->profile_manager()->GetLastOpenedProfiles();
1502 #endif
1503
1504   if (!parsed_command_line().HasSwitch(switches::kDisableComponentUpdate))
1505     RegisterComponentsForUpdate(parsed_command_line());
1506
1507 #if defined(USE_AURA)
1508   // Env creates the compositor. Aura widgets need the compositor to be created
1509   // before they can be initialized by the browser.
1510   aura::Env::CreateInstance();
1511 #endif
1512
1513   if (browser_creator_->Start(parsed_command_line(), base::FilePath(),
1514                               profile_, last_opened_profiles, &result_code)) {
1515 #if defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
1516     // Initialize autoupdate timer. Timer callback costs basically nothing
1517     // when browser is not in persistent mode, so it's OK to let it ride on
1518     // the main thread. This needs to be done here because we don't want
1519     // to start the timer when Chrome is run inside a test harness.
1520     browser_process_->StartAutoupdateTimer();
1521 #endif
1522
1523 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
1524     // On Linux, the running exe will be updated if an upgrade becomes
1525     // available while the browser is running.  We need to save the last
1526     // modified time of the exe, so we can compare to determine if there is
1527     // an upgrade while the browser is kept alive by a persistent extension.
1528     upgrade_util::SaveLastModifiedTimeOfExe();
1529 #endif
1530
1531     // Record now as the last successful chrome start.
1532     GoogleUpdateSettings::SetLastRunTime();
1533
1534 #if defined(OS_MACOSX)
1535     // Call Recycle() here as late as possible, before going into the loop
1536     // because Start() will add things to it while creating the main window.
1537     if (parameters().autorelease_pool)
1538       parameters().autorelease_pool->Recycle();
1539 #endif
1540
1541     base::TimeDelta delay = base::TimeTicks::Now() - browser_open_start;
1542     UMA_HISTOGRAM_LONG_TIMES_100("Startup.BrowserOpenTabs", delay);
1543
1544     // If we're running tests (ui_task is non-null), then we don't want to
1545     // call FetchLanguageListFromTranslateServer or
1546     // StartRepeatedVariationsSeedFetch.
1547     if (parameters().ui_task == NULL) {
1548       // Request new variations seed information from server.
1549       chrome_variations::VariationsService* variations_service =
1550           browser_process_->variations_service();
1551       if (variations_service) {
1552         variations_service->StartRepeatedVariationsSeedFetch();
1553
1554 #if defined(OS_WIN)
1555         variations_service->StartGoogleUpdateRegistrySync();
1556 #endif
1557       }
1558
1559       if (translate_manager_ != NULL) {
1560         translate_manager_->FetchLanguageListFromTranslateServer(
1561             profile_->GetPrefs());
1562       }
1563     }
1564
1565     run_message_loop_ = true;
1566   } else {
1567     run_message_loop_ = false;
1568   }
1569   browser_creator_.reset();
1570 #endif  // !defined(OS_ANDROID)
1571
1572   performance_monitor::PerformanceMonitor::GetInstance()->Initialize();
1573
1574   PostBrowserStart();
1575
1576   if (parameters().ui_task) {
1577     // We end the startup timer here if we have parameters to run, because we
1578     // never start to run the main loop (where we normally stop the timer).
1579     startup_timer_->SignalStartupComplete(
1580         performance_monitor::StartupTimer::STARTUP_TEST);
1581     parameters().ui_task->Run();
1582     delete parameters().ui_task;
1583     run_message_loop_ = false;
1584   }
1585 #if defined(OS_ANDROID)
1586   // We never run the C++ main loop on Android, since the UI thread message
1587   // loop is controlled by the OS, so this is as close as we can get to
1588   // the start of the main loop
1589   if (result_code_ <= 0) {
1590     RecordBrowserStartupTime();
1591   }
1592 #endif
1593   return result_code_;
1594 }
1595
1596 bool ChromeBrowserMainParts::MainMessageLoopRun(int* result_code) {
1597   TRACE_EVENT0("startup", "ChromeBrowserMainParts::MainMessageLoopRun");
1598 #if defined(OS_ANDROID)
1599   // Chrome on Android does not use default MessageLoop. It has its own
1600   // Android specific MessageLoop
1601   NOTREACHED();
1602   return true;
1603 #else
1604   // Set the result code set in PreMainMessageLoopRun or set above.
1605   *result_code = result_code_;
1606   if (!run_message_loop_)
1607     return true;  // Don't run the default message loop.
1608
1609   // These should be invoked as close to the start of the browser's
1610   // UI thread message loop as possible to get a stable measurement
1611   // across versions.
1612   RecordBrowserStartupTime();
1613   startup_timer_->SignalStartupComplete(
1614       performance_monitor::StartupTimer::STARTUP_NORMAL);
1615
1616   DCHECK_EQ(base::MessageLoop::TYPE_UI, base::MessageLoop::current()->type());
1617 #if !defined(USE_AURA) && defined(TOOLKIT_VIEWS)
1618   views::AcceleratorHandler accelerator_handler;
1619   base::RunLoop run_loop(&accelerator_handler);
1620 #else
1621   base::RunLoop run_loop;
1622 #endif
1623
1624   performance_monitor::PerformanceMonitor::GetInstance()->StartGatherCycle();
1625
1626   MetricsService::SetExecutionPhase(MetricsService::MAIN_MESSAGE_LOOP_RUN);
1627   run_loop.Run();
1628
1629   return true;
1630 #endif
1631 }
1632
1633 void ChromeBrowserMainParts::PostMainMessageLoopRun() {
1634   TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopRun");
1635 #if defined(OS_ANDROID)
1636   // Chrome on Android does not use default MessageLoop. It has its own
1637   // Android specific MessageLoop
1638   NOTREACHED();
1639 #else
1640
1641   // Start watching for jank during shutdown. It gets disarmed when
1642   // |shutdown_watcher_| object is destructed.
1643   MetricsService::SetExecutionPhase(MetricsService::SHUTDOWN_TIMEBOMB_ARM);
1644   shutdown_watcher_->Arm(base::TimeDelta::FromSeconds(300));
1645
1646   // Disarm the startup hang detector time bomb if it is still Arm'ed.
1647   startup_watcher_->Disarm();
1648
1649   for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1650     chrome_extra_parts_[i]->PostMainMessageLoopRun();
1651
1652   // Some tests don't set parameters.ui_task, so they started translate
1653   // language fetch that was never completed so we need to cleanup here
1654   // otherwise it will be done by the destructor in a wrong thread.
1655   if (parameters().ui_task == NULL && translate_manager_ != NULL)
1656     translate_manager_->CleanupPendingUlrFetcher();
1657
1658   if (notify_result_ == ProcessSingleton::PROCESS_NONE)
1659     process_singleton_->Cleanup();
1660
1661   // Stop all tasks that might run on WatchDogThread.
1662   ThreadWatcherList::StopWatchingAll();
1663
1664   browser_process_->metrics_service()->Stop();
1665
1666   restart_last_session_ = browser_shutdown::ShutdownPreThreadsStop();
1667   browser_process_->StartTearDown();
1668 #endif
1669 }
1670
1671 void ChromeBrowserMainParts::PostDestroyThreads() {
1672 #if defined(OS_ANDROID)
1673   // On Android, there is no quit/exit. So the browser's main message loop will
1674   // not finish.
1675   NOTREACHED();
1676 #else
1677   browser_process_->PostDestroyThreads();
1678   // browser_shutdown takes care of deleting browser_process, so we need to
1679   // release it.
1680   ignore_result(browser_process_.release());
1681   browser_shutdown::ShutdownPostThreadsStop(restart_last_session_);
1682   master_prefs_.reset();
1683   process_singleton_.reset();
1684
1685   // We need to do this check as late as possible, but due to modularity, this
1686   // may be the last point in Chrome.  This would be more effective if done at
1687   // a higher level on the stack, so that it is impossible for an early return
1688   // to bypass this code.  Perhaps we need a *final* hook that is called on all
1689   // paths from content/browser/browser_main.
1690   CHECK(MetricsService::UmaMetricsProperlyShutdown());
1691
1692 #if defined(OS_CHROMEOS)
1693   chromeos::CrosSettings::Shutdown();
1694 #endif
1695 #endif
1696 }
1697
1698 // Public members:
1699
1700 void ChromeBrowserMainParts::AddParts(ChromeBrowserMainExtraParts* parts) {
1701   chrome_extra_parts_.push_back(parts);
1702 }