node_bindings.cc 35 KB

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