GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/node_messaging.h Lines: 14 22 63.6 %
Date: 2021-02-11 04:11:15 Branches: 2 4 50.0 %

Line Branch Exec Source
1
#ifndef SRC_NODE_MESSAGING_H_
2
#define SRC_NODE_MESSAGING_H_
3
4
#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
5
6
#include "env.h"
7
#include "node_mutex.h"
8
#include "v8.h"
9
#include <deque>
10
#include <string>
11
#include <unordered_map>
12
#include <set>
13
14
namespace node {
15
namespace worker {
16
17
class MessagePortData;
18
class MessagePort;
19
20
typedef MaybeStackBuffer<v8::Local<v8::Value>, 8> TransferList;
21
22
// Used to represent the in-flight structure of an object that is being
23
// transferred or cloned using postMessage().
24
67031
class TransferData : public MemoryRetainer {
25
 public:
26
  // Deserialize this object on the receiving end after a .postMessage() call.
27
  // - `context` may not be the same as `env->context()`. This method should
28
  //    not produce JS objects coming from Contexts other than `context`.
29
  // - `self` is a unique_ptr for the object that this is being called on.
30
  // - The return value is treated like a `Maybe`, i.e. if `nullptr` is
31
  //   returned, any further deserialization of the message is stopped and
32
  //   control is returned to the event loop or JS as soon as possible.
33
  virtual BaseObjectPtr<BaseObject> Deserialize(
34
      Environment* env,
35
      v8::Local<v8::Context> context,
36
      std::unique_ptr<TransferData> self) = 0;
37
  // FinalizeTransferWrite() is the counterpart to
38
  // BaseObject::FinalizeTransferRead(). It is called right after the transfer
39
  // data was created, and defaults to doing nothing. After this function,
40
  // this object should not hold any more Isolate-specific data.
41
  virtual v8::Maybe<bool> FinalizeTransferWrite(
42
      v8::Local<v8::Context> context, v8::ValueSerializer* serializer);
43
};
44
45
// Represents a single communication message.
46
class Message : public MemoryRetainer {
47
 public:
48
  // Create a Message with a specific underlying payload, in the format of the
49
  // V8 ValueSerializer API. If `payload` is empty, this message indicates
50
  // that the receiving message port should close itself.
51
  explicit Message(MallocedBuffer<char>&& payload = MallocedBuffer<char>());
52
78619
  ~Message() = default;
53
54
  Message(Message&& other) = default;
55
  Message& operator=(Message&& other) = default;
56
  Message& operator=(const Message&) = delete;
57
  Message(const Message&) = delete;
58
59
  // Whether this is a message indicating that the port is to be closed.
60
  // This is the last message to be received by a MessagePort.
61
  bool IsCloseMessage() const;
62
63
  // Deserialize the contained JS value. May only be called once, and only
64
  // after Serialize() has been called (e.g. by another thread).
65
  v8::MaybeLocal<v8::Value> Deserialize(Environment* env,
66
                                        v8::Local<v8::Context> context);
67
68
  // Serialize a JS value, and optionally transfer objects, into this message.
69
  // The Message object retains ownership of all transferred objects until
70
  // deserialization.
71
  // The source_port parameter, if provided, will make Serialize() throw a
72
  // "DataCloneError" DOMException if source_port is found in transfer_list.
73
  v8::Maybe<bool> Serialize(Environment* env,
74
                            v8::Local<v8::Context> context,
75
                            v8::Local<v8::Value> input,
76
                            const TransferList& transfer_list,
77
                            v8::Local<v8::Object> source_port =
78
                                v8::Local<v8::Object>());
79
80
  // Internal method of Message that is called when a new SharedArrayBuffer
81
  // object is encountered in the incoming value's structure.
82
  void AddSharedArrayBuffer(std::shared_ptr<v8::BackingStore> backing_store);
83
  // Internal method of Message that is called once serialization finishes
84
  // and that transfers ownership of `data` to this message.
85
  void AddTransferable(std::unique_ptr<TransferData>&& data);
86
  // Internal method of Message that is called when a new WebAssembly.Module
87
  // object is encountered in the incoming value's structure.
88
  uint32_t AddWASMModule(v8::CompiledWasmModule&& mod);
89
90
  // The host objects that will be transferred, as recorded by Serialize()
91
  // (e.g. MessagePorts).
92
  // Used for warning user about posting the target MessagePort to itself,
93
  // which will as a side effect destroy the communication channel.
94
44978
  const std::vector<std::unique_ptr<TransferData>>& transferables() const {
95
44978
    return transferables_;
96
  }
97
11
  bool has_transferables() const {
98

11
    return !transferables_.empty() || !array_buffers_.empty();
99
  }
100
101
  void MemoryInfo(MemoryTracker* tracker) const override;
102
103
  SET_MEMORY_INFO_NAME(Message)
104
  SET_SELF_SIZE(Message)
105
106
 private:
107
  MallocedBuffer<char> main_message_buf_;
108
  std::vector<std::shared_ptr<v8::BackingStore>> array_buffers_;
109
  std::vector<std::shared_ptr<v8::BackingStore>> shared_array_buffers_;
110
  std::vector<std::unique_ptr<TransferData>> transferables_;
111
  std::vector<v8::CompiledWasmModule> wasm_modules_;
112
113
  friend class MessagePort;
114
};
115
116
class SiblingGroup final : public std::enable_shared_from_this<SiblingGroup> {
117
 public:
118
  // Named SiblingGroup, Used for one-to-many BroadcastChannels.
119
  static std::shared_ptr<SiblingGroup> Get(const std::string& name);
120
121
  // Anonymous SiblingGroup, Used for one-to-one MessagePort pairs.
122
11349
  SiblingGroup() = default;
123
  explicit SiblingGroup(const std::string& name);
124
  ~SiblingGroup();
125
126
  // Dispatches the Message to the collection of associated
127
  // ports. If there is more than one destination port and
128
  // the Message contains transferables, Dispatch will fail.
129
  // Returns Just(true) if successful and the message was
130
  // dispatched to at least one destination. Returns Just(false)
131
  // if there were no destinations. Returns Nothing<bool>()
132
  // if there was an error. If error is not nullptr, it will
133
  // be set to an error message or warning message as appropriate.
134
  v8::Maybe<bool> Dispatch(
135
      MessagePortData* source,
136
      std::shared_ptr<Message> message,
137
      std::string* error = nullptr);
138
139
  void Entangle(MessagePortData* data);
140
  void Entangle(std::initializer_list<MessagePortData*> data);
141
  void Disentangle(MessagePortData* data);
142
143
  const std::string& name() const { return name_; }
144
145
112700
  size_t size() const { return ports_.size(); }
146
147
 private:
148
  std::string name_;
149
  std::set<MessagePortData*> ports_;
150
  Mutex group_mutex_;
151
152
  static void CheckSiblingGroup(const std::string& name);
153
154
  using Map =
155
      std::unordered_map<std::string, std::weak_ptr<SiblingGroup>>;
156
157
  static Mutex groups_mutex_;
158
  static Map groups_;
159
};
160
161
// This contains all data for a `MessagePort` instance that is not tied to
162
// a specific Environment/Isolate/event loop, for easier transfer between those.
163
class MessagePortData : public TransferData {
164
 public:
165
  explicit MessagePortData(MessagePort* owner);
166
  ~MessagePortData() override;
167
168
  MessagePortData(MessagePortData&& other) = delete;
169
  MessagePortData& operator=(MessagePortData&& other) = delete;
170
  MessagePortData(const MessagePortData& other) = delete;
171
  MessagePortData& operator=(const MessagePortData& other) = delete;
172
173
  // Add a message to the incoming queue and notify the receiver.
174
  // This may be called from any thread.
175
  void AddToIncomingQueue(std::shared_ptr<Message> message);
176
  v8::Maybe<bool> Dispatch(
177
      std::shared_ptr<Message> message,
178
      std::string* error = nullptr);
179
180
  // Turns `a` and `b` into siblings, i.e. connects the sending side of one
181
  // to the receiving side of the other. This is not thread-safe.
182
  static void Entangle(MessagePortData* a, MessagePortData* b);
183
184
  // Removes any possible sibling. This is thread-safe (it acquires both
185
  // `sibling_mutex_` and `mutex_`), and has to be because it is called once
186
  // the corresponding JS handle handle wants to close
187
  // which can happen on either side of a worker.
188
  void Disentangle();
189
190
  void MemoryInfo(MemoryTracker* tracker) const override;
191
  BaseObjectPtr<BaseObject> Deserialize(
192
      Environment* env,
193
      v8::Local<v8::Context> context,
194
      std::unique_ptr<TransferData> self) override;
195
196
2
  SET_MEMORY_INFO_NAME(MessagePortData)
197
2
  SET_SELF_SIZE(MessagePortData)
198
199
 private:
200
  // This mutex protects all fields below it, with the exception of
201
  // sibling_.
202
  mutable Mutex mutex_;
203
  std::deque<std::shared_ptr<Message>> incoming_messages_;
204
  MessagePort* owner_ = nullptr;
205
  std::shared_ptr<SiblingGroup> group_;
206
  friend class MessagePort;
207
  friend class SiblingGroup;
208
};
209
210
// A message port that receives messages from other threads, including
211
// the uv_async_t handle that is used to notify the current event loop of
212
// new incoming messages.
213
class MessagePort : public HandleWrap {
214
 private:
215
  // Create a new MessagePort. The `context` argument specifies the Context
216
  // instance that is used for creating the values emitted from this port.
217
  // This is called by MessagePort::New(), which is the public API used for
218
  // creating MessagePort instances.
219
  MessagePort(Environment* env,
220
              v8::Local<v8::Context> context,
221
              v8::Local<v8::Object> wrap);
222
223
 public:
224
  ~MessagePort() override;
225
226
  // Create a new message port instance, optionally over an existing
227
  // `MessagePortData` object.
228
  static MessagePort* New(Environment* env,
229
                          v8::Local<v8::Context> context,
230
                          std::unique_ptr<MessagePortData> data = {},
231
                          std::shared_ptr<SiblingGroup> sibling_group = {});
232
233
  // Send a message, i.e. deliver it into the sibling's incoming queue.
234
  // If this port is closed, or if there is no sibling, this message is
235
  // serialized with transfers, then silently discarded.
236
  v8::Maybe<bool> PostMessage(Environment* env,
237
                              v8::Local<v8::Value> message,
238
                              const TransferList& transfer);
239
240
  // Start processing messages on this port as a receiving end.
241
  void Start();
242
  // Stop processing messages on this port as a receiving end.
243
  void Stop();
244
245
  /* constructor */
246
  static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
247
  /* prototype methods */
248
  static void PostMessage(const v8::FunctionCallbackInfo<v8::Value>& args);
249
  static void Start(const v8::FunctionCallbackInfo<v8::Value>& args);
250
  static void Stop(const v8::FunctionCallbackInfo<v8::Value>& args);
251
  static void CheckType(const v8::FunctionCallbackInfo<v8::Value>& args);
252
  static void Drain(const v8::FunctionCallbackInfo<v8::Value>& args);
253
  static void ReceiveMessage(const v8::FunctionCallbackInfo<v8::Value>& args);
254
255
  /* static */
256
  static void MoveToContext(const v8::FunctionCallbackInfo<v8::Value>& args);
257
258
  // Turns `a` and `b` into siblings, i.e. connects the sending side of one
259
  // to the receiving side of the other. This is not thread-safe.
260
  static void Entangle(MessagePort* a, MessagePort* b);
261
  static void Entangle(MessagePort* a, MessagePortData* b);
262
263
  // Detach this port's data for transferring. After this, the MessagePortData
264
  // is no longer associated with this handle, although it can still receive
265
  // messages.
266
  std::unique_ptr<MessagePortData> Detach();
267
268
  void Close(
269
      v8::Local<v8::Value> close_callback = v8::Local<v8::Value>()) override;
270
271
  // Returns true if either data_ has been freed, or if the handle is being
272
  // closed. Equivalent to the [[Detached]] internal slot in the HTML Standard.
273
  //
274
  // If checking if a JavaScript MessagePort object is detached, this method
275
  // alone is often not enough, since the backing C++ MessagePort object may
276
  // have been deleted already. For all intents and purposes, an object with a
277
  // NULL pointer to the C++ MessagePort object is also detached.
278
  inline bool IsDetached() const;
279
280
  TransferMode GetTransferMode() const override;
281
  std::unique_ptr<TransferData> TransferForMessaging() override;
282
283
  void MemoryInfo(MemoryTracker* tracker) const override;
284
2
  SET_MEMORY_INFO_NAME(MessagePort)
285
2
  SET_SELF_SIZE(MessagePort)
286
287
 private:
288
  void OnClose() override;
289
  void OnMessage();
290
  void TriggerAsync();
291
  v8::MaybeLocal<v8::Value> ReceiveMessage(v8::Local<v8::Context> context,
292
                                           bool only_if_receiving);
293
294
  std::unique_ptr<MessagePortData> data_ = nullptr;
295
  bool receiving_messages_ = false;
296
  uv_async_t async_;
297
  v8::Global<v8::Function> emit_message_fn_;
298
299
  friend class MessagePortData;
300
};
301
302
// Provide a base class from which JS classes that should be transferable or
303
// cloneable by postMesssage() can inherit.
304
// See e.g. FileHandle in internal/fs/promises.js for an example.
305
6648
class JSTransferable : public BaseObject {
306
 public:
307
  JSTransferable(Environment* env, v8::Local<v8::Object> obj);
308
  static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
309
310
  TransferMode GetTransferMode() const override;
311
  std::unique_ptr<TransferData> TransferForMessaging() override;
312
  std::unique_ptr<TransferData> CloneForMessaging() const override;
313
  v8::Maybe<std::vector<BaseObjectPtr<BaseObject>>>
314
      NestedTransferables() const override;
315
  v8::Maybe<bool> FinalizeTransferRead(
316
      v8::Local<v8::Context> context,
317
      v8::ValueDeserializer* deserializer) override;
318
319
  SET_NO_MEMORY_INFO()
320
  SET_MEMORY_INFO_NAME(JSTransferable)
321
  SET_SELF_SIZE(JSTransferable)
322
323
 private:
324
  std::unique_ptr<TransferData> TransferOrClone(TransferMode mode) const;
325
326
30
  class Data : public TransferData {
327
   public:
328
    Data(std::string&& deserialize_info, v8::Global<v8::Value>&& data);
329
330
    BaseObjectPtr<BaseObject> Deserialize(
331
        Environment* env,
332
        v8::Local<v8::Context> context,
333
        std::unique_ptr<TransferData> self) override;
334
    v8::Maybe<bool> FinalizeTransferWrite(
335
        v8::Local<v8::Context> context,
336
        v8::ValueSerializer* serializer) override;
337
338
    SET_NO_MEMORY_INFO()
339
    SET_MEMORY_INFO_NAME(JSTransferableTransferData)
340
    SET_SELF_SIZE(Data)
341
342
   private:
343
    std::string deserialize_info_;
344
    v8::Global<v8::Value> data_;
345
  };
346
};
347
348
v8::Local<v8::FunctionTemplate> GetMessagePortConstructorTemplate(
349
    Environment* env);
350
351
}  // namespace worker
352
}  // namespace node
353
354
#endif  // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
355
356
357
#endif  // SRC_NODE_MESSAGING_H_