electron_main.cc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. // Copyright (c) 2013 GitHub, Inc.
  2. // Use of this source code is governed by the MIT license that can be
  3. // found in the LICENSE file.
  4. #include "shell/app/electron_main.h"
  5. #include <algorithm>
  6. #include <cstdlib>
  7. #include <memory>
  8. #include <string>
  9. #include <utility>
  10. #include <vector>
  11. #if defined(OS_WIN)
  12. #include <windows.h> // windows.h must be included first
  13. #include <atlbase.h> // ensures that ATL statics like `_AtlWinModule` are initialized (it's an issue in static debug build)
  14. #include <shellapi.h>
  15. #include <shellscalingapi.h>
  16. #include <tchar.h>
  17. #include "base/environment.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/sandbox_helper_win.h"
  25. #include "sandbox/win/src/sandbox_types.h"
  26. #include "shell/app/command_line_args.h"
  27. #include "shell/app/electron_main_delegate.h"
  28. #include "third_party/crashpad/crashpad/util/win/initial_client_data.h"
  29. #elif defined(OS_LINUX) // defined(OS_WIN)
  30. #include <unistd.h>
  31. #include <cstdio>
  32. #include "content/public/app/content_main.h"
  33. #include "shell/app/electron_main_delegate.h" // NOLINT
  34. #else // defined(OS_LINUX)
  35. #include <mach-o/dyld.h>
  36. #include <unistd.h>
  37. #include <cstdio>
  38. #include "shell/app/electron_library_main.h"
  39. #endif // defined(OS_MAC)
  40. #include "base/at_exit.h"
  41. #include "base/i18n/icu_util.h"
  42. #include "electron/buildflags/buildflags.h"
  43. #include "electron/fuses.h"
  44. #include "shell/app/node_main.h"
  45. #include "shell/common/electron_command_line.h"
  46. #include "shell/common/electron_constants.h"
  47. #if defined(HELPER_EXECUTABLE) && !defined(MAS_BUILD)
  48. #include "sandbox/mac/seatbelt_exec.h" // nogncheck
  49. #endif
  50. namespace {
  51. #if defined(OS_WIN)
  52. // Redefined here so we don't have to introduce a dependency on //content
  53. // from //electron:electron_app
  54. const char kUserDataDir[] = "user-data-dir";
  55. const char kProcessType[] = "type";
  56. #endif
  57. ALLOW_UNUSED_TYPE bool IsEnvSet(const char* name) {
  58. #if defined(OS_WIN)
  59. size_t required_size;
  60. getenv_s(&required_size, nullptr, 0, name);
  61. return required_size != 0;
  62. #else
  63. char* indicator = getenv(name);
  64. return indicator && indicator[0] != '\0';
  65. #endif
  66. }
  67. #if defined(OS_POSIX)
  68. void FixStdioStreams() {
  69. // libuv may mark stdin/stdout/stderr as close-on-exec, which interferes
  70. // with chromium's subprocess spawning. As a workaround, we detect if these
  71. // streams are closed on startup, and reopen them as /dev/null if necessary.
  72. // Otherwise, an unrelated file descriptor will be assigned as stdout/stderr
  73. // which may cause various errors when attempting to write to them.
  74. //
  75. // For details see https://github.com/libuv/libuv/issues/2062
  76. struct stat st;
  77. if (fstat(STDIN_FILENO, &st) < 0 && errno == EBADF)
  78. ignore_result(freopen("/dev/null", "r", stdin));
  79. if (fstat(STDOUT_FILENO, &st) < 0 && errno == EBADF)
  80. ignore_result(freopen("/dev/null", "w", stdout));
  81. if (fstat(STDERR_FILENO, &st) < 0 && errno == EBADF)
  82. ignore_result(freopen("/dev/null", "w", stderr));
  83. }
  84. #endif
  85. } // namespace
  86. #if defined(OS_WIN)
  87. namespace crash_reporter {
  88. extern const char kCrashpadProcess[];
  89. }
  90. // In 32-bit builds, the main thread starts with the default (small) stack size.
  91. // The ARCH_CPU_32_BITS blocks here and below are in support of moving the main
  92. // thread to a fiber with a larger stack size.
  93. #if defined(ARCH_CPU_32_BITS)
  94. // The information needed to transfer control to the large-stack fiber and later
  95. // pass the main routine's exit code back to the small-stack fiber prior to
  96. // termination.
  97. struct FiberState {
  98. HINSTANCE instance;
  99. LPVOID original_fiber;
  100. int fiber_result;
  101. };
  102. // A PFIBER_START_ROUTINE function run on a large-stack fiber that calls the
  103. // main routine, stores its return value, and returns control to the small-stack
  104. // fiber. |params| must be a pointer to a FiberState struct.
  105. void WINAPI FiberBinder(void* params) {
  106. auto* fiber_state = static_cast<FiberState*>(params);
  107. // Call the wWinMain routine from the fiber. Reusing the entry point minimizes
  108. // confusion when examining call stacks in crash reports - seeing wWinMain on
  109. // the stack is a handy hint that this is the main thread of the process.
  110. fiber_state->fiber_result =
  111. wWinMain(fiber_state->instance, nullptr, nullptr, 0);
  112. // Switch back to the main thread to exit.
  113. ::SwitchToFiber(fiber_state->original_fiber);
  114. }
  115. #endif // defined(ARCH_CPU_32_BITS)
  116. int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE, wchar_t* cmd, int) {
  117. #if defined(ARCH_CPU_32_BITS)
  118. enum class FiberStatus { kConvertFailed, kCreateFiberFailed, kSuccess };
  119. FiberStatus fiber_status = FiberStatus::kSuccess;
  120. // GetLastError result if fiber conversion failed.
  121. DWORD fiber_error = ERROR_SUCCESS;
  122. if (!::IsThreadAFiber()) {
  123. // Make the main thread's stack size 4 MiB so that it has roughly the same
  124. // effective size as the 64-bit build's 8 MiB stack.
  125. constexpr size_t kStackSize = 4 * 1024 * 1024; // 4 MiB
  126. // Leak the fiber on exit.
  127. LPVOID original_fiber =
  128. ::ConvertThreadToFiberEx(nullptr, FIBER_FLAG_FLOAT_SWITCH);
  129. if (original_fiber) {
  130. FiberState fiber_state = {instance, original_fiber};
  131. // Create a fiber with a bigger stack and switch to it. Leak the fiber on
  132. // exit.
  133. LPVOID big_stack_fiber = ::CreateFiberEx(
  134. 0, kStackSize, FIBER_FLAG_FLOAT_SWITCH, FiberBinder, &fiber_state);
  135. if (big_stack_fiber) {
  136. ::SwitchToFiber(big_stack_fiber);
  137. // The fibers must be cleaned up to avoid obscure TLS-related shutdown
  138. // crashes.
  139. ::DeleteFiber(big_stack_fiber);
  140. ::ConvertFiberToThread();
  141. // Control returns here after Chrome has finished running on FiberMain.
  142. return fiber_state.fiber_result;
  143. }
  144. fiber_status = FiberStatus::kCreateFiberFailed;
  145. } else {
  146. fiber_status = FiberStatus::kConvertFailed;
  147. }
  148. // If we reach here then creating and switching to a fiber has failed. This
  149. // probably means we are low on memory and will soon crash. Try to report
  150. // this error once crash reporting is initialized.
  151. fiber_error = ::GetLastError();
  152. base::debug::Alias(&fiber_error);
  153. }
  154. // If we are already a fiber then continue normal execution.
  155. #endif // defined(ARCH_CPU_32_BITS)
  156. struct Arguments {
  157. int argc = 0;
  158. wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc);
  159. ~Arguments() { LocalFree(argv); }
  160. } arguments;
  161. if (!arguments.argv)
  162. return -1;
  163. #ifdef _DEBUG
  164. // Don't display assert dialog boxes in CI test runs
  165. static const char* kCI = "CI";
  166. if (IsEnvSet(kCI)) {
  167. _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE);
  168. _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
  169. _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE);
  170. _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
  171. _set_error_mode(_OUT_TO_STDERR);
  172. }
  173. #endif
  174. #if BUILDFLAG(ENABLE_RUN_AS_NODE)
  175. bool run_as_node =
  176. electron::fuses::IsRunAsNodeEnabled() && IsEnvSet(electron::kRunAsNode);
  177. #else
  178. bool run_as_node = false;
  179. #endif
  180. // Make sure the output is printed to console.
  181. if (run_as_node || !IsEnvSet("ELECTRON_NO_ATTACH_CONSOLE"))
  182. base::RouteStdioToConsole(false);
  183. std::vector<char*> argv(arguments.argc);
  184. std::transform(arguments.argv, arguments.argv + arguments.argc, argv.begin(),
  185. [](auto& a) { return _strdup(base::WideToUTF8(a).c_str()); });
  186. #if BUILDFLAG(ENABLE_RUN_AS_NODE)
  187. if (electron::fuses::IsRunAsNodeEnabled() && run_as_node) {
  188. base::AtExitManager atexit_manager;
  189. base::i18n::InitializeICU();
  190. auto ret = electron::NodeMain(argv.size(), argv.data());
  191. std::for_each(argv.begin(), argv.end(), free);
  192. return ret;
  193. }
  194. #endif
  195. base::CommandLine::Init(argv.size(), argv.data());
  196. const base::CommandLine* command_line =
  197. base::CommandLine::ForCurrentProcess();
  198. const std::string process_type =
  199. command_line->GetSwitchValueASCII(kProcessType);
  200. if (process_type == crash_reporter::switches::kCrashpadHandler) {
  201. // Check if we should monitor the exit code of this process
  202. std::unique_ptr<browser_watcher::ExitCodeWatcher> exit_code_watcher;
  203. // Retrieve the client process from the command line
  204. crashpad::InitialClientData initial_client_data;
  205. if (initial_client_data.InitializeFromString(
  206. command_line->GetSwitchValueASCII("initial-client-data"))) {
  207. // Setup exit code watcher to monitor the parent process
  208. HANDLE duplicate_handle = INVALID_HANDLE_VALUE;
  209. if (DuplicateHandle(
  210. ::GetCurrentProcess(), initial_client_data.client_process(),
  211. ::GetCurrentProcess(), &duplicate_handle,
  212. PROCESS_QUERY_INFORMATION, FALSE, DUPLICATE_SAME_ACCESS)) {
  213. base::Process parent_process(duplicate_handle);
  214. exit_code_watcher =
  215. std::make_unique<browser_watcher::ExitCodeWatcher>();
  216. if (exit_code_watcher->Initialize(std::move(parent_process))) {
  217. exit_code_watcher->StartWatching();
  218. }
  219. }
  220. }
  221. // The handler process must always be passed the user data dir on the
  222. // command line.
  223. DCHECK(command_line->HasSwitch(kUserDataDir));
  224. base::FilePath user_data_dir =
  225. command_line->GetSwitchValuePath(kUserDataDir);
  226. int crashpad_status = crash_reporter::RunAsCrashpadHandler(
  227. *command_line, user_data_dir, kProcessType, kUserDataDir);
  228. if (crashpad_status != 0 && exit_code_watcher) {
  229. // Crashpad failed to initialize, explicitly stop the exit code watcher
  230. // so the crashpad-handler process can exit with an error
  231. exit_code_watcher->StopWatching();
  232. }
  233. return crashpad_status;
  234. }
  235. #if defined(ARCH_CPU_32_BITS)
  236. // Intentionally crash if converting to a fiber failed.
  237. CHECK_EQ(fiber_status, FiberStatus::kSuccess);
  238. #endif // defined(ARCH_CPU_32_BITS)
  239. if (!electron::CheckCommandLineArguments(arguments.argc, arguments.argv))
  240. return -1;
  241. sandbox::SandboxInterfaceInfo sandbox_info = {0};
  242. content::InitializeSandboxInfo(&sandbox_info);
  243. electron::ElectronMainDelegate delegate;
  244. content::ContentMainParams params(&delegate);
  245. params.instance = instance;
  246. params.sandbox_info = &sandbox_info;
  247. electron::ElectronCommandLine::Init(arguments.argc, arguments.argv);
  248. return content::ContentMain(params);
  249. }
  250. #elif defined(OS_LINUX) // defined(OS_WIN)
  251. int main(int argc, char* argv[]) {
  252. FixStdioStreams();
  253. #if BUILDFLAG(ENABLE_RUN_AS_NODE)
  254. if (electron::fuses::IsRunAsNodeEnabled() && IsEnvSet(electron::kRunAsNode)) {
  255. base::i18n::InitializeICU();
  256. base::AtExitManager atexit_manager;
  257. return electron::NodeMain(argc, argv);
  258. }
  259. #endif
  260. electron::ElectronMainDelegate delegate;
  261. content::ContentMainParams params(&delegate);
  262. params.argc = argc;
  263. params.argv = const_cast<const char**>(argv);
  264. electron::ElectronCommandLine::Init(argc, argv);
  265. return content::ContentMain(params);
  266. }
  267. #else // defined(OS_LINUX)
  268. int main(int argc, char* argv[]) {
  269. FixStdioStreams();
  270. #if BUILDFLAG(ENABLE_RUN_AS_NODE)
  271. if (electron::fuses::IsRunAsNodeEnabled() && IsEnvSet(electron::kRunAsNode)) {
  272. return ElectronInitializeICUandStartNode(argc, argv);
  273. }
  274. #endif
  275. #if defined(HELPER_EXECUTABLE) && !defined(MAS_BUILD)
  276. uint32_t exec_path_size = 0;
  277. int rv = _NSGetExecutablePath(NULL, &exec_path_size);
  278. if (rv != -1) {
  279. fprintf(stderr, "_NSGetExecutablePath: get length failed\n");
  280. abort();
  281. }
  282. std::unique_ptr<char[]> exec_path(new char[exec_path_size]);
  283. rv = _NSGetExecutablePath(exec_path.get(), &exec_path_size);
  284. if (rv != 0) {
  285. fprintf(stderr, "_NSGetExecutablePath: get path failed\n");
  286. abort();
  287. }
  288. sandbox::SeatbeltExecServer::CreateFromArgumentsResult seatbelt =
  289. sandbox::SeatbeltExecServer::CreateFromArguments(exec_path.get(), argc,
  290. argv);
  291. if (seatbelt.sandbox_required) {
  292. if (!seatbelt.server) {
  293. fprintf(stderr, "Failed to create seatbelt sandbox server.\n");
  294. abort();
  295. }
  296. if (!seatbelt.server->InitializeSandbox()) {
  297. fprintf(stderr, "Failed to initialize sandbox.\n");
  298. abort();
  299. }
  300. }
  301. #endif // defined(HELPER_EXECUTABLE) && !defined(MAS_BUILD)
  302. return ElectronMain(argc, argv);
  303. }
  304. #endif // defined(OS_MAC)