electron_main_win.cc 8.9 KB

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