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-10 04:11:54 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
117996
void IsConstructCallCallback(const FunctionCallbackInfo<Value>& args) {
56
117996
  CHECK(args.IsConstructCall());
57
117996
  StreamReq::ResetObject(args.This());
58
117996
}
59
60
455
void LibuvStreamWrap::Initialize(Local<Object> target,
61
                                 Local<Value> unused,
62
                                 Local<Context> context,
63
                                 void* priv) {
64
455
  Environment* env = Environment::GetCurrent(context);
65
66
  Local<FunctionTemplate> sw =
67
455
      FunctionTemplate::New(env->isolate(), IsConstructCallCallback);
68
910
  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
2275
  sw->InstanceTemplate()->Set(
78
      env->oncomplete_string(),
79
455
      v8::Null(env->isolate()));
80
2275
  sw->InstanceTemplate()->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "callback"),
81
455
      v8::Null(env->isolate()));
82
2275
  sw->InstanceTemplate()->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "handle"),
83
455
      v8::Null(env->isolate()));
84
85
910
  sw->Inherit(AsyncWrap::GetConstructorTemplate(env));
86
87
455
  env->SetConstructorFunction(target, "ShutdownWrap", sw);
88
455
  env->set_shutdown_wrap_template(sw->InstanceTemplate());
89
90
  Local<FunctionTemplate> ww =
91
455
      FunctionTemplate::New(env->isolate(), IsConstructCallCallback);
92
1365
  ww->InstanceTemplate()->SetInternalFieldCount(
93
455
      StreamReq::kInternalFieldCount);
94
910
  ww->Inherit(AsyncWrap::GetConstructorTemplate(env));
95
455
  env->SetConstructorFunction(target, "WriteWrap", ww);
96
455
  env->set_write_wrap_template(ww->InstanceTemplate());
97
98
455
  NODE_DEFINE_CONSTANT(target, kReadBytesOrError);
99
1365
  NODE_DEFINE_CONSTANT(target, kArrayBufferOffset);
100
2275
  NODE_DEFINE_CONSTANT(target, kBytesWritten);
101
3640
  NODE_DEFINE_CONSTANT(target, kLastWriteWasAsync);
102
4550
  target->Set(context, FIXED_ONE_BYTE_STRING(env->isolate(), "streamBaseState"),
103
5005
              env->stream_base_state().GetJSArray()).Check();
104
2730
}
105
910
106
4767
void LibuvStreamWrap::RegisterExternalReferences(
107
    ExternalReferenceRegistry* registry) {
108
4767
  registry->Register(IsConstructCallCallback);
109
4767
}
110
111
18379
LibuvStreamWrap::LibuvStreamWrap(Environment* env,
112
                                 Local<Object> object,
113
                                 uv_stream_t* stream,
114
18379
                                 AsyncWrap::ProviderType provider)
115
    : HandleWrap(env,
116
                 object,
117
                 reinterpret_cast<uv_handle_t*>(stream),
118
                 provider),
119
      StreamBase(env),
120
18379
      stream_(stream) {
121
18379
  StreamBase::AttachToObject(object);
122
18379
}
123
124
125
13526
Local<FunctionTemplate> LibuvStreamWrap::GetConstructorTemplate(
126
    Environment* env) {
127
13526
  Local<FunctionTemplate> tmpl = env->libuv_stream_wrap_ctor_template();
128
13526
  if (tmpl.IsEmpty()) {
129
4622
    tmpl = env->NewFunctionTemplate(nullptr);
130
9244
    tmpl->SetClassName(
131
4622
        FIXED_ONE_BYTE_STRING(env->isolate(), "LibuvStreamWrap"));
132
9244
    tmpl->Inherit(HandleWrap::GetConstructorTemplate(env));
133
13866
    tmpl->InstanceTemplate()->SetInternalFieldCount(
134
4622
        StreamBase::kInternalFieldCount);
135
    Local<FunctionTemplate> get_write_queue_size =
136
        FunctionTemplate::New(env->isolate(),
137
                              GetWriteQueueSize,
138
                              Local<Value>(),
139
9244
                              Signature::New(env->isolate(), tmpl));
140
18488
    tmpl->PrototypeTemplate()->SetAccessorProperty(
141
        env->write_queue_size_string(),
142
        get_write_queue_size,
143
        Local<FunctionTemplate>(),
144
4622
        static_cast<PropertyAttribute>(ReadOnly | DontDelete));
145
4622
    env->SetProtoMethod(tmpl, "setBlocking", SetBlocking);
146
4622
    StreamBase::AddMethods(env, tmpl);
147
4622
    env->set_libuv_stream_wrap_ctor_template(tmpl);
148
  }
149
13526
  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
125460
bool LibuvStreamWrap::IsAlive() {
173
125460
  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
167017
AsyncWrap* LibuvStreamWrap::GetAsyncWrap() {
183
167017
  return static_cast<AsyncWrap*>(this);
184
}
185
186
187
26610
bool LibuvStreamWrap::IsIPCPipe() {
188
26610
  return is_named_pipe_ipc();
189
}
190
191
192
22052
int LibuvStreamWrap::ReadStart() {
193
44104
  return uv_read_start(stream(), [](uv_handle_t* handle,
194
                                    size_t suggested_size,
195
164064
                                    uv_buf_t* buf) {
196
71006
    static_cast<LibuvStreamWrap*>(handle->data)->OnUvAlloc(suggested_size, buf);
197
328586
  }, [](uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf) {
198
71235
    static_cast<LibuvStreamWrap*>(stream->data)->OnUvRead(nread, buf);
199
208518
  });
200
}
201
202
203
16165
int LibuvStreamWrap::ReadStop() {
204
16165
  return uv_read_stop(stream());
205
}
206
207
208
71006
void LibuvStreamWrap::OnUvAlloc(size_t suggested_size, uv_buf_t* buf) {
209
142012
  HandleScope scope(env()->isolate());
210
71006
  Context::Scope context_scope(env()->context());
211
212
71006
  *buf = EmitAlloc(suggested_size);
213
71006
}
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
71235
void LibuvStreamWrap::OnUvRead(ssize_t nread, const uv_buf_t* buf) {
241
142362
  HandleScope scope(env()->isolate());
242
71235
  Context::Scope context_scope(env()->context());
243
71235
  uv_handle_type type = UV_UNKNOWN_HANDLE;
244
245

74516
  if (is_named_pipe_ipc() &&
246
3281
      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
142470
  CHECK_EQ(persistent().IsEmpty(), false);
253
254
71235
  if (nread > 0) {
255
    MaybeLocal<Object> pending_obj;
256
257
64979
    if (type == UV_TCP) {
258
129
      pending_obj = AcceptHandle<TCPWrap>(env(), this);
259
64850
    } else if (type == UV_NAMED_PIPE) {
260
1
      pending_obj = AcceptHandle<PipeWrap>(env(), this);
261
64849
    } else if (type == UV_UDP) {
262
30
      pending_obj = AcceptHandle<UDPWrap>(env(), this);
263
    } else {
264
64819
      CHECK_EQ(type, UV_UNKNOWN_HANDLE);
265
    }
266
267
64979
    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
71235
  EmitRead(nread, *buf);
277
71127
}
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
7474
ShutdownWrap* LibuvStreamWrap::CreateShutdownWrap(Local<Object> object) {
311
7474
  return new LibuvShutdownWrap(this, object);
312
}
313
314
297
WriteWrap* LibuvStreamWrap::CreateWriteWrap(Local<Object> object) {
315
297
  return new LibuvWriteWrap(this, object);
316
}
317
318
319
7474
int LibuvStreamWrap::DoShutdown(ShutdownWrap* req_wrap_) {
320
7474
  LibuvShutdownWrap* req_wrap = static_cast<LibuvShutdownWrap*>(req_wrap_);
321
7474
  return req_wrap->Dispatch(uv_shutdown, stream(), AfterUvShutdown);
322
}
323
324
325
7470
void LibuvStreamWrap::AfterUvShutdown(uv_shutdown_t* req, int status) {
326
7470
  LibuvShutdownWrap* req_wrap = static_cast<LibuvShutdownWrap*>(
327
14940
      LibuvShutdownWrap::from_req(req));
328
7470
  CHECK_NOT_NULL(req_wrap);
329
14940
  HandleScope scope(req_wrap->env()->isolate());
330
7470
  Context::Scope context_scope(req_wrap->env()->context());
331
7470
  req_wrap->Done(status);
332
7470
}
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
118588
int LibuvStreamWrap::DoTryWrite(uv_buf_t** bufs, size_t* count) {
340
  int err;
341
  size_t written;
342
118588
  uv_buf_t* vbufs = *bufs;
343
118588
  size_t vcount = *count;
344
345
118588
  err = uv_try_write(stream(), vbufs, vcount);
346

118588
  if (err == UV_ENOSYS || err == UV_EAGAIN)
347
59
    return 0;
348
118529
  if (err < 0)
349
3160
    return err;
350
351
  // Slice off the buffers: skip all written buffers and slice the one that
352
  // was partially written.
353
115369
  written = err;
354
493407
  for (; vcount > 0; vbufs++, vcount--) {
355
    // Slice
356
189151
    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
189019
      written -= vbufs[0].len;
365
    }
366
  }
367
368
115369
  *bufs = vbufs;
369
115369
  *count = vcount;
370
371
115369
  return 0;
372
}
373
374
375
297
int LibuvStreamWrap::DoWrite(WriteWrap* req_wrap,
376
                             uv_buf_t* bufs,
377
                             size_t count,
378
                             uv_stream_t* send_handle) {
379
297
  LibuvWriteWrap* w = static_cast<LibuvWriteWrap*>(req_wrap);
380
297
  return w->Dispatch(uv_write2,
381
                     stream(),
382
                     bufs,
383
                     count,
384
                     send_handle,
385
297
                     AfterUvWrite);
386
}
387
388
389
390
296
void LibuvStreamWrap::AfterUvWrite(uv_write_t* req, int status) {
391
296
  LibuvWriteWrap* req_wrap = static_cast<LibuvWriteWrap*>(
392
592
      LibuvWriteWrap::from_req(req));
393
296
  CHECK_NOT_NULL(req_wrap);
394
591
  HandleScope scope(req_wrap->env()->isolate());
395
296
  Context::Scope context_scope(req_wrap->env()->context());
396
296
  req_wrap->Done(status);
397
295
}
398
399
}  // namespace node
400
401
4838
NODE_MODULE_CONTEXT_AWARE_INTERNAL(stream_wrap,
402
                                   node::LibuvStreamWrap::Initialize)
403

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