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: 1235 1314 94.0 %
Date: 2019-09-17 22:33:17 Branches: 788 1194 66.0 %

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
22
#include "node_file.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
#include "string_search.h"
36
37
#include <fcntl.h>
38
#include <sys/types.h>
39
#include <sys/stat.h>
40
#include <cstring>
41
#include <cerrno>
42
#include <climits>
43
44
#if defined(__MINGW32__) || defined(_MSC_VER)
45
# include <io.h>
46
#endif
47
48
#include <memory>
49
50
namespace node {
51
52
namespace fs {
53
54
using v8::Array;
55
using v8::BigUint64Array;
56
using v8::Context;
57
using v8::DontDelete;
58
using v8::EscapableHandleScope;
59
using v8::Float64Array;
60
using v8::Function;
61
using v8::FunctionCallbackInfo;
62
using v8::FunctionTemplate;
63
using v8::HandleScope;
64
using v8::Int32;
65
using v8::Integer;
66
using v8::Isolate;
67
using v8::Local;
68
using v8::MaybeLocal;
69
using v8::Number;
70
using v8::Object;
71
using v8::ObjectTemplate;
72
using v8::Promise;
73
using v8::PropertyAttribute;
74
using v8::ReadOnly;
75
using v8::String;
76
using v8::Symbol;
77
using v8::Uint32;
78
using v8::Undefined;
79
using v8::Value;
80
81
#ifndef S_ISDIR
82
# define S_ISDIR(mode)  (((mode) & S_IFMT) == S_IFDIR)
83
#endif
84
85
#ifdef __POSIX__
86
constexpr char kPathSeparator = '/';
87
#else
88
const char* const kPathSeparator = "\\/";
89
#endif
90
91
145508
inline int64_t GetOffset(Local<Value> value) {
92

160544
  return IsSafeJsInt(value) ? value.As<Integer>()->Value() : -1;
93
}
94
95
#define TRACE_NAME(name) "fs.sync." #name
96
#define GET_TRACE_ENABLED                                                  \
97
  (*TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED                             \
98
  (TRACING_CATEGORY_NODE2(fs, sync)) != 0)
99
#define FS_SYNC_TRACE_BEGIN(syscall, ...)                                  \
100
  if (GET_TRACE_ENABLED)                                                   \
101
  TRACE_EVENT_BEGIN(TRACING_CATEGORY_NODE2(fs, sync), TRACE_NAME(syscall), \
102
  ##__VA_ARGS__);
103
#define FS_SYNC_TRACE_END(syscall, ...)                                    \
104
  if (GET_TRACE_ENABLED)                                                   \
105
  TRACE_EVENT_END(TRACING_CATEGORY_NODE2(fs, sync), TRACE_NAME(syscall),   \
106
  ##__VA_ARGS__);
107
108
// We sometimes need to convert a C++ lambda function to a raw C-style function.
109
// This is helpful, because ReqWrap::Dispatch() does not recognize lambda
110
// functions, and thus does not wrap them properly.
111
typedef void(*uv_fs_callback_t)(uv_fs_t*);
112
113
// The FileHandle object wraps a file descriptor and will close it on garbage
114
// collection if necessary. If that happens, a process warning will be
115
// emitted (or a fatal exception will occur if the fd cannot be closed.)
116
83
FileHandle::FileHandle(Environment* env, Local<Object> obj, int fd)
117
    : AsyncWrap(env, obj, AsyncWrap::PROVIDER_FILEHANDLE),
118
      StreamBase(env),
119
83
      fd_(fd) {
120
83
  MakeWeak();
121
83
  StreamBase::AttachToObject(GetObject());
122
83
}
123
124
83
FileHandle* FileHandle::New(Environment* env, int fd, Local<Object> obj) {
125

400
  if (obj.IsEmpty() && !env->fd_constructor_template()
126
287
                            ->NewInstance(env->context())
127
287
                            .ToLocal(&obj)) {
128
    return nullptr;
129
  }
130
  PropertyAttribute attr =
131
83
      static_cast<PropertyAttribute>(ReadOnly | DontDelete);
132
166
  if (obj->DefineOwnProperty(env->context(),
133
                             env->fd_string(),
134
                             Integer::New(env->isolate(), fd),
135
415
                             attr)
136
166
          .IsNothing()) {
137
    return nullptr;
138
  }
139
83
  return new FileHandle(env, obj, fd);
140
}
141
142
15
void FileHandle::New(const FunctionCallbackInfo<Value>& args) {
143
15
  Environment* env = Environment::GetCurrent(args);
144
15
  CHECK(args.IsConstructCall());
145
30
  CHECK(args[0]->IsInt32());
146
147
  FileHandle* handle =
148
45
      FileHandle::New(env, args[0].As<Int32>()->Value(), args.This());
149
30
  if (handle == nullptr) return;
150
30
  if (args[1]->IsNumber())
151
60
    handle->read_offset_ = args[1]->IntegerValue(env->context()).FromJust();
152
30
  if (args[2]->IsNumber())
153
60
    handle->read_length_ = args[2]->IntegerValue(env->context()).FromJust();
154
}
155
156
249
FileHandle::~FileHandle() {
157
83
  CHECK(!closing_);  // We should not be deleting while explicitly closing!
158
83
  Close();           // Close synchronously and emit warning
159
83
  CHECK(closed_);    // We have to be closed at the point
160
166
}
161
162
163
// Close the file descriptor if it hasn't already been closed. A process
164
// warning will be emitted using a SetImmediate to avoid calling back to
165
// JS during GC. If closing the fd fails at this point, a fatal exception
166
// will crash the process immediately.
167
83
inline void FileHandle::Close() {
168
159
  if (closed_) return;
169
  uv_fs_t req;
170
7
  int ret = uv_fs_close(env()->event_loop(), &req, fd_, nullptr);
171
7
  uv_fs_req_cleanup(&req);
172
7
  AfterClose();
173
174
  struct err_detail { int ret; int fd; };
175
176
7
  err_detail detail { ret, fd_ };
177
178
7
  if (ret < 0) {
179
    // Do not unref this
180
    env()->SetImmediate([detail](Environment* env) {
181
      char msg[70];
182
      snprintf(msg, arraysize(msg),
183
              "Closing file descriptor %d on garbage collection failed",
184
              detail.fd);
185
      // This exception will end up being fatal for the process because
186
      // it is being thrown from within the SetImmediate handler and
187
      // there is no JS stack to bubble it to. In other words, tearing
188
      // down the process is the only reasonable thing we can do here.
189
      HandleScope handle_scope(env->isolate());
190
      env->ThrowUVException(detail.ret, "close", msg);
191
    });
192
    return;
193
  }
194
195
  // If the close was successful, we still want to emit a process warning
196
  // to notify that the file descriptor was gc'd. We want to be noisy about
197
  // this because not explicitly closing the FileHandle is a bug.
198
1
  env()->SetUnrefImmediate([detail](Environment* env) {
199
    ProcessEmitWarning(env,
200
                       "Closing file descriptor %d on garbage collection",
201
1
                       detail.fd);
202
8
  });
203
}
204
205
69
void FileHandle::CloseReq::Resolve() {
206
69
  Isolate* isolate = env()->isolate();
207
69
  HandleScope scope(isolate);
208
138
  InternalCallbackScope callback_scope(this);
209
138
  Local<Promise> promise = promise_.Get(isolate);
210
69
  Local<Promise::Resolver> resolver = promise.As<Promise::Resolver>();
211
276
  resolver->Resolve(env()->context(), Undefined(isolate)).Check();
212
69
}
213
214
void FileHandle::CloseReq::Reject(Local<Value> reason) {
215
  Isolate* isolate = env()->isolate();
216
  HandleScope scope(isolate);
217
  InternalCallbackScope callback_scope(this);
218
  Local<Promise> promise = promise_.Get(isolate);
219
  Local<Promise::Resolver> resolver = promise.As<Promise::Resolver>();
220
  resolver->Reject(env()->context(), reason).Check();
221
}
222
223
69
FileHandle* FileHandle::CloseReq::file_handle() {
224
69
  Isolate* isolate = env()->isolate();
225
69
  HandleScope scope(isolate);
226
138
  Local<Value> val = ref_.Get(isolate);
227
69
  Local<Object> obj = val.As<Object>();
228
69
  return Unwrap<FileHandle>(obj);
229
}
230
231
// Closes this FileHandle asynchronously and returns a Promise that will be
232
// resolved when the callback is invoked, or rejects with a UVException if
233
// there was a problem closing the fd. This is the preferred mechanism for
234
// closing the FD object even tho the object will attempt to close
235
// automatically on gc.
236
69
inline MaybeLocal<Promise> FileHandle::ClosePromise() {
237
69
  Isolate* isolate = env()->isolate();
238
69
  EscapableHandleScope scope(isolate);
239
69
  Local<Context> context = env()->context();
240
69
  auto maybe_resolver = Promise::Resolver::New(context);
241
69
  CHECK(!maybe_resolver.IsEmpty());
242
69
  Local<Promise::Resolver> resolver = maybe_resolver.ToLocalChecked();
243
69
  Local<Promise> promise = resolver.As<Promise>();
244
69
  CHECK(!reading_);
245

69
  if (!closed_ && !closing_) {
246
69
    closing_ = true;
247
    Local<Object> close_req_obj;
248
138
    if (!env()
249
69
             ->fdclose_constructor_template()
250
276
             ->NewInstance(env()->context())
251
207
             .ToLocal(&close_req_obj)) {
252
      return MaybeLocal<Promise>();
253
    }
254
138
    CloseReq* req = new CloseReq(env(), close_req_obj, promise, object());
255
207
    auto AfterClose = uv_fs_callback_t{[](uv_fs_t* req) {
256
69
      std::unique_ptr<CloseReq> close(CloseReq::from_req(req));
257
69
      CHECK_NOT_NULL(close);
258
69
      close->file_handle()->AfterClose();
259
69
      Isolate* isolate = close->env()->isolate();
260
69
      if (req->result < 0) {
261
        close->Reject(UVException(isolate, req->result, "close"));
262
      } else {
263
69
        close->Resolve();
264
      }
265
276
    }};
266
69
    int ret = req->Dispatch(uv_fs_close, fd_, AfterClose);
267
69
    if (ret < 0) {
268
      req->Reject(UVException(isolate, ret, "close"));
269
      delete req;
270
69
    }
271
  } else {
272
    // Already closed. Just reject the promise immediately
273
    resolver->Reject(context, UVException(isolate, UV_EBADF, "close"))
274
        .Check();
275
  }
276
69
  return scope.Escape(promise);
277
}
278
279
69
void FileHandle::Close(const FunctionCallbackInfo<Value>& args) {
280
  FileHandle* fd;
281
69
  ASSIGN_OR_RETURN_UNWRAP(&fd, args.Holder());
282
  Local<Promise> ret;
283
138
  if (!fd->ClosePromise().ToLocal(&ret)) return;
284
138
  args.GetReturnValue().Set(ret);
285
}
286
287
288
7
void FileHandle::ReleaseFD(const FunctionCallbackInfo<Value>& args) {
289
  FileHandle* fd;
290
14
  ASSIGN_OR_RETURN_UNWRAP(&fd, args.Holder());
291
  // Just act as if this FileHandle has been closed.
292
7
  fd->AfterClose();
293
}
294
295
296
83
void FileHandle::AfterClose() {
297
83
  closing_ = false;
298
83
  closed_ = true;
299

83
  if (reading_ && !persistent().IsEmpty())
300
    EmitRead(UV_EOF);
301
83
}
302
303
2
void FileHandleReadWrap::MemoryInfo(MemoryTracker* tracker) const {
304
2
  tracker->TrackField("buffer", buffer_);
305
2
  tracker->TrackField("file_handle", this->file_handle_);
306
2
}
307
308
15
FileHandleReadWrap::FileHandleReadWrap(FileHandle* handle, Local<Object> obj)
309
  : ReqWrap(handle->env(), obj, AsyncWrap::PROVIDER_FSREQCALLBACK),
310
15
    file_handle_(handle) {}
311
312
227
int FileHandle::ReadStart() {
313

227
  if (!IsAlive() || IsClosing())
314
    return UV_EOF;
315
316
227
  reading_ = true;
317
318
227
  if (current_read_)
319
    return 0;
320
321
227
  std::unique_ptr<FileHandleReadWrap> read_wrap;
322
323
227
  if (read_length_ == 0) {
324
6
    EmitRead(UV_EOF);
325
6
    return 0;
326
  }
327
328
  {
329
    // Create a new FileHandleReadWrap or re-use one.
330
    // Either way, we need these two scopes for AsyncReset() or otherwise
331
    // for creating the new instance.
332
221
    HandleScope handle_scope(env()->isolate());
333
442
    AsyncHooks::DefaultTriggerAsyncIdScope trigger_scope(this);
334
335
221
    auto& freelist = env()->file_handle_read_wrap_freelist();
336
221
    if (freelist.size() > 0) {
337
206
      read_wrap = std::move(freelist.back());
338
206
      freelist.pop_back();
339
206
      read_wrap->AsyncReset();
340
206
      read_wrap->file_handle_ = this;
341
    } else {
342
      Local<Object> wrap_obj;
343
30
      if (!env()
344
15
               ->filehandlereadwrap_template()
345
60
               ->NewInstance(env()->context())
346
45
               .ToLocal(&wrap_obj)) {
347
        return UV_EBUSY;
348
      }
349
15
      read_wrap = std::make_unique<FileHandleReadWrap>(this, wrap_obj);
350
221
    }
351
  }
352
221
  int64_t recommended_read = 65536;
353

221
  if (read_length_ >= 0 && read_length_ <= recommended_read)
354
10
    recommended_read = read_length_;
355
356
221
  read_wrap->buffer_ = EmitAlloc(recommended_read);
357
358
221
  current_read_ = std::move(read_wrap);
359
360
221
  current_read_->Dispatch(uv_fs_read,
361
                          fd_,
362
221
                          &current_read_->buffer_,
363
                          1,
364
                          read_offset_,
365
663
                          uv_fs_callback_t{[](uv_fs_t* req) {
366
    FileHandle* handle;
367
    {
368
221
      FileHandleReadWrap* req_wrap = FileHandleReadWrap::from_req(req);
369
221
      handle = req_wrap->file_handle_;
370
221
      CHECK_EQ(handle->current_read_.get(), req_wrap);
371
    }
372
373
    // ReadStart() checks whether current_read_ is set to determine whether
374
    // a read is in progress. Moving it into a local variable makes sure that
375
    // the ReadStart() call below doesn't think we're still actively reading.
376
    std::unique_ptr<FileHandleReadWrap> read_wrap =
377
221
        std::move(handle->current_read_);
378
379
221
    int result = req->result;
380
221
    uv_buf_t buffer = read_wrap->buffer_;
381
382
221
    uv_fs_req_cleanup(req);
383
384
    // Push the read wrap back to the freelist, or let it be destroyed
385
    // once we’re exiting the current scope.
386
221
    constexpr size_t wanted_freelist_fill = 100;
387
221
    auto& freelist = handle->env()->file_handle_read_wrap_freelist();
388
221
    if (freelist.size() < wanted_freelist_fill) {
389
221
      read_wrap->Reset();
390
221
      freelist.emplace_back(std::move(read_wrap));
391
    }
392
393
221
    if (result >= 0) {
394
      // Read at most as many bytes as we originally planned to.
395

220
      if (handle->read_length_ >= 0 && handle->read_length_ < result)
396
        result = handle->read_length_;
397
398
      // If we read data and we have an expected length, decrease it by
399
      // how much we have read.
400
220
      if (handle->read_length_ >= 0)
401
16
        handle->read_length_ -= result;
402
403
      // If we have an offset, increase it by how much we have read.
404
220
      if (handle->read_offset_ >= 0)
405
218
        handle->read_offset_ += result;
406
    }
407
408
    // Reading 0 bytes from a file always means EOF, or that we reached
409
    // the end of the requested range.
410
221
    if (result == 0)
411
6
      result = UV_EOF;
412
413
221
    handle->EmitRead(result, buffer);
414
415
    // Start over, if EmitRead() didn’t tell us to stop.
416
221
    if (handle->reading_)
417
      handle->ReadStart();
418
1326
  }});
419
420
221
  return 0;
421
}
422
423
242
int FileHandle::ReadStop() {
424
242
  reading_ = false;
425
242
  return 0;
426
}
427
428
typedef SimpleShutdownWrap<ReqWrap<uv_fs_t>> FileHandleCloseWrap;
429
430
ShutdownWrap* FileHandle::CreateShutdownWrap(Local<Object> object) {
431
  return new FileHandleCloseWrap(this, object);
432
}
433
434
int FileHandle::DoShutdown(ShutdownWrap* req_wrap) {
435
  FileHandleCloseWrap* wrap = static_cast<FileHandleCloseWrap*>(req_wrap);
436
  closing_ = true;
437
  wrap->Dispatch(uv_fs_close, fd_, uv_fs_callback_t{[](uv_fs_t* req) {
438
    FileHandleCloseWrap* wrap = static_cast<FileHandleCloseWrap*>(
439
        FileHandleCloseWrap::from_req(req));
440
    FileHandle* handle = static_cast<FileHandle*>(wrap->stream());
441
    handle->AfterClose();
442
443
    int result = req->result;
444
    uv_fs_req_cleanup(req);
445
    wrap->Done(result);
446
  }});
447
448
  return 0;
449
}
450
451
452
5539
void FSReqCallback::Reject(Local<Value> reject) {
453
5539
  MakeCallback(env()->oncomplete_string(), 1, &reject);
454
5539
}
455
456
6018
void FSReqCallback::ResolveStat(const uv_stat_t* stat) {
457
6018
  Resolve(FillGlobalStatsArray(env(), use_bigint(), stat));
458
6018
}
459
460
56266
void FSReqCallback::Resolve(Local<Value> value) {
461
  Local<Value> argv[2] {
462
    Null(env()->isolate()),
463
    value
464
112532
  };
465
  MakeCallback(env()->oncomplete_string(),
466
157208
               value->IsUndefined() ? 1 : arraysize(argv),
467
100942
               argv);
468
56258
}
469
470
61805
void FSReqCallback::SetReturnValue(const FunctionCallbackInfo<Value>& args) {
471
123610
  args.GetReturnValue().SetUndefined();
472
61805
}
473
474
61825
void NewFSReqCallback(const FunctionCallbackInfo<Value>& args) {
475
61825
  CHECK(args.IsConstructCall());
476
61825
  Environment* env = Environment::GetCurrent(args);
477
185475
  new FSReqCallback(env, args.This(), args[0]->IsTrue());
478
61825
}
479
480
62174
FSReqAfterScope::FSReqAfterScope(FSReqBase* wrap, uv_fs_t* req)
481
    : wrap_(wrap),
482
      req_(req),
483
      handle_scope_(wrap->env()->isolate()),
484
62174
      context_scope_(wrap->env()->context()) {
485
62174
  CHECK_EQ(wrap_->req(), req);
486
62174
}
487
488
186498
FSReqAfterScope::~FSReqAfterScope() {
489
62166
  uv_fs_req_cleanup(wrap_->req());
490
62166
  delete wrap_;
491
62166
}
492
493
// TODO(joyeecheung): create a normal context object, and
494
// construct the actual errors in the JS land using the context.
495
// The context should include fds for some fs APIs, currently they are
496
// missing in the error messages. The path, dest, syscall, fd, .etc
497
// can be put into the context before the binding is even invoked,
498
// the only information that has to come from the C++ layer is the
499
// error number (and possibly the syscall for abstraction),
500
// which is also why the errors should have been constructed
501
// in JS for more flexibility.
502
5561
void FSReqAfterScope::Reject(uv_fs_t* req) {
503
  wrap_->Reject(UVException(wrap_->env()->isolate(),
504
                            req->result,
505
                            wrap_->syscall(),
506
                            nullptr,
507
                            req->path,
508
5561
                            wrap_->data()));
509
5561
}
510
511
62174
bool FSReqAfterScope::Proceed() {
512
62174
  if (req_->result < 0) {
513
5561
    Reject(req_);
514
5561
    return false;
515
  }
516
56613
  return true;
517
}
518
519
12725
void AfterNoArgs(uv_fs_t* req) {
520
12725
  FSReqBase* req_wrap = FSReqBase::from_req(req);
521
12725
  FSReqAfterScope after(req_wrap, req);
522
523
12725
  if (after.Proceed())
524
23288
    req_wrap->Resolve(Undefined(req_wrap->env()->isolate()));
525
12718
}
526
527
10256
void AfterStat(uv_fs_t* req) {
528
10256
  FSReqBase* req_wrap = FSReqBase::from_req(req);
529
10256
  FSReqAfterScope after(req_wrap, req);
530
531
10256
  if (after.Proceed()) {
532
6148
    req_wrap->ResolveStat(&req->statbuf);
533
10256
  }
534
10256
}
535
536
38900
void AfterInteger(uv_fs_t* req) {
537
38900
  FSReqBase* req_wrap = FSReqBase::from_req(req);
538
38900
  FSReqAfterScope after(req_wrap, req);
539
540
38900
  if (after.Proceed())
541
77096
    req_wrap->Resolve(Integer::New(req_wrap->env()->isolate(), req->result));
542
38900
}
543
544
67
void AfterOpenFileHandle(uv_fs_t* req) {
545
67
  FSReqBase* req_wrap = FSReqBase::from_req(req);
546
67
  FSReqAfterScope after(req_wrap, req);
547
548
67
  if (after.Proceed()) {
549
67
    FileHandle* fd = FileHandle::New(req_wrap->env(), req->result);
550
134
    if (fd == nullptr) return;
551
134
    req_wrap->Resolve(fd->object());
552
67
  }
553
}
554
555
6
void AfterStringPath(uv_fs_t* req) {
556
6
  FSReqBase* req_wrap = FSReqBase::from_req(req);
557
6
  FSReqAfterScope after(req_wrap, req);
558
559
  MaybeLocal<Value> link;
560
  Local<Value> error;
561
562
6
  if (after.Proceed()) {
563
    link = StringBytes::Encode(req_wrap->env()->isolate(),
564
                               req->path,
565
                               req_wrap->encoding(),
566
5
                               &error);
567
5
    if (link.IsEmpty())
568
      req_wrap->Reject(error);
569
    else
570
10
      req_wrap->Resolve(link.ToLocalChecked());
571
6
  }
572
6
}
573
574
65
void AfterStringPtr(uv_fs_t* req) {
575
65
  FSReqBase* req_wrap = FSReqBase::from_req(req);
576
65
  FSReqAfterScope after(req_wrap, req);
577
578
  MaybeLocal<Value> link;
579
  Local<Value> error;
580
581
65
  if (after.Proceed()) {
582
    link = StringBytes::Encode(req_wrap->env()->isolate(),
583
                               static_cast<const char*>(req->ptr),
584
                               req_wrap->encoding(),
585
50
                               &error);
586
50
    if (link.IsEmpty())
587
      req_wrap->Reject(error);
588
    else
589
100
      req_wrap->Resolve(link.ToLocalChecked());
590
64
  }
591
64
}
592
593
148
void AfterScanDir(uv_fs_t* req) {
594
148
  FSReqBase* req_wrap = FSReqBase::from_req(req);
595
148
  FSReqAfterScope after(req_wrap, req);
596
597
148
  if (!after.Proceed()) {
598
3
    return;
599
  }
600
145
  Environment* env = req_wrap->env();
601
  Local<Value> error;
602
  int r;
603
290
  std::vector<Local<Value>> name_v;
604
605
6029
  for (int i = 0; ; i++) {
606
    uv_dirent_t ent;
607
608
6029
    r = uv_fs_scandir_next(req, &ent);
609
6029
    if (r == UV_EOF)
610
145
      break;
611
5884
    if (r != 0) {
612
      return req_wrap->Reject(UVException(
613
          env->isolate(), r, nullptr, req_wrap->syscall(), req->path));
614
    }
615
616
    MaybeLocal<Value> filename =
617
      StringBytes::Encode(env->isolate(),
618
          ent.name,
619
          req_wrap->encoding(),
620
5884
          &error);
621
5884
    if (filename.IsEmpty())
622
      return req_wrap->Reject(error);
623
624
5884
    name_v.push_back(filename.ToLocalChecked());
625
5884
  }
626
627
435
  req_wrap->Resolve(Array::New(env->isolate(), name_v.data(), name_v.size()));
628
}
629
630
7
void AfterScanDirWithTypes(uv_fs_t* req) {
631
7
  FSReqBase* req_wrap = FSReqBase::from_req(req);
632
7
  FSReqAfterScope after(req_wrap, req);
633
634
7
  if (!after.Proceed()) {
635
1
    return;
636
  }
637
638
6
  Environment* env = req_wrap->env();
639
6
  Isolate* isolate = env->isolate();
640
  Local<Value> error;
641
  int r;
642
643
12
  std::vector<Local<Value>> name_v;
644
12
  std::vector<Local<Value>> type_v;
645
646
22
  for (int i = 0; ; i++) {
647
    uv_dirent_t ent;
648
649
22
    r = uv_fs_scandir_next(req, &ent);
650
22
    if (r == UV_EOF)
651
6
      break;
652
16
    if (r != 0) {
653
      return req_wrap->Reject(
654
          UVException(isolate, r, nullptr, req_wrap->syscall(), req->path));
655
    }
656
657
    MaybeLocal<Value> filename =
658
      StringBytes::Encode(isolate,
659
          ent.name,
660
          req_wrap->encoding(),
661
16
          &error);
662
16
    if (filename.IsEmpty())
663
      return req_wrap->Reject(error);
664
665
16
    name_v.push_back(filename.ToLocalChecked());
666
16
    type_v.emplace_back(Integer::New(isolate, ent.type));
667
16
  }
668
669
6
  Local<Array> result = Array::New(isolate, 2);
670
6
  result->Set(env->context(),
671
              0,
672
              Array::New(isolate, name_v.data(),
673
24
              name_v.size())).Check();
674
6
  result->Set(env->context(),
675
              1,
676
              Array::New(isolate, type_v.data(),
677
24
              type_v.size())).Check();
678
18
  req_wrap->Resolve(result);
679
}
680
681
682
// This class is only used on sync fs calls.
683
// For async calls FSReqCallback is used.
684
class FSReqWrapSync {
685
 public:
686
531112
  FSReqWrapSync() = default;
687
531114
  ~FSReqWrapSync() { uv_fs_req_cleanup(&req); }
688
  uv_fs_t req;
689
690
  FSReqWrapSync(const FSReqWrapSync&) = delete;
691
  FSReqWrapSync& operator=(const FSReqWrapSync&) = delete;
692
};
693
694
// Returns nullptr if the operation fails from the start.
695
template <typename Func, typename... Args>
696
62034
inline FSReqBase* AsyncDestCall(Environment* env,
697
    FSReqBase* req_wrap,
698
    const FunctionCallbackInfo<Value>& args,
699
    const char* syscall, const char* dest, size_t len,
700
    enum encoding enc, uv_fs_cb after, Func fn, Args... fn_args) {
701







62034
  CHECK_NOT_NULL(req_wrap);
702
62034
  req_wrap->Init(syscall, dest, len, enc);
703
62034
  int err = req_wrap->Dispatch(fn, fn_args..., after);
704







62034
  if (err < 0) {
705
1
    uv_fs_t* uv_req = req_wrap->req();
706
1
    uv_req->result = err;
707
1
    uv_req->path = nullptr;
708
1
    after(uv_req);  // after may delete req_wrap if there is an error
709
1
    req_wrap = nullptr;
710
  } else {
711
62033
    req_wrap->SetReturnValue(args);
712
  }
713
714
62034
  return req_wrap;
715
}
716
717
// Returns nullptr if the operation fails from the start.
718
template <typename Func, typename... Args>
719
61571
inline FSReqBase* AsyncCall(Environment* env,
720
    FSReqBase* req_wrap,
721
    const FunctionCallbackInfo<Value>& args,
722
    const char* syscall, enum encoding enc,
723
    uv_fs_cb after, Func fn, Args... fn_args) {
724
  return AsyncDestCall(env, req_wrap, args,
725
                       syscall, nullptr, 0, enc,
726
61571
                       after, fn, fn_args...);
727
}
728
729
// Template counterpart of SYNC_CALL, except that it only puts
730
// the error number and the syscall in the context instead of
731
// creating an error in the C++ land.
732
// ctx must be checked using value->IsObject() before being passed.
733
template <typename Func, typename... Args>
734
531114
inline int SyncCall(Environment* env, Local<Value> ctx, FSReqWrapSync* req_wrap,
735
    const char* syscall, Func fn, Args... args) {
736
531114
  env->PrintSyncTrace();
737
531117
  int err = fn(env->event_loop(), &(req_wrap->req), args..., nullptr);
738







531114
  if (err < 0) {
739
8212
    Local<Context> context = env->context();
740
8212
    Local<Object> ctx_obj = ctx.As<Object>();
741
8212
    Isolate* isolate = env->isolate();
742
    ctx_obj->Set(context,
743
             env->errno_string(),
744
32848
             Integer::New(isolate, err)).Check();
745
    ctx_obj->Set(context,
746
             env->syscall_string(),
747
32848
             OneByteString(isolate, syscall)).Check();
748
  }
749
531114
  return err;
750
}
751
752
// TODO(addaleax): Currently, callers check the return value and assume
753
// that nullptr indicates a synchronous call, rather than a failure.
754
// Failure conditions should be disambiguated and handled appropriately.
755
593290
inline FSReqBase* GetReqWrap(Environment* env, Local<Value> value,
756
                             bool use_bigint = false) {
757
593290
  if (value->IsObject()) {
758
61806
    return Unwrap<FSReqBase>(value.As<Object>());
759
1062968
  } else if (value->StrictEquals(env->fs_use_promises_symbol())) {
760
369
    if (use_bigint) {
761
3
      return FSReqPromise<AliasedBigUint64Array>::New(env, use_bigint);
762
    } else {
763
366
      return FSReqPromise<AliasedFloat64Array>::New(env, use_bigint);
764
    }
765
  }
766
531115
  return nullptr;
767
}
768
769
7125
void Access(const FunctionCallbackInfo<Value>& args) {
770
7125
  Environment* env = Environment::GetCurrent(args);
771
7125
  Isolate* isolate = env->isolate();
772
7125
  HandleScope scope(isolate);
773
774
7125
  const int argc = args.Length();
775
7125
  CHECK_GE(argc, 2);
776
777
14250
  CHECK(args[1]->IsInt32());
778
21375
  int mode = args[1].As<Int32>()->Value();
779
780
14250
  BufferValue path(isolate, args[0]);
781
7125
  CHECK_NOT_NULL(*path);
782
783
7125
  FSReqBase* req_wrap_async = GetReqWrap(env, args[2]);
784
7125
  if (req_wrap_async != nullptr) {  // access(path, mode, req)
785
    AsyncCall(env, req_wrap_async, args, "access", UTF8, AfterNoArgs,
786
60
              uv_fs_access, *path, mode);
787
  } else {  // access(path, mode, undefined, ctx)
788
7065
    CHECK_EQ(argc, 4);
789
7065
    FSReqWrapSync req_wrap_sync;
790

7067
    FS_SYNC_TRACE_BEGIN(access);
791
14130
    SyncCall(env, args[3], &req_wrap_sync, "access", uv_fs_access, *path, mode);
792

7067
    FS_SYNC_TRACE_END(access);
793
7125
  }
794
7125
}
795
796
797
61931
void Close(const FunctionCallbackInfo<Value>& args) {
798
61931
  Environment* env = Environment::GetCurrent(args);
799
800
61931
  const int argc = args.Length();
801
61931
  CHECK_GE(argc, 2);
802
803
123862
  CHECK(args[0]->IsInt32());
804
185793
  int fd = args[0].As<Int32>()->Value();
805
806
61932
  FSReqBase* req_wrap_async = GetReqWrap(env, args[1]);
807
61931
  if (req_wrap_async != nullptr) {  // close(fd, req)
808
    AsyncCall(env, req_wrap_async, args, "close", UTF8, AfterNoArgs,
809
7644
              uv_fs_close, fd);
810
  } else {  // close(fd, undefined, ctx)
811
54287
    CHECK_EQ(argc, 3);
812
54287
    FSReqWrapSync req_wrap_sync;
813

54348
    FS_SYNC_TRACE_BEGIN(close);
814
54288
    SyncCall(env, args[2], &req_wrap_sync, "close", uv_fs_close, fd);
815

54348
    FS_SYNC_TRACE_END(close);
816
  }
817
61931
}
818
819
820
// Used to speed up module loading.  Returns the contents of the file as
821
// a string or undefined when the file cannot be opened or "main" is not found
822
// in the file.
823
17521
static void InternalModuleReadJSON(const FunctionCallbackInfo<Value>& args) {
824
17521
  Environment* env = Environment::GetCurrent(args);
825
17522
  Isolate* isolate = env->isolate();
826
17522
  uv_loop_t* loop = env->event_loop();
827
828
52563
  CHECK(args[0]->IsString());
829
17521
  node::Utf8Value path(isolate, args[0]);
830
831
17522
  if (strlen(*path) != path.length())
832
1
    return;  // Contains a nul byte.
833
834
  uv_fs_t open_req;
835
17521
  const int fd = uv_fs_open(loop, &open_req, *path, O_RDONLY, 0, nullptr);
836
17521
  uv_fs_req_cleanup(&open_req);
837
838
17521
  if (fd < 0) {
839
4324
    return;
840
  }
841
842
13197
  std::shared_ptr<void> defer_close(nullptr, [fd, loop] (...) {
843
    uv_fs_t close_req;
844
13197
    CHECK_EQ(0, uv_fs_close(loop, &close_req, fd, nullptr));
845
13197
    uv_fs_req_cleanup(&close_req);
846
33235
  });
847
848
13197
  const size_t kBlockSize = 32 << 10;
849
20038
  std::vector<char> chars;
850
13197
  int64_t offset = 0;
851
  ssize_t numchars;
852
13196
  do {
853
13197
    const size_t start = chars.size();
854
13197
    chars.resize(start + kBlockSize);
855
856
    uv_buf_t buf;
857
13197
    buf.base = &chars[start];
858
13197
    buf.len = kBlockSize;
859
860
    uv_fs_t read_req;
861
13197
    numchars = uv_fs_read(loop, &read_req, fd, &buf, 1, offset, nullptr);
862
13197
    uv_fs_req_cleanup(&read_req);
863
864
13197
    if (numchars < 0)
865
1
      return;
866
867
13196
    offset += numchars;
868
  } while (static_cast<size_t>(numchars) == kBlockSize);
869
870
13196
  size_t start = 0;
871

13196
  if (offset >= 3 && 0 == memcmp(&chars[0], "\xEF\xBB\xBF", 3)) {
872
1
    start = 3;  // Skip UTF-8 BOM.
873
  }
874
875
13196
  const size_t size = offset - start;
876

32745
  if (size == 0 || (
877
19549
    size == SearchString(&chars[start], size, "\"main\"") &&
878
6355
    size == SearchString(&chars[start], size, "\"exports\""))) {
879
6355
    return;
880
  } else {
881
    Local<String> chars_string =
882
        String::NewFromUtf8(isolate,
883
6841
                            &chars[start],
884
                            v8::NewStringType::kNormal,
885
20523
                            size).ToLocalChecked();
886
13682
    args.GetReturnValue().Set(chars_string);
887
6841
  }
888
}
889
890
// Used to speed up module loading.  Returns 0 if the path refers to
891
// a file, 1 when it's a directory or < 0 on error (usually -ENOENT.)
892
// The speedup comes from not creating thousands of Stat and Error objects.
893
174639
static void InternalModuleStat(const FunctionCallbackInfo<Value>& args) {
894
174639
  Environment* env = Environment::GetCurrent(args);
895
896
523932
  CHECK(args[0]->IsString());
897
174644
  node::Utf8Value path(env->isolate(), args[0]);
898
899
  uv_fs_t req;
900
174644
  int rc = uv_fs_stat(env->event_loop(), &req, *path, nullptr);
901
174641
  if (rc == 0) {
902
72610
    const uv_stat_t* const s = static_cast<const uv_stat_t*>(req.ptr);
903
72610
    rc = !!(s->st_mode & S_IFDIR);
904
  }
905
174641
  uv_fs_req_cleanup(&req);
906
907
349284
  args.GetReturnValue().Set(rc);
908
174642
}
909
910
34870
static void Stat(const FunctionCallbackInfo<Value>& args) {
911
34870
  Environment* env = Environment::GetCurrent(args);
912
913
34870
  const int argc = args.Length();
914
34870
  CHECK_GE(argc, 2);
915
916
34870
  BufferValue path(env->isolate(), args[0]);
917
34870
  CHECK_NOT_NULL(*path);
918
919
69740
  bool use_bigint = args[1]->IsTrue();
920
69740
  FSReqBase* req_wrap_async = GetReqWrap(env, args[2], use_bigint);
921
34870
  if (req_wrap_async != nullptr) {  // stat(path, use_bigint, req)
922
    AsyncCall(env, req_wrap_async, args, "stat", UTF8, AfterStat,
923
2124
              uv_fs_stat, *path);
924
  } else {  // stat(path, use_bigint, undefined, ctx)
925
32746
    CHECK_EQ(argc, 4);
926
32746
    FSReqWrapSync req_wrap_sync;
927

32748
    FS_SYNC_TRACE_BEGIN(stat);
928
65492
    int err = SyncCall(env, args[3], &req_wrap_sync, "stat", uv_fs_stat, *path);
929

32748
    FS_SYNC_TRACE_END(stat);
930
32746
    if (err != 0) {
931
34876
      return;  // error info is in ctx
932
    }
933
934
    Local<Value> arr = FillGlobalStatsArray(env, use_bigint,
935
32740
        static_cast<const uv_stat_t*>(req_wrap_sync.req.ptr));
936

65480
    args.GetReturnValue().Set(arr);
937
34864
  }
938
}
939
940
120877
static void LStat(const FunctionCallbackInfo<Value>& args) {
941
120877
  Environment* env = Environment::GetCurrent(args);
942
943
120877
  const int argc = args.Length();
944
120877
  CHECK_GE(argc, 3);
945
946
120877
  BufferValue path(env->isolate(), args[0]);
947
120878
  CHECK_NOT_NULL(*path);
948
949
241756
  bool use_bigint = args[1]->IsTrue();
950
241756
  FSReqBase* req_wrap_async = GetReqWrap(env, args[2], use_bigint);
951
120876
  if (req_wrap_async != nullptr) {  // lstat(path, use_bigint, req)
952
    AsyncCall(env, req_wrap_async, args, "lstat", UTF8, AfterStat,
953
5349
              uv_fs_lstat, *path);
954
  } else {  // lstat(path, use_bigint, undefined, ctx)
955
115527
    CHECK_EQ(argc, 4);
956
115527
    FSReqWrapSync req_wrap_sync;
957

115561
    FS_SYNC_TRACE_BEGIN(lstat);
958
    int err = SyncCall(env, args[3], &req_wrap_sync, "lstat", uv_fs_lstat,
959
231056
                       *path);
960

115562
    FS_SYNC_TRACE_END(lstat);
961
115528
    if (err != 0) {
962
121141
      return;  // error info is in ctx
963
    }
964
965
    Local<Value> arr = FillGlobalStatsArray(env, use_bigint,
966
115265
        static_cast<const uv_stat_t*>(req_wrap_sync.req.ptr));
967

230532
    args.GetReturnValue().Set(arr);
968
120615
  }
969
}
970
971
50491
static void FStat(const FunctionCallbackInfo<Value>& args) {
972
50491
  Environment* env = Environment::GetCurrent(args);
973
974
50492
  const int argc = args.Length();
975
50492
  CHECK_GE(argc, 2);
976
977
100984
  CHECK(args[0]->IsInt32());
978
151476
  int fd = args[0].As<Int32>()->Value();
979
980
100984
  bool use_bigint = args[1]->IsTrue();
981
100982
  FSReqBase* req_wrap_async = GetReqWrap(env, args[2], use_bigint);
982
50491
  if (req_wrap_async != nullptr) {  // fstat(fd, use_bigint, req)
983
    AsyncCall(env, req_wrap_async, args, "fstat", UTF8, AfterStat,
984
2783
              uv_fs_fstat, fd);
985
  } else {  // fstat(fd, use_bigint, undefined, ctx)
986
47708
    CHECK_EQ(argc, 4);
987
47708
    FSReqWrapSync req_wrap_sync;
988

47719
    FS_SYNC_TRACE_BEGIN(fstat);
989
47709
    int err = SyncCall(env, args[3], &req_wrap_sync, "fstat", uv_fs_fstat, fd);
990

47718
    FS_SYNC_TRACE_END(fstat);
991
47709
    if (err != 0) {
992
50509
      return;  // error info is in ctx
993
    }
994
995
    Local<Value> arr = FillGlobalStatsArray(env, use_bigint,
996
47692
        static_cast<const uv_stat_t*>(req_wrap_sync.req.ptr));
997
95384
    args.GetReturnValue().Set(arr);
998
  }
999
}
1000
1001
102
static void Symlink(const FunctionCallbackInfo<Value>& args) {
1002
102
  Environment* env = Environment::GetCurrent(args);
1003
102
  Isolate* isolate = env->isolate();
1004
1005
102
  int argc = args.Length();
1006
102
  CHECK_GE(argc, 4);
1007
1008
102
  BufferValue target(isolate, args[0]);
1009
102
  CHECK_NOT_NULL(*target);
1010
204
  BufferValue path(isolate, args[1]);
1011
102
  CHECK_NOT_NULL(*path);
1012
1013
204
  CHECK(args[2]->IsInt32());
1014
306
  int flags = args[2].As<Int32>()->Value();
1015
1016
102
  FSReqBase* req_wrap_async = GetReqWrap(env, args[3]);
1017
102
  if (req_wrap_async != nullptr) {  // symlink(target, path, flags, req)
1018
20
    AsyncDestCall(env, req_wrap_async, args, "symlink", *path, path.length(),
1019
40
                  UTF8, AfterNoArgs, uv_fs_symlink, *target, *path, flags);
1020
  } else {  // symlink(target, path, flags, undefinec, ctx)
1021
82
    CHECK_EQ(argc, 5);
1022
82
    FSReqWrapSync req_wrap_sync;
1023

86
    FS_SYNC_TRACE_BEGIN(symlink);
1024
    SyncCall(env, args[4], &req_wrap_sync, "symlink",
1025
164
             uv_fs_symlink, *target, *path, flags);
1026

86
    FS_SYNC_TRACE_END(symlink);
1027
102
  }
1028
102
}
1029
1030
205
static void Link(const FunctionCallbackInfo<Value>& args) {
1031
205
  Environment* env = Environment::GetCurrent(args);
1032
205
  Isolate* isolate = env->isolate();
1033
1034
205
  int argc = args.Length();
1035
205
  CHECK_GE(argc, 3);
1036
1037
205
  BufferValue src(isolate, args[0]);
1038
205
  CHECK_NOT_NULL(*src);
1039
1040
410
  BufferValue dest(isolate, args[1]);
1041
205
  CHECK_NOT_NULL(*dest);
1042
1043
205
  FSReqBase* req_wrap_async = GetReqWrap(env, args[2]);
1044
205
  if (req_wrap_async != nullptr) {  // link(src, dest, req)
1045
200
    AsyncDestCall(env, req_wrap_async, args, "link", *dest, dest.length(), UTF8,
1046
400
                  AfterNoArgs, uv_fs_link, *src, *dest);
1047
  } else {  // link(src, dest)
1048
5
    CHECK_EQ(argc, 4);
1049
5
    FSReqWrapSync req_wrap_sync;
1050

11
    FS_SYNC_TRACE_BEGIN(link);
1051
    SyncCall(env, args[3], &req_wrap_sync, "link",
1052
10
             uv_fs_link, *src, *dest);
1053

11
    FS_SYNC_TRACE_END(link);
1054
205
  }
1055
205
}
1056
1057
89
static void ReadLink(const FunctionCallbackInfo<Value>& args) {
1058
89
  Environment* env = Environment::GetCurrent(args);
1059
89
  Isolate* isolate = env->isolate();
1060
1061
89
  int argc = args.Length();
1062
89
  CHECK_GE(argc, 3);
1063
1064
89
  BufferValue path(isolate, args[0]);
1065
89
  CHECK_NOT_NULL(*path);
1066
1067
89
  const enum encoding encoding = ParseEncoding(isolate, args[1], UTF8);
1068
1069
89
  FSReqBase* req_wrap_async = GetReqWrap(env, args[2]);
1070
89
  if (req_wrap_async != nullptr) {  // readlink(path, encoding, req)
1071
    AsyncCall(env, req_wrap_async, args, "readlink", encoding, AfterStringPtr,
1072
43
              uv_fs_readlink, *path);
1073
  } else {
1074
46
    CHECK_EQ(argc, 4);
1075
46
    FSReqWrapSync req_wrap_sync;
1076

48
    FS_SYNC_TRACE_BEGIN(readlink);
1077
    int err = SyncCall(env, args[3], &req_wrap_sync, "readlink",
1078
92
                       uv_fs_readlink, *path);
1079

48
    FS_SYNC_TRACE_END(readlink);
1080
46
    if (err < 0) {
1081
1
      return;  // syscall failed, no need to continue, error info is in ctx
1082
    }
1083
45
    const char* link_path = static_cast<const char*>(req_wrap_sync.req.ptr);
1084
1085
    Local<Value> error;
1086
    MaybeLocal<Value> rc = StringBytes::Encode(isolate,
1087
                                               link_path,
1088
                                               encoding,
1089
45
                                               &error);
1090
45
    if (rc.IsEmpty()) {
1091
      Local<Object> ctx = args[3].As<Object>();
1092
      ctx->Set(env->context(), env->error_string(), error).Check();
1093
      return;
1094
    }
1095
1096

90
    args.GetReturnValue().Set(rc.ToLocalChecked());
1097
88
  }
1098
}
1099
1100
233
static void Rename(const FunctionCallbackInfo<Value>& args) {
1101
233
  Environment* env = Environment::GetCurrent(args);
1102
233
  Isolate* isolate = env->isolate();
1103
1104
233
  int argc = args.Length();
1105
233
  CHECK_GE(argc, 3);
1106
1107
233
  BufferValue old_path(isolate, args[0]);
1108
233
  CHECK_NOT_NULL(*old_path);
1109
466
  BufferValue new_path(isolate, args[1]);
1110
233
  CHECK_NOT_NULL(*new_path);
1111
1112
233
  FSReqBase* req_wrap_async = GetReqWrap(env, args[2]);
1113
233
  if (req_wrap_async != nullptr) {
1114
228
    AsyncDestCall(env, req_wrap_async, args, "rename", *new_path,
1115
                  new_path.length(), UTF8, AfterNoArgs, uv_fs_rename,
1116
456
                  *old_path, *new_path);
1117
  } else {
1118
5
    CHECK_EQ(argc, 4);
1119
5
    FSReqWrapSync req_wrap_sync;
1120

7
    FS_SYNC_TRACE_BEGIN(rename);
1121
    SyncCall(env, args[3], &req_wrap_sync, "rename", uv_fs_rename,
1122
10
             *old_path, *new_path);
1123

7
    FS_SYNC_TRACE_END(rename);
1124
233
  }
1125
233
}
1126
1127
48
static void FTruncate(const FunctionCallbackInfo<Value>& args) {
1128
48
  Environment* env = Environment::GetCurrent(args);
1129
1130
48
  const int argc = args.Length();
1131
48
  CHECK_GE(argc, 3);
1132
1133
96
  CHECK(args[0]->IsInt32());
1134
144
  const int fd = args[0].As<Int32>()->Value();
1135
1136
48
  CHECK(IsSafeJsInt(args[1]));
1137
144
  const int64_t len = args[1].As<Integer>()->Value();
1138
1139
48
  FSReqBase* req_wrap_async = GetReqWrap(env, args[2]);
1140
48
  if (req_wrap_async != nullptr) {
1141
    AsyncCall(env, req_wrap_async, args, "ftruncate", UTF8, AfterNoArgs,
1142
34
              uv_fs_ftruncate, fd, len);
1143
  } else {
1144
14
    CHECK_EQ(argc, 4);
1145
14
    FSReqWrapSync req_wrap_sync;
1146

16
    FS_SYNC_TRACE_BEGIN(ftruncate);
1147
    SyncCall(env, args[3], &req_wrap_sync, "ftruncate", uv_fs_ftruncate, fd,
1148
14
             len);
1149

16
    FS_SYNC_TRACE_END(ftruncate);
1150
  }
1151
48
}
1152
1153
7
static void Fdatasync(const FunctionCallbackInfo<Value>& args) {
1154
7
  Environment* env = Environment::GetCurrent(args);
1155
1156
7
  const int argc = args.Length();
1157
7
  CHECK_GE(argc, 2);
1158
1159
14
  CHECK(args[0]->IsInt32());
1160
21
  const int fd = args[0].As<Int32>()->Value();
1161
1162
7
  FSReqBase* req_wrap_async = GetReqWrap(env, args[1]);
1163
7
  if (req_wrap_async != nullptr) {
1164
    AsyncCall(env, req_wrap_async, args, "fdatasync", UTF8, AfterNoArgs,
1165
4
              uv_fs_fdatasync, fd);
1166
  } else {
1167
3
    CHECK_EQ(argc, 3);
1168
3
    FSReqWrapSync req_wrap_sync;
1169

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

5
    FS_SYNC_TRACE_END(fdatasync);
1172
  }
1173
7
}
1174
1175
23
static void Fsync(const FunctionCallbackInfo<Value>& args) {
1176
23
  Environment* env = Environment::GetCurrent(args);
1177
1178
23
  const int argc = args.Length();
1179
23
  CHECK_GE(argc, 2);
1180
1181
46
  CHECK(args[0]->IsInt32());
1182
69
  const int fd = args[0].As<Int32>()->Value();
1183
1184
23
  FSReqBase* req_wrap_async = GetReqWrap(env, args[1]);
1185
23
  if (req_wrap_async != nullptr) {
1186
    AsyncCall(env, req_wrap_async, args, "fsync", UTF8, AfterNoArgs,
1187
6
              uv_fs_fsync, fd);
1188
  } else {
1189
17
    CHECK_EQ(argc, 3);
1190
17
    FSReqWrapSync req_wrap_sync;
1191

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

19
    FS_SYNC_TRACE_END(fsync);
1194
  }
1195
23
}
1196
1197
3763
static void Unlink(const FunctionCallbackInfo<Value>& args) {
1198
3763
  Environment* env = Environment::GetCurrent(args);
1199
1200
3763
  const int argc = args.Length();
1201
3763
  CHECK_GE(argc, 2);
1202
1203
3763
  BufferValue path(env->isolate(), args[0]);
1204
3763
  CHECK_NOT_NULL(*path);
1205
1206
3763
  FSReqBase* req_wrap_async = GetReqWrap(env, args[1]);
1207
3763
  if (req_wrap_async != nullptr) {
1208
    AsyncCall(env, req_wrap_async, args, "unlink", UTF8, AfterNoArgs,
1209
206
              uv_fs_unlink, *path);
1210
  } else {
1211
3557
    CHECK_EQ(argc, 3);
1212
3557
    FSReqWrapSync req_wrap_sync;
1213

3617
    FS_SYNC_TRACE_BEGIN(unlink);
1214
7114
    SyncCall(env, args[2], &req_wrap_sync, "unlink", uv_fs_unlink, *path);
1215

3617
    FS_SYNC_TRACE_END(unlink);
1216
3763
  }
1217
3763
}
1218
1219
3980
static void RMDir(const FunctionCallbackInfo<Value>& args) {
1220
3980
  Environment* env = Environment::GetCurrent(args);
1221
1222
3980
  const int argc = args.Length();
1223
3980
  CHECK_GE(argc, 2);
1224
1225
3980
  BufferValue path(env->isolate(), args[0]);
1226
3980
  CHECK_NOT_NULL(*path);
1227
1228
3980
  FSReqBase* req_wrap_async = GetReqWrap(env, args[1]);  // rmdir(path, req)
1229
3980
  if (req_wrap_async != nullptr) {
1230
    AsyncCall(env, req_wrap_async, args, "rmdir", UTF8, AfterNoArgs,
1231
132
              uv_fs_rmdir, *path);
1232
  } else {  // rmdir(path, undefined, ctx)
1233
3848
    CHECK_EQ(argc, 3);
1234
3848
    FSReqWrapSync req_wrap_sync;
1235

3854
    FS_SYNC_TRACE_BEGIN(rmdir);
1236
    SyncCall(env, args[2], &req_wrap_sync, "rmdir",
1237
7696
             uv_fs_rmdir, *path);
1238

3854
    FS_SYNC_TRACE_END(rmdir);
1239
3980
  }
1240
3980
}
1241
1242
4997
int MKDirpSync(uv_loop_t* loop,
1243
               uv_fs_t* req,
1244
               const std::string& path,
1245
               int mode,
1246
               uv_fs_cb cb) {
1247
4997
  FSContinuationData continuation_data(req, mode, cb);
1248
4997
  continuation_data.PushPath(std::move(path));
1249
1250
4997
  while (continuation_data.paths.size() > 0) {
1251
5047
    std::string next_path = continuation_data.PopPath();
1252
5047
    int err = uv_fs_mkdir(loop, req, next_path.c_str(), mode, nullptr);
1253
    while (true) {
1254

5048
      switch (err) {
1255
        case 0:
1256
48
          if (continuation_data.paths.size() == 0) {
1257
24
            return 0;
1258
          }
1259
24
          break;
1260
        case UV_ENOENT: {
1261
          std::string dirname = next_path.substr(0,
1262
26
                                        next_path.find_last_of(kPathSeparator));
1263
26
          if (dirname != next_path) {
1264
25
            continuation_data.PushPath(std::move(next_path));
1265
25
            continuation_data.PushPath(std::move(dirname));
1266
1
          } else if (continuation_data.paths.size() == 0) {
1267
1
            err = UV_EEXIST;
1268
1
            continue;
1269
          }
1270
25
          break;
1271
        }
1272
        case UV_EPERM: {
1273
          return err;
1274
        }
1275
        default:
1276
4974
          uv_fs_req_cleanup(req);
1277
4974
          int orig_err = err;
1278
4974
          err = uv_fs_stat(loop, req, next_path.c_str(), nullptr);
1279

4974
          if (err == 0 && !S_ISDIR(req->statbuf.st_mode)) {
1280
1
            uv_fs_req_cleanup(req);
1281

1
            if (orig_err == UV_EEXIST && continuation_data.paths.size() > 0) {
1282
              return UV_ENOTDIR;
1283
            }
1284
1
            return UV_EEXIST;
1285
          }
1286
4973
          if (err < 0) return err;
1287
4971
          break;
1288
      }
1289
5020
      break;
1290
    }
1291
5020
    uv_fs_req_cleanup(req);
1292
5020
  }
1293
1294
4970
  return 0;
1295
}
1296
1297
22
int MKDirpAsync(uv_loop_t* loop,
1298
                uv_fs_t* req,
1299
                const char* path,
1300
                int mode,
1301
                uv_fs_cb cb) {
1302
22
  FSReqBase* req_wrap = FSReqBase::from_req(req);
1303
  // on the first iteration of algorithm, stash state information.
1304
22
  if (req_wrap->continuation_data == nullptr) {
1305
20
    req_wrap->continuation_data =
1306
10
        std::make_unique<FSContinuationData>(req, mode, cb);
1307
10
    req_wrap->continuation_data->PushPath(std::move(path));
1308
  }
1309
1310
  // on each iteration of algorithm, mkdir directory on top of stack.
1311
22
  std::string next_path = req_wrap->continuation_data->PopPath();
1312
  int err = uv_fs_mkdir(loop, req, next_path.c_str(), mode,
1313
66
                        uv_fs_callback_t{[](uv_fs_t* req) {
1314
22
    FSReqBase* req_wrap = FSReqBase::from_req(req);
1315
22
    Environment* env = req_wrap->env();
1316
22
    uv_loop_t* loop = env->event_loop();
1317
22
    std::string path = req->path;
1318
22
    int err = req->result;
1319
1320
    while (true) {
1321

23
      switch (err) {
1322
        case 0: {
1323
11
          if (req_wrap->continuation_data->paths.size() == 0) {
1324
5
            req_wrap->continuation_data->Done(0);
1325
          } else {
1326
6
            uv_fs_req_cleanup(req);
1327
            MKDirpAsync(loop, req, path.c_str(),
1328
6
                        req_wrap->continuation_data->mode, nullptr);
1329
          }
1330
11
          break;
1331
        }
1332
        case UV_ENOENT: {
1333
          std::string dirname = path.substr(0,
1334
7
                                            path.find_last_of(kPathSeparator));
1335
7
          if (dirname != path) {
1336
6
            req_wrap->continuation_data->PushPath(std::move(path));
1337
6
            req_wrap->continuation_data->PushPath(std::move(dirname));
1338
1
          } else if (req_wrap->continuation_data->paths.size() == 0) {
1339
1
            err = UV_EEXIST;
1340
1
            continue;
1341
          }
1342
6
          uv_fs_req_cleanup(req);
1343
          MKDirpAsync(loop, req, path.c_str(),
1344
6
                      req_wrap->continuation_data->mode, nullptr);
1345
6
          break;
1346
        }
1347
        case UV_EPERM: {
1348
          req_wrap->continuation_data->Done(err);
1349
          break;
1350
        }
1351
        default:
1352
5
          uv_fs_req_cleanup(req);
1353
          // Stash err for use in the callback.
1354
5
          req->data = reinterpret_cast<void*>(static_cast<intptr_t>(err));
1355
          int err = uv_fs_stat(loop, req, path.c_str(),
1356
15
                               uv_fs_callback_t{[](uv_fs_t* req) {
1357
5
            FSReqBase* req_wrap = FSReqBase::from_req(req);
1358
5
            int err = req->result;
1359

8
            if (reinterpret_cast<intptr_t>(req->data) == UV_EEXIST &&
1360
3
                  req_wrap->continuation_data->paths.size() > 0) {
1361
              if (err == 0 && S_ISDIR(req->statbuf.st_mode)) {
1362
                Environment* env = req_wrap->env();
1363
                uv_loop_t* loop = env->event_loop();
1364
                std::string path = req->path;
1365
                uv_fs_req_cleanup(req);
1366
                MKDirpAsync(loop, req, path.c_str(),
1367
                            req_wrap->continuation_data->mode, nullptr);
1368
5
                return;
1369
              }
1370
              err = UV_ENOTDIR;
1371
            }
1372
            // verify that the path pointed to is actually a directory.
1373

5
            if (err == 0 && !S_ISDIR(req->statbuf.st_mode)) err = UV_EEXIST;
1374
5
            uv_fs_req_cleanup(req);
1375
5
            req_wrap->continuation_data->Done(err);
1376
15
          }});
1377
5
          if (err < 0) req_wrap->continuation_data->Done(err);
1378
5
          break;
1379
      }
1380
22
      break;
1381
    }
1382
88
  }});
1383
1384
22
  return err;
1385
}
1386
1387
4068
static void MKDir(const FunctionCallbackInfo<Value>& args) {
1388
4068
  Environment* env = Environment::GetCurrent(args);
1389
1390
4068
  const int argc = args.Length();
1391
4068
  CHECK_GE(argc, 4);
1392
1393
4068
  BufferValue path(env->isolate(), args[0]);
1394
4068
  CHECK_NOT_NULL(*path);
1395
1396
8136
  CHECK(args[1]->IsInt32());
1397
12204
  const int mode = args[1].As<Int32>()->Value();
1398
1399
8136
  CHECK(args[2]->IsBoolean());
1400
8136
  bool mkdirp = args[2]->IsTrue();
1401
1402
4068
  FSReqBase* req_wrap_async = GetReqWrap(env, args[3]);
1403
4068
  if (req_wrap_async != nullptr) {  // mkdir(path, mode, req)
1404
    AsyncCall(env, req_wrap_async, args, "mkdir", UTF8,
1405
1931
              AfterNoArgs, mkdirp ? MKDirpAsync : uv_fs_mkdir, *path, mode);
1406
  } else {  // mkdir(path, mode, undefined, ctx)
1407
2137
    CHECK_EQ(argc, 5);
1408
2137
    FSReqWrapSync req_wrap_sync;
1409

2141
    FS_SYNC_TRACE_BEGIN(mkdir);
1410
2137
    if (mkdirp) {
1411
      SyncCall(env, args[4], &req_wrap_sync, "mkdir",
1412
22
               MKDirpSync, *path, mode);
1413
    } else {
1414
      SyncCall(env, args[4], &req_wrap_sync, "mkdir",
1415
4252
               uv_fs_mkdir, *path, mode);
1416
    }
1417

2141
    FS_SYNC_TRACE_END(mkdir);
1418
4068
  }
1419
4068
}
1420
1421
42
static void RealPath(const FunctionCallbackInfo<Value>& args) {
1422
42
  Environment* env = Environment::GetCurrent(args);
1423
42
  Isolate* isolate = env->isolate();
1424
1425
42
  const int argc = args.Length();
1426
42
  CHECK_GE(argc, 3);
1427
1428
42
  BufferValue path(isolate, args[0]);
1429
42
  CHECK_NOT_NULL(*path);
1430
1431
42
  const enum encoding encoding = ParseEncoding(isolate, args[1], UTF8);
1432
1433
42
  FSReqBase* req_wrap_async = GetReqWrap(env, args[2]);
1434
42
  if (req_wrap_async != nullptr) {  // realpath(path, encoding, req)
1435
    AsyncCall(env, req_wrap_async, args, "realpath", encoding, AfterStringPtr,
1436
22
              uv_fs_realpath, *path);
1437
  } else {  // realpath(path, encoding, undefined, ctx)
1438
20
    CHECK_EQ(argc, 4);
1439
20
    FSReqWrapSync req_wrap_sync;
1440

22
    FS_SYNC_TRACE_BEGIN(realpath);
1441
    int err = SyncCall(env, args[3], &req_wrap_sync, "realpath",
1442
40
                       uv_fs_realpath, *path);
1443

22
    FS_SYNC_TRACE_END(realpath);
1444
20
    if (err < 0) {
1445
2
      return;  // syscall failed, no need to continue, error info is in ctx
1446
    }
1447
1448
18
    const char* link_path = static_cast<const char*>(req_wrap_sync.req.ptr);
1449
1450
    Local<Value> error;
1451
    MaybeLocal<Value> rc = StringBytes::Encode(isolate,
1452
                                               link_path,
1453
                                               encoding,
1454
18
                                               &error);
1455
18
    if (rc.IsEmpty()) {
1456
      Local<Object> ctx = args[3].As<Object>();
1457
      ctx->Set(env->context(), env->error_string(), error).Check();
1458
      return;
1459
    }
1460
1461

36
    args.GetReturnValue().Set(rc.ToLocalChecked());
1462
40
  }
1463
}
1464
1465
16101
static void ReadDir(const FunctionCallbackInfo<Value>& args) {
1466
16101
  Environment* env = Environment::GetCurrent(args);
1467
16101
  Isolate* isolate = env->isolate();
1468
1469
16101
  const int argc = args.Length();
1470
16101
  CHECK_GE(argc, 3);
1471
1472
16101
  BufferValue path(isolate, args[0]);
1473
16101
  CHECK_NOT_NULL(*path);
1474
1475
16101
  const enum encoding encoding = ParseEncoding(isolate, args[1], UTF8);
1476
1477
32202
  bool with_types = args[2]->IsTrue();
1478
1479
16101
  FSReqBase* req_wrap_async = GetReqWrap(env, args[3]);
1480
16101
  if (req_wrap_async != nullptr) {  // readdir(path, encoding, withTypes, req)
1481
155
    if (with_types) {
1482
      AsyncCall(env, req_wrap_async, args, "scandir", encoding,
1483
7
                AfterScanDirWithTypes, uv_fs_scandir, *path, 0 /*flags*/);
1484
    } else {
1485
      AsyncCall(env, req_wrap_async, args, "scandir", encoding,
1486
148
                AfterScanDir, uv_fs_scandir, *path, 0 /*flags*/);
1487
    }
1488
  } else {  // readdir(path, encoding, withTypes, undefined, ctx)
1489
15946
    CHECK_EQ(argc, 5);
1490
15946
    FSReqWrapSync req_wrap_sync;
1491

15948
    FS_SYNC_TRACE_BEGIN(readdir);
1492
    int err = SyncCall(env, args[4], &req_wrap_sync, "scandir",
1493
31892
                       uv_fs_scandir, *path, 0 /*flags*/);
1494

15948
    FS_SYNC_TRACE_END(readdir);
1495
15946
    if (err < 0) {
1496
49
      return;  // syscall failed, no need to continue, error info is in ctx
1497
    }
1498
1499
15897
    CHECK_GE(req_wrap_sync.req.result, 0);
1500
    int r;
1501
31794
    std::vector<Local<Value>> name_v;
1502
31794
    std::vector<Local<Value>> type_v;
1503
1504
686906
    for (int i = 0; ; i++) {
1505
      uv_dirent_t ent;
1506
1507
686906
      r = uv_fs_scandir_next(&(req_wrap_sync.req), &ent);
1508
686906
      if (r == UV_EOF)
1509
15897
        break;
1510
671009
      if (r != 0) {
1511
        Local<Object> ctx = args[4].As<Object>();
1512
        ctx->Set(env->context(), env->errno_string(),
1513
                 Integer::New(isolate, r)).Check();
1514
        ctx->Set(env->context(), env->syscall_string(),
1515
                 OneByteString(isolate, "readdir")).Check();
1516
        return;
1517
      }
1518
1519
      Local<Value> error;
1520
      MaybeLocal<Value> filename = StringBytes::Encode(isolate,
1521
                                                       ent.name,
1522
                                                       encoding,
1523
671009
                                                       &error);
1524
1525
671009
      if (filename.IsEmpty()) {
1526
        Local<Object> ctx = args[4].As<Object>();
1527
        ctx->Set(env->context(), env->error_string(), error).Check();
1528
        return;
1529
      }
1530
1531
671009
      name_v.push_back(filename.ToLocalChecked());
1532
1533
671009
      if (with_types) {
1534
368
        type_v.emplace_back(Integer::New(isolate, ent.type));
1535
      }
1536
671009
    }
1537
1538
1539
15897
    Local<Array> names = Array::New(isolate, name_v.data(), name_v.size());
1540
15897
    if (with_types) {
1541
10
      Local<Array> result = Array::New(isolate, 2);
1542
30
      result->Set(env->context(), 0, names).Check();
1543
10
      result->Set(env->context(),
1544
                  1,
1545
                  Array::New(isolate, type_v.data(),
1546
40
                             type_v.size())).Check();
1547
20
      args.GetReturnValue().Set(result);
1548
    } else {
1549
31774
      args.GetReturnValue().Set(names);
1550
15897
    }
1551
16052
  }
1552
}
1553
1554
63066
static void Open(const FunctionCallbackInfo<Value>& args) {
1555
63066
  Environment* env = Environment::GetCurrent(args);
1556
1557
63066
  const int argc = args.Length();
1558
63066
  CHECK_GE(argc, 3);
1559
1560
63066
  BufferValue path(env->isolate(), args[0]);
1561
63066
  CHECK_NOT_NULL(*path);
1562
1563
126134
  CHECK(args[1]->IsInt32());
1564
189201
  const int flags = args[1].As<Int32>()->Value();
1565
1566
126134
  CHECK(args[2]->IsInt32());
1567
189201
  const int mode = args[2].As<Int32>()->Value();
1568
1569
63066
  FSReqBase* req_wrap_async = GetReqWrap(env, args[3]);
1570
63066
  if (req_wrap_async != nullptr) {  // open(path, flags, mode, req)
1571
    AsyncCall(env, req_wrap_async, args, "open", UTF8, AfterInteger,
1572
8050
              uv_fs_open, *path, flags, mode);
1573
  } else {  // open(path, flags, mode, undefined, ctx)
1574
55016
    CHECK_EQ(argc, 5);
1575
55016
    FSReqWrapSync req_wrap_sync;
1576

55089
    FS_SYNC_TRACE_BEGIN(open);
1577
    int result = SyncCall(env, args[4], &req_wrap_sync, "open",
1578
110033
                          uv_fs_open, *path, flags, mode);
1579

55088
    FS_SYNC_TRACE_END(open);
1580
110032
    args.GetReturnValue().Set(result);
1581
63066
  }
1582
63067
}
1583
1584
68
static void OpenFileHandle(const FunctionCallbackInfo<Value>& args) {
1585
68
  Environment* env = Environment::GetCurrent(args);
1586
68
  Isolate* isolate = env->isolate();
1587
1588
68
  const int argc = args.Length();
1589
68
  CHECK_GE(argc, 3);
1590
1591
68
  BufferValue path(isolate, args[0]);
1592
68
  CHECK_NOT_NULL(*path);
1593
1594
136
  CHECK(args[1]->IsInt32());
1595
204
  const int flags = args[1].As<Int32>()->Value();
1596
1597
136
  CHECK(args[2]->IsInt32());
1598
204
  const int mode = args[2].As<Int32>()->Value();
1599
1600
68
  FSReqBase* req_wrap_async = GetReqWrap(env, args[3]);
1601
68
  if (req_wrap_async != nullptr) {  // openFileHandle(path, flags, mode, req)
1602
    AsyncCall(env, req_wrap_async, args, "open", UTF8, AfterOpenFileHandle,
1603
67
              uv_fs_open, *path, flags, mode);
1604
  } else {  // openFileHandle(path, flags, mode, undefined, ctx)
1605
1
    CHECK_EQ(argc, 5);
1606
1
    FSReqWrapSync req_wrap_sync;
1607

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

1
    FS_SYNC_TRACE_END(open);
1611
1
    if (result < 0) {
1612
      return;  // syscall failed, no need to continue, error info is in ctx
1613
    }
1614
1
    FileHandle* fd = FileHandle::New(env, result);
1615
1
    if (fd == nullptr) return;
1616

3
    args.GetReturnValue().Set(fd->object());
1617
68
  }
1618
}
1619
1620
35
static void CopyFile(const FunctionCallbackInfo<Value>& args) {
1621
35
  Environment* env = Environment::GetCurrent(args);
1622
35
  Isolate* isolate = env->isolate();
1623
1624
35
  const int argc = args.Length();
1625
35
  CHECK_GE(argc, 3);
1626
1627
35
  BufferValue src(isolate, args[0]);
1628
35
  CHECK_NOT_NULL(*src);
1629
1630
70
  BufferValue dest(isolate, args[1]);
1631
35
  CHECK_NOT_NULL(*dest);
1632
1633
70
  CHECK(args[2]->IsInt32());
1634
105
  const int flags = args[2].As<Int32>()->Value();
1635
1636
35
  FSReqBase* req_wrap_async = GetReqWrap(env, args[3]);
1637
35
  if (req_wrap_async != nullptr) {  // copyFile(src, dest, flags, req)
1638
    AsyncDestCall(env, req_wrap_async, args, "copyfile",
1639
15
                  *dest, dest.length(), UTF8, AfterNoArgs,
1640
30
                  uv_fs_copyfile, *src, *dest, flags);
1641
  } else {  // copyFile(src, dest, flags, undefined, ctx)
1642
20
    CHECK_EQ(argc, 5);
1643
20
    FSReqWrapSync req_wrap_sync;
1644

22
    FS_SYNC_TRACE_BEGIN(copyfile);
1645
    SyncCall(env, args[4], &req_wrap_sync, "copyfile",
1646
40
             uv_fs_copyfile, *src, *dest, flags);
1647

22
    FS_SYNC_TRACE_END(copyfile);
1648
35
  }
1649
35
}
1650
1651
1652
// Wrapper for write(2).
1653
//
1654
// bytesWritten = write(fd, buffer, offset, length, position, callback)
1655
// 0 fd        integer. file descriptor
1656
// 1 buffer    the data to write
1657
// 2 offset    where in the buffer to start from
1658
// 3 length    how much to write
1659
// 4 position  if integer, position to write at in the file.
1660
//             if null, write from the current position
1661
144114
static void WriteBuffer(const FunctionCallbackInfo<Value>& args) {
1662
144114
  Environment* env = Environment::GetCurrent(args);
1663
1664
144114
  const int argc = args.Length();
1665
144114
  CHECK_GE(argc, 4);
1666
1667
288228
  CHECK(args[0]->IsInt32());
1668
432342
  const int fd = args[0].As<Int32>()->Value();
1669
1670
144114
  CHECK(Buffer::HasInstance(args[1]));
1671
288228
  Local<Object> buffer_obj = args[1].As<Object>();
1672
144114
  char* buffer_data = Buffer::Data(buffer_obj);
1673
144114
  size_t buffer_length = Buffer::Length(buffer_obj);
1674
1675
144114
  CHECK(IsSafeJsInt(args[2]));
1676
432342
  const int64_t off_64 = args[2].As<Integer>()->Value();
1677
144114
  CHECK_GE(off_64, 0);
1678
144114
  CHECK_LE(static_cast<uint64_t>(off_64), buffer_length);
1679
144114
  const size_t off = static_cast<size_t>(off_64);
1680
1681
288228
  CHECK(args[3]->IsInt32());
1682
432342
  const size_t len = static_cast<size_t>(args[3].As<Int32>()->Value());
1683
144114
  CHECK(Buffer::IsWithinBounds(off, len, buffer_length));
1684
144114
  CHECK_LE(len, buffer_length);
1685
144114
  CHECK_GE(off + len, off);
1686
1687
144114
  const int64_t pos = GetOffset(args[4]);
1688
1689
144114
  char* buf = buffer_data + off;
1690
144114
  uv_buf_t uvbuf = uv_buf_init(buf, len);
1691
1692
144114
  FSReqBase* req_wrap_async = GetReqWrap(env, args[5]);
1693
144114
  if (req_wrap_async != nullptr) {  // write(fd, buffer, off, len, pos, req)
1694
    AsyncCall(env, req_wrap_async, args, "write", UTF8, AfterInteger,
1695
17200
              uv_fs_write, fd, &uvbuf, 1, pos);
1696
  } else {  // write(fd, buffer, off, len, pos, undefined, ctx)
1697
126914
    CHECK_EQ(argc, 7);
1698
126914
    FSReqWrapSync req_wrap_sync;
1699

126964
    FS_SYNC_TRACE_BEGIN(write);
1700
    int bytesWritten = SyncCall(env, args[6], &req_wrap_sync, "write",
1701
126914
                                uv_fs_write, fd, &uvbuf, 1, pos);
1702

126964
    FS_SYNC_TRACE_END(write, "bytesWritten", bytesWritten);
1703
380742
    args.GetReturnValue().Set(bytesWritten);
1704
  }
1705
144114
}
1706
1707
1708
// Wrapper for writev(2).
1709
//
1710
// bytesWritten = writev(fd, chunks, position, callback)
1711
// 0 fd        integer. file descriptor
1712
// 1 chunks    array of buffers to write
1713
// 2 position  if integer, position to write at in the file.
1714
//             if null, write from the current position
1715
28
static void WriteBuffers(const FunctionCallbackInfo<Value>& args) {
1716
28
  Environment* env = Environment::GetCurrent(args);
1717
1718
28
  const int argc = args.Length();
1719
28
  CHECK_GE(argc, 3);
1720
1721
56
  CHECK(args[0]->IsInt32());
1722
84
  const int fd = args[0].As<Int32>()->Value();
1723
1724
56
  CHECK(args[1]->IsArray());
1725
56
  Local<Array> chunks = args[1].As<Array>();
1726
1727
28
  int64_t pos = GetOffset(args[2]);
1728
1729
28
  MaybeStackBuffer<uv_buf_t> iovs(chunks->Length());
1730
1731
148746
  for (uint32_t i = 0; i < iovs.length(); i++) {
1732
446154
    Local<Value> chunk = chunks->Get(env->context(), i).ToLocalChecked();
1733
148718
    CHECK(Buffer::HasInstance(chunk));
1734
148718
    iovs[i] = uv_buf_init(Buffer::Data(chunk), Buffer::Length(chunk));
1735
  }
1736
1737
28
  FSReqBase* req_wrap_async = GetReqWrap(env, args[3]);
1738
28
  if (req_wrap_async != nullptr) {  // writeBuffers(fd, chunks, pos, req)
1739
    AsyncCall(env, req_wrap_async, args, "write", UTF8, AfterInteger,
1740
24
              uv_fs_write, fd, *iovs, iovs.length(), pos);
1741
  } else {  // writeBuffers(fd, chunks, pos, undefined, ctx)
1742
4
    CHECK_EQ(argc, 5);
1743
4
    FSReqWrapSync req_wrap_sync;
1744

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

4
    FS_SYNC_TRACE_END(write, "bytesWritten", bytesWritten);
1748
12
    args.GetReturnValue().Set(bytesWritten);
1749
28
  }
1750
28
}
1751
1752
1753
// Wrapper for write(2).
1754
//
1755
// bytesWritten = write(fd, string, position, enc, callback)
1756
// 0 fd        integer. file descriptor
1757
// 1 string    non-buffer values are converted to strings
1758
// 2 position  if integer, position to write at in the file.
1759
//             if null, write from the current position
1760
// 3 enc       encoding of string
1761
1366
static void WriteString(const FunctionCallbackInfo<Value>& args) {
1762
1366
  Environment* env = Environment::GetCurrent(args);
1763
1366
  Isolate* isolate = env->isolate();
1764
1765
1366
  const int argc = args.Length();
1766
1366
  CHECK_GE(argc, 4);
1767
1768
2732
  CHECK(args[0]->IsInt32());
1769
4098
  const int fd = args[0].As<Int32>()->Value();
1770
1771
1366
  const int64_t pos = GetOffset(args[2]);
1772
1773
1366
  const auto enc = ParseEncoding(isolate, args[3], UTF8);
1774
1775
1366
  Local<Value> value = args[1];
1776
1366
  char* buf = nullptr;
1777
  size_t len;
1778
1779
1366
  FSReqBase* req_wrap_async = GetReqWrap(env, args[4]);
1780
1366
  const bool is_async = req_wrap_async != nullptr;
1781
1782
  // Avoid copying the string when it is externalized but only when:
1783
  // 1. The target encoding is compatible with the string's encoding, and
1784
  // 2. The write is synchronous, otherwise the string might get neutered
1785
  //    while the request is in flight, and
1786
  // 3. For UCS2, when the host system is little-endian.  Big-endian systems
1787
  //    need to call StringBytes::Write() to ensure proper byte swapping.
1788
  // The const_casts are conceptually sound: memory is read but not written.
1789

3816
  if (!is_async && value->IsString()) {
1790
1225
    auto string = value.As<String>();
1791


1226
    if ((enc == ASCII || enc == LATIN1) && string->IsExternalOneByte()) {
1792
1
      auto ext = string->GetExternalOneByteStringResource();
1793
1
      buf = const_cast<char*>(ext->data());
1794
1
      len = ext->length();
1795


1225
    } else if (enc == UCS2 && IsLittleEndian() && string->IsExternal()) {
1796
2
      auto ext = string->GetExternalStringResource();
1797
1
      buf = reinterpret_cast<char*>(const_cast<uint16_t*>(ext->data()));
1798
1
      len = ext->length() * sizeof(*ext->data());
1799
    }
1800
  }
1801
1802
1366
  if (is_async) {  // write(fd, string, pos, enc, req)
1803
141
    CHECK_NOT_NULL(req_wrap_async);
1804
282
    if (!StringBytes::StorageSize(isolate, value, enc).To(&len)) return;
1805
    FSReqBase::FSReqBuffer& stack_buffer =
1806
141
        req_wrap_async->Init("write", len, enc);
1807
    // StorageSize may return too large a char, so correct the actual length
1808
    // by the write size
1809
141
    len = StringBytes::Write(isolate, *stack_buffer, len, args[1], enc);
1810
141
    stack_buffer.SetLengthAndZeroTerminate(len);
1811
141
    uv_buf_t uvbuf = uv_buf_init(*stack_buffer, len);
1812
    int err = req_wrap_async->Dispatch(uv_fs_write,
1813
                                       fd,
1814
                                       &uvbuf,
1815
                                       1,
1816
                                       pos,
1817
141
                                       AfterInteger);
1818
141
    if (err < 0) {
1819
      uv_fs_t* uv_req = req_wrap_async->req();
1820
      uv_req->result = err;
1821
      uv_req->path = nullptr;
1822
      AfterInteger(uv_req);  // after may delete req_wrap_async if there is
1823
                             // an error
1824
    } else {
1825
141
      req_wrap_async->SetReturnValue(args);
1826
    }
1827
  } else {  // write(fd, string, pos, enc, undefined, ctx)
1828
1225
    CHECK_EQ(argc, 6);
1829
1225
    FSReqWrapSync req_wrap_sync;
1830
2450
    FSReqBase::FSReqBuffer stack_buffer;
1831
1225
    if (buf == nullptr) {
1832
2446
      if (!StringBytes::StorageSize(isolate, value, enc).To(&len))
1833
        return;
1834
1223
      stack_buffer.AllocateSufficientStorage(len + 1);
1835
      // StorageSize may return too large a char, so correct the actual length
1836
      // by the write size
1837
      len = StringBytes::Write(isolate, *stack_buffer,
1838
1223
                               len, args[1], enc);
1839
1223
      stack_buffer.SetLengthAndZeroTerminate(len);
1840
1223
      buf = *stack_buffer;
1841
    }
1842
1225
    uv_buf_t uvbuf = uv_buf_init(buf, len);
1843

1225
    FS_SYNC_TRACE_BEGIN(write);
1844
    int bytesWritten = SyncCall(env, args[5], &req_wrap_sync, "write",
1845
1225
                                uv_fs_write, fd, &uvbuf, 1, pos);
1846

1225
    FS_SYNC_TRACE_END(write, "bytesWritten", bytesWritten);
1847
4900
    args.GetReturnValue().Set(bytesWritten);
1848
  }
1849
}
1850
1851
1852
/*
1853
 * Wrapper for read(2).
1854
 *
1855
 * bytesRead = fs.read(fd, buffer, offset, length, position)
1856
 *
1857
 * 0 fd        int32. file descriptor
1858
 * 1 buffer    instance of Buffer
1859
 * 2 offset    int64. offset to start reading into inside buffer
1860
 * 3 length    int32. length to read
1861
 * 4 position  int64. file position - -1 for current position
1862
 */
1863
78348
static void Read(const FunctionCallbackInfo<Value>& args) {
1864
78348
  Environment* env = Environment::GetCurrent(args);
1865
1866
78349
  const int argc = args.Length();
1867
78349
  CHECK_GE(argc, 5);
1868
1869
156698
  CHECK(args[0]->IsInt32());
1870
235044
  const int fd = args[0].As<Int32>()->Value();
1871
1872
78349
  CHECK(Buffer::HasInstance(args[1]));
1873
156698
  Local<Object> buffer_obj = args[1].As<Object>();
1874
78349
  char* buffer_data = Buffer::Data(buffer_obj);
1875
78349
  size_t buffer_length = Buffer::Length(buffer_obj);
1876
1877
78348
  CHECK(IsSafeJsInt(args[2]));
1878
235047
  const int64_t off_64 = args[2].As<Integer>()->Value();
1879
78349
  CHECK_GE(off_64, 0);
1880
78349
  CHECK_LT(static_cast<uint64_t>(off_64), buffer_length);
1881
78349
  const size_t off = static_cast<size_t>(off_64);
1882
1883
156698
  CHECK(args[3]->IsInt32());
1884
235047
  const size_t len = static_cast<size_t>(args[3].As<Int32>()->Value());
1885
78349
  CHECK(Buffer::IsWithinBounds(off, len, buffer_length));
1886
1887
78349
  CHECK(IsSafeJsInt(args[4]));
1888
235047
  const int64_t pos = args[4].As<Integer>()->Value();
1889
1890
78348
  char* buf = buffer_data + off;
1891
78348
  uv_buf_t uvbuf = uv_buf_init(buf, len);
1892
1893
78349
  FSReqBase* req_wrap_async = GetReqWrap(env, args[5]);
1894
78348
  if (req_wrap_async != nullptr) {  // read(fd, buffer, offset, len, pos, req)
1895
    AsyncCall(env, req_wrap_async, args, "read", UTF8, AfterInteger,
1896
13485
              uv_fs_read, fd, &uvbuf, 1, pos);
1897
  } else {  // read(fd, buffer, offset, len, pos, undefined, ctx)
1898
64863
    CHECK_EQ(argc, 7);
1899
64863
    FSReqWrapSync req_wrap_sync;
1900

64874
    FS_SYNC_TRACE_BEGIN(read);
1901
    const int bytesRead = SyncCall(env, args[6], &req_wrap_sync, "read",
1902
64864
                                   uv_fs_read, fd, &uvbuf, 1, pos);
1903

64873
    FS_SYNC_TRACE_END(read, "bytesRead", bytesRead);
1904
194589
    args.GetReturnValue().Set(bytesRead);
1905
  }
1906
78348
}
1907
1908
1909
/* fs.chmod(path, mode);
1910
 * Wrapper for chmod(1) / EIO_CHMOD
1911
 */
1912
330
static void Chmod(const FunctionCallbackInfo<Value>& args) {
1913
330
  Environment* env = Environment::GetCurrent(args);
1914
1915
330
  const int argc = args.Length();
1916
330
  CHECK_GE(argc, 2);
1917
1918
330
  BufferValue path(env->isolate(), args[0]);
1919
330
  CHECK_NOT_NULL(*path);
1920
1921
660
  CHECK(args[1]->IsInt32());
1922
990
  int mode = args[1].As<Int32>()->Value();
1923
1924
330
  FSReqBase* req_wrap_async = GetReqWrap(env, args[2]);
1925
330
  if (req_wrap_async != nullptr) {  // chmod(path, mode, req)
1926
    AsyncCall(env, req_wrap_async, args, "chmod", UTF8, AfterNoArgs,
1927
316
              uv_fs_chmod, *path, mode);
1928
  } else {  // chmod(path, mode, undefined, ctx)
1929
14
    CHECK_EQ(argc, 4);
1930
14
    FSReqWrapSync req_wrap_sync;
1931

16
    FS_SYNC_TRACE_BEGIN(chmod);
1932
    SyncCall(env, args[3], &req_wrap_sync, "chmod",
1933
28
             uv_fs_chmod, *path, mode);
1934

16
    FS_SYNC_TRACE_END(chmod);
1935
330
  }
1936
330
}
1937
1938
1939
/* fs.fchmod(fd, mode);
1940
 * Wrapper for fchmod(1) / EIO_FCHMOD
1941
 */
1942
12
static void FChmod(const FunctionCallbackInfo<Value>& args) {
1943
12
  Environment* env = Environment::GetCurrent(args);
1944
1945
12
  const int argc = args.Length();
1946
12
  CHECK_GE(argc, 2);
1947
1948
24
  CHECK(args[0]->IsInt32());
1949
36
  const int fd = args[0].As<Int32>()->Value();
1950
1951
24
  CHECK(args[1]->IsInt32());
1952
36
  const int mode = args[1].As<Int32>()->Value();
1953
1954
12
  FSReqBase* req_wrap_async = GetReqWrap(env, args[2]);
1955
12
  if (req_wrap_async != nullptr) {  // fchmod(fd, mode, req)
1956
    AsyncCall(env, req_wrap_async, args, "fchmod", UTF8, AfterNoArgs,
1957
7
              uv_fs_fchmod, fd, mode);
1958
  } else {  // fchmod(fd, mode, undefined, ctx)
1959
5
    CHECK_EQ(argc, 4);
1960
5
    FSReqWrapSync req_wrap_sync;
1961

7
    FS_SYNC_TRACE_BEGIN(fchmod);
1962
    SyncCall(env, args[3], &req_wrap_sync, "fchmod",
1963
5
             uv_fs_fchmod, fd, mode);
1964

7
    FS_SYNC_TRACE_END(fchmod);
1965
  }
1966
12
}
1967
1968
1969
/* fs.chown(path, uid, gid);
1970
 * Wrapper for chown(1) / EIO_CHOWN
1971
 */
1972
109
static void Chown(const FunctionCallbackInfo<Value>& args) {
1973
109
  Environment* env = Environment::GetCurrent(args);
1974
1975
109
  const int argc = args.Length();
1976
109
  CHECK_GE(argc, 3);
1977
1978
109
  BufferValue path(env->isolate(), args[0]);
1979
109
  CHECK_NOT_NULL(*path);
1980
1981
218
  CHECK(args[1]->IsUint32());
1982
327
  const uv_uid_t uid = static_cast<uv_uid_t>(args[1].As<Uint32>()->Value());
1983
1984
218
  CHECK(args[2]->IsUint32());
1985
327
  const uv_gid_t gid = static_cast<uv_gid_t>(args[2].As<Uint32>()->Value());
1986
1987
109
  FSReqBase* req_wrap_async = GetReqWrap(env, args[3]);
1988
109
  if (req_wrap_async != nullptr) {  // chown(path, uid, gid, req)
1989
    AsyncCall(env, req_wrap_async, args, "chown", UTF8, AfterNoArgs,
1990
106
              uv_fs_chown, *path, uid, gid);
1991
  } else {  // chown(path, uid, gid, undefined, ctx)
1992
3
    CHECK_EQ(argc, 5);
1993
3
    FSReqWrapSync req_wrap_sync;
1994

5
    FS_SYNC_TRACE_BEGIN(chown);
1995
    SyncCall(env, args[4], &req_wrap_sync, "chown",
1996
6
             uv_fs_chown, *path, uid, gid);
1997

5
    FS_SYNC_TRACE_END(chown);
1998
109
  }
1999
109
}
2000
2001
2002
/* fs.fchown(fd, uid, gid);
2003
 * Wrapper for fchown(1) / EIO_FCHOWN
2004
 */
2005
4
static void FChown(const FunctionCallbackInfo<Value>& args) {
2006
4
  Environment* env = Environment::GetCurrent(args);
2007
2008
4
  const int argc = args.Length();
2009
4
  CHECK_GE(argc, 3);
2010
2011
8
  CHECK(args[0]->IsInt32());
2012
12
  const int fd = args[0].As<Int32>()->Value();
2013
2014
8
  CHECK(args[1]->IsUint32());
2015
12
  const uv_uid_t uid = static_cast<uv_uid_t>(args[1].As<Uint32>()->Value());
2016
2017
8
  CHECK(args[2]->IsUint32());
2018
12
  const uv_gid_t gid = static_cast<uv_gid_t>(args[2].As<Uint32>()->Value());
2019
2020
4
  FSReqBase* req_wrap_async = GetReqWrap(env, args[3]);
2021
4
  if (req_wrap_async != nullptr) {  // fchown(fd, uid, gid, req)
2022
    AsyncCall(env, req_wrap_async, args, "fchown", UTF8, AfterNoArgs,
2023
2
              uv_fs_fchown, fd, uid, gid);
2024
  } else {  // fchown(fd, uid, gid, undefined, ctx)
2025
2
    CHECK_EQ(argc, 5);
2026
2
    FSReqWrapSync req_wrap_sync;
2027

4
    FS_SYNC_TRACE_BEGIN(fchown);
2028
    SyncCall(env, args[4], &req_wrap_sync, "fchown",
2029
2
             uv_fs_fchown, fd, uid, gid);
2030

4
    FS_SYNC_TRACE_END(fchown);
2031
  }
2032
4
}
2033
2034
2035
9
static void LChown(const FunctionCallbackInfo<Value>& args) {
2036
9
  Environment* env = Environment::GetCurrent(args);
2037
2038
9
  const int argc = args.Length();
2039
9
  CHECK_GE(argc, 3);
2040
2041
9
  BufferValue path(env->isolate(), args[0]);
2042
9
  CHECK_NOT_NULL(*path);
2043
2044
18
  CHECK(args[1]->IsUint32());
2045
27
  const uv_uid_t uid = static_cast<uv_uid_t>(args[1].As<Uint32>()->Value());
2046
2047
18
  CHECK(args[2]->IsUint32());
2048
27
  const uv_gid_t gid = static_cast<uv_gid_t>(args[2].As<Uint32>()->Value());
2049
2050
9
  FSReqBase* req_wrap_async = GetReqWrap(env, args[3]);
2051
9
  if (req_wrap_async != nullptr) {  // lchown(path, uid, gid, req)
2052
    AsyncCall(env, req_wrap_async, args, "lchown", UTF8, AfterNoArgs,
2053
7
              uv_fs_lchown, *path, uid, gid);
2054
  } else {  // lchown(path, uid, gid, undefined, ctx)
2055
2
    CHECK_EQ(argc, 5);
2056
2
    FSReqWrapSync req_wrap_sync;
2057

4
    FS_SYNC_TRACE_BEGIN(lchown);
2058
    SyncCall(env, args[4], &req_wrap_sync, "lchown",
2059
4
             uv_fs_lchown, *path, uid, gid);
2060

4
    FS_SYNC_TRACE_END(lchown);
2061
9
  }
2062
9
}
2063
2064
2065
29
static void UTimes(const FunctionCallbackInfo<Value>& args) {
2066
29
  Environment* env = Environment::GetCurrent(args);
2067
2068
29
  const int argc = args.Length();
2069
29
  CHECK_GE(argc, 3);
2070
2071
29
  BufferValue path(env->isolate(), args[0]);
2072
29
  CHECK_NOT_NULL(*path);
2073
2074
58
  CHECK(args[1]->IsNumber());
2075
87
  const double atime = args[1].As<Number>()->Value();
2076
2077
58
  CHECK(args[2]->IsNumber());
2078
87
  const double mtime = args[2].As<Number>()->Value();
2079
2080
29
  FSReqBase* req_wrap_async = GetReqWrap(env, args[3]);
2081
29
  if (req_wrap_async != nullptr) {  // utimes(path, atime, mtime, req)
2082
    AsyncCall(env, req_wrap_async, args, "utime", UTF8, AfterNoArgs,
2083
14
              uv_fs_utime, *path, atime, mtime);
2084
  } else {  // utimes(path, atime, mtime, undefined, ctx)
2085
15
    CHECK_EQ(argc, 5);
2086
15
    FSReqWrapSync req_wrap_sync;
2087

17
    FS_SYNC_TRACE_BEGIN(utimes);
2088
    SyncCall(env, args[4], &req_wrap_sync, "utime",
2089
30
             uv_fs_utime, *path, atime, mtime);
2090

17
    FS_SYNC_TRACE_END(utimes);
2091
29
  }
2092
29
}
2093
2094
1802
static void FUTimes(const FunctionCallbackInfo<Value>& args) {
2095
1802
  Environment* env = Environment::GetCurrent(args);
2096
2097
1802
  const int argc = args.Length();
2098
1802
  CHECK_GE(argc, 3);
2099
2100
3604
  CHECK(args[0]->IsInt32());
2101
5406
  const int fd = args[0].As<Int32>()->Value();
2102
2103
3604
  CHECK(args[1]->IsNumber());
2104
5406
  const double atime = args[1].As<Number>()->Value();
2105
2106
3604
  CHECK(args[2]->IsNumber());
2107
5406
  const double mtime = args[2].As<Number>()->Value();
2108
2109
1802
  FSReqBase* req_wrap_async = GetReqWrap(env, args[3]);
2110
1802
  if (req_wrap_async != nullptr) {  // futimes(fd, atime, mtime, req)
2111
    AsyncCall(env, req_wrap_async, args, "futime", UTF8, AfterNoArgs,
2112
1794
              uv_fs_futime, fd, atime, mtime);
2113
  } else {  // futimes(fd, atime, mtime, undefined, ctx)
2114
8
    CHECK_EQ(argc, 5);
2115
8
    FSReqWrapSync req_wrap_sync;
2116

10
    FS_SYNC_TRACE_BEGIN(futimes);
2117
    SyncCall(env, args[4], &req_wrap_sync, "futime",
2118
8
             uv_fs_futime, fd, atime, mtime);
2119

10
    FS_SYNC_TRACE_END(futimes);
2120
  }
2121
1802
}
2122
2123
13
static void Mkdtemp(const FunctionCallbackInfo<Value>& args) {
2124
13
  Environment* env = Environment::GetCurrent(args);
2125
13
  Isolate* isolate = env->isolate();
2126
2127
13
  const int argc = args.Length();
2128
13
  CHECK_GE(argc, 2);
2129
2130
13
  BufferValue tmpl(isolate, args[0]);
2131
13
  CHECK_NOT_NULL(*tmpl);
2132
2133
13
  const enum encoding encoding = ParseEncoding(isolate, args[1], UTF8);
2134
2135
13
  FSReqBase* req_wrap_async = GetReqWrap(env, args[2]);
2136
13
  if (req_wrap_async != nullptr) {  // mkdtemp(tmpl, encoding, req)
2137
    AsyncCall(env, req_wrap_async, args, "mkdtemp", encoding, AfterStringPath,
2138
6
              uv_fs_mkdtemp, *tmpl);
2139
  } else {  // mkdtemp(tmpl, encoding, undefined, ctx)
2140
7
    CHECK_EQ(argc, 4);
2141
7
    FSReqWrapSync req_wrap_sync;
2142

9
    FS_SYNC_TRACE_BEGIN(mkdtemp);
2143
    SyncCall(env, args[3], &req_wrap_sync, "mkdtemp",
2144
14
             uv_fs_mkdtemp, *tmpl);
2145

9
    FS_SYNC_TRACE_END(mkdtemp);
2146
7
    const char* path = req_wrap_sync.req.path;
2147
2148
    Local<Value> error;
2149
    MaybeLocal<Value> rc =
2150
7
        StringBytes::Encode(isolate, path, encoding, &error);
2151
7
    if (rc.IsEmpty()) {
2152
      Local<Object> ctx = args[3].As<Object>();
2153
      ctx->Set(env->context(), env->error_string(), error).Check();
2154
13
      return;
2155
    }
2156

14
    args.GetReturnValue().Set(rc.ToLocalChecked());
2157
13
  }
2158
}
2159
2160
5182
void Initialize(Local<Object> target,
2161
                Local<Value> unused,
2162
                Local<Context> context,
2163
                void* priv) {
2164
5182
  Environment* env = Environment::GetCurrent(context);
2165
5182
  Isolate* isolate = env->isolate();
2166
2167
5182
  env->SetMethod(target, "access", Access);
2168
5182
  env->SetMethod(target, "close", Close);
2169
5182
  env->SetMethod(target, "open", Open);
2170
5182
  env->SetMethod(target, "openFileHandle", OpenFileHandle);
2171
5182
  env->SetMethod(target, "read", Read);
2172
5182
  env->SetMethod(target, "fdatasync", Fdatasync);
2173
5182
  env->SetMethod(target, "fsync", Fsync);
2174
5182
  env->SetMethod(target, "rename", Rename);
2175
5182
  env->SetMethod(target, "ftruncate", FTruncate);
2176
5182
  env->SetMethod(target, "rmdir", RMDir);
2177
5182
  env->SetMethod(target, "mkdir", MKDir);
2178
5182
  env->SetMethod(target, "readdir", ReadDir);
2179
5182
  env->SetMethod(target, "internalModuleReadJSON", InternalModuleReadJSON);
2180
5182
  env->SetMethod(target, "internalModuleStat", InternalModuleStat);
2181
5182
  env->SetMethod(target, "stat", Stat);
2182
5182
  env->SetMethod(target, "lstat", LStat);
2183
5182
  env->SetMethod(target, "fstat", FStat);
2184
5182
  env->SetMethod(target, "link", Link);
2185
5182
  env->SetMethod(target, "symlink", Symlink);
2186
5182
  env->SetMethod(target, "readlink", ReadLink);
2187
5182
  env->SetMethod(target, "unlink", Unlink);
2188
5182
  env->SetMethod(target, "writeBuffer", WriteBuffer);
2189
5182
  env->SetMethod(target, "writeBuffers", WriteBuffers);
2190
5182
  env->SetMethod(target, "writeString", WriteString);
2191
5182
  env->SetMethod(target, "realpath", RealPath);
2192
5182
  env->SetMethod(target, "copyFile", CopyFile);
2193
2194
5182
  env->SetMethod(target, "chmod", Chmod);
2195
5182
  env->SetMethod(target, "fchmod", FChmod);
2196
  // env->SetMethod(target, "lchmod", LChmod);
2197
2198
5182
  env->SetMethod(target, "chown", Chown);
2199
5182
  env->SetMethod(target, "fchown", FChown);
2200
5182
  env->SetMethod(target, "lchown", LChown);
2201
2202
5182
  env->SetMethod(target, "utimes", UTimes);
2203
5182
  env->SetMethod(target, "futimes", FUTimes);
2204
2205
5182
  env->SetMethod(target, "mkdtemp", Mkdtemp);
2206
2207
  target
2208
      ->Set(context,
2209
            FIXED_ONE_BYTE_STRING(isolate, "kFsStatsFieldsNumber"),
2210
            Integer::New(
2211
                isolate,
2212
20728
                static_cast<int32_t>(FsStatsOffset::kFsStatsFieldsNumber)))
2213
10364
      .Check();
2214
2215
  target->Set(context,
2216
              FIXED_ONE_BYTE_STRING(isolate, "statValues"),
2217
20728
              env->fs_stats_field_array()->GetJSArray()).Check();
2218
2219
  target->Set(context,
2220
              FIXED_ONE_BYTE_STRING(isolate, "bigintStatValues"),
2221
20728
              env->fs_stats_field_bigint_array()->GetJSArray()).Check();
2222
2223
5182
  StatWatcher::Initialize(env, target);
2224
2225
  // Create FunctionTemplate for FSReqCallback
2226
5182
  Local<FunctionTemplate> fst = env->NewFunctionTemplate(NewFSReqCallback);
2227
10364
  fst->InstanceTemplate()->SetInternalFieldCount(1);
2228
10364
  fst->Inherit(AsyncWrap::GetConstructorTemplate(env));
2229
  Local<String> wrapString =
2230
5182
      FIXED_ONE_BYTE_STRING(isolate, "FSReqCallback");
2231
5182
  fst->SetClassName(wrapString);
2232
  target
2233
      ->Set(context, wrapString,
2234
20728
            fst->GetFunction(env->context()).ToLocalChecked())
2235
10364
      .Check();
2236
2237
  // Create FunctionTemplate for FileHandleReadWrap. There’s no need
2238
  // to do anything in the constructor, so we only store the instance template.
2239
5182
  Local<FunctionTemplate> fh_rw = FunctionTemplate::New(isolate);
2240
10364
  fh_rw->InstanceTemplate()->SetInternalFieldCount(1);
2241
10364
  fh_rw->Inherit(AsyncWrap::GetConstructorTemplate(env));
2242
  Local<String> fhWrapString =
2243
5182
      FIXED_ONE_BYTE_STRING(isolate, "FileHandleReqWrap");
2244
5182
  fh_rw->SetClassName(fhWrapString);
2245
  env->set_filehandlereadwrap_template(
2246
5182
      fst->InstanceTemplate());
2247
2248
  // Create Function Template for FSReqPromise
2249
5182
  Local<FunctionTemplate> fpt = FunctionTemplate::New(isolate);
2250
10364
  fpt->Inherit(AsyncWrap::GetConstructorTemplate(env));
2251
  Local<String> promiseString =
2252
5182
      FIXED_ONE_BYTE_STRING(isolate, "FSReqPromise");
2253
5182
  fpt->SetClassName(promiseString);
2254
5182
  Local<ObjectTemplate> fpo = fpt->InstanceTemplate();
2255
5182
  fpo->SetInternalFieldCount(1);
2256
5182
  env->set_fsreqpromise_constructor_template(fpo);
2257
2258
  // Create FunctionTemplate for FileHandle
2259
5182
  Local<FunctionTemplate> fd = env->NewFunctionTemplate(FileHandle::New);
2260
10364
  fd->Inherit(AsyncWrap::GetConstructorTemplate(env));
2261
5182
  env->SetProtoMethod(fd, "close", FileHandle::Close);
2262
5182
  env->SetProtoMethod(fd, "releaseFD", FileHandle::ReleaseFD);
2263
5182
  Local<ObjectTemplate> fdt = fd->InstanceTemplate();
2264
5182
  fdt->SetInternalFieldCount(StreamBase::kStreamBaseFieldCount);
2265
  Local<String> handleString =
2266
5182
       FIXED_ONE_BYTE_STRING(isolate, "FileHandle");
2267
5182
  fd->SetClassName(handleString);
2268
5182
  StreamBase::AddMethods(env, fd);
2269
  target
2270
      ->Set(context, handleString,
2271
20728
            fd->GetFunction(env->context()).ToLocalChecked())
2272
10364
      .Check();
2273
5182
  env->set_fd_constructor_template(fdt);
2274
2275
  // Create FunctionTemplate for FileHandle::CloseReq
2276
5182
  Local<FunctionTemplate> fdclose = FunctionTemplate::New(isolate);
2277
  fdclose->SetClassName(FIXED_ONE_BYTE_STRING(isolate,
2278
10364
                        "FileHandleCloseReq"));
2279
10364
  fdclose->Inherit(AsyncWrap::GetConstructorTemplate(env));
2280
5182
  Local<ObjectTemplate> fdcloset = fdclose->InstanceTemplate();
2281
5182
  fdcloset->SetInternalFieldCount(1);
2282
5182
  env->set_fdclose_constructor_template(fdcloset);
2283
2284
  Local<Symbol> use_promises_symbol =
2285
    Symbol::New(isolate,
2286
5182
                FIXED_ONE_BYTE_STRING(isolate, "use promises"));
2287
5182
  env->set_fs_use_promises_symbol(use_promises_symbol);
2288
  target->Set(context,
2289
              FIXED_ONE_BYTE_STRING(isolate, "kUsePromises"),
2290
15546
              use_promises_symbol).Check();
2291
5182
}
2292
2293
}  // namespace fs
2294
2295
}  // end namespace node
2296
2297

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