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