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/app/main_dll_loader_win.h"
7 #include <windows.h> // NOLINT
10 #include <userenv.h> // NOLINT
15 #include "base/base_paths.h"
16 #include "base/base_switches.h"
17 #include "base/command_line.h"
18 #include "base/compiler_specific.h"
19 #include "base/files/file.h"
20 #include "base/files/file_path.h"
21 #include "base/files/file_util.h"
22 #include "base/functional/bind.h"
23 #include "base/lazy_instance.h"
24 #include "base/logging.h"
25 #include "base/path_service.h"
26 #include "base/strings/string_piece.h"
27 #include "base/strings/string_util.h"
28 #include "base/strings/utf_string_conversions.h"
29 #include "base/trace_event/trace_event.h"
30 #include "base/win/scoped_handle.h"
31 #include "base/win/shlwapi.h"
32 #include "base/win/windows_version.h"
33 #include "build/branding_buildflags.h"
34 #include "chrome/browser/active_use_util.h"
35 #include "chrome/chrome_elf/chrome_elf_main.h"
36 #include "chrome/common/chrome_constants.h"
37 #include "chrome/common/chrome_paths.h"
38 #include "chrome/common/chrome_result_codes.h"
39 #include "chrome/common/chrome_switches.h"
40 #include "chrome/installer/util/update_did_run_state.h"
41 #include "chrome/installer/util/util_constants.h"
42 #include "content/public/app/sandbox_helper_win.h"
43 #include "content/public/common/content_switches.h"
44 #include "sandbox/policy/mojom/sandbox.mojom.h"
45 #include "sandbox/policy/sandbox_type.h"
46 #include "sandbox/win/src/sandbox.h"
49 // The entry point signature of chrome.dll.
50 typedef int (*DLL_MAIN)(HINSTANCE, sandbox::SandboxInterfaceInfo*, int64_t);
52 typedef void (*RelaunchChromeBrowserWithNewCommandLineIfNeededFunc)();
54 void RecordDidRun(const base::FilePath& dll_path) {
55 installer::UpdateDidRunState(true);
58 // Indicates whether a file can be opened using the same flags that
59 // ::LoadLibrary() uses to open modules.
60 bool ModuleCanBeRead(const base::FilePath& file_path) {
61 return base::File(file_path, base::File::FLAG_OPEN | base::File::FLAG_READ)
65 // Returns the full path to |module_name|. Both dev builds (where |module_name|
66 // is in the current executable's directory) and proper installs (where
67 // |module_name| is in a versioned sub-directory of the current executable's
68 // directory) are suported. The identified file is not guaranteed to exist.
69 base::FilePath GetModulePath(base::WStringPiece module_name) {
70 base::FilePath exe_dir;
71 const bool has_path = base::PathService::Get(base::DIR_EXE, &exe_dir);
74 // Look for the module in a versioned sub-directory of the current
75 // executable's directory and return the path if it can be read. This is the
76 // expected location of modules for proper installs.
77 const base::FilePath module_path =
78 exe_dir.AppendASCII(chrome::kChromeVersion).Append(module_name);
79 if (ModuleCanBeRead(module_path))
82 // Othwerwise, return the path to the module in the current executable's
83 // directory. This is the expected location of modules for dev builds.
84 return exe_dir.Append(module_name);
87 // Prefetches and loads |module| after setting the CWD to |module|'s
88 // directory. Returns a handle to the loaded module on success, or nullptr on
90 HMODULE LoadModuleWithDirectory(const base::FilePath& module,
91 const base::CommandLine& cmd_line) {
92 ::SetCurrentDirectoryW(module.DirName().value().c_str());
93 if (!cmd_line.HasSwitch(switches::kNoPreReadMainDll)) {
94 base::PreReadFile(module, /*is_executable=*/true);
96 HMODULE handle = ::LoadLibraryExW(module.value().c_str(), nullptr,
97 LOAD_WITH_ALTERED_SEARCH_PATH);
101 // Prefetches and loads the appropriate DLL for the process type
102 // |process_type_|. Populates |module| with the path of the loaded DLL.
103 // Returns a handle to the loaded DLL, or nullptr on failure.
104 HMODULE Load(base::FilePath* module, const base::CommandLine& cmd_line) {
105 *module = GetModulePath(installer::kChromeDll);
106 if (module->empty()) {
107 PLOG(ERROR) << "Cannot find module " << installer::kChromeDll;
110 HMODULE dll = LoadModuleWithDirectory(*module, cmd_line);
112 PLOG(ERROR) << "Failed to load Chrome DLL from " << module->value();
118 //=============================================================================
120 MainDllLoader::MainDllLoader() : dll_(nullptr) {}
122 MainDllLoader::~MainDllLoader() = default;
124 const int kNonBrowserShutdownPriority = 0x280;
126 // Launching is a matter of loading the right dll and calling the entry point.
127 // Derived classes can add custom code in the OnBeforeLaunch callback.
128 int MainDllLoader::Launch(HINSTANCE instance,
129 base::TimeTicks exe_entry_point_ticks) {
130 const base::CommandLine& cmd_line = *base::CommandLine::ForCurrentProcess();
131 process_type_ = cmd_line.GetSwitchValueASCII(switches::kProcessType);
133 // Initialize the sandbox services.
134 sandbox::SandboxInterfaceInfo sandbox_info = {nullptr};
135 const bool is_browser = process_type_.empty();
136 // IsUnsandboxedSandboxType() can't be used here because its result can be
137 // gated behind a feature flag, which are not yet initialized.
138 const bool is_sandboxed =
139 sandbox::policy::SandboxTypeFromCommandLine(cmd_line) !=
140 sandbox::mojom::Sandbox::kNoSandbox;
141 if (is_browser || is_sandboxed) {
142 // For child processes that are running as --no-sandbox, don't initialize
143 // the sandbox info, otherwise they'll be treated as brokers (as if they
144 // were the browser).
145 content::InitializeSandboxInfo(
146 &sandbox_info, IsExtensionPointDisableSet()
147 ? sandbox::MITIGATION_EXTENSION_POINT_DISABLE
152 dll_ = Load(&file, cmd_line);
154 return chrome::RESULT_CODE_MISSING_DATA;
157 // Set non-browser processes up to be killed by the system after the
158 // browser goes away. The browser uses the default shutdown order, which
159 // is 0x280. Note that lower numbers here denote "kill later" and higher
160 // numbers mean "kill sooner". This gets rid of most of those unsightly
161 // sad tabs on logout and shutdown.
162 ::SetProcessShutdownParameters(kNonBrowserShutdownPriority - 1,
166 OnBeforeLaunch(process_type_, file);
167 DLL_MAIN chrome_main =
168 reinterpret_cast<DLL_MAIN>(::GetProcAddress(dll_, "ChromeMain"));
169 int rc = chrome_main(instance, &sandbox_info,
170 exe_entry_point_ticks.ToInternalValue());
174 void MainDllLoader::RelaunchChromeBrowserWithNewCommandLineIfNeeded() {
175 // The relaunch-if-needed behavior is a NOP for processes other than the
176 // browser process, so early out here.
177 if (!dll_ || !process_type_.empty())
180 RelaunchChromeBrowserWithNewCommandLineIfNeededFunc relaunch_function =
181 reinterpret_cast<RelaunchChromeBrowserWithNewCommandLineIfNeededFunc>(
182 ::GetProcAddress(dll_,
183 "RelaunchChromeBrowserWithNewCommandLineIfNeeded"));
184 CHECK(relaunch_function);
188 //=============================================================================
190 class ChromeDllLoader : public MainDllLoader {
192 // MainDllLoader implementation.
193 void OnBeforeLaunch(const std::string& process_type,
194 const base::FilePath& dll_path) override;
197 void ChromeDllLoader::OnBeforeLaunch(const std::string& process_type,
198 const base::FilePath& dll_path) {
199 if (process_type.empty()) {
200 if constexpr (kShouldRecordActiveUse) {
201 RecordDidRun(dll_path);
204 // Set non-browser processes up to be killed by the system after the browser
205 // goes away. The browser uses the default shutdown order, which is 0x280.
206 // Note that lower numbers here denote "kill later" and higher numbers mean
208 // This gets rid of most of those unsightly sad tabs on logout and shutdown.
209 ::SetProcessShutdownParameters(kNonBrowserShutdownPriority - 1,
214 //=============================================================================
216 MainDllLoader* MakeMainDllLoader() {
217 #if BUILDFLAG(GOOGLE_CHROME_BRANDING)
218 return new ChromeDllLoader();
220 return new MainDllLoader();