Where Online Learning is simpler!
The C and C++ Include Header Files
cat -n /usr/include/nodejs/src/base_object.h
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 "util.h" 31 #include "v8.h" 32 33 namespace node { 34 35 class Environment; 36 class IsolateData; 37 class Realm; 38 template <typename T, bool kIsWeak> 39 class BaseObjectPtrImpl; 40 41 namespace worker { 42 class TransferData; 43 } 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(IsolateData* isolate_data, 77 v8::Local<v8::Object> object, 78 void* slot); 79 static inline bool IsBaseObject(IsolateData* isolate_data, 80 v8::Local<v8::Object> object); 81 static inline void TagBaseObject(IsolateData* isolate_data, 82 v8::Local<v8::Object> object); 83 static void LazilyInitializedJSTemplateConstructor( 84 const v8::FunctionCallbackInfo<v8::Value>& args); 85 static inline BaseObject* FromJSObject(v8::Local<v8::Value> object); 86 template <typename T> 87 static inline T* FromJSObject(v8::Local<v8::Value> object); 88 89 // Make the `v8::Global` a weak reference and, `delete` this object once 90 // the JS object has been garbage collected and there are no (strong) 91 // BaseObjectPtr references to it. 92 void MakeWeak(); 93 94 // Undo `MakeWeak()`, i.e. turn this into a strong reference that is a GC 95 // root and will not be touched by the garbage collector. 96 inline void ClearWeak(); 97 98 // Reports whether this BaseObject is using a weak reference or detached, 99 // i.e. whether is can be deleted by GC once no strong BaseObjectPtrs refer 100 // to it anymore. 101 inline bool IsWeakOrDetached() const; 102 103 inline v8::EmbedderGraph::Node::Detachedness GetDetachedness() const override; 104 105 // Utility to create a FunctionTemplate with one internal field (used for 106 // the `BaseObject*` pointer) and a constructor that initializes that field 107 // to `nullptr`. 108 static v8::Local<v8::FunctionTemplate> MakeLazilyInitializedJSTemplate( 109 IsolateData* isolate); 110 static v8::Local<v8::FunctionTemplate> MakeLazilyInitializedJSTemplate( 111 Environment* env); 112 113 // Setter/Getter pair for internal fields that can be passed to SetAccessor. 114 template <int Field> 115 static void InternalFieldGet(const v8::FunctionCallbackInfo<v8::Value>& args); 116 template <int Field, bool (v8::Value::*typecheck)() const> 117 static void InternalFieldSet(const v8::FunctionCallbackInfo<v8::Value>& args); 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 // Interface for transferring BaseObject instances using the .postMessage() 129 // method of MessagePorts (and, by extension, Workers). 130 // GetTransferMode() returns a transfer mode that indicates how to deal with 131 // the current object: 132 // - kDisallowCloneAndTransfer: 133 // No transfer or clone is possible, either because this type of 134 // BaseObject does not know how to be transferred, or because it is not 135 // in a state in which it is possible to do so (e.g. because it has 136 // already been transferred). 137 // - kTransferable: 138 // This object can be transferred in a destructive fashion, i.e. will be 139 // rendered unusable on the sending side of the channel in the process 140 // of being transferred. (In C++ this would be referred to as movable but 141 // not copyable.) Objects of this type need to be listed in the 142 // `transferList` argument of the relevant postMessage() call in order to 143 // make sure that they are not accidentally destroyed on the sending side. 144 // TransferForMessaging() will be called to get a representation of the 145 // object that is used for subsequent deserialization. 146 // The NestedTransferables() method can be used to transfer other objects 147 // along with this one, if a situation requires it. 148 // - kCloneable: 149 // This object can be cloned without being modified. 150 // CloneForMessaging() will be called to get a representation of the 151 // object that is used for subsequent deserialization, unless the 152 // object is listed in transferList and is kTransferable, in which case 153 // TransferForMessaging() is attempted first. 154 // - kTransferableAndCloneable: 155 // This object can be transferred or cloned. 156 // After a successful clone, FinalizeTransferRead() is called on the receiving 157 // end, and can read deserialize JS data possibly serialized by a previous 158 // FinalizeTransferWrite() call. 159 // By default, a BaseObject is kDisallowCloneAndTransfer and a JS Object is 160 // kCloneable unless otherwise specified. 161 enum TransferMode : uint32_t { 162 kDisallowCloneAndTransfer = 0, 163 kTransferable = 1 << 0, 164 kCloneable = 1 << 1, 165 kTransferableAndCloneable = kTransferable | 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<void> 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 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 void DeleteMe(); 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 ListNode<BaseObject> base_object_list_node_; 232 233 friend class BaseObjectList; 234 }; 235 236 class BaseObjectList 237 : public ListHead<BaseObject, &BaseObject::base_object_list_node_>, 238 public MemoryRetainer { 239 public: 240 void Cleanup(); 241 242 SET_MEMORY_INFO_NAME(BaseObjectList) 243 SET_SELF_SIZE(BaseObjectList) 244 void MemoryInfo(node::MemoryTracker* tracker) const override; 245 }; 246 247 // Global alias for FromJSObject() to avoid churn. 248 template <typename T> 249 inline T* Unwrap(v8::Local<v8::Value> obj) { 250 return BaseObject::FromJSObject<T>(obj); 251 } 252 253 #define ASSIGN_OR_RETURN_UNWRAP(ptr, obj, ...) \ 254 do { \ 255 *ptr = static_cast<typename std::remove_reference<decltype(*ptr)>::type>( \ 256 BaseObject::FromJSObject(obj)); \ 257 if (*ptr == nullptr) return __VA_ARGS__; \ 258 } while (0) 259 260 // Implementation of a generic strong or weak pointer to a BaseObject. 261 // If strong, this will keep the target BaseObject alive regardless of other 262 // circumstances such as the GC or Environment cleanup. 263 // If weak, destruction behaviour is not affected, but the pointer will be 264 // reset to nullptr once the BaseObject is destroyed. 265 // The API matches std::shared_ptr closely. However, this class is not thread 266 // safe, that is, we can't have different BaseObjectPtrImpl instances in 267 // different threads referring to the same BaseObject instance. 268 template <typename T, bool kIsWeak> 269 class BaseObjectPtrImpl final { 270 public: 271 inline BaseObjectPtrImpl(); 272 inline ~BaseObjectPtrImpl(); 273 inline explicit BaseObjectPtrImpl(T* target); 274 275 // Copy and move constructors. Note that the templated version is not a copy 276 // or move constructor in the C++ sense of the word, so an identical 277 // untemplated version is provided. 278 template <typename U, bool kW> 279 inline BaseObjectPtrImpl(const BaseObjectPtrImpl<U, kW>& other); 280 inline BaseObjectPtrImpl(const BaseObjectPtrImpl& other); 281 template <typename U, bool kW> 282 inline BaseObjectPtrImpl& operator=(const BaseObjectPtrImpl<U, kW>& other); 283 inline BaseObjectPtrImpl& operator=(const BaseObjectPtrImpl& other); 284 inline BaseObjectPtrImpl(BaseObjectPtrImpl&& other); 285 inline BaseObjectPtrImpl& operator=(BaseObjectPtrImpl&& other); 286 287 inline BaseObjectPtrImpl(std::nullptr_t); 288 inline BaseObjectPtrImpl& operator=(std::nullptr_t); 289 290 inline void reset(T* ptr = nullptr); 291 inline T* get() const; 292 inline T& operator*() const; 293 inline T* operator->() const; 294 inline operator bool() const; 295 296 template <typename U, bool kW> 297 inline bool operator ==(const BaseObjectPtrImpl<U, kW>& other) const; 298 template <typename U, bool kW> 299 inline bool operator !=(const BaseObjectPtrImpl<U, kW>& other) const; 300 301 private: 302 union { 303 BaseObject* target; // Used for strong pointers. 304 BaseObject::PointerData* pointer_data; // Used for weak pointers. 305 } data_; 306 307 inline BaseObject* get_base_object() const; 308 inline BaseObject::PointerData* pointer_data() const; 309 }; 310 311 template <typename T, bool kIsWeak> 312 inline static bool operator==(const BaseObjectPtrImpl<T, kIsWeak>, 313 const std::nullptr_t); 314 template <typename T, bool kIsWeak> 315 inline static bool operator==(const std::nullptr_t, 316 const BaseObjectPtrImpl<T, kIsWeak>); 317 318 template <typename T> 319 using BaseObjectPtr = BaseObjectPtrImpl<T, false>; 320 template <typename T> 321 using BaseObjectWeakPtr = BaseObjectPtrImpl<T, true>; 322 323 // Create a BaseObject instance and return a pointer to it. 324 // This variant leaves the object as a GC root by default. 325 template <typename T, typename... Args> 326 inline BaseObjectPtr<T> MakeBaseObject(Args&&... args); 327 // Create a BaseObject instance and return a pointer to it. 328 // This variant makes the object a weak GC root by default. 329 template <typename T, typename... Args> 330 inline BaseObjectWeakPtr<T> MakeWeakBaseObject(Args&&... args); 331 // Create a BaseObject instance and return a pointer to it. 332 // This variant detaches the object by default, meaning that the caller fully 333 // owns it, and once the last BaseObjectPtr to it is destroyed, the object 334 // itself is also destroyed. 335 template <typename T, typename... Args> 336 inline BaseObjectPtr<T> MakeDetachedBaseObject(Args&&... args); 337 338 } // namespace node 339 340 #endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS 341 342 #endif // SRC_BASE_OBJECT_H_