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.
5 #include "chrome/browser/chrome_browser_main_win.h"
16 #include "base/base_switches.h"
17 #include "base/bind.h"
18 #include "base/bind_helpers.h"
19 #include "base/command_line.h"
20 #include "base/enterprise_util.h"
21 #include "base/environment.h"
22 #include "base/feature_list.h"
23 #include "base/files/file_path.h"
24 #include "base/files/file_util.h"
25 #include "base/files/important_file_writer_cleaner.h"
26 #include "base/i18n/rtl.h"
27 #include "base/location.h"
28 #include "base/metrics/histogram_macros.h"
29 #include "base/no_destructor.h"
30 #include "base/path_service.h"
31 #include "base/scoped_native_library.h"
32 #include "base/stl_util.h"
33 #include "base/strings/string_number_conversions.h"
34 #include "base/strings/utf_string_conversions.h"
35 #include "base/task/post_task.h"
36 #include "base/task/thread_pool.h"
37 #include "base/threading/sequenced_task_runner_handle.h"
38 #include "base/trace_event/trace_event.h"
39 #include "base/version.h"
40 #include "base/win/pe_image.h"
41 #include "base/win/registry.h"
42 #include "base/win/win_util.h"
43 #include "base/win/windows_version.h"
44 #include "base/win/wrapped_window_proc.h"
45 #include "build/branding_buildflags.h"
46 #include "chrome/browser/after_startup_task_utils.h"
47 #include "chrome/browser/browser_process.h"
48 #include "chrome/browser/first_run/first_run.h"
49 #include "chrome/browser/profiles/profile_manager.h"
50 #include "chrome/browser/profiles/profile_shortcut_manager.h"
51 #include "chrome/browser/safe_browsing/chrome_cleaner/settings_resetter_win.h"
52 #include "chrome/browser/safe_browsing/settings_reset_prompt/settings_reset_prompt_config.h"
53 #include "chrome/browser/safe_browsing/settings_reset_prompt/settings_reset_prompt_util_win.h"
54 #include "chrome/browser/ui/simple_message_box.h"
55 #include "chrome/browser/ui/uninstall_browser_prompt.h"
56 #include "chrome/browser/web_applications/chrome_pwa_launcher/last_browser_file_util.h"
57 #include "chrome/browser/web_applications/chrome_pwa_launcher/launcher_log_reporter.h"
58 #include "chrome/browser/web_applications/chrome_pwa_launcher/launcher_update.h"
59 #include "chrome/browser/web_applications/components/web_app_file_handler_registration_win.h"
60 #include "chrome/browser/web_applications/components/web_app_shortcut.h"
61 #include "chrome/browser/win/browser_util.h"
62 #include "chrome/browser/win/chrome_elf_init.h"
63 #include "chrome/browser/win/conflicts/enumerate_input_method_editors.h"
64 #include "chrome/browser/win/conflicts/enumerate_shell_extensions.h"
65 #include "chrome/browser/win/conflicts/module_database.h"
66 #include "chrome/browser/win/conflicts/module_event_sink_impl.h"
67 #include "chrome/browser/win/util_win_service.h"
68 #include "chrome/common/channel_info.h"
69 #include "chrome/common/chrome_constants.h"
70 #include "chrome/common/chrome_features.h"
71 #include "chrome/common/chrome_paths.h"
72 #include "chrome/common/chrome_result_codes.h"
73 #include "chrome/common/chrome_switches.h"
74 #include "chrome/common/conflicts/module_watcher_win.h"
75 #include "chrome/common/crash_keys.h"
76 #include "chrome/common/env_vars.h"
77 #include "chrome/grit/chromium_strings.h"
78 #include "chrome/grit/generated_resources.h"
79 #include "chrome/install_static/install_details.h"
80 #include "chrome/installer/util/helper.h"
81 #include "chrome/installer/util/install_util.h"
82 #include "chrome/installer/util/installer_util_strings.h"
83 #include "chrome/installer/util/l10n_string_util.h"
84 #include "chrome/installer/util/shell_util.h"
85 #include "components/crash/core/app/crash_export_thunks.h"
86 #include "components/crash/core/app/dump_hung_process_with_ptype.h"
87 #include "components/crash/core/common/crash_key.h"
88 #include "components/os_crypt/os_crypt.h"
89 #include "components/version_info/channel.h"
90 #include "content/public/browser/browser_task_traits.h"
91 #include "content/public/browser/browser_thread.h"
92 #include "content/public/browser/render_process_host.h"
93 #include "content/public/common/content_switches.h"
94 #include "content/public/common/main_function_params.h"
95 #include "extensions/browser/extension_registry.h"
96 #include "ui/base/cursor/cursor_loader_win.h"
97 #include "ui/base/l10n/l10n_util.h"
98 #include "ui/base/l10n/l10n_util_win.h"
99 #include "ui/base/ui_base_switches.h"
100 #include "ui/base/win/hidden_window.h"
101 #include "ui/base/win/message_box_win.h"
102 #include "ui/display/win/dpi.h"
103 #include "ui/gfx/switches.h"
104 #include "ui/gfx/system_fonts_win.h"
105 #include "ui/gfx/win/crash_id_helper.h"
106 #include "ui/strings/grit/app_locale_settings.h"
108 #if BUILDFLAG(GOOGLE_CHROME_BRANDING)
109 #include "chrome/browser/win/conflicts/third_party_conflicts_manager.h"
114 typedef HRESULT (STDAPICALLTYPE* RegisterApplicationRestartProc)(
115 const wchar_t* command_line,
118 void InitializeWindowProcExceptions() {
119 base::win::WinProcExceptionFilter exception_filter =
120 base::win::SetWinProcExceptionFilter(&CrashForException_ExportThunk);
121 DCHECK(!exception_filter);
124 // TODO(siggi): Remove once https://crbug.com/806661 is resolved.
125 void DumpHungRendererProcessImpl(const base::Process& renderer) {
126 // Use a distinguishing process type for these reports.
127 crash_reporter::DumpHungProcessWithPtype(renderer, "hung-renderer");
130 // gfx::Font callbacks
131 void AdjustUIFont(gfx::win::FontAdjustment* font_adjustment) {
132 l10n_util::NeedOverrideDefaultUIFont(&font_adjustment->font_family_override,
133 &font_adjustment->font_scale);
134 font_adjustment->font_scale *= display::win::GetAccessibilityFontScale();
137 int GetMinimumFontSize() {
139 base::StringToInt(l10n_util::GetStringUTF16(IDS_MINIMUM_UI_FONT_SIZE),
141 return min_font_size;
144 class TranslationDelegate : public installer::TranslationDelegate {
146 base::string16 GetLocalizedString(int installer_string_id) override;
149 void DetectFaultTolerantHeap() {
153 FTH_ACLAYERS_LOADED = 4,
154 FTH_ACXTRNAL_LOADED = 8,
158 // The Fault Tolerant Heap (FTH) is enabled on some customer machines and is
159 // affecting their performance. We need to know how many machines are
160 // affected in order to decide what to do.
162 // The main way that the FTH is enabled is by having a value set in
163 // HKLM\Software\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers
164 // whose name is the full path to the executable and whose data is the
165 // string FaultTolerantHeap. Some documents suggest that this data may also
166 // be found in HKCU. There have also been cases observed where this registry
167 // key is set but the FTH is not enabled, so we also look for AcXtrnal.dll
168 // and AcLayers.dll which are used to implement the FTH on Windows 7 and 8
171 // Get the module path so that we can look for it in the registry.
172 wchar_t module_path[MAX_PATH];
173 GetModuleFileName(NULL, module_path, ARRAYSIZE(module_path));
174 // Force null-termination, necessary on Windows XP.
175 module_path[ARRAYSIZE(module_path)-1] = 0;
177 const wchar_t* const kRegPath = L"Software\\Microsoft\\Windows NT\\"
178 L"CurrentVersion\\AppCompatFlags\\Layers";
179 const wchar_t* const kFTHData = L"FaultTolerantHeap";
180 // We always want to read from the 64-bit version of the registry if present,
181 // since that is what the OS looks at, even for 32-bit processes.
182 const DWORD kRegFlags = KEY_READ | KEY_WOW64_64KEY;
184 base::win::RegKey FTH_HKLM_reg(HKEY_LOCAL_MACHINE, kRegPath, kRegFlags);
185 FTHFlags detected = FTHFlags();
186 base::string16 chrome_app_compat;
187 if (FTH_HKLM_reg.ReadValue(module_path, &chrome_app_compat) == 0) {
188 // This *usually* indicates that the fault tolerant heap is enabled.
189 if (wcsicmp(chrome_app_compat.c_str(), kFTHData) == 0)
190 detected = static_cast<FTHFlags>(detected | FTH_HKLM);
193 base::win::RegKey FTH_HKCU_reg(HKEY_CURRENT_USER, kRegPath, kRegFlags);
194 if (FTH_HKCU_reg.ReadValue(module_path, &chrome_app_compat) == 0) {
195 if (wcsicmp(chrome_app_compat.c_str(), kFTHData) == 0)
196 detected = static_cast<FTHFlags>(detected | FTH_HKCU);
199 // Look for the DLLs used to implement the FTH and other compat hacks.
200 if (GetModuleHandleW(L"AcLayers.dll") != NULL)
201 detected = static_cast<FTHFlags>(detected | FTH_ACLAYERS_LOADED);
202 if (GetModuleHandleW(L"AcXtrnal.dll") != NULL)
203 detected = static_cast<FTHFlags>(detected | FTH_ACXTRNAL_LOADED);
205 UMA_HISTOGRAM_ENUMERATION("FaultTolerantHeap", detected, FTH_FLAGS_COUNT);
208 void DelayedRecordProcessorMetrics() {
209 mojo::Remote<chrome::mojom::UtilWin> remote_util_win =
210 LaunchUtilWinServiceInstance();
211 auto* remote_util_win_ptr = remote_util_win.get();
212 remote_util_win_ptr->RecordProcessorMetrics(base::BindOnce(
213 [](mojo::Remote<chrome::mojom::UtilWin>) {}, std::move(remote_util_win)));
216 // Initializes the ModuleDatabase on its owning sequence. Also starts the
217 // enumeration of registered modules in the Windows Registry.
218 void InitializeModuleDatabase(
219 bool is_third_party_blocking_policy_enabled) {
220 DCHECK(ModuleDatabase::GetTaskRunner()->RunsTasksInCurrentSequence());
222 ModuleDatabase::SetInstance(
223 std::make_unique<ModuleDatabase>(is_third_party_blocking_policy_enabled));
225 auto* module_database = ModuleDatabase::GetInstance();
226 module_database->StartDrainingModuleLoadAttemptsLog();
228 // Enumerate shell extensions and input method editors. It is safe to use
229 // base::Unretained() here because the ModuleDatabase is never freed.
230 EnumerateShellExtensions(
231 base::BindRepeating(&ModuleDatabase::OnShellExtensionEnumerated,
232 base::Unretained(module_database)),
233 base::BindOnce(&ModuleDatabase::OnShellExtensionEnumerationFinished,
234 base::Unretained(module_database)));
235 EnumerateInputMethodEditors(
236 base::BindRepeating(&ModuleDatabase::OnImeEnumerated,
237 base::Unretained(module_database)),
238 base::BindOnce(&ModuleDatabase::OnImeEnumerationFinished,
239 base::Unretained(module_database)));
242 // Notes on the OnModuleEvent() callback.
244 // The ModuleDatabase uses the TimeDateStamp value of the DLL to uniquely
245 // identify modules as they are discovered. Unlike the SizeOfImage, this value
246 // isn't provided via LdrDllNotification events or CreateToolhelp32Snapshot().
248 // The easiest way to obtain the TimeDateStamp is to read the mapped module in
249 // memory. Unfortunately, this could cause an ACCESS_VIOLATION_EXCEPTION if the
250 // module is unloaded before being accessed. This can occur when enumerating
251 // already loaded modules with CreateToolhelp32Snapshot(). Note that this
252 // problem doesn't affect LdrDllNotification events, where it is guaranteed that
253 // the module stays in memory for the duration of the callback.
255 // To get around this, there are multiple solutions:
256 // (1) Read the file on disk instead.
257 // Sidesteps the problem altogether. The drawback is that it must be done on
258 // a sequence that allow blocking IO, and it is way slower. We don't want to
259 // pay that price for each module in the process. This can fail if the file
260 // can not be found when attemping to read it.
262 // (2) Increase the reference count of the module.
263 // Calling ::LoadLibraryEx() or ::GetModuleHandleEx() lets us ensure that
264 // the module won't go away while we hold the extra handle. It's still
265 // possible that the module was unloaded before we have a chance to increase
266 // the reference count, which would mean either reloading the DLL, or
267 // failing to get a new handle.
269 // This isn't ideal but the worst that can happen is that we hold the last
270 // reference to the module. The DLL would be unloaded on our thread when
271 // ::FreeLibrary() is called. This could go horribly wrong if the DLL's
272 // creator didn't consider this possibility.
274 // (3) Do it in a Structured Exception Handler (SEH)
275 // Make the read inside a __try/__except handler and handle the possible
276 // ACCESS_VIOLATION_EXCEPTION if it happens.
278 // The current solution is (3) with a fallback that uses (1). In the rare case
279 // that both fail to get the TimeDateStamp, the module load event is dropped
280 // altogether, as our best effort was unsuccessful.
282 // Gets the TimeDateStamp from the file on disk and, if successful, sends the
283 // load event to the ModuleDatabase.
284 void HandleModuleLoadEventWithoutTimeDateStamp(
285 const base::FilePath& module_path,
286 size_t module_size) {
287 uint32_t size_of_image = 0;
288 uint32_t time_date_stamp = 0;
289 bool got_time_date_stamp = GetModuleImageSizeAndTimeDateStamp(
290 module_path, &size_of_image, &time_date_stamp);
292 // Simple sanity check.
293 got_time_date_stamp = got_time_date_stamp && size_of_image == module_size;
294 UMA_HISTOGRAM_BOOLEAN("ThirdPartyModules.TimeDateStampObtained",
295 got_time_date_stamp);
297 // Drop the load event if it's not possible to get the time date stamp.
298 if (!got_time_date_stamp)
301 ModuleDatabase::HandleModuleLoadEvent(
302 content::PROCESS_TYPE_BROWSER, module_path, module_size, time_date_stamp);
305 // Helper function for getting the module size associated with a module in this
306 // process based on its load address.
307 uint32_t GetModuleSizeOfImage(const void* module_load_address) {
308 base::win::PEImage pe_image(module_load_address);
309 return pe_image.GetNTHeaders()->OptionalHeader.SizeOfImage;
312 // Helper function for getting the time date stamp associated with a module in
313 // this process based on its load address.
314 uint32_t GetModuleTimeDateStamp(const void* module_load_address) {
315 base::win::PEImage pe_image(module_load_address);
316 return pe_image.GetNTHeaders()->FileHeader.TimeDateStamp;
319 // An exception filter for handling Access Violation exceptions within the
320 // memory range [module_load_address, module_load_address + size_of_image).
321 DWORD FilterAccessViolation(DWORD exception_code,
322 const EXCEPTION_POINTERS* exception_information,
323 void* module_load_address,
324 uint32_t size_of_image) {
325 if (exception_code != EXCEPTION_ACCESS_VIOLATION)
326 return EXCEPTION_CONTINUE_SEARCH;
328 // To make sure an unrelated exception is not swallowed by the exception
329 // handler, the address where the exception happened is verified.
330 const EXCEPTION_RECORD* exception_record =
331 exception_information->ExceptionRecord;
332 const DWORD access_violation_address =
333 exception_record->ExceptionInformation[1];
335 uintptr_t range_start = reinterpret_cast<uintptr_t>(module_load_address);
336 uintptr_t range_end = range_start + size_of_image;
337 if (range_start > access_violation_address ||
338 range_end <= access_violation_address) {
339 return EXCEPTION_CONTINUE_SEARCH;
342 return EXCEPTION_EXECUTE_HANDLER;
345 // Wrapper around GetModuleTimeDateStamp that handles a potential
346 // EXCEPTION_ACCESS_VIOLATION that can happen if the |module_load_address| is
347 // accessed after the module is unloaded. Also ensures that the expected module
348 // is loaded at this address.
349 bool TryGetModuleTimeDateStamp(void* module_load_address,
350 const base::FilePath& module_path,
351 uint32_t size_of_image,
352 uint32_t* time_date_stamp) {
354 // Make sure it's the correct module, to protect against a potential race
355 // where a new module was loaded at the same address. This is safe because
356 // the only possibles races are either there was a module loaded at
357 // |module_load_address| and it was unloaded, or there was no module loaded
358 // at |module_load_address| and a new one took its place.
359 wchar_t module_file_name[MAX_PATH];
361 ::GetModuleFileName(reinterpret_cast<HMODULE>(module_load_address),
362 module_file_name, ARRAYSIZE(module_file_name));
363 if (!size || !base::FilePath::CompareEqualIgnoreCase(module_path.value(),
367 if (size_of_image != GetModuleSizeOfImage(module_load_address))
370 *time_date_stamp = GetModuleTimeDateStamp(module_load_address);
371 } __except(FilterAccessViolation(GetExceptionCode(),
372 GetExceptionInformation(),
373 module_load_address, size_of_image)) {
379 // Used as the callback for ModuleWatcher events in this process. Dispatches
380 // them to the ModuleDatabase.
381 // Note: This callback may be invoked on any thread, even those not owned by the
382 // task scheduler, under the loader lock, directly on the thread where the
383 // DLL is currently loading.
384 void OnModuleEvent(const ModuleWatcher::ModuleEvent& event) {
385 TRACE_EVENT1("browser", "OnModuleEvent", "module_path",
386 event.module_path.BaseName().AsUTF8Unsafe());
388 switch (event.event_type) {
389 case ModuleWatcher::ModuleEventType::kModuleAlreadyLoaded: {
390 // kModuleAlreadyLoaded comes from the enumeration of loaded modules
391 // using CreateToolhelp32Snapshot().
392 uint32_t time_date_stamp = 0;
393 if (TryGetModuleTimeDateStamp(event.module_load_address,
394 event.module_path, event.module_size,
396 ModuleDatabase::HandleModuleLoadEvent(
397 content::PROCESS_TYPE_BROWSER, event.module_path, event.module_size,
400 // Failed to get the TimeDateStamp directly from memory. The next step
401 // to try is to read the file on disk. This must be done in a blocking
403 base::ThreadPool::PostTask(
405 {base::MayBlock(), base::TaskPriority::BEST_EFFORT,
406 base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
407 base::BindOnce(&HandleModuleLoadEventWithoutTimeDateStamp,
408 event.module_path, event.module_size));
412 case ModuleWatcher::ModuleEventType::kModuleLoaded: {
413 ModuleDatabase::HandleModuleLoadEvent(
414 content::PROCESS_TYPE_BROWSER, event.module_path, event.module_size,
415 GetModuleTimeDateStamp(event.module_load_address));
421 // Helper function for initializing the module database subsystem and populating
422 // the provided |module_watcher|.
423 void SetupModuleDatabase(std::unique_ptr<ModuleWatcher>* module_watcher) {
424 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
425 DCHECK(module_watcher);
427 bool third_party_blocking_policy_enabled =
428 #if BUILDFLAG(GOOGLE_CHROME_BRANDING)
429 ModuleDatabase::IsThirdPartyBlockingPolicyEnabled();
434 ModuleDatabase::GetTaskRunner()->PostTask(
435 FROM_HERE, base::BindOnce(&InitializeModuleDatabase,
436 third_party_blocking_policy_enabled));
438 *module_watcher = ModuleWatcher::Create(base::BindRepeating(&OnModuleEvent));
441 void ShowCloseBrowserFirstMessageBox() {
442 chrome::ShowWarningMessageBox(
443 nullptr, l10n_util::GetStringUTF16(IDS_PRODUCT_NAME),
444 l10n_util::GetStringUTF16(IDS_UNINSTALL_CLOSE_APP));
447 void MaybePostSettingsResetPrompt() {
448 if (base::FeatureList::IsEnabled(safe_browsing::kSettingsResetPrompt)) {
449 content::GetUIThreadTaskRunner({base::TaskPriority::BEST_EFFORT})
450 ->PostTask(FROM_HERE,
452 safe_browsing::MaybeShowSettingsResetPromptWithDelay));
456 // Updates all Progressive Web App launchers in |profile_dir| to the latest
458 void UpdatePwaLaunchersForProfile(const base::FilePath& profile_dir) {
459 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
461 g_browser_process->profile_manager()->GetProfileByPath(profile_dir);
463 // The profile was unloaded.
467 // Create a vector of all PWA-launcher paths in |profile_dir|.
468 std::vector<base::FilePath> pwa_launcher_paths;
469 for (const auto& extension :
470 extensions::ExtensionRegistry::Get(profile)->enabled_extensions()) {
471 if (extension->from_bookmark()) {
472 base::FilePath web_app_path =
473 web_app::GetOsIntegrationResourcesDirectoryForApp(
474 profile_dir, extension->id(), GURL());
476 web_app_path.Append(web_app::GetAppSpecificLauncherFilename(
477 base::UTF8ToUTF16(extension->name())));
478 pwa_launcher_paths.push_back(std::move(web_app_path));
482 base::ThreadPool::PostTask(
484 {base::TaskPriority::BEST_EFFORT,
485 base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN, base::MayBlock()},
486 base::BindOnce(&web_app::UpdatePwaLaunchers,
487 std::move(pwa_launcher_paths)));
490 // This error message is not localized because we failed to load the
491 // localization data files.
492 const char kMissingLocaleDataTitle[] = "Missing File Error";
494 // TODO(http://crbug.com/338969): This should be used on Linux Aura as well.
495 const char kMissingLocaleDataMessage[] =
496 "Unable to find locale data files. Please reinstall.";
500 int DoUninstallTasks(bool chrome_still_running) {
501 // We want to show a warning to user (and exit) if Chrome is already running
502 // *before* we show the uninstall confirmation dialog box. But while the
503 // uninstall confirmation dialog is up, user might start Chrome, so we
504 // check once again after user acknowledges Uninstall dialog.
505 if (chrome_still_running) {
506 ShowCloseBrowserFirstMessageBox();
507 return chrome::RESULT_CODE_UNINSTALL_CHROME_ALIVE;
509 int result = chrome::ShowUninstallBrowserPrompt();
510 if (browser_util::IsBrowserAlreadyRunning()) {
511 ShowCloseBrowserFirstMessageBox();
512 return chrome::RESULT_CODE_UNINSTALL_CHROME_ALIVE;
515 if (result != chrome::RESULT_CODE_UNINSTALL_USER_CANCEL) {
516 // The following actions are just best effort.
517 // TODO(gab): Look into removing this code which is now redundant with the
518 // work done by setup.exe on uninstall.
519 VLOG(1) << "Executing uninstall actions";
520 base::FilePath chrome_exe;
521 if (base::PathService::Get(base::FILE_EXE, &chrome_exe)) {
522 ShellUtil::ShortcutLocation user_shortcut_locations[] = {
523 ShellUtil::SHORTCUT_LOCATION_DESKTOP,
524 ShellUtil::SHORTCUT_LOCATION_QUICK_LAUNCH,
525 ShellUtil::SHORTCUT_LOCATION_START_MENU_ROOT,
526 ShellUtil::SHORTCUT_LOCATION_START_MENU_CHROME_DIR_DEPRECATED,
527 ShellUtil::SHORTCUT_LOCATION_START_MENU_CHROME_APPS_DIR,
529 for (size_t i = 0; i < base::size(user_shortcut_locations); ++i) {
530 if (!ShellUtil::RemoveShortcuts(user_shortcut_locations[i],
531 ShellUtil::CURRENT_USER, chrome_exe)) {
532 VLOG(1) << "Failed to delete shortcut at location "
533 << user_shortcut_locations[i];
543 // ChromeBrowserMainPartsWin ---------------------------------------------------
545 ChromeBrowserMainPartsWin::ChromeBrowserMainPartsWin(
546 const content::MainFunctionParams& parameters,
547 StartupData* startup_data)
548 : ChromeBrowserMainParts(parameters, startup_data) {}
550 ChromeBrowserMainPartsWin::~ChromeBrowserMainPartsWin() = default;
552 void ChromeBrowserMainPartsWin::ToolkitInitialized() {
553 DCHECK_NE(base::PlatformThread::CurrentId(), base::kInvalidThreadId);
554 gfx::CrashIdHelper::RegisterMainThread(base::PlatformThread::CurrentId());
555 ChromeBrowserMainParts::ToolkitInitialized();
556 gfx::win::SetAdjustFontCallback(&AdjustUIFont);
557 gfx::win::SetGetMinimumFontSizeCallback(&GetMinimumFontSize);
558 ui::CursorLoaderWin::SetCursorResourceModule(chrome::kBrowserResourcesDll);
561 void ChromeBrowserMainPartsWin::PreMainMessageLoopStart() {
562 // installer_util references strings that are normally compiled into
563 // setup.exe. In Chrome, these strings are in the locale files.
564 SetupInstallerUtilStrings();
566 PrefService* local_state = g_browser_process->local_state();
569 // Initialize the OSCrypt.
570 bool os_crypt_init = OSCrypt::Init(local_state);
571 DCHECK(os_crypt_init);
573 ChromeBrowserMainParts::PreMainMessageLoopStart();
574 if (!parameters().ui_task) {
575 // Make sure that we know how to handle exceptions from the message loop.
576 InitializeWindowProcExceptions();
580 int ChromeBrowserMainPartsWin::PreCreateThreads() {
581 // Record whether the machine is enterprise managed in a crash key. This will
582 // be used to better identify whether crashes are from enterprise users.
583 static crash_reporter::CrashKeyString<4> is_enterprise_managed(
584 "is-enterprise-managed");
585 is_enterprise_managed.Set(base::IsMachineExternallyManaged() ? "yes" : "no");
587 // Set crash keys containing the registry values used to determine Chrome's
588 // update channel at process startup; see https://crbug.com/579504.
589 const auto& details = install_static::InstallDetails::Get();
591 static crash_reporter::CrashKeyString<50> ap_value("ap");
592 ap_value.Set(base::UTF16ToUTF8(details.update_ap()));
594 static crash_reporter::CrashKeyString<32> update_cohort_name("cohort-name");
595 update_cohort_name.Set(base::UTF16ToUTF8(details.update_cohort_name()));
597 if (chrome::GetChannel() == version_info::Channel::CANARY) {
598 content::RenderProcessHost::SetHungRendererAnalysisFunction(
599 &DumpHungRendererProcessImpl);
602 return ChromeBrowserMainParts::PreCreateThreads();
605 void ChromeBrowserMainPartsWin::PostMainMessageLoopRun() {
606 base::ImportantFileWriterCleaner::GetInstance().Stop();
608 ChromeBrowserMainParts::PostMainMessageLoopRun();
611 void ChromeBrowserMainPartsWin::ShowMissingLocaleMessageBox() {
612 ui::MessageBox(NULL, base::ASCIIToUTF16(kMissingLocaleDataMessage),
613 base::ASCIIToUTF16(kMissingLocaleDataTitle),
614 MB_OK | MB_ICONERROR | MB_TOPMOST);
617 void ChromeBrowserMainPartsWin::PostProfileInit() {
618 ChromeBrowserMainParts::PostProfileInit();
620 #if BUILDFLAG(GOOGLE_CHROME_BRANDING)
621 // Explicitly disable the third-party modules blocking.
623 // Because the blocking code lives in chrome_elf, it is not possible to check
624 // the feature (via the FeatureList API) or the policy to control whether it
625 // is enabled or not.
627 // What truly controls if the blocking is enabled is the presence of the
628 // module blacklist cache file. This means that to disable the feature, the
629 // cache must be deleted and the browser relaunched.
630 if (!ModuleDatabase::IsThirdPartyBlockingPolicyEnabled() ||
631 !ModuleBlacklistCacheUpdater::IsBlockingEnabled())
632 ThirdPartyConflictsManager::DisableThirdPartyModuleBlocking(
633 base::ThreadPool::CreateTaskRunner(
634 {base::TaskPriority::BEST_EFFORT,
635 base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN,
640 // Create the module database and hook up the in-process module watcher. This
641 // needs to be done before any child processes are initialized as the
642 // ModuleDatabase is an endpoint for IPC from child processes.
643 SetupModuleDatabase(&module_watcher_);
646 void ChromeBrowserMainPartsWin::PostBrowserStart() {
647 ChromeBrowserMainParts::PostBrowserStart();
649 UMA_HISTOGRAM_BOOLEAN("Windows.Tablet",
650 base::win::IsTabletDevice(nullptr, ui::GetHiddenWindow()));
652 InitializeChromeElf();
654 // Reset settings for the current profile if it's tagged to be reset after a
655 // complete run of the Chrome Cleanup tool. If post-cleanup settings reset is
656 // enabled, we delay checks for settings reset prompt until the scheduled
657 // reset is finished.
658 if (safe_browsing::PostCleanupSettingsResetter::IsEnabled()) {
659 // Using last opened profiles, because we want to find reset the profile
660 // that was open in the last Chrome run, which may not be open yet in
662 safe_browsing::PostCleanupSettingsResetter().ResetTaggedProfiles(
663 g_browser_process->profile_manager()->GetLastOpenedProfiles(),
664 base::BindOnce(&MaybePostSettingsResetPrompt),
666 safe_browsing::PostCleanupSettingsResetter::Delegate>());
668 MaybePostSettingsResetPrompt();
670 // Record UMA data about whether the fault-tolerant heap is enabled.
671 // Use a delayed task to minimize the impact on startup time.
672 content::GetUIThreadTaskRunner({})->PostDelayedTask(
673 FROM_HERE, base::BindOnce(&DetectFaultTolerantHeap),
674 base::TimeDelta::FromMinutes(1));
676 // Record Processor Metrics. This is a very low priority, hence posting to
677 // start after Chrome startup has completed. This metric is only available
678 // starting Windows 10.
679 if (base::win::OSInfo::GetInstance()->version() >=
680 base::win::Version::WIN10) {
681 AfterStartupTaskUtils::PostTask(
682 FROM_HERE, base::ThreadPool::CreateSequencedTaskRunner({}),
683 base::BindOnce(&DelayedRecordProcessorMetrics));
686 // Write current executable path to the User Data directory to inform
687 // Progressive Web App launchers, which run from within the User Data
688 // directory, which chrome.exe to launch from.
689 base::ThreadPool::PostTask(
690 FROM_HERE, {base::TaskPriority::BEST_EFFORT, base::MayBlock()},
691 base::BindOnce(&web_app::WriteChromePathToLastBrowserFile,
694 // If Chrome was launched by a Progressive Web App launcher that needs to be
695 // updated, update all launchers for this profile.
696 if (parsed_command_line().HasSwitch(switches::kAppId) &&
697 parsed_command_line().GetSwitchValueASCII(
698 switches::kPwaLauncherVersion) != chrome::kChromeVersion) {
699 content::BrowserThread::PostBestEffortTask(
700 FROM_HERE, base::SequencedTaskRunnerHandle::Get(),
701 base::BindOnce(&UpdatePwaLaunchersForProfile, profile()->GetPath()));
704 // Record the result of the latest Progressive Web App launcher launch.
705 base::ThreadPool::PostTask(
706 FROM_HERE, {base::TaskPriority::BEST_EFFORT, base::MayBlock()},
707 base::BindOnce(&web_app::RecordPwaLauncherResult));
709 base::ImportantFileWriterCleaner::GetInstance().Start();
713 void ChromeBrowserMainPartsWin::PrepareRestartOnCrashEnviroment(
714 const base::CommandLine& parsed_command_line) {
715 // Clear this var so child processes don't show the dialog by default.
716 std::unique_ptr<base::Environment> env(base::Environment::Create());
717 env->UnSetVar(env_vars::kShowRestart);
719 // For non-interactive tests we don't restart on crash.
720 if (env->HasVar(env_vars::kHeadless))
723 // If the known command-line test options are used we don't create the
724 // environment block which means we don't get the restart dialog.
725 if (parsed_command_line.HasSwitch(switches::kBrowserCrashTest) ||
726 parsed_command_line.HasSwitch(switches::kNoErrorDialogs))
729 // The encoding we use for the info is "title|context|direction" where
730 // direction is either env_vars::kRtlLocale or env_vars::kLtrLocale depending
731 // on the current locale.
732 base::string16 dlg_strings(
733 l10n_util::GetStringUTF16(IDS_CRASH_RECOVERY_TITLE));
734 dlg_strings.push_back('|');
735 base::string16 adjusted_string(
736 l10n_util::GetStringUTF16(IDS_CRASH_RECOVERY_CONTENT));
737 base::i18n::AdjustStringForLocaleDirection(&adjusted_string);
738 dlg_strings.append(adjusted_string);
739 dlg_strings.push_back('|');
740 dlg_strings.append(base::ASCIIToUTF16(
741 base::i18n::IsRTL() ? env_vars::kRtlLocale : env_vars::kLtrLocale));
743 env->SetVar(env_vars::kRestartInfo, base::UTF16ToUTF8(dlg_strings));
747 void ChromeBrowserMainPartsWin::RegisterApplicationRestart(
748 const base::CommandLine& parsed_command_line) {
749 base::ScopedNativeLibrary library(base::FilePath(L"kernel32.dll"));
750 // Get the function pointer for RegisterApplicationRestart.
751 RegisterApplicationRestartProc register_application_restart =
752 reinterpret_cast<RegisterApplicationRestartProc>(
753 library.GetFunctionPointer("RegisterApplicationRestart"));
754 if (!register_application_restart) {
755 LOG(WARNING) << "Cannot find RegisterApplicationRestart in kernel32.dll";
758 // The Windows Restart Manager expects a string of command line flags only,
759 // without the program.
760 base::CommandLine command_line(base::CommandLine::NO_PROGRAM);
761 command_line.AppendArguments(parsed_command_line, false);
762 if (!command_line.HasSwitch(switches::kRestoreLastSession))
763 command_line.AppendSwitch(switches::kRestoreLastSession);
765 // Restart Chrome if the computer is restarted as the result of an update.
766 // This could be extended to handle crashes, hangs, and patches.
767 const auto& command_line_string = command_line.GetCommandLineString();
768 HRESULT hr = register_application_restart(
769 command_line_string.c_str(),
770 RESTART_NO_CRASH | RESTART_NO_HANG | RESTART_NO_PATCH);
772 if (hr == E_INVALIDARG) {
773 LOG(WARNING) << "Command line too long for RegisterApplicationRestart: "
774 << command_line_string;
776 NOTREACHED() << "RegisterApplicationRestart failed. hr: " << hr
777 << ", command_line: " << command_line_string;
783 int ChromeBrowserMainPartsWin::HandleIconsCommands(
784 const base::CommandLine& parsed_command_line) {
785 if (parsed_command_line.HasSwitch(switches::kHideIcons)) {
786 // TODO(740976): This is not up-to-date and not localized. Figure out if
787 // the --hide-icons and --show-icons switches are still used.
788 base::string16 cp_applet(L"Programs and Features");
789 const base::string16 msg =
790 l10n_util::GetStringFUTF16(IDS_HIDE_ICONS_NOT_SUPPORTED, cp_applet);
791 const base::string16 caption = l10n_util::GetStringUTF16(IDS_PRODUCT_NAME);
792 const UINT flags = MB_OKCANCEL | MB_ICONWARNING | MB_TOPMOST;
793 if (IDOK == ui::MessageBox(NULL, msg, caption, flags))
794 ShellExecute(NULL, NULL, L"appwiz.cpl", NULL, NULL, SW_SHOWNORMAL);
796 // Exit as we are not launching the browser.
797 return service_manager::RESULT_CODE_NORMAL_EXIT;
799 // We don't hide icons so we shouldn't do anything special to show them
800 return chrome::RESULT_CODE_UNSUPPORTED_PARAM;
804 bool ChromeBrowserMainPartsWin::CheckMachineLevelInstall() {
805 base::Version version =
806 InstallUtil::GetChromeVersion(true /* system_install */);
807 if (version.IsValid()) {
808 base::FilePath exe_path;
809 base::PathService::Get(base::DIR_EXE, &exe_path);
810 std::wstring exe = exe_path.value();
811 base::FilePath user_exe_path(installer::GetChromeInstallPath(false));
812 if (base::FilePath::CompareEqualIgnoreCase(exe, user_exe_path.value())) {
813 base::CommandLine uninstall_cmd(
814 InstallUtil::GetChromeUninstallCmd(false));
815 if (!uninstall_cmd.GetProgram().empty()) {
816 uninstall_cmd.AppendSwitch(installer::switches::kSelfDestruct);
817 uninstall_cmd.AppendSwitch(installer::switches::kForceUninstall);
818 uninstall_cmd.AppendSwitch(
819 installer::switches::kDoNotRemoveSharedItems);
821 // Trigger Active Setup for the system-level Chrome to make sure
822 // per-user shortcuts to the system-level Chrome are created. Skip this
823 // if the system-level Chrome will undergo first run anyway, as Active
824 // Setup is triggered on system-level Chrome's first run.
825 // TODO(gab): Instead of having callers of Active Setup think about
826 // other callers, have Active Setup itself register when it ran and
827 // no-op otherwise (http://crbug.com/346843).
828 if (!first_run::IsChromeFirstRun())
829 uninstall_cmd.AppendSwitch(installer::switches::kTriggerActiveSetup);
831 const base::FilePath setup_exe(uninstall_cmd.GetProgram());
832 const base::string16 params(uninstall_cmd.GetArgumentsString());
834 SHELLEXECUTEINFO sei = { sizeof(sei) };
835 sei.fMask = SEE_MASK_NOASYNC;
836 sei.nShow = SW_SHOWNORMAL;
837 sei.lpFile = setup_exe.value().c_str();
838 sei.lpParameters = params.c_str();
840 if (!::ShellExecuteEx(&sei))
849 base::string16 TranslationDelegate::GetLocalizedString(
850 int installer_string_id) {
852 switch (installer_string_id) {
853 // HANDLE_STRING is used by the DO_STRING_MAPPING macro which is in the
854 // generated header installer_util_strings.h.
855 #define HANDLE_STRING(base_id, chrome_id) \
857 resource_id = chrome_id; \
865 return l10n_util::GetStringUTF16(resource_id);
866 return base::string16();
870 void ChromeBrowserMainPartsWin::SetupInstallerUtilStrings() {
871 static base::NoDestructor<TranslationDelegate> delegate;
872 installer::SetTranslationDelegate(delegate.get());