node_bindings.cc 28 KB

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