electron_main_win.cc 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  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 <vector>
  15. #include "base/at_exit.h"
  16. #include "base/debug/alias.h"
  17. #include "base/i18n/icu_util.h"
  18. #include "base/memory/raw_ptr_exclusion.h"
  19. #include "base/process/launch.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. bool IsEnvSet(const char* name) {
  42. size_t required_size;
  43. getenv_s(&required_size, nullptr, 0, name);
  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. struct Arguments {
  117. int argc = 0;
  118. RAW_PTR_EXCLUSION wchar_t** argv =
  119. ::CommandLineToArgvW(::GetCommandLineW(), &argc);
  120. ~Arguments() { LocalFree(argv); }
  121. } arguments;
  122. if (!arguments.argv)
  123. return -1;
  124. #ifdef _DEBUG
  125. // Don't display assert dialog boxes in CI test runs
  126. static const char kCI[] = "CI";
  127. if (IsEnvSet(kCI)) {
  128. _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE);
  129. _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
  130. _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE);
  131. _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
  132. _set_error_mode(_OUT_TO_STDERR);
  133. }
  134. #endif
  135. bool run_as_node =
  136. electron::fuses::IsRunAsNodeEnabled() && IsEnvSet(electron::kRunAsNode);
  137. // Make sure the output is printed to console.
  138. if (run_as_node || !IsEnvSet("ELECTRON_NO_ATTACH_CONSOLE"))
  139. base::RouteStdioToConsole(false);
  140. std::vector<char*> argv(arguments.argc);
  141. std::transform(arguments.argv, arguments.argv + arguments.argc, argv.begin(),
  142. [](auto& a) { return _strdup(base::WideToUTF8(a).c_str()); });
  143. if (run_as_node) {
  144. base::AtExitManager atexit_manager;
  145. base::i18n::InitializeICU();
  146. auto ret = electron::NodeMain(argv.size(), argv.data());
  147. std::ranges::for_each(argv, free);
  148. return ret;
  149. }
  150. base::CommandLine::Init(argv.size(), argv.data());
  151. const base::CommandLine* command_line =
  152. base::CommandLine::ForCurrentProcess();
  153. const std::string process_type =
  154. command_line->GetSwitchValueASCII(kProcessType);
  155. if (process_type == crash_reporter::switches::kCrashpadHandler) {
  156. // Check if we should monitor the exit code of this process
  157. std::unique_ptr<ExitCodeWatcher> exit_code_watcher;
  158. // Retrieve the client process from the command line
  159. crashpad::InitialClientData initial_client_data;
  160. if (initial_client_data.InitializeFromString(
  161. command_line->GetSwitchValueASCII("initial-client-data"))) {
  162. // Setup exit code watcher to monitor the parent process
  163. HANDLE duplicate_handle = INVALID_HANDLE_VALUE;
  164. if (DuplicateHandle(
  165. ::GetCurrentProcess(), initial_client_data.client_process(),
  166. ::GetCurrentProcess(), &duplicate_handle,
  167. PROCESS_QUERY_INFORMATION, FALSE, DUPLICATE_SAME_ACCESS)) {
  168. base::Process parent_process(duplicate_handle);
  169. exit_code_watcher = std::make_unique<ExitCodeWatcher>();
  170. if (exit_code_watcher->Initialize(std::move(parent_process))) {
  171. exit_code_watcher->StartWatching();
  172. }
  173. }
  174. }
  175. // The handler process must always be passed the user data dir on the
  176. // command line.
  177. DCHECK(command_line->HasSwitch(kUserDataDir));
  178. base::FilePath user_data_dir =
  179. command_line->GetSwitchValuePath(kUserDataDir);
  180. int crashpad_status = crash_reporter::RunAsCrashpadHandler(
  181. *command_line, user_data_dir, kProcessType, kUserDataDir);
  182. if (crashpad_status != 0 && exit_code_watcher) {
  183. // Crashpad failed to initialize, explicitly stop the exit code watcher
  184. // so the crashpad-handler process can exit with an error
  185. exit_code_watcher->StopWatching();
  186. }
  187. return crashpad_status;
  188. }
  189. #if BUILDFLAG(IS_WIN)
  190. // access ui native theme here to prevent blocking calls later
  191. base::win::AllowDarkModeForApp(true);
  192. #endif
  193. #if defined(ARCH_CPU_32_BITS)
  194. // Intentionally crash if converting to a fiber failed.
  195. CHECK_EQ(fiber_status, FiberStatus::kSuccess);
  196. #endif // defined(ARCH_CPU_32_BITS)
  197. if (!electron::CheckCommandLineArguments(command_line->argv()))
  198. return -1;
  199. sandbox::SandboxInterfaceInfo sandbox_info = {nullptr};
  200. content::InitializeSandboxInfo(&sandbox_info);
  201. electron::ElectronMainDelegate delegate;
  202. content::ContentMainParams params(&delegate);
  203. params.instance = instance;
  204. params.sandbox_info = &sandbox_info;
  205. electron::ElectronCommandLine::Init(arguments.argc, arguments.argv);
  206. return content::ContentMain(std::move(params));
  207. }