node_bindings.h 6.5 KB

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