GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: stream_base.cc Lines: 323 346 93.4 %
Date: 2022-07-18 04:15:58 Branches: 149 212 70.3 %

Line Branch Exec Source
1
#include "stream_base.h"  // NOLINT(build/include_inline)
2
#include "stream_base-inl.h"
3
#include "stream_wrap.h"
4
5
#include "env-inl.h"
6
#include "js_stream.h"
7
#include "node.h"
8
#include "node_buffer.h"
9
#include "node_errors.h"
10
#include "node_external_reference.h"
11
#include "string_bytes.h"
12
#include "util-inl.h"
13
#include "v8.h"
14
15
#include <climits>  // INT_MAX
16
17
namespace node {
18
19
using v8::Array;
20
using v8::ArrayBuffer;
21
using v8::BackingStore;
22
using v8::ConstructorBehavior;
23
using v8::Context;
24
using v8::DontDelete;
25
using v8::DontEnum;
26
using v8::External;
27
using v8::Function;
28
using v8::FunctionCallbackInfo;
29
using v8::FunctionTemplate;
30
using v8::HandleScope;
31
using v8::Integer;
32
using v8::Isolate;
33
using v8::Local;
34
using v8::MaybeLocal;
35
using v8::Object;
36
using v8::PropertyAttribute;
37
using v8::ReadOnly;
38
using v8::SideEffectType;
39
using v8::Signature;
40
using v8::String;
41
using v8::Value;
42
43
template int StreamBase::WriteString<ASCII>(
44
    const FunctionCallbackInfo<Value>& args);
45
template int StreamBase::WriteString<UTF8>(
46
    const FunctionCallbackInfo<Value>& args);
47
template int StreamBase::WriteString<UCS2>(
48
    const FunctionCallbackInfo<Value>& args);
49
template int StreamBase::WriteString<LATIN1>(
50
    const FunctionCallbackInfo<Value>& args);
51
52
53
54999
int StreamBase::ReadStartJS(const FunctionCallbackInfo<Value>& args) {
54
54999
  return ReadStart();
55
}
56
57
58
13378
int StreamBase::ReadStopJS(const FunctionCallbackInfo<Value>& args) {
59
13378
  return ReadStop();
60
}
61
62
12
int StreamBase::UseUserBuffer(const FunctionCallbackInfo<Value>& args) {
63
12
  CHECK(Buffer::HasInstance(args[0]));
64
65
24
  uv_buf_t buf = uv_buf_init(Buffer::Data(args[0]), Buffer::Length(args[0]));
66
12
  PushStreamListener(new CustomBufferJSListener(buf));
67
12
  return 0;
68
}
69
70
32869
int StreamBase::Shutdown(const FunctionCallbackInfo<Value>& args) {
71
32869
  CHECK(args[0]->IsObject());
72
32869
  Local<Object> req_wrap_obj = args[0].As<Object>();
73
74
32869
  return Shutdown(req_wrap_obj);
75
}
76
77
86987
void StreamBase::SetWriteResult(const StreamWriteResult& res) {
78
86987
  env_->stream_base_state()[kBytesWritten] = res.bytes;
79
86987
  env_->stream_base_state()[kLastWriteWasAsync] = res.async;
80
86987
}
81
82
13465
int StreamBase::Writev(const FunctionCallbackInfo<Value>& args) {
83
13465
  Environment* env = Environment::GetCurrent(args);
84
13465
  Isolate* isolate = env->isolate();
85
13465
  Local<Context> context = env->context();
86
87
13465
  CHECK(args[0]->IsObject());
88
13465
  CHECK(args[1]->IsArray());
89
90
26930
  Local<Object> req_wrap_obj = args[0].As<Object>();
91
26930
  Local<Array> chunks = args[1].As<Array>();
92
13465
  bool all_buffers = args[2]->IsTrue();
93
94
  size_t count;
95
13465
  if (all_buffers)
96
319
    count = chunks->Length();
97
  else
98
13146
    count = chunks->Length() >> 1;
99
100
26930
  MaybeStackBuffer<uv_buf_t, 16> bufs(count);
101
102
13465
  size_t storage_size = 0;
103
  size_t offset;
104
105
13465
  if (!all_buffers) {
106
    // Determine storage size first
107
88455
    for (size_t i = 0; i < count; i++) {
108
      Local<Value> chunk;
109
150618
      if (!chunks->Get(context, i * 2).ToLocal(&chunk))
110
        return -1;
111
112
75309
      if (Buffer::HasInstance(chunk))
113
33017
        continue;
114
        // Buffer chunk, no additional storage required
115
116
      // String chunk
117
      Local<String> string;
118
84584
      if (!chunk->ToString(context).ToLocal(&string))
119
        return -1;
120
      Local<Value> next_chunk;
121
84584
      if (!chunks->Get(context, i * 2 + 1).ToLocal(&next_chunk))
122
        return -1;
123
42292
      enum encoding encoding = ParseEncoding(isolate, next_chunk);
124
      size_t chunk_size;
125
8197
      if ((encoding == UTF8 &&
126
8197
             string->Length() > 65535 &&
127

84612
             !StringBytes::Size(isolate, string, encoding).To(&chunk_size)) ||
128
84584
              !StringBytes::StorageSize(isolate, string, encoding)
129
42292
                  .To(&chunk_size)) {
130
        return -1;
131
      }
132
42292
      storage_size += chunk_size;
133
    }
134
135
13146
    if (storage_size > INT_MAX)
136
      return UV_ENOBUFS;
137
  } else {
138
27295
    for (size_t i = 0; i < count; i++) {
139
      Local<Value> chunk;
140
53952
      if (!chunks->Get(context, i).ToLocal(&chunk))
141
        return -1;
142
26976
      bufs[i].base = Buffer::Data(chunk);
143
26976
      bufs[i].len = Buffer::Length(chunk);
144
    }
145
  }
146
147
13465
  std::unique_ptr<BackingStore> bs;
148
13465
  if (storage_size > 0) {
149
13100
    NoArrayBufferZeroFillScope no_zero_fill_scope(env->isolate_data());
150
13100
    bs = ArrayBuffer::NewBackingStore(isolate, storage_size);
151
  }
152
153
13465
  offset = 0;
154
13465
  if (!all_buffers) {
155
88455
    for (size_t i = 0; i < count; i++) {
156
      Local<Value> chunk;
157
150618
      if (!chunks->Get(context, i * 2).ToLocal(&chunk))
158
        return -1;
159
160
      // Write buffer
161
75309
      if (Buffer::HasInstance(chunk)) {
162
33017
        bufs[i].base = Buffer::Data(chunk);
163
33017
        bufs[i].len = Buffer::Length(chunk);
164
33017
        continue;
165
      }
166
167
      // Write string
168
42292
      CHECK_LE(offset, storage_size);
169
      char* str_storage =
170
42292
          static_cast<char*>(bs ? bs->Data() : nullptr) + offset;
171
42292
      size_t str_size = (bs ? bs->ByteLength() : 0) - offset;
172
173
      Local<String> string;
174
84584
      if (!chunk->ToString(context).ToLocal(&string))
175
        return -1;
176
      Local<Value> next_chunk;
177
84584
      if (!chunks->Get(context, i * 2 + 1).ToLocal(&next_chunk))
178
        return -1;
179
42292
      enum encoding encoding = ParseEncoding(isolate, next_chunk);
180
42292
      str_size = StringBytes::Write(isolate,
181
                                    str_storage,
182
                                    str_size,
183
                                    string,
184
                                    encoding);
185
42292
      bufs[i].base = str_storage;
186
42292
      bufs[i].len = str_size;
187
42292
      offset += str_size;
188
    }
189
  }
190
191
13465
  StreamWriteResult res = Write(*bufs, count, nullptr, req_wrap_obj);
192
13465
  SetWriteResult(res);
193

13465
  if (res.wrap != nullptr && storage_size > 0)
194
341
    res.wrap->SetBackingStore(std::move(bs));
195
13465
  return res.err;
196
}
197
198
199
45232
int StreamBase::WriteBuffer(const FunctionCallbackInfo<Value>& args) {
200
45232
  CHECK(args[0]->IsObject());
201
202
45232
  Environment* env = Environment::GetCurrent(args);
203
204
45232
  if (!args[1]->IsUint8Array()) {
205
1
    node::THROW_ERR_INVALID_ARG_TYPE(env, "Second argument must be a buffer");
206
1
    return 0;
207
  }
208
209
90462
  Local<Object> req_wrap_obj = args[0].As<Object>();
210
  uv_buf_t buf;
211
45231
  buf.base = Buffer::Data(args[1]);
212
45231
  buf.len = Buffer::Length(args[1]);
213
214
45231
  uv_stream_t* send_handle = nullptr;
215
216

45231
  if (args[2]->IsObject() && IsIPCPipe()) {
217
    Local<Object> send_handle_obj = args[2].As<Object>();
218
219
    HandleWrap* wrap;
220
    ASSIGN_OR_RETURN_UNWRAP(&wrap, send_handle_obj, UV_EINVAL);
221
    send_handle = reinterpret_cast<uv_stream_t*>(wrap->GetHandle());
222
    // Reference LibuvStreamWrap instance to prevent it from being garbage
223
    // collected before `AfterWrite` is called.
224
    if (req_wrap_obj->Set(env->context(),
225
                          env->handle_string(),
226
                          send_handle_obj).IsNothing()) {
227
      return -1;
228
    }
229
  }
230
231
45231
  StreamWriteResult res = Write(&buf, 1, send_handle, req_wrap_obj);
232
45231
  SetWriteResult(res);
233
234
45231
  return res.err;
235
}
236
237
238
template <enum encoding enc>
239
56582
int StreamBase::WriteString(const FunctionCallbackInfo<Value>& args) {
240
56582
  Environment* env = Environment::GetCurrent(args);
241
56582
  Isolate* isolate = env->isolate();
242
56582
  CHECK(args[0]->IsObject());
243
113164
  CHECK(args[1]->IsString());
244
245
113164
  Local<Object> req_wrap_obj = args[0].As<Object>();
246
113164
  Local<String> string = args[1].As<String>();
247
  Local<Object> send_handle_obj;
248
56582
  if (args[2]->IsObject())
249
440
    send_handle_obj = args[2].As<Object>();
250
251
  // Compute the size of the storage that the string will be flattened into.
252
  // For UTF8 strings that are very long, go ahead and take the hit for
253
  // computing their actual size, rather than tripling the storage.
254
  size_t storage_size;
255
56582
  if ((enc == UTF8 &&
256
50052
         string->Length() > 65535 &&
257

106918
         !StringBytes::Size(isolate, string, enc).To(&storage_size)) ||
258

163216
          !StringBytes::StorageSize(isolate, string, enc).To(&storage_size)) {
259
    return -1;
260
  }
261
262
56582
  if (storage_size > INT_MAX)
263
    return UV_ENOBUFS;
264
265
  // Try writing immediately if write size isn't too big
266
  char stack_storage[16384];  // 16kb
267
  size_t data_size;
268
56582
  size_t synchronously_written = 0;
269
  uv_buf_t buf;
270
271
110958
  bool try_write = storage_size <= sizeof(stack_storage) &&
272

65182
                   (!IsIPCPipe() || send_handle_obj.IsEmpty());
273
56582
  if (try_write) {
274
54160
    data_size = StringBytes::Write(isolate,
275
                                   stack_storage,
276
                                   storage_size,
277
                                   string,
278
                                   enc);
279
54160
    buf = uv_buf_init(stack_storage, data_size);
280
281
54160
    uv_buf_t* bufs = &buf;
282
54160
    size_t count = 1;
283
54160
    const int err = DoTryWrite(&bufs, &count);
284
    // Keep track of the bytes written here, because we're taking a shortcut
285
    // by using `DoTryWrite()` directly instead of using the utilities
286
    // provided by `Write()`.
287
54160
    synchronously_written = count == 0 ? data_size : data_size - buf.len;
288
54160
    bytes_written_ += synchronously_written;
289
290
    // Immediate failure or success
291

54160
    if (err != 0 || count == 0) {
292
49606
      SetWriteResult(StreamWriteResult { false, err, nullptr, data_size, {} });
293
49606
      return err;
294
    }
295
296
    // Partial write
297
4554
    CHECK_EQ(count, 1);
298
  }
299
300
6976
  std::unique_ptr<BackingStore> bs;
301
302
6976
  if (try_write) {
303
    // Copy partial data
304
4554
    NoArrayBufferZeroFillScope no_zero_fill_scope(env->isolate_data());
305
4554
    bs = ArrayBuffer::NewBackingStore(isolate, buf.len);
306
4554
    memcpy(static_cast<char*>(bs->Data()), buf.base, buf.len);
307
4554
    data_size = buf.len;
308
  } else {
309
    // Write it
310
2422
    NoArrayBufferZeroFillScope no_zero_fill_scope(env->isolate_data());
311
2422
    bs = ArrayBuffer::NewBackingStore(isolate, storage_size);
312
2422
    data_size = StringBytes::Write(isolate,
313
2422
                                   static_cast<char*>(bs->Data()),
314
                                   storage_size,
315
                                   string,
316
                                   enc);
317
  }
318
319
6976
  CHECK_LE(data_size, storage_size);
320
321
6976
  buf = uv_buf_init(static_cast<char*>(bs->Data()), data_size);
322
323
6976
  uv_stream_t* send_handle = nullptr;
324
325

7200
  if (IsIPCPipe() && !send_handle_obj.IsEmpty()) {
326
    HandleWrap* wrap;
327
220
    ASSIGN_OR_RETURN_UNWRAP(&wrap, send_handle_obj, UV_EINVAL);
328
220
    send_handle = reinterpret_cast<uv_stream_t*>(wrap->GetHandle());
329
    // Reference LibuvStreamWrap instance to prevent it from being garbage
330
    // collected before `AfterWrite` is called.
331
440
    if (req_wrap_obj->Set(env->context(),
332
                          env->handle_string(),
333
220
                          send_handle_obj).IsNothing()) {
334
      return -1;
335
    }
336
  }
337
338
6976
  StreamWriteResult res = Write(&buf, 1, send_handle, req_wrap_obj);
339
6976
  res.bytes += synchronously_written;
340
341
6976
  SetWriteResult(res);
342
6976
  if (res.wrap != nullptr)
343
6932
    res.wrap->SetBackingStore(std::move(bs));
344
345
6976
  return res.err;
346
}
347
348
349
63618
MaybeLocal<Value> StreamBase::CallJSOnreadMethod(ssize_t nread,
350
                                                 Local<ArrayBuffer> ab,
351
                                                 size_t offset,
352
                                                 StreamBaseJSChecks checks) {
353
63618
  Environment* env = env_;
354
355
  DCHECK_EQ(static_cast<int32_t>(nread), nread);
356
  DCHECK_LE(offset, INT32_MAX);
357
358
63618
  if (checks == DONT_SKIP_NREAD_CHECKS) {
359
61528
    if (ab.IsEmpty()) {
360
      DCHECK_EQ(offset, 0);
361
      DCHECK_LE(nread, 0);
362
    } else {
363
      DCHECK_GE(nread, 0);
364
    }
365
  }
366
367
63618
  env->stream_base_state()[kReadBytesOrError] = static_cast<int32_t>(nread);
368
63618
  env->stream_base_state()[kArrayBufferOffset] = offset;
369
370
  Local<Value> argv[] = {
371
106150
    ab.IsEmpty() ? Undefined(env->isolate()).As<Value>() : ab.As<Value>()
372
63618
  };
373
374
63618
  AsyncWrap* wrap = GetAsyncWrap();
375
63618
  CHECK_NOT_NULL(wrap);
376
63618
  Local<Value> onread = wrap->object()->GetInternalField(
377
127236
      StreamBase::kOnReadFunctionField);
378
63618
  CHECK(onread->IsFunction());
379
127236
  return wrap->MakeCallback(onread.As<Function>(), arraysize(argv), argv);
380
}
381
382
383
4503
bool StreamBase::IsIPCPipe() {
384
4503
  return false;
385
}
386
387
388
int StreamBase::GetFD() {
389
  return -1;
390
}
391
392
393
54250
Local<Object> StreamBase::GetObject() {
394
54250
  return GetAsyncWrap()->object();
395
}
396
397
39312
void StreamBase::AddMethod(Environment* env,
398
                           Local<Signature> signature,
399
                           enum PropertyAttribute attributes,
400
                           Local<FunctionTemplate> t,
401
                           JSMethodFunction* stream_method,
402
                           Local<String> string) {
403
  Local<FunctionTemplate> templ =
404
      env->NewFunctionTemplate(stream_method,
405
                               signature,
406
                               ConstructorBehavior::kThrow,
407
39312
                               SideEffectType::kHasNoSideEffect);
408
78624
  t->PrototypeTemplate()->SetAccessorProperty(
409
      string, templ, Local<FunctionTemplate>(), attributes);
410
39312
}
411
412
9828
void StreamBase::AddMethods(Environment* env, Local<FunctionTemplate> t) {
413
9828
  HandleScope scope(env->isolate());
414
415
9828
  enum PropertyAttribute attributes =
416
      static_cast<PropertyAttribute>(ReadOnly | DontDelete | DontEnum);
417
9828
  Local<Signature> sig = Signature::New(env->isolate(), t);
418
419
9828
  AddMethod(env, sig, attributes, t, GetFD, env->fd_string());
420
9828
  AddMethod(
421
      env, sig, attributes, t, GetExternal, env->external_stream_string());
422
9828
  AddMethod(env, sig, attributes, t, GetBytesRead, env->bytes_read_string());
423
9828
  AddMethod(
424
      env, sig, attributes, t, GetBytesWritten, env->bytes_written_string());
425
9828
  env->SetProtoMethod(t, "readStart", JSMethod<&StreamBase::ReadStartJS>);
426
9828
  env->SetProtoMethod(t, "readStop", JSMethod<&StreamBase::ReadStopJS>);
427
9828
  env->SetProtoMethod(t, "shutdown", JSMethod<&StreamBase::Shutdown>);
428
9828
  env->SetProtoMethod(t,
429
                      "useUserBuffer",
430
                      JSMethod<&StreamBase::UseUserBuffer>);
431
9828
  env->SetProtoMethod(t, "writev", JSMethod<&StreamBase::Writev>);
432
9828
  env->SetProtoMethod(t, "writeBuffer", JSMethod<&StreamBase::WriteBuffer>);
433
9828
  env->SetProtoMethod(
434
      t, "writeAsciiString", JSMethod<&StreamBase::WriteString<ASCII>>);
435
9828
  env->SetProtoMethod(
436
      t, "writeUtf8String", JSMethod<&StreamBase::WriteString<UTF8>>);
437
9828
  env->SetProtoMethod(
438
      t, "writeUcs2String", JSMethod<&StreamBase::WriteString<UCS2>>);
439
9828
  env->SetProtoMethod(
440
      t, "writeLatin1String", JSMethod<&StreamBase::WriteString<LATIN1>>);
441
39312
  t->PrototypeTemplate()->Set(FIXED_ONE_BYTE_STRING(env->isolate(),
442
                                                    "isStreamBase"),
443
                              True(env->isolate()));
444
29484
  t->PrototypeTemplate()->SetAccessor(
445
      FIXED_ONE_BYTE_STRING(env->isolate(), "onread"),
446
      BaseObject::InternalFieldGet<
447
          StreamBase::kOnReadFunctionField>,
448
      BaseObject::InternalFieldSet<
449
          StreamBase::kOnReadFunctionField,
450
          &Value::IsFunction>);
451
9828
}
452
453
10522
void StreamBase::RegisterExternalReferences(
454
    ExternalReferenceRegistry* registry) {
455
  // This function is called by a single thread during start up, so it is safe
456
  // to use a local static variable here.
457
  static bool is_registered = false;
458
10522
  if (is_registered) return;
459
5261
  registry->Register(GetFD);
460
5261
  registry->Register(GetExternal);
461
5261
  registry->Register(GetBytesRead);
462
5261
  registry->Register(GetBytesWritten);
463
5261
  registry->Register(JSMethod<&StreamBase::ReadStartJS>);
464
5261
  registry->Register(JSMethod<&StreamBase::ReadStopJS>);
465
5261
  registry->Register(JSMethod<&StreamBase::Shutdown>);
466
5261
  registry->Register(JSMethod<&StreamBase::UseUserBuffer>);
467
5261
  registry->Register(JSMethod<&StreamBase::Writev>);
468
5261
  registry->Register(JSMethod<&StreamBase::WriteBuffer>);
469
5261
  registry->Register(JSMethod<&StreamBase::WriteString<ASCII>>);
470
5261
  registry->Register(JSMethod<&StreamBase::WriteString<UTF8>>);
471
5261
  registry->Register(JSMethod<&StreamBase::WriteString<UCS2>>);
472
5261
  registry->Register(JSMethod<&StreamBase::WriteString<LATIN1>>);
473
5261
  registry->Register(
474
      BaseObject::InternalFieldGet<StreamBase::kOnReadFunctionField>);
475
5261
  registry->Register(
476
      BaseObject::InternalFieldSet<StreamBase::kOnReadFunctionField,
477
                                   &Value::IsFunction>);
478
5261
  is_registered = true;
479
}
480
481
2006
void StreamBase::GetFD(const FunctionCallbackInfo<Value>& args) {
482
  // Mimic implementation of StreamBase::GetFD() and UDPWrap::GetFD().
483
4012
  StreamBase* wrap = StreamBase::FromObject(args.This().As<Object>());
484
2006
  if (wrap == nullptr) return args.GetReturnValue().Set(UV_EINVAL);
485
486
2006
  if (!wrap->IsAlive()) return args.GetReturnValue().Set(UV_EINVAL);
487
488
4012
  args.GetReturnValue().Set(wrap->GetFD());
489
}
490
491
35185
void StreamBase::GetBytesRead(const FunctionCallbackInfo<Value>& args) {
492
70370
  StreamBase* wrap = StreamBase::FromObject(args.This().As<Object>());
493
35187
  if (wrap == nullptr) return args.GetReturnValue().Set(0);
494
495
  // uint64_t -> double. 53bits is enough for all real cases.
496
70368
  args.GetReturnValue().Set(static_cast<double>(wrap->bytes_read_));
497
}
498
499
35223
void StreamBase::GetBytesWritten(const FunctionCallbackInfo<Value>& args) {
500
70446
  StreamBase* wrap = StreamBase::FromObject(args.This().As<Object>());
501
35223
  if (wrap == nullptr) return args.GetReturnValue().Set(0);
502
503
  // uint64_t -> double. 53bits is enough for all real cases.
504
70446
  args.GetReturnValue().Set(static_cast<double>(wrap->bytes_written_));
505
}
506
507
2
void StreamBase::GetExternal(const FunctionCallbackInfo<Value>& args) {
508
4
  StreamBase* wrap = StreamBase::FromObject(args.This().As<Object>());
509
2
  if (wrap == nullptr) return;
510
511
2
  Local<External> ext = External::New(args.GetIsolate(), wrap);
512
4
  args.GetReturnValue().Set(ext);
513
}
514
515
template <int (StreamBase::*Method)(const FunctionCallbackInfo<Value>& args)>
516
376496
void StreamBase::JSMethod(const FunctionCallbackInfo<Value>& args) {
517
752992
  StreamBase* wrap = StreamBase::FromObject(args.Holder().As<Object>());
518
376500
  if (wrap == nullptr) return;
519
520
376504
  if (!wrap->IsAlive()) return args.GetReturnValue().Set(UV_EINVAL);
521
522
376492
  AsyncHooks::DefaultTriggerAsyncIdScope trigger_scope(wrap->GetAsyncWrap());
523
752984
  args.GetReturnValue().Set((wrap->*Method)(args));
524
}
525
526
11474
int StreamResource::DoTryWrite(uv_buf_t** bufs, size_t* count) {
527
  // No TryWrite by default
528
11474
  return 0;
529
}
530
531
532
52198
const char* StreamResource::Error() const {
533
52198
  return nullptr;
534
}
535
536
537
void StreamResource::ClearError() {
538
  // No-op
539
}
540
541
542
32796
uv_buf_t EmitToJSStreamListener::OnStreamAlloc(size_t suggested_size) {
543
32796
  CHECK_NOT_NULL(stream_);
544
32796
  Environment* env = static_cast<StreamBase*>(stream_)->stream_env();
545
32796
  return env->allocate_managed_buffer(suggested_size);
546
}
547
548
47698
void EmitToJSStreamListener::OnStreamRead(ssize_t nread, const uv_buf_t& buf_) {
549
47698
  CHECK_NOT_NULL(stream_);
550
47698
  StreamBase* stream = static_cast<StreamBase*>(stream_);
551
47698
  Environment* env = stream->stream_env();
552
47698
  Isolate* isolate = env->isolate();
553
47698
  HandleScope handle_scope(isolate);
554
47698
  Context::Scope context_scope(env->context());
555
47698
  std::unique_ptr<BackingStore> bs = env->release_managed_buffer(buf_);
556
557
47698
  if (nread <= 0)  {
558
19178
    if (nread < 0)
559
19170
      stream->CallJSOnreadMethod(nread, Local<ArrayBuffer>());
560
19119
    return;
561
  }
562
563
28520
  CHECK_LE(static_cast<size_t>(nread), bs->ByteLength());
564
28520
  bs = BackingStore::Reallocate(isolate, std::move(bs), nread);
565
566
28520
  stream->CallJSOnreadMethod(nread, ArrayBuffer::New(isolate, std::move(bs)));
567
}
568
569
570
2090
uv_buf_t CustomBufferJSListener::OnStreamAlloc(size_t suggested_size) {
571
2090
  return buffer_;
572
}
573
574
575
2096
void CustomBufferJSListener::OnStreamRead(ssize_t nread, const uv_buf_t& buf) {
576
2096
  CHECK_NOT_NULL(stream_);
577
578
2096
  StreamBase* stream = static_cast<StreamBase*>(stream_);
579
2096
  Environment* env = stream->stream_env();
580
2096
  HandleScope handle_scope(env->isolate());
581
2096
  Context::Scope context_scope(env->context());
582
583
  // To deal with the case where POLLHUP is received and UV_EOF is returned, as
584
  // libuv returns an empty buffer (on unices only).
585

2096
  if (nread == UV_EOF && buf.base == nullptr) {
586
6
    stream->CallJSOnreadMethod(nread, Local<ArrayBuffer>());
587
6
    return;
588
  }
589
590
2090
  CHECK_EQ(buf.base, buffer_.base);
591
592
  MaybeLocal<Value> ret = stream->CallJSOnreadMethod(nread,
593
                             Local<ArrayBuffer>(),
594
                             0,
595
2090
                             StreamBase::SKIP_NREAD_CHECKS);
596
  Local<Value> next_buf_v;
597

6270
  if (ret.ToLocal(&next_buf_v) && !next_buf_v->IsUndefined()) {
598
24
    buffer_.base = Buffer::Data(next_buf_v);
599
24
    buffer_.len = Buffer::Length(next_buf_v);
600
  }
601
}
602
603
604
13351
void ReportWritesToJSStreamListener::OnStreamAfterReqFinished(
605
    StreamReq* req_wrap, int status) {
606
13351
  StreamBase* stream = static_cast<StreamBase*>(stream_);
607
13351
  Environment* env = stream->stream_env();
608
13351
  if (env->is_stopping()) return;
609
12916
  AsyncWrap* async_wrap = req_wrap->GetAsyncWrap();
610
25831
  HandleScope handle_scope(env->isolate());
611
12916
  Context::Scope context_scope(env->context());
612
12916
  CHECK(!async_wrap->persistent().IsEmpty());
613
12916
  Local<Object> req_wrap_obj = async_wrap->object();
614
615
  Local<Value> argv[] = {
616
    Integer::New(env->isolate(), status),
617
12916
    stream->GetObject(),
618
    Undefined(env->isolate())
619
38748
  };
620
621
12916
  const char* msg = stream->Error();
622
12916
  if (msg != nullptr) {
623
    argv[2] = OneByteString(env->isolate(), msg);
624
    stream->ClearError();
625
  }
626
627
38748
  if (req_wrap_obj->Has(env->context(), env->oncomplete_string()).FromJust())
628
12915
    async_wrap->MakeCallback(env->oncomplete_string(), arraysize(argv), argv);
629
}
630
631
5952
void ReportWritesToJSStreamListener::OnStreamAfterWrite(
632
    WriteWrap* req_wrap, int status) {
633
5952
  OnStreamAfterReqFinished(req_wrap, status);
634
5951
}
635
636
7399
void ReportWritesToJSStreamListener::OnStreamAfterShutdown(
637
    ShutdownWrap* req_wrap, int status) {
638
7399
  OnStreamAfterReqFinished(req_wrap, status);
639
7399
}
640
641
7399
void ShutdownWrap::OnDone(int status) {
642
7399
  stream()->EmitAfterShutdown(this, status);
643
7399
  Dispose();
644
7399
}
645
646
9067
void WriteWrap::OnDone(int status) {
647
9067
  stream()->EmitAfterWrite(this, status);
648
9066
  Dispose();
649
9066
}
650
651
464140
StreamListener::~StreamListener() {
652
232070
  if (stream_ != nullptr)
653
195836
    stream_->RemoveStreamListener(this);
654
}
655
656
2635
void StreamListener::OnStreamAfterShutdown(ShutdownWrap* w, int status) {
657
2635
  CHECK_NOT_NULL(previous_listener_);
658
2635
  previous_listener_->OnStreamAfterShutdown(w, status);
659
2635
}
660
661
4580
void StreamListener::OnStreamAfterWrite(WriteWrap* w, int status) {
662
4580
  CHECK_NOT_NULL(previous_listener_);
663
4580
  previous_listener_->OnStreamAfterWrite(w, status);
664
4580
}
665
666
140882
StreamResource::~StreamResource() {
667
142140
  while (listener_ != nullptr) {
668
1258
    StreamListener* listener = listener_;
669
1258
    listener->OnStreamDestroy();
670
    // Remove the listener if it didn’t remove itself. This makes the logic
671
    // in `OnStreamDestroy()` implementations easier, because they
672
    // may call generic cleanup functions which can just remove the
673
    // listener unconditionally.
674
1258
    if (listener == listener_)
675
1234
      RemoveStreamListener(listener_);
676
  }
677
}
678
679
13
ShutdownWrap* StreamBase::CreateShutdownWrap(
680
    Local<Object> object) {
681
13
  auto* wrap = new SimpleShutdownWrap<AsyncWrap>(this, object);
682
13
  wrap->MakeWeak();
683
13
  return wrap;
684
}
685
686
9193
WriteWrap* StreamBase::CreateWriteWrap(
687
    Local<Object> object) {
688
9193
  auto* wrap = new SimpleWriteWrap<AsyncWrap>(this, object);
689
9193
  wrap->MakeWeak();
690
9193
  return wrap;
691
}
692
693
}  // namespace node