node_bindings.cc 30 KB

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