node_main.cc 9.6 KB

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