1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/chrome_browser_main_win.h"
7 // windows.h must be included before shellapi.h
19 #include "base/base_switches.h"
20 #include "base/command_line.h"
21 #include "base/dcheck_is_on.h"
22 #include "base/enterprise_util.h"
23 #include "base/environment.h"
24 #include "base/feature_list.h"
25 #include "base/files/file_path.h"
26 #include "base/files/file_util.h"
27 #include "base/files/important_file_writer_cleaner.h"
28 #include "base/functional/bind.h"
29 #include "base/functional/callback_helpers.h"
30 #include "base/i18n/rtl.h"
31 #include "base/location.h"
32 #include "base/no_destructor.h"
33 #include "base/path_service.h"
34 #include "base/scoped_native_library.h"
35 #include "base/strings/string_number_conversions.h"
36 #include "base/strings/utf_string_conversions.h"
37 #include "base/task/sequenced_task_runner.h"
38 #include "base/task/thread_pool.h"
39 #include "base/trace_event/base_tracing.h"
40 #include "base/version.h"
41 #include "base/win/pe_image.h"
42 #include "base/win/registry.h"
43 #include "base/win/win_util.h"
44 #include "base/win/wrapped_window_proc.h"
45 #include "build/branding_buildflags.h"
46 #include "build/build_config.h"
47 #include "chrome/browser/about_flags.h"
48 #include "chrome/browser/browser_features.h"
49 #include "chrome/browser/browser_process.h"
50 #include "chrome/browser/enterprise/browser_management/management_service_factory.h"
51 #include "chrome/browser/enterprise/platform_auth/platform_auth_policy_observer.h"
52 #include "chrome/browser/first_run/first_run.h"
53 #include "chrome/browser/os_crypt/app_bound_encryption_metrics_win.h"
54 #include "chrome/browser/profiles/profile_manager.h"
55 #include "chrome/browser/profiles/profile_shortcut_manager.h"
56 #include "chrome/browser/shell_integration_win.h"
57 #include "chrome/browser/ui/accessibility_util.h"
58 #include "chrome/browser/ui/simple_message_box.h"
59 #include "chrome/browser/ui/uninstall_browser_prompt.h"
60 #include "chrome/browser/web_applications/chrome_pwa_launcher/last_browser_file_util.h"
61 #include "chrome/browser/web_applications/chrome_pwa_launcher/launcher_log_reporter.h"
62 #include "chrome/browser/web_applications/chrome_pwa_launcher/launcher_update.h"
63 #include "chrome/browser/web_applications/os_integration/web_app_handler_registration_utils_win.h"
64 #include "chrome/browser/web_applications/os_integration/web_app_shortcut.h"
65 #include "chrome/browser/web_applications/web_app_provider.h"
66 #include "chrome/browser/web_applications/web_app_registrar.h"
67 #include "chrome/browser/win/browser_util.h"
68 #include "chrome/browser/win/chrome_elf_init.h"
69 #include "chrome/browser/win/conflicts/enumerate_input_method_editors.h"
70 #include "chrome/browser/win/conflicts/enumerate_shell_extensions.h"
71 #include "chrome/browser/win/conflicts/module_database.h"
72 #include "chrome/browser/win/conflicts/module_event_sink_impl.h"
73 #include "chrome/browser/win/util_win_service.h"
74 #include "chrome/common/channel_info.h"
75 #include "chrome/common/chrome_constants.h"
76 #include "chrome/common/chrome_paths.h"
77 #include "chrome/common/chrome_result_codes.h"
78 #include "chrome/common/chrome_switches.h"
79 #include "chrome/common/conflicts/module_watcher_win.h"
80 #include "chrome/common/crash_keys.h"
81 #include "chrome/common/env_vars.h"
82 #include "chrome/common/pref_names.h"
83 #include "chrome/grit/branded_strings.h"
84 #include "chrome/grit/generated_resources.h"
85 #include "chrome/install_static/install_details.h"
86 #include "chrome/installer/util/helper.h"
87 #include "chrome/installer/util/install_util.h"
88 #include "chrome/installer/util/installer_util_strings.h"
89 #include "chrome/installer/util/l10n_string_util.h"
90 #include "chrome/installer/util/shell_util.h"
91 #include "chrome/installer/util/util_constants.h"
92 #include "components/crash/core/app/crash_export_thunks.h"
93 #include "components/crash/core/app/dump_hung_process_with_ptype.h"
94 #include "components/crash/core/common/crash_key.h"
95 #include "components/os_crypt/sync/os_crypt.h"
96 #include "components/policy/core/common/management/management_service.h"
97 #include "components/prefs/pref_service.h"
98 #include "components/version_info/channel.h"
99 #include "components/version_info/version_info.h"
100 #include "components/webapps/common/web_app_id.h"
101 #include "content/public/browser/browser_task_traits.h"
102 #include "content/public/browser/browser_thread.h"
103 #include "content/public/browser/render_process_host.h"
104 #include "content/public/common/content_switches.h"
105 #include "content/public/common/main_function_params.h"
106 #include "ui/base/l10n/l10n_util.h"
107 #include "ui/base/l10n/l10n_util_win.h"
108 #include "ui/base/ui_base_switches.h"
109 #include "ui/base/win/hidden_window.h"
110 #include "ui/base/win/message_box_win.h"
111 #include "ui/gfx/switches.h"
112 #include "ui/gfx/system_fonts_win.h"
113 #include "ui/gfx/win/crash_id_helper.h"
114 #include "ui/strings/grit/app_locale_settings.h"
116 #if BUILDFLAG(GOOGLE_CHROME_BRANDING)
117 #include "chrome/browser/win/conflicts/third_party_conflicts_manager.h"
122 typedef HRESULT (STDAPICALLTYPE* RegisterApplicationRestartProc)(
123 const wchar_t* command_line,
126 void InitializeWindowProcExceptions() {
127 base::win::WinProcExceptionFilter exception_filter =
128 base::win::SetWinProcExceptionFilter(&CrashForException_ExportThunk);
129 DCHECK(!exception_filter);
132 // TODO(siggi): Remove once https://crbug.com/806661 is resolved.
133 void DumpHungRendererProcessImpl(const base::Process& renderer) {
134 // Use a distinguishing process type for these reports.
135 crash_reporter::DumpHungProcessWithPtype(renderer, "hung-renderer");
138 int GetMinimumFontSize() {
140 base::StringToInt(l10n_util::GetStringUTF16(IDS_MINIMUM_UI_FONT_SIZE),
142 return min_font_size;
145 class TranslationDelegate : public installer::TranslationDelegate {
147 std::wstring GetLocalizedString(int installer_string_id) override;
150 void DelayedRecordProcessorMetrics() {
151 mojo::Remote<chrome::mojom::ProcessorMetrics> remote_util_win =
152 LaunchProcessorMetricsService();
153 auto* remote_util_win_ptr = remote_util_win.get();
154 remote_util_win_ptr->RecordProcessorMetrics(
155 base::DoNothingWithBoundArgs(std::move(remote_util_win)));
158 // Initializes the ModuleDatabase on its owning sequence. Also starts the
159 // enumeration of registered modules in the Windows Registry.
160 void InitializeModuleDatabase(
161 bool is_third_party_blocking_policy_enabled) {
162 DCHECK(ModuleDatabase::GetTaskRunner()->RunsTasksInCurrentSequence());
164 ModuleDatabase::SetInstance(
165 std::make_unique<ModuleDatabase>(is_third_party_blocking_policy_enabled));
167 auto* module_database = ModuleDatabase::GetInstance();
168 module_database->StartDrainingModuleLoadAttemptsLog();
170 // Enumerate shell extensions and input method editors. It is safe to use
171 // base::Unretained() here because the ModuleDatabase is never freed.
172 EnumerateShellExtensions(
173 base::BindRepeating(&ModuleDatabase::OnShellExtensionEnumerated,
174 base::Unretained(module_database)),
175 base::BindOnce(&ModuleDatabase::OnShellExtensionEnumerationFinished,
176 base::Unretained(module_database)));
177 EnumerateInputMethodEditors(
178 base::BindRepeating(&ModuleDatabase::OnImeEnumerated,
179 base::Unretained(module_database)),
180 base::BindOnce(&ModuleDatabase::OnImeEnumerationFinished,
181 base::Unretained(module_database)));
184 // Notes on the OnModuleEvent() callback.
186 // The ModuleDatabase uses the TimeDateStamp value of the DLL to uniquely
187 // identify modules as they are discovered. Unlike the SizeOfImage, this value
188 // isn't provided via LdrDllNotification events or CreateToolhelp32Snapshot().
190 // The easiest way to obtain the TimeDateStamp is to read the mapped module in
191 // memory. Unfortunately, this could cause an ACCESS_VIOLATION_EXCEPTION if the
192 // module is unloaded before being accessed. This can occur when enumerating
193 // already loaded modules with CreateToolhelp32Snapshot(). Note that this
194 // problem doesn't affect LdrDllNotification events, where it is guaranteed that
195 // the module stays in memory for the duration of the callback.
197 // To get around this, there are multiple solutions:
198 // (1) Read the file on disk instead.
199 // Sidesteps the problem altogether. The drawback is that it must be done on
200 // a sequence that allow blocking IO, and it is way slower. We don't want to
201 // pay that price for each module in the process. This can fail if the file
202 // can not be found when attemping to read it.
204 // (2) Increase the reference count of the module.
205 // Calling ::LoadLibraryEx() or ::GetModuleHandleEx() lets us ensure that
206 // the module won't go away while we hold the extra handle. It's still
207 // possible that the module was unloaded before we have a chance to increase
208 // the reference count, which would mean either reloading the DLL, or
209 // failing to get a new handle.
211 // This isn't ideal but the worst that can happen is that we hold the last
212 // reference to the module. The DLL would be unloaded on our thread when
213 // ::FreeLibrary() is called. This could go horribly wrong if the DLL's
214 // creator didn't consider this possibility.
216 // (3) Do it in a Structured Exception Handler (SEH)
217 // Make the read inside a __try/__except handler and handle the possible
218 // ACCESS_VIOLATION_EXCEPTION if it happens.
220 // The current solution is (3) with a fallback that uses (1). In the rare case
221 // that both fail to get the TimeDateStamp, the module load event is dropped
222 // altogether, as our best effort was unsuccessful.
224 // Gets the TimeDateStamp from the file on disk and, if successful, sends the
225 // load event to the ModuleDatabase.
226 void HandleModuleLoadEventWithoutTimeDateStamp(
227 const base::FilePath& module_path,
228 size_t module_size) {
229 uint32_t size_of_image = 0;
230 uint32_t time_date_stamp = 0;
231 bool got_time_date_stamp = GetModuleImageSizeAndTimeDateStamp(
232 module_path, &size_of_image, &time_date_stamp);
234 // Simple sanity check.
235 got_time_date_stamp = got_time_date_stamp && size_of_image == module_size;
237 // Drop the load event if it's not possible to get the time date stamp.
238 if (!got_time_date_stamp)
241 ModuleDatabase::HandleModuleLoadEvent(
242 content::PROCESS_TYPE_BROWSER, module_path, module_size, time_date_stamp);
245 // Helper function for getting the module size associated with a module in this
246 // process based on its load address.
247 uint32_t GetModuleSizeOfImage(const void* module_load_address) {
248 base::win::PEImage pe_image(module_load_address);
249 return pe_image.GetNTHeaders()->OptionalHeader.SizeOfImage;
252 // Helper function for getting the time date stamp associated with a module in
253 // this process based on its load address.
254 uint32_t GetModuleTimeDateStamp(const void* module_load_address) {
255 base::win::PEImage pe_image(module_load_address);
256 return pe_image.GetNTHeaders()->FileHeader.TimeDateStamp;
259 // An exception filter for handling Access Violation exceptions within the
260 // memory range [module_load_address, module_load_address + size_of_image).
261 DWORD FilterAccessViolation(DWORD exception_code,
262 const EXCEPTION_POINTERS* exception_information,
263 void* module_load_address,
264 uint32_t size_of_image) {
265 if (exception_code != EXCEPTION_ACCESS_VIOLATION)
266 return EXCEPTION_CONTINUE_SEARCH;
268 // To make sure an unrelated exception is not swallowed by the exception
269 // handler, the address where the exception happened is verified.
270 const EXCEPTION_RECORD* exception_record =
271 exception_information->ExceptionRecord;
272 const DWORD access_violation_address =
273 exception_record->ExceptionInformation[1];
275 uintptr_t range_start = reinterpret_cast<uintptr_t>(module_load_address);
276 uintptr_t range_end = range_start + size_of_image;
277 if (range_start > access_violation_address ||
278 range_end <= access_violation_address) {
279 return EXCEPTION_CONTINUE_SEARCH;
282 return EXCEPTION_EXECUTE_HANDLER;
285 // Wrapper around GetModuleTimeDateStamp that handles a potential
286 // EXCEPTION_ACCESS_VIOLATION that can happen if the |module_load_address| is
287 // accessed after the module is unloaded. Also ensures that the expected module
288 // is loaded at this address.
289 bool TryGetModuleTimeDateStamp(void* module_load_address,
290 const base::FilePath& module_path,
291 uint32_t size_of_image,
292 uint32_t* time_date_stamp) {
294 // Make sure it's the correct module, to protect against a potential race
295 // where a new module was loaded at the same address. This is safe because
296 // the only possibles races are either there was a module loaded at
297 // |module_load_address| and it was unloaded, or there was no module loaded
298 // at |module_load_address| and a new one took its place.
299 wchar_t module_file_name[MAX_PATH];
301 ::GetModuleFileName(reinterpret_cast<HMODULE>(module_load_address),
302 module_file_name, ARRAYSIZE(module_file_name));
303 if (!size || !base::FilePath::CompareEqualIgnoreCase(module_path.value(),
307 if (size_of_image != GetModuleSizeOfImage(module_load_address))
310 *time_date_stamp = GetModuleTimeDateStamp(module_load_address);
311 } __except(FilterAccessViolation(GetExceptionCode(),
312 GetExceptionInformation(),
313 module_load_address, size_of_image)) {
319 void ShowCloseBrowserFirstMessageBox() {
320 chrome::ShowWarningMessageBox(
321 nullptr, l10n_util::GetStringUTF16(IDS_PRODUCT_NAME),
322 l10n_util::GetStringUTF16(IDS_UNINSTALL_CLOSE_APP));
325 // Updates all Progressive Web App launchers in |profile_dir| to the latest
327 void UpdatePwaLaunchersForProfile(const base::FilePath& profile_dir) {
328 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
330 g_browser_process->profile_manager()->GetProfileByPath(profile_dir);
332 // The profile was unloaded.
335 auto* provider = web_app::WebAppProvider::GetForWebApps(profile);
338 web_app::WebAppRegistrar& registrar = provider->registrar_unsafe();
340 // Create a vector of all PWA-launcher paths in |profile_dir|.
341 std::vector<base::FilePath> pwa_launcher_paths;
342 for (const webapps::AppId& app_id : registrar.GetAppIds()) {
343 base::FilePath web_app_path =
344 web_app::GetOsIntegrationResourcesDirectoryForApp(profile_dir, app_id,
346 web_app_path = web_app_path.Append(web_app::GetAppSpecificLauncherFilename(
347 base::UTF8ToWide(registrar.GetAppShortName(app_id))));
348 pwa_launcher_paths.push_back(std::move(web_app_path));
351 base::ThreadPool::PostTask(
353 {base::TaskPriority::BEST_EFFORT,
354 base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN, base::MayBlock()},
355 base::BindOnce(&web_app::UpdatePwaLaunchers,
356 std::move(pwa_launcher_paths)));
359 void MigratePinnedTaskBarShortcutsIfNeeded() {
360 // Update this number when users should go through a taskbar shortcut
361 // migration again. The last reason to do this was crrev.com/798174. @
364 // Note: If shortcut updates need to be done once after a future OS upgrade,
365 // that should be done by re-versioning Active Setup (see //chrome/installer
366 // and https://crbug.com/577697 for details).
367 const base::Version kLastVersionNeedingMigration({86, 0, 4231, 0});
369 PrefService* local_state = g_browser_process->local_state();
371 const base::Version last_version_migrated(
372 local_state->GetString(prefs::kShortcutMigrationVersion));
373 if (!last_version_migrated.IsValid() ||
374 last_version_migrated < kLastVersionNeedingMigration) {
375 shell_integration::win::MigrateTaskbarPins(
376 base::BindOnce(&PrefService::SetString, base::Unretained(local_state),
377 prefs::kShortcutMigrationVersion,
378 std::string(version_info::GetVersionNumber())));
382 // This error message is not localized because we failed to load the
383 // localization data files.
384 const char kMissingLocaleDataTitle[] = "Missing File Error";
386 // TODO(http://crbug.com/338969): This should be used on Linux Aura as well.
387 const char kMissingLocaleDataMessage[] =
388 "Unable to find locale data files. Please reinstall.";
392 int DoUninstallTasks(bool chrome_still_running) {
393 // We want to show a warning to user (and exit) if Chrome is already running
394 // *before* we show the uninstall confirmation dialog box. But while the
395 // uninstall confirmation dialog is up, user might start Chrome, so we
396 // check once again after user acknowledges Uninstall dialog.
397 if (chrome_still_running) {
398 ShowCloseBrowserFirstMessageBox();
399 return chrome::RESULT_CODE_UNINSTALL_CHROME_ALIVE;
401 int result = chrome::ShowUninstallBrowserPrompt();
402 if (browser_util::IsBrowserAlreadyRunning()) {
403 ShowCloseBrowserFirstMessageBox();
404 return chrome::RESULT_CODE_UNINSTALL_CHROME_ALIVE;
407 if (result != chrome::RESULT_CODE_UNINSTALL_USER_CANCEL) {
408 // The following actions are just best effort.
409 VLOG(1) << "Executing uninstall actions";
410 // Remove shortcuts targeting chrome.exe or chrome_proxy.exe.
411 base::FilePath install_dir;
412 if (base::PathService::Get(base::DIR_EXE, &install_dir)) {
413 std::vector<base::FilePath> shortcut_targets{
414 install_dir.Append(installer::kChromeExe),
415 install_dir.Append(installer::kChromeProxyExe)};
416 ShellUtil::RemoveAllShortcuts(ShellUtil::CURRENT_USER, shortcut_targets);
423 // ChromeBrowserMainPartsWin ---------------------------------------------------
425 ChromeBrowserMainPartsWin::ChromeBrowserMainPartsWin(bool is_integration_test,
426 StartupData* startup_data)
427 : ChromeBrowserMainParts(is_integration_test, startup_data) {}
429 ChromeBrowserMainPartsWin::~ChromeBrowserMainPartsWin() = default;
431 void ChromeBrowserMainPartsWin::ToolkitInitialized() {
432 DCHECK_NE(base::PlatformThread::CurrentId(), base::kInvalidThreadId);
433 gfx::CrashIdHelper::RegisterMainThread(base::PlatformThread::CurrentId());
434 ChromeBrowserMainParts::ToolkitInitialized();
435 gfx::win::SetAdjustFontCallback(&l10n_util::AdjustUiFont);
436 gfx::win::SetGetMinimumFontSizeCallback(&GetMinimumFontSize);
439 void ChromeBrowserMainPartsWin::PreCreateMainMessageLoop() {
440 // installer_util references strings that are normally compiled into
441 // setup.exe. In Chrome, these strings are in the locale files.
442 SetupInstallerUtilStrings();
444 PrefService* local_state = g_browser_process->local_state();
447 // Initialize the OSCrypt.
448 bool os_crypt_init = OSCrypt::Init(local_state);
449 DCHECK(os_crypt_init);
451 base::SetExtraNoExecuteAllowedPath(chrome::DIR_USER_DATA);
453 ChromeBrowserMainParts::PreCreateMainMessageLoop();
454 if (!is_integration_test()) {
455 // Make sure that we know how to handle exceptions from the message loop.
456 InitializeWindowProcExceptions();
460 int ChromeBrowserMainPartsWin::PreCreateThreads() {
461 // Record whether the machine is enterprise managed in a crash key. This will
462 // be used to better identify whether crashes are from enterprise users.
463 static crash_reporter::CrashKeyString<4> is_enterprise_managed(
464 "is-enterprise-managed");
465 is_enterprise_managed.Set(
466 policy::ManagementServiceFactory::GetForPlatform()
467 ->GetManagementAuthorityTrustworthiness() >=
468 policy::ManagementAuthorityTrustworthiness::TRUSTED
472 // Set crash keys containing the registry values used to determine Chrome's
473 // update channel at process startup; see https://crbug.com/579504.
474 const auto& details = install_static::InstallDetails::Get();
476 static crash_reporter::CrashKeyString<50> ap_value("ap");
477 ap_value.Set(base::WideToUTF8(details.update_ap()));
479 static crash_reporter::CrashKeyString<32> update_cohort_name("cohort-name");
480 update_cohort_name.Set(base::WideToUTF8(details.update_cohort_name()));
482 if (chrome::GetChannel() == version_info::Channel::CANARY) {
483 content::RenderProcessHost::SetHungRendererAnalysisFunction(
484 &DumpHungRendererProcessImpl);
487 return ChromeBrowserMainParts::PreCreateThreads();
490 void ChromeBrowserMainPartsWin::PostMainMessageLoopRun() {
491 base::ImportantFileWriterCleaner::GetInstance().Stop();
493 // The `ProfileManager` has been destroyed, so no new platform authentication
494 // requests will be created.
495 platform_auth_policy_observer_.reset();
497 ChromeBrowserMainParts::PostMainMessageLoopRun();
500 void ChromeBrowserMainPartsWin::ShowMissingLocaleMessageBox() {
501 ui::MessageBox(NULL, base::ASCIIToWide(kMissingLocaleDataMessage),
502 base::ASCIIToWide(kMissingLocaleDataTitle),
503 MB_OK | MB_ICONERROR | MB_TOPMOST);
506 void ChromeBrowserMainPartsWin::PreProfileInit() {
507 ChromeBrowserMainParts::PreProfileInit();
509 // Create the module database and hook up the in-process module watcher. This
510 // needs to be done before any child processes are initialized as the
511 // `ModuleDatabase` is an endpoint for IPC from child processes.
512 SetupModuleDatabase(&module_watcher_);
514 // Start up the platform auth SSO policy observer.
515 PrefService* const local_state = g_browser_process->local_state();
517 platform_auth_policy_observer_ =
518 std::make_unique<PlatformAuthPolicyObserver>(local_state);
521 void ChromeBrowserMainPartsWin::PostProfileInit(Profile* profile,
522 bool is_initial_profile) {
523 ChromeBrowserMainParts::PostProfileInit(profile, is_initial_profile);
525 // The setup below is intended to run for only the initial profile.
526 if (!is_initial_profile)
529 // If Chrome was launched by a Progressive Web App launcher that needs to be
530 // updated, update all launchers for this profile.
531 if (base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kAppId) &&
532 base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
533 switches::kPwaLauncherVersion) != chrome::kChromeVersion) {
534 content::BrowserThread::PostBestEffortTask(
535 FROM_HERE, base::SequencedTaskRunner::GetCurrentDefault(),
536 base::BindOnce(&UpdatePwaLaunchersForProfile, profile->GetPath()));
540 void ChromeBrowserMainPartsWin::PostBrowserStart() {
541 ChromeBrowserMainParts::PostBrowserStart();
543 // Verify that the delay load helper hooks are in place. This cannot be tested
544 // from unit tests, so rely on this failing here.
545 DCHECK(__pfnDliFailureHook2);
547 InitializeChromeElf();
549 // Query feature first, to include full population in field trial.
550 if (base::FeatureList::IsEnabled(features::kAppBoundEncryptionMetrics) &&
551 install_static::IsSystemInstall()) {
552 os_crypt::MeasureAppBoundEncryptionStatus(g_browser_process->local_state());
555 // Record Processor Metrics. This is very low priority, hence posting as
556 // BEST_EFFORT to start after Chrome startup has completed.
557 scoped_refptr<base::SequencedTaskRunner> task_runner =
558 base::ThreadPool::CreateSequencedTaskRunner(
559 {base::MayBlock(), base::TaskPriority::BEST_EFFORT});
560 task_runner->PostTask(FROM_HERE,
561 base::BindOnce(&DelayedRecordProcessorMetrics));
563 // Write current executable path to the User Data directory to inform
564 // Progressive Web App launchers, which run from within the User Data
565 // directory, which chrome.exe to launch from.
566 base::ThreadPool::PostTask(
567 FROM_HERE, {base::TaskPriority::BEST_EFFORT, base::MayBlock()},
568 base::BindOnce(&web_app::WriteChromePathToLastBrowserFile,
571 // Record the result of the latest Progressive Web App launcher launch.
572 base::ThreadPool::PostTask(
573 FROM_HERE, {base::TaskPriority::BEST_EFFORT, base::MayBlock()},
574 base::BindOnce(&web_app::RecordPwaLauncherResult));
576 // Possibly migrate pinned taskbar shortcuts.
577 content::GetUIThreadTaskRunner({base::TaskPriority::BEST_EFFORT})
578 ->PostTask(FROM_HERE,
579 base::BindOnce(&MigratePinnedTaskBarShortcutsIfNeeded));
581 // Send an accessibility announcement if this launch originated from the
583 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
584 switches::kFromInstaller)) {
585 AnnounceInActiveBrowser(l10n_util::GetStringUTF16(IDS_WELCOME_TO_CHROME));
588 base::ImportantFileWriterCleaner::GetInstance().Start();
592 void ChromeBrowserMainPartsWin::PrepareRestartOnCrashEnviroment(
593 const base::CommandLine& parsed_command_line) {
594 // Clear this var so child processes don't show the dialog by default.
595 std::unique_ptr<base::Environment> env(base::Environment::Create());
596 env->UnSetVar(env_vars::kShowRestart);
598 // For non-interactive tests we don't restart on crash.
599 if (env->HasVar(env_vars::kHeadless))
602 // If the known command-line test options are used we don't create the
603 // environment block which means we don't get the restart dialog.
604 if (parsed_command_line.HasSwitch(switches::kBrowserCrashTest) ||
605 parsed_command_line.HasSwitch(switches::kNoErrorDialogs))
608 // The encoding we use for the info is "title|context|direction" where
609 // direction is either env_vars::kRtlLocale or env_vars::kLtrLocale depending
610 // on the current locale.
611 std::u16string dlg_strings(
612 l10n_util::GetStringUTF16(IDS_CRASH_RECOVERY_TITLE));
613 dlg_strings.push_back('|');
614 std::u16string adjusted_string(
615 l10n_util::GetStringUTF16(IDS_CRASH_RECOVERY_CONTENT));
616 base::i18n::AdjustStringForLocaleDirection(&adjusted_string);
617 dlg_strings.append(adjusted_string);
618 dlg_strings.push_back('|');
619 dlg_strings.append(base::ASCIIToUTF16(
620 base::i18n::IsRTL() ? env_vars::kRtlLocale : env_vars::kLtrLocale));
622 env->SetVar(env_vars::kRestartInfo, base::UTF16ToUTF8(dlg_strings));
626 void ChromeBrowserMainPartsWin::RegisterApplicationRestart(
627 const base::CommandLine& parsed_command_line) {
628 base::ScopedNativeLibrary library(base::FilePath(L"kernel32.dll"));
629 // Get the function pointer for RegisterApplicationRestart.
630 RegisterApplicationRestartProc register_application_restart =
631 reinterpret_cast<RegisterApplicationRestartProc>(
632 library.GetFunctionPointer("RegisterApplicationRestart"));
633 if (!register_application_restart) {
634 LOG(WARNING) << "Cannot find RegisterApplicationRestart in kernel32.dll";
637 // Restart Chrome if the computer is restarted as the result of an update.
638 // This could be extended to handle crashes, hangs, and patches.
639 const auto command_line_string =
640 GetRestartCommandLine(parsed_command_line).GetCommandLineString();
641 HRESULT hr = register_application_restart(
642 command_line_string.c_str(),
643 RESTART_NO_CRASH | RESTART_NO_HANG | RESTART_NO_PATCH);
645 if (hr == E_INVALIDARG) {
646 LOG(WARNING) << "Command line too long for RegisterApplicationRestart: "
647 << command_line_string;
649 NOTREACHED() << "RegisterApplicationRestart failed. hr: " << hr
650 << ", command_line: " << command_line_string;
656 int ChromeBrowserMainPartsWin::HandleIconsCommands(
657 const base::CommandLine& parsed_command_line) {
658 if (parsed_command_line.HasSwitch(switches::kHideIcons)) {
659 // TODO(740976): This is not up-to-date and not localized. Figure out if
660 // the --hide-icons and --show-icons switches are still used.
661 std::u16string cp_applet = u"Programs and Features";
662 const std::u16string msg =
663 l10n_util::GetStringFUTF16(IDS_HIDE_ICONS_NOT_SUPPORTED, cp_applet);
664 const std::u16string caption = l10n_util::GetStringUTF16(IDS_PRODUCT_NAME);
665 const UINT flags = MB_OKCANCEL | MB_ICONWARNING | MB_TOPMOST;
666 if (IDOK == ui::MessageBox(NULL, base::AsWString(msg),
667 base::AsWString(caption), flags)) {
668 ShellExecute(NULL, NULL, L"appwiz.cpl", NULL, NULL, SW_SHOWNORMAL);
671 // Exit as we are not launching the browser.
672 return content::RESULT_CODE_NORMAL_EXIT;
674 // We don't hide icons so we shouldn't do anything special to show them
675 return chrome::RESULT_CODE_UNSUPPORTED_PARAM;
679 bool ChromeBrowserMainPartsWin::CheckMachineLevelInstall() {
680 base::Version version =
681 InstallUtil::GetChromeVersion(true /* system_install */);
682 if (version.IsValid()) {
683 base::FilePath exe_path;
684 base::PathService::Get(base::DIR_EXE, &exe_path);
685 const base::FilePath user_exe_path(
686 installer::GetInstalledDirectory(/*system_install=*/false));
687 if (base::FilePath::CompareEqualIgnoreCase(exe_path.value(),
688 user_exe_path.value())) {
689 base::CommandLine uninstall_cmd(
690 InstallUtil::GetChromeUninstallCmd(false));
691 if (!uninstall_cmd.GetProgram().empty()) {
692 uninstall_cmd.AppendSwitch(installer::switches::kSelfDestruct);
693 uninstall_cmd.AppendSwitch(installer::switches::kForceUninstall);
694 uninstall_cmd.AppendSwitch(
695 installer::switches::kDoNotRemoveSharedItems);
697 // Trigger Active Setup for the system-level Chrome to make sure
698 // per-user shortcuts to the system-level Chrome are created. Skip this
699 // if the system-level Chrome will undergo first run anyway, as Active
700 // Setup is triggered on system-level Chrome's first run.
701 // TODO(gab): Instead of having callers of Active Setup think about
702 // other callers, have Active Setup itself register when it ran and
703 // no-op otherwise (http://crbug.com/346843).
704 if (!first_run::IsChromeFirstRun())
705 uninstall_cmd.AppendSwitch(installer::switches::kTriggerActiveSetup);
707 const base::FilePath setup_exe(uninstall_cmd.GetProgram());
708 const std::wstring params(uninstall_cmd.GetArgumentsString());
710 SHELLEXECUTEINFO sei = { sizeof(sei) };
711 sei.fMask = SEE_MASK_NOASYNC;
712 sei.nShow = SW_SHOWNORMAL;
713 sei.lpFile = setup_exe.value().c_str();
714 sei.lpParameters = params.c_str();
716 if (!::ShellExecuteEx(&sei))
725 std::wstring TranslationDelegate::GetLocalizedString(int installer_string_id) {
727 switch (installer_string_id) {
728 // HANDLE_STRING is used by the DO_STRING_MAPPING macro which is in the
729 // generated header installer_util_strings.h.
730 #define HANDLE_STRING(base_id, chrome_id) \
732 resource_id = chrome_id; \
740 return base::UTF16ToWide(l10n_util::GetStringUTF16(resource_id));
741 return std::wstring();
745 void ChromeBrowserMainPartsWin::SetupInstallerUtilStrings() {
746 static base::NoDestructor<TranslationDelegate> delegate;
747 installer::SetTranslationDelegate(delegate.get());
751 base::CommandLine ChromeBrowserMainPartsWin::GetRestartCommandLine(
752 const base::CommandLine& command_line) {
753 base::CommandLine restart_command(base::CommandLine::NO_PROGRAM);
754 base::CommandLine::SwitchMap switches = command_line.GetSwitches();
756 // Remove flag switches added by about::flags.
757 about_flags::RemoveFlagsSwitches(&switches);
759 // Remove switches that should never be conveyed to the restart.
760 switches.erase(switches::kFromInstaller);
762 // Add remaining switches, but not non-switch arguments.
763 for (const auto& it : switches)
764 restart_command.AppendSwitchNative(it.first, it.second);
766 if (!command_line.HasSwitch(switches::kRestoreLastSession))
767 restart_command.AppendSwitch(switches::kRestoreLastSession);
769 // This is used when recording launch mode metric.
770 if (!command_line.HasSwitch(switches::kRestart))
771 restart_command.AppendSwitch(switches::kRestart);
773 // TODO(crbug.com/964541): Remove other unneeded switches, including
774 // duplicates, perhaps harmonize with switches::RemoveSwitchesForAutostart.
775 return restart_command;
778 // Used as the callback for ModuleWatcher events in this process. Dispatches
779 // them to the ModuleDatabase.
780 // Note: This callback may be invoked on any thread, even those not owned by the
781 // task scheduler, under the loader lock, directly on the thread where the
782 // DLL is currently loading.
783 void ChromeBrowserMainPartsWin::OnModuleEvent(
784 const ModuleWatcher::ModuleEvent& event) {
786 TRACE_EVENT1("browser", "OnModuleEvent", "module_path",
787 event.module_path.BaseName().AsUTF8Unsafe());
789 switch (event.event_type) {
790 case ModuleWatcher::ModuleEventType::kModuleAlreadyLoaded: {
791 // kModuleAlreadyLoaded comes from the enumeration of loaded modules
792 // using CreateToolhelp32Snapshot().
793 uint32_t time_date_stamp = 0;
794 if (TryGetModuleTimeDateStamp(event.module_load_address,
795 event.module_path, event.module_size,
797 ModuleDatabase::HandleModuleLoadEvent(
798 content::PROCESS_TYPE_BROWSER, event.module_path,
799 event.module_size, time_date_stamp);
801 // Failed to get the TimeDateStamp directly from memory. The next step
802 // to try is to read the file on disk. This must be done in a blocking
804 base::ThreadPool::PostTask(
806 {base::MayBlock(), base::TaskPriority::BEST_EFFORT,
807 base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
808 base::BindOnce(&HandleModuleLoadEventWithoutTimeDateStamp,
809 event.module_path, event.module_size));
813 case ModuleWatcher::ModuleEventType::kModuleLoaded: {
814 ModuleDatabase::HandleModuleLoadEvent(
815 content::PROCESS_TYPE_BROWSER, event.module_path, event.module_size,
816 GetModuleTimeDateStamp(event.module_load_address));
821 // Since OnModuleEvent can be invoked from any thread, the above trace event's
822 // END might be the last event on this thread, emit an empty event to force
823 // the END to be flushed. TODO(crbug.com/1021571): Remove this once fixed.
824 PERFETTO_INTERNAL_ADD_EMPTY_EVENT();
827 // Helper function for initializing the module database subsystem and populating
828 // the provided |module_watcher|.
829 void ChromeBrowserMainPartsWin::SetupModuleDatabase(
830 std::unique_ptr<ModuleWatcher>* module_watcher) {
831 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
832 DCHECK(module_watcher);
834 #if BUILDFLAG(GOOGLE_CHROME_BRANDING)
835 // Explicitly disable the third-party modules blocking.
837 // Because the blocking code lives in chrome_elf, it is not possible to check
838 // the feature (via the FeatureList API) or the policy to control whether it
839 // is enabled or not.
841 // What truly controls if the blocking is enabled is the presence of the
842 // module blocklist cache file. This means that to disable the feature, the
843 // cache must be deleted and the browser relaunched.
844 if (!ModuleDatabase::IsThirdPartyBlockingPolicyEnabled() ||
845 !ModuleBlocklistCacheUpdater::IsBlockingEnabled())
846 ThirdPartyConflictsManager::DisableThirdPartyModuleBlocking(
847 base::ThreadPool::CreateTaskRunner(
848 {base::TaskPriority::BEST_EFFORT,
849 base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN,
854 bool third_party_blocking_policy_enabled =
855 #if BUILDFLAG(GOOGLE_CHROME_BRANDING)
856 ModuleDatabase::IsThirdPartyBlockingPolicyEnabled();
861 ModuleDatabase::GetTaskRunner()->PostTask(
862 FROM_HERE, base::BindOnce(&InitializeModuleDatabase,
863 third_party_blocking_policy_enabled));
865 *module_watcher = ModuleWatcher::Create(base::BindRepeating(
866 &ChromeBrowserMainPartsWin::OnModuleEvent, base::Unretained(this)));