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


13864
  CHECK(!sw.IsEmpty() && sw->HasInstance(object));
158
3466
  return Unwrap<LibuvStreamWrap>(object);
159
}
160
161
162
195
int LibuvStreamWrap::GetFD() {
163
#ifdef _WIN32
164
  return fd_;
165
#else
166
195
  int fd = -1;
167
195
  if (stream() != nullptr)
168
195
    uv_fileno(reinterpret_cast<uv_handle_t*>(stream()), &fd);
169
195
  return fd;
170
#endif
171
}
172
173
174
817733
bool LibuvStreamWrap::IsAlive() {
175
817733
  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
375531
AsyncWrap* LibuvStreamWrap::GetAsyncWrap() {
185
375531
  return static_cast<AsyncWrap*>(this);
186
}
187
188
189
675535
bool LibuvStreamWrap::IsIPCPipe() {
190
675535
  return is_named_pipe_ipc();
191
}
192
193
194
30649
int LibuvStreamWrap::ReadStart() {
195
  return uv_read_start(stream(), [](uv_handle_t* handle,
196
                                    size_t suggested_size,
197
883667
                                    uv_buf_t* buf) {
198
426509
    static_cast<LibuvStreamWrap*>(handle->data)->OnUvAlloc(suggested_size, buf);
199
1767790
  }, [](uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf) {
200
426737
    static_cast<LibuvStreamWrap*>(stream->data)->OnUvRead(nread, buf);
201
914703
  });
202
}
203
204
205
2068
int LibuvStreamWrap::ReadStop() {
206
2068
  return uv_read_stop(stream());
207
}
208
209
210
426509
void LibuvStreamWrap::OnUvAlloc(size_t suggested_size, uv_buf_t* buf) {
211
426509
  HandleScope scope(env()->isolate());
212
426509
  Context::Scope context_scope(env()->context());
213
214
853018
  *buf = EmitAlloc(suggested_size);
215
426509
}
216
217
template <class WrapType>
218
156
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
156
  EscapableHandleScope scope(env->isolate());
225
  Local<Object> wrap_obj;
226
227

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

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

156
  CHECK_NOT_NULL(stream);
234
235

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

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

795190
  if (err == UV_ENOSYS || err == UV_EAGAIN)
349
201
    return 0;
350
794989
  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
794945
  written = err;
356
1704627
  for (; vcount > 0; vbufs++, vcount--) {
357
    // Slice
358
909832
    if (vbufs[0].len > written) {
359
150
      vbufs[0].base += written;
360
150
      vbufs[0].len -= written;
361
150
      written = 0;
362
150
      break;
363
364
    // Discard
365
    } else {
366
909682
      written -= vbufs[0].len;
367
    }
368
  }
369
370
794945
  *bufs = vbufs;
371
794945
  *count = vcount;
372
373
794945
  return 0;
374
}
375
376
377
443
int LibuvStreamWrap::DoWrite(WriteWrap* req_wrap,
378
                             uv_buf_t* bufs,
379
                             size_t count,
380
                             uv_stream_t* send_handle) {
381
443
  LibuvWriteWrap* w = static_cast<LibuvWriteWrap*>(req_wrap);
382
  return w->Dispatch(uv_write2,
383
                     stream(),
384
                     bufs,
385
                     count,
386
                     send_handle,
387
443
                     AfterUvWrite);
388
}
389
390
391
392
434
void LibuvStreamWrap::AfterUvWrite(uv_write_t* req, int status) {
393
  LibuvWriteWrap* req_wrap = static_cast<LibuvWriteWrap*>(
394
434
      LibuvWriteWrap::from_req(req));
395
434
  CHECK_NOT_NULL(req_wrap);
396
434
  HandleScope scope(req_wrap->env()->isolate());
397
434
  Context::Scope context_scope(req_wrap->env()->context());
398
866
  req_wrap->Done(status);
399
432
}
400
401
}  // namespace node
402
403
4314
NODE_MODULE_CONTEXT_AWARE_INTERNAL(stream_wrap,
404
                                   node::LibuvStreamWrap::Initialize)