node_bindings.cc 22 KB

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