GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_file.cc Lines: 1451 1533 94.7 %
Date: 2021-09-24 04:12:43 Branches: 799 1252 63.8 %

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
11
std::string Basename(const std::string& str, const std::string& extension) {
88
  // Remove everything leading up to and including the final path separator.
89
11
  std::string::size_type pos = str.find_last_of(kPathSeparator);
90
91
  // Starting index for the resulting string
92
11
  std::size_t start_pos = 0;
93
  // String size to return
94
11
  std::size_t str_size = str.size();
95
11
  if (pos != std::string::npos) {
96
11
    start_pos = pos + 1;
97
11
    str_size -= start_pos;
98
  }
99
100
  // Strip away the extension, if any.
101

22
  if (str_size >= extension.size() &&
102
11
      str.compare(str.size() - extension.size(),
103
        extension.size(), extension) == 0) {
104
    str_size -= extension.size();
105
  }
106
107
11
  return str.substr(start_pos, str_size);
108
}
109
110
181193
inline int64_t GetOffset(Local<Value> value) {
111
182283
  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
923
FileHandle::FileHandle(BindingData* binding_data,
149
923
                       Local<Object> obj, int fd)
150
    : AsyncWrap(binding_data->env(), obj, AsyncWrap::PROVIDER_FILEHANDLE),
151
      StreamBase(env()),
152
      fd_(fd),
153
923
      binding_data_(binding_data) {
154
923
  MakeWeak();
155
923
  StreamBase::AttachToObject(GetObject());
156
923
}
157
158
923
FileHandle* FileHandle::New(BindingData* binding_data,
159
                            int fd, Local<Object> obj) {
160
923
  Environment* env = binding_data->env();
161
1831
  if (obj.IsEmpty() && !env->fd_constructor_template()
162
1831
                            ->NewInstance(env->context())
163
908
                            .ToLocal(&obj)) {
164
    return nullptr;
165
  }
166
923
  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
15
  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
3572
FileHandle::~FileHandle() {
185
1786
  CHECK(!closing_);  // We should not be deleting while explicitly closing!
186
1786
  Close();           // Close synchronously and emit warning
187
1786
  CHECK(closed_);    // We have to be closed at the point
188
3572
}
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
893
inline void FileHandle::Close() {
241

893
  if (closed_ || closing_) return;
242
  uv_fs_t req;
243
13
  CHECK_NE(fd_, -1);
244
13
  int ret = uv_fs_close(env()->event_loop(), &req, fd_, nullptr);
245
13
  uv_fs_req_cleanup(&req);
246
247
  struct err_detail { int ret; int fd; };
248
249
13
  err_detail detail { ret, fd_ };
250
251
13
  AfterClose();
252
253
13
  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
13
  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
      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").IsNothing();
287
    }
288
4
  }, CallbackFlags::kUnrefed);
289
}
290
291
893
void FileHandle::CloseReq::Resolve() {
292
893
  Isolate* isolate = env()->isolate();
293
1766
  HandleScope scope(isolate);
294
893
  Context::Scope context_scope(env()->context());
295
893
  InternalCallbackScope callback_scope(this);
296
1786
  Local<Promise> promise = promise_.Get(isolate);
297
893
  Local<Promise::Resolver> resolver = promise.As<Promise::Resolver>();
298
2679
  resolver->Resolve(env()->context(), Undefined(isolate)).Check();
299
873
}
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
894
FileHandle* FileHandle::CloseReq::file_handle() {
312
894
  Isolate* isolate = env()->isolate();
313
894
  HandleScope scope(isolate);
314
1788
  Local<Value> val = ref_.Get(isolate);
315
894
  Local<Object> obj = val.As<Object>();
316
894
  return Unwrap<FileHandle>(obj);
317
}
318
319
894
FileHandle::CloseReq::CloseReq(Environment* env,
320
                               Local<Object> obj,
321
                               Local<Promise> promise,
322
894
                               Local<Value> ref)
323
894
  : ReqWrap(env, obj, AsyncWrap::PROVIDER_FILEHANDLECLOSEREQ) {
324
894
  promise_.Reset(env->isolate(), promise);
325
894
  ref_.Reset(env->isolate(), ref);
326
894
}
327
328
6992
FileHandle::CloseReq::~CloseReq() {
329
1748
  uv_fs_req_cleanup(req());
330
1748
  promise_.Reset();
331
1748
  ref_.Reset();
332
3496
}
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
894
MaybeLocal<Promise> FileHandle::ClosePromise() {
347
894
  Isolate* isolate = env()->isolate();
348
894
  EscapableHandleScope scope(isolate);
349
894
  Local<Context> context = env()->context();
350
351
  Local<Value> close_resolver =
352
2682
      object()->GetInternalField(FileHandle::kClosingPromiseSlot);
353

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

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

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

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

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

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

36274
  if (result >= 0 && req_wrap->is_plain_open())
683
5359
    req_wrap->env()->AddUnmanagedFd(result);
684
685
36274
  if (after.Proceed())
686
72206
    req_wrap->Resolve(Integer::New(req_wrap->env()->isolate(), result));
687
36274
}
688
689
930
void AfterOpenFileHandle(uv_fs_t* req) {
690
930
  FSReqBase* req_wrap = FSReqBase::from_req(req);
691
930
  FSReqAfterScope after(req_wrap, req);
692
693
930
  if (after.Proceed()) {
694
905
    FileHandle* fd = FileHandle::New(req_wrap->binding_data(),
695
905
                                     static_cast<int>(req->result));
696
905
    if (fd == nullptr) return;
697
1810
    req_wrap->Resolve(fd->object());
698
  }
699
}
700
701
// Reverse the logic applied by path.toNamespacedPath() to create a
702
// namespace-prefixed path.
703
482
void FromNamespacedPath(std::string* path) {
704
#ifdef _WIN32
705
  if (path->compare(0, 8, "\\\\?\\UNC\\", 8) == 0) {
706
    *path = path->substr(8);
707
    path->insert(0, "\\\\");
708
  } else if (path->compare(0, 4, "\\\\?\\", 4) == 0) {
709
    *path = path->substr(4);
710
  }
711
#endif
712
482
}
713
714
344
void AfterMkdirp(uv_fs_t* req) {
715
344
  FSReqBase* req_wrap = FSReqBase::from_req(req);
716
688
  FSReqAfterScope after(req_wrap, req);
717
718
  MaybeLocal<Value> path;
719
  Local<Value> error;
720
721
344
  if (after.Proceed()) {
722
338
    if (!req_wrap->continuation_data()->first_path().empty()) {
723
436
      std::string first_path(req_wrap->continuation_data()->first_path());
724
218
      FromNamespacedPath(&first_path);
725
      path = StringBytes::Encode(req_wrap->env()->isolate(), first_path.c_str(),
726
                                 req_wrap->encoding(),
727
218
                                 &error);
728
218
      if (path.IsEmpty())
729
        req_wrap->Reject(error);
730
      else
731
436
        req_wrap->Resolve(path.ToLocalChecked());
732
    } else {
733
240
      req_wrap->Resolve(Undefined(req_wrap->env()->isolate()));
734
    }
735
  }
736
344
}
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
152
void AfterScanDir(uv_fs_t* req) {
777
152
  FSReqBase* req_wrap = FSReqBase::from_req(req);
778
152
  FSReqAfterScope after(req_wrap, req);
779
780
152
  if (!after.Proceed()) {
781
8
    return;
782
  }
783
144
  Environment* env = req_wrap->env();
784
  Local<Value> error;
785
  int r;
786
144
  std::vector<Local<Value>> name_v;
787
788
  for (;;) {
789
    uv_dirent_t ent;
790
791
7551
    r = uv_fs_scandir_next(req, &ent);
792
7551
    if (r == UV_EOF)
793
144
      break;
794
7407
    if (r != 0) {
795
      return req_wrap->Reject(UVException(
796
          env->isolate(), r, nullptr, req_wrap->syscall(), req->path));
797
    }
798
799
    MaybeLocal<Value> filename =
800
      StringBytes::Encode(env->isolate(),
801
          ent.name,
802
          req_wrap->encoding(),
803
7407
          &error);
804
7407
    if (filename.IsEmpty())
805
      return req_wrap->Reject(error);
806
807
7407
    name_v.push_back(filename.ToLocalChecked());
808
7407
  }
809
810
288
  req_wrap->Resolve(Array::New(env->isolate(), name_v.data(), name_v.size()));
811
}
812
813
121
void AfterScanDirWithTypes(uv_fs_t* req) {
814
121
  FSReqBase* req_wrap = FSReqBase::from_req(req);
815
121
  FSReqAfterScope after(req_wrap, req);
816
817
121
  if (!after.Proceed()) {
818
1
    return;
819
  }
820
821
120
  Environment* env = req_wrap->env();
822
120
  Isolate* isolate = env->isolate();
823
  Local<Value> error;
824
  int r;
825
826
120
  std::vector<Local<Value>> name_v;
827
120
  std::vector<Local<Value>> type_v;
828
829
  for (;;) {
830
    uv_dirent_t ent;
831
832
137
    r = uv_fs_scandir_next(req, &ent);
833
137
    if (r == UV_EOF)
834
120
      break;
835
17
    if (r != 0) {
836
      return req_wrap->Reject(
837
          UVException(isolate, r, nullptr, req_wrap->syscall(), req->path));
838
    }
839
840
    MaybeLocal<Value> filename =
841
      StringBytes::Encode(isolate,
842
          ent.name,
843
          req_wrap->encoding(),
844
17
          &error);
845
17
    if (filename.IsEmpty())
846
      return req_wrap->Reject(error);
847
848
17
    name_v.push_back(filename.ToLocalChecked());
849
17
    type_v.emplace_back(Integer::New(isolate, ent.type));
850
17
  }
851
852
  Local<Value> result[] = {
853
    Array::New(isolate, name_v.data(), name_v.size()),
854
    Array::New(isolate, type_v.data(), type_v.size())
855
240
  };
856
240
  req_wrap->Resolve(Array::New(isolate, result, arraysize(result)));
857
}
858
859
287
void Access(const FunctionCallbackInfo<Value>& args) {
860
287
  Environment* env = Environment::GetCurrent(args);
861
287
  Isolate* isolate = env->isolate();
862
574
  HandleScope scope(isolate);
863
864
287
  const int argc = args.Length();
865
287
  CHECK_GE(argc, 2);
866
867
287
  CHECK(args[1]->IsInt32());
868
574
  int mode = args[1].As<Int32>()->Value();
869
870
574
  BufferValue path(isolate, args[0]);
871
287
  CHECK_NOT_NULL(*path);
872
873
287
  FSReqBase* req_wrap_async = GetReqWrap(args, 2);
874
287
  if (req_wrap_async != nullptr) {  // access(path, mode, req)
875
44
    AsyncCall(env, req_wrap_async, args, "access", UTF8, AfterNoArgs,
876
              uv_fs_access, *path, mode);
877
  } else {  // access(path, mode, undefined, ctx)
878
243
    CHECK_EQ(argc, 4);
879
486
    FSReqWrapSync req_wrap_sync;
880

245
    FS_SYNC_TRACE_BEGIN(access);
881
486
    SyncCall(env, args[3], &req_wrap_sync, "access", uv_fs_access, *path, mode);
882

245
    FS_SYNC_TRACE_END(access);
883
  }
884
287
}
885
886
887
55990
void Close(const FunctionCallbackInfo<Value>& args) {
888
55990
  Environment* env = Environment::GetCurrent(args);
889
890
55990
  const int argc = args.Length();
891
55990
  CHECK_GE(argc, 2);
892
893
55990
  CHECK(args[0]->IsInt32());
894
111980
  int fd = args[0].As<Int32>()->Value();
895
55990
  env->RemoveUnmanagedFd(fd);
896
897
55990
  FSReqBase* req_wrap_async = GetReqWrap(args, 1);
898
55990
  if (req_wrap_async != nullptr) {  // close(fd, req)
899
5289
    AsyncCall(env, req_wrap_async, args, "close", UTF8, AfterNoArgs,
900
              uv_fs_close, fd);
901
  } else {  // close(fd, undefined, ctx)
902
50701
    CHECK_EQ(argc, 3);
903
101402
    FSReqWrapSync req_wrap_sync;
904

50757
    FS_SYNC_TRACE_BEGIN(close);
905
50701
    SyncCall(env, args[2], &req_wrap_sync, "close", uv_fs_close, fd);
906

50757
    FS_SYNC_TRACE_END(close);
907
  }
908
55990
}
909
910
911
// Used to speed up module loading. Returns an array [string, boolean]
912
51198
static void InternalModuleReadJSON(const FunctionCallbackInfo<Value>& args) {
913
51198
  Environment* env = Environment::GetCurrent(args);
914
51198
  Isolate* isolate = env->isolate();
915
51198
  uv_loop_t* loop = env->event_loop();
916
917
102396
  CHECK(args[0]->IsString());
918
51198
  node::Utf8Value path(isolate, args[0]);
919
920
51198
  if (strlen(*path) != path.length()) {
921
3
    args.GetReturnValue().Set(Array::New(isolate));
922
3
    return;  // Contains a nul byte.
923
  }
924
  uv_fs_t open_req;
925
51195
  const int fd = uv_fs_open(loop, &open_req, *path, O_RDONLY, 0, nullptr);
926
51195
  uv_fs_req_cleanup(&open_req);
927
928
51195
  if (fd < 0) {
929
45637
    args.GetReturnValue().Set(Array::New(isolate));
930
45637
    return;
931
  }
932
933
5558
  auto defer_close = OnScopeLeave([fd, loop]() {
934
    uv_fs_t close_req;
935
5558
    CHECK_EQ(0, uv_fs_close(loop, &close_req, fd, nullptr));
936
5558
    uv_fs_req_cleanup(&close_req);
937
5558
  });
938
939
5558
  const size_t kBlockSize = 32 << 10;
940
5558
  std::vector<char> chars;
941
5558
  int64_t offset = 0;
942
  ssize_t numchars;
943
  do {
944
5558
    const size_t start = chars.size();
945
5558
    chars.resize(start + kBlockSize);
946
947
    uv_buf_t buf;
948
5558
    buf.base = &chars[start];
949
5558
    buf.len = kBlockSize;
950
951
    uv_fs_t read_req;
952
5558
    numchars = uv_fs_read(loop, &read_req, fd, &buf, 1, offset, nullptr);
953
5558
    uv_fs_req_cleanup(&read_req);
954
955
5558
    if (numchars < 0) {
956
1
      args.GetReturnValue().Set(Array::New(isolate));
957
1
      return;
958
    }
959
5557
    offset += numchars;
960
5557
  } while (static_cast<size_t>(numchars) == kBlockSize);
961
962
5557
  size_t start = 0;
963

5557
  if (offset >= 3 && 0 == memcmp(&chars[0], "\xEF\xBB\xBF", 3)) {
964
1
    start = 3;  // Skip UTF-8 BOM.
965
  }
966
967
5557
  const size_t size = offset - start;
968
5557
  char* p = &chars[start];
969
5557
  char* pe = &chars[size];
970
  char* pos[2];
971
5557
  char** ppos = &pos[0];
972
973
82775
  while (p < pe) {
974
82763
    char c = *p++;
975

82763
    if (c == '\\' && p < pe && *p == '"') p++;
976
82763
    if (c != '"') continue;
977
12752
    *ppos++ = p;
978
12752
    if (ppos < &pos[2]) continue;
979
6376
    ppos = &pos[0];
980
981
6376
    char* s = &pos[0][0];
982
6376
    char* se = &pos[1][-1];  // Exclude quote.
983
6376
    size_t n = se - s;
984
985
6376
    if (n == 4) {
986
5538
      if (0 == memcmp(s, "main", 4)) break;
987
5497
      if (0 == memcmp(s, "name", 4)) break;
988
27
      if (0 == memcmp(s, "type", 4)) break;
989
838
    } else if (n == 7) {
990
12
      if (0 == memcmp(s, "exports", 7)) break;
991
6
      if (0 == memcmp(s, "imports", 7)) break;
992
    }
993
  }
994
995
996
  Local<Value> return_value[] = {
997
5557
    String::NewFromUtf8(isolate,
998
5557
                        &chars[start],
999
                        v8::NewStringType::kNormal,
1000
5557
                        size).ToLocalChecked(),
1001
    Boolean::New(isolate, p < pe ? true : false)
1002
16671
  };
1003
11114
  args.GetReturnValue().Set(
1004
    Array::New(isolate, return_value, arraysize(return_value)));
1005
}
1006
1007
// Used to speed up module loading.  Returns 0 if the path refers to
1008
// a file, 1 when it's a directory or < 0 on error (usually -ENOENT.)
1009
// The speedup comes from not creating thousands of Stat and Error objects.
1010
138016
static void InternalModuleStat(const FunctionCallbackInfo<Value>& args) {
1011
138016
  Environment* env = Environment::GetCurrent(args);
1012
1013
276032
  CHECK(args[0]->IsString());
1014
138016
  node::Utf8Value path(env->isolate(), args[0]);
1015
1016
  uv_fs_t req;
1017
138016
  int rc = uv_fs_stat(env->event_loop(), &req, *path, nullptr);
1018
138016
  if (rc == 0) {
1019
68111
    const uv_stat_t* const s = static_cast<const uv_stat_t*>(req.ptr);
1020
68111
    rc = !!(s->st_mode & S_IFDIR);
1021
  }
1022
138016
  uv_fs_req_cleanup(&req);
1023
1024
276032
  args.GetReturnValue().Set(rc);
1025
138016
}
1026
1027
17110
static void Stat(const FunctionCallbackInfo<Value>& args) {
1028
17110
  BindingData* binding_data = Environment::GetBindingData<BindingData>(args);
1029
17110
  Environment* env = binding_data->env();
1030
1031
17110
  const int argc = args.Length();
1032
17110
  CHECK_GE(argc, 2);
1033
1034
17110
  BufferValue path(env->isolate(), args[0]);
1035
17110
  CHECK_NOT_NULL(*path);
1036
1037
17110
  bool use_bigint = args[1]->IsTrue();
1038
17110
  FSReqBase* req_wrap_async = GetReqWrap(args, 2, use_bigint);
1039
17110
  if (req_wrap_async != nullptr) {  // stat(path, use_bigint, req)
1040
2467
    AsyncCall(env, req_wrap_async, args, "stat", UTF8, AfterStat,
1041
              uv_fs_stat, *path);
1042
  } else {  // stat(path, use_bigint, undefined, ctx)
1043
14643
    CHECK_EQ(argc, 4);
1044
14643
    FSReqWrapSync req_wrap_sync;
1045

14645
    FS_SYNC_TRACE_BEGIN(stat);
1046
29286
    int err = SyncCall(env, args[3], &req_wrap_sync, "stat", uv_fs_stat, *path);
1047

14645
    FS_SYNC_TRACE_END(stat);
1048
14643
    if (err != 0) {
1049
660
      return;  // error info is in ctx
1050
    }
1051
1052
    Local<Value> arr = FillGlobalStatsArray(binding_data, use_bigint,
1053
13983
        static_cast<const uv_stat_t*>(req_wrap_sync.req.ptr));
1054
27966
    args.GetReturnValue().Set(arr);
1055
  }
1056
}
1057
1058
105556
static void LStat(const FunctionCallbackInfo<Value>& args) {
1059
105556
  BindingData* binding_data = Environment::GetBindingData<BindingData>(args);
1060
105556
  Environment* env = binding_data->env();
1061
1062
105556
  const int argc = args.Length();
1063
105556
  CHECK_GE(argc, 3);
1064
1065
105556
  BufferValue path(env->isolate(), args[0]);
1066
105556
  CHECK_NOT_NULL(*path);
1067
1068
105556
  bool use_bigint = args[1]->IsTrue();
1069
105556
  FSReqBase* req_wrap_async = GetReqWrap(args, 2, use_bigint);
1070
105556
  if (req_wrap_async != nullptr) {  // lstat(path, use_bigint, req)
1071
4700
    AsyncCall(env, req_wrap_async, args, "lstat", UTF8, AfterStat,
1072
              uv_fs_lstat, *path);
1073
  } else {  // lstat(path, use_bigint, undefined, ctx)
1074
100856
    CHECK_EQ(argc, 4);
1075
100856
    FSReqWrapSync req_wrap_sync;
1076

100873
    FS_SYNC_TRACE_BEGIN(lstat);
1077
201712
    int err = SyncCall(env, args[3], &req_wrap_sync, "lstat", uv_fs_lstat,
1078
                       *path);
1079

100873
    FS_SYNC_TRACE_END(lstat);
1080
100856
    if (err != 0) {
1081
419
      return;  // error info is in ctx
1082
    }
1083
1084
    Local<Value> arr = FillGlobalStatsArray(binding_data, use_bigint,
1085
100437
        static_cast<const uv_stat_t*>(req_wrap_sync.req.ptr));
1086
200874
    args.GetReturnValue().Set(arr);
1087
  }
1088
}
1089
1090
46214
static void FStat(const FunctionCallbackInfo<Value>& args) {
1091
46214
  BindingData* binding_data = Environment::GetBindingData<BindingData>(args);
1092
46214
  Environment* env = binding_data->env();
1093
1094
46214
  const int argc = args.Length();
1095
46214
  CHECK_GE(argc, 2);
1096
1097
46214
  CHECK(args[0]->IsInt32());
1098
92428
  int fd = args[0].As<Int32>()->Value();
1099
1100
46214
  bool use_bigint = args[1]->IsTrue();
1101
46214
  FSReqBase* req_wrap_async = GetReqWrap(args, 2, use_bigint);
1102
46214
  if (req_wrap_async != nullptr) {  // fstat(fd, use_bigint, req)
1103
982
    AsyncCall(env, req_wrap_async, args, "fstat", UTF8, AfterStat,
1104
              uv_fs_fstat, fd);
1105
  } else {  // fstat(fd, use_bigint, undefined, ctx)
1106
45232
    CHECK_EQ(argc, 4);
1107
45232
    FSReqWrapSync req_wrap_sync;
1108

45240
    FS_SYNC_TRACE_BEGIN(fstat);
1109
45232
    int err = SyncCall(env, args[3], &req_wrap_sync, "fstat", uv_fs_fstat, fd);
1110

45240
    FS_SYNC_TRACE_END(fstat);
1111
45232
    if (err != 0) {
1112
21
      return;  // error info is in ctx
1113
    }
1114
1115
    Local<Value> arr = FillGlobalStatsArray(binding_data, use_bigint,
1116
45211
        static_cast<const uv_stat_t*>(req_wrap_sync.req.ptr));
1117
90422
    args.GetReturnValue().Set(arr);
1118
  }
1119
}
1120
1121
348
static void Symlink(const FunctionCallbackInfo<Value>& args) {
1122
348
  Environment* env = Environment::GetCurrent(args);
1123
348
  Isolate* isolate = env->isolate();
1124
1125
348
  const int argc = args.Length();
1126
348
  CHECK_GE(argc, 4);
1127
1128
696
  BufferValue target(isolate, args[0]);
1129
348
  CHECK_NOT_NULL(*target);
1130
696
  BufferValue path(isolate, args[1]);
1131
348
  CHECK_NOT_NULL(*path);
1132
1133
348
  CHECK(args[2]->IsInt32());
1134
696
  int flags = args[2].As<Int32>()->Value();
1135
1136
348
  FSReqBase* req_wrap_async = GetReqWrap(args, 3);
1137
348
  if (req_wrap_async != nullptr) {  // symlink(target, path, flags, req)
1138
22
    AsyncDestCall(env, req_wrap_async, args, "symlink", *path, path.length(),
1139
                  UTF8, AfterNoArgs, uv_fs_symlink, *target, *path, flags);
1140
  } else {  // symlink(target, path, flags, undefinec, ctx)
1141
326
    CHECK_EQ(argc, 5);
1142
652
    FSReqWrapSync req_wrap_sync;
1143

330
    FS_SYNC_TRACE_BEGIN(symlink);
1144
652
    SyncCall(env, args[4], &req_wrap_sync, "symlink",
1145
             uv_fs_symlink, *target, *path, flags);
1146

330
    FS_SYNC_TRACE_END(symlink);
1147
  }
1148
348
}
1149
1150
9
static void Link(const FunctionCallbackInfo<Value>& args) {
1151
9
  Environment* env = Environment::GetCurrent(args);
1152
9
  Isolate* isolate = env->isolate();
1153
1154
9
  const int argc = args.Length();
1155
9
  CHECK_GE(argc, 3);
1156
1157
18
  BufferValue src(isolate, args[0]);
1158
9
  CHECK_NOT_NULL(*src);
1159
1160
18
  BufferValue dest(isolate, args[1]);
1161
9
  CHECK_NOT_NULL(*dest);
1162
1163
9
  FSReqBase* req_wrap_async = GetReqWrap(args, 2);
1164
9
  if (req_wrap_async != nullptr) {  // link(src, dest, req)
1165
4
    AsyncDestCall(env, req_wrap_async, args, "link", *dest, dest.length(), UTF8,
1166
                  AfterNoArgs, uv_fs_link, *src, *dest);
1167
  } else {  // link(src, dest)
1168
5
    CHECK_EQ(argc, 4);
1169
10
    FSReqWrapSync req_wrap_sync;
1170

11
    FS_SYNC_TRACE_BEGIN(link);
1171
10
    SyncCall(env, args[3], &req_wrap_sync, "link",
1172
             uv_fs_link, *src, *dest);
1173

11
    FS_SYNC_TRACE_END(link);
1174
  }
1175
9
}
1176
1177
102
static void ReadLink(const FunctionCallbackInfo<Value>& args) {
1178
102
  Environment* env = Environment::GetCurrent(args);
1179
102
  Isolate* isolate = env->isolate();
1180
1181
102
  const int argc = args.Length();
1182
102
  CHECK_GE(argc, 3);
1183
1184
102
  BufferValue path(isolate, args[0]);
1185
102
  CHECK_NOT_NULL(*path);
1186
1187
102
  const enum encoding encoding = ParseEncoding(isolate, args[1], UTF8);
1188
1189
102
  FSReqBase* req_wrap_async = GetReqWrap(args, 2);
1190
102
  if (req_wrap_async != nullptr) {  // readlink(path, encoding, req)
1191
42
    AsyncCall(env, req_wrap_async, args, "readlink", encoding, AfterStringPtr,
1192
              uv_fs_readlink, *path);
1193
  } else {
1194
60
    CHECK_EQ(argc, 4);
1195
60
    FSReqWrapSync req_wrap_sync;
1196

62
    FS_SYNC_TRACE_BEGIN(readlink);
1197
120
    int err = SyncCall(env, args[3], &req_wrap_sync, "readlink",
1198
                       uv_fs_readlink, *path);
1199

62
    FS_SYNC_TRACE_END(readlink);
1200
60
    if (err < 0) {
1201
2
      return;  // syscall failed, no need to continue, error info is in ctx
1202
    }
1203
58
    const char* link_path = static_cast<const char*>(req_wrap_sync.req.ptr);
1204
1205
    Local<Value> error;
1206
    MaybeLocal<Value> rc = StringBytes::Encode(isolate,
1207
                                               link_path,
1208
                                               encoding,
1209
58
                                               &error);
1210
58
    if (rc.IsEmpty()) {
1211
      Local<Object> ctx = args[3].As<Object>();
1212
      ctx->Set(env->context(), env->error_string(), error).Check();
1213
      return;
1214
    }
1215
1216
116
    args.GetReturnValue().Set(rc.ToLocalChecked());
1217
  }
1218
}
1219
1220
6
static void Rename(const FunctionCallbackInfo<Value>& args) {
1221
6
  Environment* env = Environment::GetCurrent(args);
1222
6
  Isolate* isolate = env->isolate();
1223
1224
6
  const int argc = args.Length();
1225
6
  CHECK_GE(argc, 3);
1226
1227
12
  BufferValue old_path(isolate, args[0]);
1228
6
  CHECK_NOT_NULL(*old_path);
1229
12
  BufferValue new_path(isolate, args[1]);
1230
6
  CHECK_NOT_NULL(*new_path);
1231
1232
6
  FSReqBase* req_wrap_async = GetReqWrap(args, 2);
1233
6
  if (req_wrap_async != nullptr) {
1234
3
    AsyncDestCall(env, req_wrap_async, args, "rename", *new_path,
1235
                  new_path.length(), UTF8, AfterNoArgs, uv_fs_rename,
1236
                  *old_path, *new_path);
1237
  } else {
1238
3
    CHECK_EQ(argc, 4);
1239
6
    FSReqWrapSync req_wrap_sync;
1240

5
    FS_SYNC_TRACE_BEGIN(rename);
1241
6
    SyncCall(env, args[3], &req_wrap_sync, "rename", uv_fs_rename,
1242
             *old_path, *new_path);
1243

5
    FS_SYNC_TRACE_END(rename);
1244
  }
1245
6
}
1246
1247
69
static void FTruncate(const FunctionCallbackInfo<Value>& args) {
1248
69
  Environment* env = Environment::GetCurrent(args);
1249
1250
69
  const int argc = args.Length();
1251
69
  CHECK_GE(argc, 3);
1252
1253
69
  CHECK(args[0]->IsInt32());
1254
138
  const int fd = args[0].As<Int32>()->Value();
1255
1256
69
  CHECK(IsSafeJsInt(args[1]));
1257
138
  const int64_t len = args[1].As<Integer>()->Value();
1258
1259
69
  FSReqBase* req_wrap_async = GetReqWrap(args, 2);
1260
69
  if (req_wrap_async != nullptr) {
1261
54
    AsyncCall(env, req_wrap_async, args, "ftruncate", UTF8, AfterNoArgs,
1262
              uv_fs_ftruncate, fd, len);
1263
  } else {
1264
15
    CHECK_EQ(argc, 4);
1265
30
    FSReqWrapSync req_wrap_sync;
1266

17
    FS_SYNC_TRACE_BEGIN(ftruncate);
1267
15
    SyncCall(env, args[3], &req_wrap_sync, "ftruncate", uv_fs_ftruncate, fd,
1268
             len);
1269

17
    FS_SYNC_TRACE_END(ftruncate);
1270
  }
1271
69
}
1272
1273
7
static void Fdatasync(const FunctionCallbackInfo<Value>& args) {
1274
7
  Environment* env = Environment::GetCurrent(args);
1275
1276
7
  const int argc = args.Length();
1277
7
  CHECK_GE(argc, 2);
1278
1279
7
  CHECK(args[0]->IsInt32());
1280
14
  const int fd = args[0].As<Int32>()->Value();
1281
1282
7
  FSReqBase* req_wrap_async = GetReqWrap(args, 1);
1283
7
  if (req_wrap_async != nullptr) {
1284
4
    AsyncCall(env, req_wrap_async, args, "fdatasync", UTF8, AfterNoArgs,
1285
              uv_fs_fdatasync, fd);
1286
  } else {
1287
3
    CHECK_EQ(argc, 3);
1288
6
    FSReqWrapSync req_wrap_sync;
1289

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

5
    FS_SYNC_TRACE_END(fdatasync);
1292
  }
1293
7
}
1294
1295
21
static void Fsync(const FunctionCallbackInfo<Value>& args) {
1296
21
  Environment* env = Environment::GetCurrent(args);
1297
1298
21
  const int argc = args.Length();
1299
21
  CHECK_GE(argc, 2);
1300
1301
21
  CHECK(args[0]->IsInt32());
1302
42
  const int fd = args[0].As<Int32>()->Value();
1303
1304
21
  FSReqBase* req_wrap_async = GetReqWrap(args, 1);
1305
21
  if (req_wrap_async != nullptr) {
1306
4
    AsyncCall(env, req_wrap_async, args, "fsync", UTF8, AfterNoArgs,
1307
              uv_fs_fsync, fd);
1308
  } else {
1309
17
    CHECK_EQ(argc, 3);
1310
34
    FSReqWrapSync req_wrap_sync;
1311

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

19
    FS_SYNC_TRACE_END(fsync);
1314
  }
1315
21
}
1316
1317
2419
static void Unlink(const FunctionCallbackInfo<Value>& args) {
1318
2419
  Environment* env = Environment::GetCurrent(args);
1319
1320
2419
  const int argc = args.Length();
1321
2419
  CHECK_GE(argc, 2);
1322
1323
4838
  BufferValue path(env->isolate(), args[0]);
1324
2419
  CHECK_NOT_NULL(*path);
1325
1326
2419
  FSReqBase* req_wrap_async = GetReqWrap(args, 1);
1327
2419
  if (req_wrap_async != nullptr) {
1328
965
    AsyncCall(env, req_wrap_async, args, "unlink", UTF8, AfterNoArgs,
1329
              uv_fs_unlink, *path);
1330
  } else {
1331
1454
    CHECK_EQ(argc, 3);
1332
2908
    FSReqWrapSync req_wrap_sync;
1333

1509
    FS_SYNC_TRACE_BEGIN(unlink);
1334
2908
    SyncCall(env, args[2], &req_wrap_sync, "unlink", uv_fs_unlink, *path);
1335

1509
    FS_SYNC_TRACE_END(unlink);
1336
  }
1337
2419
}
1338
1339
1697
static void RMDir(const FunctionCallbackInfo<Value>& args) {
1340
1697
  Environment* env = Environment::GetCurrent(args);
1341
1342
1697
  const int argc = args.Length();
1343
1697
  CHECK_GE(argc, 2);
1344
1345
3394
  BufferValue path(env->isolate(), args[0]);
1346
1697
  CHECK_NOT_NULL(*path);
1347
1348
1697
  FSReqBase* req_wrap_async = GetReqWrap(args, 1);  // rmdir(path, req)
1349
1697
  if (req_wrap_async != nullptr) {
1350
217
    AsyncCall(env, req_wrap_async, args, "rmdir", UTF8, AfterNoArgs,
1351
              uv_fs_rmdir, *path);
1352
  } else {  // rmdir(path, undefined, ctx)
1353
1480
    CHECK_EQ(argc, 3);
1354
2960
    FSReqWrapSync req_wrap_sync;
1355

1486
    FS_SYNC_TRACE_BEGIN(rmdir);
1356
2960
    SyncCall(env, args[2], &req_wrap_sync, "rmdir",
1357
             uv_fs_rmdir, *path);
1358

1486
    FS_SYNC_TRACE_END(rmdir);
1359
  }
1360
1697
}
1361
1362
5700
int MKDirpSync(uv_loop_t* loop,
1363
               uv_fs_t* req,
1364
               const std::string& path,
1365
               int mode,
1366
               uv_fs_cb cb) {
1367
5700
  FSReqWrapSync* req_wrap = ContainerOf(&FSReqWrapSync::req, req);
1368
1369
  // on the first iteration of algorithm, stash state information.
1370
5700
  if (req_wrap->continuation_data() == nullptr) {
1371
5700
    req_wrap->set_continuation_data(
1372
11400
        std::make_unique<FSContinuationData>(req, mode, cb));
1373
5700
    req_wrap->continuation_data()->PushPath(std::move(path));
1374
  }
1375
1376
11258
  while (req_wrap->continuation_data()->paths().size() > 0) {
1377
5848
    std::string next_path = req_wrap->continuation_data()->PopPath();
1378
5848
    int err = uv_fs_mkdir(loop, req, next_path.c_str(), mode, nullptr);
1379
    while (true) {
1380

5849
      switch (err) {
1381
        // Note: uv_fs_req_cleanup in terminal paths will be called by
1382
        // ~FSReqWrapSync():
1383
359
        case 0:
1384
359
          req_wrap->continuation_data()->MaybeSetFirstPath(next_path);
1385
359
          if (req_wrap->continuation_data()->paths().size() == 0) {
1386
286
            return 0;
1387
          }
1388
73
          break;
1389
2
        case UV_EACCES:
1390
        case UV_ENOTDIR:
1391
        case UV_EPERM: {
1392
2
          return err;
1393
        }
1394
75
        case UV_ENOENT: {
1395
          std::string dirname = next_path.substr(0,
1396
75
                                        next_path.find_last_of(kPathSeparator));
1397
75
          if (dirname != next_path) {
1398
74
            req_wrap->continuation_data()->PushPath(std::move(next_path));
1399
74
            req_wrap->continuation_data()->PushPath(std::move(dirname));
1400
1
          } else if (req_wrap->continuation_data()->paths().size() == 0) {
1401
1
            err = UV_EEXIST;
1402
1
            continue;
1403
          }
1404
74
          break;
1405
        }
1406
5413
        default:
1407
5413
          uv_fs_req_cleanup(req);
1408
5413
          int orig_err = err;
1409
5413
          err = uv_fs_stat(loop, req, next_path.c_str(), nullptr);
1410

5413
          if (err == 0 && !S_ISDIR(req->statbuf.st_mode)) {
1411
1
            uv_fs_req_cleanup(req);
1412

2
            if (orig_err == UV_EEXIST &&
1413
1
              req_wrap->continuation_data()->paths().size() > 0) {
1414
              return UV_ENOTDIR;
1415
            }
1416
1
            return UV_EEXIST;
1417
          }
1418
5412
          if (err < 0) return err;
1419
5411
          break;
1420
      }
1421
5558
      break;
1422
1
    }
1423
5558
    uv_fs_req_cleanup(req);
1424
  }
1425
1426
5410
  return 0;
1427
}
1428
1429
588
int MKDirpAsync(uv_loop_t* loop,
1430
                uv_fs_t* req,
1431
                const char* path,
1432
                int mode,
1433
                uv_fs_cb cb) {
1434
588
  FSReqBase* req_wrap = FSReqBase::from_req(req);
1435
  // on the first iteration of algorithm, stash state information.
1436
588
  if (req_wrap->continuation_data() == nullptr) {
1437
344
    req_wrap->set_continuation_data(
1438
688
        std::make_unique<FSContinuationData>(req, mode, cb));
1439
344
    req_wrap->continuation_data()->PushPath(std::move(path));
1440
  }
1441
1442
  // on each iteration of algorithm, mkdir directory on top of stack.
1443
588
  std::string next_path = req_wrap->continuation_data()->PopPath();
1444
588
  int err = uv_fs_mkdir(loop, req, next_path.c_str(), mode,
1445
588
                        uv_fs_callback_t{[](uv_fs_t* req) {
1446
588
    FSReqBase* req_wrap = FSReqBase::from_req(req);
1447
588
    Environment* env = req_wrap->env();
1448
588
    uv_loop_t* loop = env->event_loop();
1449
1176
    std::string path = req->path;
1450
588
    int err = static_cast<int>(req->result);
1451
1452
    while (true) {
1453

589
      switch (err) {
1454
        // Note: uv_fs_req_cleanup in terminal paths will be called by
1455
        // FSReqAfterScope::~FSReqAfterScope()
1456
229
        case 0: {
1457
229
          if (req_wrap->continuation_data()->paths().size() == 0) {
1458
218
            req_wrap->continuation_data()->MaybeSetFirstPath(path);
1459
218
            req_wrap->continuation_data()->Done(0);
1460
          } else {
1461
11
            req_wrap->continuation_data()->MaybeSetFirstPath(path);
1462
11
            uv_fs_req_cleanup(req);
1463
11
            MKDirpAsync(loop, req, path.c_str(),
1464
                        req_wrap->continuation_data()->mode(), nullptr);
1465
          }
1466
229
          break;
1467
        }
1468
3
        case UV_EACCES:
1469
        case UV_ENOTDIR:
1470
        case UV_EPERM: {
1471
3
          req_wrap->continuation_data()->Done(err);
1472
3
          break;
1473
        }
1474
123
        case UV_ENOENT: {
1475
          std::string dirname = path.substr(0,
1476
123
                                            path.find_last_of(kPathSeparator));
1477
123
          if (dirname != path) {
1478
122
            req_wrap->continuation_data()->PushPath(std::move(path));
1479
122
            req_wrap->continuation_data()->PushPath(std::move(dirname));
1480
1
          } else if (req_wrap->continuation_data()->paths().size() == 0) {
1481
1
            err = UV_EEXIST;
1482
1
            continue;
1483
          }
1484
122
          uv_fs_req_cleanup(req);
1485
122
          MKDirpAsync(loop, req, path.c_str(),
1486
                      req_wrap->continuation_data()->mode(), nullptr);
1487
122
          break;
1488
        }
1489
234
        default:
1490
234
          uv_fs_req_cleanup(req);
1491
          // Stash err for use in the callback.
1492
234
          req->data = reinterpret_cast<void*>(static_cast<intptr_t>(err));
1493
234
          int err = uv_fs_stat(loop, req, path.c_str(),
1494
234
                               uv_fs_callback_t{[](uv_fs_t* req) {
1495
234
            FSReqBase* req_wrap = FSReqBase::from_req(req);
1496
234
            int err = static_cast<int>(req->result);
1497

468
            if (reinterpret_cast<intptr_t>(req->data) == UV_EEXIST &&
1498
234
                  req_wrap->continuation_data()->paths().size() > 0) {
1499

111
              if (err == 0 && S_ISDIR(req->statbuf.st_mode)) {
1500
111
                Environment* env = req_wrap->env();
1501
111
                uv_loop_t* loop = env->event_loop();
1502
111
                std::string path = req->path;
1503
111
                uv_fs_req_cleanup(req);
1504
111
                MKDirpAsync(loop, req, path.c_str(),
1505
                            req_wrap->continuation_data()->mode(), nullptr);
1506
111
                return;
1507
              }
1508
              err = UV_ENOTDIR;
1509
            }
1510
            // verify that the path pointed to is actually a directory.
1511

123
            if (err == 0 && !S_ISDIR(req->statbuf.st_mode)) err = UV_EEXIST;
1512
123
            req_wrap->continuation_data()->Done(err);
1513
234
          }});
1514
234
          if (err < 0) req_wrap->continuation_data()->Done(err);
1515
234
          break;
1516
      }
1517
588
      break;
1518
1
    }
1519
588
  }});
1520
1521
588
  return err;
1522
}
1523
1524
270
int CallMKDirpSync(Environment* env, const FunctionCallbackInfo<Value>& args,
1525
                   FSReqWrapSync* req_wrap, const char* path, int mode) {
1526
270
  env->PrintSyncTrace();
1527
270
  int err = MKDirpSync(env->event_loop(), &req_wrap->req, path, mode,
1528
                       nullptr);
1529
270
  if (err < 0) {
1530
4
    v8::Local<v8::Context> context = env->context();
1531
4
    v8::Local<v8::Object> ctx_obj = args[4].As<v8::Object>();
1532
4
    v8::Isolate* isolate = env->isolate();
1533
4
    ctx_obj->Set(context,
1534
                 env->errno_string(),
1535
16
                 v8::Integer::New(isolate, err)).Check();
1536
4
    ctx_obj->Set(context,
1537
                 env->syscall_string(),
1538
16
                 OneByteString(isolate, "mkdir")).Check();
1539
  }
1540
270
  return err;
1541
}
1542
1543
1661
static void MKDir(const FunctionCallbackInfo<Value>& args) {
1544
1661
  Environment* env = Environment::GetCurrent(args);
1545
1546
1661
  const int argc = args.Length();
1547
1661
  CHECK_GE(argc, 4);
1548
1549
1661
  BufferValue path(env->isolate(), args[0]);
1550
1661
  CHECK_NOT_NULL(*path);
1551
1552
1661
  CHECK(args[1]->IsInt32());
1553
3322
  const int mode = args[1].As<Int32>()->Value();
1554
1555
1661
  CHECK(args[2]->IsBoolean());
1556
1661
  bool mkdirp = args[2]->IsTrue();
1557
1558
1661
  FSReqBase* req_wrap_async = GetReqWrap(args, 3);
1559
1661
  if (req_wrap_async != nullptr) {  // mkdir(path, mode, req)
1560

541
    AsyncCall(env, req_wrap_async, args, "mkdir", UTF8,
1561
              mkdirp ? AfterMkdirp : AfterNoArgs,
1562
              mkdirp ? MKDirpAsync : uv_fs_mkdir, *path, mode);
1563
  } else {  // mkdir(path, mode, undefined, ctx)
1564
1120
    CHECK_EQ(argc, 5);
1565
1120
    FSReqWrapSync req_wrap_sync;
1566

1124
    FS_SYNC_TRACE_BEGIN(mkdir);
1567
1120
    if (mkdirp) {
1568
270
      int err = CallMKDirpSync(env, args, &req_wrap_sync, *path, mode);
1569

536
      if (err == 0 &&
1570
266
          !req_wrap_sync.continuation_data()->first_path().empty()) {
1571
        Local<Value> error;
1572
264
        std::string first_path(req_wrap_sync.continuation_data()->first_path());
1573
264
        FromNamespacedPath(&first_path);
1574
        MaybeLocal<Value> path = StringBytes::Encode(env->isolate(),
1575
                                                     first_path.c_str(),
1576
264
                                                     UTF8, &error);
1577
264
        if (path.IsEmpty()) {
1578
          Local<Object> ctx = args[4].As<Object>();
1579
          ctx->Set(env->context(), env->error_string(), error).Check();
1580
          return;
1581
        }
1582
528
        args.GetReturnValue().Set(path.ToLocalChecked());
1583
      }
1584
    } else {
1585
1700
      SyncCall(env, args[4], &req_wrap_sync, "mkdir",
1586
               uv_fs_mkdir, *path, mode);
1587
    }
1588

1124
    FS_SYNC_TRACE_END(mkdir);
1589
  }
1590
}
1591
1592
42
static void RealPath(const FunctionCallbackInfo<Value>& args) {
1593
42
  Environment* env = Environment::GetCurrent(args);
1594
42
  Isolate* isolate = env->isolate();
1595
1596
42
  const int argc = args.Length();
1597
42
  CHECK_GE(argc, 3);
1598
1599
42
  BufferValue path(isolate, args[0]);
1600
42
  CHECK_NOT_NULL(*path);
1601
1602
42
  const enum encoding encoding = ParseEncoding(isolate, args[1], UTF8);
1603
1604
42
  FSReqBase* req_wrap_async = GetReqWrap(args, 2);
1605
42
  if (req_wrap_async != nullptr) {  // realpath(path, encoding, req)
1606
22
    AsyncCall(env, req_wrap_async, args, "realpath", encoding, AfterStringPtr,
1607
              uv_fs_realpath, *path);
1608
  } else {  // realpath(path, encoding, undefined, ctx)
1609
20
    CHECK_EQ(argc, 4);
1610
20
    FSReqWrapSync req_wrap_sync;
1611

22
    FS_SYNC_TRACE_BEGIN(realpath);
1612
40
    int err = SyncCall(env, args[3], &req_wrap_sync, "realpath",
1613
                       uv_fs_realpath, *path);
1614

22
    FS_SYNC_TRACE_END(realpath);
1615
20
    if (err < 0) {
1616
2
      return;  // syscall failed, no need to continue, error info is in ctx
1617
    }
1618
1619
18
    const char* link_path = static_cast<const char*>(req_wrap_sync.req.ptr);
1620
1621
    Local<Value> error;
1622
    MaybeLocal<Value> rc = StringBytes::Encode(isolate,
1623
                                               link_path,
1624
                                               encoding,
1625
18
                                               &error);
1626
18
    if (rc.IsEmpty()) {
1627
      Local<Object> ctx = args[3].As<Object>();
1628
      ctx->Set(env->context(), env->error_string(), error).Check();
1629
      return;
1630
    }
1631
1632
36
    args.GetReturnValue().Set(rc.ToLocalChecked());
1633
  }
1634
}
1635
1636
14035
static void ReadDir(const FunctionCallbackInfo<Value>& args) {
1637
14035
  Environment* env = Environment::GetCurrent(args);
1638
14035
  Isolate* isolate = env->isolate();
1639
1640
14035
  const int argc = args.Length();
1641
14035
  CHECK_GE(argc, 3);
1642
1643
14035
  BufferValue path(isolate, args[0]);
1644
14035
  CHECK_NOT_NULL(*path);
1645
1646
14035
  const enum encoding encoding = ParseEncoding(isolate, args[1], UTF8);
1647
1648
14035
  bool with_types = args[2]->IsTrue();
1649
1650
14035
  FSReqBase* req_wrap_async = GetReqWrap(args, 3);
1651
14035
  if (req_wrap_async != nullptr) {  // readdir(path, encoding, withTypes, req)
1652
273
    if (with_types) {
1653
121
      AsyncCall(env, req_wrap_async, args, "scandir", encoding,
1654
                AfterScanDirWithTypes, uv_fs_scandir, *path, 0 /*flags*/);
1655
    } else {
1656
152
      AsyncCall(env, req_wrap_async, args, "scandir", encoding,
1657
                AfterScanDir, uv_fs_scandir, *path, 0 /*flags*/);
1658
    }
1659
  } else {  // readdir(path, encoding, withTypes, undefined, ctx)
1660
13762
    CHECK_EQ(argc, 5);
1661
13762
    FSReqWrapSync req_wrap_sync;
1662

13764
    FS_SYNC_TRACE_BEGIN(readdir);
1663
27524
    int err = SyncCall(env, args[4], &req_wrap_sync, "scandir",
1664
                       uv_fs_scandir, *path, 0 /*flags*/);
1665

13764
    FS_SYNC_TRACE_END(readdir);
1666
13762
    if (err < 0) {
1667
133
      return;  // syscall failed, no need to continue, error info is in ctx
1668
    }
1669
1670
13629
    CHECK_GE(req_wrap_sync.req.result, 0);
1671
    int r;
1672
13629
    std::vector<Local<Value>> name_v;
1673
13629
    std::vector<Local<Value>> type_v;
1674
1675
    for (;;) {
1676
      uv_dirent_t ent;
1677
1678
765667
      r = uv_fs_scandir_next(&(req_wrap_sync.req), &ent);
1679
765667
      if (r == UV_EOF)
1680
13629
        break;
1681
752038
      if (r != 0) {
1682
        Local<Object> ctx = args[4].As<Object>();
1683
        ctx->Set(env->context(), env->errno_string(),
1684
                 Integer::New(isolate, r)).Check();
1685
        ctx->Set(env->context(), env->syscall_string(),
1686
                 OneByteString(isolate, "readdir")).Check();
1687
        return;
1688
      }
1689
1690
      Local<Value> error;
1691
      MaybeLocal<Value> filename = StringBytes::Encode(isolate,
1692
                                                       ent.name,
1693
                                                       encoding,
1694
752038
                                                       &error);
1695
1696
752038
      if (filename.IsEmpty()) {
1697
        Local<Object> ctx = args[4].As<Object>();
1698
        ctx->Set(env->context(), env->error_string(), error).Check();
1699
        return;
1700
      }
1701
1702
752038
      name_v.push_back(filename.ToLocalChecked());
1703
1704
752038
      if (with_types) {
1705
47681
        type_v.emplace_back(Integer::New(isolate, ent.type));
1706
      }
1707
752038
    }
1708
1709
1710
13629
    Local<Array> names = Array::New(isolate, name_v.data(), name_v.size());
1711
13629
    if (with_types) {
1712
      Local<Value> result[] = {
1713
        names,
1714
        Array::New(isolate, type_v.data(), type_v.size())
1715
386
      };
1716
386
      args.GetReturnValue().Set(Array::New(isolate, result, arraysize(result)));
1717
    } else {
1718
26872
      args.GetReturnValue().Set(names);
1719
    }
1720
  }
1721
}
1722
1723
56586
static void Open(const FunctionCallbackInfo<Value>& args) {
1724
56586
  Environment* env = Environment::GetCurrent(args);
1725
1726
56586
  const int argc = args.Length();
1727
56586
  CHECK_GE(argc, 3);
1728
1729
113172
  BufferValue path(env->isolate(), args[0]);
1730
56586
  CHECK_NOT_NULL(*path);
1731
1732
56586
  CHECK(args[1]->IsInt32());
1733
113172
  const int flags = args[1].As<Int32>()->Value();
1734
1735
56586
  CHECK(args[2]->IsInt32());
1736
113172
  const int mode = args[2].As<Int32>()->Value();
1737
1738
56586
  FSReqBase* req_wrap_async = GetReqWrap(args, 3);
1739
56586
  if (req_wrap_async != nullptr) {  // open(path, flags, mode, req)
1740
5523
    req_wrap_async->set_is_plain_open(true);
1741
5523
    AsyncCall(env, req_wrap_async, args, "open", UTF8, AfterInteger,
1742
              uv_fs_open, *path, flags, mode);
1743
  } else {  // open(path, flags, mode, undefined, ctx)
1744
51063
    CHECK_EQ(argc, 5);
1745
51063
    FSReqWrapSync req_wrap_sync;
1746

51125
    FS_SYNC_TRACE_BEGIN(open);
1747
102126
    int result = SyncCall(env, args[4], &req_wrap_sync, "open",
1748
                          uv_fs_open, *path, flags, mode);
1749

51125
    FS_SYNC_TRACE_END(open);
1750
51063
    if (result >= 0) env->AddUnmanagedFd(result);
1751
102126
    args.GetReturnValue().Set(result);
1752
  }
1753
56586
}
1754
1755
936
static void OpenFileHandle(const FunctionCallbackInfo<Value>& args) {
1756
936
  BindingData* binding_data = Environment::GetBindingData<BindingData>(args);
1757
936
  Environment* env = binding_data->env();
1758
936
  Isolate* isolate = env->isolate();
1759
1760
936
  const int argc = args.Length();
1761
936
  CHECK_GE(argc, 3);
1762
1763
936
  BufferValue path(isolate, args[0]);
1764
936
  CHECK_NOT_NULL(*path);
1765
1766
936
  CHECK(args[1]->IsInt32());
1767
1872
  const int flags = args[1].As<Int32>()->Value();
1768
1769
936
  CHECK(args[2]->IsInt32());
1770
1872
  const int mode = args[2].As<Int32>()->Value();
1771
1772
936
  FSReqBase* req_wrap_async = GetReqWrap(args, 3);
1773
936
  if (req_wrap_async != nullptr) {  // openFileHandle(path, flags, mode, req)
1774
935
    AsyncCall(env, req_wrap_async, args, "open", UTF8, AfterOpenFileHandle,
1775
              uv_fs_open, *path, flags, mode);
1776
  } else {  // openFileHandle(path, flags, mode, undefined, ctx)
1777
1
    CHECK_EQ(argc, 5);
1778
1
    FSReqWrapSync req_wrap_sync;
1779

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

1
    FS_SYNC_TRACE_END(open);
1783
1
    if (result < 0) {
1784
      return;  // syscall failed, no need to continue, error info is in ctx
1785
    }
1786
1
    FileHandle* fd = FileHandle::New(binding_data, result);
1787
1
    if (fd == nullptr) return;
1788
2
    args.GetReturnValue().Set(fd->object());
1789
  }
1790
}
1791
1792
212
static void CopyFile(const FunctionCallbackInfo<Value>& args) {
1793
212
  Environment* env = Environment::GetCurrent(args);
1794
212
  Isolate* isolate = env->isolate();
1795
1796
212
  const int argc = args.Length();
1797
212
  CHECK_GE(argc, 3);
1798
1799
424
  BufferValue src(isolate, args[0]);
1800
212
  CHECK_NOT_NULL(*src);
1801
1802
424
  BufferValue dest(isolate, args[1]);
1803
212
  CHECK_NOT_NULL(*dest);
1804
1805
212
  CHECK(args[2]->IsInt32());
1806
424
  const int flags = args[2].As<Int32>()->Value();
1807
1808
212
  FSReqBase* req_wrap_async = GetReqWrap(args, 3);
1809
212
  if (req_wrap_async != nullptr) {  // copyFile(src, dest, flags, req)
1810
204
    AsyncDestCall(env, req_wrap_async, args, "copyfile",
1811
102
                  *dest, dest.length(), UTF8, AfterNoArgs,
1812
                  uv_fs_copyfile, *src, *dest, flags);
1813
  } else {  // copyFile(src, dest, flags, undefined, ctx)
1814
110
    CHECK_EQ(argc, 5);
1815
220
    FSReqWrapSync req_wrap_sync;
1816

112
    FS_SYNC_TRACE_BEGIN(copyfile);
1817
220
    SyncCall(env, args[4], &req_wrap_sync, "copyfile",
1818
             uv_fs_copyfile, *src, *dest, flags);
1819

112
    FS_SYNC_TRACE_END(copyfile);
1820
  }
1821
212
}
1822
1823
1824
// Wrapper for write(2).
1825
//
1826
// bytesWritten = write(fd, buffer, offset, length, position, callback)
1827
// 0 fd        integer. file descriptor
1828
// 1 buffer    the data to write
1829
// 2 offset    where in the buffer to start from
1830
// 3 length    how much to write
1831
// 4 position  if integer, position to write at in the file.
1832
//             if null, write from the current position
1833
61220
static void WriteBuffer(const FunctionCallbackInfo<Value>& args) {
1834
61220
  Environment* env = Environment::GetCurrent(args);
1835
1836
61220
  const int argc = args.Length();
1837
61220
  CHECK_GE(argc, 4);
1838
1839
61220
  CHECK(args[0]->IsInt32());
1840
122440
  const int fd = args[0].As<Int32>()->Value();
1841
1842
61220
  CHECK(Buffer::HasInstance(args[1]));
1843
61220
  Local<Object> buffer_obj = args[1].As<Object>();
1844
61220
  char* buffer_data = Buffer::Data(buffer_obj);
1845
61220
  size_t buffer_length = Buffer::Length(buffer_obj);
1846
1847
61220
  CHECK(IsSafeJsInt(args[2]));
1848
122440
  const int64_t off_64 = args[2].As<Integer>()->Value();
1849
61220
  CHECK_GE(off_64, 0);
1850
61220
  CHECK_LE(static_cast<uint64_t>(off_64), buffer_length);
1851
61220
  const size_t off = static_cast<size_t>(off_64);
1852
1853
61220
  CHECK(args[3]->IsInt32());
1854
122440
  const size_t len = static_cast<size_t>(args[3].As<Int32>()->Value());
1855
61220
  CHECK(Buffer::IsWithinBounds(off, len, buffer_length));
1856
61220
  CHECK_LE(len, buffer_length);
1857
61220
  CHECK_GE(off + len, off);
1858
1859
61220
  const int64_t pos = GetOffset(args[4]);
1860
1861
61220
  char* buf = buffer_data + off;
1862
61220
  uv_buf_t uvbuf = uv_buf_init(buf, len);
1863
1864
61220
  FSReqBase* req_wrap_async = GetReqWrap(args, 5);
1865
61220
  if (req_wrap_async != nullptr) {  // write(fd, buffer, off, len, pos, req)
1866
17063
    AsyncCall(env, req_wrap_async, args, "write", UTF8, AfterInteger,
1867
              uv_fs_write, fd, &uvbuf, 1, pos);
1868
  } else {  // write(fd, buffer, off, len, pos, undefined, ctx)
1869
44157
    CHECK_EQ(argc, 7);
1870
44157
    FSReqWrapSync req_wrap_sync;
1871

44207
    FS_SYNC_TRACE_BEGIN(write);
1872
44157
    int bytesWritten = SyncCall(env, args[6], &req_wrap_sync, "write",
1873
44157
                                uv_fs_write, fd, &uvbuf, 1, pos);
1874

44207
    FS_SYNC_TRACE_END(write, "bytesWritten", bytesWritten);
1875
88314
    args.GetReturnValue().Set(bytesWritten);
1876
  }
1877
61220
}
1878
1879
1880
// Wrapper for writev(2).
1881
//
1882
// bytesWritten = writev(fd, chunks, position, callback)
1883
// 0 fd        integer. file descriptor
1884
// 1 chunks    array of buffers to write
1885
// 2 position  if integer, position to write at in the file.
1886
//             if null, write from the current position
1887
18
static void WriteBuffers(const FunctionCallbackInfo<Value>& args) {
1888
18
  Environment* env = Environment::GetCurrent(args);
1889
1890
18
  const int argc = args.Length();
1891
18
  CHECK_GE(argc, 3);
1892
1893
18
  CHECK(args[0]->IsInt32());
1894
36
  const int fd = args[0].As<Int32>()->Value();
1895
1896
18
  CHECK(args[1]->IsArray());
1897
36
  Local<Array> chunks = args[1].As<Array>();
1898
1899
18
  int64_t pos = GetOffset(args[2]);
1900
1901
36
  MaybeStackBuffer<uv_buf_t> iovs(chunks->Length());
1902
1903
71
  for (uint32_t i = 0; i < iovs.length(); i++) {
1904
53
    Local<Value> chunk = chunks->Get(env->context(), i).ToLocalChecked();
1905
53
    CHECK(Buffer::HasInstance(chunk));
1906
53
    iovs[i] = uv_buf_init(Buffer::Data(chunk), Buffer::Length(chunk));
1907
  }
1908
1909
18
  FSReqBase* req_wrap_async = GetReqWrap(args, 3);
1910
18
  if (req_wrap_async != nullptr) {  // writeBuffers(fd, chunks, pos, req)
1911
14
    AsyncCall(env, req_wrap_async, args, "write", UTF8, AfterInteger,
1912
              uv_fs_write, fd, *iovs, iovs.length(), pos);
1913
  } else {  // writeBuffers(fd, chunks, pos, undefined, ctx)
1914
4
    CHECK_EQ(argc, 5);
1915
4
    FSReqWrapSync req_wrap_sync;
1916

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

4
    FS_SYNC_TRACE_END(write, "bytesWritten", bytesWritten);
1920
8
    args.GetReturnValue().Set(bytesWritten);
1921
  }
1922
18
}
1923
1924
1925
// Wrapper for write(2).
1926
//
1927
// bytesWritten = write(fd, string, position, enc, callback)
1928
// 0 fd        integer. file descriptor
1929
// 1 string    non-buffer values are converted to strings
1930
// 2 position  if integer, position to write at in the file.
1931
//             if null, write from the current position
1932
// 3 enc       encoding of string
1933
119944
static void WriteString(const FunctionCallbackInfo<Value>& args) {
1934
119944
  Environment* env = Environment::GetCurrent(args);
1935
119944
  Isolate* isolate = env->isolate();
1936
1937
119944
  const int argc = args.Length();
1938
119944
  CHECK_GE(argc, 4);
1939
1940
119944
  CHECK(args[0]->IsInt32());
1941
239888
  const int fd = args[0].As<Int32>()->Value();
1942
1943
119944
  const int64_t pos = GetOffset(args[2]);
1944
1945
119944
  const auto enc = ParseEncoding(isolate, args[3], UTF8);
1946
1947
119944
  Local<Value> value = args[1];
1948
119944
  char* buf = nullptr;
1949
  size_t len;
1950
1951
119944
  FSReqBase* req_wrap_async = GetReqWrap(args, 4);
1952
119944
  const bool is_async = req_wrap_async != nullptr;
1953
1954
  // Avoid copying the string when it is externalized but only when:
1955
  // 1. The target encoding is compatible with the string's encoding, and
1956
  // 2. The write is synchronous, otherwise the string might get neutered
1957
  //    while the request is in flight, and
1958
  // 3. For UCS2, when the host system is little-endian.  Big-endian systems
1959
  //    need to call StringBytes::Write() to ensure proper byte swapping.
1960
  // The const_casts are conceptually sound: memory is read but not written.
1961

359676
  if (!is_async && value->IsString()) {
1962
119866
    auto string = value.As<String>();
1963


119867
    if ((enc == ASCII || enc == LATIN1) && string->IsExternalOneByte()) {
1964
1
      auto ext = string->GetExternalOneByteStringResource();
1965
1
      buf = const_cast<char*>(ext->data());
1966
1
      len = ext->length();
1967


119866
    } else if (enc == UCS2 && IsLittleEndian() && string->IsExternalTwoByte()) {
1968
1
      auto ext = string->GetExternalStringResource();
1969
1
      buf = reinterpret_cast<char*>(const_cast<uint16_t*>(ext->data()));
1970
1
      len = ext->length() * sizeof(*ext->data());
1971
    }
1972
  }
1973
1974
119944
  if (is_async) {  // write(fd, string, pos, enc, req)
1975
78
    CHECK_NOT_NULL(req_wrap_async);
1976
156
    if (!StringBytes::StorageSize(isolate, value, enc).To(&len)) return;
1977
    FSReqBase::FSReqBuffer& stack_buffer =
1978
78
        req_wrap_async->Init("write", len, enc);
1979
    // StorageSize may return too large a char, so correct the actual length
1980
    // by the write size
1981
78
    len = StringBytes::Write(isolate, *stack_buffer, len, args[1], enc);
1982
78
    stack_buffer.SetLengthAndZeroTerminate(len);
1983
78
    uv_buf_t uvbuf = uv_buf_init(*stack_buffer, len);
1984
78
    int err = req_wrap_async->Dispatch(uv_fs_write,
1985
                                       fd,
1986
                                       &uvbuf,
1987
                                       1,
1988
                                       pos,
1989
                                       AfterInteger);
1990
78
    if (err < 0) {
1991
      uv_fs_t* uv_req = req_wrap_async->req();
1992
      uv_req->result = err;
1993
      uv_req->path = nullptr;
1994
      AfterInteger(uv_req);  // after may delete req_wrap_async if there is
1995
                             // an error
1996
    } else {
1997
78
      req_wrap_async->SetReturnValue(args);
1998
    }
1999
  } else {  // write(fd, string, pos, enc, undefined, ctx)
2000
119866
    CHECK_EQ(argc, 6);
2001
119866
    FSReqWrapSync req_wrap_sync;
2002
119866
    FSReqBase::FSReqBuffer stack_buffer;
2003
119866
    if (buf == nullptr) {
2004
239728
      if (!StringBytes::StorageSize(isolate, value, enc).To(&len))
2005
        return;
2006
119864
      stack_buffer.AllocateSufficientStorage(len + 1);
2007
      // StorageSize may return too large a char, so correct the actual length
2008
      // by the write size
2009
119864
      len = StringBytes::Write(isolate, *stack_buffer,
2010
                               len, args[1], enc);
2011
119864
      stack_buffer.SetLengthAndZeroTerminate(len);
2012
119864
      buf = *stack_buffer;
2013
    }
2014
119866
    uv_buf_t uvbuf = uv_buf_init(buf, len);
2015

119866
    FS_SYNC_TRACE_BEGIN(write);
2016
119866
    int bytesWritten = SyncCall(env, args[5], &req_wrap_sync, "write",
2017
119866
                                uv_fs_write, fd, &uvbuf, 1, pos);
2018

119866
    FS_SYNC_TRACE_END(write, "bytesWritten", bytesWritten);
2019
239732
    args.GetReturnValue().Set(bytesWritten);
2020
  }
2021
}
2022
2023
2024
/*
2025
 * Wrapper for read(2).
2026
 *
2027
 * bytesRead = fs.read(fd, buffer, offset, length, position)
2028
 *
2029
 * 0 fd        int32. file descriptor
2030
 * 1 buffer    instance of Buffer
2031
 * 2 offset    int64. offset to start reading into inside buffer
2032
 * 3 length    int32. length to read
2033
 * 4 position  int64. file position - -1 for current position
2034
 */
2035
62629
static void Read(const FunctionCallbackInfo<Value>& args) {
2036
62629
  Environment* env = Environment::GetCurrent(args);
2037
2038
62629
  const int argc = args.Length();
2039
62629
  CHECK_GE(argc, 5);
2040
2041
62629
  CHECK(args[0]->IsInt32());
2042
125258
  const int fd = args[0].As<Int32>()->Value();
2043
2044
62629
  CHECK(Buffer::HasInstance(args[1]));
2045
62629
  Local<Object> buffer_obj = args[1].As<Object>();
2046
62629
  char* buffer_data = Buffer::Data(buffer_obj);
2047
62629
  size_t buffer_length = Buffer::Length(buffer_obj);
2048
2049
62629
  CHECK(IsSafeJsInt(args[2]));
2050
125258
  const int64_t off_64 = args[2].As<Integer>()->Value();
2051
62629
  CHECK_GE(off_64, 0);
2052
62629
  CHECK_LT(static_cast<uint64_t>(off_64), buffer_length);
2053
62629
  const size_t off = static_cast<size_t>(off_64);
2054
2055
62629
  CHECK(args[3]->IsInt32());
2056
125258
  const size_t len = static_cast<size_t>(args[3].As<Int32>()->Value());
2057
62629
  CHECK(Buffer::IsWithinBounds(off, len, buffer_length));
2058
2059

62633
  CHECK(IsSafeJsInt(args[4]) || args[4]->IsBigInt());
2060
62629
  const int64_t pos = args[4]->IsNumber() ?
2061
125250
                      args[4].As<Integer>()->Value() :
2062
8
                      args[4].As<BigInt>()->Int64Value();
2063
2064
62629
  char* buf = buffer_data + off;
2065
62629
  uv_buf_t uvbuf = uv_buf_init(buf, len);
2066
2067
62629
  FSReqBase* req_wrap_async = GetReqWrap(args, 5);
2068
62629
  if (req_wrap_async != nullptr) {  // read(fd, buffer, offset, len, pos, req)
2069
13589
    AsyncCall(env, req_wrap_async, args, "read", UTF8, AfterInteger,
2070
              uv_fs_read, fd, &uvbuf, 1, pos);
2071
  } else {  // read(fd, buffer, offset, len, pos, undefined, ctx)
2072
49040
    CHECK_EQ(argc, 7);
2073
49040
    FSReqWrapSync req_wrap_sync;
2074

49048
    FS_SYNC_TRACE_BEGIN(read);
2075
49040
    const int bytesRead = SyncCall(env, args[6], &req_wrap_sync, "read",
2076
49040
                                   uv_fs_read, fd, &uvbuf, 1, pos);
2077

49048
    FS_SYNC_TRACE_END(read, "bytesRead", bytesRead);
2078
98080
    args.GetReturnValue().Set(bytesRead);
2079
  }
2080
62629
}
2081
2082
2083
// Wrapper for readv(2).
2084
//
2085
// bytesRead = fs.readv(fd, buffers[, position], callback)
2086
// 0 fd        integer. file descriptor
2087
// 1 buffers   array of buffers to read
2088
// 2 position  if integer, position to read at in the file.
2089
//             if null, read from the current position
2090
11
static void ReadBuffers(const FunctionCallbackInfo<Value>& args) {
2091
11
  Environment* env = Environment::GetCurrent(args);
2092
2093
11
  const int argc = args.Length();
2094
11
  CHECK_GE(argc, 3);
2095
2096
11
  CHECK(args[0]->IsInt32());
2097
22
  const int fd = args[0].As<Int32>()->Value();
2098
2099
11
  CHECK(args[1]->IsArray());
2100
22
  Local<Array> buffers = args[1].As<Array>();
2101
2102
11
  int64_t pos = GetOffset(args[2]);  // -1 if not a valid JS int
2103
2104
22
  MaybeStackBuffer<uv_buf_t> iovs(buffers->Length());
2105
2106
  // Init uv buffers from ArrayBufferViews
2107
28
  for (uint32_t i = 0; i < iovs.length(); i++) {
2108
17
    Local<Value> buffer = buffers->Get(env->context(), i).ToLocalChecked();
2109
17
    CHECK(Buffer::HasInstance(buffer));
2110
17
    iovs[i] = uv_buf_init(Buffer::Data(buffer), Buffer::Length(buffer));
2111
  }
2112
2113
11
  FSReqBase* req_wrap_async = GetReqWrap(args, 3);
2114
11
  if (req_wrap_async != nullptr) {  // readBuffers(fd, buffers, pos, req)
2115
7
    AsyncCall(env, req_wrap_async, args, "read", UTF8, AfterInteger,
2116
              uv_fs_read, fd, *iovs, iovs.length(), pos);
2117
  } else {  // readBuffers(fd, buffers, undefined, ctx)
2118
4
    CHECK_EQ(argc, 5);
2119
4
    FSReqWrapSync req_wrap_sync;
2120

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

4
    FS_SYNC_TRACE_END(read, "bytesRead", bytesRead);
2124
8
    args.GetReturnValue().Set(bytesRead);
2125
  }
2126
11
}
2127
2128
2129
/* fs.chmod(path, mode);
2130
 * Wrapper for chmod(1) / EIO_CHMOD
2131
 */
2132
304
static void Chmod(const FunctionCallbackInfo<Value>& args) {
2133
304
  Environment* env = Environment::GetCurrent(args);
2134
2135
304
  const int argc = args.Length();
2136
304
  CHECK_GE(argc, 2);
2137
2138
608
  BufferValue path(env->isolate(), args[0]);
2139
304
  CHECK_NOT_NULL(*path);
2140
2141
304
  CHECK(args[1]->IsInt32());
2142
608
  int mode = args[1].As<Int32>()->Value();
2143
2144
304
  FSReqBase* req_wrap_async = GetReqWrap(args, 2);
2145
304
  if (req_wrap_async != nullptr) {  // chmod(path, mode, req)
2146
140
    AsyncCall(env, req_wrap_async, args, "chmod", UTF8, AfterNoArgs,
2147
              uv_fs_chmod, *path, mode);
2148
  } else {  // chmod(path, mode, undefined, ctx)
2149
164
    CHECK_EQ(argc, 4);
2150
328
    FSReqWrapSync req_wrap_sync;
2151

166
    FS_SYNC_TRACE_BEGIN(chmod);
2152
328
    SyncCall(env, args[3], &req_wrap_sync, "chmod",
2153
             uv_fs_chmod, *path, mode);
2154

166
    FS_SYNC_TRACE_END(chmod);
2155
  }
2156
304
}
2157
2158
2159
/* fs.fchmod(fd, mode);
2160
 * Wrapper for fchmod(1) / EIO_FCHMOD
2161
 */
2162
12
static void FChmod(const FunctionCallbackInfo<Value>& args) {
2163
12
  Environment* env = Environment::GetCurrent(args);
2164
2165
12
  const int argc = args.Length();
2166
12
  CHECK_GE(argc, 2);
2167
2168
12
  CHECK(args[0]->IsInt32());
2169
24
  const int fd = args[0].As<Int32>()->Value();
2170
2171
12
  CHECK(args[1]->IsInt32());
2172
24
  const int mode = args[1].As<Int32>()->Value();
2173
2174
12
  FSReqBase* req_wrap_async = GetReqWrap(args, 2);
2175
12
  if (req_wrap_async != nullptr) {  // fchmod(fd, mode, req)
2176
7
    AsyncCall(env, req_wrap_async, args, "fchmod", UTF8, AfterNoArgs,
2177
              uv_fs_fchmod, fd, mode);
2178
  } else {  // fchmod(fd, mode, undefined, ctx)
2179
5
    CHECK_EQ(argc, 4);
2180
10
    FSReqWrapSync req_wrap_sync;
2181

7
    FS_SYNC_TRACE_BEGIN(fchmod);
2182
5
    SyncCall(env, args[3], &req_wrap_sync, "fchmod",
2183
             uv_fs_fchmod, fd, mode);
2184

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

4
    FS_SYNC_TRACE_BEGIN(chown);
2215
4
    SyncCall(env, args[4], &req_wrap_sync, "chown",
2216
             uv_fs_chown, *path, uid, gid);
2217

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

4
    FS_SYNC_TRACE_BEGIN(fchown);
2248
2
    SyncCall(env, args[4], &req_wrap_sync, "fchown",
2249
             uv_fs_fchown, fd, uid, gid);
2250

4
    FS_SYNC_TRACE_END(fchown);
2251
  }
2252
4
}
2253
2254
2255
5
static void LChown(const FunctionCallbackInfo<Value>& args) {
2256
5
  Environment* env = Environment::GetCurrent(args);
2257
2258
5
  const int argc = args.Length();
2259
5
  CHECK_GE(argc, 3);
2260
2261
10
  BufferValue path(env->isolate(), args[0]);
2262
5
  CHECK_NOT_NULL(*path);
2263
2264
5
  CHECK(IsSafeJsInt(args[1]));
2265
10
  const uv_uid_t uid = static_cast<uv_uid_t>(args[1].As<Integer>()->Value());
2266
2267
5
  CHECK(IsSafeJsInt(args[2]));
2268
10
  const uv_gid_t gid = static_cast<uv_gid_t>(args[2].As<Integer>()->Value());
2269
2270
5
  FSReqBase* req_wrap_async = GetReqWrap(args, 3);
2271
5
  if (req_wrap_async != nullptr) {  // lchown(path, uid, gid, req)
2272
3
    AsyncCall(env, req_wrap_async, args, "lchown", UTF8, AfterNoArgs,
2273
              uv_fs_lchown, *path, uid, gid);
2274
  } else {  // lchown(path, uid, gid, undefined, ctx)
2275
2
    CHECK_EQ(argc, 5);
2276
4
    FSReqWrapSync req_wrap_sync;
2277

4
    FS_SYNC_TRACE_BEGIN(lchown);
2278
4
    SyncCall(env, args[4], &req_wrap_sync, "lchown",
2279
             uv_fs_lchown, *path, uid, gid);
2280

4
    FS_SYNC_TRACE_END(lchown);
2281
  }
2282
5
}
2283
2284
2285
53
static void UTimes(const FunctionCallbackInfo<Value>& args) {
2286
53
  Environment* env = Environment::GetCurrent(args);
2287
2288
53
  const int argc = args.Length();
2289
53
  CHECK_GE(argc, 3);
2290
2291
106
  BufferValue path(env->isolate(), args[0]);
2292
53
  CHECK_NOT_NULL(*path);
2293
2294
53
  CHECK(args[1]->IsNumber());
2295
106
  const double atime = args[1].As<Number>()->Value();
2296
2297
53
  CHECK(args[2]->IsNumber());
2298
106
  const double mtime = args[2].As<Number>()->Value();
2299
2300
53
  FSReqBase* req_wrap_async = GetReqWrap(args, 3);
2301
53
  if (req_wrap_async != nullptr) {  // utimes(path, atime, mtime, req)
2302
26
    AsyncCall(env, req_wrap_async, args, "utime", UTF8, AfterNoArgs,
2303
              uv_fs_utime, *path, atime, mtime);
2304
  } else {  // utimes(path, atime, mtime, undefined, ctx)
2305
27
    CHECK_EQ(argc, 5);
2306
54
    FSReqWrapSync req_wrap_sync;
2307

29
    FS_SYNC_TRACE_BEGIN(utimes);
2308
54
    SyncCall(env, args[4], &req_wrap_sync, "utime",
2309
             uv_fs_utime, *path, atime, mtime);
2310

29
    FS_SYNC_TRACE_END(utimes);
2311
  }
2312
53
}
2313
2314
18
static void FUTimes(const FunctionCallbackInfo<Value>& args) {
2315
18
  Environment* env = Environment::GetCurrent(args);
2316
2317
18
  const int argc = args.Length();
2318
18
  CHECK_GE(argc, 3);
2319
2320
18
  CHECK(args[0]->IsInt32());
2321
36
  const int fd = args[0].As<Int32>()->Value();
2322
2323
18
  CHECK(args[1]->IsNumber());
2324
36
  const double atime = args[1].As<Number>()->Value();
2325
2326
18
  CHECK(args[2]->IsNumber());
2327
36
  const double mtime = args[2].As<Number>()->Value();
2328
2329
18
  FSReqBase* req_wrap_async = GetReqWrap(args, 3);
2330
18
  if (req_wrap_async != nullptr) {  // futimes(fd, atime, mtime, req)
2331
9
    AsyncCall(env, req_wrap_async, args, "futime", UTF8, AfterNoArgs,
2332
              uv_fs_futime, fd, atime, mtime);
2333
  } else {  // futimes(fd, atime, mtime, undefined, ctx)
2334
9
    CHECK_EQ(argc, 5);
2335
18
    FSReqWrapSync req_wrap_sync;
2336

11
    FS_SYNC_TRACE_BEGIN(futimes);
2337
9
    SyncCall(env, args[4], &req_wrap_sync, "futime",
2338
             uv_fs_futime, fd, atime, mtime);
2339

11
    FS_SYNC_TRACE_END(futimes);
2340
  }
2341
18
}
2342
2343
15
static void LUTimes(const FunctionCallbackInfo<Value>& args) {
2344
15
  Environment* env = Environment::GetCurrent(args);
2345
2346
15
  const int argc = args.Length();
2347
15
  CHECK_GE(argc, 3);
2348
2349
30
  BufferValue path(env->isolate(), args[0]);
2350
15
  CHECK_NOT_NULL(*path);
2351
2352
15
  CHECK(args[1]->IsNumber());
2353
30
  const double atime = args[1].As<Number>()->Value();
2354
2355
15
  CHECK(args[2]->IsNumber());
2356
30
  const double mtime = args[2].As<Number>()->Value();
2357
2358
15
  FSReqBase* req_wrap_async = GetReqWrap(args, 3);
2359
15
  if (req_wrap_async != nullptr) {  // lutimes(path, atime, mtime, req)
2360
8
    AsyncCall(env, req_wrap_async, args, "lutime", UTF8, AfterNoArgs,
2361
              uv_fs_lutime, *path, atime, mtime);
2362
  } else {  // lutimes(path, atime, mtime, undefined, ctx)
2363
7
    CHECK_EQ(argc, 5);
2364
14
    FSReqWrapSync req_wrap_sync;
2365

7
    FS_SYNC_TRACE_BEGIN(lutimes);
2366
14
    SyncCall(env, args[4], &req_wrap_sync, "lutime",
2367
             uv_fs_lutime, *path, atime, mtime);
2368

7
    FS_SYNC_TRACE_END(lutimes);
2369
  }
2370
15
}
2371
2372
15
static void Mkdtemp(const FunctionCallbackInfo<Value>& args) {
2373
15
  Environment* env = Environment::GetCurrent(args);
2374
15
  Isolate* isolate = env->isolate();
2375
2376
15
  const int argc = args.Length();
2377
15
  CHECK_GE(argc, 2);
2378
2379
15
  BufferValue tmpl(isolate, args[0]);
2380
15
  CHECK_NOT_NULL(*tmpl);
2381
2382
15
  const enum encoding encoding = ParseEncoding(isolate, args[1], UTF8);
2383
2384
15
  FSReqBase* req_wrap_async = GetReqWrap(args, 2);
2385
15
  if (req_wrap_async != nullptr) {  // mkdtemp(tmpl, encoding, req)
2386
6
    AsyncCall(env, req_wrap_async, args, "mkdtemp", encoding, AfterStringPath,
2387
              uv_fs_mkdtemp, *tmpl);
2388
  } else {  // mkdtemp(tmpl, encoding, undefined, ctx)
2389
9
    CHECK_EQ(argc, 4);
2390
9
    FSReqWrapSync req_wrap_sync;
2391

11
    FS_SYNC_TRACE_BEGIN(mkdtemp);
2392
18
    SyncCall(env, args[3], &req_wrap_sync, "mkdtemp",
2393
             uv_fs_mkdtemp, *tmpl);
2394

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