electron_main_win.cc 8.8 KB

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