GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: stream_base.cc Lines: 322 345 93.3 %
Date: 2022-04-11 04:20:14 Branches: 145 208 69.7 %

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

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

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

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

106024
         !StringBytes::Size(isolate, string, enc).To(&storage_size)) ||
259

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

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

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

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

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

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