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