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