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