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