node_bindings.h 7.8 KB

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