GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/stream_wrap.cc Lines: 165 170 97.1 %
Date: 2019-02-26 22:23:30 Branches: 56 86 65.1 %

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 "stream_wrap.h"
23
#include "stream_base-inl.h"
24
25
#include "env-inl.h"
26
#include "handle_wrap.h"
27
#include "node_buffer.h"
28
#include "pipe_wrap.h"
29
#include "req_wrap-inl.h"
30
#include "tcp_wrap.h"
31
#include "udp_wrap.h"
32
#include "util-inl.h"
33
34
#include <string.h>  // memcpy()
35
#include <limits.h>  // INT_MAX
36
37
38
namespace node {
39
40
using v8::Context;
41
using v8::DontDelete;
42
using v8::EscapableHandleScope;
43
using v8::FunctionCallbackInfo;
44
using v8::FunctionTemplate;
45
using v8::HandleScope;
46
using v8::Local;
47
using v8::MaybeLocal;
48
using v8::Object;
49
using v8::ReadOnly;
50
using v8::Signature;
51
using v8::Value;
52
53
54
4032
void LibuvStreamWrap::Initialize(Local<Object> target,
55
                                 Local<Value> unused,
56
                                 Local<Context> context,
57
                                 void* priv) {
58
4032
  Environment* env = Environment::GetCurrent(context);
59
60
  auto is_construct_call_callback =
61
1602228
      [](const FunctionCallbackInfo<Value>& args) {
62
797082
    CHECK(args.IsConstructCall());
63
797082
    StreamReq::ResetObject(args.This());
64
1602228
  };
65
  Local<FunctionTemplate> sw =
66
4032
      FunctionTemplate::New(env->isolate(), is_construct_call_callback);
67
4032
  sw->InstanceTemplate()->SetInternalFieldCount(
68
8064
      StreamReq::kStreamReqField + 1 + 3);
69
  Local<String> wrapString =
70
4032
      FIXED_ONE_BYTE_STRING(env->isolate(), "ShutdownWrap");
71
4032
  sw->SetClassName(wrapString);
72
73
  // we need to set handle and callback to null,
74
  // so that those fields are created and functions
75
  // do not become megamorphic
76
  // Fields:
77
  // - oncomplete
78
  // - callback
79
  // - handle
80
12096
  sw->InstanceTemplate()->Set(
81
      FIXED_ONE_BYTE_STRING(env->isolate(), "oncomplete"),
82
16128
      v8::Null(env->isolate()));
83
12096
  sw->InstanceTemplate()->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "callback"),
84
16128
      v8::Null(env->isolate()));
85
12096
  sw->InstanceTemplate()->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "handle"),
86
16128
      v8::Null(env->isolate()));
87
88
8064
  sw->Inherit(AsyncWrap::GetConstructorTemplate(env));
89
90
  target->Set(env->context(),
91
              wrapString,
92
20160
              sw->GetFunction(env->context()).ToLocalChecked()).FromJust();
93
4032
  env->set_shutdown_wrap_template(sw->InstanceTemplate());
94
95
  Local<FunctionTemplate> ww =
96
4032
      FunctionTemplate::New(env->isolate(), is_construct_call_callback);
97
8064
  ww->InstanceTemplate()->SetInternalFieldCount(StreamReq::kStreamReqField + 1);
98
  Local<String> writeWrapString =
99
4032
      FIXED_ONE_BYTE_STRING(env->isolate(), "WriteWrap");
100
4032
  ww->SetClassName(writeWrapString);
101
8064
  ww->Inherit(AsyncWrap::GetConstructorTemplate(env));
102
  target->Set(env->context(),
103
              writeWrapString,
104
20160
              ww->GetFunction(env->context()).ToLocalChecked()).FromJust();
105
4032
  env->set_write_wrap_template(ww->InstanceTemplate());
106
107
16128
  NODE_DEFINE_CONSTANT(target, kReadBytesOrError);
108
16128
  NODE_DEFINE_CONSTANT(target, kArrayBufferOffset);
109
16128
  NODE_DEFINE_CONSTANT(target, kBytesWritten);
110
16128
  NODE_DEFINE_CONSTANT(target, kLastWriteWasAsync);
111
  target->Set(context, FIXED_ONE_BYTE_STRING(env->isolate(), "streamBaseState"),
112
16128
              env->stream_base_state().GetJSArray()).FromJust();
113
4032
}
114
115
116
33608
LibuvStreamWrap::LibuvStreamWrap(Environment* env,
117
                                 Local<Object> object,
118
                                 uv_stream_t* stream,
119
                                 AsyncWrap::ProviderType provider)
120
    : HandleWrap(env,
121
                 object,
122
                 reinterpret_cast<uv_handle_t*>(stream),
123
                 provider),
124
      StreamBase(env),
125
33608
      stream_(stream) {
126
33608
}
127
128
129
12166
Local<FunctionTemplate> LibuvStreamWrap::GetConstructorTemplate(
130
    Environment* env) {
131
12166
  Local<FunctionTemplate> tmpl = env->libuv_stream_wrap_ctor_template();
132
12166
  if (tmpl.IsEmpty()) {
133
4102
    tmpl = env->NewFunctionTemplate(nullptr);
134
    tmpl->SetClassName(
135
8204
        FIXED_ONE_BYTE_STRING(env->isolate(), "LibuvStreamWrap"));
136
8204
    tmpl->Inherit(HandleWrap::GetConstructorTemplate(env));
137
    Local<FunctionTemplate> get_write_queue_size =
138
        FunctionTemplate::New(env->isolate(),
139
                              GetWriteQueueSize,
140
                              env->as_external(),
141
8204
                              Signature::New(env->isolate(), tmpl));
142
12306
    tmpl->PrototypeTemplate()->SetAccessorProperty(
143
        env->write_queue_size_string(),
144
        get_write_queue_size,
145
        Local<FunctionTemplate>(),
146
12306
        static_cast<PropertyAttribute>(ReadOnly | DontDelete));
147
4102
    env->SetProtoMethod(tmpl, "setBlocking", SetBlocking);
148
4102
    StreamBase::AddMethods<LibuvStreamWrap>(env, tmpl);
149
4102
    env->set_libuv_stream_wrap_ctor_template(tmpl);
150
  }
151
12166
  return tmpl;
152
}
153
154
155
3461
LibuvStreamWrap* LibuvStreamWrap::From(Environment* env, Local<Object> object) {
156
3461
  Local<FunctionTemplate> sw = env->libuv_stream_wrap_ctor_template();
157


13844
  CHECK(!sw.IsEmpty() && sw->HasInstance(object));
158
3461
  return Unwrap<LibuvStreamWrap>(object);
159
}
160
161
162
189
int LibuvStreamWrap::GetFD() {
163
#ifdef _WIN32
164
  return fd_;
165
#else
166
189
  int fd = -1;
167
189
  if (stream() != nullptr)
168
189
    uv_fileno(reinterpret_cast<uv_handle_t*>(stream()), &fd);
169
189
  return fd;
170
#endif
171
}
172
173
174
804321
bool LibuvStreamWrap::IsAlive() {
175
804321
  return HandleWrap::IsAlive(this);
176
}
177
178
179
3
bool LibuvStreamWrap::IsClosing() {
180
3
  return uv_is_closing(reinterpret_cast<uv_handle_t*>(stream()));
181
}
182
183
184
390578
AsyncWrap* LibuvStreamWrap::GetAsyncWrap() {
185
390578
  return static_cast<AsyncWrap*>(this);
186
}
187
188
189
663513
bool LibuvStreamWrap::IsIPCPipe() {
190
663513
  return is_named_pipe_ipc();
191
}
192
193
194
29958
int LibuvStreamWrap::ReadStart() {
195
  return uv_read_start(stream(), [](uv_handle_t* handle,
196
                                    size_t suggested_size,
197
913974
                                    uv_buf_t* buf) {
198
442008
    static_cast<LibuvStreamWrap*>(handle->data)->OnUvAlloc(suggested_size, buf);
199
1828358
  }, [](uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf) {
200
442213
    static_cast<LibuvStreamWrap*>(stream->data)->OnUvRead(nread, buf);
201
944272
  });
202
}
203
204
205
2063
int LibuvStreamWrap::ReadStop() {
206
2063
  return uv_read_stop(stream());
207
}
208
209
210
442008
void LibuvStreamWrap::OnUvAlloc(size_t suggested_size, uv_buf_t* buf) {
211
442008
  HandleScope scope(env()->isolate());
212
442008
  Context::Scope context_scope(env()->context());
213
214
884016
  *buf = EmitAlloc(suggested_size);
215
442008
}
216
217
template <class WrapType>
218
154
static MaybeLocal<Object> AcceptHandle(Environment* env,
219
                                       LibuvStreamWrap* parent) {
220
  static_assert(std::is_base_of<LibuvStreamWrap, WrapType>::value ||
221
                std::is_base_of<UDPWrap, WrapType>::value,
222
                "Can only accept stream handles");
223
224
154
  EscapableHandleScope scope(env->isolate());
225
  Local<Object> wrap_obj;
226
227

308
  if (!WrapType::Instantiate(env, parent, WrapType::SOCKET).ToLocal(&wrap_obj))
228
    return Local<Object>();
229
230
154
  HandleWrap* wrap = Unwrap<HandleWrap>(wrap_obj);
231

154
  CHECK_NOT_NULL(wrap);
232
154
  uv_stream_t* stream = reinterpret_cast<uv_stream_t*>(wrap->GetHandle());
233

154
  CHECK_NOT_NULL(stream);
234
235

154
  if (uv_accept(parent->stream(), stream))
236
    ABORT();
237
238
154
  return scope.Escape(wrap_obj);
239
}
240
241
242
442213
void LibuvStreamWrap::OnUvRead(ssize_t nread, const uv_buf_t* buf) {
243
442213
  HandleScope scope(env()->isolate());
244
442213
  Context::Scope context_scope(env()->context());
245
442213
  uv_handle_type type = UV_UNKNOWN_HANDLE;
246
247

444845
  if (is_named_pipe_ipc() &&
248
2632
      uv_pipe_pending_count(reinterpret_cast<uv_pipe_t*>(stream())) > 0) {
249
154
    type = uv_pipe_pending_type(reinterpret_cast<uv_pipe_t*>(stream()));
250
  }
251
252
  // We should not be getting this callback if someone has already called
253
  // uv_close() on the handle.
254
884426
  CHECK_EQ(persistent().IsEmpty(), false);
255
256
442213
  if (nread > 0) {
257
    MaybeLocal<Object> pending_obj;
258
259
435836
    if (type == UV_TCP) {
260
129
      pending_obj = AcceptHandle<TCPWrap>(env(), this);
261
435707
    } else if (type == UV_NAMED_PIPE) {
262
1
      pending_obj = AcceptHandle<PipeWrap>(env(), this);
263
435706
    } else if (type == UV_UDP) {
264
24
      pending_obj = AcceptHandle<UDPWrap>(env(), this);
265
    } else {
266
435682
      CHECK_EQ(type, UV_UNKNOWN_HANDLE);
267
    }
268
269
435836
    if (!pending_obj.IsEmpty()) {
270
154
      object()
271
          ->Set(env()->context(),
272
                env()->pending_handle_string(),
273
770
                pending_obj.ToLocalChecked())
274
308
          .FromJust();
275
    }
276
  }
277
278
884356
  EmitRead(nread, *buf);
279
442143
}
280
281
282
12740
void LibuvStreamWrap::GetWriteQueueSize(
283
    const FunctionCallbackInfo<Value>& info) {
284
  LibuvStreamWrap* wrap;
285
12740
  ASSIGN_OR_RETURN_UNWRAP(&wrap, info.This());
286
287
12740
  if (wrap->stream() == nullptr) {
288
    info.GetReturnValue().Set(0);
289
    return;
290
  }
291
292
12740
  uint32_t write_queue_size = wrap->stream()->write_queue_size;
293
25480
  info.GetReturnValue().Set(write_queue_size);
294
}
295
296
297
22
void LibuvStreamWrap::SetBlocking(const FunctionCallbackInfo<Value>& args) {
298
  LibuvStreamWrap* wrap;
299
22
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
300
301
22
  CHECK_GT(args.Length(), 0);
302
22
  if (!wrap->IsAlive())
303
    return args.GetReturnValue().Set(UV_EINVAL);
304
305
44
  bool enable = args[0]->IsTrue();
306
66
  args.GetReturnValue().Set(uv_stream_set_blocking(wrap->stream(), enable));
307
}
308
309
typedef SimpleShutdownWrap<ReqWrap<uv_shutdown_t>> LibuvShutdownWrap;
310
typedef SimpleWriteWrap<ReqWrap<uv_write_t>> LibuvWriteWrap;
311
312
21481
ShutdownWrap* LibuvStreamWrap::CreateShutdownWrap(Local<Object> object) {
313
21481
  return new LibuvShutdownWrap(this, object);
314
}
315
316
438
WriteWrap* LibuvStreamWrap::CreateWriteWrap(Local<Object> object) {
317
438
  return new LibuvWriteWrap(this, object);
318
}
319
320
321
21481
int LibuvStreamWrap::DoShutdown(ShutdownWrap* req_wrap_) {
322
21481
  LibuvShutdownWrap* req_wrap = static_cast<LibuvShutdownWrap*>(req_wrap_);
323
21481
  return req_wrap->Dispatch(uv_shutdown, stream(), AfterUvShutdown);
324
}
325
326
327
21478
void LibuvStreamWrap::AfterUvShutdown(uv_shutdown_t* req, int status) {
328
  LibuvShutdownWrap* req_wrap = static_cast<LibuvShutdownWrap*>(
329
21478
      LibuvShutdownWrap::from_req(req));
330
21478
  CHECK_NOT_NULL(req_wrap);
331
21478
  HandleScope scope(req_wrap->env()->isolate());
332
21478
  Context::Scope context_scope(req_wrap->env()->context());
333
42956
  req_wrap->Done(status);
334
21478
}
335
336
337
// NOTE: Call to this function could change both `buf`'s and `count`'s
338
// values, shifting their base and decrementing their length. This is
339
// required in order to skip the data that was successfully written via
340
// uv_try_write().
341
783146
int LibuvStreamWrap::DoTryWrite(uv_buf_t** bufs, size_t* count) {
342
  int err;
343
  size_t written;
344
783146
  uv_buf_t* vbufs = *bufs;
345
783146
  size_t vcount = *count;
346
347
783146
  err = uv_try_write(stream(), vbufs, vcount);
348

783146
  if (err == UV_ENOSYS || err == UV_EAGAIN)
349
199
    return 0;
350
782947
  if (err < 0)
351
42
    return err;
352
353
  // Slice off the buffers: skip all written buffers and slice the one that
354
  // was partially written.
355
782905
  written = err;
356
1680437
  for (; vcount > 0; vbufs++, vcount--) {
357
    // Slice
358
897680
    if (vbufs[0].len > written) {
359
148
      vbufs[0].base += written;
360
148
      vbufs[0].len -= written;
361
148
      written = 0;
362
148
      break;
363
364
    // Discard
365
    } else {
366
897532
      written -= vbufs[0].len;
367
    }
368
  }
369
370
782905
  *bufs = vbufs;
371
782905
  *count = vcount;
372
373
782905
  return 0;
374
}
375
376
377
438
int LibuvStreamWrap::DoWrite(WriteWrap* req_wrap,
378
                             uv_buf_t* bufs,
379
                             size_t count,
380
                             uv_stream_t* send_handle) {
381
438
  LibuvWriteWrap* w = static_cast<LibuvWriteWrap*>(req_wrap);
382
  return w->Dispatch(uv_write2,
383
                     stream(),
384
                     bufs,
385
                     count,
386
                     send_handle,
387
438
                     AfterUvWrite);
388
}
389
390
391
392
429
void LibuvStreamWrap::AfterUvWrite(uv_write_t* req, int status) {
393
  LibuvWriteWrap* req_wrap = static_cast<LibuvWriteWrap*>(
394
429
      LibuvWriteWrap::from_req(req));
395
429
  CHECK_NOT_NULL(req_wrap);
396
429
  HandleScope scope(req_wrap->env()->isolate());
397
429
  Context::Scope context_scope(req_wrap->env()->context());
398
856
  req_wrap->Done(status);
399
427
}
400
401
}  // namespace node
402
403
4282
NODE_MODULE_CONTEXT_AWARE_INTERNAL(stream_wrap,
404
                                   node::LibuvStreamWrap::Initialize)