GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/node_file.cc Lines: 807 1502 53.7 %
Date: 2021-02-19 04:08:54 Branches: 303 1226 24.7 %

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_process.h"
27
#include "node_stat_watcher.h"
28
#include "util-inl.h"
29
30
#include "tracing/trace_event.h"
31
32
#include "req_wrap-inl.h"
33
#include "stream_base-inl.h"
34
#include "string_bytes.h"
35
36
#include <fcntl.h>
37
#include <sys/types.h>
38
#include <sys/stat.h>
39
#include <cstring>
40
#include <cerrno>
41
#include <climits>
42
43
#if defined(__MINGW32__) || defined(_MSC_VER)
44
# include <io.h>
45
#endif
46
47
#include <memory>
48
49
namespace node {
50
51
namespace fs {
52
53
using v8::Array;
54
using v8::BigInt;
55
using v8::Boolean;
56
using v8::Context;
57
using v8::EscapableHandleScope;
58
using v8::Function;
59
using v8::FunctionCallbackInfo;
60
using v8::FunctionTemplate;
61
using v8::HandleScope;
62
using v8::Int32;
63
using v8::Integer;
64
using v8::Isolate;
65
using v8::Local;
66
using v8::MaybeLocal;
67
using v8::Number;
68
using v8::Object;
69
using v8::ObjectTemplate;
70
using v8::Promise;
71
using v8::String;
72
using v8::Symbol;
73
using v8::Uint32;
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
std::string Basename(const std::string& str, const std::string& extension) {
88
  // Remove everything leading up to and including the final path separator.
89
  std::string::size_type pos = str.find_last_of(kPathSeparator);
90
91
  // Starting index for the resulting string
92
  std::size_t start_pos = 0;
93
  // String size to return
94
  std::size_t str_size = str.size();
95
  if (pos != std::string::npos) {
96
    start_pos = pos + 1;
97
    str_size -= start_pos;
98
  }
99
100
  // Strip away the extension, if any.
101
  if (str_size >= extension.size() &&
102
      str.compare(str.size() - extension.size(),
103
        extension.size(), extension) == 0) {
104
    str_size -= extension.size();
105
  }
106
107
  return str.substr(start_pos, str_size);
108
}
109
110
57439
inline int64_t GetOffset(Local<Value> value) {
111
57439
  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
void FSReqBase::MemoryInfo(MemoryTracker* tracker) const {
142
  tracker->TrackField("continuation_data", continuation_data_);
143
}
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
115
FileHandle::FileHandle(BindingData* binding_data,
149
115
                       Local<Object> obj, int fd)
150
    : AsyncWrap(binding_data->env(), obj, AsyncWrap::PROVIDER_FILEHANDLE),
151
      StreamBase(env()),
152
      fd_(fd),
153
115
      binding_data_(binding_data) {
154
115
  MakeWeak();
155
115
  StreamBase::AttachToObject(GetObject());
156
115
}
157
158
115
FileHandle* FileHandle::New(BindingData* binding_data,
159
                            int fd, Local<Object> obj) {
160
115
  Environment* env = binding_data->env();
161

460
  if (obj.IsEmpty() && !env->fd_constructor_template()
162
345
                            ->NewInstance(env->context())
163
115
                            .ToLocal(&obj)) {
164
    return nullptr;
165
  }
166
115
  return new FileHandle(binding_data, obj, fd);
167
}
168
169
void FileHandle::New(const FunctionCallbackInfo<Value>& args) {
170
  BindingData* binding_data = Environment::GetBindingData<BindingData>(args);
171
  Environment* env = binding_data->env();
172
  CHECK(args.IsConstructCall());
173
  CHECK(args[0]->IsInt32());
174
175
  FileHandle* handle =
176
      FileHandle::New(binding_data, args[0].As<Int32>()->Value(), args.This());
177
  if (handle == nullptr) return;
178
  if (args[1]->IsNumber())
179
    handle->read_offset_ = args[1]->IntegerValue(env->context()).FromJust();
180
  if (args[2]->IsNumber())
181
    handle->read_length_ = args[2]->IntegerValue(env->context()).FromJust();
182
}
183
184
345
FileHandle::~FileHandle() {
185
115
  CHECK(!closing_);  // We should not be deleting while explicitly closing!
186
115
  Close();           // Close synchronously and emit warning
187
115
  CHECK(closed_);    // We have to be closed at the point
188
230
}
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
FileHandle::TransferMode FileHandle::GetTransferMode() const {
202
  return reading_ || closing_ || closed_ ?
203
      TransferMode::kUntransferable : TransferMode::kTransferable;
204
}
205
206
std::unique_ptr<worker::TransferData> FileHandle::TransferForMessaging() {
207
  CHECK_NE(GetTransferMode(), TransferMode::kUntransferable);
208
  auto ret = std::make_unique<TransferData>(fd_);
209
  closed_ = true;
210
  return ret;
211
}
212
213
FileHandle::TransferData::TransferData(int fd) : fd_(fd) {}
214
215
FileHandle::TransferData::~TransferData() {
216
  if (fd_ > 0) {
217
    uv_fs_t close_req;
218
    CHECK_EQ(0, uv_fs_close(nullptr, &close_req, fd_, nullptr));
219
    uv_fs_req_cleanup(&close_req);
220
  }
221
}
222
223
BaseObjectPtr<BaseObject> FileHandle::TransferData::Deserialize(
224
    Environment* env,
225
    v8::Local<v8::Context> context,
226
    std::unique_ptr<worker::TransferData> self) {
227
  BindingData* bd = Environment::GetBindingData<BindingData>(context);
228
  if (bd == nullptr) return {};
229
230
  int fd = fd_;
231
  fd_ = -1;
232
  return BaseObjectPtr<BaseObject> { FileHandle::New(bd, fd) };
233
}
234
235
// Close the file descriptor if it hasn't already been closed. A process
236
// warning will be emitted using a SetImmediate to avoid calling back to
237
// JS during GC. If closing the fd fails at this point, a fatal exception
238
// will crash the process immediately.
239
115
inline void FileHandle::Close() {
240
230
  if (closed_) return;
241
  uv_fs_t req;
242
  int ret = uv_fs_close(env()->event_loop(), &req, fd_, nullptr);
243
  uv_fs_req_cleanup(&req);
244
245
  struct err_detail { int ret; int fd; };
246
247
  err_detail detail { ret, fd_ };
248
249
  AfterClose();
250
251
  if (ret < 0) {
252
    // Do not unref this
253
    env()->SetImmediate([detail](Environment* env) {
254
      char msg[70];
255
      snprintf(msg, arraysize(msg),
256
              "Closing file descriptor %d on garbage collection failed",
257
              detail.fd);
258
      // This exception will end up being fatal for the process because
259
      // it is being thrown from within the SetImmediate handler and
260
      // there is no JS stack to bubble it to. In other words, tearing
261
      // down the process is the only reasonable thing we can do here.
262
      HandleScope handle_scope(env->isolate());
263
      env->ThrowUVException(detail.ret, "close", msg);
264
    });
265
    return;
266
  }
267
268
  // If the close was successful, we still want to emit a process warning
269
  // to notify that the file descriptor was gc'd. We want to be noisy about
270
  // this because not explicitly closing the FileHandle is a bug.
271
272
  env()->SetImmediate([detail](Environment* env) {
273
    ProcessEmitWarning(env,
274
                       "Closing file descriptor %d on garbage collection",
275
                       detail.fd);
276
    if (env->filehandle_close_warning()) {
277
      env->set_filehandle_close_warning(false);
278
      ProcessEmitDeprecationWarning(
279
          env,
280
          "Closing a FileHandle object on garbage collection is deprecated. "
281
          "Please close FileHandle objects explicitly using "
282
          "FileHandle.prototype.close(). In the future, an error will be "
283
          "thrown if a file descriptor is closed during garbage collection.",
284
          "DEP0137").IsNothing();
285
    }
286
  }, CallbackFlags::kUnrefed);
287
}
288
289
115
void FileHandle::CloseReq::Resolve() {
290
115
  Isolate* isolate = env()->isolate();
291
230
  HandleScope scope(isolate);
292
115
  Context::Scope context_scope(env()->context());
293
230
  InternalCallbackScope callback_scope(this);
294
230
  Local<Promise> promise = promise_.Get(isolate);
295
115
  Local<Promise::Resolver> resolver = promise.As<Promise::Resolver>();
296
345
  resolver->Resolve(env()->context(), Undefined(isolate)).Check();
297
115
}
298
299
void FileHandle::CloseReq::Reject(Local<Value> reason) {
300
  Isolate* isolate = env()->isolate();
301
  HandleScope scope(isolate);
302
  Context::Scope context_scope(env()->context());
303
  InternalCallbackScope callback_scope(this);
304
  Local<Promise> promise = promise_.Get(isolate);
305
  Local<Promise::Resolver> resolver = promise.As<Promise::Resolver>();
306
  resolver->Reject(env()->context(), reason).Check();
307
}
308
309
115
FileHandle* FileHandle::CloseReq::file_handle() {
310
115
  Isolate* isolate = env()->isolate();
311
230
  HandleScope scope(isolate);
312
230
  Local<Value> val = ref_.Get(isolate);
313
115
  Local<Object> obj = val.As<Object>();
314
230
  return Unwrap<FileHandle>(obj);
315
}
316
317
115
FileHandle::CloseReq::CloseReq(Environment* env,
318
                               Local<Object> obj,
319
                               Local<Promise> promise,
320
115
                               Local<Value> ref)
321
230
  : ReqWrap(env, obj, AsyncWrap::PROVIDER_FILEHANDLECLOSEREQ) {
322
115
  promise_.Reset(env->isolate(), promise);
323
115
  ref_.Reset(env->isolate(), ref);
324
115
}
325
326
575
FileHandle::CloseReq::~CloseReq() {
327
115
  uv_fs_req_cleanup(req());
328
115
  promise_.Reset();
329
115
  ref_.Reset();
330
230
}
331
332
void FileHandle::CloseReq::MemoryInfo(MemoryTracker* tracker) const {
333
  tracker->TrackField("promise", promise_);
334
  tracker->TrackField("ref", ref_);
335
}
336
337
338
339
// Closes this FileHandle asynchronously and returns a Promise that will be
340
// resolved when the callback is invoked, or rejects with a UVException if
341
// there was a problem closing the fd. This is the preferred mechanism for
342
// closing the FD object even tho the object will attempt to close
343
// automatically on gc.
344
115
MaybeLocal<Promise> FileHandle::ClosePromise() {
345
115
  Isolate* isolate = env()->isolate();
346
115
  EscapableHandleScope scope(isolate);
347
115
  Local<Context> context = env()->context();
348
115
  auto maybe_resolver = Promise::Resolver::New(context);
349
115
  CHECK(!maybe_resolver.IsEmpty());
350
115
  Local<Promise::Resolver> resolver = maybe_resolver.ToLocalChecked();
351
115
  Local<Promise> promise = resolver.As<Promise>();
352
115
  CHECK(!reading_);
353

115
  if (!closed_ && !closing_) {
354
115
    closing_ = true;
355
    Local<Object> close_req_obj;
356
230
    if (!env()
357
230
             ->fdclose_constructor_template()
358
345
             ->NewInstance(env()->context())
359
115
             .ToLocal(&close_req_obj)) {
360
      return MaybeLocal<Promise>();
361
    }
362
230
    CloseReq* req = new CloseReq(env(), close_req_obj, promise, object());
363
345
    auto AfterClose = uv_fs_callback_t{[](uv_fs_t* req) {
364
230
      std::unique_ptr<CloseReq> close(CloseReq::from_req(req));
365
115
      CHECK_NOT_NULL(close);
366
115
      close->file_handle()->AfterClose();
367
115
      Isolate* isolate = close->env()->isolate();
368
115
      if (req->result < 0) {
369
        HandleScope handle_scope(isolate);
370
        close->Reject(
371
            UVException(isolate, static_cast<int>(req->result), "close"));
372
      } else {
373
115
        close->Resolve();
374
      }
375
460
    }};
376
115
    int ret = req->Dispatch(uv_fs_close, fd_, AfterClose);
377
115
    if (ret < 0) {
378
      req->Reject(UVException(isolate, ret, "close"));
379
      delete req;
380
115
    }
381
  } else {
382
    // Already closed. Just reject the promise immediately
383
    resolver->Reject(context, UVException(isolate, UV_EBADF, "close"))
384
        .Check();
385
  }
386
115
  return scope.Escape(promise);
387
}
388
389
115
void FileHandle::Close(const FunctionCallbackInfo<Value>& args) {
390
  FileHandle* fd;
391
115
  ASSIGN_OR_RETURN_UNWRAP(&fd, args.Holder());
392
  Local<Promise> ret;
393
230
  if (!fd->ClosePromise().ToLocal(&ret)) return;
394
230
  args.GetReturnValue().Set(ret);
395
}
396
397
398
void FileHandle::ReleaseFD(const FunctionCallbackInfo<Value>& args) {
399
  FileHandle* fd;
400
  ASSIGN_OR_RETURN_UNWRAP(&fd, args.Holder());
401
  // Just act as if this FileHandle has been closed.
402
  fd->AfterClose();
403
}
404
405
406
115
void FileHandle::AfterClose() {
407
115
  closing_ = false;
408
115
  closed_ = true;
409
115
  fd_ = -1;
410

115
  if (reading_ && !persistent().IsEmpty())
411
    EmitRead(UV_EOF);
412
115
}
413
414
void FileHandleReadWrap::MemoryInfo(MemoryTracker* tracker) const {
415
  tracker->TrackField("buffer", buffer_);
416
  tracker->TrackField("file_handle", this->file_handle_);
417
}
418
419
FileHandleReadWrap::FileHandleReadWrap(FileHandle* handle, Local<Object> obj)
420
  : ReqWrap(handle->env(), obj, AsyncWrap::PROVIDER_FSREQCALLBACK),
421
    file_handle_(handle) {}
422
423
int FileHandle::ReadStart() {
424
  if (!IsAlive() || IsClosing())
425
    return UV_EOF;
426
427
  reading_ = true;
428
429
  if (current_read_)
430
    return 0;
431
432
  BaseObjectPtr<FileHandleReadWrap> read_wrap;
433
434
  if (read_length_ == 0) {
435
    EmitRead(UV_EOF);
436
    return 0;
437
  }
438
439
  {
440
    // Create a new FileHandleReadWrap or re-use one.
441
    // Either way, we need these two scopes for AsyncReset() or otherwise
442
    // for creating the new instance.
443
    HandleScope handle_scope(env()->isolate());
444
    AsyncHooks::DefaultTriggerAsyncIdScope trigger_scope(this);
445
446
    auto& freelist = binding_data_->file_handle_read_wrap_freelist;
447
    if (freelist.size() > 0) {
448
      read_wrap = std::move(freelist.back());
449
      freelist.pop_back();
450
      // Use a fresh async resource.
451
      // Lifetime is ensured via AsyncWrap::resource_.
452
      Local<Object> resource = Object::New(env()->isolate());
453
      USE(resource->Set(
454
          env()->context(), env()->handle_string(), read_wrap->object()));
455
      read_wrap->AsyncReset(resource);
456
      read_wrap->file_handle_ = this;
457
    } else {
458
      Local<Object> wrap_obj;
459
      if (!env()
460
               ->filehandlereadwrap_template()
461
               ->NewInstance(env()->context())
462
               .ToLocal(&wrap_obj)) {
463
        return UV_EBUSY;
464
      }
465
      read_wrap = MakeDetachedBaseObject<FileHandleReadWrap>(this, wrap_obj);
466
    }
467
  }
468
  int64_t recommended_read = 65536;
469
  if (read_length_ >= 0 && read_length_ <= recommended_read)
470
    recommended_read = read_length_;
471
472
  read_wrap->buffer_ = EmitAlloc(recommended_read);
473
474
  current_read_ = std::move(read_wrap);
475
476
  current_read_->Dispatch(uv_fs_read,
477
                          fd_,
478
                          &current_read_->buffer_,
479
                          1,
480
                          read_offset_,
481
                          uv_fs_callback_t{[](uv_fs_t* req) {
482
    FileHandle* handle;
483
    {
484
      FileHandleReadWrap* req_wrap = FileHandleReadWrap::from_req(req);
485
      handle = req_wrap->file_handle_;
486
      CHECK_EQ(handle->current_read_.get(), req_wrap);
487
    }
488
489
    // ReadStart() checks whether current_read_ is set to determine whether
490
    // a read is in progress. Moving it into a local variable makes sure that
491
    // the ReadStart() call below doesn't think we're still actively reading.
492
    BaseObjectPtr<FileHandleReadWrap> read_wrap =
493
        std::move(handle->current_read_);
494
495
    ssize_t result = req->result;
496
    uv_buf_t buffer = read_wrap->buffer_;
497
498
    uv_fs_req_cleanup(req);
499
500
    // Push the read wrap back to the freelist, or let it be destroyed
501
    // once we’re exiting the current scope.
502
    constexpr size_t kWantedFreelistFill = 100;
503
    auto& freelist = handle->binding_data_->file_handle_read_wrap_freelist;
504
    if (freelist.size() < kWantedFreelistFill) {
505
      read_wrap->Reset();
506
      freelist.emplace_back(std::move(read_wrap));
507
    }
508
509
    if (result >= 0) {
510
      // Read at most as many bytes as we originally planned to.
511
      if (handle->read_length_ >= 0 && handle->read_length_ < result)
512
        result = handle->read_length_;
513
514
      // If we read data and we have an expected length, decrease it by
515
      // how much we have read.
516
      if (handle->read_length_ >= 0)
517
        handle->read_length_ -= result;
518
519
      // If we have an offset, increase it by how much we have read.
520
      if (handle->read_offset_ >= 0)
521
        handle->read_offset_ += result;
522
    }
523
524
    // Reading 0 bytes from a file always means EOF, or that we reached
525
    // the end of the requested range.
526
    if (result == 0)
527
      result = UV_EOF;
528
529
    handle->EmitRead(result, buffer);
530
531
    // Start over, if EmitRead() didn’t tell us to stop.
532
    if (handle->reading_)
533
      handle->ReadStart();
534
  }});
535
536
  return 0;
537
}
538
539
int FileHandle::ReadStop() {
540
  reading_ = false;
541
  return 0;
542
}
543
544
typedef SimpleShutdownWrap<ReqWrap<uv_fs_t>> FileHandleCloseWrap;
545
546
ShutdownWrap* FileHandle::CreateShutdownWrap(Local<Object> object) {
547
  return new FileHandleCloseWrap(this, object);
548
}
549
550
int FileHandle::DoShutdown(ShutdownWrap* req_wrap) {
551
  FileHandleCloseWrap* wrap = static_cast<FileHandleCloseWrap*>(req_wrap);
552
  closing_ = true;
553
  wrap->Dispatch(uv_fs_close, fd_, uv_fs_callback_t{[](uv_fs_t* req) {
554
    FileHandleCloseWrap* wrap = static_cast<FileHandleCloseWrap*>(
555
        FileHandleCloseWrap::from_req(req));
556
    FileHandle* handle = static_cast<FileHandle*>(wrap->stream());
557
    handle->AfterClose();
558
559
    int result = static_cast<int>(req->result);
560
    uv_fs_req_cleanup(req);
561
    wrap->Done(result);
562
  }});
563
564
  return 0;
565
}
566
567
568
3684
void FSReqCallback::Reject(Local<Value> reject) {
569
3684
  MakeCallback(env()->oncomplete_string(), 1, &reject);
570
3684
}
571
572
1355
void FSReqCallback::ResolveStat(const uv_stat_t* stat) {
573
1355
  Resolve(FillGlobalStatsArray(binding_data(), use_bigint(), stat));
574
1355
}
575
576
12469
void FSReqCallback::Resolve(Local<Value> value) {
577
  Local<Value> argv[2] {
578
    Null(env()->isolate()),
579
    value
580
24938
  };
581
  MakeCallback(env()->oncomplete_string(),
582
32279
               value->IsUndefined() ? 1 : arraysize(argv),
583
19810
               argv);
584
12467
}
585
586
16153
void FSReqCallback::SetReturnValue(const FunctionCallbackInfo<Value>& args) {
587
32306
  args.GetReturnValue().SetUndefined();
588
16153
}
589
590
16153
void NewFSReqCallback(const FunctionCallbackInfo<Value>& args) {
591
16153
  CHECK(args.IsConstructCall());
592
16153
  BindingData* binding_data = Environment::GetBindingData<BindingData>(args);
593
48459
  new FSReqCallback(binding_data, args.This(), args[0]->IsTrue());
594
16153
}
595
596
16881
FSReqAfterScope::FSReqAfterScope(FSReqBase* wrap, uv_fs_t* req)
597
    : wrap_(wrap),
598
      req_(req),
599
      handle_scope_(wrap->env()->isolate()),
600
16881
      context_scope_(wrap->env()->context()) {
601
16881
  CHECK_EQ(wrap_->req(), req);
602
16881
}
603
604
50637
FSReqAfterScope::~FSReqAfterScope() {
605
16879
  Clear();
606
16879
}
607
608
20737
void FSReqAfterScope::Clear() {
609
20737
  if (!wrap_) return;
610
611
16879
  uv_fs_req_cleanup(wrap_->req());
612
16879
  wrap_->Detach();
613
16879
  wrap_.reset();
614
}
615
616
// TODO(joyeecheung): create a normal context object, and
617
// construct the actual errors in the JS land using the context.
618
// The context should include fds for some fs APIs, currently they are
619
// missing in the error messages. The path, dest, syscall, fd, .etc
620
// can be put into the context before the binding is even invoked,
621
// the only information that has to come from the C++ layer is the
622
// error number (and possibly the syscall for abstraction),
623
// which is also why the errors should have been constructed
624
// in JS for more flexibility.
625
3858
void FSReqAfterScope::Reject(uv_fs_t* req) {
626
7716
  BaseObjectPtr<FSReqBase> wrap { wrap_ };
627
3858
  Local<Value> exception = UVException(wrap_->env()->isolate(),
628
3858
                                       static_cast<int>(req->result),
629
                                       wrap_->syscall(),
630
                                       nullptr,
631
                                       req->path,
632
11574
                                       wrap_->data());
633
3858
  Clear();
634
3858
  wrap->Reject(exception);
635
3858
}
636
637
16881
bool FSReqAfterScope::Proceed() {
638
16881
  if (req_->result < 0) {
639
3858
    Reject(req_);
640
3858
    return false;
641
  }
642
13023
  return true;
643
}
644
645
4887
void AfterNoArgs(uv_fs_t* req) {
646
4887
  FSReqBase* req_wrap = FSReqBase::from_req(req);
647
9772
  FSReqAfterScope after(req_wrap, req);
648
649
4887
  if (after.Proceed())
650
9568
    req_wrap->Resolve(Undefined(req_wrap->env()->isolate()));
651
4885
}
652
653
5128
void AfterStat(uv_fs_t* req) {
654
5128
  FSReqBase* req_wrap = FSReqBase::from_req(req);
655
10256
  FSReqAfterScope after(req_wrap, req);
656
657
5128
  if (after.Proceed()) {
658
1561
    req_wrap->ResolveStat(&req->statbuf);
659
  }
660
5128
}
661
662
5994
void AfterInteger(uv_fs_t* req) {
663
5994
  FSReqBase* req_wrap = FSReqBase::from_req(req);
664
11988
  FSReqAfterScope after(req_wrap, req);
665
666
5994
  int result = static_cast<int>(req->result);
667

5994
  if (result >= 0 && req_wrap->is_plain_open())
668
2622
    req_wrap->env()->AddUnmanagedFd(result);
669
670
5994
  if (after.Proceed())
671
11638
    req_wrap->Resolve(Integer::New(req_wrap->env()->isolate(), result));
672
5994
}
673
674
124
void AfterOpenFileHandle(uv_fs_t* req) {
675
124
  FSReqBase* req_wrap = FSReqBase::from_req(req);
676
248
  FSReqAfterScope after(req_wrap, req);
677
678
124
  if (after.Proceed()) {
679
230
    FileHandle* fd = FileHandle::New(req_wrap->binding_data(),
680
230
                                     static_cast<int>(req->result));
681
115
    if (fd == nullptr) return;
682
230
    req_wrap->Resolve(fd->object());
683
  }
684
}
685
686
// Reverse the logic applied by path.toNamespacedPath() to create a
687
// namespace-prefixed path.
688
244
void FromNamespacedPath(std::string* path) {
689
#ifdef _WIN32
690
  if (path->compare(0, 8, "\\\\?\\UNC\\", 8) == 0) {
691
    *path = path->substr(8);
692
    path->insert(0, "\\\\");
693
  } else if (path->compare(0, 4, "\\\\?\\", 4) == 0) {
694
    *path = path->substr(4);
695
  }
696
#endif
697
244
}
698
699
588
void AfterMkdirp(uv_fs_t* req) {
700
588
  FSReqBase* req_wrap = FSReqBase::from_req(req);
701
1176
  FSReqAfterScope after(req_wrap, req);
702
703
  MaybeLocal<Value> path;
704
  Local<Value> error;
705
706
588
  if (after.Proceed()) {
707
588
    if (!req_wrap->continuation_data()->first_path().empty()) {
708
488
      std::string first_path(req_wrap->continuation_data()->first_path());
709
244
      FromNamespacedPath(&first_path);
710
      path = StringBytes::Encode(req_wrap->env()->isolate(), first_path.c_str(),
711
                                 req_wrap->encoding(),
712
244
                                 &error);
713
244
      if (path.IsEmpty())
714
        req_wrap->Reject(error);
715
      else
716
488
        req_wrap->Resolve(path.ToLocalChecked());
717
    } else {
718
688
      req_wrap->Resolve(Undefined(req_wrap->env()->isolate()));
719
    }
720
  }
721
588
}
722
723
void AfterStringPath(uv_fs_t* req) {
724
  FSReqBase* req_wrap = FSReqBase::from_req(req);
725
  FSReqAfterScope after(req_wrap, req);
726
727
  MaybeLocal<Value> link;
728
  Local<Value> error;
729
730
  if (after.Proceed()) {
731
    link = StringBytes::Encode(req_wrap->env()->isolate(),
732
                               req->path,
733
                               req_wrap->encoding(),
734
                               &error);
735
    if (link.IsEmpty())
736
      req_wrap->Reject(error);
737
    else
738
      req_wrap->Resolve(link.ToLocalChecked());
739
  }
740
}
741
742
void AfterStringPtr(uv_fs_t* req) {
743
  FSReqBase* req_wrap = FSReqBase::from_req(req);
744
  FSReqAfterScope after(req_wrap, req);
745
746
  MaybeLocal<Value> link;
747
  Local<Value> error;
748
749
  if (after.Proceed()) {
750
    link = StringBytes::Encode(req_wrap->env()->isolate(),
751
                               static_cast<const char*>(req->ptr),
752
                               req_wrap->encoding(),
753
                               &error);
754
    if (link.IsEmpty())
755
      req_wrap->Reject(error);
756
    else
757
      req_wrap->Resolve(link.ToLocalChecked());
758
  }
759
}
760
761
9
void AfterScanDir(uv_fs_t* req) {
762
9
  FSReqBase* req_wrap = FSReqBase::from_req(req);
763
14
  FSReqAfterScope after(req_wrap, req);
764
765
9
  if (!after.Proceed()) {
766
4
    return;
767
  }
768
5
  Environment* env = req_wrap->env();
769
  Local<Value> error;
770
  int r;
771
10
  std::vector<Local<Value>> name_v;
772
773
  for (;;) {
774
    uv_dirent_t ent;
775
776
109
    r = uv_fs_scandir_next(req, &ent);
777
109
    if (r == UV_EOF)
778
5
      break;
779
104
    if (r != 0) {
780
      return req_wrap->Reject(UVException(
781
          env->isolate(), r, nullptr, req_wrap->syscall(), req->path));
782
    }
783
784
    MaybeLocal<Value> filename =
785
      StringBytes::Encode(env->isolate(),
786
          ent.name,
787
          req_wrap->encoding(),
788
104
          &error);
789
104
    if (filename.IsEmpty())
790
      return req_wrap->Reject(error);
791
792
104
    name_v.push_back(filename.ToLocalChecked());
793
104
  }
794
795
10
  req_wrap->Resolve(Array::New(env->isolate(), name_v.data(), name_v.size()));
796
}
797
798
151
void AfterScanDirWithTypes(uv_fs_t* req) {
799
151
  FSReqBase* req_wrap = FSReqBase::from_req(req);
800
302
  FSReqAfterScope after(req_wrap, req);
801
802
151
  if (!after.Proceed()) {
803
    return;
804
  }
805
806
151
  Environment* env = req_wrap->env();
807
151
  Isolate* isolate = env->isolate();
808
  Local<Value> error;
809
  int r;
810
811
302
  std::vector<Local<Value>> name_v;
812
302
  std::vector<Local<Value>> type_v;
813
814
  for (;;) {
815
    uv_dirent_t ent;
816
817
151
    r = uv_fs_scandir_next(req, &ent);
818
151
    if (r == UV_EOF)
819
151
      break;
820
    if (r != 0) {
821
      return req_wrap->Reject(
822
          UVException(isolate, r, nullptr, req_wrap->syscall(), req->path));
823
    }
824
825
    MaybeLocal<Value> filename =
826
      StringBytes::Encode(isolate,
827
          ent.name,
828
          req_wrap->encoding(),
829
          &error);
830
    if (filename.IsEmpty())
831
      return req_wrap->Reject(error);
832
833
    name_v.push_back(filename.ToLocalChecked());
834
    type_v.emplace_back(Integer::New(isolate, ent.type));
835
  }
836
837
  Local<Value> result[] = {
838
    Array::New(isolate, name_v.data(), name_v.size()),
839
    Array::New(isolate, type_v.data(), type_v.size())
840
453
  };
841
302
  req_wrap->Resolve(Array::New(isolate, result, arraysize(result)));
842
}
843
844
void Access(const FunctionCallbackInfo<Value>& args) {
845
  Environment* env = Environment::GetCurrent(args);
846
  Isolate* isolate = env->isolate();
847
  HandleScope scope(isolate);
848
849
  const int argc = args.Length();
850
  CHECK_GE(argc, 2);
851
852
  CHECK(args[1]->IsInt32());
853
  int mode = args[1].As<Int32>()->Value();
854
855
  BufferValue path(isolate, args[0]);
856
  CHECK_NOT_NULL(*path);
857
858
  FSReqBase* req_wrap_async = GetReqWrap(args, 2);
859
  if (req_wrap_async != nullptr) {  // access(path, mode, req)
860
    AsyncCall(env, req_wrap_async, args, "access", UTF8, AfterNoArgs,
861
              uv_fs_access, *path, mode);
862
  } else {  // access(path, mode, undefined, ctx)
863
    CHECK_EQ(argc, 4);
864
    FSReqWrapSync req_wrap_sync;
865
    FS_SYNC_TRACE_BEGIN(access);
866
    SyncCall(env, args[3], &req_wrap_sync, "access", uv_fs_access, *path, mode);
867
    FS_SYNC_TRACE_END(access);
868
  }
869
}
870
871
872
16606
void Close(const FunctionCallbackInfo<Value>& args) {
873
16606
  Environment* env = Environment::GetCurrent(args);
874
875
16606
  const int argc = args.Length();
876
16606
  CHECK_GE(argc, 2);
877
878
33212
  CHECK(args[0]->IsInt32());
879
49818
  int fd = args[0].As<Int32>()->Value();
880
16606
  env->RemoveUnmanagedFd(fd);
881
882
16606
  FSReqBase* req_wrap_async = GetReqWrap(args, 1);
883
16606
  if (req_wrap_async != nullptr) {  // close(fd, req)
884
    AsyncCall(env, req_wrap_async, args, "close", UTF8, AfterNoArgs,
885
2622
              uv_fs_close, fd);
886
  } else {  // close(fd, undefined, ctx)
887
13984
    CHECK_EQ(argc, 3);
888
27968
    FSReqWrapSync req_wrap_sync;
889
13984
    FS_SYNC_TRACE_BEGIN(close);
890
13984
    SyncCall(env, args[2], &req_wrap_sync, "close", uv_fs_close, fd);
891
13984
    FS_SYNC_TRACE_END(close);
892
  }
893
16606
}
894
895
896
// Used to speed up module loading. Returns an array [string, boolean]
897
6868
static void InternalModuleReadJSON(const FunctionCallbackInfo<Value>& args) {
898
6868
  Environment* env = Environment::GetCurrent(args);
899
6868
  Isolate* isolate = env->isolate();
900
6868
  uv_loop_t* loop = env->event_loop();
901
902
20604
  CHECK(args[0]->IsString());
903
11702
  node::Utf8Value path(isolate, args[0]);
904
905
6868
  if (strlen(*path) != path.length()) {
906
    args.GetReturnValue().Set(Array::New(isolate));
907
    return;  // Contains a nul byte.
908
  }
909
  uv_fs_t open_req;
910
6868
  const int fd = uv_fs_open(loop, &open_req, *path, O_RDONLY, 0, nullptr);
911
6868
  uv_fs_req_cleanup(&open_req);
912
913
6868
  if (fd < 0) {
914
6102
    args.GetReturnValue().Set(Array::New(isolate));
915
2034
    return;
916
  }
917
918
4834
  auto defer_close = OnScopeLeave([fd, loop]() {
919
    uv_fs_t close_req;
920
4834
    CHECK_EQ(0, uv_fs_close(loop, &close_req, fd, nullptr));
921
4834
    uv_fs_req_cleanup(&close_req);
922
14502
  });
923
924
4834
  const size_t kBlockSize = 32 << 10;
925
9668
  std::vector<char> chars;
926
4834
  int64_t offset = 0;
927
  ssize_t numchars;
928
  do {
929
4834
    const size_t start = chars.size();
930
4834
    chars.resize(start + kBlockSize);
931
932
    uv_buf_t buf;
933
4834
    buf.base = &chars[start];
934
4834
    buf.len = kBlockSize;
935
936
    uv_fs_t read_req;
937
4834
    numchars = uv_fs_read(loop, &read_req, fd, &buf, 1, offset, nullptr);
938
4834
    uv_fs_req_cleanup(&read_req);
939
940
4834
    if (numchars < 0) {
941
      args.GetReturnValue().Set(Array::New(isolate));
942
      return;
943
    }
944
4834
    offset += numchars;
945
4834
  } while (static_cast<size_t>(numchars) == kBlockSize);
946
947
4834
  size_t start = 0;
948

4834
  if (offset >= 3 && 0 == memcmp(&chars[0], "\xEF\xBB\xBF", 3)) {
949
    start = 3;  // Skip UTF-8 BOM.
950
  }
951
952
4834
  const size_t size = offset - start;
953
4834
  char* p = &chars[start];
954
4834
  char* pe = &chars[size];
955
  char* pos[2];
956
4834
  char** ppos = &pos[0];
957
958
143346
  while (p < pe) {
959
74090
    char c = *p++;
960

74090
    if (c == '\\' && p < pe && *p == '"') p++;
961
74090
    if (c != '"') continue;
962
11220
    *ppos++ = p;
963
11220
    if (ppos < &pos[2]) continue;
964
5610
    ppos = &pos[0];
965
966
5610
    char* s = &pos[0][0];
967
5610
    char* se = &pos[1][-1];  // Exclude quote.
968
5610
    size_t n = se - s;
969
970
5610
    if (n == 4) {
971
4834
      if (0 == memcmp(s, "main", 4)) break;
972
4834
      if (0 == memcmp(s, "name", 4)) break;
973
1
      if (0 == memcmp(s, "type", 4)) break;
974
776
    } else if (n == 7) {
975
2
      if (0 == memcmp(s, "exports", 7)) break;
976
2
      if (0 == memcmp(s, "imports", 7)) break;
977
    }
978
  }
979
980
981
  Local<Value> return_value[] = {
982
9668
    String::NewFromUtf8(isolate,
983
4834
                        &chars[start],
984
                        v8::NewStringType::kNormal,
985
4834
                        size).ToLocalChecked(),
986
    Boolean::New(isolate, p < pe ? true : false)
987
14502
  };
988
14502
  args.GetReturnValue().Set(
989
    Array::New(isolate, return_value, arraysize(return_value)));
990
}
991
992
// Used to speed up module loading.  Returns 0 if the path refers to
993
// a file, 1 when it's a directory or < 0 on error (usually -ENOENT.)
994
// The speedup comes from not creating thousands of Stat and Error objects.
995
72525
static void InternalModuleStat(const FunctionCallbackInfo<Value>& args) {
996
72525
  Environment* env = Environment::GetCurrent(args);
997
998
217575
  CHECK(args[0]->IsString());
999
145050
  node::Utf8Value path(env->isolate(), args[0]);
1000
1001
  uv_fs_t req;
1002
72525
  int rc = uv_fs_stat(env->event_loop(), &req, *path, nullptr);
1003
72525
  if (rc == 0) {
1004
34321
    const uv_stat_t* const s = static_cast<const uv_stat_t*>(req.ptr);
1005
34321
    rc = !!(s->st_mode & S_IFDIR);
1006
  }
1007
72525
  uv_fs_req_cleanup(&req);
1008
1009
145050
  args.GetReturnValue().Set(rc);
1010
72525
}
1011
1012
2693
static void Stat(const FunctionCallbackInfo<Value>& args) {
1013
2693
  BindingData* binding_data = Environment::GetBindingData<BindingData>(args);
1014
2693
  Environment* env = binding_data->env();
1015
1016
2693
  const int argc = args.Length();
1017
2693
  CHECK_GE(argc, 2);
1018
1019
5364
  BufferValue path(env->isolate(), args[0]);
1020
2693
  CHECK_NOT_NULL(*path);
1021
1022
5386
  bool use_bigint = args[1]->IsTrue();
1023
2693
  FSReqBase* req_wrap_async = GetReqWrap(args, 2, use_bigint);
1024
2693
  if (req_wrap_async != nullptr) {  // stat(path, use_bigint, req)
1025
2439
    AsyncCall(env, req_wrap_async, args, "stat", UTF8, AfterStat,
1026
2439
              uv_fs_stat, *path);
1027
  } else {  // stat(path, use_bigint, undefined, ctx)
1028
254
    CHECK_EQ(argc, 4);
1029
486
    FSReqWrapSync req_wrap_sync;
1030
254
    FS_SYNC_TRACE_BEGIN(stat);
1031
508
    int err = SyncCall(env, args[3], &req_wrap_sync, "stat", uv_fs_stat, *path);
1032
254
    FS_SYNC_TRACE_END(stat);
1033

254
    if (err != 0) {
1034
22
      return;  // error info is in ctx
1035
    }
1036
1037
    Local<Value> arr = FillGlobalStatsArray(binding_data, use_bigint,
1038
232
        static_cast<const uv_stat_t*>(req_wrap_sync.req.ptr));
1039
464
    args.GetReturnValue().Set(arr);
1040
  }
1041
}
1042
1043
23085
static void LStat(const FunctionCallbackInfo<Value>& args) {
1044
23085
  BindingData* binding_data = Environment::GetBindingData<BindingData>(args);
1045
23085
  Environment* env = binding_data->env();
1046
1047
23085
  const int argc = args.Length();
1048
23085
  CHECK_GE(argc, 3);
1049
1050
46170
  BufferValue path(env->isolate(), args[0]);
1051
23085
  CHECK_NOT_NULL(*path);
1052
1053
46170
  bool use_bigint = args[1]->IsTrue();
1054
23085
  FSReqBase* req_wrap_async = GetReqWrap(args, 2, use_bigint);
1055
23085
  if (req_wrap_async != nullptr) {  // lstat(path, use_bigint, req)
1056
2347
    AsyncCall(env, req_wrap_async, args, "lstat", UTF8, AfterStat,
1057
2347
              uv_fs_lstat, *path);
1058
  } else {  // lstat(path, use_bigint, undefined, ctx)
1059
20738
    CHECK_EQ(argc, 4);
1060
41476
    FSReqWrapSync req_wrap_sync;
1061
20738
    FS_SYNC_TRACE_BEGIN(lstat);
1062
20738
    int err = SyncCall(env, args[3], &req_wrap_sync, "lstat", uv_fs_lstat,
1063
20738
                       *path);
1064

20738
    FS_SYNC_TRACE_END(lstat);
1065
20738
    if (err != 0) {
1066
      return;  // error info is in ctx
1067
    }
1068
1069
    Local<Value> arr = FillGlobalStatsArray(binding_data, use_bigint,
1070
20738
        static_cast<const uv_stat_t*>(req_wrap_sync.req.ptr));
1071
41476
    args.GetReturnValue().Set(arr);
1072
  }
1073
}
1074
1075
14183
static void FStat(const FunctionCallbackInfo<Value>& args) {
1076
14183
  BindingData* binding_data = Environment::GetBindingData<BindingData>(args);
1077
14183
  Environment* env = binding_data->env();
1078
1079
14183
  const int argc = args.Length();
1080
14183
  CHECK_GE(argc, 2);
1081
1082
28366
  CHECK(args[0]->IsInt32());
1083
42549
  int fd = args[0].As<Int32>()->Value();
1084
1085
28366
  bool use_bigint = args[1]->IsTrue();
1086
14183
  FSReqBase* req_wrap_async = GetReqWrap(args, 2, use_bigint);
1087
14183
  if (req_wrap_async != nullptr) {  // fstat(fd, use_bigint, req)
1088
    AsyncCall(env, req_wrap_async, args, "fstat", UTF8, AfterStat,
1089
342
              uv_fs_fstat, fd);
1090
  } else {  // fstat(fd, use_bigint, undefined, ctx)
1091
13841
    CHECK_EQ(argc, 4);
1092
27682
    FSReqWrapSync req_wrap_sync;
1093
13841
    FS_SYNC_TRACE_BEGIN(fstat);
1094
13841
    int err = SyncCall(env, args[3], &req_wrap_sync, "fstat", uv_fs_fstat, fd);
1095
13841
    FS_SYNC_TRACE_END(fstat);
1096

13841
    if (err != 0) {
1097
      return;  // error info is in ctx
1098
    }
1099
1100
    Local<Value> arr = FillGlobalStatsArray(binding_data, use_bigint,
1101
13841
        static_cast<const uv_stat_t*>(req_wrap_sync.req.ptr));
1102
27682
    args.GetReturnValue().Set(arr);
1103
  }
1104
}
1105
1106
5
static void Symlink(const FunctionCallbackInfo<Value>& args) {
1107
5
  Environment* env = Environment::GetCurrent(args);
1108
5
  Isolate* isolate = env->isolate();
1109
1110
5
  const int argc = args.Length();
1111
5
  CHECK_GE(argc, 4);
1112
1113
10
  BufferValue target(isolate, args[0]);
1114
5
  CHECK_NOT_NULL(*target);
1115
10
  BufferValue path(isolate, args[1]);
1116
5
  CHECK_NOT_NULL(*path);
1117
1118
10
  CHECK(args[2]->IsInt32());
1119
15
  int flags = args[2].As<Int32>()->Value();
1120
1121
5
  FSReqBase* req_wrap_async = GetReqWrap(args, 3);
1122
5
  if (req_wrap_async != nullptr) {  // symlink(target, path, flags, req)
1123
5
    AsyncDestCall(env, req_wrap_async, args, "symlink", *path, path.length(),
1124
5
                  UTF8, AfterNoArgs, uv_fs_symlink, *target, *path, flags);
1125
  } else {  // symlink(target, path, flags, undefinec, ctx)
1126
    CHECK_EQ(argc, 5);
1127
    FSReqWrapSync req_wrap_sync;
1128
    FS_SYNC_TRACE_BEGIN(symlink);
1129
    SyncCall(env, args[4], &req_wrap_sync, "symlink",
1130
             uv_fs_symlink, *target, *path, flags);
1131
    FS_SYNC_TRACE_END(symlink);
1132
  }
1133
5
}
1134
1135
62
static void Link(const FunctionCallbackInfo<Value>& args) {
1136
62
  Environment* env = Environment::GetCurrent(args);
1137
62
  Isolate* isolate = env->isolate();
1138
1139
62
  const int argc = args.Length();
1140
62
  CHECK_GE(argc, 3);
1141
1142
124
  BufferValue src(isolate, args[0]);
1143
62
  CHECK_NOT_NULL(*src);
1144
1145
124
  BufferValue dest(isolate, args[1]);
1146
62
  CHECK_NOT_NULL(*dest);
1147
1148
62
  FSReqBase* req_wrap_async = GetReqWrap(args, 2);
1149
62
  if (req_wrap_async != nullptr) {  // link(src, dest, req)
1150
62
    AsyncDestCall(env, req_wrap_async, args, "link", *dest, dest.length(), UTF8,
1151
62
                  AfterNoArgs, uv_fs_link, *src, *dest);
1152
  } else {  // link(src, dest)
1153
    CHECK_EQ(argc, 4);
1154
    FSReqWrapSync req_wrap_sync;
1155
    FS_SYNC_TRACE_BEGIN(link);
1156
    SyncCall(env, args[3], &req_wrap_sync, "link",
1157
             uv_fs_link, *src, *dest);
1158
    FS_SYNC_TRACE_END(link);
1159
  }
1160
62
}
1161
1162
1
static void ReadLink(const FunctionCallbackInfo<Value>& args) {
1163
1
  Environment* env = Environment::GetCurrent(args);
1164
1
  Isolate* isolate = env->isolate();
1165
1166
1
  const int argc = args.Length();
1167
1
  CHECK_GE(argc, 3);
1168
1169
2
  BufferValue path(isolate, args[0]);
1170
1
  CHECK_NOT_NULL(*path);
1171
1172
1
  const enum encoding encoding = ParseEncoding(isolate, args[1], UTF8);
1173
1174
1
  FSReqBase* req_wrap_async = GetReqWrap(args, 2);
1175
1
  if (req_wrap_async != nullptr) {  // readlink(path, encoding, req)
1176
    AsyncCall(env, req_wrap_async, args, "readlink", encoding, AfterStringPtr,
1177
              uv_fs_readlink, *path);
1178
  } else {
1179
1
    CHECK_EQ(argc, 4);
1180
2
    FSReqWrapSync req_wrap_sync;
1181
1
    FS_SYNC_TRACE_BEGIN(readlink);
1182
1
    int err = SyncCall(env, args[3], &req_wrap_sync, "readlink",
1183
1
                       uv_fs_readlink, *path);
1184

1
    FS_SYNC_TRACE_END(readlink);
1185
1
    if (err < 0) {
1186
      return;  // syscall failed, no need to continue, error info is in ctx
1187
    }
1188
1
    const char* link_path = static_cast<const char*>(req_wrap_sync.req.ptr);
1189
1190
    Local<Value> error;
1191
    MaybeLocal<Value> rc = StringBytes::Encode(isolate,
1192
                                               link_path,
1193
                                               encoding,
1194
1
                                               &error);
1195
1
    if (rc.IsEmpty()) {
1196
      Local<Object> ctx = args[3].As<Object>();
1197
      ctx->Set(env->context(), env->error_string(), error).Check();
1198
      return;
1199
    }
1200
1201
2
    args.GetReturnValue().Set(rc.ToLocalChecked());
1202
  }
1203
}
1204
1205
static void Rename(const FunctionCallbackInfo<Value>& args) {
1206
  Environment* env = Environment::GetCurrent(args);
1207
  Isolate* isolate = env->isolate();
1208
1209
  const int argc = args.Length();
1210
  CHECK_GE(argc, 3);
1211
1212
  BufferValue old_path(isolate, args[0]);
1213
  CHECK_NOT_NULL(*old_path);
1214
  BufferValue new_path(isolate, args[1]);
1215
  CHECK_NOT_NULL(*new_path);
1216
1217
  FSReqBase* req_wrap_async = GetReqWrap(args, 2);
1218
  if (req_wrap_async != nullptr) {
1219
    AsyncDestCall(env, req_wrap_async, args, "rename", *new_path,
1220
                  new_path.length(), UTF8, AfterNoArgs, uv_fs_rename,
1221
                  *old_path, *new_path);
1222
  } else {
1223
    CHECK_EQ(argc, 4);
1224
    FSReqWrapSync req_wrap_sync;
1225
    FS_SYNC_TRACE_BEGIN(rename);
1226
    SyncCall(env, args[3], &req_wrap_sync, "rename", uv_fs_rename,
1227
             *old_path, *new_path);
1228
    FS_SYNC_TRACE_END(rename);
1229
  }
1230
}
1231
1232
static void FTruncate(const FunctionCallbackInfo<Value>& args) {
1233
  Environment* env = Environment::GetCurrent(args);
1234
1235
  const int argc = args.Length();
1236
  CHECK_GE(argc, 3);
1237
1238
  CHECK(args[0]->IsInt32());
1239
  const int fd = args[0].As<Int32>()->Value();
1240
1241
  CHECK(IsSafeJsInt(args[1]));
1242
  const int64_t len = args[1].As<Integer>()->Value();
1243
1244
  FSReqBase* req_wrap_async = GetReqWrap(args, 2);
1245
  if (req_wrap_async != nullptr) {
1246
    AsyncCall(env, req_wrap_async, args, "ftruncate", UTF8, AfterNoArgs,
1247
              uv_fs_ftruncate, fd, len);
1248
  } else {
1249
    CHECK_EQ(argc, 4);
1250
    FSReqWrapSync req_wrap_sync;
1251
    FS_SYNC_TRACE_BEGIN(ftruncate);
1252
    SyncCall(env, args[3], &req_wrap_sync, "ftruncate", uv_fs_ftruncate, fd,
1253
             len);
1254
    FS_SYNC_TRACE_END(ftruncate);
1255
  }
1256
}
1257
1258
static void Fdatasync(const FunctionCallbackInfo<Value>& args) {
1259
  Environment* env = Environment::GetCurrent(args);
1260
1261
  const int argc = args.Length();
1262
  CHECK_GE(argc, 2);
1263
1264
  CHECK(args[0]->IsInt32());
1265
  const int fd = args[0].As<Int32>()->Value();
1266
1267
  FSReqBase* req_wrap_async = GetReqWrap(args, 1);
1268
  if (req_wrap_async != nullptr) {
1269
    AsyncCall(env, req_wrap_async, args, "fdatasync", UTF8, AfterNoArgs,
1270
              uv_fs_fdatasync, fd);
1271
  } else {
1272
    CHECK_EQ(argc, 3);
1273
    FSReqWrapSync req_wrap_sync;
1274
    FS_SYNC_TRACE_BEGIN(fdatasync);
1275
    SyncCall(env, args[2], &req_wrap_sync, "fdatasync", uv_fs_fdatasync, fd);
1276
    FS_SYNC_TRACE_END(fdatasync);
1277
  }
1278
}
1279
1280
static void Fsync(const FunctionCallbackInfo<Value>& args) {
1281
  Environment* env = Environment::GetCurrent(args);
1282
1283
  const int argc = args.Length();
1284
  CHECK_GE(argc, 2);
1285
1286
  CHECK(args[0]->IsInt32());
1287
  const int fd = args[0].As<Int32>()->Value();
1288
1289
  FSReqBase* req_wrap_async = GetReqWrap(args, 1);
1290
  if (req_wrap_async != nullptr) {
1291
    AsyncCall(env, req_wrap_async, args, "fsync", UTF8, AfterNoArgs,
1292
              uv_fs_fsync, fd);
1293
  } else {
1294
    CHECK_EQ(argc, 3);
1295
    FSReqWrapSync req_wrap_sync;
1296
    FS_SYNC_TRACE_BEGIN(fsync);
1297
    SyncCall(env, args[2], &req_wrap_sync, "fsync", uv_fs_fsync, fd);
1298
    FS_SYNC_TRACE_END(fsync);
1299
  }
1300
}
1301
1302
62
static void Unlink(const FunctionCallbackInfo<Value>& args) {
1303
62
  Environment* env = Environment::GetCurrent(args);
1304
1305
62
  const int argc = args.Length();
1306
62
  CHECK_GE(argc, 2);
1307
1308
124
  BufferValue path(env->isolate(), args[0]);
1309
62
  CHECK_NOT_NULL(*path);
1310
1311
62
  FSReqBase* req_wrap_async = GetReqWrap(args, 1);
1312
62
  if (req_wrap_async != nullptr) {
1313
62
    AsyncCall(env, req_wrap_async, args, "unlink", UTF8, AfterNoArgs,
1314
62
              uv_fs_unlink, *path);
1315
  } else {
1316
    CHECK_EQ(argc, 3);
1317
    FSReqWrapSync req_wrap_sync;
1318
    FS_SYNC_TRACE_BEGIN(unlink);
1319
    SyncCall(env, args[2], &req_wrap_sync, "unlink", uv_fs_unlink, *path);
1320
    FS_SYNC_TRACE_END(unlink);
1321
  }
1322
62
}
1323
1324
static void RMDir(const FunctionCallbackInfo<Value>& args) {
1325
  Environment* env = Environment::GetCurrent(args);
1326
1327
  const int argc = args.Length();
1328
  CHECK_GE(argc, 2);
1329
1330
  BufferValue path(env->isolate(), args[0]);
1331
  CHECK_NOT_NULL(*path);
1332
1333
  FSReqBase* req_wrap_async = GetReqWrap(args, 1);  // rmdir(path, req)
1334
  if (req_wrap_async != nullptr) {
1335
    AsyncCall(env, req_wrap_async, args, "rmdir", UTF8, AfterNoArgs,
1336
              uv_fs_rmdir, *path);
1337
  } else {  // rmdir(path, undefined, ctx)
1338
    CHECK_EQ(argc, 3);
1339
    FSReqWrapSync req_wrap_sync;
1340
    FS_SYNC_TRACE_BEGIN(rmdir);
1341
    SyncCall(env, args[2], &req_wrap_sync, "rmdir",
1342
             uv_fs_rmdir, *path);
1343
    FS_SYNC_TRACE_END(rmdir);
1344
  }
1345
}
1346
1347
118
int MKDirpSync(uv_loop_t* loop,
1348
               uv_fs_t* req,
1349
               const std::string& path,
1350
               int mode,
1351
               uv_fs_cb cb) {
1352
118
  FSReqWrapSync* req_wrap = ContainerOf(&FSReqWrapSync::req, req);
1353
1354
  // on the first iteration of algorithm, stash state information.
1355
118
  if (req_wrap->continuation_data() == nullptr) {
1356
    req_wrap->set_continuation_data(
1357
118
        std::make_unique<FSContinuationData>(req, mode, cb));
1358
118
    req_wrap->continuation_data()->PushPath(std::move(path));
1359
  }
1360
1361
358
  while (req_wrap->continuation_data()->paths().size() > 0) {
1362
242
    std::string next_path = req_wrap->continuation_data()->PopPath();
1363
122
    int err = uv_fs_mkdir(loop, req, next_path.c_str(), mode, nullptr);
1364
    while (true) {
1365

122
      switch (err) {
1366
        // Note: uv_fs_req_cleanup in terminal paths will be called by
1367
        // ~FSReqWrapSync():
1368
        case 0:
1369
4
          req_wrap->continuation_data()->MaybeSetFirstPath(next_path);
1370
4
          if (req_wrap->continuation_data()->paths().size() == 0) {
1371
2
            return 0;
1372
          }
1373
2
          break;
1374
        case UV_EACCES:
1375
        case UV_ENOTDIR:
1376
        case UV_EPERM: {
1377
          return err;
1378
        }
1379
        case UV_ENOENT: {
1380
          std::string dirname = next_path.substr(0,
1381
2
                                        next_path.find_last_of(kPathSeparator));
1382
2
          if (dirname != next_path) {
1383
2
            req_wrap->continuation_data()->PushPath(std::move(next_path));
1384
2
            req_wrap->continuation_data()->PushPath(std::move(dirname));
1385
          } else if (req_wrap->continuation_data()->paths().size() == 0) {
1386
            err = UV_EEXIST;
1387
            continue;
1388
          }
1389
2
          break;
1390
        }
1391
        default:
1392
116
          uv_fs_req_cleanup(req);
1393
116
          int orig_err = err;
1394
116
          err = uv_fs_stat(loop, req, next_path.c_str(), nullptr);
1395

116
          if (err == 0 && !S_ISDIR(req->statbuf.st_mode)) {
1396
            uv_fs_req_cleanup(req);
1397
            if (orig_err == UV_EEXIST &&
1398
              req_wrap->continuation_data()->paths().size() > 0) {
1399
              return UV_ENOTDIR;
1400
            }
1401
            return UV_EEXIST;
1402
          }
1403
116
          if (err < 0) return err;
1404
116
          break;
1405
      }
1406
120
      break;
1407
    }
1408
120
    uv_fs_req_cleanup(req);
1409
  }
1410
1411
116
  return 0;
1412
}
1413
1414
774
int MKDirpAsync(uv_loop_t* loop,
1415
                uv_fs_t* req,
1416
                const char* path,
1417
                int mode,
1418
                uv_fs_cb cb) {
1419
774
  FSReqBase* req_wrap = FSReqBase::from_req(req);
1420
  // on the first iteration of algorithm, stash state information.
1421
774
  if (req_wrap->continuation_data() == nullptr) {
1422
    req_wrap->set_continuation_data(
1423
588
        std::make_unique<FSContinuationData>(req, mode, cb));
1424
588
    req_wrap->continuation_data()->PushPath(std::move(path));
1425
  }
1426
1427
  // on each iteration of algorithm, mkdir directory on top of stack.
1428
1548
  std::string next_path = req_wrap->continuation_data()->PopPath();
1429
774
  int err = uv_fs_mkdir(loop, req, next_path.c_str(), mode,
1430
2322
                        uv_fs_callback_t{[](uv_fs_t* req) {
1431
774
    FSReqBase* req_wrap = FSReqBase::from_req(req);
1432
774
    Environment* env = req_wrap->env();
1433
774
    uv_loop_t* loop = env->event_loop();
1434
1548
    std::string path = req->path;
1435
774
    int err = static_cast<int>(req->result);
1436
1437
    while (true) {
1438

774
      switch (err) {
1439
        // Note: uv_fs_req_cleanup in terminal paths will be called by
1440
        // FSReqAfterScope::~FSReqAfterScope()
1441
        case 0: {
1442
249
          if (req_wrap->continuation_data()->paths().size() == 0) {
1443
244
            req_wrap->continuation_data()->MaybeSetFirstPath(path);
1444
244
            req_wrap->continuation_data()->Done(0);
1445
          } else {
1446
5
            req_wrap->continuation_data()->MaybeSetFirstPath(path);
1447
5
            uv_fs_req_cleanup(req);
1448
5
            MKDirpAsync(loop, req, path.c_str(),
1449
5
                        req_wrap->continuation_data()->mode(), nullptr);
1450
          }
1451
249
          break;
1452
        }
1453
        case UV_EACCES:
1454
        case UV_ENOTDIR:
1455
        case UV_EPERM: {
1456
          req_wrap->continuation_data()->Done(err);
1457
          break;
1458
        }
1459
        case UV_ENOENT: {
1460
          std::string dirname = path.substr(0,
1461
93
                                            path.find_last_of(kPathSeparator));
1462
93
          if (dirname != path) {
1463
93
            req_wrap->continuation_data()->PushPath(std::move(path));
1464
93
            req_wrap->continuation_data()->PushPath(std::move(dirname));
1465
          } else if (req_wrap->continuation_data()->paths().size() == 0) {
1466
            err = UV_EEXIST;
1467
            continue;
1468
          }
1469
93
          uv_fs_req_cleanup(req);
1470
93
          MKDirpAsync(loop, req, path.c_str(),
1471
93
                      req_wrap->continuation_data()->mode(), nullptr);
1472
93
          break;
1473
        }
1474
        default:
1475
432
          uv_fs_req_cleanup(req);
1476
          // Stash err for use in the callback.
1477
432
          req->data = reinterpret_cast<void*>(static_cast<intptr_t>(err));
1478
432
          int err = uv_fs_stat(loop, req, path.c_str(),
1479
1296
                               uv_fs_callback_t{[](uv_fs_t* req) {
1480
432
            FSReqBase* req_wrap = FSReqBase::from_req(req);
1481
432
            int err = static_cast<int>(req->result);
1482

864
            if (reinterpret_cast<intptr_t>(req->data) == UV_EEXIST &&
1483
432
                  req_wrap->continuation_data()->paths().size() > 0) {
1484

88
              if (err == 0 && S_ISDIR(req->statbuf.st_mode)) {
1485
88
                Environment* env = req_wrap->env();
1486
88
                uv_loop_t* loop = env->event_loop();
1487
176
                std::string path = req->path;
1488
88
                uv_fs_req_cleanup(req);
1489
88
                MKDirpAsync(loop, req, path.c_str(),
1490
88
                            req_wrap->continuation_data()->mode(), nullptr);
1491
88
                return;
1492
              }
1493
              err = UV_ENOTDIR;
1494
            }
1495
            // verify that the path pointed to is actually a directory.
1496

344
            if (err == 0 && !S_ISDIR(req->statbuf.st_mode)) err = UV_EEXIST;
1497
344
            req_wrap->continuation_data()->Done(err);
1498
1296
          }});
1499
432
          if (err < 0) req_wrap->continuation_data()->Done(err);
1500
432
          break;
1501
      }
1502
774
      break;
1503
    }
1504
3096
  }});
1505
1506
1548
  return err;
1507
}
1508
1509
int CallMKDirpSync(Environment* env, const FunctionCallbackInfo<Value>& args,
1510
                   FSReqWrapSync* req_wrap, const char* path, int mode) {
1511
  env->PrintSyncTrace();
1512
  int err = MKDirpSync(env->event_loop(), &req_wrap->req, path, mode,
1513
                       nullptr);
1514
  if (err < 0) {
1515
    v8::Local<v8::Context> context = env->context();
1516
    v8::Local<v8::Object> ctx_obj = args[4].As<v8::Object>();
1517
    v8::Isolate* isolate = env->isolate();
1518
    ctx_obj->Set(context,
1519
                 env->errno_string(),
1520
                 v8::Integer::New(isolate, err)).Check();
1521
    ctx_obj->Set(context,
1522
                 env->syscall_string(),
1523
                 OneByteString(isolate, "mkdir")).Check();
1524
  }
1525
  return err;
1526
}
1527
1528
934
static void MKDir(const FunctionCallbackInfo<Value>& args) {
1529
934
  Environment* env = Environment::GetCurrent(args);
1530
1531
934
  const int argc = args.Length();
1532
934
  CHECK_GE(argc, 4);
1533
1534
1868
  BufferValue path(env->isolate(), args[0]);
1535
934
  CHECK_NOT_NULL(*path);
1536
1537
1868
  CHECK(args[1]->IsInt32());
1538
2802
  const int mode = args[1].As<Int32>()->Value();
1539
1540
1868
  CHECK(args[2]->IsBoolean());
1541
1868
  bool mkdirp = args[2]->IsTrue();
1542
1543
934
  FSReqBase* req_wrap_async = GetReqWrap(args, 3);
1544
934
  if (req_wrap_async != nullptr) {  // mkdir(path, mode, req)
1545

791
    AsyncCall(env, req_wrap_async, args, "mkdir", UTF8,
1546
              mkdirp ? AfterMkdirp : AfterNoArgs,
1547
791
              mkdirp ? MKDirpAsync : uv_fs_mkdir, *path, mode);
1548
  } else {  // mkdir(path, mode, undefined, ctx)
1549
143
    CHECK_EQ(argc, 5);
1550
286
    FSReqWrapSync req_wrap_sync;
1551
143
    FS_SYNC_TRACE_BEGIN(mkdir);
1552
143
    if (mkdirp) {
1553
      int err = CallMKDirpSync(env, args, &req_wrap_sync, *path, mode);
1554
      if (err == 0 &&
1555
          !req_wrap_sync.continuation_data()->first_path().empty()) {
1556
        Local<Value> error;
1557
        std::string first_path(req_wrap_sync.continuation_data()->first_path());
1558
        FromNamespacedPath(&first_path);
1559
        MaybeLocal<Value> path = StringBytes::Encode(env->isolate(),
1560
                                                     first_path.c_str(),
1561
                                                     UTF8, &error);
1562
        if (path.IsEmpty()) {
1563
          Local<Object> ctx = args[4].As<Object>();
1564
          ctx->Set(env->context(), env->error_string(), error).Check();
1565
          return;
1566
        }
1567
        args.GetReturnValue().Set(path.ToLocalChecked());
1568
      }
1569
    } else {
1570
143
      SyncCall(env, args[4], &req_wrap_sync, "mkdir",
1571
143
               uv_fs_mkdir, *path, mode);
1572
    }
1573
143
    FS_SYNC_TRACE_END(mkdir);
1574
  }
1575
}
1576
1577
static void RealPath(const FunctionCallbackInfo<Value>& args) {
1578
  Environment* env = Environment::GetCurrent(args);
1579
  Isolate* isolate = env->isolate();
1580
1581
  const int argc = args.Length();
1582
  CHECK_GE(argc, 3);
1583
1584
  BufferValue path(isolate, args[0]);
1585
  CHECK_NOT_NULL(*path);
1586
1587
  const enum encoding encoding = ParseEncoding(isolate, args[1], UTF8);
1588
1589
  FSReqBase* req_wrap_async = GetReqWrap(args, 2);
1590
  if (req_wrap_async != nullptr) {  // realpath(path, encoding, req)
1591
    AsyncCall(env, req_wrap_async, args, "realpath", encoding, AfterStringPtr,
1592
              uv_fs_realpath, *path);
1593
  } else {  // realpath(path, encoding, undefined, ctx)
1594
    CHECK_EQ(argc, 4);
1595
    FSReqWrapSync req_wrap_sync;
1596
    FS_SYNC_TRACE_BEGIN(realpath);
1597
    int err = SyncCall(env, args[3], &req_wrap_sync, "realpath",
1598
                       uv_fs_realpath, *path);
1599
    FS_SYNC_TRACE_END(realpath);
1600
    if (err < 0) {
1601
      return;  // syscall failed, no need to continue, error info is in ctx
1602
    }
1603
1604
    const char* link_path = static_cast<const char*>(req_wrap_sync.req.ptr);
1605
1606
    Local<Value> error;
1607
    MaybeLocal<Value> rc = StringBytes::Encode(isolate,
1608
                                               link_path,
1609
                                               encoding,
1610
                                               &error);
1611
    if (rc.IsEmpty()) {
1612
      Local<Object> ctx = args[3].As<Object>();
1613
      ctx->Set(env->context(), env->error_string(), error).Check();
1614
      return;
1615
    }
1616
1617
    args.GetReturnValue().Set(rc.ToLocalChecked());
1618
  }
1619
}
1620
1621
183
static void ReadDir(const FunctionCallbackInfo<Value>& args) {
1622
183
  Environment* env = Environment::GetCurrent(args);
1623
183
  Isolate* isolate = env->isolate();
1624
1625
183
  const int argc = args.Length();
1626
183
  CHECK_GE(argc, 3);
1627
1628
366
  BufferValue path(isolate, args[0]);
1629
183
  CHECK_NOT_NULL(*path);
1630
1631
183
  const enum encoding encoding = ParseEncoding(isolate, args[1], UTF8);
1632
1633
366
  bool with_types = args[2]->IsTrue();
1634
1635
183
  FSReqBase* req_wrap_async = GetReqWrap(args, 3);
1636
183
  if (req_wrap_async != nullptr) {  // readdir(path, encoding, withTypes, req)
1637
160
    if (with_types) {
1638
151
      AsyncCall(env, req_wrap_async, args, "scandir", encoding,
1639
151
                AfterScanDirWithTypes, uv_fs_scandir, *path, 0 /*flags*/);
1640
    } else {
1641
9
      AsyncCall(env, req_wrap_async, args, "scandir", encoding,
1642
9
                AfterScanDir, uv_fs_scandir, *path, 0 /*flags*/);
1643
    }
1644
  } else {  // readdir(path, encoding, withTypes, undefined, ctx)
1645
23
    CHECK_EQ(argc, 5);
1646
46
    FSReqWrapSync req_wrap_sync;
1647
23
    FS_SYNC_TRACE_BEGIN(readdir);
1648
23
    int err = SyncCall(env, args[4], &req_wrap_sync, "scandir",
1649
23
                       uv_fs_scandir, *path, 0 /*flags*/);
1650

23
    FS_SYNC_TRACE_END(readdir);
1651
23
    if (err < 0) {
1652
      return;  // syscall failed, no need to continue, error info is in ctx
1653
    }
1654
1655

23
    CHECK_GE(req_wrap_sync.req.result, 0);
1656
    int r;
1657
46
    std::vector<Local<Value>> name_v;
1658
46
    std::vector<Local<Value>> type_v;
1659
1660
    for (;;) {
1661
      uv_dirent_t ent;
1662
1663
402
      r = uv_fs_scandir_next(&(req_wrap_sync.req), &ent);
1664
402
      if (r == UV_EOF)
1665
23
        break;
1666
379
      if (r != 0) {
1667
        Local<Object> ctx = args[4].As<Object>();
1668
        ctx->Set(env->context(), env->errno_string(),
1669
                 Integer::New(isolate, r)).Check();
1670
        ctx->Set(env->context(), env->syscall_string(),
1671
                 OneByteString(isolate, "readdir")).Check();
1672
        return;
1673
      }
1674
1675
      Local<Value> error;
1676
      MaybeLocal<Value> filename = StringBytes::Encode(isolate,
1677
                                                       ent.name,
1678
                                                       encoding,
1679
379
                                                       &error);
1680
1681
379
      if (filename.IsEmpty()) {
1682
        Local<Object> ctx = args[4].As<Object>();
1683
        ctx->Set(env->context(), env->error_string(), error).Check();
1684
        return;
1685
      }
1686
1687
379
      name_v.push_back(filename.ToLocalChecked());
1688
1689
379
      if (with_types) {
1690
        type_v.emplace_back(Integer::New(isolate, ent.type));
1691
      }
1692
379
    }
1693
1694
1695
23
    Local<Array> names = Array::New(isolate, name_v.data(), name_v.size());
1696
23
    if (with_types) {
1697
      Local<Value> result[] = {
1698
        names,
1699
        Array::New(isolate, type_v.data(), type_v.size())
1700
      };
1701
      args.GetReturnValue().Set(Array::New(isolate, result, arraysize(result)));
1702
    } else {
1703
46
      args.GetReturnValue().Set(names);
1704
    }
1705
  }
1706
}
1707
1708
16781
static void Open(const FunctionCallbackInfo<Value>& args) {
1709
16781
  Environment* env = Environment::GetCurrent(args);
1710
1711
16781
  const int argc = args.Length();
1712
16781
  CHECK_GE(argc, 3);
1713
1714
33562
  BufferValue path(env->isolate(), args[0]);
1715
16781
  CHECK_NOT_NULL(*path);
1716
1717
33562
  CHECK(args[1]->IsInt32());
1718
50343
  const int flags = args[1].As<Int32>()->Value();
1719
1720
33562
  CHECK(args[2]->IsInt32());
1721
50343
  const int mode = args[2].As<Int32>()->Value();
1722
1723
16781
  FSReqBase* req_wrap_async = GetReqWrap(args, 3);
1724
16781
  if (req_wrap_async != nullptr) {  // open(path, flags, mode, req)
1725
2797
    req_wrap_async->set_is_plain_open(true);
1726
2797
    AsyncCall(env, req_wrap_async, args, "open", UTF8, AfterInteger,
1727
2797
              uv_fs_open, *path, flags, mode);
1728
  } else {  // open(path, flags, mode, undefined, ctx)
1729
13984
    CHECK_EQ(argc, 5);
1730
27968
    FSReqWrapSync req_wrap_sync;
1731

13984
    FS_SYNC_TRACE_BEGIN(open);
1732
13984
    int result = SyncCall(env, args[4], &req_wrap_sync, "open",
1733
13984
                          uv_fs_open, *path, flags, mode);
1734
13984
    FS_SYNC_TRACE_END(open);
1735
13984
    if (result >= 0) env->AddUnmanagedFd(result);
1736
27968
    args.GetReturnValue().Set(result);
1737
  }
1738
16781
}
1739
1740
124
static void OpenFileHandle(const FunctionCallbackInfo<Value>& args) {
1741
124
  BindingData* binding_data = Environment::GetBindingData<BindingData>(args);
1742
124
  Environment* env = binding_data->env();
1743
124
  Isolate* isolate = env->isolate();
1744
1745
124
  const int argc = args.Length();
1746
124
  CHECK_GE(argc, 3);
1747
1748
248
  BufferValue path(isolate, args[0]);
1749
124
  CHECK_NOT_NULL(*path);
1750
1751
248
  CHECK(args[1]->IsInt32());
1752
372
  const int flags = args[1].As<Int32>()->Value();
1753
1754
248
  CHECK(args[2]->IsInt32());
1755
372
  const int mode = args[2].As<Int32>()->Value();
1756
1757
124
  FSReqBase* req_wrap_async = GetReqWrap(args, 3);
1758
124
  if (req_wrap_async != nullptr) {  // openFileHandle(path, flags, mode, req)
1759
124
    AsyncCall(env, req_wrap_async, args, "open", UTF8, AfterOpenFileHandle,
1760
124
              uv_fs_open, *path, flags, mode);
1761
  } else {  // openFileHandle(path, flags, mode, undefined, ctx)
1762
    CHECK_EQ(argc, 5);
1763
    FSReqWrapSync req_wrap_sync;
1764
    FS_SYNC_TRACE_BEGIN(open);
1765
    int result = SyncCall(env, args[4], &req_wrap_sync, "open",
1766
                          uv_fs_open, *path, flags, mode);
1767
    FS_SYNC_TRACE_END(open);
1768
    if (result < 0) {
1769
      return;  // syscall failed, no need to continue, error info is in ctx
1770
    }
1771
    FileHandle* fd = FileHandle::New(binding_data, result);
1772
    if (fd == nullptr) return;
1773
    args.GetReturnValue().Set(fd->object());
1774
  }
1775
}
1776
1777
static void CopyFile(const FunctionCallbackInfo<Value>& args) {
1778
  Environment* env = Environment::GetCurrent(args);
1779
  Isolate* isolate = env->isolate();
1780
1781
  const int argc = args.Length();
1782
  CHECK_GE(argc, 3);
1783
1784
  BufferValue src(isolate, args[0]);
1785
  CHECK_NOT_NULL(*src);
1786
1787
  BufferValue dest(isolate, args[1]);
1788
  CHECK_NOT_NULL(*dest);
1789
1790
  CHECK(args[2]->IsInt32());
1791
  const int flags = args[2].As<Int32>()->Value();
1792
1793
  FSReqBase* req_wrap_async = GetReqWrap(args, 3);
1794
  if (req_wrap_async != nullptr) {  // copyFile(src, dest, flags, req)
1795
    AsyncDestCall(env, req_wrap_async, args, "copyfile",
1796
                  *dest, dest.length(), UTF8, AfterNoArgs,
1797
                  uv_fs_copyfile, *src, *dest, flags);
1798
  } else {  // copyFile(src, dest, flags, undefined, ctx)
1799
    CHECK_EQ(argc, 5);
1800
    FSReqWrapSync req_wrap_sync;
1801
    FS_SYNC_TRACE_BEGIN(copyfile);
1802
    SyncCall(env, args[4], &req_wrap_sync, "copyfile",
1803
             uv_fs_copyfile, *src, *dest, flags);
1804
    FS_SYNC_TRACE_END(copyfile);
1805
  }
1806
}
1807
1808
1809
// Wrapper for write(2).
1810
//
1811
// bytesWritten = write(fd, buffer, offset, length, position, callback)
1812
// 0 fd        integer. file descriptor
1813
// 1 buffer    the data to write
1814
// 2 offset    where in the buffer to start from
1815
// 3 length    how much to write
1816
// 4 position  if integer, position to write at in the file.
1817
//             if null, write from the current position
1818
2468
static void WriteBuffer(const FunctionCallbackInfo<Value>& args) {
1819
2468
  Environment* env = Environment::GetCurrent(args);
1820
1821
2468
  const int argc = args.Length();
1822
2468
  CHECK_GE(argc, 4);
1823
1824
4936
  CHECK(args[0]->IsInt32());
1825
7404
  const int fd = args[0].As<Int32>()->Value();
1826
1827
2468
  CHECK(Buffer::HasInstance(args[1]));
1828
4936
  Local<Object> buffer_obj = args[1].As<Object>();
1829
2468
  char* buffer_data = Buffer::Data(buffer_obj);
1830
2468
  size_t buffer_length = Buffer::Length(buffer_obj);
1831
1832
2468
  CHECK(IsSafeJsInt(args[2]));
1833
7404
  const int64_t off_64 = args[2].As<Integer>()->Value();
1834
2468
  CHECK_GE(off_64, 0);
1835
2468
  CHECK_LE(static_cast<uint64_t>(off_64), buffer_length);
1836
2468
  const size_t off = static_cast<size_t>(off_64);
1837
1838
2468
  CHECK(IsSafeJsInt(args[3]));
1839
7404
  const size_t len = static_cast<size_t>(args[3].As<Integer>()->Value());
1840
2468
  CHECK(Buffer::IsWithinBounds(off, len, buffer_length));
1841
2468
  CHECK_LE(len, buffer_length);
1842
2468
  CHECK_GE(off + len, off);
1843
1844
2468
  const int64_t pos = GetOffset(args[4]);
1845
1846
2468
  char* buf = buffer_data + off;
1847
2468
  uv_buf_t uvbuf = uv_buf_init(buf, len);
1848
1849
2468
  FSReqBase* req_wrap_async = GetReqWrap(args, 5);
1850
2468
  if (req_wrap_async != nullptr) {  // write(fd, buffer, off, len, pos, req)
1851
    AsyncCall(env, req_wrap_async, args, "write", UTF8, AfterInteger,
1852
2460
              uv_fs_write, fd, &uvbuf, 1, pos);
1853
  } else {  // write(fd, buffer, off, len, pos, undefined, ctx)
1854
8
    CHECK_EQ(argc, 7);
1855
16
    FSReqWrapSync req_wrap_sync;
1856

8
    FS_SYNC_TRACE_BEGIN(write);
1857
8
    int bytesWritten = SyncCall(env, args[6], &req_wrap_sync, "write",
1858
8
                                uv_fs_write, fd, &uvbuf, 1, pos);
1859
8
    FS_SYNC_TRACE_END(write, "bytesWritten", bytesWritten);
1860
24
    args.GetReturnValue().Set(bytesWritten);
1861
  }
1862
2468
}
1863
1864
1865
// Wrapper for writev(2).
1866
//
1867
// bytesWritten = writev(fd, chunks, position, callback)
1868
// 0 fd        integer. file descriptor
1869
// 1 chunks    array of buffers to write
1870
// 2 position  if integer, position to write at in the file.
1871
//             if null, write from the current position
1872
static void WriteBuffers(const FunctionCallbackInfo<Value>& args) {
1873
  Environment* env = Environment::GetCurrent(args);
1874
1875
  const int argc = args.Length();
1876
  CHECK_GE(argc, 3);
1877
1878
  CHECK(args[0]->IsInt32());
1879
  const int fd = args[0].As<Int32>()->Value();
1880
1881
  CHECK(args[1]->IsArray());
1882
  Local<Array> chunks = args[1].As<Array>();
1883
1884
  int64_t pos = GetOffset(args[2]);
1885
1886
  MaybeStackBuffer<uv_buf_t> iovs(chunks->Length());
1887
1888
  for (uint32_t i = 0; i < iovs.length(); i++) {
1889
    Local<Value> chunk = chunks->Get(env->context(), i).ToLocalChecked();
1890
    CHECK(Buffer::HasInstance(chunk));
1891
    iovs[i] = uv_buf_init(Buffer::Data(chunk), Buffer::Length(chunk));
1892
  }
1893
1894
  FSReqBase* req_wrap_async = GetReqWrap(args, 3);
1895
  if (req_wrap_async != nullptr) {  // writeBuffers(fd, chunks, pos, req)
1896
    AsyncCall(env, req_wrap_async, args, "write", UTF8, AfterInteger,
1897
              uv_fs_write, fd, *iovs, iovs.length(), pos);
1898
  } else {  // writeBuffers(fd, chunks, pos, undefined, ctx)
1899
    CHECK_EQ(argc, 5);
1900
    FSReqWrapSync req_wrap_sync;
1901
    FS_SYNC_TRACE_BEGIN(write);
1902
    int bytesWritten = SyncCall(env, args[4], &req_wrap_sync, "write",
1903
                                uv_fs_write, fd, *iovs, iovs.length(), pos);
1904
    FS_SYNC_TRACE_END(write, "bytesWritten", bytesWritten);
1905
    args.GetReturnValue().Set(bytesWritten);
1906
  }
1907
}
1908
1909
1910
// Wrapper for write(2).
1911
//
1912
// bytesWritten = write(fd, string, position, enc, callback)
1913
// 0 fd        integer. file descriptor
1914
// 1 string    non-buffer values are converted to strings
1915
// 2 position  if integer, position to write at in the file.
1916
//             if null, write from the current position
1917
// 3 enc       encoding of string
1918
54971
static void WriteString(const FunctionCallbackInfo<Value>& args) {
1919
54971
  Environment* env = Environment::GetCurrent(args);
1920
54971
  Isolate* isolate = env->isolate();
1921
1922
54971
  const int argc = args.Length();
1923
54971
  CHECK_GE(argc, 4);
1924
1925
109942
  CHECK(args[0]->IsInt32());
1926
164913
  const int fd = args[0].As<Int32>()->Value();
1927
1928
54971
  const int64_t pos = GetOffset(args[2]);
1929
1930
54971
  const auto enc = ParseEncoding(isolate, args[3], UTF8);
1931
1932
54971
  Local<Value> value = args[1];
1933
54971
  char* buf = nullptr;
1934
  size_t len;
1935
1936
54971
  FSReqBase* req_wrap_async = GetReqWrap(args, 4);
1937
54971
  const bool is_async = req_wrap_async != nullptr;
1938
1939
  // Avoid copying the string when it is externalized but only when:
1940
  // 1. The target encoding is compatible with the string's encoding, and
1941
  // 2. The write is synchronous, otherwise the string might get neutered
1942
  //    while the request is in flight, and
1943
  // 3. For UCS2, when the host system is little-endian.  Big-endian systems
1944
  //    need to call StringBytes::Write() to ensure proper byte swapping.
1945
  // The const_casts are conceptually sound: memory is read but not written.
1946

164913
  if (!is_async && value->IsString()) {
1947
54971
    auto string = value.As<String>();
1948


54971
    if ((enc == ASCII || enc == LATIN1) && string->IsExternalOneByte()) {
1949
      auto ext = string->GetExternalOneByteStringResource();
1950
      buf = const_cast<char*>(ext->data());
1951
      len = ext->length();
1952


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

54971
    FS_SYNC_TRACE_END(write, "bytesWritten", bytesWritten);
2004
164913
    args.GetReturnValue().Set(bytesWritten);
2005
  }
2006
}
2007
2008
2009
/*
2010
 * Wrapper for read(2).
2011
 *
2012
 * bytesRead = fs.read(fd, buffer, offset, length, position)
2013
 *
2014
 * 0 fd        int32. file descriptor
2015
 * 1 buffer    instance of Buffer
2016
 * 2 offset    int64. offset to start reading into inside buffer
2017
 * 3 length    int32. length to read
2018
 * 4 position  int64. file position - -1 for current position
2019
 */
2020
14578
static void Read(const FunctionCallbackInfo<Value>& args) {
2021
14578
  Environment* env = Environment::GetCurrent(args);
2022
2023
14578
  const int argc = args.Length();
2024
14578
  CHECK_GE(argc, 5);
2025
2026
29156
  CHECK(args[0]->IsInt32());
2027
43734
  const int fd = args[0].As<Int32>()->Value();
2028
2029
14578
  CHECK(Buffer::HasInstance(args[1]));
2030
29156
  Local<Object> buffer_obj = args[1].As<Object>();
2031
14578
  char* buffer_data = Buffer::Data(buffer_obj);
2032
14578
  size_t buffer_length = Buffer::Length(buffer_obj);
2033
2034
14578
  CHECK(IsSafeJsInt(args[2]));
2035
43734
  const int64_t off_64 = args[2].As<Integer>()->Value();
2036
14578
  CHECK_GE(off_64, 0);
2037
14578
  CHECK_LT(static_cast<uint64_t>(off_64), buffer_length);
2038
14578
  const size_t off = static_cast<size_t>(off_64);
2039
2040
29156
  CHECK(args[3]->IsInt32());
2041
43734
  const size_t len = static_cast<size_t>(args[3].As<Int32>()->Value());
2042
14578
  CHECK(Buffer::IsWithinBounds(off, len, buffer_length));
2043
2044

14578
  CHECK(IsSafeJsInt(args[4]) || args[4]->IsBigInt());
2045
58312
  const int64_t pos = args[4]->IsNumber() ?
2046
58312
                      args[4].As<Integer>()->Value() :
2047
14578
                      args[4].As<BigInt>()->Int64Value();
2048
2049
14578
  char* buf = buffer_data + off;
2050
14578
  uv_buf_t uvbuf = uv_buf_init(buf, len);
2051
2052
14578
  FSReqBase* req_wrap_async = GetReqWrap(args, 5);
2053
14578
  if (req_wrap_async != nullptr) {  // read(fd, buffer, offset, len, pos, req)
2054
    AsyncCall(env, req_wrap_async, args, "read", UTF8, AfterInteger,
2055
737
              uv_fs_read, fd, &uvbuf, 1, pos);
2056
  } else {  // read(fd, buffer, offset, len, pos, undefined, ctx)
2057
13841
    CHECK_EQ(argc, 7);
2058
27682
    FSReqWrapSync req_wrap_sync;
2059

13841
    FS_SYNC_TRACE_BEGIN(read);
2060
13841
    const int bytesRead = SyncCall(env, args[6], &req_wrap_sync, "read",
2061
13841
                                   uv_fs_read, fd, &uvbuf, 1, pos);
2062
13841
    FS_SYNC_TRACE_END(read, "bytesRead", bytesRead);
2063
41523
    args.GetReturnValue().Set(bytesRead);
2064
  }
2065
14578
}
2066
2067
2068
// Wrapper for readv(2).
2069
//
2070
// bytesRead = fs.readv(fd, buffers[, position], callback)
2071
// 0 fd        integer. file descriptor
2072
// 1 buffers   array of buffers to read
2073
// 2 position  if integer, position to read at in the file.
2074
//             if null, read from the current position
2075
static void ReadBuffers(const FunctionCallbackInfo<Value>& args) {
2076
  Environment* env = Environment::GetCurrent(args);
2077
2078
  const int argc = args.Length();
2079
  CHECK_GE(argc, 3);
2080
2081
  CHECK(args[0]->IsInt32());
2082
  const int fd = args[0].As<Int32>()->Value();
2083
2084
  CHECK(args[1]->IsArray());
2085
  Local<Array> buffers = args[1].As<Array>();
2086
2087
  int64_t pos = GetOffset(args[2]);  // -1 if not a valid JS int
2088
2089
  MaybeStackBuffer<uv_buf_t> iovs(buffers->Length());
2090
2091
  // Init uv buffers from ArrayBufferViews
2092
  for (uint32_t i = 0; i < iovs.length(); i++) {
2093
    Local<Value> buffer = buffers->Get(env->context(), i).ToLocalChecked();
2094
    CHECK(Buffer::HasInstance(buffer));
2095
    iovs[i] = uv_buf_init(Buffer::Data(buffer), Buffer::Length(buffer));
2096
  }
2097
2098
  FSReqBase* req_wrap_async = GetReqWrap(args, 3);
2099
  if (req_wrap_async != nullptr) {  // readBuffers(fd, buffers, pos, req)
2100
    AsyncCall(env, req_wrap_async, args, "read", UTF8, AfterInteger,
2101
              uv_fs_read, fd, *iovs, iovs.length(), pos);
2102
  } else {  // readBuffers(fd, buffers, undefined, ctx)
2103
    CHECK_EQ(argc, 5);
2104
    FSReqWrapSync req_wrap_sync;
2105
    FS_SYNC_TRACE_BEGIN(read);
2106
    int bytesRead = SyncCall(env, /* ctx */ args[4], &req_wrap_sync, "read",
2107
                             uv_fs_read, fd, *iovs, iovs.length(), pos);
2108
    FS_SYNC_TRACE_END(read, "bytesRead", bytesRead);
2109
    args.GetReturnValue().Set(bytesRead);
2110
  }
2111
}
2112
2113
2114
/* fs.chmod(path, mode);
2115
 * Wrapper for chmod(1) / EIO_CHMOD
2116
 */
2117
67
static void Chmod(const FunctionCallbackInfo<Value>& args) {
2118
67
  Environment* env = Environment::GetCurrent(args);
2119
2120
67
  const int argc = args.Length();
2121
67
  CHECK_GE(argc, 2);
2122
2123
134
  BufferValue path(env->isolate(), args[0]);
2124
67
  CHECK_NOT_NULL(*path);
2125
2126
134
  CHECK(args[1]->IsInt32());
2127
201
  int mode = args[1].As<Int32>()->Value();
2128
2129
67
  FSReqBase* req_wrap_async = GetReqWrap(args, 2);
2130
67
  if (req_wrap_async != nullptr) {  // chmod(path, mode, req)
2131
67
    AsyncCall(env, req_wrap_async, args, "chmod", UTF8, AfterNoArgs,
2132
67
              uv_fs_chmod, *path, mode);
2133
  } else {  // chmod(path, mode, undefined, ctx)
2134
    CHECK_EQ(argc, 4);
2135
    FSReqWrapSync req_wrap_sync;
2136
    FS_SYNC_TRACE_BEGIN(chmod);
2137
    SyncCall(env, args[3], &req_wrap_sync, "chmod",
2138
             uv_fs_chmod, *path, mode);
2139
    FS_SYNC_TRACE_END(chmod);
2140
  }
2141
67
}
2142
2143
2144
/* fs.fchmod(fd, mode);
2145
 * Wrapper for fchmod(1) / EIO_FCHMOD
2146
 */
2147
static void FChmod(const FunctionCallbackInfo<Value>& args) {
2148
  Environment* env = Environment::GetCurrent(args);
2149
2150
  const int argc = args.Length();
2151
  CHECK_GE(argc, 2);
2152
2153
  CHECK(args[0]->IsInt32());
2154
  const int fd = args[0].As<Int32>()->Value();
2155
2156
  CHECK(args[1]->IsInt32());
2157
  const int mode = args[1].As<Int32>()->Value();
2158
2159
  FSReqBase* req_wrap_async = GetReqWrap(args, 2);
2160
  if (req_wrap_async != nullptr) {  // fchmod(fd, mode, req)
2161
    AsyncCall(env, req_wrap_async, args, "fchmod", UTF8, AfterNoArgs,
2162
              uv_fs_fchmod, fd, mode);
2163
  } else {  // fchmod(fd, mode, undefined, ctx)
2164
    CHECK_EQ(argc, 4);
2165
    FSReqWrapSync req_wrap_sync;
2166
    FS_SYNC_TRACE_BEGIN(fchmod);
2167
    SyncCall(env, args[3], &req_wrap_sync, "fchmod",
2168
             uv_fs_fchmod, fd, mode);
2169
    FS_SYNC_TRACE_END(fchmod);
2170
  }
2171
}
2172
2173
2174
/* fs.chown(path, uid, gid);
2175
 * Wrapper for chown(1) / EIO_CHOWN
2176
 */
2177
static void Chown(const FunctionCallbackInfo<Value>& args) {
2178
  Environment* env = Environment::GetCurrent(args);
2179
2180
  const int argc = args.Length();
2181
  CHECK_GE(argc, 3);
2182
2183
  BufferValue path(env->isolate(), args[0]);
2184
  CHECK_NOT_NULL(*path);
2185
2186
  CHECK(args[1]->IsUint32());
2187
  const uv_uid_t uid = static_cast<uv_uid_t>(args[1].As<Uint32>()->Value());
2188
2189
  CHECK(args[2]->IsUint32());
2190
  const uv_gid_t gid = static_cast<uv_gid_t>(args[2].As<Uint32>()->Value());
2191
2192
  FSReqBase* req_wrap_async = GetReqWrap(args, 3);
2193
  if (req_wrap_async != nullptr) {  // chown(path, uid, gid, req)
2194
    AsyncCall(env, req_wrap_async, args, "chown", UTF8, AfterNoArgs,
2195
              uv_fs_chown, *path, uid, gid);
2196
  } else {  // chown(path, uid, gid, undefined, ctx)
2197
    CHECK_EQ(argc, 5);
2198
    FSReqWrapSync req_wrap_sync;
2199
    FS_SYNC_TRACE_BEGIN(chown);
2200
    SyncCall(env, args[4], &req_wrap_sync, "chown",
2201
             uv_fs_chown, *path, uid, gid);
2202
    FS_SYNC_TRACE_END(chown);
2203
  }
2204
}
2205
2206
2207
/* fs.fchown(fd, uid, gid);
2208
 * Wrapper for fchown(1) / EIO_FCHOWN
2209
 */
2210
static void FChown(const FunctionCallbackInfo<Value>& args) {
2211
  Environment* env = Environment::GetCurrent(args);
2212
2213
  const int argc = args.Length();
2214
  CHECK_GE(argc, 3);
2215
2216
  CHECK(args[0]->IsInt32());
2217
  const int fd = args[0].As<Int32>()->Value();
2218
2219
  CHECK(args[1]->IsUint32());
2220
  const uv_uid_t uid = static_cast<uv_uid_t>(args[1].As<Uint32>()->Value());
2221
2222
  CHECK(args[2]->IsUint32());
2223
  const uv_gid_t gid = static_cast<uv_gid_t>(args[2].As<Uint32>()->Value());
2224
2225
  FSReqBase* req_wrap_async = GetReqWrap(args, 3);
2226
  if (req_wrap_async != nullptr) {  // fchown(fd, uid, gid, req)
2227
    AsyncCall(env, req_wrap_async, args, "fchown", UTF8, AfterNoArgs,
2228
              uv_fs_fchown, fd, uid, gid);
2229
  } else {  // fchown(fd, uid, gid, undefined, ctx)
2230
    CHECK_EQ(argc, 5);
2231
    FSReqWrapSync req_wrap_sync;
2232
    FS_SYNC_TRACE_BEGIN(fchown);
2233
    SyncCall(env, args[4], &req_wrap_sync, "fchown",
2234
             uv_fs_fchown, fd, uid, gid);
2235
    FS_SYNC_TRACE_END(fchown);
2236
  }
2237
}
2238
2239
2240
static void LChown(const FunctionCallbackInfo<Value>& args) {
2241
  Environment* env = Environment::GetCurrent(args);
2242
2243
  const int argc = args.Length();
2244
  CHECK_GE(argc, 3);
2245
2246
  BufferValue path(env->isolate(), args[0]);
2247
  CHECK_NOT_NULL(*path);
2248
2249
  CHECK(args[1]->IsUint32());
2250
  const uv_uid_t uid = static_cast<uv_uid_t>(args[1].As<Uint32>()->Value());
2251
2252
  CHECK(args[2]->IsUint32());
2253
  const uv_gid_t gid = static_cast<uv_gid_t>(args[2].As<Uint32>()->Value());
2254
2255
  FSReqBase* req_wrap_async = GetReqWrap(args, 3);
2256
  if (req_wrap_async != nullptr) {  // lchown(path, uid, gid, req)
2257
    AsyncCall(env, req_wrap_async, args, "lchown", UTF8, AfterNoArgs,
2258
              uv_fs_lchown, *path, uid, gid);
2259
  } else {  // lchown(path, uid, gid, undefined, ctx)
2260
    CHECK_EQ(argc, 5);
2261
    FSReqWrapSync req_wrap_sync;
2262
    FS_SYNC_TRACE_BEGIN(lchown);
2263
    SyncCall(env, args[4], &req_wrap_sync, "lchown",
2264
             uv_fs_lchown, *path, uid, gid);
2265
    FS_SYNC_TRACE_END(lchown);
2266
  }
2267
}
2268
2269
2270
static void UTimes(const FunctionCallbackInfo<Value>& args) {
2271
  Environment* env = Environment::GetCurrent(args);
2272
2273
  const int argc = args.Length();
2274
  CHECK_GE(argc, 3);
2275
2276
  BufferValue path(env->isolate(), args[0]);
2277
  CHECK_NOT_NULL(*path);
2278
2279
  CHECK(args[1]->IsNumber());
2280
  const double atime = args[1].As<Number>()->Value();
2281
2282
  CHECK(args[2]->IsNumber());
2283
  const double mtime = args[2].As<Number>()->Value();
2284
2285
  FSReqBase* req_wrap_async = GetReqWrap(args, 3);
2286
  if (req_wrap_async != nullptr) {  // utimes(path, atime, mtime, req)
2287
    AsyncCall(env, req_wrap_async, args, "utime", UTF8, AfterNoArgs,
2288
              uv_fs_utime, *path, atime, mtime);
2289
  } else {  // utimes(path, atime, mtime, undefined, ctx)
2290
    CHECK_EQ(argc, 5);
2291
    FSReqWrapSync req_wrap_sync;
2292
    FS_SYNC_TRACE_BEGIN(utimes);
2293
    SyncCall(env, args[4], &req_wrap_sync, "utime",
2294
             uv_fs_utime, *path, atime, mtime);
2295
    FS_SYNC_TRACE_END(utimes);
2296
  }
2297
}
2298
2299
1866
static void FUTimes(const FunctionCallbackInfo<Value>& args) {
2300
1866
  Environment* env = Environment::GetCurrent(args);
2301
2302
1866
  const int argc = args.Length();
2303
1866
  CHECK_GE(argc, 3);
2304
2305
3732
  CHECK(args[0]->IsInt32());
2306
5598
  const int fd = args[0].As<Int32>()->Value();
2307
2308
3732
  CHECK(args[1]->IsNumber());
2309
5598
  const double atime = args[1].As<Number>()->Value();
2310
2311
3732
  CHECK(args[2]->IsNumber());
2312
5598
  const double mtime = args[2].As<Number>()->Value();
2313
2314
1866
  FSReqBase* req_wrap_async = GetReqWrap(args, 3);
2315
1866
  if (req_wrap_async != nullptr) {  // futimes(fd, atime, mtime, req)
2316
    AsyncCall(env, req_wrap_async, args, "futime", UTF8, AfterNoArgs,
2317
1866
              uv_fs_futime, fd, atime, mtime);
2318
  } else {  // futimes(fd, atime, mtime, undefined, ctx)
2319
    CHECK_EQ(argc, 5);
2320
    FSReqWrapSync req_wrap_sync;
2321
    FS_SYNC_TRACE_BEGIN(futimes);
2322
    SyncCall(env, args[4], &req_wrap_sync, "futime",
2323
             uv_fs_futime, fd, atime, mtime);
2324
    FS_SYNC_TRACE_END(futimes);
2325
  }
2326
1866
}
2327
2328
static void LUTimes(const FunctionCallbackInfo<Value>& args) {
2329
  Environment* env = Environment::GetCurrent(args);
2330
2331
  const int argc = args.Length();
2332
  CHECK_GE(argc, 3);
2333
2334
  BufferValue path(env->isolate(), args[0]);
2335
  CHECK_NOT_NULL(*path);
2336
2337
  CHECK(args[1]->IsNumber());
2338
  const double atime = args[1].As<Number>()->Value();
2339
2340
  CHECK(args[2]->IsNumber());
2341
  const double mtime = args[2].As<Number>()->Value();
2342
2343
  FSReqBase* req_wrap_async = GetReqWrap(args, 3);
2344
  if (req_wrap_async != nullptr) {  // lutimes(path, atime, mtime, req)
2345
    AsyncCall(env, req_wrap_async, args, "lutime", UTF8, AfterNoArgs,
2346
              uv_fs_lutime, *path, atime, mtime);
2347
  } else {  // lutimes(path, atime, mtime, undefined, ctx)
2348
    CHECK_EQ(argc, 5);
2349
    FSReqWrapSync req_wrap_sync;
2350
    FS_SYNC_TRACE_BEGIN(lutimes);
2351
    SyncCall(env, args[4], &req_wrap_sync, "lutime",
2352
             uv_fs_lutime, *path, atime, mtime);
2353
    FS_SYNC_TRACE_END(lutimes);
2354
  }
2355
}
2356
2357
static void Mkdtemp(const FunctionCallbackInfo<Value>& args) {
2358
  Environment* env = Environment::GetCurrent(args);
2359
  Isolate* isolate = env->isolate();
2360
2361
  const int argc = args.Length();
2362
  CHECK_GE(argc, 2);
2363
2364
  BufferValue tmpl(isolate, args[0]);
2365
  CHECK_NOT_NULL(*tmpl);
2366
2367
  const enum encoding encoding = ParseEncoding(isolate, args[1], UTF8);
2368
2369
  FSReqBase* req_wrap_async = GetReqWrap(args, 2);
2370
  if (req_wrap_async != nullptr) {  // mkdtemp(tmpl, encoding, req)
2371
    AsyncCall(env, req_wrap_async, args, "mkdtemp", encoding, AfterStringPath,
2372
              uv_fs_mkdtemp, *tmpl);
2373
  } else {  // mkdtemp(tmpl, encoding, undefined, ctx)
2374
    CHECK_EQ(argc, 4);
2375
    FSReqWrapSync req_wrap_sync;
2376
    FS_SYNC_TRACE_BEGIN(mkdtemp);
2377
    SyncCall(env, args[3], &req_wrap_sync, "mkdtemp",
2378
             uv_fs_mkdtemp, *tmpl);
2379
    FS_SYNC_TRACE_END(mkdtemp);
2380
    const char* path = req_wrap_sync.req.path;
2381
2382
    Local<Value> error;
2383
    MaybeLocal<Value> rc =
2384
        StringBytes::Encode(isolate, path, encoding, &error);
2385
    if (rc.IsEmpty()) {
2386
      Local<Object> ctx = args[3].As<Object>();
2387
      ctx->Set(env->context(), env->error_string(), error).Check();
2388
      return;
2389
    }
2390
    args.GetReturnValue().Set(rc.ToLocalChecked());
2391
  }
2392
}
2393
2394
void BindingData::MemoryInfo(MemoryTracker* tracker) const {
2395
  tracker->TrackField("stats_field_array", stats_field_array);
2396
  tracker->TrackField("stats_field_bigint_array", stats_field_bigint_array);
2397
  tracker->TrackField("file_handle_read_wrap_freelist",
2398
                      file_handle_read_wrap_freelist);
2399
}
2400
2401
// TODO(addaleax): Remove once we're on C++17.
2402
constexpr FastStringKey BindingData::type_name;
2403
2404
120
void Initialize(Local<Object> target,
2405
                Local<Value> unused,
2406
                Local<Context> context,
2407
                void* priv) {
2408
120
  Environment* env = Environment::GetCurrent(context);
2409
120
  Isolate* isolate = env->isolate();
2410
  BindingData* const binding_data =
2411
120
      env->AddBindingData<BindingData>(context, target);
2412
120
  if (binding_data == nullptr) return;
2413
2414
120
  env->SetMethod(target, "access", Access);
2415
120
  env->SetMethod(target, "close", Close);
2416
120
  env->SetMethod(target, "open", Open);
2417
120
  env->SetMethod(target, "openFileHandle", OpenFileHandle);
2418
120
  env->SetMethod(target, "read", Read);
2419
120
  env->SetMethod(target, "readBuffers", ReadBuffers);
2420
120
  env->SetMethod(target, "fdatasync", Fdatasync);
2421
120
  env->SetMethod(target, "fsync", Fsync);
2422
120
  env->SetMethod(target, "rename", Rename);
2423
120
  env->SetMethod(target, "ftruncate", FTruncate);
2424
120
  env->SetMethod(target, "rmdir", RMDir);
2425
120
  env->SetMethod(target, "mkdir", MKDir);
2426
120
  env->SetMethod(target, "readdir", ReadDir);
2427
120
  env->SetMethod(target, "internalModuleReadJSON", InternalModuleReadJSON);
2428
120
  env->SetMethod(target, "internalModuleStat", InternalModuleStat);
2429
120
  env->SetMethod(target, "stat", Stat);
2430
120
  env->SetMethod(target, "lstat", LStat);
2431
120
  env->SetMethod(target, "fstat", FStat);
2432
120
  env->SetMethod(target, "link", Link);
2433
120
  env->SetMethod(target, "symlink", Symlink);
2434
120
  env->SetMethod(target, "readlink", ReadLink);
2435
120
  env->SetMethod(target, "unlink", Unlink);
2436
120
  env->SetMethod(target, "writeBuffer", WriteBuffer);
2437
120
  env->SetMethod(target, "writeBuffers", WriteBuffers);
2438
120
  env->SetMethod(target, "writeString", WriteString);
2439
120
  env->SetMethod(target, "realpath", RealPath);
2440
120
  env->SetMethod(target, "copyFile", CopyFile);
2441
2442
120
  env->SetMethod(target, "chmod", Chmod);
2443
120
  env->SetMethod(target, "fchmod", FChmod);
2444
  // env->SetMethod(target, "lchmod", LChmod);
2445
2446
120
  env->SetMethod(target, "chown", Chown);
2447
120
  env->SetMethod(target, "fchown", FChown);
2448
120
  env->SetMethod(target, "lchown", LChown);
2449
2450
120
  env->SetMethod(target, "utimes", UTimes);
2451
120
  env->SetMethod(target, "futimes", FUTimes);
2452
120
  env->SetMethod(target, "lutimes", LUTimes);
2453
2454
120
  env->SetMethod(target, "mkdtemp", Mkdtemp);
2455
2456
  target
2457
240
      ->Set(context,
2458
            FIXED_ONE_BYTE_STRING(isolate, "kFsStatsFieldsNumber"),
2459
            Integer::New(
2460
                isolate,
2461
480
                static_cast<int32_t>(FsStatsOffset::kFsStatsFieldsNumber)))
2462
      .Check();
2463
2464
240
  target->Set(context,
2465
              FIXED_ONE_BYTE_STRING(isolate, "statValues"),
2466
480
              binding_data->stats_field_array.GetJSArray()).Check();
2467
2468
240
  target->Set(context,
2469
              FIXED_ONE_BYTE_STRING(isolate, "bigintStatValues"),
2470
480
              binding_data->stats_field_bigint_array.GetJSArray()).Check();
2471
2472
120
  StatWatcher::Initialize(env, target);
2473
2474
  // Create FunctionTemplate for FSReqCallback
2475
120
  Local<FunctionTemplate> fst = env->NewFunctionTemplate(NewFSReqCallback);
2476
360
  fst->InstanceTemplate()->SetInternalFieldCount(
2477
120
      FSReqBase::kInternalFieldCount);
2478
240
  fst->Inherit(AsyncWrap::GetConstructorTemplate(env));
2479
120
  env->SetConstructorFunction(target, "FSReqCallback", fst);
2480
2481
  // Create FunctionTemplate for FileHandleReadWrap. There’s no need
2482
  // to do anything in the constructor, so we only store the instance template.
2483
120
  Local<FunctionTemplate> fh_rw = FunctionTemplate::New(isolate);
2484
360
  fh_rw->InstanceTemplate()->SetInternalFieldCount(
2485
120
      FSReqBase::kInternalFieldCount);
2486
240
  fh_rw->Inherit(AsyncWrap::GetConstructorTemplate(env));
2487
  Local<String> fhWrapString =
2488
120
      FIXED_ONE_BYTE_STRING(isolate, "FileHandleReqWrap");
2489
120
  fh_rw->SetClassName(fhWrapString);
2490
120
  env->set_filehandlereadwrap_template(
2491
120
      fst->InstanceTemplate());
2492
2493
  // Create Function Template for FSReqPromise
2494
120
  Local<FunctionTemplate> fpt = FunctionTemplate::New(isolate);
2495
240
  fpt->Inherit(AsyncWrap::GetConstructorTemplate(env));
2496
  Local<String> promiseString =
2497
120
      FIXED_ONE_BYTE_STRING(isolate, "FSReqPromise");
2498
120
  fpt->SetClassName(promiseString);
2499
120
  Local<ObjectTemplate> fpo = fpt->InstanceTemplate();
2500
120
  fpo->SetInternalFieldCount(FSReqBase::kInternalFieldCount);
2501
120
  env->set_fsreqpromise_constructor_template(fpo);
2502
2503
  // Create FunctionTemplate for FileHandle
2504
120
  Local<FunctionTemplate> fd = env->NewFunctionTemplate(FileHandle::New);
2505
240
  fd->Inherit(AsyncWrap::GetConstructorTemplate(env));
2506
120
  env->SetProtoMethod(fd, "close", FileHandle::Close);
2507
120
  env->SetProtoMethod(fd, "releaseFD", FileHandle::ReleaseFD);
2508
120
  Local<ObjectTemplate> fdt = fd->InstanceTemplate();
2509
120
  fdt->SetInternalFieldCount(StreamBase::kInternalFieldCount);
2510
120
  StreamBase::AddMethods(env, fd);
2511
120
  env->SetConstructorFunction(target, "FileHandle", fd);
2512
120
  env->set_fd_constructor_template(fdt);
2513
2514
  // Create FunctionTemplate for FileHandle::CloseReq
2515
120
  Local<FunctionTemplate> fdclose = FunctionTemplate::New(isolate);
2516
240
  fdclose->SetClassName(FIXED_ONE_BYTE_STRING(isolate,
2517
120
                        "FileHandleCloseReq"));
2518
240
  fdclose->Inherit(AsyncWrap::GetConstructorTemplate(env));
2519
120
  Local<ObjectTemplate> fdcloset = fdclose->InstanceTemplate();
2520
120
  fdcloset->SetInternalFieldCount(FSReqBase::kInternalFieldCount);
2521
120
  env->set_fdclose_constructor_template(fdcloset);
2522
2523
  Local<Symbol> use_promises_symbol =
2524
    Symbol::New(isolate,
2525
120
                FIXED_ONE_BYTE_STRING(isolate, "use promises"));
2526
120
  env->set_fs_use_promises_symbol(use_promises_symbol);
2527
240
  target->Set(context,
2528
              FIXED_ONE_BYTE_STRING(isolate, "kUsePromises"),
2529
360
              use_promises_symbol).Check();
2530
}
2531
2532
1470
BindingData* FSReqBase::binding_data() {
2533
1470
  return binding_data_.get();
2534
}
2535
}  // namespace fs
2536
2537
}  // end namespace node
2538
2539

481
NODE_MODULE_CONTEXT_AWARE_INTERNAL(fs, node::fs::Initialize)