node_bindings.cc 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  1. // Copyright (c) 2013 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/common/node_bindings.h"
  5. #include <algorithm>
  6. #include <memory>
  7. #include <set>
  8. #include <string>
  9. #include <unordered_set>
  10. #include <utility>
  11. #include <vector>
  12. #include "base/base_paths.h"
  13. #include "base/command_line.h"
  14. #include "base/environment.h"
  15. #include "base/path_service.h"
  16. #include "base/run_loop.h"
  17. #include "base/strings/string_split.h"
  18. #include "base/strings/utf_string_conversions.h"
  19. #include "base/task/single_thread_task_runner.h"
  20. #include "base/threading/thread_task_runner_handle.h"
  21. #include "base/trace_event/trace_event.h"
  22. #include "content/public/browser/browser_thread.h"
  23. #include "content/public/common/content_paths.h"
  24. #include "electron/buildflags/buildflags.h"
  25. #include "electron/fuses.h"
  26. #include "shell/browser/api/electron_api_app.h"
  27. #include "shell/common/api/electron_bindings.h"
  28. #include "shell/common/electron_command_line.h"
  29. #include "shell/common/gin_converters/file_path_converter.h"
  30. #include "shell/common/gin_helper/dictionary.h"
  31. #include "shell/common/gin_helper/event_emitter_caller.h"
  32. #include "shell/common/gin_helper/locker.h"
  33. #include "shell/common/gin_helper/microtasks_scope.h"
  34. #include "shell/common/mac/main_application_bundle.h"
  35. #include "shell/common/node_includes.h"
  36. #include "third_party/blink/renderer/bindings/core/v8/v8_initializer.h" // nogncheck
  37. #include "third_party/electron_node/src/debug_utils.h"
  38. #if !defined(MAS_BUILD)
  39. #include "shell/common/crash_keys.h"
  40. #endif
  41. #define ELECTRON_BUILTIN_MODULES(V) \
  42. V(electron_browser_app) \
  43. V(electron_browser_auto_updater) \
  44. V(electron_browser_browser_view) \
  45. V(electron_browser_content_tracing) \
  46. V(electron_browser_crash_reporter) \
  47. V(electron_browser_dialog) \
  48. V(electron_browser_event) \
  49. V(electron_browser_event_emitter) \
  50. V(electron_browser_global_shortcut) \
  51. V(electron_browser_in_app_purchase) \
  52. V(electron_browser_menu) \
  53. V(electron_browser_message_port) \
  54. V(electron_browser_native_theme) \
  55. V(electron_browser_net) \
  56. V(electron_browser_notification) \
  57. V(electron_browser_power_monitor) \
  58. V(electron_browser_power_save_blocker) \
  59. V(electron_browser_protocol) \
  60. V(electron_browser_printing) \
  61. V(electron_browser_safe_storage) \
  62. V(electron_browser_session) \
  63. V(electron_browser_screen) \
  64. V(electron_browser_system_preferences) \
  65. V(electron_browser_base_window) \
  66. V(electron_browser_tray) \
  67. V(electron_browser_view) \
  68. V(electron_browser_web_contents) \
  69. V(electron_browser_web_contents_view) \
  70. V(electron_browser_web_frame_main) \
  71. V(electron_browser_web_view_manager) \
  72. V(electron_browser_window) \
  73. V(electron_common_asar) \
  74. V(electron_common_clipboard) \
  75. V(electron_common_command_line) \
  76. V(electron_common_environment) \
  77. V(electron_common_features) \
  78. V(electron_common_native_image) \
  79. V(electron_common_shell) \
  80. V(electron_common_v8_util) \
  81. V(electron_renderer_context_bridge) \
  82. V(electron_renderer_crash_reporter) \
  83. V(electron_renderer_ipc) \
  84. V(electron_renderer_web_frame)
  85. #define ELECTRON_VIEWS_MODULES(V) V(electron_browser_image_view)
  86. #define ELECTRON_DESKTOP_CAPTURER_MODULE(V) V(electron_browser_desktop_capturer)
  87. #define ELECTRON_TESTING_MODULE(V) V(electron_common_testing)
  88. // This is used to load built-in modules. Instead of using
  89. // __attribute__((constructor)), we call the _register_<modname>
  90. // function for each built-in modules explicitly. This is only
  91. // forward declaration. The definitions are in each module's
  92. // implementation when calling the NODE_LINKED_MODULE_CONTEXT_AWARE.
  93. #define V(modname) void _register_##modname();
  94. ELECTRON_BUILTIN_MODULES(V)
  95. #if BUILDFLAG(ENABLE_VIEWS_API)
  96. ELECTRON_VIEWS_MODULES(V)
  97. #endif
  98. #if BUILDFLAG(ENABLE_DESKTOP_CAPTURER)
  99. ELECTRON_DESKTOP_CAPTURER_MODULE(V)
  100. #endif
  101. #if DCHECK_IS_ON()
  102. ELECTRON_TESTING_MODULE(V)
  103. #endif
  104. #undef V
  105. namespace {
  106. void stop_and_close_uv_loop(uv_loop_t* loop) {
  107. uv_stop(loop);
  108. auto const ensure_closing = [](uv_handle_t* handle, void*) {
  109. // We should be using the UvHandle wrapper everywhere, in which case
  110. // all handles should already be in a closing state...
  111. DCHECK(uv_is_closing(handle));
  112. // ...but if a raw handle got through, through, do the right thing anyway
  113. if (!uv_is_closing(handle)) {
  114. uv_close(handle, nullptr);
  115. }
  116. };
  117. uv_walk(loop, ensure_closing, nullptr);
  118. // All remaining handles are in a closing state now.
  119. // Pump the event loop so that they can finish closing.
  120. for (;;)
  121. if (uv_run(loop, UV_RUN_DEFAULT) == 0)
  122. break;
  123. DCHECK_EQ(0, uv_loop_alive(loop));
  124. node::CheckedUvLoopClose(loop);
  125. }
  126. bool g_is_initialized = false;
  127. void V8FatalErrorCallback(const char* location, const char* message) {
  128. LOG(ERROR) << "Fatal error in V8: " << location << " " << message;
  129. #if !defined(MAS_BUILD)
  130. electron::crash_keys::SetCrashKey("electron.v8-fatal.message", message);
  131. electron::crash_keys::SetCrashKey("electron.v8-fatal.location", location);
  132. #endif
  133. volatile int* zero = nullptr;
  134. *zero = 0;
  135. }
  136. bool AllowWasmCodeGenerationCallback(v8::Local<v8::Context> context,
  137. v8::Local<v8::String>) {
  138. // If we're running with contextIsolation enabled in the renderer process,
  139. // fall back to Blink's logic.
  140. v8::Isolate* isolate = context->GetIsolate();
  141. if (node::Environment::GetCurrent(isolate) == nullptr) {
  142. if (gin_helper::Locker::IsBrowserProcess())
  143. return false;
  144. return blink::V8Initializer::WasmCodeGenerationCheckCallbackInMainThread(
  145. context, v8::String::Empty(isolate));
  146. }
  147. return node::AllowWasmCodeGenerationCallback(context,
  148. v8::String::Empty(isolate));
  149. }
  150. void ErrorMessageListener(v8::Local<v8::Message> message,
  151. v8::Local<v8::Value> data) {
  152. v8::Isolate* isolate = v8::Isolate::GetCurrent();
  153. gin_helper::MicrotasksScope microtasks_scope(
  154. isolate, v8::MicrotasksScope::kDoNotRunMicrotasks);
  155. node::Environment* env = node::Environment::GetCurrent(isolate);
  156. if (env) {
  157. // Emit the after() hooks now that the exception has been handled.
  158. // Analogous to node/lib/internal/process/execution.js#L176-L180
  159. if (env->async_hooks()->fields()[node::AsyncHooks::kAfter]) {
  160. while (env->async_hooks()->fields()[node::AsyncHooks::kStackLength]) {
  161. node::AsyncWrap::EmitAfter(env, env->execution_async_id());
  162. env->async_hooks()->pop_async_context(env->execution_async_id());
  163. }
  164. }
  165. // Ensure that the async id stack is properly cleared so the async
  166. // hook stack does not become corrupted.
  167. env->async_hooks()->clear_async_id_stack();
  168. }
  169. }
  170. const std::unordered_set<base::StringPiece, base::StringPieceHash>
  171. GetAllowedDebugOptions() {
  172. if (electron::fuses::IsNodeCliInspectEnabled()) {
  173. // Only allow DebugOptions in non-ELECTRON_RUN_AS_NODE mode
  174. return {
  175. "--inspect", "--inspect-brk",
  176. "--inspect-port", "--debug",
  177. "--debug-brk", "--debug-port",
  178. "--inspect-brk-node", "--inspect-publish-uid",
  179. };
  180. }
  181. // If node CLI inspect support is disabled, allow no debug options.
  182. return {};
  183. }
  184. // Initialize Node.js cli options to pass to Node.js
  185. // See https://nodejs.org/api/cli.html#cli_options
  186. void SetNodeCliFlags() {
  187. const std::unordered_set<base::StringPiece, base::StringPieceHash> allowed =
  188. GetAllowedDebugOptions();
  189. const auto argv = base::CommandLine::ForCurrentProcess()->argv();
  190. std::vector<std::string> args;
  191. // TODO(codebytere): We need to set the first entry in args to the
  192. // process name owing to src/node_options-inl.h#L286-L290 but this is
  193. // redundant and so should be refactored upstream.
  194. args.reserve(argv.size() + 1);
  195. args.emplace_back("electron");
  196. for (const auto& arg : argv) {
  197. #if BUILDFLAG(IS_WIN)
  198. const auto& option = base::WideToUTF8(arg);
  199. #else
  200. const auto& option = arg;
  201. #endif
  202. const auto stripped = base::StringPiece(option).substr(0, option.find('='));
  203. // Only allow in no-op (--) option or DebugOptions
  204. if (allowed.count(stripped) != 0 || stripped == "--")
  205. args.push_back(option);
  206. }
  207. std::vector<std::string> errors;
  208. const int exit_code = ProcessGlobalArgs(&args, nullptr, &errors,
  209. node::kDisallowedInEnvironment);
  210. const std::string err_str = "Error parsing Node.js cli flags ";
  211. if (exit_code != 0) {
  212. LOG(ERROR) << err_str;
  213. } else if (!errors.empty()) {
  214. LOG(ERROR) << err_str << base::JoinString(errors, " ");
  215. }
  216. }
  217. // Initialize NODE_OPTIONS to pass to Node.js
  218. // See https://nodejs.org/api/cli.html#cli_node_options_options
  219. void SetNodeOptions(base::Environment* env) {
  220. // Options that are unilaterally disallowed
  221. const std::set<std::string> disallowed = {
  222. "--openssl-config", "--use-bundled-ca", "--use-openssl-ca",
  223. "--force-fips", "--enable-fips"};
  224. // Subset of options allowed in packaged apps
  225. const std::set<std::string> allowed_in_packaged = {"--max-http-header-size",
  226. "--http-parser"};
  227. if (env->HasVar("NODE_OPTIONS")) {
  228. if (electron::fuses::IsNodeOptionsEnabled()) {
  229. std::string options;
  230. env->GetVar("NODE_OPTIONS", &options);
  231. std::vector<std::string> parts = base::SplitString(
  232. options, " ", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
  233. bool is_packaged_app = electron::api::App::IsPackaged();
  234. for (const auto& part : parts) {
  235. // Strip off values passed to individual NODE_OPTIONs
  236. std::string option = part.substr(0, part.find('='));
  237. if (is_packaged_app &&
  238. allowed_in_packaged.find(option) == allowed_in_packaged.end()) {
  239. // Explicitly disallow majority of NODE_OPTIONS in packaged apps
  240. LOG(ERROR) << "Most NODE_OPTIONs are not supported in packaged apps."
  241. << " See documentation for more details.";
  242. options.erase(options.find(option), part.length());
  243. } else if (disallowed.find(option) != disallowed.end()) {
  244. // Remove NODE_OPTIONS specifically disallowed for use in Node.js
  245. // through Electron owing to constraints like BoringSSL.
  246. LOG(ERROR) << "The NODE_OPTION " << option
  247. << " is not supported in Electron";
  248. options.erase(options.find(option), part.length());
  249. }
  250. }
  251. // overwrite new NODE_OPTIONS without unsupported variables
  252. env->SetVar("NODE_OPTIONS", options);
  253. } else {
  254. LOG(ERROR) << "NODE_OPTIONS have been disabled in this app";
  255. env->SetVar("NODE_OPTIONS", "");
  256. }
  257. }
  258. }
  259. } // namespace
  260. namespace electron {
  261. namespace {
  262. base::FilePath GetResourcesPath() {
  263. #if BUILDFLAG(IS_MAC)
  264. return MainApplicationBundlePath().Append("Contents").Append("Resources");
  265. #else
  266. auto* command_line = base::CommandLine::ForCurrentProcess();
  267. base::FilePath exec_path(command_line->GetProgram());
  268. base::PathService::Get(base::FILE_EXE, &exec_path);
  269. return exec_path.DirName().Append(FILE_PATH_LITERAL("resources"));
  270. #endif
  271. }
  272. } // namespace
  273. NodeBindings::NodeBindings(BrowserEnvironment browser_env)
  274. : browser_env_(browser_env) {
  275. if (browser_env == BrowserEnvironment::kWorker) {
  276. uv_loop_init(&worker_loop_);
  277. uv_loop_ = &worker_loop_;
  278. } else {
  279. uv_loop_ = uv_default_loop();
  280. }
  281. // Interrupt embed polling when a handle is started.
  282. uv_loop_configure(uv_loop_, UV_LOOP_INTERRUPT_ON_IO_CHANGE);
  283. }
  284. NodeBindings::~NodeBindings() {
  285. // Quit the embed thread.
  286. embed_closed_ = true;
  287. uv_sem_post(&embed_sem_);
  288. WakeupEmbedThread();
  289. // Wait for everything to be done.
  290. uv_thread_join(&embed_thread_);
  291. // Clear uv.
  292. uv_sem_destroy(&embed_sem_);
  293. dummy_uv_handle_.reset();
  294. // Clean up worker loop
  295. if (in_worker_loop())
  296. stop_and_close_uv_loop(uv_loop_);
  297. }
  298. void NodeBindings::RegisterBuiltinModules() {
  299. #define V(modname) _register_##modname();
  300. ELECTRON_BUILTIN_MODULES(V)
  301. #if BUILDFLAG(ENABLE_VIEWS_API)
  302. ELECTRON_VIEWS_MODULES(V)
  303. #endif
  304. #if BUILDFLAG(ENABLE_DESKTOP_CAPTURER)
  305. ELECTRON_DESKTOP_CAPTURER_MODULE(V)
  306. #endif
  307. #if DCHECK_IS_ON()
  308. ELECTRON_TESTING_MODULE(V)
  309. #endif
  310. #undef V
  311. }
  312. bool NodeBindings::IsInitialized() {
  313. return g_is_initialized;
  314. }
  315. void NodeBindings::Initialize() {
  316. TRACE_EVENT0("electron", "NodeBindings::Initialize");
  317. // Open node's error reporting system for browser process.
  318. #if BUILDFLAG(IS_LINUX)
  319. // Get real command line in renderer process forked by zygote.
  320. if (browser_env_ != BrowserEnvironment::kBrowser)
  321. ElectronCommandLine::InitializeFromCommandLine();
  322. #endif
  323. // Explicitly register electron's builtin modules.
  324. RegisterBuiltinModules();
  325. // Parse and set Node.js cli flags.
  326. SetNodeCliFlags();
  327. auto env = base::Environment::Create();
  328. SetNodeOptions(env.get());
  329. std::vector<std::string> argv = {"electron"};
  330. std::vector<std::string> exec_argv;
  331. std::vector<std::string> errors;
  332. uint64_t process_flags = node::ProcessFlags::kEnableStdioInheritance;
  333. if (!fuses::IsNodeOptionsEnabled())
  334. process_flags |= node::ProcessFlags::kDisableNodeOptionsEnv;
  335. int exit_code = node::InitializeNodeWithArgs(
  336. &argv, &exec_argv, &errors,
  337. static_cast<node::ProcessFlags::Flags>(process_flags));
  338. for (const std::string& error : errors)
  339. fprintf(stderr, "%s: %s\n", argv[0].c_str(), error.c_str());
  340. if (exit_code != 0)
  341. exit(exit_code);
  342. #if BUILDFLAG(IS_WIN)
  343. // uv_init overrides error mode to suppress the default crash dialog, bring
  344. // it back if user wants to show it.
  345. if (browser_env_ == BrowserEnvironment::kBrowser ||
  346. env->HasVar("ELECTRON_DEFAULT_ERROR_MODE"))
  347. SetErrorMode(GetErrorMode() & ~SEM_NOGPFAULTERRORBOX);
  348. #endif
  349. g_is_initialized = true;
  350. }
  351. node::Environment* NodeBindings::CreateEnvironment(
  352. v8::Handle<v8::Context> context,
  353. node::MultiIsolatePlatform* platform) {
  354. #if BUILDFLAG(IS_WIN)
  355. auto& atom_args = ElectronCommandLine::argv();
  356. std::vector<std::string> args(atom_args.size());
  357. std::transform(atom_args.cbegin(), atom_args.cend(), args.begin(),
  358. [](auto& a) { return base::WideToUTF8(a); });
  359. #else
  360. auto args = ElectronCommandLine::argv();
  361. #endif
  362. // Feed node the path to initialization script.
  363. std::string process_type;
  364. switch (browser_env_) {
  365. case BrowserEnvironment::kBrowser:
  366. process_type = "browser";
  367. break;
  368. case BrowserEnvironment::kRenderer:
  369. process_type = "renderer";
  370. break;
  371. case BrowserEnvironment::kWorker:
  372. process_type = "worker";
  373. break;
  374. }
  375. v8::Isolate* isolate = context->GetIsolate();
  376. gin_helper::Dictionary global(isolate, context->Global());
  377. // Do not set DOM globals for renderer process.
  378. // We must set this before the node bootstrapper which is run inside
  379. // CreateEnvironment
  380. if (browser_env_ != BrowserEnvironment::kBrowser)
  381. global.Set("_noBrowserGlobals", true);
  382. if (browser_env_ == BrowserEnvironment::kBrowser) {
  383. const std::vector<std::string> search_paths = {"app.asar", "app",
  384. "default_app.asar"};
  385. const std::vector<std::string> app_asar_search_paths = {"app.asar"};
  386. context->Global()->SetPrivate(
  387. context,
  388. v8::Private::ForApi(
  389. isolate,
  390. gin::ConvertToV8(isolate, "appSearchPaths").As<v8::String>()),
  391. gin::ConvertToV8(isolate,
  392. electron::fuses::IsOnlyLoadAppFromAsarEnabled()
  393. ? app_asar_search_paths
  394. : search_paths));
  395. }
  396. std::vector<std::string> exec_args;
  397. base::FilePath resources_path = GetResourcesPath();
  398. std::string init_script = "electron/js2c/" + process_type + "_init";
  399. args.insert(args.begin() + 1, init_script);
  400. if (!isolate_data_)
  401. isolate_data_ = node::CreateIsolateData(isolate, uv_loop_, platform);
  402. node::Environment* env;
  403. uint64_t flags = node::EnvironmentFlags::kDefaultFlags |
  404. node::EnvironmentFlags::kHideConsoleWindows |
  405. node::EnvironmentFlags::kNoGlobalSearchPaths;
  406. if (browser_env_ != BrowserEnvironment::kBrowser) {
  407. // Only one ESM loader can be registered per isolate -
  408. // in renderer processes this should be blink. We need to tell Node.js
  409. // not to register its handler (overriding blinks) in non-browser processes.
  410. flags |= node::EnvironmentFlags::kNoRegisterESMLoader |
  411. node::EnvironmentFlags::kNoInitializeInspector;
  412. }
  413. if (!electron::fuses::IsNodeCliInspectEnabled()) {
  414. // If --inspect and friends are disabled we also shouldn't listen for
  415. // SIGUSR1
  416. flags |= node::EnvironmentFlags::kNoStartDebugSignalHandler;
  417. }
  418. v8::TryCatch try_catch(isolate);
  419. env = node::CreateEnvironment(
  420. isolate_data_, context, args, exec_args,
  421. static_cast<node::EnvironmentFlags::Flags>(flags));
  422. if (try_catch.HasCaught()) {
  423. std::string err_msg =
  424. "Failed to initialize node environment in process: " + process_type;
  425. v8::Local<v8::Message> message = try_catch.Message();
  426. std::string msg;
  427. if (!message.IsEmpty() && gin::ConvertFromV8(isolate, message->Get(), &msg))
  428. err_msg += " , with error: " + msg;
  429. LOG(ERROR) << err_msg;
  430. }
  431. DCHECK(env);
  432. // Clean up the global _noBrowserGlobals that we unironically injected into
  433. // the global scope
  434. if (browser_env_ != BrowserEnvironment::kBrowser) {
  435. // We need to bootstrap the env in non-browser processes so that
  436. // _noBrowserGlobals is read correctly before we remove it
  437. global.Delete("_noBrowserGlobals");
  438. }
  439. node::IsolateSettings is;
  440. // Use a custom fatal error callback to allow us to add
  441. // crash message and location to CrashReports.
  442. is.fatal_error_callback = V8FatalErrorCallback;
  443. // We don't want to abort either in the renderer or browser processes.
  444. // We already listen for uncaught exceptions and handle them there.
  445. is.should_abort_on_uncaught_exception_callback = [](v8::Isolate*) {
  446. return false;
  447. };
  448. // Use a custom callback here to allow us to leverage Blink's logic in the
  449. // renderer process.
  450. is.allow_wasm_code_generation_callback = AllowWasmCodeGenerationCallback;
  451. if (browser_env_ == BrowserEnvironment::kBrowser) {
  452. // Node.js requires that microtask checkpoints be explicitly invoked.
  453. is.policy = v8::MicrotasksPolicy::kExplicit;
  454. } else {
  455. // Blink expects the microtasks policy to be kScoped, but Node.js expects it
  456. // to be kExplicit. In the renderer, there can be many contexts within the
  457. // same isolate, so we don't want to change the existing policy here, which
  458. // could be either kExplicit or kScoped depending on whether we're executing
  459. // from within a Node.js or a Blink entrypoint. Instead, the policy is
  460. // toggled to kExplicit when entering Node.js through UvRunOnce.
  461. is.policy = context->GetIsolate()->GetMicrotasksPolicy();
  462. // We do not want to use Node.js' message listener as it interferes with
  463. // Blink's.
  464. is.flags &= ~node::IsolateSettingsFlags::MESSAGE_LISTENER_WITH_ERROR_LEVEL;
  465. // Isolate message listeners are additive (you can add multiple), so instead
  466. // we add an extra one here to ensure that the async hook stack is properly
  467. // cleared when errors are thrown.
  468. context->GetIsolate()->AddMessageListenerWithErrorLevel(
  469. ErrorMessageListener, v8::Isolate::kMessageError);
  470. // We do not want to use the promise rejection callback that Node.js uses,
  471. // because it does not send PromiseRejectionEvents to the global script
  472. // context. We need to use the one Blink already provides.
  473. is.flags |=
  474. node::IsolateSettingsFlags::SHOULD_NOT_SET_PROMISE_REJECTION_CALLBACK;
  475. // We do not want to use the stack trace callback that Node.js uses,
  476. // because it relies on Node.js being aware of the current Context and
  477. // that's not always the case. We need to use the one Blink already
  478. // provides.
  479. is.flags |=
  480. node::IsolateSettingsFlags::SHOULD_NOT_SET_PREPARE_STACK_TRACE_CALLBACK;
  481. }
  482. node::SetIsolateUpForNode(context->GetIsolate(), is);
  483. gin_helper::Dictionary process(context->GetIsolate(), env->process_object());
  484. process.SetReadOnly("type", process_type);
  485. process.Set("resourcesPath", resources_path);
  486. // The path to helper app.
  487. base::FilePath helper_exec_path;
  488. base::PathService::Get(content::CHILD_PROCESS_EXE, &helper_exec_path);
  489. process.Set("helperExecPath", helper_exec_path);
  490. return env;
  491. }
  492. void NodeBindings::LoadEnvironment(node::Environment* env) {
  493. node::LoadEnvironment(env, node::StartExecutionCallback{});
  494. gin_helper::EmitEvent(env->isolate(), env->process_object(), "loaded");
  495. }
  496. void NodeBindings::PrepareMessageLoop() {
  497. // Add dummy handle for libuv, otherwise libuv would quit when there is
  498. // nothing to do.
  499. uv_async_init(uv_loop_, dummy_uv_handle_.get(), nullptr);
  500. // Start worker that will interrupt main loop when having uv events.
  501. uv_sem_init(&embed_sem_, 0);
  502. uv_thread_create(&embed_thread_, EmbedThreadRunner, this);
  503. }
  504. void NodeBindings::RunMessageLoop() {
  505. // The MessageLoop should have been created, remember the one in main thread.
  506. task_runner_ = base::ThreadTaskRunnerHandle::Get();
  507. // Run uv loop for once to give the uv__io_poll a chance to add all events.
  508. UvRunOnce();
  509. }
  510. void NodeBindings::UvRunOnce() {
  511. node::Environment* env = uv_env();
  512. // When doing navigation without restarting renderer process, it may happen
  513. // that the node environment is destroyed but the message loop is still there.
  514. // In this case we should not run uv loop.
  515. if (!env)
  516. return;
  517. // Use Locker in browser process.
  518. gin_helper::Locker locker(env->isolate());
  519. v8::HandleScope handle_scope(env->isolate());
  520. // Enter node context while dealing with uv events.
  521. v8::Context::Scope context_scope(env->context());
  522. // Node.js expects `kExplicit` microtasks policy and will run microtasks
  523. // checkpoints after every call into JavaScript. Since we use a different
  524. // policy in the renderer - switch to `kExplicit` and then drop back to the
  525. // previous policy value.
  526. auto old_policy = env->isolate()->GetMicrotasksPolicy();
  527. DCHECK_EQ(v8::MicrotasksScope::GetCurrentDepth(env->isolate()), 0);
  528. env->isolate()->SetMicrotasksPolicy(v8::MicrotasksPolicy::kExplicit);
  529. if (browser_env_ != BrowserEnvironment::kBrowser)
  530. TRACE_EVENT_BEGIN0("devtools.timeline", "FunctionCall");
  531. // Deal with uv events.
  532. int r = uv_run(uv_loop_, UV_RUN_NOWAIT);
  533. if (browser_env_ != BrowserEnvironment::kBrowser)
  534. TRACE_EVENT_END0("devtools.timeline", "FunctionCall");
  535. env->isolate()->SetMicrotasksPolicy(old_policy);
  536. if (r == 0)
  537. base::RunLoop().QuitWhenIdle(); // Quit from uv.
  538. // Tell the worker thread to continue polling.
  539. uv_sem_post(&embed_sem_);
  540. }
  541. void NodeBindings::WakeupMainThread() {
  542. DCHECK(task_runner_);
  543. task_runner_->PostTask(FROM_HERE, base::BindOnce(&NodeBindings::UvRunOnce,
  544. weak_factory_.GetWeakPtr()));
  545. }
  546. void NodeBindings::WakeupEmbedThread() {
  547. uv_async_send(dummy_uv_handle_.get());
  548. }
  549. // static
  550. void NodeBindings::EmbedThreadRunner(void* arg) {
  551. auto* self = static_cast<NodeBindings*>(arg);
  552. while (true) {
  553. // Wait for the main loop to deal with events.
  554. uv_sem_wait(&self->embed_sem_);
  555. if (self->embed_closed_)
  556. break;
  557. // Wait for something to happen in uv loop.
  558. // Note that the PollEvents() is implemented by derived classes, so when
  559. // this class is being destructed the PollEvents() would not be available
  560. // anymore. Because of it we must make sure we only invoke PollEvents()
  561. // when this class is alive.
  562. self->PollEvents();
  563. if (self->embed_closed_)
  564. break;
  565. // Deal with event in main thread.
  566. self->WakeupMainThread();
  567. }
  568. }
  569. } // namespace electron