node_bindings.cc 33 KB

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