node_main.cc 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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 defined(OS_LINUX)
  30. #include "components/crash/core/app/breakpad_linux.h"
  31. #endif
  32. #if defined(OS_WIN)
  33. #include "chrome/child/v8_crashpad_support_win.h"
  34. #endif
  35. #if !defined(MAS_BUILD)
  36. #include "components/crash/core/app/crashpad.h" // nogncheck
  37. #include "shell/app/electron_crash_reporter_client.h"
  38. #include "shell/browser/api/electron_api_crash_reporter.h"
  39. #include "shell/common/crash_keys.h"
  40. #endif
  41. namespace {
  42. // Initialize Node.js cli options to pass to Node.js
  43. // See https://nodejs.org/api/cli.html#cli_options
  44. int SetNodeCliFlags() {
  45. // Options that are unilaterally disallowed
  46. const std::unordered_set<base::StringPiece, base::StringPieceHash>
  47. disallowed = {"--openssl-config", "--use-bundled-ca", "--use-openssl-ca",
  48. "--force-fips", "--enable-fips"};
  49. const auto argv = base::CommandLine::ForCurrentProcess()->argv();
  50. std::vector<std::string> args;
  51. // TODO(codebytere): We need to set the first entry in args to the
  52. // process name owing to src/node_options-inl.h#L286-L290 but this is
  53. // redundant and so should be refactored upstream.
  54. args.reserve(argv.size() + 1);
  55. args.emplace_back("electron");
  56. for (const auto& arg : argv) {
  57. #if defined(OS_WIN)
  58. const auto& option = base::WideToUTF8(arg);
  59. #else
  60. const auto& option = arg;
  61. #endif
  62. const auto stripped = base::StringPiece(option).substr(0, option.find('='));
  63. if (disallowed.count(stripped) != 0) {
  64. LOG(ERROR) << "The Node.js cli flag " << stripped
  65. << " is not supported in Electron";
  66. // Node.js returns 9 from ProcessGlobalArgs for any errors encountered
  67. // when setting up cli flags and env vars. Since we're outlawing these
  68. // flags (making them errors) return 9 here for consistency.
  69. return 9;
  70. } else {
  71. args.push_back(option);
  72. }
  73. }
  74. std::vector<std::string> errors;
  75. // Node.js itself will output parsing errors to
  76. // console so we don't need to handle that ourselves
  77. return ProcessGlobalArgs(&args, nullptr, &errors,
  78. node::kDisallowedInEnvironment);
  79. }
  80. #if defined(MAS_BUILD)
  81. void SetCrashKeyStub(const std::string& key, const std::string& value) {}
  82. void ClearCrashKeyStub(const std::string& key) {}
  83. #endif
  84. } // namespace
  85. namespace electron {
  86. #if defined(OS_LINUX)
  87. void CrashReporterStart(gin_helper::Dictionary options) {
  88. std::string submit_url;
  89. bool upload_to_server = true;
  90. bool ignore_system_crash_handler = false;
  91. bool rate_limit = false;
  92. bool compress = false;
  93. std::map<std::string, std::string> global_extra;
  94. std::map<std::string, std::string> extra;
  95. options.Get("submitURL", &submit_url);
  96. options.Get("uploadToServer", &upload_to_server);
  97. options.Get("ignoreSystemCrashHandler", &ignore_system_crash_handler);
  98. options.Get("rateLimit", &rate_limit);
  99. options.Get("compress", &compress);
  100. options.Get("extra", &extra);
  101. options.Get("globalExtra", &global_extra);
  102. std::string product_name;
  103. if (options.Get("productName", &product_name))
  104. global_extra["_productName"] = product_name;
  105. std::string company_name;
  106. if (options.Get("companyName", &company_name))
  107. global_extra["_companyName"] = company_name;
  108. api::crash_reporter::Start(submit_url, upload_to_server,
  109. ignore_system_crash_handler, rate_limit, compress,
  110. global_extra, extra, true);
  111. }
  112. #endif
  113. v8::Local<v8::Value> GetParameters(v8::Isolate* isolate) {
  114. std::map<std::string, std::string> keys;
  115. #if !defined(MAS_BUILD)
  116. electron::crash_keys::GetCrashKeys(&keys);
  117. #endif
  118. return gin::ConvertToV8(isolate, keys);
  119. }
  120. int NodeMain(int argc, char* argv[]) {
  121. base::CommandLine::Init(argc, argv);
  122. #if defined(OS_WIN)
  123. v8_crashpad_support::SetUp();
  124. #endif
  125. #if !defined(MAS_BUILD)
  126. ElectronCrashReporterClient::Create();
  127. #endif
  128. #if defined(OS_WIN) || (defined(OS_MAC) && !defined(MAS_BUILD))
  129. crash_reporter::InitializeCrashpad(false, "node");
  130. #endif
  131. #if !defined(MAS_BUILD)
  132. crash_keys::SetCrashKeysFromCommandLine(
  133. *base::CommandLine::ForCurrentProcess());
  134. crash_keys::SetPlatformCrashKey();
  135. #endif
  136. int exit_code = 1;
  137. {
  138. // Feed gin::PerIsolateData with a task runner.
  139. uv_loop_t* loop = uv_default_loop();
  140. auto uv_task_runner = base::MakeRefCounted<UvTaskRunner>(loop);
  141. base::ThreadTaskRunnerHandle handle(uv_task_runner);
  142. // Initialize feature list.
  143. auto feature_list = std::make_unique<base::FeatureList>();
  144. feature_list->InitializeFromCommandLine("", "");
  145. base::FeatureList::SetInstance(std::move(feature_list));
  146. // Explicitly register electron's builtin modules.
  147. NodeBindings::RegisterBuiltinModules();
  148. // Parse and set Node.js cli flags.
  149. int flags_exit_code = SetNodeCliFlags();
  150. if (flags_exit_code != 0)
  151. exit(flags_exit_code);
  152. node::InitializationSettingsFlags flags = node::kRunPlatformInit;
  153. node::InitializationResult result =
  154. node::InitializeOncePerProcess(argc, argv, flags);
  155. if (result.early_return)
  156. exit(result.exit_code);
  157. gin::V8Initializer::LoadV8Snapshot(
  158. gin::V8SnapshotFileType::kWithAdditionalContext);
  159. // V8 requires a task scheduler.
  160. base::ThreadPoolInstance::CreateAndStartWithDefaultParams("Electron");
  161. // Allow Node.js to track the amount of time the event loop has spent
  162. // idle in the kernel’s event provider .
  163. uv_loop_configure(loop, UV_METRICS_IDLE_TIME);
  164. // Initialize gin::IsolateHolder.
  165. JavascriptEnvironment gin_env(loop);
  166. v8::Isolate* isolate = gin_env.isolate();
  167. v8::Isolate::Scope isolate_scope(isolate);
  168. v8::Locker locker(isolate);
  169. node::Environment* env = nullptr;
  170. node::IsolateData* isolate_data = nullptr;
  171. {
  172. v8::HandleScope scope(isolate);
  173. isolate_data = node::CreateIsolateData(isolate, loop, gin_env.platform());
  174. CHECK_NE(nullptr, isolate_data);
  175. uint64_t flags = node::EnvironmentFlags::kDefaultFlags |
  176. node::EnvironmentFlags::kHideConsoleWindows;
  177. env = node::CreateEnvironment(
  178. isolate_data, gin_env.context(), result.args, result.exec_args,
  179. static_cast<node::EnvironmentFlags::Flags>(flags));
  180. CHECK_NE(nullptr, env);
  181. node::IsolateSettings is;
  182. node::SetIsolateUpForNode(isolate, is);
  183. gin_helper::Dictionary process(isolate, env->process_object());
  184. process.SetMethod("crash", &ElectronBindings::Crash);
  185. // Setup process.crashReporter in child node processes
  186. gin_helper::Dictionary reporter = gin::Dictionary::CreateEmpty(isolate);
  187. #if defined(OS_LINUX)
  188. reporter.SetMethod("start", &CrashReporterStart);
  189. #endif
  190. reporter.SetMethod("getParameters", &GetParameters);
  191. #if defined(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. env->set_trace_sync_io(env->options()->trace_sync_io);
  209. {
  210. v8::SealHandleScope seal(isolate);
  211. bool more;
  212. env->performance_state()->Mark(
  213. node::performance::NODE_PERFORMANCE_MILESTONE_LOOP_START);
  214. do {
  215. uv_run(env->event_loop(), UV_RUN_DEFAULT);
  216. gin_env.platform()->DrainTasks(isolate);
  217. more = uv_loop_alive(env->event_loop());
  218. if (more && !env->is_stopping())
  219. continue;
  220. if (!uv_loop_alive(env->event_loop())) {
  221. EmitBeforeExit(env);
  222. }
  223. // Emit `beforeExit` if the loop became alive either after emitting
  224. // event, or after running some callbacks.
  225. more = uv_loop_alive(env->event_loop());
  226. } while (more && !env->is_stopping());
  227. env->performance_state()->Mark(
  228. node::performance::NODE_PERFORMANCE_MILESTONE_LOOP_EXIT);
  229. }
  230. env->set_trace_sync_io(false);
  231. exit_code = node::EmitExit(env);
  232. node::ResetStdio();
  233. node::Stop(env);
  234. node::FreeEnvironment(env);
  235. node::FreeIsolateData(isolate_data);
  236. }
  237. // According to "src/gin/shell/gin_main.cc":
  238. //
  239. // gin::IsolateHolder waits for tasks running in ThreadPool in its
  240. // destructor and thus must be destroyed before ThreadPool starts skipping
  241. // CONTINUE_ON_SHUTDOWN tasks.
  242. base::ThreadPoolInstance::Get()->Shutdown();
  243. v8::V8::Dispose();
  244. return exit_code;
  245. }
  246. } // namespace electron