diff options
author | legendecas <legendecas@gmail.com> | 2022-08-01 19:01:02 +0300 |
---|---|---|
committer | legendecas <legendecas@gmail.com> | 2022-08-01 19:01:02 +0300 |
commit | a7e5b413efd5f98d4b9acf39ff5e87ddbd8c63ff (patch) | |
tree | b3ae111dcfe5ab8db74df9d355aa009a9ea024c7 | |
parent | 7f7a899fa5f3b192d4f503f6602f24f7ff4ec57a (diff) |
src: split property helpers from node::Environment
PR-URL: https://github.com/nodejs/node/pull/44056
Refs: https://github.com/nodejs/node/issues/42528
Reviewed-By: Ben Noordhuis <info@bnoordhuis.nl>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Joyee Cheung <joyeec9h3@gmail.com>
Reviewed-By: Feng Yu <F3n67u@outlook.com>
78 files changed, 1508 insertions, 1292 deletions
diff --git a/src/README.md b/src/README.md index 8162deecb3c..314cd343418 100644 --- a/src/README.md +++ b/src/README.md @@ -390,32 +390,33 @@ void Initialize(Local<Object> target, void* priv) { Environment* env = Environment::GetCurrent(context); - env->SetMethod(target, "getaddrinfo", GetAddrInfo); - env->SetMethod(target, "getnameinfo", GetNameInfo); + SetMethod(context, target, "getaddrinfo", GetAddrInfo); + SetMethod(context, target, "getnameinfo", GetNameInfo); // 'SetMethodNoSideEffect' means that debuggers can safely execute this // function for e.g. previews. - env->SetMethodNoSideEffect(target, "canonicalizeIP", CanonicalizeIP); + SetMethodNoSideEffect(context, target, "canonicalizeIP", CanonicalizeIP); // ... more code ... + Isolate* isolate = env->isolate(); // Building the `ChannelWrap` class for JS: Local<FunctionTemplate> channel_wrap = - env->NewFunctionTemplate(ChannelWrap::New); + NewFunctionTemplate(isolate, ChannelWrap::New); // Allow for 1 internal field, see `BaseObject` for details on this: channel_wrap->InstanceTemplate()->SetInternalFieldCount(1); channel_wrap->Inherit(AsyncWrap::GetConstructorTemplate(env)); // Set various methods on the class (i.e. on the prototype): - env->SetProtoMethod(channel_wrap, "queryAny", Query<QueryAnyWrap>); - env->SetProtoMethod(channel_wrap, "queryA", Query<QueryAWrap>); + SetProtoMethod(isolate, channel_wrap, "queryAny", Query<QueryAnyWrap>); + SetProtoMethod(isolate, channel_wrap, "queryA", Query<QueryAWrap>); // ... - env->SetProtoMethod(channel_wrap, "querySoa", Query<QuerySoaWrap>); - env->SetProtoMethod(channel_wrap, "getHostByAddr", Query<GetHostByAddrWrap>); + SetProtoMethod(isolate, channel_wrap, "querySoa", Query<QuerySoaWrap>); + SetProtoMethod(isolate, channel_wrap, "getHostByAddr", Query<GetHostByAddrWrap>); - env->SetProtoMethodNoSideEffect(channel_wrap, "getServers", GetServers); + SetProtoMethodNoSideEffect(isolate, channel_wrap, "getServers", GetServers); - env->SetConstructorFunction(target, "ChannelWrap", channel_wrap); + SetConstructorFunction(context, target, "ChannelWrap", channel_wrap); } // Run the `Initialize` function when loading this module through diff --git a/src/async_wrap.cc b/src/async_wrap.cc index 38f2eb421f4..9e76ad63ca6 100644 --- a/src/async_wrap.cc +++ b/src/async_wrap.cc @@ -337,12 +337,14 @@ void AsyncWrap::SetCallbackTrampoline(const FunctionCallbackInfo<Value>& args) { Local<FunctionTemplate> AsyncWrap::GetConstructorTemplate(Environment* env) { Local<FunctionTemplate> tmpl = env->async_wrap_ctor_template(); if (tmpl.IsEmpty()) { - tmpl = env->NewFunctionTemplate(nullptr); + Isolate* isolate = env->isolate(); + tmpl = NewFunctionTemplate(isolate, nullptr); tmpl->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "AsyncWrap")); tmpl->Inherit(BaseObject::GetConstructorTemplate(env)); - env->SetProtoMethod(tmpl, "getAsyncId", AsyncWrap::GetAsyncId); - env->SetProtoMethod(tmpl, "asyncReset", AsyncWrap::AsyncReset); - env->SetProtoMethod(tmpl, "getProviderType", AsyncWrap::GetProviderType); + SetProtoMethod(isolate, tmpl, "getAsyncId", AsyncWrap::GetAsyncId); + SetProtoMethod(isolate, tmpl, "asyncReset", AsyncWrap::AsyncReset); + SetProtoMethod( + isolate, tmpl, "getProviderType", AsyncWrap::GetProviderType); env->set_async_wrap_ctor_template(tmpl); } return tmpl; @@ -356,15 +358,15 @@ void AsyncWrap::Initialize(Local<Object> target, Isolate* isolate = env->isolate(); HandleScope scope(isolate); - env->SetMethod(target, "setupHooks", SetupHooks); - env->SetMethod(target, "setCallbackTrampoline", SetCallbackTrampoline); - env->SetMethod(target, "pushAsyncContext", PushAsyncContext); - env->SetMethod(target, "popAsyncContext", PopAsyncContext); - env->SetMethod(target, "executionAsyncResource", ExecutionAsyncResource); - env->SetMethod(target, "clearAsyncIdStack", ClearAsyncIdStack); - env->SetMethod(target, "queueDestroyAsyncId", QueueDestroyAsyncId); - env->SetMethod(target, "setPromiseHooks", SetPromiseHooks); - env->SetMethod(target, "registerDestroyHook", RegisterDestroyHook); + SetMethod(context, target, "setupHooks", SetupHooks); + SetMethod(context, target, "setCallbackTrampoline", SetCallbackTrampoline); + SetMethod(context, target, "pushAsyncContext", PushAsyncContext); + SetMethod(context, target, "popAsyncContext", PopAsyncContext); + SetMethod(context, target, "executionAsyncResource", ExecutionAsyncResource); + SetMethod(context, target, "clearAsyncIdStack", ClearAsyncIdStack); + SetMethod(context, target, "queueDestroyAsyncId", QueueDestroyAsyncId); + SetMethod(context, target, "setPromiseHooks", SetPromiseHooks); + SetMethod(context, target, "registerDestroyHook", RegisterDestroyHook); PropertyAttribute ReadOnlyDontDelete = static_cast<PropertyAttribute>(ReadOnly | DontDelete); diff --git a/src/cares_wrap.cc b/src/cares_wrap.cc index a16a0dcbd1b..1757d56d09a 100644 --- a/src/cares_wrap.cc +++ b/src/cares_wrap.cc @@ -1886,12 +1886,13 @@ void Initialize(Local<Object> target, Local<Context> context, void* priv) { Environment* env = Environment::GetCurrent(context); + Isolate* isolate = env->isolate(); - env->SetMethod(target, "getaddrinfo", GetAddrInfo); - env->SetMethod(target, "getnameinfo", GetNameInfo); - env->SetMethodNoSideEffect(target, "canonicalizeIP", CanonicalizeIP); + SetMethod(context, target, "getaddrinfo", GetAddrInfo); + SetMethod(context, target, "getnameinfo", GetNameInfo); + SetMethodNoSideEffect(context, target, "canonicalizeIP", CanonicalizeIP); - env->SetMethod(target, "strerror", StrError); + SetMethod(context, target, "strerror", StrError); target->Set(env->context(), FIXED_ONE_BYTE_STRING(env->isolate(), "AF_INET"), Integer::New(env->isolate(), AF_INET)).Check(); @@ -1913,44 +1914,45 @@ void Initialize(Local<Object> target, Local<FunctionTemplate> aiw = BaseObject::MakeLazilyInitializedJSTemplate(env); aiw->Inherit(AsyncWrap::GetConstructorTemplate(env)); - env->SetConstructorFunction(target, "GetAddrInfoReqWrap", aiw); + SetConstructorFunction(context, target, "GetAddrInfoReqWrap", aiw); Local<FunctionTemplate> niw = BaseObject::MakeLazilyInitializedJSTemplate(env); niw->Inherit(AsyncWrap::GetConstructorTemplate(env)); - env->SetConstructorFunction(target, "GetNameInfoReqWrap", niw); + SetConstructorFunction(context, target, "GetNameInfoReqWrap", niw); Local<FunctionTemplate> qrw = BaseObject::MakeLazilyInitializedJSTemplate(env); qrw->Inherit(AsyncWrap::GetConstructorTemplate(env)); - env->SetConstructorFunction(target, "QueryReqWrap", qrw); + SetConstructorFunction(context, target, "QueryReqWrap", qrw); Local<FunctionTemplate> channel_wrap = - env->NewFunctionTemplate(ChannelWrap::New); + NewFunctionTemplate(isolate, ChannelWrap::New); channel_wrap->InstanceTemplate()->SetInternalFieldCount( ChannelWrap::kInternalFieldCount); channel_wrap->Inherit(AsyncWrap::GetConstructorTemplate(env)); - env->SetProtoMethod(channel_wrap, "queryAny", Query<QueryAnyWrap>); - env->SetProtoMethod(channel_wrap, "queryA", Query<QueryAWrap>); - env->SetProtoMethod(channel_wrap, "queryAaaa", Query<QueryAaaaWrap>); - env->SetProtoMethod(channel_wrap, "queryCaa", Query<QueryCaaWrap>); - env->SetProtoMethod(channel_wrap, "queryCname", Query<QueryCnameWrap>); - env->SetProtoMethod(channel_wrap, "queryMx", Query<QueryMxWrap>); - env->SetProtoMethod(channel_wrap, "queryNs", Query<QueryNsWrap>); - env->SetProtoMethod(channel_wrap, "queryTxt", Query<QueryTxtWrap>); - env->SetProtoMethod(channel_wrap, "querySrv", Query<QuerySrvWrap>); - env->SetProtoMethod(channel_wrap, "queryPtr", Query<QueryPtrWrap>); - env->SetProtoMethod(channel_wrap, "queryNaptr", Query<QueryNaptrWrap>); - env->SetProtoMethod(channel_wrap, "querySoa", Query<QuerySoaWrap>); - env->SetProtoMethod(channel_wrap, "getHostByAddr", Query<GetHostByAddrWrap>); - - env->SetProtoMethodNoSideEffect(channel_wrap, "getServers", GetServers); - env->SetProtoMethod(channel_wrap, "setServers", SetServers); - env->SetProtoMethod(channel_wrap, "setLocalAddress", SetLocalAddress); - env->SetProtoMethod(channel_wrap, "cancel", Cancel); - - env->SetConstructorFunction(target, "ChannelWrap", channel_wrap); + SetProtoMethod(isolate, channel_wrap, "queryAny", Query<QueryAnyWrap>); + SetProtoMethod(isolate, channel_wrap, "queryA", Query<QueryAWrap>); + SetProtoMethod(isolate, channel_wrap, "queryAaaa", Query<QueryAaaaWrap>); + SetProtoMethod(isolate, channel_wrap, "queryCaa", Query<QueryCaaWrap>); + SetProtoMethod(isolate, channel_wrap, "queryCname", Query<QueryCnameWrap>); + SetProtoMethod(isolate, channel_wrap, "queryMx", Query<QueryMxWrap>); + SetProtoMethod(isolate, channel_wrap, "queryNs", Query<QueryNsWrap>); + SetProtoMethod(isolate, channel_wrap, "queryTxt", Query<QueryTxtWrap>); + SetProtoMethod(isolate, channel_wrap, "querySrv", Query<QuerySrvWrap>); + SetProtoMethod(isolate, channel_wrap, "queryPtr", Query<QueryPtrWrap>); + SetProtoMethod(isolate, channel_wrap, "queryNaptr", Query<QueryNaptrWrap>); + SetProtoMethod(isolate, channel_wrap, "querySoa", Query<QuerySoaWrap>); + SetProtoMethod( + isolate, channel_wrap, "getHostByAddr", Query<GetHostByAddrWrap>); + + SetProtoMethodNoSideEffect(isolate, channel_wrap, "getServers", GetServers); + SetProtoMethod(isolate, channel_wrap, "setServers", SetServers); + SetProtoMethod(isolate, channel_wrap, "setLocalAddress", SetLocalAddress); + SetProtoMethod(isolate, channel_wrap, "cancel", Cancel); + + SetConstructorFunction(context, target, "ChannelWrap", channel_wrap); } } // namespace cares_wrap diff --git a/src/crypto/crypto_cipher.cc b/src/crypto/crypto_cipher.cc index 6c663a2b21d..0ce2708d12c 100644 --- a/src/crypto/crypto_cipher.cc +++ b/src/crypto/crypto_cipher.cc @@ -13,10 +13,12 @@ namespace node { using v8::Array; using v8::ArrayBuffer; using v8::BackingStore; +using v8::Context; using v8::FunctionCallbackInfo; using v8::FunctionTemplate; using v8::HandleScope; using v8::Int32; +using v8::Isolate; using v8::Local; using v8::Object; using v8::Uint32; @@ -270,43 +272,54 @@ void CipherBase::MemoryInfo(MemoryTracker* tracker) const { } void CipherBase::Initialize(Environment* env, Local<Object> target) { - Local<FunctionTemplate> t = env->NewFunctionTemplate(New); + Isolate* isolate = env->isolate(); + Local<Context> context = env->context(); + + Local<FunctionTemplate> t = NewFunctionTemplate(isolate, New); t->InstanceTemplate()->SetInternalFieldCount( CipherBase::kInternalFieldCount); t->Inherit(BaseObject::GetConstructorTemplate(env)); - env->SetProtoMethod(t, "init", Init); - env->SetProtoMethod(t, "initiv", InitIv); - env->SetProtoMethod(t, "update", Update); - env->SetProtoMethod(t, "final", Final); - env->SetProtoMethod(t, "setAutoPadding", SetAutoPadding); - env->SetProtoMethodNoSideEffect(t, "getAuthTag", GetAuthTag); - env->SetProtoMethod(t, "setAuthTag", SetAuthTag); - env->SetProtoMethod(t, "setAAD", SetAAD); - env->SetConstructorFunction(target, "CipherBase", t); - - env->SetMethodNoSideEffect(target, "getSSLCiphers", GetSSLCiphers); - env->SetMethodNoSideEffect(target, "getCiphers", GetCiphers); - - env->SetMethod(target, "publicEncrypt", - PublicKeyCipher::Cipher<PublicKeyCipher::kPublic, - EVP_PKEY_encrypt_init, - EVP_PKEY_encrypt>); - env->SetMethod(target, "privateDecrypt", - PublicKeyCipher::Cipher<PublicKeyCipher::kPrivate, - EVP_PKEY_decrypt_init, - EVP_PKEY_decrypt>); - env->SetMethod(target, "privateEncrypt", - PublicKeyCipher::Cipher<PublicKeyCipher::kPrivate, - EVP_PKEY_sign_init, - EVP_PKEY_sign>); - env->SetMethod(target, "publicDecrypt", - PublicKeyCipher::Cipher<PublicKeyCipher::kPublic, - EVP_PKEY_verify_recover_init, - EVP_PKEY_verify_recover>); - - env->SetMethodNoSideEffect(target, "getCipherInfo", GetCipherInfo); + SetProtoMethod(isolate, t, "init", Init); + SetProtoMethod(isolate, t, "initiv", InitIv); + SetProtoMethod(isolate, t, "update", Update); + SetProtoMethod(isolate, t, "final", Final); + SetProtoMethod(isolate, t, "setAutoPadding", SetAutoPadding); + SetProtoMethodNoSideEffect(isolate, t, "getAuthTag", GetAuthTag); + SetProtoMethod(isolate, t, "setAuthTag", SetAuthTag); + SetProtoMethod(isolate, t, "setAAD", SetAAD); + SetConstructorFunction(context, target, "CipherBase", t); + + SetMethodNoSideEffect(context, target, "getSSLCiphers", GetSSLCiphers); + SetMethodNoSideEffect(context, target, "getCiphers", GetCiphers); + + SetMethod(context, + target, + "publicEncrypt", + PublicKeyCipher::Cipher<PublicKeyCipher::kPublic, + EVP_PKEY_encrypt_init, + EVP_PKEY_encrypt>); + SetMethod(context, + target, + "privateDecrypt", + PublicKeyCipher::Cipher<PublicKeyCipher::kPrivate, + EVP_PKEY_decrypt_init, + EVP_PKEY_decrypt>); + SetMethod(context, + target, + "privateEncrypt", + PublicKeyCipher::Cipher<PublicKeyCipher::kPrivate, + EVP_PKEY_sign_init, + EVP_PKEY_sign>); + SetMethod(context, + target, + "publicDecrypt", + PublicKeyCipher::Cipher<PublicKeyCipher::kPublic, + EVP_PKEY_verify_recover_init, + EVP_PKEY_verify_recover>); + + SetMethodNoSideEffect(context, target, "getCipherInfo", GetCipherInfo); NODE_DEFINE_CONSTANT(target, kWebCryptoCipherEncrypt); NODE_DEFINE_CONSTANT(target, kWebCryptoCipherDecrypt); diff --git a/src/crypto/crypto_context.cc b/src/crypto/crypto_context.cc index e2291f72b66..2265cfb63d0 100644 --- a/src/crypto/crypto_context.cc +++ b/src/crypto/crypto_context.cc @@ -31,6 +31,7 @@ using v8::FunctionTemplate; using v8::HandleScope; using v8::Int32; using v8::Integer; +using v8::Isolate; using v8::Local; using v8::Object; using v8::PropertyAttribute; @@ -256,51 +257,52 @@ Local<FunctionTemplate> SecureContext::GetConstructorTemplate( Environment* env) { Local<FunctionTemplate> tmpl = env->secure_context_constructor_template(); if (tmpl.IsEmpty()) { - tmpl = env->NewFunctionTemplate(New); + Isolate* isolate = env->isolate(); + tmpl = NewFunctionTemplate(isolate, New); tmpl->InstanceTemplate()->SetInternalFieldCount( SecureContext::kInternalFieldCount); tmpl->Inherit(BaseObject::GetConstructorTemplate(env)); tmpl->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "SecureContext")); - env->SetProtoMethod(tmpl, "init", Init); - env->SetProtoMethod(tmpl, "setKey", SetKey); - env->SetProtoMethod(tmpl, "setCert", SetCert); - env->SetProtoMethod(tmpl, "addCACert", AddCACert); - env->SetProtoMethod(tmpl, "addCRL", AddCRL); - env->SetProtoMethod(tmpl, "addRootCerts", AddRootCerts); - env->SetProtoMethod(tmpl, "setCipherSuites", SetCipherSuites); - env->SetProtoMethod(tmpl, "setCiphers", SetCiphers); - env->SetProtoMethod(tmpl, "setSigalgs", SetSigalgs); - env->SetProtoMethod(tmpl, "setECDHCurve", SetECDHCurve); - env->SetProtoMethod(tmpl, "setDHParam", SetDHParam); - env->SetProtoMethod(tmpl, "setMaxProto", SetMaxProto); - env->SetProtoMethod(tmpl, "setMinProto", SetMinProto); - env->SetProtoMethod(tmpl, "getMaxProto", GetMaxProto); - env->SetProtoMethod(tmpl, "getMinProto", GetMinProto); - env->SetProtoMethod(tmpl, "setOptions", SetOptions); - env->SetProtoMethod(tmpl, "setSessionIdContext", SetSessionIdContext); - env->SetProtoMethod(tmpl, "setSessionTimeout", SetSessionTimeout); - env->SetProtoMethod(tmpl, "close", Close); - env->SetProtoMethod(tmpl, "loadPKCS12", LoadPKCS12); - env->SetProtoMethod(tmpl, "setTicketKeys", SetTicketKeys); - env->SetProtoMethod(tmpl, "setFreeListLength", SetFreeListLength); - env->SetProtoMethod(tmpl, "enableTicketKeyCallback", - EnableTicketKeyCallback); - - env->SetProtoMethodNoSideEffect(tmpl, "getTicketKeys", GetTicketKeys); - env->SetProtoMethodNoSideEffect(tmpl, "getCertificate", - GetCertificate<true>); - env->SetProtoMethodNoSideEffect(tmpl, "getIssuer", - GetCertificate<false>); - - #ifndef OPENSSL_NO_ENGINE - env->SetProtoMethod(tmpl, "setEngineKey", SetEngineKey); - env->SetProtoMethod(tmpl, "setClientCertEngine", SetClientCertEngine); - #endif // !OPENSSL_NO_ENGINE - - #define SET_INTEGER_CONSTANTS(name, value) \ - tmpl->Set(FIXED_ONE_BYTE_STRING(env->isolate(), name), \ - Integer::NewFromUnsigned(env->isolate(), value)); + SetProtoMethod(isolate, tmpl, "init", Init); + SetProtoMethod(isolate, tmpl, "setKey", SetKey); + SetProtoMethod(isolate, tmpl, "setCert", SetCert); + SetProtoMethod(isolate, tmpl, "addCACert", AddCACert); + SetProtoMethod(isolate, tmpl, "addCRL", AddCRL); + SetProtoMethod(isolate, tmpl, "addRootCerts", AddRootCerts); + SetProtoMethod(isolate, tmpl, "setCipherSuites", SetCipherSuites); + SetProtoMethod(isolate, tmpl, "setCiphers", SetCiphers); + SetProtoMethod(isolate, tmpl, "setSigalgs", SetSigalgs); + SetProtoMethod(isolate, tmpl, "setECDHCurve", SetECDHCurve); + SetProtoMethod(isolate, tmpl, "setDHParam", SetDHParam); + SetProtoMethod(isolate, tmpl, "setMaxProto", SetMaxProto); + SetProtoMethod(isolate, tmpl, "setMinProto", SetMinProto); + SetProtoMethod(isolate, tmpl, "getMaxProto", GetMaxProto); + SetProtoMethod(isolate, tmpl, "getMinProto", GetMinProto); + SetProtoMethod(isolate, tmpl, "setOptions", SetOptions); + SetProtoMethod(isolate, tmpl, "setSessionIdContext", SetSessionIdContext); + SetProtoMethod(isolate, tmpl, "setSessionTimeout", SetSessionTimeout); + SetProtoMethod(isolate, tmpl, "close", Close); + SetProtoMethod(isolate, tmpl, "loadPKCS12", LoadPKCS12); + SetProtoMethod(isolate, tmpl, "setTicketKeys", SetTicketKeys); + SetProtoMethod(isolate, tmpl, "setFreeListLength", SetFreeListLength); + SetProtoMethod( + isolate, tmpl, "enableTicketKeyCallback", EnableTicketKeyCallback); + + SetProtoMethodNoSideEffect(isolate, tmpl, "getTicketKeys", GetTicketKeys); + SetProtoMethodNoSideEffect( + isolate, tmpl, "getCertificate", GetCertificate<true>); + SetProtoMethodNoSideEffect( + isolate, tmpl, "getIssuer", GetCertificate<false>); + +#ifndef OPENSSL_NO_ENGINE + SetProtoMethod(isolate, tmpl, "setEngineKey", SetEngineKey); + SetProtoMethod(isolate, tmpl, "setClientCertEngine", SetClientCertEngine); +#endif // !OPENSSL_NO_ENGINE + +#define SET_INTEGER_CONSTANTS(name, value) \ + tmpl->Set(FIXED_ONE_BYTE_STRING(isolate, name), \ + Integer::NewFromUnsigned(isolate, value)); SET_INTEGER_CONSTANTS("kTicketKeyReturnIndex", kTicketKeyReturnIndex); SET_INTEGER_CONSTANTS("kTicketKeyHMACIndex", kTicketKeyHMACIndex); SET_INTEGER_CONSTANTS("kTicketKeyAESIndex", kTicketKeyAESIndex); @@ -308,14 +310,11 @@ Local<FunctionTemplate> SecureContext::GetConstructorTemplate( SET_INTEGER_CONSTANTS("kTicketKeyIVIndex", kTicketKeyIVIndex); #undef SET_INTEGER_CONSTANTS - Local<FunctionTemplate> ctx_getter_templ = - FunctionTemplate::New(env->isolate(), - CtxGetter, - Local<Value>(), - Signature::New(env->isolate(), tmpl)); + Local<FunctionTemplate> ctx_getter_templ = FunctionTemplate::New( + isolate, CtxGetter, Local<Value>(), Signature::New(isolate, tmpl)); tmpl->PrototypeTemplate()->SetAccessorProperty( - FIXED_ONE_BYTE_STRING(env->isolate(), "_external"), + FIXED_ONE_BYTE_STRING(isolate, "_external"), ctx_getter_templ, Local<FunctionTemplate>(), static_cast<PropertyAttribute>(ReadOnly | DontDelete)); @@ -326,17 +325,20 @@ Local<FunctionTemplate> SecureContext::GetConstructorTemplate( } void SecureContext::Initialize(Environment* env, Local<Object> target) { - env->SetConstructorFunction( - target, - "SecureContext", - GetConstructorTemplate(env), - Environment::SetConstructorFunctionFlag::NONE); - - env->SetMethodNoSideEffect(target, "getRootCertificates", - GetRootCertificates); + Local<Context> context = env->context(); + SetConstructorFunction(context, + target, + "SecureContext", + GetConstructorTemplate(env), + SetConstructorFunctionFlag::NONE); + + SetMethodNoSideEffect( + context, target, "getRootCertificates", GetRootCertificates); // Exposed for testing purposes only. - env->SetMethodNoSideEffect(target, "isExtraRootCertsFileLoaded", - IsExtraRootCertsFileLoaded); + SetMethodNoSideEffect(context, + target, + "isExtraRootCertsFileLoaded", + IsExtraRootCertsFileLoaded); } void SecureContext::RegisterExternalReferences( diff --git a/src/crypto/crypto_dh.cc b/src/crypto/crypto_dh.cc index da1b810a66d..dd69323b800 100644 --- a/src/crypto/crypto_dh.cc +++ b/src/crypto/crypto_dh.cc @@ -14,12 +14,14 @@ namespace node { using v8::ArrayBuffer; using v8::BackingStore; using v8::ConstructorBehavior; +using v8::Context; using v8::DontDelete; using v8::FunctionCallback; using v8::FunctionCallbackInfo; using v8::FunctionTemplate; using v8::HandleScope; using v8::Int32; +using v8::Isolate; using v8::Just; using v8::Local; using v8::Maybe; @@ -57,8 +59,10 @@ DiffieHellman::DiffieHellman(Environment* env, Local<Object> wrap) } void DiffieHellman::Initialize(Environment* env, Local<Object> target) { - auto make = [&] (Local<String> name, FunctionCallback callback) { - Local<FunctionTemplate> t = env->NewFunctionTemplate(callback); + Isolate* isolate = env->isolate(); + Local<Context> context = env->context(); + auto make = [&](Local<String> name, FunctionCallback callback) { + Local<FunctionTemplate> t = NewFunctionTemplate(isolate, callback); const PropertyAttribute attributes = static_cast<PropertyAttribute>(ReadOnly | DontDelete); @@ -67,17 +71,17 @@ void DiffieHellman::Initialize(Environment* env, Local<Object> target) { DiffieHellman::kInternalFieldCount); t->Inherit(BaseObject::GetConstructorTemplate(env)); - env->SetProtoMethod(t, "generateKeys", GenerateKeys); - env->SetProtoMethod(t, "computeSecret", ComputeSecret); - env->SetProtoMethodNoSideEffect(t, "getPrime", GetPrime); - env->SetProtoMethodNoSideEffect(t, "getGenerator", GetGenerator); - env->SetProtoMethodNoSideEffect(t, "getPublicKey", GetPublicKey); - env->SetProtoMethodNoSideEffect(t, "getPrivateKey", GetPrivateKey); - env->SetProtoMethod(t, "setPublicKey", SetPublicKey); - env->SetProtoMethod(t, "setPrivateKey", SetPrivateKey); + SetProtoMethod(isolate, t, "generateKeys", GenerateKeys); + SetProtoMethod(isolate, t, "computeSecret", ComputeSecret); + SetProtoMethodNoSideEffect(isolate, t, "getPrime", GetPrime); + SetProtoMethodNoSideEffect(isolate, t, "getGenerator", GetGenerator); + SetProtoMethodNoSideEffect(isolate, t, "getPublicKey", GetPublicKey); + SetProtoMethodNoSideEffect(isolate, t, "getPrivateKey", GetPrivateKey); + SetProtoMethod(isolate, t, "setPublicKey", SetPublicKey); + SetProtoMethod(isolate, t, "setPrivateKey", SetPrivateKey); Local<FunctionTemplate> verify_error_getter_templ = - FunctionTemplate::New(env->isolate(), + FunctionTemplate::New(isolate, DiffieHellman::VerifyErrorGetter, Local<Value>(), Signature::New(env->isolate(), t), @@ -91,14 +95,15 @@ void DiffieHellman::Initialize(Environment* env, Local<Object> target) { Local<FunctionTemplate>(), attributes); - env->SetConstructorFunction(target, name, t); + SetConstructorFunction(context, target, name, t); }; make(FIXED_ONE_BYTE_STRING(env->isolate(), "DiffieHellman"), New); make(FIXED_ONE_BYTE_STRING(env->isolate(), "DiffieHellmanGroup"), DiffieHellmanGroup); - env->SetMethodNoSideEffect(target, "statelessDH", DiffieHellman::Stateless); + SetMethodNoSideEffect( + context, target, "statelessDH", DiffieHellman::Stateless); DHKeyPairGenJob::Initialize(env, target); DHKeyExportJob::Initialize(env, target); DHBitsJob::Initialize(env, target); diff --git a/src/crypto/crypto_ec.cc b/src/crypto/crypto_ec.cc index e6a90200a43..0c14b09f638 100644 --- a/src/crypto/crypto_ec.cc +++ b/src/crypto/crypto_ec.cc @@ -21,9 +21,11 @@ namespace node { using v8::Array; using v8::ArrayBuffer; using v8::BackingStore; +using v8::Context; using v8::FunctionCallbackInfo; using v8::FunctionTemplate; using v8::Int32; +using v8::Isolate; using v8::Just; using v8::JustVoid; using v8::Local; @@ -60,22 +62,25 @@ int GetOKPCurveFromName(const char* name) { } void ECDH::Initialize(Environment* env, Local<Object> target) { - Local<FunctionTemplate> t = env->NewFunctionTemplate(New); + Isolate* isolate = env->isolate(); + Local<Context> context = env->context(); + + Local<FunctionTemplate> t = NewFunctionTemplate(isolate, New); t->Inherit(BaseObject::GetConstructorTemplate(env)); t->InstanceTemplate()->SetInternalFieldCount(ECDH::kInternalFieldCount); - env->SetProtoMethod(t, "generateKeys", GenerateKeys); - env->SetProtoMethod(t, "computeSecret", ComputeSecret); - env->SetProtoMethodNoSideEffect(t, "getPublicKey", GetPublicKey); - env->SetProtoMethodNoSideEffect(t, "getPrivateKey", GetPrivateKey); - env->SetProtoMethod(t, "setPublicKey", SetPublicKey); - env->SetProtoMethod(t, "setPrivateKey", SetPrivateKey); + SetProtoMethod(isolate, t, "generateKeys", GenerateKeys); + SetProtoMethod(isolate, t, "computeSecret", ComputeSecret); + SetProtoMethodNoSideEffect(isolate, t, "getPublicKey", GetPublicKey); + SetProtoMethodNoSideEffect(isolate, t, "getPrivateKey", GetPrivateKey); + SetProtoMethod(isolate, t, "setPublicKey", SetPublicKey); + SetProtoMethod(isolate, t, "setPrivateKey", SetPrivateKey); - env->SetConstructorFunction(target, "ECDH", t); + SetConstructorFunction(context, target, "ECDH", t); - env->SetMethodNoSideEffect(target, "ECDHConvertKey", ECDH::ConvertKey); - env->SetMethodNoSideEffect(target, "getCurves", ECDH::GetCurves); + SetMethodNoSideEffect(context, target, "ECDHConvertKey", ECDH::ConvertKey); + SetMethodNoSideEffect(context, target, "getCurves", ECDH::GetCurves); ECDHBitsJob::Initialize(env, target); ECKeyPairGenJob::Initialize(env, target); diff --git a/src/crypto/crypto_hash.cc b/src/crypto/crypto_hash.cc index 24dc436d248..200603a85ef 100644 --- a/src/crypto/crypto_hash.cc +++ b/src/crypto/crypto_hash.cc @@ -11,8 +11,10 @@ namespace node { +using v8::Context; using v8::FunctionCallbackInfo; using v8::FunctionTemplate; +using v8::Isolate; using v8::Just; using v8::Local; using v8::Maybe; @@ -51,18 +53,20 @@ void Hash::GetHashes(const FunctionCallbackInfo<Value>& args) { } void Hash::Initialize(Environment* env, Local<Object> target) { - Local<FunctionTemplate> t = env->NewFunctionTemplate(New); + Isolate* isolate = env->isolate(); + Local<Context> context = env->context(); + Local<FunctionTemplate> t = NewFunctionTemplate(isolate, New); t->InstanceTemplate()->SetInternalFieldCount( Hash::kInternalFieldCount); t->Inherit(BaseObject::GetConstructorTemplate(env)); - env->SetProtoMethod(t, "update", HashUpdate); - env->SetProtoMethod(t, "digest", HashDigest); + SetProtoMethod(isolate, t, "update", HashUpdate); + SetProtoMethod(isolate, t, "digest", HashDigest); - env->SetConstructorFunction(target, "Hash", t); + SetConstructorFunction(context, target, "Hash", t); - env->SetMethodNoSideEffect(target, "getHashes", GetHashes); + SetMethodNoSideEffect(context, target, "getHashes", GetHashes); HashJob::Initialize(env, target); } diff --git a/src/crypto/crypto_hmac.cc b/src/crypto/crypto_hmac.cc index afda92265e8..2e1c97ce480 100644 --- a/src/crypto/crypto_hmac.cc +++ b/src/crypto/crypto_hmac.cc @@ -16,6 +16,7 @@ namespace node { using v8::FunctionCallbackInfo; using v8::FunctionTemplate; using v8::HandleScope; +using v8::Isolate; using v8::Just; using v8::Local; using v8::Maybe; @@ -37,17 +38,18 @@ void Hmac::MemoryInfo(MemoryTracker* tracker) const { } void Hmac::Initialize(Environment* env, Local<Object> target) { - Local<FunctionTemplate> t = env->NewFunctionTemplate(New); + Isolate* isolate = env->isolate(); + Local<FunctionTemplate> t = NewFunctionTemplate(isolate, New); t->InstanceTemplate()->SetInternalFieldCount( Hmac::kInternalFieldCount); t->Inherit(BaseObject::GetConstructorTemplate(env)); - env->SetProtoMethod(t, "init", HmacInit); - env->SetProtoMethod(t, "update", HmacUpdate); - env->SetProtoMethod(t, "digest", HmacDigest); + SetProtoMethod(isolate, t, "init", HmacInit); + SetProtoMethod(isolate, t, "update", HmacUpdate); + SetProtoMethod(isolate, t, "digest", HmacDigest); - env->SetConstructorFunction(target, "Hmac", t); + SetConstructorFunction(env->context(), target, "Hmac", t); HmacJob::Initialize(env, target); } diff --git a/src/crypto/crypto_keys.cc b/src/crypto/crypto_keys.cc index ba37f24c48d..27e3f4f8676 100644 --- a/src/crypto/crypto_keys.cc +++ b/src/crypto/crypto_keys.cc @@ -24,6 +24,7 @@ using v8::Function; using v8::FunctionCallbackInfo; using v8::FunctionTemplate; using v8::Int32; +using v8::Isolate; using v8::Just; using v8::Local; using v8::Maybe; @@ -906,23 +907,24 @@ v8::Local<v8::Function> KeyObjectHandle::Initialize(Environment* env) { if (!templ.IsEmpty()) { return templ; } - Local<FunctionTemplate> t = env->NewFunctionTemplate(New); + Isolate* isolate = env->isolate(); + Local<FunctionTemplate> t = NewFunctionTemplate(isolate, New); t->InstanceTemplate()->SetInternalFieldCount( KeyObjectHandle::kInternalFieldCount); t->Inherit(BaseObject::GetConstructorTemplate(env)); - env->SetProtoMethod(t, "init", Init); - env->SetProtoMethodNoSideEffect(t, "getSymmetricKeySize", - GetSymmetricKeySize); - env->SetProtoMethodNoSideEffect(t, "getAsymmetricKeyType", - GetAsymmetricKeyType); - env->SetProtoMethod(t, "export", Export); - env->SetProtoMethod(t, "exportJwk", ExportJWK); - env->SetProtoMethod(t, "initECRaw", InitECRaw); - env->SetProtoMethod(t, "initEDRaw", InitEDRaw); - env->SetProtoMethod(t, "initJwk", InitJWK); - env->SetProtoMethod(t, "keyDetail", GetKeyDetail); - env->SetProtoMethod(t, "equals", Equals); + SetProtoMethod(isolate, t, "init", Init); + SetProtoMethodNoSideEffect( + isolate, t, "getSymmetricKeySize", GetSymmetricKeySize); + SetProtoMethodNoSideEffect( + isolate, t, "getAsymmetricKeyType", GetAsymmetricKeyType); + SetProtoMethod(isolate, t, "export", Export); + SetProtoMethod(isolate, t, "exportJwk", ExportJWK); + SetProtoMethod(isolate, t, "initECRaw", InitECRaw); + SetProtoMethod(isolate, t, "initEDRaw", InitEDRaw); + SetProtoMethod(isolate, t, "initJwk", InitJWK); + SetProtoMethod(isolate, t, "keyDetail", GetKeyDetail); + SetProtoMethod(isolate, t, "equals", Equals); auto function = t->GetFunction(env->context()).ToLocalChecked(); env->set_crypto_key_object_handle_constructor(function); @@ -1317,8 +1319,10 @@ void KeyObjectHandle::ExportJWK( } void NativeKeyObject::Initialize(Environment* env, Local<Object> target) { - env->SetMethod(target, "createNativeKeyObjectClass", - NativeKeyObject::CreateNativeKeyObjectClass); + SetMethod(env->context(), + target, + "createNativeKeyObjectClass", + NativeKeyObject::CreateNativeKeyObjectClass); } void NativeKeyObject::RegisterExternalReferences( @@ -1338,12 +1342,14 @@ void NativeKeyObject::New(const FunctionCallbackInfo<Value>& args) { void NativeKeyObject::CreateNativeKeyObjectClass( const FunctionCallbackInfo<Value>& args) { Environment* env = Environment::GetCurrent(args); + Isolate* isolate = env->isolate(); CHECK_EQ(args.Length(), 1); Local<Value> callback = args[0]; CHECK(callback->IsFunction()); - Local<FunctionTemplate> t = env->NewFunctionTemplate(NativeKeyObject::New); + Local<FunctionTemplate> t = + NewFunctionTemplate(isolate, NativeKeyObject::New); t->InstanceTemplate()->SetInternalFieldCount( KeyObjectHandle::kInternalFieldCount); t->Inherit(BaseObject::GetConstructorTemplate(env)); diff --git a/src/crypto/crypto_sig.cc b/src/crypto/crypto_sig.cc index 9bebaafb371..72f98788d17 100644 --- a/src/crypto/crypto_sig.cc +++ b/src/crypto/crypto_sig.cc @@ -17,6 +17,7 @@ using v8::FunctionCallbackInfo; using v8::FunctionTemplate; using v8::HandleScope; using v8::Int32; +using v8::Isolate; using v8::Just; using v8::Local; using v8::Maybe; @@ -325,17 +326,18 @@ Sign::Sign(Environment* env, Local<Object> wrap) : SignBase(env, wrap) { } void Sign::Initialize(Environment* env, Local<Object> target) { - Local<FunctionTemplate> t = env->NewFunctionTemplate(New); + Isolate* isolate = env->isolate(); + Local<FunctionTemplate> t = NewFunctionTemplate(isolate, New); t->InstanceTemplate()->SetInternalFieldCount( SignBase::kInternalFieldCount); t->Inherit(BaseObject::GetConstructorTemplate(env)); - env->SetProtoMethod(t, "init", SignInit); - env->SetProtoMethod(t, "update", SignUpdate); - env->SetProtoMethod(t, "sign", SignFinal); + SetProtoMethod(isolate, t, "init", SignInit); + SetProtoMethod(isolate, t, "update", SignUpdate); + SetProtoMethod(isolate, t, "sign", SignFinal); - env->SetConstructorFunction(target, "Sign", t); + SetConstructorFunction(env->context(), target, "Sign", t); SignJob::Initialize(env, target); @@ -454,17 +456,18 @@ Verify::Verify(Environment* env, Local<Object> wrap) } void Verify::Initialize(Environment* env, Local<Object> target) { - Local<FunctionTemplate> t = env->NewFunctionTemplate(New); + Isolate* isolate = env->isolate(); + Local<FunctionTemplate> t = NewFunctionTemplate(isolate, New); t->InstanceTemplate()->SetInternalFieldCount( SignBase::kInternalFieldCount); t->Inherit(BaseObject::GetConstructorTemplate(env)); - env->SetProtoMethod(t, "init", VerifyInit); - env->SetProtoMethod(t, "update", VerifyUpdate); - env->SetProtoMethod(t, "verify", VerifyFinal); + SetProtoMethod(isolate, t, "init", VerifyInit); + SetProtoMethod(isolate, t, "update", VerifyUpdate); + SetProtoMethod(isolate, t, "verify", VerifyFinal); - env->SetConstructorFunction(target, "Verify", t); + SetConstructorFunction(env->context(), target, "Verify", t); } void Verify::RegisterExternalReferences(ExternalReferenceRegistry* registry) { diff --git a/src/crypto/crypto_spkac.cc b/src/crypto/crypto_spkac.cc index 3489dee3378..92484847afb 100644 --- a/src/crypto/crypto_spkac.cc +++ b/src/crypto/crypto_spkac.cc @@ -8,6 +8,7 @@ namespace node { +using v8::Context; using v8::FunctionCallbackInfo; using v8::Local; using v8::Object; @@ -125,9 +126,12 @@ void ExportChallenge(const FunctionCallbackInfo<Value>& args) { } void Initialize(Environment* env, Local<Object> target) { - env->SetMethodNoSideEffect(target, "certVerifySpkac", VerifySpkac); - env->SetMethodNoSideEffect(target, "certExportPublicKey", ExportPublicKey); - env->SetMethodNoSideEffect(target, "certExportChallenge", ExportChallenge); + Local<Context> context = env->context(); + SetMethodNoSideEffect(context, target, "certVerifySpkac", VerifySpkac); + SetMethodNoSideEffect( + context, target, "certExportPublicKey", ExportPublicKey); + SetMethodNoSideEffect( + context, target, "certExportChallenge", ExportChallenge); } void RegisterExternalReferences(ExternalReferenceRegistry* registry) { diff --git a/src/crypto/crypto_timing.cc b/src/crypto/crypto_timing.cc index 3cc1a12ec00..8904f6b140d 100644 --- a/src/crypto/crypto_timing.cc +++ b/src/crypto/crypto_timing.cc @@ -47,7 +47,8 @@ void TimingSafeEqual(const FunctionCallbackInfo<Value>& args) { } void Initialize(Environment* env, Local<Object> target) { - env->SetMethodNoSideEffect(target, "timingSafeEqual", TimingSafeEqual); + SetMethodNoSideEffect( + env->context(), target, "timingSafeEqual", TimingSafeEqual); } void RegisterExternalReferences(ExternalReferenceRegistry* registry) { registry->Register(TimingSafeEqual); diff --git a/src/crypto/crypto_tls.cc b/src/crypto/crypto_tls.cc index 6e6ef5251fc..849b21f28df 100644 --- a/src/crypto/crypto_tls.cc +++ b/src/crypto/crypto_tls.cc @@ -2030,8 +2030,9 @@ void TLSWrap::Initialize( Local<Context> context, void* priv) { Environment* env = Environment::GetCurrent(context); + Isolate* isolate = env->isolate(); - env->SetMethod(target, "wrap", TLSWrap::Wrap); + SetMethod(context, target, "wrap", TLSWrap::Wrap); NODE_DEFINE_CONSTANT(target, HAVE_SSL_TRACE); @@ -2054,54 +2055,56 @@ void TLSWrap::Initialize( t->Inherit(AsyncWrap::GetConstructorTemplate(env)); - env->SetProtoMethod(t, "certCbDone", CertCbDone); - env->SetProtoMethod(t, "destroySSL", DestroySSL); - env->SetProtoMethod(t, "enableCertCb", EnableCertCb); - env->SetProtoMethod(t, "endParser", EndParser); - env->SetProtoMethod(t, "enableKeylogCallback", EnableKeylogCallback); - env->SetProtoMethod(t, "enableSessionCallbacks", EnableSessionCallbacks); - env->SetProtoMethod(t, "enableTrace", EnableTrace); - env->SetProtoMethod(t, "getServername", GetServername); - env->SetProtoMethod(t, "loadSession", LoadSession); - env->SetProtoMethod(t, "newSessionDone", NewSessionDone); - env->SetProtoMethod(t, "receive", Receive); - env->SetProtoMethod(t, "renegotiate", Renegotiate); - env->SetProtoMethod(t, "requestOCSP", RequestOCSP); - env->SetProtoMethod(t, "setALPNProtocols", SetALPNProtocols); - env->SetProtoMethod(t, "setOCSPResponse", SetOCSPResponse); - env->SetProtoMethod(t, "setServername", SetServername); - env->SetProtoMethod(t, "setSession", SetSession); - env->SetProtoMethod(t, "setVerifyMode", SetVerifyMode); - env->SetProtoMethod(t, "start", Start); - - env->SetProtoMethodNoSideEffect(t, "exportKeyingMaterial", - ExportKeyingMaterial); - env->SetProtoMethodNoSideEffect(t, "isSessionReused", IsSessionReused); - env->SetProtoMethodNoSideEffect(t, "getALPNNegotiatedProtocol", - GetALPNNegotiatedProto); - env->SetProtoMethodNoSideEffect(t, "getCertificate", GetCertificate); - env->SetProtoMethodNoSideEffect(t, "getX509Certificate", GetX509Certificate); - env->SetProtoMethodNoSideEffect(t, "getCipher", GetCipher); - env->SetProtoMethodNoSideEffect(t, "getEphemeralKeyInfo", - GetEphemeralKeyInfo); - env->SetProtoMethodNoSideEffect(t, "getFinished", GetFinished); - env->SetProtoMethodNoSideEffect(t, "getPeerCertificate", GetPeerCertificate); - env->SetProtoMethodNoSideEffect(t, "getPeerX509Certificate", - GetPeerX509Certificate); - env->SetProtoMethodNoSideEffect(t, "getPeerFinished", GetPeerFinished); - env->SetProtoMethodNoSideEffect(t, "getProtocol", GetProtocol); - env->SetProtoMethodNoSideEffect(t, "getSession", GetSession); - env->SetProtoMethodNoSideEffect(t, "getSharedSigalgs", GetSharedSigalgs); - env->SetProtoMethodNoSideEffect(t, "getTLSTicket", GetTLSTicket); - env->SetProtoMethodNoSideEffect(t, "verifyError", VerifyError); + SetProtoMethod(isolate, t, "certCbDone", CertCbDone); + SetProtoMethod(isolate, t, "destroySSL", DestroySSL); + SetProtoMethod(isolate, t, "enableCertCb", EnableCertCb); + SetProtoMethod(isolate, t, "endParser", EndParser); + SetProtoMethod(isolate, t, "enableKeylogCallback", EnableKeylogCallback); + SetProtoMethod(isolate, t, "enableSessionCallbacks", EnableSessionCallbacks); + SetProtoMethod(isolate, t, "enableTrace", EnableTrace); + SetProtoMethod(isolate, t, "getServername", GetServername); + SetProtoMethod(isolate, t, "loadSession", LoadSession); + SetProtoMethod(isolate, t, "newSessionDone", NewSessionDone); + SetProtoMethod(isolate, t, "receive", Receive); + SetProtoMethod(isolate, t, "renegotiate", Renegotiate); + SetProtoMethod(isolate, t, "requestOCSP", RequestOCSP); + SetProtoMethod(isolate, t, "setALPNProtocols", SetALPNProtocols); + SetProtoMethod(isolate, t, "setOCSPResponse", SetOCSPResponse); + SetProtoMethod(isolate, t, "setServername", SetServername); + SetProtoMethod(isolate, t, "setSession", SetSession); + SetProtoMethod(isolate, t, "setVerifyMode", SetVerifyMode); + SetProtoMethod(isolate, t, "start", Start); + + SetProtoMethodNoSideEffect( + isolate, t, "exportKeyingMaterial", ExportKeyingMaterial); + SetProtoMethodNoSideEffect(isolate, t, "isSessionReused", IsSessionReused); + SetProtoMethodNoSideEffect( + isolate, t, "getALPNNegotiatedProtocol", GetALPNNegotiatedProto); + SetProtoMethodNoSideEffect(isolate, t, "getCertificate", GetCertificate); + SetProtoMethodNoSideEffect( + isolate, t, "getX509Certificate", GetX509Certificate); + SetProtoMethodNoSideEffect(isolate, t, "getCipher", GetCipher); + SetProtoMethodNoSideEffect( + isolate, t, "getEphemeralKeyInfo", GetEphemeralKeyInfo); + SetProtoMethodNoSideEffect(isolate, t, "getFinished", GetFinished); + SetProtoMethodNoSideEffect( + isolate, t, "getPeerCertificate", GetPeerCertificate); + SetProtoMethodNoSideEffect( + isolate, t, "getPeerX509Certificate", GetPeerX509Certificate); + SetProtoMethodNoSideEffect(isolate, t, "getPeerFinished", GetPeerFinished); + SetProtoMethodNoSideEffect(isolate, t, "getProtocol", GetProtocol); + SetProtoMethodNoSideEffect(isolate, t, "getSession", GetSession); + SetProtoMethodNoSideEffect(isolate, t, "getSharedSigalgs", GetSharedSigalgs); + SetProtoMethodNoSideEffect(isolate, t, "getTLSTicket", GetTLSTicket); + SetProtoMethodNoSideEffect(isolate, t, "verifyError", VerifyError); #ifdef SSL_set_max_send_fragment - env->SetProtoMethod(t, "setMaxSendFragment", SetMaxSendFragment); + SetProtoMethod(isolate, t, "setMaxSendFragment", SetMaxSendFragment); #endif // SSL_set_max_send_fragment #ifndef OPENSSL_NO_PSK - env->SetProtoMethod(t, "enablePskCallback", EnablePskCallback); - env->SetProtoMethod(t, "setPskIdentityHint", SetPskIdentityHint); + SetProtoMethod(isolate, t, "enablePskCallback", EnablePskCallback); + SetProtoMethod(isolate, t, "setPskIdentityHint", SetPskIdentityHint); #endif // !OPENSSL_NO_PSK StreamBase::AddMethods(env, t); diff --git a/src/crypto/crypto_util.cc b/src/crypto/crypto_util.cc index 7da959b45d4..5cbf553e46e 100644 --- a/src/crypto/crypto_util.cc +++ b/src/crypto/crypto_util.cc @@ -711,19 +711,20 @@ void SecureHeapUsed(const FunctionCallbackInfo<Value>& args) { namespace Util { void Initialize(Environment* env, Local<Object> target) { + Local<Context> context = env->context(); #ifndef OPENSSL_NO_ENGINE - env->SetMethod(target, "setEngine", SetEngine); + SetMethod(context, target, "setEngine", SetEngine); #endif // !OPENSSL_NO_ENGINE - env->SetMethodNoSideEffect(target, "getFipsCrypto", GetFipsCrypto); - env->SetMethod(target, "setFipsCrypto", SetFipsCrypto); - env->SetMethodNoSideEffect(target, "testFipsCrypto", TestFipsCrypto); + SetMethodNoSideEffect(context, target, "getFipsCrypto", GetFipsCrypto); + SetMethod(context, target, "setFipsCrypto", SetFipsCrypto); + SetMethodNoSideEffect(context, target, "testFipsCrypto", TestFipsCrypto); NODE_DEFINE_CONSTANT(target, kCryptoJobAsync); NODE_DEFINE_CONSTANT(target, kCryptoJobSync); - env->SetMethod(target, "secureBuffer", SecureBuffer); - env->SetMethod(target, "secureHeapUsed", SecureHeapUsed); + SetMethod(context, target, "secureBuffer", SecureBuffer); + SetMethod(context, target, "secureHeapUsed", SecureHeapUsed); } void RegisterExternalReferences(ExternalReferenceRegistry* registry) { #ifndef OPENSSL_NO_ENGINE diff --git a/src/crypto/crypto_util.h b/src/crypto/crypto_util.h index 9e33b3777b0..69ada7995bd 100644 --- a/src/crypto/crypto_util.h +++ b/src/crypto/crypto_util.h @@ -443,12 +443,15 @@ class CryptoJob : public AsyncWrap, public ThreadPoolWork { v8::FunctionCallback new_fn, Environment* env, v8::Local<v8::Object> target) { - v8::Local<v8::FunctionTemplate> job = env->NewFunctionTemplate(new_fn); + v8::Isolate* isolate = env->isolate(); + v8::HandleScope scope(isolate); + v8::Local<v8::Context> context = env->context(); + v8::Local<v8::FunctionTemplate> job = NewFunctionTemplate(isolate, new_fn); job->Inherit(AsyncWrap::GetConstructorTemplate(env)); job->InstanceTemplate()->SetInternalFieldCount( AsyncWrap::kInternalFieldCount); - env->SetProtoMethod(job, "run", Run); - env->SetConstructorFunction(target, CryptoJobTraits::JobName, job); + SetProtoMethod(isolate, job, "run", Run); + SetConstructorFunction(context, target, CryptoJobTraits::JobName, job); } static void RegisterExternalReferences(v8::FunctionCallback new_fn, diff --git a/src/crypto/crypto_x509.cc b/src/crypto/crypto_x509.cc index a301a139215..3c30749c394 100644 --- a/src/crypto/crypto_x509.cc +++ b/src/crypto/crypto_x509.cc @@ -21,6 +21,7 @@ using v8::EscapableHandleScope; using v8::Function; using v8::FunctionCallbackInfo; using v8::FunctionTemplate; +using v8::Isolate; using v8::Local; using v8::MaybeLocal; using v8::Object; @@ -54,35 +55,36 @@ Local<FunctionTemplate> X509Certificate::GetConstructorTemplate( Environment* env) { Local<FunctionTemplate> tmpl = env->x509_constructor_template(); if (tmpl.IsEmpty()) { - tmpl = FunctionTemplate::New(env->isolate()); + Isolate* isolate = env->isolate(); + tmpl = NewFunctionTemplate(isolate, nullptr); tmpl->InstanceTemplate()->SetInternalFieldCount( BaseObject::kInternalFieldCount); tmpl->Inherit(BaseObject::GetConstructorTemplate(env)); tmpl->SetClassName( FIXED_ONE_BYTE_STRING(env->isolate(), "X509Certificate")); - env->SetProtoMethod(tmpl, "subject", Subject); - env->SetProtoMethod(tmpl, "subjectAltName", SubjectAltName); - env->SetProtoMethod(tmpl, "infoAccess", InfoAccess); - env->SetProtoMethod(tmpl, "issuer", Issuer); - env->SetProtoMethod(tmpl, "validTo", ValidTo); - env->SetProtoMethod(tmpl, "validFrom", ValidFrom); - env->SetProtoMethod(tmpl, "fingerprint", Fingerprint); - env->SetProtoMethod(tmpl, "fingerprint256", Fingerprint256); - env->SetProtoMethod(tmpl, "fingerprint512", Fingerprint512); - env->SetProtoMethod(tmpl, "keyUsage", KeyUsage); - env->SetProtoMethod(tmpl, "serialNumber", SerialNumber); - env->SetProtoMethod(tmpl, "pem", Pem); - env->SetProtoMethod(tmpl, "raw", Raw); - env->SetProtoMethod(tmpl, "publicKey", PublicKey); - env->SetProtoMethod(tmpl, "checkCA", CheckCA); - env->SetProtoMethod(tmpl, "checkHost", CheckHost); - env->SetProtoMethod(tmpl, "checkEmail", CheckEmail); - env->SetProtoMethod(tmpl, "checkIP", CheckIP); - env->SetProtoMethod(tmpl, "checkIssued", CheckIssued); - env->SetProtoMethod(tmpl, "checkPrivateKey", CheckPrivateKey); - env->SetProtoMethod(tmpl, "verify", Verify); - env->SetProtoMethod(tmpl, "toLegacy", ToLegacy); - env->SetProtoMethod(tmpl, "getIssuerCert", GetIssuerCert); + SetProtoMethod(isolate, tmpl, "subject", Subject); + SetProtoMethod(isolate, tmpl, "subjectAltName", SubjectAltName); + SetProtoMethod(isolate, tmpl, "infoAccess", InfoAccess); + SetProtoMethod(isolate, tmpl, "issuer", Issuer); + SetProtoMethod(isolate, tmpl, "validTo", ValidTo); + SetProtoMethod(isolate, tmpl, "validFrom", ValidFrom); + SetProtoMethod(isolate, tmpl, "fingerprint", Fingerprint); + SetProtoMethod(isolate, tmpl, "fingerprint256", Fingerprint256); + SetProtoMethod(isolate, tmpl, "fingerprint512", Fingerprint512); + SetProtoMethod(isolate, tmpl, "keyUsage", KeyUsage); + SetProtoMethod(isolate, tmpl, "serialNumber", SerialNumber); + SetProtoMethod(isolate, tmpl, "pem", Pem); + SetProtoMethod(isolate, tmpl, "raw", Raw); + SetProtoMethod(isolate, tmpl, "publicKey", PublicKey); + SetProtoMethod(isolate, tmpl, "checkCA", CheckCA); + SetProtoMethod(isolate, tmpl, "checkHost", CheckHost); + SetProtoMethod(isolate, tmpl, "checkEmail", CheckEmail); + SetProtoMethod(isolate, tmpl, "checkIP", CheckIP); + SetProtoMethod(isolate, tmpl, "checkIssued", CheckIssued); + SetProtoMethod(isolate, tmpl, "checkPrivateKey", CheckPrivateKey); + SetProtoMethod(isolate, tmpl, "verify", Verify); + SetProtoMethod(isolate, tmpl, "toLegacy", ToLegacy); + SetProtoMethod(isolate, tmpl, "getIssuerCert", GetIssuerCert); env->set_x509_constructor_template(tmpl); } return tmpl; @@ -543,7 +545,7 @@ std::unique_ptr<worker::TransferData> X509Certificate::CloneForMessaging() void X509Certificate::Initialize(Environment* env, Local<Object> target) { - env->SetMethod(target, "parseX509", X509Certificate::Parse); + SetMethod(env->context(), target, "parseX509", X509Certificate::Parse); NODE_DEFINE_CONSTANT(target, X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT); NODE_DEFINE_CONSTANT(target, X509_CHECK_FLAG_NEVER_CHECK_SUBJECT); diff --git a/src/env.cc b/src/env.cc index be3327ec8d9..062a9d8e984 100644 --- a/src/env.cc +++ b/src/env.cc @@ -580,147 +580,6 @@ std::unique_ptr<v8::BackingStore> Environment::release_managed_buffer( return bs; } -Local<v8::FunctionTemplate> Environment::NewFunctionTemplate( - v8::FunctionCallback callback, - Local<v8::Signature> signature, - v8::ConstructorBehavior behavior, - v8::SideEffectType side_effect_type, - const v8::CFunction* c_function) { - return v8::FunctionTemplate::New(isolate(), - callback, - Local<v8::Value>(), - signature, - 0, - behavior, - side_effect_type, - c_function); -} - -void Environment::SetMethod(Local<v8::Object> that, - const char* name, - v8::FunctionCallback callback) { - Local<v8::Context> context = isolate()->GetCurrentContext(); - Local<v8::Function> function = - NewFunctionTemplate(callback, - Local<v8::Signature>(), - v8::ConstructorBehavior::kThrow, - v8::SideEffectType::kHasSideEffect) - ->GetFunction(context) - .ToLocalChecked(); - // kInternalized strings are created in the old space. - const v8::NewStringType type = v8::NewStringType::kInternalized; - Local<v8::String> name_string = - v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked(); - that->Set(context, name_string, function).Check(); - function->SetName(name_string); // NODE_SET_METHOD() compatibility. -} - -void Environment::SetFastMethod(Local<v8::Object> that, - const char* name, - v8::FunctionCallback slow_callback, - const v8::CFunction* c_function) { - Local<v8::Context> context = isolate()->GetCurrentContext(); - Local<v8::Function> function = - NewFunctionTemplate(slow_callback, - Local<v8::Signature>(), - v8::ConstructorBehavior::kThrow, - v8::SideEffectType::kHasNoSideEffect, - c_function) - ->GetFunction(context) - .ToLocalChecked(); - const v8::NewStringType type = v8::NewStringType::kInternalized; - Local<v8::String> name_string = - v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked(); - that->Set(context, name_string, function).Check(); -} - -void Environment::SetMethodNoSideEffect(Local<v8::Object> that, - const char* name, - v8::FunctionCallback callback) { - Local<v8::Context> context = isolate()->GetCurrentContext(); - Local<v8::Function> function = - NewFunctionTemplate(callback, - Local<v8::Signature>(), - v8::ConstructorBehavior::kThrow, - v8::SideEffectType::kHasNoSideEffect) - ->GetFunction(context) - .ToLocalChecked(); - // kInternalized strings are created in the old space. - const v8::NewStringType type = v8::NewStringType::kInternalized; - Local<v8::String> name_string = - v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked(); - that->Set(context, name_string, function).Check(); - function->SetName(name_string); // NODE_SET_METHOD() compatibility. -} - -void Environment::SetProtoMethod(Local<v8::FunctionTemplate> that, - const char* name, - v8::FunctionCallback callback) { - Local<v8::Signature> signature = v8::Signature::New(isolate(), that); - Local<v8::FunctionTemplate> t = - NewFunctionTemplate(callback, - signature, - v8::ConstructorBehavior::kThrow, - v8::SideEffectType::kHasSideEffect); - // kInternalized strings are created in the old space. - const v8::NewStringType type = v8::NewStringType::kInternalized; - Local<v8::String> name_string = - v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked(); - that->PrototypeTemplate()->Set(name_string, t); - t->SetClassName(name_string); // NODE_SET_PROTOTYPE_METHOD() compatibility. -} - -void Environment::SetProtoMethodNoSideEffect(Local<v8::FunctionTemplate> that, - const char* name, - v8::FunctionCallback callback) { - Local<v8::Signature> signature = v8::Signature::New(isolate(), that); - Local<v8::FunctionTemplate> t = - NewFunctionTemplate(callback, - signature, - v8::ConstructorBehavior::kThrow, - v8::SideEffectType::kHasNoSideEffect); - // kInternalized strings are created in the old space. - const v8::NewStringType type = v8::NewStringType::kInternalized; - Local<v8::String> name_string = - v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked(); - that->PrototypeTemplate()->Set(name_string, t); - t->SetClassName(name_string); // NODE_SET_PROTOTYPE_METHOD() compatibility. -} - -void Environment::SetInstanceMethod(Local<v8::FunctionTemplate> that, - const char* name, - v8::FunctionCallback callback) { - Local<v8::Signature> signature = v8::Signature::New(isolate(), that); - Local<v8::FunctionTemplate> t = - NewFunctionTemplate(callback, - signature, - v8::ConstructorBehavior::kThrow, - v8::SideEffectType::kHasSideEffect); - // kInternalized strings are created in the old space. - const v8::NewStringType type = v8::NewStringType::kInternalized; - Local<v8::String> name_string = - v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked(); - that->InstanceTemplate()->Set(name_string, t); - t->SetClassName(name_string); -} - -void Environment::SetConstructorFunction(Local<v8::Object> that, - const char* name, - Local<v8::FunctionTemplate> tmpl, - SetConstructorFunctionFlag flag) { - SetConstructorFunction(that, OneByteString(isolate(), name), tmpl, flag); -} - -void Environment::SetConstructorFunction(Local<v8::Object> that, - Local<v8::String> name, - Local<v8::FunctionTemplate> tmpl, - SetConstructorFunctionFlag flag) { - if (LIKELY(flag == SetConstructorFunctionFlag::SET_CLASS_NAME)) - tmpl->SetClassName(name); - that->Set(context(), name, tmpl->GetFunction(context()).ToLocalChecked()) - .Check(); -} - void Environment::CreateProperties() { HandleScope handle_scope(isolate_); Local<Context> ctx = context(); @@ -2222,8 +2081,8 @@ void BaseObject::LazilyInitializedJSTemplateConstructor( Local<FunctionTemplate> BaseObject::MakeLazilyInitializedJSTemplate( Environment* env) { - Local<FunctionTemplate> t = - env->NewFunctionTemplate(LazilyInitializedJSTemplateConstructor); + Local<FunctionTemplate> t = NewFunctionTemplate( + env->isolate(), LazilyInitializedJSTemplateConstructor); t->Inherit(BaseObject::GetConstructorTemplate(env)); t->InstanceTemplate()->SetInternalFieldCount(BaseObject::kInternalFieldCount); return t; @@ -2282,7 +2141,7 @@ bool BaseObject::IsRootNode() const { Local<FunctionTemplate> BaseObject::GetConstructorTemplate(Environment* env) { Local<FunctionTemplate> tmpl = env->base_object_ctor_template(); if (tmpl.IsEmpty()) { - tmpl = env->NewFunctionTemplate(nullptr); + tmpl = NewFunctionTemplate(env->isolate(), nullptr); tmpl->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "BaseObject")); env->set_base_object_ctor_template(tmpl); } diff --git a/src/env.h b/src/env.h index 84e477a7b7e..fd10025224b 100644 --- a/src/env.h +++ b/src/env.h @@ -1292,56 +1292,6 @@ class Environment : public MemoryRetainer { const char* path = nullptr, const char* dest = nullptr); - v8::Local<v8::FunctionTemplate> NewFunctionTemplate( - v8::FunctionCallback callback, - v8::Local<v8::Signature> signature = v8::Local<v8::Signature>(), - v8::ConstructorBehavior behavior = v8::ConstructorBehavior::kAllow, - v8::SideEffectType side_effect = v8::SideEffectType::kHasSideEffect, - const v8::CFunction* c_function = nullptr); - - // Convenience methods for NewFunctionTemplate(). - void SetMethod(v8::Local<v8::Object> that, - const char* name, - v8::FunctionCallback callback); - - void SetFastMethod(v8::Local<v8::Object> that, - const char* name, - v8::FunctionCallback slow_callback, - const v8::CFunction* c_function); - - void SetProtoMethod(v8::Local<v8::FunctionTemplate> that, - const char* name, - v8::FunctionCallback callback); - - void SetInstanceMethod(v8::Local<v8::FunctionTemplate> that, - const char* name, - v8::FunctionCallback callback); - - // Safe variants denote the function has no side effects. - void SetMethodNoSideEffect(v8::Local<v8::Object> that, - const char* name, - v8::FunctionCallback callback); - void SetProtoMethodNoSideEffect(v8::Local<v8::FunctionTemplate> that, - const char* name, - v8::FunctionCallback callback); - - enum class SetConstructorFunctionFlag { - NONE, - SET_CLASS_NAME, - }; - - void SetConstructorFunction(v8::Local<v8::Object> that, - const char* name, - v8::Local<v8::FunctionTemplate> tmpl, - SetConstructorFunctionFlag flag = - SetConstructorFunctionFlag::SET_CLASS_NAME); - - void SetConstructorFunction(v8::Local<v8::Object> that, - v8::Local<v8::String> name, - v8::Local<v8::FunctionTemplate> tmpl, - SetConstructorFunctionFlag flag = - SetConstructorFunctionFlag::SET_CLASS_NAME); - void AtExit(void (*cb)(void* arg), void* arg); void RunAtExitCallbacks(); diff --git a/src/fs_event_wrap.cc b/src/fs_event_wrap.cc index f13d22535c1..7b4a3278028 100644 --- a/src/fs_event_wrap.cc +++ b/src/fs_event_wrap.cc @@ -35,6 +35,7 @@ using v8::FunctionCallbackInfo; using v8::FunctionTemplate; using v8::HandleScope; using v8::Integer; +using v8::Isolate; using v8::Local; using v8::MaybeLocal; using v8::Object; @@ -95,13 +96,14 @@ void FSEventWrap::Initialize(Local<Object> target, Local<Context> context, void* priv) { Environment* env = Environment::GetCurrent(context); + Isolate* isolate = env->isolate(); - Local<FunctionTemplate> t = env->NewFunctionTemplate(New); + Local<FunctionTemplate> t = NewFunctionTemplate(isolate, New); t->InstanceTemplate()->SetInternalFieldCount( FSEventWrap::kInternalFieldCount); t->Inherit(HandleWrap::GetConstructorTemplate(env)); - env->SetProtoMethod(t, "start", Start); + SetProtoMethod(isolate, t, "start", Start); Local<FunctionTemplate> get_initialized_templ = FunctionTemplate::New(env->isolate(), @@ -115,7 +117,7 @@ void FSEventWrap::Initialize(Local<Object> target, Local<FunctionTemplate>(), static_cast<PropertyAttribute>(ReadOnly | DontDelete | DontEnum)); - env->SetConstructorFunction(target, "FSEvent", t); + SetConstructorFunction(context, target, "FSEvent", t); } void FSEventWrap::RegisterExternalReferences( diff --git a/src/handle_wrap.cc b/src/handle_wrap.cc index caad0e05546..4ea6a67d57f 100644 --- a/src/handle_wrap.cc +++ b/src/handle_wrap.cc @@ -31,6 +31,7 @@ using v8::Context; using v8::FunctionCallbackInfo; using v8::FunctionTemplate; using v8::HandleScope; +using v8::Isolate; using v8::Local; using v8::Object; using v8::Value; @@ -157,13 +158,14 @@ void HandleWrap::OnClose(uv_handle_t* handle) { Local<FunctionTemplate> HandleWrap::GetConstructorTemplate(Environment* env) { Local<FunctionTemplate> tmpl = env->handle_wrap_ctor_template(); if (tmpl.IsEmpty()) { - tmpl = env->NewFunctionTemplate(nullptr); + Isolate* isolate = env->isolate(); + tmpl = NewFunctionTemplate(isolate, nullptr); tmpl->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "HandleWrap")); tmpl->Inherit(AsyncWrap::GetConstructorTemplate(env)); - env->SetProtoMethod(tmpl, "close", HandleWrap::Close); - env->SetProtoMethodNoSideEffect(tmpl, "hasRef", HandleWrap::HasRef); - env->SetProtoMethod(tmpl, "ref", HandleWrap::Ref); - env->SetProtoMethod(tmpl, "unref", HandleWrap::Unref); + SetProtoMethod(isolate, tmpl, "close", HandleWrap::Close); + SetProtoMethodNoSideEffect(isolate, tmpl, "hasRef", HandleWrap::HasRef); + SetProtoMethod(isolate, tmpl, "ref", HandleWrap::Ref); + SetProtoMethod(isolate, tmpl, "unref", HandleWrap::Unref); env->set_handle_wrap_ctor_template(tmpl); } return tmpl; diff --git a/src/heap_utils.cc b/src/heap_utils.cc index 467e7ee5f82..8556b58f151 100644 --- a/src/heap_utils.cc +++ b/src/heap_utils.cc @@ -448,11 +448,10 @@ void Initialize(Local<Object> target, Local<Value> unused, Local<Context> context, void* priv) { - Environment* env = Environment::GetCurrent(context); - - env->SetMethod(target, "buildEmbedderGraph", BuildEmbedderGraph); - env->SetMethod(target, "triggerHeapSnapshot", TriggerHeapSnapshot); - env->SetMethod(target, "createHeapSnapshotStream", CreateHeapSnapshotStream); + SetMethod(context, target, "buildEmbedderGraph", BuildEmbedderGraph); + SetMethod(context, target, "triggerHeapSnapshot", TriggerHeapSnapshot); + SetMethod( + context, target, "createHeapSnapshotStream", CreateHeapSnapshotStream); } void RegisterExternalReferences(ExternalReferenceRegistry* registry) { diff --git a/src/histogram.cc b/src/histogram.cc index 63fa52a57df..3a3228ddc9e 100644 --- a/src/histogram.cc +++ b/src/histogram.cc @@ -11,6 +11,7 @@ using v8::BigInt; using v8::FunctionCallbackInfo; using v8::FunctionTemplate; using v8::Integer; +using v8::Isolate; using v8::Local; using v8::Map; using v8::Number; @@ -280,7 +281,8 @@ Local<FunctionTemplate> HistogramBase::GetConstructorTemplate( Environment* env) { Local<FunctionTemplate> tmpl = env->histogram_ctor_template(); if (tmpl.IsEmpty()) { - tmpl = env->NewFunctionTemplate(New); + Isolate* isolate = env->isolate(); + tmpl = NewFunctionTemplate(isolate, New); Local<String> classname = FIXED_ONE_BYTE_STRING(env->isolate(), "Histogram"); tmpl->SetClassName(classname); @@ -288,26 +290,27 @@ Local<FunctionTemplate> HistogramBase::GetConstructorTemplate( tmpl->InstanceTemplate()->SetInternalFieldCount( HistogramBase::kInternalFieldCount); - env->SetProtoMethodNoSideEffect(tmpl, "count", GetCount); - env->SetProtoMethodNoSideEffect(tmpl, "countBigInt", GetCountBigInt); - env->SetProtoMethodNoSideEffect(tmpl, "exceeds", GetExceeds); - env->SetProtoMethodNoSideEffect(tmpl, "exceedsBigInt", GetExceedsBigInt); - env->SetProtoMethodNoSideEffect(tmpl, "min", GetMin); - env->SetProtoMethodNoSideEffect(tmpl, "minBigInt", GetMinBigInt); - env->SetProtoMethodNoSideEffect(tmpl, "max", GetMax); - env->SetProtoMethodNoSideEffect(tmpl, "maxBigInt", GetMaxBigInt); - env->SetProtoMethodNoSideEffect(tmpl, "mean", GetMean); - env->SetProtoMethodNoSideEffect(tmpl, "stddev", GetStddev); - env->SetProtoMethodNoSideEffect(tmpl, "percentile", GetPercentile); - env->SetProtoMethodNoSideEffect(tmpl, "percentileBigInt", - GetPercentileBigInt); - env->SetProtoMethodNoSideEffect(tmpl, "percentiles", GetPercentiles); - env->SetProtoMethodNoSideEffect(tmpl, "percentilesBigInt", - GetPercentilesBigInt); - env->SetProtoMethod(tmpl, "reset", DoReset); - env->SetProtoMethod(tmpl, "record", Record); - env->SetProtoMethod(tmpl, "recordDelta", RecordDelta); - env->SetProtoMethod(tmpl, "add", Add); + SetProtoMethodNoSideEffect(isolate, tmpl, "count", GetCount); + SetProtoMethodNoSideEffect(isolate, tmpl, "countBigInt", GetCountBigInt); + SetProtoMethodNoSideEffect(isolate, tmpl, "exceeds", GetExceeds); + SetProtoMethodNoSideEffect( + isolate, tmpl, "exceedsBigInt", GetExceedsBigInt); + SetProtoMethodNoSideEffect(isolate, tmpl, "min", GetMin); + SetProtoMethodNoSideEffect(isolate, tmpl, "minBigInt", GetMinBigInt); + SetProtoMethodNoSideEffect(isolate, tmpl, "max", GetMax); + SetProtoMethodNoSideEffect(isolate, tmpl, "maxBigInt", GetMaxBigInt); + SetProtoMethodNoSideEffect(isolate, tmpl, "mean", GetMean); + SetProtoMethodNoSideEffect(isolate, tmpl, "stddev", GetStddev); + SetProtoMethodNoSideEffect(isolate, tmpl, "percentile", GetPercentile); + SetProtoMethodNoSideEffect( + isolate, tmpl, "percentileBigInt", GetPercentileBigInt); + SetProtoMethodNoSideEffect(isolate, tmpl, "percentiles", GetPercentiles); + SetProtoMethodNoSideEffect( + isolate, tmpl, "percentilesBigInt", GetPercentilesBigInt); + SetProtoMethod(isolate, tmpl, "reset", DoReset); + SetProtoMethod(isolate, tmpl, "record", Record); + SetProtoMethod(isolate, tmpl, "recordDelta", RecordDelta); + SetProtoMethod(isolate, tmpl, "add", Add); env->set_histogram_ctor_template(tmpl); } return tmpl; @@ -337,7 +340,8 @@ void HistogramBase::RegisterExternalReferences( } void HistogramBase::Initialize(Environment* env, Local<Object> target) { - env->SetConstructorFunction(target, "Histogram", GetConstructorTemplate(env)); + SetConstructorFunction( + env->context(), target, "Histogram", GetConstructorTemplate(env)); } BaseObjectPtr<BaseObject> HistogramBase::HistogramTransferData::Deserialize( @@ -360,29 +364,31 @@ Local<FunctionTemplate> IntervalHistogram::GetConstructorTemplate( Environment* env) { Local<FunctionTemplate> tmpl = env->intervalhistogram_constructor_template(); if (tmpl.IsEmpty()) { - tmpl = FunctionTemplate::New(env->isolate()); + Isolate* isolate = env->isolate(); + tmpl = NewFunctionTemplate(isolate, nullptr); tmpl->Inherit(HandleWrap::GetConstructorTemplate(env)); tmpl->InstanceTemplate()->SetInternalFieldCount( HistogramBase::kInternalFieldCount); - env->SetProtoMethodNoSideEffect(tmpl, "count", GetCount); - env->SetProtoMethodNoSideEffect(tmpl, "countBigInt", GetCountBigInt); - env->SetProtoMethodNoSideEffect(tmpl, "exceeds", GetExceeds); - env->SetProtoMethodNoSideEffect(tmpl, "exceedsBigInt", GetExceedsBigInt); - env->SetProtoMethodNoSideEffect(tmpl, "min", GetMin); - env->SetProtoMethodNoSideEffect(tmpl, "minBigInt", GetMinBigInt); - env->SetProtoMethodNoSideEffect(tmpl, "max", GetMax); - env->SetProtoMethodNoSideEffect(tmpl, "maxBigInt", GetMaxBigInt); - env->SetProtoMethodNoSideEffect(tmpl, "mean", GetMean); - env->SetProtoMethodNoSideEffect(tmpl, "stddev", GetStddev); - env->SetProtoMethodNoSideEffect(tmpl, "percentile", GetPercentile); - env->SetProtoMethodNoSideEffect(tmpl, "percentileBigInt", - GetPercentileBigInt); - env->SetProtoMethodNoSideEffect(tmpl, "percentiles", GetPercentiles); - env->SetProtoMethodNoSideEffect(tmpl, "percentilesBigInt", - GetPercentilesBigInt); - env->SetProtoMethod(tmpl, "reset", DoReset); - env->SetProtoMethod(tmpl, "start", Start); - env->SetProtoMethod(tmpl, "stop", Stop); + SetProtoMethodNoSideEffect(isolate, tmpl, "count", GetCount); + SetProtoMethodNoSideEffect(isolate, tmpl, "countBigInt", GetCountBigInt); + SetProtoMethodNoSideEffect(isolate, tmpl, "exceeds", GetExceeds); + SetProtoMethodNoSideEffect( + isolate, tmpl, "exceedsBigInt", GetExceedsBigInt); + SetProtoMethodNoSideEffect(isolate, tmpl, "min", GetMin); + SetProtoMethodNoSideEffect(isolate, tmpl, "minBigInt", GetMinBigInt); + SetProtoMethodNoSideEffect(isolate, tmpl, "max", GetMax); + SetProtoMethodNoSideEffect(isolate, tmpl, "maxBigInt", GetMaxBigInt); + SetProtoMethodNoSideEffect(isolate, tmpl, "mean", GetMean); + SetProtoMethodNoSideEffect(isolate, tmpl, "stddev", GetStddev); + SetProtoMethodNoSideEffect(isolate, tmpl, "percentile", GetPercentile); + SetProtoMethodNoSideEffect( + isolate, tmpl, "percentileBigInt", GetPercentileBigInt); + SetProtoMethodNoSideEffect(isolate, tmpl, "percentiles", GetPercentiles); + SetProtoMethodNoSideEffect( + isolate, tmpl, "percentilesBigInt", GetPercentilesBigInt); + SetProtoMethod(isolate, tmpl, "reset", DoReset); + SetProtoMethod(isolate, tmpl, "start", Start); + SetProtoMethod(isolate, tmpl, "stop", Stop); env->set_intervalhistogram_constructor_template(tmpl); } return tmpl; diff --git a/src/inspector_js_api.cc b/src/inspector_js_api.cc index 298066dfc75..dd05a5b9c3f 100644 --- a/src/inspector_js_api.cc +++ b/src/inspector_js_api.cc @@ -102,17 +102,17 @@ class JSBindingsConnection : public AsyncWrap { } static void Bind(Environment* env, Local<Object> target) { + Isolate* isolate = env->isolate(); Local<FunctionTemplate> tmpl = - env->NewFunctionTemplate(JSBindingsConnection::New); + NewFunctionTemplate(isolate, JSBindingsConnection::New); tmpl->InstanceTemplate()->SetInternalFieldCount( JSBindingsConnection::kInternalFieldCount); tmpl->Inherit(AsyncWrap::GetConstructorTemplate(env)); - env->SetProtoMethod(tmpl, "dispatch", JSBindingsConnection::Dispatch); - env->SetProtoMethod(tmpl, "disconnect", JSBindingsConnection::Disconnect); - env->SetConstructorFunction( - target, - ConnectionType::GetClassName(env), - tmpl); + SetProtoMethod(isolate, tmpl, "dispatch", JSBindingsConnection::Dispatch); + SetProtoMethod( + isolate, tmpl, "disconnect", JSBindingsConnection::Disconnect); + SetConstructorFunction( + env->context(), target, ConnectionType::GetClassName(env), tmpl); } static void New(const FunctionCallbackInfo<Value>& info) { @@ -314,37 +314,47 @@ void Url(const FunctionCallbackInfo<Value>& args) { void Initialize(Local<Object> target, Local<Value> unused, Local<Context> context, void* priv) { Environment* env = Environment::GetCurrent(context); + Isolate* isolate = env->isolate(); v8::Local<v8::Function> consoleCallFunc = - env->NewFunctionTemplate(InspectorConsoleCall, v8::Local<v8::Signature>(), - v8::ConstructorBehavior::kThrow, - v8::SideEffectType::kHasSideEffect) + NewFunctionTemplate(isolate, + InspectorConsoleCall, + v8::Local<v8::Signature>(), + v8::ConstructorBehavior::kThrow, + v8::SideEffectType::kHasSideEffect) ->GetFunction(context) .ToLocalChecked(); - auto name_string = FIXED_ONE_BYTE_STRING(env->isolate(), "consoleCall"); + auto name_string = FIXED_ONE_BYTE_STRING(isolate, "consoleCall"); target->Set(context, name_string, consoleCallFunc).Check(); consoleCallFunc->SetName(name_string); - env->SetMethod( - target, "setConsoleExtensionInstaller", SetConsoleExtensionInstaller); - env->SetMethod(target, "callAndPauseOnStart", CallAndPauseOnStart); - env->SetMethod(target, "open", Open); - env->SetMethodNoSideEffect(target, "url", Url); - env->SetMethod(target, "waitForDebugger", WaitForDebugger); - - env->SetMethod(target, "asyncTaskScheduled", AsyncTaskScheduledWrapper); - env->SetMethod(target, "asyncTaskCanceled", - InvokeAsyncTaskFnWithId<&Agent::AsyncTaskCanceled>); - env->SetMethod(target, "asyncTaskStarted", - InvokeAsyncTaskFnWithId<&Agent::AsyncTaskStarted>); - env->SetMethod(target, "asyncTaskFinished", - InvokeAsyncTaskFnWithId<&Agent::AsyncTaskFinished>); - - env->SetMethod(target, "registerAsyncHook", RegisterAsyncHookWrapper); - env->SetMethodNoSideEffect(target, "isEnabled", IsEnabled); - - Local<String> console_string = - FIXED_ONE_BYTE_STRING(env->isolate(), "console"); + SetMethod(context, + target, + "setConsoleExtensionInstaller", + SetConsoleExtensionInstaller); + SetMethod(context, target, "callAndPauseOnStart", CallAndPauseOnStart); + SetMethod(context, target, "open", Open); + SetMethodNoSideEffect(context, target, "url", Url); + SetMethod(context, target, "waitForDebugger", WaitForDebugger); + + SetMethod(context, target, "asyncTaskScheduled", AsyncTaskScheduledWrapper); + SetMethod(context, + target, + "asyncTaskCanceled", + InvokeAsyncTaskFnWithId<&Agent::AsyncTaskCanceled>); + SetMethod(context, + target, + "asyncTaskStarted", + InvokeAsyncTaskFnWithId<&Agent::AsyncTaskStarted>); + SetMethod(context, + target, + "asyncTaskFinished", + InvokeAsyncTaskFnWithId<&Agent::AsyncTaskFinished>); + + SetMethod(context, target, "registerAsyncHook", RegisterAsyncHookWrapper); + SetMethodNoSideEffect(context, target, "isEnabled", IsEnabled); + + Local<String> console_string = FIXED_ONE_BYTE_STRING(isolate, "console"); // Grab the console from the binding object and expose those to our binding // layer. diff --git a/src/inspector_profiler.cc b/src/inspector_profiler.cc index 332aa536364..538125f091a 100644 --- a/src/inspector_profiler.cc +++ b/src/inspector_profiler.cc @@ -507,11 +507,11 @@ static void Initialize(Local<Object> target, Local<Value> unused, Local<Context> context, void* priv) { - Environment* env = Environment::GetCurrent(context); - env->SetMethod(target, "setCoverageDirectory", SetCoverageDirectory); - env->SetMethod(target, "setSourceMapCacheGetter", SetSourceMapCacheGetter); - env->SetMethod(target, "takeCoverage", TakeCoverage); - env->SetMethod(target, "stopCoverage", StopCoverage); + SetMethod(context, target, "setCoverageDirectory", SetCoverageDirectory); + SetMethod( + context, target, "setSourceMapCacheGetter", SetSourceMapCacheGetter); + SetMethod(context, target, "takeCoverage", TakeCoverage); + SetMethod(context, target, "stopCoverage", StopCoverage); } void RegisterExternalReferences(ExternalReferenceRegistry* registry) { diff --git a/src/js_stream.cc b/src/js_stream.cc index 720008ecefc..5bf64a9e0a9 100644 --- a/src/js_stream.cc +++ b/src/js_stream.cc @@ -17,6 +17,7 @@ using v8::FunctionCallbackInfo; using v8::FunctionTemplate; using v8::HandleScope; using v8::Int32; +using v8::Isolate; using v8::Local; using v8::Object; using v8::Value; @@ -197,19 +198,20 @@ void JSStream::Initialize(Local<Object> target, Local<Context> context, void* priv) { Environment* env = Environment::GetCurrent(context); + Isolate* isolate = env->isolate(); - Local<FunctionTemplate> t = env->NewFunctionTemplate(New); + Local<FunctionTemplate> t = NewFunctionTemplate(isolate, New); t->InstanceTemplate() ->SetInternalFieldCount(StreamBase::kInternalFieldCount); t->Inherit(AsyncWrap::GetConstructorTemplate(env)); - env->SetProtoMethod(t, "finishWrite", Finish<WriteWrap>); - env->SetProtoMethod(t, "finishShutdown", Finish<ShutdownWrap>); - env->SetProtoMethod(t, "readBuffer", ReadBuffer); - env->SetProtoMethod(t, "emitEOF", EmitEOF); + SetProtoMethod(isolate, t, "finishWrite", Finish<WriteWrap>); + SetProtoMethod(isolate, t, "finishShutdown", Finish<ShutdownWrap>); + SetProtoMethod(isolate, t, "readBuffer", ReadBuffer); + SetProtoMethod(isolate, t, "emitEOF", EmitEOF); StreamBase::AddMethods(env, t); - env->SetConstructorFunction(target, "JSStream", t); + SetConstructorFunction(context, target, "JSStream", t); } } // namespace node diff --git a/src/js_udp_wrap.cc b/src/js_udp_wrap.cc index 3f02771ee1a..99362ccc609 100644 --- a/src/js_udp_wrap.cc +++ b/src/js_udp_wrap.cc @@ -17,6 +17,7 @@ using v8::FunctionCallbackInfo; using v8::FunctionTemplate; using v8::HandleScope; using v8::Int32; +using v8::Isolate; using v8::Local; using v8::Object; using v8::Value; @@ -198,18 +199,19 @@ void JSUDPWrap::Initialize(Local<Object> target, Local<Context> context, void* priv) { Environment* env = Environment::GetCurrent(context); + Isolate* isolate = env->isolate(); - Local<FunctionTemplate> t = env->NewFunctionTemplate(New); + Local<FunctionTemplate> t = NewFunctionTemplate(isolate, New); t->InstanceTemplate() ->SetInternalFieldCount(UDPWrapBase::kUDPWrapBaseField + 1); t->Inherit(AsyncWrap::GetConstructorTemplate(env)); UDPWrapBase::AddMethods(env, t); - env->SetProtoMethod(t, "emitReceived", EmitReceived); - env->SetProtoMethod(t, "onSendDone", OnSendDone); - env->SetProtoMethod(t, "onAfterBind", OnAfterBind); + SetProtoMethod(isolate, t, "emitReceived", EmitReceived); + SetProtoMethod(isolate, t, "onSendDone", OnSendDone); + SetProtoMethod(isolate, t, "onAfterBind", OnAfterBind); - env->SetConstructorFunction(target, "JSUDPWrap", t); + SetConstructorFunction(context, target, "JSUDPWrap", t); } diff --git a/src/module_wrap.cc b/src/module_wrap.cc index 50ce8d510cb..b445189d388 100644 --- a/src/module_wrap.cc +++ b/src/module_wrap.cc @@ -765,31 +765,37 @@ void ModuleWrap::Initialize(Local<Object> target, Local<Context> context, void* priv) { Environment* env = Environment::GetCurrent(context); + Isolate* isolate = env->isolate(); - Local<FunctionTemplate> tpl = env->NewFunctionTemplate(New); + Local<FunctionTemplate> tpl = NewFunctionTemplate(isolate, New); tpl->InstanceTemplate()->SetInternalFieldCount( ModuleWrap::kInternalFieldCount); tpl->Inherit(BaseObject::GetConstructorTemplate(env)); - env->SetProtoMethod(tpl, "link", Link); - env->SetProtoMethod(tpl, "instantiate", Instantiate); - env->SetProtoMethod(tpl, "evaluate", Evaluate); - env->SetProtoMethod(tpl, "setExport", SetSyntheticExport); - env->SetProtoMethodNoSideEffect(tpl, "createCachedData", CreateCachedData); - env->SetProtoMethodNoSideEffect(tpl, "getNamespace", GetNamespace); - env->SetProtoMethodNoSideEffect(tpl, "getStatus", GetStatus); - env->SetProtoMethodNoSideEffect(tpl, "getError", GetError); - env->SetProtoMethodNoSideEffect(tpl, "getStaticDependencySpecifiers", - GetStaticDependencySpecifiers); - - env->SetConstructorFunction(target, "ModuleWrap", tpl); - - env->SetMethod(target, - "setImportModuleDynamicallyCallback", - SetImportModuleDynamicallyCallback); - env->SetMethod(target, - "setInitializeImportMetaObjectCallback", - SetInitializeImportMetaObjectCallback); + SetProtoMethod(isolate, tpl, "link", Link); + SetProtoMethod(isolate, tpl, "instantiate", Instantiate); + SetProtoMethod(isolate, tpl, "evaluate", Evaluate); + SetProtoMethod(isolate, tpl, "setExport", SetSyntheticExport); + SetProtoMethodNoSideEffect( + isolate, tpl, "createCachedData", CreateCachedData); + SetProtoMethodNoSideEffect(isolate, tpl, "getNamespace", GetNamespace); + SetProtoMethodNoSideEffect(isolate, tpl, "getStatus", GetStatus); + SetProtoMethodNoSideEffect(isolate, tpl, "getError", GetError); + SetProtoMethodNoSideEffect(isolate, + tpl, + "getStaticDependencySpecifiers", + GetStaticDependencySpecifiers); + + SetConstructorFunction(context, target, "ModuleWrap", tpl); + + SetMethod(context, + target, + "setImportModuleDynamicallyCallback", + SetImportModuleDynamicallyCallback); + SetMethod(context, + target, + "setInitializeImportMetaObjectCallback", + SetInitializeImportMetaObjectCallback); #define V(name) \ target->Set(context, \ diff --git a/src/node.cc b/src/node.cc index 69a4904850c..c2df8975a28 100644 --- a/src/node.cc +++ b/src/node.cc @@ -301,10 +301,10 @@ MaybeLocal<Value> Environment::BootstrapInternalLoaders() { primordials_string()}; std::vector<Local<Value>> loaders_args = { process_object(), - NewFunctionTemplate(binding::GetLinkedBinding) + NewFunctionTemplate(isolate_, binding::GetLinkedBinding) ->GetFunction(context()) .ToLocalChecked(), - NewFunctionTemplate(binding::GetInternalBinding) + NewFunctionTemplate(isolate_, binding::GetInternalBinding) ->GetFunction(context()) .ToLocalChecked(), primordials()}; @@ -443,7 +443,7 @@ MaybeLocal<Value> StartExecution(Environment* env, const char* main_script_id) { env->native_module_require(), env->internal_binding_loader(), env->primordials(), - env->NewFunctionTemplate(MarkBootstrapComplete) + NewFunctionTemplate(env->isolate(), MarkBootstrapComplete) ->GetFunction(env->context()) .ToLocalChecked()}; diff --git a/src/node_blob.cc b/src/node_blob.cc index e1bf3be2b07..b319a74ebae 100644 --- a/src/node_blob.cc +++ b/src/node_blob.cc @@ -22,6 +22,7 @@ using v8::Function; using v8::FunctionCallbackInfo; using v8::FunctionTemplate; using v8::HandleScope; +using v8::Isolate; using v8::Local; using v8::MaybeLocal; using v8::Number; @@ -42,24 +43,25 @@ void Blob::Initialize( env->AddBindingData<BlobBindingData>(context, target); if (binding_data == nullptr) return; - env->SetMethod(target, "createBlob", New); - env->SetMethod(target, "storeDataObject", StoreDataObject); - env->SetMethod(target, "getDataObject", GetDataObject); - env->SetMethod(target, "revokeDataObject", RevokeDataObject); + SetMethod(context, target, "createBlob", New); + SetMethod(context, target, "storeDataObject", StoreDataObject); + SetMethod(context, target, "getDataObject", GetDataObject); + SetMethod(context, target, "revokeDataObject", RevokeDataObject); FixedSizeBlobCopyJob::Initialize(env, target); } Local<FunctionTemplate> Blob::GetConstructorTemplate(Environment* env) { Local<FunctionTemplate> tmpl = env->blob_constructor_template(); if (tmpl.IsEmpty()) { - tmpl = FunctionTemplate::New(env->isolate()); + Isolate* isolate = env->isolate(); + tmpl = NewFunctionTemplate(isolate, nullptr); tmpl->InstanceTemplate()->SetInternalFieldCount( BaseObject::kInternalFieldCount); tmpl->Inherit(BaseObject::GetConstructorTemplate(env)); tmpl->SetClassName( FIXED_ONE_BYTE_STRING(env->isolate(), "Blob")); - env->SetProtoMethod(tmpl, "toArrayBuffer", ToArrayBuffer); - env->SetProtoMethod(tmpl, "slice", ToSlice); + SetProtoMethod(isolate, tmpl, "toArrayBuffer", ToArrayBuffer); + SetProtoMethod(isolate, tmpl, "slice", ToSlice); env->set_blob_constructor_template(tmpl); } return tmpl; @@ -362,12 +364,13 @@ void FixedSizeBlobCopyJob::MemoryInfo(MemoryTracker* tracker) const { } void FixedSizeBlobCopyJob::Initialize(Environment* env, Local<Object> target) { - v8::Local<v8::FunctionTemplate> job = env->NewFunctionTemplate(New); + Isolate* isolate = env->isolate(); + v8::Local<v8::FunctionTemplate> job = NewFunctionTemplate(isolate, New); job->Inherit(AsyncWrap::GetConstructorTemplate(env)); job->InstanceTemplate()->SetInternalFieldCount( AsyncWrap::kInternalFieldCount); - env->SetProtoMethod(job, "run", Run); - env->SetConstructorFunction(target, "FixedSizeBlobCopyJob", job); + SetProtoMethod(isolate, job, "run", Run); + SetConstructorFunction(env->context(), target, "FixedSizeBlobCopyJob", job); } void FixedSizeBlobCopyJob::New(const FunctionCallbackInfo<Value>& args) { diff --git a/src/node_buffer.cc b/src/node_buffer.cc index aec97f15e2c..f8885ab3771 100644 --- a/src/node_buffer.cc +++ b/src/node_buffer.cc @@ -1275,54 +1275,60 @@ void Initialize(Local<Object> target, Local<Context> context, void* priv) { Environment* env = Environment::GetCurrent(context); + Isolate* isolate = env->isolate(); - env->SetMethod(target, "setBufferPrototype", SetBufferPrototype); - env->SetMethodNoSideEffect(target, "createFromString", CreateFromString); - - env->SetMethodNoSideEffect(target, "byteLengthUtf8", ByteLengthUtf8); - env->SetMethod(target, "copy", Copy); - env->SetMethodNoSideEffect(target, "compare", Compare); - env->SetMethodNoSideEffect(target, "compareOffset", CompareOffset); - env->SetMethod(target, "fill", Fill); - env->SetMethodNoSideEffect(target, "indexOfBuffer", IndexOfBuffer); - env->SetMethodNoSideEffect(target, "indexOfNumber", IndexOfNumber); - env->SetMethodNoSideEffect(target, "indexOfString", IndexOfString); - - env->SetMethod(target, "detachArrayBuffer", DetachArrayBuffer); - env->SetMethod(target, "copyArrayBuffer", CopyArrayBuffer); - - env->SetMethod(target, "swap16", Swap16); - env->SetMethod(target, "swap32", Swap32); - env->SetMethod(target, "swap64", Swap64); - - env->SetMethod(target, "encodeInto", EncodeInto); - env->SetMethodNoSideEffect(target, "encodeUtf8String", EncodeUtf8String); - - target->Set(env->context(), - FIXED_ONE_BYTE_STRING(env->isolate(), "kMaxLength"), - Number::New(env->isolate(), kMaxLength)).Check(); - - target->Set(env->context(), - FIXED_ONE_BYTE_STRING(env->isolate(), "kStringMaxLength"), - Integer::New(env->isolate(), String::kMaxLength)).Check(); - - env->SetMethodNoSideEffect(target, "asciiSlice", StringSlice<ASCII>); - env->SetMethodNoSideEffect(target, "base64Slice", StringSlice<BASE64>); - env->SetMethodNoSideEffect(target, "base64urlSlice", StringSlice<BASE64URL>); - env->SetMethodNoSideEffect(target, "latin1Slice", StringSlice<LATIN1>); - env->SetMethodNoSideEffect(target, "hexSlice", StringSlice<HEX>); - env->SetMethodNoSideEffect(target, "ucs2Slice", StringSlice<UCS2>); - env->SetMethodNoSideEffect(target, "utf8Slice", StringSlice<UTF8>); - - env->SetMethod(target, "asciiWrite", StringWrite<ASCII>); - env->SetMethod(target, "base64Write", StringWrite<BASE64>); - env->SetMethod(target, "base64urlWrite", StringWrite<BASE64URL>); - env->SetMethod(target, "latin1Write", StringWrite<LATIN1>); - env->SetMethod(target, "hexWrite", StringWrite<HEX>); - env->SetMethod(target, "ucs2Write", StringWrite<UCS2>); - env->SetMethod(target, "utf8Write", StringWrite<UTF8>); - - env->SetMethod(target, "getZeroFillToggle", GetZeroFillToggle); + SetMethod(context, target, "setBufferPrototype", SetBufferPrototype); + SetMethodNoSideEffect(context, target, "createFromString", CreateFromString); + + SetMethodNoSideEffect(context, target, "byteLengthUtf8", ByteLengthUtf8); + SetMethod(context, target, "copy", Copy); + SetMethodNoSideEffect(context, target, "compare", Compare); + SetMethodNoSideEffect(context, target, "compareOffset", CompareOffset); + SetMethod(context, target, "fill", Fill); + SetMethodNoSideEffect(context, target, "indexOfBuffer", IndexOfBuffer); + SetMethodNoSideEffect(context, target, "indexOfNumber", IndexOfNumber); + SetMethodNoSideEffect(context, target, "indexOfString", IndexOfString); + + SetMethod(context, target, "detachArrayBuffer", DetachArrayBuffer); + SetMethod(context, target, "copyArrayBuffer", CopyArrayBuffer); + + SetMethod(context, target, "swap16", Swap16); + SetMethod(context, target, "swap32", Swap32); + SetMethod(context, target, "swap64", Swap64); + + SetMethod(context, target, "encodeInto", EncodeInto); + SetMethodNoSideEffect(context, target, "encodeUtf8String", EncodeUtf8String); + + target + ->Set(context, + FIXED_ONE_BYTE_STRING(isolate, "kMaxLength"), + Number::New(isolate, kMaxLength)) + .Check(); + + target + ->Set(context, + FIXED_ONE_BYTE_STRING(isolate, "kStringMaxLength"), + Integer::New(isolate, String::kMaxLength)) + .Check(); + + SetMethodNoSideEffect(context, target, "asciiSlice", StringSlice<ASCII>); + SetMethodNoSideEffect(context, target, "base64Slice", StringSlice<BASE64>); + SetMethodNoSideEffect( + context, target, "base64urlSlice", StringSlice<BASE64URL>); + SetMethodNoSideEffect(context, target, "latin1Slice", StringSlice<LATIN1>); + SetMethodNoSideEffect(context, target, "hexSlice", StringSlice<HEX>); + SetMethodNoSideEffect(context, target, "ucs2Slice", StringSlice<UCS2>); + SetMethodNoSideEffect(context, target, "utf8Slice", StringSlice<UTF8>); + + SetMethod(context, target, "asciiWrite", StringWrite<ASCII>); + SetMethod(context, target, "base64Write", StringWrite<BASE64>); + SetMethod(context, target, "base64urlWrite", StringWrite<BASE64URL>); + SetMethod(context, target, "latin1Write", StringWrite<LATIN1>); + SetMethod(context, target, "hexWrite", StringWrite<HEX>); + SetMethod(context, target, "ucs2Write", StringWrite<UCS2>); + SetMethod(context, target, "utf8Write", StringWrite<UTF8>); + + SetMethod(context, target, "getZeroFillToggle", GetZeroFillToggle); } } // anonymous namespace diff --git a/src/node_contextify.cc b/src/node_contextify.cc index f383b6def93..95ba72c3db2 100644 --- a/src/node_contextify.cc +++ b/src/node_contextify.cc @@ -255,16 +255,19 @@ MaybeLocal<Context> ContextifyContext::CreateV8Context( void ContextifyContext::Init(Environment* env, Local<Object> target) { + Isolate* isolate = env->isolate(); + Local<Context> context = env->context(); + Local<FunctionTemplate> function_template = - FunctionTemplate::New(env->isolate()); + NewFunctionTemplate(isolate, nullptr); function_template->InstanceTemplate()->SetInternalFieldCount( ContextifyContext::kInternalFieldCount); env->set_script_data_constructor_function( function_template->GetFunction(env->context()).ToLocalChecked()); - env->SetMethod(target, "makeContext", MakeContext); - env->SetMethod(target, "isContext", IsContext); - env->SetMethod(target, "compileFunction", CompileFunction); + SetMethod(context, target, "makeContext", MakeContext); + SetMethod(context, target, "isContext", IsContext); + SetMethod(context, target, "compileFunction", CompileFunction); } void ContextifyContext::RegisterExternalReferences( @@ -657,16 +660,17 @@ void ContextifyContext::IndexedPropertyDeleterCallback( } void ContextifyScript::Init(Environment* env, Local<Object> target) { + Isolate* isolate = env->isolate(); HandleScope scope(env->isolate()); Local<String> class_name = FIXED_ONE_BYTE_STRING(env->isolate(), "ContextifyScript"); - Local<FunctionTemplate> script_tmpl = env->NewFunctionTemplate(New); + Local<FunctionTemplate> script_tmpl = NewFunctionTemplate(isolate, New); script_tmpl->InstanceTemplate()->SetInternalFieldCount( ContextifyScript::kInternalFieldCount); script_tmpl->SetClassName(class_name); - env->SetProtoMethod(script_tmpl, "createCachedData", CreateCachedData); - env->SetProtoMethod(script_tmpl, "runInContext", RunInContext); + SetProtoMethod(isolate, script_tmpl, "createCachedData", CreateCachedData); + SetProtoMethod(isolate, script_tmpl, "runInContext", RunInContext); Local<Context> context = env->context(); @@ -1262,12 +1266,14 @@ void MicrotaskQueueWrap::New(const FunctionCallbackInfo<Value>& args) { } void MicrotaskQueueWrap::Init(Environment* env, Local<Object> target) { - HandleScope scope(env->isolate()); - Local<FunctionTemplate> tmpl = env->NewFunctionTemplate(New); + Isolate* isolate = env->isolate(); + HandleScope scope(isolate); + Local<Context> context = env->context(); + Local<FunctionTemplate> tmpl = NewFunctionTemplate(isolate, New); tmpl->InstanceTemplate()->SetInternalFieldCount( ContextifyScript::kInternalFieldCount); env->set_microtask_queue_ctor_template(tmpl); - env->SetConstructorFunction(target, "MicrotaskQueue", tmpl); + SetConstructorFunction(context, target, "MicrotaskQueue", tmpl); } void MicrotaskQueueWrap::RegisterExternalReferences( @@ -1285,11 +1291,11 @@ void Initialize(Local<Object> target, ContextifyScript::Init(env, target); MicrotaskQueueWrap::Init(env, target); - env->SetMethod(target, "startSigintWatchdog", StartSigintWatchdog); - env->SetMethod(target, "stopSigintWatchdog", StopSigintWatchdog); + SetMethod(context, target, "startSigintWatchdog", StartSigintWatchdog); + SetMethod(context, target, "stopSigintWatchdog", StopSigintWatchdog); // Used in tests. - env->SetMethodNoSideEffect( - target, "watchdogHasPendingSigint", WatchdogHasPendingSigint); + SetMethodNoSideEffect( + context, target, "watchdogHasPendingSigint", WatchdogHasPendingSigint); { Local<FunctionTemplate> tpl = FunctionTemplate::New(env->isolate()); @@ -1325,7 +1331,7 @@ void Initialize(Local<Object> target, target->Set(context, env->constants_string(), constants).Check(); - env->SetMethod(target, "measureMemory", MeasureMemory); + SetMethod(context, target, "measureMemory", MeasureMemory); } void RegisterExternalReferences(ExternalReferenceRegistry* registry) { diff --git a/src/node_credentials.cc b/src/node_credentials.cc index d7471eb0d4e..458fa13217e 100644 --- a/src/node_credentials.cc +++ b/src/node_credentials.cc @@ -448,23 +448,23 @@ static void Initialize(Local<Object> target, Environment* env = Environment::GetCurrent(context); Isolate* isolate = env->isolate(); - env->SetMethod(target, "safeGetenv", SafeGetenv); + SetMethod(context, target, "safeGetenv", SafeGetenv); #ifdef NODE_IMPLEMENTS_POSIX_CREDENTIALS READONLY_TRUE_PROPERTY(target, "implementsPosixCredentials"); - env->SetMethodNoSideEffect(target, "getuid", GetUid); - env->SetMethodNoSideEffect(target, "geteuid", GetEUid); - env->SetMethodNoSideEffect(target, "getgid", GetGid); - env->SetMethodNoSideEffect(target, "getegid", GetEGid); - env->SetMethodNoSideEffect(target, "getgroups", GetGroups); + SetMethodNoSideEffect(context, target, "getuid", GetUid); + SetMethodNoSideEffect(context, target, "geteuid", GetEUid); + SetMethodNoSideEffect(context, target, "getgid", GetGid); + SetMethodNoSideEffect(context, target, "getegid", GetEGid); + SetMethodNoSideEffect(context, target, "getgroups", GetGroups); if (env->owns_process_state()) { - env->SetMethod(target, "initgroups", InitGroups); - env->SetMethod(target, "setegid", SetEGid); - env->SetMethod(target, "seteuid", SetEUid); - env->SetMethod(target, "setgid", SetGid); - env->SetMethod(target, "setuid", SetUid); - env->SetMethod(target, "setgroups", SetGroups); + SetMethod(context, target, "initgroups", InitGroups); + SetMethod(context, target, "setegid", SetEGid); + SetMethod(context, target, "seteuid", SetEUid); + SetMethod(context, target, "setgid", SetGid); + SetMethod(context, target, "setuid", SetUid); + SetMethod(context, target, "setgroups", SetGroups); } #endif // NODE_IMPLEMENTS_POSIX_CREDENTIALS } diff --git a/src/node_dir.cc b/src/node_dir.cc index c530da0cc3b..e501934ecc7 100644 --- a/src/node_dir.cc +++ b/src/node_dir.cc @@ -351,17 +351,18 @@ void Initialize(Local<Object> target, Local<Context> context, void* priv) { Environment* env = Environment::GetCurrent(context); + Isolate* isolate = env->isolate(); - env->SetMethod(target, "opendir", OpenDir); + SetMethod(context, target, "opendir", OpenDir); // Create FunctionTemplate for DirHandle - Local<FunctionTemplate> dir = env->NewFunctionTemplate(DirHandle::New); + Local<FunctionTemplate> dir = NewFunctionTemplate(isolate, DirHandle::New); dir->Inherit(AsyncWrap::GetConstructorTemplate(env)); - env->SetProtoMethod(dir, "read", DirHandle::Read); - env->SetProtoMethod(dir, "close", DirHandle::Close); + SetProtoMethod(isolate, dir, "read", DirHandle::Read); + SetProtoMethod(isolate, dir, "close", DirHandle::Close); Local<ObjectTemplate> dirt = dir->InstanceTemplate(); dirt->SetInternalFieldCount(DirHandle::kInternalFieldCount); - env->SetConstructorFunction(target, "DirHandle", dir); + SetConstructorFunction(context, target, "DirHandle", dir); env->set_dir_instance_template(dirt); } diff --git a/src/node_errors.cc b/src/node_errors.cc index 63c6ea09d59..af0164df26e 100644 --- a/src/node_errors.cc +++ b/src/node_errors.cc @@ -964,21 +964,27 @@ void Initialize(Local<Object> target, Local<Value> unused, Local<Context> context, void* priv) { - Environment* env = Environment::GetCurrent(context); - env->SetMethod( - target, "setPrepareStackTraceCallback", SetPrepareStackTraceCallback); - env->SetMethod( - target, "setGetSourceMapErrorSource", SetGetSourceMapErrorSource); - env->SetMethod(target, "setSourceMapsEnabled", SetSourceMapsEnabled); - env->SetMethod(target, - "setMaybeCacheGeneratedSourceMap", - SetMaybeCacheGeneratedSourceMap); - env->SetMethod(target, - "setEnhanceStackForFatalException", - SetEnhanceStackForFatalException); - env->SetMethodNoSideEffect( - target, "noSideEffectsToString", NoSideEffectsToString); - env->SetMethod(target, "triggerUncaughtException", TriggerUncaughtException); + SetMethod(context, + target, + "setPrepareStackTraceCallback", + SetPrepareStackTraceCallback); + SetMethod(context, + target, + "setGetSourceMapErrorSource", + SetGetSourceMapErrorSource); + SetMethod(context, target, "setSourceMapsEnabled", SetSourceMapsEnabled); + SetMethod(context, + target, + "setMaybeCacheGeneratedSourceMap", + SetMaybeCacheGeneratedSourceMap); + SetMethod(context, + target, + "setEnhanceStackForFatalException", + SetEnhanceStackForFatalException); + SetMethodNoSideEffect( + context, target, "noSideEffectsToString", NoSideEffectsToString); + SetMethod( + context, target, "triggerUncaughtException", TriggerUncaughtException); } void DecorateErrorStack(Environment* env, diff --git a/src/node_file.cc b/src/node_file.cc index a010479cd71..8815bd8d52e 100644 --- a/src/node_file.cc +++ b/src/node_file.cc @@ -2433,46 +2433,46 @@ void Initialize(Local<Object> target, env->AddBindingData<BindingData>(context, target); if (binding_data == nullptr) return; - env->SetMethod(target, "access", Access); - env->SetMethod(target, "close", Close); - env->SetMethod(target, "open", Open); - env->SetMethod(target, "openFileHandle", OpenFileHandle); - env->SetMethod(target, "read", Read); - env->SetMethod(target, "readBuffers", ReadBuffers); - env->SetMethod(target, "fdatasync", Fdatasync); - env->SetMethod(target, "fsync", Fsync); - env->SetMethod(target, "rename", Rename); - env->SetMethod(target, "ftruncate", FTruncate); - env->SetMethod(target, "rmdir", RMDir); - env->SetMethod(target, "mkdir", MKDir); - env->SetMethod(target, "readdir", ReadDir); - env->SetMethod(target, "internalModuleReadJSON", InternalModuleReadJSON); - env->SetMethod(target, "internalModuleStat", InternalModuleStat); - env->SetMethod(target, "stat", Stat); - env->SetMethod(target, "lstat", LStat); - env->SetMethod(target, "fstat", FStat); - env->SetMethod(target, "link", Link); - env->SetMethod(target, "symlink", Symlink); - env->SetMethod(target, "readlink", ReadLink); - env->SetMethod(target, "unlink", Unlink); - env->SetMethod(target, "writeBuffer", WriteBuffer); - env->SetMethod(target, "writeBuffers", WriteBuffers); - env->SetMethod(target, "writeString", WriteString); - env->SetMethod(target, "realpath", RealPath); - env->SetMethod(target, "copyFile", CopyFile); - - env->SetMethod(target, "chmod", Chmod); - env->SetMethod(target, "fchmod", FChmod); - - env->SetMethod(target, "chown", Chown); - env->SetMethod(target, "fchown", FChown); - env->SetMethod(target, "lchown", LChown); - - env->SetMethod(target, "utimes", UTimes); - env->SetMethod(target, "futimes", FUTimes); - env->SetMethod(target, "lutimes", LUTimes); - - env->SetMethod(target, "mkdtemp", Mkdtemp); + SetMethod(context, target, "access", Access); + SetMethod(context, target, "close", Close); + SetMethod(context, target, "open", Open); + SetMethod(context, target, "openFileHandle", OpenFileHandle); + SetMethod(context, target, "read", Read); + SetMethod(context, target, "readBuffers", ReadBuffers); + SetMethod(context, target, "fdatasync", Fdatasync); + SetMethod(context, target, "fsync", Fsync); + SetMethod(context, target, "rename", Rename); + SetMethod(context, target, "ftruncate", FTruncate); + SetMethod(context, target, "rmdir", RMDir); + SetMethod(context, target, "mkdir", MKDir); + SetMethod(context, target, "readdir", ReadDir); + SetMethod(context, target, "internalModuleReadJSON", InternalModuleReadJSON); + SetMethod(context, target, "internalModuleStat", InternalModuleStat); + SetMethod(context, target, "stat", Stat); + SetMethod(context, target, "lstat", LStat); + SetMethod(context, target, "fstat", FStat); + SetMethod(context, target, "link", Link); + SetMethod(context, target, "symlink", Symlink); + SetMethod(context, target, "readlink", ReadLink); + SetMethod(context, target, "unlink", Unlink); + SetMethod(context, target, "writeBuffer", WriteBuffer); + SetMethod(context, target, "writeBuffers", WriteBuffers); + SetMethod(context, target, "writeString", WriteString); + SetMethod(context, target, "realpath", RealPath); + SetMethod(context, target, "copyFile", CopyFile); + + SetMethod(context, target, "chmod", Chmod); + SetMethod(context, target, "fchmod", FChmod); + + SetMethod(context, target, "chown", Chown); + SetMethod(context, target, "fchown", FChown); + SetMethod(context, target, "lchown", LChown); + + SetMethod(context, target, "utimes", UTimes); + SetMethod(context, target, "futimes", FUTimes); + SetMethod(context, target, "lutimes", LUTimes); + + SetMethod(context, target, "mkdtemp", Mkdtemp); target ->Set(context, @@ -2485,11 +2485,11 @@ void Initialize(Local<Object> target, StatWatcher::Initialize(env, target); // Create FunctionTemplate for FSReqCallback - Local<FunctionTemplate> fst = env->NewFunctionTemplate(NewFSReqCallback); + Local<FunctionTemplate> fst = NewFunctionTemplate(isolate, NewFSReqCallback); fst->InstanceTemplate()->SetInternalFieldCount( FSReqBase::kInternalFieldCount); fst->Inherit(AsyncWrap::GetConstructorTemplate(env)); - env->SetConstructorFunction(target, "FSReqCallback", fst); + SetConstructorFunction(context, target, "FSReqCallback", fst); // Create FunctionTemplate for FileHandleReadWrap. There’s no need // to do anything in the constructor, so we only store the instance template. @@ -2514,14 +2514,14 @@ void Initialize(Local<Object> target, env->set_fsreqpromise_constructor_template(fpo); // Create FunctionTemplate for FileHandle - Local<FunctionTemplate> fd = env->NewFunctionTemplate(FileHandle::New); + Local<FunctionTemplate> fd = NewFunctionTemplate(isolate, FileHandle::New); fd->Inherit(AsyncWrap::GetConstructorTemplate(env)); - env->SetProtoMethod(fd, "close", FileHandle::Close); - env->SetProtoMethod(fd, "releaseFD", FileHandle::ReleaseFD); + SetProtoMethod(isolate, fd, "close", FileHandle::Close); + SetProtoMethod(isolate, fd, "releaseFD", FileHandle::ReleaseFD); Local<ObjectTemplate> fdt = fd->InstanceTemplate(); fdt->SetInternalFieldCount(FileHandle::kInternalFieldCount); StreamBase::AddMethods(env, fd); - env->SetConstructorFunction(target, "FileHandle", fd); + SetConstructorFunction(context, target, "FileHandle", fd); env->set_fd_constructor_template(fdt); // Create FunctionTemplate for FileHandle::CloseReq diff --git a/src/node_http2.cc b/src/node_http2.cc index f5723821f3f..e4b9e277593 100644 --- a/src/node_http2.cc +++ b/src/node_http2.cc @@ -3201,10 +3201,10 @@ void Initialize(Local<Object> target, NODE_DEFINE_CONSTANT(target, kSessionHasAltsvcListeners); // Method to fetch the nghttp2 string description of an nghttp2 error code - env->SetMethod(target, "nghttp2ErrorString", HttpErrorString); - env->SetMethod(target, "refreshDefaultSettings", RefreshDefaultSettings); - env->SetMethod(target, "packSettings", PackSettings); - env->SetMethod(target, "setCallbackFunctions", SetCallbackFunctions); + SetMethod(context, target, "nghttp2ErrorString", HttpErrorString); + SetMethod(context, target, "refreshDefaultSettings", RefreshDefaultSettings); + SetMethod(context, target, "packSettings", PackSettings); + SetMethod(context, target, "setCallbackFunctions", SetCallbackFunctions); Local<FunctionTemplate> ping = FunctionTemplate::New(env->isolate()); ping->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "Http2Ping")); @@ -3220,50 +3220,54 @@ void Initialize(Local<Object> target, env->set_http2settings_constructor_template(settingt); Local<FunctionTemplate> stream = FunctionTemplate::New(env->isolate()); - env->SetProtoMethod(stream, "id", Http2Stream::GetID); - env->SetProtoMethod(stream, "destroy", Http2Stream::Destroy); - env->SetProtoMethod(stream, "priority", Http2Stream::Priority); - env->SetProtoMethod(stream, "pushPromise", Http2Stream::PushPromise); - env->SetProtoMethod(stream, "info", Http2Stream::Info); - env->SetProtoMethod(stream, "trailers", Http2Stream::Trailers); - env->SetProtoMethod(stream, "respond", Http2Stream::Respond); - env->SetProtoMethod(stream, "rstStream", Http2Stream::RstStream); - env->SetProtoMethod(stream, "refreshState", Http2Stream::RefreshState); + SetProtoMethod(isolate, stream, "id", Http2Stream::GetID); + SetProtoMethod(isolate, stream, "destroy", Http2Stream::Destroy); + SetProtoMethod(isolate, stream, "priority", Http2Stream::Priority); + SetProtoMethod(isolate, stream, "pushPromise", Http2Stream::PushPromise); + SetProtoMethod(isolate, stream, "info", Http2Stream::Info); + SetProtoMethod(isolate, stream, "trailers", Http2Stream::Trailers); + SetProtoMethod(isolate, stream, "respond", Http2Stream::Respond); + SetProtoMethod(isolate, stream, "rstStream", Http2Stream::RstStream); + SetProtoMethod(isolate, stream, "refreshState", Http2Stream::RefreshState); stream->Inherit(AsyncWrap::GetConstructorTemplate(env)); StreamBase::AddMethods(env, stream); Local<ObjectTemplate> streamt = stream->InstanceTemplate(); streamt->SetInternalFieldCount(StreamBase::kInternalFieldCount); env->set_http2stream_constructor_template(streamt); - env->SetConstructorFunction(target, "Http2Stream", stream); + SetConstructorFunction(context, target, "Http2Stream", stream); Local<FunctionTemplate> session = - env->NewFunctionTemplate(Http2Session::New); + NewFunctionTemplate(isolate, Http2Session::New); session->InstanceTemplate()->SetInternalFieldCount( Http2Session::kInternalFieldCount); session->Inherit(AsyncWrap::GetConstructorTemplate(env)); - env->SetProtoMethod(session, "origin", Http2Session::Origin); - env->SetProtoMethod(session, "altsvc", Http2Session::AltSvc); - env->SetProtoMethod(session, "ping", Http2Session::Ping); - env->SetProtoMethod(session, "consume", Http2Session::Consume); - env->SetProtoMethod(session, "receive", Http2Session::Receive); - env->SetProtoMethod(session, "destroy", Http2Session::Destroy); - env->SetProtoMethod(session, "goaway", Http2Session::Goaway); - env->SetProtoMethod(session, "settings", Http2Session::Settings); - env->SetProtoMethod(session, "request", Http2Session::Request); - env->SetProtoMethod(session, "setNextStreamID", - Http2Session::SetNextStreamID); - env->SetProtoMethod(session, "setLocalWindowSize", - Http2Session::SetLocalWindowSize); - env->SetProtoMethod(session, "updateChunksSent", - Http2Session::UpdateChunksSent); - env->SetProtoMethod(session, "refreshState", Http2Session::RefreshState); - env->SetProtoMethod( - session, "localSettings", + SetProtoMethod(isolate, session, "origin", Http2Session::Origin); + SetProtoMethod(isolate, session, "altsvc", Http2Session::AltSvc); + SetProtoMethod(isolate, session, "ping", Http2Session::Ping); + SetProtoMethod(isolate, session, "consume", Http2Session::Consume); + SetProtoMethod(isolate, session, "receive", Http2Session::Receive); + SetProtoMethod(isolate, session, "destroy", Http2Session::Destroy); + SetProtoMethod(isolate, session, "goaway", Http2Session::Goaway); + SetProtoMethod(isolate, session, "settings", Http2Session::Settings); + SetProtoMethod(isolate, session, "request", Http2Session::Request); + SetProtoMethod( + isolate, session, "setNextStreamID", Http2Session::SetNextStreamID); + SetProtoMethod( + isolate, session, "setLocalWindowSize", Http2Session::SetLocalWindowSize); + SetProtoMethod( + isolate, session, "updateChunksSent", Http2Session::UpdateChunksSent); + SetProtoMethod(isolate, session, "refreshState", Http2Session::RefreshState); + SetProtoMethod( + isolate, + session, + "localSettings", Http2Session::RefreshSettings<nghttp2_session_get_local_settings>); - env->SetProtoMethod( - session, "remoteSettings", + SetProtoMethod( + isolate, + session, + "remoteSettings", Http2Session::RefreshSettings<nghttp2_session_get_remote_settings>); - env->SetConstructorFunction(target, "Http2Session", session); + SetConstructorFunction(context, target, "Http2Session", session); Local<Object> constants = Object::New(isolate); diff --git a/src/node_http_parser.cc b/src/node_http_parser.cc index 620d608713d..914d0294214 100644 --- a/src/node_http_parser.cc +++ b/src/node_http_parser.cc @@ -1175,11 +1175,12 @@ void InitializeHttpParser(Local<Object> target, Local<Context> context, void* priv) { Environment* env = Environment::GetCurrent(context); + Isolate* isolate = env->isolate(); BindingData* const binding_data = env->AddBindingData<BindingData>(context, target); if (binding_data == nullptr) return; - Local<FunctionTemplate> t = env->NewFunctionTemplate(Parser::New); + Local<FunctionTemplate> t = NewFunctionTemplate(isolate, Parser::New); t->InstanceTemplate()->SetInternalFieldCount(Parser::kInternalFieldCount); t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "REQUEST"), @@ -1223,30 +1224,31 @@ void InitializeHttpParser(Local<Object> target, methods).Check(); t->Inherit(AsyncWrap::GetConstructorTemplate(env)); - env->SetProtoMethod(t, "close", Parser::Close); - env->SetProtoMethod(t, "free", Parser::Free); - env->SetProtoMethod(t, "remove", Parser::Remove); - env->SetProtoMethod(t, "execute", Parser::Execute); - env->SetProtoMethod(t, "finish", Parser::Finish); - env->SetProtoMethod(t, "initialize", Parser::Initialize); - env->SetProtoMethod(t, "pause", Parser::Pause<true>); - env->SetProtoMethod(t, "resume", Parser::Pause<false>); - env->SetProtoMethod(t, "consume", Parser::Consume); - env->SetProtoMethod(t, "unconsume", Parser::Unconsume); - env->SetProtoMethod(t, "getCurrentBuffer", Parser::GetCurrentBuffer); - env->SetProtoMethod(t, "duration", Parser::Duration); - env->SetProtoMethod(t, "headersCompleted", Parser::HeadersCompleted); - - env->SetConstructorFunction(target, "HTTPParser", t); - - Local<FunctionTemplate> c = env->NewFunctionTemplate(ConnectionsList::New); + SetProtoMethod(isolate, t, "close", Parser::Close); + SetProtoMethod(isolate, t, "free", Parser::Free); + SetProtoMethod(isolate, t, "remove", Parser::Remove); + SetProtoMethod(isolate, t, "execute", Parser::Execute); + SetProtoMethod(isolate, t, "finish", Parser::Finish); + SetProtoMethod(isolate, t, "initialize", Parser::Initialize); + SetProtoMethod(isolate, t, "pause", Parser::Pause<true>); + SetProtoMethod(isolate, t, "resume", Parser::Pause<false>); + SetProtoMethod(isolate, t, "consume", Parser::Consume); + SetProtoMethod(isolate, t, "unconsume", Parser::Unconsume); + SetProtoMethod(isolate, t, "getCurrentBuffer", Parser::GetCurrentBuffer); + SetProtoMethod(isolate, t, "duration", Parser::Duration); + SetProtoMethod(isolate, t, "headersCompleted", Parser::HeadersCompleted); + + SetConstructorFunction(context, target, "HTTPParser", t); + + Local<FunctionTemplate> c = + NewFunctionTemplate(isolate, ConnectionsList::New); c->InstanceTemplate() ->SetInternalFieldCount(ConnectionsList::kInternalFieldCount); - env->SetProtoMethod(c, "all", ConnectionsList::All); - env->SetProtoMethod(c, "idle", ConnectionsList::Idle); - env->SetProtoMethod(c, "active", ConnectionsList::Active); - env->SetProtoMethod(c, "expired", ConnectionsList::Expired); - env->SetConstructorFunction(target, "ConnectionsList", c); + SetProtoMethod(isolate, c, "all", ConnectionsList::All); + SetProtoMethod(isolate, c, "idle", ConnectionsList::Idle); + SetProtoMethod(isolate, c, "active", ConnectionsList::Active); + SetProtoMethod(isolate, c, "expired", ConnectionsList::Expired); + SetConstructorFunction(context, target, "ConnectionsList", c); } } // anonymous namespace diff --git a/src/node_i18n.cc b/src/node_i18n.cc index d96efaa9df7..581d52a7d05 100644 --- a/src/node_i18n.cc +++ b/src/node_i18n.cc @@ -838,17 +838,17 @@ void Initialize(Local<Object> target, Local<Context> context, void* priv) { Environment* env = Environment::GetCurrent(context); - env->SetMethod(target, "toUnicode", ToUnicode); - env->SetMethod(target, "toASCII", ToASCII); - env->SetMethod(target, "getStringWidth", GetStringWidth); + SetMethod(context, target, "toUnicode", ToUnicode); + SetMethod(context, target, "toASCII", ToASCII); + SetMethod(context, target, "getStringWidth", GetStringWidth); // One-shot converters - env->SetMethod(target, "icuErrName", ICUErrorName); - env->SetMethod(target, "transcode", Transcode); + SetMethod(context, target, "icuErrName", ICUErrorName); + SetMethod(context, target, "transcode", Transcode); // ConverterObject { - Local<FunctionTemplate> t = FunctionTemplate::New(env->isolate()); + Local<FunctionTemplate> t = NewFunctionTemplate(env->isolate(), nullptr); t->Inherit(BaseObject::GetConstructorTemplate(env)); t->InstanceTemplate()->SetInternalFieldCount( ConverterObject::kInternalFieldCount); @@ -858,9 +858,9 @@ void Initialize(Local<Object> target, env->set_i18n_converter_template(t->InstanceTemplate()); } - env->SetMethod(target, "getConverter", ConverterObject::Create); - env->SetMethod(target, "decode", ConverterObject::Decode); - env->SetMethod(target, "hasConverter", ConverterObject::Has); + SetMethod(context, target, "getConverter", ConverterObject::Create); + SetMethod(context, target, "decode", ConverterObject::Decode); + SetMethod(context, target, "hasConverter", ConverterObject::Has); } void RegisterExternalReferences(ExternalReferenceRegistry* registry) { diff --git a/src/node_messaging.cc b/src/node_messaging.cc index 6403950e9c8..58cd1882dd2 100644 --- a/src/node_messaging.cc +++ b/src/node_messaging.cc @@ -1111,14 +1111,15 @@ Local<FunctionTemplate> GetMessagePortConstructorTemplate(Environment* env) { return templ; { - Local<FunctionTemplate> m = env->NewFunctionTemplate(MessagePort::New); + Isolate* isolate = env->isolate(); + Local<FunctionTemplate> m = NewFunctionTemplate(isolate, MessagePort::New); m->SetClassName(env->message_port_constructor_string()); m->InstanceTemplate()->SetInternalFieldCount( MessagePort::kInternalFieldCount); m->Inherit(HandleWrap::GetConstructorTemplate(env)); - env->SetProtoMethod(m, "postMessage", MessagePort::PostMessage); - env->SetProtoMethod(m, "start", MessagePort::Start); + SetProtoMethod(isolate, m, "postMessage", MessagePort::PostMessage); + SetProtoMethod(isolate, m, "start", MessagePort::Start); env->set_message_port_constructor_template(m); } @@ -1451,38 +1452,43 @@ static void InitMessaging(Local<Object> target, Local<Context> context, void* priv) { Environment* env = Environment::GetCurrent(context); + Isolate* isolate = env->isolate(); { - env->SetConstructorFunction( - target, - "MessageChannel", - env->NewFunctionTemplate(MessageChannel)); + SetConstructorFunction(context, + target, + "MessageChannel", + NewFunctionTemplate(isolate, MessageChannel)); } { - Local<FunctionTemplate> t = env->NewFunctionTemplate(JSTransferable::New); + Local<FunctionTemplate> t = + NewFunctionTemplate(isolate, JSTransferable::New); t->Inherit(BaseObject::GetConstructorTemplate(env)); t->InstanceTemplate()->SetInternalFieldCount( JSTransferable::kInternalFieldCount); - env->SetConstructorFunction(target, "JSTransferable", t); + SetConstructorFunction(context, target, "JSTransferable", t); } - env->SetConstructorFunction( - target, - env->message_port_constructor_string(), - GetMessagePortConstructorTemplate(env)); + SetConstructorFunction(context, + target, + env->message_port_constructor_string(), + GetMessagePortConstructorTemplate(env)); // These are not methods on the MessagePort prototype, because // the browser equivalents do not provide them. - env->SetMethod(target, "stopMessagePort", MessagePort::Stop); - env->SetMethod(target, "checkMessagePort", MessagePort::CheckType); - env->SetMethod(target, "drainMessagePort", MessagePort::Drain); - env->SetMethod(target, "receiveMessageOnPort", MessagePort::ReceiveMessage); - env->SetMethod(target, "moveMessagePortToContext", - MessagePort::MoveToContext); - env->SetMethod(target, "setDeserializerCreateObjectFunction", - SetDeserializerCreateObjectFunction); - env->SetMethod(target, "broadcastChannel", BroadcastChannel); + SetMethod(context, target, "stopMessagePort", MessagePort::Stop); + SetMethod(context, target, "checkMessagePort", MessagePort::CheckType); + SetMethod(context, target, "drainMessagePort", MessagePort::Drain); + SetMethod( + context, target, "receiveMessageOnPort", MessagePort::ReceiveMessage); + SetMethod( + context, target, "moveMessagePortToContext", MessagePort::MoveToContext); + SetMethod(context, + target, + "setDeserializerCreateObjectFunction", + SetDeserializerCreateObjectFunction); + SetMethod(context, target, "broadcastChannel", BroadcastChannel); { Local<Function> domexception = GetDOMException(context).ToLocalChecked(); diff --git a/src/node_native_module.cc b/src/node_native_module.cc index 38af67c8955..7a515cc1efa 100644 --- a/src/node_native_module.cc +++ b/src/node_native_module.cc @@ -568,9 +568,10 @@ void NativeModuleLoader::Initialize(Local<Object> target, Local<Context> context, void* priv) { Environment* env = Environment::GetCurrent(context); + Isolate* isolate = env->isolate(); target - ->SetAccessor(env->context(), + ->SetAccessor(context, env->config_string(), ConfigStringGetter, nullptr, @@ -580,8 +581,8 @@ void NativeModuleLoader::Initialize(Local<Object> target, SideEffectType::kHasNoSideEffect) .Check(); target - ->SetAccessor(env->context(), - FIXED_ONE_BYTE_STRING(env->isolate(), "moduleIds"), + ->SetAccessor(context, + FIXED_ONE_BYTE_STRING(isolate, "moduleIds"), ModuleIdsGetter, nullptr, MaybeLocal<Value>(), @@ -591,8 +592,8 @@ void NativeModuleLoader::Initialize(Local<Object> target, .Check(); target - ->SetAccessor(env->context(), - FIXED_ONE_BYTE_STRING(env->isolate(), "moduleCategories"), + ->SetAccessor(context, + FIXED_ONE_BYTE_STRING(isolate, "moduleCategories"), GetModuleCategories, nullptr, Local<Value>(), @@ -601,10 +602,11 @@ void NativeModuleLoader::Initialize(Local<Object> target, SideEffectType::kHasNoSideEffect) .Check(); - env->SetMethod(target, "getCacheUsage", NativeModuleLoader::GetCacheUsage); - env->SetMethod( - target, "compileFunction", NativeModuleLoader::CompileFunction); - env->SetMethod(target, "hasCachedBuiltins", HasCachedBuiltins); + SetMethod( + context, target, "getCacheUsage", NativeModuleLoader::GetCacheUsage); + SetMethod( + context, target, "compileFunction", NativeModuleLoader::CompileFunction); + SetMethod(context, target, "hasCachedBuiltins", HasCachedBuiltins); // internalBinding('native_module') should be frozen target->SetIntegrityLevel(context, IntegrityLevel::kFrozen).FromJust(); } diff --git a/src/node_options.cc b/src/node_options.cc index 5189df1ae66..0c148af8608 100644 --- a/src/node_options.cc +++ b/src/node_options.cc @@ -1160,8 +1160,9 @@ void Initialize(Local<Object> target, void* priv) { Environment* env = Environment::GetCurrent(context); Isolate* isolate = env->isolate(); - env->SetMethodNoSideEffect(target, "getCLIOptions", GetCLIOptions); - env->SetMethodNoSideEffect(target, "getEmbedderOptions", GetEmbedderOptions); + SetMethodNoSideEffect(context, target, "getCLIOptions", GetCLIOptions); + SetMethodNoSideEffect( + context, target, "getEmbedderOptions", GetEmbedderOptions); Local<Object> env_settings = Object::New(isolate); NODE_DEFINE_CONSTANT(env_settings, kAllowedInEnvironment); diff --git a/src/node_os.cc b/src/node_os.cc index 046a6106ccd..5b4d6567fb3 100644 --- a/src/node_os.cc +++ b/src/node_os.cc @@ -382,21 +382,23 @@ void Initialize(Local<Object> target, Local<Context> context, void* priv) { Environment* env = Environment::GetCurrent(context); - env->SetMethod(target, "getHostname", GetHostname); - env->SetMethod(target, "getLoadAvg", GetLoadAvg); - env->SetMethod(target, "getUptime", GetUptime); - env->SetMethod(target, "getTotalMem", GetTotalMemory); - env->SetMethod(target, "getFreeMem", GetFreeMemory); - env->SetMethod(target, "getCPUs", GetCPUInfo); - env->SetMethod(target, "getInterfaceAddresses", GetInterfaceAddresses); - env->SetMethod(target, "getHomeDirectory", GetHomeDirectory); - env->SetMethod(target, "getUserInfo", GetUserInfo); - env->SetMethod(target, "setPriority", SetPriority); - env->SetMethod(target, "getPriority", GetPriority); - env->SetMethod(target, "getOSInformation", GetOSInformation); - target->Set(env->context(), - FIXED_ONE_BYTE_STRING(env->isolate(), "isBigEndian"), - Boolean::New(env->isolate(), IsBigEndian())).Check(); + SetMethod(context, target, "getHostname", GetHostname); + SetMethod(context, target, "getLoadAvg", GetLoadAvg); + SetMethod(context, target, "getUptime", GetUptime); + SetMethod(context, target, "getTotalMem", GetTotalMemory); + SetMethod(context, target, "getFreeMem", GetFreeMemory); + SetMethod(context, target, "getCPUs", GetCPUInfo); + SetMethod(context, target, "getInterfaceAddresses", GetInterfaceAddresses); + SetMethod(context, target, "getHomeDirectory", GetHomeDirectory); + SetMethod(context, target, "getUserInfo", GetUserInfo); + SetMethod(context, target, "setPriority", SetPriority); + SetMethod(context, target, "getPriority", GetPriority); + SetMethod(context, target, "getOSInformation", GetOSInformation); + target + ->Set(context, + FIXED_ONE_BYTE_STRING(env->isolate(), "isBigEndian"), + Boolean::New(env->isolate(), IsBigEndian())) + .Check(); } void RegisterExternalReferences(ExternalReferenceRegistry* registry) { diff --git a/src/node_perf.cc b/src/node_perf.cc index 2511a71ba2c..cf48b471a6f 100644 --- a/src/node_perf.cc +++ b/src/node_perf.cc @@ -291,19 +291,21 @@ void Initialize(Local<Object> target, target->Set(context, performanceEntryString, fn).Check(); env->set_performance_entry_template(fn); - env->SetMethod(target, "markMilestone", MarkMilestone); - env->SetMethod(target, "setupObservers", SetupPerformanceObservers); - env->SetMethod(target, - "installGarbageCollectionTracking", - InstallGarbageCollectionTracking); - env->SetMethod(target, - "removeGarbageCollectionTracking", - RemoveGarbageCollectionTracking); - env->SetMethod(target, "notify", Notify); - env->SetMethod(target, "loopIdleTime", LoopIdleTime); - env->SetMethod(target, "getTimeOrigin", GetTimeOrigin); - env->SetMethod(target, "getTimeOriginTimestamp", GetTimeOriginTimeStamp); - env->SetMethod(target, "createELDHistogram", CreateELDHistogram); + SetMethod(context, target, "markMilestone", MarkMilestone); + SetMethod(context, target, "setupObservers", SetupPerformanceObservers); + SetMethod(context, + target, + "installGarbageCollectionTracking", + InstallGarbageCollectionTracking); + SetMethod(context, + target, + "removeGarbageCollectionTracking", + RemoveGarbageCollectionTracking); + SetMethod(context, target, "notify", Notify); + SetMethod(context, target, "loopIdleTime", LoopIdleTime); + SetMethod(context, target, "getTimeOrigin", GetTimeOrigin); + SetMethod(context, target, "getTimeOriginTimestamp", GetTimeOriginTimeStamp); + SetMethod(context, target, "createELDHistogram", CreateELDHistogram); Local<Object> constants = Object::New(isolate); diff --git a/src/node_process_methods.cc b/src/node_process_methods.cc index 350a7094baa..024212132f2 100644 --- a/src/node_process_methods.cc +++ b/src/node_process_methods.cc @@ -464,8 +464,9 @@ v8::CFunction BindingData::fast_number_(v8::CFunction::Make(FastNumber)); v8::CFunction BindingData::fast_bigint_(v8::CFunction::Make(FastBigInt)); void BindingData::AddMethods() { - env()->SetFastMethod(object(), "hrtime", SlowNumber, &fast_number_); - env()->SetFastMethod(object(), "hrtimeBigInt", SlowBigInt, &fast_bigint_); + Local<Context> ctx = env()->context(); + SetFastMethod(ctx, object(), "hrtime", SlowNumber, &fast_number_); + SetFastMethod(ctx, object(), "hrtimeBigInt", SlowBigInt, &fast_bigint_); } void BindingData::RegisterExternalReferences( @@ -560,31 +561,31 @@ static void Initialize(Local<Object> target, // define various internal methods if (env->owns_process_state()) { - env->SetMethod(target, "_debugProcess", DebugProcess); - env->SetMethod(target, "_debugEnd", DebugEnd); - env->SetMethod(target, "abort", Abort); - env->SetMethod(target, "causeSegfault", CauseSegfault); - env->SetMethod(target, "chdir", Chdir); + SetMethod(context, target, "_debugProcess", DebugProcess); + SetMethod(context, target, "_debugEnd", DebugEnd); + SetMethod(context, target, "abort", Abort); + SetMethod(context, target, "causeSegfault", CauseSegfault); + SetMethod(context, target, "chdir", Chdir); } - env->SetMethod(target, "umask", Umask); - env->SetMethod(target, "_rawDebug", RawDebug); - env->SetMethod(target, "memoryUsage", MemoryUsage); - env->SetMethod(target, "rss", Rss); - env->SetMethod(target, "cpuUsage", CPUUsage); - env->SetMethod(target, "resourceUsage", ResourceUsage); - - env->SetMethod(target, "_getActiveRequests", GetActiveRequests); - env->SetMethod(target, "_getActiveRequestsInfo", GetActiveRequestsInfo); - env->SetMethod(target, "_getActiveHandles", GetActiveHandles); - env->SetMethod(target, "_getActiveHandlesInfo", GetActiveHandlesInfo); - env->SetMethod(target, "_kill", Kill); - - env->SetMethodNoSideEffect(target, "cwd", Cwd); - env->SetMethod(target, "dlopen", binding::DLOpen); - env->SetMethod(target, "reallyExit", ReallyExit); - env->SetMethodNoSideEffect(target, "uptime", Uptime); - env->SetMethod(target, "patchProcessObject", PatchProcessObject); + SetMethod(context, target, "umask", Umask); + SetMethod(context, target, "_rawDebug", RawDebug); + SetMethod(context, target, "memoryUsage", MemoryUsage); + SetMethod(context, target, "rss", Rss); + SetMethod(context, target, "cpuUsage", CPUUsage); + SetMethod(context, target, "resourceUsage", ResourceUsage); + + SetMethod(context, target, "_getActiveRequestsInfo", GetActiveRequestsInfo); + SetMethod(context, target, "_getActiveRequests", GetActiveRequests); + SetMethod(context, target, "_getActiveHandles", GetActiveHandles); + SetMethod(context, target, "_getActiveHandlesInfo", GetActiveHandlesInfo); + SetMethod(context, target, "_kill", Kill); + + SetMethodNoSideEffect(context, target, "cwd", Cwd); + SetMethod(context, target, "dlopen", binding::DLOpen); + SetMethod(context, target, "reallyExit", ReallyExit); + SetMethodNoSideEffect(context, target, "uptime", Uptime); + SetMethod(context, target, "patchProcessObject", PatchProcessObject); } void RegisterExternalReferences(ExternalReferenceRegistry* registry) { diff --git a/src/node_process_object.cc b/src/node_process_object.cc index 3a44c45c6b8..569c93ccb31 100644 --- a/src/node_process_object.cc +++ b/src/node_process_object.cc @@ -144,7 +144,7 @@ MaybeLocal<Object> CreateProcessObject(Environment* env) { // process._rawDebug: may be overwritten later in JS land, but should be // available from the beginning for debugging purposes - env->SetMethod(process, "_rawDebug", RawDebug); + SetMethod(context, process, "_rawDebug", RawDebug); return scope.Escape(process); } diff --git a/src/node_report_module.cc b/src/node_report_module.cc index 160498c6276..b57a933972d 100644 --- a/src/node_report_module.cc +++ b/src/node_report_module.cc @@ -18,6 +18,7 @@ namespace report { using node::Environment; using node::Mutex; +using node::SetMethod; using node::Utf8Value; using v8::Context; using v8::FunctionCallbackInfo; @@ -175,26 +176,29 @@ static void Initialize(Local<Object> exports, Local<Value> unused, Local<Context> context, void* priv) { - Environment* env = Environment::GetCurrent(context); - - env->SetMethod(exports, "writeReport", WriteReport); - env->SetMethod(exports, "getReport", GetReport); - env->SetMethod(exports, "getCompact", GetCompact); - env->SetMethod(exports, "setCompact", SetCompact); - env->SetMethod(exports, "getDirectory", GetDirectory); - env->SetMethod(exports, "setDirectory", SetDirectory); - env->SetMethod(exports, "getFilename", GetFilename); - env->SetMethod(exports, "setFilename", SetFilename); - env->SetMethod(exports, "getSignal", GetSignal); - env->SetMethod(exports, "setSignal", SetSignal); - env->SetMethod(exports, "shouldReportOnFatalError", ShouldReportOnFatalError); - env->SetMethod(exports, "setReportOnFatalError", SetReportOnFatalError); - env->SetMethod(exports, "shouldReportOnSignal", ShouldReportOnSignal); - env->SetMethod(exports, "setReportOnSignal", SetReportOnSignal); - env->SetMethod(exports, "shouldReportOnUncaughtException", - ShouldReportOnUncaughtException); - env->SetMethod(exports, "setReportOnUncaughtException", - SetReportOnUncaughtException); + SetMethod(context, exports, "writeReport", WriteReport); + SetMethod(context, exports, "getReport", GetReport); + SetMethod(context, exports, "getCompact", GetCompact); + SetMethod(context, exports, "setCompact", SetCompact); + SetMethod(context, exports, "getDirectory", GetDirectory); + SetMethod(context, exports, "setDirectory", SetDirectory); + SetMethod(context, exports, "getFilename", GetFilename); + SetMethod(context, exports, "setFilename", SetFilename); + SetMethod(context, exports, "getSignal", GetSignal); + SetMethod(context, exports, "setSignal", SetSignal); + SetMethod( + context, exports, "shouldReportOnFatalError", ShouldReportOnFatalError); + SetMethod(context, exports, "setReportOnFatalError", SetReportOnFatalError); + SetMethod(context, exports, "shouldReportOnSignal", ShouldReportOnSignal); + SetMethod(context, exports, "setReportOnSignal", SetReportOnSignal); + SetMethod(context, + exports, + "shouldReportOnUncaughtException", + ShouldReportOnUncaughtException); + SetMethod(context, + exports, + "setReportOnUncaughtException", + SetReportOnUncaughtException); } void RegisterExternalReferences(node::ExternalReferenceRegistry* registry) { diff --git a/src/node_serdes.cc b/src/node_serdes.cc index f6f0034bc24..45a16d9de43 100644 --- a/src/node_serdes.cc +++ b/src/node_serdes.cc @@ -455,53 +455,62 @@ void Initialize(Local<Object> target, Local<Context> context, void* priv) { Environment* env = Environment::GetCurrent(context); + Isolate* isolate = env->isolate(); + Local<FunctionTemplate> ser = - env->NewFunctionTemplate(SerializerContext::New); + NewFunctionTemplate(isolate, SerializerContext::New); ser->InstanceTemplate()->SetInternalFieldCount( SerializerContext::kInternalFieldCount); ser->Inherit(BaseObject::GetConstructorTemplate(env)); - env->SetProtoMethod(ser, "writeHeader", SerializerContext::WriteHeader); - env->SetProtoMethod(ser, "writeValue", SerializerContext::WriteValue); - env->SetProtoMethod(ser, "releaseBuffer", SerializerContext::ReleaseBuffer); - env->SetProtoMethod(ser, - "transferArrayBuffer", - SerializerContext::TransferArrayBuffer); - env->SetProtoMethod(ser, "writeUint32", SerializerContext::WriteUint32); - env->SetProtoMethod(ser, "writeUint64", SerializerContext::WriteUint64); - env->SetProtoMethod(ser, "writeDouble", SerializerContext::WriteDouble); - env->SetProtoMethod(ser, "writeRawBytes", SerializerContext::WriteRawBytes); - env->SetProtoMethod(ser, - "_setTreatArrayBufferViewsAsHostObjects", - SerializerContext::SetTreatArrayBufferViewsAsHostObjects); + SetProtoMethod(isolate, ser, "writeHeader", SerializerContext::WriteHeader); + SetProtoMethod(isolate, ser, "writeValue", SerializerContext::WriteValue); + SetProtoMethod( + isolate, ser, "releaseBuffer", SerializerContext::ReleaseBuffer); + SetProtoMethod(isolate, + ser, + "transferArrayBuffer", + SerializerContext::TransferArrayBuffer); + SetProtoMethod(isolate, ser, "writeUint32", SerializerContext::WriteUint32); + SetProtoMethod(isolate, ser, "writeUint64", SerializerContext::WriteUint64); + SetProtoMethod(isolate, ser, "writeDouble", SerializerContext::WriteDouble); + SetProtoMethod( + isolate, ser, "writeRawBytes", SerializerContext::WriteRawBytes); + SetProtoMethod(isolate, + ser, + "_setTreatArrayBufferViewsAsHostObjects", + SerializerContext::SetTreatArrayBufferViewsAsHostObjects); ser->ReadOnlyPrototype(); - env->SetConstructorFunction(target, "Serializer", ser); + SetConstructorFunction(context, target, "Serializer", ser); Local<FunctionTemplate> des = - env->NewFunctionTemplate(DeserializerContext::New); + NewFunctionTemplate(isolate, DeserializerContext::New); des->InstanceTemplate()->SetInternalFieldCount( DeserializerContext::kInternalFieldCount); des->Inherit(BaseObject::GetConstructorTemplate(env)); - env->SetProtoMethod(des, "readHeader", DeserializerContext::ReadHeader); - env->SetProtoMethod(des, "readValue", DeserializerContext::ReadValue); - env->SetProtoMethod(des, - "getWireFormatVersion", - DeserializerContext::GetWireFormatVersion); - env->SetProtoMethod(des, - "transferArrayBuffer", - DeserializerContext::TransferArrayBuffer); - env->SetProtoMethod(des, "readUint32", DeserializerContext::ReadUint32); - env->SetProtoMethod(des, "readUint64", DeserializerContext::ReadUint64); - env->SetProtoMethod(des, "readDouble", DeserializerContext::ReadDouble); - env->SetProtoMethod(des, "_readRawBytes", DeserializerContext::ReadRawBytes); + SetProtoMethod(isolate, des, "readHeader", DeserializerContext::ReadHeader); + SetProtoMethod(isolate, des, "readValue", DeserializerContext::ReadValue); + SetProtoMethod(isolate, + des, + "getWireFormatVersion", + DeserializerContext::GetWireFormatVersion); + SetProtoMethod(isolate, + des, + "transferArrayBuffer", + DeserializerContext::TransferArrayBuffer); + SetProtoMethod(isolate, des, "readUint32", DeserializerContext::ReadUint32); + SetProtoMethod(isolate, des, "readUint64", DeserializerContext::ReadUint64); + SetProtoMethod(isolate, des, "readDouble", DeserializerContext::ReadDouble); + SetProtoMethod( + isolate, des, "_readRawBytes", DeserializerContext::ReadRawBytes); des->SetLength(1); des->ReadOnlyPrototype(); - env->SetConstructorFunction(target, "Deserializer", des); + SetConstructorFunction(context, target, "Deserializer", des); } void RegisterExternalReferences(ExternalReferenceRegistry* registry) { diff --git a/src/node_snapshotable.cc b/src/node_snapshotable.cc index 9e88c2157d2..a7551bf1af1 100644 --- a/src/node_snapshotable.cc +++ b/src/node_snapshotable.cc @@ -520,13 +520,14 @@ void Initialize(Local<Object> target, Local<Value> unused, Local<Context> context, void* priv) { - Environment* env = Environment::GetCurrent(context); - env->SetMethod(target, "compileSerializeMain", CompileSerializeMain); - env->SetMethod(target, "markBootstrapComplete", MarkBootstrapComplete); - env->SetMethod(target, "setSerializeCallback", SetSerializeCallback); - env->SetMethod(target, "setDeserializeCallback", SetDeserializeCallback); - env->SetMethod( - target, "setDeserializeMainFunction", SetDeserializeMainFunction); + SetMethod(context, target, "compileSerializeMain", CompileSerializeMain); + SetMethod(context, target, "markBootstrapComplete", MarkBootstrapComplete); + SetMethod(context, target, "setSerializeCallback", SetSerializeCallback); + SetMethod(context, target, "setDeserializeCallback", SetDeserializeCallback); + SetMethod(context, + target, + "setDeserializeMainFunction", + SetDeserializeMainFunction); } void RegisterExternalReferences(ExternalReferenceRegistry* registry) { diff --git a/src/node_sockaddr.cc b/src/node_sockaddr.cc index d29414302b7..331af1d9dba 100644 --- a/src/node_sockaddr.cc +++ b/src/node_sockaddr.cc @@ -17,6 +17,7 @@ using v8::Context; using v8::FunctionCallbackInfo; using v8::FunctionTemplate; using v8::Int32; +using v8::Isolate; using v8::Local; using v8::MaybeLocal; using v8::Object; @@ -697,15 +698,16 @@ Local<FunctionTemplate> SocketAddressBlockListWrap::GetConstructorTemplate( Environment* env) { Local<FunctionTemplate> tmpl = env->blocklist_constructor_template(); if (tmpl.IsEmpty()) { - tmpl = env->NewFunctionTemplate(SocketAddressBlockListWrap::New); + Isolate* isolate = env->isolate(); + tmpl = NewFunctionTemplate(isolate, SocketAddressBlockListWrap::New); tmpl->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "BlockList")); tmpl->Inherit(BaseObject::GetConstructorTemplate(env)); tmpl->InstanceTemplate()->SetInternalFieldCount(kInternalFieldCount); - env->SetProtoMethod(tmpl, "addAddress", AddAddress); - env->SetProtoMethod(tmpl, "addRange", AddRange); - env->SetProtoMethod(tmpl, "addSubnet", AddSubnet); - env->SetProtoMethod(tmpl, "check", Check); - env->SetProtoMethod(tmpl, "getRules", GetRules); + SetProtoMethod(isolate, tmpl, "addAddress", AddAddress); + SetProtoMethod(isolate, tmpl, "addRange", AddRange); + SetProtoMethod(isolate, tmpl, "addSubnet", AddSubnet); + SetProtoMethod(isolate, tmpl, "check", Check); + SetProtoMethod(isolate, tmpl, "getRules", GetRules); env->set_blocklist_constructor_template(tmpl); } return tmpl; @@ -718,11 +720,11 @@ void SocketAddressBlockListWrap::Initialize( void* priv) { Environment* env = Environment::GetCurrent(context); - env->SetConstructorFunction( - target, - "BlockList", - GetConstructorTemplate(env), - Environment::SetConstructorFunctionFlag::NONE); + SetConstructorFunction(context, + target, + "BlockList", + GetConstructorTemplate(env), + SetConstructorFunctionFlag::NONE); SocketAddressBase::Initialize(env, target); @@ -750,25 +752,26 @@ Local<FunctionTemplate> SocketAddressBase::GetConstructorTemplate( Environment* env) { Local<FunctionTemplate> tmpl = env->socketaddress_constructor_template(); if (tmpl.IsEmpty()) { - tmpl = env->NewFunctionTemplate(New); + Isolate* isolate = env->isolate(); + tmpl = NewFunctionTemplate(isolate, New); tmpl->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "SocketAddress")); tmpl->InstanceTemplate()->SetInternalFieldCount( SocketAddressBase::kInternalFieldCount); tmpl->Inherit(BaseObject::GetConstructorTemplate(env)); - env->SetProtoMethod(tmpl, "detail", Detail); - env->SetProtoMethod(tmpl, "legacyDetail", LegacyDetail); - env->SetProtoMethodNoSideEffect(tmpl, "flowlabel", GetFlowLabel); + SetProtoMethod(isolate, tmpl, "detail", Detail); + SetProtoMethod(isolate, tmpl, "legacyDetail", LegacyDetail); + SetProtoMethodNoSideEffect(isolate, tmpl, "flowlabel", GetFlowLabel); env->set_socketaddress_constructor_template(tmpl); } return tmpl; } void SocketAddressBase::Initialize(Environment* env, Local<Object> target) { - env->SetConstructorFunction( - target, - "SocketAddress", - GetConstructorTemplate(env), - Environment::SetConstructorFunctionFlag::NONE); + SetConstructorFunction(env->context(), + target, + "SocketAddress", + GetConstructorTemplate(env), + SetConstructorFunctionFlag::NONE); } BaseObjectPtr<SocketAddressBase> SocketAddressBase::Create( diff --git a/src/node_stat_watcher.cc b/src/node_stat_watcher.cc index b9f7903a2fd..de8c099ca58 100644 --- a/src/node_stat_watcher.cc +++ b/src/node_stat_watcher.cc @@ -37,23 +37,24 @@ using v8::FunctionCallbackInfo; using v8::FunctionTemplate; using v8::HandleScope; using v8::Integer; +using v8::Isolate; using v8::Local; using v8::Object; using v8::Uint32; using v8::Value; - void StatWatcher::Initialize(Environment* env, Local<Object> target) { + Isolate* isolate = env->isolate(); HandleScope scope(env->isolate()); - Local<FunctionTemplate> t = env->NewFunctionTemplate(StatWatcher::New); + Local<FunctionTemplate> t = NewFunctionTemplate(isolate, StatWatcher::New); t->InstanceTemplate()->SetInternalFieldCount( StatWatcher::kInternalFieldCount); t->Inherit(HandleWrap::GetConstructorTemplate(env)); - env->SetProtoMethod(t, "start", StatWatcher::Start); + SetProtoMethod(isolate, t, "start", StatWatcher::Start); - env->SetConstructorFunction(target, "StatWatcher", t); + SetConstructorFunction(env->context(), target, "StatWatcher", t); } void StatWatcher::RegisterExternalReferences( diff --git a/src/node_task_queue.cc b/src/node_task_queue.cc index 9bbdb318021..2e62a072ee4 100644 --- a/src/node_task_queue.cc +++ b/src/node_task_queue.cc @@ -196,9 +196,9 @@ static void Initialize(Local<Object> target, Environment* env = Environment::GetCurrent(context); Isolate* isolate = env->isolate(); - env->SetMethod(target, "enqueueMicrotask", EnqueueMicrotask); - env->SetMethod(target, "setTickCallback", SetTickCallback); - env->SetMethod(target, "runMicrotasks", RunMicrotasks); + SetMethod(context, target, "enqueueMicrotask", EnqueueMicrotask); + SetMethod(context, target, "setTickCallback", SetTickCallback); + SetMethod(context, target, "runMicrotasks", RunMicrotasks); target->Set(env->context(), FIXED_ONE_BYTE_STRING(isolate, "tickInfo"), env->tick_info()->fields().GetJSArray()).Check(); @@ -212,9 +212,8 @@ static void Initialize(Local<Object> target, target->Set(env->context(), FIXED_ONE_BYTE_STRING(isolate, "promiseRejectEvents"), events).Check(); - env->SetMethod(target, - "setPromiseRejectCallback", - SetPromiseRejectCallback); + SetMethod( + context, target, "setPromiseRejectCallback", SetPromiseRejectCallback); } void RegisterExternalReferences(ExternalReferenceRegistry* registry) { diff --git a/src/node_trace_events.cc b/src/node_trace_events.cc index af60aff4ab7..fd277b997de 100644 --- a/src/node_trace_events.cc +++ b/src/node_trace_events.cc @@ -20,6 +20,7 @@ using v8::Context; using v8::Function; using v8::FunctionCallbackInfo; using v8::FunctionTemplate; +using v8::Isolate; using v8::Local; using v8::NewStringType; using v8::Object; @@ -124,21 +125,23 @@ void NodeCategorySet::Initialize(Local<Object> target, Local<Context> context, void* priv) { Environment* env = Environment::GetCurrent(context); + Isolate* isolate = env->isolate(); - env->SetMethod(target, "getEnabledCategories", GetEnabledCategories); - env->SetMethod( - target, "setTraceCategoryStateUpdateHandler", - SetTraceCategoryStateUpdateHandler); + SetMethod(context, target, "getEnabledCategories", GetEnabledCategories); + SetMethod(context, + target, + "setTraceCategoryStateUpdateHandler", + SetTraceCategoryStateUpdateHandler); Local<FunctionTemplate> category_set = - env->NewFunctionTemplate(NodeCategorySet::New); + NewFunctionTemplate(isolate, NodeCategorySet::New); category_set->InstanceTemplate()->SetInternalFieldCount( NodeCategorySet::kInternalFieldCount); category_set->Inherit(BaseObject::GetConstructorTemplate(env)); - env->SetProtoMethod(category_set, "enable", NodeCategorySet::Enable); - env->SetProtoMethod(category_set, "disable", NodeCategorySet::Disable); + SetProtoMethod(isolate, category_set, "enable", NodeCategorySet::Enable); + SetProtoMethod(isolate, category_set, "disable", NodeCategorySet::Disable); - env->SetConstructorFunction(target, "CategorySet", category_set); + SetConstructorFunction(context, target, "CategorySet", category_set); Local<String> isTraceCategoryEnabled = FIXED_ONE_BYTE_STRING(env->isolate(), "isTraceCategoryEnabled"); diff --git a/src/node_types.cc b/src/node_types.cc index 1889d8c3041..87550a1428b 100644 --- a/src/node_types.cc +++ b/src/node_types.cc @@ -65,16 +65,12 @@ void InitializeTypes(Local<Object> target, Local<Value> unused, Local<Context> context, void* priv) { - Environment* env = Environment::GetCurrent(context); - -#define V(type) env->SetMethodNoSideEffect(target, \ - "is" #type, \ - Is##type); +#define V(type) SetMethodNoSideEffect(context, target, "is" #type, Is##type); VALUE_METHOD_MAP(V) #undef V - env->SetMethodNoSideEffect(target, "isAnyArrayBuffer", IsAnyArrayBuffer); - env->SetMethodNoSideEffect(target, "isBoxedPrimitive", IsBoxedPrimitive); + SetMethodNoSideEffect(context, target, "isAnyArrayBuffer", IsAnyArrayBuffer); + SetMethodNoSideEffect(context, target, "isBoxedPrimitive", IsBoxedPrimitive); } } // anonymous namespace diff --git a/src/node_url.cc b/src/node_url.cc index 41e46710861..f5b17999f36 100644 --- a/src/node_url.cc +++ b/src/node_url.cc @@ -1799,12 +1799,11 @@ void Initialize(Local<Object> target, Local<Value> unused, Local<Context> context, void* priv) { - Environment* env = Environment::GetCurrent(context); - env->SetMethod(target, "parse", Parse); - env->SetMethodNoSideEffect(target, "encodeAuth", EncodeAuthSet); - env->SetMethodNoSideEffect(target, "domainToASCII", DomainToASCII); - env->SetMethodNoSideEffect(target, "domainToUnicode", DomainToUnicode); - env->SetMethod(target, "setURLConstructor", SetURLConstructor); + SetMethod(context, target, "parse", Parse); + SetMethodNoSideEffect(context, target, "encodeAuth", EncodeAuthSet); + SetMethodNoSideEffect(context, target, "domainToASCII", DomainToASCII); + SetMethodNoSideEffect(context, target, "domainToUnicode", DomainToUnicode); + SetMethod(context, target, "setURLConstructor", SetURLConstructor); #define XX(name, _) NODE_DEFINE_CONSTANT(target, name); FLAGS(XX) diff --git a/src/node_util.cc b/src/node_util.cc index 5b5dab36f08..1613a276c58 100644 --- a/src/node_util.cc +++ b/src/node_util.cc @@ -347,6 +347,7 @@ void Initialize(Local<Object> target, Local<Context> context, void* priv) { Environment* env = Environment::GetCurrent(context); + Isolate* isolate = env->isolate(); #define V(name, _) \ target->Set(context, \ @@ -368,18 +369,21 @@ void Initialize(Local<Object> target, V(kRejected); #undef V - env->SetMethodNoSideEffect(target, "getHiddenValue", GetHiddenValue); - env->SetMethod(target, "setHiddenValue", SetHiddenValue); - env->SetMethodNoSideEffect(target, "getPromiseDetails", GetPromiseDetails); - env->SetMethodNoSideEffect(target, "getProxyDetails", GetProxyDetails); - env->SetMethodNoSideEffect(target, "previewEntries", PreviewEntries); - env->SetMethodNoSideEffect(target, "getOwnNonIndexProperties", - GetOwnNonIndexProperties); - env->SetMethodNoSideEffect(target, "getConstructorName", GetConstructorName); - env->SetMethodNoSideEffect(target, "getExternalValue", GetExternalValue); - env->SetMethod(target, "sleep", Sleep); - - env->SetMethod(target, "arrayBufferViewHasBuffer", ArrayBufferViewHasBuffer); + SetMethodNoSideEffect(context, target, "getHiddenValue", GetHiddenValue); + SetMethod(context, target, "setHiddenValue", SetHiddenValue); + SetMethodNoSideEffect( + context, target, "getPromiseDetails", GetPromiseDetails); + SetMethodNoSideEffect(context, target, "getProxyDetails", GetProxyDetails); + SetMethodNoSideEffect(context, target, "previewEntries", PreviewEntries); + SetMethodNoSideEffect( + context, target, "getOwnNonIndexProperties", GetOwnNonIndexProperties); + SetMethodNoSideEffect( + context, target, "getConstructorName", GetConstructorName); + SetMethodNoSideEffect(context, target, "getExternalValue", GetExternalValue); + SetMethod(context, target, "sleep", Sleep); + + SetMethod( + context, target, "arrayBufferViewHasBuffer", ArrayBufferViewHasBuffer); Local<Object> constants = Object::New(env->isolate()); NODE_DEFINE_CONSTANT(constants, ALL_PROPERTIES); NODE_DEFINE_CONSTANT(constants, ONLY_WRITABLE); @@ -394,24 +398,24 @@ void Initialize(Local<Object> target, Local<String> should_abort_on_uncaught_toggle = FIXED_ONE_BYTE_STRING(env->isolate(), "shouldAbortOnUncaughtToggle"); CHECK(target - ->Set(env->context(), + ->Set(context, should_abort_on_uncaught_toggle, env->should_abort_on_uncaught_toggle().GetJSArray()) .FromJust()); Local<FunctionTemplate> weak_ref = - env->NewFunctionTemplate(WeakReference::New); + NewFunctionTemplate(isolate, WeakReference::New); weak_ref->InstanceTemplate()->SetInternalFieldCount( WeakReference::kInternalFieldCount); weak_ref->Inherit(BaseObject::GetConstructorTemplate(env)); - env->SetProtoMethod(weak_ref, "get", WeakReference::Get); - env->SetProtoMethod(weak_ref, "incRef", WeakReference::IncRef); - env->SetProtoMethod(weak_ref, "decRef", WeakReference::DecRef); - env->SetConstructorFunction(target, "WeakReference", weak_ref); + SetProtoMethod(isolate, weak_ref, "get", WeakReference::Get); + SetProtoMethod(isolate, weak_ref, "incRef", WeakReference::IncRef); + SetProtoMethod(isolate, weak_ref, "decRef", WeakReference::DecRef); + SetConstructorFunction(context, target, "WeakReference", weak_ref); - env->SetMethod(target, "guessHandleType", GuessHandleType); + SetMethod(context, target, "guessHandleType", GuessHandleType); - env->SetMethodNoSideEffect(target, "toUSVString", ToUSVString); + SetMethodNoSideEffect(context, target, "toUSVString", ToUSVString); } } // namespace util diff --git a/src/node_v8.cc b/src/node_v8.cc index cf7a494b7c7..5a1346a904e 100644 --- a/src/node_v8.cc +++ b/src/node_v8.cc @@ -206,13 +206,17 @@ void Initialize(Local<Object> target, env->AddBindingData<BindingData>(context, target); if (binding_data == nullptr) return; - env->SetMethodNoSideEffect(target, "cachedDataVersionTag", - CachedDataVersionTag); - env->SetMethod( - target, "updateHeapStatisticsBuffer", UpdateHeapStatisticsBuffer); - - env->SetMethod( - target, "updateHeapCodeStatisticsBuffer", UpdateHeapCodeStatisticsBuffer); + SetMethodNoSideEffect( + context, target, "cachedDataVersionTag", CachedDataVersionTag); + SetMethod(context, + target, + "updateHeapStatisticsBuffer", + UpdateHeapStatisticsBuffer); + + SetMethod(context, + target, + "updateHeapCodeStatisticsBuffer", + UpdateHeapCodeStatisticsBuffer); size_t number_of_heap_spaces = env->isolate()->NumberOfHeapSpaces(); @@ -225,19 +229,21 @@ void Initialize(Local<Object> target, heap_spaces[i] = String::NewFromUtf8(env->isolate(), s.space_name()) .ToLocalChecked(); } - target->Set(env->context(), - FIXED_ONE_BYTE_STRING(env->isolate(), "kHeapSpaces"), - Array::New(env->isolate(), - heap_spaces.out(), - number_of_heap_spaces)).Check(); + target + ->Set( + context, + FIXED_ONE_BYTE_STRING(env->isolate(), "kHeapSpaces"), + Array::New(env->isolate(), heap_spaces.out(), number_of_heap_spaces)) + .Check(); - env->SetMethod(target, - "updateHeapSpaceStatisticsBuffer", - UpdateHeapSpaceStatisticsBuffer); + SetMethod(context, + target, + "updateHeapSpaceStatisticsBuffer", + UpdateHeapSpaceStatisticsBuffer); #define V(i, _, name) \ target \ - ->Set(env->context(), \ + ->Set(context, \ FIXED_ONE_BYTE_STRING(env->isolate(), #name), \ Uint32::NewFromUnsigned(env->isolate(), i)) \ .Check(); @@ -248,7 +254,7 @@ void Initialize(Local<Object> target, #undef V // Export symbols used by v8.setFlagsFromString() - env->SetMethod(target, "setFlagsFromString", SetFlagsFromString); + SetMethod(context, target, "setFlagsFromString", SetFlagsFromString); } void RegisterExternalReferences(ExternalReferenceRegistry* registry) { diff --git a/src/node_wasi.cc b/src/node_wasi.cc index 965a619c8d4..a1b244018a6 100644 --- a/src/node_wasi.cc +++ b/src/node_wasi.cc @@ -1668,62 +1668,67 @@ static void Initialize(Local<Object> target, Local<Context> context, void* priv) { Environment* env = Environment::GetCurrent(context); + Isolate* isolate = env->isolate(); - Local<FunctionTemplate> tmpl = env->NewFunctionTemplate(WASI::New); + Local<FunctionTemplate> tmpl = NewFunctionTemplate(isolate, WASI::New); tmpl->InstanceTemplate()->SetInternalFieldCount(WASI::kInternalFieldCount); tmpl->Inherit(BaseObject::GetConstructorTemplate(env)); - env->SetProtoMethod(tmpl, "args_get", WASI::ArgsGet); - env->SetProtoMethod(tmpl, "args_sizes_get", WASI::ArgsSizesGet); - env->SetProtoMethod(tmpl, "clock_res_get", WASI::ClockResGet); - env->SetProtoMethod(tmpl, "clock_time_get", WASI::ClockTimeGet); - env->SetProtoMethod(tmpl, "environ_get", WASI::EnvironGet); - env->SetProtoMethod(tmpl, "environ_sizes_get", WASI::EnvironSizesGet); - env->SetProtoMethod(tmpl, "fd_advise", WASI::FdAdvise); - env->SetProtoMethod(tmpl, "fd_allocate", WASI::FdAllocate); - env->SetProtoMethod(tmpl, "fd_close", WASI::FdClose); - env->SetProtoMethod(tmpl, "fd_datasync", WASI::FdDatasync); - env->SetProtoMethod(tmpl, "fd_fdstat_get", WASI::FdFdstatGet); - env->SetProtoMethod(tmpl, "fd_fdstat_set_flags", WASI::FdFdstatSetFlags); - env->SetProtoMethod(tmpl, "fd_fdstat_set_rights", WASI::FdFdstatSetRights); - env->SetProtoMethod(tmpl, "fd_filestat_get", WASI::FdFilestatGet); - env->SetProtoMethod(tmpl, "fd_filestat_set_size", WASI::FdFilestatSetSize); - env->SetProtoMethod(tmpl, "fd_filestat_set_times", WASI::FdFilestatSetTimes); - env->SetProtoMethod(tmpl, "fd_pread", WASI::FdPread); - env->SetProtoMethod(tmpl, "fd_prestat_get", WASI::FdPrestatGet); - env->SetProtoMethod(tmpl, "fd_prestat_dir_name", WASI::FdPrestatDirName); - env->SetProtoMethod(tmpl, "fd_pwrite", WASI::FdPwrite); - env->SetProtoMethod(tmpl, "fd_read", WASI::FdRead); - env->SetProtoMethod(tmpl, "fd_readdir", WASI::FdReaddir); - env->SetProtoMethod(tmpl, "fd_renumber", WASI::FdRenumber); - env->SetProtoMethod(tmpl, "fd_seek", WASI::FdSeek); - env->SetProtoMethod(tmpl, "fd_sync", WASI::FdSync); - env->SetProtoMethod(tmpl, "fd_tell", WASI::FdTell); - env->SetProtoMethod(tmpl, "fd_write", WASI::FdWrite); - env->SetProtoMethod(tmpl, "path_create_directory", WASI::PathCreateDirectory); - env->SetProtoMethod(tmpl, "path_filestat_get", WASI::PathFilestatGet); - env->SetProtoMethod(tmpl, - "path_filestat_set_times", - WASI::PathFilestatSetTimes); - env->SetProtoMethod(tmpl, "path_link", WASI::PathLink); - env->SetProtoMethod(tmpl, "path_open", WASI::PathOpen); - env->SetProtoMethod(tmpl, "path_readlink", WASI::PathReadlink); - env->SetProtoMethod(tmpl, "path_remove_directory", WASI::PathRemoveDirectory); - env->SetProtoMethod(tmpl, "path_rename", WASI::PathRename); - env->SetProtoMethod(tmpl, "path_symlink", WASI::PathSymlink); - env->SetProtoMethod(tmpl, "path_unlink_file", WASI::PathUnlinkFile); - env->SetProtoMethod(tmpl, "poll_oneoff", WASI::PollOneoff); - env->SetProtoMethod(tmpl, "proc_exit", WASI::ProcExit); - env->SetProtoMethod(tmpl, "proc_raise", WASI::ProcRaise); - env->SetProtoMethod(tmpl, "random_get", WASI::RandomGet); - env->SetProtoMethod(tmpl, "sched_yield", WASI::SchedYield); - env->SetProtoMethod(tmpl, "sock_recv", WASI::SockRecv); - env->SetProtoMethod(tmpl, "sock_send", WASI::SockSend); - env->SetProtoMethod(tmpl, "sock_shutdown", WASI::SockShutdown); - - env->SetInstanceMethod(tmpl, "_setMemory", WASI::_SetMemory); - - env->SetConstructorFunction(target, "WASI", tmpl); + SetProtoMethod(isolate, tmpl, "args_get", WASI::ArgsGet); + SetProtoMethod(isolate, tmpl, "args_sizes_get", WASI::ArgsSizesGet); + SetProtoMethod(isolate, tmpl, "clock_res_get", WASI::ClockResGet); + SetProtoMethod(isolate, tmpl, "clock_time_get", WASI::ClockTimeGet); + SetProtoMethod(isolate, tmpl, "environ_get", WASI::EnvironGet); + SetProtoMethod(isolate, tmpl, "environ_sizes_get", WASI::EnvironSizesGet); + SetProtoMethod(isolate, tmpl, "fd_advise", WASI::FdAdvise); + SetProtoMethod(isolate, tmpl, "fd_allocate", WASI::FdAllocate); + SetProtoMethod(isolate, tmpl, "fd_close", WASI::FdClose); + SetProtoMethod(isolate, tmpl, "fd_datasync", WASI::FdDatasync); + SetProtoMethod(isolate, tmpl, "fd_fdstat_get", WASI::FdFdstatGet); + SetProtoMethod(isolate, tmpl, "fd_fdstat_set_flags", WASI::FdFdstatSetFlags); + SetProtoMethod( + isolate, tmpl, "fd_fdstat_set_rights", WASI::FdFdstatSetRights); + SetProtoMethod(isolate, tmpl, "fd_filestat_get", WASI::FdFilestatGet); + SetProtoMethod( + isolate, tmpl, "fd_filestat_set_size", WASI::FdFilestatSetSize); + SetProtoMethod( + isolate, tmpl, "fd_filestat_set_times", WASI::FdFilestatSetTimes); + SetProtoMethod(isolate, tmpl, "fd_pread", WASI::FdPread); + SetProtoMethod(isolate, tmpl, "fd_prestat_get", WASI::FdPrestatGet); + SetProtoMethod(isolate, tmpl, "fd_prestat_dir_name", WASI::FdPrestatDirName); + SetProtoMethod(isolate, tmpl, "fd_pwrite", WASI::FdPwrite); + SetProtoMethod(isolate, tmpl, "fd_read", WASI::FdRead); + SetProtoMethod(isolate, tmpl, "fd_readdir", WASI::FdReaddir); + SetProtoMethod(isolate, tmpl, "fd_renumber", WASI::FdRenumber); + SetProtoMethod(isolate, tmpl, "fd_seek", WASI::FdSeek); + SetProtoMethod(isolate, tmpl, "fd_sync", WASI::FdSync); + SetProtoMethod(isolate, tmpl, "fd_tell", WASI::FdTell); + SetProtoMethod(isolate, tmpl, "fd_write", WASI::FdWrite); + SetProtoMethod( + isolate, tmpl, "path_create_directory", WASI::PathCreateDirectory); + SetProtoMethod(isolate, tmpl, "path_filestat_get", WASI::PathFilestatGet); + SetProtoMethod( + isolate, tmpl, "path_filestat_set_times", WASI::PathFilestatSetTimes); + SetProtoMethod(isolate, tmpl, "path_link", WASI::PathLink); + SetProtoMethod(isolate, tmpl, "path_open", WASI::PathOpen); + SetProtoMethod(isolate, tmpl, "path_readlink", WASI::PathReadlink); + SetProtoMethod( + isolate, tmpl, "path_remove_directory", WASI::PathRemoveDirectory); + SetProtoMethod(isolate, tmpl, "path_rename", WASI::PathRename); + SetProtoMethod(isolate, tmpl, "path_symlink", WASI::PathSymlink); + SetProtoMethod(isolate, tmpl, "path_unlink_file", WASI::PathUnlinkFile); + SetProtoMethod(isolate, tmpl, "poll_oneoff", WASI::PollOneoff); + SetProtoMethod(isolate, tmpl, "proc_exit", WASI::ProcExit); + SetProtoMethod(isolate, tmpl, "proc_raise", WASI::ProcRaise); + SetProtoMethod(isolate, tmpl, "random_get", WASI::RandomGet); + SetProtoMethod(isolate, tmpl, "sched_yield", WASI::SchedYield); + SetProtoMethod(isolate, tmpl, "sock_recv", WASI::SockRecv); + SetProtoMethod(isolate, tmpl, "sock_send", WASI::SockSend); + SetProtoMethod(isolate, tmpl, "sock_shutdown", WASI::SockShutdown); + + SetInstanceMethod(isolate, tmpl, "_setMemory", WASI::_SetMemory); + + SetConstructorFunction(context, target, "WASI", tmpl); } diff --git a/src/node_wasm_web_api.cc b/src/node_wasm_web_api.cc index 67437034bbe..7fc423978b2 100644 --- a/src/node_wasm_web_api.cc +++ b/src/node_wasm_web_api.cc @@ -13,6 +13,7 @@ using v8::Context; using v8::Function; using v8::FunctionCallbackInfo; using v8::FunctionTemplate; +using v8::Isolate; using v8::Local; using v8::MaybeLocal; using v8::Object; @@ -25,15 +26,16 @@ Local<Function> WasmStreamingObject::Initialize(Environment* env) { return templ; } - Local<FunctionTemplate> t = env->NewFunctionTemplate(New); + Isolate* isolate = env->isolate(); + Local<FunctionTemplate> t = NewFunctionTemplate(isolate, New); t->Inherit(BaseObject::GetConstructorTemplate(env)); t->InstanceTemplate()->SetInternalFieldCount( WasmStreamingObject::kInternalFieldCount); - env->SetProtoMethod(t, "setURL", SetURL); - env->SetProtoMethod(t, "push", Push); - env->SetProtoMethod(t, "finish", Finish); - env->SetProtoMethod(t, "abort", Abort); + SetProtoMethod(isolate, t, "setURL", SetURL); + SetProtoMethod(isolate, t, "push", Push); + SetProtoMethod(isolate, t, "finish", Finish); + SetProtoMethod(isolate, t, "abort", Abort); auto function = t->GetFunction(env->context()).ToLocalChecked(); env->set_wasm_streaming_object_constructor(function); @@ -194,8 +196,7 @@ void Initialize(Local<Object> target, Local<Value>, Local<Context> context, void*) { - Environment* env = Environment::GetCurrent(context); - env->SetMethod(target, "setImplementation", SetImplementation); + SetMethod(context, target, "setImplementation", SetImplementation); } void RegisterExternalReferences(ExternalReferenceRegistry* registry) { diff --git a/src/node_watchdog.cc b/src/node_watchdog.cc index 31c8f744a3b..7062d4aa661 100644 --- a/src/node_watchdog.cc +++ b/src/node_watchdog.cc @@ -34,6 +34,7 @@ namespace node { using v8::Context; using v8::FunctionCallbackInfo; using v8::FunctionTemplate; +using v8::Isolate; using v8::Local; using v8::Object; using v8::Value; @@ -123,15 +124,17 @@ SignalPropagation SigintWatchdog::HandleSigint() { } void TraceSigintWatchdog::Init(Environment* env, Local<Object> target) { - Local<FunctionTemplate> constructor = env->NewFunctionTemplate(New); + Isolate* isolate = env->isolate(); + Local<FunctionTemplate> constructor = NewFunctionTemplate(isolate, New); constructor->InstanceTemplate()->SetInternalFieldCount( TraceSigintWatchdog::kInternalFieldCount); constructor->Inherit(HandleWrap::GetConstructorTemplate(env)); - env->SetProtoMethod(constructor, "start", Start); - env->SetProtoMethod(constructor, "stop", Stop); + SetProtoMethod(isolate, constructor, "start", Start); + SetProtoMethod(isolate, constructor, "stop", Stop); - env->SetConstructorFunction(target, "TraceSigintWatchdog", constructor); + SetConstructorFunction( + env->context(), target, "TraceSigintWatchdog", constructor); } void TraceSigintWatchdog::New(const FunctionCallbackInfo<Value>& args) { diff --git a/src/node_worker.cc b/src/node_worker.cc index c70ccd6bd43..6c5ab615c80 100644 --- a/src/node_worker.cc +++ b/src/node_worker.cc @@ -839,65 +839,66 @@ void InitWorker(Local<Object> target, Local<Context> context, void* priv) { Environment* env = Environment::GetCurrent(context); + Isolate* isolate = env->isolate(); { - Local<FunctionTemplate> w = env->NewFunctionTemplate(Worker::New); + Local<FunctionTemplate> w = NewFunctionTemplate(isolate, Worker::New); w->InstanceTemplate()->SetInternalFieldCount( Worker::kInternalFieldCount); w->Inherit(AsyncWrap::GetConstructorTemplate(env)); - env->SetProtoMethod(w, "startThread", Worker::StartThread); - env->SetProtoMethod(w, "stopThread", Worker::StopThread); - env->SetProtoMethod(w, "hasRef", Worker::HasRef); - env->SetProtoMethod(w, "ref", Worker::Ref); - env->SetProtoMethod(w, "unref", Worker::Unref); - env->SetProtoMethod(w, "getResourceLimits", Worker::GetResourceLimits); - env->SetProtoMethod(w, "takeHeapSnapshot", Worker::TakeHeapSnapshot); - env->SetProtoMethod(w, "loopIdleTime", Worker::LoopIdleTime); - env->SetProtoMethod(w, "loopStartTime", Worker::LoopStartTime); - - env->SetConstructorFunction(target, "Worker", w); + SetProtoMethod(isolate, w, "startThread", Worker::StartThread); + SetProtoMethod(isolate, w, "stopThread", Worker::StopThread); + SetProtoMethod(isolate, w, "hasRef", Worker::HasRef); + SetProtoMethod(isolate, w, "ref", Worker::Ref); + SetProtoMethod(isolate, w, "unref", Worker::Unref); + SetProtoMethod(isolate, w, "getResourceLimits", Worker::GetResourceLimits); + SetProtoMethod(isolate, w, "takeHeapSnapshot", Worker::TakeHeapSnapshot); + SetProtoMethod(isolate, w, "loopIdleTime", Worker::LoopIdleTime); + SetProtoMethod(isolate, w, "loopStartTime", Worker::LoopStartTime); + + SetConstructorFunction(context, target, "Worker", w); } { - Local<FunctionTemplate> wst = FunctionTemplate::New(env->isolate()); + Local<FunctionTemplate> wst = NewFunctionTemplate(isolate, nullptr); wst->InstanceTemplate()->SetInternalFieldCount( WorkerHeapSnapshotTaker::kInternalFieldCount); wst->Inherit(AsyncWrap::GetConstructorTemplate(env)); Local<String> wst_string = - FIXED_ONE_BYTE_STRING(env->isolate(), "WorkerHeapSnapshotTaker"); + FIXED_ONE_BYTE_STRING(isolate, "WorkerHeapSnapshotTaker"); wst->SetClassName(wst_string); env->set_worker_heap_snapshot_taker_template(wst->InstanceTemplate()); } - env->SetMethod(target, "getEnvMessagePort", GetEnvMessagePort); + SetMethod(context, target, "getEnvMessagePort", GetEnvMessagePort); target ->Set(env->context(), env->thread_id_string(), - Number::New(env->isolate(), static_cast<double>(env->thread_id()))) + Number::New(isolate, static_cast<double>(env->thread_id()))) .Check(); target ->Set(env->context(), - FIXED_ONE_BYTE_STRING(env->isolate(), "isMainThread"), - Boolean::New(env->isolate(), env->is_main_thread())) + FIXED_ONE_BYTE_STRING(isolate, "isMainThread"), + Boolean::New(isolate, env->is_main_thread())) .Check(); target ->Set(env->context(), - FIXED_ONE_BYTE_STRING(env->isolate(), "ownsProcessState"), - Boolean::New(env->isolate(), env->owns_process_state())) + FIXED_ONE_BYTE_STRING(isolate, "ownsProcessState"), + Boolean::New(isolate, env->owns_process_state())) .Check(); if (!env->is_main_thread()) { target ->Set(env->context(), - FIXED_ONE_BYTE_STRING(env->isolate(), "resourceLimits"), - env->worker_context()->GetResourceLimits(env->isolate())) + FIXED_ONE_BYTE_STRING(isolate, "resourceLimits"), + env->worker_context()->GetResourceLimits(isolate)) .Check(); } diff --git a/src/node_zlib.cc b/src/node_zlib.cc index 5930ffd7a8a..e2433d887b4 100644 --- a/src/node_zlib.cc +++ b/src/node_zlib.cc @@ -52,6 +52,7 @@ using v8::FunctionTemplate; using v8::HandleScope; using v8::Int32; using v8::Integer; +using v8::Isolate; using v8::Local; using v8::Object; using v8::Uint32Array; @@ -1256,21 +1257,22 @@ CompressionError BrotliDecoderContext::GetErrorInfo() const { template <typename Stream> struct MakeClass { static void Make(Environment* env, Local<Object> target, const char* name) { - Local<FunctionTemplate> z = env->NewFunctionTemplate(Stream::New); + Isolate* isolate = env->isolate(); + Local<FunctionTemplate> z = NewFunctionTemplate(isolate, Stream::New); z->InstanceTemplate()->SetInternalFieldCount( Stream::kInternalFieldCount); z->Inherit(AsyncWrap::GetConstructorTemplate(env)); - env->SetProtoMethod(z, "write", Stream::template Write<true>); - env->SetProtoMethod(z, "writeSync", Stream::template Write<false>); - env->SetProtoMethod(z, "close", Stream::Close); + SetProtoMethod(isolate, z, "write", Stream::template Write<true>); + SetProtoMethod(isolate, z, "writeSync", Stream::template Write<false>); + SetProtoMethod(isolate, z, "close", Stream::Close); - env->SetProtoMethod(z, "init", Stream::Init); - env->SetProtoMethod(z, "params", Stream::Params); - env->SetProtoMethod(z, "reset", Stream::Reset); + SetProtoMethod(isolate, z, "init", Stream::Init); + SetProtoMethod(isolate, z, "params", Stream::Params); + SetProtoMethod(isolate, z, "reset", Stream::Reset); - env->SetConstructorFunction(target, name, z); + SetConstructorFunction(env->context(), target, name, z); } static void Make(ExternalReferenceRegistry* registry) { diff --git a/src/pipe_wrap.cc b/src/pipe_wrap.cc index 85daf4a1e61..4f1bfda569f 100644 --- a/src/pipe_wrap.cc +++ b/src/pipe_wrap.cc @@ -41,6 +41,7 @@ using v8::Function; using v8::FunctionCallbackInfo; using v8::FunctionTemplate; using v8::Int32; +using v8::Isolate; using v8::Local; using v8::MaybeLocal; using v8::Object; @@ -67,31 +68,32 @@ void PipeWrap::Initialize(Local<Object> target, Local<Context> context, void* priv) { Environment* env = Environment::GetCurrent(context); + Isolate* isolate = env->isolate(); - Local<FunctionTemplate> t = env->NewFunctionTemplate(New); + Local<FunctionTemplate> t = NewFunctionTemplate(isolate, New); t->InstanceTemplate() ->SetInternalFieldCount(StreamBase::kInternalFieldCount); t->Inherit(LibuvStreamWrap::GetConstructorTemplate(env)); - env->SetProtoMethod(t, "bind", Bind); - env->SetProtoMethod(t, "listen", Listen); - env->SetProtoMethod(t, "connect", Connect); - env->SetProtoMethod(t, "open", Open); + SetProtoMethod(isolate, t, "bind", Bind); + SetProtoMethod(isolate, t, "listen", Listen); + SetProtoMethod(isolate, t, "connect", Connect); + SetProtoMethod(isolate, t, "open", Open); #ifdef _WIN32 - env->SetProtoMethod(t, "setPendingInstances", SetPendingInstances); + SetProtoMethod(isolate, t, "setPendingInstances", SetPendingInstances); #endif - env->SetProtoMethod(t, "fchmod", Fchmod); + SetProtoMethod(isolate, t, "fchmod", Fchmod); - env->SetConstructorFunction(target, "Pipe", t); + SetConstructorFunction(context, target, "Pipe", t); env->set_pipe_constructor_template(t); // Create FunctionTemplate for PipeConnectWrap. auto cwt = BaseObject::MakeLazilyInitializedJSTemplate(env); cwt->Inherit(AsyncWrap::GetConstructorTemplate(env)); - env->SetConstructorFunction(target, "PipeConnectWrap", cwt); + SetConstructorFunction(context, target, "PipeConnectWrap", cwt); // Define constants Local<Object> constants = Object::New(env->isolate()); diff --git a/src/process_wrap.cc b/src/process_wrap.cc index 6905cacb1c8..3a55048ef79 100644 --- a/src/process_wrap.cc +++ b/src/process_wrap.cc @@ -36,6 +36,7 @@ using v8::FunctionTemplate; using v8::HandleScope; using v8::Int32; using v8::Integer; +using v8::Isolate; using v8::Local; using v8::Number; using v8::Object; @@ -51,16 +52,17 @@ class ProcessWrap : public HandleWrap { Local<Context> context, void* priv) { Environment* env = Environment::GetCurrent(context); - Local<FunctionTemplate> constructor = env->NewFunctionTemplate(New); + Isolate* isolate = env->isolate(); + Local<FunctionTemplate> constructor = NewFunctionTemplate(isolate, New); constructor->InstanceTemplate()->SetInternalFieldCount( ProcessWrap::kInternalFieldCount); constructor->Inherit(HandleWrap::GetConstructorTemplate(env)); - env->SetProtoMethod(constructor, "spawn", Spawn); - env->SetProtoMethod(constructor, "kill", Kill); + SetProtoMethod(isolate, constructor, "spawn", Spawn); + SetProtoMethod(isolate, constructor, "kill", Kill); - env->SetConstructorFunction(target, "Process", constructor); + SetConstructorFunction(context, target, "Process", constructor); } SET_NO_MEMORY_INFO() diff --git a/src/signal_wrap.cc b/src/signal_wrap.cc index df7f94eeec8..d5dfdd51da6 100644 --- a/src/signal_wrap.cc +++ b/src/signal_wrap.cc @@ -34,6 +34,7 @@ using v8::FunctionCallbackInfo; using v8::FunctionTemplate; using v8::HandleScope; using v8::Integer; +using v8::Isolate; using v8::Local; using v8::Object; using v8::Value; @@ -52,15 +53,16 @@ class SignalWrap : public HandleWrap { Local<Context> context, void* priv) { Environment* env = Environment::GetCurrent(context); - Local<FunctionTemplate> constructor = env->NewFunctionTemplate(New); + Isolate* isolate = env->isolate(); + Local<FunctionTemplate> constructor = NewFunctionTemplate(isolate, New); constructor->InstanceTemplate()->SetInternalFieldCount( SignalWrap::kInternalFieldCount); constructor->Inherit(HandleWrap::GetConstructorTemplate(env)); - env->SetProtoMethod(constructor, "start", Start); - env->SetProtoMethod(constructor, "stop", Stop); + SetProtoMethod(isolate, constructor, "start", Start); + SetProtoMethod(isolate, constructor, "stop", Stop); - env->SetConstructorFunction(target, "Signal", constructor); + SetConstructorFunction(context, target, "Signal", constructor); } static void RegisterExternalReferences(ExternalReferenceRegistry* registry) { diff --git a/src/spawn_sync.cc b/src/spawn_sync.cc index afd08519d7f..2db7d82d32f 100644 --- a/src/spawn_sync.cc +++ b/src/spawn_sync.cc @@ -363,8 +363,7 @@ void SyncProcessRunner::Initialize(Local<Object> target, Local<Value> unused, Local<Context> context, void* priv) { - Environment* env = Environment::GetCurrent(context); - env->SetMethod(target, "spawn", Spawn); + SetMethod(context, target, "spawn", Spawn); } diff --git a/src/stream_base.cc b/src/stream_base.cc index 783e12a36c8..8701434c24f 100644 --- a/src/stream_base.cc +++ b/src/stream_base.cc @@ -400,21 +400,24 @@ void StreamBase::AddMethod(Environment* env, Local<FunctionTemplate> t, JSMethodFunction* stream_method, Local<String> string) { + Isolate* isolate = env->isolate(); Local<FunctionTemplate> templ = - env->NewFunctionTemplate(stream_method, - signature, - ConstructorBehavior::kThrow, - SideEffectType::kHasNoSideEffect); + NewFunctionTemplate(isolate, + stream_method, + signature, + ConstructorBehavior::kThrow, + SideEffectType::kHasNoSideEffect); t->PrototypeTemplate()->SetAccessorProperty( string, templ, Local<FunctionTemplate>(), attributes); } void StreamBase::AddMethods(Environment* env, Local<FunctionTemplate> t) { - HandleScope scope(env->isolate()); + Isolate* isolate = env->isolate(); + HandleScope scope(isolate); enum PropertyAttribute attributes = static_cast<PropertyAttribute>(ReadOnly | DontDelete | DontEnum); - Local<Signature> sig = Signature::New(env->isolate(), t); + Local<Signature> sig = Signature::New(isolate, t); AddMethod(env, sig, attributes, t, GetFD, env->fd_string()); AddMethod( @@ -422,32 +425,32 @@ void StreamBase::AddMethods(Environment* env, Local<FunctionTemplate> t) { AddMethod(env, sig, attributes, t, GetBytesRead, env->bytes_read_string()); AddMethod( env, sig, attributes, t, GetBytesWritten, env->bytes_written_string()); - env->SetProtoMethod(t, "readStart", JSMethod<&StreamBase::ReadStartJS>); - env->SetProtoMethod(t, "readStop", JSMethod<&StreamBase::ReadStopJS>); - env->SetProtoMethod(t, "shutdown", JSMethod<&StreamBase::Shutdown>); - env->SetProtoMethod(t, - "useUserBuffer", - JSMethod<&StreamBase::UseUserBuffer>); - env->SetProtoMethod(t, "writev", JSMethod<&StreamBase::Writev>); - env->SetProtoMethod(t, "writeBuffer", JSMethod<&StreamBase::WriteBuffer>); - env->SetProtoMethod( - t, "writeAsciiString", JSMethod<&StreamBase::WriteString<ASCII>>); - env->SetProtoMethod( - t, "writeUtf8String", JSMethod<&StreamBase::WriteString<UTF8>>); - env->SetProtoMethod( - t, "writeUcs2String", JSMethod<&StreamBase::WriteString<UCS2>>); - env->SetProtoMethod( - t, "writeLatin1String", JSMethod<&StreamBase::WriteString<LATIN1>>); - t->PrototypeTemplate()->Set(FIXED_ONE_BYTE_STRING(env->isolate(), - "isStreamBase"), - True(env->isolate())); + SetProtoMethod(isolate, t, "readStart", JSMethod<&StreamBase::ReadStartJS>); + SetProtoMethod(isolate, t, "readStop", JSMethod<&StreamBase::ReadStopJS>); + SetProtoMethod(isolate, t, "shutdown", JSMethod<&StreamBase::Shutdown>); + SetProtoMethod( + isolate, t, "useUserBuffer", JSMethod<&StreamBase::UseUserBuffer>); + SetProtoMethod(isolate, t, "writev", JSMethod<&StreamBase::Writev>); + SetProtoMethod(isolate, t, "writeBuffer", JSMethod<&StreamBase::WriteBuffer>); + SetProtoMethod(isolate, + t, + "writeAsciiString", + JSMethod<&StreamBase::WriteString<ASCII>>); + SetProtoMethod( + isolate, t, "writeUtf8String", JSMethod<&StreamBase::WriteString<UTF8>>); + SetProtoMethod( + isolate, t, "writeUcs2String", JSMethod<&StreamBase::WriteString<UCS2>>); + SetProtoMethod(isolate, + t, + "writeLatin1String", + JSMethod<&StreamBase::WriteString<LATIN1>>); + t->PrototypeTemplate()->Set(FIXED_ONE_BYTE_STRING(isolate, "isStreamBase"), + True(isolate)); t->PrototypeTemplate()->SetAccessor( - FIXED_ONE_BYTE_STRING(env->isolate(), "onread"), - BaseObject::InternalFieldGet< - StreamBase::kOnReadFunctionField>, - BaseObject::InternalFieldSet< - StreamBase::kOnReadFunctionField, - &Value::IsFunction>); + FIXED_ONE_BYTE_STRING(isolate, "onread"), + BaseObject::InternalFieldGet<StreamBase::kOnReadFunctionField>, + BaseObject::InternalFieldSet<StreamBase::kOnReadFunctionField, + &Value::IsFunction>); } void StreamBase::RegisterExternalReferences( diff --git a/src/stream_pipe.cc b/src/stream_pipe.cc index 93b7ffeca9c..7d4be978a11 100644 --- a/src/stream_pipe.cc +++ b/src/stream_pipe.cc @@ -11,6 +11,7 @@ using v8::Function; using v8::FunctionCallbackInfo; using v8::FunctionTemplate; using v8::HandleScope; +using v8::Isolate; using v8::Just; using v8::Local; using v8::Maybe; @@ -313,17 +314,18 @@ void InitializeStreamPipe(Local<Object> target, Local<Context> context, void* priv) { Environment* env = Environment::GetCurrent(context); + Isolate* isolate = env->isolate(); // Create FunctionTemplate for FileHandle::CloseReq - Local<FunctionTemplate> pipe = env->NewFunctionTemplate(StreamPipe::New); - env->SetProtoMethod(pipe, "unpipe", StreamPipe::Unpipe); - env->SetProtoMethod(pipe, "start", StreamPipe::Start); - env->SetProtoMethod(pipe, "isClosed", StreamPipe::IsClosed); - env->SetProtoMethod(pipe, "pendingWrites", StreamPipe::PendingWrites); + Local<FunctionTemplate> pipe = NewFunctionTemplate(isolate, StreamPipe::New); + SetProtoMethod(isolate, pipe, "unpipe", StreamPipe::Unpipe); + SetProtoMethod(isolate, pipe, "start", StreamPipe::Start); + SetProtoMethod(isolate, pipe, "isClosed", StreamPipe::IsClosed); + SetProtoMethod(isolate, pipe, "pendingWrites", StreamPipe::PendingWrites); pipe->Inherit(AsyncWrap::GetConstructorTemplate(env)); pipe->InstanceTemplate()->SetInternalFieldCount( StreamPipe::kInternalFieldCount); - env->SetConstructorFunction(target, "StreamPipe", pipe); + SetConstructorFunction(context, target, "StreamPipe", pipe); } } // anonymous namespace diff --git a/src/stream_wrap.cc b/src/stream_wrap.cc index d0c5664adcd..88f0bce66ad 100644 --- a/src/stream_wrap.cc +++ b/src/stream_wrap.cc @@ -46,6 +46,7 @@ using v8::EscapableHandleScope; using v8::FunctionCallbackInfo; using v8::FunctionTemplate; using v8::HandleScope; +using v8::Isolate; using v8::JustVoid; using v8::Local; using v8::Maybe; @@ -67,9 +68,10 @@ void LibuvStreamWrap::Initialize(Local<Object> target, Local<Context> context, void* priv) { Environment* env = Environment::GetCurrent(context); + Isolate* isolate = env->isolate(); Local<FunctionTemplate> sw = - FunctionTemplate::New(env->isolate(), IsConstructCallCallback); + NewFunctionTemplate(isolate, IsConstructCallCallback); sw->InstanceTemplate()->SetInternalFieldCount(StreamReq::kInternalFieldCount); // we need to set handle and callback to null, @@ -79,33 +81,34 @@ void LibuvStreamWrap::Initialize(Local<Object> target, // - oncomplete // - callback // - handle - sw->InstanceTemplate()->Set( - env->oncomplete_string(), - v8::Null(env->isolate())); - sw->InstanceTemplate()->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "callback"), - v8::Null(env->isolate())); - sw->InstanceTemplate()->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "handle"), - v8::Null(env->isolate())); + sw->InstanceTemplate()->Set(env->oncomplete_string(), v8::Null(isolate)); + sw->InstanceTemplate()->Set(FIXED_ONE_BYTE_STRING(isolate, "callback"), + v8::Null(isolate)); + sw->InstanceTemplate()->Set(FIXED_ONE_BYTE_STRING(isolate, "handle"), + v8::Null(isolate)); sw->Inherit(AsyncWrap::GetConstructorTemplate(env)); - env->SetConstructorFunction(target, "ShutdownWrap", sw); + SetConstructorFunction(context, target, "ShutdownWrap", sw); env->set_shutdown_wrap_template(sw->InstanceTemplate()); Local<FunctionTemplate> ww = - FunctionTemplate::New(env->isolate(), IsConstructCallCallback); + FunctionTemplate::New(isolate, IsConstructCallCallback); ww->InstanceTemplate()->SetInternalFieldCount( StreamReq::kInternalFieldCount); ww->Inherit(AsyncWrap::GetConstructorTemplate(env)); - env->SetConstructorFunction(target, "WriteWrap", ww); + SetConstructorFunction(context, target, "WriteWrap", ww); env->set_write_wrap_template(ww->InstanceTemplate()); NODE_DEFINE_CONSTANT(target, kReadBytesOrError); NODE_DEFINE_CONSTANT(target, kArrayBufferOffset); NODE_DEFINE_CONSTANT(target, kBytesWritten); NODE_DEFINE_CONSTANT(target, kLastWriteWasAsync); - target->Set(context, FIXED_ONE_BYTE_STRING(env->isolate(), "streamBaseState"), - env->stream_base_state().GetJSArray()).Check(); + target + ->Set(context, + FIXED_ONE_BYTE_STRING(isolate, "streamBaseState"), + env->stream_base_state().GetJSArray()) + .Check(); } void LibuvStreamWrap::RegisterExternalReferences( @@ -134,23 +137,23 @@ Local<FunctionTemplate> LibuvStreamWrap::GetConstructorTemplate( Environment* env) { Local<FunctionTemplate> tmpl = env->libuv_stream_wrap_ctor_template(); if (tmpl.IsEmpty()) { - tmpl = env->NewFunctionTemplate(nullptr); - tmpl->SetClassName( - FIXED_ONE_BYTE_STRING(env->isolate(), "LibuvStreamWrap")); + Isolate* isolate = env->isolate(); + tmpl = NewFunctionTemplate(isolate, nullptr); + tmpl->SetClassName(FIXED_ONE_BYTE_STRING(isolate, "LibuvStreamWrap")); tmpl->Inherit(HandleWrap::GetConstructorTemplate(env)); tmpl->InstanceTemplate()->SetInternalFieldCount( StreamBase::kInternalFieldCount); Local<FunctionTemplate> get_write_queue_size = - FunctionTemplate::New(env->isolate(), + FunctionTemplate::New(isolate, GetWriteQueueSize, Local<Value>(), - Signature::New(env->isolate(), tmpl)); + Signature::New(isolate, tmpl)); tmpl->PrototypeTemplate()->SetAccessorProperty( env->write_queue_size_string(), get_write_queue_size, Local<FunctionTemplate>(), static_cast<PropertyAttribute>(ReadOnly | DontDelete)); - env->SetProtoMethod(tmpl, "setBlocking", SetBlocking); + SetProtoMethod(isolate, tmpl, "setBlocking", SetBlocking); StreamBase::AddMethods(env, tmpl); env->set_libuv_stream_wrap_ctor_template(tmpl); } diff --git a/src/string_decoder.cc b/src/string_decoder.cc index a915f5744f3..b447474c09f 100644 --- a/src/string_decoder.cc +++ b/src/string_decoder.cc @@ -328,8 +328,8 @@ void InitializeStringDecoder(Local<Object> target, FIXED_ONE_BYTE_STRING(isolate, "kSize"), Integer::New(isolate, sizeof(StringDecoder))).Check(); - env->SetMethod(target, "decode", DecodeData); - env->SetMethod(target, "flush", FlushData); + SetMethod(context, target, "decode", DecodeData); + SetMethod(context, target, "flush", FlushData); } } // anonymous namespace diff --git a/src/tcp_wrap.cc b/src/tcp_wrap.cc index 53ecfd2b7ab..eda5aedf5a1 100644 --- a/src/tcp_wrap.cc +++ b/src/tcp_wrap.cc @@ -45,6 +45,7 @@ using v8::FunctionCallbackInfo; using v8::FunctionTemplate; using v8::Int32; using v8::Integer; +using v8::Isolate; using v8::Local; using v8::MaybeLocal; using v8::Object; @@ -73,8 +74,9 @@ void TCPWrap::Initialize(Local<Object> target, Local<Context> context, void* priv) { Environment* env = Environment::GetCurrent(context); + Isolate* isolate = env->isolate(); - Local<FunctionTemplate> t = env->NewFunctionTemplate(New); + Local<FunctionTemplate> t = NewFunctionTemplate(isolate, New); t->InstanceTemplate()->SetInternalFieldCount(StreamBase::kInternalFieldCount); // Init properties @@ -85,32 +87,36 @@ void TCPWrap::Initialize(Local<Object> target, t->Inherit(LibuvStreamWrap::GetConstructorTemplate(env)); - env->SetProtoMethod(t, "open", Open); - env->SetProtoMethod(t, "bind", Bind); - env->SetProtoMethod(t, "listen", Listen); - env->SetProtoMethod(t, "connect", Connect); - env->SetProtoMethod(t, "bind6", Bind6); - env->SetProtoMethod(t, "connect6", Connect6); - env->SetProtoMethod(t, "getsockname", - GetSockOrPeerName<TCPWrap, uv_tcp_getsockname>); - env->SetProtoMethod(t, "getpeername", - GetSockOrPeerName<TCPWrap, uv_tcp_getpeername>); - env->SetProtoMethod(t, "setNoDelay", SetNoDelay); - env->SetProtoMethod(t, "setKeepAlive", SetKeepAlive); - env->SetProtoMethod(t, "reset", Reset); + SetProtoMethod(isolate, t, "open", Open); + SetProtoMethod(isolate, t, "bind", Bind); + SetProtoMethod(isolate, t, "listen", Listen); + SetProtoMethod(isolate, t, "connect", Connect); + SetProtoMethod(isolate, t, "bind6", Bind6); + SetProtoMethod(isolate, t, "connect6", Connect6); + SetProtoMethod(isolate, + t, + "getsockname", + GetSockOrPeerName<TCPWrap, uv_tcp_getsockname>); + SetProtoMethod(isolate, + t, + "getpeername", + GetSockOrPeerName<TCPWrap, uv_tcp_getpeername>); + SetProtoMethod(isolate, t, "setNoDelay", SetNoDelay); + SetProtoMethod(isolate, t, "setKeepAlive", SetKeepAlive); + SetProtoMethod(isolate, t, "reset", Reset); #ifdef _WIN32 - env->SetProtoMethod(t, "setSimultaneousAccepts", SetSimultaneousAccepts); + SetProtoMethod(isolate, t, "setSimultaneousAccepts", SetSimultaneousAccepts); #endif - env->SetConstructorFunction(target, "TCP", t); + SetConstructorFunction(context, target, "TCP", t); env->set_tcp_constructor_template(t); // Create FunctionTemplate for TCPConnectWrap. Local<FunctionTemplate> cwt = BaseObject::MakeLazilyInitializedJSTemplate(env); cwt->Inherit(AsyncWrap::GetConstructorTemplate(env)); - env->SetConstructorFunction(target, "TCPConnectWrap", cwt); + SetConstructorFunction(context, target, "TCPConnectWrap", cwt); // Define constants Local<Object> constants = Object::New(env->isolate()); diff --git a/src/timers.cc b/src/timers.cc index 5014f2c66a5..2ecfd25f7ee 100644 --- a/src/timers.cc +++ b/src/timers.cc @@ -48,15 +48,17 @@ void Initialize(Local<Object> target, void* priv) { Environment* env = Environment::GetCurrent(context); - env->SetMethod(target, "getLibuvNow", GetLibuvNow); - env->SetMethod(target, "setupTimers", SetupTimers); - env->SetMethod(target, "scheduleTimer", ScheduleTimer); - env->SetMethod(target, "toggleTimerRef", ToggleTimerRef); - env->SetMethod(target, "toggleImmediateRef", ToggleImmediateRef); + SetMethod(context, target, "getLibuvNow", GetLibuvNow); + SetMethod(context, target, "setupTimers", SetupTimers); + SetMethod(context, target, "scheduleTimer", ScheduleTimer); + SetMethod(context, target, "toggleTimerRef", ToggleTimerRef); + SetMethod(context, target, "toggleImmediateRef", ToggleImmediateRef); - target->Set(env->context(), - FIXED_ONE_BYTE_STRING(env->isolate(), "immediateInfo"), - env->immediate_info()->fields().GetJSArray()).Check(); + target + ->Set(context, + FIXED_ONE_BYTE_STRING(env->isolate(), "immediateInfo"), + env->immediate_info()->fields().GetJSArray()) + .Check(); } } // anonymous namespace void RegisterTimerExternalReferences(ExternalReferenceRegistry* registry) { diff --git a/src/tty_wrap.cc b/src/tty_wrap.cc index ca8c9356afe..fff42c35900 100644 --- a/src/tty_wrap.cc +++ b/src/tty_wrap.cc @@ -36,6 +36,7 @@ using v8::Context; using v8::FunctionCallbackInfo; using v8::FunctionTemplate; using v8::Integer; +using v8::Isolate; using v8::Local; using v8::Object; using v8::String; @@ -53,22 +54,24 @@ void TTYWrap::Initialize(Local<Object> target, Local<Context> context, void* priv) { Environment* env = Environment::GetCurrent(context); + Isolate* isolate = env->isolate(); Local<String> ttyString = FIXED_ONE_BYTE_STRING(env->isolate(), "TTY"); - Local<FunctionTemplate> t = env->NewFunctionTemplate(New); + Local<FunctionTemplate> t = NewFunctionTemplate(isolate, New); t->SetClassName(ttyString); t->InstanceTemplate()->SetInternalFieldCount(StreamBase::kInternalFieldCount); t->Inherit(LibuvStreamWrap::GetConstructorTemplate(env)); - env->SetProtoMethodNoSideEffect(t, "getWindowSize", TTYWrap::GetWindowSize); - env->SetProtoMethod(t, "setRawMode", SetRawMode); + SetProtoMethodNoSideEffect( + isolate, t, "getWindowSize", TTYWrap::GetWindowSize); + SetProtoMethod(isolate, t, "setRawMode", SetRawMode); - env->SetMethodNoSideEffect(target, "isTTY", IsTTY); + SetMethodNoSideEffect(context, target, "isTTY", IsTTY); Local<Value> func; - if (t->GetFunction(env->context()).ToLocal(&func) && - target->Set(env->context(), ttyString, func).IsJust()) { + if (t->GetFunction(context).ToLocal(&func) && + target->Set(context, ttyString, func).IsJust()) { env->set_tty_constructor_template(t); } } diff --git a/src/udp_wrap.cc b/src/udp_wrap.cc index 127a1a6e5d8..a6911e2e921 100644 --- a/src/udp_wrap.cc +++ b/src/udp_wrap.cc @@ -110,8 +110,8 @@ UDPWrapBase* UDPWrapBase::FromObject(Local<Object> obj) { } void UDPWrapBase::AddMethods(Environment* env, Local<FunctionTemplate> t) { - env->SetProtoMethod(t, "recvStart", RecvStart); - env->SetProtoMethod(t, "recvStop", RecvStop); + SetProtoMethod(env->isolate(), t, "recvStart", RecvStart); + SetProtoMethod(env->isolate(), t, "recvStop", RecvStop); } UDPWrap::UDPWrap(Environment* env, Local<Object> object) @@ -134,21 +134,19 @@ void UDPWrap::Initialize(Local<Object> target, Local<Context> context, void* priv) { Environment* env = Environment::GetCurrent(context); + Isolate* isolate = env->isolate(); - Local<FunctionTemplate> t = env->NewFunctionTemplate(New); + Local<FunctionTemplate> t = NewFunctionTemplate(isolate, New); t->InstanceTemplate()->SetInternalFieldCount( UDPWrapBase::kInternalFieldCount); enum PropertyAttribute attributes = static_cast<PropertyAttribute>(ReadOnly | DontDelete); - Local<Signature> signature = Signature::New(env->isolate(), t); + Local<Signature> signature = Signature::New(isolate, t); Local<FunctionTemplate> get_fd_templ = - FunctionTemplate::New(env->isolate(), - UDPWrap::GetFD, - Local<Value>(), - signature); + FunctionTemplate::New(isolate, UDPWrap::GetFD, Local<Value>(), signature); t->PrototypeTemplate()->SetAccessorProperty(env->fd_string(), get_fd_templ, @@ -156,44 +154,47 @@ void UDPWrap::Initialize(Local<Object> target, attributes); UDPWrapBase::AddMethods(env, t); - env->SetProtoMethod(t, "open", Open); - env->SetProtoMethod(t, "bind", Bind); - env->SetProtoMethod(t, "connect", Connect); - env->SetProtoMethod(t, "send", Send); - env->SetProtoMethod(t, "bind6", Bind6); - env->SetProtoMethod(t, "connect6", Connect6); - env->SetProtoMethod(t, "send6", Send6); - env->SetProtoMethod(t, "disconnect", Disconnect); - env->SetProtoMethod(t, "getpeername", - GetSockOrPeerName<UDPWrap, uv_udp_getpeername>); - env->SetProtoMethod(t, "getsockname", - GetSockOrPeerName<UDPWrap, uv_udp_getsockname>); - env->SetProtoMethod(t, "addMembership", AddMembership); - env->SetProtoMethod(t, "dropMembership", DropMembership); - env->SetProtoMethod(t, "addSourceSpecificMembership", - AddSourceSpecificMembership); - env->SetProtoMethod(t, "dropSourceSpecificMembership", - DropSourceSpecificMembership); - env->SetProtoMethod(t, "setMulticastInterface", SetMulticastInterface); - env->SetProtoMethod(t, "setMulticastTTL", SetMulticastTTL); - env->SetProtoMethod(t, "setMulticastLoopback", SetMulticastLoopback); - env->SetProtoMethod(t, "setBroadcast", SetBroadcast); - env->SetProtoMethod(t, "setTTL", SetTTL); - env->SetProtoMethod(t, "bufferSize", BufferSize); + SetProtoMethod(isolate, t, "open", Open); + SetProtoMethod(isolate, t, "bind", Bind); + SetProtoMethod(isolate, t, "connect", Connect); + SetProtoMethod(isolate, t, "send", Send); + SetProtoMethod(isolate, t, "bind6", Bind6); + SetProtoMethod(isolate, t, "connect6", Connect6); + SetProtoMethod(isolate, t, "send6", Send6); + SetProtoMethod(isolate, t, "disconnect", Disconnect); + SetProtoMethod(isolate, + t, + "getpeername", + GetSockOrPeerName<UDPWrap, uv_udp_getpeername>); + SetProtoMethod(isolate, + t, + "getsockname", + GetSockOrPeerName<UDPWrap, uv_udp_getsockname>); + SetProtoMethod(isolate, t, "addMembership", AddMembership); + SetProtoMethod(isolate, t, "dropMembership", DropMembership); + SetProtoMethod( + isolate, t, "addSourceSpecificMembership", AddSourceSpecificMembership); + SetProtoMethod( + isolate, t, "dropSourceSpecificMembership", DropSourceSpecificMembership); + SetProtoMethod(isolate, t, "setMulticastInterface", SetMulticastInterface); + SetProtoMethod(isolate, t, "setMulticastTTL", SetMulticastTTL); + SetProtoMethod(isolate, t, "setMulticastLoopback", SetMulticastLoopback); + SetProtoMethod(isolate, t, "setBroadcast", SetBroadcast); + SetProtoMethod(isolate, t, "setTTL", SetTTL); + SetProtoMethod(isolate, t, "bufferSize", BufferSize); t->Inherit(HandleWrap::GetConstructorTemplate(env)); - env->SetConstructorFunction(target, "UDP", t); - env->set_udp_constructor_function( - t->GetFunction(env->context()).ToLocalChecked()); + SetConstructorFunction(context, target, "UDP", t); + env->set_udp_constructor_function(t->GetFunction(context).ToLocalChecked()); // Create FunctionTemplate for SendWrap Local<FunctionTemplate> swt = BaseObject::MakeLazilyInitializedJSTemplate(env); swt->Inherit(AsyncWrap::GetConstructorTemplate(env)); - env->SetConstructorFunction(target, "SendWrap", swt); + SetConstructorFunction(context, target, "SendWrap", swt); - Local<Object> constants = Object::New(env->isolate()); + Local<Object> constants = Object::New(isolate); NODE_DEFINE_CONSTANT(constants, UV_UDP_IPV6ONLY); NODE_DEFINE_CONSTANT(constants, UV_UDP_REUSEADDR); target->Set(context, diff --git a/src/util.cc b/src/util.cc index b881f9f9f88..6bbd9fd926f 100644 --- a/src/util.cc +++ b/src/util.cc @@ -317,4 +317,161 @@ std::string DiagnosticFilename::MakeFilename( return oss.str(); } +Local<v8::FunctionTemplate> NewFunctionTemplate( + v8::Isolate* isolate, + v8::FunctionCallback callback, + Local<v8::Signature> signature, + v8::ConstructorBehavior behavior, + v8::SideEffectType side_effect_type, + const v8::CFunction* c_function) { + return v8::FunctionTemplate::New(isolate, + callback, + Local<v8::Value>(), + signature, + 0, + behavior, + side_effect_type, + c_function); +} + +void SetMethod(Local<v8::Context> context, + Local<v8::Object> that, + const char* name, + v8::FunctionCallback callback) { + Isolate* isolate = context->GetIsolate(); + Local<v8::Function> function = + NewFunctionTemplate(isolate, + callback, + Local<v8::Signature>(), + v8::ConstructorBehavior::kThrow, + v8::SideEffectType::kHasSideEffect) + ->GetFunction(context) + .ToLocalChecked(); + // kInternalized strings are created in the old space. + const v8::NewStringType type = v8::NewStringType::kInternalized; + Local<v8::String> name_string = + v8::String::NewFromUtf8(isolate, name, type).ToLocalChecked(); + that->Set(context, name_string, function).Check(); + function->SetName(name_string); // NODE_SET_METHOD() compatibility. +} + +void SetFastMethod(Local<v8::Context> context, + Local<v8::Object> that, + const char* name, + v8::FunctionCallback slow_callback, + const v8::CFunction* c_function) { + Isolate* isolate = context->GetIsolate(); + Local<v8::Function> function = + NewFunctionTemplate(isolate, + slow_callback, + Local<v8::Signature>(), + v8::ConstructorBehavior::kThrow, + v8::SideEffectType::kHasNoSideEffect, + c_function) + ->GetFunction(context) + .ToLocalChecked(); + const v8::NewStringType type = v8::NewStringType::kInternalized; + Local<v8::String> name_string = + v8::String::NewFromUtf8(isolate, name, type).ToLocalChecked(); + that->Set(context, name_string, function).Check(); +} + +void SetMethodNoSideEffect(Local<v8::Context> context, + Local<v8::Object> that, + const char* name, + v8::FunctionCallback callback) { + Isolate* isolate = context->GetIsolate(); + Local<v8::Function> function = + NewFunctionTemplate(isolate, + callback, + Local<v8::Signature>(), + v8::ConstructorBehavior::kThrow, + v8::SideEffectType::kHasNoSideEffect) + ->GetFunction(context) + .ToLocalChecked(); + // kInternalized strings are created in the old space. + const v8::NewStringType type = v8::NewStringType::kInternalized; + Local<v8::String> name_string = + v8::String::NewFromUtf8(isolate, name, type).ToLocalChecked(); + that->Set(context, name_string, function).Check(); + function->SetName(name_string); // NODE_SET_METHOD() compatibility. +} + +void SetProtoMethod(v8::Isolate* isolate, + Local<v8::FunctionTemplate> that, + const char* name, + v8::FunctionCallback callback) { + Local<v8::Signature> signature = v8::Signature::New(isolate, that); + Local<v8::FunctionTemplate> t = + NewFunctionTemplate(isolate, + callback, + signature, + v8::ConstructorBehavior::kThrow, + v8::SideEffectType::kHasSideEffect); + // kInternalized strings are created in the old space. + const v8::NewStringType type = v8::NewStringType::kInternalized; + Local<v8::String> name_string = + v8::String::NewFromUtf8(isolate, name, type).ToLocalChecked(); + that->PrototypeTemplate()->Set(name_string, t); + t->SetClassName(name_string); // NODE_SET_PROTOTYPE_METHOD() compatibility. +} + +void SetProtoMethodNoSideEffect(v8::Isolate* isolate, + Local<v8::FunctionTemplate> that, + const char* name, + v8::FunctionCallback callback) { + Local<v8::Signature> signature = v8::Signature::New(isolate, that); + Local<v8::FunctionTemplate> t = + NewFunctionTemplate(isolate, + callback, + signature, + v8::ConstructorBehavior::kThrow, + v8::SideEffectType::kHasNoSideEffect); + // kInternalized strings are created in the old space. + const v8::NewStringType type = v8::NewStringType::kInternalized; + Local<v8::String> name_string = + v8::String::NewFromUtf8(isolate, name, type).ToLocalChecked(); + that->PrototypeTemplate()->Set(name_string, t); + t->SetClassName(name_string); // NODE_SET_PROTOTYPE_METHOD() compatibility. +} + +void SetInstanceMethod(v8::Isolate* isolate, + Local<v8::FunctionTemplate> that, + const char* name, + v8::FunctionCallback callback) { + Local<v8::Signature> signature = v8::Signature::New(isolate, that); + Local<v8::FunctionTemplate> t = + NewFunctionTemplate(isolate, + callback, + signature, + v8::ConstructorBehavior::kThrow, + v8::SideEffectType::kHasSideEffect); + // kInternalized strings are created in the old space. + const v8::NewStringType type = v8::NewStringType::kInternalized; + Local<v8::String> name_string = + v8::String::NewFromUtf8(isolate, name, type).ToLocalChecked(); + that->InstanceTemplate()->Set(name_string, t); + t->SetClassName(name_string); +} + +void SetConstructorFunction(Local<v8::Context> context, + Local<v8::Object> that, + const char* name, + Local<v8::FunctionTemplate> tmpl, + SetConstructorFunctionFlag flag) { + Isolate* isolate = context->GetIsolate(); + SetConstructorFunction( + context, that, OneByteString(isolate, name), tmpl, flag); +} + +void SetConstructorFunction(Local<v8::Context> context, + Local<v8::Object> that, + Local<v8::String> name, + Local<v8::FunctionTemplate> tmpl, + SetConstructorFunctionFlag flag) { + if (LIKELY(flag == SetConstructorFunctionFlag::SET_CLASS_NAME)) + tmpl->SetClassName(name); + that->Set(context, name, tmpl->GetFunction(context).ToLocalChecked()).Check(); +} + } // namespace node diff --git a/src/util.h b/src/util.h index a48071b093d..ea3ccb364bd 100644 --- a/src/util.h +++ b/src/util.h @@ -856,6 +856,66 @@ std::unique_ptr<T> static_unique_pointer_cast(std::unique_ptr<U>&& ptr) { // Returns a non-zero code if it fails to open or read the file, // aborts if it fails to close the file. int ReadFileSync(std::string* result, const char* path); + +v8::Local<v8::FunctionTemplate> NewFunctionTemplate( + v8::Isolate* isolate, + v8::FunctionCallback callback, + v8::Local<v8::Signature> signature = v8::Local<v8::Signature>(), + v8::ConstructorBehavior behavior = v8::ConstructorBehavior::kAllow, + v8::SideEffectType side_effect = v8::SideEffectType::kHasSideEffect, + const v8::CFunction* c_function = nullptr); + +// Convenience methods for NewFunctionTemplate(). +void SetMethod(v8::Local<v8::Context> context, + v8::Local<v8::Object> that, + const char* name, + v8::FunctionCallback callback); + +void SetFastMethod(v8::Local<v8::Context> context, + v8::Local<v8::Object> that, + const char* name, + v8::FunctionCallback slow_callback, + const v8::CFunction* c_function); + +void SetProtoMethod(v8::Isolate* isolate, + v8::Local<v8::FunctionTemplate> that, + const char* name, + v8::FunctionCallback callback); + +void SetInstanceMethod(v8::Isolate* isolate, + v8::Local<v8::FunctionTemplate> that, + const char* name, + v8::FunctionCallback callback); + +// Safe variants denote the function has no side effects. +void SetMethodNoSideEffect(v8::Local<v8::Context> context, + v8::Local<v8::Object> that, + const char* name, + v8::FunctionCallback callback); +void SetProtoMethodNoSideEffect(v8::Isolate* isolate, + v8::Local<v8::FunctionTemplate> that, + const char* name, + v8::FunctionCallback callback); + +enum class SetConstructorFunctionFlag { + NONE, + SET_CLASS_NAME, +}; + +void SetConstructorFunction(v8::Local<v8::Context> context, + v8::Local<v8::Object> that, + const char* name, + v8::Local<v8::FunctionTemplate> tmpl, + SetConstructorFunctionFlag flag = + SetConstructorFunctionFlag::SET_CLASS_NAME); + +void SetConstructorFunction(v8::Local<v8::Context> context, + v8::Local<v8::Object> that, + v8::Local<v8::String> name, + v8::Local<v8::FunctionTemplate> tmpl, + SetConstructorFunctionFlag flag = + SetConstructorFunctionFlag::SET_CLASS_NAME); + } // namespace node #endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS diff --git a/src/uv.cc b/src/uv.cc index 2b0c424587e..81e80711df8 100644 --- a/src/uv.cc +++ b/src/uv.cc @@ -109,10 +109,8 @@ void Initialize(Local<Object> target, void* priv) { Environment* env = Environment::GetCurrent(context); Isolate* isolate = env->isolate(); - env->SetConstructorFunction( - target, - "errname", - env->NewFunctionTemplate(ErrName)); + SetConstructorFunction( + context, target, "errname", NewFunctionTemplate(isolate, ErrName)); // TODO(joyeecheung): This should be deprecated in user land in favor of // `util.getSystemErrorName(err)`. @@ -128,7 +126,7 @@ void Initialize(Local<Object> target, target->DefineOwnProperty(context, name, value, attributes).Check(); } - env->SetMethod(target, "getErrorMap", GetErrMap); + SetMethod(context, target, "getErrorMap", GetErrMap); } void RegisterExternalReferences(ExternalReferenceRegistry* registry) { diff --git a/test/parallel/test-env-newprotomethod-remove-unnecessary-prototypes.js b/test/parallel/test-env-newprotomethod-remove-unnecessary-prototypes.js index deb7993a145..22c0c8665d1 100644 --- a/test/parallel/test-env-newprotomethod-remove-unnecessary-prototypes.js +++ b/test/parallel/test-env-newprotomethod-remove-unnecessary-prototypes.js @@ -3,7 +3,7 @@ require('../common'); // This test ensures that unnecessary prototypes are no longer -// being generated by Environment::NewFunctionTemplate. +// being generated by node::NewFunctionTemplate. const assert = require('assert'); const { internalBinding } = require('internal/test/binding'); |