node_bindings.cc 22 KB

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