node_main.cc 9.2 KB

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