node_main.cc 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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. // Preparse Node.js cli options to pass to Node.js
  46. // See https://nodejs.org/api/cli.html#cli_options
  47. void ExitIfContainsDisallowedFlags(const std::vector<std::string>& argv) {
  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. for (const auto& arg : argv) {
  57. const auto key = base::StringPiece(arg).substr(0, arg.find('='));
  58. if (disallowed.contains(key)) {
  59. LOG(ERROR) << "The Node.js cli flag " << key
  60. << " is not supported in Electron";
  61. // Node.js returns 9 from ProcessGlobalArgs for any errors encountered
  62. // when setting up cli flags and env vars. Since we're outlawing these
  63. // flags (making them errors) exit with the same error code for
  64. // consistency.
  65. exit(9);
  66. }
  67. }
  68. }
  69. #if IS_MAS_BUILD()
  70. void SetCrashKeyStub(const std::string& key, const std::string& value) {}
  71. void ClearCrashKeyStub(const std::string& key) {}
  72. #endif
  73. } // namespace
  74. namespace electron {
  75. v8::Local<v8::Value> GetParameters(v8::Isolate* isolate) {
  76. std::map<std::string, std::string> keys;
  77. #if !IS_MAS_BUILD()
  78. electron::crash_keys::GetCrashKeys(&keys);
  79. #endif
  80. return gin::ConvertToV8(isolate, keys);
  81. }
  82. int NodeMain(int argc, char* argv[]) {
  83. bool initialized = base::CommandLine::Init(argc, argv);
  84. if (!initialized) {
  85. LOG(ERROR) << "Failed to initialize CommandLine";
  86. exit(1);
  87. }
  88. #if BUILDFLAG(IS_WIN)
  89. v8_crashpad_support::SetUp();
  90. #endif
  91. #if BUILDFLAG(IS_LINUX)
  92. auto os_env = base::Environment::Create();
  93. std::string fd_string, pid_string;
  94. if (os_env->GetVar("CRASHDUMP_SIGNAL_FD", &fd_string) &&
  95. os_env->GetVar("CRASHPAD_HANDLER_PID", &pid_string)) {
  96. int fd = -1, pid = -1;
  97. DCHECK(base::StringToInt(fd_string, &fd));
  98. DCHECK(base::StringToInt(pid_string, &pid));
  99. base::GlobalDescriptors::GetInstance()->Set(kCrashDumpSignal, fd);
  100. // Following API is unsafe in multi-threaded scenario, but at this point
  101. // we are still single threaded.
  102. os_env->UnSetVar("CRASHDUMP_SIGNAL_FD");
  103. os_env->UnSetVar("CRASHPAD_HANDLER_PID");
  104. }
  105. #endif
  106. int exit_code = 1;
  107. {
  108. // Feed gin::PerIsolateData with a task runner.
  109. uv_loop_t* loop = uv_default_loop();
  110. auto uv_task_runner = base::MakeRefCounted<UvTaskRunner>(loop);
  111. base::SingleThreadTaskRunner::CurrentDefaultHandle handle(uv_task_runner);
  112. // Initialize feature list.
  113. auto feature_list = std::make_unique<base::FeatureList>();
  114. feature_list->InitializeFromCommandLine("", "");
  115. base::FeatureList::SetInstance(std::move(feature_list));
  116. // Explicitly register electron's builtin bindings.
  117. NodeBindings::RegisterBuiltinBindings();
  118. // Hack around with the argv pointer. Used for process.title = "blah".
  119. argv = uv_setup_args(argc, argv);
  120. // Parse Node.js cli flags and strip out disallowed options.
  121. std::vector<std::string> args(argv, argv + argc);
  122. ExitIfContainsDisallowedFlags(args);
  123. std::unique_ptr<node::InitializationResult> result =
  124. node::InitializeOncePerProcess(
  125. args,
  126. {node::ProcessInitializationFlags::kNoInitializeV8,
  127. node::ProcessInitializationFlags::kNoInitializeNodeV8Platform});
  128. for (const std::string& error : result->errors())
  129. fprintf(stderr, "%s: %s\n", args[0].c_str(), error.c_str());
  130. if (result->early_return() != 0) {
  131. return result->exit_code();
  132. }
  133. #if BUILDFLAG(IS_LINUX)
  134. // On Linux, initialize crashpad after Nodejs init phase so that
  135. // crash and termination signal handlers can be set by the crashpad client.
  136. if (!pid_string.empty()) {
  137. auto* command_line = base::CommandLine::ForCurrentProcess();
  138. command_line->AppendSwitchASCII(
  139. crash_reporter::switches::kCrashpadHandlerPid, pid_string);
  140. ElectronCrashReporterClient::Create();
  141. crash_reporter::InitializeCrashpad(false, "node");
  142. crash_keys::SetCrashKeysFromCommandLine(
  143. *base::CommandLine::ForCurrentProcess());
  144. crash_keys::SetPlatformCrashKey();
  145. // Ensure the flags and env variable does not propagate to userland.
  146. command_line->RemoveSwitch(crash_reporter::switches::kCrashpadHandlerPid);
  147. }
  148. #elif BUILDFLAG(IS_WIN) || (BUILDFLAG(IS_MAC) && !IS_MAS_BUILD())
  149. ElectronCrashReporterClient::Create();
  150. crash_reporter::InitializeCrashpad(false, "node");
  151. crash_keys::SetCrashKeysFromCommandLine(
  152. *base::CommandLine::ForCurrentProcess());
  153. crash_keys::SetPlatformCrashKey();
  154. #endif
  155. gin::V8Initializer::LoadV8Snapshot(
  156. gin::V8SnapshotFileType::kWithAdditionalContext);
  157. // V8 requires a task scheduler.
  158. base::ThreadPoolInstance::CreateAndStartWithDefaultParams("Electron");
  159. // Allow Node.js to track the amount of time the event loop has spent
  160. // idle in the kernel’s event provider .
  161. uv_loop_configure(loop, UV_METRICS_IDLE_TIME);
  162. // Initialize gin::IsolateHolder.
  163. bool setup_wasm_streaming =
  164. node::per_process::cli_options->get_per_isolate_options()
  165. ->get_per_env_options()
  166. ->experimental_fetch;
  167. JavascriptEnvironment gin_env(loop, setup_wasm_streaming);
  168. v8::Isolate* isolate = gin_env.isolate();
  169. v8::Isolate::Scope isolate_scope(isolate);
  170. v8::Locker locker(isolate);
  171. node::Environment* env = nullptr;
  172. node::IsolateData* isolate_data = nullptr;
  173. {
  174. v8::HandleScope scope(isolate);
  175. isolate_data = node::CreateIsolateData(isolate, loop, gin_env.platform());
  176. CHECK_NE(nullptr, isolate_data);
  177. uint64_t env_flags = node::EnvironmentFlags::kDefaultFlags |
  178. node::EnvironmentFlags::kHideConsoleWindows;
  179. env = node::CreateEnvironment(
  180. isolate_data, isolate->GetCurrentContext(), result->args(),
  181. result->exec_args(),
  182. static_cast<node::EnvironmentFlags::Flags>(env_flags));
  183. CHECK_NE(nullptr, env);
  184. node::SetIsolateUpForNode(isolate);
  185. gin_helper::Dictionary process(isolate, env->process_object());
  186. process.SetMethod("crash", &ElectronBindings::Crash);
  187. // Setup process.crashReporter in child node processes
  188. gin_helper::Dictionary reporter = gin::Dictionary::CreateEmpty(isolate);
  189. reporter.SetMethod("getParameters", &GetParameters);
  190. #if IS_MAS_BUILD()
  191. reporter.SetMethod("addExtraParameter", &SetCrashKeyStub);
  192. reporter.SetMethod("removeExtraParameter", &ClearCrashKeyStub);
  193. #else
  194. reporter.SetMethod("addExtraParameter",
  195. &electron::crash_keys::SetCrashKey);
  196. reporter.SetMethod("removeExtraParameter",
  197. &electron::crash_keys::ClearCrashKey);
  198. #endif
  199. process.Set("crashReporter", reporter);
  200. gin_helper::Dictionary versions;
  201. if (process.Get("versions", &versions)) {
  202. versions.SetReadOnly(ELECTRON_PROJECT_NAME, ELECTRON_VERSION_STRING);
  203. }
  204. }
  205. v8::HandleScope scope(isolate);
  206. node::LoadEnvironment(env, node::StartExecutionCallback{});
  207. // Potential reasons we get Nothing here may include: the env
  208. // is stopping, or the user hooks process.emit('exit').
  209. exit_code = node::SpinEventLoop(env).FromMaybe(1);
  210. node::ResetStdio();
  211. node::Stop(env, false);
  212. node::FreeEnvironment(env);
  213. node::FreeIsolateData(isolate_data);
  214. }
  215. // According to "src/gin/shell/gin_main.cc":
  216. //
  217. // gin::IsolateHolder waits for tasks running in ThreadPool in its
  218. // destructor and thus must be destroyed before ThreadPool starts skipping
  219. // CONTINUE_ON_SHUTDOWN tasks.
  220. base::ThreadPoolInstance::Get()->Shutdown();
  221. v8::V8::Dispose();
  222. return exit_code;
  223. }
  224. } // namespace electron