electron_main.cc 13 KB

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