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 <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 !defined(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 defined(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 !defined(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. node::InitializationSettingsFlags flags = node::kRunPlatformInit;
  133. node::InitializationResult result =
  134. node::InitializeOncePerProcess(argc, argv, flags);
  135. if (result.early_return)
  136. exit(result.exit_code);
  137. #if BUILDFLAG(IS_LINUX)
  138. // On Linux, initialize crashpad after Nodejs init phase so that
  139. // crash and termination signal handlers can be set by the crashpad client.
  140. if (!pid_string.empty()) {
  141. auto* command_line = base::CommandLine::ForCurrentProcess();
  142. command_line->AppendSwitchASCII(
  143. crash_reporter::switches::kCrashpadHandlerPid, pid_string);
  144. ElectronCrashReporterClient::Create();
  145. crash_reporter::InitializeCrashpad(false, "node");
  146. crash_keys::SetCrashKeysFromCommandLine(
  147. *base::CommandLine::ForCurrentProcess());
  148. crash_keys::SetPlatformCrashKey();
  149. // Ensure the flags and env variable does not propagate to userland.
  150. command_line->RemoveSwitch(crash_reporter::switches::kCrashpadHandlerPid);
  151. }
  152. #elif BUILDFLAG(IS_WIN) || (BUILDFLAG(IS_MAC) && !defined(MAS_BUILD))
  153. ElectronCrashReporterClient::Create();
  154. crash_reporter::InitializeCrashpad(false, "node");
  155. crash_keys::SetCrashKeysFromCommandLine(
  156. *base::CommandLine::ForCurrentProcess());
  157. crash_keys::SetPlatformCrashKey();
  158. #endif
  159. gin::V8Initializer::LoadV8Snapshot(
  160. gin::V8SnapshotFileType::kWithAdditionalContext);
  161. // V8 requires a task scheduler.
  162. base::ThreadPoolInstance::CreateAndStartWithDefaultParams("Electron");
  163. // Allow Node.js to track the amount of time the event loop has spent
  164. // idle in the kernel’s event provider .
  165. uv_loop_configure(loop, UV_METRICS_IDLE_TIME);
  166. // Initialize gin::IsolateHolder.
  167. JavascriptEnvironment gin_env(loop);
  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, gin_env.context(), result.args, result.exec_args,
  181. static_cast<node::EnvironmentFlags::Flags>(env_flags));
  182. CHECK_NE(nullptr, env);
  183. node::IsolateSettings is;
  184. node::SetIsolateUpForNode(isolate, is);
  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 defined(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);
  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