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: 1214 1294 93.8 %
Date: 2019-02-13 22:28:58 Branches: 788 1188 66.3 %

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 "node_buffer.h"
25
#include "node_process.h"
26
#include "node_stat_watcher.h"
27
#include "util.h"
28
29
#include "tracing/trace_event.h"
30
31
#include "req_wrap-inl.h"
32
#include "stream_base-inl.h"
33
#include "string_bytes.h"
34
#include "string_search.h"
35
36
#include <fcntl.h>
37
#include <sys/types.h>
38
#include <sys/stat.h>
39
#include <string.h>
40
#include <errno.h>
41
#include <limits.h>
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::BigUint64Array;
55
using v8::Context;
56
using v8::EscapableHandleScope;
57
using v8::Float64Array;
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 MIN
78
# define MIN(a, b) ((a) < (b) ? (a) : (b))
79
#endif
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
#define GET_OFFSET(a) ((a)->IsNumber() ? (a).As<Integer>()->Value() : -1)
92
#define TRACE_NAME(name) "fs.sync." #name
93
#define GET_TRACE_ENABLED                                                  \
94
  (*TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED                             \
95
  (TRACING_CATEGORY_NODE2(fs, sync)) != 0)
96
#define FS_SYNC_TRACE_BEGIN(syscall, ...)                                  \
97
  if (GET_TRACE_ENABLED)                                                   \
98
  TRACE_EVENT_BEGIN(TRACING_CATEGORY_NODE2(fs, sync), TRACE_NAME(syscall), \
99
  ##__VA_ARGS__);
100
#define FS_SYNC_TRACE_END(syscall, ...)                                    \
101
  if (GET_TRACE_ENABLED)                                                   \
102
  TRACE_EVENT_END(TRACING_CATEGORY_NODE2(fs, sync), TRACE_NAME(syscall),   \
103
  ##__VA_ARGS__);
104
105
// We sometimes need to convert a C++ lambda function to a raw C-style function.
106
// This is helpful, because ReqWrap::Dispatch() does not recognize lambda
107
// functions, and thus does not wrap them properly.
108
typedef void(*uv_fs_callback_t)(uv_fs_t*);
109
110
// The FileHandle object wraps a file descriptor and will close it on garbage
111
// collection if necessary. If that happens, a process warning will be
112
// emitted (or a fatal exception will occur if the fd cannot be closed.)
113
77
FileHandle::FileHandle(Environment* env, Local<Object> obj, int fd)
114
    : AsyncWrap(env, obj, AsyncWrap::PROVIDER_FILEHANDLE),
115
      StreamBase(env),
116
77
      fd_(fd) {
117
77
  MakeWeak();
118
77
}
119
120
77
FileHandle* FileHandle::New(Environment* env, int fd, Local<Object> obj) {
121

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

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

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

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

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

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







171767
  CHECK_NOT_NULL(req_wrap);
700
171767
  req_wrap->Init(syscall, dest, len, enc);
701
171767
  int err = req_wrap->Dispatch(fn, fn_args..., after);
702







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







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

1068
    FS_SYNC_TRACE_BEGIN(access);
789
2136
    SyncCall(env, args[3], &req_wrap_sync, "access", uv_fs_access, *path, mode);
790

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

455828
    FS_SYNC_TRACE_BEGIN(close);
812
455828
    SyncCall(env, args[2], &req_wrap_sync, "close", uv_fs_close, fd);
813

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

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

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

31929
    FS_SYNC_TRACE_BEGIN(stat);
924
63858
    int err = SyncCall(env, args[3], &req_wrap_sync, "stat", uv_fs_stat, *path);
925

31929
    FS_SYNC_TRACE_END(stat);
926
31929
    if (err != 0) {
927
33132
      return;  // error info is in ctx
928
    }
929
930
    Local<Value> arr = FillGlobalStatsArray(env, use_bigint,
931
31927
        static_cast<const uv_stat_t*>(req_wrap_sync.req.ptr));
932

63854
    args.GetReturnValue().Set(arr);
933
33128
  }
934
}
935
936
106791
static void LStat(const FunctionCallbackInfo<Value>& args) {
937
106791
  Environment* env = Environment::GetCurrent(args);
938
939
106791
  const int argc = args.Length();
940
106791
  CHECK_GE(argc, 3);
941
942
106791
  BufferValue path(env->isolate(), args[0]);
943
106791
  CHECK_NOT_NULL(*path);
944
945
213582
  bool use_bigint = args[1]->IsTrue();
946
213582
  FSReqBase* req_wrap_async = GetReqWrap(env, args[2], use_bigint);
947
106791
  if (req_wrap_async != nullptr) {  // lstat(path, use_bigint, req)
948
    AsyncCall(env, req_wrap_async, args, "lstat", UTF8, AfterStat,
949
1658
              uv_fs_lstat, *path);
950
  } else {  // lstat(path, use_bigint, undefined, ctx)
951
105133
    CHECK_EQ(argc, 4);
952
105133
    FSReqWrapSync req_wrap_sync;
953

105133
    FS_SYNC_TRACE_BEGIN(lstat);
954
    int err = SyncCall(env, args[3], &req_wrap_sync, "lstat", uv_fs_lstat,
955
210266
                       *path);
956

105133
    FS_SYNC_TRACE_END(lstat);
957
105133
    if (err != 0) {
958
106793
      return;  // error info is in ctx
959
    }
960
961
    Local<Value> arr = FillGlobalStatsArray(env, use_bigint,
962
105131
        static_cast<const uv_stat_t*>(req_wrap_sync.req.ptr));
963

210262
    args.GetReturnValue().Set(arr);
964
106789
  }
965
}
966
967
450396
static void FStat(const FunctionCallbackInfo<Value>& args) {
968
450396
  Environment* env = Environment::GetCurrent(args);
969
970
450396
  const int argc = args.Length();
971
450396
  CHECK_GE(argc, 2);
972
973
900792
  CHECK(args[0]->IsInt32());
974
1351188
  int fd = args[0].As<Int32>()->Value();
975
976
900792
  bool use_bigint = args[1]->IsTrue();
977
900792
  FSReqBase* req_wrap_async = GetReqWrap(env, args[2], use_bigint);
978
450396
  if (req_wrap_async != nullptr) {  // fstat(fd, use_bigint, req)
979
    AsyncCall(env, req_wrap_async, args, "fstat", UTF8, AfterStat,
980
2204
              uv_fs_fstat, fd);
981
  } else {  // fstat(fd, use_bigint, undefined, ctx)
982
448192
    CHECK_EQ(argc, 4);
983
448192
    FSReqWrapSync req_wrap_sync;
984

448192
    FS_SYNC_TRACE_BEGIN(fstat);
985
448192
    int err = SyncCall(env, args[3], &req_wrap_sync, "fstat", uv_fs_fstat, fd);
986

448192
    FS_SYNC_TRACE_END(fstat);
987
448192
    if (err != 0) {
988
450413
      return;  // error info is in ctx
989
    }
990
991
    Local<Value> arr = FillGlobalStatsArray(env, use_bigint,
992
448175
        static_cast<const uv_stat_t*>(req_wrap_sync.req.ptr));
993
896350
    args.GetReturnValue().Set(arr);
994
  }
995
}
996
997
87
static void Symlink(const FunctionCallbackInfo<Value>& args) {
998
87
  Environment* env = Environment::GetCurrent(args);
999
87
  Isolate* isolate = env->isolate();
1000
1001
87
  int argc = args.Length();
1002
87
  CHECK_GE(argc, 4);
1003
1004
87
  BufferValue target(isolate, args[0]);
1005
87
  CHECK_NOT_NULL(*target);
1006
174
  BufferValue path(isolate, args[1]);
1007
87
  CHECK_NOT_NULL(*path);
1008
1009
174
  CHECK(args[2]->IsInt32());
1010
261
  int flags = args[2].As<Int32>()->Value();
1011
1012
87
  FSReqBase* req_wrap_async = GetReqWrap(env, args[3]);
1013
87
  if (req_wrap_async != nullptr) {  // symlink(target, path, flags, req)
1014
14
    AsyncDestCall(env, req_wrap_async, args, "symlink", *path, path.length(),
1015
28
                  UTF8, AfterNoArgs, uv_fs_symlink, *target, *path, flags);
1016
  } else {  // symlink(target, path, flags, undefinec, ctx)
1017
73
    CHECK_EQ(argc, 5);
1018
73
    FSReqWrapSync req_wrap_sync;
1019

73
    FS_SYNC_TRACE_BEGIN(symlink);
1020
    SyncCall(env, args[4], &req_wrap_sync, "symlink",
1021
146
             uv_fs_symlink, *target, *path, flags);
1022

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

5
    FS_SYNC_TRACE_BEGIN(link);
1047
    SyncCall(env, args[3], &req_wrap_sync, "link",
1048
10
             uv_fs_link, *src, *dest);
1049

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

38
    FS_SYNC_TRACE_BEGIN(readlink);
1073
    int err = SyncCall(env, args[3], &req_wrap_sync, "readlink",
1074
76
                       uv_fs_readlink, *path);
1075

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

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

3
    FS_SYNC_TRACE_BEGIN(rename);
1117
    SyncCall(env, args[3], &req_wrap_sync, "rename", uv_fs_rename,
1118
6
             *old_path, *new_path);
1119

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

14
    FS_SYNC_TRACE_BEGIN(ftruncate);
1143
    SyncCall(env, args[3], &req_wrap_sync, "ftruncate", uv_fs_ftruncate, fd,
1144
14
             len);
1145

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

3
    FS_SYNC_TRACE_BEGIN(fdatasync);
1166
3
    SyncCall(env, args[2], &req_wrap_sync, "fdatasync", uv_fs_fdatasync, fd);
1167

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

15
    FS_SYNC_TRACE_BEGIN(fsync);
1188
15
    SyncCall(env, args[2], &req_wrap_sync, "fsync", uv_fs_fsync, fd);
1189

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

478
    FS_SYNC_TRACE_BEGIN(unlink);
1210
956
    SyncCall(env, args[2], &req_wrap_sync, "unlink", uv_fs_unlink, *path);
1211

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

685
    FS_SYNC_TRACE_BEGIN(rmdir);
1232
    SyncCall(env, args[2], &req_wrap_sync, "rmdir",
1233
1370
             uv_fs_rmdir, *path);
1234

685
    FS_SYNC_TRACE_END(rmdir);
1235
689
  }
1236
689
}
1237
1238
4599
int MKDirpSync(uv_loop_t* loop, uv_fs_t* req, const std::string& path, int mode,
1239
               uv_fs_cb cb = nullptr) {
1240
4599
  FSContinuationData continuation_data(req, mode, cb);
1241
4599
  continuation_data.PushPath(std::move(path));
1242
1243
4599
  while (continuation_data.paths.size() > 0) {
1244
4613
    std::string next_path = continuation_data.PopPath();
1245
4613
    int err = uv_fs_mkdir(loop, req, next_path.c_str(), mode, nullptr);
1246
    while (true) {
1247

4614
      switch (err) {
1248
        case 0:
1249
18
          if (continuation_data.paths.size() == 0) {
1250
12
            return 0;
1251
          }
1252
6
          break;
1253
        case UV_ENOENT: {
1254
          std::string dirname = next_path.substr(0,
1255
8
                                        next_path.find_last_of(kPathSeparator));
1256
8
          if (dirname != next_path) {
1257
7
            continuation_data.PushPath(std::move(next_path));
1258
7
            continuation_data.PushPath(std::move(dirname));
1259
1
          } else if (continuation_data.paths.size() == 0) {
1260
1
            err = UV_EEXIST;
1261
1
            continue;
1262
          }
1263
7
          break;
1264
        }
1265
        case UV_EPERM: {
1266
          return err;
1267
        }
1268
        default:
1269
4588
          uv_fs_req_cleanup(req);
1270
4588
          err = uv_fs_stat(loop, req, next_path.c_str(), nullptr);
1271

4588
          if (err == 0 && !S_ISDIR(req->statbuf.st_mode)) return UV_EEXIST;
1272
4587
          if (err < 0) return err;
1273
4586
          break;
1274
      }
1275
4599
      break;
1276
    }
1277
4599
    uv_fs_req_cleanup(req);
1278
4599
  }
1279
1280
4585
  return 0;
1281
}
1282
1283
20
int MKDirpAsync(uv_loop_t* loop,
1284
                uv_fs_t* req,
1285
                const char* path,
1286
                int mode,
1287
                uv_fs_cb cb) {
1288
20
  FSReqBase* req_wrap = FSReqBase::from_req(req);
1289
  // on the first iteration of algorithm, stash state information.
1290
20
  if (req_wrap->continuation_data == nullptr) {
1291
24
    req_wrap->continuation_data = std::unique_ptr<FSContinuationData>{
1292
16
      new FSContinuationData(req, mode, cb)};
1293
8
    req_wrap->continuation_data->PushPath(std::move(path));
1294
  }
1295
1296
  // on each iteration of algorithm, mkdir directory on top of stack.
1297
20
  std::string next_path = req_wrap->continuation_data->PopPath();
1298
  int err = uv_fs_mkdir(loop, req, next_path.c_str(), mode,
1299
60
                        uv_fs_callback_t{[](uv_fs_t* req) {
1300
20
    FSReqBase* req_wrap = FSReqBase::from_req(req);
1301
20
    Environment* env = req_wrap->env();
1302
20
    uv_loop_t* loop = env->event_loop();
1303
20
    std::string path = req->path;
1304
20
    int err = req->result;
1305
1306
    while (true) {
1307

21
      switch (err) {
1308
        case 0: {
1309
11
          if (req_wrap->continuation_data->paths.size() == 0) {
1310
5
            req_wrap->continuation_data->Done(0);
1311
          } else {
1312
6
            uv_fs_req_cleanup(req);
1313
            MKDirpAsync(loop, req, path.c_str(),
1314
6
                        req_wrap->continuation_data->mode, nullptr);
1315
          }
1316
11
          break;
1317
        }
1318
        case UV_ENOENT: {
1319
          std::string dirname = path.substr(0,
1320
7
                                            path.find_last_of(kPathSeparator));
1321
7
          if (dirname != path) {
1322
6
            req_wrap->continuation_data->PushPath(std::move(path));
1323
6
            req_wrap->continuation_data->PushPath(std::move(dirname));
1324
1
          } else if (req_wrap->continuation_data->paths.size() == 0) {
1325
1
            err = UV_EEXIST;
1326
1
            continue;
1327
          }
1328
6
          uv_fs_req_cleanup(req);
1329
          MKDirpAsync(loop, req, path.c_str(),
1330
6
                      req_wrap->continuation_data->mode, nullptr);
1331
6
          break;
1332
        }
1333
        case UV_EPERM: {
1334
          req_wrap->continuation_data->Done(err);
1335
          break;
1336
        }
1337
        default:
1338

6
          if (err == UV_EEXIST &&
1339
3
              req_wrap->continuation_data->paths.size() > 0) {
1340
            uv_fs_req_cleanup(req);
1341
            MKDirpAsync(loop, req, path.c_str(),
1342
                        req_wrap->continuation_data->mode, nullptr);
1343
          } else {
1344
            // verify that the path pointed to is actually a directory.
1345
3
            uv_fs_req_cleanup(req);
1346
            int err = uv_fs_stat(loop, req, path.c_str(),
1347
9
                                 uv_fs_callback_t{[](uv_fs_t* req) {
1348
3
              FSReqBase* req_wrap = FSReqBase::from_req(req);
1349
3
              int err = req->result;
1350

3
              if (err == 0 && !S_ISDIR(req->statbuf.st_mode)) err = UV_EEXIST;
1351
3
              req_wrap->continuation_data->Done(err);
1352
12
            }});
1353
3
            if (err < 0) req_wrap->continuation_data->Done(err);
1354
          }
1355
3
          break;
1356
      }
1357
20
      break;
1358
    }
1359
80
  }});
1360
1361
20
  return err;
1362
}
1363
1364
5489
static void MKDir(const FunctionCallbackInfo<Value>& args) {
1365
5489
  Environment* env = Environment::GetCurrent(args);
1366
1367
5489
  const int argc = args.Length();
1368
5489
  CHECK_GE(argc, 4);
1369
1370
5489
  BufferValue path(env->isolate(), args[0]);
1371
5489
  CHECK_NOT_NULL(*path);
1372
1373
10978
  CHECK(args[1]->IsInt32());
1374
16467
  const int mode = args[1].As<Int32>()->Value();
1375
1376
10978
  CHECK(args[2]->IsBoolean());
1377
10978
  bool mkdirp = args[2]->IsTrue();
1378
1379
5489
  FSReqBase* req_wrap_async = GetReqWrap(env, args[3]);
1380
5489
  if (req_wrap_async != nullptr) {  // mkdir(path, mode, req)
1381
    AsyncCall(env, req_wrap_async, args, "mkdir", UTF8,
1382
321
              AfterNoArgs, mkdirp ? MKDirpAsync : uv_fs_mkdir, *path, mode);
1383
  } else {  // mkdir(path, mode, undefined, ctx)
1384
5168
    CHECK_EQ(argc, 5);
1385
5168
    FSReqWrapSync req_wrap_sync;
1386

5168
    FS_SYNC_TRACE_BEGIN(mkdir);
1387
5168
    if (mkdirp) {
1388
      SyncCall(env, args[4], &req_wrap_sync, "mkdir",
1389
9198
               MKDirpSync, *path, mode);
1390
    } else {
1391
      SyncCall(env, args[4], &req_wrap_sync, "mkdir",
1392
1138
               uv_fs_mkdir, *path, mode);
1393
    }
1394

5168
    FS_SYNC_TRACE_END(mkdir);
1395
5489
  }
1396
5489
}
1397
1398
36
static void RealPath(const FunctionCallbackInfo<Value>& args) {
1399
36
  Environment* env = Environment::GetCurrent(args);
1400
36
  Isolate* isolate = env->isolate();
1401
1402
36
  const int argc = args.Length();
1403
36
  CHECK_GE(argc, 3);
1404
1405
36
  BufferValue path(isolate, args[0]);
1406
36
  CHECK_NOT_NULL(*path);
1407
1408
36
  const enum encoding encoding = ParseEncoding(isolate, args[1], UTF8);
1409
1410
36
  FSReqBase* req_wrap_async = GetReqWrap(env, args[2]);
1411
36
  if (req_wrap_async != nullptr) {  // realpath(path, encoding, req)
1412
    AsyncCall(env, req_wrap_async, args, "realpath", encoding, AfterStringPtr,
1413
18
              uv_fs_realpath, *path);
1414
  } else {  // realpath(path, encoding, undefined, ctx)
1415
18
    CHECK_EQ(argc, 4);
1416
18
    FSReqWrapSync req_wrap_sync;
1417

18
    FS_SYNC_TRACE_BEGIN(realpath);
1418
    int err = SyncCall(env, args[3], &req_wrap_sync, "realpath",
1419
36
                       uv_fs_realpath, *path);
1420

18
    FS_SYNC_TRACE_END(realpath);
1421
18
    if (err < 0) {
1422
2
      return;  // syscall failed, no need to continue, error info is in ctx
1423
    }
1424
1425
16
    const char* link_path = static_cast<const char*>(req_wrap_sync.req.ptr);
1426
1427
    Local<Value> error;
1428
    MaybeLocal<Value> rc = StringBytes::Encode(isolate,
1429
                                               link_path,
1430
                                               encoding,
1431
16
                                               &error);
1432
16
    if (rc.IsEmpty()) {
1433
      Local<Object> ctx = args[3].As<Object>();
1434
      ctx->Set(env->context(), env->error_string(), error).FromJust();
1435
      return;
1436
    }
1437
1438

32
    args.GetReturnValue().Set(rc.ToLocalChecked());
1439
34
  }
1440
}
1441
1442
14348
static void ReadDir(const FunctionCallbackInfo<Value>& args) {
1443
14348
  Environment* env = Environment::GetCurrent(args);
1444
14348
  Isolate* isolate = env->isolate();
1445
1446
14348
  const int argc = args.Length();
1447
14348
  CHECK_GE(argc, 3);
1448
1449
14348
  BufferValue path(isolate, args[0]);
1450
14348
  CHECK_NOT_NULL(*path);
1451
1452
14348
  const enum encoding encoding = ParseEncoding(isolate, args[1], UTF8);
1453
1454
28696
  bool with_types = args[2]->IsTrue();
1455
1456
14348
  FSReqBase* req_wrap_async = GetReqWrap(env, args[3]);
1457
14348
  if (req_wrap_async != nullptr) {  // readdir(path, encoding, withTypes, req)
1458
32
    if (with_types) {
1459
      AsyncCall(env, req_wrap_async, args, "scandir", encoding,
1460
7
                AfterScanDirWithTypes, uv_fs_scandir, *path, 0 /*flags*/);
1461
    } else {
1462
      AsyncCall(env, req_wrap_async, args, "scandir", encoding,
1463
25
                AfterScanDir, uv_fs_scandir, *path, 0 /*flags*/);
1464
    }
1465
  } else {  // readdir(path, encoding, withTypes, undefined, ctx)
1466
14316
    CHECK_EQ(argc, 5);
1467
14316
    FSReqWrapSync req_wrap_sync;
1468

14316
    FS_SYNC_TRACE_BEGIN(readdir);
1469
    int err = SyncCall(env, args[4], &req_wrap_sync, "scandir",
1470
28632
                       uv_fs_scandir, *path, 0 /*flags*/);
1471

14316
    FS_SYNC_TRACE_END(readdir);
1472
14316
    if (err < 0) {
1473
39
      return;  // syscall failed, no need to continue, error info is in ctx
1474
    }
1475
1476
14277
    CHECK_GE(req_wrap_sync.req.result, 0);
1477
    int r;
1478
28554
    std::vector<Local<Value>> name_v;
1479
28554
    std::vector<Local<Value>> type_v;
1480
1481
652309
    for (int i = 0; ; i++) {
1482
      uv_dirent_t ent;
1483
1484
652309
      r = uv_fs_scandir_next(&(req_wrap_sync.req), &ent);
1485
652309
      if (r == UV_EOF)
1486
14277
        break;
1487
638032
      if (r != 0) {
1488
        Local<Object> ctx = args[4].As<Object>();
1489
        ctx->Set(env->context(), env->errno_string(),
1490
                 Integer::New(isolate, r)).FromJust();
1491
        ctx->Set(env->context(), env->syscall_string(),
1492
                 OneByteString(isolate, "readdir")).FromJust();
1493
        return;
1494
      }
1495
1496
      Local<Value> error;
1497
      MaybeLocal<Value> filename = StringBytes::Encode(isolate,
1498
                                                       ent.name,
1499
                                                       encoding,
1500
638032
                                                       &error);
1501
1502
638032
      if (filename.IsEmpty()) {
1503
        Local<Object> ctx = args[4].As<Object>();
1504
        ctx->Set(env->context(), env->error_string(), error).FromJust();
1505
        return;
1506
      }
1507
1508
638032
      name_v.push_back(filename.ToLocalChecked());
1509
1510
638032
      if (with_types) {
1511
20
        type_v.push_back(Integer::New(isolate, ent.type));
1512
      }
1513
638032
    }
1514
1515
1516
14277
    Local<Array> names = Array::New(isolate, name_v.data(), name_v.size());
1517
14277
    if (with_types) {
1518
2
      Local<Array> result = Array::New(isolate, 2);
1519
6
      result->Set(env->context(), 0, names).FromJust();
1520
2
      result->Set(env->context(),
1521
                  1,
1522
                  Array::New(isolate, type_v.data(),
1523
8
                             type_v.size())).FromJust();
1524
4
      args.GetReturnValue().Set(result);
1525
    } else {
1526
28550
      args.GetReturnValue().Set(names);
1527
14277
    }
1528
14309
  }
1529
}
1530
1531
461754
static void Open(const FunctionCallbackInfo<Value>& args) {
1532
461754
  Environment* env = Environment::GetCurrent(args);
1533
1534
461754
  const int argc = args.Length();
1535
461754
  CHECK_GE(argc, 3);
1536
1537
461754
  BufferValue path(env->isolate(), args[0]);
1538
461754
  CHECK_NOT_NULL(*path);
1539
1540
923508
  CHECK(args[1]->IsInt32());
1541
1385262
  const int flags = args[1].As<Int32>()->Value();
1542
1543
923508
  CHECK(args[2]->IsInt32());
1544
1385262
  const int mode = args[2].As<Int32>()->Value();
1545
1546
461754
  FSReqBase* req_wrap_async = GetReqWrap(env, args[3]);
1547
461754
  if (req_wrap_async != nullptr) {  // open(path, flags, mode, req)
1548
    AsyncCall(env, req_wrap_async, args, "open", UTF8, AfterInteger,
1549
5489
              uv_fs_open, *path, flags, mode);
1550
  } else {  // open(path, flags, mode, undefined, ctx)
1551
456265
    CHECK_EQ(argc, 5);
1552
456265
    FSReqWrapSync req_wrap_sync;
1553

456265
    FS_SYNC_TRACE_BEGIN(open);
1554
    int result = SyncCall(env, args[4], &req_wrap_sync, "open",
1555
912530
                          uv_fs_open, *path, flags, mode);
1556

456265
    FS_SYNC_TRACE_END(open);
1557
912530
    args.GetReturnValue().Set(result);
1558
461754
  }
1559
461754
}
1560
1561
63
static void OpenFileHandle(const FunctionCallbackInfo<Value>& args) {
1562
63
  Environment* env = Environment::GetCurrent(args);
1563
63
  Isolate* isolate = env->isolate();
1564
1565
63
  const int argc = args.Length();
1566
63
  CHECK_GE(argc, 3);
1567
1568
63
  BufferValue path(isolate, args[0]);
1569
63
  CHECK_NOT_NULL(*path);
1570
1571
126
  CHECK(args[1]->IsInt32());
1572
189
  const int flags = args[1].As<Int32>()->Value();
1573
1574
126
  CHECK(args[2]->IsInt32());
1575
189
  const int mode = args[2].As<Int32>()->Value();
1576
1577
63
  FSReqBase* req_wrap_async = GetReqWrap(env, args[3]);
1578
63
  if (req_wrap_async != nullptr) {  // openFileHandle(path, flags, mode, req)
1579
    AsyncCall(env, req_wrap_async, args, "open", UTF8, AfterOpenFileHandle,
1580
62
              uv_fs_open, *path, flags, mode);
1581
  } else {  // openFileHandle(path, flags, mode, undefined, ctx)
1582
1
    CHECK_EQ(argc, 5);
1583
1
    FSReqWrapSync req_wrap_sync;
1584

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

1
    FS_SYNC_TRACE_END(open);
1588
1
    if (result < 0) {
1589
      return;  // syscall failed, no need to continue, error info is in ctx
1590
    }
1591
1
    FileHandle* fd = FileHandle::New(env, result);
1592
1
    if (fd == nullptr) return;
1593

3
    args.GetReturnValue().Set(fd->object());
1594
63
  }
1595
}
1596
1597
33
static void CopyFile(const FunctionCallbackInfo<Value>& args) {
1598
33
  Environment* env = Environment::GetCurrent(args);
1599
33
  Isolate* isolate = env->isolate();
1600
1601
33
  const int argc = args.Length();
1602
33
  CHECK_GE(argc, 3);
1603
1604
33
  BufferValue src(isolate, args[0]);
1605
33
  CHECK_NOT_NULL(*src);
1606
1607
66
  BufferValue dest(isolate, args[1]);
1608
33
  CHECK_NOT_NULL(*dest);
1609
1610
66
  CHECK(args[2]->IsInt32());
1611
99
  const int flags = args[2].As<Int32>()->Value();
1612
1613
33
  FSReqBase* req_wrap_async = GetReqWrap(env, args[3]);
1614
33
  if (req_wrap_async != nullptr) {  // copyFile(src, dest, flags, req)
1615
    AsyncDestCall(env, req_wrap_async, args, "copyfile",
1616
13
                  *dest, dest.length(), UTF8, AfterNoArgs,
1617
26
                  uv_fs_copyfile, *src, *dest, flags);
1618
  } else {  // copyFile(src, dest, flags, undefined, ctx)
1619
20
    CHECK_EQ(argc, 5);
1620
20
    FSReqWrapSync req_wrap_sync;
1621

20
    FS_SYNC_TRACE_BEGIN(copyfile);
1622
    SyncCall(env, args[4], &req_wrap_sync, "copyfile",
1623
40
             uv_fs_copyfile, *src, *dest, flags);
1624

20
    FS_SYNC_TRACE_END(copyfile);
1625
33
  }
1626
33
}
1627
1628
1629
// Wrapper for write(2).
1630
//
1631
// bytesWritten = write(fd, buffer, offset, length, position, callback)
1632
// 0 fd        integer. file descriptor
1633
// 1 buffer    the data to write
1634
// 2 offset    where in the buffer to start from
1635
// 3 length    how much to write
1636
// 4 position  if integer, position to write at in the file.
1637
//             if null, write from the current position
1638
145014
static void WriteBuffer(const FunctionCallbackInfo<Value>& args) {
1639
145014
  Environment* env = Environment::GetCurrent(args);
1640
1641
145014
  const int argc = args.Length();
1642
145014
  CHECK_GE(argc, 4);
1643
1644
290028
  CHECK(args[0]->IsInt32());
1645
435042
  const int fd = args[0].As<Int32>()->Value();
1646
1647
145014
  CHECK(Buffer::HasInstance(args[1]));
1648
290028
  Local<Object> buffer_obj = args[1].As<Object>();
1649
145014
  char* buffer_data = Buffer::Data(buffer_obj);
1650
145014
  size_t buffer_length = Buffer::Length(buffer_obj);
1651
1652
290028
  CHECK(args[2]->IsInt32());
1653
435042
  const size_t off = static_cast<size_t>(args[2].As<Int32>()->Value());
1654
145014
  CHECK_LE(off, buffer_length);
1655
1656
290028
  CHECK(args[3]->IsInt32());
1657
435042
  const size_t len = static_cast<size_t>(args[3].As<Int32>()->Value());
1658
145014
  CHECK(Buffer::IsWithinBounds(off, len, buffer_length));
1659
145014
  CHECK_LE(len, buffer_length);
1660
145014
  CHECK_GE(off + len, off);
1661
1662

307758
  const int64_t pos = GET_OFFSET(args[4]);
1663
1664
145014
  char* buf = buffer_data + off;
1665
145014
  uv_buf_t uvbuf = uv_buf_init(const_cast<char*>(buf), len);
1666
1667
145014
  FSReqBase* req_wrap_async = GetReqWrap(env, args[5]);
1668
145014
  if (req_wrap_async != nullptr) {  // write(fd, buffer, off, len, pos, req)
1669
    AsyncCall(env, req_wrap_async, args, "write", UTF8, AfterInteger,
1670
12407
              uv_fs_write, fd, &uvbuf, 1, pos);
1671
  } else {  // write(fd, buffer, off, len, pos, undefined, ctx)
1672
132607
    CHECK_EQ(argc, 7);
1673
132607
    FSReqWrapSync req_wrap_sync;
1674

132607
    FS_SYNC_TRACE_BEGIN(write);
1675
    int bytesWritten = SyncCall(env, args[6], &req_wrap_sync, "write",
1676
132607
                                uv_fs_write, fd, &uvbuf, 1, pos);
1677

132607
    FS_SYNC_TRACE_END(write, "bytesWritten", bytesWritten);
1678
397821
    args.GetReturnValue().Set(bytesWritten);
1679
  }
1680
145014
}
1681
1682
1683
// Wrapper for writev(2).
1684
//
1685
// bytesWritten = writev(fd, chunks, position, callback)
1686
// 0 fd        integer. file descriptor
1687
// 1 chunks    array of buffers to write
1688
// 2 position  if integer, position to write at in the file.
1689
//             if null, write from the current position
1690
13
static void WriteBuffers(const FunctionCallbackInfo<Value>& args) {
1691
13
  Environment* env = Environment::GetCurrent(args);
1692
1693
13
  const int argc = args.Length();
1694
13
  CHECK_GE(argc, 3);
1695
1696
26
  CHECK(args[0]->IsInt32());
1697
39
  const int fd = args[0].As<Int32>()->Value();
1698
1699
26
  CHECK(args[1]->IsArray());
1700
26
  Local<Array> chunks = args[1].As<Array>();
1701
1702

26
  int64_t pos = GET_OFFSET(args[2]);
1703
1704
13
  MaybeStackBuffer<uv_buf_t> iovs(chunks->Length());
1705
1706
66798
  for (uint32_t i = 0; i < iovs.length(); i++) {
1707
200355
    Local<Value> chunk = chunks->Get(env->context(), i).ToLocalChecked();
1708
66785
    CHECK(Buffer::HasInstance(chunk));
1709
66785
    iovs[i] = uv_buf_init(Buffer::Data(chunk), Buffer::Length(chunk));
1710
  }
1711
1712
13
  FSReqBase* req_wrap_async = GetReqWrap(env, args[3]);
1713
13
  if (req_wrap_async != nullptr) {  // writeBuffers(fd, chunks, pos, req)
1714
    AsyncCall(env, req_wrap_async, args, "write", UTF8, AfterInteger,
1715
13
              uv_fs_write, fd, *iovs, iovs.length(), pos);
1716
  } else {  // writeBuffers(fd, chunks, pos, undefined, ctx)
1717
    CHECK_EQ(argc, 5);
1718
    FSReqWrapSync req_wrap_sync;
1719
    FS_SYNC_TRACE_BEGIN(write);
1720
    int bytesWritten = SyncCall(env, args[4], &req_wrap_sync, "write",
1721
                                uv_fs_write, fd, *iovs, iovs.length(), pos);
1722
    FS_SYNC_TRACE_END(write, "bytesWritten", bytesWritten);
1723
    args.GetReturnValue().Set(bytesWritten);
1724
13
  }
1725
13
}
1726
1727
1728
// Wrapper for write(2).
1729
//
1730
// bytesWritten = write(fd, string, position, enc, callback)
1731
// 0 fd        integer. file descriptor
1732
// 1 string    non-buffer values are converted to strings
1733
// 2 position  if integer, position to write at in the file.
1734
//             if null, write from the current position
1735
// 3 enc       encoding of string
1736
1256
static void WriteString(const FunctionCallbackInfo<Value>& args) {
1737
1256
  Environment* env = Environment::GetCurrent(args);
1738
1256
  Isolate* isolate = env->isolate();
1739
1740
1256
  const int argc = args.Length();
1741
1256
  CHECK_GE(argc, 4);
1742
1743
2512
  CHECK(args[0]->IsInt32());
1744
3768
  const int fd = args[0].As<Int32>()->Value();
1745
1746

2626
  const int64_t pos = GET_OFFSET(args[2]);
1747
1748
1256
  const auto enc = ParseEncoding(isolate, args[3], UTF8);
1749
1750
1256
  Local<Value> value = args[1];
1751
1256
  char* buf = nullptr;
1752
  size_t len;
1753
1754
1256
  FSReqBase* req_wrap_async = GetReqWrap(env, args[4]);
1755
1256
  const bool is_async = req_wrap_async != nullptr;
1756
1757
  // Avoid copying the string when it is externalized but only when:
1758
  // 1. The target encoding is compatible with the string's encoding, and
1759
  // 2. The write is synchronous, otherwise the string might get neutered
1760
  //    while the request is in flight, and
1761
  // 3. For UCS2, when the host system is little-endian.  Big-endian systems
1762
  //    need to call StringBytes::Write() to ensure proper byte swapping.
1763
  // The const_casts are conceptually sound: memory is read but not written.
1764

3692
  if (!is_async && value->IsString()) {
1765
1218
    auto string = value.As<String>();
1766


1219
    if ((enc == ASCII || enc == LATIN1) && string->IsExternalOneByte()) {
1767
1
      auto ext = string->GetExternalOneByteStringResource();
1768
1
      buf = const_cast<char*>(ext->data());
1769
1
      len = ext->length();
1770


1218
    } else if (enc == UCS2 && IsLittleEndian() && string->IsExternal()) {
1771
2
      auto ext = string->GetExternalStringResource();
1772
1
      buf = reinterpret_cast<char*>(const_cast<uint16_t*>(ext->data()));
1773
1
      len = ext->length() * sizeof(*ext->data());
1774
    }
1775
  }
1776
1777
1256
  if (is_async) {  // write(fd, string, pos, enc, req)
1778
38
    CHECK_NOT_NULL(req_wrap_async);
1779
76
    if (!StringBytes::StorageSize(isolate, value, enc).To(&len)) return;
1780
    FSReqBase::FSReqBuffer& stack_buffer =
1781
38
        req_wrap_async->Init("write", len, enc);
1782
    // StorageSize may return too large a char, so correct the actual length
1783
    // by the write size
1784
38
    len = StringBytes::Write(isolate, *stack_buffer, len, args[1], enc);
1785
38
    stack_buffer.SetLengthAndZeroTerminate(len);
1786
38
    uv_buf_t uvbuf = uv_buf_init(*stack_buffer, len);
1787
    int err = req_wrap_async->Dispatch(uv_fs_write,
1788
                                       fd,
1789
                                       &uvbuf,
1790
                                       1,
1791
                                       pos,
1792
38
                                       AfterInteger);
1793
38
    if (err < 0) {
1794
      uv_fs_t* uv_req = req_wrap_async->req();
1795
      uv_req->result = err;
1796
      uv_req->path = nullptr;
1797
      AfterInteger(uv_req);  // after may delete req_wrap_async if there is
1798
                             // an error
1799
    } else {
1800
38
      req_wrap_async->SetReturnValue(args);
1801
    }
1802
  } else {  // write(fd, string, pos, enc, undefined, ctx)
1803
1218
    CHECK_EQ(argc, 6);
1804
1218
    FSReqWrapSync req_wrap_sync;
1805
2436
    FSReqBase::FSReqBuffer stack_buffer;
1806
1218
    if (buf == nullptr) {
1807
2432
      if (!StringBytes::StorageSize(isolate, value, enc).To(&len))
1808
        return;
1809
1216
      stack_buffer.AllocateSufficientStorage(len + 1);
1810
      // StorageSize may return too large a char, so correct the actual length
1811
      // by the write size
1812
      len = StringBytes::Write(isolate, *stack_buffer,
1813
1216
                               len, args[1], enc);
1814
1216
      stack_buffer.SetLengthAndZeroTerminate(len);
1815
1216
      buf = *stack_buffer;
1816
    }
1817
1218
    uv_buf_t uvbuf = uv_buf_init(buf, len);
1818

1218
    FS_SYNC_TRACE_BEGIN(write);
1819
    int bytesWritten = SyncCall(env, args[5], &req_wrap_sync, "write",
1820
1218
                                uv_fs_write, fd, &uvbuf, 1, pos);
1821

1218
    FS_SYNC_TRACE_END(write, "bytesWritten", bytesWritten);
1822
4872
    args.GetReturnValue().Set(bytesWritten);
1823
  }
1824
}
1825
1826
1827
/*
1828
 * Wrapper for read(2).
1829
 *
1830
 * bytesRead = fs.read(fd, buffer, offset, length, position)
1831
 *
1832
 * 0 fd        int32. file descriptor
1833
 * 1 buffer    instance of Buffer
1834
 * 2 offset    int32. offset to start reading into inside buffer
1835
 * 3 length    int32. length to read
1836
 * 4 position  int64. file position - -1 for current position
1837
 */
1838
595794
static void Read(const FunctionCallbackInfo<Value>& args) {
1839
595794
  Environment* env = Environment::GetCurrent(args);
1840
1841
595794
  const int argc = args.Length();
1842
595794
  CHECK_GE(argc, 5);
1843
1844
1191588
  CHECK(args[0]->IsInt32());
1845
1787382
  const int fd = args[0].As<Int32>()->Value();
1846
1847
595794
  CHECK(Buffer::HasInstance(args[1]));
1848
1191588
  Local<Object> buffer_obj = args[1].As<Object>();
1849
595794
  char* buffer_data = Buffer::Data(buffer_obj);
1850
595794
  size_t buffer_length = Buffer::Length(buffer_obj);
1851
1852
1191588
  CHECK(args[2]->IsInt32());
1853
1787382
  const size_t off = static_cast<size_t>(args[2].As<Int32>()->Value());
1854
595794
  CHECK_LT(off, buffer_length);
1855
1856
1191588
  CHECK(args[3]->IsInt32());
1857
1787382
  const size_t len = static_cast<size_t>(args[3].As<Int32>()->Value());
1858
595794
  CHECK(Buffer::IsWithinBounds(off, len, buffer_length));
1859
1860
1191588
  CHECK(args[4]->IsNumber());
1861
1787382
  const int64_t pos = args[4].As<Integer>()->Value();
1862
1863
595794
  char* buf = buffer_data + off;
1864
595794
  uv_buf_t uvbuf = uv_buf_init(const_cast<char*>(buf), len);
1865
1866
595794
  FSReqBase* req_wrap_async = GetReqWrap(env, args[5]);
1867
595794
  if (req_wrap_async != nullptr) {  // read(fd, buffer, offset, len, pos, req)
1868
    AsyncCall(env, req_wrap_async, args, "read", UTF8, AfterInteger,
1869
142068
              uv_fs_read, fd, &uvbuf, 1, pos);
1870
  } else {  // read(fd, buffer, offset, len, pos, undefined, ctx)
1871
453726
    CHECK_EQ(argc, 7);
1872
453726
    FSReqWrapSync req_wrap_sync;
1873

453726
    FS_SYNC_TRACE_BEGIN(read);
1874
    const int bytesRead = SyncCall(env, args[6], &req_wrap_sync, "read",
1875
453726
                                   uv_fs_read, fd, &uvbuf, 1, pos);
1876

453726
    FS_SYNC_TRACE_END(read, "bytesRead", bytesRead);
1877
1361178
    args.GetReturnValue().Set(bytesRead);
1878
  }
1879
595794
}
1880
1881
1882
/* fs.chmod(path, mode);
1883
 * Wrapper for chmod(1) / EIO_CHMOD
1884
 */
1885
21
static void Chmod(const FunctionCallbackInfo<Value>& args) {
1886
21
  Environment* env = Environment::GetCurrent(args);
1887
1888
21
  const int argc = args.Length();
1889
21
  CHECK_GE(argc, 2);
1890
1891
21
  BufferValue path(env->isolate(), args[0]);
1892
21
  CHECK_NOT_NULL(*path);
1893
1894
42
  CHECK(args[1]->IsInt32());
1895
63
  int mode = args[1].As<Int32>()->Value();
1896
1897
21
  FSReqBase* req_wrap_async = GetReqWrap(env, args[2]);
1898
21
  if (req_wrap_async != nullptr) {  // chmod(path, mode, req)
1899
    AsyncCall(env, req_wrap_async, args, "chmod", UTF8, AfterNoArgs,
1900
11
              uv_fs_chmod, *path, mode);
1901
  } else {  // chmod(path, mode, undefined, ctx)
1902
10
    CHECK_EQ(argc, 4);
1903
10
    FSReqWrapSync req_wrap_sync;
1904

10
    FS_SYNC_TRACE_BEGIN(chmod);
1905
    SyncCall(env, args[3], &req_wrap_sync, "chmod",
1906
20
             uv_fs_chmod, *path, mode);
1907

10
    FS_SYNC_TRACE_END(chmod);
1908
21
  }
1909
21
}
1910
1911
1912
/* fs.fchmod(fd, mode);
1913
 * Wrapper for fchmod(1) / EIO_FCHMOD
1914
 */
1915
12
static void FChmod(const FunctionCallbackInfo<Value>& args) {
1916
12
  Environment* env = Environment::GetCurrent(args);
1917
1918
12
  const int argc = args.Length();
1919
12
  CHECK_GE(argc, 2);
1920
1921
24
  CHECK(args[0]->IsInt32());
1922
36
  const int fd = args[0].As<Int32>()->Value();
1923
1924
24
  CHECK(args[1]->IsInt32());
1925
36
  const int mode = args[1].As<Int32>()->Value();
1926
1927
12
  FSReqBase* req_wrap_async = GetReqWrap(env, args[2]);
1928
12
  if (req_wrap_async != nullptr) {  // fchmod(fd, mode, req)
1929
    AsyncCall(env, req_wrap_async, args, "fchmod", UTF8, AfterNoArgs,
1930
7
              uv_fs_fchmod, fd, mode);
1931
  } else {  // fchmod(fd, mode, undefined, ctx)
1932
5
    CHECK_EQ(argc, 4);
1933
5
    FSReqWrapSync req_wrap_sync;
1934

5
    FS_SYNC_TRACE_BEGIN(fchmod);
1935
    SyncCall(env, args[3], &req_wrap_sync, "fchmod",
1936
5
             uv_fs_fchmod, fd, mode);
1937

5
    FS_SYNC_TRACE_END(fchmod);
1938
  }
1939
12
}
1940
1941
1942
/* fs.chown(path, uid, gid);
1943
 * Wrapper for chown(1) / EIO_CHOWN
1944
 */
1945
5
static void Chown(const FunctionCallbackInfo<Value>& args) {
1946
5
  Environment* env = Environment::GetCurrent(args);
1947
1948
5
  const int argc = args.Length();
1949
5
  CHECK_GE(argc, 3);
1950
1951
5
  BufferValue path(env->isolate(), args[0]);
1952
5
  CHECK_NOT_NULL(*path);
1953
1954
10
  CHECK(args[1]->IsUint32());
1955
15
  const uv_uid_t uid = static_cast<uv_uid_t>(args[1].As<Uint32>()->Value());
1956
1957
10
  CHECK(args[2]->IsUint32());
1958
15
  const uv_gid_t gid = static_cast<uv_gid_t>(args[2].As<Uint32>()->Value());
1959
1960
5
  FSReqBase* req_wrap_async = GetReqWrap(env, args[3]);
1961
5
  if (req_wrap_async != nullptr) {  // chown(path, uid, gid, req)
1962
    AsyncCall(env, req_wrap_async, args, "chown", UTF8, AfterNoArgs,
1963
3
              uv_fs_chown, *path, uid, gid);
1964
  } else {  // chown(path, uid, gid, undefined, ctx)
1965
2
    CHECK_EQ(argc, 5);
1966
2
    FSReqWrapSync req_wrap_sync;
1967

2
    FS_SYNC_TRACE_BEGIN(chown);
1968
    SyncCall(env, args[4], &req_wrap_sync, "chown",
1969
4
             uv_fs_chown, *path, uid, gid);
1970

2
    FS_SYNC_TRACE_END(chown);
1971
5
  }
1972
5
}
1973
1974
1975
/* fs.fchown(fd, uid, gid);
1976
 * Wrapper for fchown(1) / EIO_FCHOWN
1977
 */
1978
4
static void FChown(const FunctionCallbackInfo<Value>& args) {
1979
4
  Environment* env = Environment::GetCurrent(args);
1980
1981
4
  const int argc = args.Length();
1982
4
  CHECK_GE(argc, 3);
1983
1984
8
  CHECK(args[0]->IsInt32());
1985
12
  const int fd = args[0].As<Int32>()->Value();
1986
1987
8
  CHECK(args[1]->IsUint32());
1988
12
  const uv_uid_t uid = static_cast<uv_uid_t>(args[1].As<Uint32>()->Value());
1989
1990
8
  CHECK(args[2]->IsUint32());
1991
12
  const uv_gid_t gid = static_cast<uv_gid_t>(args[2].As<Uint32>()->Value());
1992
1993
4
  FSReqBase* req_wrap_async = GetReqWrap(env, args[3]);
1994
4
  if (req_wrap_async != nullptr) {  // fchown(fd, uid, gid, req)
1995
    AsyncCall(env, req_wrap_async, args, "fchown", UTF8, AfterNoArgs,
1996
2
              uv_fs_fchown, fd, uid, gid);
1997
  } else {  // fchown(fd, uid, gid, undefined, ctx)
1998
2
    CHECK_EQ(argc, 5);
1999
2
    FSReqWrapSync req_wrap_sync;
2000

2
    FS_SYNC_TRACE_BEGIN(fchown);
2001
    SyncCall(env, args[4], &req_wrap_sync, "fchown",
2002
2
             uv_fs_fchown, fd, uid, gid);
2003

2
    FS_SYNC_TRACE_END(fchown);
2004
  }
2005
4
}
2006
2007
2008
10
static void LChown(const FunctionCallbackInfo<Value>& args) {
2009
10
  Environment* env = Environment::GetCurrent(args);
2010
2011
10
  const int argc = args.Length();
2012
10
  CHECK_GE(argc, 3);
2013
2014
10
  BufferValue path(env->isolate(), args[0]);
2015
10
  CHECK_NOT_NULL(*path);
2016
2017
20
  CHECK(args[1]->IsUint32());
2018
30
  const uv_uid_t uid = static_cast<uv_uid_t>(args[1].As<Uint32>()->Value());
2019
2020
20
  CHECK(args[2]->IsUint32());
2021
30
  const uv_gid_t gid = static_cast<uv_gid_t>(args[2].As<Uint32>()->Value());
2022
2023
10
  FSReqBase* req_wrap_async = GetReqWrap(env, args[3]);
2024
10
  if (req_wrap_async != nullptr) {  // lchown(path, uid, gid, req)
2025
    AsyncCall(env, req_wrap_async, args, "lchown", UTF8, AfterNoArgs,
2026
8
              uv_fs_lchown, *path, uid, gid);
2027
  } else {  // lchown(path, uid, gid, undefined, ctx)
2028
2
    CHECK_EQ(argc, 5);
2029
2
    FSReqWrapSync req_wrap_sync;
2030

2
    FS_SYNC_TRACE_BEGIN(lchown);
2031
    SyncCall(env, args[4], &req_wrap_sync, "lchown",
2032
4
             uv_fs_lchown, *path, uid, gid);
2033

2
    FS_SYNC_TRACE_END(lchown);
2034
10
  }
2035
10
}
2036
2037
2038
29
static void UTimes(const FunctionCallbackInfo<Value>& args) {
2039
29
  Environment* env = Environment::GetCurrent(args);
2040
2041
29
  const int argc = args.Length();
2042
29
  CHECK_GE(argc, 3);
2043
2044
29
  BufferValue path(env->isolate(), args[0]);
2045
29
  CHECK_NOT_NULL(*path);
2046
2047
58
  CHECK(args[1]->IsNumber());
2048
87
  const double atime = args[1].As<Number>()->Value();
2049
2050
58
  CHECK(args[2]->IsNumber());
2051
87
  const double mtime = args[2].As<Number>()->Value();
2052
2053
29
  FSReqBase* req_wrap_async = GetReqWrap(env, args[3]);
2054
29
  if (req_wrap_async != nullptr) {  // utimes(path, atime, mtime, req)
2055
    AsyncCall(env, req_wrap_async, args, "utime", UTF8, AfterNoArgs,
2056
14
              uv_fs_utime, *path, atime, mtime);
2057
  } else {  // utimes(path, atime, mtime, undefined, ctx)
2058
15
    CHECK_EQ(argc, 5);
2059
15
    FSReqWrapSync req_wrap_sync;
2060

15
    FS_SYNC_TRACE_BEGIN(utimes);
2061
    SyncCall(env, args[4], &req_wrap_sync, "utime",
2062
30
             uv_fs_utime, *path, atime, mtime);
2063

15
    FS_SYNC_TRACE_END(utimes);
2064
29
  }
2065
29
}
2066
2067
725
static void FUTimes(const FunctionCallbackInfo<Value>& args) {
2068
725
  Environment* env = Environment::GetCurrent(args);
2069
2070
725
  const int argc = args.Length();
2071
725
  CHECK_GE(argc, 3);
2072
2073
1450
  CHECK(args[0]->IsInt32());
2074
2175
  const int fd = args[0].As<Int32>()->Value();
2075
2076
1450
  CHECK(args[1]->IsNumber());
2077
2175
  const double atime = args[1].As<Number>()->Value();
2078
2079
1450
  CHECK(args[2]->IsNumber());
2080
2175
  const double mtime = args[2].As<Number>()->Value();
2081
2082
725
  FSReqBase* req_wrap_async = GetReqWrap(env, args[3]);
2083
725
  if (req_wrap_async != nullptr) {  // futimes(fd, atime, mtime, req)
2084
    AsyncCall(env, req_wrap_async, args, "futime", UTF8, AfterNoArgs,
2085
717
              uv_fs_futime, fd, atime, mtime);
2086
  } else {  // futimes(fd, atime, mtime, undefined, ctx)
2087
8
    CHECK_EQ(argc, 5);
2088
8
    FSReqWrapSync req_wrap_sync;
2089

8
    FS_SYNC_TRACE_BEGIN(futimes);
2090
    SyncCall(env, args[4], &req_wrap_sync, "futime",
2091
8
             uv_fs_futime, fd, atime, mtime);
2092

8
    FS_SYNC_TRACE_END(futimes);
2093
  }
2094
725
}
2095
2096
12
static void Mkdtemp(const FunctionCallbackInfo<Value>& args) {
2097
12
  Environment* env = Environment::GetCurrent(args);
2098
12
  Isolate* isolate = env->isolate();
2099
2100
12
  const int argc = args.Length();
2101
12
  CHECK_GE(argc, 2);
2102
2103
12
  BufferValue tmpl(isolate, args[0]);
2104
12
  CHECK_NOT_NULL(*tmpl);
2105
2106
12
  const enum encoding encoding = ParseEncoding(isolate, args[1], UTF8);
2107
2108
12
  FSReqBase* req_wrap_async = GetReqWrap(env, args[2]);
2109
12
  if (req_wrap_async != nullptr) {  // mkdtemp(tmpl, encoding, req)
2110
    AsyncCall(env, req_wrap_async, args, "mkdtemp", encoding, AfterStringPath,
2111
5
              uv_fs_mkdtemp, *tmpl);
2112
  } else {  // mkdtemp(tmpl, encoding, undefined, ctx)
2113
7
    CHECK_EQ(argc, 4);
2114
7
    FSReqWrapSync req_wrap_sync;
2115

7
    FS_SYNC_TRACE_BEGIN(mkdtemp);
2116
    SyncCall(env, args[3], &req_wrap_sync, "mkdtemp",
2117
14
             uv_fs_mkdtemp, *tmpl);
2118

7
    FS_SYNC_TRACE_END(mkdtemp);
2119
7
    const char* path = static_cast<const char*>(req_wrap_sync.req.path);
2120
2121
    Local<Value> error;
2122
    MaybeLocal<Value> rc =
2123
7
        StringBytes::Encode(isolate, path, encoding, &error);
2124
7
    if (rc.IsEmpty()) {
2125
      Local<Object> ctx = args[3].As<Object>();
2126
      ctx->Set(env->context(), env->error_string(), error).FromJust();
2127
12
      return;
2128
    }
2129

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