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