• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright Joyent, Inc. and other Node contributors.
2 //
3 // Permission is hereby granted, free of charge, to any person obtaining a
4 // copy of this software and associated documentation files (the
5 // "Software"), to deal in the Software without restriction, including
6 // without limitation the rights to use, copy, modify, merge, publish,
7 // distribute, sublicense, and/or sell copies of the Software, and to permit
8 // persons to whom the Software is furnished to do so, subject to the
9 // following conditions:
10 //
11 // The above copyright notice and this permission notice shall be included
12 // in all copies or substantial portions of the Software.
13 //
14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20 // USE OR OTHER DEALINGS IN THE SOFTWARE.
21 
22 #ifndef SRC_BASE_OBJECT_H_
23 #define SRC_BASE_OBJECT_H_
24 
25 #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
26 
27 #include <type_traits>  // std::remove_reference
28 #include "base_object_types.h"
29 #include "memory_tracker.h"
30 #include "v8.h"
31 
32 namespace node {
33 
34 class Environment;
35 class IsolateData;
36 class Realm;
37 template <typename T, bool kIsWeak>
38 class BaseObjectPtrImpl;
39 
40 namespace worker {
41 class TransferData;
42 }
43 
44 extern uint16_t kNodeEmbedderId;
45 
46 class BaseObject : public MemoryRetainer {
47  public:
48   enum InternalFields { kEmbedderType, kSlot, kInternalFieldCount };
49 
50   // Associates this object with `object`. It uses the 1st internal field for
51   // that, and in particular aborts if there is no such field.
52   // This is the designated constructor.
53   BaseObject(Realm* realm, v8::Local<v8::Object> object);
54   // Convenient constructor for constructing BaseObject in the principal realm.
55   inline BaseObject(Environment* env, v8::Local<v8::Object> object);
56   ~BaseObject() override;
57 
58   BaseObject() = delete;
59 
60   // Returns the wrapped object.  Returns an empty handle when
61   // persistent.IsEmpty() is true.
62   inline v8::Local<v8::Object> object() const;
63 
64   // Same as the above, except it additionally verifies that this object
65   // is associated with the passed Isolate in debug mode.
66   inline v8::Local<v8::Object> object(v8::Isolate* isolate) const;
67 
68   inline v8::Global<v8::Object>& persistent();
69 
70   inline Environment* env() const;
71   inline Realm* realm() const;
72 
73   // Get a BaseObject* pointer, or subclass pointer, for the JS object that
74   // was also passed to the `BaseObject()` constructor initially.
75   // This may return `nullptr` if the C++ object has not been constructed yet,
76   // e.g. when the JS object used `MakeLazilyInitializedJSTemplate`.
77   static inline void SetInternalFields(v8::Local<v8::Object> object,
78                                        void* slot);
79   static inline void TagNodeObject(v8::Local<v8::Object> object);
80   static void LazilyInitializedJSTemplateConstructor(
81       const v8::FunctionCallbackInfo<v8::Value>& args);
82   static inline BaseObject* FromJSObject(v8::Local<v8::Value> object);
83   template <typename T>
84   static inline T* FromJSObject(v8::Local<v8::Value> object);
85 
86   // Make the `v8::Global` a weak reference and, `delete` this object once
87   // the JS object has been garbage collected and there are no (strong)
88   // BaseObjectPtr references to it.
89   void MakeWeak();
90 
91   // Undo `MakeWeak()`, i.e. turn this into a strong reference that is a GC
92   // root and will not be touched by the garbage collector.
93   inline void ClearWeak();
94 
95   // Reports whether this BaseObject is using a weak reference or detached,
96   // i.e. whether is can be deleted by GC once no strong BaseObjectPtrs refer
97   // to it anymore.
98   inline bool IsWeakOrDetached() const;
99 
100   inline v8::EmbedderGraph::Node::Detachedness GetDetachedness() const override;
101 
102   // Utility to create a FunctionTemplate with one internal field (used for
103   // the `BaseObject*` pointer) and a constructor that initializes that field
104   // to `nullptr`.
105   static v8::Local<v8::FunctionTemplate> MakeLazilyInitializedJSTemplate(
106       IsolateData* isolate);
107   static v8::Local<v8::FunctionTemplate> MakeLazilyInitializedJSTemplate(
108       Environment* env);
109 
110   // Setter/Getter pair for internal fields that can be passed to SetAccessor.
111   template <int Field>
112   static void InternalFieldGet(v8::Local<v8::String> property,
113                                const v8::PropertyCallbackInfo<v8::Value>& info);
114   template <int Field, bool (v8::Value::*typecheck)() const>
115   static void InternalFieldSet(v8::Local<v8::String> property,
116                                v8::Local<v8::Value> value,
117                                const v8::PropertyCallbackInfo<void>& info);
118 
119   // This is a bit of a hack. See the override in async_wrap.cc for details.
120   virtual bool IsDoneInitializing() const;
121 
122   // Can be used to avoid this object keeping itself alive as a GC root
123   // indefinitely, for example when this object is owned and deleted by another
124   // BaseObject once that is torn down. This can only be called when there is
125   // a BaseObjectPtr to this object.
126   inline void Detach();
127 
128   static inline v8::Local<v8::FunctionTemplate> GetConstructorTemplate(
129       Environment* env);
130   static v8::Local<v8::FunctionTemplate> GetConstructorTemplate(
131       IsolateData* isolate_data);
132 
133   // Interface for transferring BaseObject instances using the .postMessage()
134   // method of MessagePorts (and, by extension, Workers).
135   // GetTransferMode() returns a transfer mode that indicates how to deal with
136   // the current object:
137   // - kUntransferable:
138   //     No transfer is possible, either because this type of BaseObject does
139   //     not know how to be transferred, or because it is not in a state in
140   //     which it is possible to do so (e.g. because it has already been
141   //     transferred).
142   // - kTransferable:
143   //     This object can be transferred in a destructive fashion, i.e. will be
144   //     rendered unusable on the sending side of the channel in the process
145   //     of being transferred. (In C++ this would be referred to as movable but
146   //     not copyable.) Objects of this type need to be listed in the
147   //     `transferList` argument of the relevant postMessage() call in order to
148   //     make sure that they are not accidentally destroyed on the sending side.
149   //     TransferForMessaging() will be called to get a representation of the
150   //     object that is used for subsequent deserialization.
151   //     The NestedTransferables() method can be used to transfer other objects
152   //     along with this one, if a situation requires it.
153   // - kCloneable:
154   //     This object can be cloned without being modified.
155   //     CloneForMessaging() will be called to get a representation of the
156   //     object that is used for subsequent deserialization, unless the
157   //     object is listed in transferList, in which case TransferForMessaging()
158   //     is attempted first.
159   // After a successful clone, FinalizeTransferRead() is called on the receiving
160   // end, and can read deserialize JS data possibly serialized by a previous
161   // FinalizeTransferWrite() call.
162   enum class TransferMode {
163     kUntransferable,
164     kTransferable,
165     kCloneable
166   };
167   virtual TransferMode GetTransferMode() const;
168   virtual std::unique_ptr<worker::TransferData> TransferForMessaging();
169   virtual std::unique_ptr<worker::TransferData> CloneForMessaging() const;
170   virtual v8::Maybe<std::vector<BaseObjectPtrImpl<BaseObject, false>>>
171       NestedTransferables() const;
172   virtual v8::Maybe<bool> FinalizeTransferRead(
173       v8::Local<v8::Context> context, v8::ValueDeserializer* deserializer);
174 
175   // Indicates whether this object is expected to use a strong reference during
176   // a clean process exit (due to an empty event loop).
177   virtual bool IsNotIndicativeOfMemoryLeakAtExit() const;
178 
179   virtual inline void OnGCCollect();
180 
is_snapshotable()181   virtual inline bool is_snapshotable() const { return false; }
182 
183  private:
184   v8::Local<v8::Object> WrappedObject() const override;
185   bool IsRootNode() const override;
186   static void DeleteMe(void* data);
187 
188   // persistent_handle_ needs to be at a fixed offset from the start of the
189   // class because it is used by src/node_postmortem_metadata.cc to calculate
190   // offsets and generate debug symbols for BaseObject, which assumes that the
191   // position of members in memory are predictable. For more information please
192   // refer to `doc/contributing/node-postmortem-support.md`
193   friend int GenDebugSymbols();
194   friend class CleanupQueue;
195   template <typename T, bool kIsWeak>
196   friend class BaseObjectPtrImpl;
197 
198   v8::Global<v8::Object> persistent_handle_;
199 
200   // Metadata that is associated with this BaseObject if there are BaseObjectPtr
201   // or BaseObjectWeakPtr references to it.
202   // This object is deleted when the BaseObject itself is destroyed, and there
203   // are no weak references to it.
204   struct PointerData {
205     // Number of BaseObjectPtr instances that refer to this object. If this
206     // is non-zero, the BaseObject is always a GC root and will not be destroyed
207     // during cleanup until the count drops to zero again.
208     unsigned int strong_ptr_count = 0;
209     // Number of BaseObjectWeakPtr instances that refer to this object.
210     unsigned int weak_ptr_count = 0;
211     // Indicates whether MakeWeak() has been called.
212     bool wants_weak_jsobj = false;
213     // Indicates whether Detach() has been called. If that is the case, this
214     // object will be destroyed once the strong pointer count drops to zero.
215     bool is_detached = false;
216     // Reference to the original BaseObject. This is used by weak pointers.
217     BaseObject* self = nullptr;
218   };
219 
220   inline bool has_pointer_data() const;
221   // This creates a PointerData struct if none was associated with this
222   // BaseObject before.
223   PointerData* pointer_data();
224 
225   // Functions that adjust the strong pointer count.
226   void decrease_refcount();
227   void increase_refcount();
228 
229   Realm* realm_;
230   PointerData* pointer_data_ = nullptr;
231 };
232 
233 // Global alias for FromJSObject() to avoid churn.
234 template <typename T>
Unwrap(v8::Local<v8::Value> obj)235 inline T* Unwrap(v8::Local<v8::Value> obj) {
236   return BaseObject::FromJSObject<T>(obj);
237 }
238 
239 #define ASSIGN_OR_RETURN_UNWRAP(ptr, obj, ...)                                 \
240   do {                                                                         \
241     *ptr = static_cast<typename std::remove_reference<decltype(*ptr)>::type>(  \
242         BaseObject::FromJSObject(obj));                                        \
243     if (*ptr == nullptr) return __VA_ARGS__;                                   \
244   } while (0)
245 
246 // Implementation of a generic strong or weak pointer to a BaseObject.
247 // If strong, this will keep the target BaseObject alive regardless of other
248 // circumstances such as the GC or Environment cleanup.
249 // If weak, destruction behaviour is not affected, but the pointer will be
250 // reset to nullptr once the BaseObject is destroyed.
251 // The API matches std::shared_ptr closely. However, this class is not thread
252 // safe, that is, we can't have different BaseObjectPtrImpl instances in
253 // different threads referring to the same BaseObject instance.
254 template <typename T, bool kIsWeak>
255 class BaseObjectPtrImpl final {
256  public:
257   inline BaseObjectPtrImpl();
258   inline ~BaseObjectPtrImpl();
259   inline explicit BaseObjectPtrImpl(T* target);
260 
261   // Copy and move constructors. Note that the templated version is not a copy
262   // or move constructor in the C++ sense of the word, so an identical
263   // untemplated version is provided.
264   template <typename U, bool kW>
265   inline BaseObjectPtrImpl(const BaseObjectPtrImpl<U, kW>& other);
266   inline BaseObjectPtrImpl(const BaseObjectPtrImpl& other);
267   template <typename U, bool kW>
268   inline BaseObjectPtrImpl& operator=(const BaseObjectPtrImpl<U, kW>& other);
269   inline BaseObjectPtrImpl& operator=(const BaseObjectPtrImpl& other);
270   inline BaseObjectPtrImpl(BaseObjectPtrImpl&& other);
271   inline BaseObjectPtrImpl& operator=(BaseObjectPtrImpl&& other);
272 
273   inline void reset(T* ptr = nullptr);
274   inline T* get() const;
275   inline T& operator*() const;
276   inline T* operator->() const;
277   inline operator bool() const;
278 
279   template <typename U, bool kW>
280   inline bool operator ==(const BaseObjectPtrImpl<U, kW>& other) const;
281   template <typename U, bool kW>
282   inline bool operator !=(const BaseObjectPtrImpl<U, kW>& other) const;
283 
284  private:
285   union {
286     BaseObject* target;                     // Used for strong pointers.
287     BaseObject::PointerData* pointer_data;  // Used for weak pointers.
288   } data_;
289 
290   inline BaseObject* get_base_object() const;
291   inline BaseObject::PointerData* pointer_data() const;
292 };
293 
294 template <typename T>
295 using BaseObjectPtr = BaseObjectPtrImpl<T, false>;
296 template <typename T>
297 using BaseObjectWeakPtr = BaseObjectPtrImpl<T, true>;
298 
299 // Create a BaseObject instance and return a pointer to it.
300 // This variant leaves the object as a GC root by default.
301 template <typename T, typename... Args>
302 inline BaseObjectPtr<T> MakeBaseObject(Args&&... args);
303 // Create a BaseObject instance and return a pointer to it.
304 // This variant detaches the object by default, meaning that the caller fully
305 // owns it, and once the last BaseObjectPtr to it is destroyed, the object
306 // itself is also destroyed.
307 template <typename T, typename... Args>
308 inline BaseObjectPtr<T> MakeDetachedBaseObject(Args&&... args);
309 
310 }  // namespace node
311 
312 #endif  // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
313 
314 #endif  // SRC_BASE_OBJECT_H_
315