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/js_native_api_v8.cc at main · dims/node Expand file tree/ Copy pathjs_native_api_v8.ccMore file actions 3257 lines (2647 loc) · 111 KB / Copy pathjs_native_api_v8.ccFile metadata and controls3257 lines (2647 loc) · 111 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 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) namespace v8impl { namespace { 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()); Reference::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, true, 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; 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); } }; enum WrapType { retrievable, anonymous }; template <WrapType wrap_type> 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 (wrap_type == retrievable) { // 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); } else if (wrap_type == anonymous) { // If no finalize callback is provided, we error out. CHECK_ARG(env, finalize_cb); } 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, false, 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, true, finalize_cb, native_object, finalize_cb == nullptr ? nullptr : finalize_hint); } if (wrap_type == retrievable) { CHECK(obj->SetPrivate(context, NAPI_PRIVATE_KEY(context, wrapper), v8::External::New(env->isolate, reference)) .FromJust()); } return GET_RETURN_STATUS(env); } } // end of anonymous namespace // Wrapper around v8impl::Persistent that implements reference counting. RefBase::RefBase(napi_env env, uint32_t initial_refcount, bool delete_self, napi_finalize finalize_callback, void* finalize_data, void* finalize_hint) : Finalizer(env, finalize_callback, finalize_data, finalize_hint), _refcount(initial_refcount), _delete_self(delete_self) { Link(finalize_callback == nullptr ? &env->reflist : &env->finalizing_reflist); } RefBase* RefBase::New(napi_env env, uint32_t initial_refcount, bool delete_self, napi_finalize finalize_callback, void* finalize_data, void* finalize_hint) { return new RefBase(env, initial_refcount, delete_self, finalize_callback, finalize_data, finalize_hint); } RefBase::~RefBase() { Unlink(); } void* RefBase::Data() { return _finalize_data; } // Delete is called in 2 ways. Either from the finalizer or // from one of Unwrap or napi_delete_reference. // // When it is called from Unwrap or napi_delete_reference we only // want to do the delete if the finalizer has already run or // cannot have been queued to run (ie the reference count is > 0), // otherwise we may crash when the finalizer does run. // If the finalizer may have been queued and has not already run // delay the delete until the finalizer runs by not doing the delete // and setting _delete_self to true so that the finalizer will // delete it when it runs. // // The second way this is called is from // the finalizer and _delete_self is set. In this case we // know we need to do the deletion so just do it. void RefBase::Delete(RefBase* reference) { if ((reference->RefCount() != 0) || (reference->_delete_self) || (reference->_finalize_ran)) { delete reference; } else { // defer until finalizer runs as // it may already be queued reference->_delete_self = true; } } 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(bool is_env_teardown) { // In addition to being called during environment teardown, this method is // also the entry point for the garbage collector. During environment // teardown we have to remove the garbage collector's reference to this // method so that, if, as part of the user's callback, JS gets executed, // resulting in a garbage collection pass, this method is not re-entered as // part of that pass, because that'll cause a double free (as seen in // https://github.com/nodejs/node/issues/37236). // // Since this class does not have access to the V8 persistent reference, // this method is overridden in the `Reference` class below. Therein the // weak callback is removed, ensuring that the garbage collector does not // re-enter this method, and the method chains up to continue the process of // environment-teardown-induced finalization. // During environment teardown we have to convert a strong reference to // a weak reference to force the deferring behavior if the user's finalizer // happens to delete this reference so that the code in this function that // follows the call to the user's finalizer may safely access variables from // this instance. if (is_env_teardown && RefCount() > 0) _refcount = 0; if (_finalize_callback != nullptr) { // This ensures that we never call the finalizer twice. napi_finalize fini = _finalize_callback; _finalize_callback = nullptr; _env->CallFinalizer(fini, _finalize_data, _finalize_hint); } // this is safe because if a request to delete the reference // is made in the finalize_callback it will defer deletion // to this block and set _delete_self to true if (_delete_self || is_env_teardown) { Delete(this); } else { _finalize_ran = true; } } 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), _secondPassParameter(new SecondPassCallParameterRef(this)), _secondPassScheduled(false) { if (RefCount() == 0) { SetWeak(); } } Reference* Reference::New(napi_env env, v8::Local<v8::Value> value, uint32_t initial_refcount, bool delete_self, napi_finalize finalize_callback, void* finalize_data, void* finalize_hint) { return new Reference(env, value, initial_refcount, delete_self, finalize_callback, finalize_data, finalize_hint); } Reference::~Reference() { // If the second pass callback is scheduled, it will delete the // parameter passed to it, otherwise it will never be scheduled // and we need to delete it here. if (!_secondPassScheduled) { delete _secondPassParameter; } } uint32_t Reference::Ref() { uint32_t refcount = RefBase::Ref(); if (refcount == 1) { ClearWeak(); } return refcount; } uint32_t Reference::Unref() { 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(bool is_env_teardown) { // During env teardown, `~napi_env()` alone is responsible for finalizing. // Thus, we don't want any stray gc passes to trigger a second call to // `RefBase::Finalize()`. ClearWeak will ensure that even if the // gc is in progress no Finalization will be run for this Reference // by the gc. if (is_env_teardown) { ClearWeak(); } // Chain up to perform the rest of the finalization. RefBase::Finalize(is_env_teardown); } // ClearWeak is marking the Reference so that the gc should not // collect it, but it is possible that a second pass callback // may have been scheduled already if we are in shutdown. We clear // the secondPassParameter so that even if it has been // scheduled no Finalization will be run. void Reference::ClearWeak() { if (!_persistent.IsEmpty()) { _persistent.ClearWeak(); } if (_secondPassParameter != nullptr) { *_secondPassParameter = nullptr; } } // Mark the reference as weak and eligible for collection // by the gc. void Reference::SetWeak() { if (_secondPassParameter == nullptr) { // This means that the Reference has already been processed // by the second pass callback, so its already been Finalized, do // nothing return; } _persistent.SetWeak( _secondPassParameter, FinalizeCallback, v8::WeakCallbackType::kParameter); *_secondPassParameter = this; } // 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. However, it provides a mechanism for adding // a finalizer which may make calls back into the engine by allowing us to // attach such a second-pass finalizer from the first pass finalizer. Thus, // we do that here to ensure that the N-API finalizer callback is free to call // into the engine. void Reference::FinalizeCallback( const v8::WeakCallbackInfo<SecondPassCallParameterRef>& data) { SecondPassCallParameterRef* parameter = data.GetParameter(); Reference* reference = *parameter; if (reference == nullptr) { return; } // The reference must be reset during the first pass. reference->_persistent.Reset(); // Mark the parameter not delete-able until the second pass callback is // invoked. reference->_secondPassScheduled = true; data.SetSecondPassCallback(SecondPassCallback); } // Second pass callbacks are scheduled with platform tasks. At env teardown, // the tasks may have already be scheduled and we are unable to cancel the // second pass callback task. We have to make sure that parameter is kept // alive until the second pass callback is been invoked. In order to do // this and still allow our code to Finalize/delete the Reference during // shutdown we have to use a separately allocated parameter instead // of a parameter within the Reference object itself. This is what // is stored in _secondPassParameter and it is allocated in the // constructor for the Reference. void Reference::SecondPassCallback( const v8::WeakCallbackInfo<SecondPassCallParameterRef>& data) { SecondPassCallParameterRef* parameter = data.GetParameter(); Reference* reference = *parameter; delete parameter; if (reference == nullptr) { // the reference itself has already been deleted so nothing to do return; } reference->_secondPassParameter = nullptr; reference->Finalize(); } } // 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", }; napi_status NAPI_CDECL napi_get_last_error_info( napi_env env, const napi_extended_error_info** result) { 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_would_deadlock; 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; } v8::Local<v8::Name> property_name; STATUS_CALL(v8impl::V8NameFromPropertyDescriptor(env, p, &property_name)); v8::PropertyAttribute attributes = v8impl::V8PropertyAttributesFromDescriptor(p); // This code is similar to that in napi_define_properties(); the // difference is it applies to a template instead of an object, // and preferred PropertyAttribute for lack of PropertyDescriptor // support on ObjectTemplate. if (p->getter != nullptr || p->setter != nullptr) { v8::Local<v8::FunctionTemplate> getter_tpl; v8::Local<v8::FunctionTemplate> setter_tpl; if (p->getter != nullptr) { STATUS_CALL(v8impl::FunctionCallbackWrapper::NewTemplate( env, p->getter, p->data, &getter_tpl)); } if (p->setter != nullptr) { STATUS_CALL(v8impl::FunctionCallbackWrapper::NewTemplate( env, p->setter, p->data, &setter_tpl)); } tpl->PrototypeTemplate()->SetAccessorProperty(property_name, getter_tpl, setter_tpl, attributes, v8::AccessControl::DEFAULT); } else if (p->method != nullptr) { v8::Local<v8::FunctionTemplate> t; STATUS_CALL(v8impl::FunctionCallbackWrapper::NewTemplate( env, p->method, p->data, &t, v8::Signature::New(isolate, tpl))); tpl->PrototypeTemplate()->Set(property_name, t, attributes); } else { v8::Local<v8::Value> value = v8impl::V8LocalValueFromJsValue(p->value); tpl->PrototypeTemplate()->Set(property_name, value, attributes); } } v8::Local<v8::Context> context = env->context(); *result = v8impl::JsValueFromV8LocalValue( scope.Escape(tpl->GetFunction(context).ToLocalChecked())); if (static_property_count > 0) { std::vector<napi_property_descriptor> static_descriptors; static_descriptors.reserve(static_property_count); for (size_t i = 0; i < property_count; i++) { const napi_property_descriptor* p = properties + i; if ((p->attributes & napi_static) != 0) { static_descriptors.push_back(*p); } } STATUS_CALL(napi_define_properties( env, *result, static_descriptors.size(), static_descriptors.data())); } return GET_RETURN_STATUS(env); } napi_status NAPI_CDECL napi_get_property_names(napi_env env, napi_value object, napi_value* result) { return napi_get_all_property_names( env, object, napi_key_include_prototypes, static_cast<napi_key_filter>(napi_key_enumerable | napi_key_skip_symbols), napi_key_numbers_to_strings, result); } napi_status NAPI_CDECL napi_get_all_property_names(napi_env env, napi_value object, napi_key_collection_mode key_mode, napi_key_filter key_filter, napi_key_conversion key_conversion, napi_value* result) { NAPI_PREAMBLE(env); CHECK_ARG(env, result); v8::Local<v8::Context> context = env->context(); v8::Local<v8::Object> obj; CHECK_TO_OBJECT(env, context, obj, object); v8::PropertyFilter filter = v8::PropertyFilter::ALL_PROPERTIES; if (key_filter & napi_key_writable) { filter = static_cast<v8::PropertyFilter>(filter | v8::PropertyFilter::ONLY_WRITABLE); } if (key_filter & napi_key_enumerable) { filter = static_cast<v8::PropertyFilter>( filter | v8::PropertyFilter::ONLY_ENUMERABLE); } if (key_filter & napi_key_configurable) { filter = static_cast<v8::PropertyFilter>( filter | v8::PropertyFilter::ONLY_CONFIGURABLE); } if (key_filter & napi_key_skip_strings) { filter = static_cast<v8::PropertyFilter>(filter | v8::PropertyFilter::SKIP_STRINGS); } if (key_filter & napi_key_skip_symbols) { filter = static_cast<v8::PropertyFilter>(filter | v8::PropertyFilter::SKIP_SYMBOLS); } v8::KeyCollectionMode collection_mode; v8::KeyConversionMode conversion_mode; switch (key_mode) { case napi_key_include_prototypes: collection_mode = v8::KeyCollectionMode::kIncludePrototypes; break; case napi_key_own_only: collection_mode = v8::KeyCollectionMode::kOwnOnly; break; default: return napi_set_last_error(env, napi_invalid_arg); } switch (key_conversion) { case napi_key_keep_numbers: conversion_mode = v8::KeyConversionMode::kKeepNumbers; break; case napi_key_numbers_to_strings: conversion_mode = v8::KeyConversionMode::kConvertToString; break; default: return napi_set_last_error(env, napi_invalid_arg); } v8::MaybeLocal<v8::Array> maybe_all_propertynames = obj->GetPropertyNames(context, collection_mode, filter, v8::IndexFilter::kIncludeIndices, conversion_mode); CHECK_MAYBE_EMPTY_WITH_PREAMBLE( env, maybe_all_propertynames, napi_generic_failure); *result = v8impl::JsValueFromV8LocalValue(maybe_all_propertynames.ToLocalChecked()); return GET_RETURN_STATUS(env); } napi_status NAPI_CDECL napi_set_property(napi_env env, napi_value object, napi_value key, napi_value value) { NAPI_PREAMBLE(env); CHECK_ARG(env, key); CHECK_ARG(env, value); v8::Local<v8::Context> context = env->context(); v8::Local<v8::Object> obj; |
| 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. |