electron_main_win.cc 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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/dark_mode_support.h"
  21. #include "base/win/windows_version.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. [[maybe_unused]] 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. wchar_t** argv = ::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. #if BUILDFLAG(ENABLE_RUN_AS_NODE)
  135. bool run_as_node =
  136. electron::fuses::IsRunAsNodeEnabled() && IsEnvSet(electron::kRunAsNode);
  137. #else
  138. bool run_as_node = false;
  139. #endif
  140. // Make sure the output is printed to console.
  141. if (run_as_node || !IsEnvSet("ELECTRON_NO_ATTACH_CONSOLE"))
  142. base::RouteStdioToConsole(false);
  143. std::vector<char*> argv(arguments.argc);
  144. std::transform(arguments.argv, arguments.argv + arguments.argc, argv.begin(),
  145. [](auto& a) { return _strdup(base::WideToUTF8(a).c_str()); });
  146. #if BUILDFLAG(ENABLE_RUN_AS_NODE)
  147. if (electron::fuses::IsRunAsNodeEnabled() && run_as_node) {
  148. base::AtExitManager atexit_manager;
  149. base::i18n::InitializeICU();
  150. auto ret = electron::NodeMain(argv.size(), argv.data());
  151. std::for_each(argv.begin(), argv.end(), free);
  152. return ret;
  153. }
  154. #endif
  155. base::CommandLine::Init(argv.size(), argv.data());
  156. const base::CommandLine* command_line =
  157. base::CommandLine::ForCurrentProcess();
  158. const std::string process_type =
  159. command_line->GetSwitchValueASCII(kProcessType);
  160. if (process_type == crash_reporter::switches::kCrashpadHandler) {
  161. // Check if we should monitor the exit code of this process
  162. std::unique_ptr<ExitCodeWatcher> exit_code_watcher;
  163. // Retrieve the client process from the command line
  164. crashpad::InitialClientData initial_client_data;
  165. if (initial_client_data.InitializeFromString(
  166. command_line->GetSwitchValueASCII("initial-client-data"))) {
  167. // Setup exit code watcher to monitor the parent process
  168. HANDLE duplicate_handle = INVALID_HANDLE_VALUE;
  169. if (DuplicateHandle(
  170. ::GetCurrentProcess(), initial_client_data.client_process(),
  171. ::GetCurrentProcess(), &duplicate_handle,
  172. PROCESS_QUERY_INFORMATION, FALSE, DUPLICATE_SAME_ACCESS)) {
  173. base::Process parent_process(duplicate_handle);
  174. exit_code_watcher = std::make_unique<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 BUILDFLAG(IS_WIN)
  195. // access ui native theme here to prevent blocking calls later
  196. base::win::AllowDarkModeForApp(true);
  197. #endif
  198. #if defined(ARCH_CPU_32_BITS)
  199. // Intentionally crash if converting to a fiber failed.
  200. CHECK_EQ(fiber_status, FiberStatus::kSuccess);
  201. #endif // defined(ARCH_CPU_32_BITS)
  202. if (!electron::CheckCommandLineArguments(arguments.argc, arguments.argv))
  203. return -1;
  204. sandbox::SandboxInterfaceInfo sandbox_info = {nullptr};
  205. content::InitializeSandboxInfo(&sandbox_info);
  206. electron::ElectronMainDelegate delegate;
  207. content::ContentMainParams params(&delegate);
  208. params.instance = instance;
  209. params.sandbox_info = &sandbox_info;
  210. electron::ElectronCommandLine::Init(arguments.argc, arguments.argv);
  211. return content::ContentMain(std::move(params));
  212. }