diff --git a/src/README.md b/src/README.md index 8162deecb3cc83..314cd343418cbf 100644 --- a/src/README.md +++ b/src/README.md @@ -390,32 +390,33 @@ void Initialize(Local 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 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); - env->SetProtoMethod(channel_wrap, "queryA", Query); + SetProtoMethod(isolate, channel_wrap, "queryAny", Query); + SetProtoMethod(isolate, channel_wrap, "queryA", Query); // ... - env->SetProtoMethod(channel_wrap, "querySoa", Query); - env->SetProtoMethod(channel_wrap, "getHostByAddr", Query); + SetProtoMethod(isolate, channel_wrap, "querySoa", Query); + SetProtoMethod(isolate, channel_wrap, "getHostByAddr", Query); - 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 ff7ff59092104a..d65e456930b080 100644 --- a/src/async_wrap.cc +++ b/src/async_wrap.cc @@ -340,12 +340,14 @@ void AsyncWrap::SetCallbackTrampoline(const FunctionCallbackInfo& args) { Local AsyncWrap::GetConstructorTemplate(Environment* env) { Local 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; @@ -359,15 +361,15 @@ void AsyncWrap::Initialize(Local 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(ReadOnly | DontDelete); diff --git a/src/cares_wrap.cc b/src/cares_wrap.cc index a16a0dcbd1bcec..1757d56d09ab4d 100644 --- a/src/cares_wrap.cc +++ b/src/cares_wrap.cc @@ -1886,12 +1886,13 @@ void Initialize(Local target, Local 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 target, Local aiw = BaseObject::MakeLazilyInitializedJSTemplate(env); aiw->Inherit(AsyncWrap::GetConstructorTemplate(env)); - env->SetConstructorFunction(target, "GetAddrInfoReqWrap", aiw); + SetConstructorFunction(context, target, "GetAddrInfoReqWrap", aiw); Local niw = BaseObject::MakeLazilyInitializedJSTemplate(env); niw->Inherit(AsyncWrap::GetConstructorTemplate(env)); - env->SetConstructorFunction(target, "GetNameInfoReqWrap", niw); + SetConstructorFunction(context, target, "GetNameInfoReqWrap", niw); Local qrw = BaseObject::MakeLazilyInitializedJSTemplate(env); qrw->Inherit(AsyncWrap::GetConstructorTemplate(env)); - env->SetConstructorFunction(target, "QueryReqWrap", qrw); + SetConstructorFunction(context, target, "QueryReqWrap", qrw); Local 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); - env->SetProtoMethod(channel_wrap, "queryA", Query); - env->SetProtoMethod(channel_wrap, "queryAaaa", Query); - env->SetProtoMethod(channel_wrap, "queryCaa", Query); - env->SetProtoMethod(channel_wrap, "queryCname", Query); - env->SetProtoMethod(channel_wrap, "queryMx", Query); - env->SetProtoMethod(channel_wrap, "queryNs", Query); - env->SetProtoMethod(channel_wrap, "queryTxt", Query); - env->SetProtoMethod(channel_wrap, "querySrv", Query); - env->SetProtoMethod(channel_wrap, "queryPtr", Query); - env->SetProtoMethod(channel_wrap, "queryNaptr", Query); - env->SetProtoMethod(channel_wrap, "querySoa", Query); - env->SetProtoMethod(channel_wrap, "getHostByAddr", Query); - - 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); + SetProtoMethod(isolate, channel_wrap, "queryA", Query); + SetProtoMethod(isolate, channel_wrap, "queryAaaa", Query); + SetProtoMethod(isolate, channel_wrap, "queryCaa", Query); + SetProtoMethod(isolate, channel_wrap, "queryCname", Query); + SetProtoMethod(isolate, channel_wrap, "queryMx", Query); + SetProtoMethod(isolate, channel_wrap, "queryNs", Query); + SetProtoMethod(isolate, channel_wrap, "queryTxt", Query); + SetProtoMethod(isolate, channel_wrap, "querySrv", Query); + SetProtoMethod(isolate, channel_wrap, "queryPtr", Query); + SetProtoMethod(isolate, channel_wrap, "queryNaptr", Query); + SetProtoMethod(isolate, channel_wrap, "querySoa", Query); + SetProtoMethod( + isolate, channel_wrap, "getHostByAddr", Query); + + 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 6c663a2b21d0a2..0ce2708d12ceb8 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 target) { - Local t = env->NewFunctionTemplate(New); + Isolate* isolate = env->isolate(); + Local context = env->context(); + + Local 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); - env->SetMethod(target, "privateDecrypt", - PublicKeyCipher::Cipher); - env->SetMethod(target, "privateEncrypt", - PublicKeyCipher::Cipher); - env->SetMethod(target, "publicDecrypt", - PublicKeyCipher::Cipher); - - 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); + SetMethod(context, + target, + "privateDecrypt", + PublicKeyCipher::Cipher); + SetMethod(context, + target, + "privateEncrypt", + PublicKeyCipher::Cipher); + SetMethod(context, + target, + "publicDecrypt", + PublicKeyCipher::Cipher); + + 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 e2291f72b6622f..2265cfb63d0851 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 SecureContext::GetConstructorTemplate( Environment* env) { Local 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); - env->SetProtoMethodNoSideEffect(tmpl, "getIssuer", - GetCertificate); - - #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); + SetProtoMethodNoSideEffect( + isolate, tmpl, "getIssuer", GetCertificate); + +#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 SecureContext::GetConstructorTemplate( SET_INTEGER_CONSTANTS("kTicketKeyIVIndex", kTicketKeyIVIndex); #undef SET_INTEGER_CONSTANTS - Local ctx_getter_templ = - FunctionTemplate::New(env->isolate(), - CtxGetter, - Local(), - Signature::New(env->isolate(), tmpl)); + Local ctx_getter_templ = FunctionTemplate::New( + isolate, CtxGetter, Local(), Signature::New(isolate, tmpl)); tmpl->PrototypeTemplate()->SetAccessorProperty( - FIXED_ONE_BYTE_STRING(env->isolate(), "_external"), + FIXED_ONE_BYTE_STRING(isolate, "_external"), ctx_getter_templ, Local(), static_cast(ReadOnly | DontDelete)); @@ -326,17 +325,20 @@ Local SecureContext::GetConstructorTemplate( } void SecureContext::Initialize(Environment* env, Local target) { - env->SetConstructorFunction( - target, - "SecureContext", - GetConstructorTemplate(env), - Environment::SetConstructorFunctionFlag::NONE); - - env->SetMethodNoSideEffect(target, "getRootCertificates", - GetRootCertificates); + Local 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 c02e22bb542ff5..3f0146e63bece1 100644 --- a/src/crypto/crypto_dh.cc +++ b/src/crypto/crypto_dh.cc @@ -13,12 +13,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; @@ -56,8 +58,10 @@ DiffieHellman::DiffieHellman(Environment* env, Local wrap) } void DiffieHellman::Initialize(Environment* env, Local target) { - auto make = [&] (Local name, FunctionCallback callback) { - Local t = env->NewFunctionTemplate(callback); + Isolate* isolate = env->isolate(); + Local context = env->context(); + auto make = [&](Local name, FunctionCallback callback) { + Local t = NewFunctionTemplate(isolate, callback); const PropertyAttribute attributes = static_cast(ReadOnly | DontDelete); @@ -66,17 +70,17 @@ void DiffieHellman::Initialize(Environment* env, Local 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 verify_error_getter_templ = - FunctionTemplate::New(env->isolate(), + FunctionTemplate::New(isolate, DiffieHellman::VerifyErrorGetter, Local(), Signature::New(env->isolate(), t), @@ -90,14 +94,15 @@ void DiffieHellman::Initialize(Environment* env, Local target) { Local(), 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 e9fe65ffd571ca..ed9d96a3d56d13 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 target) { - Local t = env->NewFunctionTemplate(New); + Isolate* isolate = env->isolate(); + Local context = env->context(); + + Local 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 8f7128569c7aa5..00ec9d60530dd2 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& args) { } void Hash::Initialize(Environment* env, Local target) { - Local t = env->NewFunctionTemplate(New); + Isolate* isolate = env->isolate(); + Local context = env->context(); + Local 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 296ae541a3e68f..117d91da85e932 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 target) { - Local t = env->NewFunctionTemplate(New); + Isolate* isolate = env->isolate(); + Local 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 8999e7ab03c9a9..5a7ef797de596a 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; @@ -904,23 +905,24 @@ v8::Local KeyObjectHandle::Initialize(Environment* env) { if (!templ.IsEmpty()) { return templ; } - Local t = env->NewFunctionTemplate(New); + Isolate* isolate = env->isolate(); + Local 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); @@ -1315,8 +1317,10 @@ void KeyObjectHandle::ExportJWK( } void NativeKeyObject::Initialize(Environment* env, Local target) { - env->SetMethod(target, "createNativeKeyObjectClass", - NativeKeyObject::CreateNativeKeyObjectClass); + SetMethod(env->context(), + target, + "createNativeKeyObjectClass", + NativeKeyObject::CreateNativeKeyObjectClass); } void NativeKeyObject::RegisterExternalReferences( @@ -1336,12 +1340,14 @@ void NativeKeyObject::New(const FunctionCallbackInfo& args) { void NativeKeyObject::CreateNativeKeyObjectClass( const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); + Isolate* isolate = env->isolate(); CHECK_EQ(args.Length(), 1); Local callback = args[0]; CHECK(callback->IsFunction()); - Local t = env->NewFunctionTemplate(NativeKeyObject::New); + Local 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 c4483a71744e35..cb22809387c17b 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; @@ -329,17 +330,18 @@ Sign::Sign(Environment* env, Local wrap) : SignBase(env, wrap) { } void Sign::Initialize(Environment* env, Local target) { - Local t = env->NewFunctionTemplate(New); + Isolate* isolate = env->isolate(); + Local 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); @@ -458,17 +460,18 @@ Verify::Verify(Environment* env, Local wrap) } void Verify::Initialize(Environment* env, Local target) { - Local t = env->NewFunctionTemplate(New); + Isolate* isolate = env->isolate(); + Local 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 c29d94edc0f9f9..cc31808e7cef8f 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; @@ -128,9 +129,12 @@ void ExportChallenge(const FunctionCallbackInfo& args) { } void Initialize(Environment* env, Local target) { - env->SetMethodNoSideEffect(target, "certVerifySpkac", VerifySpkac); - env->SetMethodNoSideEffect(target, "certExportPublicKey", ExportPublicKey); - env->SetMethodNoSideEffect(target, "certExportChallenge", ExportChallenge); + Local 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 3cc1a12ec009d6..8904f6b140dbb5 100644 --- a/src/crypto/crypto_timing.cc +++ b/src/crypto/crypto_timing.cc @@ -47,7 +47,8 @@ void TimingSafeEqual(const FunctionCallbackInfo& args) { } void Initialize(Environment* env, Local 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 a192956f0f7cfe..7ef47a5181abf8 100644 --- a/src/crypto/crypto_tls.cc +++ b/src/crypto/crypto_tls.cc @@ -2029,8 +2029,9 @@ void TLSWrap::Initialize( Local 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); @@ -2053,54 +2054,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 58a5d88d7a10de..54ac285e7f7671 100644 --- a/src/crypto/crypto_util.cc +++ b/src/crypto/crypto_util.cc @@ -739,19 +739,20 @@ void SecureHeapUsed(const FunctionCallbackInfo& args) { namespace Util { void Initialize(Environment* env, Local target) { + Local 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 07ea8e44da3e54..3a1d21b4f567d5 100644 --- a/src/crypto/crypto_util.h +++ b/src/crypto/crypto_util.h @@ -418,12 +418,15 @@ class CryptoJob : public AsyncWrap, public ThreadPoolWork { v8::FunctionCallback new_fn, Environment* env, v8::Local target) { - v8::Local job = env->NewFunctionTemplate(new_fn); + v8::Isolate* isolate = env->isolate(); + v8::HandleScope scope(isolate); + v8::Local context = env->context(); + v8::Local 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 398b1a85795431..a8c4255d52d7e5 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 X509Certificate::GetConstructorTemplate( Environment* env) { Local 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 X509Certificate::CloneForMessaging() void X509Certificate::Initialize(Environment* env, Local 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 5350c0d7cba98c..01045d1c62a12a 100644 --- a/src/env.cc +++ b/src/env.cc @@ -501,147 +501,6 @@ std::unique_ptr Environment::release_managed_buffer( return bs; } -Local Environment::NewFunctionTemplate( - v8::FunctionCallback callback, - Local signature, - v8::ConstructorBehavior behavior, - v8::SideEffectType side_effect_type, - const v8::CFunction* c_function) { - return v8::FunctionTemplate::New(isolate(), - callback, - Local(), - signature, - 0, - behavior, - side_effect_type, - c_function); -} - -void Environment::SetMethod(Local that, - const char* name, - v8::FunctionCallback callback) { - Local context = isolate()->GetCurrentContext(); - Local function = - NewFunctionTemplate(callback, - Local(), - 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 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 that, - const char* name, - v8::FunctionCallback slow_callback, - const v8::CFunction* c_function) { - Local context = isolate()->GetCurrentContext(); - Local function = - NewFunctionTemplate(slow_callback, - Local(), - v8::ConstructorBehavior::kThrow, - v8::SideEffectType::kHasNoSideEffect, - c_function) - ->GetFunction(context) - .ToLocalChecked(); - const v8::NewStringType type = v8::NewStringType::kInternalized; - Local name_string = - v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked(); - that->Set(context, name_string, function).Check(); -} - -void Environment::SetMethodNoSideEffect(Local that, - const char* name, - v8::FunctionCallback callback) { - Local context = isolate()->GetCurrentContext(); - Local function = - NewFunctionTemplate(callback, - Local(), - 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 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 that, - const char* name, - v8::FunctionCallback callback) { - Local signature = v8::Signature::New(isolate(), that); - Local 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 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 that, - const char* name, - v8::FunctionCallback callback) { - Local signature = v8::Signature::New(isolate(), that); - Local 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 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 that, - const char* name, - v8::FunctionCallback callback) { - Local signature = v8::Signature::New(isolate(), that); - Local 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 name_string = - v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked(); - that->InstanceTemplate()->Set(name_string, t); - t->SetClassName(name_string); -} - -void Environment::SetConstructorFunction(Local that, - const char* name, - Local tmpl, - SetConstructorFunctionFlag flag) { - SetConstructorFunction(that, OneByteString(isolate(), name), tmpl, flag); -} - -void Environment::SetConstructorFunction(Local that, - Local name, - Local 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 ctx = context(); @@ -2181,8 +2040,8 @@ void BaseObject::LazilyInitializedJSTemplateConstructor( Local BaseObject::MakeLazilyInitializedJSTemplate( Environment* env) { - Local t = - env->NewFunctionTemplate(LazilyInitializedJSTemplateConstructor); + Local t = NewFunctionTemplate( + env->isolate(), LazilyInitializedJSTemplateConstructor); t->Inherit(BaseObject::GetConstructorTemplate(env)); t->InstanceTemplate()->SetInternalFieldCount(BaseObject::kInternalFieldCount); return t; @@ -2241,7 +2100,7 @@ bool BaseObject::IsRootNode() const { Local BaseObject::GetConstructorTemplate(Environment* env) { Local 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 7b0210f92f6640..cedaacd2d482c7 100644 --- a/src/env.h +++ b/src/env.h @@ -1237,56 +1237,6 @@ class Environment : public MemoryRetainer { const char* path = nullptr, const char* dest = nullptr); - v8::Local NewFunctionTemplate( - v8::FunctionCallback callback, - v8::Local signature = v8::Local(), - 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 that, - const char* name, - v8::FunctionCallback callback); - - void SetFastMethod(v8::Local that, - const char* name, - v8::FunctionCallback slow_callback, - const v8::CFunction* c_function); - - void SetProtoMethod(v8::Local that, - const char* name, - v8::FunctionCallback callback); - - void SetInstanceMethod(v8::Local that, - const char* name, - v8::FunctionCallback callback); - - // Safe variants denote the function has no side effects. - void SetMethodNoSideEffect(v8::Local that, - const char* name, - v8::FunctionCallback callback); - void SetProtoMethodNoSideEffect(v8::Local that, - const char* name, - v8::FunctionCallback callback); - - enum class SetConstructorFunctionFlag { - NONE, - SET_CLASS_NAME, - }; - - void SetConstructorFunction(v8::Local that, - const char* name, - v8::Local tmpl, - SetConstructorFunctionFlag flag = - SetConstructorFunctionFlag::SET_CLASS_NAME); - - void SetConstructorFunction(v8::Local that, - v8::Local name, - v8::Local 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 f13d22535c1015..7b4a3278028a96 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 target, Local context, void* priv) { Environment* env = Environment::GetCurrent(context); + Isolate* isolate = env->isolate(); - Local t = env->NewFunctionTemplate(New); + Local 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 get_initialized_templ = FunctionTemplate::New(env->isolate(), @@ -115,7 +117,7 @@ void FSEventWrap::Initialize(Local target, Local(), static_cast(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 caad0e0554622a..4ea6a67d57f8e2 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 HandleWrap::GetConstructorTemplate(Environment* env) { Local 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 bc779489637048..a7c5dcdfb89e82 100644 --- a/src/heap_utils.cc +++ b/src/heap_utils.cc @@ -393,11 +393,10 @@ void Initialize(Local target, Local unused, Local 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 63fa52a57df157..3a3228ddc9eb6b 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 HistogramBase::GetConstructorTemplate( Environment* env) { Local tmpl = env->histogram_ctor_template(); if (tmpl.IsEmpty()) { - tmpl = env->NewFunctionTemplate(New); + Isolate* isolate = env->isolate(); + tmpl = NewFunctionTemplate(isolate, New); Local classname = FIXED_ONE_BYTE_STRING(env->isolate(), "Histogram"); tmpl->SetClassName(classname); @@ -288,26 +290,27 @@ Local 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 target) { - env->SetConstructorFunction(target, "Histogram", GetConstructorTemplate(env)); + SetConstructorFunction( + env->context(), target, "Histogram", GetConstructorTemplate(env)); } BaseObjectPtr HistogramBase::HistogramTransferData::Deserialize( @@ -360,29 +364,31 @@ Local IntervalHistogram::GetConstructorTemplate( Environment* env) { Local 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 4ebb8acd689d58..c50646954d0987 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 target) { + Isolate* isolate = env->isolate(); Local 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& info) { @@ -314,34 +314,45 @@ void Url(const FunctionCallbackInfo& args) { void Initialize(Local target, Local unused, Local context, void* priv) { Environment* env = Environment::GetCurrent(context); + Isolate* isolate = env->isolate(); v8::Local consoleCallFunc = - env->NewFunctionTemplate(InspectorConsoleCall, v8::Local(), - v8::ConstructorBehavior::kThrow, - v8::SideEffectType::kHasSideEffect) + NewFunctionTemplate(isolate, + InspectorConsoleCall, + v8::Local(), + 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); + 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); JSBindingsConnection::Bind(env, target); JSBindingsConnection::Bind(env, target); diff --git a/src/inspector_profiler.cc b/src/inspector_profiler.cc index 332aa536364fba..538125f091a323 100644 --- a/src/inspector_profiler.cc +++ b/src/inspector_profiler.cc @@ -507,11 +507,11 @@ static void Initialize(Local target, Local unused, Local 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 720008ecefcb48..5bf64a9e0a928b 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 target, Local context, void* priv) { Environment* env = Environment::GetCurrent(context); + Isolate* isolate = env->isolate(); - Local t = env->NewFunctionTemplate(New); + Local t = NewFunctionTemplate(isolate, New); t->InstanceTemplate() ->SetInternalFieldCount(StreamBase::kInternalFieldCount); t->Inherit(AsyncWrap::GetConstructorTemplate(env)); - env->SetProtoMethod(t, "finishWrite", Finish); - env->SetProtoMethod(t, "finishShutdown", Finish); - env->SetProtoMethod(t, "readBuffer", ReadBuffer); - env->SetProtoMethod(t, "emitEOF", EmitEOF); + SetProtoMethod(isolate, t, "finishWrite", Finish); + SetProtoMethod(isolate, t, "finishShutdown", Finish); + 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 3f02771ee1a907..99362ccc6097d5 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 target, Local context, void* priv) { Environment* env = Environment::GetCurrent(context); + Isolate* isolate = env->isolate(); - Local t = env->NewFunctionTemplate(New); + Local 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 b4b70ec1afd3ea..bd13d1e2825ff0 100644 --- a/src/module_wrap.cc +++ b/src/module_wrap.cc @@ -765,31 +765,37 @@ void ModuleWrap::Initialize(Local target, Local context, void* priv) { Environment* env = Environment::GetCurrent(context); + Isolate* isolate = env->isolate(); - Local tpl = env->NewFunctionTemplate(New); + Local 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 5ac6ca75389d19..ca0735e775eaa2 100644 --- a/src/node.cc +++ b/src/node.cc @@ -312,10 +312,10 @@ MaybeLocal Environment::BootstrapInternalLoaders() { primordials_string()}; std::vector> 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()}; @@ -445,7 +445,7 @@ MaybeLocal 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 ee61437f402fcd..ffc3de1453add6 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(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 Blob::GetConstructorTemplate(Environment* env) { Local 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 target) { - v8::Local job = env->NewFunctionTemplate(New); + Isolate* isolate = env->isolate(); + v8::Local 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& args) { diff --git a/src/node_buffer.cc b/src/node_buffer.cc index b2b3cfd9c8faa1..9094fd121e5010 100644 --- a/src/node_buffer.cc +++ b/src/node_buffer.cc @@ -1267,54 +1267,60 @@ void Initialize(Local target, Local 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); - env->SetMethodNoSideEffect(target, "base64Slice", StringSlice); - env->SetMethodNoSideEffect(target, "base64urlSlice", StringSlice); - env->SetMethodNoSideEffect(target, "latin1Slice", StringSlice); - env->SetMethodNoSideEffect(target, "hexSlice", StringSlice); - env->SetMethodNoSideEffect(target, "ucs2Slice", StringSlice); - env->SetMethodNoSideEffect(target, "utf8Slice", StringSlice); - - env->SetMethod(target, "asciiWrite", StringWrite); - env->SetMethod(target, "base64Write", StringWrite); - env->SetMethod(target, "base64urlWrite", StringWrite); - env->SetMethod(target, "latin1Write", StringWrite); - env->SetMethod(target, "hexWrite", StringWrite); - env->SetMethod(target, "ucs2Write", StringWrite); - env->SetMethod(target, "utf8Write", StringWrite); - - 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); + SetMethodNoSideEffect(context, target, "base64Slice", StringSlice); + SetMethodNoSideEffect( + context, target, "base64urlSlice", StringSlice); + SetMethodNoSideEffect(context, target, "latin1Slice", StringSlice); + SetMethodNoSideEffect(context, target, "hexSlice", StringSlice); + SetMethodNoSideEffect(context, target, "ucs2Slice", StringSlice); + SetMethodNoSideEffect(context, target, "utf8Slice", StringSlice); + + SetMethod(context, target, "asciiWrite", StringWrite); + SetMethod(context, target, "base64Write", StringWrite); + SetMethod(context, target, "base64urlWrite", StringWrite); + SetMethod(context, target, "latin1Write", StringWrite); + SetMethod(context, target, "hexWrite", StringWrite); + SetMethod(context, target, "ucs2Write", StringWrite); + SetMethod(context, target, "utf8Write", StringWrite); + + SetMethod(context, target, "getZeroFillToggle", GetZeroFillToggle); } } // anonymous namespace diff --git a/src/node_contextify.cc b/src/node_contextify.cc index ae1b9f98e7b537..a02c211db8d6c2 100644 --- a/src/node_contextify.cc +++ b/src/node_contextify.cc @@ -255,16 +255,19 @@ MaybeLocal ContextifyContext::CreateV8Context( void ContextifyContext::Init(Environment* env, Local target) { + Isolate* isolate = env->isolate(); + Local context = env->context(); + Local 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( @@ -665,16 +668,17 @@ void ContextifyContext::IndexedPropertyDeleterCallback( } void ContextifyScript::Init(Environment* env, Local target) { + Isolate* isolate = env->isolate(); HandleScope scope(env->isolate()); Local class_name = FIXED_ONE_BYTE_STRING(env->isolate(), "ContextifyScript"); - Local script_tmpl = env->NewFunctionTemplate(New); + Local 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 = env->context(); @@ -1270,12 +1274,14 @@ void MicrotaskQueueWrap::New(const FunctionCallbackInfo& args) { } void MicrotaskQueueWrap::Init(Environment* env, Local target) { - HandleScope scope(env->isolate()); - Local tmpl = env->NewFunctionTemplate(New); + Isolate* isolate = env->isolate(); + HandleScope scope(isolate); + Local context = env->context(); + Local 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( @@ -1293,11 +1299,11 @@ void Initialize(Local 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 tpl = FunctionTemplate::New(env->isolate()); @@ -1333,7 +1339,7 @@ void Initialize(Local 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 511ea3b01408eb..4c098c9870aa8e 100644 --- a/src/node_credentials.cc +++ b/src/node_credentials.cc @@ -413,23 +413,23 @@ static void Initialize(Local 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 c530da0cc3be4b..e501934ecc70ac 100644 --- a/src/node_dir.cc +++ b/src/node_dir.cc @@ -351,17 +351,18 @@ void Initialize(Local target, Local 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 dir = env->NewFunctionTemplate(DirHandle::New); + Local 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 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_dtrace.cc b/src/node_dtrace.cc index 52e63992833c38..9768880ac78a37 100644 --- a/src/node_dtrace.cc +++ b/src/node_dtrace.cc @@ -301,10 +301,8 @@ void InitializeDTrace(Local target, Local unused, Local context, void* priv) { - Environment* env = Environment::GetCurrent(context); - #if defined HAVE_DTRACE || defined HAVE_ETW -#define V(name) env->SetMethod(target, #name, name); +#define V(name) SetMethod(context, target, #name, name); NODE_PROBES(V) #undef V #endif // defined HAVE_DTRACE || defined HAVE_ETW diff --git a/src/node_errors.cc b/src/node_errors.cc index 7c017264a88fd1..12e3ff957e035a 100644 --- a/src/node_errors.cc +++ b/src/node_errors.cc @@ -924,19 +924,23 @@ void Initialize(Local target, Local unused, Local context, void* priv) { - Environment* env = Environment::GetCurrent(context); - env->SetMethod( - target, "setPrepareStackTraceCallback", SetPrepareStackTraceCallback); - 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, "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 21297acbcfa90d..0d4b8cac801a30 100644 --- a/src/node_file.cc +++ b/src/node_file.cc @@ -2436,46 +2436,46 @@ void Initialize(Local target, env->AddBindingData(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, @@ -2488,11 +2488,11 @@ void Initialize(Local target, StatWatcher::Initialize(env, target); // Create FunctionTemplate for FSReqCallback - Local fst = env->NewFunctionTemplate(NewFSReqCallback); + Local 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. @@ -2517,14 +2517,14 @@ void Initialize(Local target, env->set_fsreqpromise_constructor_template(fpo); // Create FunctionTemplate for FileHandle - Local fd = env->NewFunctionTemplate(FileHandle::New); + Local 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 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 8df924a29028e2..574ddc14a30cb4 100644 --- a/src/node_http2.cc +++ b/src/node_http2.cc @@ -3204,10 +3204,10 @@ void Initialize(Local 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 ping = FunctionTemplate::New(env->isolate()); ping->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "Http2Ping")); @@ -3223,50 +3223,54 @@ void Initialize(Local target, env->set_http2settings_constructor_template(settingt); Local 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 streamt = stream->InstanceTemplate(); streamt->SetInternalFieldCount(StreamBase::kInternalFieldCount); env->set_http2stream_constructor_template(streamt); - env->SetConstructorFunction(target, "Http2Stream", stream); + SetConstructorFunction(context, target, "Http2Stream", stream); Local 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); - env->SetProtoMethod( - session, "remoteSettings", + SetProtoMethod( + isolate, + session, + "remoteSettings", Http2Session::RefreshSettings); - env->SetConstructorFunction(target, "Http2Session", session); + SetConstructorFunction(context, target, "Http2Session", session); Local constants = Object::New(isolate); diff --git a/src/node_http_parser.cc b/src/node_http_parser.cc index 1b7e4ad1b8676b..74f32480b95be3 100644 --- a/src/node_http_parser.cc +++ b/src/node_http_parser.cc @@ -60,6 +60,7 @@ using v8::FunctionTemplate; using v8::HandleScope; using v8::Int32; using v8::Integer; +using v8::Isolate; using v8::Local; using v8::MaybeLocal; using v8::Number; @@ -941,11 +942,12 @@ void InitializeHttpParser(Local target, Local context, void* priv) { Environment* env = Environment::GetCurrent(context); + Isolate* isolate = env->isolate(); BindingData* const binding_data = env->AddBindingData(context, target); if (binding_data == nullptr) return; - Local t = env->NewFunctionTemplate(Parser::New); + Local t = NewFunctionTemplate(isolate, Parser::New); t->InstanceTemplate()->SetInternalFieldCount(Parser::kInternalFieldCount); t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "REQUEST"), @@ -989,18 +991,18 @@ void InitializeHttpParser(Local target, methods).Check(); t->Inherit(AsyncWrap::GetConstructorTemplate(env)); - env->SetProtoMethod(t, "close", Parser::Close); - env->SetProtoMethod(t, "free", Parser::Free); - env->SetProtoMethod(t, "execute", Parser::Execute); - env->SetProtoMethod(t, "finish", Parser::Finish); - env->SetProtoMethod(t, "initialize", Parser::Initialize); - env->SetProtoMethod(t, "pause", Parser::Pause); - env->SetProtoMethod(t, "resume", Parser::Pause); - env->SetProtoMethod(t, "consume", Parser::Consume); - env->SetProtoMethod(t, "unconsume", Parser::Unconsume); - env->SetProtoMethod(t, "getCurrentBuffer", Parser::GetCurrentBuffer); - - env->SetConstructorFunction(target, "HTTPParser", t); + SetProtoMethod(isolate, t, "close", Parser::Close); + SetProtoMethod(isolate, t, "free", Parser::Free); + SetProtoMethod(isolate, t, "execute", Parser::Execute); + SetProtoMethod(isolate, t, "finish", Parser::Finish); + SetProtoMethod(isolate, t, "initialize", Parser::Initialize); + SetProtoMethod(isolate, t, "pause", Parser::Pause); + SetProtoMethod(isolate, t, "resume", Parser::Pause); + SetProtoMethod(isolate, t, "consume", Parser::Consume); + SetProtoMethod(isolate, t, "unconsume", Parser::Unconsume); + SetProtoMethod(isolate, t, "getCurrentBuffer", Parser::GetCurrentBuffer); + + SetConstructorFunction(context, target, "HTTPParser", t); } } // anonymous namespace diff --git a/src/node_i18n.cc b/src/node_i18n.cc index d96efaa9df7b2f..581d52a7d05738 100644 --- a/src/node_i18n.cc +++ b/src/node_i18n.cc @@ -838,17 +838,17 @@ void Initialize(Local target, Local 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 t = FunctionTemplate::New(env->isolate()); + Local t = NewFunctionTemplate(env->isolate(), nullptr); t->Inherit(BaseObject::GetConstructorTemplate(env)); t->InstanceTemplate()->SetInternalFieldCount( ConverterObject::kInternalFieldCount); @@ -858,9 +858,9 @@ void Initialize(Local 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 152d9c164750c2..f88270fc75de91 100644 --- a/src/node_messaging.cc +++ b/src/node_messaging.cc @@ -1111,14 +1111,15 @@ Local GetMessagePortConstructorTemplate(Environment* env) { return templ; { - Local m = env->NewFunctionTemplate(MessagePort::New); + Isolate* isolate = env->isolate(); + Local 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 target, Local 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 t = env->NewFunctionTemplate(JSTransferable::New); + Local 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 domexception = GetDOMException(context).ToLocalChecked(); diff --git a/src/node_native_module_env.cc b/src/node_native_module_env.cc index b59ed7cb75cf67..523c5152f3c8dc 100644 --- a/src/node_native_module_env.cc +++ b/src/node_native_module_env.cc @@ -179,7 +179,7 @@ void NativeModuleEnv::Initialize(Local target, Environment* env = Environment::GetCurrent(context); target - ->SetAccessor(env->context(), + ->SetAccessor(context, env->config_string(), ConfigStringGetter, nullptr, @@ -189,7 +189,7 @@ void NativeModuleEnv::Initialize(Local target, SideEffectType::kHasNoSideEffect) .Check(); target - ->SetAccessor(env->context(), + ->SetAccessor(context, FIXED_ONE_BYTE_STRING(env->isolate(), "moduleIds"), ModuleIdsGetter, nullptr, @@ -200,7 +200,7 @@ void NativeModuleEnv::Initialize(Local target, .Check(); target - ->SetAccessor(env->context(), + ->SetAccessor(context, FIXED_ONE_BYTE_STRING(env->isolate(), "moduleCategories"), GetModuleCategories, nullptr, @@ -210,9 +210,10 @@ void NativeModuleEnv::Initialize(Local target, SideEffectType::kHasNoSideEffect) .Check(); - env->SetMethod(target, "getCacheUsage", NativeModuleEnv::GetCacheUsage); - env->SetMethod(target, "compileFunction", NativeModuleEnv::CompileFunction); - env->SetMethod(target, "hasCachedBuiltins", HasCachedBuiltins); + SetMethod(context, target, "getCacheUsage", NativeModuleEnv::GetCacheUsage); + SetMethod( + context, target, "compileFunction", NativeModuleEnv::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 3daa3cc12debb1..2c31d64cb3e47e 100644 --- a/src/node_options.cc +++ b/src/node_options.cc @@ -1141,8 +1141,9 @@ void Initialize(Local 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 env_settings = Object::New(isolate); NODE_DEFINE_CONSTANT(env_settings, kAllowedInEnvironment); diff --git a/src/node_os.cc b/src/node_os.cc index 046a6106ccd0e5..5b4d6567fb3b0a 100644 --- a/src/node_os.cc +++ b/src/node_os.cc @@ -382,21 +382,23 @@ void Initialize(Local target, Local 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 f6637aa97e9d63..76f77be694326a 100644 --- a/src/node_perf.cc +++ b/src/node_perf.cc @@ -302,19 +302,21 @@ void Initialize(Local 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 constants = Object::New(isolate); diff --git a/src/node_process_methods.cc b/src/node_process_methods.cc index bc5d41382f20f1..f75d51fe2b5d9c 100644 --- a/src/node_process_methods.cc +++ b/src/node_process_methods.cc @@ -466,8 +466,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 ctx = env()->context(); + SetFastMethod(ctx, object(), "hrtime", SlowNumber, &fast_number_); + SetFastMethod(ctx, object(), "hrtimeBigInt", SlowBigInt, &fast_bigint_); } void BindingData::RegisterExternalReferences( @@ -562,31 +563,31 @@ static void Initialize(Local 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 29f6569a45e5b2..438ab3c0f09eea 100644 --- a/src/node_process_object.cc +++ b/src/node_process_object.cc @@ -135,7 +135,7 @@ MaybeLocal 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 160498c6276a3f..b57a933972d6c0 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 exports, Local unused, Local 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 f6f0034bc24d09..45a16d9de43703 100644 --- a/src/node_serdes.cc +++ b/src/node_serdes.cc @@ -455,53 +455,62 @@ void Initialize(Local target, Local context, void* priv) { Environment* env = Environment::GetCurrent(context); + Isolate* isolate = env->isolate(); + Local 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 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 15b488e9e2cce4..bb5ca091dca4b9 100644 --- a/src/node_snapshotable.cc +++ b/src/node_snapshotable.cc @@ -420,13 +420,14 @@ void Initialize(Local target, Local unused, Local 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 d29414302b7d28..331af1d9dba8e0 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 SocketAddressBlockListWrap::GetConstructorTemplate( Environment* env) { Local 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 SocketAddressBase::GetConstructorTemplate( Environment* env) { Local 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 target) { - env->SetConstructorFunction( - target, - "SocketAddress", - GetConstructorTemplate(env), - Environment::SetConstructorFunctionFlag::NONE); + SetConstructorFunction(env->context(), + target, + "SocketAddress", + GetConstructorTemplate(env), + SetConstructorFunctionFlag::NONE); } BaseObjectPtr SocketAddressBase::Create( diff --git a/src/node_stat_watcher.cc b/src/node_stat_watcher.cc index b9f7903a2fdcb6..de8c099ca58594 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 target) { + Isolate* isolate = env->isolate(); HandleScope scope(env->isolate()); - Local t = env->NewFunctionTemplate(StatWatcher::New); + Local 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 9bbdb3180217b3..2e62a072ee493d 100644 --- a/src/node_task_queue.cc +++ b/src/node_task_queue.cc @@ -196,9 +196,9 @@ static void Initialize(Local 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 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 af60aff4ab7bbe..fd277b997dea6c 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 target, Local 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 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 isTraceCategoryEnabled = FIXED_ONE_BYTE_STRING(env->isolate(), "isTraceCategoryEnabled"); diff --git a/src/node_types.cc b/src/node_types.cc index 1889d8c304110b..87550a1428bd34 100644 --- a/src/node_types.cc +++ b/src/node_types.cc @@ -65,16 +65,12 @@ void InitializeTypes(Local target, Local unused, Local 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 1f9f4e40b084cb..ecc7cee6a39ffb 100644 --- a/src/node_url.cc +++ b/src/node_url.cc @@ -1800,12 +1800,11 @@ void Initialize(Local target, Local unused, Local 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 5b5dab36f08fbf..1613a276c58111 100644 --- a/src/node_util.cc +++ b/src/node_util.cc @@ -347,6 +347,7 @@ void Initialize(Local target, Local 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 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 constants = Object::New(env->isolate()); NODE_DEFINE_CONSTANT(constants, ALL_PROPERTIES); NODE_DEFINE_CONSTANT(constants, ONLY_WRITABLE); @@ -394,24 +398,24 @@ void Initialize(Local target, Local 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 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 9c72ddaf5293ec..36057762fa6e15 100644 --- a/src/node_v8.cc +++ b/src/node_v8.cc @@ -208,13 +208,17 @@ void Initialize(Local target, env->AddBindingData(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(); @@ -227,19 +231,21 @@ void Initialize(Local 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(); @@ -250,7 +256,7 @@ void Initialize(Local 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 965a619c8d4acd..a1b244018a6760 100644 --- a/src/node_wasi.cc +++ b/src/node_wasi.cc @@ -1668,62 +1668,67 @@ static void Initialize(Local target, Local context, void* priv) { Environment* env = Environment::GetCurrent(context); + Isolate* isolate = env->isolate(); - Local tmpl = env->NewFunctionTemplate(WASI::New); + Local 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_watchdog.cc b/src/node_watchdog.cc index 31c8f744a3b320..7062d4aa661abb 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 target) { - Local constructor = env->NewFunctionTemplate(New); + Isolate* isolate = env->isolate(); + Local 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& args) { diff --git a/src/node_worker.cc b/src/node_worker.cc index 86493374af13b4..0d2cf9bb81f9ea 100644 --- a/src/node_worker.cc +++ b/src/node_worker.cc @@ -830,65 +830,66 @@ void InitWorker(Local target, Local context, void* priv) { Environment* env = Environment::GetCurrent(context); + Isolate* isolate = env->isolate(); { - Local w = env->NewFunctionTemplate(Worker::New); + Local 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 wst = FunctionTemplate::New(env->isolate()); + Local wst = NewFunctionTemplate(isolate, nullptr); wst->InstanceTemplate()->SetInternalFieldCount( WorkerHeapSnapshotTaker::kInternalFieldCount); wst->Inherit(AsyncWrap::GetConstructorTemplate(env)); Local 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(env->thread_id()))) + Number::New(isolate, static_cast(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 5930ffd7a8ae8e..e2433d887b421a 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 struct MakeClass { static void Make(Environment* env, Local target, const char* name) { - Local z = env->NewFunctionTemplate(Stream::New); + Isolate* isolate = env->isolate(); + Local z = NewFunctionTemplate(isolate, Stream::New); z->InstanceTemplate()->SetInternalFieldCount( Stream::kInternalFieldCount); z->Inherit(AsyncWrap::GetConstructorTemplate(env)); - env->SetProtoMethod(z, "write", Stream::template Write); - env->SetProtoMethod(z, "writeSync", Stream::template Write); - env->SetProtoMethod(z, "close", Stream::Close); + SetProtoMethod(isolate, z, "write", Stream::template Write); + SetProtoMethod(isolate, z, "writeSync", Stream::template Write); + 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 85daf4a1e618ae..4f1bfda569f910 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 target, Local context, void* priv) { Environment* env = Environment::GetCurrent(context); + Isolate* isolate = env->isolate(); - Local t = env->NewFunctionTemplate(New); + Local 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 constants = Object::New(env->isolate()); diff --git a/src/process_wrap.cc b/src/process_wrap.cc index 6905cacb1c8193..3a55048ef79a0e 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, void* priv) { Environment* env = Environment::GetCurrent(context); - Local constructor = env->NewFunctionTemplate(New); + Isolate* isolate = env->isolate(); + Local 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 df7f94eeec8451..d5dfdd51da656a 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, void* priv) { Environment* env = Environment::GetCurrent(context); - Local constructor = env->NewFunctionTemplate(New); + Isolate* isolate = env->isolate(); + Local 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 afd08519d7f897..2db7d82d32f13a 100644 --- a/src/spawn_sync.cc +++ b/src/spawn_sync.cc @@ -363,8 +363,7 @@ void SyncProcessRunner::Initialize(Local target, Local unused, Local 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 783e12a36c8e52..8701434c24fb26 100644 --- a/src/stream_base.cc +++ b/src/stream_base.cc @@ -400,21 +400,24 @@ void StreamBase::AddMethod(Environment* env, Local t, JSMethodFunction* stream_method, Local string) { + Isolate* isolate = env->isolate(); Local 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(), attributes); } void StreamBase::AddMethods(Environment* env, Local t) { - HandleScope scope(env->isolate()); + Isolate* isolate = env->isolate(); + HandleScope scope(isolate); enum PropertyAttribute attributes = static_cast(ReadOnly | DontDelete | DontEnum); - Local sig = Signature::New(env->isolate(), t); + Local 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 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>); - env->SetProtoMethod( - t, "writeUtf8String", JSMethod<&StreamBase::WriteString>); - env->SetProtoMethod( - t, "writeUcs2String", JSMethod<&StreamBase::WriteString>); - env->SetProtoMethod( - t, "writeLatin1String", JSMethod<&StreamBase::WriteString>); - 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>); + SetProtoMethod( + isolate, t, "writeUtf8String", JSMethod<&StreamBase::WriteString>); + SetProtoMethod( + isolate, t, "writeUcs2String", JSMethod<&StreamBase::WriteString>); + SetProtoMethod(isolate, + t, + "writeLatin1String", + JSMethod<&StreamBase::WriteString>); + 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, + BaseObject::InternalFieldSet); } void StreamBase::RegisterExternalReferences( diff --git a/src/stream_pipe.cc b/src/stream_pipe.cc index 93b7ffeca9cd53..7d4be978a11c4c 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 target, Local context, void* priv) { Environment* env = Environment::GetCurrent(context); + Isolate* isolate = env->isolate(); // Create FunctionTemplate for FileHandle::CloseReq - Local 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 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 d0c5664adcd897..88f0bce66adfcc 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 target, Local context, void* priv) { Environment* env = Environment::GetCurrent(context); + Isolate* isolate = env->isolate(); Local 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 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 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 LibuvStreamWrap::GetConstructorTemplate( Environment* env) { Local 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 get_write_queue_size = - FunctionTemplate::New(env->isolate(), + FunctionTemplate::New(isolate, GetWriteQueueSize, Local(), - Signature::New(env->isolate(), tmpl)); + Signature::New(isolate, tmpl)); tmpl->PrototypeTemplate()->SetAccessorProperty( env->write_queue_size_string(), get_write_queue_size, Local(), static_cast(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 a915f5744f3b00..b447474c09f583 100644 --- a/src/string_decoder.cc +++ b/src/string_decoder.cc @@ -328,8 +328,8 @@ void InitializeStringDecoder(Local 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 0fcc12d649eac4..ca4e77757e521b 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 target, Local context, void* priv) { Environment* env = Environment::GetCurrent(context); + Isolate* isolate = env->isolate(); - Local t = env->NewFunctionTemplate(New); + Local t = NewFunctionTemplate(isolate, New); t->InstanceTemplate()->SetInternalFieldCount(StreamBase::kInternalFieldCount); // Init properties @@ -85,32 +87,36 @@ void TCPWrap::Initialize(Local 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); - env->SetProtoMethod(t, "getpeername", - GetSockOrPeerName); - 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); + SetProtoMethod(isolate, + t, + "getpeername", + GetSockOrPeerName); + 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 cwt = BaseObject::MakeLazilyInitializedJSTemplate(env); cwt->Inherit(AsyncWrap::GetConstructorTemplate(env)); - env->SetConstructorFunction(target, "TCPConnectWrap", cwt); + SetConstructorFunction(context, target, "TCPConnectWrap", cwt); // Define constants Local constants = Object::New(env->isolate()); diff --git a/src/timers.cc b/src/timers.cc index 5014f2c66a5d24..2ecfd25f7eeb8b 100644 --- a/src/timers.cc +++ b/src/timers.cc @@ -48,15 +48,17 @@ void Initialize(Local 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 1c749a9741c312..0a7c1467d24895 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 target, Local context, void* priv) { Environment* env = Environment::GetCurrent(context); + Isolate* isolate = env->isolate(); Local ttyString = FIXED_ONE_BYTE_STRING(env->isolate(), "TTY"); - Local t = env->NewFunctionTemplate(New); + Local 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 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 127a1a6e5d8fe7..a6911e2e921b98 100644 --- a/src/udp_wrap.cc +++ b/src/udp_wrap.cc @@ -110,8 +110,8 @@ UDPWrapBase* UDPWrapBase::FromObject(Local obj) { } void UDPWrapBase::AddMethods(Environment* env, Local 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) @@ -134,21 +134,19 @@ void UDPWrap::Initialize(Local target, Local context, void* priv) { Environment* env = Environment::GetCurrent(context); + Isolate* isolate = env->isolate(); - Local t = env->NewFunctionTemplate(New); + Local t = NewFunctionTemplate(isolate, New); t->InstanceTemplate()->SetInternalFieldCount( UDPWrapBase::kInternalFieldCount); enum PropertyAttribute attributes = static_cast(ReadOnly | DontDelete); - Local signature = Signature::New(env->isolate(), t); + Local signature = Signature::New(isolate, t); Local get_fd_templ = - FunctionTemplate::New(env->isolate(), - UDPWrap::GetFD, - Local(), - signature); + FunctionTemplate::New(isolate, UDPWrap::GetFD, Local(), signature); t->PrototypeTemplate()->SetAccessorProperty(env->fd_string(), get_fd_templ, @@ -156,44 +154,47 @@ void UDPWrap::Initialize(Local 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); - env->SetProtoMethod(t, "getsockname", - GetSockOrPeerName); - 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); + SetProtoMethod(isolate, + t, + "getsockname", + GetSockOrPeerName); + 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 swt = BaseObject::MakeLazilyInitializedJSTemplate(env); swt->Inherit(AsyncWrap::GetConstructorTemplate(env)); - env->SetConstructorFunction(target, "SendWrap", swt); + SetConstructorFunction(context, target, "SendWrap", swt); - Local constants = Object::New(env->isolate()); + Local 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 b881f9f9f88cee..6bbd9fd926f61a 100644 --- a/src/util.cc +++ b/src/util.cc @@ -317,4 +317,161 @@ std::string DiagnosticFilename::MakeFilename( return oss.str(); } +Local NewFunctionTemplate( + v8::Isolate* isolate, + v8::FunctionCallback callback, + Local signature, + v8::ConstructorBehavior behavior, + v8::SideEffectType side_effect_type, + const v8::CFunction* c_function) { + return v8::FunctionTemplate::New(isolate, + callback, + Local(), + signature, + 0, + behavior, + side_effect_type, + c_function); +} + +void SetMethod(Local context, + Local that, + const char* name, + v8::FunctionCallback callback) { + Isolate* isolate = context->GetIsolate(); + Local function = + NewFunctionTemplate(isolate, + callback, + Local(), + 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 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 context, + Local that, + const char* name, + v8::FunctionCallback slow_callback, + const v8::CFunction* c_function) { + Isolate* isolate = context->GetIsolate(); + Local function = + NewFunctionTemplate(isolate, + slow_callback, + Local(), + v8::ConstructorBehavior::kThrow, + v8::SideEffectType::kHasNoSideEffect, + c_function) + ->GetFunction(context) + .ToLocalChecked(); + const v8::NewStringType type = v8::NewStringType::kInternalized; + Local name_string = + v8::String::NewFromUtf8(isolate, name, type).ToLocalChecked(); + that->Set(context, name_string, function).Check(); +} + +void SetMethodNoSideEffect(Local context, + Local that, + const char* name, + v8::FunctionCallback callback) { + Isolate* isolate = context->GetIsolate(); + Local function = + NewFunctionTemplate(isolate, + callback, + Local(), + 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 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 that, + const char* name, + v8::FunctionCallback callback) { + Local signature = v8::Signature::New(isolate, that); + Local 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 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 that, + const char* name, + v8::FunctionCallback callback) { + Local signature = v8::Signature::New(isolate, that); + Local 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 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 that, + const char* name, + v8::FunctionCallback callback) { + Local signature = v8::Signature::New(isolate, that); + Local 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 name_string = + v8::String::NewFromUtf8(isolate, name, type).ToLocalChecked(); + that->InstanceTemplate()->Set(name_string, t); + t->SetClassName(name_string); +} + +void SetConstructorFunction(Local context, + Local that, + const char* name, + Local tmpl, + SetConstructorFunctionFlag flag) { + Isolate* isolate = context->GetIsolate(); + SetConstructorFunction( + context, that, OneByteString(isolate, name), tmpl, flag); +} + +void SetConstructorFunction(Local context, + Local that, + Local name, + Local 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 4ca1004b0fd896..edf0de3202a223 100644 --- a/src/util.h +++ b/src/util.h @@ -860,6 +860,66 @@ std::unique_ptr static_unique_pointer_cast(std::unique_ptr&& 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 NewFunctionTemplate( + v8::Isolate* isolate, + v8::FunctionCallback callback, + v8::Local signature = v8::Local(), + 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 context, + v8::Local that, + const char* name, + v8::FunctionCallback callback); + +void SetFastMethod(v8::Local context, + v8::Local that, + const char* name, + v8::FunctionCallback slow_callback, + const v8::CFunction* c_function); + +void SetProtoMethod(v8::Isolate* isolate, + v8::Local that, + const char* name, + v8::FunctionCallback callback); + +void SetInstanceMethod(v8::Isolate* isolate, + v8::Local that, + const char* name, + v8::FunctionCallback callback); + +// Safe variants denote the function has no side effects. +void SetMethodNoSideEffect(v8::Local context, + v8::Local that, + const char* name, + v8::FunctionCallback callback); +void SetProtoMethodNoSideEffect(v8::Isolate* isolate, + v8::Local that, + const char* name, + v8::FunctionCallback callback); + +enum class SetConstructorFunctionFlag { + NONE, + SET_CLASS_NAME, +}; + +void SetConstructorFunction(v8::Local context, + v8::Local that, + const char* name, + v8::Local tmpl, + SetConstructorFunctionFlag flag = + SetConstructorFunctionFlag::SET_CLASS_NAME); + +void SetConstructorFunction(v8::Local context, + v8::Local that, + v8::Local name, + v8::Local 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 2b0c424587e420..81e80711df8fc5 100644 --- a/src/uv.cc +++ b/src/uv.cc @@ -109,10 +109,8 @@ void Initialize(Local 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 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 deb7993a145825..22c0c8665d148b 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');