electron_main_win.cc 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. // Copyright (c) 2022 Slack Technologies, Inc.
  2. // Use of this source code is governed by the MIT license that can be
  3. // found in the LICENSE file.
  4. #include <windows.h> // windows.h must be included first
  5. #include <atlbase.h> // ensures that ATL statics like `_AtlWinModule` are initialized (it's an issue in static debug build)
  6. #include <shellapi.h>
  7. #include <shellscalingapi.h>
  8. #include <tchar.h>
  9. #include <algorithm>
  10. #include <cstdlib>
  11. #include <memory>
  12. #include <string>
  13. #include <utility>
  14. #include "base/at_exit.h"
  15. #include "base/debug/alias.h"
  16. #include "base/i18n/icu_util.h"
  17. #include "base/memory/raw_ptr_exclusion.h"
  18. #include "base/process/launch.h"
  19. #include "base/strings/cstring_view.h"
  20. #include "base/strings/utf_string_conversions.h"
  21. #include "base/win/dark_mode_support.h"
  22. #include "chrome/app/exit_code_watcher_win.h"
  23. #include "components/crash/core/app/crash_switches.h"
  24. #include "components/crash/core/app/run_as_crashpad_handler_win.h"
  25. #include "content/public/app/content_main.h"
  26. #include "content/public/app/sandbox_helper_win.h"
  27. #include "electron/buildflags/buildflags.h"
  28. #include "electron/fuses.h"
  29. #include "sandbox/win/src/sandbox_types.h"
  30. #include "shell/app/command_line_args.h"
  31. #include "shell/app/electron_main_delegate.h"
  32. #include "shell/app/node_main.h"
  33. #include "shell/common/electron_command_line.h"
  34. #include "shell/common/electron_constants.h"
  35. #include "third_party/crashpad/crashpad/util/win/initial_client_data.h"
  36. namespace {
  37. // Redefined here so we don't have to introduce a dependency on //content
  38. // from //electron:electron_app
  39. const char kUserDataDir[] = "user-data-dir";
  40. const char kProcessType[] = "type";
  41. [[nodiscard]] bool IsEnvSet(const base::cstring_view name) {
  42. size_t required_size = 0;
  43. getenv_s(&required_size, nullptr, 0, name.c_str());
  44. return required_size != 0;
  45. }
  46. } // namespace
  47. namespace crash_reporter {
  48. extern const char kCrashpadProcess[];
  49. }
  50. // In 32-bit builds, the main thread starts with the default (small) stack size.
  51. // The ARCH_CPU_32_BITS blocks here and below are in support of moving the main
  52. // thread to a fiber with a larger stack size.
  53. #if defined(ARCH_CPU_32_BITS)
  54. // The information needed to transfer control to the large-stack fiber and later
  55. // pass the main routine's exit code back to the small-stack fiber prior to
  56. // termination.
  57. struct FiberState {
  58. HINSTANCE instance;
  59. LPVOID original_fiber;
  60. int fiber_result;
  61. };
  62. // A PFIBER_START_ROUTINE function run on a large-stack fiber that calls the
  63. // main routine, stores its return value, and returns control to the small-stack
  64. // fiber. |params| must be a pointer to a FiberState struct.
  65. void WINAPI FiberBinder(void* params) {
  66. auto* fiber_state = static_cast<FiberState*>(params);
  67. // Call the wWinMain routine from the fiber. Reusing the entry point minimizes
  68. // confusion when examining call stacks in crash reports - seeing wWinMain on
  69. // the stack is a handy hint that this is the main thread of the process.
  70. fiber_state->fiber_result =
  71. wWinMain(fiber_state->instance, nullptr, nullptr, 0);
  72. // Switch back to the main thread to exit.
  73. ::SwitchToFiber(fiber_state->original_fiber);
  74. }
  75. #endif // defined(ARCH_CPU_32_BITS)
  76. int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE, wchar_t* cmd, int) {
  77. #if defined(ARCH_CPU_32_BITS)
  78. enum class FiberStatus { kConvertFailed, kCreateFiberFailed, kSuccess };
  79. FiberStatus fiber_status = FiberStatus::kSuccess;
  80. // GetLastError result if fiber conversion failed.
  81. DWORD fiber_error = ERROR_SUCCESS;
  82. if (!::IsThreadAFiber()) {
  83. // Make the main thread's stack size 4 MiB so that it has roughly the same
  84. // effective size as the 64-bit build's 8 MiB stack.
  85. constexpr size_t kStackSize = 4 * 1024 * 1024; // 4 MiB
  86. // Leak the fiber on exit.
  87. LPVOID original_fiber =
  88. ::ConvertThreadToFiberEx(nullptr, FIBER_FLAG_FLOAT_SWITCH);
  89. if (original_fiber) {
  90. FiberState fiber_state = {instance, original_fiber};
  91. // Create a fiber with a bigger stack and switch to it. Leak the fiber on
  92. // exit.
  93. LPVOID big_stack_fiber = ::CreateFiberEx(
  94. 0, kStackSize, FIBER_FLAG_FLOAT_SWITCH, FiberBinder, &fiber_state);
  95. if (big_stack_fiber) {
  96. ::SwitchToFiber(big_stack_fiber);
  97. // The fibers must be cleaned up to avoid obscure TLS-related shutdown
  98. // crashes.
  99. ::DeleteFiber(big_stack_fiber);
  100. ::ConvertFiberToThread();
  101. // Control returns here after Chrome has finished running on FiberMain.
  102. return fiber_state.fiber_result;
  103. }
  104. fiber_status = FiberStatus::kCreateFiberFailed;
  105. } else {
  106. fiber_status = FiberStatus::kConvertFailed;
  107. }
  108. // If we reach here then creating and switching to a fiber has failed. This
  109. // probably means we are low on memory and will soon crash. Try to report
  110. // this error once crash reporting is initialized.
  111. fiber_error = ::GetLastError();
  112. base::debug::Alias(&fiber_error);
  113. }
  114. // If we are already a fiber then continue normal execution.
  115. #endif // defined(ARCH_CPU_32_BITS)
  116. {
  117. int argc = 0;
  118. wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc);
  119. if (!argv)
  120. return -1;
  121. base::CommandLine::Init(0, nullptr); // args ignored on Windows
  122. electron::ElectronCommandLine::Init(argc, argv);
  123. LocalFree(argv);
  124. }
  125. #ifdef _DEBUG
  126. // Don't display assert dialog boxes in CI test runs
  127. static constexpr base::cstring_view kCI = "CI";
  128. if (IsEnvSet(kCI)) {
  129. _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE);
  130. _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
  131. _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE);
  132. _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
  133. _set_error_mode(_OUT_TO_STDERR);
  134. }
  135. #endif
  136. bool run_as_node =
  137. electron::fuses::IsRunAsNodeEnabled() && IsEnvSet(electron::kRunAsNode);
  138. // Make sure the output is printed to console.
  139. if (run_as_node || !IsEnvSet("ELECTRON_NO_ATTACH_CONSOLE"))
  140. base::RouteStdioToConsole(false);
  141. if (run_as_node) {
  142. base::AtExitManager atexit_manager;
  143. base::i18n::InitializeICU();
  144. return electron::NodeMain();
  145. }
  146. const base::CommandLine* command_line =
  147. base::CommandLine::ForCurrentProcess();
  148. const std::string process_type =
  149. command_line->GetSwitchValueASCII(kProcessType);
  150. if (process_type == crash_reporter::switches::kCrashpadHandler) {
  151. // Check if we should monitor the exit code of this process
  152. std::unique_ptr<ExitCodeWatcher> exit_code_watcher;
  153. // Retrieve the client process from the command line
  154. crashpad::InitialClientData initial_client_data;
  155. if (initial_client_data.InitializeFromString(
  156. command_line->GetSwitchValueASCII("initial-client-data"))) {
  157. // Setup exit code watcher to monitor the parent process
  158. HANDLE duplicate_handle = INVALID_HANDLE_VALUE;
  159. if (DuplicateHandle(
  160. ::GetCurrentProcess(), initial_client_data.client_process(),
  161. ::GetCurrentProcess(), &duplicate_handle,
  162. PROCESS_QUERY_INFORMATION, FALSE, DUPLICATE_SAME_ACCESS)) {
  163. base::Process parent_process(duplicate_handle);
  164. exit_code_watcher = std::make_unique<ExitCodeWatcher>();
  165. if (exit_code_watcher->Initialize(std::move(parent_process))) {
  166. exit_code_watcher->StartWatching();
  167. }
  168. }
  169. }
  170. // The handler process must always be passed the user data dir on the
  171. // command line.
  172. DCHECK(command_line->HasSwitch(kUserDataDir));
  173. base::FilePath user_data_dir =
  174. command_line->GetSwitchValuePath(kUserDataDir);
  175. int crashpad_status = crash_reporter::RunAsCrashpadHandler(
  176. *command_line, user_data_dir, kProcessType, kUserDataDir);
  177. if (crashpad_status != 0 && exit_code_watcher) {
  178. // Crashpad failed to initialize, explicitly stop the exit code watcher
  179. // so the crashpad-handler process can exit with an error
  180. exit_code_watcher->StopWatching();
  181. }
  182. return crashpad_status;
  183. }
  184. #if BUILDFLAG(IS_WIN)
  185. // access ui native theme here to prevent blocking calls later
  186. base::win::AllowDarkModeForApp(true);
  187. #endif
  188. #if defined(ARCH_CPU_32_BITS)
  189. // Intentionally crash if converting to a fiber failed.
  190. CHECK_EQ(fiber_status, FiberStatus::kSuccess);
  191. #endif // defined(ARCH_CPU_32_BITS)
  192. if (!electron::CheckCommandLineArguments(command_line->argv()))
  193. return -1;
  194. sandbox::SandboxInterfaceInfo sandbox_info = {nullptr};
  195. content::InitializeSandboxInfo(&sandbox_info);
  196. electron::ElectronMainDelegate delegate;
  197. content::ContentMainParams params(&delegate);
  198. params.instance = instance;
  199. params.sandbox_info = &sandbox_info;
  200. return content::ContentMain(std::move(params));
  201. }