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-06-07 04:11:51 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
117907
void IsConstructCallCallback(const FunctionCallbackInfo<Value>& args) {
56
117907
  CHECK(args.IsConstructCall());
57
117907
  StreamReq::ResetObject(args.This());
58
117907
}
59
60
459
void LibuvStreamWrap::Initialize(Local<Object> target,
61
                                 Local<Value> unused,
62
                                 Local<Context> context,
63
                                 void* priv) {
64
459
  Environment* env = Environment::GetCurrent(context);
65
66
  Local<FunctionTemplate> sw =
67
459
      FunctionTemplate::New(env->isolate(), IsConstructCallCallback);
68
918
  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
2295
  sw->InstanceTemplate()->Set(
78
      env->oncomplete_string(),
79
459
      v8::Null(env->isolate()));
80
2295
  sw->InstanceTemplate()->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "callback"),
81
459
      v8::Null(env->isolate()));
82
2295
  sw->InstanceTemplate()->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "handle"),
83
459
      v8::Null(env->isolate()));
84
85
918
  sw->Inherit(AsyncWrap::GetConstructorTemplate(env));
86
87
459
  env->SetConstructorFunction(target, "ShutdownWrap", sw);
88
459
  env->set_shutdown_wrap_template(sw->InstanceTemplate());
89
90
  Local<FunctionTemplate> ww =
91
459
      FunctionTemplate::New(env->isolate(), IsConstructCallCallback);
92
1377
  ww->InstanceTemplate()->SetInternalFieldCount(
93
459
      StreamReq::kInternalFieldCount);
94
918
  ww->Inherit(AsyncWrap::GetConstructorTemplate(env));
95
459
  env->SetConstructorFunction(target, "WriteWrap", ww);
96
459
  env->set_write_wrap_template(ww->InstanceTemplate());
97
98
459
  NODE_DEFINE_CONSTANT(target, kReadBytesOrError);
99
1377
  NODE_DEFINE_CONSTANT(target, kArrayBufferOffset);
100
2295
  NODE_DEFINE_CONSTANT(target, kBytesWritten);
101
3672
  NODE_DEFINE_CONSTANT(target, kLastWriteWasAsync);
102
4590
  target->Set(context, FIXED_ONE_BYTE_STRING(env->isolate(), "streamBaseState"),
103
5049
              env->stream_base_state().GetJSArray()).Check();
104
2754
}
105
918
106
4779
void LibuvStreamWrap::RegisterExternalReferences(
107
    ExternalReferenceRegistry* registry) {
108
4779
  registry->Register(IsConstructCallCallback);
109
4779
}
110
111
18381
LibuvStreamWrap::LibuvStreamWrap(Environment* env,
112
                                 Local<Object> object,
113
                                 uv_stream_t* stream,
114
18381
                                 AsyncWrap::ProviderType provider)
115
    : HandleWrap(env,
116
                 object,
117
                 reinterpret_cast<uv_handle_t*>(stream),
118
                 provider),
119
      StreamBase(env),
120
18381
      stream_(stream) {
121
18381
  StreamBase::AttachToObject(object);
122
18381
}
123
124
125
13529
Local<FunctionTemplate> LibuvStreamWrap::GetConstructorTemplate(
126
    Environment* env) {
127
13529
  Local<FunctionTemplate> tmpl = env->libuv_stream_wrap_ctor_template();
128
13529
  if (tmpl.IsEmpty()) {
129
4623
    tmpl = env->NewFunctionTemplate(nullptr);
130
9246
    tmpl->SetClassName(
131
4623
        FIXED_ONE_BYTE_STRING(env->isolate(), "LibuvStreamWrap"));
132
9246
    tmpl->Inherit(HandleWrap::GetConstructorTemplate(env));
133
13869
    tmpl->InstanceTemplate()->SetInternalFieldCount(
134
4623
        StreamBase::kInternalFieldCount);
135
    Local<FunctionTemplate> get_write_queue_size =
136
        FunctionTemplate::New(env->isolate(),
137
                              GetWriteQueueSize,
138
                              Local<Value>(),
139
9246
                              Signature::New(env->isolate(), tmpl));
140
18492
    tmpl->PrototypeTemplate()->SetAccessorProperty(
141
        env->write_queue_size_string(),
142
        get_write_queue_size,
143
        Local<FunctionTemplate>(),
144
4623
        static_cast<PropertyAttribute>(ReadOnly | DontDelete));
145
4623
    env->SetProtoMethod(tmpl, "setBlocking", SetBlocking);
146
4623
    StreamBase::AddMethods(env, tmpl);
147
4623
    env->set_libuv_stream_wrap_ctor_template(tmpl);
148
  }
149
13529
  return tmpl;
150
}
151
152
153
3712
LibuvStreamWrap* LibuvStreamWrap::From(Environment* env, Local<Object> object) {
154
3712
  Local<FunctionTemplate> sw = env->libuv_stream_wrap_ctor_template();
155

7424
  CHECK(!sw.IsEmpty() && sw->HasInstance(object));
156
3712
  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
125335
bool LibuvStreamWrap::IsAlive() {
173
125335
  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
168029
AsyncWrap* LibuvStreamWrap::GetAsyncWrap() {
183
168029
  return static_cast<AsyncWrap*>(this);
184
}
185
186
187
27481
bool LibuvStreamWrap::IsIPCPipe() {
188
27481
  return is_named_pipe_ipc();
189
}
190
191
192
22005
int LibuvStreamWrap::ReadStart() {
193
44010
  return uv_read_start(stream(), [](uv_handle_t* handle,
194
                                    size_t suggested_size,
195
166611
                                    uv_buf_t* buf) {
196
72303
    static_cast<LibuvStreamWrap*>(handle->data)->OnUvAlloc(suggested_size, buf);
197
333690
  }, [](uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf) {
198
72537
    static_cast<LibuvStreamWrap*>(stream->data)->OnUvRead(nread, buf);
199
210893
  });
200
}
201
202
203
16165
int LibuvStreamWrap::ReadStop() {
204
16165
  return uv_read_stop(stream());
205
}
206
207
208
72303
void LibuvStreamWrap::OnUvAlloc(size_t suggested_size, uv_buf_t* buf) {
209
144606
  HandleScope scope(env()->isolate());
210
72303
  Context::Scope context_scope(env()->context());
211
212
72303
  *buf = EmitAlloc(suggested_size);
213
72303
}
214
215
template <class WrapType>
216
158
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
158
  EscapableHandleScope scope(env->isolate());
223
  Local<Object> wrap_obj;
224
225

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

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

158
  CHECK_NOT_NULL(stream);
232
233

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

76513
  if (is_named_pipe_ipc() &&
246
3976
      uv_pipe_pending_count(reinterpret_cast<uv_pipe_t*>(stream())) > 0) {
247
158
    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
145074
  CHECK_EQ(persistent().IsEmpty(), false);
253
254
72537
  if (nread > 0) {
255
    MaybeLocal<Object> pending_obj;
256
257
66250
    if (type == UV_TCP) {
258
127
      pending_obj = AcceptHandle<TCPWrap>(env(), this);
259
66123
    } else if (type == UV_NAMED_PIPE) {
260
1
      pending_obj = AcceptHandle<PipeWrap>(env(), this);
261
66122
    } else if (type == UV_UDP) {
262
30
      pending_obj = AcceptHandle<UDPWrap>(env(), this);
263
    } else {
264
66092
      CHECK_EQ(type, UV_UNKNOWN_HANDLE);
265
    }
266
267
66250
    if (!pending_obj.IsEmpty()) {
268
316
      object()
269
316
          ->Set(env()->context(),
270
                env()->pending_handle_string(),
271
632
                pending_obj.ToLocalChecked())
272
          .Check();
273
    }
274
  }
275
276
72537
  EmitRead(nread, *buf);
277
72341
}
278
279
280
5409
void LibuvStreamWrap::GetWriteQueueSize(
281
    const FunctionCallbackInfo<Value>& info) {
282
  LibuvStreamWrap* wrap;
283
5409
  ASSIGN_OR_RETURN_UNWRAP(&wrap, info.This());
284
285
5409
  if (wrap->stream() == nullptr) {
286
    info.GetReturnValue().Set(0);
287
    return;
288
  }
289
290
5409
  uint32_t write_queue_size = wrap->stream()->write_queue_size;
291
10818
  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
250
WriteWrap* LibuvStreamWrap::CreateWriteWrap(Local<Object> object) {
315
250
  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
118534
int LibuvStreamWrap::DoTryWrite(uv_buf_t** bufs, size_t* count) {
340
  int err;
341
  size_t written;
342
118534
  uv_buf_t* vbufs = *bufs;
343
118534
  size_t vcount = *count;
344
345
118534
  err = uv_try_write(stream(), vbufs, vcount);
346

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

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