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-04-29 04:13:25 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
67284
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
82962
  ~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(
66
      Environment* env,
67
      v8::Local<v8::Context> context,
68
      v8::Local<v8::Value>* port_list = nullptr);
69
70
  // Serialize a JS value, and optionally transfer objects, into this message.
71
  // The Message object retains ownership of all transferred objects until
72
  // deserialization.
73
  // The source_port parameter, if provided, will make Serialize() throw a
74
  // "DataCloneError" DOMException if source_port is found in transfer_list.
75
  v8::Maybe<bool> Serialize(Environment* env,
76
                            v8::Local<v8::Context> context,
77
                            v8::Local<v8::Value> input,
78
                            const TransferList& transfer_list,
79
                            v8::Local<v8::Object> source_port =
80
                                v8::Local<v8::Object>());
81
82
  // Internal method of Message that is called when a new SharedArrayBuffer
83
  // object is encountered in the incoming value's structure.
84
  void AddSharedArrayBuffer(std::shared_ptr<v8::BackingStore> backing_store);
85
  // Internal method of Message that is called once serialization finishes
86
  // and that transfers ownership of `data` to this message.
87
  void AddTransferable(std::unique_ptr<TransferData>&& data);
88
  // Internal method of Message that is called when a new WebAssembly.Module
89
  // object is encountered in the incoming value's structure.
90
  uint32_t AddWASMModule(v8::CompiledWasmModule&& mod);
91
92
  // The host objects that will be transferred, as recorded by Serialize()
93
  // (e.g. MessagePorts).
94
  // Used for warning user about posting the target MessagePort to itself,
95
  // which will as a side effect destroy the communication channel.
96
48948
  const std::vector<std::unique_ptr<TransferData>>& transferables() const {
97
48948
    return transferables_;
98
  }
99
11
  bool has_transferables() const {
100

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