node_bindings.h 7.0 KB

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