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