GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/base_object.h Lines: 3 4 75.0 %
Date: 2021-05-03 04:13:35 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
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 keeping 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
  virtual inline bool is_snapshotable() const { return false; }
162
163
 private:
164
  v8::Local<v8::Object> WrappedObject() const override;
165
  bool IsRootNode() const override;
166
  static void DeleteMe(void* data);
167
168
  // persistent_handle_ needs to be at a fixed offset from the start of the
169
  // class because it is used by src/node_postmortem_metadata.cc to calculate
170
  // offsets and generate debug symbols for BaseObject, which assumes that the
171
  // position of members in memory are predictable. For more information please
172
  // refer to `doc/guides/node-postmortem-support.md`
173
  friend int GenDebugSymbols();
174
  friend class CleanupHookCallback;
175
  template <typename T, bool kIsWeak>
176
  friend class BaseObjectPtrImpl;
177
178
  v8::Global<v8::Object> persistent_handle_;
179
180
  // Metadata that is associated with this BaseObject if there are BaseObjectPtr
181
  // or BaseObjectWeakPtr references to it.
182
  // This object is deleted when the BaseObject itself is destroyed, and there
183
  // are no weak references to it.
184
162202
  struct PointerData {
185
    // Number of BaseObjectPtr instances that refer to this object. If this
186
    // is non-zero, the BaseObject is always a GC root and will not be destroyed
187
    // during cleanup until the count drops to zero again.
188
    unsigned int strong_ptr_count = 0;
189
    // Number of BaseObjectWeakPtr instances that refer to this object.
190
    unsigned int weak_ptr_count = 0;
191
    // Indicates whether MakeWeak() has been called.
192
    bool wants_weak_jsobj = false;
193
    // Indicates whether Detach() has been called. If that is the case, this
194
    // object will be destryoed once the strong pointer count drops to zero.
195
    bool is_detached = false;
196
    // Reference to the original BaseObject. This is used by weak pointers.
197
    BaseObject* self = nullptr;
198
  };
199
200
  inline bool has_pointer_data() const;
201
  // This creates a PointerData struct if none was associated with this
202
  // BaseObject before.
203
  inline PointerData* pointer_data();
204
205
  // Functions that adjust the strong pointer count.
206
  inline void decrease_refcount();
207
  inline void increase_refcount();
208
209
  Environment* env_;
210
  PointerData* pointer_data_ = nullptr;
211
};
212
213
// Global alias for FromJSObject() to avoid churn.
214
template <typename T>
215
209851
inline T* Unwrap(v8::Local<v8::Value> obj) {
216
209851
  return BaseObject::FromJSObject<T>(obj);
217
}
218
219
#define ASSIGN_OR_RETURN_UNWRAP(ptr, obj, ...)                                 \
220
  do {                                                                         \
221
    *ptr = static_cast<typename std::remove_reference<decltype(*ptr)>::type>(  \
222
        BaseObject::FromJSObject(obj));                                        \
223
    if (*ptr == nullptr) return __VA_ARGS__;                                   \
224
  } while (0)
225
226
// Implementation of a generic strong or weak pointer to a BaseObject.
227
// If strong, this will keep the target BaseObject alive regardless of other
228
// circumstances such as the GC or Environment cleanup.
229
// If weak, destruction behaviour is not affected, but the pointer will be
230
// reset to nullptr once the BaseObject is destroyed.
231
// The API matches std::shared_ptr closely.
232
template <typename T, bool kIsWeak>
233
class BaseObjectPtrImpl final {
234
 public:
235
  inline BaseObjectPtrImpl();
236
  inline ~BaseObjectPtrImpl();
237
  inline explicit BaseObjectPtrImpl(T* target);
238
239
  // Copy and move constructors. Note that the templated version is not a copy
240
  // or move constructor in the C++ sense of the word, so an identical
241
  // untemplated version is provided.
242
  template <typename U, bool kW>
243
  inline BaseObjectPtrImpl(const BaseObjectPtrImpl<U, kW>& other);
244
  inline BaseObjectPtrImpl(const BaseObjectPtrImpl& other);
245
  template <typename U, bool kW>
246
  inline BaseObjectPtrImpl& operator=(const BaseObjectPtrImpl<U, kW>& other);
247
  inline BaseObjectPtrImpl& operator=(const BaseObjectPtrImpl& other);
248
  inline BaseObjectPtrImpl(BaseObjectPtrImpl&& other);
249
  inline BaseObjectPtrImpl& operator=(BaseObjectPtrImpl&& other);
250
251
  inline void reset(T* ptr = nullptr);
252
  inline T* get() const;
253
  inline T& operator*() const;
254
  inline T* operator->() const;
255
  inline operator bool() const;
256
257
  template <typename U, bool kW>
258
  inline bool operator ==(const BaseObjectPtrImpl<U, kW>& other) const;
259
  template <typename U, bool kW>
260
  inline bool operator !=(const BaseObjectPtrImpl<U, kW>& other) const;
261
262
 private:
263
  union {
264
    BaseObject* target;                     // Used for strong pointers.
265
    BaseObject::PointerData* pointer_data;  // Used for weak pointers.
266
  } data_;
267
268
  inline BaseObject* get_base_object() const;
269
  inline BaseObject::PointerData* pointer_data() const;
270
};
271
272
template <typename T>
273
using BaseObjectPtr = BaseObjectPtrImpl<T, false>;
274
template <typename T>
275
using BaseObjectWeakPtr = BaseObjectPtrImpl<T, true>;
276
277
// Create a BaseObject instance and return a pointer to it.
278
// This variant leaves the object as a GC root by default.
279
template <typename T, typename... Args>
280
inline BaseObjectPtr<T> MakeBaseObject(Args&&... args);
281
// Create a BaseObject instance and return a pointer to it.
282
// This variant detaches the object by default, meaning that the caller fully
283
// owns it, and once the last BaseObjectPtr to it is destroyed, the object
284
// itself is also destroyed.
285
template <typename T, typename... Args>
286
inline BaseObjectPtr<T> MakeDetachedBaseObject(Args&&... args);
287
288
}  // namespace node
289
290
#endif  // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
291
292
#endif  // SRC_BASE_OBJECT_H_