node_main.cc 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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. void 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::UTF16ToUTF8(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. } else {
  67. args.push_back(option);
  68. }
  69. }
  70. std::vector<std::string> errors;
  71. // Node.js itself will output parsing errors to
  72. // console so we don't need to handle that ourselves
  73. ProcessGlobalArgs(&args, nullptr, &errors, node::kDisallowedInEnvironment);
  74. }
  75. #if defined(MAS_BUILD)
  76. void SetCrashKeyStub(const std::string& key, const std::string& value) {}
  77. void ClearCrashKeyStub(const std::string& key) {}
  78. #endif
  79. } // namespace
  80. namespace electron {
  81. #if defined(OS_LINUX)
  82. void CrashReporterStart(gin_helper::Dictionary options) {
  83. std::string submit_url;
  84. bool upload_to_server = true;
  85. bool ignore_system_crash_handler = false;
  86. bool rate_limit = false;
  87. bool compress = false;
  88. std::map<std::string, std::string> global_extra;
  89. std::map<std::string, std::string> extra;
  90. options.Get("submitURL", &submit_url);
  91. options.Get("uploadToServer", &upload_to_server);
  92. options.Get("ignoreSystemCrashHandler", &ignore_system_crash_handler);
  93. options.Get("rateLimit", &rate_limit);
  94. options.Get("compress", &compress);
  95. options.Get("extra", &extra);
  96. options.Get("globalExtra", &global_extra);
  97. std::string product_name;
  98. if (options.Get("productName", &product_name))
  99. global_extra["_productName"] = product_name;
  100. std::string company_name;
  101. if (options.Get("companyName", &company_name))
  102. global_extra["_companyName"] = company_name;
  103. api::crash_reporter::Start(submit_url, upload_to_server,
  104. ignore_system_crash_handler, rate_limit, compress,
  105. global_extra, extra, true);
  106. }
  107. #endif
  108. v8::Local<v8::Value> GetParameters(v8::Isolate* isolate) {
  109. std::map<std::string, std::string> keys;
  110. #if !defined(MAS_BUILD)
  111. electron::crash_keys::GetCrashKeys(&keys);
  112. #endif
  113. return gin::ConvertToV8(isolate, keys);
  114. }
  115. int NodeMain(int argc, char* argv[]) {
  116. base::CommandLine::Init(argc, argv);
  117. #if defined(OS_WIN)
  118. v8_crashpad_support::SetUp();
  119. #endif
  120. #if !defined(MAS_BUILD)
  121. ElectronCrashReporterClient::Create();
  122. #endif
  123. #if defined(OS_WIN) || (defined(OS_MAC) && !defined(MAS_BUILD))
  124. crash_reporter::InitializeCrashpad(false, "node");
  125. #endif
  126. #if !defined(MAS_BUILD)
  127. crash_keys::SetCrashKeysFromCommandLine(
  128. *base::CommandLine::ForCurrentProcess());
  129. crash_keys::SetPlatformCrashKey();
  130. #endif
  131. int exit_code = 1;
  132. {
  133. // Feed gin::PerIsolateData with a task runner.
  134. argv = uv_setup_args(argc, argv);
  135. uv_loop_t* loop = uv_default_loop();
  136. scoped_refptr<UvTaskRunner> uv_task_runner(new UvTaskRunner(loop));
  137. base::ThreadTaskRunnerHandle handle(uv_task_runner);
  138. // Initialize feature list.
  139. auto feature_list = std::make_unique<base::FeatureList>();
  140. feature_list->InitializeFromCommandLine("", "");
  141. base::FeatureList::SetInstance(std::move(feature_list));
  142. // Explicitly register electron's builtin modules.
  143. NodeBindings::RegisterBuiltinModules();
  144. // Parse and set Node.js cli flags.
  145. SetNodeCliFlags();
  146. int exec_argc;
  147. const char** exec_argv;
  148. node::Init(&argc, const_cast<const char**>(argv), &exec_argc, &exec_argv);
  149. gin::V8Initializer::LoadV8Snapshot(
  150. gin::V8Initializer::V8SnapshotFileType::kWithAdditionalContext);
  151. // V8 requires a task scheduler.
  152. base::ThreadPoolInstance::CreateAndStartWithDefaultParams("Electron");
  153. // Allow Node.js to track the amount of time the event loop has spent
  154. // idle in the kernel’s event provider .
  155. uv_loop_configure(loop, UV_METRICS_IDLE_TIME);
  156. // Initialize gin::IsolateHolder.
  157. JavascriptEnvironment gin_env(loop);
  158. v8::Isolate* isolate = gin_env.isolate();
  159. v8::Isolate::Scope isolate_scope(isolate);
  160. v8::Locker locker(isolate);
  161. node::Environment* env = nullptr;
  162. node::IsolateData* isolate_data = nullptr;
  163. {
  164. v8::HandleScope scope(isolate);
  165. isolate_data = node::CreateIsolateData(isolate, loop, gin_env.platform());
  166. CHECK_NE(nullptr, isolate_data);
  167. std::vector<std::string> args(argv, argv + argc); // NOLINT
  168. std::vector<std::string> exec_args(exec_argv,
  169. exec_argv + exec_argc); // NOLINT
  170. env = node::CreateEnvironment(isolate_data, gin_env.context(), args,
  171. exec_args);
  172. CHECK_NOT_NULL(env);
  173. node::IsolateSettings is;
  174. node::SetIsolateUpForNode(isolate, is);
  175. gin_helper::Dictionary process(isolate, env->process_object());
  176. process.SetMethod("crash", &ElectronBindings::Crash);
  177. // Setup process.crashReporter in child node processes
  178. gin_helper::Dictionary reporter = gin::Dictionary::CreateEmpty(isolate);
  179. #if defined(OS_LINUX)
  180. reporter.SetMethod("start", &CrashReporterStart);
  181. #endif
  182. reporter.SetMethod("getParameters", &GetParameters);
  183. #if defined(MAS_BUILD)
  184. reporter.SetMethod("addExtraParameter", &SetCrashKeyStub);
  185. reporter.SetMethod("removeExtraParameter", &ClearCrashKeyStub);
  186. #else
  187. reporter.SetMethod("addExtraParameter",
  188. &electron::crash_keys::SetCrashKey);
  189. reporter.SetMethod("removeExtraParameter",
  190. &electron::crash_keys::ClearCrashKey);
  191. #endif
  192. process.Set("crashReporter", reporter);
  193. gin_helper::Dictionary versions;
  194. if (process.Get("versions", &versions)) {
  195. versions.SetReadOnly(ELECTRON_PROJECT_NAME, ELECTRON_VERSION_STRING);
  196. }
  197. }
  198. v8::HandleScope scope(isolate);
  199. node::LoadEnvironment(env);
  200. env->set_trace_sync_io(env->options()->trace_sync_io);
  201. {
  202. v8::SealHandleScope seal(isolate);
  203. bool more;
  204. env->performance_state()->Mark(
  205. node::performance::NODE_PERFORMANCE_MILESTONE_LOOP_START);
  206. do {
  207. uv_run(env->event_loop(), UV_RUN_DEFAULT);
  208. gin_env.platform()->DrainTasks(isolate);
  209. more = uv_loop_alive(env->event_loop());
  210. if (more && !env->is_stopping())
  211. continue;
  212. if (!uv_loop_alive(env->event_loop())) {
  213. EmitBeforeExit(env);
  214. }
  215. // Emit `beforeExit` if the loop became alive either after emitting
  216. // event, or after running some callbacks.
  217. more = uv_loop_alive(env->event_loop());
  218. } while (more && !env->is_stopping());
  219. env->performance_state()->Mark(
  220. node::performance::NODE_PERFORMANCE_MILESTONE_LOOP_EXIT);
  221. }
  222. env->set_trace_sync_io(false);
  223. exit_code = node::EmitExit(env);
  224. node::ResetStdio();
  225. node::Stop(env);
  226. node::FreeEnvironment(env);
  227. node::FreeIsolateData(isolate_data);
  228. }
  229. // According to "src/gin/shell/gin_main.cc":
  230. //
  231. // gin::IsolateHolder waits for tasks running in ThreadPool in its
  232. // destructor and thus must be destroyed before ThreadPool starts skipping
  233. // CONTINUE_ON_SHUTDOWN tasks.
  234. base::ThreadPoolInstance::Get()->Shutdown();
  235. v8::V8::Dispose();
  236. return exit_code;
  237. }
  238. } // namespace electron