GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: base_object.h Lines: 2 3 66.7 %
Date: 2022-08-17 04:19:55 Branches: 0 0 - %

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