electron_main_win.cc 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  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. [[maybe_unused]] 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. #if BUILDFLAG(ENABLE_RUN_AS_NODE)
  137. bool run_as_node =
  138. electron::fuses::IsRunAsNodeEnabled() && IsEnvSet(electron::kRunAsNode);
  139. #else
  140. bool run_as_node = false;
  141. #endif
  142. // Make sure the output is printed to console.
  143. if (run_as_node || !IsEnvSet("ELECTRON_NO_ATTACH_CONSOLE"))
  144. base::RouteStdioToConsole(false);
  145. std::vector<char*> argv(arguments.argc);
  146. std::transform(arguments.argv, arguments.argv + arguments.argc, argv.begin(),
  147. [](auto& a) { return _strdup(base::WideToUTF8(a).c_str()); });
  148. #if BUILDFLAG(ENABLE_RUN_AS_NODE)
  149. if (electron::fuses::IsRunAsNodeEnabled() && run_as_node) {
  150. base::AtExitManager atexit_manager;
  151. base::i18n::InitializeICU();
  152. auto ret = electron::NodeMain(argv.size(), argv.data());
  153. std::for_each(argv.begin(), argv.end(), free);
  154. return ret;
  155. }
  156. #endif
  157. base::CommandLine::Init(argv.size(), argv.data());
  158. const base::CommandLine* command_line =
  159. base::CommandLine::ForCurrentProcess();
  160. const std::string process_type =
  161. command_line->GetSwitchValueASCII(kProcessType);
  162. if (process_type == crash_reporter::switches::kCrashpadHandler) {
  163. // Check if we should monitor the exit code of this process
  164. std::unique_ptr<ExitCodeWatcher> exit_code_watcher;
  165. // Retrieve the client process from the command line
  166. crashpad::InitialClientData initial_client_data;
  167. if (initial_client_data.InitializeFromString(
  168. command_line->GetSwitchValueASCII("initial-client-data"))) {
  169. // Setup exit code watcher to monitor the parent process
  170. HANDLE duplicate_handle = INVALID_HANDLE_VALUE;
  171. if (DuplicateHandle(
  172. ::GetCurrentProcess(), initial_client_data.client_process(),
  173. ::GetCurrentProcess(), &duplicate_handle,
  174. PROCESS_QUERY_INFORMATION, FALSE, DUPLICATE_SAME_ACCESS)) {
  175. base::Process parent_process(duplicate_handle);
  176. exit_code_watcher = std::make_unique<ExitCodeWatcher>();
  177. if (exit_code_watcher->Initialize(std::move(parent_process))) {
  178. exit_code_watcher->StartWatching();
  179. }
  180. }
  181. }
  182. // The handler process must always be passed the user data dir on the
  183. // command line.
  184. DCHECK(command_line->HasSwitch(kUserDataDir));
  185. base::FilePath user_data_dir =
  186. command_line->GetSwitchValuePath(kUserDataDir);
  187. int crashpad_status = crash_reporter::RunAsCrashpadHandler(
  188. *command_line, user_data_dir, kProcessType, kUserDataDir);
  189. if (crashpad_status != 0 && exit_code_watcher) {
  190. // Crashpad failed to initialize, explicitly stop the exit code watcher
  191. // so the crashpad-handler process can exit with an error
  192. exit_code_watcher->StopWatching();
  193. }
  194. return crashpad_status;
  195. }
  196. #if BUILDFLAG(IS_WIN)
  197. // access ui native theme here to prevent blocking calls later
  198. base::win::AllowDarkModeForApp(true);
  199. #endif
  200. #if defined(ARCH_CPU_32_BITS)
  201. // Intentionally crash if converting to a fiber failed.
  202. CHECK_EQ(fiber_status, FiberStatus::kSuccess);
  203. #endif // defined(ARCH_CPU_32_BITS)
  204. if (!electron::CheckCommandLineArguments(arguments.argc, arguments.argv))
  205. return -1;
  206. sandbox::SandboxInterfaceInfo sandbox_info = {nullptr};
  207. content::InitializeSandboxInfo(&sandbox_info);
  208. electron::ElectronMainDelegate delegate;
  209. content::ContentMainParams params(&delegate);
  210. params.instance = instance;
  211. params.sandbox_info = &sandbox_info;
  212. electron::ElectronCommandLine::Init(arguments.argc, arguments.argv);
  213. return content::ContentMain(std::move(params));
  214. }