node_bindings.h 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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. #ifndef ELECTRON_SHELL_COMMON_NODE_BINDINGS_H_
  5. #define ELECTRON_SHELL_COMMON_NODE_BINDINGS_H_
  6. #include <memory>
  7. #include <optional>
  8. #include <string>
  9. #include <type_traits>
  10. #include <vector>
  11. #include "base/functional/callback.h"
  12. #include "base/memory/raw_ptr.h"
  13. #include "base/memory/raw_ptr_exclusion.h"
  14. #include "base/memory/weak_ptr.h"
  15. #include "gin/public/context_holder.h"
  16. #include "gin/public/gin_embedders.h"
  17. #include "uv.h" // NOLINT(build/include_directory)
  18. #include "v8/include/v8-forward.h"
  19. namespace base {
  20. class SingleThreadTaskRunner;
  21. }
  22. namespace node {
  23. class Environment;
  24. class IsolateData;
  25. class MultiIsolatePlatform;
  26. } // namespace node
  27. namespace electron {
  28. // A helper class to manage uv_handle_t types, e.g. uv_async_t.
  29. //
  30. // As per the uv docs: "uv_close() MUST be called on each handle before
  31. // memory is released. Moreover, the memory can only be released in
  32. // close_cb or after it has returned." This class encapsulates the work
  33. // needed to follow those requirements.
  34. template <typename T,
  35. typename std::enable_if<
  36. // these are the C-style 'subclasses' of uv_handle_t
  37. std::is_same<T, uv_async_t>::value ||
  38. std::is_same<T, uv_check_t>::value ||
  39. std::is_same<T, uv_fs_event_t>::value ||
  40. std::is_same<T, uv_fs_poll_t>::value ||
  41. std::is_same<T, uv_idle_t>::value ||
  42. std::is_same<T, uv_pipe_t>::value ||
  43. std::is_same<T, uv_poll_t>::value ||
  44. std::is_same<T, uv_prepare_t>::value ||
  45. std::is_same<T, uv_process_t>::value ||
  46. std::is_same<T, uv_signal_t>::value ||
  47. std::is_same<T, uv_stream_t>::value ||
  48. std::is_same<T, uv_tcp_t>::value ||
  49. std::is_same<T, uv_timer_t>::value ||
  50. std::is_same<T, uv_tty_t>::value ||
  51. std::is_same<T, uv_udp_t>::value>::type* = nullptr>
  52. class UvHandle {
  53. public:
  54. UvHandle() : t_(new T) {}
  55. ~UvHandle() { reset(); }
  56. T* get() { return t_; }
  57. uv_handle_t* handle() { return reinterpret_cast<uv_handle_t*>(t_); }
  58. void reset() {
  59. auto* h = handle();
  60. if (h != nullptr) {
  61. DCHECK_EQ(0, uv_is_closing(h));
  62. uv_close(h, OnClosed);
  63. t_ = nullptr;
  64. }
  65. }
  66. private:
  67. static void OnClosed(uv_handle_t* handle) {
  68. delete reinterpret_cast<T*>(handle);
  69. }
  70. RAW_PTR_EXCLUSION T* t_ = {};
  71. };
  72. class NodeBindings {
  73. public:
  74. enum class BrowserEnvironment { kBrowser, kRenderer, kUtility, kWorker };
  75. static NodeBindings* Create(BrowserEnvironment browser_env);
  76. static void RegisterBuiltinBindings();
  77. static bool IsInitialized();
  78. virtual ~NodeBindings();
  79. // Setup V8, libuv.
  80. void Initialize(v8::Local<v8::Context> context);
  81. std::vector<std::string> ParseNodeCliFlags();
  82. // Create the environment and load node.js.
  83. std::shared_ptr<node::Environment> CreateEnvironment(
  84. v8::Local<v8::Context> context,
  85. node::MultiIsolatePlatform* platform,
  86. std::vector<std::string> args,
  87. std::vector<std::string> exec_args,
  88. std::optional<base::RepeatingCallback<void()>> on_app_code_ready =
  89. std::nullopt);
  90. std::shared_ptr<node::Environment> CreateEnvironment(
  91. v8::Local<v8::Context> context,
  92. node::MultiIsolatePlatform* platform,
  93. std::optional<base::RepeatingCallback<void()>> on_app_code_ready =
  94. std::nullopt);
  95. // Load node.js in the environment.
  96. void LoadEnvironment(node::Environment* env);
  97. // Prepare embed thread for message loop integration.
  98. void PrepareEmbedThread();
  99. // Notify embed thread to start polling after environment is loaded.
  100. void StartPolling();
  101. node::IsolateData* isolate_data(v8::Local<v8::Context> context) const;
  102. // Gets/sets the environment to wrap uv loop.
  103. void set_uv_env(node::Environment* env) { uv_env_ = env; }
  104. node::Environment* uv_env() const { return uv_env_; }
  105. [[nodiscard]] constexpr uv_loop_t* uv_loop() { return uv_loop_; }
  106. // disable copy
  107. NodeBindings(const NodeBindings&) = delete;
  108. NodeBindings& operator=(const NodeBindings&) = delete;
  109. // Blocks until app code is signaled to be loaded via |SetAppCodeLoaded|.
  110. // Only has an effect if called in the browser process
  111. void JoinAppCode();
  112. protected:
  113. explicit NodeBindings(BrowserEnvironment browser_env);
  114. // Called to poll events in new thread.
  115. virtual void PollEvents() = 0;
  116. // Make the main thread run libuv loop.
  117. void WakeupMainThread();
  118. // Interrupt the PollEvents.
  119. void WakeupEmbedThread();
  120. private:
  121. static uv_loop_t* InitEventLoop(BrowserEnvironment browser_env,
  122. uv_loop_t* worker_loop);
  123. // Run the libuv loop for once.
  124. void UvRunOnce();
  125. [[nodiscard]] constexpr bool in_worker_loop() const {
  126. return browser_env_ == BrowserEnvironment::kWorker;
  127. }
  128. // Which environment we are running.
  129. const BrowserEnvironment browser_env_;
  130. // Loop used when constructed in WORKER mode
  131. uv_loop_t worker_loop_;
  132. // Current thread's libuv loop.
  133. // depends-on: worker_loop_
  134. const raw_ptr<uv_loop_t> uv_loop_;
  135. // Current thread's MessageLoop.
  136. scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
  137. // Choose a reasonable unique index that's higher than any Blink uses
  138. // and thus unlikely to collide with an existing index.
  139. static constexpr int kElectronContextEmbedderDataIndex =
  140. static_cast<int>(gin::kPerContextDataStartIndex) +
  141. static_cast<int>(gin::kEmbedderElectron);
  142. // Thread to poll uv events.
  143. static void EmbedThreadRunner(void* arg);
  144. // Default callback to indicate when the node environment has finished
  145. // initializing and the primary import chain is fully resolved and executed
  146. void SetAppCodeLoaded();
  147. // Indicates whether polling thread has been created.
  148. bool initialized_ = false;
  149. // Indicates whether the app code has finished loading
  150. // for ESM this is async after the module is loaded
  151. bool app_code_loaded_ = false;
  152. // Whether the libuv loop has ended.
  153. bool embed_closed_ = false;
  154. // Dummy handle to make uv's loop not quit.
  155. UvHandle<uv_async_t> dummy_uv_handle_;
  156. // Thread for polling events.
  157. uv_thread_t embed_thread_;
  158. // Semaphore to wait for main loop in the embed thread.
  159. uv_sem_t embed_sem_;
  160. // Environment that to wrap the uv loop.
  161. raw_ptr<node::Environment> uv_env_ = nullptr;
  162. // Isolate data used in creating the environment
  163. raw_ptr<node::IsolateData> isolate_data_ = nullptr;
  164. base::WeakPtrFactory<NodeBindings> weak_factory_{this};
  165. };
  166. // A thread-safe function responsible for loading preload script which runs for
  167. // all node environments (including child processes and workers).
  168. void OnNodePreload(node::Environment* env,
  169. v8::Local<v8::Value> process,
  170. v8::Local<v8::Value> require);
  171. } // namespace electron
  172. #endif // ELECTRON_SHELL_COMMON_NODE_BINDINGS_H_