GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: stream_base.cc Lines: 322 345 93.3 %
Date: 2022-05-21 04:15:56 Branches: 147 210 70.0 %

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
55092
int StreamBase::ReadStartJS(const FunctionCallbackInfo<Value>& args) {
54
55092
  return ReadStart();
55
}
56
57
58
13293
int StreamBase::ReadStopJS(const FunctionCallbackInfo<Value>& args) {
59
13293
  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
35715
int StreamBase::Shutdown(const FunctionCallbackInfo<Value>& args) {
71
35715
  CHECK(args[0]->IsObject());
72
35715
  Local<Object> req_wrap_obj = args[0].As<Object>();
73
74
35715
  return Shutdown(req_wrap_obj);
75
}
76
77
88930
void StreamBase::SetWriteResult(const StreamWriteResult& res) {
78
88930
  env_->stream_base_state()[kBytesWritten] = res.bytes;
79
88930
  env_->stream_base_state()[kLastWriteWasAsync] = res.async;
80
88930
}
81
82
13708
int StreamBase::Writev(const FunctionCallbackInfo<Value>& args) {
83
13708
  Environment* env = Environment::GetCurrent(args);
84
13708
  Isolate* isolate = env->isolate();
85
13708
  Local<Context> context = env->context();
86
87
13708
  CHECK(args[0]->IsObject());
88
13708
  CHECK(args[1]->IsArray());
89
90
27416
  Local<Object> req_wrap_obj = args[0].As<Object>();
91
27416
  Local<Array> chunks = args[1].As<Array>();
92
13708
  bool all_buffers = args[2]->IsTrue();
93
94
  size_t count;
95
13708
  if (all_buffers)
96
319
    count = chunks->Length();
97
  else
98
13389
    count = chunks->Length() >> 1;
99
100
27416
  MaybeStackBuffer<uv_buf_t, 16> bufs(count);
101
102
13708
  size_t storage_size = 0;
103
  size_t offset;
104
105
13708
  if (!all_buffers) {
106
    // Determine storage size first
107
89343
    for (size_t i = 0; i < count; i++) {
108
      Local<Value> chunk;
109
151908
      if (!chunks->Get(context, i * 2).ToLocal(&chunk))
110
        return -1;
111
112
75954
      if (Buffer::HasInstance(chunk))
113
33236
        continue;
114
        // Buffer chunk, no additional storage required
115
116
      // String chunk
117
      Local<String> string;
118
85436
      if (!chunk->ToString(context).ToLocal(&string))
119
        return -1;
120
      Local<Value> next_chunk;
121
85436
      if (!chunks->Get(context, i * 2 + 1).ToLocal(&next_chunk))
122
        return -1;
123
42718
      enum encoding encoding = ParseEncoding(isolate, next_chunk);
124
      size_t chunk_size;
125
8357
      if ((encoding == UTF8 &&
126
8357
             string->Length() > 65535 &&
127

85464
             !StringBytes::Size(isolate, string, encoding).To(&chunk_size)) ||
128
85436
              !StringBytes::StorageSize(isolate, string, encoding)
129
42718
                  .To(&chunk_size)) {
130
        return -1;
131
      }
132
42718
      storage_size += chunk_size;
133
    }
134
135
13389
    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
13708
  std::unique_ptr<BackingStore> bs;
148
13708
  if (storage_size > 0) {
149
13343
    NoArrayBufferZeroFillScope no_zero_fill_scope(env->isolate_data());
150
13343
    bs = ArrayBuffer::NewBackingStore(isolate, storage_size);
151
  }
152
153
13708
  offset = 0;
154
13708
  if (!all_buffers) {
155
89343
    for (size_t i = 0; i < count; i++) {
156
      Local<Value> chunk;
157
151908
      if (!chunks->Get(context, i * 2).ToLocal(&chunk))
158
        return -1;
159
160
      // Write buffer
161
75954
      if (Buffer::HasInstance(chunk)) {
162
33236
        bufs[i].base = Buffer::Data(chunk);
163
33236
        bufs[i].len = Buffer::Length(chunk);
164
33236
        continue;
165
      }
166
167
      // Write string
168
42718
      CHECK_LE(offset, storage_size);
169
      char* str_storage =
170
42718
          static_cast<char*>(bs ? bs->Data() : nullptr) + offset;
171
42718
      size_t str_size = (bs ? bs->ByteLength() : 0) - offset;
172
173
      Local<String> string;
174
85436
      if (!chunk->ToString(context).ToLocal(&string))
175
        return -1;
176
      Local<Value> next_chunk;
177
85436
      if (!chunks->Get(context, i * 2 + 1).ToLocal(&next_chunk))
178
        return -1;
179
42718
      enum encoding encoding = ParseEncoding(isolate, next_chunk);
180
42718
      str_size = StringBytes::Write(isolate,
181
                                    str_storage,
182
                                    str_size,
183
                                    string,
184
                                    encoding);
185
42718
      bufs[i].base = str_storage;
186
42718
      bufs[i].len = str_size;
187
42718
      offset += str_size;
188
    }
189
  }
190
191
13708
  StreamWriteResult res = Write(*bufs, count, nullptr, req_wrap_obj);
192
13708
  SetWriteResult(res);
193

13708
  if (res.wrap != nullptr && storage_size > 0)
194
349
    res.wrap->SetBackingStore(std::move(bs));
195
13708
  return res.err;
196
}
197
198
199
46260
int StreamBase::WriteBuffer(const FunctionCallbackInfo<Value>& args) {
200
46260
  CHECK(args[0]->IsObject());
201
202
46260
  Environment* env = Environment::GetCurrent(args);
203
204
46260
  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
92518
  Local<Object> req_wrap_obj = args[0].As<Object>();
210
  uv_buf_t buf;
211
46259
  buf.base = Buffer::Data(args[1]);
212
46259
  buf.len = Buffer::Length(args[1]);
213
214
46259
  uv_stream_t* send_handle = nullptr;
215
216

46259
  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
46259
  StreamWriteResult res = Write(&buf, 1, send_handle, req_wrap_obj);
232
46259
  SetWriteResult(res);
233
234
46259
  return res.err;
235
}
236
237
238
template <enum encoding enc>
239
57926
int StreamBase::WriteString(const FunctionCallbackInfo<Value>& args) {
240
57926
  Environment* env = Environment::GetCurrent(args);
241
57926
  Isolate* isolate = env->isolate();
242
57926
  CHECK(args[0]->IsObject());
243
115852
  CHECK(args[1]->IsString());
244
245
115852
  Local<Object> req_wrap_obj = args[0].As<Object>();
246
115852
  Local<String> string = args[1].As<String>();
247
  Local<Object> send_handle_obj;
248
57926
  if (args[2]->IsObject())
249
412
    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
57926
  if ((enc == UTF8 &&
256
51246
         string->Length() > 65535 &&
257

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

167098
          !StringBytes::StorageSize(isolate, string, enc).To(&storage_size)) {
259
    return -1;
260
  }
261
262
57926
  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
57926
  size_t synchronously_written = 0;
269
  uv_buf_t buf;
270
271
113646
  bool try_write = storage_size <= sizeof(stack_storage) &&
272

66456
                   (!IsIPCPipe() || send_handle_obj.IsEmpty());
273
57926
  if (try_write) {
274
55518
    data_size = StringBytes::Write(isolate,
275
                                   stack_storage,
276
                                   storage_size,
277
                                   string,
278
                                   enc);
279
55518
    buf = uv_buf_init(stack_storage, data_size);
280
281
55518
    uv_buf_t* bufs = &buf;
282
55518
    size_t count = 1;
283
55518
    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
55518
    synchronously_written = count == 0 ? data_size : data_size - buf.len;
288
55518
    bytes_written_ += synchronously_written;
289
290
    // Immediate failure or success
291

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

7240
  if (IsIPCPipe() && !send_handle_obj.IsEmpty()) {
326
    HandleWrap* wrap;
327
206
    ASSIGN_OR_RETURN_UNWRAP(&wrap, send_handle_obj, UV_EINVAL);
328
206
    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
412
    if (req_wrap_obj->Set(env->context(),
332
                          env->handle_string(),
333
206
                          send_handle_obj).IsNothing()) {
334
      return -1;
335
    }
336
  }
337
338
7030
  StreamWriteResult res = Write(&buf, 1, send_handle, req_wrap_obj);
339
7030
  res.bytes += synchronously_written;
340
341
7030
  SetWriteResult(res);
342
7030
  if (res.wrap != nullptr)
343
6984
    res.wrap->SetBackingStore(std::move(bs));
344
345
7030
  return res.err;
346
}
347
348
349
65646
MaybeLocal<Value> StreamBase::CallJSOnreadMethod(ssize_t nread,
350
                                                 Local<ArrayBuffer> ab,
351
                                                 size_t offset,
352
                                                 StreamBaseJSChecks checks) {
353
65646
  Environment* env = env_;
354
355
  DCHECK_EQ(static_cast<int32_t>(nread), nread);
356
  DCHECK_LE(offset, INT32_MAX);
357
358
65646
  if (checks == DONT_SKIP_NREAD_CHECKS) {
359
63556
    if (ab.IsEmpty()) {
360
      DCHECK_EQ(offset, 0);
361
      DCHECK_LE(nread, 0);
362
    } else {
363
      DCHECK_GE(nread, 0);
364
    }
365
  }
366
367
65646
  env->stream_base_state()[kReadBytesOrError] = static_cast<int32_t>(nread);
368
65646
  env->stream_base_state()[kArrayBufferOffset] = offset;
369
370
  Local<Value> argv[] = {
371
110214
    ab.IsEmpty() ? Undefined(env->isolate()).As<Value>() : ab.As<Value>()
372
65646
  };
373
374
65646
  AsyncWrap* wrap = GetAsyncWrap();
375
65646
  CHECK_NOT_NULL(wrap);
376
65646
  Local<Value> onread = wrap->object()->GetInternalField(
377
131292
      StreamBase::kOnReadFunctionField);
378
65646
  CHECK(onread->IsFunction());
379
131292
  return wrap->MakeCallback(onread.As<Function>(), arraysize(argv), argv);
380
}
381
382
383
4575
bool StreamBase::IsIPCPipe() {
384
4575
  return false;
385
}
386
387
388
int StreamBase::GetFD() {
389
  return -1;
390
}
391
392
393
56380
Local<Object> StreamBase::GetObject() {
394
56380
  return GetAsyncWrap()->object();
395
}
396
397
35392
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
35392
                               SideEffectType::kHasNoSideEffect);
408
70784
  t->PrototypeTemplate()->SetAccessorProperty(
409
      string, templ, Local<FunctionTemplate>(), attributes);
410
35392
}
411
412
8848
void StreamBase::AddMethods(Environment* env, Local<FunctionTemplate> t) {
413
8848
  HandleScope scope(env->isolate());
414
415
8848
  enum PropertyAttribute attributes =
416
      static_cast<PropertyAttribute>(ReadOnly | DontDelete | DontEnum);
417
8848
  Local<Signature> sig = Signature::New(env->isolate(), t);
418
419
8848
  AddMethod(env, sig, attributes, t, GetFD, env->fd_string());
420
8848
  AddMethod(
421
      env, sig, attributes, t, GetExternal, env->external_stream_string());
422
8848
  AddMethod(env, sig, attributes, t, GetBytesRead, env->bytes_read_string());
423
8848
  AddMethod(
424
      env, sig, attributes, t, GetBytesWritten, env->bytes_written_string());
425
8848
  env->SetProtoMethod(t, "readStart", JSMethod<&StreamBase::ReadStartJS>);
426
8848
  env->SetProtoMethod(t, "readStop", JSMethod<&StreamBase::ReadStopJS>);
427
8848
  env->SetProtoMethod(t, "shutdown", JSMethod<&StreamBase::Shutdown>);
428
8848
  env->SetProtoMethod(t,
429
                      "useUserBuffer",
430
                      JSMethod<&StreamBase::UseUserBuffer>);
431
8848
  env->SetProtoMethod(t, "writev", JSMethod<&StreamBase::Writev>);
432
8848
  env->SetProtoMethod(t, "writeBuffer", JSMethod<&StreamBase::WriteBuffer>);
433
8848
  env->SetProtoMethod(
434
      t, "writeAsciiString", JSMethod<&StreamBase::WriteString<ASCII>>);
435
8848
  env->SetProtoMethod(
436
      t, "writeUtf8String", JSMethod<&StreamBase::WriteString<UTF8>>);
437
8848
  env->SetProtoMethod(
438
      t, "writeUcs2String", JSMethod<&StreamBase::WriteString<UCS2>>);
439
8848
  env->SetProtoMethod(
440
      t, "writeLatin1String", JSMethod<&StreamBase::WriteString<LATIN1>>);
441
35392
  t->PrototypeTemplate()->Set(FIXED_ONE_BYTE_STRING(env->isolate(),
442
                                                    "isStreamBase"),
443
                              True(env->isolate()));
444
26544
  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
8848
}
452
453
5184
void StreamBase::RegisterExternalReferences(
454
    ExternalReferenceRegistry* registry) {
455
5184
  registry->Register(GetFD);
456
5184
  registry->Register(GetExternal);
457
5184
  registry->Register(GetBytesRead);
458
5184
  registry->Register(GetBytesWritten);
459
5184
  registry->Register(JSMethod<&StreamBase::ReadStartJS>);
460
5184
  registry->Register(JSMethod<&StreamBase::ReadStopJS>);
461
5184
  registry->Register(JSMethod<&StreamBase::Shutdown>);
462
5184
  registry->Register(JSMethod<&StreamBase::UseUserBuffer>);
463
5184
  registry->Register(JSMethod<&StreamBase::Writev>);
464
5184
  registry->Register(JSMethod<&StreamBase::WriteBuffer>);
465
5184
  registry->Register(JSMethod<&StreamBase::WriteString<ASCII>>);
466
5184
  registry->Register(JSMethod<&StreamBase::WriteString<UTF8>>);
467
5184
  registry->Register(JSMethod<&StreamBase::WriteString<UCS2>>);
468
5184
  registry->Register(JSMethod<&StreamBase::WriteString<LATIN1>>);
469
5184
  registry->Register(
470
      BaseObject::InternalFieldGet<StreamBase::kOnReadFunctionField>);
471
5184
  registry->Register(
472
      BaseObject::InternalFieldSet<StreamBase::kOnReadFunctionField,
473
                                   &Value::IsFunction>);
474
5184
}
475
476
1349
void StreamBase::GetFD(const FunctionCallbackInfo<Value>& args) {
477
  // Mimic implementation of StreamBase::GetFD() and UDPWrap::GetFD().
478
2698
  StreamBase* wrap = StreamBase::FromObject(args.This().As<Object>());
479
1349
  if (wrap == nullptr) return args.GetReturnValue().Set(UV_EINVAL);
480
481
1349
  if (!wrap->IsAlive()) return args.GetReturnValue().Set(UV_EINVAL);
482
483
2698
  args.GetReturnValue().Set(wrap->GetFD());
484
}
485
486
36239
void StreamBase::GetBytesRead(const FunctionCallbackInfo<Value>& args) {
487
72478
  StreamBase* wrap = StreamBase::FromObject(args.This().As<Object>());
488
36241
  if (wrap == nullptr) return args.GetReturnValue().Set(0);
489
490
  // uint64_t -> double. 53bits is enough for all real cases.
491
72476
  args.GetReturnValue().Set(static_cast<double>(wrap->bytes_read_));
492
}
493
494
36273
void StreamBase::GetBytesWritten(const FunctionCallbackInfo<Value>& args) {
495
72546
  StreamBase* wrap = StreamBase::FromObject(args.This().As<Object>());
496
36273
  if (wrap == nullptr) return args.GetReturnValue().Set(0);
497
498
  // uint64_t -> double. 53bits is enough for all real cases.
499
72546
  args.GetReturnValue().Set(static_cast<double>(wrap->bytes_written_));
500
}
501
502
2
void StreamBase::GetExternal(const FunctionCallbackInfo<Value>& args) {
503
4
  StreamBase* wrap = StreamBase::FromObject(args.This().As<Object>());
504
2
  if (wrap == nullptr) return;
505
506
2
  Local<External> ext = External::New(args.GetIsolate(), wrap);
507
4
  args.GetReturnValue().Set(ext);
508
}
509
510
template <int (StreamBase::*Method)(const FunctionCallbackInfo<Value>& args)>
511
386090
void StreamBase::JSMethod(const FunctionCallbackInfo<Value>& args) {
512
772180
  StreamBase* wrap = StreamBase::FromObject(args.Holder().As<Object>());
513
386094
  if (wrap == nullptr) return;
514
515
386098
  if (!wrap->IsAlive()) return args.GetReturnValue().Set(UV_EINVAL);
516
517
386086
  AsyncHooks::DefaultTriggerAsyncIdScope trigger_scope(wrap->GetAsyncWrap());
518
772172
  args.GetReturnValue().Set((wrap->*Method)(args));
519
}
520
521
11651
int StreamResource::DoTryWrite(uv_buf_t** bufs, size_t* count) {
522
  // No TryWrite by default
523
11651
  return 0;
524
}
525
526
527
57808
const char* StreamResource::Error() const {
528
57808
  return nullptr;
529
}
530
531
532
void StreamResource::ClearError() {
533
  // No-op
534
}
535
536
537
35113
uv_buf_t EmitToJSStreamListener::OnStreamAlloc(size_t suggested_size) {
538
35113
  CHECK_NOT_NULL(stream_);
539
35113
  Environment* env = static_cast<StreamBase*>(stream_)->stream_env();
540
35113
  return env->allocate_managed_buffer(suggested_size);
541
}
542
543
49747
void EmitToJSStreamListener::OnStreamRead(ssize_t nread, const uv_buf_t& buf_) {
544
49747
  CHECK_NOT_NULL(stream_);
545
49747
  StreamBase* stream = static_cast<StreamBase*>(stream_);
546
49747
  Environment* env = stream->stream_env();
547
49747
  Isolate* isolate = env->isolate();
548
49747
  HandleScope handle_scope(isolate);
549
49747
  Context::Scope context_scope(env->context());
550
49747
  std::unique_ptr<BackingStore> bs = env->release_managed_buffer(buf_);
551
552
49747
  if (nread <= 0)  {
553
20196
    if (nread < 0)
554
20188
      stream->CallJSOnreadMethod(nread, Local<ArrayBuffer>());
555
20139
    return;
556
  }
557
558
29551
  CHECK_LE(static_cast<size_t>(nread), bs->ByteLength());
559
29551
  bs = BackingStore::Reallocate(isolate, std::move(bs), nread);
560
561
29551
  stream->CallJSOnreadMethod(nread, ArrayBuffer::New(isolate, std::move(bs)));
562
}
563
564
565
2090
uv_buf_t CustomBufferJSListener::OnStreamAlloc(size_t suggested_size) {
566
2090
  return buffer_;
567
}
568
569
570
2096
void CustomBufferJSListener::OnStreamRead(ssize_t nread, const uv_buf_t& buf) {
571
2096
  CHECK_NOT_NULL(stream_);
572
573
2096
  StreamBase* stream = static_cast<StreamBase*>(stream_);
574
2096
  Environment* env = stream->stream_env();
575
2096
  HandleScope handle_scope(env->isolate());
576
2096
  Context::Scope context_scope(env->context());
577
578
  // To deal with the case where POLLHUP is received and UV_EOF is returned, as
579
  // libuv returns an empty buffer (on unices only).
580

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

6270
  if (ret.ToLocal(&next_buf_v) && !next_buf_v->IsUndefined()) {
593
24
    buffer_.base = Buffer::Data(next_buf_v);
594
24
    buffer_.len = Buffer::Length(next_buf_v);
595
  }
596
}
597
598
599
15937
void ReportWritesToJSStreamListener::OnStreamAfterReqFinished(
600
    StreamReq* req_wrap, int status) {
601
15937
  StreamBase* stream = static_cast<StreamBase*>(stream_);
602
15937
  Environment* env = stream->stream_env();
603
15937
  if (env->is_stopping()) return;
604
15525
  AsyncWrap* async_wrap = req_wrap->GetAsyncWrap();
605
31049
  HandleScope handle_scope(env->isolate());
606
15525
  Context::Scope context_scope(env->context());
607
15525
  CHECK(!async_wrap->persistent().IsEmpty());
608
15525
  Local<Object> req_wrap_obj = async_wrap->object();
609
610
  Local<Value> argv[] = {
611
    Integer::New(env->isolate(), status),
612
15525
    stream->GetObject(),
613
    Undefined(env->isolate())
614
46575
  };
615
616
15525
  const char* msg = stream->Error();
617
15525
  if (msg != nullptr) {
618
    argv[2] = OneByteString(env->isolate(), msg);
619
    stream->ClearError();
620
  }
621
622
46575
  if (req_wrap_obj->Has(env->context(), env->oncomplete_string()).FromJust())
623
15524
    async_wrap->MakeCallback(env->oncomplete_string(), arraysize(argv), argv);
624
}
625
626
5926
void ReportWritesToJSStreamListener::OnStreamAfterWrite(
627
    WriteWrap* req_wrap, int status) {
628
5926
  OnStreamAfterReqFinished(req_wrap, status);
629
5925
}
630
631
10011
void ReportWritesToJSStreamListener::OnStreamAfterShutdown(
632
    ShutdownWrap* req_wrap, int status) {
633
10011
  OnStreamAfterReqFinished(req_wrap, status);
634
10011
}
635
636
10011
void ShutdownWrap::OnDone(int status) {
637
10011
  stream()->EmitAfterShutdown(this, status);
638
10011
  Dispose();
639
10011
}
640
641
9138
void WriteWrap::OnDone(int status) {
642
9138
  stream()->EmitAfterWrite(this, status);
643
9137
  Dispose();
644
9137
}
645
646
463536
StreamListener::~StreamListener() {
647
231768
  if (stream_ != nullptr)
648
195532
    stream_->RemoveStreamListener(this);
649
}
650
651
3926
void StreamListener::OnStreamAfterShutdown(ShutdownWrap* w, int status) {
652
3926
  CHECK_NOT_NULL(previous_listener_);
653
3926
  previous_listener_->OnStreamAfterShutdown(w, status);
654
3926
}
655
656
4621
void StreamListener::OnStreamAfterWrite(WriteWrap* w, int status) {
657
4621
  CHECK_NOT_NULL(previous_listener_);
658
4621
  previous_listener_->OnStreamAfterWrite(w, status);
659
4621
}
660
661
140196
StreamResource::~StreamResource() {
662
141446
  while (listener_ != nullptr) {
663
1250
    StreamListener* listener = listener_;
664
1250
    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
1250
    if (listener == listener_)
670
1226
      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
9331
WriteWrap* StreamBase::CreateWriteWrap(
682
    Local<Object> object) {
683
9331
  auto* wrap = new SimpleWriteWrap<AsyncWrap>(this, object);
684
9331
  wrap->MakeWeak();
685
9331
  return wrap;
686
}
687
688
}  // namespace node