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