node_bindings.cc 23 KB

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