node_bindings.cc 22 KB

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