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