node_main.cc 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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/browser/node_debugger.h"
  26. #include "shell/common/api/electron_bindings.h"
  27. #include "shell/common/gin_helper/dictionary.h"
  28. #include "shell/common/node_bindings.h"
  29. #include "shell/common/node_includes.h"
  30. #if defined(OS_LINUX)
  31. #include "components/crash/core/app/breakpad_linux.h"
  32. #endif
  33. #if defined(OS_WIN)
  34. #include "chrome/child/v8_crashpad_support_win.h"
  35. #endif
  36. #if !defined(MAS_BUILD)
  37. #include "components/crash/core/app/crashpad.h" // nogncheck
  38. #include "shell/app/electron_crash_reporter_client.h"
  39. #include "shell/browser/api/electron_api_crash_reporter.h"
  40. #include "shell/common/crash_keys.h"
  41. #endif
  42. namespace {
  43. // Initialize Node.js cli options to pass to Node.js
  44. // See https://nodejs.org/api/cli.html#cli_options
  45. void SetNodeCliFlags() {
  46. // Options that are unilaterally disallowed
  47. const std::unordered_set<base::StringPiece, base::StringPieceHash>
  48. disallowed = {"--openssl-config", "--use-bundled-ca", "--use-openssl-ca",
  49. "--force-fips", "--enable-fips"};
  50. const auto argv = base::CommandLine::ForCurrentProcess()->argv();
  51. std::vector<std::string> args;
  52. // TODO(codebytere): We need to set the first entry in args to the
  53. // process name owing to src/node_options-inl.h#L286-L290 but this is
  54. // redundant and so should be refactored upstream.
  55. args.reserve(argv.size() + 1);
  56. args.emplace_back("electron");
  57. for (const auto& arg : argv) {
  58. #if defined(OS_WIN)
  59. const auto& option = base::UTF16ToUTF8(arg);
  60. #else
  61. const auto& option = arg;
  62. #endif
  63. const auto stripped = base::StringPiece(option).substr(0, option.find('='));
  64. if (disallowed.count(stripped) != 0) {
  65. LOG(ERROR) << "The Node.js cli flag " << stripped
  66. << " is not supported in Electron";
  67. } else {
  68. args.push_back(option);
  69. }
  70. }
  71. std::vector<std::string> errors;
  72. // Node.js itself will output parsing errors to
  73. // console so we don't need to handle that ourselves
  74. ProcessGlobalArgs(&args, nullptr, &errors, node::kDisallowedInEnvironment);
  75. }
  76. #if defined(MAS_BUILD)
  77. void SetCrashKeyStub(const std::string& key, const std::string& value) {}
  78. void ClearCrashKeyStub(const std::string& key) {}
  79. #endif
  80. } // namespace
  81. namespace electron {
  82. #if defined(OS_LINUX)
  83. void CrashReporterStart(gin_helper::Dictionary options) {
  84. std::string submit_url;
  85. bool upload_to_server = true;
  86. bool ignore_system_crash_handler = false;
  87. bool rate_limit = false;
  88. bool compress = false;
  89. std::map<std::string, std::string> global_extra;
  90. std::map<std::string, std::string> extra;
  91. options.Get("submitURL", &submit_url);
  92. options.Get("uploadToServer", &upload_to_server);
  93. options.Get("ignoreSystemCrashHandler", &ignore_system_crash_handler);
  94. options.Get("rateLimit", &rate_limit);
  95. options.Get("compress", &compress);
  96. options.Get("extra", &extra);
  97. options.Get("globalExtra", &global_extra);
  98. std::string product_name;
  99. if (options.Get("productName", &product_name))
  100. global_extra["_productName"] = product_name;
  101. std::string company_name;
  102. if (options.Get("companyName", &company_name))
  103. global_extra["_companyName"] = company_name;
  104. api::crash_reporter::Start(submit_url, upload_to_server,
  105. ignore_system_crash_handler, rate_limit, compress,
  106. global_extra, extra, true);
  107. }
  108. #endif
  109. v8::Local<v8::Value> GetParameters(v8::Isolate* isolate) {
  110. std::map<std::string, std::string> keys;
  111. #if !defined(MAS_BUILD)
  112. electron::crash_keys::GetCrashKeys(&keys);
  113. #endif
  114. return gin::ConvertToV8(isolate, keys);
  115. }
  116. int NodeMain(int argc, char* argv[]) {
  117. base::CommandLine::Init(argc, argv);
  118. #if defined(OS_WIN)
  119. v8_crashpad_support::SetUp();
  120. #endif
  121. #if !defined(MAS_BUILD)
  122. ElectronCrashReporterClient::Create();
  123. #endif
  124. #if defined(OS_WIN) || (defined(OS_MAC) && !defined(MAS_BUILD))
  125. crash_reporter::InitializeCrashpad(false, "node");
  126. #endif
  127. #if !defined(MAS_BUILD)
  128. crash_keys::SetCrashKeysFromCommandLine(
  129. *base::CommandLine::ForCurrentProcess());
  130. crash_keys::SetPlatformCrashKey();
  131. #endif
  132. int exit_code = 1;
  133. {
  134. // Feed gin::PerIsolateData with a task runner.
  135. argv = uv_setup_args(argc, argv);
  136. uv_loop_t* loop = uv_default_loop();
  137. scoped_refptr<UvTaskRunner> uv_task_runner(new UvTaskRunner(loop));
  138. base::ThreadTaskRunnerHandle handle(uv_task_runner);
  139. // Initialize feature list.
  140. auto feature_list = std::make_unique<base::FeatureList>();
  141. feature_list->InitializeFromCommandLine("", "");
  142. base::FeatureList::SetInstance(std::move(feature_list));
  143. // Explicitly register electron's builtin modules.
  144. NodeBindings::RegisterBuiltinModules();
  145. // Parse and set Node.js cli flags.
  146. SetNodeCliFlags();
  147. int exec_argc;
  148. const char** exec_argv;
  149. node::Init(&argc, const_cast<const char**>(argv), &exec_argc, &exec_argv);
  150. gin::V8Initializer::LoadV8Snapshot(
  151. gin::V8Initializer::V8SnapshotFileType::kWithAdditionalContext);
  152. // V8 requires a task scheduler apparently
  153. base::ThreadPoolInstance::CreateAndStartWithDefaultParams("Electron");
  154. // Initialize gin::IsolateHolder.
  155. JavascriptEnvironment gin_env(loop);
  156. v8::Isolate* isolate = gin_env.isolate();
  157. v8::Isolate::Scope isolate_scope(isolate);
  158. v8::Locker locker(isolate);
  159. node::Environment* env = nullptr;
  160. node::IsolateData* isolate_data = nullptr;
  161. {
  162. v8::HandleScope scope(isolate);
  163. isolate_data = node::CreateIsolateData(isolate, loop, gin_env.platform());
  164. CHECK_NE(nullptr, isolate_data);
  165. env = node::CreateEnvironment(isolate_data, gin_env.context(), argc, argv,
  166. exec_argc, exec_argv);
  167. CHECK_NE(nullptr, env);
  168. // This needs to be called before the inspector is initialized.
  169. env->InitializeDiagnostics();
  170. node::IsolateSettings is;
  171. node::SetIsolateUpForNode(isolate, is);
  172. gin_helper::Dictionary process(isolate, env->process_object());
  173. #if defined(OS_WIN)
  174. process.SetMethod("log", &ElectronBindings::Log);
  175. #endif
  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. // Enable support for v8 inspector.
  199. NodeDebugger node_debugger(env);
  200. node_debugger.Start();
  201. v8::HandleScope scope(isolate);
  202. node::LoadEnvironment(env);
  203. env->set_trace_sync_io(env->options()->trace_sync_io);
  204. {
  205. v8::SealHandleScope seal(isolate);
  206. bool more;
  207. do {
  208. uv_run(env->event_loop(), UV_RUN_DEFAULT);
  209. gin_env.platform()->DrainTasks(isolate);
  210. more = uv_loop_alive(env->event_loop());
  211. if (more && !env->is_stopping())
  212. continue;
  213. if (!uv_loop_alive(env->event_loop())) {
  214. EmitBeforeExit(env);
  215. }
  216. // Emit `beforeExit` if the loop became alive either after emitting
  217. // event, or after running some callbacks.
  218. more = uv_loop_alive(env->event_loop());
  219. } while (more && !env->is_stopping());
  220. }
  221. node_debugger.Stop();
  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