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: 176 181 97.2 %
Date: 2021-05-31 04:11:52 Branches: 57 88 64.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 "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 "node_external_reference.h"
29
#include "pipe_wrap.h"
30
#include "req_wrap-inl.h"
31
#include "tcp_wrap.h"
32
#include "udp_wrap.h"
33
#include "util-inl.h"
34
35
#include <cstring>  // memcpy()
36
#include <climits>  // INT_MAX
37
38
39
namespace node {
40
41
using v8::Context;
42
using v8::DontDelete;
43
using v8::EscapableHandleScope;
44
using v8::FunctionCallbackInfo;
45
using v8::FunctionTemplate;
46
using v8::HandleScope;
47
using v8::Local;
48
using v8::MaybeLocal;
49
using v8::Object;
50
using v8::PropertyAttribute;
51
using v8::ReadOnly;
52
using v8::Signature;
53
using v8::Value;
54
55
119627
void IsConstructCallCallback(const FunctionCallbackInfo<Value>& args) {
56
119627
  CHECK(args.IsConstructCall());
57
119627
  StreamReq::ResetObject(args.This());
58
119627
}
59
60
466
void LibuvStreamWrap::Initialize(Local<Object> target,
61
                                 Local<Value> unused,
62
                                 Local<Context> context,
63
                                 void* priv) {
64
466
  Environment* env = Environment::GetCurrent(context);
65
66
  Local<FunctionTemplate> sw =
67
466
      FunctionTemplate::New(env->isolate(), IsConstructCallCallback);
68
932
  sw->InstanceTemplate()->SetInternalFieldCount(StreamReq::kInternalFieldCount);
69
70
  // we need to set handle and callback to null,
71
  // so that those fields are created and functions
72
  // do not become megamorphic
73
  // Fields:
74
  // - oncomplete
75
  // - callback
76
  // - handle
77
2330
  sw->InstanceTemplate()->Set(
78
      env->oncomplete_string(),
79
466
      v8::Null(env->isolate()));
80
2330
  sw->InstanceTemplate()->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "callback"),
81
466
      v8::Null(env->isolate()));
82
2330
  sw->InstanceTemplate()->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "handle"),
83
466
      v8::Null(env->isolate()));
84
85
932
  sw->Inherit(AsyncWrap::GetConstructorTemplate(env));
86
87
466
  env->SetConstructorFunction(target, "ShutdownWrap", sw);
88
466
  env->set_shutdown_wrap_template(sw->InstanceTemplate());
89
90
  Local<FunctionTemplate> ww =
91
466
      FunctionTemplate::New(env->isolate(), IsConstructCallCallback);
92
1398
  ww->InstanceTemplate()->SetInternalFieldCount(
93
466
      StreamReq::kInternalFieldCount);
94
932
  ww->Inherit(AsyncWrap::GetConstructorTemplate(env));
95
466
  env->SetConstructorFunction(target, "WriteWrap", ww);
96
466
  env->set_write_wrap_template(ww->InstanceTemplate());
97
98
466
  NODE_DEFINE_CONSTANT(target, kReadBytesOrError);
99
1398
  NODE_DEFINE_CONSTANT(target, kArrayBufferOffset);
100
2330
  NODE_DEFINE_CONSTANT(target, kBytesWritten);
101
3728
  NODE_DEFINE_CONSTANT(target, kLastWriteWasAsync);
102
4660
  target->Set(context, FIXED_ONE_BYTE_STRING(env->isolate(), "streamBaseState"),
103
5126
              env->stream_base_state().GetJSArray()).Check();
104
2796
}
105
932
106
4774
void LibuvStreamWrap::RegisterExternalReferences(
107
    ExternalReferenceRegistry* registry) {
108
4774
  registry->Register(IsConstructCallCallback);
109
4774
}
110
111
18380
LibuvStreamWrap::LibuvStreamWrap(Environment* env,
112
                                 Local<Object> object,
113
                                 uv_stream_t* stream,
114
18380
                                 AsyncWrap::ProviderType provider)
115
    : HandleWrap(env,
116
                 object,
117
                 reinterpret_cast<uv_handle_t*>(stream),
118
                 provider),
119
      StreamBase(env),
120
18380
      stream_(stream) {
121
18380
  StreamBase::AttachToObject(object);
122
18380
}
123
124
125
13514
Local<FunctionTemplate> LibuvStreamWrap::GetConstructorTemplate(
126
    Environment* env) {
127
13514
  Local<FunctionTemplate> tmpl = env->libuv_stream_wrap_ctor_template();
128
13514
  if (tmpl.IsEmpty()) {
129
4618
    tmpl = env->NewFunctionTemplate(nullptr);
130
9236
    tmpl->SetClassName(
131
4618
        FIXED_ONE_BYTE_STRING(env->isolate(), "LibuvStreamWrap"));
132
9236
    tmpl->Inherit(HandleWrap::GetConstructorTemplate(env));
133
13854
    tmpl->InstanceTemplate()->SetInternalFieldCount(
134
4618
        StreamBase::kInternalFieldCount);
135
    Local<FunctionTemplate> get_write_queue_size =
136
        FunctionTemplate::New(env->isolate(),
137
                              GetWriteQueueSize,
138
                              Local<Value>(),
139
9236
                              Signature::New(env->isolate(), tmpl));
140
18472
    tmpl->PrototypeTemplate()->SetAccessorProperty(
141
        env->write_queue_size_string(),
142
        get_write_queue_size,
143
        Local<FunctionTemplate>(),
144
4618
        static_cast<PropertyAttribute>(ReadOnly | DontDelete));
145
4618
    env->SetProtoMethod(tmpl, "setBlocking", SetBlocking);
146
4618
    StreamBase::AddMethods(env, tmpl);
147
4618
    env->set_libuv_stream_wrap_ctor_template(tmpl);
148
  }
149
13514
  return tmpl;
150
}
151
152
153
3709
LibuvStreamWrap* LibuvStreamWrap::From(Environment* env, Local<Object> object) {
154
3709
  Local<FunctionTemplate> sw = env->libuv_stream_wrap_ctor_template();
155

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

320
  if (!WrapType::Instantiate(env, parent, WrapType::SOCKET).ToLocal(&wrap_obj))
226
    return Local<Object>();
227
228
160
  HandleWrap* wrap = Unwrap<HandleWrap>(wrap_obj);
229

160
  CHECK_NOT_NULL(wrap);
230
160
  uv_stream_t* stream = reinterpret_cast<uv_stream_t*>(wrap->GetHandle());
231

160
  CHECK_NOT_NULL(stream);
232
233

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

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

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

19294
NODE_MODULE_EXTERNAL_REFERENCE(
404
    stream_wrap, node::LibuvStreamWrap::RegisterExternalReferences)