electron_main.cc 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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. int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE, wchar_t* cmd, int) {
  91. struct Arguments {
  92. int argc = 0;
  93. wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc);
  94. ~Arguments() { LocalFree(argv); }
  95. } arguments;
  96. if (!arguments.argv)
  97. return -1;
  98. #ifdef _DEBUG
  99. // Don't display assert dialog boxes in CI test runs
  100. static const char kCI[] = "CI";
  101. if (IsEnvSet(kCI)) {
  102. _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE);
  103. _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
  104. _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE);
  105. _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
  106. _set_error_mode(_OUT_TO_STDERR);
  107. }
  108. #endif
  109. #if BUILDFLAG(ENABLE_RUN_AS_NODE)
  110. bool run_as_node =
  111. electron::fuses::IsRunAsNodeEnabled() && IsEnvSet(electron::kRunAsNode);
  112. #else
  113. bool run_as_node = false;
  114. #endif
  115. // Make sure the output is printed to console.
  116. if (run_as_node || !IsEnvSet("ELECTRON_NO_ATTACH_CONSOLE"))
  117. base::RouteStdioToConsole(false);
  118. std::vector<char*> argv(arguments.argc);
  119. std::transform(arguments.argv, arguments.argv + arguments.argc, argv.begin(),
  120. [](auto& a) { return _strdup(base::WideToUTF8(a).c_str()); });
  121. #if BUILDFLAG(ENABLE_RUN_AS_NODE)
  122. if (electron::fuses::IsRunAsNodeEnabled() && run_as_node) {
  123. base::AtExitManager atexit_manager;
  124. base::i18n::InitializeICU();
  125. auto ret = electron::NodeMain(argv.size(), argv.data());
  126. std::for_each(argv.begin(), argv.end(), free);
  127. return ret;
  128. }
  129. #endif
  130. base::CommandLine::Init(argv.size(), argv.data());
  131. const base::CommandLine* command_line =
  132. base::CommandLine::ForCurrentProcess();
  133. const std::string process_type =
  134. command_line->GetSwitchValueASCII(kProcessType);
  135. if (process_type == crash_reporter::switches::kCrashpadHandler) {
  136. // Check if we should monitor the exit code of this process
  137. std::unique_ptr<browser_watcher::ExitCodeWatcher> exit_code_watcher;
  138. // Retrieve the client process from the command line
  139. crashpad::InitialClientData initial_client_data;
  140. if (initial_client_data.InitializeFromString(
  141. command_line->GetSwitchValueASCII("initial-client-data"))) {
  142. // Setup exit code watcher to monitor the parent process
  143. HANDLE duplicate_handle = INVALID_HANDLE_VALUE;
  144. if (DuplicateHandle(
  145. ::GetCurrentProcess(), initial_client_data.client_process(),
  146. ::GetCurrentProcess(), &duplicate_handle,
  147. PROCESS_QUERY_INFORMATION, FALSE, DUPLICATE_SAME_ACCESS)) {
  148. base::Process parent_process(duplicate_handle);
  149. exit_code_watcher =
  150. std::make_unique<browser_watcher::ExitCodeWatcher>();
  151. if (exit_code_watcher->Initialize(std::move(parent_process))) {
  152. exit_code_watcher->StartWatching();
  153. }
  154. }
  155. }
  156. // The handler process must always be passed the user data dir on the
  157. // command line.
  158. DCHECK(command_line->HasSwitch(kUserDataDir));
  159. base::FilePath user_data_dir =
  160. command_line->GetSwitchValuePath(kUserDataDir);
  161. int crashpad_status = crash_reporter::RunAsCrashpadHandler(
  162. *command_line, user_data_dir, kProcessType, kUserDataDir);
  163. if (crashpad_status != 0 && exit_code_watcher) {
  164. // Crashpad failed to initialize, explicitly stop the exit code watcher
  165. // so the crashpad-handler process can exit with an error
  166. exit_code_watcher->StopWatching();
  167. }
  168. return crashpad_status;
  169. }
  170. if (!electron::CheckCommandLineArguments(arguments.argc, arguments.argv))
  171. return -1;
  172. sandbox::SandboxInterfaceInfo sandbox_info = {0};
  173. content::InitializeSandboxInfo(&sandbox_info);
  174. electron::ElectronMainDelegate delegate;
  175. content::ContentMainParams params(&delegate);
  176. params.instance = instance;
  177. params.sandbox_info = &sandbox_info;
  178. electron::ElectronCommandLine::Init(arguments.argc, arguments.argv);
  179. return content::ContentMain(params);
  180. }
  181. #elif defined(OS_LINUX) // defined(OS_WIN)
  182. int main(int argc, char* argv[]) {
  183. FixStdioStreams();
  184. #if BUILDFLAG(ENABLE_RUN_AS_NODE)
  185. if (electron::fuses::IsRunAsNodeEnabled() && IsEnvSet(electron::kRunAsNode)) {
  186. base::i18n::InitializeICU();
  187. base::AtExitManager atexit_manager;
  188. return electron::NodeMain(argc, argv);
  189. }
  190. #endif
  191. electron::ElectronMainDelegate delegate;
  192. content::ContentMainParams params(&delegate);
  193. params.argc = argc;
  194. params.argv = const_cast<const char**>(argv);
  195. electron::ElectronCommandLine::Init(argc, argv);
  196. return content::ContentMain(params);
  197. }
  198. #else // defined(OS_LINUX)
  199. int main(int argc, char* argv[]) {
  200. FixStdioStreams();
  201. #if BUILDFLAG(ENABLE_RUN_AS_NODE)
  202. if (electron::fuses::IsRunAsNodeEnabled() && IsEnvSet(electron::kRunAsNode)) {
  203. return ElectronInitializeICUandStartNode(argc, argv);
  204. }
  205. #endif
  206. #if defined(HELPER_EXECUTABLE) && !defined(MAS_BUILD)
  207. uint32_t exec_path_size = 0;
  208. int rv = _NSGetExecutablePath(NULL, &exec_path_size);
  209. if (rv != -1) {
  210. fprintf(stderr, "_NSGetExecutablePath: get length failed\n");
  211. abort();
  212. }
  213. auto exec_path = std::make_unique<char[]>(exec_path_size);
  214. rv = _NSGetExecutablePath(exec_path.get(), &exec_path_size);
  215. if (rv != 0) {
  216. fprintf(stderr, "_NSGetExecutablePath: get path failed\n");
  217. abort();
  218. }
  219. sandbox::SeatbeltExecServer::CreateFromArgumentsResult seatbelt =
  220. sandbox::SeatbeltExecServer::CreateFromArguments(exec_path.get(), argc,
  221. argv);
  222. if (seatbelt.sandbox_required) {
  223. if (!seatbelt.server) {
  224. fprintf(stderr, "Failed to create seatbelt sandbox server.\n");
  225. abort();
  226. }
  227. if (!seatbelt.server->InitializeSandbox()) {
  228. fprintf(stderr, "Failed to initialize sandbox.\n");
  229. abort();
  230. }
  231. }
  232. #endif // defined(HELPER_EXECUTABLE) && !defined(MAS_BUILD)
  233. return ElectronMain(argc, argv);
  234. }
  235. #endif // defined(OS_MAC)