node_bindings.cc 36 KB

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