electron_main.cc 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  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 "shell/app/node_main.h"
  44. #include "shell/common/electron_command_line.h"
  45. #include "shell/common/electron_constants.h"
  46. #if defined(HELPER_EXECUTABLE) && !defined(MAS_BUILD)
  47. #include "sandbox/mac/seatbelt_exec.h" // nogncheck
  48. #endif
  49. namespace {
  50. #if defined(OS_WIN)
  51. // Redefined here so we don't have to introduce a dependency on //content
  52. // from //electron:electron_app
  53. const char kUserDataDir[] = "user-data-dir";
  54. const char kProcessType[] = "type";
  55. #endif
  56. ALLOW_UNUSED_TYPE bool IsEnvSet(const char* name) {
  57. #if defined(OS_WIN)
  58. size_t required_size;
  59. getenv_s(&required_size, nullptr, 0, name);
  60. return required_size != 0;
  61. #else
  62. char* indicator = getenv(name);
  63. return indicator && indicator[0] != '\0';
  64. #endif
  65. }
  66. #if defined(OS_POSIX)
  67. void FixStdioStreams() {
  68. // libuv may mark stdin/stdout/stderr as close-on-exec, which interferes
  69. // with chromium's subprocess spawning. As a workaround, we detect if these
  70. // streams are closed on startup, and reopen them as /dev/null if necessary.
  71. // Otherwise, an unrelated file descriptor will be assigned as stdout/stderr
  72. // which may cause various errors when attempting to write to them.
  73. //
  74. // For details see https://github.com/libuv/libuv/issues/2062
  75. struct stat st;
  76. if (fstat(STDIN_FILENO, &st) < 0 && errno == EBADF)
  77. ignore_result(freopen("/dev/null", "r", stdin));
  78. if (fstat(STDOUT_FILENO, &st) < 0 && errno == EBADF)
  79. ignore_result(freopen("/dev/null", "w", stdout));
  80. if (fstat(STDERR_FILENO, &st) < 0 && errno == EBADF)
  81. ignore_result(freopen("/dev/null", "w", stderr));
  82. }
  83. #endif
  84. } // namespace
  85. #if defined(OS_WIN)
  86. namespace crash_reporter {
  87. extern const char kCrashpadProcess[];
  88. }
  89. int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE, wchar_t* cmd, int) {
  90. struct Arguments {
  91. int argc = 0;
  92. wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc);
  93. ~Arguments() { LocalFree(argv); }
  94. } arguments;
  95. if (!arguments.argv)
  96. return -1;
  97. #ifdef _DEBUG
  98. // Don't display assert dialog boxes in CI test runs
  99. static const char* kCI = "CI";
  100. if (IsEnvSet(kCI)) {
  101. _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE);
  102. _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
  103. _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE);
  104. _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
  105. _set_error_mode(_OUT_TO_STDERR);
  106. }
  107. #endif
  108. #if BUILDFLAG(ENABLE_RUN_AS_NODE)
  109. bool run_as_node = IsEnvSet(electron::kRunAsNode);
  110. #else
  111. bool run_as_node = false;
  112. #endif
  113. // Make sure the output is printed to console.
  114. if (run_as_node || !IsEnvSet("ELECTRON_NO_ATTACH_CONSOLE"))
  115. base::RouteStdioToConsole(false);
  116. std::vector<char*> argv(arguments.argc);
  117. std::transform(arguments.argv, arguments.argv + arguments.argc, argv.begin(),
  118. [](auto& a) { return _strdup(base::WideToUTF8(a).c_str()); });
  119. #if BUILDFLAG(ENABLE_RUN_AS_NODE)
  120. if (run_as_node) {
  121. base::AtExitManager atexit_manager;
  122. base::i18n::InitializeICU();
  123. auto ret = electron::NodeMain(argv.size(), argv.data());
  124. std::for_each(argv.begin(), argv.end(), free);
  125. return ret;
  126. }
  127. #endif
  128. base::CommandLine::Init(argv.size(), argv.data());
  129. const base::CommandLine* command_line =
  130. base::CommandLine::ForCurrentProcess();
  131. const std::string process_type =
  132. command_line->GetSwitchValueASCII(kProcessType);
  133. if (process_type == crash_reporter::switches::kCrashpadHandler) {
  134. // Check if we should monitor the exit code of this process
  135. std::unique_ptr<browser_watcher::ExitCodeWatcher> exit_code_watcher;
  136. // Retrieve the client process from the command line
  137. crashpad::InitialClientData initial_client_data;
  138. if (initial_client_data.InitializeFromString(
  139. command_line->GetSwitchValueASCII("initial-client-data"))) {
  140. // Setup exit code watcher to monitor the parent process
  141. HANDLE duplicate_handle = INVALID_HANDLE_VALUE;
  142. if (DuplicateHandle(
  143. ::GetCurrentProcess(), initial_client_data.client_process(),
  144. ::GetCurrentProcess(), &duplicate_handle,
  145. PROCESS_QUERY_INFORMATION, FALSE, DUPLICATE_SAME_ACCESS)) {
  146. base::Process parent_process(duplicate_handle);
  147. exit_code_watcher =
  148. std::make_unique<browser_watcher::ExitCodeWatcher>();
  149. if (exit_code_watcher->Initialize(std::move(parent_process))) {
  150. exit_code_watcher->StartWatching();
  151. }
  152. }
  153. }
  154. // The handler process must always be passed the user data dir on the
  155. // command line.
  156. DCHECK(command_line->HasSwitch(kUserDataDir));
  157. base::FilePath user_data_dir =
  158. command_line->GetSwitchValuePath(kUserDataDir);
  159. int crashpad_status = crash_reporter::RunAsCrashpadHandler(
  160. *command_line, user_data_dir, kProcessType, kUserDataDir);
  161. if (crashpad_status != 0 && exit_code_watcher) {
  162. // Crashpad failed to initialize, explicitly stop the exit code watcher
  163. // so the crashpad-handler process can exit with an error
  164. exit_code_watcher->StopWatching();
  165. }
  166. return crashpad_status;
  167. }
  168. if (!electron::CheckCommandLineArguments(arguments.argc, arguments.argv))
  169. return -1;
  170. sandbox::SandboxInterfaceInfo sandbox_info = {0};
  171. content::InitializeSandboxInfo(&sandbox_info);
  172. electron::ElectronMainDelegate delegate;
  173. content::ContentMainParams params(&delegate);
  174. params.instance = instance;
  175. params.sandbox_info = &sandbox_info;
  176. electron::ElectronCommandLine::Init(arguments.argc, arguments.argv);
  177. return content::ContentMain(params);
  178. }
  179. #elif defined(OS_LINUX) // defined(OS_WIN)
  180. int main(int argc, char* argv[]) {
  181. FixStdioStreams();
  182. #if BUILDFLAG(ENABLE_RUN_AS_NODE)
  183. if (IsEnvSet(electron::kRunAsNode)) {
  184. base::i18n::InitializeICU();
  185. base::AtExitManager atexit_manager;
  186. return electron::NodeMain(argc, argv);
  187. }
  188. #endif
  189. electron::ElectronMainDelegate delegate;
  190. content::ContentMainParams params(&delegate);
  191. params.argc = argc;
  192. params.argv = const_cast<const char**>(argv);
  193. electron::ElectronCommandLine::Init(argc, argv);
  194. return content::ContentMain(params);
  195. }
  196. #else // defined(OS_LINUX)
  197. int main(int argc, char* argv[]) {
  198. FixStdioStreams();
  199. #if BUILDFLAG(ENABLE_RUN_AS_NODE)
  200. if (IsEnvSet(electron::kRunAsNode)) {
  201. return ElectronInitializeICUandStartNode(argc, argv);
  202. }
  203. #endif
  204. #if defined(HELPER_EXECUTABLE) && !defined(MAS_BUILD)
  205. uint32_t exec_path_size = 0;
  206. int rv = _NSGetExecutablePath(NULL, &exec_path_size);
  207. if (rv != -1) {
  208. fprintf(stderr, "_NSGetExecutablePath: get length failed\n");
  209. abort();
  210. }
  211. std::unique_ptr<char[]> exec_path(new char[exec_path_size]);
  212. rv = _NSGetExecutablePath(exec_path.get(), &exec_path_size);
  213. if (rv != 0) {
  214. fprintf(stderr, "_NSGetExecutablePath: get path failed\n");
  215. abort();
  216. }
  217. sandbox::SeatbeltExecServer::CreateFromArgumentsResult seatbelt =
  218. sandbox::SeatbeltExecServer::CreateFromArguments(exec_path.get(), argc,
  219. argv);
  220. if (seatbelt.sandbox_required) {
  221. if (!seatbelt.server) {
  222. fprintf(stderr, "Failed to create seatbelt sandbox server.\n");
  223. abort();
  224. }
  225. if (!seatbelt.server->InitializeSandbox()) {
  226. fprintf(stderr, "Failed to initialize sandbox.\n");
  227. abort();
  228. }
  229. }
  230. #endif // defined(HELPER_EXECUTABLE) && !defined(MAS_BUILD)
  231. return ElectronMain(argc, argv);
  232. }
  233. #endif // defined(OS_MAC)