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


24
  if (args[1]->IsUndefined() || args[1]->IsNull()) {
307
6
      iface_cstr = nullptr;
308
  }
309
310
  int err = uv_udp_set_membership(&wrap->handle_,
311
6
                                  *address,
312
                                  iface_cstr,
313
6
                                  membership);
314
18
  args.GetReturnValue().Set(err);
315
}
316
317
318
3
void UDPWrap::AddMembership(const FunctionCallbackInfo<Value>& args) {
319
3
  SetMembership(args, UV_JOIN_GROUP);
320
3
}
321
322
323
3
void UDPWrap::DropMembership(const FunctionCallbackInfo<Value>& args) {
324
3
  SetMembership(args, UV_LEAVE_GROUP);
325
3
}
326
327
328
250
void UDPWrap::DoSend(const FunctionCallbackInfo<Value>& args, int family) {
329
250
  Environment* env = Environment::GetCurrent(args);
330
331
  UDPWrap* wrap;
332
500
  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
500
  CHECK(args[0]->IsObject());
338
500
  CHECK(args[1]->IsArray());
339
500
  CHECK(args[2]->IsUint32());
340
500
  CHECK(args[3]->IsUint32());
341
750
  CHECK(args[4]->IsString());
342
500
  CHECK(args[5]->IsBoolean());
343
344
500
  Local<Object> req_wrap_obj = args[0].As<Object>();
345
500
  Local<Array> chunks = args[1].As<Array>();
346
  // it is faster to fetch the length of the
347
  // array in js-land
348
500
  size_t count = args[2]->Uint32Value();
349
500
  const unsigned short port = args[3]->Uint32Value();
350
250
  node::Utf8Value address(env->isolate(), args[4]);
351
500
  const bool have_callback = args[5]->IsTrue();
352
353
250
  env->set_init_trigger_async_id(wrap->get_async_id());
354
250
  SendWrap* req_wrap = new SendWrap(env, req_wrap_obj, have_callback);
355
250
  size_t msg_size = 0;
356
357
500
  MaybeStackBuffer<uv_buf_t, 16> bufs(count);
358
359
  // construct uv_buf_t array
360
505
  for (size_t i = 0; i < count; i++) {
361
510
    Local<Value> chunk = chunks->Get(i);
362
363
255
    size_t length = Buffer::Length(chunk);
364
365
255
    bufs[i] = uv_buf_init(Buffer::Data(chunk), length);
366
255
    msg_size += length;
367
  }
368
369
250
  req_wrap->msg_size = msg_size;
370
371
  char addr[sizeof(sockaddr_in6)];
372
  int err;
373
374
250
  switch (family) {
375
  case AF_INET:
376
246
    err = uv_ip4_addr(*address, port, reinterpret_cast<sockaddr_in*>(&addr));
377
246
    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
250
  if (err == 0) {
387
    err = uv_udp_send(req_wrap->req(),
388
                      &wrap->handle_,
389
250
                      *bufs,
390
                      count,
391
                      reinterpret_cast<const sockaddr*>(&addr),
392
500
                      OnSend);
393
  }
394
395
250
  req_wrap->Dispatched();
396
250
  if (err)
397
    delete req_wrap;
398
399
750
  args.GetReturnValue().Set(err);
400
}
401
402
403
246
void UDPWrap::Send(const FunctionCallbackInfo<Value>& args) {
404
246
  DoSend(args, AF_INET);
405
246
}
406
407
408
4
void UDPWrap::Send6(const FunctionCallbackInfo<Value>& args) {
409
4
  DoSend(args, AF_INET6);
410
4
}
411
412
413
98
void UDPWrap::RecvStart(const FunctionCallbackInfo<Value>& args) {
414
  UDPWrap* wrap;
415
196
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
416
                          args.Holder(),
417
                          args.GetReturnValue().Set(UV_EBADF));
418
98
  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
98
  if (err == UV_EALREADY)
421
    err = 0;
422
196
  args.GetReturnValue().Set(err);
423
}
424
425
426
87
void UDPWrap::RecvStop(const FunctionCallbackInfo<Value>& args) {
427
  UDPWrap* wrap;
428
174
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
429
                          args.Holder(),
430
                          args.GetReturnValue().Set(UV_EBADF));
431
87
  int r = uv_udp_recv_stop(&wrap->handle_);
432
174
  args.GetReturnValue().Set(r);
433
}
434
435
436
250
void UDPWrap::OnSend(uv_udp_send_t* req, int status) {
437
250
  SendWrap* req_wrap = static_cast<SendWrap*>(req->data);
438
250
  if (req_wrap->have_callback()) {
439
78
    Environment* env = req_wrap->env();
440
78
    HandleScope handle_scope(env->isolate());
441
78
    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
234
    };
446
156
    req_wrap->MakeCallback(env->oncomplete_string(), 2, arg);
447
  }
448
250
  delete req_wrap;
449
250
}
450
451
452
429
void UDPWrap::OnAlloc(uv_handle_t* handle,
453
                      size_t suggested_size,
454
                      uv_buf_t* buf) {
455
429
  buf->base = node::Malloc(suggested_size);
456
429
  buf->len = suggested_size;
457
429
}
458
459
460
429
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

429
  if (nread == 0 && addr == nullptr) {
466
193
    if (buf->base != nullptr)
467
193
      free(buf->base);
468
386
    return;
469
  }
470
471
236
  UDPWrap* wrap = static_cast<UDPWrap*>(handle->data);
472
236
  Environment* env = wrap->env();
473
474
236
  HandleScope handle_scope(env->isolate());
475
472
  Context::Scope context_scope(env->context());
476
477
236
  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
1180
  };
484
485
236
  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
236
  char* base = node::UncheckedRealloc(buf->base, nread);
493
472
  argv[2] = Buffer::New(env, base, nread).ToLocalChecked();
494
472
  argv[3] = AddressToJS(env, addr);
495
472
  wrap->MakeCallback(env->onmessage_string(), arraysize(argv), argv);
496
}
497
498
499
19
Local<Object> UDPWrap::Instantiate(Environment* env, AsyncWrap* parent) {
500
19
  EscapableHandleScope scope(env->isolate());
501
38
  AsyncHooks::InitScope init_scope(env, parent->get_async_id());
502
  // If this assert fires then Initialize hasn't been called yet.
503
38
  CHECK_EQ(env->udp_constructor_function().IsEmpty(), false);
504
  Local<Object> instance = env->udp_constructor_function()
505
57
      ->NewInstance(env->context()).ToLocalChecked();
506
19
  return scope.Escape(instance);
507
}
508
509
510
19
uv_udp_t* UDPWrap::UVHandle() {
511
19
  return &handle_;
512
}
513
514
515
}  // namespace node
516
517
3245
NODE_MODULE_CONTEXT_AWARE_BUILTIN(udp_wrap, node::UDPWrap::Initialize)