1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "chrome/browser/chrome_browser_main.h"
6 
7 #include <stddef.h>
8 #include <stdint.h>
9 
10 #include <memory>
11 #include <set>
12 #include <string>
13 #include <utility>
14 #include <vector>
15 
16 #include "base/at_exit.h"
17 #include "base/base_switches.h"
18 #include "base/bind.h"
19 #include "base/command_line.h"
20 #include "base/debug/crash_logging.h"
21 #include "base/debug/debugger.h"
22 #include "base/debug/leak_annotations.h"
23 #include "base/feature_list.h"
24 #include "base/files/file_path.h"
25 #include "base/files/file_util.h"
26 #include "base/logging.h"
27 #include "base/memory/ptr_util.h"
28 #include "base/memory/scoped_refptr.h"
29 #include "base/metrics/field_trial.h"
30 #include "base/metrics/histogram_macros.h"
31 #include "base/path_service.h"
32 #include "base/run_loop.h"
33 #include "base/strings/string16.h"
34 #include "base/strings/string_number_conversions.h"
35 #include "base/strings/string_piece.h"
36 #include "base/strings/sys_string_conversions.h"
37 #include "base/strings/utf_string_conversions.h"
38 #include "base/system/sys_info.h"
39 #include "base/task/current_thread.h"
40 #include "base/task/thread_pool.h"
41 #include "base/threading/hang_watcher.h"
42 #include "base/threading/platform_thread.h"
43 #include "base/threading/thread_task_runner_handle.h"
44 #include "base/time/default_tick_clock.h"
45 #include "base/time/time.h"
46 #include "base/trace_event/trace_event.h"
47 #include "base/values.h"
48 #include "build/branding_buildflags.h"
49 #include "build/build_config.h"
50 #include "build/chromeos_buildflags.h"
51 #include "cc/base/switches.h"
52 #include "chrome/browser/about_flags.h"
53 #include "chrome/browser/active_use_util.h"
54 #include "chrome/browser/after_startup_task_utils.h"
55 #include "chrome/browser/browser_process.h"
56 #include "chrome/browser/browser_process_impl.h"
57 #include "chrome/browser/browser_process_platform_part.h"
58 #include "chrome/browser/chrome_browser_field_trials.h"
59 #include "chrome/browser/chrome_browser_main_extra_parts.h"
60 #include "chrome/browser/component_updater/registration.h"
61 #include "chrome/browser/defaults.h"
62 #include "chrome/browser/first_run/first_run.h"
63 #include "chrome/browser/language/url_language_histogram_factory.h"
64 #include "chrome/browser/lifetime/application_lifetime.h"
65 #include "chrome/browser/lifetime/browser_shutdown.h"
66 #include "chrome/browser/media/router/chrome_media_router_factory.h"
67 #include "chrome/browser/media/webrtc/media_capture_devices_dispatcher.h"
68 #include "chrome/browser/media/webrtc/webrtc_log_util.h"
69 #include "chrome/browser/metrics/chrome_feature_list_creator.h"
70 #include "chrome/browser/metrics/chrome_metrics_service_accessor.h"
71 #include "chrome/browser/metrics/expired_histograms_array.h"
72 #include "chrome/browser/metrics/renderer_uptime_tracker.h"
73 #include "chrome/browser/metrics/thread_watcher.h"
74 #include "chrome/browser/nacl_host/nacl_browser_delegate_impl.h"
75 #include "chrome/browser/net/system_network_context_manager.h"
76 #include "chrome/browser/performance_monitor/process_monitor.h"
77 #include "chrome/browser/performance_monitor/system_monitor.h"
78 #include "chrome/browser/policy/chrome_browser_policy_connector.h"
79 #include "chrome/browser/prefs/chrome_command_line_pref_store.h"
80 #include "chrome/browser/prefs/chrome_pref_service_factory.h"
81 #include "chrome/browser/prefs/pref_metrics_service.h"
82 #include "chrome/browser/process_singleton.h"
83 #include "chrome/browser/profiles/profile.h"
84 #include "chrome/browser/profiles/profile_attributes_entry.h"
85 #include "chrome/browser/profiles/profile_attributes_storage.h"
86 #include "chrome/browser/profiles/profile_manager.h"
87 #include "chrome/browser/profiles/profiles_state.h"
88 #include "chrome/browser/sessions/chrome_serialized_navigation_driver.h"
89 #include "chrome/browser/shell_integration.h"
90 #include "chrome/browser/startup_data.h"
91 #include "chrome/browser/tracing/background_tracing_field_trial.h"
92 #include "chrome/browser/tracing/trace_event_system_stats_monitor.h"
93 #include "chrome/browser/translate/translate_service.h"
94 #include "chrome/browser/ui/javascript_dialogs/chrome_javascript_app_modal_dialog_view_factory.h"
95 #include "chrome/browser/ui/profile_error_dialog.h"
96 #include "chrome/browser/ui/startup/bad_flags_prompt.h"
97 #include "chrome/browser/ui/startup/startup_browser_creator.h"
98 #include "chrome/browser/ui/webui/chrome_web_ui_controller_factory.h"
99 #include "chrome/common/buildflags.h"
100 #include "chrome/common/channel_info.h"
101 #include "chrome/common/chrome_constants.h"
102 #include "chrome/common/chrome_features.h"
103 #include "chrome/common/chrome_paths.h"
104 #include "chrome/common/chrome_result_codes.h"
105 #include "chrome/common/chrome_switches.h"
106 #include "chrome/common/crash_keys.h"
107 #include "chrome/common/env_vars.h"
108 #include "chrome/common/logging_chrome.h"
109 #include "chrome/common/media/media_resource_provider.h"
110 #include "chrome/common/net/net_resource_provider.h"
111 #include "chrome/common/pref_names.h"
112 #include "chrome/common/profiler/thread_profiler.h"
113 #include "chrome/common/profiler/thread_profiler_configuration.h"
114 #include "chrome/grit/generated_resources.h"
115 #include "chrome/installer/util/google_update_settings.h"
116 #include "components/device_event_log/device_event_log.h"
117 #include "components/embedder_support/switches.h"
118 #include "components/flags_ui/pref_service_flags_storage.h"
119 #include "components/google/core/common/google_util.h"
120 #include "components/language/content/browser/geo_language_provider.h"
121 #include "components/language/core/browser/pref_names.h"
122 #include "components/language/core/common/language_experiments.h"
123 #include "components/language_usage_metrics/language_usage_metrics.h"
124 #include "components/metrics/call_stack_profile_metrics_provider.h"
125 #include "components/metrics/call_stack_profile_params.h"
126 #include "components/metrics/expired_histogram_util.h"
127 #include "components/metrics/metrics_reporting_default_state.h"
128 #include "components/metrics/metrics_service.h"
129 #include "components/metrics_services_manager/metrics_services_manager.h"
130 #include "components/nacl/browser/nacl_browser.h"
131 #include "components/nacl/common/buildflags.h"
132 #include "components/offline_pages/buildflags/buildflags.h"
133 #include "components/prefs/json_pref_store.h"
134 #include "components/prefs/pref_registry_simple.h"
135 #include "components/prefs/pref_service.h"
136 #include "components/prefs/pref_value_store.h"
137 #include "components/prefs/scoped_user_pref_update.h"
138 #include "components/rappor/rappor_service_impl.h"
139 #include "components/site_isolation/site_isolation_policy.h"
140 #include "components/spellcheck/spellcheck_buildflags.h"
141 #include "components/startup_metric_utils/browser/startup_metric_utils.h"
142 #include "components/tracing/common/tracing_switches.h"
143 #include "components/translate/core/browser/translate_download_manager.h"
144 #include "components/variations/field_trial_config/field_trial_util.h"
145 #include "components/variations/pref_names.h"
146 #include "components/variations/service/variations_service.h"
147 #include "components/variations/synthetic_trials_active_group_id_provider.h"
148 #include "components/variations/variations_associated_data.h"
149 #include "components/variations/variations_crash_keys.h"
150 #include "components/variations/variations_ids_provider.h"
151 #include "components/variations/variations_switches.h"
152 #include "components/version_info/version_info.h"
153 #include "content/public/browser/browser_context.h"
154 #include "content/public/browser/browser_task_traits.h"
155 #include "content/public/browser/browser_thread.h"
156 #include "content/public/browser/notification_observer.h"
157 #include "content/public/browser/notification_registrar.h"
158 #include "content/public/browser/notification_service.h"
159 #include "content/public/browser/notification_types.h"
160 #include "content/public/browser/site_instance.h"
161 #include "content/public/browser/system_connector.h"
162 #include "content/public/common/content_client.h"
163 #include "content/public/common/content_features.h"
164 #include "content/public/common/content_switches.h"
165 #include "content/public/common/main_function_params.h"
166 #include "content/public/common/profiling.h"
167 #include "extensions/buildflags/buildflags.h"
168 #include "media/base/localized_strings.h"
169 #include "media/media_buildflags.h"
170 #include "net/base/net_module.h"
171 #include "net/cookies/cookie_monster.h"
172 #include "net/http/http_network_layer.h"
173 #include "net/http/http_stream_factory.h"
174 #include "ppapi/buildflags/buildflags.h"
175 #include "printing/buildflags/buildflags.h"
176 #include "rlz/buildflags/buildflags.h"
177 #include "services/tracing/public/cpp/stack_sampling/tracing_sampler_profiler.h"
178 #include "third_party/blink/public/common/experiments/memory_ablation_experiment.h"
179 #include "ui/base/layout.h"
180 #include "ui/base/resource/resource_bundle.h"
181 
182 #if defined(OS_ANDROID)
183 #include "chrome/browser/flags/android/chrome_feature_list.h"
184 #include "chrome/browser/metrics/thread_watcher_android.h"
185 #include "chrome/browser/ui/page_info/chrome_page_info_client.h"
186 #include "ui/base/resource/resource_bundle_android.h"
187 #else
188 #include "chrome/browser/resource_coordinator/tab_activity_watcher.h"
189 #include "chrome/browser/resource_coordinator/tab_manager.h"
190 #include "chrome/browser/ui/browser.h"
191 #include "chrome/browser/ui/browser_finder.h"
192 #include "chrome/browser/ui/uma_browsing_activity_observer.h"
193 #include "chrome/browser/upgrade_detector/upgrade_detector.h"
194 #include "chrome/browser/usb/web_usb_detector.h"
195 #include "ui/base/l10n/l10n_util.h"
196 #endif  // defined(OS_ANDROID)
197 
198 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
199 #include "chrome/browser/first_run/upgrade_util.h"
200 #include "components/enterprise/browser/controller/chrome_browser_cloud_management_controller.h"
201 #endif
202 
203 #if defined(OS_CHROMEOS)
204 #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h"
205 #include "chrome/browser/chromeos/settings/cros_settings.h"
206 #include "chrome/browser/chromeos/settings/stats_reporting_controller.h"
207 #include "chromeos/constants/chromeos_switches.h"
208 #include "chromeos/settings/cros_settings_names.h"
209 #include "components/arc/metrics/stability_metrics_manager.h"
210 #endif  // defined(OS_CHROMEOS)
211 
212 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
213 #include "chrome/browser/first_run/upgrade_util_linux.h"
214 #endif  // defined(OS_LINUX) && !defined(OS_CHROMEOS)
215 
216 #if defined(OS_LINUX) || defined(OS_CHROMEOS)
217 #include "components/crash/core/app/breakpad_linux.h"
218 #include "components/crash/core/app/crashpad.h"
219 #endif
220 
221 #if defined(OS_MAC)
222 #include <Security/Security.h>
223 
224 #include "base/mac/scoped_nsautorelease_pool.h"
225 #include "chrome/browser/app_controller_mac.h"
226 #include "chrome/browser/mac/keystone_glue.h"
227 #endif  // defined(OS_MAC)
228 
229 // TODO(port): several win-only methods have been pulled out of this, but
230 // BrowserMain() as a whole needs to be broken apart so that it's usable by
231 // other platforms. For now, it's just a stub. This is a serious work in
232 // progress and should not be taken as an indication of a real refactoring.
233 
234 #if defined(OS_WIN)
235 #include "base/trace_event/trace_event_etw_export_win.h"
236 #include "base/win/win_util.h"
237 #include "chrome/browser/chrome_browser_main_win.h"
238 #include "chrome/browser/first_run/upgrade_util_win.h"
239 #include "chrome/browser/notifications/win/notification_launch_id.h"
240 #include "chrome/browser/ui/network_profile_bubble.h"
241 #include "chrome/browser/ui/views/try_chrome_dialog_win/try_chrome_dialog.h"
242 #include "chrome/browser/win/browser_util.h"
243 #include "chrome/browser/win/chrome_select_file_dialog_factory.h"
244 #include "chrome/browser/win/parental_controls.h"
245 #include "chrome/install_static/install_util.h"
246 #include "ui/shell_dialogs/select_file_dialog.h"
247 #endif  // defined(OS_WIN)
248 
249 #if defined(OS_WIN) || defined(OS_MAC) || \
250     (defined(OS_LINUX) && !defined(OS_CHROMEOS)) || defined(OS_BSD)
251 #include "chrome/browser/metrics/desktop_session_duration/desktop_session_duration_tracker.h"
252 #include "chrome/browser/metrics/desktop_session_duration/touch_mode_stats_tracker.h"
253 #include "chrome/browser/profiles/profile_activity_metrics_recorder.h"
254 #include "ui/base/pointer/touch_ui_controller.h"
255 #endif
256 
257 #if BUILDFLAG(ENABLE_BACKGROUND_MODE)
258 #include "chrome/browser/background/background_mode_manager.h"
259 #endif  // BUILDFLAG(ENABLE_BACKGROUND_MODE)
260 
261 #if BUILDFLAG(ENABLE_EXTENSIONS)
262 #include "chrome/browser/extensions/startup_helper.h"
263 #include "extensions/browser/extension_protocols.h"
264 #include "extensions/common/features/feature_provider.h"
265 #include "extensions/components/javascript_dialog_extensions_client/javascript_dialog_extension_client_impl.h"
266 #endif  // BUILDFLAG(ENABLE_EXTENSIONS)
267 
268 #if BUILDFLAG(ENABLE_NACL)
269 #include "components/nacl/browser/nacl_process_host.h"
270 #endif  // BUILDFLAG(ENABLE_NACL)
271 
272 #if BUILDFLAG(ENABLE_OFFLINE_PAGES)
273 #include "chrome/browser/offline_pages/offline_page_info_handler.h"
274 #endif
275 
276 #if BUILDFLAG(ENABLE_PLUGINS)
277 #include "chrome/browser/plugins/plugin_prefs.h"
278 #endif
279 
280 #if BUILDFLAG(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
281 #include "printing/printed_document.h"
282 #endif
283 
284 #if BUILDFLAG(ENABLE_PRINT_PREVIEW) && defined(OS_WIN)
285 #include "components/printing/browser/printer_capabilities.h"
286 #include "printing/backend/win_helper.h"
287 #endif
288 
289 #if BUILDFLAG(ENABLE_PRINT_PREVIEW) && !defined(OS_CHROMEOS)
290 #include "chrome/browser/printing/cloud_print/cloud_print_proxy_service.h"
291 #include "chrome/browser/printing/cloud_print/cloud_print_proxy_service_factory.h"
292 #endif
293 
294 #if BUILDFLAG(ENABLE_RLZ)
295 #include "chrome/browser/rlz/chrome_rlz_tracker_delegate.h"
296 #include "components/rlz/rlz_tracker.h"  // nogncheck crbug.com/1125897
297 #endif  // BUILDFLAG(ENABLE_RLZ)
298 
299 #if BUILDFLAG(IS_LACROS)
300 #include "ui/shell_dialogs/select_file_dialog_lacros.h"
301 #endif
302 
303 #if defined(USE_AURA)
304 #include "ui/aura/env.h"
305 #endif
306 
307 #if defined(OS_WIN) && BUILDFLAG(USE_BROWSER_SPELLCHECKER)
308 #include "chrome/browser/spellchecker/spellcheck_factory.h"
309 #include "chrome/browser/spellchecker/spellcheck_service.h"
310 #include "components/spellcheck/browser/pref_names.h"
311 #include "components/spellcheck/common/spellcheck_features.h"
312 #endif  // defined(OS_WIN) && BUILDFLAG(USE_BROWSER_SPELLCHECKER)
313 
314 namespace {
315 
316 #if !defined(OS_ANDROID)
317 // Holds the RunLoop for the non-Android MainMessageLoopRun() to Run().
318 base::RunLoop* g_run_loop = nullptr;
319 #endif
320 
321 // This function provides some ways to test crash and assertion handling
322 // behavior of the program.
HandleTestParameters(const base::CommandLine & command_line)323 void HandleTestParameters(const base::CommandLine& command_line) {
324   // This parameter causes a null pointer crash (crash reporter trigger).
325   if (command_line.HasSwitch(switches::kBrowserCrashTest)) {
326     IMMEDIATE_CRASH();
327   }
328 }
329 
330 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
AddFirstRunNewTabs(StartupBrowserCreator * browser_creator,const std::vector<GURL> & new_tabs)331 void AddFirstRunNewTabs(StartupBrowserCreator* browser_creator,
332                         const std::vector<GURL>& new_tabs) {
333   for (auto it = new_tabs.begin(); it != new_tabs.end(); ++it) {
334     if (it->is_valid())
335       browser_creator->AddFirstRunTab(*it);
336   }
337 }
338 #endif  // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
339 
340 // Initializes the primary profile, possibly doing some user prompting to pick
341 // a fallback profile. Returns the newly created profile, or NULL if startup
342 // should not continue.
CreatePrimaryProfile(const content::MainFunctionParams & parameters,const base::FilePath & user_data_dir,const base::CommandLine & parsed_command_line)343 Profile* CreatePrimaryProfile(const content::MainFunctionParams& parameters,
344                               const base::FilePath& user_data_dir,
345                               const base::CommandLine& parsed_command_line) {
346   TRACE_EVENT0("startup", "ChromeBrowserMainParts::CreateProfile")
347 
348   base::Time start = base::Time::Now();
349 
350   bool set_last_used_profile = false;
351 
352 // If the browser is launched due to activation on Windows native
353 // notification, the profile id encoded in the notification launch id should
354 // be chosen over all others.
355 #if defined(OS_WIN)
356   std::string last_used_profile_id =
357       NotificationLaunchId::GetNotificationLaunchProfileId(parsed_command_line);
358   if (!last_used_profile_id.empty()) {
359     profiles::SetLastUsedProfile(last_used_profile_id);
360     set_last_used_profile = true;
361   }
362 #endif  // defined(OS_WIN)
363 
364   bool profile_dir_specified =
365       profiles::IsMultipleProfilesEnabled() &&
366       parsed_command_line.HasSwitch(switches::kProfileDirectory);
367   if (!set_last_used_profile && profile_dir_specified) {
368     profiles::SetLastUsedProfile(
369         parsed_command_line.GetSwitchValueASCII(switches::kProfileDirectory));
370     set_last_used_profile = true;
371   }
372 
373   if (set_last_used_profile) {
374     // Clear kProfilesLastActive since the user only wants to launch a specific
375     // profile.
376     ListPrefUpdate update(g_browser_process->local_state(),
377                           prefs::kProfilesLastActive);
378     base::ListValue* profile_list = update.Get();
379     profile_list->Clear();
380   }
381 
382   Profile* profile = nullptr;
383 #if defined(OS_CHROMEOS) || defined(OS_ANDROID)
384   // On ChromeOS and Android the ProfileManager will use the same path as the
385   // one we got passed. CreateInitialProfile will therefore use the correct path
386   // automatically.
387   DCHECK_EQ(user_data_dir.value(),
388             g_browser_process->profile_manager()->user_data_dir().value());
389   profile = ProfileManager::CreateInitialProfile();
390 
391   // TODO(port): fix this. See comments near the definition of |user_data_dir|.
392   // It is better to CHECK-fail here than it is to silently exit because of
393   // missing code in the above test.
394   CHECK(profile) << "Cannot get default profile.";
395 
396 #else
397   profile = GetStartupProfile(user_data_dir, parsed_command_line);
398 
399   if (!profile && !set_last_used_profile)
400     profile = GetFallbackStartupProfile();
401 
402   if (!profile) {
403     ProfileErrorType error_type =
404         profile_dir_specified ? ProfileErrorType::CREATE_FAILURE_SPECIFIED
405                               : ProfileErrorType::CREATE_FAILURE_ALL;
406 
407     // TODO(lwchkg): What diagnostics do you want to include in the feedback
408     // report when an error occurs?
409     ShowProfileErrorDialog(error_type, IDS_COULDNT_STARTUP_PROFILE_ERROR,
410                            "Error creating primary profile.");
411     return nullptr;
412   }
413 #endif  // defined(OS_CHROMEOS) || defined(OS_ANDROID)
414 
415   UMA_HISTOGRAM_LONG_TIMES(
416       "Startup.CreateFirstProfile", base::Time::Now() - start);
417   return profile;
418 }
419 
420 #if defined(OS_MAC)
KeychainCallback(SecKeychainEvent keychain_event,SecKeychainCallbackInfo * info,void * context)421 OSStatus KeychainCallback(SecKeychainEvent keychain_event,
422                           SecKeychainCallbackInfo* info, void* context) {
423   return noErr;
424 }
425 #endif  // defined(OS_MAC)
426 
427 #if !defined(OS_ANDROID)
ProcessSingletonNotificationCallbackImpl(const base::CommandLine & command_line,const base::FilePath & current_directory)428 void ProcessSingletonNotificationCallbackImpl(
429     const base::CommandLine& command_line,
430     const base::FilePath& current_directory) {
431   // Drop the request if the browser process is already shutting down.
432   if (!g_browser_process || g_browser_process->IsShuttingDown())
433     return;
434 
435   g_browser_process->platform_part()->PlatformSpecificCommandLineProcessing(
436       command_line);
437 
438   base::FilePath user_data_dir =
439       g_browser_process->profile_manager()->user_data_dir();
440   base::FilePath startup_profile_dir =
441       GetStartupProfilePath(user_data_dir, command_line);
442 
443   StartupBrowserCreator::ProcessCommandLineAlreadyRunning(
444       command_line, current_directory, startup_profile_dir);
445 
446   // Record now as the last successful chrome start.
447   if (ShouldRecordActiveUse(command_line))
448     GoogleUpdateSettings::SetLastRunTime();
449 }
450 
ProcessSingletonNotificationCallback(const base::CommandLine & command_line,const base::FilePath & current_directory)451 bool ProcessSingletonNotificationCallback(
452     const base::CommandLine& command_line,
453     const base::FilePath& current_directory) {
454   // Drop the request if the browser process is already shutting down.
455   // Note that we're going to post an async task below. Even if the browser
456   // process isn't shutting down right now, it could be by the time the task
457   // starts running. So, an additional check needs to happen when it starts.
458   // But regardless of any future check, there is no reason to post the task
459   // now if we know we're already shutting down.
460   if (!g_browser_process || g_browser_process->IsShuttingDown())
461     return false;
462 
463   // In order to handle this request on Windows, there is platform specific
464   // code in browser_finder.cc that requires making outbound COM calls to
465   // cross-apartment shell objects (via IVirtualDesktopManager). That is not
466   // allowed within a SendMessage handler, which this function is a part of.
467   // So, we post a task to asynchronously finish the command line processing.
468   return base::ThreadTaskRunnerHandle::Get()->PostTask(
469       FROM_HERE, base::BindOnce(&ProcessSingletonNotificationCallbackImpl,
470                                 command_line, current_directory));
471 }
472 #endif  // !defined(OS_ANDROID)
473 
474 class ScopedMainMessageLoopRunEvent {
475  public:
ScopedMainMessageLoopRunEvent()476   ScopedMainMessageLoopRunEvent() {
477     TRACE_EVENT_NESTABLE_ASYNC_BEGIN0(
478         "toplevel", "ChromeBrowserMainParts::MainMessageLoopRun", this);
479   }
~ScopedMainMessageLoopRunEvent()480   ~ScopedMainMessageLoopRunEvent() {
481     TRACE_EVENT_NESTABLE_ASYNC_END0(
482         "toplevel", "ChromeBrowserMainParts::MainMessageLoopRun", this);
483   }
484 };
485 
486 }  // namespace
487 
488 // BrowserMainParts ------------------------------------------------------------
489 
ChromeBrowserMainParts(const content::MainFunctionParams & parameters,StartupData * startup_data)490 ChromeBrowserMainParts::ChromeBrowserMainParts(
491     const content::MainFunctionParams& parameters,
492     StartupData* startup_data)
493     : parameters_(parameters),
494       parsed_command_line_(parameters.command_line),
495       result_code_(content::RESULT_CODE_NORMAL_EXIT),
496       should_call_pre_main_loop_start_startup_on_variations_service_(
497           !parameters.ui_task),
498       profile_(nullptr),
499       run_message_loop_(true),
500       startup_data_(startup_data) {
501   DCHECK(startup_data_);
502   // If we're running tests (ui_task is non-null).
503   if (parameters.ui_task)
504     browser_defaults::enable_help_app = false;
505 
506 #if !defined(OS_ANDROID)
507   shutdown_watcher_ = std::make_unique<ShutdownWatcherHelper>();
508 #endif  // !defined(OS_ANDROID)
509 }
510 
~ChromeBrowserMainParts()511 ChromeBrowserMainParts::~ChromeBrowserMainParts() {
512   // Delete parts in the reverse of the order they were added.
513   while (!chrome_extra_parts_.empty())
514     chrome_extra_parts_.pop_back();
515 }
516 
SetupMetrics()517 void ChromeBrowserMainParts::SetupMetrics() {
518   TRACE_EVENT0("startup", "ChromeBrowserMainParts::SetupMetrics");
519   metrics::MetricsService* metrics = browser_process_->metrics_service();
520   metrics->synthetic_trial_registry()->AddSyntheticTrialObserver(
521       variations::VariationsIdsProvider::GetInstance());
522   metrics->synthetic_trial_registry()->AddSyntheticTrialObserver(
523       variations::SyntheticTrialsActiveGroupIdProvider::GetInstance());
524   // Now that field trials have been created, initializes metrics recording.
525   metrics->InitializeMetricsRecordingState();
526 
527   startup_data_->chrome_feature_list_creator()
528       ->browser_field_trials()
529       ->RegisterSyntheticTrials();
530 }
531 
532 // static
StartMetricsRecording()533 void ChromeBrowserMainParts::StartMetricsRecording() {
534   TRACE_EVENT0("startup", "ChromeBrowserMainParts::StartMetricsRecording");
535 
536   // Register a synthetic field trial for the sampling profiler configuration
537   // that was already chosen.
538   std::string trial_name, group_name;
539   if (ThreadProfilerConfiguration::Get()->GetSyntheticFieldTrial(&trial_name,
540                                                                  &group_name)) {
541     ChromeMetricsServiceAccessor::RegisterSyntheticFieldTrial(trial_name,
542                                                               group_name);
543   }
544 
545 #if defined(OS_ANDROID)
546   // Android updates the metrics service dynamically depending on whether the
547   // application is in the foreground or not. Do not start here unless
548   // kUmaBackgroundSessions is enabled.
549   if (!base::FeatureList::IsEnabled(chrome::android::kUmaBackgroundSessions))
550     return;
551 #endif
552 
553   g_browser_process->metrics_service()->CheckForClonedInstall();
554 
555 #if defined(OS_WIN)
556   // The last live timestamp is used to assess whether a browser crash occurred
557   // due to a full system crash. Update the last live timestamp on a slow
558   // schedule to get the bast possible accuracy for the assessment.
559   g_browser_process->metrics_service()->StartUpdatingLastLiveTimestamp();
560 #endif
561 
562   g_browser_process->GetMetricsServicesManager()->UpdateUploadPermissions(true);
563 }
564 
RecordBrowserStartupTime()565 void ChromeBrowserMainParts::RecordBrowserStartupTime() {
566   // Don't record any metrics if UI was displayed before this point e.g.
567   // warning dialogs or browser was started in background mode.
568   if (startup_metric_utils::WasMainWindowStartupInterrupted())
569     return;
570 
571   bool is_first_run = false;
572 #if !defined(OS_ANDROID)
573   // On Android, first run is handled in Java code, and the C++ side of Chrome
574   // doesn't know if this is the first run. This will cause some inaccuracy in
575   // the UMA statistics, but this should be minor (first runs are rare).
576   is_first_run = first_run::IsChromeFirstRun();
577 #endif  // defined(OS_ANDROID)
578 
579   // Record collected startup metrics.
580   startup_metric_utils::RecordBrowserMainMessageLoopStart(
581       base::TimeTicks::Now(), is_first_run);
582 }
583 
SetupOriginTrialsCommandLine(PrefService * local_state)584 void ChromeBrowserMainParts::SetupOriginTrialsCommandLine(
585     PrefService* local_state) {
586   base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
587   if (!command_line->HasSwitch(embedder_support::kOriginTrialPublicKey)) {
588     std::string new_public_key =
589         local_state->GetString(prefs::kOriginTrialPublicKey);
590     if (!new_public_key.empty()) {
591       command_line->AppendSwitchASCII(
592           embedder_support::kOriginTrialPublicKey,
593           local_state->GetString(prefs::kOriginTrialPublicKey));
594     }
595   }
596   if (!command_line->HasSwitch(
597           embedder_support::kOriginTrialDisabledFeatures)) {
598     const base::ListValue* override_disabled_feature_list =
599         local_state->GetList(prefs::kOriginTrialDisabledFeatures);
600     if (override_disabled_feature_list) {
601       std::vector<base::StringPiece> disabled_features;
602       base::StringPiece disabled_feature;
603       for (const auto& item : *override_disabled_feature_list) {
604         if (item.GetAsString(&disabled_feature)) {
605           disabled_features.push_back(disabled_feature);
606         }
607       }
608       if (!disabled_features.empty()) {
609         const std::string override_disabled_features =
610             base::JoinString(disabled_features, "|");
611         command_line->AppendSwitchASCII(
612             embedder_support::kOriginTrialDisabledFeatures,
613             override_disabled_features);
614       }
615     }
616   }
617   if (!command_line->HasSwitch(embedder_support::kOriginTrialDisabledTokens)) {
618     const base::ListValue* disabled_token_list =
619         local_state->GetList(prefs::kOriginTrialDisabledTokens);
620     if (disabled_token_list) {
621       std::vector<base::StringPiece> disabled_tokens;
622       base::StringPiece disabled_token;
623       for (const auto& item : *disabled_token_list) {
624         if (item.GetAsString(&disabled_token)) {
625           disabled_tokens.push_back(disabled_token);
626         }
627       }
628       if (!disabled_tokens.empty()) {
629         const std::string disabled_token_switch =
630             base::JoinString(disabled_tokens, "|");
631         command_line->AppendSwitchASCII(
632             embedder_support::kOriginTrialDisabledTokens,
633             disabled_token_switch);
634       }
635     }
636   }
637 }
638 
639 // -----------------------------------------------------------------------------
640 // TODO(viettrungluu): move more/rest of BrowserMain() into BrowserMainParts.
641 
642 #if defined(OS_WIN)
643 #define DLLEXPORT __declspec(dllexport)
644 
645 // We use extern C for the prototype DLLEXPORT to avoid C++ name mangling.
646 extern "C" {
647 DLLEXPORT void __cdecl RelaunchChromeBrowserWithNewCommandLineIfNeeded();
648 }
649 
RelaunchChromeBrowserWithNewCommandLineIfNeeded()650 DLLEXPORT void __cdecl RelaunchChromeBrowserWithNewCommandLineIfNeeded() {
651   // Need an instance of AtExitManager to handle singleton creations and
652   // deletions.  We need this new instance because, the old instance created
653   // in ChromeMain() got destructed when the function returned.
654   base::AtExitManager exit_manager;
655   upgrade_util::RelaunchChromeBrowserWithNewCommandLineIfNeeded();
656 }
657 #endif
658 
659 // content::BrowserMainParts implementation ------------------------------------
660 
PreEarlyInitialization()661 int ChromeBrowserMainParts::PreEarlyInitialization() {
662   TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreEarlyInitialization");
663   for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
664     chrome_extra_parts_[i]->PreEarlyInitialization();
665 
666   // Create BrowserProcess in PreEarlyInitialization() so that we can load
667   // field trials (and all it depends upon).
668   browser_process_ = std::make_unique<BrowserProcessImpl>(startup_data_);
669 
670   bool failed_to_load_resource_bundle = false;
671   const int load_local_state_result =
672       OnLocalStateLoaded(&failed_to_load_resource_bundle);
673 
674   // Reuses the MetricsServicesManager and GetMetricsServicesManagerClient
675   // instances created in the FeatureListCreator so they won't be created
676   // again.
677   auto* chrome_feature_list_creator =
678       startup_data_->chrome_feature_list_creator();
679   browser_process_->SetMetricsServices(
680       chrome_feature_list_creator->TakeMetricsServicesManager(),
681       chrome_feature_list_creator->GetMetricsServicesManagerClient());
682 
683   if (load_local_state_result == chrome::RESULT_CODE_MISSING_DATA &&
684       failed_to_load_resource_bundle) {
685     if (base::CommandLine::ForCurrentProcess()->HasSwitch(
686             switches::kNoErrorDialogs)) {
687       return chrome::RESULT_CODE_MISSING_DATA;
688     }
689     // Continue on and show error later (once UI has been initialized and main
690     // message loop is running).
691     return content::RESULT_CODE_NORMAL_EXIT;
692   }
693   return load_local_state_result;
694 }
695 
PostEarlyInitialization()696 void ChromeBrowserMainParts::PostEarlyInitialization() {
697   TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostEarlyInitialization");
698   for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
699     chrome_extra_parts_[i]->PostEarlyInitialization();
700 }
701 
ToolkitInitialized()702 void ChromeBrowserMainParts::ToolkitInitialized() {
703   TRACE_EVENT0("startup", "ChromeBrowserMainParts::ToolkitInitialized");
704   for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
705     chrome_extra_parts_[i]->ToolkitInitialized();
706 }
707 
PreMainMessageLoopStart()708 void ChromeBrowserMainParts::PreMainMessageLoopStart() {
709   TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopStart");
710 
711   for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
712     chrome_extra_parts_[i]->PreMainMessageLoopStart();
713 }
714 
PostMainMessageLoopStart()715 void ChromeBrowserMainParts::PostMainMessageLoopStart() {
716   TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopStart");
717 
718 #if !defined(OS_ANDROID)
719   // Initialize the upgrade detector here after ChromeBrowserMainPartsChromeos
720   // has had a chance to connect the DBus services.
721   UpgradeDetector::GetInstance()->Init();
722 #endif
723 
724   ThreadProfiler::SetMainThreadTaskRunner(base::ThreadTaskRunnerHandle::Get());
725 
726   system_monitor_ = performance_monitor::SystemMonitor::Create();
727 
728   // TODO(sebmarchand): Allow this to be created earlier if startup tracing is
729   // enabled.
730   trace_event_system_stats_monitor_ =
731       std::make_unique<tracing::TraceEventSystemStatsMonitor>();
732 
733   // device_event_log must be initialized after the message loop. Calls to
734   // {DEVICE}_LOG prior to here will only be logged with VLOG. Some
735   // platforms (e.g. chromeos) may have already initialized this.
736   if (!device_event_log::IsInitialized())
737     device_event_log::Initialize(0 /* default max entries */);
738 
739   for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
740     chrome_extra_parts_[i]->PostMainMessageLoopStart();
741 }
742 
PreCreateThreads()743 int ChromeBrowserMainParts::PreCreateThreads() {
744   // IMPORTANT
745   // Calls in this function should not post tasks or create threads as
746   // components used to handle those tasks are not yet available. This work
747   // should be deferred to PreMainMessageLoopRunImpl.
748 
749   TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreads");
750   result_code_ = PreCreateThreadsImpl();
751 
752   if (result_code_ == content::RESULT_CODE_NORMAL_EXIT) {
753     // These members must be initialized before exiting this function normally.
754 #if !defined(OS_ANDROID)
755     DCHECK(browser_creator_.get());
756 #endif
757 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
758     DCHECK(master_prefs_.get());
759 #endif
760 
761     for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
762       chrome_extra_parts_[i]->PreCreateThreads();
763   }
764 
765   // Create an instance of GpuModeManager to watch gpu mode pref change.
766   g_browser_process->gpu_mode_manager();
767 
768   return result_code_;
769 }
770 
OnLocalStateLoaded(bool * failed_to_load_resource_bundle)771 int ChromeBrowserMainParts::OnLocalStateLoaded(
772     bool* failed_to_load_resource_bundle) {
773   *failed_to_load_resource_bundle = false;
774   if (!base::PathService::Get(chrome::DIR_USER_DATA, &user_data_dir_))
775     return chrome::RESULT_CODE_MISSING_DATA;
776 
777 #if defined(OS_WIN)
778   if (first_run::IsChromeFirstRun()) {
779     bool stats_default;
780     if (GoogleUpdateSettings::GetCollectStatsConsentDefault(&stats_default)) {
781       // |stats_default| == true means that the default state of consent for the
782       // product at the time of install was to report usage statistics, meaning
783       // "opt-out".
784       metrics::RecordMetricsReportingDefaultState(
785           browser_process_->local_state(),
786           stats_default ? metrics::EnableMetricsDefault::OPT_OUT
787                         : metrics::EnableMetricsDefault::OPT_IN);
788     }
789   }
790 #endif  // defined(OS_WIN)
791 
792   std::string locale =
793       startup_data_->chrome_feature_list_creator()->actual_locale();
794   if (locale.empty()) {
795     *failed_to_load_resource_bundle = true;
796     return chrome::RESULT_CODE_MISSING_DATA;
797   }
798   browser_process_->SetApplicationLocale(locale);
799 
800   const int apply_first_run_result = ApplyFirstRunPrefs();
801   if (apply_first_run_result != content::RESULT_CODE_NORMAL_EXIT)
802     return apply_first_run_result;
803 
804   SetupOriginTrialsCommandLine(browser_process_->local_state());
805 
806   metrics::EnableExpiryChecker(chrome_metrics::kExpiredHistogramsHashes,
807                                chrome_metrics::kNumExpiredHistograms);
808 
809   return content::RESULT_CODE_NORMAL_EXIT;
810 }
811 
ApplyFirstRunPrefs()812 int ChromeBrowserMainParts::ApplyFirstRunPrefs() {
813 // Android does first run in Java instead of native.
814 // Chrome OS has its own out-of-box-experience code.
815 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
816   master_prefs_ = std::make_unique<first_run::MasterPrefs>();
817 
818   std::unique_ptr<installer::InitialPreferences> installer_initial_prefs =
819       startup_data_->chrome_feature_list_creator()->TakeInitialPrefs();
820   if (!installer_initial_prefs)
821     return content::RESULT_CODE_NORMAL_EXIT;
822 
823   // On first run, we need to process the predictor preferences before the
824   // browser's profile_manager object is created, but after ResourceBundle
825   // is initialized.
826   first_run::ProcessInitialPreferencesResult pip_result =
827       first_run::ProcessInitialPreferences(user_data_dir_,
828                                            std::move(installer_initial_prefs),
829                                            master_prefs_.get());
830   if (pip_result == first_run::EULA_EXIT_NOW)
831     return chrome::RESULT_CODE_EULA_REFUSED;
832 
833   // TODO(macourteau): refactor preferences that are copied from
834   // master_preferences into local_state, as a "local_state" section in
835   // initial preferences. If possible, a generic solution would be preferred
836   // over a copy one-by-one of specific preferences. Also see related TODO
837   // in first_run.h.
838 
839   PrefService* local_state = g_browser_process->local_state();
840   if (!master_prefs_->suppress_default_browser_prompt_for_version.empty()) {
841     local_state->SetString(
842         prefs::kBrowserSuppressDefaultBrowserPrompt,
843         master_prefs_->suppress_default_browser_prompt_for_version);
844   }
845 
846 #endif  // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
847   return content::RESULT_CODE_NORMAL_EXIT;
848 }
849 
PreCreateThreadsImpl()850 int ChromeBrowserMainParts::PreCreateThreadsImpl() {
851   TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreadsImpl")
852   run_message_loop_ = false;
853 
854   if (browser_process_->GetApplicationLocale().empty()) {
855     ShowMissingLocaleMessageBox();
856     return chrome::RESULT_CODE_MISSING_DATA;
857   }
858 
859 #if !defined(OS_ANDROID)
860   chrome::MaybeShowInvalidUserDataDirWarningDialog();
861 #endif  // !defined(OS_ANDROID)
862 
863   DCHECK(!user_data_dir_.empty());
864 
865   // Force MediaCaptureDevicesDispatcher to be created on UI thread.
866   MediaCaptureDevicesDispatcher::GetInstance();
867 
868   // Android's first run is done in Java instead of native.
869 #if !defined(OS_ANDROID)
870   process_singleton_ = std::make_unique<ChromeProcessSingleton>(
871       user_data_dir_,
872       base::BindRepeating(&ProcessSingletonNotificationCallback));
873 
874   // Cache first run state early.
875   first_run::IsChromeFirstRun();
876 
877 #endif  // !defined(OS_ANDROID)
878 
879   PrefService* local_state = browser_process_->local_state();
880 
881 #if defined(OS_CHROMEOS)
882   chromeos::CrosSettings::Initialize(local_state);
883   chromeos::StatsReportingController::Initialize(local_state);
884   arc::StabilityMetricsManager::Initialize(local_state);
885 #endif  // defined(OS_CHROMEOS)
886 
887   {
888     TRACE_EVENT0(
889         "startup",
890         "ChromeBrowserMainParts::PreCreateThreadsImpl:InitBrowserProcessImpl");
891     browser_process_->Init();
892   }
893 
894 #if !defined(OS_ANDROID)
895   // Create the RunLoop for MainMessageLoopRun() to use, and pass a copy of
896   // its QuitClosure to the BrowserProcessImpl to call when it is time to exit.
897   DCHECK(!g_run_loop);
898   g_run_loop = new base::RunLoop;
899 
900   // These members must be initialized before returning from this function.
901   // Android doesn't use StartupBrowserCreator.
902   browser_creator_.reset(new StartupBrowserCreator);
903   // TODO(yfriedman): Refactor Android to re-use UMABrowsingActivityObserver
904   chrome::UMABrowsingActivityObserver::Init();
905 #endif  // !defined(OS_ANDROID)
906 
907 #if defined(OS_WIN)
908   // This is needed to enable ETW exporting. This is only relevant for the
909   // browser process, as other processes enable it separately.
910   base::trace_event::TraceEventETWExport::EnableETWExport();
911 #endif  // OS_WIN
912 
913   // Reset the command line in the crash report details, since we may have
914   // just changed it to include experiments.
915   crash_keys::SetCrashKeysFromCommandLine(
916       *base::CommandLine::ForCurrentProcess());
917 
918   browser_process_->browser_policy_connector()->OnResourceBundleCreated();
919 
920 // Android does first run in Java instead of native.
921 // Chrome OS has its own out-of-box-experience code.
922 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
923   if (first_run::IsChromeFirstRun()) {
924     if (!parsed_command_line().HasSwitch(switches::kApp) &&
925         !parsed_command_line().HasSwitch(switches::kAppId)) {
926       AddFirstRunNewTabs(browser_creator_.get(), master_prefs_->new_tabs);
927     }
928 
929 #if defined(OS_MAC) || defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_BSD)
930     // Create directory for user-level Native Messaging manifest files. This
931     // makes it less likely that the directory will be created by third-party
932     // software with incorrect owner or permission. See crbug.com/725513 .
933     base::FilePath user_native_messaging_dir;
934     CHECK(base::PathService::Get(chrome::DIR_USER_NATIVE_MESSAGING,
935                                  &user_native_messaging_dir));
936     if (!base::PathExists(user_native_messaging_dir))
937       base::CreateDirectory(user_native_messaging_dir);
938 #endif  // defined(OS_MAC) || defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_BSD)
939   }
940 #endif  // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
941 
942 #if defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_OPENBSD)
943   // Set the product channel for crash reports.
944   if (!crash_reporter::IsCrashpadEnabled()) {
945     breakpad::SetChannelCrashKey(chrome::GetChannelName());
946   }
947 #endif  // defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_OPENBSD)
948 
949 #if defined(OS_MAC)
950   // Get the Keychain API to register for distributed notifications on the main
951   // thread, which has a proper CFRunloop, instead of later on the I/O thread,
952   // which doesn't. This ensures those notifications will get delivered
953   // properly. See issue 37766.
954   // (Note that the callback mask here is empty. I don't want to register for
955   // any callbacks, I just want to initialize the mechanism.)
956   SecKeychainAddCallback(&KeychainCallback, 0, nullptr);
957 #endif  // defined(OS_MAC)
958 
959 #if defined(OS_WIN) || defined(OS_MAC) || \
960     (defined(OS_LINUX) && !defined(OS_CHROMEOS)) || defined(OS_BSD)
961   metrics::DesktopSessionDurationTracker::Initialize();
962   ProfileActivityMetricsRecorder::Initialize();
963   TouchModeStatsTracker::Initialize(
964       metrics::DesktopSessionDurationTracker::Get(),
965       ui::TouchUiController::Get());
966 #endif
967   metrics::RendererUptimeTracker::Initialize();
968 
969   // Add Site Isolation switches as dictated by policy.
970   auto* command_line = base::CommandLine::ForCurrentProcess();
971   if (local_state->GetBoolean(prefs::kSitePerProcess) &&
972       site_isolation::SiteIsolationPolicy::IsEnterprisePolicyApplicable() &&
973       !command_line->HasSwitch(switches::kSitePerProcess)) {
974     command_line->AppendSwitch(switches::kSitePerProcess);
975   }
976   // IsolateOrigins policy is taken care of through SiteIsolationPrefsObserver
977   // (constructed and owned by BrowserProcessImpl).
978 
979 #if defined(OS_ANDROID)
980   // The admin should also be able to use these policies to force Site Isolation
981   // off (on Android; using enterprise policies to disable Site Isolation is not
982   // supported on other platforms).  Note that disabling either SitePerProcess
983   // or IsolateOrigins via policy will disable both types of isolation.
984   if ((local_state->IsManagedPreference(prefs::kSitePerProcess) &&
985        !local_state->GetBoolean(prefs::kSitePerProcess)) ||
986       (local_state->IsManagedPreference(prefs::kIsolateOrigins) &&
987        local_state->GetString(prefs::kIsolateOrigins).empty())) {
988     base::CommandLine::ForCurrentProcess()->AppendSwitch(
989         switches::kDisableSiteIsolationForPolicy);
990   }
991 #endif
992 
993   // ChromeOS needs ui::ResourceBundle::InitSharedInstance to be called before
994   // this.
995   browser_process_->PreCreateThreads(parsed_command_line());
996 
997   // This must occur in PreCreateThreads() because it initializes global state
998   // which is then read by all threads without synchronization. It must be after
999   // browser_process_->PreCreateThreads() as that instantiates the IOThread
1000   // which is used in SetupMetrics().
1001   SetupMetrics();
1002 
1003   return content::RESULT_CODE_NORMAL_EXIT;
1004 }
1005 
PostCreateThreads()1006 void ChromeBrowserMainParts::PostCreateThreads() {
1007   // This task should be posted after the IO thread starts, and prior to the
1008   // base version of the function being invoked. It is functionally okay to post
1009   // this task in method ChromeBrowserMainParts::BrowserThreadsStarted() which
1010   // we also need to add in this class, and call this method at the very top of
1011   // BrowserMainLoop::InitializeMainThread(). PostCreateThreads is preferred to
1012   // BrowserThreadsStarted as it matches the PreCreateThreads and CreateThreads
1013   // stages.
1014   content::GetIOThreadTaskRunner({})->PostTask(
1015       FROM_HERE, base::BindOnce(&ThreadProfiler::StartOnChildThread,
1016                                 metrics::CallStackProfileParams::IO_THREAD));
1017 // Sampling multiple threads might cause overhead on Android and we don't want
1018 // to enable it unless the data is needed.
1019 #if !defined(OS_ANDROID)
1020   content::GetIOThreadTaskRunner({})->PostTask(
1021       FROM_HERE,
1022       base::BindOnce(&tracing::TracingSamplerProfiler::CreateOnChildThread));
1023 #endif
1024 
1025   tracing::SetupBackgroundTracingFieldTrial();
1026 
1027   for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1028     chrome_extra_parts_[i]->PostCreateThreads();
1029 }
1030 
PreMainMessageLoopRun()1031 void ChromeBrowserMainParts::PreMainMessageLoopRun() {
1032   TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRun");
1033 
1034   result_code_ = PreMainMessageLoopRunImpl();
1035 
1036   for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1037     chrome_extra_parts_[i]->PreMainMessageLoopRun();
1038 }
1039 
1040 // PreMainMessageLoopRun calls these extra stages in the following order:
1041 //  PreMainMessageLoopRunImpl()
1042 //   ... initial setup, including browser_process_ setup.
1043 //   PreProfileInit()
1044 //   ... additional setup, including CreateProfile()
1045 //   PostProfileInit()
1046 //   ... additional setup
1047 //   PreBrowserStart()
1048 //   ... browser_creator_->Start (OR parameters().ui_task->Run())
1049 //   PostBrowserStart()
1050 
PreProfileInit()1051 void ChromeBrowserMainParts::PreProfileInit() {
1052   TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreProfileInit");
1053 
1054   for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1055     chrome_extra_parts_[i]->PreProfileInit();
1056 
1057 #if !defined(OS_ANDROID)
1058   // Ephemeral profiles may have been left behind if the browser crashed.
1059   g_browser_process->profile_manager()->CleanUpEphemeralProfiles();
1060   // Files of deleted profiles can also be left behind after a crash.
1061   g_browser_process->profile_manager()->CleanUpDeletedProfiles();
1062 #endif  // !defined(OS_ANDROID)
1063 
1064 #if BUILDFLAG(ENABLE_EXTENSIONS)
1065   javascript_dialog_extensions_client::InstallClient();
1066 #endif  // BUILDFLAG(ENABLE_EXTENSIONS)
1067 
1068   InstallChromeJavaScriptAppModalDialogViewFactory();
1069   media_router::ChromeMediaRouterFactory::DoPlatformInit();
1070 }
1071 
PostProfileInit()1072 void ChromeBrowserMainParts::PostProfileInit() {
1073   TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostProfileInit");
1074 
1075   g_browser_process->CreateDevToolsProtocolHandler();
1076   if (parsed_command_line().HasSwitch(::switches::kAutoOpenDevToolsForTabs))
1077     g_browser_process->CreateDevToolsAutoOpener();
1078 
1079   for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1080     chrome_extra_parts_[i]->PostProfileInit();
1081 }
1082 
PreBrowserStart()1083 void ChromeBrowserMainParts::PreBrowserStart() {
1084   TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreBrowserStart");
1085   for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1086     chrome_extra_parts_[i]->PreBrowserStart();
1087 
1088 #if !defined(OS_ANDROID)
1089   // Start the tab manager here so that we give the most amount of time for the
1090   // other services to start up before we start adjusting the oom priority.
1091   g_browser_process->GetTabManager()->Start();
1092 #endif
1093 
1094   // The RulesetService will make the filtering rules available to renderers
1095   // immediately after its construction, provided that the rules are already
1096   // available at no cost in an indexed format. This enables activating
1097   // subresource filtering, if needed, also for page loads on start-up.
1098   g_browser_process->subresource_filter_ruleset_service();
1099 }
1100 
PostBrowserStart()1101 void ChromeBrowserMainParts::PostBrowserStart() {
1102   TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostBrowserStart");
1103   for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1104     chrome_extra_parts_[i]->PostBrowserStart();
1105 #if !defined(OS_ANDROID)
1106   // Allow ProcessSingleton to process messages.
1107   process_singleton_->Unlock();
1108 #endif  // !defined(OS_ANDROID)
1109   // Set up a task to delete old WebRTC log files for all profiles. Use a delay
1110   // to reduce the impact on startup time.
1111   content::GetUIThreadTaskRunner({})->PostDelayedTask(
1112       FROM_HERE,
1113       base::BindOnce(&WebRtcLogUtil::DeleteOldWebRtcLogFilesForAllProfiles),
1114       base::TimeDelta::FromMinutes(1));
1115 
1116 #if !defined(OS_ANDROID)
1117 #if !defined(OS_BSD)
1118   if (base::FeatureList::IsEnabled(features::kWebUsb)) {
1119     web_usb_detector_.reset(new WebUsbDetector());
1120     content::GetUIThreadTaskRunner({base::TaskPriority::BEST_EFFORT})
1121         ->PostTask(FROM_HERE,
1122                    base::BindOnce(&WebUsbDetector::Initialize,
1123                                   base::Unretained(web_usb_detector_.get())));
1124   }
1125 #endif
1126   if (base::FeatureList::IsEnabled(features::kTabMetricsLogging)) {
1127     // Initialize the TabActivityWatcher to begin logging tab activity events.
1128     resource_coordinator::TabActivityWatcher::GetInstance();
1129   }
1130 #endif
1131 
1132   // At this point, StartupBrowserCreator::Start has run creating initial
1133   // browser windows and tabs, but no progress has been made in loading
1134   // content as the main message loop hasn't started processing tasks yet.
1135   // We setup to observe to the initial page load here to defer running
1136   // task posted via PostAfterStartupTask until its complete.
1137   AfterStartupTaskUtils::StartMonitoringStartup();
1138 }
1139 
PreMainMessageLoopRunImpl()1140 int ChromeBrowserMainParts::PreMainMessageLoopRunImpl() {
1141   TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRunImpl");
1142 
1143   SCOPED_UMA_HISTOGRAM_LONG_TIMER("Startup.PreMainMessageLoopRunImplLongTime");
1144 
1145   // Can't be in SetupFieldTrials() because it needs a task runner.
1146   blink::MemoryAblationExperiment::MaybeStart(
1147       content::GetIOThreadTaskRunner({}));
1148 
1149 #if defined(OS_WIN)
1150   // Windows parental controls calls can be slow, so we do an early init here
1151   // that calculates this value off of the UI thread.
1152   InitializeWinParentalControls();
1153 #endif
1154 
1155   // Now that the file thread has been started, start metrics.
1156   StartMetricsRecording();
1157 
1158   if (!base::debug::BeingDebugged()) {
1159     // Create watchdog thread after creating all other threads because it will
1160     // watch the other threads and they must be running.
1161     browser_process_->watchdog_thread();
1162   }
1163 
1164   // Do any initializating in the browser process that requires all threads
1165   // running.
1166   browser_process_->PreMainMessageLoopRun();
1167 
1168   // Record last shutdown time into a histogram.
1169   browser_shutdown::ReadLastShutdownInfo();
1170 
1171 #if defined(OS_WIN)
1172   // On Windows, we use our startup as an opportunity to do upgrade/uninstall
1173   // tasks.  Those care whether the browser is already running.  On Linux/Mac,
1174   // upgrade/uninstall happen separately.
1175   bool already_running = browser_util::IsBrowserAlreadyRunning();
1176 
1177   // If the command line specifies 'uninstall' then we need to work here
1178   // unless we detect another chrome browser running.
1179   if (parsed_command_line().HasSwitch(switches::kUninstall)) {
1180     return DoUninstallTasks(already_running);
1181   }
1182 
1183   if (parsed_command_line().HasSwitch(switches::kHideIcons) ||
1184       parsed_command_line().HasSwitch(switches::kShowIcons)) {
1185     return ChromeBrowserMainPartsWin::HandleIconsCommands(
1186         parsed_command_line_);
1187   }
1188 
1189   ui::SelectFileDialog::SetFactory(new ChromeSelectFileDialogFactory());
1190 #elif BUILDFLAG(IS_LACROS)
1191   ui::SelectFileDialog::SetFactory(new ui::SelectFileDialogLacros::Factory());
1192 #endif  // defined(OS_WIN)
1193 
1194   if (parsed_command_line().HasSwitch(switches::kMakeDefaultBrowser)) {
1195     bool is_managed = g_browser_process->local_state()->IsManagedPreference(
1196         prefs::kDefaultBrowserSettingEnabled);
1197     if (is_managed && !g_browser_process->local_state()->GetBoolean(
1198         prefs::kDefaultBrowserSettingEnabled)) {
1199       return static_cast<int>(chrome::RESULT_CODE_ACTION_DISALLOWED_BY_POLICY);
1200     }
1201 
1202     return shell_integration::SetAsDefaultBrowser()
1203                ? static_cast<int>(content::RESULT_CODE_NORMAL_EXIT)
1204                : static_cast<int>(chrome::RESULT_CODE_SHELL_INTEGRATION_FAILED);
1205   }
1206 
1207 #if defined(USE_AURA)
1208   // Make sure aura::Env has been initialized.
1209   CHECK(aura::Env::GetInstance());
1210 #endif  // defined(USE_AURA)
1211 
1212   // Android doesn't support extensions and doesn't implement ProcessSingleton.
1213 #if !defined(OS_ANDROID)
1214   // If the command line specifies --pack-extension, attempt the pack extension
1215   // startup action and exit.
1216   if (parsed_command_line().HasSwitch(switches::kPackExtension)) {
1217     extensions::StartupHelper extension_startup_helper;
1218     if (extension_startup_helper.PackExtension(parsed_command_line()))
1219       return content::RESULT_CODE_NORMAL_EXIT;
1220     return chrome::RESULT_CODE_PACK_EXTENSION_ERROR;
1221   }
1222 
1223   // When another process is running, use that process instead of starting a
1224   // new one. NotifyOtherProcess will currently give the other process up to
1225   // 20 seconds to respond. Note that this needs to be done before we attempt
1226   // to read the profile.
1227   notify_result_ = process_singleton_->NotifyOtherProcessOrCreate();
1228   UMA_HISTOGRAM_ENUMERATION("Chrome.ProcessSingleton.NotifyResult",
1229                             notify_result_,
1230                             ProcessSingleton::kNumNotifyResults);
1231   switch (notify_result_) {
1232     case ProcessSingleton::PROCESS_NONE:
1233       // No process already running, fall through to starting a new one.
1234       g_browser_process->platform_part()->PlatformSpecificCommandLineProcessing(
1235           *base::CommandLine::ForCurrentProcess());
1236       break;
1237 
1238     case ProcessSingleton::PROCESS_NOTIFIED:
1239       printf("%s\n", base::SysWideToNativeMB(
1240                          base::UTF16ToWide(l10n_util::GetStringUTF16(
1241                              IDS_USED_EXISTING_BROWSER)))
1242                          .c_str());
1243 
1244       // Having a differentiated return type for testing allows for tests to
1245       // verify proper handling of some switches. When not testing, stick to
1246       // the standard Unix convention of returning zero when things went as
1247       // expected.
1248       if (parsed_command_line().HasSwitch(switches::kTestType))
1249         return chrome::RESULT_CODE_NORMAL_EXIT_PROCESS_NOTIFIED;
1250       return content::RESULT_CODE_NORMAL_EXIT;
1251 
1252     case ProcessSingleton::PROFILE_IN_USE:
1253       return chrome::RESULT_CODE_PROFILE_IN_USE;
1254 
1255     case ProcessSingleton::LOCK_ERROR:
1256       LOG(ERROR) << "Failed to create a ProcessSingleton for your profile "
1257                     "directory. This means that running multiple instances "
1258                     "would start multiple browser processes rather than "
1259                     "opening a new window in the existing process. Aborting "
1260                     "now to avoid profile corruption.";
1261       return chrome::RESULT_CODE_PROFILE_IN_USE;
1262   }
1263 
1264 #if BUILDFLAG(ENABLE_DOWNGRADE_PROCESSING)
1265   // Begin relaunch processing immediately if User Data migration is required
1266   // to handle a version downgrade.
1267   if (downgrade_manager_.PrepareUserDataDirectoryForCurrentVersion(
1268           user_data_dir_)) {
1269     return chrome::RESULT_CODE_DOWNGRADE_AND_RELAUNCH;
1270   }
1271   downgrade_manager_.UpdateLastVersion(user_data_dir_);
1272 #endif
1273 
1274 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
1275   // Initialize the chrome browser cloud management controller controller after
1276   // the browser process singleton is acquired to remove race conditions where
1277   // multiple browser processes start simultaneously.  The main
1278   // initialization of browser_policy_connector is performed inside
1279   // PreMainMessageLoopRun() so that policies can be applied as soon as
1280   // possible.
1281   //
1282   // Note that this protects against multiple browser process starts in
1283   // the same user data dir and not multiple starts across user data dirs.
1284   browser_process_->browser_policy_connector()
1285       ->chrome_browser_cloud_management_controller()
1286       ->Init(browser_process_->local_state(),
1287              browser_process_->system_network_context_manager()
1288                  ->GetSharedURLLoaderFactory());
1289 
1290   // Wait for the chrome browser cloud management enrollment to finish.
1291   // If no enrollment is needed, this function returns immediately.
1292   // Abort the launch process if the enrollment fails.
1293   if (!browser_process_->browser_policy_connector()
1294            ->chrome_browser_cloud_management_controller()
1295            ->WaitUntilPolicyEnrollmentFinished()) {
1296     return chrome::RESULT_CODE_CLOUD_POLICY_ENROLLMENT_FAILED;
1297   }
1298 #endif
1299 
1300   // Handle special early return paths (which couldn't be processed even earlier
1301   // as they require the process singleton to be held) first.
1302 
1303   std::string try_chrome =
1304       parsed_command_line().GetSwitchValueASCII(switches::kTryChromeAgain);
1305 
1306   // The TryChromeDialog may be aborted by a rendezvous from another browser
1307   // process (e.g., a launch via Chrome's taskbar icon or some such). In this
1308   // case, browser startup should continue without processing the original
1309   // command line (the one with --try-chrome-again), but rather with the command
1310   // line from the other process (handled in
1311   // ProcessSingletonNotificationCallback thanks to the ProcessSingleton). This
1312   // variable is cleared in that particular case, leading to a bypass of the
1313   // StartupBrowserCreator.
1314   bool process_command_line = true;
1315   if (!try_chrome.empty()) {
1316 #if defined(OS_WIN)
1317     // Setup.exe has determined that we need to run a retention experiment
1318     // and has lauched chrome to show the experiment UI. It is guaranteed that
1319     // no other Chrome is currently running as the process singleton was
1320     // successfully grabbed above.
1321     int try_chrome_int;
1322     base::StringToInt(try_chrome, &try_chrome_int);
1323     TryChromeDialog::Result answer = TryChromeDialog::Show(
1324         try_chrome_int,
1325         base::BindRepeating(
1326             &ChromeProcessSingleton::SetModalDialogNotificationHandler,
1327             base::Unretained(process_singleton_.get())));
1328     switch (answer) {
1329       case TryChromeDialog::NOT_NOW:
1330         return chrome::RESULT_CODE_NORMAL_EXIT_CANCEL;
1331       case TryChromeDialog::OPEN_CHROME_WELCOME:
1332         browser_creator_->set_welcome_back_page(true);
1333         break;
1334       case TryChromeDialog::OPEN_CHROME_DEFAULT:
1335         break;
1336       case TryChromeDialog::OPEN_CHROME_DEFER:
1337         process_command_line = false;
1338         break;
1339     }
1340 #else
1341     // We don't support retention experiments on Mac or Linux.
1342     return content::RESULT_CODE_NORMAL_EXIT;
1343 #endif  // defined(OS_WIN)
1344   }
1345 #endif  // !defined(OS_ANDROID)
1346 
1347 #if defined(OS_WIN)
1348   // Do the tasks if chrome has been upgraded while it was last running.
1349   if (!already_running && upgrade_util::DoUpgradeTasks(parsed_command_line()))
1350     return content::RESULT_CODE_NORMAL_EXIT;
1351 
1352   // Check if there is any machine level Chrome installed on the current
1353   // machine. If yes and the current Chrome process is user level, we do not
1354   // allow the user level Chrome to run. So we notify the user and uninstall
1355   // user level Chrome.
1356   // Note this check needs to happen here (after the process singleton was
1357   // obtained but before potentially creating the first run sentinel).
1358   if (ChromeBrowserMainPartsWin::CheckMachineLevelInstall())
1359     return chrome::RESULT_CODE_MACHINE_LEVEL_INSTALL_EXISTS;
1360 #endif  // defined(OS_WIN)
1361 
1362   // Desktop construction occurs here, (required before profile creation).
1363   PreProfileInit();
1364 
1365   // This step is costly and is already measured in Startup.CreateFirstProfile
1366   // and more directly Profile.CreateAndInitializeProfile.
1367   profile_ = CreatePrimaryProfile(parameters(),
1368                                   user_data_dir_,
1369                                   parsed_command_line());
1370   if (!profile_)
1371     return content::RESULT_CODE_NORMAL_EXIT;
1372 
1373 #if defined(OS_WIN) && BUILDFLAG(USE_BROWSER_SPELLCHECKER)
1374   if (first_run::IsChromeFirstRun()) {
1375     // The installed Windows language packs aren't determined until
1376     // the spellcheck service is initialized. Make sure the primary
1377     // preferred language is enabled for spellchecking until the user
1378     // opts out later. If there is no dictionary support for the language
1379     // then it will later be automatically disabled.
1380     SpellcheckService::EnableFirstUserLanguageForSpellcheck(
1381         profile_->GetPrefs());
1382   }
1383 
1384   // Create the spellcheck service. This will asynchronously retrieve the
1385   // Windows platform spellcheck dictionary language tags used to populate the
1386   // context menu for editable content.
1387   if (spellcheck::UseBrowserSpellChecker() &&
1388       profile_->GetPrefs()->GetBoolean(spellcheck::prefs::kSpellCheckEnable) &&
1389       !base::FeatureList::IsEnabled(
1390           spellcheck::kWinDelaySpellcheckServiceInit)) {
1391     SpellcheckServiceFactory::GetForContext(profile_);
1392   }
1393 #endif  // defined(OS_WIN) && BUILDFLAG(USE_BROWSER_SPELLCHECKER)
1394 
1395 #if !defined(OS_ANDROID)
1396   // The first run sentinel must be created after the process singleton was
1397   // grabbed and no early return paths were otherwise hit above.
1398   first_run::CreateSentinelIfNeeded();
1399 #endif  // !defined(OS_ANDROID)
1400 
1401 #if BUILDFLAG(ENABLE_BACKGROUND_MODE)
1402   // Autoload any profiles which are running background apps.
1403   // TODO(rlp): Do this on a separate thread. See http://crbug.com/99075.
1404   browser_process_->profile_manager()->AutoloadProfiles();
1405 #endif  // BUILDFLAG(ENABLE_BACKGROUND_MODE)
1406   // Post-profile init ---------------------------------------------------------
1407 
1408   TranslateService::Initialize();
1409   if (base::FeatureList::IsEnabled(features::kGeoLanguage) ||
1410       base::FeatureList::IsEnabled(language::kExplicitLanguageAsk) ||
1411       language::GetOverrideLanguageModel() ==
1412           language::OverrideLanguageModel::GEO) {
1413     language::GeoLanguageProvider::GetInstance()->StartUp(
1414         browser_process_->local_state());
1415   }
1416 
1417   // Needs to be done before PostProfileInit, since login manager on CrOS is
1418   // called inside PostProfileInit.
1419   content::WebUIControllerFactory::RegisterFactory(
1420       ChromeWebUIControllerFactory::GetInstance());
1421 
1422 #if defined(OS_ANDROID)
1423   page_info::SetPageInfoClient(new ChromePageInfoClient());
1424 #endif
1425 
1426 #if BUILDFLAG(ENABLE_NACL)
1427   // NaClBrowserDelegateImpl is accessed inside PostProfileInit().
1428   // So make sure to create it before that.
1429   nacl::NaClBrowser::SetDelegate(std::make_unique<NaClBrowserDelegateImpl>(
1430       browser_process_->profile_manager()));
1431 #endif  // BUILDFLAG(ENABLE_NACL)
1432 
1433   // TODO(stevenjb): Move WIN and MACOSX specific code to appropriate Parts.
1434   // (requires supporting early exit).
1435   PostProfileInit();
1436 
1437 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1438   // Execute first run specific code after the PrefService has been initialized
1439   // and preferences have been registered since some of the import code depends
1440   // on preferences.
1441   if (first_run::IsChromeFirstRun()) {
1442     first_run::AutoImport(profile_, master_prefs_->import_bookmarks_path);
1443 
1444     // Note: This can pop-up the first run consent dialog on Linux & Mac.
1445     first_run::DoPostImportTasks(profile_,
1446                                  master_prefs_->make_chrome_default_for_user);
1447 
1448     // The first run dialog is modal, and spins a RunLoop, which could receive
1449     // a SIGTERM, and call chrome::AttemptExit(). Exit cleanly in that case.
1450     if (browser_shutdown::IsTryingToQuit())
1451       return content::RESULT_CODE_NORMAL_EXIT;
1452   }
1453 #endif  // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1454 
1455 #if defined(OS_WIN)
1456   // Sets things up so that if we crash from this point on, a dialog will
1457   // popup asking the user to restart chrome. It is done this late to avoid
1458   // testing against a bunch of special cases that are taken care early on.
1459   ChromeBrowserMainPartsWin::PrepareRestartOnCrashEnviroment(
1460       parsed_command_line());
1461 
1462   // Registers Chrome with the Windows Restart Manager, which will restore the
1463   // Chrome session when the computer is restarted after a system update.
1464   // This could be run as late as WM_QUERYENDSESSION for system update reboots,
1465   // but should run on startup if extended to handle crashes/hangs/patches.
1466   // Also, better to run once here than once for each HWND's WM_QUERYENDSESSION.
1467   if (!parsed_command_line().HasSwitch(switches::kBrowserTest)) {
1468     ChromeBrowserMainPartsWin::RegisterApplicationRestart(
1469         parsed_command_line());
1470   }
1471 
1472   // Verify that the profile is not on a network share and if so prepare to show
1473   // notification to the user.
1474   if (NetworkProfileBubble::ShouldCheckNetworkProfile(profile_)) {
1475     base::ThreadPool::PostTask(
1476         FROM_HERE, {base::MayBlock()},
1477         base::BindOnce(&NetworkProfileBubble::CheckNetworkProfile,
1478                        profile_->GetPath()));
1479   }
1480 #endif  // defined(OS_WIN)
1481 
1482 #if BUILDFLAG(ENABLE_RLZ) && !defined(OS_CHROMEOS)
1483   // Init the RLZ library. This just binds the dll and schedules a task on the
1484   // file thread to be run sometime later. If this is the first run we record
1485   // the installation event.
1486   int ping_delay =
1487       profile_->GetPrefs()->GetInteger(prefs::kRlzPingDelaySeconds);
1488   // Negative ping delay means to send ping immediately after a first search is
1489   // recorded.
1490   rlz::RLZTracker::SetRlzDelegate(
1491       base::WrapUnique(new ChromeRLZTrackerDelegate));
1492   rlz::RLZTracker::InitRlzDelayed(
1493       first_run::IsChromeFirstRun(), ping_delay < 0,
1494       base::TimeDelta::FromSeconds(abs(ping_delay)),
1495       ChromeRLZTrackerDelegate::IsGoogleDefaultSearch(profile_),
1496       ChromeRLZTrackerDelegate::IsGoogleHomepage(profile_),
1497       ChromeRLZTrackerDelegate::IsGoogleInStartpages(profile_));
1498 #endif  // BUILDFLAG(ENABLE_RLZ) && !defined(OS_CHROMEOS)
1499 
1500   // Configure modules that need access to resources.
1501   net::NetModule::SetResourceProvider(ChromeNetResourceProvider);
1502   media::SetLocalizedStringProvider(ChromeMediaLocalizedStringProvider);
1503 
1504 #if !defined(OS_ANDROID)
1505   // In unittest mode, this will do nothing.  In normal mode, this will create
1506   // the global IntranetRedirectDetector instance, which will promptly go to
1507   // sleep for seven seconds (to avoid slowing startup), and wake up afterwards
1508   // to see if it should do anything else.
1509   //
1510   // A simpler way of doing all this would be to have some function which could
1511   // give the time elapsed since startup, and simply have this object check that
1512   // when asked to initialize itself, but this doesn't seem to exist.
1513   //
1514   // This can't be created in the BrowserProcessImpl constructor because it
1515   // needs to read prefs that get set after that runs.
1516   browser_process_->intranet_redirect_detector();
1517 #endif
1518 
1519 #if BUILDFLAG(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
1520   if (parsed_command_line().HasSwitch(switches::kDebugPrint)) {
1521     base::FilePath path =
1522         parsed_command_line().GetSwitchValuePath(switches::kDebugPrint);
1523     if (!path.empty())
1524       printing::PrintedDocument::SetDebugDumpPath(path);
1525   }
1526 #endif  // BUILDFLAG(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
1527 
1528 #if BUILDFLAG(ENABLE_PRINT_PREVIEW) && defined(OS_WIN)
1529   printing::SetGetDisplayNameFunction(&printing::GetUserFriendlyName);
1530 #endif
1531 
1532   HandleTestParameters(parsed_command_line());
1533   browser_process_->metrics_service()->RecordBreakpadHasDebugger(
1534       base::debug::BeingDebugged());
1535 
1536   language_usage_metrics::LanguageUsageMetrics::RecordAcceptLanguages(
1537       profile_->GetPrefs()->GetString(language::prefs::kAcceptLanguages));
1538   language_usage_metrics::LanguageUsageMetrics::RecordApplicationLanguage(
1539       browser_process_->GetApplicationLocale());
1540 // On ChromeOS results in a crash. https://crbug.com/1151558
1541 #if !defined(OS_CHROMEOS)
1542   language_usage_metrics::LanguageUsageMetrics::RecordPageLanguages(
1543       *UrlLanguageHistogramFactory::GetForBrowserContext(profile_));
1544 #endif  // defined(OS_CHROMEOS)
1545 
1546 // On mobile, need for clean shutdown arises only when the application comes
1547 // to foreground (i.e. MetricsService::OnAppEnterForeground is called).
1548 // http://crbug.com/179143
1549 #if !defined(OS_ANDROID)
1550   // Start watching for a hang.
1551   browser_process_->metrics_service()->LogNeedForCleanShutdown();
1552 #endif  // !defined(OS_ANDROID)
1553 
1554 #if BUILDFLAG(ENABLE_PRINT_PREVIEW) && !defined(OS_CHROMEOS)
1555   // Create the instance of the cloud print proxy service so that it can launch
1556   // the service process if needed. This is needed because the service process
1557   // might have shutdown because an update was available.
1558   // TODO(torne): this should maybe be done with
1559   // BrowserContextKeyedServiceFactory::ServiceIsCreatedWithBrowserContext()
1560   // instead?
1561   CloudPrintProxyServiceFactory::GetForProfile(profile_);
1562 #endif
1563 
1564   // Two different types of hang detection cannot run at the same time or they
1565   // would interfere with each other.
1566   if (!base::HangWatcher::IsEnabled()) {
1567     // Start watching all browser threads for responsiveness.
1568     ThreadWatcherList::StartWatchingAll(parsed_command_line());
1569   }
1570 
1571   // This has to come before the first GetInstance() call. PreBrowserStart()
1572   // seems like a reasonable place to put this, except on Android,
1573   // OfflinePageInfoHandler::Register() below calls GetInstance().
1574   // TODO(thestig): See if the Android code below can be moved to later.
1575   sessions::ContentSerializedNavigationDriver::SetInstance(
1576       ChromeSerializedNavigationDriver::GetInstance());
1577 
1578 #if defined(OS_ANDROID)
1579   ThreadWatcherAndroid::RegisterApplicationStatusListener();
1580 #endif  // defined(OS_ANDROID)
1581 
1582 #if BUILDFLAG(ENABLE_OFFLINE_PAGES)
1583   offline_pages::OfflinePageInfoHandler::Register();
1584 #endif
1585 
1586 #if BUILDFLAG(ENABLE_NACL)
1587   content::GetIOThreadTaskRunner({})->PostTask(
1588       FROM_HERE, base::BindOnce(nacl::NaClProcessHost::EarlyStartup));
1589 #endif  // BUILDFLAG(ENABLE_NACL)
1590 
1591   // Make sure initial prefs are recorded
1592   PrefMetricsService::Factory::GetForProfile(profile_);
1593 
1594   PreBrowserStart();
1595 
1596   if (!parsed_command_line().HasSwitch(switches::kDisableComponentUpdate)) {
1597     component_updater::RegisterComponentsForUpdate(profile_->IsOffTheRecord(),
1598                                                    profile_->GetPrefs());
1599   }
1600 
1601   variations::VariationsService* variations_service =
1602       browser_process_->variations_service();
1603   if (should_call_pre_main_loop_start_startup_on_variations_service_)
1604     variations_service->PerformPreMainMessageLoopStartup();
1605 
1606 #if defined(OS_ANDROID)
1607   // Just initialize the policy prefs service here. Variations seed fetching
1608   // will be initialized when the app enters foreground mode.
1609   variations_service->set_policy_pref_service(profile_->GetPrefs());
1610 
1611 #else
1612   // We are in regular browser boot sequence. Open initial tabs and enter the
1613   // main message loop.
1614   std::vector<Profile*> last_opened_profiles;
1615 #if !defined(OS_CHROMEOS)
1616   // On ChromeOS multiple profiles doesn't apply, and will break if we load
1617   // them this early as the cryptohome hasn't yet been mounted (which happens
1618   // only once we log in).
1619   last_opened_profiles =
1620       g_browser_process->profile_manager()->GetLastOpenedProfiles();
1621 #endif  // defined(OS_CHROMEOS)
1622 
1623   // This step is costly and is already measured in
1624   // Startup.StartupBrowserCreator_Start.
1625   // See the comment above for an explanation of |process_command_line|.
1626   const bool started =
1627       !process_command_line ||
1628       browser_creator_->Start(parsed_command_line(), base::FilePath(), profile_,
1629                               last_opened_profiles);
1630   if (started) {
1631 #if defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
1632     // Initialize autoupdate timer. Timer callback costs basically nothing
1633     // when browser is not in persistent mode, so it's OK to let it ride on
1634     // the main thread. This needs to be done here because we don't want
1635     // to start the timer when Chrome is run inside a test harness.
1636     browser_process_->StartAutoupdateTimer();
1637 #endif  // defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
1638 
1639 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
1640     // On Linux, the running exe will be updated if an upgrade becomes
1641     // available while the browser is running.  We need to save the last
1642     // modified time of the exe, so we can compare to determine if there is
1643     // an upgrade while the browser is kept alive by a persistent extension.
1644     upgrade_util::SaveLastModifiedTimeOfExe();
1645 #endif  // defined(OS_LINUX) && !defined(OS_CHROMEOS)
1646 
1647     // Record now as the last successful chrome start.
1648     if (ShouldRecordActiveUse(parsed_command_line()))
1649       GoogleUpdateSettings::SetLastRunTime();
1650 
1651 #if defined(OS_MAC)
1652     // Call Recycle() here as late as possible, before going into the loop
1653     // because Start() will add things to it while creating the main window.
1654     if (parameters().autorelease_pool)
1655       parameters().autorelease_pool->Recycle();
1656 #endif  // defined(OS_MAC)
1657 
1658     // Transfer ownership of the browser's lifetime to the BrowserProcess.
1659     browser_process_->SetQuitClosure(g_run_loop->QuitWhenIdleClosure());
1660     DCHECK(!run_message_loop_);
1661     run_message_loop_ = true;
1662   }
1663   browser_creator_.reset();
1664 #endif  // !defined(OS_ANDROID)
1665 
1666   PostBrowserStart();
1667 
1668   // The ui_task can be injected by tests to replace the main message loop.
1669   // In that case we Run() it here, and set a flag to avoid running the main
1670   // message loop later, as the test will do so as needed from the |ui_task|.
1671   if (parameters().ui_task) {
1672     std::move(*parameters().ui_task).Run();
1673     delete parameters().ui_task;
1674     run_message_loop_ = false;
1675   }
1676 
1677 #if BUILDFLAG(ENABLE_DOWNGRADE_PROCESSING)
1678   // Clean up old user data directory, snapshots and disk cache directory.
1679   downgrade_manager_.DeleteMovedUserDataSoon(user_data_dir_);
1680 #endif
1681 
1682 #if defined(OS_ANDROID)
1683   // We never run the C++ main loop on Android, since the UI thread message
1684   // loop is controlled by the OS, so this is as close as we can get to
1685   // the start of the main loop.
1686   if (result_code_ <= 0) {
1687     RecordBrowserStartupTime();
1688   }
1689 #endif  // defined(OS_ANDROID)
1690 
1691   return result_code_;
1692 }
1693 
MainMessageLoopRun(int * result_code)1694 bool ChromeBrowserMainParts::MainMessageLoopRun(int* result_code) {
1695   // Trace the entry and exit of this method. We don't use the TRACE_EVENT0
1696   // macro because the tracing infrastructure doesn't expect a synchronous event
1697   // around the main loop of a thread.
1698   ScopedMainMessageLoopRunEvent scoped_main_message_loop_run_event;
1699 #if defined(OS_ANDROID)
1700   // Chrome on Android does not use default MessageLoop. It has its own
1701   // Android specific MessageLoop
1702   NOTREACHED();
1703   return true;
1704 #else
1705   // Set the result code set in PreMainMessageLoopRun or set above.
1706   *result_code = result_code_;
1707   if (!run_message_loop_)
1708     return true;  // Don't run the default message loop.
1709 
1710   // These should be invoked as close to the start of the browser's
1711   // UI thread message loop as possible to get a stable measurement
1712   // across versions.
1713   RecordBrowserStartupTime();
1714 
1715   DCHECK(base::CurrentUIThread::IsSet());
1716 
1717   performance_monitor::ProcessMonitor::GetInstance()->StartGatherCycle();
1718 
1719   g_run_loop->Run();
1720 
1721   return true;
1722 #endif  // defined(OS_ANDROID)
1723 }
1724 
PostMainMessageLoopRun()1725 void ChromeBrowserMainParts::PostMainMessageLoopRun() {
1726   TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopRun");
1727 #if defined(OS_ANDROID)
1728   // Chrome on Android does not use default MessageLoop. It has its own
1729   // Android specific MessageLoop
1730   NOTREACHED();
1731 #else
1732   // Shutdown the UpgradeDetector here before ChromeBrowserMainPartsChromeos
1733   // disconnects DBus services in its PostDestroyThreads.
1734   UpgradeDetector::GetInstance()->Shutdown();
1735 
1736   // Start watching for jank during shutdown. It gets disarmed when
1737   // |shutdown_watcher_| object is destructed.
1738   shutdown_watcher_->Arm(base::TimeDelta::FromSeconds(300));
1739 
1740   web_usb_detector_.reset();
1741 
1742   for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1743     chrome_extra_parts_[i]->PostMainMessageLoopRun();
1744 
1745   // Some tests don't set parameters.ui_task, so they started translate
1746   // language fetch that was never completed so we need to cleanup here
1747   // otherwise it will be done by the destructor in a wrong thread.
1748   TranslateService::Shutdown(!parameters().ui_task);
1749 
1750   if (notify_result_ == ProcessSingleton::PROCESS_NONE)
1751     process_singleton_->Cleanup();
1752 
1753   // Stop all tasks that might run on WatchDogThread.
1754   ThreadWatcherList::StopWatchingAll();
1755 
1756   browser_process_->metrics_service()->Stop();
1757 
1758   restart_last_session_ = browser_shutdown::ShutdownPreThreadsStop();
1759   browser_process_->StartTearDown();
1760 #endif  // defined(OS_ANDROID)
1761 }
1762 
PostDestroyThreads()1763 void ChromeBrowserMainParts::PostDestroyThreads() {
1764 #if defined(OS_ANDROID)
1765   // On Android, there is no quit/exit. So the browser's main message loop will
1766   // not finish.
1767   NOTREACHED();
1768 #else
1769   browser_shutdown::RestartMode restart_mode =
1770       browser_shutdown::RestartMode::kNoRestart;
1771 
1772   if (restart_last_session_) {
1773     restart_mode = browser_shutdown::RestartMode::kRestartLastSession;
1774 
1775 #if BUILDFLAG(ENABLE_BACKGROUND_MODE)
1776     if (BackgroundModeManager::should_restart_in_background())
1777       restart_mode = browser_shutdown::RestartMode::kRestartInBackground;
1778 #endif  // BUILDFLAG(ENABLE_BACKGROUND_MODE)
1779   }
1780 
1781   browser_process_->PostDestroyThreads();
1782   // browser_shutdown takes care of deleting browser_process, so we need to
1783   // release it.
1784   ignore_result(browser_process_.release());
1785 
1786 #if BUILDFLAG(ENABLE_DOWNGRADE_PROCESSING)
1787   if (result_code_ == chrome::RESULT_CODE_DOWNGRADE_AND_RELAUNCH) {
1788     // Process a pending User Data downgrade before restarting.
1789     downgrade_manager_.ProcessDowngrade(user_data_dir_);
1790 
1791     // It's impossible for there to also be a user-driven relaunch since the
1792     // browser never fully starts in this case.
1793     DCHECK(!restart_last_session_);
1794     restart_mode = browser_shutdown::RestartMode::kRestartThisSession;
1795   }
1796 #endif  // BUILDFLAG(ENABLE_DOWNGRADE_PROCESSING)
1797 
1798   browser_shutdown::ShutdownPostThreadsStop(restart_mode);
1799 
1800 #if !defined(OS_CHROMEOS)
1801   master_prefs_.reset();
1802 #endif  // !defined(OS_CHROMEOS)
1803 
1804   process_singleton_.reset();
1805   device_event_log::Shutdown();
1806 
1807   // We need to do this check as late as possible, but due to modularity, this
1808   // may be the last point in Chrome.  This would be more effective if done at
1809   // a higher level on the stack, so that it is impossible for an early return
1810   // to bypass this code.  Perhaps we need a *final* hook that is called on all
1811   // paths from content/browser/browser_main.
1812   CHECK(metrics::MetricsService::UmaMetricsProperlyShutdown());
1813 
1814 #if defined(OS_CHROMEOS)
1815   arc::StabilityMetricsManager::Shutdown();
1816   chromeos::StatsReportingController::Shutdown();
1817   chromeos::CrosSettings::Shutdown();
1818 #endif  // defined(OS_CHROMEOS)
1819 #endif  // defined(OS_ANDROID)
1820 }
1821 
1822 // Public members:
1823 
AddParts(std::unique_ptr<ChromeBrowserMainExtraParts> parts)1824 void ChromeBrowserMainParts::AddParts(
1825     std::unique_ptr<ChromeBrowserMainExtraParts> parts) {
1826   chrome_extra_parts_.push_back(std::move(parts));
1827 }
1828 
1829 #if !defined(OS_ANDROID)
1830 // static
TakeRunLoopForTest()1831 std::unique_ptr<base::RunLoop> ChromeBrowserMainParts::TakeRunLoopForTest() {
1832   auto run_loop = base::WrapUnique<base::RunLoop>(g_run_loop);
1833   g_run_loop = nullptr;
1834   return run_loop;
1835 }
1836 #endif
1837