node_bindings.cc 28 KB

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