node_main.cc 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. // Copyright (c) 2015 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/node_main.h"
  5. #include <map>
  6. #include <memory>
  7. #include <string>
  8. #include <utility>
  9. #include <vector>
  10. #include "base/base_switches.h"
  11. #include "base/command_line.h"
  12. #include "base/containers/fixed_flat_set.h"
  13. #include "base/feature_list.h"
  14. #include "base/strings/string_util.h"
  15. #include "base/strings/utf_string_conversions.h"
  16. #include "base/task/single_thread_task_runner.h"
  17. #include "base/task/thread_pool/thread_pool_instance.h"
  18. #include "content/public/common/content_switches.h"
  19. #include "electron/electron_version.h"
  20. #include "gin/array_buffer.h"
  21. #include "gin/public/isolate_holder.h"
  22. #include "gin/v8_initializer.h"
  23. #include "shell/app/uv_task_runner.h"
  24. #include "shell/browser/javascript_environment.h"
  25. #include "shell/common/api/electron_bindings.h"
  26. #include "shell/common/gin_helper/dictionary.h"
  27. #include "shell/common/node_bindings.h"
  28. #include "shell/common/node_includes.h"
  29. #if BUILDFLAG(IS_WIN)
  30. #include "chrome/child/v8_crashpad_support_win.h"
  31. #endif
  32. #if BUILDFLAG(IS_LINUX)
  33. #include "base/environment.h"
  34. #include "base/posix/global_descriptors.h"
  35. #include "base/strings/string_number_conversions.h"
  36. #include "components/crash/core/app/crash_switches.h" // nogncheck
  37. #include "content/public/common/content_descriptors.h"
  38. #endif
  39. #if !IS_MAS_BUILD()
  40. #include "components/crash/core/app/crashpad.h" // nogncheck
  41. #include "shell/app/electron_crash_reporter_client.h"
  42. #include "shell/common/crash_keys.h"
  43. #endif
  44. namespace {
  45. // Initialize Node.js cli options to pass to Node.js
  46. // See https://nodejs.org/api/cli.html#cli_options
  47. int SetNodeCliFlags() {
  48. // Options that are unilaterally disallowed
  49. static constexpr auto disallowed = base::MakeFixedFlatSet<base::StringPiece>({
  50. "--enable-fips",
  51. "--force-fips",
  52. "--openssl-config",
  53. "--use-bundled-ca",
  54. "--use-openssl-ca",
  55. });
  56. const auto argv = base::CommandLine::ForCurrentProcess()->argv();
  57. std::vector<std::string> args;
  58. // TODO(codebytere): We need to set the first entry in args to the
  59. // process name owing to src/node_options-inl.h#L286-L290 but this is
  60. // redundant and so should be refactored upstream.
  61. args.reserve(argv.size() + 1);
  62. args.emplace_back("electron");
  63. for (const auto& arg : argv) {
  64. #if BUILDFLAG(IS_WIN)
  65. const auto& option = base::WideToUTF8(arg);
  66. #else
  67. const auto& option = arg;
  68. #endif
  69. const auto stripped = base::StringPiece(option).substr(0, option.find('='));
  70. if (disallowed.contains(stripped)) {
  71. LOG(ERROR) << "The Node.js cli flag " << stripped
  72. << " is not supported in Electron";
  73. // Node.js returns 9 from ProcessGlobalArgs for any errors encountered
  74. // when setting up cli flags and env vars. Since we're outlawing these
  75. // flags (making them errors) return 9 here for consistency.
  76. return 9;
  77. } else {
  78. args.push_back(option);
  79. }
  80. }
  81. std::vector<std::string> errors;
  82. // Node.js itself will output parsing errors to
  83. // console so we don't need to handle that ourselves
  84. return ProcessGlobalArgs(&args, nullptr, &errors,
  85. node::kDisallowedInEnvironment);
  86. }
  87. #if IS_MAS_BUILD()
  88. void SetCrashKeyStub(const std::string& key, const std::string& value) {}
  89. void ClearCrashKeyStub(const std::string& key) {}
  90. #endif
  91. } // namespace
  92. namespace electron {
  93. v8::Local<v8::Value> GetParameters(v8::Isolate* isolate) {
  94. std::map<std::string, std::string> keys;
  95. #if !IS_MAS_BUILD()
  96. electron::crash_keys::GetCrashKeys(&keys);
  97. #endif
  98. return gin::ConvertToV8(isolate, keys);
  99. }
  100. int NodeMain(int argc, char* argv[]) {
  101. base::CommandLine::Init(argc, argv);
  102. #if BUILDFLAG(IS_WIN)
  103. v8_crashpad_support::SetUp();
  104. #endif
  105. #if BUILDFLAG(IS_LINUX)
  106. auto os_env = base::Environment::Create();
  107. std::string fd_string, pid_string;
  108. if (os_env->GetVar("CRASHDUMP_SIGNAL_FD", &fd_string) &&
  109. os_env->GetVar("CRASHPAD_HANDLER_PID", &pid_string)) {
  110. int fd = -1, pid = -1;
  111. DCHECK(base::StringToInt(fd_string, &fd));
  112. DCHECK(base::StringToInt(pid_string, &pid));
  113. base::GlobalDescriptors::GetInstance()->Set(kCrashDumpSignal, fd);
  114. // Following API is unsafe in multi-threaded scenario, but at this point
  115. // we are still single threaded.
  116. os_env->UnSetVar("CRASHDUMP_SIGNAL_FD");
  117. os_env->UnSetVar("CRASHPAD_HANDLER_PID");
  118. }
  119. #endif
  120. int exit_code = 1;
  121. {
  122. // Feed gin::PerIsolateData with a task runner.
  123. uv_loop_t* loop = uv_default_loop();
  124. auto uv_task_runner = base::MakeRefCounted<UvTaskRunner>(loop);
  125. base::SingleThreadTaskRunner::CurrentDefaultHandle handle(uv_task_runner);
  126. // Initialize feature list.
  127. auto feature_list = std::make_unique<base::FeatureList>();
  128. feature_list->InitializeFromCommandLine("", "");
  129. base::FeatureList::SetInstance(std::move(feature_list));
  130. // Explicitly register electron's builtin bindings.
  131. NodeBindings::RegisterBuiltinBindings();
  132. // Parse and set Node.js cli flags.
  133. int flags_exit_code = SetNodeCliFlags();
  134. if (flags_exit_code != 0)
  135. exit(flags_exit_code);
  136. // Hack around with the argv pointer. Used for process.title = "blah".
  137. argv = uv_setup_args(argc, argv);
  138. std::vector<std::string> args(argv, argv + argc);
  139. std::unique_ptr<node::InitializationResult> result =
  140. node::InitializeOncePerProcess(
  141. args,
  142. {node::ProcessInitializationFlags::kNoInitializeV8,
  143. node::ProcessInitializationFlags::kNoInitializeNodeV8Platform});
  144. for (const std::string& error : result->errors())
  145. fprintf(stderr, "%s: %s\n", args[0].c_str(), error.c_str());
  146. if (result->early_return() != 0) {
  147. return result->exit_code();
  148. }
  149. #if BUILDFLAG(IS_LINUX)
  150. // On Linux, initialize crashpad after Nodejs init phase so that
  151. // crash and termination signal handlers can be set by the crashpad client.
  152. if (!pid_string.empty()) {
  153. auto* command_line = base::CommandLine::ForCurrentProcess();
  154. command_line->AppendSwitchASCII(
  155. crash_reporter::switches::kCrashpadHandlerPid, pid_string);
  156. ElectronCrashReporterClient::Create();
  157. crash_reporter::InitializeCrashpad(false, "node");
  158. crash_keys::SetCrashKeysFromCommandLine(
  159. *base::CommandLine::ForCurrentProcess());
  160. crash_keys::SetPlatformCrashKey();
  161. // Ensure the flags and env variable does not propagate to userland.
  162. command_line->RemoveSwitch(crash_reporter::switches::kCrashpadHandlerPid);
  163. }
  164. #elif BUILDFLAG(IS_WIN) || (BUILDFLAG(IS_MAC) && !IS_MAS_BUILD())
  165. ElectronCrashReporterClient::Create();
  166. crash_reporter::InitializeCrashpad(false, "node");
  167. crash_keys::SetCrashKeysFromCommandLine(
  168. *base::CommandLine::ForCurrentProcess());
  169. crash_keys::SetPlatformCrashKey();
  170. #endif
  171. gin::V8Initializer::LoadV8Snapshot(
  172. gin::V8SnapshotFileType::kWithAdditionalContext);
  173. // V8 requires a task scheduler.
  174. base::ThreadPoolInstance::CreateAndStartWithDefaultParams("Electron");
  175. // Allow Node.js to track the amount of time the event loop has spent
  176. // idle in the kernel’s event provider .
  177. uv_loop_configure(loop, UV_METRICS_IDLE_TIME);
  178. // Initialize gin::IsolateHolder.
  179. bool setup_wasm_streaming =
  180. node::per_process::cli_options->get_per_isolate_options()
  181. ->get_per_env_options()
  182. ->experimental_fetch;
  183. JavascriptEnvironment gin_env(loop, setup_wasm_streaming);
  184. v8::Isolate* isolate = gin_env.isolate();
  185. v8::Isolate::Scope isolate_scope(isolate);
  186. v8::Locker locker(isolate);
  187. node::Environment* env = nullptr;
  188. node::IsolateData* isolate_data = nullptr;
  189. {
  190. v8::HandleScope scope(isolate);
  191. isolate_data = node::CreateIsolateData(isolate, loop, gin_env.platform());
  192. CHECK_NE(nullptr, isolate_data);
  193. uint64_t env_flags = node::EnvironmentFlags::kDefaultFlags |
  194. node::EnvironmentFlags::kHideConsoleWindows;
  195. env = node::CreateEnvironment(
  196. isolate_data, isolate->GetCurrentContext(), result->args(),
  197. result->exec_args(),
  198. static_cast<node::EnvironmentFlags::Flags>(env_flags));
  199. CHECK_NE(nullptr, env);
  200. node::SetIsolateUpForNode(isolate);
  201. gin_helper::Dictionary process(isolate, env->process_object());
  202. process.SetMethod("crash", &ElectronBindings::Crash);
  203. // Setup process.crashReporter in child node processes
  204. gin_helper::Dictionary reporter = gin::Dictionary::CreateEmpty(isolate);
  205. reporter.SetMethod("getParameters", &GetParameters);
  206. #if IS_MAS_BUILD()
  207. reporter.SetMethod("addExtraParameter", &SetCrashKeyStub);
  208. reporter.SetMethod("removeExtraParameter", &ClearCrashKeyStub);
  209. #else
  210. reporter.SetMethod("addExtraParameter",
  211. &electron::crash_keys::SetCrashKey);
  212. reporter.SetMethod("removeExtraParameter",
  213. &electron::crash_keys::ClearCrashKey);
  214. #endif
  215. process.Set("crashReporter", reporter);
  216. gin_helper::Dictionary versions;
  217. if (process.Get("versions", &versions)) {
  218. versions.SetReadOnly(ELECTRON_PROJECT_NAME, ELECTRON_VERSION_STRING);
  219. }
  220. }
  221. v8::HandleScope scope(isolate);
  222. node::LoadEnvironment(env, node::StartExecutionCallback{});
  223. // Potential reasons we get Nothing here may include: the env
  224. // is stopping, or the user hooks process.emit('exit').
  225. exit_code = node::SpinEventLoop(env).FromMaybe(1);
  226. node::ResetStdio();
  227. node::Stop(env, node::StopFlags::kDoNotTerminateIsolate);
  228. node::FreeEnvironment(env);
  229. node::FreeIsolateData(isolate_data);
  230. }
  231. // According to "src/gin/shell/gin_main.cc":
  232. //
  233. // gin::IsolateHolder waits for tasks running in ThreadPool in its
  234. // destructor and thus must be destroyed before ThreadPool starts skipping
  235. // CONTINUE_ON_SHUTDOWN tasks.
  236. base::ThreadPoolInstance::Get()->Shutdown();
  237. v8::V8::Dispose();
  238. return exit_code;
  239. }
  240. } // namespace electron