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

14
X(SetTTL, uv_udp_set_ttl)
277

21
X(SetBroadcast, uv_udp_set_broadcast)
278

14
X(SetMulticastTTL, uv_udp_set_multicast_ttl)
279

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


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

14903
  if (nread == 0 && addr == nullptr) {
473
5118
    if (buf->base != nullptr)
474
5118
      free(buf->base);
475
10236
    return;
476
  }
477
478
9785
  UDPWrap* wrap = static_cast<UDPWrap*>(handle->data);
479
9785
  Environment* env = wrap->env();
480
481
9785
  HandleScope handle_scope(env->isolate());
482
19570
  Context::Scope context_scope(env->context());
483
484
9785
  Local<Object> wrap_obj = wrap->object();
485
  Local<Value> argv[] = {
486
    Integer::New(env->isolate(), nread),
487
    wrap_obj,
488
    Undefined(env->isolate()),
489
    Undefined(env->isolate())
490
48925
  };
491
492
9785
  if (nread < 0) {
493
    if (buf->base != nullptr)
494
      free(buf->base);
495
    wrap->MakeCallback(env->onmessage_string(), arraysize(argv), argv);
496
    return;
497
  }
498
499
9785
  char* base = node::UncheckedRealloc(buf->base, nread);
500
19570
  argv[2] = Buffer::New(env, base, nread).ToLocalChecked();
501
19570
  argv[3] = AddressToJS(env, addr);
502
19570
  wrap->MakeCallback(env->onmessage_string(), arraysize(argv), argv);
503
}
504
505
506
19
Local<Object> UDPWrap::Instantiate(Environment* env,
507
                                   AsyncWrap* parent,
508
                                   UDPWrap::SocketType type) {
509
19
  EscapableHandleScope scope(env->isolate());
510
38
  AsyncHooks::InitScope init_scope(env, parent->get_async_id());
511
  // If this assert fires then Initialize hasn't been called yet.
512
38
  CHECK_EQ(env->udp_constructor_function().IsEmpty(), false);
513
  Local<Object> instance = env->udp_constructor_function()
514
57
      ->NewInstance(env->context()).ToLocalChecked();
515
19
  return scope.Escape(instance);
516
}
517
518
519
19
uv_udp_t* UDPWrap::UVHandle() {
520
19
  return &handle_;
521
}
522
523
524
}  // namespace node
525
526
3391
NODE_BUILTIN_MODULE_CONTEXT_AWARE(udp_wrap, node::UDPWrap::Initialize)