GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — node/src/node_file.cc at master · emacslisp/node Expand file tree/ Copy pathnode_file.ccMore file actions 2449 lines (2060 loc) · 79.5 KB / Copy pathnode_file.ccFile metadata and controls2449 lines (2060 loc) · 79.5 KB 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 "node_file-inl.h" #include "aliased_buffer.h" #include "memory_tracker-inl.h" #include "node_buffer.h" #include "node_process.h" #include "node_stat_watcher.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 <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <cstring> #include <cerrno> #include <climits> #if defined(__MINGW32__) || defined(_MSC_VER) # include <io.h> #endif #include <memory> namespace node { namespace fs { using v8::Array; 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::Local; using v8::MaybeLocal; using v8::Number; using v8::Object; using v8::ObjectTemplate; using v8::Promise; using v8::String; using v8::Symbol; using v8::Uint32; 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) { std::string ret = str; // Remove everything leading up to and including the final path separator. std::string::size_type pos = ret.find_last_of(kPathSeparator); if (pos != std::string::npos) ret = ret.substr(pos + 1); // Strip away the extension, if any. if (ret.size() >= extension.size() && ret.substr(ret.size() - extension.size()) == extension) { ret = ret.substr(0, ret.size() - extension.size()); } return ret; } inline int64_t GetOffset(Local<Value> value) { return IsSafeJsInt(value) ? value.As<Integer>()->Value() : -1; } #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__); // 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() {} FSReqBase::~FSReqBase() {} 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) { Environment* env = binding_data->env(); if (obj.IsEmpty() && !env->fd_constructor_template() ->NewInstance(env->context()) .ToLocal(&obj)) { return nullptr; } return new FileHandle(binding_data, obj, fd); } void FileHandle::New(const FunctionCallbackInfo<Value>& args) { BindingData* binding_data = Unwrap<BindingData>(args.Data()); Environment* env = binding_data->env(); CHECK(args.IsConstructCall()); CHECK(args[0]->IsInt32()); FileHandle* handle = FileHandle::New(binding_data, args[0].As<Int32>()->Value(), args.This()); if (handle == nullptr) return; if (args[1]->IsNumber()) handle->read_offset_ = args[1]->IntegerValue(env->context()).FromJust(); if (args[2]->IsNumber()) handle->read_length_ = args[2]->IntegerValue(env->context()).FromJust(); } 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_); } // 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_) return; uv_fs_t req; int ret = uv_fs_close(env()->event_loop(), &req, fd_, nullptr); 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()->SetUnrefImmediate([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); 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").IsNothing(); } }); } void FileHandle::CloseReq::Resolve() { Isolate* isolate = env()->isolate(); HandleScope scope(isolate); 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); 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(); auto maybe_resolver = Promise::Resolver::New(context); CHECK(!maybe_resolver.IsEmpty()); Local<Promise::Resolver> resolver = maybe_resolver.ToLocalChecked(); Local<Promise> promise = resolver.As<Promise>(); CHECK(!reading_); if (!closed_ && !closing_) { closing_ = true; Local<Object> close_req_obj; if (!env() ->fdclose_constructor_template() ->NewInstance(env()->context()) .ToLocal(&close_req_obj)) { return MaybeLocal<Promise>(); } CloseReq* req = new CloseReq(env(), close_req_obj, promise, object()); auto AfterClose = uv_fs_callback_t{[](uv_fs_t* req) { std::unique_ptr<CloseReq> close(CloseReq::from_req(req)); CHECK_NOT_NULL(close); close->file_handle()->AfterClose(); Isolate* isolate = close->env()->isolate(); if (req->result < 0) { HandleScope handle_scope(isolate); close->Reject(UVException(isolate, req->result, "close")); } else { close->Resolve(); } }}; int ret = req->Dispatch(uv_fs_close, fd_, AfterClose); if (ret < 0) { req->Reject(UVException(isolate, ret, "close")); delete req; } } else { // Already closed. Just reject the promise immediately resolver->Reject(context, UVException(isolate, UV_EBADF, "close")) .Check(); } 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()); // Just act as if this FileHandle has been closed. fd->AfterClose(); } 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); 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); 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_); int 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 wanted_freelist_fill = 100; auto& freelist = handle->binding_data_->file_handle_read_wrap_freelist; if (freelist.size() < wanted_freelist_fill) { 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) { FileHandleCloseWrap* wrap = static_cast<FileHandleCloseWrap*>(req_wrap); closing_ = true; wrap->Dispatch(uv_fs_close, fd_, uv_fs_callback_t{[](uv_fs_t* req) { FileHandleCloseWrap* wrap = static_cast<FileHandleCloseWrap*>( FileHandleCloseWrap::from_req(req)); FileHandle* handle = static_cast<FileHandle*>(wrap->stream()); handle->AfterClose(); int result = 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::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 = Unwrap<BindingData>(args.Data()); 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() { uv_fs_req_cleanup(wrap_->req()); delete wrap_; } // 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) { wrap_->Reject(UVException(wrap_->env()->isolate(), req->result, wrap_->syscall(), nullptr, req->path, wrap_->data())); } bool FSReqAfterScope::Proceed() { 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); 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); if (after.Proceed()) { req_wrap->ResolveStat(&req->statbuf); } } void AfterInteger(uv_fs_t* req) { FSReqBase* req_wrap = FSReqBase::from_req(req); FSReqAfterScope after(req_wrap, req); if (after.Proceed()) req_wrap->Resolve(Integer::New(req_wrap->env()->isolate(), req->result)); } void AfterOpenFileHandle(uv_fs_t* req) { FSReqBase* req_wrap = FSReqBase::from_req(req); FSReqAfterScope after(req_wrap, req); if (after.Proceed()) { FileHandle* fd = FileHandle::New(req_wrap->binding_data(), req->result); if (fd == nullptr) return; req_wrap->Resolve(fd->object()); } } // Reverse the logic applied by path.toNamespacedPath() to create a // namespace-prefixed path. void FromNamespacedPath(std::string* path) { #ifdef _WIN32 if (path->compare(0, 8, "\\\\?\\UNC\\", 8) == 0) { *path = path->substr(8); path->insert(0, "\\\\"); } else if (path->compare(0, 4, "\\\\?\\", 4) == 0) { *path = path->substr(4); } #endif } void AfterMkdirp(uv_fs_t* req) { FSReqBase* req_wrap = FSReqBase::from_req(req); FSReqAfterScope after(req_wrap, req); MaybeLocal<Value> path; Local<Value> error; if (after.Proceed()) { if (!req_wrap->continuation_data()->first_path().empty()) { std::string first_path(req_wrap->continuation_data()->first_path()); FromNamespacedPath(&first_path); path = StringBytes::Encode(req_wrap->env()->isolate(), first_path.c_str(), req_wrap->encoding(), &error); if (path.IsEmpty()) req_wrap->Reject(error); else req_wrap->Resolve(path.ToLocalChecked()); } else { req_wrap->Resolve(Undefined(req_wrap->env()->isolate())); } } } void AfterStringPath(uv_fs_t* req) { FSReqBase* req_wrap = FSReqBase::from_req(req); FSReqAfterScope after(req_wrap, req); 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); 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); if (!after.Proceed()) { return; } Environment* env = req_wrap->env(); Local<Value> error; int r; std::vector<Local<Value>> name_v; for (int i = 0; ; i++) { uv_dirent_t ent; r = uv_fs_scandir_next(req, &ent); if (r == UV_EOF) break; if (r != 0) { return req_wrap->Reject(UVException( env->isolate(), r, nullptr, req_wrap->syscall(), req->path)); } MaybeLocal<Value> filename = StringBytes::Encode(env->isolate(), ent.name, req_wrap->encoding(), &error); if (filename.IsEmpty()) return req_wrap->Reject(error); name_v.push_back(filename.ToLocalChecked()); } req_wrap->Resolve(Array::New(env->isolate(), name_v.data(), name_v.size())); } void AfterScanDirWithTypes(uv_fs_t* req) { FSReqBase* req_wrap = FSReqBase::from_req(req); FSReqAfterScope after(req_wrap, req); 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; for (int i = 0; ; i++) { 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)); } MaybeLocal<Value> filename = StringBytes::Encode(isolate, ent.name, req_wrap->encoding(), &error); if (filename.IsEmpty()) return req_wrap->Reject(error); name_v.push_back(filename.ToLocalChecked()); type_v.emplace_back(Integer::New(isolate, ent.type)); } 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))); } 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); CHECK(args[1]->IsInt32()); int mode = args[1].As<Int32>()->Value(); BufferValue path(isolate, args[0]); CHECK_NOT_NULL(*path); FSReqBase* req_wrap_async = GetReqWrap(args, 2); if (req_wrap_async != nullptr) { // access(path, mode, req) AsyncCall(env, req_wrap_async, args, "access", UTF8, AfterNoArgs, uv_fs_access, *path, mode); } else { // access(path, mode, undefined, ctx) CHECK_EQ(argc, 4); FSReqWrapSync req_wrap_sync; FS_SYNC_TRACE_BEGIN(access); SyncCall(env, args[3], &req_wrap_sync, "access", 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, 2); CHECK(args[0]->IsInt32()); int fd = args[0].As<Int32>()->Value(); FSReqBase* req_wrap_async = GetReqWrap(args, 1); if (req_wrap_async != nullptr) { // close(fd, req) AsyncCall(env, req_wrap_async, args, "close", UTF8, AfterNoArgs, uv_fs_close, fd); } else { // close(fd, undefined, ctx) CHECK_EQ(argc, 3); FSReqWrapSync req_wrap_sync; FS_SYNC_TRACE_BEGIN(close); SyncCall(env, args[2], &req_wrap_sync, "close", uv_fs_close, fd); FS_SYNC_TRACE_END(close); } } // Used to speed up module loading. Returns the contents of the file as // a string or undefined when the file cannot be opened or "main" is not found // in the file. static void InternalModuleReadJSON(const FunctionCallbackInfo<Value>& args) { Environment* env = Environment::GetCurrent(args); Isolate* isolate = env->isolate(); uv_loop_t* loop = env->event_loop(); CHECK(args[0]->IsString()); node::Utf8Value path(isolate, args[0]); if (strlen(*path) != path.length()) return; // Contains a nul byte. uv_fs_t open_req; const int fd = uv_fs_open(loop, &open_req, *path, O_RDONLY, 0, nullptr); uv_fs_req_cleanup(&open_req); if (fd < 0) { return; } auto defer_close = OnScopeLeave([fd, loop]() { uv_fs_t close_req; CHECK_EQ(0, uv_fs_close(loop, &close_req, fd, nullptr)); uv_fs_req_cleanup(&close_req); }); const size_t kBlockSize = 32 << 10; std::vector<char> chars; int64_t offset = 0; ssize_t numchars; do { const size_t start = chars.size(); chars.resize(start + kBlockSize); uv_buf_t buf; buf.base = &chars[start]; buf.len = kBlockSize; uv_fs_t read_req; numchars = uv_fs_read(loop, &read_req, fd, &buf, 1, offset, nullptr); uv_fs_req_cleanup(&read_req); if (numchars < 0) return; offset += numchars; } while (static_cast<size_t>(numchars) == kBlockSize); size_t start = 0; if (offset >= 3 && 0 == memcmp(&chars[0], "\xEF\xBB\xBF", 3)) { start = 3; // Skip UTF-8 BOM. } const size_t size = offset - start; char* p = &chars[start]; char* pe = &chars[size]; char* pos[2]; char** ppos = &pos[0]; while (p < pe) { char c = *p++; if (c == '\\' && p < pe && *p == '"') p++; if (c != '"') continue; *ppos++ = p; if (ppos < &pos[2]) continue; ppos = &pos[0]; char* s = &pos[0][0]; char* se = &pos[1][-1]; // Exclude quote. size_t n = se - s; if (n == 4) { if (0 == memcmp(s, "main", 4)) break; if (0 == memcmp(s, "name", 4)) break; if (0 == memcmp(s, "type", 4)) break; } else if (n == 7) { if (0 == memcmp(s, "exports", 7)) break; } } Local<String> return_value; if (p < pe) { return_value = String::NewFromUtf8(isolate, &chars[start], v8::NewStringType::kNormal, size).ToLocalChecked(); } else { return_value = env->empty_object_string(); } args.GetReturnValue().Set(return_value); } // Used to speed up module loading. Returns 0 if the path refers to // a file, 1 when it's a directory or < 0 on error (usually -ENOENT.) // The speedup comes from not creating thousands of Stat and Error objects. static void InternalModuleStat(const FunctionCallbackInfo<Value>& args) { Environment* env = Environment::GetCurrent(args); CHECK(args[0]->IsString()); node::Utf8Value path(env->isolate(), args[0]); uv_fs_t req; int rc = uv_fs_stat(env->event_loop(), &req, *path, nullptr); if (rc == 0) { const uv_stat_t* const s = static_cast<const uv_stat_t*>(req.ptr); rc = !!(s->st_mode & S_IFDIR); } uv_fs_req_cleanup(&req); args.GetReturnValue().Set(rc); } static void Stat(const FunctionCallbackInfo<Value>& args) { BindingData* binding_data = Unwrap<BindingData>(args.Data()); Environment* env = binding_data->env(); const int argc = args.Length(); CHECK_GE(argc, 2); BufferValue path(env->isolate(), args[0]); CHECK_NOT_NULL(*path); bool use_bigint = args[1]->IsTrue(); FSReqBase* req_wrap_async = GetReqWrap(args, 2, use_bigint); if (req_wrap_async != nullptr) { // stat(path, use_bigint, req) AsyncCall(env, req_wrap_async, args, "stat", UTF8, AfterStat, uv_fs_stat, *path); } else { // stat(path, use_bigint, undefined, ctx) CHECK_EQ(argc, 4); FSReqWrapSync req_wrap_sync; FS_SYNC_TRACE_BEGIN(stat); int err = SyncCall(env, args[3], &req_wrap_sync, "stat", uv_fs_stat, *path); FS_SYNC_TRACE_END(stat); if (err != 0) { return; // error info is in ctx } Local<Value> arr = FillGlobalStatsArray(binding_data, use_bigint, static_cast<const uv_stat_t*>(req_wrap_sync.req.ptr)); args.GetReturnValue().Set(arr); } } static void LStat(const FunctionCallbackInfo<Value>& args) { BindingData* binding_data = Unwrap<BindingData>(args.Data()); Environment* env = binding_data->env(); const int argc = args.Length(); CHECK_GE(argc, 3); BufferValue path(env->isolate(), args[0]); CHECK_NOT_NULL(*path); bool use_bigint = args[1]->IsTrue(); FSReqBase* req_wrap_async = GetReqWrap(args, 2, use_bigint); if (req_wrap_async != nullptr) { // lstat(path, use_bigint, req) AsyncCall(env, req_wrap_async, args, "lstat", UTF8, AfterStat, uv_fs_lstat, *path); } else { // lstat(path, use_bigint, undefined, ctx) CHECK_EQ(argc, 4); FSReqWrapSync req_wrap_sync; FS_SYNC_TRACE_BEGIN(lstat); int err = SyncCall(env, args[3], &req_wrap_sync, "lstat", uv_fs_lstat, |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |