GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_file.cc Lines: 1450 1532 94.6 %
Date: 2022-05-21 04:15:56 Branches: 798 1250 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
189199
inline int64_t GetOffset(Local<Value> value) {
111
190297
  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
1244
FileHandle::FileHandle(BindingData* binding_data,
149
1244
                       Local<Object> obj, int fd)
150
    : AsyncWrap(binding_data->env(), obj, AsyncWrap::PROVIDER_FILEHANDLE),
151
      StreamBase(env()),
152
      fd_(fd),
153
1244
      binding_data_(binding_data) {
154
1244
  MakeWeak();
155
1244
  StreamBase::AttachToObject(GetObject());
156
1244
}
157
158
1244
FileHandle* FileHandle::New(BindingData* binding_data,
159
                            int fd, Local<Object> obj) {
160
1244
  Environment* env = binding_data->env();
161
2473
  if (obj.IsEmpty() && !env->fd_constructor_template()
162
2473
                            ->NewInstance(env->context())
163
1229
                            .ToLocal(&obj)) {
164
    return nullptr;
165
  }
166
1244
  return new FileHandle(binding_data, obj, fd);
167
}
168
169
15
void FileHandle::New(const FunctionCallbackInfo<Value>& args) {
170
15
  BindingData* binding_data = Environment::GetBindingData<BindingData>(args);
171
15
  Environment* env = binding_data->env();
172
15
  CHECK(args.IsConstructCall());
173
15
  CHECK(args[0]->IsInt32());
174
175
  FileHandle* handle =
176
30
      FileHandle::New(binding_data, args[0].As<Int32>()->Value(), args.This());
177
15
  if (handle == nullptr) return;
178
30
  if (args[1]->IsNumber())
179
30
    handle->read_offset_ = args[1]->IntegerValue(env->context()).FromJust();
180
15
  if (args[2]->IsNumber())
181
30
    handle->read_length_ = args[2]->IntegerValue(env->context()).FromJust();
182
}
183
184
4820
FileHandle::~FileHandle() {
185
2410
  CHECK(!closing_);  // We should not be deleting while explicitly closing!
186
2410
  Close();           // Close synchronously and emit warning
187
2410
  CHECK(closed_);    // We have to be closed at the point
188
4820
}
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
1205
inline void FileHandle::Close() {
241

1205
  if (closed_ || closing_) return;
242
  uv_fs_t req;
243
20
  CHECK_NE(fd_, -1);
244
20
  int ret = uv_fs_close(env()->event_loop(), &req, fd_, nullptr);
245
20
  uv_fs_req_cleanup(&req);
246
247
  struct err_detail { int ret; int fd; };
248
249
20
  err_detail detail { ret, fd_ };
250
251
20
  AfterClose();
252
253
20
  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
20
  env()->SetImmediate([detail](Environment* env) {
275
    ProcessEmitWarning(env,
276
                       "Closing file descriptor %d on garbage collection",
277
4
                       detail.fd);
278
4
    if (env->filehandle_close_warning()) {
279
3
      env->set_filehandle_close_warning(false);
280
3
      USE(ProcessEmitDeprecationWarning(
281
          env,
282
          "Closing a FileHandle object on garbage collection is deprecated. "
283
          "Please close FileHandle objects explicitly using "
284
          "FileHandle.prototype.close(). In the future, an error will be "
285
          "thrown if a file descriptor is closed during garbage collection.",
286
3
          "DEP0137"));
287
    }
288
4
  }, CallbackFlags::kUnrefed);
289
}
290
291
1207
void FileHandle::CloseReq::Resolve() {
292
1207
  Isolate* isolate = env()->isolate();
293
2385
  HandleScope scope(isolate);
294
1207
  Context::Scope context_scope(env()->context());
295
1207
  InternalCallbackScope callback_scope(this);
296
2414
  Local<Promise> promise = promise_.Get(isolate);
297
1207
  Local<Promise::Resolver> resolver = promise.As<Promise::Resolver>();
298
3621
  resolver->Resolve(env()->context(), Undefined(isolate)).Check();
299
1178
}
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
1208
FileHandle* FileHandle::CloseReq::file_handle() {
312
1208
  Isolate* isolate = env()->isolate();
313
1208
  HandleScope scope(isolate);
314
2416
  Local<Value> val = ref_.Get(isolate);
315
1208
  Local<Object> obj = val.As<Object>();
316
1208
  return Unwrap<FileHandle>(obj);
317
}
318
319
1208
FileHandle::CloseReq::CloseReq(Environment* env,
320
                               Local<Object> obj,
321
                               Local<Promise> promise,
322
1208
                               Local<Value> ref)
323
1208
  : ReqWrap(env, obj, AsyncWrap::PROVIDER_FILEHANDLECLOSEREQ) {
324
1208
  promise_.Reset(env->isolate(), promise);
325
1208
  ref_.Reset(env->isolate(), ref);
326
1208
}
327
328
9432
FileHandle::CloseReq::~CloseReq() {
329
2358
  uv_fs_req_cleanup(req());
330
2358
  promise_.Reset();
331
2358
  ref_.Reset();
332
4716
}
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
1208
MaybeLocal<Promise> FileHandle::ClosePromise() {
347
1208
  Isolate* isolate = env()->isolate();
348
1208
  EscapableHandleScope scope(isolate);
349
1208
  Local<Context> context = env()->context();
350
351
  Local<Value> close_resolver =
352
3624
      object()->GetInternalField(FileHandle::kClosingPromiseSlot);
353

3624
  if (!close_resolver.IsEmpty() && !close_resolver->IsUndefined()) {
354
    CHECK(close_resolver->IsPromise());
355
    return close_resolver.As<Promise>();
356
  }
357
358
1208
  CHECK(!closed_);
359
1208
  CHECK(!closing_);
360
1208
  CHECK(!reading_);
361
362
1208
  auto maybe_resolver = Promise::Resolver::New(context);
363
1208
  CHECK(!maybe_resolver.IsEmpty());
364
1208
  Local<Promise::Resolver> resolver = maybe_resolver.ToLocalChecked();
365
1208
  Local<Promise> promise = resolver.As<Promise>();
366
367
  Local<Object> close_req_obj;
368
1208
  if (!env()->fdclose_constructor_template()
369
2416
          ->NewInstance(env()->context()).ToLocal(&close_req_obj)) {
370
    return MaybeLocal<Promise>();
371
  }
372
1208
  closing_ = true;
373
2416
  object()->SetInternalField(FileHandle::kClosingPromiseSlot, promise);
374
375
2416
  CloseReq* req = new CloseReq(env(), close_req_obj, promise, object());
376
2416
  auto AfterClose = uv_fs_callback_t{[](uv_fs_t* req) {
377
2387
    std::unique_ptr<CloseReq> close(CloseReq::from_req(req));
378
1208
    CHECK_NOT_NULL(close);
379
1208
    close->file_handle()->AfterClose();
380
1208
    Isolate* isolate = close->env()->isolate();
381
1208
    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
1207
      close->Resolve();
387
    }
388
1179
  }};
389
1208
  CHECK_NE(fd_, -1);
390
1208
  int ret = req->Dispatch(uv_fs_close, fd_, AfterClose);
391
1208
  if (ret < 0) {
392
    req->Reject(UVException(isolate, ret, "close"));
393
    delete req;
394
  }
395
396
1208
  return scope.Escape(promise);
397
}
398
399
1208
void FileHandle::Close(const FunctionCallbackInfo<Value>& args) {
400
  FileHandle* fd;
401
1208
  ASSIGN_OR_RETURN_UNWRAP(&fd, args.Holder());
402
  Local<Promise> ret;
403
2416
  if (!fd->ClosePromise().ToLocal(&ret)) return;
404
2416
  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
1236
void FileHandle::AfterClose() {
417
1236
  closing_ = false;
418
1236
  closed_ = true;
419
1236
  fd_ = -1;
420

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

227
  if (!IsAlive() || IsClosing())
435
    return UV_EOF;
436
437
227
  reading_ = true;
438
439
227
  if (current_read_)
440
9
    return 0;
441
442
436
  BaseObjectPtr<FileHandleReadWrap> read_wrap;
443
444
218
  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
213
    HandleScope handle_scope(env()->isolate());
454
213
    AsyncHooks::DefaultTriggerAsyncIdScope trigger_scope(this);
455
456
213
    auto& freelist = binding_data_->file_handle_read_wrap_freelist;
457
213
    if (freelist.size() > 0) {
458
195
      read_wrap = std::move(freelist.back());
459
195
      freelist.pop_back();
460
      // Use a fresh async resource.
461
      // Lifetime is ensured via AsyncWrap::resource_.
462
195
      Local<Object> resource = Object::New(env()->isolate());
463
195
      USE(resource->Set(
464
585
          env()->context(), env()->handle_string(), read_wrap->object()));
465
195
      read_wrap->AsyncReset(resource);
466
195
      read_wrap->file_handle_ = this;
467
    } else {
468
      Local<Object> wrap_obj;
469
36
      if (!env()
470
18
               ->filehandlereadwrap_template()
471
18
               ->NewInstance(env()->context())
472
18
               .ToLocal(&wrap_obj)) {
473
        return UV_EBUSY;
474
      }
475
18
      read_wrap = MakeDetachedBaseObject<FileHandleReadWrap>(this, wrap_obj);
476
    }
477
  }
478
213
  int64_t recommended_read = 65536;
479

213
  if (read_length_ >= 0 && read_length_ <= recommended_read)
480
7
    recommended_read = read_length_;
481
482
213
  read_wrap->buffer_ = EmitAlloc(recommended_read);
483
484
213
  current_read_ = std::move(read_wrap);
485
486
426
  current_read_->Dispatch(uv_fs_read,
487
                          fd_,
488
213
                          &current_read_->buffer_,
489
                          1,
490
                          read_offset_,
491
213
                          uv_fs_callback_t{[](uv_fs_t* req) {
492
    FileHandle* handle;
493
    {
494
213
      FileHandleReadWrap* req_wrap = FileHandleReadWrap::from_req(req);
495
213
      handle = req_wrap->file_handle_;
496
213
      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
426
        std::move(handle->current_read_);
504
505
213
    ssize_t result = req->result;
506
213
    uv_buf_t buffer = read_wrap->buffer_;
507
508
213
    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
213
    constexpr size_t kWantedFreelistFill = 100;
513
213
    auto& freelist = handle->binding_data_->file_handle_read_wrap_freelist;
514
213
    if (freelist.size() < kWantedFreelistFill) {
515
213
      read_wrap->Reset();
516
213
      freelist.emplace_back(std::move(read_wrap));
517
    }
518
519
213
    if (result >= 0) {
520
      // Read at most as many bytes as we originally planned to.
521

212
      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
212
      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
212
      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
213
    if (result == 0)
537
10
      result = UV_EOF;
538
539
213
    handle->EmitRead(result, buffer);
540
541
    // Start over, if EmitRead() didn’t tell us to stop.
542
213
    if (handle->reading_)
543
3
      handle->ReadStart();
544
213
  }});
545
546
213
  return 0;
547
}
548
549
230
int FileHandle::ReadStop() {
550
230
  reading_ = false;
551
230
  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
4695
void FSReqCallback::Reject(Local<Value> reject) {
584
4695
  MakeCallback(env()->oncomplete_string(), 1, &reject);
585
4695
}
586
587
2519
void FSReqCallback::ResolveStat(const uv_stat_t* stat) {
588
2519
  Resolve(FillGlobalStatsArray(binding_data(), use_bigint(), stat));
589
2519
}
590
591
47009
void FSReqCallback::Resolve(Local<Value> value) {
592
  Local<Value> argv[2] {
593
    Null(env()->isolate()),
594
    value
595
47009
  };
596
  MakeCallback(env()->oncomplete_string(),
597
87054
               value->IsUndefined() ? 1 : arraysize(argv),
598
134063
               argv);
599
47005
}
600
601
51704
void FSReqCallback::SetReturnValue(const FunctionCallbackInfo<Value>& args) {
602
51704
  args.GetReturnValue().SetUndefined();
603
51704
}
604
605
51704
void NewFSReqCallback(const FunctionCallbackInfo<Value>& args) {
606
51704
  CHECK(args.IsConstructCall());
607
51704
  BindingData* binding_data = Environment::GetBindingData<BindingData>(args);
608
103408
  new FSReqCallback(binding_data, args.This(), args[0]->IsTrue());
609
51704
}
610
611
56507
FSReqAfterScope::FSReqAfterScope(FSReqBase* wrap, uv_fs_t* req)
612
    : wrap_(wrap),
613
      req_(req),
614
      handle_scope_(wrap->env()->isolate()),
615
56507
      context_scope_(wrap->env()->context()) {
616
56507
  CHECK_EQ(wrap_->req(), req);
617
56507
}
618
619
113006
FSReqAfterScope::~FSReqAfterScope() {
620
56503
  Clear();
621
56503
}
622
623
61749
void FSReqAfterScope::Clear() {
624
61749
  if (!wrap_) return;
625
626
56503
  uv_fs_req_cleanup(wrap_->req());
627
56503
  wrap_->Detach();
628
56503
  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
5110
void FSReqAfterScope::Reject(uv_fs_t* req) {
641
10220
  BaseObjectPtr<FSReqBase> wrap { wrap_ };
642
5110
  Local<Value> exception = UVException(wrap_->env()->isolate(),
643
5110
                                       static_cast<int>(req->result),
644
                                       wrap_->syscall(),
645
                                       nullptr,
646
                                       req->path,
647
5110
                                       wrap_->data());
648
5110
  Clear();
649
5110
  wrap->Reject(exception);
650
5110
}
651
652
56507
bool FSReqAfterScope::Proceed() {
653
56507
  if (req_->result < 0) {
654
5110
    Reject(req_);
655
5110
    return false;
656
  }
657
51397
  return true;
658
}
659
660
7298
void AfterNoArgs(uv_fs_t* req) {
661
7298
  FSReqBase* req_wrap = FSReqBase::from_req(req);
662
14593
  FSReqAfterScope after(req_wrap, req);
663
664
7298
  if (after.Proceed())
665
14248
    req_wrap->Resolve(Undefined(req_wrap->env()->isolate()));
666
7295
}
667
668
8642
void AfterStat(uv_fs_t* req) {
669
8642
  FSReqBase* req_wrap = FSReqBase::from_req(req);
670
17284
  FSReqAfterScope after(req_wrap, req);
671
672
8642
  if (after.Proceed()) {
673
4030
    req_wrap->ResolveStat(&req->statbuf);
674
  }
675
8642
}
676
677
38259
void AfterInteger(uv_fs_t* req) {
678
38259
  FSReqBase* req_wrap = FSReqBase::from_req(req);
679
76518
  FSReqAfterScope after(req_wrap, req);
680
681
38259
  int result = static_cast<int>(req->result);
682

38259
  if (result >= 0 && req_wrap->is_plain_open())
683
5432
    req_wrap->env()->AddUnmanagedFd(result);
684
685
38259
  if (after.Proceed())
686
76170
    req_wrap->Resolve(Integer::New(req_wrap->env()->isolate(), result));
687
38259
}
688
689
1355
void AfterOpenFileHandle(uv_fs_t* req) {
690
1355
  FSReqBase* req_wrap = FSReqBase::from_req(req);
691
1355
  FSReqAfterScope after(req_wrap, req);
692
693
1355
  if (after.Proceed()) {
694
1226
    FileHandle* fd = FileHandle::New(req_wrap->binding_data(),
695
1226
                                     static_cast<int>(req->result));
696
1226
    if (fd == nullptr) return;
697
2452
    req_wrap->Resolve(fd->object());
698
  }
699
}
700
701
// Reverse the logic applied by path.toNamespacedPath() to create a
702
// namespace-prefixed path.
703
504
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
504
}
713
714
360
void AfterMkdirp(uv_fs_t* req) {
715
360
  FSReqBase* req_wrap = FSReqBase::from_req(req);
716
360
  FSReqAfterScope after(req_wrap, req);
717
360
  if (after.Proceed()) {
718
708
    std::string first_path(req_wrap->continuation_data()->first_path());
719
354
    if (first_path.empty())
720
254
      return req_wrap->Resolve(Undefined(req_wrap->env()->isolate()));
721
227
    FromNamespacedPath(&first_path);
722
    Local<Value> path;
723
    Local<Value> error;
724
227
    if (!StringBytes::Encode(req_wrap->env()->isolate(), first_path.c_str(),
725
                             req_wrap->encoding(),
726
454
                             &error).ToLocal(&path)) {
727
      return req_wrap->Reject(error);
728
    }
729
227
    return req_wrap->Resolve(path);
730
  }
731
}
732
733
6
void AfterStringPath(uv_fs_t* req) {
734
6
  FSReqBase* req_wrap = FSReqBase::from_req(req);
735
12
  FSReqAfterScope after(req_wrap, req);
736
737
  MaybeLocal<Value> link;
738
  Local<Value> error;
739
740
6
  if (after.Proceed()) {
741
    link = StringBytes::Encode(req_wrap->env()->isolate(),
742
                               req->path,
743
                               req_wrap->encoding(),
744
5
                               &error);
745
5
    if (link.IsEmpty())
746
      req_wrap->Reject(error);
747
    else
748
10
      req_wrap->Resolve(link.ToLocalChecked());
749
  }
750
6
}
751
752
64
void AfterStringPtr(uv_fs_t* req) {
753
64
  FSReqBase* req_wrap = FSReqBase::from_req(req);
754
127
  FSReqAfterScope after(req_wrap, req);
755
756
  MaybeLocal<Value> link;
757
  Local<Value> error;
758
759
64
  if (after.Proceed()) {
760
    link = StringBytes::Encode(req_wrap->env()->isolate(),
761
58
                               static_cast<const char*>(req->ptr),
762
                               req_wrap->encoding(),
763
58
                               &error);
764
58
    if (link.IsEmpty())
765
      req_wrap->Reject(error);
766
    else
767
116
      req_wrap->Resolve(link.ToLocalChecked());
768
  }
769
63
}
770
771
101
void AfterScanDir(uv_fs_t* req) {
772
101
  FSReqBase* req_wrap = FSReqBase::from_req(req);
773
101
  FSReqAfterScope after(req_wrap, req);
774
775
101
  if (!after.Proceed()) {
776
6
    return;
777
  }
778
95
  Environment* env = req_wrap->env();
779
  Local<Value> error;
780
  int r;
781
95
  std::vector<Local<Value>> name_v;
782
783
  for (;;) {
784
    uv_dirent_t ent;
785
786
7677
    r = uv_fs_scandir_next(req, &ent);
787
7677
    if (r == UV_EOF)
788
95
      break;
789
7582
    if (r != 0) {
790
      return req_wrap->Reject(UVException(
791
          env->isolate(), r, nullptr, req_wrap->syscall(), req->path));
792
    }
793
794
    MaybeLocal<Value> filename =
795
      StringBytes::Encode(env->isolate(),
796
          ent.name,
797
          req_wrap->encoding(),
798
7582
          &error);
799
7582
    if (filename.IsEmpty())
800
      return req_wrap->Reject(error);
801
802
7582
    name_v.push_back(filename.ToLocalChecked());
803
7582
  }
804
805
190
  req_wrap->Resolve(Array::New(env->isolate(), name_v.data(), name_v.size()));
806
}
807
808
125
void AfterScanDirWithTypes(uv_fs_t* req) {
809
125
  FSReqBase* req_wrap = FSReqBase::from_req(req);
810
125
  FSReqAfterScope after(req_wrap, req);
811
812
125
  if (!after.Proceed()) {
813
1
    return;
814
  }
815
816
124
  Environment* env = req_wrap->env();
817
124
  Isolate* isolate = env->isolate();
818
  Local<Value> error;
819
  int r;
820
821
124
  std::vector<Local<Value>> name_v;
822
124
  std::vector<Local<Value>> type_v;
823
824
  for (;;) {
825
    uv_dirent_t ent;
826
827
141
    r = uv_fs_scandir_next(req, &ent);
828
141
    if (r == UV_EOF)
829
124
      break;
830
17
    if (r != 0) {
831
      return req_wrap->Reject(
832
          UVException(isolate, r, nullptr, req_wrap->syscall(), req->path));
833
    }
834
835
    MaybeLocal<Value> filename =
836
      StringBytes::Encode(isolate,
837
          ent.name,
838
          req_wrap->encoding(),
839
17
          &error);
840
17
    if (filename.IsEmpty())
841
      return req_wrap->Reject(error);
842
843
17
    name_v.push_back(filename.ToLocalChecked());
844
17
    type_v.emplace_back(Integer::New(isolate, ent.type));
845
17
  }
846
847
  Local<Value> result[] = {
848
    Array::New(isolate, name_v.data(), name_v.size()),
849
    Array::New(isolate, type_v.data(), type_v.size())
850
248
  };
851
248
  req_wrap->Resolve(Array::New(isolate, result, arraysize(result)));
852
}
853
854
3971
void Access(const FunctionCallbackInfo<Value>& args) {
855
3971
  Environment* env = Environment::GetCurrent(args);
856
3971
  Isolate* isolate = env->isolate();
857
7942
  HandleScope scope(isolate);
858
859
3971
  const int argc = args.Length();
860
3971
  CHECK_GE(argc, 2);
861
862
3971
  CHECK(args[1]->IsInt32());
863
7942
  int mode = args[1].As<Int32>()->Value();
864
865
7942
  BufferValue path(isolate, args[0]);
866
3971
  CHECK_NOT_NULL(*path);
867
868
3971
  FSReqBase* req_wrap_async = GetReqWrap(args, 2);
869
3971
  if (req_wrap_async != nullptr) {  // access(path, mode, req)
870
44
    AsyncCall(env, req_wrap_async, args, "access", UTF8, AfterNoArgs,
871
              uv_fs_access, *path, mode);
872
  } else {  // access(path, mode, undefined, ctx)
873
3927
    CHECK_EQ(argc, 4);
874
7854
    FSReqWrapSync req_wrap_sync;
875

3929
    FS_SYNC_TRACE_BEGIN(access);
876
7854
    SyncCall(env, args[3], &req_wrap_sync, "access", uv_fs_access, *path, mode);
877

3929
    FS_SYNC_TRACE_END(access);
878
  }
879
3971
}
880
881
882
64546
void Close(const FunctionCallbackInfo<Value>& args) {
883
64546
  Environment* env = Environment::GetCurrent(args);
884
885
64546
  const int argc = args.Length();
886
64546
  CHECK_GE(argc, 2);
887
888
64546
  CHECK(args[0]->IsInt32());
889
129092
  int fd = args[0].As<Int32>()->Value();
890
64546
  env->RemoveUnmanagedFd(fd);
891
892
64546
  FSReqBase* req_wrap_async = GetReqWrap(args, 1);
893
64546
  if (req_wrap_async != nullptr) {  // close(fd, req)
894
5350
    AsyncCall(env, req_wrap_async, args, "close", UTF8, AfterNoArgs,
895
              uv_fs_close, fd);
896
  } else {  // close(fd, undefined, ctx)
897
59196
    CHECK_EQ(argc, 3);
898
118392
    FSReqWrapSync req_wrap_sync;
899

59253
    FS_SYNC_TRACE_BEGIN(close);
900
59196
    SyncCall(env, args[2], &req_wrap_sync, "close", uv_fs_close, fd);
901

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

5557
  if (offset >= 3 && 0 == memcmp(&chars[0], "\xEF\xBB\xBF", 3)) {
959
1
    start = 3;  // Skip UTF-8 BOM.
960
  }
961
962
5557
  const size_t size = offset - start;
963
5557
  char* p = &chars[start];
964
5557
  char* pe = &chars[size];
965
  char* pos[2];
966
5557
  char** ppos = &pos[0];
967
968
91951
  while (p < pe) {
969
91939
    char c = *p++;
970

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

15253
    FS_SYNC_TRACE_BEGIN(stat);
1041
30502
    int err = SyncCall(env, args[3], &req_wrap_sync, "stat", uv_fs_stat, *path);
1042

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

109438
    FS_SYNC_TRACE_BEGIN(lstat);
1072
218842
    int err = SyncCall(env, args[3], &req_wrap_sync, "lstat", uv_fs_lstat,
1073
                       *path);
1074

109438
    FS_SYNC_TRACE_END(lstat);
1075
109421
    if (err != 0) {
1076
444
      return;  // error info is in ctx
1077
    }
1078
1079
    Local<Value> arr = FillGlobalStatsArray(binding_data, use_bigint,
1080
108977
        static_cast<const uv_stat_t*>(req_wrap_sync.req.ptr));
1081
217954
    args.GetReturnValue().Set(arr);
1082
  }
1083
}
1084
1085
54421
static void FStat(const FunctionCallbackInfo<Value>& args) {
1086
54421
  BindingData* binding_data = Environment::GetBindingData<BindingData>(args);
1087
54421
  Environment* env = binding_data->env();
1088
1089
54421
  const int argc = args.Length();
1090
54421
  CHECK_GE(argc, 2);
1091
1092
54421
  CHECK(args[0]->IsInt32());
1093
108842
  int fd = args[0].As<Int32>()->Value();
1094
1095
54421
  bool use_bigint = args[1]->IsTrue();
1096
54421
  FSReqBase* req_wrap_async = GetReqWrap(args, 2, use_bigint);
1097
54421
  if (req_wrap_async != nullptr) {  // fstat(fd, use_bigint, req)
1098
1161
    AsyncCall(env, req_wrap_async, args, "fstat", UTF8, AfterStat,
1099
              uv_fs_fstat, fd);
1100
  } else {  // fstat(fd, use_bigint, undefined, ctx)
1101
53260
    CHECK_EQ(argc, 4);
1102
53260
    FSReqWrapSync req_wrap_sync;
1103

53269
    FS_SYNC_TRACE_BEGIN(fstat);
1104
53260
    int err = SyncCall(env, args[3], &req_wrap_sync, "fstat", uv_fs_fstat, fd);
1105

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

336
    FS_SYNC_TRACE_BEGIN(symlink);
1139
664
    SyncCall(env, args[4], &req_wrap_sync, "symlink",
1140
             uv_fs_symlink, *target, *path, flags);
1141

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

11
    FS_SYNC_TRACE_BEGIN(link);
1166
10
    SyncCall(env, args[3], &req_wrap_sync, "link",
1167
             uv_fs_link, *src, *dest);
1168

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

69
    FS_SYNC_TRACE_BEGIN(readlink);
1192
134
    int err = SyncCall(env, args[3], &req_wrap_sync, "readlink",
1193
                       uv_fs_readlink, *path);
1194

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

5
    FS_SYNC_TRACE_BEGIN(rename);
1236
6
    SyncCall(env, args[3], &req_wrap_sync, "rename", uv_fs_rename,
1237
             *old_path, *new_path);
1238

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

17
    FS_SYNC_TRACE_BEGIN(ftruncate);
1262
15
    SyncCall(env, args[3], &req_wrap_sync, "ftruncate", uv_fs_ftruncate, fd,
1263
             len);
1264

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

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

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

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

19
    FS_SYNC_TRACE_END(fsync);
1309
  }
1310
21
}
1311
1312
2586
static void Unlink(const FunctionCallbackInfo<Value>& args) {
1313
2586
  Environment* env = Environment::GetCurrent(args);
1314
1315
2586
  const int argc = args.Length();
1316
2586
  CHECK_GE(argc, 2);
1317
1318
5172
  BufferValue path(env->isolate(), args[0]);
1319
2586
  CHECK_NOT_NULL(*path);
1320
1321
2586
  FSReqBase* req_wrap_async = GetReqWrap(args, 1);
1322
2586
  if (req_wrap_async != nullptr) {
1323
1029
    AsyncCall(env, req_wrap_async, args, "unlink", UTF8, AfterNoArgs,
1324
              uv_fs_unlink, *path);
1325
  } else {
1326
1557
    CHECK_EQ(argc, 3);
1327
3114
    FSReqWrapSync req_wrap_sync;
1328

1612
    FS_SYNC_TRACE_BEGIN(unlink);
1329
3114
    SyncCall(env, args[2], &req_wrap_sync, "unlink", uv_fs_unlink, *path);
1330

1612
    FS_SYNC_TRACE_END(unlink);
1331
  }
1332
2586
}
1333
1334
1882
static void RMDir(const FunctionCallbackInfo<Value>& args) {
1335
1882
  Environment* env = Environment::GetCurrent(args);
1336
1337
1882
  const int argc = args.Length();
1338
1882
  CHECK_GE(argc, 2);
1339
1340
3764
  BufferValue path(env->isolate(), args[0]);
1341
1882
  CHECK_NOT_NULL(*path);
1342
1343
1882
  FSReqBase* req_wrap_async = GetReqWrap(args, 1);  // rmdir(path, req)
1344
1882
  if (req_wrap_async != nullptr) {
1345
259
    AsyncCall(env, req_wrap_async, args, "rmdir", UTF8, AfterNoArgs,
1346
              uv_fs_rmdir, *path);
1347
  } else {  // rmdir(path, undefined, ctx)
1348
1623
    CHECK_EQ(argc, 3);
1349
3246
    FSReqWrapSync req_wrap_sync;
1350

1629
    FS_SYNC_TRACE_BEGIN(rmdir);
1351
3246
    SyncCall(env, args[2], &req_wrap_sync, "rmdir",
1352
             uv_fs_rmdir, *path);
1353

1629
    FS_SYNC_TRACE_END(rmdir);
1354
  }
1355
1882
}
1356
1357
6286
int MKDirpSync(uv_loop_t* loop,
1358
               uv_fs_t* req,
1359
               const std::string& path,
1360
               int mode,
1361
               uv_fs_cb cb) {
1362
6286
  FSReqWrapSync* req_wrap = ContainerOf(&FSReqWrapSync::req, req);
1363
1364
  // on the first iteration of algorithm, stash state information.
1365
6286
  if (req_wrap->continuation_data() == nullptr) {
1366
6286
    req_wrap->set_continuation_data(
1367
12572
        std::make_unique<FSContinuationData>(req, mode, cb));
1368
6286
    req_wrap->continuation_data()->PushPath(std::move(path));
1369
  }
1370
1371
12419
  while (req_wrap->continuation_data()->paths().size() > 0) {
1372
6436
    std::string next_path = req_wrap->continuation_data()->PopPath();
1373
6436
    int err = uv_fs_mkdir(loop, req, next_path.c_str(), mode, nullptr);
1374
    while (true) {
1375

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

5986
          if (err == 0 && !S_ISDIR(req->statbuf.st_mode)) {
1407
1
            uv_fs_req_cleanup(req);
1408

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

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

490
            if (reinterpret_cast<intptr_t>(req->data) == UV_EEXIST &&
1494
245
                  req_wrap->continuation_data()->paths().size() > 0) {
1495

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

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

583
    AsyncCall(env, req_wrap_async, args, "mkdir", UTF8,
1557
              mkdirp ? AfterMkdirp : AfterNoArgs,
1558
              mkdirp ? MKDirpAsync : uv_fs_mkdir, *path, mode);
1559
  } else {  // mkdir(path, mode, undefined, ctx)
1560
1203
    CHECK_EQ(argc, 5);
1561
1203
    FSReqWrapSync req_wrap_sync;
1562

1207
    FS_SYNC_TRACE_BEGIN(mkdir);
1563
1203
    if (mkdirp) {
1564
283
      int err = CallMKDirpSync(env, args, &req_wrap_sync, *path, mode);
1565

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

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

22
    FS_SYNC_TRACE_BEGIN(realpath);
1608
40
    int err = SyncCall(env, args[3], &req_wrap_sync, "realpath",
1609
                       uv_fs_realpath, *path);
1610

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

13774
    FS_SYNC_TRACE_BEGIN(readdir);
1659
27544
    int err = SyncCall(env, args[4], &req_wrap_sync, "scandir",
1660
                       uv_fs_scandir, *path, 0 /*flags*/);
1661

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

59723
    FS_SYNC_TRACE_BEGIN(open);
1743
119320
    int result = SyncCall(env, args[4], &req_wrap_sync, "open",
1744
                          uv_fs_open, *path, flags, mode);
1745

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

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

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

118
    FS_SYNC_TRACE_BEGIN(copyfile);
1813
232
    SyncCall(env, args[4], &req_wrap_sync, "copyfile",
1814
             uv_fs_copyfile, *src, *dest, flags);
1815

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

45014
    FS_SYNC_TRACE_BEGIN(write);
1868
44964
    int bytesWritten = SyncCall(env, args[6], &req_wrap_sync, "write",
1869
44964
                                uv_fs_write, fd, &uvbuf, 1, pos);
1870

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

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

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

379703
  if (!is_async && value->IsString()) {
1958
126542
    auto string = value.As<String>();
1959


126543
    if ((enc == ASCII || enc == LATIN1) && string->IsExternalOneByte()) {
1960
1
      auto ext = string->GetExternalOneByteStringResource();
1961
1
      buf = const_cast<char*>(ext->data());
1962
1
      len = ext->length();
1963


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

126542
    FS_SYNC_TRACE_BEGIN(write);
2012
126542
    int bytesWritten = SyncCall(env, args[5], &req_wrap_sync, "write",
2013
126542
                                uv_fs_write, fd, &uvbuf, 1, pos);
2014

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

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

193563
    FS_SYNC_TRACE_BEGIN(read);
2071
193524
    const int bytesRead = SyncCall(env, args[6], &req_wrap_sync, "read",
2072
193524
                                   uv_fs_read, fd, &uvbuf, 1, pos);
2073

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

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

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

171
    FS_SYNC_TRACE_BEGIN(chmod);
2148
338
    SyncCall(env, args[3], &req_wrap_sync, "chmod",
2149
             uv_fs_chmod, *path, mode);
2150

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

7
    FS_SYNC_TRACE_BEGIN(fchmod);
2178
5
    SyncCall(env, args[3], &req_wrap_sync, "fchmod",
2179
             uv_fs_fchmod, fd, mode);
2180

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

4
    FS_SYNC_TRACE_BEGIN(chown);
2211
4
    SyncCall(env, args[4], &req_wrap_sync, "chown",
2212
             uv_fs_chown, *path, uid, gid);
2213

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

4
    FS_SYNC_TRACE_BEGIN(fchown);
2244
2
    SyncCall(env, args[4], &req_wrap_sync, "fchown",
2245
             uv_fs_fchown, fd, uid, gid);
2246

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

4
    FS_SYNC_TRACE_BEGIN(lchown);
2274
4
    SyncCall(env, args[4], &req_wrap_sync, "lchown",
2275
             uv_fs_lchown, *path, uid, gid);
2276

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

29
    FS_SYNC_TRACE_BEGIN(utimes);
2304
54
    SyncCall(env, args[4], &req_wrap_sync, "utime",
2305
             uv_fs_utime, *path, atime, mtime);
2306

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

11
    FS_SYNC_TRACE_BEGIN(futimes);
2333
9
    SyncCall(env, args[4], &req_wrap_sync, "futime",
2334
             uv_fs_futime, fd, atime, mtime);
2335

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

7
    FS_SYNC_TRACE_BEGIN(lutimes);
2362
14
    SyncCall(env, args[4], &req_wrap_sync, "lutime",
2363
             uv_fs_lutime, *path, atime, mtime);
2364

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

11
    FS_SYNC_TRACE_BEGIN(mkdtemp);
2388
18
    SyncCall(env, args[3], &req_wrap_sync, "mkdtemp",
2389
             uv_fs_mkdtemp, *tmpl);
2390

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