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 — nodeTest/src/js_native_api_v8.cc at main · aakar/nodeTest Expand file tree/ Copy pathjs_native_api_v8.ccMore file actions 3534 lines (2895 loc) · 121 KB / Copy pathjs_native_api_v8.ccFile metadata and controls3534 lines (2895 loc) · 121 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 #include <algorithm> #include <climits> // INT_MAX #include <cmath> #define NAPI_EXPERIMENTAL #include "env-inl.h" #include "js_native_api.h" #include "js_native_api_v8.h" #include "util-inl.h" #define CHECK_MAYBE_NOTHING(env, maybe, status) \ RETURN_STATUS_IF_FALSE((env), !((maybe).IsNothing()), (status)) #define CHECK_MAYBE_NOTHING_WITH_PREAMBLE(env, maybe, status) \ RETURN_STATUS_IF_FALSE_WITH_PREAMBLE((env), !((maybe).IsNothing()), (status)) #define CHECK_TO_NUMBER(env, context, result, src) \ CHECK_TO_TYPE((env), Number, (context), (result), (src), napi_number_expected) // n-api defines NAPI_AUTO_LENGTH as the indicator that a string // is null terminated. For V8 the equivalent is -1. The assert // validates that our cast of NAPI_AUTO_LENGTH results in -1 as // needed by V8. #define CHECK_NEW_FROM_UTF8_LEN(env, result, str, len) \ do { \ static_assert(static_cast<int>(NAPI_AUTO_LENGTH) == -1, \ "Casting NAPI_AUTO_LENGTH to int must result in -1"); \ RETURN_STATUS_IF_FALSE( \ (env), (len == NAPI_AUTO_LENGTH) || len <= INT_MAX, napi_invalid_arg); \ RETURN_STATUS_IF_FALSE((env), (str) != nullptr, napi_invalid_arg); \ auto str_maybe = v8::String::NewFromUtf8((env)->isolate, \ (str), \ v8::NewStringType::kInternalized, \ static_cast<int>(len)); \ CHECK_MAYBE_EMPTY((env), str_maybe, napi_generic_failure); \ (result) = str_maybe.ToLocalChecked(); \ } while (0) #define CHECK_NEW_FROM_UTF8(env, result, str) \ CHECK_NEW_FROM_UTF8_LEN((env), (result), (str), NAPI_AUTO_LENGTH) #define CHECK_NEW_STRING_ARGS(env, str, length, result) \ do { \ CHECK_ENV_NOT_IN_GC((env)); \ if ((length) > 0) CHECK_ARG((env), (str)); \ CHECK_ARG((env), (result)); \ RETURN_STATUS_IF_FALSE( \ (env), \ ((length) == NAPI_AUTO_LENGTH) || (length) <= INT_MAX, \ napi_invalid_arg); \ } while (0) #define CREATE_TYPED_ARRAY( \ env, type, size_of_element, buffer, byte_offset, length, out) \ do { \ if ((size_of_element) > 1) { \ THROW_RANGE_ERROR_IF_FALSE( \ (env), \ (byte_offset) % (size_of_element) == 0, \ "ERR_NAPI_INVALID_TYPEDARRAY_ALIGNMENT", \ "start offset of " #type \ " should be a multiple of " #size_of_element); \ } \ THROW_RANGE_ERROR_IF_FALSE( \ (env), \ (length) * (size_of_element) + (byte_offset) <= buffer->ByteLength(), \ "ERR_NAPI_INVALID_TYPEDARRAY_LENGTH", \ "Invalid typed array length"); \ (out) = v8::type::New((buffer), (byte_offset), (length)); \ } while (0) void napi_env__::InvokeFinalizerFromGC(v8impl::RefTracker* finalizer) { if (module_api_version != NAPI_VERSION_EXPERIMENTAL) { EnqueueFinalizer(finalizer); } else { // The experimental code calls finalizers immediately to release native // objects as soon as possible. In that state any code that may affect GC // state causes a fatal error. To work around this issue the finalizer code // can call node_api_post_finalizer. auto restore_state = node::OnScopeLeave( [this, saved = in_gc_finalizer] { in_gc_finalizer = saved; }); in_gc_finalizer = true; finalizer->Finalize(); } } namespace v8impl { namespace { template <typename CCharType, typename StringMaker> napi_status NewString(napi_env env, const CCharType* str, size_t length, napi_value* result, StringMaker string_maker) { CHECK_NEW_STRING_ARGS(env, str, length, result); auto isolate = env->isolate; auto str_maybe = string_maker(isolate); CHECK_MAYBE_EMPTY(env, str_maybe, napi_generic_failure); *result = v8impl::JsValueFromV8LocalValue(str_maybe.ToLocalChecked()); return napi_clear_last_error(env); } template <typename CharType, typename CreateAPI, typename StringMaker> napi_status NewExternalString(napi_env env, CharType* str, size_t length, napi_finalize finalize_callback, void* finalize_hint, napi_value* result, bool* copied, CreateAPI create_api, StringMaker string_maker) { CHECK_NEW_STRING_ARGS(env, str, length, result); napi_status status; #if defined(V8_ENABLE_SANDBOX) status = create_api(env, str, length, result); if (status == napi_ok) { if (copied != nullptr) { *copied = true; } if (finalize_callback) { env->CallFinalizer( finalize_callback, static_cast<CharType*>(str), finalize_hint); } } #else status = NewString(env, str, length, result, string_maker); if (status == napi_ok && copied != nullptr) { *copied = false; } #endif // V8_ENABLE_SANDBOX return status; } class TrackedStringResource : public Finalizer, RefTracker { public: TrackedStringResource(napi_env env, napi_finalize finalize_callback, void* data, void* finalize_hint) : Finalizer(env, finalize_callback, data, finalize_hint) { Link(finalize_callback == nullptr ? &env->reflist : &env->finalizing_reflist); } protected: // The only time Finalize() gets called before Dispose() is if the // environment is dying. Finalize() expects that the item will be unlinked, // so we do it here. V8 will still call Dispose() on us later, so we don't do // any deleting here. We just null out env_ to avoid passing a stale pointer // to the user's finalizer when V8 does finally call Dispose(). void Finalize() override { Unlink(); env_ = nullptr; } ~TrackedStringResource() { if (finalize_callback_ == nullptr) return; if (env_ == nullptr) { // The environment is dead. Call the finalizer directly. finalize_callback_(nullptr, finalize_data_, finalize_hint_); } else { // The environment is still alive. Let's remove ourselves from its list // of references and call the user's finalizer. Unlink(); env_->CallFinalizer(finalize_callback_, finalize_data_, finalize_hint_); } } }; class ExternalOneByteStringResource : public v8::String::ExternalOneByteStringResource, TrackedStringResource { public: ExternalOneByteStringResource(napi_env env, char* string, const size_t length, napi_finalize finalize_callback, void* finalize_hint) : TrackedStringResource(env, finalize_callback, string, finalize_hint), string_(string), length_(length) {} const char* data() const override { return string_; } size_t length() const override { return length_; } private: const char* string_; const size_t length_; }; class ExternalStringResource : public v8::String::ExternalStringResource, TrackedStringResource { public: ExternalStringResource(napi_env env, char16_t* string, const size_t length, napi_finalize finalize_callback, void* finalize_hint) : TrackedStringResource(env, finalize_callback, string, finalize_hint), string_(reinterpret_cast<uint16_t*>(string)), length_(length) {} const uint16_t* data() const override { return string_; } size_t length() const override { return length_; } private: const uint16_t* string_; const size_t length_; }; inline napi_status V8NameFromPropertyDescriptor( napi_env env, const napi_property_descriptor* p, v8::Local<v8::Name>* result) { if (p->utf8name != nullptr) { CHECK_NEW_FROM_UTF8(env, *result, p->utf8name); } else { v8::Local<v8::Value> property_value = v8impl::V8LocalValueFromJsValue(p->name); RETURN_STATUS_IF_FALSE(env, property_value->IsName(), napi_name_expected); *result = property_value.As<v8::Name>(); } return napi_ok; } // convert from n-api property attributes to v8::PropertyAttribute inline v8::PropertyAttribute V8PropertyAttributesFromDescriptor( const napi_property_descriptor* descriptor) { unsigned int attribute_flags = v8::PropertyAttribute::None; // The napi_writable attribute is ignored for accessor descriptors, but // V8 would throw `TypeError`s on assignment with nonexistence of a setter. if ((descriptor->getter == nullptr && descriptor->setter == nullptr) && (descriptor->attributes & napi_writable) == 0) { attribute_flags |= v8::PropertyAttribute::ReadOnly; } if ((descriptor->attributes & napi_enumerable) == 0) { attribute_flags |= v8::PropertyAttribute::DontEnum; } if ((descriptor->attributes & napi_configurable) == 0) { attribute_flags |= v8::PropertyAttribute::DontDelete; } return static_cast<v8::PropertyAttribute>(attribute_flags); } inline napi_deferred JsDeferredFromNodePersistent( v8impl::Persistent<v8::Value>* local) { return reinterpret_cast<napi_deferred>(local); } inline v8impl::Persistent<v8::Value>* NodePersistentFromJsDeferred( napi_deferred local) { return reinterpret_cast<v8impl::Persistent<v8::Value>*>(local); } class HandleScopeWrapper { public: explicit HandleScopeWrapper(v8::Isolate* isolate) : scope(isolate) {} private: v8::HandleScope scope; }; // In node v0.10 version of v8, there is no EscapableHandleScope and the // node v0.10 port use HandleScope::Close(Local<T> v) to mimic the behavior // of a EscapableHandleScope::Escape(Local<T> v), but it is not the same // semantics. This is an example of where the api abstraction fail to work // across different versions. class EscapableHandleScopeWrapper { public: explicit EscapableHandleScopeWrapper(v8::Isolate* isolate) : scope(isolate), escape_called_(false) {} bool escape_called() const { return escape_called_; } template <typename T> v8::Local<T> Escape(v8::Local<T> handle) { escape_called_ = true; return scope.Escape(handle); } private: v8::EscapableHandleScope scope; bool escape_called_; }; inline napi_handle_scope JsHandleScopeFromV8HandleScope(HandleScopeWrapper* s) { return reinterpret_cast<napi_handle_scope>(s); } inline HandleScopeWrapper* V8HandleScopeFromJsHandleScope(napi_handle_scope s) { return reinterpret_cast<HandleScopeWrapper*>(s); } inline napi_escapable_handle_scope JsEscapableHandleScopeFromV8EscapableHandleScope( EscapableHandleScopeWrapper* s) { return reinterpret_cast<napi_escapable_handle_scope>(s); } inline EscapableHandleScopeWrapper* V8EscapableHandleScopeFromJsEscapableHandleScope( napi_escapable_handle_scope s) { return reinterpret_cast<EscapableHandleScopeWrapper*>(s); } inline napi_status ConcludeDeferred(napi_env env, napi_deferred deferred, napi_value result, bool is_resolved) { NAPI_PREAMBLE(env); CHECK_ARG(env, result); v8::Local<v8::Context> context = env->context(); v8impl::Persistent<v8::Value>* deferred_ref = NodePersistentFromJsDeferred(deferred); v8::Local<v8::Value> v8_deferred = v8::Local<v8::Value>::New(env->isolate, *deferred_ref); auto v8_resolver = v8_deferred.As<v8::Promise::Resolver>(); v8::Maybe<bool> success = is_resolved ? v8_resolver->Resolve( context, v8impl::V8LocalValueFromJsValue(result)) : v8_resolver->Reject( context, v8impl::V8LocalValueFromJsValue(result)); delete deferred_ref; RETURN_STATUS_IF_FALSE(env, success.FromMaybe(false), napi_generic_failure); return GET_RETURN_STATUS(env); } enum UnwrapAction { KeepWrap, RemoveWrap }; inline napi_status Unwrap(napi_env env, napi_value js_object, void** result, UnwrapAction action) { NAPI_PREAMBLE(env); CHECK_ARG(env, js_object); if (action == KeepWrap) { CHECK_ARG(env, result); } v8::Local<v8::Context> context = env->context(); v8::Local<v8::Value> value = v8impl::V8LocalValueFromJsValue(js_object); RETURN_STATUS_IF_FALSE(env, value->IsObject(), napi_invalid_arg); v8::Local<v8::Object> obj = value.As<v8::Object>(); auto val = obj->GetPrivate(context, NAPI_PRIVATE_KEY(context, wrapper)) .ToLocalChecked(); RETURN_STATUS_IF_FALSE(env, val->IsExternal(), napi_invalid_arg); Reference* reference = static_cast<v8impl::Reference*>(val.As<v8::External>()->Value()); if (result) { *result = reference->Data(); } if (action == RemoveWrap) { CHECK(obj->DeletePrivate(context, NAPI_PRIVATE_KEY(context, wrapper)) .FromJust()); if (reference->ownership() == Ownership::kUserland) { // When the wrap is been removed, the finalizer should be reset. reference->ResetFinalizer(); } else { delete reference; } } return GET_RETURN_STATUS(env); } //=== Function napi_callback wrapper ================================= // Use this data structure to associate callback data with each N-API function // exposed to JavaScript. The structure is stored in a v8::External which gets // passed into our callback wrapper. This reduces the performance impact of // calling through N-API. // Ref: benchmark/misc/function_call // Discussion (incl. perf. data): https://github.com/nodejs/node/pull/21072 class CallbackBundle { public: // Creates an object to be made available to the static function callback // wrapper, used to retrieve the native callback function and data pointer. static inline v8::Local<v8::Value> New(napi_env env, napi_callback cb, void* data) { CallbackBundle* bundle = new CallbackBundle(); bundle->cb = cb; bundle->cb_data = data; bundle->env = env; v8::Local<v8::Value> cbdata = v8::External::New(env->isolate, bundle); Reference::New( env, cbdata, 0, Ownership::kRuntime, Delete, bundle, nullptr); return cbdata; } napi_env env; // Necessary to invoke C++ NAPI callback void* cb_data; // The user provided callback data napi_callback cb; private: static void Delete(napi_env env, void* data, void* hint) { CallbackBundle* bundle = static_cast<CallbackBundle*>(data); delete bundle; } }; // Base class extended by classes that wrap V8 function and property callback // info. class CallbackWrapper { public: inline CallbackWrapper(napi_value this_arg, size_t args_length, void* data) : _this(this_arg), _args_length(args_length), _data(data) {} virtual napi_value GetNewTarget() = 0; virtual void Args(napi_value* buffer, size_t bufferlength) = 0; virtual void SetReturnValue(napi_value value) = 0; napi_value This() { return _this; } size_t ArgsLength() { return _args_length; } void* Data() { return _data; } protected: const napi_value _this; const size_t _args_length; void* _data; }; class CallbackWrapperBase : public CallbackWrapper { public: inline CallbackWrapperBase(const v8::FunctionCallbackInfo<v8::Value>& cbinfo, const size_t args_length) : CallbackWrapper( JsValueFromV8LocalValue(cbinfo.This()), args_length, nullptr), _cbinfo(cbinfo) { _bundle = reinterpret_cast<CallbackBundle*>( cbinfo.Data().As<v8::External>()->Value()); _data = _bundle->cb_data; } protected: inline void InvokeCallback() { napi_callback_info cbinfo_wrapper = reinterpret_cast<napi_callback_info>( static_cast<CallbackWrapper*>(this)); // All other pointers we need are stored in `_bundle` napi_env env = _bundle->env; napi_callback cb = _bundle->cb; napi_value result = nullptr; bool exceptionOccurred = false; env->CallIntoModule([&](napi_env env) { result = cb(env, cbinfo_wrapper); }, [&](napi_env env, v8::Local<v8::Value> value) { exceptionOccurred = true; if (env->terminatedOrTerminating()) { return; } env->isolate->ThrowException(value); }); if (!exceptionOccurred && (result != nullptr)) { this->SetReturnValue(result); } } const v8::FunctionCallbackInfo<v8::Value>& _cbinfo; CallbackBundle* _bundle; }; class FunctionCallbackWrapper : public CallbackWrapperBase { public: static void Invoke(const v8::FunctionCallbackInfo<v8::Value>& info) { FunctionCallbackWrapper cbwrapper(info); cbwrapper.InvokeCallback(); } static inline napi_status NewFunction(napi_env env, napi_callback cb, void* cb_data, v8::Local<v8::Function>* result) { v8::Local<v8::Value> cbdata = v8impl::CallbackBundle::New(env, cb, cb_data); RETURN_STATUS_IF_FALSE(env, !cbdata.IsEmpty(), napi_generic_failure); v8::MaybeLocal<v8::Function> maybe_function = v8::Function::New(env->context(), Invoke, cbdata); CHECK_MAYBE_EMPTY(env, maybe_function, napi_generic_failure); *result = maybe_function.ToLocalChecked(); return napi_clear_last_error(env); } static inline napi_status NewTemplate( napi_env env, napi_callback cb, void* cb_data, v8::Local<v8::FunctionTemplate>* result, v8::Local<v8::Signature> sig = v8::Local<v8::Signature>()) { v8::Local<v8::Value> cbdata = v8impl::CallbackBundle::New(env, cb, cb_data); RETURN_STATUS_IF_FALSE(env, !cbdata.IsEmpty(), napi_generic_failure); *result = v8::FunctionTemplate::New(env->isolate, Invoke, cbdata, sig); return napi_clear_last_error(env); } explicit FunctionCallbackWrapper( const v8::FunctionCallbackInfo<v8::Value>& cbinfo) : CallbackWrapperBase(cbinfo, cbinfo.Length()) {} napi_value GetNewTarget() override { if (_cbinfo.IsConstructCall()) { return v8impl::JsValueFromV8LocalValue(_cbinfo.NewTarget()); } else { return nullptr; } } /*virtual*/ void Args(napi_value* buffer, size_t buffer_length) override { size_t i = 0; size_t min = std::min(buffer_length, _args_length); for (; i < min; i += 1) { buffer[i] = v8impl::JsValueFromV8LocalValue(_cbinfo[i]); } if (i < buffer_length) { napi_value undefined = v8impl::JsValueFromV8LocalValue(v8::Undefined(_cbinfo.GetIsolate())); for (; i < buffer_length; i += 1) { buffer[i] = undefined; } } } /*virtual*/ void SetReturnValue(napi_value value) override { v8::Local<v8::Value> val = v8impl::V8LocalValueFromJsValue(value); _cbinfo.GetReturnValue().Set(val); } }; inline napi_status Wrap(napi_env env, napi_value js_object, void* native_object, napi_finalize finalize_cb, void* finalize_hint, napi_ref* result) { NAPI_PREAMBLE(env); CHECK_ARG(env, js_object); v8::Local<v8::Context> context = env->context(); v8::Local<v8::Value> value = v8impl::V8LocalValueFromJsValue(js_object); RETURN_STATUS_IF_FALSE(env, value->IsObject(), napi_invalid_arg); v8::Local<v8::Object> obj = value.As<v8::Object>(); // If we've already wrapped this object, we error out. RETURN_STATUS_IF_FALSE( env, !obj->HasPrivate(context, NAPI_PRIVATE_KEY(context, wrapper)).FromJust(), napi_invalid_arg); v8impl::Reference* reference = nullptr; if (result != nullptr) { // The returned reference should be deleted via napi_delete_reference() // ONLY in response to the finalize callback invocation. (If it is deleted // before then, then the finalize callback will never be invoked.) // Therefore a finalize callback is required when returning a reference. CHECK_ARG(env, finalize_cb); reference = v8impl::Reference::New(env, obj, 0, v8impl::Ownership::kUserland, finalize_cb, native_object, finalize_hint); *result = reinterpret_cast<napi_ref>(reference); } else { // Create a self-deleting reference. reference = v8impl::Reference::New( env, obj, 0, v8impl::Ownership::kRuntime, finalize_cb, native_object, finalize_cb == nullptr ? nullptr : finalize_hint); } CHECK(obj->SetPrivate(context, NAPI_PRIVATE_KEY(context, wrapper), v8::External::New(env->isolate, reference)) .FromJust()); return GET_RETURN_STATUS(env); } // In JavaScript, weak references can be created for object types (Object, // Function, and external Object) and for local symbols that are created with // the `Symbol` function call. Global symbols created with the `Symbol.for` // method cannot be weak references because they are never collected. // // Currently, V8 has no API to detect if a symbol is local or global. // Until we have a V8 API for it, we consider that all symbols can be weak. // This matches the current Node-API behavior. inline bool CanBeHeldWeakly(v8::Local<v8::Value> value) { return value->IsObject() || value->IsSymbol(); } } // end of anonymous namespace void Finalizer::ResetFinalizer() { finalize_callback_ = nullptr; finalize_data_ = nullptr; finalize_hint_ = nullptr; } TrackedFinalizer::TrackedFinalizer(napi_env env, napi_finalize finalize_callback, void* finalize_data, void* finalize_hint) : Finalizer(env, finalize_callback, finalize_data, finalize_hint), RefTracker() { Link(finalize_callback == nullptr ? &env->reflist : &env->finalizing_reflist); } TrackedFinalizer* TrackedFinalizer::New(napi_env env, napi_finalize finalize_callback, void* finalize_data, void* finalize_hint) { return new TrackedFinalizer( env, finalize_callback, finalize_data, finalize_hint); } // When a TrackedFinalizer is being deleted, it may have been queued to call its // finalizer. TrackedFinalizer::~TrackedFinalizer() { // Remove from the env's tracked list. Unlink(); // Try to remove the finalizer from the scheduled second pass callback. env_->DequeueFinalizer(this); } void TrackedFinalizer::Finalize() { FinalizeCore(/*deleteMe:*/ true); } void TrackedFinalizer::FinalizeCore(bool deleteMe) { // Swap out the field finalize_callback so that it can not be accidentally // called more than once. napi_finalize finalize_callback = finalize_callback_; void* finalize_data = finalize_data_; void* finalize_hint = finalize_hint_; ResetFinalizer(); // Either the RefBase is going to be deleted in the finalize_callback or not, // it should be removed from the tracked list. Unlink(); // If the finalize_callback is present, it should either delete the // derived RefBase, or the RefBase ownership was set to Ownership::kRuntime // and the deleteMe parameter is true. if (finalize_callback != nullptr) { env_->CallFinalizer(finalize_callback, finalize_data, finalize_hint); } if (deleteMe) { delete this; } } // Wrapper around v8impl::Persistent that implements reference counting. RefBase::RefBase(napi_env env, uint32_t initial_refcount, Ownership ownership, napi_finalize finalize_callback, void* finalize_data, void* finalize_hint) : TrackedFinalizer(env, finalize_callback, finalize_data, finalize_hint), refcount_(initial_refcount), ownership_(ownership) {} RefBase* RefBase::New(napi_env env, uint32_t initial_refcount, Ownership ownership, napi_finalize finalize_callback, void* finalize_data, void* finalize_hint) { return new RefBase(env, initial_refcount, ownership, finalize_callback, finalize_data, finalize_hint); } void* RefBase::Data() { return finalize_data_; } uint32_t RefBase::Ref() { return ++refcount_; } uint32_t RefBase::Unref() { if (refcount_ == 0) { return 0; } return --refcount_; } uint32_t RefBase::RefCount() { return refcount_; } void RefBase::Finalize() { // If the RefBase is not Ownership::kRuntime, userland code should delete it. // Delete it if it is Ownership::kRuntime. FinalizeCore(/*deleteMe:*/ ownership_ == Ownership::kRuntime); } template <typename... Args> Reference::Reference(napi_env env, v8::Local<v8::Value> value, Args&&... args) : RefBase(env, std::forward<Args>(args)...), persistent_(env->isolate, value), can_be_weak_(CanBeHeldWeakly(value)) { if (RefCount() == 0) { SetWeak(); } } Reference::~Reference() { // Reset the handle. And no weak callback will be invoked. persistent_.Reset(); } Reference* Reference::New(napi_env env, v8::Local<v8::Value> value, uint32_t initial_refcount, Ownership ownership, napi_finalize finalize_callback, void* finalize_data, void* finalize_hint) { return new Reference(env, value, initial_refcount, ownership, finalize_callback, finalize_data, finalize_hint); } uint32_t Reference::Ref() { // When the persistent_ is cleared in the WeakCallback, and a second pass // callback is pending, return 0 unconditionally. if (persistent_.IsEmpty()) { return 0; } uint32_t refcount = RefBase::Ref(); if (refcount == 1 && can_be_weak_) { persistent_.ClearWeak(); } return refcount; } uint32_t Reference::Unref() { // When the persistent_ is cleared in the WeakCallback, and a second pass // callback is pending, return 0 unconditionally. if (persistent_.IsEmpty()) { return 0; } uint32_t old_refcount = RefCount(); uint32_t refcount = RefBase::Unref(); if (old_refcount == 1 && refcount == 0) { SetWeak(); } return refcount; } v8::Local<v8::Value> Reference::Get() { if (persistent_.IsEmpty()) { return v8::Local<v8::Value>(); } else { return v8::Local<v8::Value>::New(env_->isolate, persistent_); } } void Reference::Finalize() { // Unconditionally reset the persistent handle so that no weak callback will // be invoked again. persistent_.Reset(); // Chain up to perform the rest of the finalization. RefBase::Finalize(); } // Mark the reference as weak and eligible for collection // by the gc. void Reference::SetWeak() { if (can_be_weak_) { persistent_.SetWeak(this, WeakCallback, v8::WeakCallbackType::kParameter); } else { persistent_.Reset(); } } // The N-API finalizer callback may make calls into the engine. V8's heap is // not in a consistent state during the weak callback, and therefore it does // not support calls back into it. Enqueue the invocation of the finalizer. void Reference::WeakCallback(const v8::WeakCallbackInfo<Reference>& data) { Reference* reference = data.GetParameter(); // The reference must be reset during the weak callback as the API protocol. reference->persistent_.Reset(); reference->env_->InvokeFinalizerFromGC(reference); } /** * A wrapper for `v8::External` to support type-tagging. `v8::External` doesn't * support defining any properties and private properties on it, even though it * is an object. This wrapper is used to store the type tag and the data of the * external value. */ class ExternalWrapper { private: explicit ExternalWrapper(void* data) : data_(data), type_tag_{0, 0} {} static void WeakCallback(const v8::WeakCallbackInfo<ExternalWrapper>& data) { ExternalWrapper* wrapper = data.GetParameter(); delete wrapper; } public: static v8::Local<v8::External> New(napi_env env, void* data) { ExternalWrapper* wrapper = new ExternalWrapper(data); v8::Local<v8::External> external = v8::External::New(env->isolate, wrapper); wrapper->persistent_.Reset(env->isolate, external); wrapper->persistent_.SetWeak( wrapper, WeakCallback, v8::WeakCallbackType::kParameter); return external; } static ExternalWrapper* From(v8::Local<v8::External> external) { return static_cast<ExternalWrapper*>(external->Value()); } void* Data() { return data_; } bool TypeTag(const napi_type_tag* type_tag) { if (has_tag_) { return false; } type_tag_ = *type_tag; has_tag_ = true; return true; } bool CheckTypeTag(const napi_type_tag* type_tag) { return has_tag_ && type_tag->lower == type_tag_.lower && type_tag->upper == type_tag_.upper; } private: v8impl::Persistent<v8::Value> persistent_; void* data_; napi_type_tag type_tag_; bool has_tag_ = false; }; } // end of namespace v8impl // Warning: Keep in-sync with napi_status enum static const char* error_messages[] = { nullptr, "Invalid argument", "An object was expected", "A string was expected", "A string or symbol was expected", "A function was expected", "A number was expected", "A boolean was expected", "An array was expected", "Unknown failure", "An exception is pending", "The async work item was cancelled", "napi_escape_handle already called on scope", "Invalid handle scope usage", "Invalid callback scope usage", "Thread-safe function queue is full", "Thread-safe function handle is closing", "A bigint was expected", "A date was expected", "An arraybuffer was expected", "A detachable arraybuffer was expected", "Main thread would deadlock", "External buffers are not allowed", "Cannot run JavaScript", }; napi_status NAPI_CDECL napi_get_last_error_info( node_api_nogc_env nogc_env, const napi_extended_error_info** result) { napi_env env = const_cast<napi_env>(nogc_env); CHECK_ENV(env); CHECK_ARG(env, result); // The value of the constant below must be updated to reference the last // message in the `napi_status` enum each time a new error message is added. // We don't have a napi_status_last as this would result in an ABI // change each time a message was added. const int last_status = napi_cannot_run_js; static_assert(NAPI_ARRAYSIZE(error_messages) == last_status + 1, "Count of error messages must match count of error values"); CHECK_LE(env->last_error.error_code, last_status); // Wait until someone requests the last error information to fetch the error // message string env->last_error.error_message = error_messages[env->last_error.error_code]; if (env->last_error.error_code == napi_ok) { napi_clear_last_error(env); } *result = &(env->last_error); return napi_ok; } napi_status NAPI_CDECL napi_create_function(napi_env env, const char* utf8name, size_t length, napi_callback cb, void* callback_data, napi_value* result) { NAPI_PREAMBLE(env); CHECK_ARG(env, result); CHECK_ARG(env, cb); v8::Local<v8::Function> return_value; v8::EscapableHandleScope scope(env->isolate); v8::Local<v8::Function> fn; STATUS_CALL(v8impl::FunctionCallbackWrapper::NewFunction( env, cb, callback_data, &fn)); return_value = scope.Escape(fn); if (utf8name != nullptr) { v8::Local<v8::String> name_string; CHECK_NEW_FROM_UTF8_LEN(env, name_string, utf8name, length); return_value->SetName(name_string); } *result = v8impl::JsValueFromV8LocalValue(return_value); return GET_RETURN_STATUS(env); } napi_status NAPI_CDECL napi_define_class(napi_env env, const char* utf8name, size_t length, napi_callback constructor, void* callback_data, size_t property_count, const napi_property_descriptor* properties, napi_value* result) { NAPI_PREAMBLE(env); CHECK_ARG(env, result); CHECK_ARG(env, constructor); if (property_count > 0) { CHECK_ARG(env, properties); } v8::Isolate* isolate = env->isolate; v8::EscapableHandleScope scope(isolate); v8::Local<v8::FunctionTemplate> tpl; STATUS_CALL(v8impl::FunctionCallbackWrapper::NewTemplate( env, constructor, callback_data, &tpl)); v8::Local<v8::String> name_string; CHECK_NEW_FROM_UTF8_LEN(env, name_string, utf8name, length); tpl->SetClassName(name_string); size_t static_property_count = 0; for (size_t i = 0; i < property_count; i++) { const napi_property_descriptor* p = properties + i; if ((p->attributes & napi_static) != 0) { // Static properties are handled separately below. static_property_count++; continue; |
| 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. |