-
Notifications
You must be signed in to change notification settings - Fork 29.6k
/
node_file.cc
3372 lines (2857 loc) Β· 112 KB
/
node_file.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
#include "node_file.h" // NOLINT(build/include_inline)
#include "ada.h"
#include "aliased_buffer-inl.h"
#include "memory_tracker-inl.h"
#include "node_buffer.h"
#include "node_errors.h"
#include "node_external_reference.h"
#include "node_file-inl.h"
#include "node_metadata.h"
#include "node_process-inl.h"
#include "node_stat_watcher.h"
#include "node_url.h"
#include "path.h"
#include "permission/permission.h"
#include "util-inl.h"
#include "tracing/trace_event.h"
#include "req_wrap-inl.h"
#include "stream_base-inl.h"
#include "string_bytes.h"
#include "uv.h"
#if defined(__MINGW32__) || defined(_MSC_VER)
# include <io.h>
#endif
namespace node {
namespace fs {
using v8::Array;
using v8::BigInt;
using v8::Context;
using v8::EscapableHandleScope;
using v8::Function;
using v8::FunctionCallbackInfo;
using v8::FunctionTemplate;
using v8::HandleScope;
using v8::Int32;
using v8::Integer;
using v8::Isolate;
using v8::JustVoid;
using v8::Local;
using v8::Maybe;
using v8::MaybeLocal;
using v8::Nothing;
using v8::Number;
using v8::Object;
using v8::ObjectTemplate;
using v8::Promise;
using v8::String;
using v8::Undefined;
using v8::Value;
#ifndef S_ISDIR
# define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
#endif
#ifdef __POSIX__
constexpr char kPathSeparator = '/';
#else
const char* const kPathSeparator = "\\/";
#endif
std::string Basename(const std::string& str, const std::string& extension) {
// Remove everything leading up to and including the final path separator.
std::string::size_type pos = str.find_last_of(kPathSeparator);
// Starting index for the resulting string
std::size_t start_pos = 0;
// String size to return
std::size_t str_size = str.size();
if (pos != std::string::npos) {
start_pos = pos + 1;
str_size -= start_pos;
}
// Strip away the extension, if any.
if (str_size >= extension.size() &&
str.compare(str.size() - extension.size(),
extension.size(), extension) == 0) {
str_size -= extension.size();
}
return str.substr(start_pos, str_size);
}
inline int64_t GetOffset(Local<Value> value) {
return IsSafeJsInt(value) ? value.As<Integer>()->Value() : -1;
}
static const char* get_fs_func_name_by_type(uv_fs_type req_type) {
switch (req_type) {
#define FS_TYPE_TO_NAME(type, name) \
case UV_FS_##type: \
return name;
FS_TYPE_TO_NAME(OPEN, "open")
FS_TYPE_TO_NAME(CLOSE, "close")
FS_TYPE_TO_NAME(READ, "read")
FS_TYPE_TO_NAME(WRITE, "write")
FS_TYPE_TO_NAME(SENDFILE, "sendfile")
FS_TYPE_TO_NAME(STAT, "stat")
FS_TYPE_TO_NAME(LSTAT, "lstat")
FS_TYPE_TO_NAME(FSTAT, "fstat")
FS_TYPE_TO_NAME(FTRUNCATE, "ftruncate")
FS_TYPE_TO_NAME(UTIME, "utime")
FS_TYPE_TO_NAME(FUTIME, "futime")
FS_TYPE_TO_NAME(ACCESS, "access")
FS_TYPE_TO_NAME(CHMOD, "chmod")
FS_TYPE_TO_NAME(FCHMOD, "fchmod")
FS_TYPE_TO_NAME(FSYNC, "fsync")
FS_TYPE_TO_NAME(FDATASYNC, "fdatasync")
FS_TYPE_TO_NAME(UNLINK, "unlink")
FS_TYPE_TO_NAME(RMDIR, "rmdir")
FS_TYPE_TO_NAME(MKDIR, "mkdir")
FS_TYPE_TO_NAME(MKDTEMP, "mkdtemp")
FS_TYPE_TO_NAME(RENAME, "rename")
FS_TYPE_TO_NAME(SCANDIR, "scandir")
FS_TYPE_TO_NAME(LINK, "link")
FS_TYPE_TO_NAME(SYMLINK, "symlink")
FS_TYPE_TO_NAME(READLINK, "readlink")
FS_TYPE_TO_NAME(CHOWN, "chown")
FS_TYPE_TO_NAME(FCHOWN, "fchown")
FS_TYPE_TO_NAME(REALPATH, "realpath")
FS_TYPE_TO_NAME(COPYFILE, "copyfile")
FS_TYPE_TO_NAME(LCHOWN, "lchown")
FS_TYPE_TO_NAME(STATFS, "statfs")
FS_TYPE_TO_NAME(MKSTEMP, "mkstemp")
FS_TYPE_TO_NAME(LUTIME, "lutime")
#undef FS_TYPE_TO_NAME
default:
return "unknown";
}
}
#define TRACE_NAME(name) "fs.sync." #name
#define GET_TRACE_ENABLED \
(*TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED( \
TRACING_CATEGORY_NODE2(fs, sync)) != 0)
#define FS_SYNC_TRACE_BEGIN(syscall, ...) \
if (GET_TRACE_ENABLED) \
TRACE_EVENT_BEGIN( \
TRACING_CATEGORY_NODE2(fs, sync), TRACE_NAME(syscall), ##__VA_ARGS__);
#define FS_SYNC_TRACE_END(syscall, ...) \
if (GET_TRACE_ENABLED) \
TRACE_EVENT_END( \
TRACING_CATEGORY_NODE2(fs, sync), TRACE_NAME(syscall), ##__VA_ARGS__);
#define FS_ASYNC_TRACE_BEGIN0(fs_type, id) \
TRACE_EVENT_NESTABLE_ASYNC_BEGIN0(TRACING_CATEGORY_NODE2(fs, async), \
get_fs_func_name_by_type(fs_type), \
id);
#define FS_ASYNC_TRACE_END0(fs_type, id) \
TRACE_EVENT_NESTABLE_ASYNC_END0(TRACING_CATEGORY_NODE2(fs, async), \
get_fs_func_name_by_type(fs_type), \
id);
#define FS_ASYNC_TRACE_BEGIN1(fs_type, id, name, value) \
TRACE_EVENT_NESTABLE_ASYNC_BEGIN1(TRACING_CATEGORY_NODE2(fs, async), \
get_fs_func_name_by_type(fs_type), \
id, \
name, \
value);
#define FS_ASYNC_TRACE_END1(fs_type, id, name, value) \
TRACE_EVENT_NESTABLE_ASYNC_END1(TRACING_CATEGORY_NODE2(fs, async), \
get_fs_func_name_by_type(fs_type), \
id, \
name, \
value);
#define FS_ASYNC_TRACE_BEGIN2(fs_type, id, name1, value1, name2, value2) \
TRACE_EVENT_NESTABLE_ASYNC_BEGIN2(TRACING_CATEGORY_NODE2(fs, async), \
get_fs_func_name_by_type(fs_type), \
id, \
name1, \
value1, \
name2, \
value2);
#define FS_ASYNC_TRACE_END2(fs_type, id, name1, value1, name2, value2) \
TRACE_EVENT_NESTABLE_ASYNC_END2(TRACING_CATEGORY_NODE2(fs, async), \
get_fs_func_name_by_type(fs_type), \
id, \
name1, \
value1, \
name2, \
value2);
// We sometimes need to convert a C++ lambda function to a raw C-style function.
// This is helpful, because ReqWrap::Dispatch() does not recognize lambda
// functions, and thus does not wrap them properly.
typedef void(*uv_fs_callback_t)(uv_fs_t*);
void FSContinuationData::MemoryInfo(MemoryTracker* tracker) const {
tracker->TrackField("paths", paths_);
}
FileHandleReadWrap::~FileHandleReadWrap() = default;
FSReqBase::~FSReqBase() = default;
void FSReqBase::MemoryInfo(MemoryTracker* tracker) const {
tracker->TrackField("continuation_data", continuation_data_);
}
// The FileHandle object wraps a file descriptor and will close it on garbage
// collection if necessary. If that happens, a process warning will be
// emitted (or a fatal exception will occur if the fd cannot be closed.)
FileHandle::FileHandle(BindingData* binding_data,
Local<Object> obj, int fd)
: AsyncWrap(binding_data->env(), obj, AsyncWrap::PROVIDER_FILEHANDLE),
StreamBase(env()),
fd_(fd),
binding_data_(binding_data) {
MakeWeak();
StreamBase::AttachToObject(GetObject());
}
FileHandle* FileHandle::New(BindingData* binding_data,
int fd,
Local<Object> obj,
std::optional<int64_t> maybeOffset,
std::optional<int64_t> maybeLength) {
Environment* env = binding_data->env();
if (obj.IsEmpty() && !env->fd_constructor_template()
->NewInstance(env->context())
.ToLocal(&obj)) {
return nullptr;
}
auto handle = new FileHandle(binding_data, obj, fd);
if (maybeOffset.has_value()) handle->read_offset_ = maybeOffset.value();
if (maybeLength.has_value()) handle->read_length_ = maybeLength.value();
return handle;
}
void FileHandle::New(const FunctionCallbackInfo<Value>& args) {
CHECK(args.IsConstructCall());
CHECK(args[0]->IsInt32());
Realm* realm = Realm::GetCurrent(args);
BindingData* binding_data = realm->GetBindingData<BindingData>();
std::optional<int64_t> maybeOffset = std::nullopt;
std::optional<int64_t> maybeLength = std::nullopt;
if (args[1]->IsNumber())
maybeOffset = args[1]->IntegerValue(realm->context()).FromJust();
if (args[2]->IsNumber())
maybeLength = args[2]->IntegerValue(realm->context()).FromJust();
FileHandle::New(binding_data,
args[0].As<Int32>()->Value(),
args.This(),
maybeOffset,
maybeLength);
}
FileHandle::~FileHandle() {
CHECK(!closing_); // We should not be deleting while explicitly closing!
Close(); // Close synchronously and emit warning
CHECK(closed_); // We have to be closed at the point
}
int FileHandle::DoWrite(WriteWrap* w,
uv_buf_t* bufs,
size_t count,
uv_stream_t* send_handle) {
return UV_ENOSYS; // Not implemented (yet).
}
void FileHandle::MemoryInfo(MemoryTracker* tracker) const {
tracker->TrackField("current_read", current_read_);
}
BaseObject::TransferMode FileHandle::GetTransferMode() const {
return reading_ || closing_ || closed_
? TransferMode::kDisallowCloneAndTransfer
: TransferMode::kTransferable;
}
std::unique_ptr<worker::TransferData> FileHandle::TransferForMessaging() {
CHECK_NE(GetTransferMode(), TransferMode::kDisallowCloneAndTransfer);
auto ret = std::make_unique<TransferData>(fd_);
closed_ = true;
return ret;
}
FileHandle::TransferData::TransferData(int fd) : fd_(fd) {}
FileHandle::TransferData::~TransferData() {
if (fd_ > 0) {
uv_fs_t close_req;
CHECK_NE(fd_, -1);
FS_SYNC_TRACE_BEGIN(close);
CHECK_EQ(0, uv_fs_close(nullptr, &close_req, fd_, nullptr));
FS_SYNC_TRACE_END(close);
uv_fs_req_cleanup(&close_req);
}
}
BaseObjectPtr<BaseObject> FileHandle::TransferData::Deserialize(
Environment* env,
v8::Local<v8::Context> context,
std::unique_ptr<worker::TransferData> self) {
BindingData* bd = Realm::GetBindingData<BindingData>(context);
if (bd == nullptr) return {};
int fd = fd_;
fd_ = -1;
return BaseObjectPtr<BaseObject> { FileHandle::New(bd, fd) };
}
// Close the file descriptor if it hasn't already been closed. A process
// warning will be emitted using a SetImmediate to avoid calling back to
// JS during GC. If closing the fd fails at this point, a fatal exception
// will crash the process immediately.
inline void FileHandle::Close() {
if (closed_ || closing_) return;
uv_fs_t req;
CHECK_NE(fd_, -1);
FS_SYNC_TRACE_BEGIN(close);
int ret = uv_fs_close(env()->event_loop(), &req, fd_, nullptr);
FS_SYNC_TRACE_END(close);
uv_fs_req_cleanup(&req);
struct err_detail { int ret; int fd; };
err_detail detail { ret, fd_ };
AfterClose();
if (ret < 0) {
// Do not unref this
env()->SetImmediate([detail](Environment* env) {
char msg[70];
snprintf(msg, arraysize(msg),
"Closing file descriptor %d on garbage collection failed",
detail.fd);
// This exception will end up being fatal for the process because
// it is being thrown from within the SetImmediate handler and
// there is no JS stack to bubble it to. In other words, tearing
// down the process is the only reasonable thing we can do here.
HandleScope handle_scope(env->isolate());
env->ThrowUVException(detail.ret, "close", msg);
});
return;
}
// If the close was successful, we still want to emit a process warning
// to notify that the file descriptor was gc'd. We want to be noisy about
// this because not explicitly closing the FileHandle is a bug.
env()->SetImmediate([detail](Environment* env) {
ProcessEmitWarning(env,
"Closing file descriptor %d on garbage collection",
detail.fd);
if (env->filehandle_close_warning()) {
env->set_filehandle_close_warning(false);
USE(ProcessEmitDeprecationWarning(
env,
"Closing a FileHandle object on garbage collection is deprecated. "
"Please close FileHandle objects explicitly using "
"FileHandle.prototype.close(). In the future, an error will be "
"thrown if a file descriptor is closed during garbage collection.",
"DEP0137"));
}
}, CallbackFlags::kUnrefed);
}
void FileHandle::CloseReq::Resolve() {
Isolate* isolate = env()->isolate();
HandleScope scope(isolate);
Context::Scope context_scope(env()->context());
InternalCallbackScope callback_scope(this);
Local<Promise> promise = promise_.Get(isolate);
Local<Promise::Resolver> resolver = promise.As<Promise::Resolver>();
resolver->Resolve(env()->context(), Undefined(isolate)).Check();
}
void FileHandle::CloseReq::Reject(Local<Value> reason) {
Isolate* isolate = env()->isolate();
HandleScope scope(isolate);
Context::Scope context_scope(env()->context());
InternalCallbackScope callback_scope(this);
Local<Promise> promise = promise_.Get(isolate);
Local<Promise::Resolver> resolver = promise.As<Promise::Resolver>();
resolver->Reject(env()->context(), reason).Check();
}
FileHandle* FileHandle::CloseReq::file_handle() {
Isolate* isolate = env()->isolate();
HandleScope scope(isolate);
Local<Value> val = ref_.Get(isolate);
Local<Object> obj = val.As<Object>();
return Unwrap<FileHandle>(obj);
}
FileHandle::CloseReq::CloseReq(Environment* env,
Local<Object> obj,
Local<Promise> promise,
Local<Value> ref)
: ReqWrap(env, obj, AsyncWrap::PROVIDER_FILEHANDLECLOSEREQ) {
promise_.Reset(env->isolate(), promise);
ref_.Reset(env->isolate(), ref);
}
FileHandle::CloseReq::~CloseReq() {
uv_fs_req_cleanup(req());
promise_.Reset();
ref_.Reset();
}
void FileHandle::CloseReq::MemoryInfo(MemoryTracker* tracker) const {
tracker->TrackField("promise", promise_);
tracker->TrackField("ref", ref_);
}
// Closes this FileHandle asynchronously and returns a Promise that will be
// resolved when the callback is invoked, or rejects with a UVException if
// there was a problem closing the fd. This is the preferred mechanism for
// closing the FD object even tho the object will attempt to close
// automatically on gc.
MaybeLocal<Promise> FileHandle::ClosePromise() {
Isolate* isolate = env()->isolate();
EscapableHandleScope scope(isolate);
Local<Context> context = env()->context();
Local<Value> close_resolver =
object()->GetInternalField(FileHandle::kClosingPromiseSlot).As<Value>();
if (close_resolver->IsPromise()) {
return close_resolver.As<Promise>();
}
CHECK(!closed_);
CHECK(!closing_);
CHECK(!reading_);
auto maybe_resolver = Promise::Resolver::New(context);
CHECK(!maybe_resolver.IsEmpty());
Local<Promise::Resolver> resolver = maybe_resolver.ToLocalChecked();
Local<Promise> promise = resolver.As<Promise>();
Local<Object> close_req_obj;
if (!env()->fdclose_constructor_template()
->NewInstance(env()->context()).ToLocal(&close_req_obj)) {
return MaybeLocal<Promise>();
}
closing_ = true;
object()->SetInternalField(FileHandle::kClosingPromiseSlot, promise);
CloseReq* req = new CloseReq(env(), close_req_obj, promise, object());
auto AfterClose = uv_fs_callback_t{[](uv_fs_t* req) {
CloseReq* req_wrap = CloseReq::from_req(req);
FS_ASYNC_TRACE_END1(
req->fs_type, req_wrap, "result", static_cast<int>(req->result))
BaseObjectPtr<CloseReq> close(req_wrap);
CHECK(close);
close->file_handle()->AfterClose();
if (!close->env()->can_call_into_js()) return;
Isolate* isolate = close->env()->isolate();
if (req->result < 0) {
HandleScope handle_scope(isolate);
close->Reject(
UVException(isolate, static_cast<int>(req->result), "close"));
} else {
close->Resolve();
}
}};
CHECK_NE(fd_, -1);
FS_ASYNC_TRACE_BEGIN0(UV_FS_CLOSE, req)
int ret = req->Dispatch(uv_fs_close, fd_, AfterClose);
if (ret < 0) {
req->Reject(UVException(isolate, ret, "close"));
delete req;
}
return scope.Escape(promise);
}
void FileHandle::Close(const FunctionCallbackInfo<Value>& args) {
FileHandle* fd;
ASSIGN_OR_RETURN_UNWRAP(&fd, args.Holder());
Local<Promise> ret;
if (!fd->ClosePromise().ToLocal(&ret)) return;
args.GetReturnValue().Set(ret);
}
void FileHandle::ReleaseFD(const FunctionCallbackInfo<Value>& args) {
FileHandle* fd;
ASSIGN_OR_RETURN_UNWRAP(&fd, args.Holder());
fd->Release();
}
int FileHandle::Release() {
int fd = GetFD();
// Just pretend that Close was called and we're all done.
AfterClose();
return fd;
}
void FileHandle::AfterClose() {
closing_ = false;
closed_ = true;
fd_ = -1;
if (reading_ && !persistent().IsEmpty())
EmitRead(UV_EOF);
}
void FileHandleReadWrap::MemoryInfo(MemoryTracker* tracker) const {
tracker->TrackField("buffer", buffer_);
tracker->TrackField("file_handle", this->file_handle_);
}
FileHandleReadWrap::FileHandleReadWrap(FileHandle* handle, Local<Object> obj)
: ReqWrap(handle->env(), obj, AsyncWrap::PROVIDER_FSREQCALLBACK),
file_handle_(handle) {}
int FileHandle::ReadStart() {
if (!IsAlive() || IsClosing())
return UV_EOF;
reading_ = true;
if (current_read_)
return 0;
BaseObjectPtr<FileHandleReadWrap> read_wrap;
if (read_length_ == 0) {
EmitRead(UV_EOF);
return 0;
}
{
// Create a new FileHandleReadWrap or re-use one.
// Either way, we need these two scopes for AsyncReset() or otherwise
// for creating the new instance.
HandleScope handle_scope(env()->isolate());
AsyncHooks::DefaultTriggerAsyncIdScope trigger_scope(this);
auto& freelist = binding_data_->file_handle_read_wrap_freelist;
if (freelist.size() > 0) {
read_wrap = std::move(freelist.back());
freelist.pop_back();
// Use a fresh async resource.
// Lifetime is ensured via AsyncWrap::resource_.
Local<Object> resource = Object::New(env()->isolate());
USE(resource->Set(
env()->context(), env()->handle_string(), read_wrap->object()));
read_wrap->AsyncReset(resource);
read_wrap->file_handle_ = this;
} else {
Local<Object> wrap_obj;
if (!env()
->filehandlereadwrap_template()
->NewInstance(env()->context())
.ToLocal(&wrap_obj)) {
return UV_EBUSY;
}
read_wrap = MakeDetachedBaseObject<FileHandleReadWrap>(this, wrap_obj);
}
}
int64_t recommended_read = 65536;
if (read_length_ >= 0 && read_length_ <= recommended_read)
recommended_read = read_length_;
read_wrap->buffer_ = EmitAlloc(recommended_read);
current_read_ = std::move(read_wrap);
FS_ASYNC_TRACE_BEGIN0(UV_FS_READ, current_read_.get())
current_read_->Dispatch(uv_fs_read,
fd_,
¤t_read_->buffer_,
1,
read_offset_,
uv_fs_callback_t{[](uv_fs_t* req) {
FileHandle* handle;
{
FileHandleReadWrap* req_wrap = FileHandleReadWrap::from_req(req);
FS_ASYNC_TRACE_END1(
req->fs_type, req_wrap, "result", static_cast<int>(req->result))
handle = req_wrap->file_handle_;
CHECK_EQ(handle->current_read_.get(), req_wrap);
}
// ReadStart() checks whether current_read_ is set to determine whether
// a read is in progress. Moving it into a local variable makes sure that
// the ReadStart() call below doesn't think we're still actively reading.
BaseObjectPtr<FileHandleReadWrap> read_wrap =
std::move(handle->current_read_);
ssize_t result = req->result;
uv_buf_t buffer = read_wrap->buffer_;
uv_fs_req_cleanup(req);
// Push the read wrap back to the freelist, or let it be destroyed
// once weβre exiting the current scope.
constexpr size_t kWantedFreelistFill = 100;
auto& freelist = handle->binding_data_->file_handle_read_wrap_freelist;
if (freelist.size() < kWantedFreelistFill) {
read_wrap->Reset();
freelist.emplace_back(std::move(read_wrap));
}
if (result >= 0) {
// Read at most as many bytes as we originally planned to.
if (handle->read_length_ >= 0 && handle->read_length_ < result)
result = handle->read_length_;
// If we read data and we have an expected length, decrease it by
// how much we have read.
if (handle->read_length_ >= 0)
handle->read_length_ -= result;
// If we have an offset, increase it by how much we have read.
if (handle->read_offset_ >= 0)
handle->read_offset_ += result;
}
// Reading 0 bytes from a file always means EOF, or that we reached
// the end of the requested range.
if (result == 0)
result = UV_EOF;
handle->EmitRead(result, buffer);
// Start over, if EmitRead() didnβt tell us to stop.
if (handle->reading_)
handle->ReadStart();
}});
return 0;
}
int FileHandle::ReadStop() {
reading_ = false;
return 0;
}
typedef SimpleShutdownWrap<ReqWrap<uv_fs_t>> FileHandleCloseWrap;
ShutdownWrap* FileHandle::CreateShutdownWrap(Local<Object> object) {
return new FileHandleCloseWrap(this, object);
}
int FileHandle::DoShutdown(ShutdownWrap* req_wrap) {
if (closing_ || closed_) {
req_wrap->Done(0);
return 1;
}
FileHandleCloseWrap* wrap = static_cast<FileHandleCloseWrap*>(req_wrap);
closing_ = true;
CHECK_NE(fd_, -1);
FS_ASYNC_TRACE_BEGIN0(UV_FS_CLOSE, wrap)
wrap->Dispatch(uv_fs_close, fd_, uv_fs_callback_t{[](uv_fs_t* req) {
FileHandleCloseWrap* wrap = static_cast<FileHandleCloseWrap*>(
FileHandleCloseWrap::from_req(req));
FS_ASYNC_TRACE_END1(
req->fs_type, wrap, "result", static_cast<int>(req->result))
FileHandle* handle = static_cast<FileHandle*>(wrap->stream());
handle->AfterClose();
int result = static_cast<int>(req->result);
uv_fs_req_cleanup(req);
wrap->Done(result);
}});
return 0;
}
void FSReqCallback::Reject(Local<Value> reject) {
MakeCallback(env()->oncomplete_string(), 1, &reject);
}
void FSReqCallback::ResolveStat(const uv_stat_t* stat) {
Resolve(FillGlobalStatsArray(binding_data(), use_bigint(), stat));
}
void FSReqCallback::ResolveStatFs(const uv_statfs_t* stat) {
Resolve(FillGlobalStatFsArray(binding_data(), use_bigint(), stat));
}
void FSReqCallback::Resolve(Local<Value> value) {
Local<Value> argv[2] {
Null(env()->isolate()),
value
};
MakeCallback(env()->oncomplete_string(),
value->IsUndefined() ? 1 : arraysize(argv),
argv);
}
void FSReqCallback::SetReturnValue(const FunctionCallbackInfo<Value>& args) {
args.GetReturnValue().SetUndefined();
}
void NewFSReqCallback(const FunctionCallbackInfo<Value>& args) {
CHECK(args.IsConstructCall());
BindingData* binding_data = Realm::GetBindingData<BindingData>(args);
new FSReqCallback(binding_data, args.This(), args[0]->IsTrue());
}
FSReqAfterScope::FSReqAfterScope(FSReqBase* wrap, uv_fs_t* req)
: wrap_(wrap),
req_(req),
handle_scope_(wrap->env()->isolate()),
context_scope_(wrap->env()->context()) {
CHECK_EQ(wrap_->req(), req);
}
FSReqAfterScope::~FSReqAfterScope() {
Clear();
}
void FSReqAfterScope::Clear() {
if (!wrap_) return;
uv_fs_req_cleanup(wrap_->req());
wrap_->Detach();
wrap_.reset();
}
// TODO(joyeecheung): create a normal context object, and
// construct the actual errors in the JS land using the context.
// The context should include fds for some fs APIs, currently they are
// missing in the error messages. The path, dest, syscall, fd, .etc
// can be put into the context before the binding is even invoked,
// the only information that has to come from the C++ layer is the
// error number (and possibly the syscall for abstraction),
// which is also why the errors should have been constructed
// in JS for more flexibility.
void FSReqAfterScope::Reject(uv_fs_t* req) {
BaseObjectPtr<FSReqBase> wrap { wrap_ };
Local<Value> exception = UVException(wrap_->env()->isolate(),
static_cast<int>(req->result),
wrap_->syscall(),
nullptr,
req->path,
wrap_->data());
Clear();
wrap->Reject(exception);
}
bool FSReqAfterScope::Proceed() {
if (!wrap_->env()->can_call_into_js()) {
return false;
}
if (req_->result < 0) {
Reject(req_);
return false;
}
return true;
}
void AfterNoArgs(uv_fs_t* req) {
FSReqBase* req_wrap = FSReqBase::from_req(req);
FSReqAfterScope after(req_wrap, req);
FS_ASYNC_TRACE_END1(
req->fs_type, req_wrap, "result", static_cast<int>(req->result))
if (after.Proceed())
req_wrap->Resolve(Undefined(req_wrap->env()->isolate()));
}
void AfterStat(uv_fs_t* req) {
FSReqBase* req_wrap = FSReqBase::from_req(req);
FSReqAfterScope after(req_wrap, req);
FS_ASYNC_TRACE_END1(
req->fs_type, req_wrap, "result", static_cast<int>(req->result))
if (after.Proceed()) {
req_wrap->ResolveStat(&req->statbuf);
}
}
void AfterStatFs(uv_fs_t* req) {
FSReqBase* req_wrap = FSReqBase::from_req(req);
FSReqAfterScope after(req_wrap, req);
FS_ASYNC_TRACE_END1(
req->fs_type, req_wrap, "result", static_cast<int>(req->result))
if (after.Proceed()) {
req_wrap->ResolveStatFs(static_cast<uv_statfs_t*>(req->ptr));
}
}
void AfterInteger(uv_fs_t* req) {
FSReqBase* req_wrap = FSReqBase::from_req(req);
FSReqAfterScope after(req_wrap, req);
FS_ASYNC_TRACE_END1(
req->fs_type, req_wrap, "result", static_cast<int>(req->result))
int result = static_cast<int>(req->result);
if (result >= 0 && req_wrap->is_plain_open())
req_wrap->env()->AddUnmanagedFd(result);
if (after.Proceed())
req_wrap->Resolve(Integer::New(req_wrap->env()->isolate(), result));
}
void AfterOpenFileHandle(uv_fs_t* req) {
FSReqBase* req_wrap = FSReqBase::from_req(req);
FSReqAfterScope after(req_wrap, req);
FS_ASYNC_TRACE_END1(
req->fs_type, req_wrap, "result", static_cast<int>(req->result))
if (after.Proceed()) {
FileHandle* fd = FileHandle::New(req_wrap->binding_data(),
static_cast<int>(req->result));
if (fd == nullptr) return;
req_wrap->Resolve(fd->object());
}
}
void AfterMkdirp(uv_fs_t* req) {
FSReqBase* req_wrap = FSReqBase::from_req(req);
FSReqAfterScope after(req_wrap, req);
FS_ASYNC_TRACE_END1(
req->fs_type, req_wrap, "result", static_cast<int>(req->result))
if (after.Proceed()) {
std::string first_path(req_wrap->continuation_data()->first_path());
if (first_path.empty())
return req_wrap->Resolve(Undefined(req_wrap->env()->isolate()));
node::url::FromNamespacedPath(&first_path);
Local<Value> path;
Local<Value> error;
if (!StringBytes::Encode(req_wrap->env()->isolate(), first_path.c_str(),
req_wrap->encoding(),
&error).ToLocal(&path)) {
return req_wrap->Reject(error);
}
return req_wrap->Resolve(path);
}
}
void AfterStringPath(uv_fs_t* req) {
FSReqBase* req_wrap = FSReqBase::from_req(req);
FSReqAfterScope after(req_wrap, req);
FS_ASYNC_TRACE_END1(
req->fs_type, req_wrap, "result", static_cast<int>(req->result))
MaybeLocal<Value> link;
Local<Value> error;
if (after.Proceed()) {
link = StringBytes::Encode(req_wrap->env()->isolate(),
req->path,
req_wrap->encoding(),
&error);
if (link.IsEmpty())
req_wrap->Reject(error);
else
req_wrap->Resolve(link.ToLocalChecked());
}
}
void AfterStringPtr(uv_fs_t* req) {
FSReqBase* req_wrap = FSReqBase::from_req(req);
FSReqAfterScope after(req_wrap, req);
FS_ASYNC_TRACE_END1(
req->fs_type, req_wrap, "result", static_cast<int>(req->result))
MaybeLocal<Value> link;
Local<Value> error;
if (after.Proceed()) {
link = StringBytes::Encode(req_wrap->env()->isolate(),
static_cast<const char*>(req->ptr),
req_wrap->encoding(),
&error);
if (link.IsEmpty())
req_wrap->Reject(error);
else
req_wrap->Resolve(link.ToLocalChecked());
}
}
void AfterScanDir(uv_fs_t* req) {
FSReqBase* req_wrap = FSReqBase::from_req(req);
FSReqAfterScope after(req_wrap, req);
FS_ASYNC_TRACE_END1(
req->fs_type, req_wrap, "result", static_cast<int>(req->result))
if (!after.Proceed()) {
return;
}
Environment* env = req_wrap->env();
Isolate* isolate = env->isolate();
Local<Value> error;
int r;
std::vector<Local<Value>> name_v;
std::vector<Local<Value>> type_v;
const bool with_file_types = req_wrap->with_file_types();
for (;;) {
uv_dirent_t ent;
r = uv_fs_scandir_next(req, &ent);
if (r == UV_EOF)
break;
if (r != 0) {
return req_wrap->Reject(
UVException(isolate, r, nullptr, req_wrap->syscall(), req->path));
}
Local<Value> filename;
if (!StringBytes::Encode(isolate, ent.name, req_wrap->encoding(), &error)
.ToLocal(&filename)) {
return req_wrap->Reject(error);
}
name_v.push_back(filename);
if (with_file_types) type_v.emplace_back(Integer::New(isolate, ent.type));
}
if (with_file_types) {
Local<Value> result[] = {Array::New(isolate, name_v.data(), name_v.size()),
Array::New(isolate, type_v.data(), type_v.size())};
req_wrap->Resolve(Array::New(isolate, result, arraysize(result)));
} else {
req_wrap->Resolve(Array::New(isolate, name_v.data(), name_v.size()));
}
}
void Access(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
Isolate* isolate = env->isolate();
HandleScope scope(isolate);
const int argc = args.Length();
CHECK_GE(argc, 2); // path, mode
int mode;
if (!GetValidFileMode(env, args[1], UV_FS_ACCESS).To(&mode)) {
return;
}
BufferValue path(isolate, args[0]);
CHECK_NOT_NULL(*path);
THROW_IF_INSUFFICIENT_PERMISSIONS(
env, permission::PermissionScope::kFileSystemRead, path.ToStringView());
ToNamespacedPath(env, &path);
if (argc > 2) { // access(path, mode, req)
FSReqBase* req_wrap_async = GetReqWrap(args, 2);
CHECK_NOT_NULL(req_wrap_async);
FS_ASYNC_TRACE_BEGIN1(
UV_FS_ACCESS, req_wrap_async, "path", TRACE_STR_COPY(*path))
AsyncCall(env, req_wrap_async, args, "access", UTF8, AfterNoArgs,
uv_fs_access, *path, mode);
} else { // access(path, mode)
FSReqWrapSync req_wrap_sync("access", *path);
FS_SYNC_TRACE_BEGIN(access);
SyncCallAndThrowOnError(env, &req_wrap_sync, uv_fs_access, *path, mode);
FS_SYNC_TRACE_END(access);
}
}
void Close(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
const int argc = args.Length();
CHECK_GE(argc, 1);
int fd;
if (!GetValidatedFd(env, args[0]).To(&fd)) {
return;
}
env->RemoveUnmanagedFd(fd);
if (argc > 1) { // close(fd, req)
FSReqBase* req_wrap_async = GetReqWrap(args, 1);
CHECK_NOT_NULL(req_wrap_async);
FS_ASYNC_TRACE_BEGIN0(UV_FS_CLOSE, req_wrap_async)
AsyncCall(env, req_wrap_async, args, "close", UTF8, AfterNoArgs,