GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: stream_pipe.cc Lines: 142 192 74.0 %
Date: 2022-06-11 04:15:45 Branches: 52 110 47.3 %

Line Branch Exec Source
1
#include "stream_pipe.h"
2
#include "stream_base-inl.h"
3
#include "node_buffer.h"
4
#include "util-inl.h"
5
6
namespace node {
7
8
using v8::BackingStore;
9
using v8::Context;
10
using v8::Function;
11
using v8::FunctionCallbackInfo;
12
using v8::FunctionTemplate;
13
using v8::HandleScope;
14
using v8::Just;
15
using v8::Local;
16
using v8::Maybe;
17
using v8::Nothing;
18
using v8::Object;
19
using v8::Value;
20
21
15
StreamPipe::StreamPipe(StreamBase* source,
22
                       StreamBase* sink,
23
15
                       Local<Object> obj)
24
15
    : AsyncWrap(source->stream_env(), obj, AsyncWrap::PROVIDER_STREAMPIPE) {
25
15
  MakeWeak();
26
27
15
  CHECK_NOT_NULL(sink);
28
15
  CHECK_NOT_NULL(source);
29
30
15
  source->PushStreamListener(&readable_listener_);
31
15
  sink->PushStreamListener(&writable_listener_);
32
33
15
  uses_wants_write_ = sink->HasWantsWrite();
34
15
}
35
36
60
StreamPipe::~StreamPipe() {
37
30
  Unpipe(true);
38
60
}
39
40
640
StreamBase* StreamPipe::source() {
41
640
  return static_cast<StreamBase*>(readable_listener_.stream());
42
}
43
44
231
StreamBase* StreamPipe::sink() {
45
231
  return static_cast<StreamBase*>(writable_listener_.stream());
46
}
47
48
29
void StreamPipe::Unpipe(bool is_in_deletion) {
49
29
  if (is_closed_)
50
15
    return;
51
52
  // Note that we possibly cannot use virtual methods on `source` and `sink`
53
  // here, because this function can be called from their destructors via
54
  // `OnStreamDestroy()`.
55
15
  if (!source_destroyed_)
56
15
    source()->ReadStop();
57
58
15
  is_closed_ = true;
59
15
  is_reading_ = false;
60
15
  source()->RemoveStreamListener(&readable_listener_);
61
15
  if (pending_writes_ == 0)
62
14
    sink()->RemoveStreamListener(&writable_listener_);
63
64
15
  if (is_in_deletion) return;
65
66
  // Delay the JS-facing part with SetImmediate, because this might be from
67
  // inside the garbage collector, so we can’t run JS here.
68
28
  HandleScope handle_scope(env()->isolate());
69
14
  BaseObjectPtr<StreamPipe> strong_ref{this};
70
14
  env()->SetImmediate([this, strong_ref](Environment* env) {
71
14
    HandleScope handle_scope(env->isolate());
72
14
    Context::Scope context_scope(env->context());
73
14
    Local<Object> object = this->object();
74
75
    Local<Value> onunpipe;
76
42
    if (!object->Get(env->context(), env->onunpipe_string()).ToLocal(&onunpipe))
77
      return;
78
28
    if (onunpipe->IsFunction() &&
79

56
        MakeCallback(onunpipe.As<Function>(), 0, nullptr).IsEmpty()) {
80
      return;
81
    }
82
83
    // Set all the links established in the constructor to `null`.
84
28
    Local<Value> null = Null(env->isolate());
85
86
    Local<Value> source_v;
87
    Local<Value> sink_v;
88
28
    if (!object->Get(env->context(), env->source_string()).ToLocal(&source_v) ||
89
42
        !object->Get(env->context(), env->sink_string()).ToLocal(&sink_v) ||
90


42
        !source_v->IsObject() || !sink_v->IsObject()) {
91
      return;
92
    }
93
94
28
    if (object->Set(env->context(), env->source_string(), null).IsNothing() ||
95
42
        object->Set(env->context(), env->sink_string(), null).IsNothing() ||
96
14
        source_v.As<Object>()
97
28
            ->Set(env->context(), env->pipe_target_string(), null)
98

42
            .IsNothing() ||
99
14
        sink_v.As<Object>()
100
42
            ->Set(env->context(), env->pipe_source_string(), null)
101
14
            .IsNothing()) {
102
      return;
103
    }
104
  });
105
}
106
107
207
uv_buf_t StreamPipe::ReadableListener::OnStreamAlloc(size_t suggested_size) {
108
207
  StreamPipe* pipe = ContainerOf(&StreamPipe::readable_listener_, this);
109
207
  size_t size = std::min(suggested_size, pipe->wanted_data_);
110
207
  CHECK_GT(size, 0);
111
207
  return pipe->env()->allocate_managed_buffer(size);
112
}
113
114
212
void StreamPipe::ReadableListener::OnStreamRead(ssize_t nread,
115
                                                const uv_buf_t& buf_) {
116
212
  StreamPipe* pipe = ContainerOf(&StreamPipe::readable_listener_, this);
117
212
  std::unique_ptr<BackingStore> bs = pipe->env()->release_managed_buffer(buf_);
118
212
  if (nread < 0) {
119
    // EOF or error; stop reading and pass the error to the previous listener
120
    // (which might end up in JS).
121
13
    pipe->is_eof_ = true;
122
    // Cache `sink()` here because the previous listener might do things
123
    // that eventually lead to an `Unpipe()` call.
124
13
    StreamBase* sink = pipe->sink();
125
13
    stream()->ReadStop();
126
13
    CHECK_NOT_NULL(previous_listener_);
127
13
    previous_listener_->OnStreamRead(nread, uv_buf_init(nullptr, 0));
128
    // If we’re not writing, close now. Otherwise, we’ll do that in
129
    // `OnStreamAfterWrite()`.
130
13
    if (pipe->pending_writes_ == 0) {
131
8
      sink->Shutdown();
132
8
      pipe->Unpipe();
133
    }
134
13
    return;
135
  }
136
137
199
  pipe->ProcessData(nread, std::move(bs));
138
}
139
140
199
void StreamPipe::ProcessData(size_t nread,
141
                             std::unique_ptr<BackingStore> bs) {
142

199
  CHECK(uses_wants_write_ || pending_writes_ == 0);
143
199
  uv_buf_t buffer = uv_buf_init(static_cast<char*>(bs->Data()), nread);
144
398
  StreamWriteResult res = sink()->Write(&buffer, 1);
145
199
  pending_writes_++;
146
199
  if (!res.async) {
147
    writable_listener_.OnStreamAfterWrite(nullptr, res.err);
148
  } else {
149
199
    is_reading_ = false;
150
199
    res.wrap->SetBackingStore(std::move(bs));
151
199
    if (source() != nullptr)
152
199
      source()->ReadStop();
153
  }
154
199
}
155
156
198
void StreamPipe::WritableListener::OnStreamAfterWrite(WriteWrap* w,
157
                                                      int status) {
158
198
  StreamPipe* pipe = ContainerOf(&StreamPipe::writable_listener_, this);
159
198
  pipe->pending_writes_--;
160
198
  if (pipe->is_closed_) {
161
    if (pipe->pending_writes_ == 0) {
162
      Environment* env = pipe->env();
163
      HandleScope handle_scope(env->isolate());
164
      Context::Scope context_scope(env->context());
165
      if (pipe->MakeCallback(env->oncomplete_string(), 0, nullptr).IsEmpty())
166
        return;
167
      stream()->RemoveStreamListener(this);
168
    }
169
    return;
170
  }
171
172
198
  if (pipe->is_eof_) {
173
10
    HandleScope handle_scope(pipe->env()->isolate());
174
    InternalCallbackScope callback_scope(pipe,
175
5
        InternalCallbackScope::kSkipTaskQueues);
176
5
    pipe->sink()->Shutdown();
177
5
    pipe->Unpipe();
178
5
    return;
179
  }
180
181
193
  if (status != 0) {
182
1
    CHECK_NOT_NULL(previous_listener_);
183
1
    StreamListener* prev = previous_listener_;
184
1
    pipe->Unpipe();
185
1
    prev->OnStreamAfterWrite(w, status);
186
1
    return;
187
  }
188
189
192
  if (!pipe->uses_wants_write_) {
190
    OnStreamWantsWrite(65536);
191
  }
192
}
193
194
void StreamPipe::WritableListener::OnStreamAfterShutdown(ShutdownWrap* w,
195
                                                         int status) {
196
  StreamPipe* pipe = ContainerOf(&StreamPipe::writable_listener_, this);
197
  CHECK_NOT_NULL(previous_listener_);
198
  StreamListener* prev = previous_listener_;
199
  pipe->Unpipe();
200
  prev->OnStreamAfterShutdown(w, status);
201
}
202
203
void StreamPipe::ReadableListener::OnStreamDestroy() {
204
  StreamPipe* pipe = ContainerOf(&StreamPipe::readable_listener_, this);
205
  pipe->source_destroyed_ = true;
206
  if (!pipe->is_eof_) {
207
    OnStreamRead(UV_EPIPE, uv_buf_init(nullptr, 0));
208
  }
209
}
210
211
void StreamPipe::WritableListener::OnStreamDestroy() {
212
  StreamPipe* pipe = ContainerOf(&StreamPipe::writable_listener_, this);
213
  pipe->sink_destroyed_ = true;
214
  pipe->is_eof_ = true;
215
  pipe->pending_writes_ = 0;
216
  pipe->Unpipe();
217
}
218
219
227
void StreamPipe::WritableListener::OnStreamWantsWrite(size_t suggested_size) {
220
227
  StreamPipe* pipe = ContainerOf(&StreamPipe::writable_listener_, this);
221
227
  pipe->wanted_data_ = suggested_size;
222

227
  if (pipe->is_reading_ || pipe->is_closed_)
223
15
    return;
224
424
  HandleScope handle_scope(pipe->env()->isolate());
225
  InternalCallbackScope callback_scope(pipe,
226
424
      InternalCallbackScope::kSkipTaskQueues);
227
212
  pipe->is_reading_ = true;
228
212
  pipe->source()->ReadStart();
229
}
230
231
uv_buf_t StreamPipe::WritableListener::OnStreamAlloc(size_t suggested_size) {
232
  CHECK_NOT_NULL(previous_listener_);
233
  return previous_listener_->OnStreamAlloc(suggested_size);
234
}
235
236
void StreamPipe::WritableListener::OnStreamRead(ssize_t nread,
237
                                                const uv_buf_t& buf) {
238
  CHECK_NOT_NULL(previous_listener_);
239
  return previous_listener_->OnStreamRead(nread, buf);
240
}
241
242
15
Maybe<StreamPipe*> StreamPipe::New(StreamBase* source,
243
                                   StreamBase* sink,
244
                                   Local<Object> obj) {
245
30
  std::unique_ptr<StreamPipe> stream_pipe(new StreamPipe(source, sink, obj));
246
247
  // Set up links between this object and the source/sink objects.
248
  // In particular, this makes sure that they are garbage collected as a group,
249
  // if that applies to the given streams (for example, Http2Streams use
250
  // weak references).
251
15
  Environment* env = source->stream_env();
252
45
  if (obj->Set(env->context(), env->source_string(), source->GetObject())
253
15
          .IsNothing()) {
254
    return Nothing<StreamPipe*>();
255
  }
256
15
  if (source->GetObject()
257
30
          ->Set(env->context(), env->pipe_target_string(), obj)
258
15
          .IsNothing()) {
259
    return Nothing<StreamPipe*>();
260
  }
261
45
  if (obj->Set(env->context(), env->sink_string(), sink->GetObject())
262
15
          .IsNothing()) {
263
    return Nothing<StreamPipe*>();
264
  }
265
15
  if (sink->GetObject()
266
30
          ->Set(env->context(), env->pipe_source_string(), obj)
267
15
          .IsNothing()) {
268
    return Nothing<StreamPipe*>();
269
  }
270
271
15
  return Just(stream_pipe.release());
272
}
273
274
15
void StreamPipe::New(const FunctionCallbackInfo<Value>& args) {
275
15
  CHECK(args.IsConstructCall());
276
15
  CHECK(args[0]->IsObject());
277
15
  CHECK(args[1]->IsObject());
278
30
  StreamBase* source = StreamBase::FromObject(args[0].As<Object>());
279
30
  StreamBase* sink = StreamBase::FromObject(args[1].As<Object>());
280
281
30
  if (StreamPipe::New(source, sink, args.This()).IsNothing()) return;
282
}
283
284
15
void StreamPipe::Start(const FunctionCallbackInfo<Value>& args) {
285
  StreamPipe* pipe;
286
15
  ASSIGN_OR_RETURN_UNWRAP(&pipe, args.Holder());
287
15
  pipe->is_closed_ = false;
288
15
  pipe->writable_listener_.OnStreamWantsWrite(65536);
289
}
290
291
void StreamPipe::Unpipe(const FunctionCallbackInfo<Value>& args) {
292
  StreamPipe* pipe;
293
  ASSIGN_OR_RETURN_UNWRAP(&pipe, args.Holder());
294
  pipe->Unpipe();
295
}
296
297
void StreamPipe::IsClosed(const FunctionCallbackInfo<Value>& args) {
298
  StreamPipe* pipe;
299
  ASSIGN_OR_RETURN_UNWRAP(&pipe, args.Holder());
300
  args.GetReturnValue().Set(pipe->is_closed_);
301
}
302
303
void StreamPipe::PendingWrites(const FunctionCallbackInfo<Value>& args) {
304
  StreamPipe* pipe;
305
  ASSIGN_OR_RETURN_UNWRAP(&pipe, args.Holder());
306
  args.GetReturnValue().Set(pipe->pending_writes_);
307
}
308
309
namespace {
310
311
463
void InitializeStreamPipe(Local<Object> target,
312
                          Local<Value> unused,
313
                          Local<Context> context,
314
                          void* priv) {
315
463
  Environment* env = Environment::GetCurrent(context);
316
317
  // Create FunctionTemplate for FileHandle::CloseReq
318
463
  Local<FunctionTemplate> pipe = env->NewFunctionTemplate(StreamPipe::New);
319
463
  env->SetProtoMethod(pipe, "unpipe", StreamPipe::Unpipe);
320
463
  env->SetProtoMethod(pipe, "start", StreamPipe::Start);
321
463
  env->SetProtoMethod(pipe, "isClosed", StreamPipe::IsClosed);
322
463
  env->SetProtoMethod(pipe, "pendingWrites", StreamPipe::PendingWrites);
323
463
  pipe->Inherit(AsyncWrap::GetConstructorTemplate(env));
324
926
  pipe->InstanceTemplate()->SetInternalFieldCount(
325
      StreamPipe::kInternalFieldCount);
326
463
  env->SetConstructorFunction(target, "StreamPipe", pipe);
327
463
}
328
329
}  // anonymous namespace
330
331
}  // namespace node
332
333
5274
NODE_MODULE_CONTEXT_AWARE_INTERNAL(stream_pipe,
334
                                   node::InitializeStreamPipe)