node_bindings.cc 36 KB

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