GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_file.cc Lines: 1438 1517 94.8 %
Date: 2022-08-05 04:16:08 Branches: 798 1248 63.9 %

Line Branch Exec Source
1
// Copyright Joyent, Inc. and other Node contributors.
2
//
3
// Permission is hereby granted, free of charge, to any person obtaining a
4
// copy of this software and associated documentation files (the
5
// "Software"), to deal in the Software without restriction, including
6
// without limitation the rights to use, copy, modify, merge, publish,
7
// distribute, sublicense, and/or sell copies of the Software, and to permit
8
// persons to whom the Software is furnished to do so, subject to the
9
// following conditions:
10
//
11
// The above copyright notice and this permission notice shall be included
12
// in all copies or substantial portions of the Software.
13
//
14
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20
// USE OR OTHER DEALINGS IN THE SOFTWARE.
21
#include "node_file.h"  // NOLINT(build/include_inline)
22
#include "node_file-inl.h"
23
#include "aliased_buffer.h"
24
#include "memory_tracker-inl.h"
25
#include "node_buffer.h"
26
#include "node_external_reference.h"
27
#include "node_process-inl.h"
28
#include "node_stat_watcher.h"
29
#include "util-inl.h"
30
31
#include "tracing/trace_event.h"
32
33
#include "req_wrap-inl.h"
34
#include "stream_base-inl.h"
35
#include "string_bytes.h"
36
37
#include <fcntl.h>
38
#include <sys/types.h>
39
#include <sys/stat.h>
40
#include <cstring>
41
#include <cerrno>
42
#include <climits>
43
44
#if defined(__MINGW32__) || defined(_MSC_VER)
45
# include <io.h>
46
#endif
47
48
#include <memory>
49
50
namespace node {
51
52
namespace fs {
53
54
using v8::Array;
55
using v8::BigInt;
56
using v8::Boolean;
57
using v8::Context;
58
using v8::EscapableHandleScope;
59
using v8::Function;
60
using v8::FunctionCallbackInfo;
61
using v8::FunctionTemplate;
62
using v8::HandleScope;
63
using v8::Int32;
64
using v8::Integer;
65
using v8::Isolate;
66
using v8::Local;
67
using v8::MaybeLocal;
68
using v8::Number;
69
using v8::Object;
70
using v8::ObjectTemplate;
71
using v8::Promise;
72
using v8::String;
73
using v8::Symbol;
74
using v8::Undefined;
75
using v8::Value;
76
77
#ifndef S_ISDIR
78
# define S_ISDIR(mode)  (((mode) & S_IFMT) == S_IFDIR)
79
#endif
80
81
#ifdef __POSIX__
82
constexpr char kPathSeparator = '/';
83
#else
84
const char* const kPathSeparator = "\\/";
85
#endif
86
87
12
std::string Basename(const std::string& str, const std::string& extension) {
88
  // Remove everything leading up to and including the final path separator.
89
12
  std::string::size_type pos = str.find_last_of(kPathSeparator);
90
91
  // Starting index for the resulting string
92
12
  std::size_t start_pos = 0;
93
  // String size to return
94
12
  std::size_t str_size = str.size();
95
12
  if (pos != std::string::npos) {
96
12
    start_pos = pos + 1;
97
12
    str_size -= start_pos;
98
  }
99
100
  // Strip away the extension, if any.
101

24
  if (str_size >= extension.size() &&
102
12
      str.compare(str.size() - extension.size(),
103
        extension.size(), extension) == 0) {
104
    str_size -= extension.size();
105
  }
106
107
12
  return str.substr(start_pos, str_size);
108
}
109
110
193313
inline int64_t GetOffset(Local<Value> value) {
111
194413
  return IsSafeJsInt(value) ? value.As<Integer>()->Value() : -1;
112
}
113
114
#define TRACE_NAME(name) "fs.sync." #name
115
#define GET_TRACE_ENABLED                                                  \
116
  (*TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED                             \
117
  (TRACING_CATEGORY_NODE2(fs, sync)) != 0)
118
#define FS_SYNC_TRACE_BEGIN(syscall, ...)                                  \
119
  if (GET_TRACE_ENABLED)                                                   \
120
  TRACE_EVENT_BEGIN(TRACING_CATEGORY_NODE2(fs, sync), TRACE_NAME(syscall), \
121
  ##__VA_ARGS__);
122
#define FS_SYNC_TRACE_END(syscall, ...)                                    \
123
  if (GET_TRACE_ENABLED)                                                   \
124
  TRACE_EVENT_END(TRACING_CATEGORY_NODE2(fs, sync), TRACE_NAME(syscall),   \
125
  ##__VA_ARGS__);
126
127
// We sometimes need to convert a C++ lambda function to a raw C-style function.
128
// This is helpful, because ReqWrap::Dispatch() does not recognize lambda
129
// functions, and thus does not wrap them properly.
130
typedef void(*uv_fs_callback_t)(uv_fs_t*);
131
132
133
void FSContinuationData::MemoryInfo(MemoryTracker* tracker) const {
134
  tracker->TrackField("paths", paths_);
135
}
136
137
FileHandleReadWrap::~FileHandleReadWrap() = default;
138
139
FSReqBase::~FSReqBase() = default;
140
141
2
void FSReqBase::MemoryInfo(MemoryTracker* tracker) const {
142
2
  tracker->TrackField("continuation_data", continuation_data_);
143
2
}
144
145
// The FileHandle object wraps a file descriptor and will close it on garbage
146
// collection if necessary. If that happens, a process warning will be
147
// emitted (or a fatal exception will occur if the fd cannot be closed.)
148
1623
FileHandle::FileHandle(BindingData* binding_data,
149
1623
                       Local<Object> obj, int fd)
150
    : AsyncWrap(binding_data->env(), obj, AsyncWrap::PROVIDER_FILEHANDLE),
151
      StreamBase(env()),
152
      fd_(fd),
153
1623
      binding_data_(binding_data) {
154
1623
  MakeWeak();
155
1623
  StreamBase::AttachToObject(GetObject());
156
1623
}
157
158
1623
FileHandle* FileHandle::New(BindingData* binding_data,
159
                            int fd, Local<Object> obj) {
160
1623
  Environment* env = binding_data->env();
161
3231
  if (obj.IsEmpty() && !env->fd_constructor_template()
162
3231
                            ->NewInstance(env->context())
163
1608
                            .ToLocal(&obj)) {
164
    return nullptr;
165
  }
166
1623
  return new FileHandle(binding_data, obj, fd);
167
}
168
169
15
void FileHandle::New(const FunctionCallbackInfo<Value>& args) {
170
15
  BindingData* binding_data = Environment::GetBindingData<BindingData>(args);
171
15
  Environment* env = binding_data->env();
172
15
  CHECK(args.IsConstructCall());
173
15
  CHECK(args[0]->IsInt32());
174
175
  FileHandle* handle =
176
30
      FileHandle::New(binding_data, args[0].As<Int32>()->Value(), args.This());
177
15
  if (handle == nullptr) return;
178
30
  if (args[1]->IsNumber())
179
30
    handle->read_offset_ = args[1]->IntegerValue(env->context()).FromJust();
180
15
  if (args[2]->IsNumber())
181
30
    handle->read_length_ = args[2]->IntegerValue(env->context()).FromJust();
182
}
183
184
6324
FileHandle::~FileHandle() {
185
3162
  CHECK(!closing_);  // We should not be deleting while explicitly closing!
186
3162
  Close();           // Close synchronously and emit warning
187
3162
  CHECK(closed_);    // We have to be closed at the point
188
6324
}
189
190
int FileHandle::DoWrite(WriteWrap* w,
191
                        uv_buf_t* bufs,
192
                        size_t count,
193
                        uv_stream_t* send_handle) {
194
  return UV_ENOSYS;  // Not implemented (yet).
195
}
196
197
void FileHandle::MemoryInfo(MemoryTracker* tracker) const {
198
  tracker->TrackField("current_read", current_read_);
199
}
200
201
10
FileHandle::TransferMode FileHandle::GetTransferMode() const {
202

10
  return reading_ || closing_ || closed_ ?
203
10
      TransferMode::kUntransferable : TransferMode::kTransferable;
204
}
205
206
6
std::unique_ptr<worker::TransferData> FileHandle::TransferForMessaging() {
207
6
  CHECK_NE(GetTransferMode(), TransferMode::kUntransferable);
208
12
  auto ret = std::make_unique<TransferData>(fd_);
209
6
  closed_ = true;
210
6
  return ret;
211
}
212
213
6
FileHandle::TransferData::TransferData(int fd) : fd_(fd) {}
214
215
24
FileHandle::TransferData::~TransferData() {
216
12
  if (fd_ > 0) {
217
    uv_fs_t close_req;
218
8
    CHECK_NE(fd_, -1);
219
8
    CHECK_EQ(0, uv_fs_close(nullptr, &close_req, fd_, nullptr));
220
8
    uv_fs_req_cleanup(&close_req);
221
  }
222
24
}
223
224
2
BaseObjectPtr<BaseObject> FileHandle::TransferData::Deserialize(
225
    Environment* env,
226
    v8::Local<v8::Context> context,
227
    std::unique_ptr<worker::TransferData> self) {
228
2
  BindingData* bd = Environment::GetBindingData<BindingData>(context);
229
2
  if (bd == nullptr) return {};
230
231
2
  int fd = fd_;
232
2
  fd_ = -1;
233
2
  return BaseObjectPtr<BaseObject> { FileHandle::New(bd, fd) };
234
}
235
236
// Close the file descriptor if it hasn't already been closed. A process
237
// warning will be emitted using a SetImmediate to avoid calling back to
238
// JS during GC. If closing the fd fails at this point, a fatal exception
239
// will crash the process immediately.
240
1581
inline void FileHandle::Close() {
241

1581
  if (closed_ || closing_) return;
242
  uv_fs_t req;
243
21
  CHECK_NE(fd_, -1);
244
21
  int ret = uv_fs_close(env()->event_loop(), &req, fd_, nullptr);
245
21
  uv_fs_req_cleanup(&req);
246
247
  struct err_detail { int ret; int fd; };
248
249
21
  err_detail detail { ret, fd_ };
250
251
21
  AfterClose();
252
253
21
  if (ret < 0) {
254
    // Do not unref this
255
    env()->SetImmediate([detail](Environment* env) {
256
      char msg[70];
257
      snprintf(msg, arraysize(msg),
258
              "Closing file descriptor %d on garbage collection failed",
259
              detail.fd);
260
      // This exception will end up being fatal for the process because
261
      // it is being thrown from within the SetImmediate handler and
262
      // there is no JS stack to bubble it to. In other words, tearing
263
      // down the process is the only reasonable thing we can do here.
264
      HandleScope handle_scope(env->isolate());
265
      env->ThrowUVException(detail.ret, "close", msg);
266
    });
267
    return;
268
  }
269
270
  // If the close was successful, we still want to emit a process warning
271
  // to notify that the file descriptor was gc'd. We want to be noisy about
272
  // this because not explicitly closing the FileHandle is a bug.
273
274
21
  env()->SetImmediate([detail](Environment* env) {
275
    ProcessEmitWarning(env,
276
                       "Closing file descriptor %d on garbage collection",
277
4
                       detail.fd);
278
4
    if (env->filehandle_close_warning()) {
279
3
      env->set_filehandle_close_warning(false);
280
3
      USE(ProcessEmitDeprecationWarning(
281
          env,
282
          "Closing a FileHandle object on garbage collection is deprecated. "
283
          "Please close FileHandle objects explicitly using "
284
          "FileHandle.prototype.close(). In the future, an error will be "
285
          "thrown if a file descriptor is closed during garbage collection.",
286
3
          "DEP0137"));
287
    }
288
4
  }, CallbackFlags::kUnrefed);
289
}
290
291
1577
void FileHandle::CloseReq::Resolve() {
292
1577
  Isolate* isolate = env()->isolate();
293
3120
  HandleScope scope(isolate);
294
1577
  Context::Scope context_scope(env()->context());
295
1577
  InternalCallbackScope callback_scope(this);
296
3154
  Local<Promise> promise = promise_.Get(isolate);
297
1577
  Local<Promise::Resolver> resolver = promise.As<Promise::Resolver>();
298
4731
  resolver->Resolve(env()->context(), Undefined(isolate)).Check();
299
1543
}
300
301
1
void FileHandle::CloseReq::Reject(Local<Value> reason) {
302
1
  Isolate* isolate = env()->isolate();
303
2
  HandleScope scope(isolate);
304
1
  Context::Scope context_scope(env()->context());
305
1
  InternalCallbackScope callback_scope(this);
306
2
  Local<Promise> promise = promise_.Get(isolate);
307
1
  Local<Promise::Resolver> resolver = promise.As<Promise::Resolver>();
308
2
  resolver->Reject(env()->context(), reason).Check();
309
1
}
310
311
1586
FileHandle* FileHandle::CloseReq::file_handle() {
312
1586
  Isolate* isolate = env()->isolate();
313
1586
  HandleScope scope(isolate);
314
3172
  Local<Value> val = ref_.Get(isolate);
315
1586
  Local<Object> obj = val.As<Object>();
316
1586
  return Unwrap<FileHandle>(obj);
317
}
318
319
1586
FileHandle::CloseReq::CloseReq(Environment* env,
320
                               Local<Object> obj,
321
                               Local<Promise> promise,
322
1586
                               Local<Value> ref)
323
1586
  : ReqWrap(env, obj, AsyncWrap::PROVIDER_FILEHANDLECLOSEREQ) {
324
1586
  promise_.Reset(env->isolate(), promise);
325
1586
  ref_.Reset(env->isolate(), ref);
326
1586
}
327
328
12416
FileHandle::CloseReq::~CloseReq() {
329
3104
  uv_fs_req_cleanup(req());
330
3104
  promise_.Reset();
331
3104
  ref_.Reset();
332
6208
}
333
334
void FileHandle::CloseReq::MemoryInfo(MemoryTracker* tracker) const {
335
  tracker->TrackField("promise", promise_);
336
  tracker->TrackField("ref", ref_);
337
}
338
339
340
341
// Closes this FileHandle asynchronously and returns a Promise that will be
342
// resolved when the callback is invoked, or rejects with a UVException if
343
// there was a problem closing the fd. This is the preferred mechanism for
344
// closing the FD object even tho the object will attempt to close
345
// automatically on gc.
346
1586
MaybeLocal<Promise> FileHandle::ClosePromise() {
347
1586
  Isolate* isolate = env()->isolate();
348
1586
  EscapableHandleScope scope(isolate);
349
1586
  Local<Context> context = env()->context();
350
351
  Local<Value> close_resolver =
352
4758
      object()->GetInternalField(FileHandle::kClosingPromiseSlot);
353

4758
  if (!close_resolver.IsEmpty() && !close_resolver->IsUndefined()) {
354
    CHECK(close_resolver->IsPromise());
355
    return close_resolver.As<Promise>();
356
  }
357
358
1586
  CHECK(!closed_);
359
1586
  CHECK(!closing_);
360
1586
  CHECK(!reading_);
361
362
1586
  auto maybe_resolver = Promise::Resolver::New(context);
363
1586
  CHECK(!maybe_resolver.IsEmpty());
364
1586
  Local<Promise::Resolver> resolver = maybe_resolver.ToLocalChecked();
365
1586
  Local<Promise> promise = resolver.As<Promise>();
366
367
  Local<Object> close_req_obj;
368
1586
  if (!env()->fdclose_constructor_template()
369
3172
          ->NewInstance(env()->context()).ToLocal(&close_req_obj)) {
370
    return MaybeLocal<Promise>();
371
  }
372
1586
  closing_ = true;
373
3172
  object()->SetInternalField(FileHandle::kClosingPromiseSlot, promise);
374
375
3172
  CloseReq* req = new CloseReq(env(), close_req_obj, promise, object());
376
3172
  auto AfterClose = uv_fs_callback_t{[](uv_fs_t* req) {
377
1586
    std::unique_ptr<CloseReq> close(CloseReq::from_req(req));
378
1586
    CHECK_NOT_NULL(close);
379
1586
    close->file_handle()->AfterClose();
380
1586
    if (!close->env()->can_call_into_js()) return;
381
1578
    Isolate* isolate = close->env()->isolate();
382
1578
    if (req->result < 0) {
383
2
      HandleScope handle_scope(isolate);
384
2
      close->Reject(
385
1
          UVException(isolate, static_cast<int>(req->result), "close"));
386
    } else {
387
1577
      close->Resolve();
388
    }
389
  }};
390
1586
  CHECK_NE(fd_, -1);
391
1586
  int ret = req->Dispatch(uv_fs_close, fd_, AfterClose);
392
1586
  if (ret < 0) {
393
    req->Reject(UVException(isolate, ret, "close"));
394
    delete req;
395
  }
396
397
1586
  return scope.Escape(promise);
398
}
399
400
1586
void FileHandle::Close(const FunctionCallbackInfo<Value>& args) {
401
  FileHandle* fd;
402
1586
  ASSIGN_OR_RETURN_UNWRAP(&fd, args.Holder());
403
  Local<Promise> ret;
404
3172
  if (!fd->ClosePromise().ToLocal(&ret)) return;
405
3172
  args.GetReturnValue().Set(ret);
406
}
407
408
409
8
void FileHandle::ReleaseFD(const FunctionCallbackInfo<Value>& args) {
410
  FileHandle* fd;
411
8
  ASSIGN_OR_RETURN_UNWRAP(&fd, args.Holder());
412
  // Just act as if this FileHandle has been closed.
413
8
  fd->AfterClose();
414
}
415
416
417
1615
void FileHandle::AfterClose() {
418
1615
  closing_ = false;
419
1615
  closed_ = true;
420
1615
  fd_ = -1;
421

1615
  if (reading_ && !persistent().IsEmpty())
422
    EmitRead(UV_EOF);
423
1615
}
424
425
void FileHandleReadWrap::MemoryInfo(MemoryTracker* tracker) const {
426
  tracker->TrackField("buffer", buffer_);
427
  tracker->TrackField("file_handle", this->file_handle_);
428
}
429
430
18
FileHandleReadWrap::FileHandleReadWrap(FileHandle* handle, Local<Object> obj)
431
  : ReqWrap(handle->env(), obj, AsyncWrap::PROVIDER_FSREQCALLBACK),
432
18
    file_handle_(handle) {}
433
434
227
int FileHandle::ReadStart() {
435

227
  if (!IsAlive() || IsClosing())
436
    return UV_EOF;
437
438
227
  reading_ = true;
439
440
227
  if (current_read_)
441
9
    return 0;
442
443
436
  BaseObjectPtr<FileHandleReadWrap> read_wrap;
444
445
218
  if (read_length_ == 0) {
446
5
    EmitRead(UV_EOF);
447
5
    return 0;
448
  }
449
450
  {
451
    // Create a new FileHandleReadWrap or re-use one.
452
    // Either way, we need these two scopes for AsyncReset() or otherwise
453
    // for creating the new instance.
454
213
    HandleScope handle_scope(env()->isolate());
455
213
    AsyncHooks::DefaultTriggerAsyncIdScope trigger_scope(this);
456
457
213
    auto& freelist = binding_data_->file_handle_read_wrap_freelist;
458
213
    if (freelist.size() > 0) {
459
195
      read_wrap = std::move(freelist.back());
460
195
      freelist.pop_back();
461
      // Use a fresh async resource.
462
      // Lifetime is ensured via AsyncWrap::resource_.
463
195
      Local<Object> resource = Object::New(env()->isolate());
464
195
      USE(resource->Set(
465
585
          env()->context(), env()->handle_string(), read_wrap->object()));
466
195
      read_wrap->AsyncReset(resource);
467
195
      read_wrap->file_handle_ = this;
468
    } else {
469
      Local<Object> wrap_obj;
470
36
      if (!env()
471
18
               ->filehandlereadwrap_template()
472
18
               ->NewInstance(env()->context())
473
18
               .ToLocal(&wrap_obj)) {
474
        return UV_EBUSY;
475
      }
476
18
      read_wrap = MakeDetachedBaseObject<FileHandleReadWrap>(this, wrap_obj);
477
    }
478
  }
479
213
  int64_t recommended_read = 65536;
480

213
  if (read_length_ >= 0 && read_length_ <= recommended_read)
481
7
    recommended_read = read_length_;
482
483
213
  read_wrap->buffer_ = EmitAlloc(recommended_read);
484
485
213
  current_read_ = std::move(read_wrap);
486
487
426
  current_read_->Dispatch(uv_fs_read,
488
                          fd_,
489
213
                          &current_read_->buffer_,
490
                          1,
491
                          read_offset_,
492
213
                          uv_fs_callback_t{[](uv_fs_t* req) {
493
    FileHandle* handle;
494
    {
495
213
      FileHandleReadWrap* req_wrap = FileHandleReadWrap::from_req(req);
496
213
      handle = req_wrap->file_handle_;
497
213
      CHECK_EQ(handle->current_read_.get(), req_wrap);
498
    }
499
500
    // ReadStart() checks whether current_read_ is set to determine whether
501
    // a read is in progress. Moving it into a local variable makes sure that
502
    // the ReadStart() call below doesn't think we're still actively reading.
503
    BaseObjectPtr<FileHandleReadWrap> read_wrap =
504
426
        std::move(handle->current_read_);
505
506
213
    ssize_t result = req->result;
507
213
    uv_buf_t buffer = read_wrap->buffer_;
508
509
213
    uv_fs_req_cleanup(req);
510
511
    // Push the read wrap back to the freelist, or let it be destroyed
512
    // once we’re exiting the current scope.
513
213
    constexpr size_t kWantedFreelistFill = 100;
514
213
    auto& freelist = handle->binding_data_->file_handle_read_wrap_freelist;
515
213
    if (freelist.size() < kWantedFreelistFill) {
516
213
      read_wrap->Reset();
517
213
      freelist.emplace_back(std::move(read_wrap));
518
    }
519
520
213
    if (result >= 0) {
521
      // Read at most as many bytes as we originally planned to.
522

212
      if (handle->read_length_ >= 0 && handle->read_length_ < result)
523
        result = handle->read_length_;
524
525
      // If we read data and we have an expected length, decrease it by
526
      // how much we have read.
527
212
      if (handle->read_length_ >= 0)
528
9
        handle->read_length_ -= result;
529
530
      // If we have an offset, increase it by how much we have read.
531
212
      if (handle->read_offset_ >= 0)
532
204
        handle->read_offset_ += result;
533
    }
534
535
    // Reading 0 bytes from a file always means EOF, or that we reached
536
    // the end of the requested range.
537
213
    if (result == 0)
538
10
      result = UV_EOF;
539
540
213
    handle->EmitRead(result, buffer);
541
542
    // Start over, if EmitRead() didn’t tell us to stop.
543
213
    if (handle->reading_)
544
3
      handle->ReadStart();
545
213
  }});
546
547
213
  return 0;
548
}
549
550
230
int FileHandle::ReadStop() {
551
230
  reading_ = false;
552
230
  return 0;
553
}
554
555
typedef SimpleShutdownWrap<ReqWrap<uv_fs_t>> FileHandleCloseWrap;
556
557
3
ShutdownWrap* FileHandle::CreateShutdownWrap(Local<Object> object) {
558
3
  return new FileHandleCloseWrap(this, object);
559
}
560
561
3
int FileHandle::DoShutdown(ShutdownWrap* req_wrap) {
562

3
  if (closing_ || closed_) {
563
3
    req_wrap->Done(0);
564
3
    return 1;
565
  }
566
  FileHandleCloseWrap* wrap = static_cast<FileHandleCloseWrap*>(req_wrap);
567
  closing_ = true;
568
  CHECK_NE(fd_, -1);
569
  wrap->Dispatch(uv_fs_close, fd_, uv_fs_callback_t{[](uv_fs_t* req) {
570
    FileHandleCloseWrap* wrap = static_cast<FileHandleCloseWrap*>(
571
        FileHandleCloseWrap::from_req(req));
572
    FileHandle* handle = static_cast<FileHandle*>(wrap->stream());
573
    handle->AfterClose();
574
575
    int result = static_cast<int>(req->result);
576
    uv_fs_req_cleanup(req);
577
    wrap->Done(result);
578
  }});
579
580
  return 0;
581
}
582
583
584
4705
void FSReqCallback::Reject(Local<Value> reject) {
585
4705
  MakeCallback(env()->oncomplete_string(), 1, &reject);
586
4705
}
587
588
2518
void FSReqCallback::ResolveStat(const uv_stat_t* stat) {
589
2518
  Resolve(FillGlobalStatsArray(binding_data(), use_bigint(), stat));
590
2518
}
591
592
46945
void FSReqCallback::Resolve(Local<Value> value) {
593
  Local<Value> argv[2] {
594
    Null(env()->isolate()),
595
    value
596
46945
  };
597
  MakeCallback(env()->oncomplete_string(),
598
86907
               value->IsUndefined() ? 1 : arraysize(argv),
599
133852
               argv);
600
46941
}
601
602
51650
void FSReqCallback::SetReturnValue(const FunctionCallbackInfo<Value>& args) {
603
51650
  args.GetReturnValue().SetUndefined();
604
51650
}
605
606
51650
void NewFSReqCallback(const FunctionCallbackInfo<Value>& args) {
607
51650
  CHECK(args.IsConstructCall());
608
51650
  BindingData* binding_data = Environment::GetBindingData<BindingData>(args);
609
103300
  new FSReqCallback(binding_data, args.This(), args[0]->IsTrue());
610
51650
}
611
612
58558
FSReqAfterScope::FSReqAfterScope(FSReqBase* wrap, uv_fs_t* req)
613
    : wrap_(wrap),
614
      req_(req),
615
      handle_scope_(wrap->env()->isolate()),
616
58558
      context_scope_(wrap->env()->context()) {
617
58558
  CHECK_EQ(wrap_->req(), req);
618
58558
}
619
620
117108
FSReqAfterScope::~FSReqAfterScope() {
621
58554
  Clear();
622
58554
}
623
624
64603
void FSReqAfterScope::Clear() {
625
64603
  if (!wrap_) return;
626
627
58554
  uv_fs_req_cleanup(wrap_->req());
628
58554
  wrap_->Detach();
629
58554
  wrap_.reset();
630
}
631
632
// TODO(joyeecheung): create a normal context object, and
633
// construct the actual errors in the JS land using the context.
634
// The context should include fds for some fs APIs, currently they are
635
// missing in the error messages. The path, dest, syscall, fd, .etc
636
// can be put into the context before the binding is even invoked,
637
// the only information that has to come from the C++ layer is the
638
// error number (and possibly the syscall for abstraction),
639
// which is also why the errors should have been constructed
640
// in JS for more flexibility.
641
5905
void FSReqAfterScope::Reject(uv_fs_t* req) {
642
11810
  BaseObjectPtr<FSReqBase> wrap { wrap_ };
643
5905
  Local<Value> exception = UVException(wrap_->env()->isolate(),
644
5905
                                       static_cast<int>(req->result),
645
                                       wrap_->syscall(),
646
                                       nullptr,
647
                                       req->path,
648
5905
                                       wrap_->data());
649
5905
  Clear();
650
5905
  wrap->Reject(exception);
651
5905
}
652
653
58558
bool FSReqAfterScope::Proceed() {
654
58558
  if (!wrap_->env()->can_call_into_js()) {
655
796
    return false;
656
  }
657
658
57762
  if (req_->result < 0) {
659
5905
    Reject(req_);
660
5905
    return false;
661
  }
662
51857
  return true;
663
}
664
665
7323
void AfterNoArgs(uv_fs_t* req) {
666
7323
  FSReqBase* req_wrap = FSReqBase::from_req(req);
667
14643
  FSReqAfterScope after(req_wrap, req);
668
669
7323
  if (after.Proceed())
670
14298
    req_wrap->Resolve(Undefined(req_wrap->env()->isolate()));
671
7320
}
672
673
8715
void AfterStat(uv_fs_t* req) {
674
8715
  FSReqBase* req_wrap = FSReqBase::from_req(req);
675
17430
  FSReqAfterScope after(req_wrap, req);
676
677
8715
  if (after.Proceed()) {
678
4106
    req_wrap->ResolveStat(&req->statbuf);
679
  }
680
8715
}
681
682
38228
void AfterInteger(uv_fs_t* req) {
683
38228
  FSReqBase* req_wrap = FSReqBase::from_req(req);
684
76456
  FSReqAfterScope after(req_wrap, req);
685
686
38228
  int result = static_cast<int>(req->result);
687

38228
  if (result >= 0 && req_wrap->is_plain_open())
688
5447
    req_wrap->env()->AddUnmanagedFd(result);
689
690
38228
  if (after.Proceed())
691
76110
    req_wrap->Resolve(Integer::New(req_wrap->env()->isolate(), result));
692
38228
}
693
694
3329
void AfterOpenFileHandle(uv_fs_t* req) {
695
3329
  FSReqBase* req_wrap = FSReqBase::from_req(req);
696
3329
  FSReqAfterScope after(req_wrap, req);
697
698
3329
  if (after.Proceed()) {
699
1605
    FileHandle* fd = FileHandle::New(req_wrap->binding_data(),
700
1605
                                     static_cast<int>(req->result));
701
1605
    if (fd == nullptr) return;
702
3210
    req_wrap->Resolve(fd->object());
703
  }
704
}
705
706
// Reverse the logic applied by path.toNamespacedPath() to create a
707
// namespace-prefixed path.
708
505
void FromNamespacedPath(std::string* path) {
709
#ifdef _WIN32
710
  if (path->compare(0, 8, "\\\\?\\UNC\\", 8) == 0) {
711
    *path = path->substr(8);
712
    path->insert(0, "\\\\");
713
  } else if (path->compare(0, 4, "\\\\?\\", 4) == 0) {
714
    *path = path->substr(4);
715
  }
716
#endif
717
505
}
718
719
360
void AfterMkdirp(uv_fs_t* req) {
720
360
  FSReqBase* req_wrap = FSReqBase::from_req(req);
721
360
  FSReqAfterScope after(req_wrap, req);
722
360
  if (after.Proceed()) {
723
708
    std::string first_path(req_wrap->continuation_data()->first_path());
724
354
    if (first_path.empty())
725
252
      return req_wrap->Resolve(Undefined(req_wrap->env()->isolate()));
726
228
    FromNamespacedPath(&first_path);
727
    Local<Value> path;
728
    Local<Value> error;
729
228
    if (!StringBytes::Encode(req_wrap->env()->isolate(), first_path.c_str(),
730
                             req_wrap->encoding(),
731
456
                             &error).ToLocal(&path)) {
732
      return req_wrap->Reject(error);
733
    }
734
228
    return req_wrap->Resolve(path);
735
  }
736
}
737
738
6
void AfterStringPath(uv_fs_t* req) {
739
6
  FSReqBase* req_wrap = FSReqBase::from_req(req);
740
12
  FSReqAfterScope after(req_wrap, req);
741
742
  MaybeLocal<Value> link;
743
  Local<Value> error;
744
745
6
  if (after.Proceed()) {
746
    link = StringBytes::Encode(req_wrap->env()->isolate(),
747
                               req->path,
748
                               req_wrap->encoding(),
749
5
                               &error);
750
5
    if (link.IsEmpty())
751
      req_wrap->Reject(error);
752
    else
753
10
      req_wrap->Resolve(link.ToLocalChecked());
754
  }
755
6
}
756
757
64
void AfterStringPtr(uv_fs_t* req) {
758
64
  FSReqBase* req_wrap = FSReqBase::from_req(req);
759
127
  FSReqAfterScope after(req_wrap, req);
760
761
  MaybeLocal<Value> link;
762
  Local<Value> error;
763
764
64
  if (after.Proceed()) {
765
    link = StringBytes::Encode(req_wrap->env()->isolate(),
766
58
                               static_cast<const char*>(req->ptr),
767
                               req_wrap->encoding(),
768
58
                               &error);
769
58
    if (link.IsEmpty())
770
      req_wrap->Reject(error);
771
    else
772
116
      req_wrap->Resolve(link.ToLocalChecked());
773
  }
774
63
}
775
776
222
void AfterScanDir(uv_fs_t* req) {
777
222
  FSReqBase* req_wrap = FSReqBase::from_req(req);
778
222
  FSReqAfterScope after(req_wrap, req);
779
780
222
  if (!after.Proceed()) {
781
7
    return;
782
  }
783
784
215
  Environment* env = req_wrap->env();
785
215
  Isolate* isolate = env->isolate();
786
  Local<Value> error;
787
  int r;
788
789
215
  std::vector<Local<Value>> name_v;
790
215
  std::vector<Local<Value>> type_v;
791
792
215
  const bool with_file_types = req_wrap->with_file_types();
793
794
  for (;;) {
795
    uv_dirent_t ent;
796
797
7836
    r = uv_fs_scandir_next(req, &ent);
798
7836
    if (r == UV_EOF)
799
215
      break;
800
7621
    if (r != 0) {
801
      return req_wrap->Reject(
802
          UVException(isolate, r, nullptr, req_wrap->syscall(), req->path));
803
    }
804
805
    Local<Value> filename;
806
7621
    if (!StringBytes::Encode(isolate, ent.name, req_wrap->encoding(), &error)
807
7621
             .ToLocal(&filename)) {
808
      return req_wrap->Reject(error);
809
    }
810
7621
    name_v.push_back(filename);
811
812
7621
    if (with_file_types) type_v.emplace_back(Integer::New(isolate, ent.type));
813
7621
  }
814
815
215
  if (with_file_types) {
816
    Local<Value> result[] = {Array::New(isolate, name_v.data(), name_v.size()),
817
246
                             Array::New(isolate, type_v.data(), type_v.size())};
818
246
    req_wrap->Resolve(Array::New(isolate, result, arraysize(result)));
819
  } else {
820
184
    req_wrap->Resolve(Array::New(isolate, name_v.data(), name_v.size()));
821
  }
822
}
823
824
4058
void Access(const FunctionCallbackInfo<Value>& args) {
825
4058
  Environment* env = Environment::GetCurrent(args);
826
4058
  Isolate* isolate = env->isolate();
827
8116
  HandleScope scope(isolate);
828
829
4058
  const int argc = args.Length();
830
4058
  CHECK_GE(argc, 2);
831
832
4058
  CHECK(args[1]->IsInt32());
833
8116
  int mode = args[1].As<Int32>()->Value();
834
835
8116
  BufferValue path(isolate, args[0]);
836
4058
  CHECK_NOT_NULL(*path);
837
838
4058
  FSReqBase* req_wrap_async = GetReqWrap(args, 2);
839
4058
  if (req_wrap_async != nullptr) {  // access(path, mode, req)
840
44
    AsyncCall(env, req_wrap_async, args, "access", UTF8, AfterNoArgs,
841
              uv_fs_access, *path, mode);
842
  } else {  // access(path, mode, undefined, ctx)
843
4014
    CHECK_EQ(argc, 4);
844
8028
    FSReqWrapSync req_wrap_sync;
845

4016
    FS_SYNC_TRACE_BEGIN(access);
846
8028
    SyncCall(env, args[3], &req_wrap_sync, "access", uv_fs_access, *path, mode);
847

4016
    FS_SYNC_TRACE_END(access);
848
  }
849
4058
}
850
851
852
68114
void Close(const FunctionCallbackInfo<Value>& args) {
853
68114
  Environment* env = Environment::GetCurrent(args);
854
855
68114
  const int argc = args.Length();
856
68114
  CHECK_GE(argc, 2);
857
858
68114
  CHECK(args[0]->IsInt32());
859
136228
  int fd = args[0].As<Int32>()->Value();
860
68114
  env->RemoveUnmanagedFd(fd);
861
862
68114
  FSReqBase* req_wrap_async = GetReqWrap(args, 1);
863
68114
  if (req_wrap_async != nullptr) {  // close(fd, req)
864
5365
    AsyncCall(env, req_wrap_async, args, "close", UTF8, AfterNoArgs,
865
              uv_fs_close, fd);
866
  } else {  // close(fd, undefined, ctx)
867
62749
    CHECK_EQ(argc, 3);
868
125498
    FSReqWrapSync req_wrap_sync;
869

62806
    FS_SYNC_TRACE_BEGIN(close);
870
62749
    SyncCall(env, args[2], &req_wrap_sync, "close", uv_fs_close, fd);
871

62806
    FS_SYNC_TRACE_END(close);
872
  }
873
68114
}
874
875
876
// Used to speed up module loading. Returns an array [string, boolean]
877
60356
static void InternalModuleReadJSON(const FunctionCallbackInfo<Value>& args) {
878
60356
  Environment* env = Environment::GetCurrent(args);
879
60356
  Isolate* isolate = env->isolate();
880
60356
  uv_loop_t* loop = env->event_loop();
881
882
120712
  CHECK(args[0]->IsString());
883
60356
  node::Utf8Value path(isolate, args[0]);
884
885
60356
  if (strlen(*path) != path.length()) {
886
3
    args.GetReturnValue().Set(Array::New(isolate));
887
3
    return;  // Contains a nul byte.
888
  }
889
  uv_fs_t open_req;
890
60353
  const int fd = uv_fs_open(loop, &open_req, *path, O_RDONLY, 0, nullptr);
891
60353
  uv_fs_req_cleanup(&open_req);
892
893
60353
  if (fd < 0) {
894
54753
    args.GetReturnValue().Set(Array::New(isolate));
895
54753
    return;
896
  }
897
898
5600
  auto defer_close = OnScopeLeave([fd, loop]() {
899
    uv_fs_t close_req;
900
5600
    CHECK_EQ(0, uv_fs_close(loop, &close_req, fd, nullptr));
901
5600
    uv_fs_req_cleanup(&close_req);
902
5600
  });
903
904
5600
  const size_t kBlockSize = 32 << 10;
905
5600
  std::vector<char> chars;
906
5600
  int64_t offset = 0;
907
  ssize_t numchars;
908
  do {
909
5600
    const size_t start = chars.size();
910
5600
    chars.resize(start + kBlockSize);
911
912
    uv_buf_t buf;
913
5600
    buf.base = &chars[start];
914
5600
    buf.len = kBlockSize;
915
916
    uv_fs_t read_req;
917
5600
    numchars = uv_fs_read(loop, &read_req, fd, &buf, 1, offset, nullptr);
918
5600
    uv_fs_req_cleanup(&read_req);
919
920
5600
    if (numchars < 0) {
921
1
      args.GetReturnValue().Set(Array::New(isolate));
922
1
      return;
923
    }
924
5599
    offset += numchars;
925
5599
  } while (static_cast<size_t>(numchars) == kBlockSize);
926
927
5599
  size_t start = 0;
928

5599
  if (offset >= 3 && 0 == memcmp(&chars[0], "\xEF\xBB\xBF", 3)) {
929
1
    start = 3;  // Skip UTF-8 BOM.
930
  }
931
932
5599
  const size_t size = offset - start;
933
5599
  char* p = &chars[start];
934
5599
  char* pe = &chars[size];
935
  char* pos[2];
936
5599
  char** ppos = &pos[0];
937
938
92410
  while (p < pe) {
939
92394
    char c = *p++;
940

92394
    if (c == '\\' && p < pe && *p == '"') p++;
941
92394
    if (c != '"') continue;
942
13644
    *ppos++ = p;
943
13644
    if (ppos < &pos[2]) continue;
944
6822
    ppos = &pos[0];
945
946
6822
    char* s = &pos[0][0];
947
6822
    char* se = &pos[1][-1];  // Exclude quote.
948
6822
    size_t n = se - s;
949
950
6822
    if (n == 4) {
951
5575
      if (0 == memcmp(s, "main", 4)) break;
952
5536
      if (0 == memcmp(s, "name", 4)) break;
953
49
      if (0 == memcmp(s, "type", 4)) break;
954
1247
    } else if (n == 7) {
955
13
      if (0 == memcmp(s, "exports", 7)) break;
956
7
      if (0 == memcmp(s, "imports", 7)) break;
957
    }
958
  }
959
960
961
  Local<Value> return_value[] = {
962
5599
    String::NewFromUtf8(isolate,
963
5599
                        &chars[start],
964
                        v8::NewStringType::kNormal,
965
5599
                        size).ToLocalChecked(),
966
    Boolean::New(isolate, p < pe ? true : false)
967
16797
  };
968
11198
  args.GetReturnValue().Set(
969
    Array::New(isolate, return_value, arraysize(return_value)));
970
}
971
972
// Used to speed up module loading.  Returns 0 if the path refers to
973
// a file, 1 when it's a directory or < 0 on error (usually -ENOENT.)
974
// The speedup comes from not creating thousands of Stat and Error objects.
975
158463
static void InternalModuleStat(const FunctionCallbackInfo<Value>& args) {
976
158463
  Environment* env = Environment::GetCurrent(args);
977
978
316926
  CHECK(args[0]->IsString());
979
158463
  node::Utf8Value path(env->isolate(), args[0]);
980
981
  uv_fs_t req;
982
158463
  int rc = uv_fs_stat(env->event_loop(), &req, *path, nullptr);
983
158463
  if (rc == 0) {
984
79010
    const uv_stat_t* const s = static_cast<const uv_stat_t*>(req.ptr);
985
79010
    rc = !!(s->st_mode & S_IFDIR);
986
  }
987
158463
  uv_fs_req_cleanup(&req);
988
989
316926
  args.GetReturnValue().Set(rc);
990
158463
}
991
992
18146
static void Stat(const FunctionCallbackInfo<Value>& args) {
993
18146
  BindingData* binding_data = Environment::GetBindingData<BindingData>(args);
994
18146
  Environment* env = binding_data->env();
995
996
18146
  const int argc = args.Length();
997
18146
  CHECK_GE(argc, 2);
998
999
18146
  BufferValue path(env->isolate(), args[0]);
1000
18146
  CHECK_NOT_NULL(*path);
1001
1002
18146
  bool use_bigint = args[1]->IsTrue();
1003
18146
  FSReqBase* req_wrap_async = GetReqWrap(args, 2, use_bigint);
1004
18146
  if (req_wrap_async != nullptr) {  // stat(path, use_bigint, req)
1005
2693
    AsyncCall(env, req_wrap_async, args, "stat", UTF8, AfterStat,
1006
              uv_fs_stat, *path);
1007
  } else {  // stat(path, use_bigint, undefined, ctx)
1008
15453
    CHECK_EQ(argc, 4);
1009
15453
    FSReqWrapSync req_wrap_sync;
1010

15455
    FS_SYNC_TRACE_BEGIN(stat);
1011
30906
    int err = SyncCall(env, args[3], &req_wrap_sync, "stat", uv_fs_stat, *path);
1012

15455
    FS_SYNC_TRACE_END(stat);
1013
15453
    if (err != 0) {
1014
705
      return;  // error info is in ctx
1015
    }
1016
1017
    Local<Value> arr = FillGlobalStatsArray(binding_data, use_bigint,
1018
14748
        static_cast<const uv_stat_t*>(req_wrap_sync.req.ptr));
1019
29496
    args.GetReturnValue().Set(arr);
1020
  }
1021
}
1022
1023
122962
static void LStat(const FunctionCallbackInfo<Value>& args) {
1024
122962
  BindingData* binding_data = Environment::GetBindingData<BindingData>(args);
1025
122962
  Environment* env = binding_data->env();
1026
1027
122962
  const int argc = args.Length();
1028
122962
  CHECK_GE(argc, 3);
1029
1030
122962
  BufferValue path(env->isolate(), args[0]);
1031
122962
  CHECK_NOT_NULL(*path);
1032
1033
122962
  bool use_bigint = args[1]->IsTrue();
1034
122962
  FSReqBase* req_wrap_async = GetReqWrap(args, 2, use_bigint);
1035
122962
  if (req_wrap_async != nullptr) {  // lstat(path, use_bigint, req)
1036
4799
    AsyncCall(env, req_wrap_async, args, "lstat", UTF8, AfterStat,
1037
              uv_fs_lstat, *path);
1038
  } else {  // lstat(path, use_bigint, undefined, ctx)
1039
118163
    CHECK_EQ(argc, 4);
1040
118163
    FSReqWrapSync req_wrap_sync;
1041

118180
    FS_SYNC_TRACE_BEGIN(lstat);
1042
236326
    int err = SyncCall(env, args[3], &req_wrap_sync, "lstat", uv_fs_lstat,
1043
                       *path);
1044

118180
    FS_SYNC_TRACE_END(lstat);
1045
118163
    if (err != 0) {
1046
453
      return;  // error info is in ctx
1047
    }
1048
1049
    Local<Value> arr = FillGlobalStatsArray(binding_data, use_bigint,
1050
117710
        static_cast<const uv_stat_t*>(req_wrap_sync.req.ptr));
1051
235420
    args.GetReturnValue().Set(arr);
1052
  }
1053
}
1054
1055
57977
static void FStat(const FunctionCallbackInfo<Value>& args) {
1056
57977
  BindingData* binding_data = Environment::GetBindingData<BindingData>(args);
1057
57977
  Environment* env = binding_data->env();
1058
1059
57977
  const int argc = args.Length();
1060
57977
  CHECK_GE(argc, 2);
1061
1062
57977
  CHECK(args[0]->IsInt32());
1063
115954
  int fd = args[0].As<Int32>()->Value();
1064
1065
57977
  bool use_bigint = args[1]->IsTrue();
1066
57977
  FSReqBase* req_wrap_async = GetReqWrap(args, 2, use_bigint);
1067
57977
  if (req_wrap_async != nullptr) {  // fstat(fd, use_bigint, req)
1068
1225
    AsyncCall(env, req_wrap_async, args, "fstat", UTF8, AfterStat,
1069
              uv_fs_fstat, fd);
1070
  } else {  // fstat(fd, use_bigint, undefined, ctx)
1071
56752
    CHECK_EQ(argc, 4);
1072
56752
    FSReqWrapSync req_wrap_sync;
1073

56761
    FS_SYNC_TRACE_BEGIN(fstat);
1074
56752
    int err = SyncCall(env, args[3], &req_wrap_sync, "fstat", uv_fs_fstat, fd);
1075

56761
    FS_SYNC_TRACE_END(fstat);
1076
56752
    if (err != 0) {
1077
21
      return;  // error info is in ctx
1078
    }
1079
1080
    Local<Value> arr = FillGlobalStatsArray(binding_data, use_bigint,
1081
56731
        static_cast<const uv_stat_t*>(req_wrap_sync.req.ptr));
1082
113462
    args.GetReturnValue().Set(arr);
1083
  }
1084
}
1085
1086
356
static void Symlink(const FunctionCallbackInfo<Value>& args) {
1087
356
  Environment* env = Environment::GetCurrent(args);
1088
356
  Isolate* isolate = env->isolate();
1089
1090
356
  const int argc = args.Length();
1091
356
  CHECK_GE(argc, 4);
1092
1093
712
  BufferValue target(isolate, args[0]);
1094
356
  CHECK_NOT_NULL(*target);
1095
712
  BufferValue path(isolate, args[1]);
1096
356
  CHECK_NOT_NULL(*path);
1097
1098
356
  CHECK(args[2]->IsInt32());
1099
712
  int flags = args[2].As<Int32>()->Value();
1100
1101
356
  FSReqBase* req_wrap_async = GetReqWrap(args, 3);
1102
356
  if (req_wrap_async != nullptr) {  // symlink(target, path, flags, req)
1103
24
    AsyncDestCall(env, req_wrap_async, args, "symlink", *path, path.length(),
1104
                  UTF8, AfterNoArgs, uv_fs_symlink, *target, *path, flags);
1105
  } else {  // symlink(target, path, flags, undefinec, ctx)
1106
332
    CHECK_EQ(argc, 5);
1107
664
    FSReqWrapSync req_wrap_sync;
1108

336
    FS_SYNC_TRACE_BEGIN(symlink);
1109
664
    SyncCall(env, args[4], &req_wrap_sync, "symlink",
1110
             uv_fs_symlink, *target, *path, flags);
1111

336
    FS_SYNC_TRACE_END(symlink);
1112
  }
1113
356
}
1114
1115
9
static void Link(const FunctionCallbackInfo<Value>& args) {
1116
9
  Environment* env = Environment::GetCurrent(args);
1117
9
  Isolate* isolate = env->isolate();
1118
1119
9
  const int argc = args.Length();
1120
9
  CHECK_GE(argc, 3);
1121
1122
18
  BufferValue src(isolate, args[0]);
1123
9
  CHECK_NOT_NULL(*src);
1124
1125
18
  BufferValue dest(isolate, args[1]);
1126
9
  CHECK_NOT_NULL(*dest);
1127
1128
9
  FSReqBase* req_wrap_async = GetReqWrap(args, 2);
1129
9
  if (req_wrap_async != nullptr) {  // link(src, dest, req)
1130
4
    AsyncDestCall(env, req_wrap_async, args, "link", *dest, dest.length(), UTF8,
1131
                  AfterNoArgs, uv_fs_link, *src, *dest);
1132
  } else {  // link(src, dest)
1133
5
    CHECK_EQ(argc, 4);
1134
10
    FSReqWrapSync req_wrap_sync;
1135

11
    FS_SYNC_TRACE_BEGIN(link);
1136
10
    SyncCall(env, args[3], &req_wrap_sync, "link",
1137
             uv_fs_link, *src, *dest);
1138

11
    FS_SYNC_TRACE_END(link);
1139
  }
1140
9
}
1141
1142
109
static void ReadLink(const FunctionCallbackInfo<Value>& args) {
1143
109
  Environment* env = Environment::GetCurrent(args);
1144
109
  Isolate* isolate = env->isolate();
1145
1146
109
  const int argc = args.Length();
1147
109
  CHECK_GE(argc, 3);
1148
1149
109
  BufferValue path(isolate, args[0]);
1150
109
  CHECK_NOT_NULL(*path);
1151
1152
109
  const enum encoding encoding = ParseEncoding(isolate, args[1], UTF8);
1153
1154
109
  FSReqBase* req_wrap_async = GetReqWrap(args, 2);
1155
109
  if (req_wrap_async != nullptr) {  // readlink(path, encoding, req)
1156
42
    AsyncCall(env, req_wrap_async, args, "readlink", encoding, AfterStringPtr,
1157
              uv_fs_readlink, *path);
1158
  } else {
1159
67
    CHECK_EQ(argc, 4);
1160
67
    FSReqWrapSync req_wrap_sync;
1161

69
    FS_SYNC_TRACE_BEGIN(readlink);
1162
134
    int err = SyncCall(env, args[3], &req_wrap_sync, "readlink",
1163
                       uv_fs_readlink, *path);
1164

69
    FS_SYNC_TRACE_END(readlink);
1165
67
    if (err < 0) {
1166
2
      return;  // syscall failed, no need to continue, error info is in ctx
1167
    }
1168
65
    const char* link_path = static_cast<const char*>(req_wrap_sync.req.ptr);
1169
1170
    Local<Value> error;
1171
    MaybeLocal<Value> rc = StringBytes::Encode(isolate,
1172
                                               link_path,
1173
                                               encoding,
1174
65
                                               &error);
1175
65
    if (rc.IsEmpty()) {
1176
      Local<Object> ctx = args[3].As<Object>();
1177
      ctx->Set(env->context(), env->error_string(), error).Check();
1178
      return;
1179
    }
1180
1181
130
    args.GetReturnValue().Set(rc.ToLocalChecked());
1182
  }
1183
}
1184
1185
6
static void Rename(const FunctionCallbackInfo<Value>& args) {
1186
6
  Environment* env = Environment::GetCurrent(args);
1187
6
  Isolate* isolate = env->isolate();
1188
1189
6
  const int argc = args.Length();
1190
6
  CHECK_GE(argc, 3);
1191
1192
12
  BufferValue old_path(isolate, args[0]);
1193
6
  CHECK_NOT_NULL(*old_path);
1194
12
  BufferValue new_path(isolate, args[1]);
1195
6
  CHECK_NOT_NULL(*new_path);
1196
1197
6
  FSReqBase* req_wrap_async = GetReqWrap(args, 2);
1198
6
  if (req_wrap_async != nullptr) {
1199
3
    AsyncDestCall(env, req_wrap_async, args, "rename", *new_path,
1200
                  new_path.length(), UTF8, AfterNoArgs, uv_fs_rename,
1201
                  *old_path, *new_path);
1202
  } else {
1203
3
    CHECK_EQ(argc, 4);
1204
6
    FSReqWrapSync req_wrap_sync;
1205

5
    FS_SYNC_TRACE_BEGIN(rename);
1206
6
    SyncCall(env, args[3], &req_wrap_sync, "rename", uv_fs_rename,
1207
             *old_path, *new_path);
1208

5
    FS_SYNC_TRACE_END(rename);
1209
  }
1210
6
}
1211
1212
69
static void FTruncate(const FunctionCallbackInfo<Value>& args) {
1213
69
  Environment* env = Environment::GetCurrent(args);
1214
1215
69
  const int argc = args.Length();
1216
69
  CHECK_GE(argc, 3);
1217
1218
69
  CHECK(args[0]->IsInt32());
1219
138
  const int fd = args[0].As<Int32>()->Value();
1220
1221
69
  CHECK(IsSafeJsInt(args[1]));
1222
138
  const int64_t len = args[1].As<Integer>()->Value();
1223
1224
69
  FSReqBase* req_wrap_async = GetReqWrap(args, 2);
1225
69
  if (req_wrap_async != nullptr) {
1226
54
    AsyncCall(env, req_wrap_async, args, "ftruncate", UTF8, AfterNoArgs,
1227
              uv_fs_ftruncate, fd, len);
1228
  } else {
1229
15
    CHECK_EQ(argc, 4);
1230
30
    FSReqWrapSync req_wrap_sync;
1231

17
    FS_SYNC_TRACE_BEGIN(ftruncate);
1232
15
    SyncCall(env, args[3], &req_wrap_sync, "ftruncate", uv_fs_ftruncate, fd,
1233
             len);
1234

17
    FS_SYNC_TRACE_END(ftruncate);
1235
  }
1236
69
}
1237
1238
7
static void Fdatasync(const FunctionCallbackInfo<Value>& args) {
1239
7
  Environment* env = Environment::GetCurrent(args);
1240
1241
7
  const int argc = args.Length();
1242
7
  CHECK_GE(argc, 2);
1243
1244
7
  CHECK(args[0]->IsInt32());
1245
14
  const int fd = args[0].As<Int32>()->Value();
1246
1247
7
  FSReqBase* req_wrap_async = GetReqWrap(args, 1);
1248
7
  if (req_wrap_async != nullptr) {
1249
4
    AsyncCall(env, req_wrap_async, args, "fdatasync", UTF8, AfterNoArgs,
1250
              uv_fs_fdatasync, fd);
1251
  } else {
1252
3
    CHECK_EQ(argc, 3);
1253
6
    FSReqWrapSync req_wrap_sync;
1254

5
    FS_SYNC_TRACE_BEGIN(fdatasync);
1255
3
    SyncCall(env, args[2], &req_wrap_sync, "fdatasync", uv_fs_fdatasync, fd);
1256

5
    FS_SYNC_TRACE_END(fdatasync);
1257
  }
1258
7
}
1259
1260
21
static void Fsync(const FunctionCallbackInfo<Value>& args) {
1261
21
  Environment* env = Environment::GetCurrent(args);
1262
1263
21
  const int argc = args.Length();
1264
21
  CHECK_GE(argc, 2);
1265
1266
21
  CHECK(args[0]->IsInt32());
1267
42
  const int fd = args[0].As<Int32>()->Value();
1268
1269
21
  FSReqBase* req_wrap_async = GetReqWrap(args, 1);
1270
21
  if (req_wrap_async != nullptr) {
1271
4
    AsyncCall(env, req_wrap_async, args, "fsync", UTF8, AfterNoArgs,
1272
              uv_fs_fsync, fd);
1273
  } else {
1274
17
    CHECK_EQ(argc, 3);
1275
34
    FSReqWrapSync req_wrap_sync;
1276

19
    FS_SYNC_TRACE_BEGIN(fsync);
1277
17
    SyncCall(env, args[2], &req_wrap_sync, "fsync", uv_fs_fsync, fd);
1278

19
    FS_SYNC_TRACE_END(fsync);
1279
  }
1280
21
}
1281
1282
2595
static void Unlink(const FunctionCallbackInfo<Value>& args) {
1283
2595
  Environment* env = Environment::GetCurrent(args);
1284
1285
2595
  const int argc = args.Length();
1286
2595
  CHECK_GE(argc, 2);
1287
1288
5190
  BufferValue path(env->isolate(), args[0]);
1289
2595
  CHECK_NOT_NULL(*path);
1290
1291
2595
  FSReqBase* req_wrap_async = GetReqWrap(args, 1);
1292
2595
  if (req_wrap_async != nullptr) {
1293
1029
    AsyncCall(env, req_wrap_async, args, "unlink", UTF8, AfterNoArgs,
1294
              uv_fs_unlink, *path);
1295
  } else {
1296
1566
    CHECK_EQ(argc, 3);
1297
3132
    FSReqWrapSync req_wrap_sync;
1298

1621
    FS_SYNC_TRACE_BEGIN(unlink);
1299
3132
    SyncCall(env, args[2], &req_wrap_sync, "unlink", uv_fs_unlink, *path);
1300

1621
    FS_SYNC_TRACE_END(unlink);
1301
  }
1302
2595
}
1303
1304
1900
static void RMDir(const FunctionCallbackInfo<Value>& args) {
1305
1900
  Environment* env = Environment::GetCurrent(args);
1306
1307
1900
  const int argc = args.Length();
1308
1900
  CHECK_GE(argc, 2);
1309
1310
3800
  BufferValue path(env->isolate(), args[0]);
1311
1900
  CHECK_NOT_NULL(*path);
1312
1313
1900
  FSReqBase* req_wrap_async = GetReqWrap(args, 1);  // rmdir(path, req)
1314
1900
  if (req_wrap_async != nullptr) {
1315
259
    AsyncCall(env, req_wrap_async, args, "rmdir", UTF8, AfterNoArgs,
1316
              uv_fs_rmdir, *path);
1317
  } else {  // rmdir(path, undefined, ctx)
1318
1641
    CHECK_EQ(argc, 3);
1319
3282
    FSReqWrapSync req_wrap_sync;
1320

1647
    FS_SYNC_TRACE_BEGIN(rmdir);
1321
3282
    SyncCall(env, args[2], &req_wrap_sync, "rmdir",
1322
             uv_fs_rmdir, *path);
1323

1647
    FS_SYNC_TRACE_END(rmdir);
1324
  }
1325
1900
}
1326
1327
6866
int MKDirpSync(uv_loop_t* loop,
1328
               uv_fs_t* req,
1329
               const std::string& path,
1330
               int mode,
1331
               uv_fs_cb cb) {
1332
6866
  FSReqWrapSync* req_wrap = ContainerOf(&FSReqWrapSync::req, req);
1333
1334
  // on the first iteration of algorithm, stash state information.
1335
6866
  if (req_wrap->continuation_data() == nullptr) {
1336
6866
    req_wrap->set_continuation_data(
1337
13732
        std::make_unique<FSContinuationData>(req, mode, cb));
1338
6866
    req_wrap->continuation_data()->PushPath(std::move(path));
1339
  }
1340
1341
13579
  while (req_wrap->continuation_data()->paths().size() > 0) {
1342
7016
    std::string next_path = req_wrap->continuation_data()->PopPath();
1343
7016
    int err = uv_fs_mkdir(loop, req, next_path.c_str(), mode, nullptr);
1344
    while (true) {
1345

7017
      switch (err) {
1346
        // Note: uv_fs_req_cleanup in terminal paths will be called by
1347
        // ~FSReqWrapSync():
1348
373
        case 0:
1349
373
          req_wrap->continuation_data()->MaybeSetFirstPath(next_path);
1350
373
          if (req_wrap->continuation_data()->paths().size() == 0) {
1351
299
            return 0;
1352
          }
1353
74
          break;
1354
2
        case UV_EACCES:
1355
        case UV_ENOSPC:
1356
        case UV_ENOTDIR:
1357
        case UV_EPERM: {
1358
2
          return err;
1359
        }
1360
76
        case UV_ENOENT: {
1361
          std::string dirname = next_path.substr(0,
1362
76
                                        next_path.find_last_of(kPathSeparator));
1363
76
          if (dirname != next_path) {
1364
75
            req_wrap->continuation_data()->PushPath(std::move(next_path));
1365
75
            req_wrap->continuation_data()->PushPath(std::move(dirname));
1366
1
          } else if (req_wrap->continuation_data()->paths().size() == 0) {
1367
1
            err = UV_EEXIST;
1368
1
            continue;
1369
          }
1370
75
          break;
1371
        }
1372
6566
        default:
1373
6566
          uv_fs_req_cleanup(req);
1374
6566
          int orig_err = err;
1375
6566
          err = uv_fs_stat(loop, req, next_path.c_str(), nullptr);
1376

6566
          if (err == 0 && !S_ISDIR(req->statbuf.st_mode)) {
1377
1
            uv_fs_req_cleanup(req);
1378

2
            if (orig_err == UV_EEXIST &&
1379
1
              req_wrap->continuation_data()->paths().size() > 0) {
1380
              return UV_ENOTDIR;
1381
            }
1382
1
            return UV_EEXIST;
1383
          }
1384
6565
          if (err < 0) return err;
1385
6564
          break;
1386
      }
1387
6713
      break;
1388
1
    }
1389
6713
    uv_fs_req_cleanup(req);
1390
  }
1391
1392
6563
  return 0;
1393
}
1394
1395
614
int MKDirpAsync(uv_loop_t* loop,
1396
                uv_fs_t* req,
1397
                const char* path,
1398
                int mode,
1399
                uv_fs_cb cb) {
1400
614
  FSReqBase* req_wrap = FSReqBase::from_req(req);
1401
  // on the first iteration of algorithm, stash state information.
1402
614
  if (req_wrap->continuation_data() == nullptr) {
1403
360
    req_wrap->set_continuation_data(
1404
720
        std::make_unique<FSContinuationData>(req, mode, cb));
1405
360
    req_wrap->continuation_data()->PushPath(std::move(path));
1406
  }
1407
1408
  // on each iteration of algorithm, mkdir directory on top of stack.
1409
614
  std::string next_path = req_wrap->continuation_data()->PopPath();
1410
614
  int err = uv_fs_mkdir(loop, req, next_path.c_str(), mode,
1411
614
                        uv_fs_callback_t{[](uv_fs_t* req) {
1412
614
    FSReqBase* req_wrap = FSReqBase::from_req(req);
1413
614
    Environment* env = req_wrap->env();
1414
614
    uv_loop_t* loop = env->event_loop();
1415
1228
    std::string path = req->path;
1416
614
    int err = static_cast<int>(req->result);
1417
1418
    while (true) {
1419

615
      switch (err) {
1420
        // Note: uv_fs_req_cleanup in terminal paths will be called by
1421
        // FSReqAfterScope::~FSReqAfterScope()
1422
237
        case 0: {
1423
237
          if (req_wrap->continuation_data()->paths().size() == 0) {
1424
228
            req_wrap->continuation_data()->MaybeSetFirstPath(path);
1425
228
            req_wrap->continuation_data()->Done(0);
1426
          } else {
1427
9
            req_wrap->continuation_data()->MaybeSetFirstPath(path);
1428
9
            uv_fs_req_cleanup(req);
1429
9
            MKDirpAsync(loop, req, path.c_str(),
1430
                        req_wrap->continuation_data()->mode(), nullptr);
1431
          }
1432
237
          break;
1433
        }
1434
3
        case UV_EACCES:
1435
        case UV_ENOTDIR:
1436
        case UV_EPERM: {
1437
3
          req_wrap->continuation_data()->Done(err);
1438
3
          break;
1439
        }
1440
128
        case UV_ENOENT: {
1441
          std::string dirname = path.substr(0,
1442
128
                                            path.find_last_of(kPathSeparator));
1443
128
          if (dirname != path) {
1444
127
            req_wrap->continuation_data()->PushPath(std::move(path));
1445
127
            req_wrap->continuation_data()->PushPath(std::move(dirname));
1446
1
          } else if (req_wrap->continuation_data()->paths().size() == 0) {
1447
1
            err = UV_EEXIST;
1448
1
            continue;
1449
          }
1450
127
          uv_fs_req_cleanup(req);
1451
127
          MKDirpAsync(loop, req, path.c_str(),
1452
                      req_wrap->continuation_data()->mode(), nullptr);
1453
127
          break;
1454
        }
1455
247
        default:
1456
247
          uv_fs_req_cleanup(req);
1457
          // Stash err for use in the callback.
1458
247
          req->data = reinterpret_cast<void*>(static_cast<intptr_t>(err));
1459
247
          int err = uv_fs_stat(loop, req, path.c_str(),
1460
247
                               uv_fs_callback_t{[](uv_fs_t* req) {
1461
247
            FSReqBase* req_wrap = FSReqBase::from_req(req);
1462
247
            int err = static_cast<int>(req->result);
1463

494
            if (reinterpret_cast<intptr_t>(req->data) == UV_EEXIST &&
1464
247
                  req_wrap->continuation_data()->paths().size() > 0) {
1465

118
              if (err == 0 && S_ISDIR(req->statbuf.st_mode)) {
1466
118
                Environment* env = req_wrap->env();
1467
118
                uv_loop_t* loop = env->event_loop();
1468
118
                std::string path = req->path;
1469
118
                uv_fs_req_cleanup(req);
1470
118
                MKDirpAsync(loop, req, path.c_str(),
1471
                            req_wrap->continuation_data()->mode(), nullptr);
1472
118
                return;
1473
              }
1474
              err = UV_ENOTDIR;
1475
            }
1476
            // verify that the path pointed to is actually a directory.
1477

129
            if (err == 0 && !S_ISDIR(req->statbuf.st_mode)) err = UV_EEXIST;
1478
129
            req_wrap->continuation_data()->Done(err);
1479
247
          }});
1480
247
          if (err < 0) req_wrap->continuation_data()->Done(err);
1481
247
          break;
1482
      }
1483
614
      break;
1484
1
    }
1485
614
  }});
1486
1487
614
  return err;
1488
}
1489
1490
283
int CallMKDirpSync(Environment* env, const FunctionCallbackInfo<Value>& args,
1491
                   FSReqWrapSync* req_wrap, const char* path, int mode) {
1492
283
  env->PrintSyncTrace();
1493
283
  int err = MKDirpSync(env->event_loop(), &req_wrap->req, path, mode,
1494
                       nullptr);
1495
283
  if (err < 0) {
1496
4
    v8::Local<v8::Context> context = env->context();
1497
4
    v8::Local<v8::Object> ctx_obj = args[4].As<v8::Object>();
1498
4
    v8::Isolate* isolate = env->isolate();
1499
4
    ctx_obj->Set(context,
1500
                 env->errno_string(),
1501
16
                 v8::Integer::New(isolate, err)).Check();
1502
4
    ctx_obj->Set(context,
1503
                 env->syscall_string(),
1504
16
                 OneByteString(isolate, "mkdir")).Check();
1505
  }
1506
283
  return err;
1507
}
1508
1509
1808
static void MKDir(const FunctionCallbackInfo<Value>& args) {
1510
1808
  Environment* env = Environment::GetCurrent(args);
1511
1512
1808
  const int argc = args.Length();
1513
1808
  CHECK_GE(argc, 4);
1514
1515
1808
  BufferValue path(env->isolate(), args[0]);
1516
1808
  CHECK_NOT_NULL(*path);
1517
1518
1808
  CHECK(args[1]->IsInt32());
1519
3616
  const int mode = args[1].As<Int32>()->Value();
1520
1521
1808
  CHECK(args[2]->IsBoolean());
1522
1808
  bool mkdirp = args[2]->IsTrue();
1523
1524
1808
  FSReqBase* req_wrap_async = GetReqWrap(args, 3);
1525
1808
  if (req_wrap_async != nullptr) {  // mkdir(path, mode, req)
1526

585
    AsyncCall(env, req_wrap_async, args, "mkdir", UTF8,
1527
              mkdirp ? AfterMkdirp : AfterNoArgs,
1528
              mkdirp ? MKDirpAsync : uv_fs_mkdir, *path, mode);
1529
  } else {  // mkdir(path, mode, undefined, ctx)
1530
1223
    CHECK_EQ(argc, 5);
1531
1223
    FSReqWrapSync req_wrap_sync;
1532

1227
    FS_SYNC_TRACE_BEGIN(mkdir);
1533
1223
    if (mkdirp) {
1534
283
      int err = CallMKDirpSync(env, args, &req_wrap_sync, *path, mode);
1535

562
      if (err == 0 &&
1536
279
          !req_wrap_sync.continuation_data()->first_path().empty()) {
1537
        Local<Value> error;
1538
277
        std::string first_path(req_wrap_sync.continuation_data()->first_path());
1539
277
        FromNamespacedPath(&first_path);
1540
        MaybeLocal<Value> path = StringBytes::Encode(env->isolate(),
1541
                                                     first_path.c_str(),
1542
277
                                                     UTF8, &error);
1543
277
        if (path.IsEmpty()) {
1544
          Local<Object> ctx = args[4].As<Object>();
1545
          ctx->Set(env->context(), env->error_string(), error).Check();
1546
          return;
1547
        }
1548
554
        args.GetReturnValue().Set(path.ToLocalChecked());
1549
      }
1550
    } else {
1551
1880
      SyncCall(env, args[4], &req_wrap_sync, "mkdir",
1552
               uv_fs_mkdir, *path, mode);
1553
    }
1554

1227
    FS_SYNC_TRACE_END(mkdir);
1555
  }
1556
}
1557
1558
42
static void RealPath(const FunctionCallbackInfo<Value>& args) {
1559
42
  Environment* env = Environment::GetCurrent(args);
1560
42
  Isolate* isolate = env->isolate();
1561
1562
42
  const int argc = args.Length();
1563
42
  CHECK_GE(argc, 3);
1564
1565
42
  BufferValue path(isolate, args[0]);
1566
42
  CHECK_NOT_NULL(*path);
1567
1568
42
  const enum encoding encoding = ParseEncoding(isolate, args[1], UTF8);
1569
1570
42
  FSReqBase* req_wrap_async = GetReqWrap(args, 2);
1571
42
  if (req_wrap_async != nullptr) {  // realpath(path, encoding, req)
1572
22
    AsyncCall(env, req_wrap_async, args, "realpath", encoding, AfterStringPtr,
1573
              uv_fs_realpath, *path);
1574
  } else {  // realpath(path, encoding, undefined, ctx)
1575
20
    CHECK_EQ(argc, 4);
1576
20
    FSReqWrapSync req_wrap_sync;
1577

22
    FS_SYNC_TRACE_BEGIN(realpath);
1578
40
    int err = SyncCall(env, args[3], &req_wrap_sync, "realpath",
1579
                       uv_fs_realpath, *path);
1580

22
    FS_SYNC_TRACE_END(realpath);
1581
20
    if (err < 0) {
1582
2
      return;  // syscall failed, no need to continue, error info is in ctx
1583
    }
1584
1585
18
    const char* link_path = static_cast<const char*>(req_wrap_sync.req.ptr);
1586
1587
    Local<Value> error;
1588
    MaybeLocal<Value> rc = StringBytes::Encode(isolate,
1589
                                               link_path,
1590
                                               encoding,
1591
18
                                               &error);
1592
18
    if (rc.IsEmpty()) {
1593
      Local<Object> ctx = args[3].As<Object>();
1594
      ctx->Set(env->context(), env->error_string(), error).Check();
1595
      return;
1596
    }
1597
1598
36
    args.GetReturnValue().Set(rc.ToLocalChecked());
1599
  }
1600
}
1601
1602
14005
static void ReadDir(const FunctionCallbackInfo<Value>& args) {
1603
14005
  Environment* env = Environment::GetCurrent(args);
1604
14005
  Isolate* isolate = env->isolate();
1605
1606
14005
  const int argc = args.Length();
1607
14005
  CHECK_GE(argc, 3);
1608
1609
14005
  BufferValue path(isolate, args[0]);
1610
14005
  CHECK_NOT_NULL(*path);
1611
1612
14005
  const enum encoding encoding = ParseEncoding(isolate, args[1], UTF8);
1613
1614
14005
  bool with_types = args[2]->IsTrue();
1615
1616
14005
  FSReqBase* req_wrap_async = GetReqWrap(args, 3);
1617
14005
  if (req_wrap_async != nullptr) {  // readdir(path, encoding, withTypes, req)
1618
222
    req_wrap_async->set_with_file_types(with_types);
1619
222
    AsyncCall(env,
1620
              req_wrap_async,
1621
              args,
1622
              "scandir",
1623
              encoding,
1624
              AfterScanDir,
1625
              uv_fs_scandir,
1626
              *path,
1627
              0 /*flags*/);
1628
  } else {  // readdir(path, encoding, withTypes, undefined, ctx)
1629
13783
    CHECK_EQ(argc, 5);
1630
13783
    FSReqWrapSync req_wrap_sync;
1631

13785
    FS_SYNC_TRACE_BEGIN(readdir);
1632
27566
    int err = SyncCall(env, args[4], &req_wrap_sync, "scandir",
1633
                       uv_fs_scandir, *path, 0 /*flags*/);
1634

13785
    FS_SYNC_TRACE_END(readdir);
1635
13783
    if (err < 0) {
1636
133
      return;  // syscall failed, no need to continue, error info is in ctx
1637
    }
1638
1639
13650
    CHECK_GE(req_wrap_sync.req.result, 0);
1640
    int r;
1641
13650
    std::vector<Local<Value>> name_v;
1642
13650
    std::vector<Local<Value>> type_v;
1643
1644
    for (;;) {
1645
      uv_dirent_t ent;
1646
1647
789709
      r = uv_fs_scandir_next(&(req_wrap_sync.req), &ent);
1648
789709
      if (r == UV_EOF)
1649
13650
        break;
1650
776059
      if (r != 0) {
1651
        Local<Object> ctx = args[4].As<Object>();
1652
        ctx->Set(env->context(), env->errno_string(),
1653
                 Integer::New(isolate, r)).Check();
1654
        ctx->Set(env->context(), env->syscall_string(),
1655
                 OneByteString(isolate, "readdir")).Check();
1656
        return;
1657
      }
1658
1659
      Local<Value> error;
1660
      MaybeLocal<Value> filename = StringBytes::Encode(isolate,
1661
                                                       ent.name,
1662
                                                       encoding,
1663
776059
                                                       &error);
1664
1665
776059
      if (filename.IsEmpty()) {
1666
        Local<Object> ctx = args[4].As<Object>();
1667
        ctx->Set(env->context(), env->error_string(), error).Check();
1668
        return;
1669
      }
1670
1671
776059
      name_v.push_back(filename.ToLocalChecked());
1672
1673
776059
      if (with_types) {
1674
50423
        type_v.emplace_back(Integer::New(isolate, ent.type));
1675
      }
1676
776059
    }
1677
1678
1679
13650
    Local<Array> names = Array::New(isolate, name_v.data(), name_v.size());
1680
13650
    if (with_types) {
1681
      Local<Value> result[] = {
1682
        names,
1683
        Array::New(isolate, type_v.data(), type_v.size())
1684
386
      };
1685
386
      args.GetReturnValue().Set(Array::New(isolate, result, arraysize(result)));
1686
    } else {
1687
26914
      args.GetReturnValue().Set(names);
1688
    }
1689
  }
1690
}
1691
1692
68832
static void Open(const FunctionCallbackInfo<Value>& args) {
1693
68832
  Environment* env = Environment::GetCurrent(args);
1694
1695
68832
  const int argc = args.Length();
1696
68832
  CHECK_GE(argc, 3);
1697
1698
137664
  BufferValue path(env->isolate(), args[0]);
1699
68832
  CHECK_NOT_NULL(*path);
1700
1701
68832
  CHECK(args[1]->IsInt32());
1702
137664
  const int flags = args[1].As<Int32>()->Value();
1703
1704
68832
  CHECK(args[2]->IsInt32());
1705
137664
  const int mode = args[2].As<Int32>()->Value();
1706
1707
68832
  FSReqBase* req_wrap_async = GetReqWrap(args, 3);
1708
68832
  if (req_wrap_async != nullptr) {  // open(path, flags, mode, req)
1709
5613
    req_wrap_async->set_is_plain_open(true);
1710
5613
    AsyncCall(env, req_wrap_async, args, "open", UTF8, AfterInteger,
1711
              uv_fs_open, *path, flags, mode);
1712
  } else {  // open(path, flags, mode, undefined, ctx)
1713
63219
    CHECK_EQ(argc, 5);
1714
63219
    FSReqWrapSync req_wrap_sync;
1715

63282
    FS_SYNC_TRACE_BEGIN(open);
1716
126438
    int result = SyncCall(env, args[4], &req_wrap_sync, "open",
1717
                          uv_fs_open, *path, flags, mode);
1718

63282
    FS_SYNC_TRACE_END(open);
1719
63219
    if (result >= 0) env->AddUnmanagedFd(result);
1720
126438
    args.GetReturnValue().Set(result);
1721
  }
1722
68832
}
1723
1724
3332
static void OpenFileHandle(const FunctionCallbackInfo<Value>& args) {
1725
3332
  BindingData* binding_data = Environment::GetBindingData<BindingData>(args);
1726
3332
  Environment* env = binding_data->env();
1727
3332
  Isolate* isolate = env->isolate();
1728
1729
3332
  const int argc = args.Length();
1730
3332
  CHECK_GE(argc, 3);
1731
1732
3332
  BufferValue path(isolate, args[0]);
1733
3332
  CHECK_NOT_NULL(*path);
1734
1735
3332
  CHECK(args[1]->IsInt32());
1736
6664
  const int flags = args[1].As<Int32>()->Value();
1737
1738
3332
  CHECK(args[2]->IsInt32());
1739
6664
  const int mode = args[2].As<Int32>()->Value();
1740
1741
3332
  FSReqBase* req_wrap_async = GetReqWrap(args, 3);
1742
3332
  if (req_wrap_async != nullptr) {  // openFileHandle(path, flags, mode, req)
1743
3331
    AsyncCall(env, req_wrap_async, args, "open", UTF8, AfterOpenFileHandle,
1744
              uv_fs_open, *path, flags, mode);
1745
  } else {  // openFileHandle(path, flags, mode, undefined, ctx)
1746
1
    CHECK_EQ(argc, 5);
1747
1
    FSReqWrapSync req_wrap_sync;
1748

1
    FS_SYNC_TRACE_BEGIN(open);
1749
2
    int result = SyncCall(env, args[4], &req_wrap_sync, "open",
1750
                          uv_fs_open, *path, flags, mode);
1751

1
    FS_SYNC_TRACE_END(open);
1752
1
    if (result < 0) {
1753
      return;  // syscall failed, no need to continue, error info is in ctx
1754
    }
1755
1
    FileHandle* fd = FileHandle::New(binding_data, result);
1756
1
    if (fd == nullptr) return;
1757
2
    args.GetReturnValue().Set(fd->object());
1758
  }
1759
}
1760
1761
219
static void CopyFile(const FunctionCallbackInfo<Value>& args) {
1762
219
  Environment* env = Environment::GetCurrent(args);
1763
219
  Isolate* isolate = env->isolate();
1764
1765
219
  const int argc = args.Length();
1766
219
  CHECK_GE(argc, 3);
1767
1768
438
  BufferValue src(isolate, args[0]);
1769
219
  CHECK_NOT_NULL(*src);
1770
1771
438
  BufferValue dest(isolate, args[1]);
1772
219
  CHECK_NOT_NULL(*dest);
1773
1774
219
  CHECK(args[2]->IsInt32());
1775
438
  const int flags = args[2].As<Int32>()->Value();
1776
1777
219
  FSReqBase* req_wrap_async = GetReqWrap(args, 3);
1778
219
  if (req_wrap_async != nullptr) {  // copyFile(src, dest, flags, req)
1779
204
    AsyncDestCall(env, req_wrap_async, args, "copyfile",
1780
102
                  *dest, dest.length(), UTF8, AfterNoArgs,
1781
                  uv_fs_copyfile, *src, *dest, flags);
1782
  } else {  // copyFile(src, dest, flags, undefined, ctx)
1783
117
    CHECK_EQ(argc, 5);
1784
234
    FSReqWrapSync req_wrap_sync;
1785

119
    FS_SYNC_TRACE_BEGIN(copyfile);
1786
234
    SyncCall(env, args[4], &req_wrap_sync, "copyfile",
1787
             uv_fs_copyfile, *src, *dest, flags);
1788

119
    FS_SYNC_TRACE_END(copyfile);
1789
  }
1790
219
}
1791
1792
1793
// Wrapper for write(2).
1794
//
1795
// bytesWritten = write(fd, buffer, offset, length, position, callback)
1796
// 0 fd        integer. file descriptor
1797
// 1 buffer    the data to write
1798
// 2 offset    where in the buffer to start from
1799
// 3 length    how much to write
1800
// 4 position  if integer, position to write at in the file.
1801
//             if null, write from the current position
1802
63519
static void WriteBuffer(const FunctionCallbackInfo<Value>& args) {
1803
63519
  Environment* env = Environment::GetCurrent(args);
1804
1805
63519
  const int argc = args.Length();
1806
63519
  CHECK_GE(argc, 4);
1807
1808
63519
  CHECK(args[0]->IsInt32());
1809
127038
  const int fd = args[0].As<Int32>()->Value();
1810
1811
63519
  CHECK(Buffer::HasInstance(args[1]));
1812
63519
  Local<Object> buffer_obj = args[1].As<Object>();
1813
63519
  char* buffer_data = Buffer::Data(buffer_obj);
1814
63519
  size_t buffer_length = Buffer::Length(buffer_obj);
1815
1816
63519
  CHECK(IsSafeJsInt(args[2]));
1817
127038
  const int64_t off_64 = args[2].As<Integer>()->Value();
1818
63519
  CHECK_GE(off_64, 0);
1819
63519
  CHECK_LE(static_cast<uint64_t>(off_64), buffer_length);
1820
63519
  const size_t off = static_cast<size_t>(off_64);
1821
1822
63519
  CHECK(args[3]->IsInt32());
1823
127038
  const size_t len = static_cast<size_t>(args[3].As<Int32>()->Value());
1824
63519
  CHECK(Buffer::IsWithinBounds(off, len, buffer_length));
1825
63519
  CHECK_LE(len, buffer_length);
1826
63519
  CHECK_GE(off + len, off);
1827
1828
63519
  const int64_t pos = GetOffset(args[4]);
1829
1830
63519
  char* buf = buffer_data + off;
1831
63519
  uv_buf_t uvbuf = uv_buf_init(buf, len);
1832
1833
63519
  FSReqBase* req_wrap_async = GetReqWrap(args, 5);
1834
63519
  if (req_wrap_async != nullptr) {  // write(fd, buffer, off, len, pos, req)
1835
17602
    AsyncCall(env, req_wrap_async, args, "write", UTF8, AfterInteger,
1836
              uv_fs_write, fd, &uvbuf, 1, pos);
1837
  } else {  // write(fd, buffer, off, len, pos, undefined, ctx)
1838
45917
    CHECK_EQ(argc, 7);
1839
45917
    FSReqWrapSync req_wrap_sync;
1840

45967
    FS_SYNC_TRACE_BEGIN(write);
1841
45917
    int bytesWritten = SyncCall(env, args[6], &req_wrap_sync, "write",
1842
45917
                                uv_fs_write, fd, &uvbuf, 1, pos);
1843

45967
    FS_SYNC_TRACE_END(write, "bytesWritten", bytesWritten);
1844
91834
    args.GetReturnValue().Set(bytesWritten);
1845
  }
1846
63519
}
1847
1848
1849
// Wrapper for writev(2).
1850
//
1851
// bytesWritten = writev(fd, chunks, position, callback)
1852
// 0 fd        integer. file descriptor
1853
// 1 chunks    array of buffers to write
1854
// 2 position  if integer, position to write at in the file.
1855
//             if null, write from the current position
1856
18
static void WriteBuffers(const FunctionCallbackInfo<Value>& args) {
1857
18
  Environment* env = Environment::GetCurrent(args);
1858
1859
18
  const int argc = args.Length();
1860
18
  CHECK_GE(argc, 3);
1861
1862
18
  CHECK(args[0]->IsInt32());
1863
36
  const int fd = args[0].As<Int32>()->Value();
1864
1865
18
  CHECK(args[1]->IsArray());
1866
36
  Local<Array> chunks = args[1].As<Array>();
1867
1868
18
  int64_t pos = GetOffset(args[2]);
1869
1870
36
  MaybeStackBuffer<uv_buf_t> iovs(chunks->Length());
1871
1872
71
  for (uint32_t i = 0; i < iovs.length(); i++) {
1873
53
    Local<Value> chunk = chunks->Get(env->context(), i).ToLocalChecked();
1874
53
    CHECK(Buffer::HasInstance(chunk));
1875
53
    iovs[i] = uv_buf_init(Buffer::Data(chunk), Buffer::Length(chunk));
1876
  }
1877
1878
18
  FSReqBase* req_wrap_async = GetReqWrap(args, 3);
1879
18
  if (req_wrap_async != nullptr) {  // writeBuffers(fd, chunks, pos, req)
1880
14
    AsyncCall(env, req_wrap_async, args, "write", UTF8, AfterInteger,
1881
              uv_fs_write, fd, *iovs, iovs.length(), pos);
1882
  } else {  // writeBuffers(fd, chunks, pos, undefined, ctx)
1883
4
    CHECK_EQ(argc, 5);
1884
4
    FSReqWrapSync req_wrap_sync;
1885

4
    FS_SYNC_TRACE_BEGIN(write);
1886
8
    int bytesWritten = SyncCall(env, args[4], &req_wrap_sync, "write",
1887
4
                                uv_fs_write, fd, *iovs, iovs.length(), pos);
1888

4
    FS_SYNC_TRACE_END(write, "bytesWritten", bytesWritten);
1889
8
    args.GetReturnValue().Set(bytesWritten);
1890
  }
1891
18
}
1892
1893
1894
// Wrapper for write(2).
1895
//
1896
// bytesWritten = write(fd, string, position, enc, callback)
1897
// 0 fd        integer. file descriptor
1898
// 1 string    non-buffer values are converted to strings
1899
// 2 position  if integer, position to write at in the file.
1900
//             if null, write from the current position
1901
// 3 enc       encoding of string
1902
129765
static void WriteString(const FunctionCallbackInfo<Value>& args) {
1903
129765
  Environment* env = Environment::GetCurrent(args);
1904
129765
  Isolate* isolate = env->isolate();
1905
1906
129765
  const int argc = args.Length();
1907
129765
  CHECK_GE(argc, 4);
1908
1909
129765
  CHECK(args[0]->IsInt32());
1910
259530
  const int fd = args[0].As<Int32>()->Value();
1911
1912
129765
  const int64_t pos = GetOffset(args[2]);
1913
1914
129765
  const auto enc = ParseEncoding(isolate, args[3], UTF8);
1915
1916
129765
  Local<Value> value = args[1];
1917
129765
  char* buf = nullptr;
1918
  size_t len;
1919
1920
129765
  FSReqBase* req_wrap_async = GetReqWrap(args, 4);
1921
129765
  const bool is_async = req_wrap_async != nullptr;
1922
1923
  // Avoid copying the string when it is externalized but only when:
1924
  // 1. The target encoding is compatible with the string's encoding, and
1925
  // 2. The write is synchronous, otherwise the string might get neutered
1926
  //    while the request is in flight, and
1927
  // 3. For UCS2, when the host system is little-endian.  Big-endian systems
1928
  //    need to call StringBytes::Write() to ensure proper byte swapping.
1929
  // The const_casts are conceptually sound: memory is read but not written.
1930

389137
  if (!is_async && value->IsString()) {
1931
129686
    auto string = value.As<String>();
1932


129687
    if ((enc == ASCII || enc == LATIN1) && string->IsExternalOneByte()) {
1933
1
      auto ext = string->GetExternalOneByteStringResource();
1934
1
      buf = const_cast<char*>(ext->data());
1935
1
      len = ext->length();
1936


129686
    } else if (enc == UCS2 && IsLittleEndian() && string->IsExternalTwoByte()) {
1937
1
      auto ext = string->GetExternalStringResource();
1938
1
      buf = reinterpret_cast<char*>(const_cast<uint16_t*>(ext->data()));
1939
1
      len = ext->length() * sizeof(*ext->data());
1940
    }
1941
  }
1942
1943
129765
  if (is_async) {  // write(fd, string, pos, enc, req)
1944
79
    CHECK_NOT_NULL(req_wrap_async);
1945
158
    if (!StringBytes::StorageSize(isolate, value, enc).To(&len)) return;
1946
    FSReqBase::FSReqBuffer& stack_buffer =
1947
79
        req_wrap_async->Init("write", len, enc);
1948
    // StorageSize may return too large a char, so correct the actual length
1949
    // by the write size
1950
79
    len = StringBytes::Write(isolate, *stack_buffer, len, args[1], enc);
1951
79
    stack_buffer.SetLengthAndZeroTerminate(len);
1952
79
    uv_buf_t uvbuf = uv_buf_init(*stack_buffer, len);
1953
79
    int err = req_wrap_async->Dispatch(uv_fs_write,
1954
                                       fd,
1955
                                       &uvbuf,
1956
                                       1,
1957
                                       pos,
1958
                                       AfterInteger);
1959
79
    if (err < 0) {
1960
      uv_fs_t* uv_req = req_wrap_async->req();
1961
      uv_req->result = err;
1962
      uv_req->path = nullptr;
1963
      AfterInteger(uv_req);  // after may delete req_wrap_async if there is
1964
                             // an error
1965
    } else {
1966
79
      req_wrap_async->SetReturnValue(args);
1967
    }
1968
  } else {  // write(fd, string, pos, enc, undefined, ctx)
1969
129686
    CHECK_EQ(argc, 6);
1970
129686
    FSReqWrapSync req_wrap_sync;
1971
129686
    FSReqBase::FSReqBuffer stack_buffer;
1972
129686
    if (buf == nullptr) {
1973
259368
      if (!StringBytes::StorageSize(isolate, value, enc).To(&len))
1974
        return;
1975
129684
      stack_buffer.AllocateSufficientStorage(len + 1);
1976
      // StorageSize may return too large a char, so correct the actual length
1977
      // by the write size
1978
129684
      len = StringBytes::Write(isolate, *stack_buffer,
1979
                               len, args[1], enc);
1980
129684
      stack_buffer.SetLengthAndZeroTerminate(len);
1981
129684
      buf = *stack_buffer;
1982
    }
1983
129686
    uv_buf_t uvbuf = uv_buf_init(buf, len);
1984

129686
    FS_SYNC_TRACE_BEGIN(write);
1985
129686
    int bytesWritten = SyncCall(env, args[5], &req_wrap_sync, "write",
1986
129686
                                uv_fs_write, fd, &uvbuf, 1, pos);
1987

129686
    FS_SYNC_TRACE_END(write, "bytesWritten", bytesWritten);
1988
259372
    args.GetReturnValue().Set(bytesWritten);
1989
  }
1990
}
1991
1992
1993
/*
1994
 * Wrapper for read(2).
1995
 *
1996
 * bytesRead = fs.read(fd, buffer, offset, length, position)
1997
 *
1998
 * 0 fd        int32. file descriptor
1999
 * 1 buffer    instance of Buffer
2000
 * 2 offset    int64. offset to start reading into inside buffer
2001
 * 3 length    int32. length to read
2002
 * 4 position  int64. file position - -1 for current position
2003
 */
2004
227627
static void Read(const FunctionCallbackInfo<Value>& args) {
2005
227627
  Environment* env = Environment::GetCurrent(args);
2006
2007
227627
  const int argc = args.Length();
2008
227627
  CHECK_GE(argc, 5);
2009
2010
227627
  CHECK(args[0]->IsInt32());
2011
455254
  const int fd = args[0].As<Int32>()->Value();
2012
2013
227627
  CHECK(Buffer::HasInstance(args[1]));
2014
227627
  Local<Object> buffer_obj = args[1].As<Object>();
2015
227627
  char* buffer_data = Buffer::Data(buffer_obj);
2016
227627
  size_t buffer_length = Buffer::Length(buffer_obj);
2017
2018
227627
  CHECK(IsSafeJsInt(args[2]));
2019
455254
  const int64_t off_64 = args[2].As<Integer>()->Value();
2020
227627
  CHECK_GE(off_64, 0);
2021
227627
  CHECK_LT(static_cast<uint64_t>(off_64), buffer_length);
2022
227627
  const size_t off = static_cast<size_t>(off_64);
2023
2024
227627
  CHECK(args[3]->IsInt32());
2025
455254
  const size_t len = static_cast<size_t>(args[3].As<Int32>()->Value());
2026
227627
  CHECK(Buffer::IsWithinBounds(off, len, buffer_length));
2027
2028

227657
  CHECK(IsSafeJsInt(args[4]) || args[4]->IsBigInt());
2029
227627
  const int64_t pos = args[4]->IsNumber() ?
2030
455194
                      args[4].As<Integer>()->Value() :
2031
60
                      args[4].As<BigInt>()->Int64Value();
2032
2033
227627
  char* buf = buffer_data + off;
2034
227627
  uv_buf_t uvbuf = uv_buf_init(buf, len);
2035
2036
227627
  FSReqBase* req_wrap_async = GetReqWrap(args, 5);
2037
227627
  if (req_wrap_async != nullptr) {  // read(fd, buffer, offset, len, pos, req)
2038
14913
    AsyncCall(env, req_wrap_async, args, "read", UTF8, AfterInteger,
2039
              uv_fs_read, fd, &uvbuf, 1, pos);
2040
  } else {  // read(fd, buffer, offset, len, pos, undefined, ctx)
2041
212714
    CHECK_EQ(argc, 7);
2042
212714
    FSReqWrapSync req_wrap_sync;
2043

212753
    FS_SYNC_TRACE_BEGIN(read);
2044
212714
    const int bytesRead = SyncCall(env, args[6], &req_wrap_sync, "read",
2045
212714
                                   uv_fs_read, fd, &uvbuf, 1, pos);
2046

212753
    FS_SYNC_TRACE_END(read, "bytesRead", bytesRead);
2047
425428
    args.GetReturnValue().Set(bytesRead);
2048
  }
2049
227627
}
2050
2051
2052
// Wrapper for readv(2).
2053
//
2054
// bytesRead = fs.readv(fd, buffers[, position], callback)
2055
// 0 fd        integer. file descriptor
2056
// 1 buffers   array of buffers to read
2057
// 2 position  if integer, position to read at in the file.
2058
//             if null, read from the current position
2059
11
static void ReadBuffers(const FunctionCallbackInfo<Value>& args) {
2060
11
  Environment* env = Environment::GetCurrent(args);
2061
2062
11
  const int argc = args.Length();
2063
11
  CHECK_GE(argc, 3);
2064
2065
11
  CHECK(args[0]->IsInt32());
2066
22
  const int fd = args[0].As<Int32>()->Value();
2067
2068
11
  CHECK(args[1]->IsArray());
2069
22
  Local<Array> buffers = args[1].As<Array>();
2070
2071
11
  int64_t pos = GetOffset(args[2]);  // -1 if not a valid JS int
2072
2073
22
  MaybeStackBuffer<uv_buf_t> iovs(buffers->Length());
2074
2075
  // Init uv buffers from ArrayBufferViews
2076
28
  for (uint32_t i = 0; i < iovs.length(); i++) {
2077
17
    Local<Value> buffer = buffers->Get(env->context(), i).ToLocalChecked();
2078
17
    CHECK(Buffer::HasInstance(buffer));
2079
17
    iovs[i] = uv_buf_init(Buffer::Data(buffer), Buffer::Length(buffer));
2080
  }
2081
2082
11
  FSReqBase* req_wrap_async = GetReqWrap(args, 3);
2083
11
  if (req_wrap_async != nullptr) {  // readBuffers(fd, buffers, pos, req)
2084
7
    AsyncCall(env, req_wrap_async, args, "read", UTF8, AfterInteger,
2085
              uv_fs_read, fd, *iovs, iovs.length(), pos);
2086
  } else {  // readBuffers(fd, buffers, undefined, ctx)
2087
4
    CHECK_EQ(argc, 5);
2088
4
    FSReqWrapSync req_wrap_sync;
2089

4
    FS_SYNC_TRACE_BEGIN(read);
2090
8
    int bytesRead = SyncCall(env, /* ctx */ args[4], &req_wrap_sync, "read",
2091
4
                             uv_fs_read, fd, *iovs, iovs.length(), pos);
2092

4
    FS_SYNC_TRACE_END(read, "bytesRead", bytesRead);
2093
8
    args.GetReturnValue().Set(bytesRead);
2094
  }
2095
11
}
2096
2097
2098
/* fs.chmod(path, mode);
2099
 * Wrapper for chmod(1) / EIO_CHMOD
2100
 */
2101
310
static void Chmod(const FunctionCallbackInfo<Value>& args) {
2102
310
  Environment* env = Environment::GetCurrent(args);
2103
2104
310
  const int argc = args.Length();
2105
310
  CHECK_GE(argc, 2);
2106
2107
620
  BufferValue path(env->isolate(), args[0]);
2108
310
  CHECK_NOT_NULL(*path);
2109
2110
310
  CHECK(args[1]->IsInt32());
2111
620
  int mode = args[1].As<Int32>()->Value();
2112
2113
310
  FSReqBase* req_wrap_async = GetReqWrap(args, 2);
2114
310
  if (req_wrap_async != nullptr) {  // chmod(path, mode, req)
2115
141
    AsyncCall(env, req_wrap_async, args, "chmod", UTF8, AfterNoArgs,
2116
              uv_fs_chmod, *path, mode);
2117
  } else {  // chmod(path, mode, undefined, ctx)
2118
169
    CHECK_EQ(argc, 4);
2119
338
    FSReqWrapSync req_wrap_sync;
2120

171
    FS_SYNC_TRACE_BEGIN(chmod);
2121
338
    SyncCall(env, args[3], &req_wrap_sync, "chmod",
2122
             uv_fs_chmod, *path, mode);
2123

171
    FS_SYNC_TRACE_END(chmod);
2124
  }
2125
310
}
2126
2127
2128
/* fs.fchmod(fd, mode);
2129
 * Wrapper for fchmod(1) / EIO_FCHMOD
2130
 */
2131
12
static void FChmod(const FunctionCallbackInfo<Value>& args) {
2132
12
  Environment* env = Environment::GetCurrent(args);
2133
2134
12
  const int argc = args.Length();
2135
12
  CHECK_GE(argc, 2);
2136
2137
12
  CHECK(args[0]->IsInt32());
2138
24
  const int fd = args[0].As<Int32>()->Value();
2139
2140
12
  CHECK(args[1]->IsInt32());
2141
24
  const int mode = args[1].As<Int32>()->Value();
2142
2143
12
  FSReqBase* req_wrap_async = GetReqWrap(args, 2);
2144
12
  if (req_wrap_async != nullptr) {  // fchmod(fd, mode, req)
2145
7
    AsyncCall(env, req_wrap_async, args, "fchmod", UTF8, AfterNoArgs,
2146
              uv_fs_fchmod, fd, mode);
2147
  } else {  // fchmod(fd, mode, undefined, ctx)
2148
5
    CHECK_EQ(argc, 4);
2149
10
    FSReqWrapSync req_wrap_sync;
2150

7
    FS_SYNC_TRACE_BEGIN(fchmod);
2151
5
    SyncCall(env, args[3], &req_wrap_sync, "fchmod",
2152
             uv_fs_fchmod, fd, mode);
2153

7
    FS_SYNC_TRACE_END(fchmod);
2154
  }
2155
12
}
2156
2157
2158
/* fs.chown(path, uid, gid);
2159
 * Wrapper for chown(1) / EIO_CHOWN
2160
 */
2161
4
static void Chown(const FunctionCallbackInfo<Value>& args) {
2162
4
  Environment* env = Environment::GetCurrent(args);
2163
2164
4
  const int argc = args.Length();
2165
4
  CHECK_GE(argc, 3);
2166
2167
8
  BufferValue path(env->isolate(), args[0]);
2168
4
  CHECK_NOT_NULL(*path);
2169
2170
4
  CHECK(IsSafeJsInt(args[1]));
2171
8
  const uv_uid_t uid = static_cast<uv_uid_t>(args[1].As<Integer>()->Value());
2172
2173
4
  CHECK(IsSafeJsInt(args[2]));
2174
8
  const uv_gid_t gid = static_cast<uv_gid_t>(args[2].As<Integer>()->Value());
2175
2176
4
  FSReqBase* req_wrap_async = GetReqWrap(args, 3);
2177
4
  if (req_wrap_async != nullptr) {  // chown(path, uid, gid, req)
2178
2
    AsyncCall(env, req_wrap_async, args, "chown", UTF8, AfterNoArgs,
2179
              uv_fs_chown, *path, uid, gid);
2180
  } else {  // chown(path, uid, gid, undefined, ctx)
2181
2
    CHECK_EQ(argc, 5);
2182
4
    FSReqWrapSync req_wrap_sync;
2183

4
    FS_SYNC_TRACE_BEGIN(chown);
2184
4
    SyncCall(env, args[4], &req_wrap_sync, "chown",
2185
             uv_fs_chown, *path, uid, gid);
2186

4
    FS_SYNC_TRACE_END(chown);
2187
  }
2188
4
}
2189
2190
2191
/* fs.fchown(fd, uid, gid);
2192
 * Wrapper for fchown(1) / EIO_FCHOWN
2193
 */
2194
4
static void FChown(const FunctionCallbackInfo<Value>& args) {
2195
4
  Environment* env = Environment::GetCurrent(args);
2196
2197
4
  const int argc = args.Length();
2198
4
  CHECK_GE(argc, 3);
2199
2200
4
  CHECK(args[0]->IsInt32());
2201
8
  const int fd = args[0].As<Int32>()->Value();
2202
2203
4
  CHECK(IsSafeJsInt(args[1]));
2204
8
  const uv_uid_t uid = static_cast<uv_uid_t>(args[1].As<Integer>()->Value());
2205
2206
4
  CHECK(IsSafeJsInt(args[2]));
2207
8
  const uv_gid_t gid = static_cast<uv_gid_t>(args[2].As<Integer>()->Value());
2208
2209
4
  FSReqBase* req_wrap_async = GetReqWrap(args, 3);
2210
4
  if (req_wrap_async != nullptr) {  // fchown(fd, uid, gid, req)
2211
2
    AsyncCall(env, req_wrap_async, args, "fchown", UTF8, AfterNoArgs,
2212
              uv_fs_fchown, fd, uid, gid);
2213
  } else {  // fchown(fd, uid, gid, undefined, ctx)
2214
2
    CHECK_EQ(argc, 5);
2215
4
    FSReqWrapSync req_wrap_sync;
2216

4
    FS_SYNC_TRACE_BEGIN(fchown);
2217
2
    SyncCall(env, args[4], &req_wrap_sync, "fchown",
2218
             uv_fs_fchown, fd, uid, gid);
2219

4
    FS_SYNC_TRACE_END(fchown);
2220
  }
2221
4
}
2222
2223
2224
5
static void LChown(const FunctionCallbackInfo<Value>& args) {
2225
5
  Environment* env = Environment::GetCurrent(args);
2226
2227
5
  const int argc = args.Length();
2228
5
  CHECK_GE(argc, 3);
2229
2230
10
  BufferValue path(env->isolate(), args[0]);
2231
5
  CHECK_NOT_NULL(*path);
2232
2233
5
  CHECK(IsSafeJsInt(args[1]));
2234
10
  const uv_uid_t uid = static_cast<uv_uid_t>(args[1].As<Integer>()->Value());
2235
2236
5
  CHECK(IsSafeJsInt(args[2]));
2237
10
  const uv_gid_t gid = static_cast<uv_gid_t>(args[2].As<Integer>()->Value());
2238
2239
5
  FSReqBase* req_wrap_async = GetReqWrap(args, 3);
2240
5
  if (req_wrap_async != nullptr) {  // lchown(path, uid, gid, req)
2241
3
    AsyncCall(env, req_wrap_async, args, "lchown", UTF8, AfterNoArgs,
2242
              uv_fs_lchown, *path, uid, gid);
2243
  } else {  // lchown(path, uid, gid, undefined, ctx)
2244
2
    CHECK_EQ(argc, 5);
2245
4
    FSReqWrapSync req_wrap_sync;
2246

4
    FS_SYNC_TRACE_BEGIN(lchown);
2247
4
    SyncCall(env, args[4], &req_wrap_sync, "lchown",
2248
             uv_fs_lchown, *path, uid, gid);
2249

4
    FS_SYNC_TRACE_END(lchown);
2250
  }
2251
5
}
2252
2253
2254
61
static void UTimes(const FunctionCallbackInfo<Value>& args) {
2255
61
  Environment* env = Environment::GetCurrent(args);
2256
2257
61
  const int argc = args.Length();
2258
61
  CHECK_GE(argc, 3);
2259
2260
122
  BufferValue path(env->isolate(), args[0]);
2261
61
  CHECK_NOT_NULL(*path);
2262
2263
61
  CHECK(args[1]->IsNumber());
2264
122
  const double atime = args[1].As<Number>()->Value();
2265
2266
61
  CHECK(args[2]->IsNumber());
2267
122
  const double mtime = args[2].As<Number>()->Value();
2268
2269
61
  FSReqBase* req_wrap_async = GetReqWrap(args, 3);
2270
61
  if (req_wrap_async != nullptr) {  // utimes(path, atime, mtime, req)
2271
34
    AsyncCall(env, req_wrap_async, args, "utime", UTF8, AfterNoArgs,
2272
              uv_fs_utime, *path, atime, mtime);
2273
  } else {  // utimes(path, atime, mtime, undefined, ctx)
2274
27
    CHECK_EQ(argc, 5);
2275
54
    FSReqWrapSync req_wrap_sync;
2276

29
    FS_SYNC_TRACE_BEGIN(utimes);
2277
54
    SyncCall(env, args[4], &req_wrap_sync, "utime",
2278
             uv_fs_utime, *path, atime, mtime);
2279

29
    FS_SYNC_TRACE_END(utimes);
2280
  }
2281
61
}
2282
2283
18
static void FUTimes(const FunctionCallbackInfo<Value>& args) {
2284
18
  Environment* env = Environment::GetCurrent(args);
2285
2286
18
  const int argc = args.Length();
2287
18
  CHECK_GE(argc, 3);
2288
2289
18
  CHECK(args[0]->IsInt32());
2290
36
  const int fd = args[0].As<Int32>()->Value();
2291
2292
18
  CHECK(args[1]->IsNumber());
2293
36
  const double atime = args[1].As<Number>()->Value();
2294
2295
18
  CHECK(args[2]->IsNumber());
2296
36
  const double mtime = args[2].As<Number>()->Value();
2297
2298
18
  FSReqBase* req_wrap_async = GetReqWrap(args, 3);
2299
18
  if (req_wrap_async != nullptr) {  // futimes(fd, atime, mtime, req)
2300
9
    AsyncCall(env, req_wrap_async, args, "futime", UTF8, AfterNoArgs,
2301
              uv_fs_futime, fd, atime, mtime);
2302
  } else {  // futimes(fd, atime, mtime, undefined, ctx)
2303
9
    CHECK_EQ(argc, 5);
2304
18
    FSReqWrapSync req_wrap_sync;
2305

11
    FS_SYNC_TRACE_BEGIN(futimes);
2306
9
    SyncCall(env, args[4], &req_wrap_sync, "futime",
2307
             uv_fs_futime, fd, atime, mtime);
2308

11
    FS_SYNC_TRACE_END(futimes);
2309
  }
2310
18
}
2311
2312
15
static void LUTimes(const FunctionCallbackInfo<Value>& args) {
2313
15
  Environment* env = Environment::GetCurrent(args);
2314
2315
15
  const int argc = args.Length();
2316
15
  CHECK_GE(argc, 3);
2317
2318
30
  BufferValue path(env->isolate(), args[0]);
2319
15
  CHECK_NOT_NULL(*path);
2320
2321
15
  CHECK(args[1]->IsNumber());
2322
30
  const double atime = args[1].As<Number>()->Value();
2323
2324
15
  CHECK(args[2]->IsNumber());
2325
30
  const double mtime = args[2].As<Number>()->Value();
2326
2327
15
  FSReqBase* req_wrap_async = GetReqWrap(args, 3);
2328
15
  if (req_wrap_async != nullptr) {  // lutimes(path, atime, mtime, req)
2329
8
    AsyncCall(env, req_wrap_async, args, "lutime", UTF8, AfterNoArgs,
2330
              uv_fs_lutime, *path, atime, mtime);
2331
  } else {  // lutimes(path, atime, mtime, undefined, ctx)
2332
7
    CHECK_EQ(argc, 5);
2333
14
    FSReqWrapSync req_wrap_sync;
2334

7
    FS_SYNC_TRACE_BEGIN(lutimes);
2335
14
    SyncCall(env, args[4], &req_wrap_sync, "lutime",
2336
             uv_fs_lutime, *path, atime, mtime);
2337

7
    FS_SYNC_TRACE_END(lutimes);
2338
  }
2339
15
}
2340
2341
15
static void Mkdtemp(const FunctionCallbackInfo<Value>& args) {
2342
15
  Environment* env = Environment::GetCurrent(args);
2343
15
  Isolate* isolate = env->isolate();
2344
2345
15
  const int argc = args.Length();
2346
15
  CHECK_GE(argc, 2);
2347
2348
15
  BufferValue tmpl(isolate, args[0]);
2349
15
  CHECK_NOT_NULL(*tmpl);
2350
2351
15
  const enum encoding encoding = ParseEncoding(isolate, args[1], UTF8);
2352
2353
15
  FSReqBase* req_wrap_async = GetReqWrap(args, 2);
2354
15
  if (req_wrap_async != nullptr) {  // mkdtemp(tmpl, encoding, req)
2355
6
    AsyncCall(env, req_wrap_async, args, "mkdtemp", encoding, AfterStringPath,
2356
              uv_fs_mkdtemp, *tmpl);
2357
  } else {  // mkdtemp(tmpl, encoding, undefined, ctx)
2358
9
    CHECK_EQ(argc, 4);
2359
9
    FSReqWrapSync req_wrap_sync;
2360

11
    FS_SYNC_TRACE_BEGIN(mkdtemp);
2361
18
    SyncCall(env, args[3], &req_wrap_sync, "mkdtemp",
2362
             uv_fs_mkdtemp, *tmpl);
2363

11
    FS_SYNC_TRACE_END(mkdtemp);
2364
9
    const char* path = req_wrap_sync.req.path;
2365
2366
    Local<Value> error;
2367
    MaybeLocal<Value> rc =
2368
9
        StringBytes::Encode(isolate, path, encoding, &error);
2369
9
    if (rc.IsEmpty()) {
2370
      Local<Object> ctx = args[3].As<Object>();
2371
      ctx->Set(env->context(), env->error_string(), error).Check();
2372
      return;
2373
    }
2374
18
    args.GetReturnValue().Set(rc.ToLocalChecked());
2375
  }
2376
}
2377
2378
24
void BindingData::MemoryInfo(MemoryTracker* tracker) const {
2379
24
  tracker->TrackField("stats_field_array", stats_field_array);
2380
24
  tracker->TrackField("stats_field_bigint_array", stats_field_bigint_array);
2381
24
  tracker->TrackField("file_handle_read_wrap_freelist",
2382
24
                      file_handle_read_wrap_freelist);
2383
24
}
2384
2385
6612
BindingData::BindingData(Environment* env, v8::Local<v8::Object> wrap)
2386
    : SnapshotableObject(env, wrap, type_int),
2387
      stats_field_array(env->isolate(), kFsStatsBufferLength),
2388
6612
      stats_field_bigint_array(env->isolate(), kFsStatsBufferLength) {
2389
6612
  wrap->Set(env->context(),
2390
            FIXED_ONE_BYTE_STRING(env->isolate(), "statValues"),
2391
26448
            stats_field_array.GetJSArray())
2392
      .Check();
2393
2394
6612
  wrap->Set(env->context(),
2395
            FIXED_ONE_BYTE_STRING(env->isolate(), "bigintStatValues"),
2396
19836
            stats_field_bigint_array.GetJSArray())
2397
      .Check();
2398
6612
}
2399
2400
5307
void BindingData::Deserialize(Local<Context> context,
2401
                              Local<Object> holder,
2402
                              int index,
2403
                              InternalFieldInfo* info) {
2404
  DCHECK_EQ(index, BaseObject::kSlot);
2405
10614
  HandleScope scope(context->GetIsolate());
2406
5307
  Environment* env = Environment::GetCurrent(context);
2407
5307
  BindingData* binding = env->AddBindingData<BindingData>(context, holder);
2408
5307
  CHECK_NOT_NULL(binding);
2409
5307
}
2410
2411
6
void BindingData::PrepareForSerialization(Local<Context> context,
2412
                                          v8::SnapshotCreator* creator) {
2413
6
  CHECK(file_handle_read_wrap_freelist.empty());
2414
  // We'll just re-initialize the buffers in the constructor since their
2415
  // contents can be thrown away once consumed in the previous call.
2416
6
  stats_field_array.Release();
2417
6
  stats_field_bigint_array.Release();
2418
6
}
2419
2420
6
InternalFieldInfo* BindingData::Serialize(int index) {
2421
  DCHECK_EQ(index, BaseObject::kSlot);
2422
6
  InternalFieldInfo* info = InternalFieldInfo::New(type());
2423
6
  return info;
2424
}
2425
2426
1305
void Initialize(Local<Object> target,
2427
                Local<Value> unused,
2428
                Local<Context> context,
2429
                void* priv) {
2430
1305
  Environment* env = Environment::GetCurrent(context);
2431
1305
  Isolate* isolate = env->isolate();
2432
  BindingData* const binding_data =
2433
1305
      env->AddBindingData<BindingData>(context, target);
2434
1305
  if (binding_data == nullptr) return;
2435
2436
1305
  SetMethod(context, target, "access", Access);
2437
1305
  SetMethod(context, target, "close", Close);
2438
1305
  SetMethod(context, target, "open", Open);
2439
1305
  SetMethod(context, target, "openFileHandle", OpenFileHandle);
2440
1305
  SetMethod(context, target, "read", Read);
2441
1305
  SetMethod(context, target, "readBuffers", ReadBuffers);
2442
1305
  SetMethod(context, target, "fdatasync", Fdatasync);
2443
1305
  SetMethod(context, target, "fsync", Fsync);
2444
1305
  SetMethod(context, target, "rename", Rename);
2445
1305
  SetMethod(context, target, "ftruncate", FTruncate);
2446
1305
  SetMethod(context, target, "rmdir", RMDir);
2447
1305
  SetMethod(context, target, "mkdir", MKDir);
2448
1305
  SetMethod(context, target, "readdir", ReadDir);
2449
1305
  SetMethod(context, target, "internalModuleReadJSON", InternalModuleReadJSON);
2450
1305
  SetMethod(context, target, "internalModuleStat", InternalModuleStat);
2451
1305
  SetMethod(context, target, "stat", Stat);
2452
1305
  SetMethod(context, target, "lstat", LStat);
2453
1305
  SetMethod(context, target, "fstat", FStat);
2454
1305
  SetMethod(context, target, "link", Link);
2455
1305
  SetMethod(context, target, "symlink", Symlink);
2456
1305
  SetMethod(context, target, "readlink", ReadLink);
2457
1305
  SetMethod(context, target, "unlink", Unlink);
2458
1305
  SetMethod(context, target, "writeBuffer", WriteBuffer);
2459
1305
  SetMethod(context, target, "writeBuffers", WriteBuffers);
2460
1305
  SetMethod(context, target, "writeString", WriteString);
2461
1305
  SetMethod(context, target, "realpath", RealPath);
2462
1305
  SetMethod(context, target, "copyFile", CopyFile);
2463
2464
1305
  SetMethod(context, target, "chmod", Chmod);
2465
1305
  SetMethod(context, target, "fchmod", FChmod);
2466
2467
1305
  SetMethod(context, target, "chown", Chown);
2468
1305
  SetMethod(context, target, "fchown", FChown);
2469
1305
  SetMethod(context, target, "lchown", LChown);
2470
2471
1305
  SetMethod(context, target, "utimes", UTimes);
2472
1305
  SetMethod(context, target, "futimes", FUTimes);
2473
1305
  SetMethod(context, target, "lutimes", LUTimes);
2474
2475
1305
  SetMethod(context, target, "mkdtemp", Mkdtemp);
2476
2477
  target
2478
1305
      ->Set(context,
2479
            FIXED_ONE_BYTE_STRING(isolate, "kFsStatsFieldsNumber"),
2480
            Integer::New(
2481
                isolate,
2482
3915
                static_cast<int32_t>(FsStatsOffset::kFsStatsFieldsNumber)))
2483
      .Check();
2484
2485
1305
  StatWatcher::Initialize(env, target);
2486
2487
  // Create FunctionTemplate for FSReqCallback
2488
1305
  Local<FunctionTemplate> fst = NewFunctionTemplate(isolate, NewFSReqCallback);
2489
2610
  fst->InstanceTemplate()->SetInternalFieldCount(
2490
      FSReqBase::kInternalFieldCount);
2491
1305
  fst->Inherit(AsyncWrap::GetConstructorTemplate(env));
2492
1305
  SetConstructorFunction(context, target, "FSReqCallback", fst);
2493
2494
  // Create FunctionTemplate for FileHandleReadWrap. There’s no need
2495
  // to do anything in the constructor, so we only store the instance template.
2496
1305
  Local<FunctionTemplate> fh_rw = FunctionTemplate::New(isolate);
2497
2610
  fh_rw->InstanceTemplate()->SetInternalFieldCount(
2498
      FSReqBase::kInternalFieldCount);
2499
1305
  fh_rw->Inherit(AsyncWrap::GetConstructorTemplate(env));
2500
  Local<String> fhWrapString =
2501
1305
      FIXED_ONE_BYTE_STRING(isolate, "FileHandleReqWrap");
2502
1305
  fh_rw->SetClassName(fhWrapString);
2503
1305
  env->set_filehandlereadwrap_template(
2504
      fst->InstanceTemplate());
2505
2506
  // Create Function Template for FSReqPromise
2507
1305
  Local<FunctionTemplate> fpt = FunctionTemplate::New(isolate);
2508
1305
  fpt->Inherit(AsyncWrap::GetConstructorTemplate(env));
2509
  Local<String> promiseString =
2510
1305
      FIXED_ONE_BYTE_STRING(isolate, "FSReqPromise");
2511
1305
  fpt->SetClassName(promiseString);
2512
1305
  Local<ObjectTemplate> fpo = fpt->InstanceTemplate();
2513
1305
  fpo->SetInternalFieldCount(FSReqBase::kInternalFieldCount);
2514
1305
  env->set_fsreqpromise_constructor_template(fpo);
2515
2516
  // Create FunctionTemplate for FileHandle
2517
1305
  Local<FunctionTemplate> fd = NewFunctionTemplate(isolate, FileHandle::New);
2518
1305
  fd->Inherit(AsyncWrap::GetConstructorTemplate(env));
2519
1305
  SetProtoMethod(isolate, fd, "close", FileHandle::Close);
2520
1305
  SetProtoMethod(isolate, fd, "releaseFD", FileHandle::ReleaseFD);
2521
1305
  Local<ObjectTemplate> fdt = fd->InstanceTemplate();
2522
1305
  fdt->SetInternalFieldCount(FileHandle::kInternalFieldCount);
2523
1305
  StreamBase::AddMethods(env, fd);
2524
1305
  SetConstructorFunction(context, target, "FileHandle", fd);
2525
1305
  env->set_fd_constructor_template(fdt);
2526
2527
  // Create FunctionTemplate for FileHandle::CloseReq
2528
1305
  Local<FunctionTemplate> fdclose = FunctionTemplate::New(isolate);
2529
1305
  fdclose->SetClassName(FIXED_ONE_BYTE_STRING(isolate,
2530
                        "FileHandleCloseReq"));
2531
1305
  fdclose->Inherit(AsyncWrap::GetConstructorTemplate(env));
2532
1305
  Local<ObjectTemplate> fdcloset = fdclose->InstanceTemplate();
2533
1305
  fdcloset->SetInternalFieldCount(FSReqBase::kInternalFieldCount);
2534
1305
  env->set_fdclose_constructor_template(fdcloset);
2535
2536
  Local<Symbol> use_promises_symbol =
2537
    Symbol::New(isolate,
2538
1305
                FIXED_ONE_BYTE_STRING(isolate, "use promises"));
2539
1305
  env->set_fs_use_promises_symbol(use_promises_symbol);
2540
1305
  target->Set(context,
2541
              FIXED_ONE_BYTE_STRING(isolate, "kUsePromises"),
2542
3915
              use_promises_symbol).Check();
2543
}
2544
2545
4123
BindingData* FSReqBase::binding_data() {
2546
4123
  return binding_data_.get();
2547
}
2548
2549
5314
void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
2550
5314
  registry->Register(Access);
2551
5314
  StatWatcher::RegisterExternalReferences(registry);
2552
2553
5314
  registry->Register(Close);
2554
5314
  registry->Register(Open);
2555
5314
  registry->Register(OpenFileHandle);
2556
5314
  registry->Register(Read);
2557
5314
  registry->Register(ReadBuffers);
2558
5314
  registry->Register(Fdatasync);
2559
5314
  registry->Register(Fsync);
2560
5314
  registry->Register(Rename);
2561
5314
  registry->Register(FTruncate);
2562
5314
  registry->Register(RMDir);
2563
5314
  registry->Register(MKDir);
2564
5314
  registry->Register(ReadDir);
2565
5314
  registry->Register(InternalModuleReadJSON);
2566
5314
  registry->Register(InternalModuleStat);
2567
5314
  registry->Register(Stat);
2568
5314
  registry->Register(LStat);
2569
5314
  registry->Register(FStat);
2570
5314
  registry->Register(Link);
2571
5314
  registry->Register(Symlink);
2572
5314
  registry->Register(ReadLink);
2573
5314
  registry->Register(Unlink);
2574
5314
  registry->Register(WriteBuffer);
2575
5314
  registry->Register(WriteBuffers);
2576
5314
  registry->Register(WriteString);
2577
5314
  registry->Register(RealPath);
2578
5314
  registry->Register(CopyFile);
2579
2580
5314
  registry->Register(Chmod);
2581
5314
  registry->Register(FChmod);
2582
2583
5314
  registry->Register(Chown);
2584
5314
  registry->Register(FChown);
2585
5314
  registry->Register(LChown);
2586
2587
5314
  registry->Register(UTimes);
2588
5314
  registry->Register(FUTimes);
2589
5314
  registry->Register(LUTimes);
2590
2591
5314
  registry->Register(Mkdtemp);
2592
5314
  registry->Register(NewFSReqCallback);
2593
2594
5314
  registry->Register(FileHandle::New);
2595
5314
  registry->Register(FileHandle::Close);
2596
5314
  registry->Register(FileHandle::ReleaseFD);
2597
5314
  StreamBase::RegisterExternalReferences(registry);
2598
5314
}
2599
2600
}  // namespace fs
2601
2602
}  // end namespace node
2603
2604
5386
NODE_MODULE_CONTEXT_AWARE_INTERNAL(fs, node::fs::Initialize)
2605
5314
NODE_MODULE_EXTERNAL_REFERENCE(fs, node::fs::RegisterExternalReferences)