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-03-02 22:23:06 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 <cstring>  // memcpy()
35
#include <climits>  // 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
4052
void LibuvStreamWrap::Initialize(Local<Object> target,
55
                                 Local<Value> unused,
56
                                 Local<Context> context,
57
                                 void* priv) {
58
4052
  Environment* env = Environment::GetCurrent(context);
59
60
  auto is_construct_call_callback =
61
1602932
      [](const FunctionCallbackInfo<Value>& args) {
62
797414
    CHECK(args.IsConstructCall());
63
797414
    StreamReq::ResetObject(args.This());
64
1602932
  };
65
  Local<FunctionTemplate> sw =
66
4052
      FunctionTemplate::New(env->isolate(), is_construct_call_callback);
67
4052
  sw->InstanceTemplate()->SetInternalFieldCount(
68
8104
      StreamReq::kStreamReqField + 1 + 3);
69
  Local<String> wrapString =
70
4052
      FIXED_ONE_BYTE_STRING(env->isolate(), "ShutdownWrap");
71
4052
  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
12156
  sw->InstanceTemplate()->Set(
81
      FIXED_ONE_BYTE_STRING(env->isolate(), "oncomplete"),
82
16208
      v8::Null(env->isolate()));
83
12156
  sw->InstanceTemplate()->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "callback"),
84
16208
      v8::Null(env->isolate()));
85
12156
  sw->InstanceTemplate()->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "handle"),
86
16208
      v8::Null(env->isolate()));
87
88
8104
  sw->Inherit(AsyncWrap::GetConstructorTemplate(env));
89
90
  target->Set(env->context(),
91
              wrapString,
92
20260
              sw->GetFunction(env->context()).ToLocalChecked()).FromJust();
93
4052
  env->set_shutdown_wrap_template(sw->InstanceTemplate());
94
95
  Local<FunctionTemplate> ww =
96
4052
      FunctionTemplate::New(env->isolate(), is_construct_call_callback);
97
8104
  ww->InstanceTemplate()->SetInternalFieldCount(StreamReq::kStreamReqField + 1);
98
  Local<String> writeWrapString =
99
4052
      FIXED_ONE_BYTE_STRING(env->isolate(), "WriteWrap");
100
4052
  ww->SetClassName(writeWrapString);
101
8104
  ww->Inherit(AsyncWrap::GetConstructorTemplate(env));
102
  target->Set(env->context(),
103
              writeWrapString,
104
20260
              ww->GetFunction(env->context()).ToLocalChecked()).FromJust();
105
4052
  env->set_write_wrap_template(ww->InstanceTemplate());
106
107
16208
  NODE_DEFINE_CONSTANT(target, kReadBytesOrError);
108
16208
  NODE_DEFINE_CONSTANT(target, kArrayBufferOffset);
109
16208
  NODE_DEFINE_CONSTANT(target, kBytesWritten);
110
16208
  NODE_DEFINE_CONSTANT(target, kLastWriteWasAsync);
111
  target->Set(context, FIXED_ONE_BYTE_STRING(env->isolate(), "streamBaseState"),
112
16208
              env->stream_base_state().GetJSArray()).FromJust();
113
4052
}
114
115
116
33381
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
33381
      stream_(stream) {
126
33381
}
127
128
129
12226
Local<FunctionTemplate> LibuvStreamWrap::GetConstructorTemplate(
130
    Environment* env) {
131
12226
  Local<FunctionTemplate> tmpl = env->libuv_stream_wrap_ctor_template();
132
12226
  if (tmpl.IsEmpty()) {
133
4122
    tmpl = env->NewFunctionTemplate(nullptr);
134
    tmpl->SetClassName(
135
8244
        FIXED_ONE_BYTE_STRING(env->isolate(), "LibuvStreamWrap"));
136
8244
    tmpl->Inherit(HandleWrap::GetConstructorTemplate(env));
137
    Local<FunctionTemplate> get_write_queue_size =
138
        FunctionTemplate::New(env->isolate(),
139
                              GetWriteQueueSize,
140
                              env->as_external(),
141
8244
                              Signature::New(env->isolate(), tmpl));
142
12366
    tmpl->PrototypeTemplate()->SetAccessorProperty(
143
        env->write_queue_size_string(),
144
        get_write_queue_size,
145
        Local<FunctionTemplate>(),
146
12366
        static_cast<PropertyAttribute>(ReadOnly | DontDelete));
147
4122
    env->SetProtoMethod(tmpl, "setBlocking", SetBlocking);
148
4122
    StreamBase::AddMethods<LibuvStreamWrap>(env, tmpl);
149
4122
    env->set_libuv_stream_wrap_ctor_template(tmpl);
150
  }
151
12226
  return tmpl;
152
}
153
154
155
3473
LibuvStreamWrap* LibuvStreamWrap::From(Environment* env, Local<Object> object) {
156
3473
  Local<FunctionTemplate> sw = env->libuv_stream_wrap_ctor_template();
157


13892
  CHECK(!sw.IsEmpty() && sw->HasInstance(object));
158
3473
  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
804189
bool LibuvStreamWrap::IsAlive() {
175
804189
  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
400201
AsyncWrap* LibuvStreamWrap::GetAsyncWrap() {
185
400201
  return static_cast<AsyncWrap*>(this);
186
}
187
188
189
664041
bool LibuvStreamWrap::IsIPCPipe() {
190
664041
  return is_named_pipe_ipc();
191
}
192
193
194
29666
int LibuvStreamWrap::ReadStart() {
195
  return uv_read_start(stream(), [](uv_handle_t* handle,
196
                                    size_t suggested_size,
197
933966
                                    uv_buf_t* buf) {
198
452150
    static_cast<LibuvStreamWrap*>(handle->data)->OnUvAlloc(suggested_size, buf);
199
1868356
  }, [](uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf) {
200
452362
    static_cast<LibuvStreamWrap*>(stream->data)->OnUvRead(nread, buf);
201
963986
  });
202
}
203
204
205
1938
int LibuvStreamWrap::ReadStop() {
206
1938
  return uv_read_stop(stream());
207
}
208
209
210
452150
void LibuvStreamWrap::OnUvAlloc(size_t suggested_size, uv_buf_t* buf) {
211
452150
  HandleScope scope(env()->isolate());
212
452150
  Context::Scope context_scope(env()->context());
213
214
904300
  *buf = EmitAlloc(suggested_size);
215
452150
}
216
217
template <class WrapType>
218
155
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
155
  EscapableHandleScope scope(env->isolate());
225
  Local<Object> wrap_obj;
226
227

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

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

155
  CHECK_NOT_NULL(stream);
234
235

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

454997
  if (is_named_pipe_ipc() &&
248
2635
      uv_pipe_pending_count(reinterpret_cast<uv_pipe_t*>(stream())) > 0) {
249
155
    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
904724
  CHECK_EQ(persistent().IsEmpty(), false);
255
256
452362
  if (nread > 0) {
257
    MaybeLocal<Object> pending_obj;
258
259
445995
    if (type == UV_TCP) {
260
129
      pending_obj = AcceptHandle<TCPWrap>(env(), this);
261
445866
    } else if (type == UV_NAMED_PIPE) {
262
1
      pending_obj = AcceptHandle<PipeWrap>(env(), this);
263
445865
    } else if (type == UV_UDP) {
264
25
      pending_obj = AcceptHandle<UDPWrap>(env(), this);
265
    } else {
266
445840
      CHECK_EQ(type, UV_UNKNOWN_HANDLE);
267
    }
268
269
445995
    if (!pending_obj.IsEmpty()) {
270
155
      object()
271
          ->Set(env()->context(),
272
                env()->pending_handle_string(),
273
775
                pending_obj.ToLocalChecked())
274
310
          .FromJust();
275
    }
276
  }
277
278
904654
  EmitRead(nread, *buf);
279
452292
}
280
281
282
12744
void LibuvStreamWrap::GetWriteQueueSize(
283
    const FunctionCallbackInfo<Value>& info) {
284
  LibuvStreamWrap* wrap;
285
12744
  ASSIGN_OR_RETURN_UNWRAP(&wrap, info.This());
286
287
12744
  if (wrap->stream() == nullptr) {
288
    info.GetReturnValue().Set(0);
289
    return;
290
  }
291
292
12744
  uint32_t write_queue_size = wrap->stream()->write_queue_size;
293
25488
  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
21224
ShutdownWrap* LibuvStreamWrap::CreateShutdownWrap(Local<Object> object) {
313
21224
  return new LibuvShutdownWrap(this, object);
314
}
315
316
305
WriteWrap* LibuvStreamWrap::CreateWriteWrap(Local<Object> object) {
317
305
  return new LibuvWriteWrap(this, object);
318
}
319
320
321
21224
int LibuvStreamWrap::DoShutdown(ShutdownWrap* req_wrap_) {
322
21224
  LibuvShutdownWrap* req_wrap = static_cast<LibuvShutdownWrap*>(req_wrap_);
323
21224
  return req_wrap->Dispatch(uv_shutdown, stream(), AfterUvShutdown);
324
}
325
326
327
21221
void LibuvStreamWrap::AfterUvShutdown(uv_shutdown_t* req, int status) {
328
  LibuvShutdownWrap* req_wrap = static_cast<LibuvShutdownWrap*>(
329
21221
      LibuvShutdownWrap::from_req(req));
330
21221
  CHECK_NOT_NULL(req_wrap);
331
21221
  HandleScope scope(req_wrap->env()->isolate());
332
21221
  Context::Scope context_scope(req_wrap->env()->context());
333
42442
  req_wrap->Done(status);
334
21221
}
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
783705
int LibuvStreamWrap::DoTryWrite(uv_buf_t** bufs, size_t* count) {
342
  int err;
343
  size_t written;
344
783705
  uv_buf_t* vbufs = *bufs;
345
783705
  size_t vcount = *count;
346
347
783705
  err = uv_try_write(stream(), vbufs, vcount);
348

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