electron_main_win.cc 8.9 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/environment.h"
  17. #include "base/i18n/icu_util.h"
  18. #include "base/process/launch.h"
  19. #include "base/strings/utf_string_conversions.h"
  20. #include "base/win/windows_version.h"
  21. #include "components/browser_watcher/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. ALLOW_UNUSED_TYPE 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. wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc);
  118. ~Arguments() { LocalFree(argv); }
  119. } arguments;
  120. if (!arguments.argv)
  121. return -1;
  122. #ifdef _DEBUG
  123. // Don't display assert dialog boxes in CI test runs
  124. static const char kCI[] = "CI";
  125. if (IsEnvSet(kCI)) {
  126. _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE);
  127. _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
  128. _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE);
  129. _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
  130. _set_error_mode(_OUT_TO_STDERR);
  131. }
  132. #endif
  133. #if BUILDFLAG(ENABLE_RUN_AS_NODE)
  134. bool run_as_node =
  135. electron::fuses::IsRunAsNodeEnabled() && IsEnvSet(electron::kRunAsNode);
  136. #else
  137. bool run_as_node = false;
  138. #endif
  139. // Make sure the output is printed to console.
  140. if (run_as_node || !IsEnvSet("ELECTRON_NO_ATTACH_CONSOLE"))
  141. base::RouteStdioToConsole(false);
  142. std::vector<char*> argv(arguments.argc);
  143. std::transform(arguments.argv, arguments.argv + arguments.argc, argv.begin(),
  144. [](auto& a) { return _strdup(base::WideToUTF8(a).c_str()); });
  145. #if BUILDFLAG(ENABLE_RUN_AS_NODE)
  146. if (electron::fuses::IsRunAsNodeEnabled() && run_as_node) {
  147. base::AtExitManager atexit_manager;
  148. base::i18n::InitializeICU();
  149. auto ret = electron::NodeMain(argv.size(), argv.data());
  150. std::for_each(argv.begin(), argv.end(), free);
  151. return ret;
  152. }
  153. #endif
  154. base::CommandLine::Init(argv.size(), argv.data());
  155. const base::CommandLine* command_line =
  156. base::CommandLine::ForCurrentProcess();
  157. const std::string process_type =
  158. command_line->GetSwitchValueASCII(kProcessType);
  159. if (process_type == crash_reporter::switches::kCrashpadHandler) {
  160. // Check if we should monitor the exit code of this process
  161. std::unique_ptr<browser_watcher::ExitCodeWatcher> exit_code_watcher;
  162. // Retrieve the client process from the command line
  163. crashpad::InitialClientData initial_client_data;
  164. if (initial_client_data.InitializeFromString(
  165. command_line->GetSwitchValueASCII("initial-client-data"))) {
  166. // Setup exit code watcher to monitor the parent process
  167. HANDLE duplicate_handle = INVALID_HANDLE_VALUE;
  168. if (DuplicateHandle(
  169. ::GetCurrentProcess(), initial_client_data.client_process(),
  170. ::GetCurrentProcess(), &duplicate_handle,
  171. PROCESS_QUERY_INFORMATION, FALSE, DUPLICATE_SAME_ACCESS)) {
  172. base::Process parent_process(duplicate_handle);
  173. exit_code_watcher =
  174. std::make_unique<browser_watcher::ExitCodeWatcher>();
  175. if (exit_code_watcher->Initialize(std::move(parent_process))) {
  176. exit_code_watcher->StartWatching();
  177. }
  178. }
  179. }
  180. // The handler process must always be passed the user data dir on the
  181. // command line.
  182. DCHECK(command_line->HasSwitch(kUserDataDir));
  183. base::FilePath user_data_dir =
  184. command_line->GetSwitchValuePath(kUserDataDir);
  185. int crashpad_status = crash_reporter::RunAsCrashpadHandler(
  186. *command_line, user_data_dir, kProcessType, kUserDataDir);
  187. if (crashpad_status != 0 && exit_code_watcher) {
  188. // Crashpad failed to initialize, explicitly stop the exit code watcher
  189. // so the crashpad-handler process can exit with an error
  190. exit_code_watcher->StopWatching();
  191. }
  192. return crashpad_status;
  193. }
  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(arguments.argc, arguments.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. }