GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage/nodes/benchmark/out/../src/udp_wrap.cc Lines: 226 235 96.2 %
Date: 2017-11-19 Branches: 67 118 56.8 %

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
#include "udp_wrap.h"
23
#include "env-inl.h"
24
#include "node_buffer.h"
25
#include "handle_wrap.h"
26
#include "req_wrap-inl.h"
27
#include "util-inl.h"
28
29
#include <stdlib.h>
30
31
32
namespace node {
33
34
using v8::Array;
35
using v8::Context;
36
using v8::EscapableHandleScope;
37
using v8::FunctionCallbackInfo;
38
using v8::FunctionTemplate;
39
using v8::HandleScope;
40
using v8::Integer;
41
using v8::Local;
42
using v8::Object;
43
using v8::PropertyAttribute;
44
using v8::PropertyCallbackInfo;
45
using v8::String;
46
using v8::Uint32;
47
using v8::Undefined;
48
using v8::Value;
49
50
using AsyncHooks = Environment::AsyncHooks;
51
52
53
class SendWrap : public ReqWrap<uv_udp_send_t> {
54
 public:
55
  SendWrap(Environment* env, Local<Object> req_wrap_obj, bool have_callback);
56
  ~SendWrap();
57
  inline bool have_callback() const;
58
  size_t msg_size;
59
  size_t self_size() const override { return sizeof(*this); }
60
 private:
61
  const bool have_callback_;
62
};
63
64
65
533
SendWrap::SendWrap(Environment* env,
66
                   Local<Object> req_wrap_obj,
67
                   bool have_callback)
68
    : ReqWrap(env, req_wrap_obj, AsyncWrap::PROVIDER_UDPSENDWRAP),
69
533
      have_callback_(have_callback) {
70
533
  Wrap(req_wrap_obj, this);
71
533
}
72
73
74
1599
SendWrap::~SendWrap() {
75
533
  ClearWrap(object());
76
1066
}
77
78
79
533
inline bool SendWrap::have_callback() const {
80
533
  return have_callback_;
81
}
82
83
84
534
static void NewSendWrap(const FunctionCallbackInfo<Value>& args) {
85
534
  CHECK(args.IsConstructCall());
86
534
  ClearWrap(args.This());
87
534
}
88
89
90
173
UDPWrap::UDPWrap(Environment* env, Local<Object> object)
91
    : HandleWrap(env,
92
                 object,
93
                 reinterpret_cast<uv_handle_t*>(&handle_),
94
173
                 AsyncWrap::PROVIDER_UDPWRAP) {
95
173
  int r = uv_udp_init(env->event_loop(), &handle_);
96
173
  CHECK_EQ(r, 0);  // can't fail anyway
97
173
}
98
99
100
2898
void UDPWrap::Initialize(Local<Object> target,
101
                         Local<Value> unused,
102
                         Local<Context> context) {
103
2898
  Environment* env = Environment::GetCurrent(context);
104
105
2898
  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
106
5796
  t->InstanceTemplate()->SetInternalFieldCount(1);
107
  Local<String> udpString =
108
2898
      FIXED_ONE_BYTE_STRING(env->isolate(), "UDP");
109
2898
  t->SetClassName(udpString);
110
111
  enum PropertyAttribute attributes =
112
2898
      static_cast<PropertyAttribute>(v8::ReadOnly | v8::DontDelete);
113
2898
  t->PrototypeTemplate()->SetAccessor(env->fd_string(),
114
                                      UDPWrap::GetFD,
115
                                      nullptr,
116
                                      env->as_external(),
117
                                      v8::DEFAULT,
118
11592
                                      attributes);
119
120
2898
  env->SetProtoMethod(t, "bind", Bind);
121
2898
  env->SetProtoMethod(t, "send", Send);
122
2898
  env->SetProtoMethod(t, "bind6", Bind6);
123
2898
  env->SetProtoMethod(t, "send6", Send6);
124
2898
  env->SetProtoMethod(t, "close", Close);
125
2898
  env->SetProtoMethod(t, "recvStart", RecvStart);
126
2898
  env->SetProtoMethod(t, "recvStop", RecvStop);
127
  env->SetProtoMethod(t, "getsockname",
128
2898
                      GetSockOrPeerName<UDPWrap, uv_udp_getsockname>);
129
2898
  env->SetProtoMethod(t, "addMembership", AddMembership);
130
2898
  env->SetProtoMethod(t, "dropMembership", DropMembership);
131
2898
  env->SetProtoMethod(t, "setMulticastInterface", SetMulticastInterface);
132
2898
  env->SetProtoMethod(t, "setMulticastTTL", SetMulticastTTL);
133
2898
  env->SetProtoMethod(t, "setMulticastLoopback", SetMulticastLoopback);
134
2898
  env->SetProtoMethod(t, "setBroadcast", SetBroadcast);
135
2898
  env->SetProtoMethod(t, "setTTL", SetTTL);
136
2898
  env->SetProtoMethod(t, "bufferSize", BufferSize);
137
138
2898
  env->SetProtoMethod(t, "ref", HandleWrap::Ref);
139
2898
  env->SetProtoMethod(t, "unref", HandleWrap::Unref);
140
2898
  env->SetProtoMethod(t, "hasRef", HandleWrap::HasRef);
141
142
2898
  AsyncWrap::AddWrapMethods(env, t);
143
144
5796
  target->Set(udpString, t->GetFunction());
145
2898
  env->set_udp_constructor_function(t->GetFunction());
146
147
  // Create FunctionTemplate for SendWrap
148
  Local<FunctionTemplate> swt =
149
2898
      FunctionTemplate::New(env->isolate(), NewSendWrap);
150
5796
  swt->InstanceTemplate()->SetInternalFieldCount(1);
151
2898
  AsyncWrap::AddWrapMethods(env, swt);
152
  Local<String> sendWrapString =
153
2898
      FIXED_ONE_BYTE_STRING(env->isolate(), "SendWrap");
154
2898
  swt->SetClassName(sendWrapString);
155
5796
  target->Set(sendWrapString, swt->GetFunction());
156
2898
}
157
158
159
173
void UDPWrap::New(const FunctionCallbackInfo<Value>& args) {
160
173
  CHECK(args.IsConstructCall());
161
173
  Environment* env = Environment::GetCurrent(args);
162
173
  new UDPWrap(env, args.This());
163
173
}
164
165
166
5
void UDPWrap::GetFD(Local<String>, const PropertyCallbackInfo<Value>& args) {
167
5
  int fd = UV_EBADF;
168
#if !defined(_WIN32)
169
5
  UDPWrap* wrap = Unwrap<UDPWrap>(args.This());
170
5
  if (wrap != nullptr)
171
4
    uv_fileno(reinterpret_cast<uv_handle_t*>(&wrap->handle_), &fd);
172
#endif
173
15
  args.GetReturnValue().Set(fd);
174
5
}
175
176
177
98
void UDPWrap::DoBind(const FunctionCallbackInfo<Value>& args, int family) {
178
  UDPWrap* wrap;
179
196
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
180
                          args.Holder(),
181
                          args.GetReturnValue().Set(UV_EBADF));
182
183
  // bind(ip, port, flags)
184
98
  CHECK_EQ(args.Length(), 3);
185
186
98
  node::Utf8Value address(args.GetIsolate(), args[0]);
187
196
  const int port = args[1]->Uint32Value();
188
196
  const int flags = args[2]->Uint32Value();
189
  char addr[sizeof(sockaddr_in6)];
190
  int err;
191
192
98
  switch (family) {
193
  case AF_INET:
194
91
    err = uv_ip4_addr(*address, port, reinterpret_cast<sockaddr_in*>(&addr));
195
91
    break;
196
  case AF_INET6:
197
7
    err = uv_ip6_addr(*address, port, reinterpret_cast<sockaddr_in6*>(&addr));
198
7
    break;
199
  default:
200
    CHECK(0 && "unexpected address family");
201
    ABORT();
202
  }
203
204
98
  if (err == 0) {
205
    err = uv_udp_bind(&wrap->handle_,
206
                      reinterpret_cast<const sockaddr*>(&addr),
207
97
                      flags);
208
  }
209
210
196
  args.GetReturnValue().Set(err);
211
}
212
213
214
91
void UDPWrap::Bind(const FunctionCallbackInfo<Value>& args) {
215
91
  DoBind(args, AF_INET);
216
91
}
217
218
219
7
void UDPWrap::Bind6(const FunctionCallbackInfo<Value>& args) {
220
7
  DoBind(args, AF_INET6);
221
7
}
222
223
224
16
void UDPWrap::BufferSize(const FunctionCallbackInfo<Value>& args) {
225
16
  Environment* env = Environment::GetCurrent(args);
226
  UDPWrap* wrap;
227
22
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
228
                          args.Holder(),
229
                          args.GetReturnValue().Set(UV_EBADF));
230
231
32
  CHECK(args[0]->IsUint32());
232
32
  CHECK(args[1]->IsBoolean());
233
48
  bool is_recv = args[1].As<v8::Boolean>()->Value();
234
  const char* uv_func_name = is_recv ? "uv_recv_buffer_size" :
235
16
                                       "uv_send_buffer_size";
236
237
32
  if (!args[0]->IsInt32()) {
238
2
    env->CollectUVExceptionInfo(args[2], UV_EINVAL, uv_func_name);
239
4
    return args.GetReturnValue().SetUndefined();
240
  }
241
242
14
  uv_handle_t* handle = reinterpret_cast<uv_handle_t*>(&wrap->handle_);
243
42
  int size = static_cast<int>(args[0].As<Uint32>()->Value());
244
  int err;
245
246
14
  if (is_recv)
247
7
    err = uv_recv_buffer_size(handle, &size);
248
  else
249
7
    err = uv_send_buffer_size(handle, &size);
250
251
14
  if (err != 0) {
252
4
    env->CollectUVExceptionInfo(args[2], err, uv_func_name);
253
8
    return args.GetReturnValue().SetUndefined();
254
  }
255
256
30
  args.GetReturnValue().Set(size);
257
}
258
259
260
#define X(name, fn)                                                           \
261
  void UDPWrap::name(const FunctionCallbackInfo<Value>& args) {               \
262
    UDPWrap* wrap = Unwrap<UDPWrap>(args.Holder());                           \
263
    CHECK_EQ(args.Length(), 1);                                               \
264
    int flag = args[0]->Int32Value();                                         \
265
    int err = wrap == nullptr ? UV_EBADF : fn(&wrap->handle_, flag);          \
266
    args.GetReturnValue().Set(err);                                           \
267
  }
268
269

14
X(SetTTL, uv_udp_set_ttl)
270

21
X(SetBroadcast, uv_udp_set_broadcast)
271

14
X(SetMulticastTTL, uv_udp_set_multicast_ttl)
272

21
X(SetMulticastLoopback, uv_udp_set_multicast_loop)
273
274
#undef X
275
276
6
void UDPWrap::SetMulticastInterface(const FunctionCallbackInfo<Value>& args) {
277
  UDPWrap* wrap;
278
12
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
279
                          args.Holder(),
280
                          args.GetReturnValue().Set(UV_EBADF));
281
282
6
  CHECK_EQ(args.Length(), 1);
283
18
  CHECK(args[0]->IsString());
284
285
6
  Utf8Value iface(args.GetIsolate(), args[0]);
286
287
6
  const char* iface_cstr = *iface;
288
289
6
  int err = uv_udp_set_multicast_interface(&wrap->handle_, iface_cstr);
290
12
  args.GetReturnValue().Set(err);
291
}
292
293
2
void UDPWrap::SetMembership(const FunctionCallbackInfo<Value>& args,
294
                            uv_membership membership) {
295
  UDPWrap* wrap;
296
4
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
297
                          args.Holder(),
298
                          args.GetReturnValue().Set(UV_EBADF));
299
300
2
  CHECK_EQ(args.Length(), 2);
301
302
2
  node::Utf8Value address(args.GetIsolate(), args[0]);
303
4
  node::Utf8Value iface(args.GetIsolate(), args[1]);
304
305
2
  const char* iface_cstr = *iface;
306


8
  if (args[1]->IsUndefined() || args[1]->IsNull()) {
307
2
      iface_cstr = nullptr;
308
  }
309
310
  int err = uv_udp_set_membership(&wrap->handle_,
311
2
                                  *address,
312
                                  iface_cstr,
313
2
                                  membership);
314
6
  args.GetReturnValue().Set(err);
315
}
316
317
318
1
void UDPWrap::AddMembership(const FunctionCallbackInfo<Value>& args) {
319
1
  SetMembership(args, UV_JOIN_GROUP);
320
1
}
321
322
323
1
void UDPWrap::DropMembership(const FunctionCallbackInfo<Value>& args) {
324
1
  SetMembership(args, UV_LEAVE_GROUP);
325
1
}
326
327
328
533
void UDPWrap::DoSend(const FunctionCallbackInfo<Value>& args, int family) {
329
533
  Environment* env = Environment::GetCurrent(args);
330
331
  UDPWrap* wrap;
332
1066
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
333
                          args.Holder(),
334
                          args.GetReturnValue().Set(UV_EBADF));
335
336
  // send(req, list, list.length, port, address, hasCallback)
337
1066
  CHECK(args[0]->IsObject());
338
1066
  CHECK(args[1]->IsArray());
339
1066
  CHECK(args[2]->IsUint32());
340
1066
  CHECK(args[3]->IsUint32());
341
1599
  CHECK(args[4]->IsString());
342
1066
  CHECK(args[5]->IsBoolean());
343
344
1066
  Local<Object> req_wrap_obj = args[0].As<Object>();
345
1066
  Local<Array> chunks = args[1].As<Array>();
346
  // it is faster to fetch the length of the
347
  // array in js-land
348
1066
  size_t count = args[2]->Uint32Value();
349
1066
  const unsigned short port = args[3]->Uint32Value();
350
533
  node::Utf8Value address(env->isolate(), args[4]);
351
1066
  const bool have_callback = args[5]->IsTrue();
352
353
533
  env->set_init_trigger_async_id(wrap->get_async_id());
354
533
  SendWrap* req_wrap = new SendWrap(env, req_wrap_obj, have_callback);
355
533
  size_t msg_size = 0;
356
357
1066
  MaybeStackBuffer<uv_buf_t, 16> bufs(count);
358
359
  // construct uv_buf_t array
360
1071
  for (size_t i = 0; i < count; i++) {
361
1076
    Local<Value> chunk = chunks->Get(i);
362
363
538
    size_t length = Buffer::Length(chunk);
364
365
538
    bufs[i] = uv_buf_init(Buffer::Data(chunk), length);
366
538
    msg_size += length;
367
  }
368
369
533
  req_wrap->msg_size = msg_size;
370
371
  char addr[sizeof(sockaddr_in6)];
372
  int err;
373
374
533
  switch (family) {
375
  case AF_INET:
376
529
    err = uv_ip4_addr(*address, port, reinterpret_cast<sockaddr_in*>(&addr));
377
529
    break;
378
  case AF_INET6:
379
4
    err = uv_ip6_addr(*address, port, reinterpret_cast<sockaddr_in6*>(&addr));
380
4
    break;
381
  default:
382
    CHECK(0 && "unexpected address family");
383
    ABORT();
384
  }
385
386
533
  if (err == 0) {
387
    err = uv_udp_send(req_wrap->req(),
388
                      &wrap->handle_,
389
533
                      *bufs,
390
                      count,
391
                      reinterpret_cast<const sockaddr*>(&addr),
392
1066
                      OnSend);
393
  }
394
395
533
  req_wrap->Dispatched();
396
533
  if (err)
397
    delete req_wrap;
398
399
1599
  args.GetReturnValue().Set(err);
400
}
401
402
403
529
void UDPWrap::Send(const FunctionCallbackInfo<Value>& args) {
404
529
  DoSend(args, AF_INET);
405
529
}
406
407
408
4
void UDPWrap::Send6(const FunctionCallbackInfo<Value>& args) {
409
4
  DoSend(args, AF_INET6);
410
4
}
411
412
413
99
void UDPWrap::RecvStart(const FunctionCallbackInfo<Value>& args) {
414
  UDPWrap* wrap;
415
198
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
416
                          args.Holder(),
417
                          args.GetReturnValue().Set(UV_EBADF));
418
99
  int err = uv_udp_recv_start(&wrap->handle_, OnAlloc, OnRecv);
419
  // UV_EALREADY means that the socket is already bound but that's okay
420
99
  if (err == UV_EALREADY)
421
    err = 0;
422
198
  args.GetReturnValue().Set(err);
423
}
424
425
426
88
void UDPWrap::RecvStop(const FunctionCallbackInfo<Value>& args) {
427
  UDPWrap* wrap;
428
176
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
429
                          args.Holder(),
430
                          args.GetReturnValue().Set(UV_EBADF));
431
88
  int r = uv_udp_recv_stop(&wrap->handle_);
432
176
  args.GetReturnValue().Set(r);
433
}
434
435
436
533
void UDPWrap::OnSend(uv_udp_send_t* req, int status) {
437
533
  SendWrap* req_wrap = static_cast<SendWrap*>(req->data);
438
533
  if (req_wrap->have_callback()) {
439
72
    Environment* env = req_wrap->env();
440
72
    HandleScope handle_scope(env->isolate());
441
72
    Context::Scope context_scope(env->context());
442
    Local<Value> arg[] = {
443
      Integer::New(env->isolate(), status),
444
      Integer::New(env->isolate(), req_wrap->msg_size),
445
216
    };
446
144
    req_wrap->MakeCallback(env->oncomplete_string(), 2, arg);
447
  }
448
533
  delete req_wrap;
449
533
}
450
451
452
902
void UDPWrap::OnAlloc(uv_handle_t* handle,
453
                      size_t suggested_size,
454
                      uv_buf_t* buf) {
455
902
  buf->base = node::Malloc(suggested_size);
456
902
  buf->len = suggested_size;
457
902
}
458
459
460
902
void UDPWrap::OnRecv(uv_udp_t* handle,
461
                     ssize_t nread,
462
                     const uv_buf_t* buf,
463
                     const struct sockaddr* addr,
464
                     unsigned int flags) {
465

902
  if (nread == 0 && addr == nullptr) {
466
383
    if (buf->base != nullptr)
467
383
      free(buf->base);
468
766
    return;
469
  }
470
471
519
  UDPWrap* wrap = static_cast<UDPWrap*>(handle->data);
472
519
  Environment* env = wrap->env();
473
474
519
  HandleScope handle_scope(env->isolate());
475
1038
  Context::Scope context_scope(env->context());
476
477
519
  Local<Object> wrap_obj = wrap->object();
478
  Local<Value> argv[] = {
479
    Integer::New(env->isolate(), nread),
480
    wrap_obj,
481
    Undefined(env->isolate()),
482
    Undefined(env->isolate())
483
2595
  };
484
485
519
  if (nread < 0) {
486
    if (buf->base != nullptr)
487
      free(buf->base);
488
    wrap->MakeCallback(env->onmessage_string(), arraysize(argv), argv);
489
    return;
490
  }
491
492
519
  char* base = node::UncheckedRealloc(buf->base, nread);
493
1038
  argv[2] = Buffer::New(env, base, nread).ToLocalChecked();
494
1038
  argv[3] = AddressToJS(env, addr);
495
1038
  wrap->MakeCallback(env->onmessage_string(), arraysize(argv), argv);
496
}
497
498
499
21
Local<Object> UDPWrap::Instantiate(Environment* env, AsyncWrap* parent) {
500
21
  EscapableHandleScope scope(env->isolate());
501
42
  AsyncHooks::InitScope init_scope(env, parent->get_async_id());
502
  // If this assert fires then Initialize hasn't been called yet.
503
42
  CHECK_EQ(env->udp_constructor_function().IsEmpty(), false);
504
  Local<Object> instance = env->udp_constructor_function()
505
63
      ->NewInstance(env->context()).ToLocalChecked();
506
21
  return scope.Escape(instance);
507
}
508
509
510
21
uv_udp_t* UDPWrap::UVHandle() {
511
21
  return &handle_;
512
}
513
514
515
}  // namespace node
516
517
3332
NODE_BUILTIN_MODULE_CONTEXT_AWARE(udp_wrap, node::UDPWrap::Initialize)